You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 103 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412
  1. /* globals wipPrefixes, issuesTribute, emojiTribute */
  2. /* exported timeAddManual, toggleStopwatch, cancelStopwatch, initHeatmap */
  3. /* exported toggleDeadlineForm, setDeadline, updateDeadline, deleteDependencyModal, cancelCodeComment, onOAuthLoginClick */
  4. import './publicPath';
  5. import './gitGraph';
  6. function htmlEncode(text) {
  7. return jQuery('<div />').text(text).html();
  8. }
  9. let csrf;
  10. let suburl;
  11. let previewFileModes;
  12. let simpleMDEditor;
  13. let codeMirrorEditor;
  14. // Disable Dropzone auto-discover because it's manually initialized
  15. if (typeof (Dropzone) !== 'undefined') {
  16. Dropzone.autoDiscover = false;
  17. }
  18. function initCommentPreviewTab($form) {
  19. const $tabMenu = $form.find('.tabular.menu');
  20. $tabMenu.find('.item').tab();
  21. $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`).click(function () {
  22. const $this = $(this);
  23. $.post($this.data('url'), {
  24. _csrf: csrf,
  25. mode: 'gfm',
  26. context: $this.data('context'),
  27. text: $form.find(`.tab.segment[data-tab="${$tabMenu.data('write')}"] textarea`).val()
  28. }, (data) => {
  29. const $previewPanel = $form.find(`.tab.segment[data-tab="${$tabMenu.data('preview')}"]`);
  30. $previewPanel.html(data);
  31. emojify.run($previewPanel[0]);
  32. $('pre code', $previewPanel[0]).each(function () {
  33. hljs.highlightBlock(this);
  34. });
  35. });
  36. });
  37. buttonsClickOnEnter();
  38. }
  39. function initEditPreviewTab($form) {
  40. const $tabMenu = $form.find('.tabular.menu');
  41. $tabMenu.find('.item').tab();
  42. const $previewTab = $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`);
  43. if ($previewTab.length) {
  44. previewFileModes = $previewTab.data('preview-file-modes').split(',');
  45. $previewTab.click(function () {
  46. const $this = $(this);
  47. $.post($this.data('url'), {
  48. _csrf: csrf,
  49. mode: 'gfm',
  50. context: $this.data('context'),
  51. text: $form.find(`.tab.segment[data-tab="${$tabMenu.data('write')}"] textarea`).val()
  52. }, (data) => {
  53. const $previewPanel = $form.find(`.tab.segment[data-tab="${$tabMenu.data('preview')}"]`);
  54. $previewPanel.html(data);
  55. emojify.run($previewPanel[0]);
  56. $('pre code', $previewPanel[0]).each(function () {
  57. hljs.highlightBlock(this);
  58. });
  59. });
  60. });
  61. }
  62. }
  63. function initEditDiffTab($form) {
  64. const $tabMenu = $form.find('.tabular.menu');
  65. $tabMenu.find('.item').tab();
  66. $tabMenu.find(`.item[data-tab="${$tabMenu.data('diff')}"]`).click(function () {
  67. const $this = $(this);
  68. $.post($this.data('url'), {
  69. _csrf: csrf,
  70. context: $this.data('context'),
  71. content: $form.find(`.tab.segment[data-tab="${$tabMenu.data('write')}"] textarea`).val()
  72. }, (data) => {
  73. const $diffPreviewPanel = $form.find(`.tab.segment[data-tab="${$tabMenu.data('diff')}"]`);
  74. $diffPreviewPanel.html(data);
  75. emojify.run($diffPreviewPanel[0]);
  76. });
  77. });
  78. }
  79. function initEditForm() {
  80. if ($('.edit.form').length === 0) {
  81. return;
  82. }
  83. initEditPreviewTab($('.edit.form'));
  84. initEditDiffTab($('.edit.form'));
  85. }
  86. function initBranchSelector() {
  87. const $selectBranch = $('.ui.select-branch');
  88. const $branchMenu = $selectBranch.find('.reference-list-menu');
  89. $branchMenu.find('.item:not(.no-select)').click(function () {
  90. const selectedValue = $(this).data('id');
  91. $($(this).data('id-selector')).val(selectedValue);
  92. $selectBranch.find('.ui .branch-name').text(selectedValue);
  93. });
  94. $selectBranch.find('.reference.column').click(function () {
  95. $selectBranch.find('.scrolling.reference-list-menu').css('display', 'none');
  96. $selectBranch.find('.reference .text').removeClass('black');
  97. $($(this).data('target')).css('display', 'block');
  98. $(this).find('.text').addClass('black');
  99. return false;
  100. });
  101. }
  102. function updateIssuesMeta(url, action, issueIds, elementId) {
  103. return new Promise(((resolve) => {
  104. $.ajax({
  105. type: 'POST',
  106. url,
  107. data: {
  108. _csrf: csrf,
  109. action,
  110. issue_ids: issueIds,
  111. id: elementId
  112. },
  113. success: resolve
  114. });
  115. }));
  116. }
  117. function initRepoStatusChecker() {
  118. const migrating = $('#repo_migrating');
  119. $('#repo_migrating_failed').hide();
  120. if (migrating) {
  121. const repo_name = migrating.attr('repo');
  122. if (typeof repo_name === 'undefined') {
  123. return;
  124. }
  125. $.ajax({
  126. type: 'GET',
  127. url: `${suburl}/${repo_name}/status`,
  128. data: {
  129. _csrf: csrf,
  130. },
  131. complete(xhr) {
  132. if (xhr.status === 200) {
  133. if (xhr.responseJSON) {
  134. if (xhr.responseJSON.status === 0) {
  135. window.location.reload();
  136. return;
  137. }
  138. setTimeout(() => {
  139. initRepoStatusChecker();
  140. }, 2000);
  141. return;
  142. }
  143. }
  144. $('#repo_migrating_progress').hide();
  145. $('#repo_migrating_failed').show();
  146. }
  147. });
  148. }
  149. }
  150. function initReactionSelector(parent) {
  151. let reactions = '';
  152. if (!parent) {
  153. parent = $(document);
  154. reactions = '.reactions > ';
  155. }
  156. parent.find(`${reactions}a.label`).popup({ position: 'bottom left', metadata: { content: 'title', title: 'none' } });
  157. parent.find(`.select-reaction > .menu > .item, ${reactions}a.label`).on('click', function (e) {
  158. const vm = this;
  159. e.preventDefault();
  160. if ($(this).hasClass('disabled')) return;
  161. const actionURL = $(this).hasClass('item')
  162. ? $(this).closest('.select-reaction').data('action-url')
  163. : $(this).data('action-url');
  164. const url = `${actionURL}/${$(this).hasClass('blue') ? 'unreact' : 'react'}`;
  165. $.ajax({
  166. type: 'POST',
  167. url,
  168. data: {
  169. _csrf: csrf,
  170. content: $(this).data('content')
  171. }
  172. }).done((resp) => {
  173. if (resp && (resp.html || resp.empty)) {
  174. const content = $(vm).closest('.content');
  175. let react = content.find('.segment.reactions');
  176. if (!resp.empty && react.length > 0) {
  177. react.remove();
  178. }
  179. if (!resp.empty) {
  180. react = $('<div class="ui attached segment reactions"></div>');
  181. const attachments = content.find('.segment.bottom:first');
  182. if (attachments.length > 0) {
  183. react.insertBefore(attachments);
  184. } else {
  185. react.appendTo(content);
  186. }
  187. react.html(resp.html);
  188. const hasEmoji = react.find('.has-emoji');
  189. for (let i = 0; i < hasEmoji.length; i++) {
  190. emojify.run(hasEmoji.get(i));
  191. }
  192. react.find('.dropdown').dropdown();
  193. initReactionSelector(react);
  194. }
  195. }
  196. });
  197. });
  198. }
  199. function insertAtCursor(field, value) {
  200. if (field.selectionStart || field.selectionStart === 0) {
  201. const startPos = field.selectionStart;
  202. const endPos = field.selectionEnd;
  203. field.value = field.value.substring(0, startPos)
  204. + value
  205. + field.value.substring(endPos, field.value.length);
  206. field.selectionStart = startPos + value.length;
  207. field.selectionEnd = startPos + value.length;
  208. } else {
  209. field.value += value;
  210. }
  211. }
  212. function replaceAndKeepCursor(field, oldval, newval) {
  213. if (field.selectionStart || field.selectionStart === 0) {
  214. const startPos = field.selectionStart;
  215. const endPos = field.selectionEnd;
  216. field.value = field.value.replace(oldval, newval);
  217. field.selectionStart = startPos + newval.length - oldval.length;
  218. field.selectionEnd = endPos + newval.length - oldval.length;
  219. } else {
  220. field.value = field.value.replace(oldval, newval);
  221. }
  222. }
  223. function retrieveImageFromClipboardAsBlob(pasteEvent, callback) {
  224. if (!pasteEvent.clipboardData) {
  225. return;
  226. }
  227. const { items } = pasteEvent.clipboardData;
  228. if (typeof items === 'undefined') {
  229. return;
  230. }
  231. for (let i = 0; i < items.length; i++) {
  232. if (items[i].type.indexOf('image') === -1) continue;
  233. const blob = items[i].getAsFile();
  234. if (typeof (callback) === 'function') {
  235. pasteEvent.preventDefault();
  236. pasteEvent.stopPropagation();
  237. callback(blob);
  238. }
  239. }
  240. }
  241. function uploadFile(file, callback) {
  242. const xhr = new XMLHttpRequest();
  243. xhr.onload = function () {
  244. if (xhr.status === 200) {
  245. callback(xhr.responseText);
  246. }
  247. };
  248. xhr.open('post', `${suburl}/attachments`, true);
  249. xhr.setRequestHeader('X-Csrf-Token', csrf);
  250. const formData = new FormData();
  251. formData.append('file', file, file.name);
  252. xhr.send(formData);
  253. }
  254. function reload() {
  255. window.location.reload();
  256. }
  257. function initImagePaste(target) {
  258. target.each(function () {
  259. const field = this;
  260. field.addEventListener('paste', (event) => {
  261. retrieveImageFromClipboardAsBlob(event, (img) => {
  262. const name = img.name.substr(0, img.name.lastIndexOf('.'));
  263. insertAtCursor(field, `![${name}]()`);
  264. uploadFile(img, (res) => {
  265. const data = JSON.parse(res);
  266. replaceAndKeepCursor(field, `![${name}]()`, `![${name}](${suburl}/attachments/${data.uuid})`);
  267. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  268. $('.files').append(input);
  269. });
  270. });
  271. }, false);
  272. });
  273. }
  274. function initCommentForm() {
  275. if ($('.comment.form').length === 0) {
  276. return;
  277. }
  278. initBranchSelector();
  279. initCommentPreviewTab($('.comment.form'));
  280. initImagePaste($('.comment.form textarea'));
  281. // Listsubmit
  282. function initListSubmits(selector, outerSelector) {
  283. const $list = $(`.ui.${outerSelector}.list`);
  284. const $noSelect = $list.find('.no-select');
  285. const $listMenu = $(`.${selector} .menu`);
  286. let hasLabelUpdateAction = $listMenu.data('action') === 'update';
  287. const labels = {};
  288. $(`.${selector}`).dropdown('setting', 'onHide', () => {
  289. hasLabelUpdateAction = $listMenu.data('action') === 'update'; // Update the var
  290. if (hasLabelUpdateAction) {
  291. const promises = [];
  292. Object.keys(labels).forEach((elementId) => {
  293. const label = labels[elementId];
  294. const promise = updateIssuesMeta(
  295. label['update-url'],
  296. label.action,
  297. label['issue-id'],
  298. elementId
  299. );
  300. promises.push(promise);
  301. });
  302. Promise.all(promises).then(reload);
  303. }
  304. });
  305. $listMenu.find('.item:not(.no-select)').click(function () {
  306. // we don't need the action attribute when updating assignees
  307. if (selector === 'select-assignees-modify') {
  308. // UI magic. We need to do this here, otherwise it would destroy the functionality of
  309. // adding/removing labels
  310. if ($(this).hasClass('checked')) {
  311. $(this).removeClass('checked');
  312. $(this).find('.octicon').removeClass('octicon-check');
  313. } else {
  314. $(this).addClass('checked');
  315. $(this).find('.octicon').addClass('octicon-check');
  316. }
  317. updateIssuesMeta(
  318. $listMenu.data('update-url'),
  319. '',
  320. $listMenu.data('issue-id'),
  321. $(this).data('id')
  322. );
  323. $listMenu.data('action', 'update'); // Update to reload the page when we updated items
  324. return false;
  325. }
  326. if ($(this).hasClass('checked')) {
  327. $(this).removeClass('checked');
  328. $(this).find('.octicon').removeClass('octicon-check');
  329. if (hasLabelUpdateAction) {
  330. if (!($(this).data('id') in labels)) {
  331. labels[$(this).data('id')] = {
  332. 'update-url': $listMenu.data('update-url'),
  333. action: 'detach',
  334. 'issue-id': $listMenu.data('issue-id'),
  335. };
  336. } else {
  337. delete labels[$(this).data('id')];
  338. }
  339. }
  340. } else {
  341. $(this).addClass('checked');
  342. $(this).find('.octicon').addClass('octicon-check');
  343. if (hasLabelUpdateAction) {
  344. if (!($(this).data('id') in labels)) {
  345. labels[$(this).data('id')] = {
  346. 'update-url': $listMenu.data('update-url'),
  347. action: 'attach',
  348. 'issue-id': $listMenu.data('issue-id'),
  349. };
  350. } else {
  351. delete labels[$(this).data('id')];
  352. }
  353. }
  354. }
  355. const listIds = [];
  356. $(this).parent().find('.item').each(function () {
  357. if ($(this).hasClass('checked')) {
  358. listIds.push($(this).data('id'));
  359. $($(this).data('id-selector')).removeClass('hide');
  360. } else {
  361. $($(this).data('id-selector')).addClass('hide');
  362. }
  363. });
  364. if (listIds.length === 0) {
  365. $noSelect.removeClass('hide');
  366. } else {
  367. $noSelect.addClass('hide');
  368. }
  369. $($(this).parent().data('id')).val(listIds.join(','));
  370. return false;
  371. });
  372. $listMenu.find('.no-select.item').click(function () {
  373. if (hasLabelUpdateAction || selector === 'select-assignees-modify') {
  374. updateIssuesMeta(
  375. $listMenu.data('update-url'),
  376. 'clear',
  377. $listMenu.data('issue-id'),
  378. ''
  379. ).then(reload);
  380. }
  381. $(this).parent().find('.item').each(function () {
  382. $(this).removeClass('checked');
  383. $(this).find('.octicon').removeClass('octicon-check');
  384. });
  385. $list.find('.item').each(function () {
  386. $(this).addClass('hide');
  387. });
  388. $noSelect.removeClass('hide');
  389. $($(this).parent().data('id')).val('');
  390. });
  391. }
  392. // Init labels and assignees
  393. initListSubmits('select-label', 'labels');
  394. initListSubmits('select-assignees', 'assignees');
  395. initListSubmits('select-assignees-modify', 'assignees');
  396. function selectItem(select_id, input_id) {
  397. const $menu = $(`${select_id} .menu`);
  398. const $list = $(`.ui${select_id}.list`);
  399. const hasUpdateAction = $menu.data('action') === 'update';
  400. $menu.find('.item:not(.no-select)').click(function () {
  401. $(this).parent().find('.item').each(function () {
  402. $(this).removeClass('selected active');
  403. });
  404. $(this).addClass('selected active');
  405. if (hasUpdateAction) {
  406. updateIssuesMeta(
  407. $menu.data('update-url'),
  408. '',
  409. $menu.data('issue-id'),
  410. $(this).data('id')
  411. ).then(reload);
  412. }
  413. switch (input_id) {
  414. case '#milestone_id':
  415. $list.find('.selected').html(`<a class="item" href=${$(this).data('href')}>${
  416. htmlEncode($(this).text())}</a>`);
  417. break;
  418. case '#assignee_id':
  419. $list.find('.selected').html(`<a class="item" href=${$(this).data('href')}>`
  420. + `<img class="ui avatar image" src=${$(this).data('avatar')}>${
  421. htmlEncode($(this).text())}</a>`);
  422. }
  423. $(`.ui${select_id}.list .no-select`).addClass('hide');
  424. $(input_id).val($(this).data('id'));
  425. });
  426. $menu.find('.no-select.item').click(function () {
  427. $(this).parent().find('.item:not(.no-select)').each(function () {
  428. $(this).removeClass('selected active');
  429. });
  430. if (hasUpdateAction) {
  431. updateIssuesMeta(
  432. $menu.data('update-url'),
  433. '',
  434. $menu.data('issue-id'),
  435. $(this).data('id')
  436. ).then(reload);
  437. }
  438. $list.find('.selected').html('');
  439. $list.find('.no-select').removeClass('hide');
  440. $(input_id).val('');
  441. });
  442. }
  443. // Milestone and assignee
  444. selectItem('.select-milestone', '#milestone_id');
  445. selectItem('.select-assignee', '#assignee_id');
  446. }
  447. function initInstall() {
  448. if ($('.install').length === 0) {
  449. return;
  450. }
  451. if ($('#db_host').val() === '') {
  452. $('#db_host').val('127.0.0.1:3306');
  453. $('#db_user').val('gitea');
  454. $('#db_name').val('gitea');
  455. }
  456. // Database type change detection.
  457. $('#db_type').change(function () {
  458. const sqliteDefault = 'data/gitea.db';
  459. const tidbDefault = 'data/gitea_tidb';
  460. const dbType = $(this).val();
  461. if (dbType === 'SQLite3') {
  462. $('#sql_settings').hide();
  463. $('#pgsql_settings').hide();
  464. $('#mysql_settings').hide();
  465. $('#sqlite_settings').show();
  466. if (dbType === 'SQLite3' && $('#db_path').val() === tidbDefault) {
  467. $('#db_path').val(sqliteDefault);
  468. }
  469. return;
  470. }
  471. const dbDefaults = {
  472. MySQL: '127.0.0.1:3306',
  473. PostgreSQL: '127.0.0.1:5432',
  474. MSSQL: '127.0.0.1:1433'
  475. };
  476. $('#sqlite_settings').hide();
  477. $('#sql_settings').show();
  478. $('#pgsql_settings').toggle(dbType === 'PostgreSQL');
  479. $('#mysql_settings').toggle(dbType === 'MySQL');
  480. $.each(dbDefaults, (_type, defaultHost) => {
  481. if ($('#db_host').val() === defaultHost) {
  482. $('#db_host').val(dbDefaults[dbType]);
  483. return false;
  484. }
  485. });
  486. });
  487. // TODO: better handling of exclusive relations.
  488. $('#offline-mode input').change(function () {
  489. if ($(this).is(':checked')) {
  490. $('#disable-gravatar').checkbox('check');
  491. $('#federated-avatar-lookup').checkbox('uncheck');
  492. }
  493. });
  494. $('#disable-gravatar input').change(function () {
  495. if ($(this).is(':checked')) {
  496. $('#federated-avatar-lookup').checkbox('uncheck');
  497. } else {
  498. $('#offline-mode').checkbox('uncheck');
  499. }
  500. });
  501. $('#federated-avatar-lookup input').change(function () {
  502. if ($(this).is(':checked')) {
  503. $('#disable-gravatar').checkbox('uncheck');
  504. $('#offline-mode').checkbox('uncheck');
  505. }
  506. });
  507. $('#enable-openid-signin input').change(function () {
  508. if ($(this).is(':checked')) {
  509. if (!$('#disable-registration input').is(':checked')) {
  510. $('#enable-openid-signup').checkbox('check');
  511. }
  512. } else {
  513. $('#enable-openid-signup').checkbox('uncheck');
  514. }
  515. });
  516. $('#disable-registration input').change(function () {
  517. if ($(this).is(':checked')) {
  518. $('#enable-captcha').checkbox('uncheck');
  519. $('#enable-openid-signup').checkbox('uncheck');
  520. } else {
  521. $('#enable-openid-signup').checkbox('check');
  522. }
  523. });
  524. $('#enable-captcha input').change(function () {
  525. if ($(this).is(':checked')) {
  526. $('#disable-registration').checkbox('uncheck');
  527. }
  528. });
  529. }
  530. function initRepository() {
  531. if ($('.repository').length === 0) {
  532. return;
  533. }
  534. function initFilterSearchDropdown(selector) {
  535. const $dropdown = $(selector);
  536. $dropdown.dropdown({
  537. fullTextSearch: true,
  538. selectOnKeydown: false,
  539. onChange(_text, _value, $choice) {
  540. if ($choice.data('url')) {
  541. window.location.href = $choice.data('url');
  542. }
  543. },
  544. message: { noResults: $dropdown.data('no-results') }
  545. });
  546. }
  547. // File list and commits
  548. if ($('.repository.file.list').length > 0 || ('.repository.commits').length > 0) {
  549. initFilterBranchTagDropdown('.choose.reference .dropdown');
  550. }
  551. // Wiki
  552. if ($('.repository.wiki.view').length > 0) {
  553. initFilterSearchDropdown('.choose.page .dropdown');
  554. }
  555. // Options
  556. if ($('.repository.settings.options').length > 0) {
  557. $('#repo_name').keyup(function () {
  558. const $prompt = $('#repo-name-change-prompt');
  559. if ($(this).val().toString().toLowerCase() !== $(this).data('name').toString().toLowerCase()) {
  560. $prompt.show();
  561. } else {
  562. $prompt.hide();
  563. }
  564. });
  565. // Enable or select internal/external wiki system and issue tracker.
  566. $('.enable-system').change(function () {
  567. if (this.checked) {
  568. $($(this).data('target')).removeClass('disabled');
  569. if (!$(this).data('context')) $($(this).data('context')).addClass('disabled');
  570. } else {
  571. $($(this).data('target')).addClass('disabled');
  572. if (!$(this).data('context')) $($(this).data('context')).removeClass('disabled');
  573. }
  574. });
  575. $('.enable-system-radio').change(function () {
  576. if (this.value === 'false') {
  577. $($(this).data('target')).addClass('disabled');
  578. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).removeClass('disabled');
  579. } else if (this.value === 'true') {
  580. $($(this).data('target')).removeClass('disabled');
  581. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).addClass('disabled');
  582. }
  583. });
  584. }
  585. // Labels
  586. if ($('.repository.labels').length > 0) {
  587. // Create label
  588. const $newLabelPanel = $('.new-label.segment');
  589. $('.new-label.button').click(() => {
  590. $newLabelPanel.show();
  591. });
  592. $('.new-label.segment .cancel').click(() => {
  593. $newLabelPanel.hide();
  594. });
  595. $('.color-picker').each(function () {
  596. $(this).minicolors();
  597. });
  598. $('.precolors .color').click(function () {
  599. const color_hex = $(this).data('color-hex');
  600. $('.color-picker').val(color_hex);
  601. $('.minicolors-swatch-color').css('background-color', color_hex);
  602. });
  603. $('.edit-label-button').click(function () {
  604. $('#label-modal-id').val($(this).data('id'));
  605. $('.edit-label .new-label-input').val($(this).data('title'));
  606. $('.edit-label .new-label-desc-input').val($(this).data('description'));
  607. $('.edit-label .color-picker').val($(this).data('color'));
  608. $('.minicolors-swatch-color').css('background-color', $(this).data('color'));
  609. $('.edit-label.modal').modal({
  610. onApprove() {
  611. $('.edit-label.form').submit();
  612. }
  613. }).modal('show');
  614. return false;
  615. });
  616. }
  617. // Milestones
  618. if ($('.repository.new.milestone').length > 0) {
  619. const $datepicker = $('.milestone.datepicker');
  620. $datepicker.datetimepicker({
  621. lang: $datepicker.data('lang'),
  622. inline: true,
  623. timepicker: false,
  624. startDate: $datepicker.data('start-date'),
  625. formatDate: 'Y-m-d',
  626. onSelectDate(ct) {
  627. $('#deadline').val(ct.dateFormat('Y-m-d'));
  628. }
  629. });
  630. $('#clear-date').click(() => {
  631. $('#deadline').val('');
  632. return false;
  633. });
  634. }
  635. // Issues
  636. if ($('.repository.view.issue').length > 0) {
  637. // Edit issue title
  638. const $issueTitle = $('#issue-title');
  639. const $editInput = $('#edit-title-input input');
  640. const editTitleToggle = function () {
  641. $issueTitle.toggle();
  642. $('.not-in-edit').toggle();
  643. $('#edit-title-input').toggle();
  644. $('.in-edit').toggle();
  645. $editInput.focus();
  646. return false;
  647. };
  648. $('#edit-title').click(editTitleToggle);
  649. $('#cancel-edit-title').click(editTitleToggle);
  650. $('#save-edit-title').click(editTitleToggle).click(function () {
  651. if ($editInput.val().length === 0 || $editInput.val() === $issueTitle.text()) {
  652. $editInput.val($issueTitle.text());
  653. return false;
  654. }
  655. $.post($(this).data('update-url'), {
  656. _csrf: csrf,
  657. title: $editInput.val()
  658. },
  659. (data) => {
  660. $editInput.val(data.title);
  661. $issueTitle.text(data.title);
  662. reload();
  663. });
  664. return false;
  665. });
  666. // Issue/PR Context Menus
  667. $('.context-dropdown').dropdown({
  668. action: 'hide'
  669. });
  670. // Quote reply
  671. $('.quote-reply').click(function (event) {
  672. $(this).closest('.dropdown').find('.menu').toggle('visible');
  673. const target = $(this).data('target');
  674. let $content;
  675. if ($(this).hasClass('quote-reply-diff')) {
  676. const $parent = $(this).closest('.comment-code-cloud');
  677. $parent.find('button.comment-form-reply').click();
  678. $content = $parent.find('[name="content"]');
  679. } else {
  680. $content = $('#content');
  681. }
  682. const quote = $(`#comment-${target}`).text().replace(/\n/g, '\n> ');
  683. const content = `> ${quote}\n\n`;
  684. if ($content.val() !== '') {
  685. $content.val(`${$content.val()}\n\n${content}`);
  686. } else {
  687. $content.val(`${content}`);
  688. }
  689. $content.focus();
  690. event.preventDefault();
  691. });
  692. // Edit issue or comment content
  693. $('.edit-content').click(function (event) {
  694. $(this).closest('.dropdown').find('.menu').toggle('visible');
  695. const $segment = $(this).closest('.header').next();
  696. const $editContentZone = $segment.find('.edit-content-zone');
  697. const $renderContent = $segment.find('.render-content');
  698. const $rawContent = $segment.find('.raw-content');
  699. let $textarea;
  700. // Setup new form
  701. if ($editContentZone.html().length === 0) {
  702. $editContentZone.html($('#edit-content-form').html());
  703. $textarea = $editContentZone.find('textarea');
  704. issuesTribute.attach($textarea.get());
  705. emojiTribute.attach($textarea.get());
  706. const $dropzone = $editContentZone.find('.dropzone');
  707. $dropzone.data('saved', false);
  708. const $files = $editContentZone.find('.comment-files');
  709. if ($dropzone.length > 0) {
  710. const filenameDict = {};
  711. $dropzone.dropzone({
  712. url: $dropzone.data('upload-url'),
  713. headers: { 'X-Csrf-Token': csrf },
  714. maxFiles: $dropzone.data('max-file'),
  715. maxFilesize: $dropzone.data('max-size'),
  716. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  717. addRemoveLinks: true,
  718. dictDefaultMessage: $dropzone.data('default-message'),
  719. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  720. dictFileTooBig: $dropzone.data('file-too-big'),
  721. dictRemoveFile: $dropzone.data('remove-file'),
  722. init() {
  723. this.on('success', (file, data) => {
  724. filenameDict[file.name] = {
  725. uuid: data.uuid,
  726. submitted: false
  727. };
  728. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  729. $files.append(input);
  730. });
  731. this.on('removedfile', (file) => {
  732. if (!(file.name in filenameDict)) {
  733. return;
  734. }
  735. $(`#${filenameDict[file.name].uuid}`).remove();
  736. if ($dropzone.data('remove-url') && $dropzone.data('csrf') && !filenameDict[file.name].submitted) {
  737. $.post($dropzone.data('remove-url'), {
  738. file: filenameDict[file.name].uuid,
  739. _csrf: $dropzone.data('csrf')
  740. });
  741. }
  742. });
  743. this.on('submit', () => {
  744. $.each(filenameDict, (name) => {
  745. filenameDict[name].submitted = true;
  746. });
  747. });
  748. this.on('reload', () => {
  749. $.getJSON($editContentZone.data('attachment-url'), (data) => {
  750. const drop = $dropzone.get(0).dropzone;
  751. drop.removeAllFiles(true);
  752. $files.empty();
  753. $.each(data, function () {
  754. const imgSrc = `${$dropzone.data('upload-url')}/${this.uuid}`;
  755. drop.emit('addedfile', this);
  756. drop.emit('thumbnail', this, imgSrc);
  757. drop.emit('complete', this);
  758. drop.files.push(this);
  759. filenameDict[this.name] = {
  760. submitted: true,
  761. uuid: this.uuid
  762. };
  763. $dropzone.find(`img[src='${imgSrc}']`).css('max-width', '100%');
  764. const input = $(`<input id="${this.uuid}" name="files" type="hidden">`).val(this.uuid);
  765. $files.append(input);
  766. });
  767. });
  768. });
  769. }
  770. });
  771. $dropzone.get(0).dropzone.emit('reload');
  772. }
  773. // Give new write/preview data-tab name to distinguish from others
  774. const $editContentForm = $editContentZone.find('.ui.comment.form');
  775. const $tabMenu = $editContentForm.find('.tabular.menu');
  776. $tabMenu.attr('data-write', $editContentZone.data('write'));
  777. $tabMenu.attr('data-preview', $editContentZone.data('preview'));
  778. $tabMenu.find('.write.item').attr('data-tab', $editContentZone.data('write'));
  779. $tabMenu.find('.preview.item').attr('data-tab', $editContentZone.data('preview'));
  780. $editContentForm.find('.write.segment').attr('data-tab', $editContentZone.data('write'));
  781. $editContentForm.find('.preview.segment').attr('data-tab', $editContentZone.data('preview'));
  782. initCommentPreviewTab($editContentForm);
  783. $editContentZone.find('.cancel.button').click(() => {
  784. $renderContent.show();
  785. $editContentZone.hide();
  786. $dropzone.get(0).dropzone.emit('reload');
  787. });
  788. $editContentZone.find('.save.button').click(() => {
  789. $renderContent.show();
  790. $editContentZone.hide();
  791. const $attachments = $files.find('[name=files]').map(function () {
  792. return $(this).val();
  793. }).get();
  794. $.post($editContentZone.data('update-url'), {
  795. _csrf: csrf,
  796. content: $textarea.val(),
  797. context: $editContentZone.data('context'),
  798. files: $attachments
  799. }, (data) => {
  800. if (data.length === 0) {
  801. $renderContent.html($('#no-content').html());
  802. } else {
  803. $renderContent.html(data.content);
  804. emojify.run($renderContent[0]);
  805. $('pre code', $renderContent[0]).each(function () {
  806. hljs.highlightBlock(this);
  807. });
  808. }
  809. const $content = $segment.parent();
  810. if (!$content.find('.ui.small.images').length) {
  811. if (data.attachments !== '') {
  812. $content.append(
  813. '<div class="ui bottom attached segment"><div class="ui small images"></div></div>'
  814. );
  815. $content.find('.ui.small.images').html(data.attachments);
  816. }
  817. } else if (data.attachments === '') {
  818. $content.find('.ui.small.images').parent().remove();
  819. } else {
  820. $content.find('.ui.small.images').html(data.attachments);
  821. }
  822. $dropzone.get(0).dropzone.emit('submit');
  823. $dropzone.get(0).dropzone.emit('reload');
  824. });
  825. });
  826. } else {
  827. $textarea = $segment.find('textarea');
  828. }
  829. // Show write/preview tab and copy raw content as needed
  830. $editContentZone.show();
  831. $renderContent.hide();
  832. if ($textarea.val().length === 0) {
  833. $textarea.val($rawContent.text());
  834. }
  835. $textarea.focus();
  836. event.preventDefault();
  837. });
  838. // Delete comment
  839. $('.delete-comment').click(function () {
  840. const $this = $(this);
  841. if (window.confirm($this.data('locale'))) {
  842. $.post($this.data('url'), {
  843. _csrf: csrf
  844. }).success(() => {
  845. $(`#${$this.data('comment-id')}`).remove();
  846. });
  847. }
  848. return false;
  849. });
  850. // Change status
  851. const $statusButton = $('#status-button');
  852. $('#comment-form .edit_area').keyup(function () {
  853. if ($(this).val().length === 0) {
  854. $statusButton.text($statusButton.data('status'));
  855. } else {
  856. $statusButton.text($statusButton.data('status-and-comment'));
  857. }
  858. });
  859. $statusButton.click(() => {
  860. $('#status').val($statusButton.data('status-val'));
  861. $('#comment-form').submit();
  862. });
  863. // Pull Request merge button
  864. const $mergeButton = $('.merge-button > button');
  865. $mergeButton.on('click', function (e) {
  866. e.preventDefault();
  867. $(`.${$(this).data('do')}-fields`).show();
  868. $(this).parent().hide();
  869. });
  870. $('.merge-button > .dropdown').dropdown({
  871. onChange(_text, _value, $choice) {
  872. if ($choice.data('do')) {
  873. $mergeButton.find('.button-text').text($choice.text());
  874. $mergeButton.data('do', $choice.data('do'));
  875. }
  876. }
  877. });
  878. $('.merge-cancel').on('click', function (e) {
  879. e.preventDefault();
  880. $(this).closest('.form').hide();
  881. $mergeButton.parent().show();
  882. });
  883. initReactionSelector();
  884. }
  885. // Diff
  886. if ($('.repository.diff').length > 0) {
  887. $('.diff-counter').each(function () {
  888. const $item = $(this);
  889. const addLine = $item.find('span[data-line].add').data('line');
  890. const delLine = $item.find('span[data-line].del').data('line');
  891. const addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
  892. $item.find('.bar .add').css('width', `${addPercent}%`);
  893. });
  894. }
  895. // Quick start and repository home
  896. $('#repo-clone-ssh').click(function () {
  897. $('.clone-url').text($(this).data('link'));
  898. $('#repo-clone-url').val($(this).data('link'));
  899. $(this).addClass('blue');
  900. $('#repo-clone-https').removeClass('blue');
  901. localStorage.setItem('repo-clone-protocol', 'ssh');
  902. });
  903. $('#repo-clone-https').click(function () {
  904. $('.clone-url').text($(this).data('link'));
  905. $('#repo-clone-url').val($(this).data('link'));
  906. $(this).addClass('blue');
  907. $('#repo-clone-ssh').removeClass('blue');
  908. localStorage.setItem('repo-clone-protocol', 'https');
  909. });
  910. $('#repo-clone-url').click(function () {
  911. $(this).select();
  912. });
  913. // Pull request
  914. const $repoComparePull = $('.repository.compare.pull');
  915. if ($repoComparePull.length > 0) {
  916. initFilterSearchDropdown('.choose.branch .dropdown');
  917. // show pull request form
  918. $repoComparePull.find('button.show-form').on('click', function (e) {
  919. e.preventDefault();
  920. $repoComparePull.find('.pullrequest-form').show();
  921. $(this).parent().hide();
  922. });
  923. }
  924. // Branches
  925. if ($('.repository.settings.branches').length > 0) {
  926. initFilterSearchDropdown('.protected-branches .dropdown');
  927. $('.enable-protection, .enable-whitelist').change(function () {
  928. if (this.checked) {
  929. $($(this).data('target')).removeClass('disabled');
  930. } else {
  931. $($(this).data('target')).addClass('disabled');
  932. }
  933. });
  934. }
  935. }
  936. function initMigration() {
  937. const toggleMigrations = function () {
  938. const authUserName = $('#auth_username').val();
  939. const cloneAddr = $('#clone_addr').val();
  940. if (!$('#mirror').is(':checked') && (authUserName && authUserName.length > 0)
  941. && (cloneAddr !== undefined && (cloneAddr.startsWith('https://github.com') || cloneAddr.startsWith('http://github.com')))) {
  942. $('#migrate_items').show();
  943. } else {
  944. $('#migrate_items').hide();
  945. }
  946. };
  947. toggleMigrations();
  948. $('#clone_addr').on('input', toggleMigrations);
  949. $('#auth_username').on('input', toggleMigrations);
  950. $('#mirror').on('change', toggleMigrations);
  951. }
  952. function initPullRequestReview() {
  953. $('.show-outdated').on('click', function (e) {
  954. e.preventDefault();
  955. const id = $(this).data('comment');
  956. $(this).addClass('hide');
  957. $(`#code-comments-${id}`).removeClass('hide');
  958. $(`#code-preview-${id}`).removeClass('hide');
  959. $(`#hide-outdated-${id}`).removeClass('hide');
  960. });
  961. $('.hide-outdated').on('click', function (e) {
  962. e.preventDefault();
  963. const id = $(this).data('comment');
  964. $(this).addClass('hide');
  965. $(`#code-comments-${id}`).addClass('hide');
  966. $(`#code-preview-${id}`).addClass('hide');
  967. $(`#show-outdated-${id}`).removeClass('hide');
  968. });
  969. $('button.comment-form-reply').on('click', function (e) {
  970. e.preventDefault();
  971. $(this).hide();
  972. const form = $(this).parent().find('.comment-form');
  973. form.removeClass('hide');
  974. assingMenuAttributes(form.find('.menu'));
  975. });
  976. // The following part is only for diff views
  977. if ($('.repository.pull.diff').length === 0) {
  978. return;
  979. }
  980. $('.diff-detail-box.ui.sticky').sticky();
  981. $('.btn-review').on('click', function (e) {
  982. e.preventDefault();
  983. $(this).closest('.dropdown').find('.menu').toggle('visible');
  984. }).closest('.dropdown').find('.link.close')
  985. .on('click', function (e) {
  986. e.preventDefault();
  987. $(this).closest('.menu').toggle('visible');
  988. });
  989. $('.code-view .lines-code,.code-view .lines-num')
  990. .on('mouseenter', function () {
  991. const parent = $(this).closest('td');
  992. $(this).closest('tr').addClass(
  993. parent.hasClass('lines-num-old') || parent.hasClass('lines-code-old')
  994. ? 'focus-lines-old' : 'focus-lines-new'
  995. );
  996. })
  997. .on('mouseleave', function () {
  998. $(this).closest('tr').removeClass('focus-lines-new focus-lines-old');
  999. });
  1000. $('.add-code-comment').on('click', function (e) {
  1001. // https://github.com/go-gitea/gitea/issues/4745
  1002. if ($(e.target).hasClass('btn-add-single')) {
  1003. return;
  1004. }
  1005. e.preventDefault();
  1006. const isSplit = $(this).closest('.code-diff').hasClass('code-diff-split');
  1007. const side = $(this).data('side');
  1008. const idx = $(this).data('idx');
  1009. const path = $(this).data('path');
  1010. const form = $('#pull_review_add_comment').html();
  1011. const tr = $(this).closest('tr');
  1012. let ntr = tr.next();
  1013. if (!ntr.hasClass('add-comment')) {
  1014. ntr = $(`<tr class="add-comment">${
  1015. isSplit ? '<td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-left"></td><td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-right"></td>'
  1016. : '<td class="lines-num"></td><td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-left add-comment-right"></td>'
  1017. }</tr>`);
  1018. tr.after(ntr);
  1019. }
  1020. const td = ntr.find(`.add-comment-${side}`);
  1021. let commentCloud = td.find('.comment-code-cloud');
  1022. if (commentCloud.length === 0) {
  1023. td.html(form);
  1024. commentCloud = td.find('.comment-code-cloud');
  1025. assingMenuAttributes(commentCloud.find('.menu'));
  1026. td.find("input[name='line']").val(idx);
  1027. td.find("input[name='side']").val(side === 'left' ? 'previous' : 'proposed');
  1028. td.find("input[name='path']").val(path);
  1029. }
  1030. commentCloud.find('textarea').focus();
  1031. });
  1032. }
  1033. function assingMenuAttributes(menu) {
  1034. const id = Math.floor(Math.random() * Math.floor(1000000));
  1035. menu.attr('data-write', menu.attr('data-write') + id);
  1036. menu.attr('data-preview', menu.attr('data-preview') + id);
  1037. menu.find('.item').each(function () {
  1038. const tab = $(this).attr('data-tab') + id;
  1039. $(this).attr('data-tab', tab);
  1040. });
  1041. menu.parent().find("*[data-tab='write']").attr('data-tab', `write${id}`);
  1042. menu.parent().find("*[data-tab='preview']").attr('data-tab', `preview${id}`);
  1043. initCommentPreviewTab(menu.parent('.form'));
  1044. return id;
  1045. }
  1046. function initRepositoryCollaboration() {
  1047. // Change collaborator access mode
  1048. $('.access-mode.menu .item').click(function () {
  1049. const $menu = $(this).parent();
  1050. $.post($menu.data('url'), {
  1051. _csrf: csrf,
  1052. uid: $menu.data('uid'),
  1053. mode: $(this).data('value')
  1054. });
  1055. });
  1056. }
  1057. function initTeamSettings() {
  1058. // Change team access mode
  1059. $('.organization.new.team input[name=permission]').change(() => {
  1060. const val = $('input[name=permission]:checked', '.organization.new.team').val();
  1061. if (val === 'admin') {
  1062. $('.organization.new.team .team-units').hide();
  1063. } else {
  1064. $('.organization.new.team .team-units').show();
  1065. }
  1066. });
  1067. }
  1068. function initWikiForm() {
  1069. const $editArea = $('.repository.wiki textarea#edit_area');
  1070. let sideBySideChanges = 0;
  1071. let sideBySideTimeout = null;
  1072. if ($editArea.length > 0) {
  1073. const simplemde = new SimpleMDE({
  1074. autoDownloadFontAwesome: false,
  1075. element: $editArea[0],
  1076. forceSync: true,
  1077. previewRender(plainText, preview) { // Async method
  1078. setTimeout(() => {
  1079. // FIXME: still send render request when return back to edit mode
  1080. const render = function () {
  1081. sideBySideChanges = 0;
  1082. if (sideBySideTimeout != null) {
  1083. clearTimeout(sideBySideTimeout);
  1084. sideBySideTimeout = null;
  1085. }
  1086. $.post($editArea.data('url'), {
  1087. _csrf: csrf,
  1088. mode: 'gfm',
  1089. context: $editArea.data('context'),
  1090. text: plainText
  1091. },
  1092. (data) => {
  1093. preview.innerHTML = `<div class="markdown ui segment">${data}</div>`;
  1094. emojify.run($('.editor-preview')[0]);
  1095. $(preview).find('pre code').each((_, e) => {
  1096. hljs.highlightBlock(e);
  1097. });
  1098. });
  1099. };
  1100. if (!simplemde.isSideBySideActive()) {
  1101. render();
  1102. } else {
  1103. // delay preview by keystroke counting
  1104. sideBySideChanges++;
  1105. if (sideBySideChanges > 10) {
  1106. render();
  1107. }
  1108. // or delay preview by timeout
  1109. if (sideBySideTimeout != null) {
  1110. clearTimeout(sideBySideTimeout);
  1111. sideBySideTimeout = null;
  1112. }
  1113. sideBySideTimeout = setTimeout(render, 600);
  1114. }
  1115. }, 0);
  1116. if (!simplemde.isSideBySideActive()) {
  1117. return 'Loading...';
  1118. }
  1119. return preview.innerHTML;
  1120. },
  1121. renderingConfig: {
  1122. singleLineBreaks: false
  1123. },
  1124. indentWithTabs: false,
  1125. tabSize: 4,
  1126. spellChecker: false,
  1127. toolbar: ['bold', 'italic', 'strikethrough', '|',
  1128. 'heading-1', 'heading-2', 'heading-3', 'heading-bigger', 'heading-smaller', '|',
  1129. {
  1130. name: 'code-inline',
  1131. action(e) {
  1132. const cm = e.codemirror;
  1133. const selection = cm.getSelection();
  1134. cm.replaceSelection(`\`${selection}\``);
  1135. if (!selection) {
  1136. const cursorPos = cm.getCursor();
  1137. cm.setCursor(cursorPos.line, cursorPos.ch - 1);
  1138. }
  1139. cm.focus();
  1140. },
  1141. className: 'fa fa-angle-right',
  1142. title: 'Add Inline Code',
  1143. }, 'code', 'quote', '|', {
  1144. name: 'checkbox-empty',
  1145. action(e) {
  1146. const cm = e.codemirror;
  1147. cm.replaceSelection(`\n- [ ] ${cm.getSelection()}`);
  1148. cm.focus();
  1149. },
  1150. className: 'fa fa-square-o',
  1151. title: 'Add Checkbox (empty)',
  1152. },
  1153. {
  1154. name: 'checkbox-checked',
  1155. action(e) {
  1156. const cm = e.codemirror;
  1157. cm.replaceSelection(`\n- [x] ${cm.getSelection()}`);
  1158. cm.focus();
  1159. },
  1160. className: 'fa fa-check-square-o',
  1161. title: 'Add Checkbox (checked)',
  1162. }, '|',
  1163. 'unordered-list', 'ordered-list', '|',
  1164. 'link', 'image', 'table', 'horizontal-rule', '|',
  1165. 'clean-block', 'preview', 'fullscreen', 'side-by-side']
  1166. });
  1167. $(simplemde.codemirror.getInputField()).addClass('js-quick-submit');
  1168. setTimeout(() => {
  1169. const $bEdit = $('.repository.wiki.new .previewtabs a[data-tab="write"]');
  1170. const $bPrev = $('.repository.wiki.new .previewtabs a[data-tab="preview"]');
  1171. const $toolbar = $('.editor-toolbar');
  1172. const $bPreview = $('.editor-toolbar a.fa-eye');
  1173. const $bSideBySide = $('.editor-toolbar a.fa-columns');
  1174. $bEdit.on('click', () => {
  1175. if ($toolbar.hasClass('disabled-for-preview')) {
  1176. $bPreview.click();
  1177. }
  1178. });
  1179. $bPrev.on('click', () => {
  1180. if (!$toolbar.hasClass('disabled-for-preview')) {
  1181. $bPreview.click();
  1182. }
  1183. });
  1184. $bPreview.on('click', () => {
  1185. setTimeout(() => {
  1186. if ($toolbar.hasClass('disabled-for-preview')) {
  1187. if ($bEdit.hasClass('active')) {
  1188. $bEdit.removeClass('active');
  1189. }
  1190. if (!$bPrev.hasClass('active')) {
  1191. $bPrev.addClass('active');
  1192. }
  1193. } else {
  1194. if (!$bEdit.hasClass('active')) {
  1195. $bEdit.addClass('active');
  1196. }
  1197. if ($bPrev.hasClass('active')) {
  1198. $bPrev.removeClass('active');
  1199. }
  1200. }
  1201. }, 0);
  1202. });
  1203. $bSideBySide.on('click', () => {
  1204. sideBySideChanges = 10;
  1205. });
  1206. }, 0);
  1207. }
  1208. }
  1209. // Adding function to get the cursor position in a text field to jQuery object.
  1210. $.fn.getCursorPosition = function () {
  1211. const el = $(this).get(0);
  1212. let pos = 0;
  1213. if ('selectionStart' in el) {
  1214. pos = el.selectionStart;
  1215. } else if ('selection' in document) {
  1216. el.focus();
  1217. const Sel = document.selection.createRange();
  1218. const SelLength = document.selection.createRange().text.length;
  1219. Sel.moveStart('character', -el.value.length);
  1220. pos = Sel.text.length - SelLength;
  1221. }
  1222. return pos;
  1223. };
  1224. function setSimpleMDE($editArea) {
  1225. if (codeMirrorEditor) {
  1226. codeMirrorEditor.toTextArea();
  1227. codeMirrorEditor = null;
  1228. }
  1229. if (simpleMDEditor) {
  1230. return true;
  1231. }
  1232. simpleMDEditor = new SimpleMDE({
  1233. autoDownloadFontAwesome: false,
  1234. element: $editArea[0],
  1235. forceSync: true,
  1236. renderingConfig: {
  1237. singleLineBreaks: false
  1238. },
  1239. indentWithTabs: false,
  1240. tabSize: 4,
  1241. spellChecker: false,
  1242. previewRender(plainText, preview) { // Async method
  1243. setTimeout(() => {
  1244. // FIXME: still send render request when return back to edit mode
  1245. $.post($editArea.data('url'), {
  1246. _csrf: csrf,
  1247. mode: 'gfm',
  1248. context: $editArea.data('context'),
  1249. text: plainText
  1250. },
  1251. (data) => {
  1252. preview.innerHTML = `<div class="markdown ui segment">${data}</div>`;
  1253. emojify.run($('.editor-preview')[0]);
  1254. });
  1255. }, 0);
  1256. return 'Loading...';
  1257. },
  1258. toolbar: ['bold', 'italic', 'strikethrough', '|',
  1259. 'heading-1', 'heading-2', 'heading-3', 'heading-bigger', 'heading-smaller', '|',
  1260. 'code', 'quote', '|',
  1261. 'unordered-list', 'ordered-list', '|',
  1262. 'link', 'image', 'table', 'horizontal-rule', '|',
  1263. 'clean-block', 'preview', 'fullscreen', 'side-by-side']
  1264. });
  1265. return true;
  1266. }
  1267. function setCodeMirror($editArea) {
  1268. if (simpleMDEditor) {
  1269. simpleMDEditor.toTextArea();
  1270. simpleMDEditor = null;
  1271. }
  1272. if (codeMirrorEditor) {
  1273. return true;
  1274. }
  1275. codeMirrorEditor = CodeMirror.fromTextArea($editArea[0], {
  1276. lineNumbers: true
  1277. });
  1278. codeMirrorEditor.on('change', (cm, _change) => {
  1279. $editArea.val(cm.getValue());
  1280. });
  1281. return true;
  1282. }
  1283. function initEditor() {
  1284. $('.js-quick-pull-choice-option').change(function () {
  1285. if ($(this).val() === 'commit-to-new-branch') {
  1286. $('.quick-pull-branch-name').show();
  1287. $('.quick-pull-branch-name input').prop('required', true);
  1288. } else {
  1289. $('.quick-pull-branch-name').hide();
  1290. $('.quick-pull-branch-name input').prop('required', false);
  1291. }
  1292. $('#commit-button').text($(this).attr('button_text'));
  1293. });
  1294. const $editFilename = $('#file-name');
  1295. $editFilename.keyup(function (e) {
  1296. const $section = $('.breadcrumb span.section');
  1297. const $divider = $('.breadcrumb div.divider');
  1298. let value;
  1299. let parts;
  1300. if (e.keyCode === 8) {
  1301. if ($(this).getCursorPosition() === 0) {
  1302. if ($section.length > 0) {
  1303. value = $section.last().find('a').text();
  1304. $(this).val(value + $(this).val());
  1305. $(this)[0].setSelectionRange(value.length, value.length);
  1306. $section.last().remove();
  1307. $divider.last().remove();
  1308. }
  1309. }
  1310. }
  1311. if (e.keyCode === 191) {
  1312. parts = $(this).val().split('/');
  1313. for (let i = 0; i < parts.length; ++i) {
  1314. value = parts[i];
  1315. if (i < parts.length - 1) {
  1316. if (value.length) {
  1317. $(`<span class="section"><a href="#">${value}</a></span>`).insertBefore($(this));
  1318. $('<div class="divider"> / </div>').insertBefore($(this));
  1319. }
  1320. } else {
  1321. $(this).val(value);
  1322. }
  1323. $(this)[0].setSelectionRange(0, 0);
  1324. }
  1325. }
  1326. parts = [];
  1327. $('.breadcrumb span.section').each(function () {
  1328. const element = $(this);
  1329. if (element.find('a').length) {
  1330. parts.push(element.find('a').text());
  1331. } else {
  1332. parts.push(element.text());
  1333. }
  1334. });
  1335. if ($(this).val()) parts.push($(this).val());
  1336. $('#tree_path').val(parts.join('/'));
  1337. }).trigger('keyup');
  1338. const $editArea = $('.repository.editor textarea#edit_area');
  1339. if (!$editArea.length) return;
  1340. const markdownFileExts = $editArea.data('markdown-file-exts').split(',');
  1341. const lineWrapExtensions = $editArea.data('line-wrap-extensions').split(',');
  1342. $editFilename.on('keyup', () => {
  1343. const val = $editFilename.val();
  1344. let mode, spec, extension, extWithDot, dataUrl, apiCall;
  1345. extension = extWithDot = '';
  1346. const m = /.+\.([^.]+)$/.exec(val);
  1347. if (m) {
  1348. extension = m[1];
  1349. extWithDot = `.${extension}`;
  1350. }
  1351. const info = CodeMirror.findModeByExtension(extension);
  1352. const previewLink = $('a[data-tab=preview]');
  1353. if (info) {
  1354. mode = info.mode;
  1355. spec = info.mime;
  1356. apiCall = mode;
  1357. } else {
  1358. apiCall = extension;
  1359. }
  1360. if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
  1361. dataUrl = previewLink.data('url');
  1362. previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, `$1/${mode}`));
  1363. previewLink.show();
  1364. } else {
  1365. previewLink.hide();
  1366. }
  1367. // If this file is a Markdown extensions, we will load that editor and return
  1368. if (markdownFileExts.indexOf(extWithDot) >= 0) {
  1369. if (setSimpleMDE($editArea)) {
  1370. return;
  1371. }
  1372. }
  1373. // Else we are going to use CodeMirror
  1374. if (!codeMirrorEditor && !setCodeMirror($editArea)) {
  1375. return;
  1376. }
  1377. if (mode) {
  1378. codeMirrorEditor.setOption('mode', spec);
  1379. CodeMirror.autoLoadMode(codeMirrorEditor, mode);
  1380. }
  1381. if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
  1382. codeMirrorEditor.setOption('lineWrapping', true);
  1383. } else {
  1384. codeMirrorEditor.setOption('lineWrapping', false);
  1385. }
  1386. // get the filename without any folder
  1387. let value = $editFilename.val();
  1388. if (value.length === 0) {
  1389. return;
  1390. }
  1391. value = value.split('/');
  1392. value = value[value.length - 1];
  1393. $.getJSON($editFilename.data('ec-url-prefix') + value, (editorconfig) => {
  1394. if (editorconfig.indent_style === 'tab') {
  1395. codeMirrorEditor.setOption('indentWithTabs', true);
  1396. codeMirrorEditor.setOption('extraKeys', {});
  1397. } else {
  1398. codeMirrorEditor.setOption('indentWithTabs', false);
  1399. // required because CodeMirror doesn't seems to use spaces correctly for {"indentWithTabs": false}:
  1400. // - https://github.com/codemirror/CodeMirror/issues/988
  1401. // - https://codemirror.net/doc/manual.html#keymaps
  1402. codeMirrorEditor.setOption('extraKeys', {
  1403. Tab(cm) {
  1404. const spaces = Array(parseInt(cm.getOption('indentUnit')) + 1).join(' ');
  1405. cm.replaceSelection(spaces);
  1406. }
  1407. });
  1408. }
  1409. codeMirrorEditor.setOption('indentUnit', editorconfig.indent_size || 4);
  1410. codeMirrorEditor.setOption('tabSize', editorconfig.tab_width || 4);
  1411. });
  1412. }).trigger('keyup');
  1413. // Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
  1414. // to enable or disable the commit button
  1415. const $commitButton = $('#commit-button');
  1416. const $editForm = $('.ui.edit.form');
  1417. const dirtyFileClass = 'dirty-file';
  1418. // Disabling the button at the start
  1419. $commitButton.prop('disabled', true);
  1420. // Registering a custom listener for the file path and the file content
  1421. $editForm.areYouSure({
  1422. silent: true,
  1423. dirtyClass: dirtyFileClass,
  1424. fieldSelector: ':input:not(.commit-form-wrapper :input)',
  1425. change() {
  1426. const dirty = $(this).hasClass(dirtyFileClass);
  1427. $commitButton.prop('disabled', !dirty);
  1428. }
  1429. });
  1430. $commitButton.click((event) => {
  1431. // A modal which asks if an empty file should be committed
  1432. if ($editArea.val().length === 0) {
  1433. $('#edit-empty-content-modal').modal({
  1434. onApprove() {
  1435. $('.edit.form').submit();
  1436. }
  1437. }).modal('show');
  1438. event.preventDefault();
  1439. }
  1440. });
  1441. }
  1442. function initOrganization() {
  1443. if ($('.organization').length === 0) {
  1444. return;
  1445. }
  1446. // Options
  1447. if ($('.organization.settings.options').length > 0) {
  1448. $('#org_name').keyup(function () {
  1449. const $prompt = $('#org-name-change-prompt');
  1450. if ($(this).val().toString().toLowerCase() !== $(this).data('org-name').toString().toLowerCase()) {
  1451. $prompt.show();
  1452. } else {
  1453. $prompt.hide();
  1454. }
  1455. });
  1456. }
  1457. }
  1458. function initUserSettings() {
  1459. // Options
  1460. if ($('.user.settings.profile').length > 0) {
  1461. $('#username').keyup(function () {
  1462. const $prompt = $('#name-change-prompt');
  1463. if ($(this).val().toString().toLowerCase() !== $(this).data('name').toString().toLowerCase()) {
  1464. $prompt.show();
  1465. } else {
  1466. $prompt.hide();
  1467. }
  1468. });
  1469. }
  1470. }
  1471. function initGithook() {
  1472. if ($('.edit.githook').length === 0) {
  1473. return;
  1474. }
  1475. CodeMirror.autoLoadMode(CodeMirror.fromTextArea($('#content')[0], {
  1476. lineNumbers: true,
  1477. mode: 'shell'
  1478. }), 'shell');
  1479. }
  1480. function initWebhook() {
  1481. if ($('.new.webhook').length === 0) {
  1482. return;
  1483. }
  1484. $('.events.checkbox input').change(function () {
  1485. if ($(this).is(':checked')) {
  1486. $('.events.fields').show();
  1487. }
  1488. });
  1489. $('.non-events.checkbox input').change(function () {
  1490. if ($(this).is(':checked')) {
  1491. $('.events.fields').hide();
  1492. }
  1493. });
  1494. const updateContentType = function () {
  1495. const visible = $('#http_method').val() === 'POST';
  1496. $('#content_type').parent().parent()[visible ? 'show' : 'hide']();
  1497. };
  1498. updateContentType();
  1499. $('#http_method').change(() => {
  1500. updateContentType();
  1501. });
  1502. // Test delivery
  1503. $('#test-delivery').click(function () {
  1504. const $this = $(this);
  1505. $this.addClass('loading disabled');
  1506. $.post($this.data('link'), {
  1507. _csrf: csrf
  1508. }).done(
  1509. setTimeout(() => {
  1510. window.location.href = $this.data('redirect');
  1511. }, 5000)
  1512. );
  1513. });
  1514. }
  1515. function initAdmin() {
  1516. if ($('.admin').length === 0) {
  1517. return;
  1518. }
  1519. // New user
  1520. if ($('.admin.new.user').length > 0 || $('.admin.edit.user').length > 0) {
  1521. $('#login_type').change(function () {
  1522. if ($(this).val().substring(0, 1) === '0') {
  1523. $('#login_name').removeAttr('required');
  1524. $('.non-local').hide();
  1525. $('.local').show();
  1526. $('#user_name').focus();
  1527. if ($(this).data('password') === 'required') {
  1528. $('#password').attr('required', 'required');
  1529. }
  1530. } else {
  1531. $('#login_name').attr('required', 'required');
  1532. $('.non-local').show();
  1533. $('.local').hide();
  1534. $('#login_name').focus();
  1535. $('#password').removeAttr('required');
  1536. }
  1537. });
  1538. }
  1539. function onSecurityProtocolChange() {
  1540. if ($('#security_protocol').val() > 0) {
  1541. $('.has-tls').show();
  1542. } else {
  1543. $('.has-tls').hide();
  1544. }
  1545. }
  1546. function onUsePagedSearchChange() {
  1547. if ($('#use_paged_search').prop('checked')) {
  1548. $('.search-page-size').show()
  1549. .find('input').attr('required', 'required');
  1550. } else {
  1551. $('.search-page-size').hide()
  1552. .find('input').removeAttr('required');
  1553. }
  1554. }
  1555. function onOAuth2Change() {
  1556. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  1557. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  1558. const provider = $('#oauth2_provider').val();
  1559. switch (provider) {
  1560. case 'github':
  1561. case 'gitlab':
  1562. case 'gitea':
  1563. $('.oauth2_use_custom_url').show();
  1564. break;
  1565. case 'openidConnect':
  1566. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  1567. $('.open_id_connect_auto_discovery_url').show();
  1568. break;
  1569. }
  1570. onOAuth2UseCustomURLChange();
  1571. }
  1572. function onOAuth2UseCustomURLChange() {
  1573. const provider = $('#oauth2_provider').val();
  1574. $('.oauth2_use_custom_url_field').hide();
  1575. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  1576. if ($('#oauth2_use_custom_url').is(':checked')) {
  1577. if (!$('#oauth2_token_url').val()) {
  1578. $('#oauth2_token_url').val($(`#${provider}_token_url`).val());
  1579. }
  1580. if (!$('#oauth2_auth_url').val()) {
  1581. $('#oauth2_auth_url').val($(`#${provider}_auth_url`).val());
  1582. }
  1583. if (!$('#oauth2_profile_url').val()) {
  1584. $('#oauth2_profile_url').val($(`#${provider}_profile_url`).val());
  1585. }
  1586. if (!$('#oauth2_email_url').val()) {
  1587. $('#oauth2_email_url').val($(`#${provider}_email_url`).val());
  1588. }
  1589. switch (provider) {
  1590. case 'github':
  1591. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  1592. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  1593. break;
  1594. case 'gitea':
  1595. case 'gitlab':
  1596. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  1597. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  1598. $('#oauth2_email_url').val('');
  1599. break;
  1600. }
  1601. }
  1602. }
  1603. // New authentication
  1604. if ($('.admin.new.authentication').length > 0) {
  1605. $('#auth_type').change(function () {
  1606. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls .search-page-size').hide();
  1607. $('.ldap input[required], .binddnrequired input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required], .has-tls input[required]').removeAttr('required');
  1608. $('.binddnrequired').removeClass('required');
  1609. const authType = $(this).val();
  1610. switch (authType) {
  1611. case '2': // LDAP
  1612. $('.ldap').show();
  1613. $('.binddnrequired input, .ldap div.required:not(.dldap) input').attr('required', 'required');
  1614. $('.binddnrequired').addClass('required');
  1615. break;
  1616. case '3': // SMTP
  1617. $('.smtp').show();
  1618. $('.has-tls').show();
  1619. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1620. break;
  1621. case '4': // PAM
  1622. $('.pam').show();
  1623. $('.pam input').attr('required', 'required');
  1624. break;
  1625. case '5': // LDAP
  1626. $('.dldap').show();
  1627. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1628. break;
  1629. case '6': // OAuth2
  1630. $('.oauth2').show();
  1631. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1632. onOAuth2Change();
  1633. break;
  1634. }
  1635. if (authType === '2' || authType === '5') {
  1636. onSecurityProtocolChange();
  1637. }
  1638. if (authType === '2') {
  1639. onUsePagedSearchChange();
  1640. }
  1641. });
  1642. $('#auth_type').change();
  1643. $('#security_protocol').change(onSecurityProtocolChange);
  1644. $('#use_paged_search').change(onUsePagedSearchChange);
  1645. $('#oauth2_provider').change(onOAuth2Change);
  1646. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1647. }
  1648. // Edit authentication
  1649. if ($('.admin.edit.authentication').length > 0) {
  1650. const authType = $('#auth_type').val();
  1651. if (authType === '2' || authType === '5') {
  1652. $('#security_protocol').change(onSecurityProtocolChange);
  1653. if (authType === '2') {
  1654. $('#use_paged_search').change(onUsePagedSearchChange);
  1655. }
  1656. } else if (authType === '6') {
  1657. $('#oauth2_provider').change(onOAuth2Change);
  1658. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1659. onOAuth2Change();
  1660. }
  1661. }
  1662. // Notice
  1663. if ($('.admin.notice')) {
  1664. const $detailModal = $('#detail-modal');
  1665. // Attach view detail modals
  1666. $('.view-detail').click(function () {
  1667. $detailModal.find('.content p').text($(this).data('content'));
  1668. $detailModal.modal('show');
  1669. return false;
  1670. });
  1671. // Select actions
  1672. const $checkboxes = $('.select.table .ui.checkbox');
  1673. $('.select.action').click(function () {
  1674. switch ($(this).data('action')) {
  1675. case 'select-all':
  1676. $checkboxes.checkbox('check');
  1677. break;
  1678. case 'deselect-all':
  1679. $checkboxes.checkbox('uncheck');
  1680. break;
  1681. case 'inverse':
  1682. $checkboxes.checkbox('toggle');
  1683. break;
  1684. }
  1685. });
  1686. $('#delete-selection').click(function () {
  1687. const $this = $(this);
  1688. $this.addClass('loading disabled');
  1689. const ids = [];
  1690. $checkboxes.each(function () {
  1691. if ($(this).checkbox('is checked')) {
  1692. ids.push($(this).data('id'));
  1693. }
  1694. });
  1695. $.post($this.data('link'), {
  1696. _csrf: csrf,
  1697. ids
  1698. }).done(() => {
  1699. window.location.href = $this.data('redirect');
  1700. });
  1701. });
  1702. }
  1703. }
  1704. function buttonsClickOnEnter() {
  1705. $('.ui.button').keypress(function (e) {
  1706. if (e.keyCode === 13 || e.keyCode === 32) { // enter key or space bar
  1707. $(this).click();
  1708. }
  1709. });
  1710. }
  1711. function searchUsers() {
  1712. const $searchUserBox = $('#search-user-box');
  1713. $searchUserBox.search({
  1714. minCharacters: 2,
  1715. apiSettings: {
  1716. url: `${suburl}/api/v1/users/search?q={query}`,
  1717. onResponse(response) {
  1718. const items = [];
  1719. $.each(response.data, (_i, item) => {
  1720. let title = item.login;
  1721. if (item.full_name && item.full_name.length > 0) {
  1722. title += ` (${htmlEncode(item.full_name)})`;
  1723. }
  1724. items.push({
  1725. title,
  1726. image: item.avatar_url
  1727. });
  1728. });
  1729. return { results: items };
  1730. }
  1731. },
  1732. searchFields: ['login', 'full_name'],
  1733. showNoResults: false
  1734. });
  1735. }
  1736. function searchTeams() {
  1737. const $searchTeamBox = $('#search-team-box');
  1738. $searchTeamBox.search({
  1739. minCharacters: 2,
  1740. apiSettings: {
  1741. url: `${suburl}/api/v1/orgs/${$searchTeamBox.data('org')}/teams/search?q={query}`,
  1742. headers: { 'X-Csrf-Token': csrf },
  1743. onResponse(response) {
  1744. const items = [];
  1745. $.each(response.data, (_i, item) => {
  1746. const title = `${item.name} (${item.permission} access)`;
  1747. items.push({
  1748. title,
  1749. });
  1750. });
  1751. return { results: items };
  1752. }
  1753. },
  1754. searchFields: ['name', 'description'],
  1755. showNoResults: false
  1756. });
  1757. }
  1758. function searchRepositories() {
  1759. const $searchRepoBox = $('#search-repo-box');
  1760. $searchRepoBox.search({
  1761. minCharacters: 2,
  1762. apiSettings: {
  1763. url: `${suburl}/api/v1/repos/search?q={query}&uid=${$searchRepoBox.data('uid')}`,
  1764. onResponse(response) {
  1765. const items = [];
  1766. $.each(response.data, (_i, item) => {
  1767. items.push({
  1768. title: item.full_name.split('/')[1],
  1769. description: item.full_name
  1770. });
  1771. });
  1772. return { results: items };
  1773. }
  1774. },
  1775. searchFields: ['full_name'],
  1776. showNoResults: false
  1777. });
  1778. }
  1779. function initCodeView() {
  1780. if ($('.code-view .linenums').length > 0) {
  1781. $(document).on('click', '.lines-num span', function (e) {
  1782. const $select = $(this);
  1783. const $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  1784. selectRange($list, $list.filter(`[rel=${$select.attr('id')}]`), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1785. deSelect();
  1786. });
  1787. $(window).on('hashchange', () => {
  1788. let m = window.location.hash.match(/^#(L\d+)-(L\d+)$/);
  1789. const $list = $('.code-view ol.linenums > li');
  1790. let $first;
  1791. if (m) {
  1792. $first = $list.filter(`.${m[1]}`);
  1793. selectRange($list, $first, $list.filter(`.${m[2]}`));
  1794. $('html, body').scrollTop($first.offset().top - 200);
  1795. return;
  1796. }
  1797. m = window.location.hash.match(/^#(L|n)(\d+)$/);
  1798. if (m) {
  1799. $first = $list.filter(`.L${m[2]}`);
  1800. selectRange($list, $first);
  1801. $('html, body').scrollTop($first.offset().top - 200);
  1802. }
  1803. }).trigger('hashchange');
  1804. }
  1805. $('.ui.fold-code').on('click', (e) => {
  1806. const $foldButton = $(e.target);
  1807. if ($foldButton.hasClass('fa-chevron-down')) {
  1808. $(e.target).parent().next().slideUp('fast', () => {
  1809. $foldButton.removeClass('fa-chevron-down').addClass('fa-chevron-right');
  1810. });
  1811. } else {
  1812. $(e.target).parent().next().slideDown('fast', () => {
  1813. $foldButton.removeClass('fa-chevron-right').addClass('fa-chevron-down');
  1814. });
  1815. }
  1816. });
  1817. function insertBlobExcerpt(e) {
  1818. const $blob = $(e.target);
  1819. const $row = $blob.parent().parent();
  1820. $.get(`${$blob.data('url')}?${$blob.data('query')}&anchor=${$blob.data('anchor')}`, (blob) => {
  1821. $row.replaceWith(blob);
  1822. $(`[data-anchor="${$blob.data('anchor')}"]`).on('click', (e) => { insertBlobExcerpt(e); });
  1823. });
  1824. }
  1825. $('.ui.blob-excerpt').on('click', (e) => { insertBlobExcerpt(e); });
  1826. }
  1827. function initU2FAuth() {
  1828. if ($('#wait-for-key').length === 0) {
  1829. return;
  1830. }
  1831. u2fApi.ensureSupport()
  1832. .then(() => {
  1833. $.getJSON(`${suburl}/user/u2f/challenge`).success((req) => {
  1834. u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
  1835. .then(u2fSigned)
  1836. .catch((err) => {
  1837. if (err === undefined) {
  1838. u2fError(1);
  1839. return;
  1840. }
  1841. u2fError(err.metaData.code);
  1842. });
  1843. });
  1844. }).catch(() => {
  1845. // Fallback in case browser do not support U2F
  1846. window.location.href = `${suburl}/user/two_factor`;
  1847. });
  1848. }
  1849. function u2fSigned(resp) {
  1850. $.ajax({
  1851. url: `${suburl}/user/u2f/sign`,
  1852. type: 'POST',
  1853. headers: { 'X-Csrf-Token': csrf },
  1854. data: JSON.stringify(resp),
  1855. contentType: 'application/json; charset=utf-8',
  1856. }).done((res) => {
  1857. window.location.replace(res);
  1858. }).fail(() => {
  1859. u2fError(1);
  1860. });
  1861. }
  1862. function u2fRegistered(resp) {
  1863. if (checkError(resp)) {
  1864. return;
  1865. }
  1866. $.ajax({
  1867. url: `${suburl}/user/settings/security/u2f/register`,
  1868. type: 'POST',
  1869. headers: { 'X-Csrf-Token': csrf },
  1870. data: JSON.stringify(resp),
  1871. contentType: 'application/json; charset=utf-8',
  1872. success() {
  1873. reload();
  1874. },
  1875. fail() {
  1876. u2fError(1);
  1877. }
  1878. });
  1879. }
  1880. function checkError(resp) {
  1881. if (!('errorCode' in resp)) {
  1882. return false;
  1883. }
  1884. if (resp.errorCode === 0) {
  1885. return false;
  1886. }
  1887. u2fError(resp.errorCode);
  1888. return true;
  1889. }
  1890. function u2fError(errorType) {
  1891. const u2fErrors = {
  1892. browser: $('#unsupported-browser'),
  1893. 1: $('#u2f-error-1'),
  1894. 2: $('#u2f-error-2'),
  1895. 3: $('#u2f-error-3'),
  1896. 4: $('#u2f-error-4'),
  1897. 5: $('.u2f-error-5')
  1898. };
  1899. u2fErrors[errorType].removeClass('hide');
  1900. Object.keys(u2fErrors).forEach((type) => {
  1901. if (type !== errorType) {
  1902. u2fErrors[type].addClass('hide');
  1903. }
  1904. });
  1905. $('#u2f-error').modal('show');
  1906. }
  1907. function initU2FRegister() {
  1908. $('#register-device').modal({ allowMultiple: false });
  1909. $('#u2f-error').modal({ allowMultiple: false });
  1910. $('#register-security-key').on('click', (e) => {
  1911. e.preventDefault();
  1912. u2fApi.ensureSupport()
  1913. .then(u2fRegisterRequest)
  1914. .catch(() => {
  1915. u2fError('browser');
  1916. });
  1917. });
  1918. }
  1919. function u2fRegisterRequest() {
  1920. $.post(`${suburl}/user/settings/security/u2f/request_register`, {
  1921. _csrf: csrf,
  1922. name: $('#nickname').val()
  1923. }).success((req) => {
  1924. $('#nickname').closest('div.field').removeClass('error');
  1925. $('#register-device').modal('show');
  1926. if (req.registeredKeys === null) {
  1927. req.registeredKeys = [];
  1928. }
  1929. u2fApi.register(req.appId, req.registerRequests, req.registeredKeys, 30)
  1930. .then(u2fRegistered)
  1931. .catch((reason) => {
  1932. if (reason === undefined) {
  1933. u2fError(1);
  1934. return;
  1935. }
  1936. u2fError(reason.metaData.code);
  1937. });
  1938. }).fail((xhr) => {
  1939. if (xhr.status === 409) {
  1940. $('#nickname').closest('div.field').addClass('error');
  1941. }
  1942. });
  1943. }
  1944. function initWipTitle() {
  1945. $('.title_wip_desc > a').click((e) => {
  1946. e.preventDefault();
  1947. const $issueTitle = $('#issue_title');
  1948. $issueTitle.focus();
  1949. const value = $issueTitle.val().trim().toUpperCase();
  1950. for (const i in wipPrefixes) {
  1951. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  1952. return;
  1953. }
  1954. }
  1955. $issueTitle.val(`${wipPrefixes[0]} ${$issueTitle.val()}`);
  1956. });
  1957. }
  1958. function initTemplateSearch() {
  1959. const $repoTemplate = $('#repo_template');
  1960. const checkTemplate = function () {
  1961. const $templateUnits = $('#template_units');
  1962. const $nonTemplate = $('#non_template');
  1963. if ($repoTemplate.val() !== '') {
  1964. $templateUnits.show();
  1965. $nonTemplate.hide();
  1966. } else {
  1967. $templateUnits.hide();
  1968. $nonTemplate.show();
  1969. }
  1970. };
  1971. $repoTemplate.change(checkTemplate);
  1972. checkTemplate();
  1973. const changeOwner = function () {
  1974. $('#repo_template_search')
  1975. .dropdown({
  1976. apiSettings: {
  1977. url: `${suburl}/api/v1/repos/search?q={query}&template=true&priority_owner_id=${$('#uid').val()}`,
  1978. onResponse(response) {
  1979. const filteredResponse = { success: true, results: [] };
  1980. filteredResponse.results.push({
  1981. name: '',
  1982. value: ''
  1983. });
  1984. // Parse the response from the api to work with our dropdown
  1985. $.each(response.data, (_r, repo) => {
  1986. filteredResponse.results.push({
  1987. name: htmlEncode(repo.full_name),
  1988. value: repo.id
  1989. });
  1990. });
  1991. return filteredResponse;
  1992. },
  1993. cache: false,
  1994. },
  1995. fullTextSearch: true
  1996. });
  1997. };
  1998. $('#uid').change(changeOwner);
  1999. changeOwner();
  2000. }
  2001. $(document).ready(() => {
  2002. csrf = $('meta[name=_csrf]').attr('content');
  2003. suburl = $('meta[name=_suburl]').attr('content');
  2004. // Show exact time
  2005. $('.time-since').each(function () {
  2006. $(this)
  2007. .addClass('poping up')
  2008. .attr('data-content', $(this).attr('title'))
  2009. .attr('data-variation', 'inverted tiny')
  2010. .attr('title', '');
  2011. });
  2012. // Semantic UI modules.
  2013. $('.dropdown:not(.custom)').dropdown();
  2014. $('.jump.dropdown').dropdown({
  2015. action: 'hide',
  2016. onShow() {
  2017. $('.poping.up').popup('hide');
  2018. }
  2019. });
  2020. $('.slide.up.dropdown').dropdown({
  2021. transition: 'slide up'
  2022. });
  2023. $('.upward.dropdown').dropdown({
  2024. direction: 'upward'
  2025. });
  2026. $('.ui.accordion').accordion();
  2027. $('.ui.checkbox').checkbox();
  2028. $('.ui.progress').progress({
  2029. showActivity: false
  2030. });
  2031. $('.poping.up').popup();
  2032. $('.top.menu .poping.up').popup({
  2033. onShow() {
  2034. if ($('.top.menu .menu.transition').hasClass('visible')) {
  2035. return false;
  2036. }
  2037. }
  2038. });
  2039. $('.tabular.menu .item').tab();
  2040. $('.tabable.menu .item').tab();
  2041. $('.toggle.button').click(function () {
  2042. $($(this).data('target')).slideToggle(100);
  2043. });
  2044. // make table <tr> element clickable like a link
  2045. $('tr[data-href]').click(function () {
  2046. window.location = $(this).data('href');
  2047. });
  2048. // Highlight JS
  2049. if (typeof hljs !== 'undefined') {
  2050. const nodes = [].slice.call(document.querySelectorAll('pre code') || []);
  2051. for (let i = 0; i < nodes.length; i++) {
  2052. hljs.highlightBlock(nodes[i]);
  2053. }
  2054. }
  2055. // Dropzone
  2056. const $dropzone = $('#dropzone');
  2057. if ($dropzone.length > 0) {
  2058. const filenameDict = {};
  2059. new Dropzone('#dropzone', {
  2060. url: $dropzone.data('upload-url'),
  2061. headers: { 'X-Csrf-Token': csrf },
  2062. maxFiles: $dropzone.data('max-file'),
  2063. maxFilesize: $dropzone.data('max-size'),
  2064. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  2065. addRemoveLinks: true,
  2066. dictDefaultMessage: $dropzone.data('default-message'),
  2067. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  2068. dictFileTooBig: $dropzone.data('file-too-big'),
  2069. dictRemoveFile: $dropzone.data('remove-file'),
  2070. init() {
  2071. this.on('success', (file, data) => {
  2072. filenameDict[file.name] = data.uuid;
  2073. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  2074. $('.files').append(input);
  2075. });
  2076. this.on('removedfile', (file) => {
  2077. if (file.name in filenameDict) {
  2078. $(`#${filenameDict[file.name]}`).remove();
  2079. }
  2080. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  2081. $.post($dropzone.data('remove-url'), {
  2082. file: filenameDict[file.name],
  2083. _csrf: $dropzone.data('csrf')
  2084. });
  2085. }
  2086. });
  2087. },
  2088. });
  2089. }
  2090. // Emojify
  2091. emojify.setConfig({
  2092. img_dir: `${suburl}/vendor/plugins/emojify/images`,
  2093. ignore_emoticons: true
  2094. });
  2095. const hasEmoji = document.getElementsByClassName('has-emoji');
  2096. for (let i = 0; i < hasEmoji.length; i++) {
  2097. emojify.run(hasEmoji[i]);
  2098. for (let j = 0; j < hasEmoji[i].childNodes.length; j++) {
  2099. if (hasEmoji[i].childNodes[j].nodeName === 'A') {
  2100. emojify.run(hasEmoji[i].childNodes[j]);
  2101. }
  2102. }
  2103. }
  2104. // Clipboard JS
  2105. const clipboard = new Clipboard('.clipboard');
  2106. clipboard.on('success', (e) => {
  2107. e.clearSelection();
  2108. $(`#${e.trigger.getAttribute('id')}`).popup('destroy');
  2109. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'));
  2110. $(`#${e.trigger.getAttribute('id')}`).popup('show');
  2111. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'));
  2112. });
  2113. clipboard.on('error', (e) => {
  2114. $(`#${e.trigger.getAttribute('id')}`).popup('destroy');
  2115. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'));
  2116. $(`#${e.trigger.getAttribute('id')}`).popup('show');
  2117. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'));
  2118. });
  2119. // Helpers.
  2120. $('.delete-button').click(showDeletePopup);
  2121. $('.add-all-button').click(showAddAllPopup);
  2122. $('.delete-branch-button').click(showDeletePopup);
  2123. $('.undo-button').click(function () {
  2124. const $this = $(this);
  2125. $.post($this.data('url'), {
  2126. _csrf: csrf,
  2127. id: $this.data('id')
  2128. }).done((data) => {
  2129. window.location.href = data.redirect;
  2130. });
  2131. });
  2132. $('.show-panel.button').click(function () {
  2133. $($(this).data('panel')).show();
  2134. });
  2135. $('.show-modal.button').click(function () {
  2136. $($(this).data('modal')).modal('show');
  2137. });
  2138. $('.delete-post.button').click(function () {
  2139. const $this = $(this);
  2140. $.post($this.data('request-url'), {
  2141. _csrf: csrf
  2142. }).done(() => {
  2143. window.location.href = $this.data('done-url');
  2144. });
  2145. });
  2146. // Set anchor.
  2147. $('.markdown').each(function () {
  2148. const headers = {};
  2149. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  2150. let node = $(this);
  2151. const val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  2152. let name = val;
  2153. if (headers[val] > 0) {
  2154. name = `${val}-${headers[val]}`;
  2155. }
  2156. if (headers[val] === undefined) {
  2157. headers[val] = 1;
  2158. } else {
  2159. headers[val] += 1;
  2160. }
  2161. node = node.wrap(`<div id="${name}" class="anchor-wrap" ></div>`);
  2162. node.append(`<a class="anchor" href="#${name}"><span class="octicon octicon-link"></span></a>`);
  2163. });
  2164. });
  2165. $('.issue-checkbox').click(() => {
  2166. const numChecked = $('.issue-checkbox').children('input:checked').length;
  2167. if (numChecked > 0) {
  2168. $('#issue-filters').addClass('hide');
  2169. $('#issue-actions').removeClass('hide');
  2170. } else {
  2171. $('#issue-filters').removeClass('hide');
  2172. $('#issue-actions').addClass('hide');
  2173. }
  2174. });
  2175. $('.issue-action').click(function () {
  2176. let { action } = this.dataset;
  2177. let { elementId } = this.dataset;
  2178. const issueIDs = $('.issue-checkbox').children('input:checked').map(function () {
  2179. return this.dataset.issueId;
  2180. }).get().join();
  2181. const { url } = this.dataset;
  2182. if (elementId === '0' && url.substr(-9) === '/assignee') {
  2183. elementId = '';
  2184. action = 'clear';
  2185. }
  2186. updateIssuesMeta(url, action, issueIDs, elementId).then(() => {
  2187. // NOTICE: This reset of checkbox state targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2188. if (action === 'close' || action === 'open') {
  2189. // uncheck all checkboxes
  2190. $('.issue-checkbox input[type="checkbox"]').each((_, e) => { e.checked = false; });
  2191. }
  2192. reload();
  2193. });
  2194. });
  2195. // NOTICE: This event trigger targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2196. // trigger ckecked event, if checkboxes are checked on load
  2197. $('.issue-checkbox input[type="checkbox"]:checked').first().each((_, e) => {
  2198. e.checked = false;
  2199. $(e).click();
  2200. });
  2201. buttonsClickOnEnter();
  2202. searchUsers();
  2203. searchTeams();
  2204. searchRepositories();
  2205. initCommentForm();
  2206. initInstall();
  2207. initRepository();
  2208. initMigration();
  2209. initWikiForm();
  2210. initEditForm();
  2211. initEditor();
  2212. initOrganization();
  2213. initGithook();
  2214. initWebhook();
  2215. initAdmin();
  2216. initCodeView();
  2217. initVueApp();
  2218. initTeamSettings();
  2219. initCtrlEnterSubmit();
  2220. initNavbarContentToggle();
  2221. initTopicbar();
  2222. initU2FAuth();
  2223. initU2FRegister();
  2224. initIssueList();
  2225. initWipTitle();
  2226. initPullRequestReview();
  2227. initRepoStatusChecker();
  2228. initTemplateSearch();
  2229. // Repo clone url.
  2230. if ($('#repo-clone-url').length > 0) {
  2231. switch (localStorage.getItem('repo-clone-protocol')) {
  2232. case 'ssh':
  2233. if ($('#repo-clone-ssh').click().length === 0) {
  2234. $('#repo-clone-https').click();
  2235. }
  2236. break;
  2237. default:
  2238. $('#repo-clone-https').click();
  2239. break;
  2240. }
  2241. }
  2242. const routes = {
  2243. 'div.user.settings': initUserSettings,
  2244. 'div.repository.settings.collaboration': initRepositoryCollaboration
  2245. };
  2246. let selector;
  2247. for (selector in routes) {
  2248. if ($(selector).length > 0) {
  2249. routes[selector]();
  2250. break;
  2251. }
  2252. }
  2253. const $cloneAddr = $('#clone_addr');
  2254. $cloneAddr.change(() => {
  2255. const $repoName = $('#repo_name');
  2256. if ($cloneAddr.val().length > 0 && $repoName.val().length === 0) { // Only modify if repo_name input is blank
  2257. $repoName.val($cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]);
  2258. }
  2259. });
  2260. });
  2261. function changeHash(hash) {
  2262. if (window.history.pushState) {
  2263. window.history.pushState(null, null, hash);
  2264. } else {
  2265. window.location.hash = hash;
  2266. }
  2267. }
  2268. function deSelect() {
  2269. if (window.getSelection) {
  2270. window.getSelection().removeAllRanges();
  2271. } else {
  2272. document.selection.empty();
  2273. }
  2274. }
  2275. function selectRange($list, $select, $from) {
  2276. $list.removeClass('active');
  2277. if ($from) {
  2278. let a = parseInt($select.attr('rel').substr(1));
  2279. let b = parseInt($from.attr('rel').substr(1));
  2280. let c;
  2281. if (a !== b) {
  2282. if (a > b) {
  2283. c = a;
  2284. a = b;
  2285. b = c;
  2286. }
  2287. const classes = [];
  2288. for (let i = a; i <= b; i++) {
  2289. classes.push(`.L${i}`);
  2290. }
  2291. $list.filter(classes.join(',')).addClass('active');
  2292. changeHash(`#L${a}-L${b}`);
  2293. return;
  2294. }
  2295. }
  2296. $select.addClass('active');
  2297. changeHash(`#${$select.attr('rel')}`);
  2298. }
  2299. $(() => {
  2300. // Warn users that try to leave a page after entering data into a form.
  2301. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  2302. if ($('.user.signin').length === 0) {
  2303. $('form:not(.ignore-dirty)').areYouSure();
  2304. }
  2305. // Parse SSH Key
  2306. $('#ssh-key-content').on('change paste keyup', function () {
  2307. const arrays = $(this).val().split(' ');
  2308. const $title = $('#ssh-key-title');
  2309. if ($title.val() === '' && arrays.length === 3 && arrays[2] !== '') {
  2310. $title.val(arrays[2]);
  2311. }
  2312. });
  2313. });
  2314. function showDeletePopup() {
  2315. const $this = $(this);
  2316. let filter = '';
  2317. if ($this.attr('id')) {
  2318. filter += `#${$this.attr('id')}`;
  2319. }
  2320. const dialog = $(`.delete.modal${filter}`);
  2321. dialog.find('.name').text($this.data('name'));
  2322. dialog.modal({
  2323. closable: false,
  2324. onApprove() {
  2325. if ($this.data('type') === 'form') {
  2326. $($this.data('form')).submit();
  2327. return;
  2328. }
  2329. $.post($this.data('url'), {
  2330. _csrf: csrf,
  2331. id: $this.data('id')
  2332. }).done((data) => {
  2333. window.location.href = data.redirect;
  2334. });
  2335. }
  2336. }).modal('show');
  2337. return false;
  2338. }
  2339. function showAddAllPopup() {
  2340. const $this = $(this);
  2341. let filter = '';
  2342. if ($this.attr('id')) {
  2343. filter += `#${$this.attr('id')}`;
  2344. }
  2345. const dialog = $(`.addall.modal${filter}`);
  2346. dialog.find('.name').text($this.data('name'));
  2347. dialog.modal({
  2348. closable: false,
  2349. onApprove() {
  2350. if ($this.data('type') === 'form') {
  2351. $($this.data('form')).submit();
  2352. return;
  2353. }
  2354. $.post($this.data('url'), {
  2355. _csrf: csrf,
  2356. id: $this.data('id')
  2357. }).done((data) => {
  2358. window.location.href = data.redirect;
  2359. });
  2360. }
  2361. }).modal('show');
  2362. return false;
  2363. }
  2364. function initVueComponents() {
  2365. const vueDelimeters = ['${', '}'];
  2366. Vue.component('repo-search', {
  2367. delimiters: vueDelimeters,
  2368. props: {
  2369. searchLimit: {
  2370. type: Number,
  2371. default: 10
  2372. },
  2373. suburl: {
  2374. type: String,
  2375. required: true
  2376. },
  2377. uid: {
  2378. type: Number,
  2379. required: true
  2380. },
  2381. organizations: {
  2382. type: Array,
  2383. default: []
  2384. },
  2385. isOrganization: {
  2386. type: Boolean,
  2387. default: true
  2388. },
  2389. canCreateOrganization: {
  2390. type: Boolean,
  2391. default: false
  2392. },
  2393. organizationsTotalCount: {
  2394. type: Number,
  2395. default: 0
  2396. },
  2397. moreReposLink: {
  2398. type: String,
  2399. default: ''
  2400. }
  2401. },
  2402. data() {
  2403. return {
  2404. tab: 'repos',
  2405. repos: [],
  2406. reposTotalCount: 0,
  2407. reposFilter: 'all',
  2408. searchQuery: '',
  2409. isLoading: false,
  2410. repoTypes: {
  2411. all: {
  2412. count: 0,
  2413. searchMode: '',
  2414. },
  2415. forks: {
  2416. count: 0,
  2417. searchMode: 'fork',
  2418. },
  2419. mirrors: {
  2420. count: 0,
  2421. searchMode: 'mirror',
  2422. },
  2423. sources: {
  2424. count: 0,
  2425. searchMode: 'source',
  2426. },
  2427. collaborative: {
  2428. count: 0,
  2429. searchMode: 'collaborative',
  2430. },
  2431. }
  2432. };
  2433. },
  2434. computed: {
  2435. showMoreReposLink() {
  2436. return this.repos.length > 0 && this.repos.length < this.repoTypes[this.reposFilter].count;
  2437. },
  2438. searchURL() {
  2439. return `${this.suburl}/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&q=${this.searchQuery
  2440. }&limit=${this.searchLimit}&mode=${this.repoTypes[this.reposFilter].searchMode
  2441. }${this.reposFilter !== 'all' ? '&exclusive=1' : ''}`;
  2442. },
  2443. repoTypeCount() {
  2444. return this.repoTypes[this.reposFilter].count;
  2445. }
  2446. },
  2447. mounted() {
  2448. this.searchRepos(this.reposFilter);
  2449. const self = this;
  2450. Vue.nextTick(() => {
  2451. self.$refs.search.focus();
  2452. });
  2453. },
  2454. methods: {
  2455. changeTab(t) {
  2456. this.tab = t;
  2457. },
  2458. changeReposFilter(filter) {
  2459. this.reposFilter = filter;
  2460. this.repos = [];
  2461. this.repoTypes[filter].count = 0;
  2462. this.searchRepos(filter);
  2463. },
  2464. showRepo(repo, filter) {
  2465. switch (filter) {
  2466. case 'sources':
  2467. return repo.owner.id === this.uid && !repo.mirror && !repo.fork;
  2468. case 'forks':
  2469. return repo.owner.id === this.uid && !repo.mirror && repo.fork;
  2470. case 'mirrors':
  2471. return repo.mirror;
  2472. case 'collaborative':
  2473. return repo.owner.id !== this.uid && !repo.mirror;
  2474. default:
  2475. return true;
  2476. }
  2477. },
  2478. searchRepos(reposFilter) {
  2479. const self = this;
  2480. this.isLoading = true;
  2481. const searchedMode = this.repoTypes[reposFilter].searchMode;
  2482. const searchedURL = this.searchURL;
  2483. const searchedQuery = this.searchQuery;
  2484. $.getJSON(searchedURL, (result, _textStatus, request) => {
  2485. if (searchedURL === self.searchURL) {
  2486. self.repos = result.data;
  2487. const count = request.getResponseHeader('X-Total-Count');
  2488. if (searchedQuery === '' && searchedMode === '') {
  2489. self.reposTotalCount = count;
  2490. }
  2491. self.repoTypes[reposFilter].count = count;
  2492. }
  2493. }).always(() => {
  2494. if (searchedURL === self.searchURL) {
  2495. self.isLoading = false;
  2496. }
  2497. });
  2498. },
  2499. repoClass(repo) {
  2500. if (repo.fork) {
  2501. return 'octicon octicon-repo-forked';
  2502. } if (repo.mirror) {
  2503. return 'octicon octicon-repo-clone';
  2504. } if (repo.private) {
  2505. return 'octicon octicon-lock';
  2506. }
  2507. return 'octicon octicon-repo';
  2508. }
  2509. }
  2510. });
  2511. }
  2512. function initCtrlEnterSubmit() {
  2513. $('.js-quick-submit').keydown(function (e) {
  2514. if (((e.ctrlKey && !e.altKey) || e.metaKey) && (e.keyCode === 13 || e.keyCode === 10)) {
  2515. $(this).closest('form').submit();
  2516. }
  2517. });
  2518. }
  2519. function initVueApp() {
  2520. const el = document.getElementById('app');
  2521. if (!el) {
  2522. return;
  2523. }
  2524. initVueComponents();
  2525. new Vue({
  2526. delimiters: ['${', '}'],
  2527. el,
  2528. data: {
  2529. searchLimit: document.querySelector('meta[name=_search_limit]').content,
  2530. suburl: document.querySelector('meta[name=_suburl]').content,
  2531. uid: document.querySelector('meta[name=_context_uid]').content,
  2532. },
  2533. });
  2534. }
  2535. window.timeAddManual = function () {
  2536. $('.mini.modal')
  2537. .modal({
  2538. duration: 200,
  2539. onApprove() {
  2540. $('#add_time_manual_form').submit();
  2541. }
  2542. }).modal('show');
  2543. };
  2544. window.toggleStopwatch = function () {
  2545. $('#toggle_stopwatch_form').submit();
  2546. };
  2547. window.cancelStopwatch = function () {
  2548. $('#cancel_stopwatch_form').submit();
  2549. };
  2550. window.initHeatmap = function (appElementId, heatmapUser, locale) {
  2551. const el = document.getElementById(appElementId);
  2552. if (!el) {
  2553. return;
  2554. }
  2555. locale = locale || {};
  2556. locale.contributions = locale.contributions || 'contributions';
  2557. locale.no_contributions = locale.no_contributions || 'No contributions';
  2558. const vueDelimeters = ['${', '}'];
  2559. Vue.component('activity-heatmap', {
  2560. delimiters: vueDelimeters,
  2561. props: {
  2562. user: {
  2563. type: String,
  2564. required: true
  2565. },
  2566. suburl: {
  2567. type: String,
  2568. required: true
  2569. },
  2570. locale: {
  2571. type: Object,
  2572. required: true
  2573. }
  2574. },
  2575. data() {
  2576. return {
  2577. isLoading: true,
  2578. colorRange: [],
  2579. endDate: null,
  2580. values: [],
  2581. totalContributions: 0,
  2582. };
  2583. },
  2584. mounted() {
  2585. this.colorRange = [
  2586. this.getColor(0),
  2587. this.getColor(1),
  2588. this.getColor(2),
  2589. this.getColor(3),
  2590. this.getColor(4),
  2591. this.getColor(5)
  2592. ];
  2593. this.endDate = new Date();
  2594. this.loadHeatmap(this.user);
  2595. },
  2596. methods: {
  2597. loadHeatmap(userName) {
  2598. const self = this;
  2599. $.get(`${this.suburl}/api/v1/users/${userName}/heatmap`, (chartRawData) => {
  2600. const chartData = [];
  2601. for (let i = 0; i < chartRawData.length; i++) {
  2602. self.totalContributions += chartRawData[i].contributions;
  2603. chartData[i] = { date: new Date(chartRawData[i].timestamp * 1000), count: chartRawData[i].contributions };
  2604. }
  2605. self.values = chartData;
  2606. self.isLoading = false;
  2607. });
  2608. },
  2609. getColor(idx) {
  2610. const el = document.createElement('div');
  2611. el.className = `heatmap-color-${idx}`;
  2612. document.body.appendChild(el);
  2613. const color = getComputedStyle(el).backgroundColor;
  2614. document.body.removeChild(el);
  2615. return color;
  2616. }
  2617. },
  2618. template: '<div><div v-show="isLoading"><slot name="loading"></slot></div><h4 class="total-contributions" v-if="!isLoading"><span v-html="totalContributions"></span> total contributions in the last 12 months</h4><calendar-heatmap v-show="!isLoading" :locale="locale" :no-data-text="locale.no_contributions" :tooltip-unit="locale.contributions" :end-date="endDate" :values="values" :range-color="colorRange" />'
  2619. });
  2620. new Vue({
  2621. delimiters: vueDelimeters,
  2622. el,
  2623. data: {
  2624. suburl: document.querySelector('meta[name=_suburl]').content,
  2625. heatmapUser,
  2626. locale
  2627. },
  2628. });
  2629. };
  2630. function initFilterBranchTagDropdown(selector) {
  2631. $(selector).each(function () {
  2632. const $dropdown = $(this);
  2633. const $data = $dropdown.find('.data');
  2634. const data = {
  2635. items: [],
  2636. mode: $data.data('mode'),
  2637. searchTerm: '',
  2638. noResults: '',
  2639. canCreateBranch: false,
  2640. menuVisible: false,
  2641. active: 0
  2642. };
  2643. $data.find('.item').each(function () {
  2644. data.items.push({
  2645. name: $(this).text(),
  2646. url: $(this).data('url'),
  2647. branch: $(this).hasClass('branch'),
  2648. tag: $(this).hasClass('tag'),
  2649. selected: $(this).hasClass('selected')
  2650. });
  2651. });
  2652. $data.remove();
  2653. new Vue({
  2654. delimiters: ['${', '}'],
  2655. el: this,
  2656. data,
  2657. beforeMount() {
  2658. const vm = this;
  2659. this.noResults = vm.$el.getAttribute('data-no-results');
  2660. this.canCreateBranch = vm.$el.getAttribute('data-can-create-branch') === 'true';
  2661. document.body.addEventListener('click', (event) => {
  2662. if (vm.$el.contains(event.target)) {
  2663. return;
  2664. }
  2665. if (vm.menuVisible) {
  2666. Vue.set(vm, 'menuVisible', false);
  2667. }
  2668. });
  2669. },
  2670. watch: {
  2671. menuVisible(visible) {
  2672. if (visible) {
  2673. this.focusSearchField();
  2674. }
  2675. }
  2676. },
  2677. computed: {
  2678. filteredItems() {
  2679. const vm = this;
  2680. const items = vm.items.filter((item) => {
  2681. return ((vm.mode === 'branches' && item.branch) || (vm.mode === 'tags' && item.tag))
  2682. && (!vm.searchTerm || item.name.toLowerCase().indexOf(vm.searchTerm.toLowerCase()) >= 0);
  2683. });
  2684. vm.active = (items.length === 0 && vm.showCreateNewBranch ? 0 : -1);
  2685. return items;
  2686. },
  2687. showNoResults() {
  2688. return this.filteredItems.length === 0 && !this.showCreateNewBranch;
  2689. },
  2690. showCreateNewBranch() {
  2691. const vm = this;
  2692. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') {
  2693. return false;
  2694. }
  2695. return vm.items.filter((item) => item.name.toLowerCase() === vm.searchTerm.toLowerCase()).length === 0;
  2696. }
  2697. },
  2698. methods: {
  2699. selectItem(item) {
  2700. const prev = this.getSelected();
  2701. if (prev !== null) {
  2702. prev.selected = false;
  2703. }
  2704. item.selected = true;
  2705. window.location.href = item.url;
  2706. },
  2707. createNewBranch() {
  2708. if (!this.showCreateNewBranch) {
  2709. return;
  2710. }
  2711. this.$refs.newBranchForm.submit();
  2712. },
  2713. focusSearchField() {
  2714. const vm = this;
  2715. Vue.nextTick(() => {
  2716. vm.$refs.searchField.focus();
  2717. });
  2718. },
  2719. getSelected() {
  2720. for (let i = 0, j = this.items.length; i < j; ++i) {
  2721. if (this.items[i].selected) return this.items[i];
  2722. }
  2723. return null;
  2724. },
  2725. getSelectedIndexInFiltered() {
  2726. for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
  2727. if (this.filteredItems[i].selected) return i;
  2728. }
  2729. return -1;
  2730. },
  2731. scrollToActive() {
  2732. let el = this.$refs[`listItem${this.active}`];
  2733. if (!el || el.length === 0) {
  2734. return;
  2735. }
  2736. if (Array.isArray(el)) {
  2737. el = el[0];
  2738. }
  2739. const cont = this.$refs.scrollContainer;
  2740. if (el.offsetTop < cont.scrollTop) {
  2741. cont.scrollTop = el.offsetTop;
  2742. } else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
  2743. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  2744. }
  2745. },
  2746. keydown(event) {
  2747. const vm = this;
  2748. if (event.keyCode === 40) {
  2749. // arrow down
  2750. event.preventDefault();
  2751. if (vm.active === -1) {
  2752. vm.active = vm.getSelectedIndexInFiltered();
  2753. }
  2754. if (vm.active + (vm.showCreateNewBranch ? 0 : 1) >= vm.filteredItems.length) {
  2755. return;
  2756. }
  2757. vm.active++;
  2758. vm.scrollToActive();
  2759. }
  2760. if (event.keyCode === 38) {
  2761. // arrow up
  2762. event.preventDefault();
  2763. if (vm.active === -1) {
  2764. vm.active = vm.getSelectedIndexInFiltered();
  2765. }
  2766. if (vm.active <= 0) {
  2767. return;
  2768. }
  2769. vm.active--;
  2770. vm.scrollToActive();
  2771. }
  2772. if (event.keyCode === 13) {
  2773. // enter
  2774. event.preventDefault();
  2775. if (vm.active >= vm.filteredItems.length) {
  2776. vm.createNewBranch();
  2777. } else if (vm.active >= 0) {
  2778. vm.selectItem(vm.filteredItems[vm.active]);
  2779. }
  2780. }
  2781. if (event.keyCode === 27) {
  2782. // escape
  2783. event.preventDefault();
  2784. vm.menuVisible = false;
  2785. }
  2786. }
  2787. }
  2788. });
  2789. });
  2790. }
  2791. $('.commit-button').click(function (e) {
  2792. e.preventDefault();
  2793. $(this).parent().find('.commit-body').toggle();
  2794. });
  2795. function initNavbarContentToggle() {
  2796. const content = $('#navbar');
  2797. const toggle = $('#navbar-expand-toggle');
  2798. let isExpanded = false;
  2799. toggle.click(() => {
  2800. isExpanded = !isExpanded;
  2801. if (isExpanded) {
  2802. content.addClass('shown');
  2803. toggle.addClass('active');
  2804. } else {
  2805. content.removeClass('shown');
  2806. toggle.removeClass('active');
  2807. }
  2808. });
  2809. }
  2810. function initTopicbar() {
  2811. const mgrBtn = $('#manage_topic');
  2812. const editDiv = $('#topic_edit');
  2813. const viewDiv = $('#repo-topics');
  2814. const saveBtn = $('#save_topic');
  2815. const topicDropdown = $('#topic_edit .dropdown');
  2816. const topicForm = $('#topic_edit.ui.form');
  2817. const topicPrompts = getPrompts();
  2818. mgrBtn.click(() => {
  2819. viewDiv.hide();
  2820. editDiv.css('display', ''); // show Semantic UI Grid
  2821. });
  2822. function getPrompts() {
  2823. const hidePrompt = $('div.hide#validate_prompt');
  2824. const prompts = {
  2825. countPrompt: hidePrompt.children('#count_prompt').text(),
  2826. formatPrompt: hidePrompt.children('#format_prompt').text()
  2827. };
  2828. hidePrompt.remove();
  2829. return prompts;
  2830. }
  2831. saveBtn.click(() => {
  2832. const topics = $('input[name=topics]').val();
  2833. $.post(saveBtn.data('link'), {
  2834. _csrf: csrf,
  2835. topics
  2836. }, (_data, _textStatus, xhr) => {
  2837. if (xhr.responseJSON.status === 'ok') {
  2838. viewDiv.children('.topic').remove();
  2839. if (topics.length) {
  2840. const topicArray = topics.split(',');
  2841. const last = viewDiv.children('a').last();
  2842. for (let i = 0; i < topicArray.length; i++) {
  2843. $(`<div class="ui small label topic" style="cursor:pointer;">${topicArray[i]}</div>`).insertBefore(last);
  2844. }
  2845. }
  2846. editDiv.css('display', 'none');
  2847. viewDiv.show();
  2848. }
  2849. }).fail((xhr) => {
  2850. if (xhr.status === 422) {
  2851. if (xhr.responseJSON.invalidTopics.length > 0) {
  2852. topicPrompts.formatPrompt = xhr.responseJSON.message;
  2853. const { invalidTopics } = xhr.responseJSON;
  2854. const topicLables = topicDropdown.children('a.ui.label');
  2855. topics.split(',').forEach((value, index) => {
  2856. for (let i = 0; i < invalidTopics.length; i++) {
  2857. if (invalidTopics[i] === value) {
  2858. topicLables.eq(index).removeClass('green').addClass('red');
  2859. }
  2860. }
  2861. });
  2862. } else {
  2863. topicPrompts.countPrompt = xhr.responseJSON.message;
  2864. }
  2865. }
  2866. }).always(() => {
  2867. topicForm.form('validate form');
  2868. });
  2869. });
  2870. topicDropdown.dropdown({
  2871. allowAdditions: true,
  2872. forceSelection: false,
  2873. fields: { name: 'description', value: 'data-value' },
  2874. saveRemoteData: false,
  2875. label: {
  2876. transition: 'horizontal flip',
  2877. duration: 200,
  2878. variation: false,
  2879. blue: true,
  2880. basic: true,
  2881. },
  2882. className: {
  2883. label: 'ui small label'
  2884. },
  2885. apiSettings: {
  2886. url: `${suburl}/api/v1/topics/search?q={query}`,
  2887. throttle: 500,
  2888. cache: false,
  2889. onResponse(res) {
  2890. const formattedResponse = {
  2891. success: false,
  2892. results: [],
  2893. };
  2894. const stripTags = function (text) {
  2895. return text.replace(/<[^>]*>?/gm, '');
  2896. };
  2897. const query = stripTags(this.urlData.query.trim());
  2898. let found_query = false;
  2899. const current_topics = [];
  2900. topicDropdown.find('div.label.visible.topic,a.label.visible').each((_, e) => { current_topics.push(e.dataset.value); });
  2901. if (res.topics) {
  2902. let found = false;
  2903. for (let i = 0; i < res.topics.length; i++) {
  2904. // skip currently added tags
  2905. if (current_topics.indexOf(res.topics[i].topic_name) !== -1) {
  2906. continue;
  2907. }
  2908. if (res.topics[i].topic_name.toLowerCase() === query.toLowerCase()) {
  2909. found_query = true;
  2910. }
  2911. formattedResponse.results.push({ description: res.topics[i].topic_name, 'data-value': res.topics[i].topic_name });
  2912. found = true;
  2913. }
  2914. formattedResponse.success = found;
  2915. }
  2916. if (query.length > 0 && !found_query) {
  2917. formattedResponse.success = true;
  2918. formattedResponse.results.unshift({ description: query, 'data-value': query });
  2919. } else if (query.length > 0 && found_query) {
  2920. formattedResponse.results.sort((a, b) => {
  2921. if (a.description.toLowerCase() === query.toLowerCase()) return -1;
  2922. if (b.description.toLowerCase() === query.toLowerCase()) return 1;
  2923. if (a.description > b.description) return -1;
  2924. if (a.description < b.description) return 1;
  2925. return 0;
  2926. });
  2927. }
  2928. return formattedResponse;
  2929. },
  2930. },
  2931. onLabelCreate(value) {
  2932. value = value.toLowerCase().trim();
  2933. this.attr('data-value', value).contents().first().replaceWith(value);
  2934. return $(this);
  2935. },
  2936. onAdd(addedValue, _addedText, $addedChoice) {
  2937. addedValue = addedValue.toLowerCase().trim();
  2938. $($addedChoice).attr('data-value', addedValue);
  2939. $($addedChoice).attr('data-text', addedValue);
  2940. }
  2941. });
  2942. $.fn.form.settings.rules.validateTopic = function (_values, regExp) {
  2943. const topics = topicDropdown.children('a.ui.label');
  2944. const status = topics.length === 0 || topics.last().attr('data-value').match(regExp);
  2945. if (!status) {
  2946. topics.last().removeClass('green').addClass('red');
  2947. }
  2948. return status && topicDropdown.children('a.ui.label.red').length === 0;
  2949. };
  2950. topicForm.form({
  2951. on: 'change',
  2952. inline: true,
  2953. fields: {
  2954. topics: {
  2955. identifier: 'topics',
  2956. rules: [
  2957. {
  2958. type: 'validateTopic',
  2959. value: /^[a-z0-9][a-z0-9-]{1,35}$/,
  2960. prompt: topicPrompts.formatPrompt
  2961. },
  2962. {
  2963. type: 'maxCount[25]',
  2964. prompt: topicPrompts.countPrompt
  2965. }
  2966. ]
  2967. },
  2968. }
  2969. });
  2970. }
  2971. window.toggleDeadlineForm = function () {
  2972. $('#deadlineForm').fadeToggle(150);
  2973. };
  2974. window.setDeadline = function () {
  2975. const deadline = $('#deadlineDate').val();
  2976. window.updateDeadline(deadline);
  2977. };
  2978. window.updateDeadline = function (deadlineString) {
  2979. $('#deadline-err-invalid-date').hide();
  2980. $('#deadline-loader').addClass('loading');
  2981. let realDeadline = null;
  2982. if (deadlineString !== '') {
  2983. const newDate = Date.parse(deadlineString);
  2984. if (Number.isNaN(newDate)) {
  2985. $('#deadline-loader').removeClass('loading');
  2986. $('#deadline-err-invalid-date').show();
  2987. return false;
  2988. }
  2989. realDeadline = new Date(newDate);
  2990. }
  2991. $.ajax(`${$('#update-issue-deadline-form').attr('action')}/deadline`, {
  2992. data: JSON.stringify({
  2993. due_date: realDeadline,
  2994. }),
  2995. headers: {
  2996. 'X-Csrf-Token': csrf,
  2997. 'X-Remote': true,
  2998. },
  2999. contentType: 'application/json',
  3000. type: 'POST',
  3001. success() {
  3002. reload();
  3003. },
  3004. error() {
  3005. $('#deadline-loader').removeClass('loading');
  3006. $('#deadline-err-invalid-date').show();
  3007. }
  3008. });
  3009. };
  3010. window.deleteDependencyModal = function (id, type) {
  3011. $('.remove-dependency')
  3012. .modal({
  3013. closable: false,
  3014. duration: 200,
  3015. onApprove() {
  3016. $('#removeDependencyID').val(id);
  3017. $('#dependencyType').val(type);
  3018. $('#removeDependencyForm').submit();
  3019. }
  3020. }).modal('show');
  3021. };
  3022. function initIssueList() {
  3023. const repolink = $('#repolink').val();
  3024. const repoId = $('#repoId').val();
  3025. const crossRepoSearch = $('#crossRepoSearch').val();
  3026. let issueSearchUrl = `${suburl}/api/v1/repos/${repolink}/issues?q={query}`;
  3027. if (crossRepoSearch === 'true') {
  3028. issueSearchUrl = `${suburl}/api/v1/repos/issues/search?q={query}&priority_repo_id=${repoId}`;
  3029. }
  3030. $('#new-dependency-drop-list')
  3031. .dropdown({
  3032. apiSettings: {
  3033. url: issueSearchUrl,
  3034. onResponse(response) {
  3035. const filteredResponse = { success: true, results: [] };
  3036. const currIssueId = $('#new-dependency-drop-list').data('issue-id');
  3037. // Parse the response from the api to work with our dropdown
  3038. $.each(response, (_i, issue) => {
  3039. // Don't list current issue in the dependency list.
  3040. if (issue.id === currIssueId) {
  3041. return;
  3042. }
  3043. filteredResponse.results.push({
  3044. name: `#${issue.number} ${htmlEncode(issue.title)
  3045. }<div class="text small dont-break-out">${htmlEncode(issue.repository.full_name)}</div>`,
  3046. value: issue.id
  3047. });
  3048. });
  3049. return filteredResponse;
  3050. },
  3051. cache: false,
  3052. },
  3053. fullTextSearch: true
  3054. });
  3055. $('.menu a.label-filter-item').each(function () {
  3056. $(this).click(function (e) {
  3057. if (e.altKey) {
  3058. e.preventDefault();
  3059. const href = $(this).attr('href');
  3060. const id = $(this).data('label-id');
  3061. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  3062. const newStr = 'labels=$1-$2$3&';
  3063. window.location = href.replace(new RegExp(regStr), newStr);
  3064. }
  3065. });
  3066. });
  3067. $('.menu .ui.dropdown.label-filter').keydown((e) => {
  3068. if (e.altKey && e.keyCode === 13) {
  3069. const selectedItems = $('.menu .ui.dropdown.label-filter .menu .item.selected');
  3070. if (selectedItems.length > 0) {
  3071. const item = $(selectedItems[0]);
  3072. const href = item.attr('href');
  3073. const id = item.data('label-id');
  3074. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  3075. const newStr = 'labels=$1-$2$3&';
  3076. window.location = href.replace(new RegExp(regStr), newStr);
  3077. }
  3078. }
  3079. });
  3080. }
  3081. window.cancelCodeComment = function (btn) {
  3082. const form = $(btn).closest('form');
  3083. if (form.length > 0 && form.hasClass('comment-form')) {
  3084. form.addClass('hide');
  3085. form.parent().find('button.comment-form-reply').show();
  3086. } else {
  3087. form.closest('.comment-code-cloud').remove();
  3088. }
  3089. };
  3090. window.onOAuthLoginClick = function () {
  3091. const oauthLoader = $('#oauth2-login-loader');
  3092. const oauthNav = $('#oauth2-login-navigator');
  3093. oauthNav.hide();
  3094. oauthLoader.removeClass('disabled');
  3095. setTimeout(() => {
  3096. // recover previous content to let user try again
  3097. // usually redirection will be performed before this action
  3098. oauthLoader.addClass('disabled');
  3099. oauthNav.show();
  3100. }, 5000);
  3101. };