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 107KB

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