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

index.js 105KB

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