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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586
  1. /* globals wipPrefixes */
  2. /* exported timeAddManual, toggleStopwatch, cancelStopwatch */
  3. /* exported toggleDeadlineForm, setDeadline, updateDeadline, deleteDependencyModal, cancelCodeComment, onOAuthLoginClick */
  4. import './publicpath.js';
  5. import './polyfills.js';
  6. import Vue from 'vue';
  7. import {htmlEscape} from 'escape-goat';
  8. import 'jquery.are-you-sure';
  9. import './vendor/semanticdropdown.js';
  10. import {svg} from './utils.js';
  11. import initContextPopups from './features/contextpopup.js';
  12. import initGitGraph from './features/gitgraph.js';
  13. import initClipboard from './features/clipboard.js';
  14. import initUserHeatmap from './features/userheatmap.js';
  15. import initDateTimePicker from './features/datetimepicker.js';
  16. import initServiceWorker from './features/serviceworker.js';
  17. import {initTribute, issuesTribute, emojiTribute} from './features/tribute.js';
  18. import createDropzone from './features/dropzone.js';
  19. import highlight from './features/highlight.js';
  20. import ActivityTopAuthors from './components/ActivityTopAuthors.vue';
  21. import {initNotificationsTable, initNotificationCount} from './features/notification.js';
  22. import {createCodeEditor} from './features/codeeditor.js';
  23. const {AppSubUrl, StaticUrlPrefix, csrf} = window.config;
  24. let previewFileModes;
  25. const commentMDEditors = {};
  26. // Silence fomantic's error logging when tabs are used without a target content element
  27. $.fn.tab.settings.silent = true;
  28. function initCommentPreviewTab($form) {
  29. const $tabMenu = $form.find('.tabular.menu');
  30. $tabMenu.find('.item').tab();
  31. $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`).on('click', function () {
  32. const $this = $(this);
  33. $.post($this.data('url'), {
  34. _csrf: csrf,
  35. mode: 'comment',
  36. context: $this.data('context'),
  37. text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val()
  38. }, (data) => {
  39. const $previewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('preview')}"]`);
  40. $previewPanel.html(data);
  41. $('pre code', $previewPanel[0]).each(function () {
  42. highlight(this);
  43. });
  44. });
  45. });
  46. buttonsClickOnEnter();
  47. }
  48. function initEditPreviewTab($form) {
  49. const $tabMenu = $form.find('.tabular.menu');
  50. $tabMenu.find('.item').tab();
  51. const $previewTab = $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`);
  52. if ($previewTab.length) {
  53. previewFileModes = $previewTab.data('preview-file-modes').split(',');
  54. $previewTab.on('click', function () {
  55. const $this = $(this);
  56. let context = `${$this.data('context')}/`;
  57. const mode = $this.data('markdown-mode') || 'comment';
  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,
  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. htmlEscape($(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. htmlEscape($(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. issuesTribute.attach($textarea.get());
  803. emojiTribute.attach($textarea.get());
  804. let dz;
  805. const $dropzone = $editContentZone.find('.dropzone');
  806. const $files = $editContentZone.find('.comment-files');
  807. if ($dropzone.length > 0) {
  808. $dropzone.data('saved', false);
  809. const filenameDict = {};
  810. dz = await createDropzone($dropzone[0], {
  811. url: $dropzone.data('upload-url'),
  812. headers: {'X-Csrf-Token': csrf},
  813. maxFiles: $dropzone.data('max-file'),
  814. maxFilesize: $dropzone.data('max-size'),
  815. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  816. addRemoveLinks: true,
  817. dictDefaultMessage: $dropzone.data('default-message'),
  818. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  819. dictFileTooBig: $dropzone.data('file-too-big'),
  820. dictRemoveFile: $dropzone.data('remove-file'),
  821. timeout: 0,
  822. init() {
  823. this.on('success', (file, data) => {
  824. filenameDict[file.name] = {
  825. uuid: data.uuid,
  826. submitted: false
  827. };
  828. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  829. $files.append(input);
  830. });
  831. this.on('removedfile', (file) => {
  832. if (!(file.name in filenameDict)) {
  833. return;
  834. }
  835. $(`#${filenameDict[file.name].uuid}`).remove();
  836. if ($dropzone.data('remove-url') && $dropzone.data('csrf') && !filenameDict[file.name].submitted) {
  837. $.post($dropzone.data('remove-url'), {
  838. file: filenameDict[file.name].uuid,
  839. _csrf: $dropzone.data('csrf')
  840. });
  841. }
  842. });
  843. this.on('submit', () => {
  844. $.each(filenameDict, (name) => {
  845. filenameDict[name].submitted = true;
  846. });
  847. });
  848. this.on('reload', () => {
  849. $.getJSON($editContentZone.data('attachment-url'), (data) => {
  850. dz.removeAllFiles(true);
  851. $files.empty();
  852. $.each(data, function () {
  853. const imgSrc = `${$dropzone.data('upload-url')}/${this.uuid}`;
  854. dz.emit('addedfile', this);
  855. dz.emit('thumbnail', this, imgSrc);
  856. dz.emit('complete', this);
  857. dz.files.push(this);
  858. filenameDict[this.name] = {
  859. submitted: true,
  860. uuid: this.uuid
  861. };
  862. $dropzone.find(`img[src='${imgSrc}']`).css('max-width', '100%');
  863. const input = $(`<input id="${this.uuid}" name="files" type="hidden">`).val(this.uuid);
  864. $files.append(input);
  865. });
  866. });
  867. });
  868. }
  869. });
  870. dz.emit('reload');
  871. }
  872. // Give new write/preview data-tab name to distinguish from others
  873. const $editContentForm = $editContentZone.find('.ui.comment.form');
  874. const $tabMenu = $editContentForm.find('.tabular.menu');
  875. $tabMenu.attr('data-write', $editContentZone.data('write'));
  876. $tabMenu.attr('data-preview', $editContentZone.data('preview'));
  877. $tabMenu.find('.write.item').attr('data-tab', $editContentZone.data('write'));
  878. $tabMenu.find('.preview.item').attr('data-tab', $editContentZone.data('preview'));
  879. $editContentForm.find('.write').attr('data-tab', $editContentZone.data('write'));
  880. $editContentForm.find('.preview').attr('data-tab', $editContentZone.data('preview'));
  881. $simplemde = setCommentSimpleMDE($textarea);
  882. commentMDEditors[$editContentZone.data('write')] = $simplemde;
  883. initCommentPreviewTab($editContentForm);
  884. initSimpleMDEImagePaste($simplemde, $files);
  885. $editContentZone.find('.cancel.button').on('click', () => {
  886. $renderContent.show();
  887. $editContentZone.hide();
  888. dz.emit('reload');
  889. });
  890. $editContentZone.find('.save.button').on('click', () => {
  891. $renderContent.show();
  892. $editContentZone.hide();
  893. const $attachments = $files.find('[name=files]').map(function () {
  894. return $(this).val();
  895. }).get();
  896. $.post($editContentZone.data('update-url'), {
  897. _csrf: csrf,
  898. content: $textarea.val(),
  899. context: $editContentZone.data('context'),
  900. files: $attachments
  901. }, (data) => {
  902. if (data.length === 0) {
  903. $renderContent.html($('#no-content').html());
  904. } else {
  905. $renderContent.html(data.content);
  906. $('pre code', $renderContent[0]).each(function () {
  907. highlight(this);
  908. });
  909. }
  910. const $content = $segment.parent();
  911. if (!$content.find('.ui.small.images').length) {
  912. if (data.attachments !== '') {
  913. $content.append(
  914. '<div class="ui bottom attached segment"><div class="ui small images"></div></div>'
  915. );
  916. $content.find('.ui.small.images').html(data.attachments);
  917. }
  918. } else if (data.attachments === '') {
  919. $content.find('.ui.small.images').parent().remove();
  920. } else {
  921. $content.find('.ui.small.images').html(data.attachments);
  922. }
  923. dz.emit('submit');
  924. dz.emit('reload');
  925. });
  926. });
  927. } else {
  928. $textarea = $segment.find('textarea');
  929. $simplemde = commentMDEditors[$editContentZone.data('write')];
  930. }
  931. // Show write/preview tab and copy raw content as needed
  932. $editContentZone.show();
  933. $renderContent.hide();
  934. if ($textarea.val().length === 0) {
  935. $textarea.val($rawContent.text());
  936. $simplemde.value($rawContent.text());
  937. }
  938. $textarea.focus();
  939. $simplemde.codemirror.focus();
  940. event.preventDefault();
  941. });
  942. // Delete comment
  943. $('.delete-comment').on('click', function () {
  944. const $this = $(this);
  945. if (window.confirm($this.data('locale'))) {
  946. $.post($this.data('url'), {
  947. _csrf: csrf
  948. }).done(() => {
  949. $(`#${$this.data('comment-id')}`).remove();
  950. });
  951. }
  952. return false;
  953. });
  954. // Change status
  955. const $statusButton = $('#status-button');
  956. $('#comment-form .edit_area').on('keyup', function () {
  957. if ($(this).val().length === 0) {
  958. $statusButton.text($statusButton.data('status'));
  959. } else {
  960. $statusButton.text($statusButton.data('status-and-comment'));
  961. }
  962. });
  963. $statusButton.on('click', () => {
  964. $('#status').val($statusButton.data('status-val'));
  965. $('#comment-form').trigger('submit');
  966. });
  967. // Pull Request merge button
  968. const $mergeButton = $('.merge-button > button');
  969. $mergeButton.on('click', function (e) {
  970. e.preventDefault();
  971. $(`.${$(this).data('do')}-fields`).show();
  972. $(this).parent().hide();
  973. });
  974. $('.merge-button > .dropdown').dropdown({
  975. onChange(_text, _value, $choice) {
  976. if ($choice.data('do')) {
  977. $mergeButton.find('.button-text').text($choice.text());
  978. $mergeButton.data('do', $choice.data('do'));
  979. }
  980. }
  981. });
  982. $('.merge-cancel').on('click', function (e) {
  983. e.preventDefault();
  984. $(this).closest('.form').hide();
  985. $mergeButton.parent().show();
  986. });
  987. initReactionSelector();
  988. }
  989. // Diff
  990. if ($('.repository.diff').length > 0) {
  991. $('.diff-counter').each(function () {
  992. const $item = $(this);
  993. const addLine = $item.find('span[data-line].add').data('line');
  994. const delLine = $item.find('span[data-line].del').data('line');
  995. const addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
  996. $item.find('.bar .add').css('width', `${addPercent}%`);
  997. });
  998. }
  999. // Quick start and repository home
  1000. $('#repo-clone-ssh').on('click', function () {
  1001. $('.clone-url').text($(this).data('link'));
  1002. $('#repo-clone-url').val($(this).data('link'));
  1003. $(this).addClass('blue');
  1004. $('#repo-clone-https').removeClass('blue');
  1005. localStorage.setItem('repo-clone-protocol', 'ssh');
  1006. });
  1007. $('#repo-clone-https').on('click', function () {
  1008. $('.clone-url').text($(this).data('link'));
  1009. $('#repo-clone-url').val($(this).data('link'));
  1010. $(this).addClass('blue');
  1011. if ($('#repo-clone-ssh').length > 0) {
  1012. $('#repo-clone-ssh').removeClass('blue');
  1013. localStorage.setItem('repo-clone-protocol', 'https');
  1014. }
  1015. });
  1016. $('#repo-clone-url').on('click', function () {
  1017. $(this).select();
  1018. });
  1019. // Pull request
  1020. const $repoComparePull = $('.repository.compare.pull');
  1021. if ($repoComparePull.length > 0) {
  1022. initFilterSearchDropdown('.choose.branch .dropdown');
  1023. // show pull request form
  1024. $repoComparePull.find('button.show-form').on('click', function (e) {
  1025. e.preventDefault();
  1026. $repoComparePull.find('.pullrequest-form').show();
  1027. autoSimpleMDE.codemirror.refresh();
  1028. $(this).parent().hide();
  1029. });
  1030. }
  1031. // Branches
  1032. if ($('.repository.settings.branches').length > 0) {
  1033. initFilterSearchDropdown('.protected-branches .dropdown');
  1034. $('.enable-protection, .enable-whitelist, .enable-statuscheck').on('change', function () {
  1035. if (this.checked) {
  1036. $($(this).data('target')).removeClass('disabled');
  1037. } else {
  1038. $($(this).data('target')).addClass('disabled');
  1039. }
  1040. });
  1041. $('.disable-whitelist').on('change', function () {
  1042. if (this.checked) {
  1043. $($(this).data('target')).addClass('disabled');
  1044. }
  1045. });
  1046. }
  1047. // Language stats
  1048. if ($('.language-stats').length > 0) {
  1049. $('.language-stats').on('click', (e) => {
  1050. e.preventDefault();
  1051. $('.language-stats-details, .repository-menu').slideToggle();
  1052. });
  1053. }
  1054. }
  1055. function initMigration() {
  1056. const toggleMigrations = function () {
  1057. const authUserName = $('#auth_username').val();
  1058. const cloneAddr = $('#clone_addr').val();
  1059. if (!$('#mirror').is(':checked') && (authUserName && authUserName.length > 0) &&
  1060. (cloneAddr !== undefined && (cloneAddr.startsWith('https://github.com') || cloneAddr.startsWith('http://github.com') || cloneAddr.startsWith('http://gitlab.com') || cloneAddr.startsWith('https://gitlab.com')))) {
  1061. $('#migrate_items').show();
  1062. } else {
  1063. $('#migrate_items').hide();
  1064. }
  1065. };
  1066. toggleMigrations();
  1067. $('#clone_addr').on('input', toggleMigrations);
  1068. $('#auth_username').on('input', toggleMigrations);
  1069. $('#mirror').on('change', toggleMigrations);
  1070. }
  1071. function initPullRequestReview() {
  1072. $('.show-outdated').on('click', function (e) {
  1073. e.preventDefault();
  1074. const id = $(this).data('comment');
  1075. $(this).addClass('hide');
  1076. $(`#code-comments-${id}`).removeClass('hide');
  1077. $(`#code-preview-${id}`).removeClass('hide');
  1078. $(`#hide-outdated-${id}`).removeClass('hide');
  1079. });
  1080. $('.hide-outdated').on('click', function (e) {
  1081. e.preventDefault();
  1082. const id = $(this).data('comment');
  1083. $(this).addClass('hide');
  1084. $(`#code-comments-${id}`).addClass('hide');
  1085. $(`#code-preview-${id}`).addClass('hide');
  1086. $(`#show-outdated-${id}`).removeClass('hide');
  1087. });
  1088. $('button.comment-form-reply').on('click', function (e) {
  1089. e.preventDefault();
  1090. $(this).hide();
  1091. const form = $(this).parent().find('.comment-form');
  1092. form.removeClass('hide');
  1093. const $textarea = form.find('textarea');
  1094. let $simplemde;
  1095. if ($textarea.data('simplemde')) {
  1096. $simplemde = $textarea.data('simplemde');
  1097. } else {
  1098. issuesTribute.attach($textarea.get());
  1099. emojiTribute.attach($textarea.get());
  1100. $simplemde = setCommentSimpleMDE($textarea);
  1101. $textarea.data('simplemde', $simplemde);
  1102. }
  1103. $textarea.focus();
  1104. $simplemde.codemirror.focus();
  1105. assingMenuAttributes(form.find('.menu'));
  1106. });
  1107. // The following part is only for diff views
  1108. if ($('.repository.pull.diff').length === 0) {
  1109. return;
  1110. }
  1111. $('.diff-detail-box.ui.sticky').sticky();
  1112. $('.btn-review').on('click', function (e) {
  1113. e.preventDefault();
  1114. $(this).closest('.dropdown').find('.menu').toggle('visible');
  1115. }).closest('.dropdown').find('.link.close')
  1116. .on('click', function (e) {
  1117. e.preventDefault();
  1118. $(this).closest('.menu').toggle('visible');
  1119. });
  1120. $('.code-view .lines-code,.code-view .lines-num')
  1121. .on('mouseenter', function () {
  1122. const parent = $(this).closest('td');
  1123. $(this).closest('tr').addClass(
  1124. parent.hasClass('lines-num-old') || parent.hasClass('lines-code-old') ? 'focus-lines-old' : 'focus-lines-new'
  1125. );
  1126. })
  1127. .on('mouseleave', function () {
  1128. $(this).closest('tr').removeClass('focus-lines-new focus-lines-old');
  1129. });
  1130. $('.add-code-comment').on('click', function (e) {
  1131. // https://github.com/go-gitea/gitea/issues/4745
  1132. if ($(e.target).hasClass('btn-add-single')) {
  1133. return;
  1134. }
  1135. e.preventDefault();
  1136. const isSplit = $(this).closest('.code-diff').hasClass('code-diff-split');
  1137. const side = $(this).data('side');
  1138. const idx = $(this).data('idx');
  1139. const path = $(this).data('path');
  1140. const form = $('#pull_review_add_comment').html();
  1141. const tr = $(this).closest('tr');
  1142. let ntr = tr.next();
  1143. if (!ntr.hasClass('add-comment')) {
  1144. ntr = $(`<tr class="add-comment">${
  1145. 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>' :
  1146. '<td class="lines-num"></td><td class="lines-num"></td><td class="add-comment-left add-comment-right" colspan="2"></td>'
  1147. }</tr>`);
  1148. tr.after(ntr);
  1149. }
  1150. const td = ntr.find(`.add-comment-${side}`);
  1151. let commentCloud = td.find('.comment-code-cloud');
  1152. if (commentCloud.length === 0) {
  1153. td.html(form);
  1154. commentCloud = td.find('.comment-code-cloud');
  1155. assingMenuAttributes(commentCloud.find('.menu'));
  1156. td.find("input[name='line']").val(idx);
  1157. td.find("input[name='side']").val(side === 'left' ? 'previous' : 'proposed');
  1158. td.find("input[name='path']").val(path);
  1159. }
  1160. const $textarea = commentCloud.find('textarea');
  1161. issuesTribute.attach($textarea.get());
  1162. emojiTribute.attach($textarea.get());
  1163. const $simplemde = setCommentSimpleMDE($textarea);
  1164. $textarea.focus();
  1165. $simplemde.codemirror.focus();
  1166. });
  1167. }
  1168. function assingMenuAttributes(menu) {
  1169. const id = Math.floor(Math.random() * Math.floor(1000000));
  1170. menu.attr('data-write', menu.attr('data-write') + id);
  1171. menu.attr('data-preview', menu.attr('data-preview') + id);
  1172. menu.find('.item').each(function () {
  1173. const tab = $(this).attr('data-tab') + id;
  1174. $(this).attr('data-tab', tab);
  1175. });
  1176. menu.parent().find("*[data-tab='write']").attr('data-tab', `write${id}`);
  1177. menu.parent().find("*[data-tab='preview']").attr('data-tab', `preview${id}`);
  1178. initCommentPreviewTab(menu.parent('.form'));
  1179. return id;
  1180. }
  1181. function initRepositoryCollaboration() {
  1182. // Change collaborator access mode
  1183. $('.access-mode.menu .item').on('click', function () {
  1184. const $menu = $(this).parent();
  1185. $.post($menu.data('url'), {
  1186. _csrf: csrf,
  1187. uid: $menu.data('uid'),
  1188. mode: $(this).data('value')
  1189. });
  1190. });
  1191. }
  1192. function initTeamSettings() {
  1193. // Change team access mode
  1194. $('.organization.new.team input[name=permission]').on('change', () => {
  1195. const val = $('input[name=permission]:checked', '.organization.new.team').val();
  1196. if (val === 'admin') {
  1197. $('.organization.new.team .team-units').hide();
  1198. } else {
  1199. $('.organization.new.team .team-units').show();
  1200. }
  1201. });
  1202. }
  1203. function initWikiForm() {
  1204. const $editArea = $('.repository.wiki textarea#edit_area');
  1205. let sideBySideChanges = 0;
  1206. let sideBySideTimeout = null;
  1207. if ($editArea.length > 0) {
  1208. const simplemde = new SimpleMDE({
  1209. autoDownloadFontAwesome: false,
  1210. element: $editArea[0],
  1211. forceSync: true,
  1212. previewRender(plainText, preview) { // Async method
  1213. setTimeout(() => {
  1214. // FIXME: still send render request when return back to edit mode
  1215. const render = function () {
  1216. sideBySideChanges = 0;
  1217. if (sideBySideTimeout !== null) {
  1218. clearTimeout(sideBySideTimeout);
  1219. sideBySideTimeout = null;
  1220. }
  1221. $.post($editArea.data('url'), {
  1222. _csrf: csrf,
  1223. mode: 'gfm',
  1224. context: $editArea.data('context'),
  1225. text: plainText,
  1226. wiki: true
  1227. }, (data) => {
  1228. preview.innerHTML = `<div class="markdown ui segment">${data}</div>`;
  1229. $(preview).find('pre code').each((_, e) => {
  1230. highlight(e);
  1231. });
  1232. });
  1233. };
  1234. if (!simplemde.isSideBySideActive()) {
  1235. render();
  1236. } else {
  1237. // delay preview by keystroke counting
  1238. sideBySideChanges++;
  1239. if (sideBySideChanges > 10) {
  1240. render();
  1241. }
  1242. // or delay preview by timeout
  1243. if (sideBySideTimeout !== null) {
  1244. clearTimeout(sideBySideTimeout);
  1245. sideBySideTimeout = null;
  1246. }
  1247. sideBySideTimeout = setTimeout(render, 600);
  1248. }
  1249. }, 0);
  1250. if (!simplemde.isSideBySideActive()) {
  1251. return 'Loading...';
  1252. }
  1253. return preview.innerHTML;
  1254. },
  1255. renderingConfig: {
  1256. singleLineBreaks: false
  1257. },
  1258. indentWithTabs: false,
  1259. tabSize: 4,
  1260. spellChecker: false,
  1261. toolbar: ['bold', 'italic', 'strikethrough', '|',
  1262. 'heading-1', 'heading-2', 'heading-3', 'heading-bigger', 'heading-smaller', '|',
  1263. {
  1264. name: 'code-inline',
  1265. action(e) {
  1266. const cm = e.codemirror;
  1267. const selection = cm.getSelection();
  1268. cm.replaceSelection(`\`${selection}\``);
  1269. if (!selection) {
  1270. const cursorPos = cm.getCursor();
  1271. cm.setCursor(cursorPos.line, cursorPos.ch - 1);
  1272. }
  1273. cm.focus();
  1274. },
  1275. className: 'fa fa-angle-right',
  1276. title: 'Add Inline Code',
  1277. }, 'code', 'quote', '|', {
  1278. name: 'checkbox-empty',
  1279. action(e) {
  1280. const cm = e.codemirror;
  1281. cm.replaceSelection(`\n- [ ] ${cm.getSelection()}`);
  1282. cm.focus();
  1283. },
  1284. className: 'fa fa-square-o',
  1285. title: 'Add Checkbox (empty)',
  1286. },
  1287. {
  1288. name: 'checkbox-checked',
  1289. action(e) {
  1290. const cm = e.codemirror;
  1291. cm.replaceSelection(`\n- [x] ${cm.getSelection()}`);
  1292. cm.focus();
  1293. },
  1294. className: 'fa fa-check-square-o',
  1295. title: 'Add Checkbox (checked)',
  1296. }, '|',
  1297. 'unordered-list', 'ordered-list', '|',
  1298. 'link', 'image', 'table', 'horizontal-rule', '|',
  1299. 'clean-block', 'preview', 'fullscreen', 'side-by-side', '|',
  1300. {
  1301. name: 'revert-to-textarea',
  1302. action(e) {
  1303. e.toTextArea();
  1304. },
  1305. className: 'fa fa-file',
  1306. title: 'Revert to simple textarea',
  1307. },
  1308. ]
  1309. });
  1310. $(simplemde.codemirror.getInputField()).addClass('js-quick-submit');
  1311. setTimeout(() => {
  1312. const $bEdit = $('.repository.wiki.new .previewtabs a[data-tab="write"]');
  1313. const $bPrev = $('.repository.wiki.new .previewtabs a[data-tab="preview"]');
  1314. const $toolbar = $('.editor-toolbar');
  1315. const $bPreview = $('.editor-toolbar a.fa-eye');
  1316. const $bSideBySide = $('.editor-toolbar a.fa-columns');
  1317. $bEdit.on('click', () => {
  1318. if ($toolbar.hasClass('disabled-for-preview')) {
  1319. $bPreview.trigger('click');
  1320. }
  1321. });
  1322. $bPrev.on('click', () => {
  1323. if (!$toolbar.hasClass('disabled-for-preview')) {
  1324. $bPreview.trigger('click');
  1325. }
  1326. });
  1327. $bPreview.on('click', () => {
  1328. setTimeout(() => {
  1329. if ($toolbar.hasClass('disabled-for-preview')) {
  1330. if ($bEdit.hasClass('active')) {
  1331. $bEdit.removeClass('active');
  1332. }
  1333. if (!$bPrev.hasClass('active')) {
  1334. $bPrev.addClass('active');
  1335. }
  1336. } else {
  1337. if (!$bEdit.hasClass('active')) {
  1338. $bEdit.addClass('active');
  1339. }
  1340. if ($bPrev.hasClass('active')) {
  1341. $bPrev.removeClass('active');
  1342. }
  1343. }
  1344. }, 0);
  1345. });
  1346. $bSideBySide.on('click', () => {
  1347. sideBySideChanges = 10;
  1348. });
  1349. }, 0);
  1350. }
  1351. }
  1352. // Adding function to get the cursor position in a text field to jQuery object.
  1353. $.fn.getCursorPosition = function () {
  1354. const el = $(this).get(0);
  1355. let pos = 0;
  1356. if ('selectionStart' in el) {
  1357. pos = el.selectionStart;
  1358. } else if ('selection' in document) {
  1359. el.focus();
  1360. const Sel = document.selection.createRange();
  1361. const SelLength = document.selection.createRange().text.length;
  1362. Sel.moveStart('character', -el.value.length);
  1363. pos = Sel.text.length - SelLength;
  1364. }
  1365. return pos;
  1366. };
  1367. function setCommentSimpleMDE($editArea) {
  1368. const simplemde = new SimpleMDE({
  1369. autoDownloadFontAwesome: false,
  1370. element: $editArea[0],
  1371. forceSync: true,
  1372. renderingConfig: {
  1373. singleLineBreaks: false
  1374. },
  1375. indentWithTabs: false,
  1376. tabSize: 4,
  1377. spellChecker: false,
  1378. toolbar: ['bold', 'italic', 'strikethrough', '|',
  1379. 'heading-1', 'heading-2', 'heading-3', 'heading-bigger', 'heading-smaller', '|',
  1380. 'code', 'quote', '|',
  1381. 'unordered-list', 'ordered-list', '|',
  1382. 'link', 'image', 'table', 'horizontal-rule', '|',
  1383. 'clean-block', '|',
  1384. {
  1385. name: 'revert-to-textarea',
  1386. action(e) {
  1387. e.toTextArea();
  1388. },
  1389. className: 'fa fa-file',
  1390. title: 'Revert to simple textarea',
  1391. },
  1392. ]
  1393. });
  1394. $(simplemde.codemirror.getInputField()).addClass('js-quick-submit');
  1395. simplemde.codemirror.setOption('extraKeys', {
  1396. Enter: () => {
  1397. if (!(issuesTribute.isActive || emojiTribute.isActive)) {
  1398. return CodeMirror.Pass;
  1399. }
  1400. },
  1401. Backspace: (cm) => {
  1402. if (cm.getInputField().trigger) {
  1403. cm.getInputField().trigger('input');
  1404. }
  1405. cm.execCommand('delCharBefore');
  1406. }
  1407. });
  1408. issuesTribute.attach(simplemde.codemirror.getInputField());
  1409. emojiTribute.attach(simplemde.codemirror.getInputField());
  1410. return simplemde;
  1411. }
  1412. async function initEditor() {
  1413. $('.js-quick-pull-choice-option').on('change', function () {
  1414. if ($(this).val() === 'commit-to-new-branch') {
  1415. $('.quick-pull-branch-name').show();
  1416. $('.quick-pull-branch-name input').prop('required', true);
  1417. } else {
  1418. $('.quick-pull-branch-name').hide();
  1419. $('.quick-pull-branch-name input').prop('required', false);
  1420. }
  1421. $('#commit-button').text($(this).attr('button_text'));
  1422. });
  1423. const $editFilename = $('#file-name');
  1424. $editFilename.on('keyup', function (e) {
  1425. const $section = $('.breadcrumb span.section');
  1426. const $divider = $('.breadcrumb div.divider');
  1427. let value;
  1428. let parts;
  1429. if (e.keyCode === 8) {
  1430. if ($(this).getCursorPosition() === 0) {
  1431. if ($section.length > 0) {
  1432. value = $section.last().find('a').text();
  1433. $(this).val(value + $(this).val());
  1434. $(this)[0].setSelectionRange(value.length, value.length);
  1435. $section.last().remove();
  1436. $divider.last().remove();
  1437. }
  1438. }
  1439. }
  1440. if (e.keyCode === 191) {
  1441. parts = $(this).val().split('/');
  1442. for (let i = 0; i < parts.length; ++i) {
  1443. value = parts[i];
  1444. if (i < parts.length - 1) {
  1445. if (value.length) {
  1446. $(`<span class="section"><a href="#">${value}</a></span>`).insertBefore($(this));
  1447. $('<div class="divider"> / </div>').insertBefore($(this));
  1448. }
  1449. } else {
  1450. $(this).val(value);
  1451. }
  1452. $(this)[0].setSelectionRange(0, 0);
  1453. }
  1454. }
  1455. parts = [];
  1456. $('.breadcrumb span.section').each(function () {
  1457. const element = $(this);
  1458. if (element.find('a').length) {
  1459. parts.push(element.find('a').text());
  1460. } else {
  1461. parts.push(element.text());
  1462. }
  1463. });
  1464. if ($(this).val()) parts.push($(this).val());
  1465. $('#tree_path').val(parts.join('/'));
  1466. }).trigger('keyup');
  1467. const $editArea = $('.repository.editor textarea#edit_area');
  1468. if (!$editArea.length) return;
  1469. await createCodeEditor($editArea[0], $editFilename[0], previewFileModes);
  1470. // Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
  1471. // to enable or disable the commit button
  1472. const $commitButton = $('#commit-button');
  1473. const $editForm = $('.ui.edit.form');
  1474. const dirtyFileClass = 'dirty-file';
  1475. // Disabling the button at the start
  1476. $commitButton.prop('disabled', true);
  1477. // Registering a custom listener for the file path and the file content
  1478. $editForm.areYouSure({
  1479. silent: true,
  1480. dirtyClass: dirtyFileClass,
  1481. fieldSelector: ':input:not(.commit-form-wrapper :input)',
  1482. change() {
  1483. const dirty = $(this).hasClass(dirtyFileClass);
  1484. $commitButton.prop('disabled', !dirty);
  1485. }
  1486. });
  1487. $commitButton.on('click', (event) => {
  1488. // A modal which asks if an empty file should be committed
  1489. if ($editArea.val().length === 0) {
  1490. $('#edit-empty-content-modal').modal({
  1491. onApprove() {
  1492. $('.edit.form').trigger('submit');
  1493. }
  1494. }).modal('show');
  1495. event.preventDefault();
  1496. }
  1497. });
  1498. }
  1499. function initOrganization() {
  1500. if ($('.organization').length === 0) {
  1501. return;
  1502. }
  1503. // Options
  1504. if ($('.organization.settings.options').length > 0) {
  1505. $('#org_name').on('keyup', function () {
  1506. const $prompt = $('#org-name-change-prompt');
  1507. if ($(this).val().toString().toLowerCase() !== $(this).data('org-name').toString().toLowerCase()) {
  1508. $prompt.show();
  1509. } else {
  1510. $prompt.hide();
  1511. }
  1512. });
  1513. }
  1514. // Labels
  1515. if ($('.organization.settings.labels').length > 0) {
  1516. initLabelEdit();
  1517. }
  1518. }
  1519. function initUserSettings() {
  1520. // Options
  1521. if ($('.user.settings.profile').length > 0) {
  1522. $('#username').on('keyup', function () {
  1523. const $prompt = $('#name-change-prompt');
  1524. if ($(this).val().toString().toLowerCase() !== $(this).data('name').toString().toLowerCase()) {
  1525. $prompt.show();
  1526. } else {
  1527. $prompt.hide();
  1528. }
  1529. });
  1530. }
  1531. }
  1532. function initGithook() {
  1533. if ($('.edit.githook').length === 0) {
  1534. return;
  1535. }
  1536. CodeMirror.autoLoadMode(CodeMirror.fromTextArea($('#content')[0], {
  1537. lineNumbers: true,
  1538. mode: 'shell'
  1539. }), 'shell');
  1540. }
  1541. function initWebhook() {
  1542. if ($('.new.webhook').length === 0) {
  1543. return;
  1544. }
  1545. $('.events.checkbox input').on('change', function () {
  1546. if ($(this).is(':checked')) {
  1547. $('.events.fields').show();
  1548. }
  1549. });
  1550. $('.non-events.checkbox input').on('change', function () {
  1551. if ($(this).is(':checked')) {
  1552. $('.events.fields').hide();
  1553. }
  1554. });
  1555. const updateContentType = function () {
  1556. const visible = $('#http_method').val() === 'POST';
  1557. $('#content_type').parent().parent()[visible ? 'show' : 'hide']();
  1558. };
  1559. updateContentType();
  1560. $('#http_method').on('change', () => {
  1561. updateContentType();
  1562. });
  1563. // Test delivery
  1564. $('#test-delivery').on('click', function () {
  1565. const $this = $(this);
  1566. $this.addClass('loading disabled');
  1567. $.post($this.data('link'), {
  1568. _csrf: csrf
  1569. }).done(
  1570. setTimeout(() => {
  1571. window.location.href = $this.data('redirect');
  1572. }, 5000)
  1573. );
  1574. });
  1575. }
  1576. function initAdmin() {
  1577. if ($('.admin').length === 0) {
  1578. return;
  1579. }
  1580. // New user
  1581. if ($('.admin.new.user').length > 0 || $('.admin.edit.user').length > 0) {
  1582. $('#login_type').on('change', function () {
  1583. if ($(this).val().substring(0, 1) === '0') {
  1584. $('#login_name').removeAttr('required');
  1585. $('.non-local').hide();
  1586. $('.local').show();
  1587. $('#user_name').focus();
  1588. if ($(this).data('password') === 'required') {
  1589. $('#password').attr('required', 'required');
  1590. }
  1591. } else {
  1592. $('#login_name').attr('required', 'required');
  1593. $('.non-local').show();
  1594. $('.local').hide();
  1595. $('#login_name').focus();
  1596. $('#password').removeAttr('required');
  1597. }
  1598. });
  1599. }
  1600. function onSecurityProtocolChange() {
  1601. if ($('#security_protocol').val() > 0) {
  1602. $('.has-tls').show();
  1603. } else {
  1604. $('.has-tls').hide();
  1605. }
  1606. }
  1607. function onUsePagedSearchChange() {
  1608. if ($('#use_paged_search').prop('checked')) {
  1609. $('.search-page-size').show()
  1610. .find('input').attr('required', 'required');
  1611. } else {
  1612. $('.search-page-size').hide()
  1613. .find('input').removeAttr('required');
  1614. }
  1615. }
  1616. function onOAuth2Change() {
  1617. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  1618. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  1619. const provider = $('#oauth2_provider').val();
  1620. switch (provider) {
  1621. case 'github':
  1622. case 'gitlab':
  1623. case 'gitea':
  1624. case 'nextcloud':
  1625. $('.oauth2_use_custom_url').show();
  1626. break;
  1627. case 'openidConnect':
  1628. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  1629. $('.open_id_connect_auto_discovery_url').show();
  1630. break;
  1631. }
  1632. onOAuth2UseCustomURLChange();
  1633. }
  1634. function onOAuth2UseCustomURLChange() {
  1635. const provider = $('#oauth2_provider').val();
  1636. $('.oauth2_use_custom_url_field').hide();
  1637. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  1638. if ($('#oauth2_use_custom_url').is(':checked')) {
  1639. $('#oauth2_token_url').val($(`#${provider}_token_url`).val());
  1640. $('#oauth2_auth_url').val($(`#${provider}_auth_url`).val());
  1641. $('#oauth2_profile_url').val($(`#${provider}_profile_url`).val());
  1642. $('#oauth2_email_url').val($(`#${provider}_email_url`).val());
  1643. switch (provider) {
  1644. case 'github':
  1645. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  1646. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  1647. break;
  1648. case 'nextcloud':
  1649. case 'gitea':
  1650. case 'gitlab':
  1651. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  1652. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  1653. $('#oauth2_email_url').val('');
  1654. break;
  1655. }
  1656. }
  1657. }
  1658. // New authentication
  1659. if ($('.admin.new.authentication').length > 0) {
  1660. $('#auth_type').on('change', function () {
  1661. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls, .search-page-size, .sspi').hide();
  1662. $('.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');
  1663. $('.binddnrequired').removeClass('required');
  1664. const authType = $(this).val();
  1665. switch (authType) {
  1666. case '2': // LDAP
  1667. $('.ldap').show();
  1668. $('.binddnrequired input, .ldap div.required:not(.dldap) input').attr('required', 'required');
  1669. $('.binddnrequired').addClass('required');
  1670. break;
  1671. case '3': // SMTP
  1672. $('.smtp').show();
  1673. $('.has-tls').show();
  1674. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1675. break;
  1676. case '4': // PAM
  1677. $('.pam').show();
  1678. $('.pam input').attr('required', 'required');
  1679. break;
  1680. case '5': // LDAP
  1681. $('.dldap').show();
  1682. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1683. break;
  1684. case '6': // OAuth2
  1685. $('.oauth2').show();
  1686. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1687. onOAuth2Change();
  1688. break;
  1689. case '7': // SSPI
  1690. $('.sspi').show();
  1691. $('.sspi div.required input').attr('required', 'required');
  1692. break;
  1693. }
  1694. if (authType === '2' || authType === '5') {
  1695. onSecurityProtocolChange();
  1696. }
  1697. if (authType === '2') {
  1698. onUsePagedSearchChange();
  1699. }
  1700. });
  1701. $('#auth_type').trigger('change');
  1702. $('#security_protocol').on('change', onSecurityProtocolChange);
  1703. $('#use_paged_search').on('change', onUsePagedSearchChange);
  1704. $('#oauth2_provider').on('change', onOAuth2Change);
  1705. $('#oauth2_use_custom_url').on('change', onOAuth2UseCustomURLChange);
  1706. }
  1707. // Edit authentication
  1708. if ($('.admin.edit.authentication').length > 0) {
  1709. const authType = $('#auth_type').val();
  1710. if (authType === '2' || authType === '5') {
  1711. $('#security_protocol').on('change', onSecurityProtocolChange);
  1712. if (authType === '2') {
  1713. $('#use_paged_search').on('change', onUsePagedSearchChange);
  1714. }
  1715. } else if (authType === '6') {
  1716. $('#oauth2_provider').on('change', onOAuth2Change);
  1717. $('#oauth2_use_custom_url').on('change', onOAuth2UseCustomURLChange);
  1718. onOAuth2Change();
  1719. }
  1720. }
  1721. // Notice
  1722. if ($('.admin.notice')) {
  1723. const $detailModal = $('#detail-modal');
  1724. // Attach view detail modals
  1725. $('.view-detail').on('click', function () {
  1726. $detailModal.find('.content pre').text($(this).parents('tr').find('.notice-description').text());
  1727. $detailModal.find('.sub.header').text($(this).parents('tr').find('.notice-created-time').text());
  1728. $detailModal.modal('show');
  1729. return false;
  1730. });
  1731. // Select actions
  1732. const $checkboxes = $('.select.table .ui.checkbox');
  1733. $('.select.action').on('click', function () {
  1734. switch ($(this).data('action')) {
  1735. case 'select-all':
  1736. $checkboxes.checkbox('check');
  1737. break;
  1738. case 'deselect-all':
  1739. $checkboxes.checkbox('uncheck');
  1740. break;
  1741. case 'inverse':
  1742. $checkboxes.checkbox('toggle');
  1743. break;
  1744. }
  1745. });
  1746. $('#delete-selection').on('click', function () {
  1747. const $this = $(this);
  1748. $this.addClass('loading disabled');
  1749. const ids = [];
  1750. $checkboxes.each(function () {
  1751. if ($(this).checkbox('is checked')) {
  1752. ids.push($(this).data('id'));
  1753. }
  1754. });
  1755. $.post($this.data('link'), {
  1756. _csrf: csrf,
  1757. ids
  1758. }).done(() => {
  1759. window.location.href = $this.data('redirect');
  1760. });
  1761. });
  1762. }
  1763. }
  1764. function buttonsClickOnEnter() {
  1765. $('.ui.button').on('keypress', function (e) {
  1766. if (e.keyCode === 13 || e.keyCode === 32) { // enter key or space bar
  1767. $(this).trigger('click');
  1768. }
  1769. });
  1770. }
  1771. function searchUsers() {
  1772. const $searchUserBox = $('#search-user-box');
  1773. $searchUserBox.search({
  1774. minCharacters: 2,
  1775. apiSettings: {
  1776. url: `${AppSubUrl}/api/v1/users/search?q={query}`,
  1777. onResponse(response) {
  1778. const items = [];
  1779. $.each(response.data, (_i, item) => {
  1780. let title = item.login;
  1781. if (item.full_name && item.full_name.length > 0) {
  1782. title += ` (${htmlEscape(item.full_name)})`;
  1783. }
  1784. items.push({
  1785. title,
  1786. image: item.avatar_url
  1787. });
  1788. });
  1789. return {results: items};
  1790. }
  1791. },
  1792. searchFields: ['login', 'full_name'],
  1793. showNoResults: false
  1794. });
  1795. }
  1796. function searchTeams() {
  1797. const $searchTeamBox = $('#search-team-box');
  1798. $searchTeamBox.search({
  1799. minCharacters: 2,
  1800. apiSettings: {
  1801. url: `${AppSubUrl}/api/v1/orgs/${$searchTeamBox.data('org')}/teams/search?q={query}`,
  1802. headers: {'X-Csrf-Token': csrf},
  1803. onResponse(response) {
  1804. const items = [];
  1805. $.each(response.data, (_i, item) => {
  1806. const title = `${item.name} (${item.permission} access)`;
  1807. items.push({
  1808. title,
  1809. });
  1810. });
  1811. return {results: items};
  1812. }
  1813. },
  1814. searchFields: ['name', 'description'],
  1815. showNoResults: false
  1816. });
  1817. }
  1818. function searchRepositories() {
  1819. const $searchRepoBox = $('#search-repo-box');
  1820. $searchRepoBox.search({
  1821. minCharacters: 2,
  1822. apiSettings: {
  1823. url: `${AppSubUrl}/api/v1/repos/search?q={query}&uid=${$searchRepoBox.data('uid')}`,
  1824. onResponse(response) {
  1825. const items = [];
  1826. $.each(response.data, (_i, item) => {
  1827. items.push({
  1828. title: item.full_name.split('/')[1],
  1829. description: item.full_name
  1830. });
  1831. });
  1832. return {results: items};
  1833. }
  1834. },
  1835. searchFields: ['full_name'],
  1836. showNoResults: false
  1837. });
  1838. }
  1839. function initCodeView() {
  1840. if ($('.code-view .linenums').length > 0) {
  1841. $(document).on('click', '.lines-num span', function (e) {
  1842. const $select = $(this);
  1843. const $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  1844. selectRange($list, $list.filter(`[rel=${$select.attr('id')}]`), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1845. deSelect();
  1846. });
  1847. $(window).on('hashchange', () => {
  1848. let m = window.location.hash.match(/^#(L\d+)-(L\d+)$/);
  1849. const $list = $('.code-view ol.linenums > li');
  1850. let $first;
  1851. if (m) {
  1852. $first = $list.filter(`.${m[1]}`);
  1853. selectRange($list, $first, $list.filter(`.${m[2]}`));
  1854. $('html, body').scrollTop($first.offset().top - 200);
  1855. return;
  1856. }
  1857. m = window.location.hash.match(/^#(L|n)(\d+)$/);
  1858. if (m) {
  1859. $first = $list.filter(`.L${m[2]}`);
  1860. selectRange($list, $first);
  1861. $('html, body').scrollTop($first.offset().top - 200);
  1862. }
  1863. }).trigger('hashchange');
  1864. }
  1865. $('.fold-code').on('click', ({target}) => {
  1866. const box = target.closest('.file-content');
  1867. const folded = box.dataset.folded !== 'true';
  1868. target.classList.add(`fa-chevron-${folded ? 'right' : 'down'}`);
  1869. target.classList.remove(`fa-chevron-${folded ? 'down' : 'right'}`);
  1870. box.dataset.folded = String(folded);
  1871. });
  1872. function insertBlobExcerpt(e) {
  1873. const $blob = $(e.target);
  1874. const $row = $blob.parent().parent();
  1875. $.get(`${$blob.data('url')}?${$blob.data('query')}&anchor=${$blob.data('anchor')}`, (blob) => {
  1876. $row.replaceWith(blob);
  1877. $(`[data-anchor="${$blob.data('anchor')}"]`).on('click', (e) => { insertBlobExcerpt(e) });
  1878. $('.diff-detail-box.ui.sticky').sticky();
  1879. });
  1880. }
  1881. $('.ui.blob-excerpt').on('click', (e) => { insertBlobExcerpt(e) });
  1882. }
  1883. function initU2FAuth() {
  1884. if ($('#wait-for-key').length === 0) {
  1885. return;
  1886. }
  1887. u2fApi.ensureSupport()
  1888. .then(() => {
  1889. $.getJSON(`${AppSubUrl}/user/u2f/challenge`).done((req) => {
  1890. u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
  1891. .then(u2fSigned)
  1892. .catch((err) => {
  1893. if (err === undefined) {
  1894. u2fError(1);
  1895. return;
  1896. }
  1897. u2fError(err.metaData.code);
  1898. });
  1899. });
  1900. }).catch(() => {
  1901. // Fallback in case browser do not support U2F
  1902. window.location.href = `${AppSubUrl}/user/two_factor`;
  1903. });
  1904. }
  1905. function u2fSigned(resp) {
  1906. $.ajax({
  1907. url: `${AppSubUrl}/user/u2f/sign`,
  1908. type: 'POST',
  1909. headers: {'X-Csrf-Token': csrf},
  1910. data: JSON.stringify(resp),
  1911. contentType: 'application/json; charset=utf-8',
  1912. }).done((res) => {
  1913. window.location.replace(res);
  1914. }).fail(() => {
  1915. u2fError(1);
  1916. });
  1917. }
  1918. function u2fRegistered(resp) {
  1919. if (checkError(resp)) {
  1920. return;
  1921. }
  1922. $.ajax({
  1923. url: `${AppSubUrl}/user/settings/security/u2f/register`,
  1924. type: 'POST',
  1925. headers: {'X-Csrf-Token': csrf},
  1926. data: JSON.stringify(resp),
  1927. contentType: 'application/json; charset=utf-8',
  1928. success() {
  1929. reload();
  1930. },
  1931. fail() {
  1932. u2fError(1);
  1933. }
  1934. });
  1935. }
  1936. function checkError(resp) {
  1937. if (!('errorCode' in resp)) {
  1938. return false;
  1939. }
  1940. if (resp.errorCode === 0) {
  1941. return false;
  1942. }
  1943. u2fError(resp.errorCode);
  1944. return true;
  1945. }
  1946. function u2fError(errorType) {
  1947. const u2fErrors = {
  1948. browser: $('#unsupported-browser'),
  1949. 1: $('#u2f-error-1'),
  1950. 2: $('#u2f-error-2'),
  1951. 3: $('#u2f-error-3'),
  1952. 4: $('#u2f-error-4'),
  1953. 5: $('.u2f-error-5')
  1954. };
  1955. u2fErrors[errorType].removeClass('hide');
  1956. Object.keys(u2fErrors).forEach((type) => {
  1957. if (type !== errorType) {
  1958. u2fErrors[type].addClass('hide');
  1959. }
  1960. });
  1961. $('#u2f-error').modal('show');
  1962. }
  1963. function initU2FRegister() {
  1964. $('#register-device').modal({allowMultiple: false});
  1965. $('#u2f-error').modal({allowMultiple: false});
  1966. $('#register-security-key').on('click', (e) => {
  1967. e.preventDefault();
  1968. u2fApi.ensureSupport()
  1969. .then(u2fRegisterRequest)
  1970. .catch(() => {
  1971. u2fError('browser');
  1972. });
  1973. });
  1974. }
  1975. function u2fRegisterRequest() {
  1976. $.post(`${AppSubUrl}/user/settings/security/u2f/request_register`, {
  1977. _csrf: csrf,
  1978. name: $('#nickname').val()
  1979. }).done((req) => {
  1980. $('#nickname').closest('div.field').removeClass('error');
  1981. $('#register-device').modal('show');
  1982. if (req.registeredKeys === null) {
  1983. req.registeredKeys = [];
  1984. }
  1985. u2fApi.register(req.appId, req.registerRequests, req.registeredKeys, 30)
  1986. .then(u2fRegistered)
  1987. .catch((reason) => {
  1988. if (reason === undefined) {
  1989. u2fError(1);
  1990. return;
  1991. }
  1992. u2fError(reason.metaData.code);
  1993. });
  1994. }).fail((xhr) => {
  1995. if (xhr.status === 409) {
  1996. $('#nickname').closest('div.field').addClass('error');
  1997. }
  1998. });
  1999. }
  2000. function initWipTitle() {
  2001. $('.title_wip_desc > a').on('click', (e) => {
  2002. e.preventDefault();
  2003. const $issueTitle = $('#issue_title');
  2004. $issueTitle.focus();
  2005. const value = $issueTitle.val().trim().toUpperCase();
  2006. for (const i in wipPrefixes) {
  2007. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  2008. return;
  2009. }
  2010. }
  2011. $issueTitle.val(`${wipPrefixes[0]} ${$issueTitle.val()}`);
  2012. });
  2013. }
  2014. function initTemplateSearch() {
  2015. const $repoTemplate = $('#repo_template');
  2016. const checkTemplate = function () {
  2017. const $templateUnits = $('#template_units');
  2018. const $nonTemplate = $('#non_template');
  2019. if ($repoTemplate.val() !== '' && $repoTemplate.val() !== '0') {
  2020. $templateUnits.show();
  2021. $nonTemplate.hide();
  2022. } else {
  2023. $templateUnits.hide();
  2024. $nonTemplate.show();
  2025. }
  2026. };
  2027. $repoTemplate.on('change', checkTemplate);
  2028. checkTemplate();
  2029. const changeOwner = function () {
  2030. $('#repo_template_search')
  2031. .dropdown({
  2032. apiSettings: {
  2033. url: `${AppSubUrl}/api/v1/repos/search?q={query}&template=true&priority_owner_id=${$('#uid').val()}`,
  2034. onResponse(response) {
  2035. const filteredResponse = {success: true, results: []};
  2036. filteredResponse.results.push({
  2037. name: '',
  2038. value: ''
  2039. });
  2040. // Parse the response from the api to work with our dropdown
  2041. $.each(response.data, (_r, repo) => {
  2042. filteredResponse.results.push({
  2043. name: htmlEscape(repo.full_name),
  2044. value: repo.id
  2045. });
  2046. });
  2047. return filteredResponse;
  2048. },
  2049. cache: false,
  2050. },
  2051. fullTextSearch: true
  2052. });
  2053. };
  2054. $('#uid').on('change', changeOwner);
  2055. changeOwner();
  2056. }
  2057. $(document).ready(async () => {
  2058. // Show exact time
  2059. $('.time-since').each(function () {
  2060. $(this)
  2061. .addClass('poping up')
  2062. .attr('data-content', $(this).attr('title'))
  2063. .attr('data-variation', 'inverted tiny')
  2064. .attr('title', '');
  2065. });
  2066. // Semantic UI modules.
  2067. $('.dropdown:not(.custom)').dropdown();
  2068. $('.jump.dropdown').dropdown({
  2069. action: 'hide',
  2070. onShow() {
  2071. $('.poping.up').popup('hide');
  2072. }
  2073. });
  2074. $('.slide.up.dropdown').dropdown({
  2075. transition: 'slide up'
  2076. });
  2077. $('.upward.dropdown').dropdown({
  2078. direction: 'upward'
  2079. });
  2080. $('.ui.accordion').accordion();
  2081. $('.ui.checkbox').checkbox();
  2082. $('.ui.progress').progress({
  2083. showActivity: false
  2084. });
  2085. $('.poping.up').popup();
  2086. $('.top.menu .poping.up').popup({
  2087. onShow() {
  2088. if ($('.top.menu .menu.transition').hasClass('visible')) {
  2089. return false;
  2090. }
  2091. }
  2092. });
  2093. $('.tabular.menu .item').tab();
  2094. $('.tabable.menu .item').tab();
  2095. $('.toggle.button').on('click', function () {
  2096. $($(this).data('target')).slideToggle(100);
  2097. });
  2098. // make table <tr> element clickable like a link
  2099. $('tr[data-href]').on('click', function () {
  2100. window.location = $(this).data('href');
  2101. });
  2102. // make table <td> element clickable like a link
  2103. $('td[data-href]').click(function () {
  2104. window.location = $(this).data('href');
  2105. });
  2106. // Dropzone
  2107. const $dropzone = $('#dropzone');
  2108. if ($dropzone.length > 0) {
  2109. const filenameDict = {};
  2110. await createDropzone('#dropzone', {
  2111. url: $dropzone.data('upload-url'),
  2112. headers: {'X-Csrf-Token': csrf},
  2113. maxFiles: $dropzone.data('max-file'),
  2114. maxFilesize: $dropzone.data('max-size'),
  2115. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  2116. addRemoveLinks: true,
  2117. dictDefaultMessage: $dropzone.data('default-message'),
  2118. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  2119. dictFileTooBig: $dropzone.data('file-too-big'),
  2120. dictRemoveFile: $dropzone.data('remove-file'),
  2121. timeout: 0,
  2122. init() {
  2123. this.on('success', (file, data) => {
  2124. filenameDict[file.name] = data.uuid;
  2125. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  2126. $('.files').append(input);
  2127. });
  2128. this.on('removedfile', (file) => {
  2129. if (file.name in filenameDict) {
  2130. $(`#${filenameDict[file.name]}`).remove();
  2131. }
  2132. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  2133. $.post($dropzone.data('remove-url'), {
  2134. file: filenameDict[file.name],
  2135. _csrf: $dropzone.data('csrf')
  2136. });
  2137. }
  2138. });
  2139. },
  2140. });
  2141. }
  2142. // Helpers.
  2143. $('.delete-button').on('click', showDeletePopup);
  2144. $('.add-all-button').on('click', showAddAllPopup);
  2145. $('.link-action').on('click', linkAction);
  2146. $('.link-email-action').on('click', linkEmailAction);
  2147. $('.delete-branch-button').on('click', showDeletePopup);
  2148. $('.undo-button').on('click', function () {
  2149. const $this = $(this);
  2150. $.post($this.data('url'), {
  2151. _csrf: csrf,
  2152. id: $this.data('id')
  2153. }).done((data) => {
  2154. window.location.href = data.redirect;
  2155. });
  2156. });
  2157. $('.show-panel.button').on('click', function () {
  2158. $($(this).data('panel')).show();
  2159. });
  2160. $('.show-modal.button').on('click', function () {
  2161. $($(this).data('modal')).modal('show');
  2162. });
  2163. $('.delete-post.button').on('click', function () {
  2164. const $this = $(this);
  2165. $.post($this.data('request-url'), {
  2166. _csrf: csrf
  2167. }).done(() => {
  2168. window.location.href = $this.data('done-url');
  2169. });
  2170. });
  2171. // Set anchor.
  2172. $('.markdown').each(function () {
  2173. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  2174. let node = $(this);
  2175. node = node.wrap('<div class="anchor-wrap"></div>');
  2176. node.append(`<a class="anchor" href="#${encodeURIComponent(node.attr('id'))}">${svg('octicon-link', 16)}</a>`);
  2177. });
  2178. });
  2179. $('.issue-checkbox').on('click', () => {
  2180. const numChecked = $('.issue-checkbox').children('input:checked').length;
  2181. if (numChecked > 0) {
  2182. $('#issue-filters').addClass('hide');
  2183. $('#issue-actions').removeClass('hide');
  2184. } else {
  2185. $('#issue-filters').removeClass('hide');
  2186. $('#issue-actions').addClass('hide');
  2187. }
  2188. });
  2189. $('.issue-action').on('click', function () {
  2190. let {action} = this.dataset;
  2191. let {elementId} = this.dataset;
  2192. const issueIDs = $('.issue-checkbox').children('input:checked').map(function () {
  2193. return this.dataset.issueId;
  2194. }).get().join();
  2195. const {url} = this.dataset;
  2196. if (elementId === '0' && url.substr(-9) === '/assignee') {
  2197. elementId = '';
  2198. action = 'clear';
  2199. }
  2200. updateIssuesMeta(url, action, issueIDs, elementId, '').then(() => {
  2201. // NOTICE: This reset of checkbox state targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2202. if (action === 'close' || action === 'open') {
  2203. // uncheck all checkboxes
  2204. $('.issue-checkbox input[type="checkbox"]').each((_, e) => { e.checked = false });
  2205. }
  2206. reload();
  2207. });
  2208. });
  2209. // NOTICE: This event trigger targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2210. // trigger ckecked event, if checkboxes are checked on load
  2211. $('.issue-checkbox input[type="checkbox"]:checked').first().each((_, e) => {
  2212. e.checked = false;
  2213. $(e).trigger('click');
  2214. });
  2215. $('.resolve-conversation').on('click', function (e) {
  2216. e.preventDefault();
  2217. const id = $(this).data('comment-id');
  2218. const action = $(this).data('action');
  2219. const url = $(this).data('update-url');
  2220. $.post(url, {
  2221. _csrf: csrf,
  2222. action,
  2223. comment_id: id,
  2224. }).then(reload);
  2225. });
  2226. buttonsClickOnEnter();
  2227. searchUsers();
  2228. searchTeams();
  2229. searchRepositories();
  2230. initCommentForm();
  2231. initInstall();
  2232. initRepository();
  2233. initMigration();
  2234. initWikiForm();
  2235. initEditForm();
  2236. initEditor();
  2237. initOrganization();
  2238. initGithook();
  2239. initWebhook();
  2240. initAdmin();
  2241. initCodeView();
  2242. initVueApp();
  2243. initTeamSettings();
  2244. initCtrlEnterSubmit();
  2245. initNavbarContentToggle();
  2246. initTopicbar();
  2247. initU2FAuth();
  2248. initU2FRegister();
  2249. initIssueList();
  2250. initWipTitle();
  2251. initPullRequestReview();
  2252. initRepoStatusChecker();
  2253. initTemplateSearch();
  2254. initContextPopups();
  2255. initNotificationsTable();
  2256. initTribute();
  2257. // Repo clone url.
  2258. if ($('#repo-clone-url').length > 0) {
  2259. switch (localStorage.getItem('repo-clone-protocol')) {
  2260. case 'ssh':
  2261. if ($('#repo-clone-ssh').length > 0) {
  2262. $('#repo-clone-ssh').trigger('click');
  2263. } else {
  2264. $('#repo-clone-https').trigger('click');
  2265. }
  2266. break;
  2267. default:
  2268. $('#repo-clone-https').trigger('click');
  2269. break;
  2270. }
  2271. }
  2272. const routes = {
  2273. 'div.user.settings': initUserSettings,
  2274. 'div.repository.settings.collaboration': initRepositoryCollaboration
  2275. };
  2276. let selector;
  2277. for (selector in routes) {
  2278. if ($(selector).length > 0) {
  2279. routes[selector]();
  2280. break;
  2281. }
  2282. }
  2283. const $cloneAddr = $('#clone_addr');
  2284. $cloneAddr.on('change', () => {
  2285. const $repoName = $('#repo_name');
  2286. if ($cloneAddr.val().length > 0 && $repoName.val().length === 0) { // Only modify if repo_name input is blank
  2287. $repoName.val($cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]);
  2288. }
  2289. });
  2290. // parallel init of async loaded features
  2291. await Promise.all([
  2292. highlight(document.querySelectorAll('pre code')),
  2293. initGitGraph(),
  2294. initClipboard(),
  2295. initUserHeatmap(),
  2296. initServiceWorker(),
  2297. initNotificationCount(),
  2298. ]);
  2299. });
  2300. function changeHash(hash) {
  2301. if (window.history.pushState) {
  2302. window.history.pushState(null, null, hash);
  2303. } else {
  2304. window.location.hash = hash;
  2305. }
  2306. }
  2307. function deSelect() {
  2308. if (window.getSelection) {
  2309. window.getSelection().removeAllRanges();
  2310. } else {
  2311. document.selection.empty();
  2312. }
  2313. }
  2314. function selectRange($list, $select, $from) {
  2315. $list.removeClass('active');
  2316. if ($from) {
  2317. let a = parseInt($select.attr('rel').substr(1));
  2318. let b = parseInt($from.attr('rel').substr(1));
  2319. let c;
  2320. if (a !== b) {
  2321. if (a > b) {
  2322. c = a;
  2323. a = b;
  2324. b = c;
  2325. }
  2326. const classes = [];
  2327. for (let i = a; i <= b; i++) {
  2328. classes.push(`.L${i}`);
  2329. }
  2330. $list.filter(classes.join(',')).addClass('active');
  2331. changeHash(`#L${a}-L${b}`);
  2332. return;
  2333. }
  2334. }
  2335. $select.addClass('active');
  2336. changeHash(`#${$select.attr('rel')}`);
  2337. }
  2338. $(() => {
  2339. // Warn users that try to leave a page after entering data into a form.
  2340. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  2341. if ($('.user.signin').length === 0) {
  2342. $('form:not(.ignore-dirty)').areYouSure();
  2343. }
  2344. // Parse SSH Key
  2345. $('#ssh-key-content').on('change paste keyup', function () {
  2346. const arrays = $(this).val().split(' ');
  2347. const $title = $('#ssh-key-title');
  2348. if ($title.val() === '' && arrays.length === 3 && arrays[2] !== '') {
  2349. $title.val(arrays[2]);
  2350. }
  2351. });
  2352. });
  2353. function showDeletePopup() {
  2354. const $this = $(this);
  2355. let filter = '';
  2356. if ($this.attr('id')) {
  2357. filter += `#${$this.attr('id')}`;
  2358. }
  2359. const dialog = $(`.delete.modal${filter}`);
  2360. dialog.find('.name').text($this.data('name'));
  2361. dialog.modal({
  2362. closable: false,
  2363. onApprove() {
  2364. if ($this.data('type') === 'form') {
  2365. $($this.data('form')).trigger('submit');
  2366. return;
  2367. }
  2368. $.post($this.data('url'), {
  2369. _csrf: csrf,
  2370. id: $this.data('id')
  2371. }).done((data) => {
  2372. window.location.href = data.redirect;
  2373. });
  2374. }
  2375. }).modal('show');
  2376. return false;
  2377. }
  2378. function showAddAllPopup() {
  2379. const $this = $(this);
  2380. let filter = '';
  2381. if ($this.attr('id')) {
  2382. filter += `#${$this.attr('id')}`;
  2383. }
  2384. const dialog = $(`.addall.modal${filter}`);
  2385. dialog.find('.name').text($this.data('name'));
  2386. dialog.modal({
  2387. closable: false,
  2388. onApprove() {
  2389. if ($this.data('type') === 'form') {
  2390. $($this.data('form')).trigger('submit');
  2391. return;
  2392. }
  2393. $.post($this.data('url'), {
  2394. _csrf: csrf,
  2395. id: $this.data('id')
  2396. }).done((data) => {
  2397. window.location.href = data.redirect;
  2398. });
  2399. }
  2400. }).modal('show');
  2401. return false;
  2402. }
  2403. function linkAction(e) {
  2404. e.preventDefault();
  2405. const $this = $(this);
  2406. const redirect = $this.data('redirect');
  2407. $.post($this.data('url'), {
  2408. _csrf: csrf
  2409. }).done((data) => {
  2410. if (data.redirect) {
  2411. window.location.href = data.redirect;
  2412. } else if (redirect) {
  2413. window.location.href = redirect;
  2414. } else {
  2415. window.location.reload();
  2416. }
  2417. });
  2418. }
  2419. function linkEmailAction(e) {
  2420. const $this = $(this);
  2421. $('#form-uid').val($this.data('uid'));
  2422. $('#form-email').val($this.data('email'));
  2423. $('#form-primary').val($this.data('primary'));
  2424. $('#form-activate').val($this.data('activate'));
  2425. $('#form-uid').val($this.data('uid'));
  2426. $('#change-email-modal').modal('show');
  2427. e.preventDefault();
  2428. }
  2429. function initVueComponents() {
  2430. const vueDelimeters = ['${', '}'];
  2431. Vue.component('repo-search', {
  2432. delimiters: vueDelimeters,
  2433. props: {
  2434. searchLimit: {
  2435. type: Number,
  2436. default: 10
  2437. },
  2438. suburl: {
  2439. type: String,
  2440. required: true
  2441. },
  2442. uid: {
  2443. type: Number,
  2444. required: true
  2445. },
  2446. organizations: {
  2447. type: Array,
  2448. default: []
  2449. },
  2450. isOrganization: {
  2451. type: Boolean,
  2452. default: true
  2453. },
  2454. canCreateOrganization: {
  2455. type: Boolean,
  2456. default: false
  2457. },
  2458. organizationsTotalCount: {
  2459. type: Number,
  2460. default: 0
  2461. },
  2462. moreReposLink: {
  2463. type: String,
  2464. default: ''
  2465. }
  2466. },
  2467. data() {
  2468. const params = new URLSearchParams(window.location.search);
  2469. let tab = params.get('repo-search-tab');
  2470. if (!tab) {
  2471. tab = 'repos';
  2472. }
  2473. let reposFilter = params.get('repo-search-filter');
  2474. if (!reposFilter) {
  2475. reposFilter = 'all';
  2476. }
  2477. let privateFilter = params.get('repo-search-private');
  2478. if (!privateFilter) {
  2479. privateFilter = 'both';
  2480. }
  2481. let archivedFilter = params.get('repo-search-archived');
  2482. if (!archivedFilter) {
  2483. archivedFilter = 'unarchived';
  2484. }
  2485. let searchQuery = params.get('repo-search-query');
  2486. if (!searchQuery) {
  2487. searchQuery = '';
  2488. }
  2489. let page = 1;
  2490. try {
  2491. page = parseInt(params.get('repo-search-page'));
  2492. } catch {
  2493. // noop
  2494. }
  2495. if (!page) {
  2496. page = 1;
  2497. }
  2498. return {
  2499. tab,
  2500. repos: [],
  2501. reposTotalCount: 0,
  2502. reposFilter,
  2503. archivedFilter,
  2504. privateFilter,
  2505. page,
  2506. finalPage: 1,
  2507. searchQuery,
  2508. isLoading: false,
  2509. staticPrefix: StaticUrlPrefix,
  2510. counts: {},
  2511. repoTypes: {
  2512. all: {
  2513. searchMode: '',
  2514. },
  2515. forks: {
  2516. searchMode: 'fork',
  2517. },
  2518. mirrors: {
  2519. searchMode: 'mirror',
  2520. },
  2521. sources: {
  2522. searchMode: 'source',
  2523. },
  2524. collaborative: {
  2525. searchMode: 'collaborative',
  2526. },
  2527. }
  2528. };
  2529. },
  2530. computed: {
  2531. showMoreReposLink() {
  2532. return this.repos.length > 0 && this.repos.length < this.counts[`${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`];
  2533. },
  2534. searchURL() {
  2535. return `${this.suburl}/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&q=${this.searchQuery
  2536. }&page=${this.page}&limit=${this.searchLimit}&mode=${this.repoTypes[this.reposFilter].searchMode
  2537. }${this.reposFilter !== 'all' ? '&exclusive=1' : ''
  2538. }${this.archivedFilter === 'archived' ? '&archived=true' : ''}${this.archivedFilter === 'unarchived' ? '&archived=false' : ''
  2539. }${this.privateFilter === 'private' ? '&is_private=true' : ''}${this.privateFilter === 'public' ? '&is_private=false' : ''
  2540. }`;
  2541. },
  2542. repoTypeCount() {
  2543. return this.counts[`${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`];
  2544. }
  2545. },
  2546. mounted() {
  2547. this.searchRepos(this.reposFilter);
  2548. $(this.$el).find('.poping.up').popup();
  2549. $(this.$el).find('.dropdown').dropdown();
  2550. this.setCheckboxes();
  2551. const self = this;
  2552. Vue.nextTick(() => {
  2553. self.$refs.search.focus();
  2554. });
  2555. },
  2556. methods: {
  2557. changeTab(t) {
  2558. this.tab = t;
  2559. this.updateHistory();
  2560. },
  2561. setCheckboxes() {
  2562. switch (this.archivedFilter) {
  2563. case 'unarchived':
  2564. $('#archivedFilterCheckbox').checkbox('set unchecked');
  2565. break;
  2566. case 'archived':
  2567. $('#archivedFilterCheckbox').checkbox('set checked');
  2568. break;
  2569. case 'both':
  2570. $('#archivedFilterCheckbox').checkbox('set indeterminate');
  2571. break;
  2572. default:
  2573. this.archivedFilter = 'unarchived';
  2574. $('#archivedFilterCheckbox').checkbox('set unchecked');
  2575. break;
  2576. }
  2577. switch (this.privateFilter) {
  2578. case 'public':
  2579. $('#privateFilterCheckbox').checkbox('set unchecked');
  2580. break;
  2581. case 'private':
  2582. $('#privateFilterCheckbox').checkbox('set checked');
  2583. break;
  2584. case 'both':
  2585. $('#privateFilterCheckbox').checkbox('set indeterminate');
  2586. break;
  2587. default:
  2588. this.privateFilter = 'both';
  2589. $('#privateFilterCheckbox').checkbox('set indeterminate');
  2590. break;
  2591. }
  2592. },
  2593. changeReposFilter(filter) {
  2594. this.reposFilter = filter;
  2595. this.repos = [];
  2596. this.page = 1;
  2597. Vue.set(this.counts, `${filter}:${this.archivedFilter}:${this.privateFilter}`, 0);
  2598. this.searchRepos();
  2599. },
  2600. updateHistory() {
  2601. const params = new URLSearchParams(window.location.search);
  2602. if (this.tab === 'repos') {
  2603. params.delete('repo-search-tab');
  2604. } else {
  2605. params.set('repo-search-tab', this.tab);
  2606. }
  2607. if (this.reposFilter === 'all') {
  2608. params.delete('repo-search-filter');
  2609. } else {
  2610. params.set('repo-search-filter', this.reposFilter);
  2611. }
  2612. if (this.privateFilter === 'both') {
  2613. params.delete('repo-search-private');
  2614. } else {
  2615. params.set('repo-search-private', this.privateFilter);
  2616. }
  2617. if (this.archivedFilter === 'unarchived') {
  2618. params.delete('repo-search-archived');
  2619. } else {
  2620. params.set('repo-search-archived', this.archivedFilter);
  2621. }
  2622. if (this.searchQuery === '') {
  2623. params.delete('repo-search-query');
  2624. } else {
  2625. params.set('repo-search-query', this.searchQuery);
  2626. }
  2627. if (this.page === 1) {
  2628. params.delete('repo-search-page');
  2629. } else {
  2630. params.set('repo-search-page', `${this.page}`);
  2631. }
  2632. const queryString = params.toString();
  2633. if (queryString) {
  2634. window.history.replaceState({}, '', `?${queryString}`);
  2635. } else {
  2636. window.history.replaceState({}, '', window.location.pathname);
  2637. }
  2638. },
  2639. toggleArchivedFilter() {
  2640. switch (this.archivedFilter) {
  2641. case 'both':
  2642. this.archivedFilter = 'unarchived';
  2643. break;
  2644. case 'unarchived':
  2645. this.archivedFilter = 'archived';
  2646. break;
  2647. case 'archived':
  2648. this.archivedFilter = 'both';
  2649. break;
  2650. default:
  2651. this.archivedFilter = 'unarchived';
  2652. break;
  2653. }
  2654. this.page = 1;
  2655. this.repos = [];
  2656. this.setCheckboxes();
  2657. Vue.set(this.counts, `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`, 0);
  2658. this.searchRepos();
  2659. },
  2660. togglePrivateFilter() {
  2661. switch (this.privateFilter) {
  2662. case 'both':
  2663. this.privateFilter = 'public';
  2664. break;
  2665. case 'public':
  2666. this.privateFilter = 'private';
  2667. break;
  2668. case 'private':
  2669. this.privateFilter = 'both';
  2670. break;
  2671. default:
  2672. this.privateFilter = 'both';
  2673. break;
  2674. }
  2675. this.page = 1;
  2676. this.repos = [];
  2677. this.setCheckboxes();
  2678. Vue.set(this.counts, `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`, 0);
  2679. this.searchRepos();
  2680. },
  2681. changePage(page) {
  2682. this.page = page;
  2683. if (this.page > this.finalPage) {
  2684. this.page = this.finalPage;
  2685. }
  2686. if (this.page < 1) {
  2687. this.page = 1;
  2688. }
  2689. this.repos = [];
  2690. Vue.set(this.counts, `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`, 0);
  2691. this.searchRepos();
  2692. },
  2693. searchRepos() {
  2694. const self = this;
  2695. this.isLoading = true;
  2696. if (!this.reposTotalCount) {
  2697. const totalCountSearchURL = `${this.suburl}/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&q=&page=1&mode=`;
  2698. $.getJSON(totalCountSearchURL, (_result, _textStatus, request) => {
  2699. self.reposTotalCount = request.getResponseHeader('X-Total-Count');
  2700. });
  2701. }
  2702. const searchedMode = this.repoTypes[this.reposFilter].searchMode;
  2703. const searchedURL = this.searchURL;
  2704. const searchedQuery = this.searchQuery;
  2705. $.getJSON(searchedURL, (result, _textStatus, request) => {
  2706. if (searchedURL === self.searchURL) {
  2707. self.repos = result.data;
  2708. const count = request.getResponseHeader('X-Total-Count');
  2709. if (searchedQuery === '' && searchedMode === '' && self.archivedFilter === 'both') {
  2710. self.reposTotalCount = count;
  2711. }
  2712. Vue.set(self.counts, `${self.reposFilter}:${self.archivedFilter}:${self.privateFilter}`, count);
  2713. self.finalPage = Math.floor(count / self.searchLimit) + 1;
  2714. self.updateHistory();
  2715. }
  2716. }).always(() => {
  2717. if (searchedURL === self.searchURL) {
  2718. self.isLoading = false;
  2719. }
  2720. });
  2721. },
  2722. repoClass(repo) {
  2723. if (repo.fork) {
  2724. return 'octicon-repo-forked';
  2725. } if (repo.mirror) {
  2726. return 'octicon-repo-clone';
  2727. } if (repo.template) {
  2728. return `octicon-repo-template${repo.private ? '-private' : ''}`;
  2729. } if (repo.private) {
  2730. return 'octicon-lock';
  2731. }
  2732. return 'octicon-repo';
  2733. }
  2734. }
  2735. });
  2736. }
  2737. function initCtrlEnterSubmit() {
  2738. $('.js-quick-submit').on('keydown', function (e) {
  2739. if (((e.ctrlKey && !e.altKey) || e.metaKey) && (e.keyCode === 13 || e.keyCode === 10)) {
  2740. $(this).closest('form').trigger('submit');
  2741. }
  2742. });
  2743. }
  2744. function initVueApp() {
  2745. const el = document.getElementById('app');
  2746. if (!el) {
  2747. return;
  2748. }
  2749. initVueComponents();
  2750. new Vue({
  2751. delimiters: ['${', '}'],
  2752. el,
  2753. data: {
  2754. searchLimit: Number((document.querySelector('meta[name=_search_limit]') || {}).content),
  2755. suburl: AppSubUrl,
  2756. uid: Number((document.querySelector('meta[name=_context_uid]') || {}).content),
  2757. activityTopAuthors: window.ActivityTopAuthors || [],
  2758. },
  2759. components: {
  2760. ActivityTopAuthors,
  2761. },
  2762. });
  2763. }
  2764. window.timeAddManual = function () {
  2765. $('.mini.modal')
  2766. .modal({
  2767. duration: 200,
  2768. onApprove() {
  2769. $('#add_time_manual_form').trigger('submit');
  2770. }
  2771. }).modal('show');
  2772. };
  2773. window.toggleStopwatch = function () {
  2774. $('#toggle_stopwatch_form').trigger('submit');
  2775. };
  2776. window.cancelStopwatch = function () {
  2777. $('#cancel_stopwatch_form').trigger('submit');
  2778. };
  2779. function initFilterBranchTagDropdown(selector) {
  2780. $(selector).each(function () {
  2781. const $dropdown = $(this);
  2782. const $data = $dropdown.find('.data');
  2783. const data = {
  2784. items: [],
  2785. mode: $data.data('mode'),
  2786. searchTerm: '',
  2787. noResults: '',
  2788. canCreateBranch: false,
  2789. menuVisible: false,
  2790. active: 0
  2791. };
  2792. $data.find('.item').each(function () {
  2793. data.items.push({
  2794. name: $(this).text(),
  2795. url: $(this).data('url'),
  2796. branch: $(this).hasClass('branch'),
  2797. tag: $(this).hasClass('tag'),
  2798. selected: $(this).hasClass('selected')
  2799. });
  2800. });
  2801. $data.remove();
  2802. new Vue({
  2803. delimiters: ['${', '}'],
  2804. el: this,
  2805. data,
  2806. beforeMount() {
  2807. const vm = this;
  2808. this.noResults = vm.$el.getAttribute('data-no-results');
  2809. this.canCreateBranch = vm.$el.getAttribute('data-can-create-branch') === 'true';
  2810. document.body.addEventListener('click', (event) => {
  2811. if (vm.$el.contains(event.target)) {
  2812. return;
  2813. }
  2814. if (vm.menuVisible) {
  2815. Vue.set(vm, 'menuVisible', false);
  2816. }
  2817. });
  2818. },
  2819. watch: {
  2820. menuVisible(visible) {
  2821. if (visible) {
  2822. this.focusSearchField();
  2823. }
  2824. }
  2825. },
  2826. computed: {
  2827. filteredItems() {
  2828. const vm = this;
  2829. const items = vm.items.filter((item) => {
  2830. return ((vm.mode === 'branches' && item.branch) || (vm.mode === 'tags' && item.tag)) &&
  2831. (!vm.searchTerm || item.name.toLowerCase().includes(vm.searchTerm.toLowerCase()));
  2832. });
  2833. vm.active = (items.length === 0 && vm.showCreateNewBranch ? 0 : -1);
  2834. return items;
  2835. },
  2836. showNoResults() {
  2837. return this.filteredItems.length === 0 && !this.showCreateNewBranch;
  2838. },
  2839. showCreateNewBranch() {
  2840. const vm = this;
  2841. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') {
  2842. return false;
  2843. }
  2844. return vm.items.filter((item) => item.name.toLowerCase() === vm.searchTerm.toLowerCase()).length === 0;
  2845. }
  2846. },
  2847. methods: {
  2848. selectItem(item) {
  2849. const prev = this.getSelected();
  2850. if (prev !== null) {
  2851. prev.selected = false;
  2852. }
  2853. item.selected = true;
  2854. window.location.href = item.url;
  2855. },
  2856. createNewBranch() {
  2857. if (!this.showCreateNewBranch) {
  2858. return;
  2859. }
  2860. $(this.$refs.newBranchForm).trigger('submit');
  2861. },
  2862. focusSearchField() {
  2863. const vm = this;
  2864. Vue.nextTick(() => {
  2865. vm.$refs.searchField.focus();
  2866. });
  2867. },
  2868. getSelected() {
  2869. for (let i = 0, j = this.items.length; i < j; ++i) {
  2870. if (this.items[i].selected) return this.items[i];
  2871. }
  2872. return null;
  2873. },
  2874. getSelectedIndexInFiltered() {
  2875. for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
  2876. if (this.filteredItems[i].selected) return i;
  2877. }
  2878. return -1;
  2879. },
  2880. scrollToActive() {
  2881. let el = this.$refs[`listItem${this.active}`];
  2882. if (!el || el.length === 0) {
  2883. return;
  2884. }
  2885. if (Array.isArray(el)) {
  2886. el = el[0];
  2887. }
  2888. const cont = this.$refs.scrollContainer;
  2889. if (el.offsetTop < cont.scrollTop) {
  2890. cont.scrollTop = el.offsetTop;
  2891. } else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
  2892. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  2893. }
  2894. },
  2895. keydown(event) {
  2896. const vm = this;
  2897. if (event.keyCode === 40) {
  2898. // arrow down
  2899. event.preventDefault();
  2900. if (vm.active === -1) {
  2901. vm.active = vm.getSelectedIndexInFiltered();
  2902. }
  2903. if (vm.active + (vm.showCreateNewBranch ? 0 : 1) >= vm.filteredItems.length) {
  2904. return;
  2905. }
  2906. vm.active++;
  2907. vm.scrollToActive();
  2908. }
  2909. if (event.keyCode === 38) {
  2910. // arrow up
  2911. event.preventDefault();
  2912. if (vm.active === -1) {
  2913. vm.active = vm.getSelectedIndexInFiltered();
  2914. }
  2915. if (vm.active <= 0) {
  2916. return;
  2917. }
  2918. vm.active--;
  2919. vm.scrollToActive();
  2920. }
  2921. if (event.keyCode === 13) {
  2922. // enter
  2923. event.preventDefault();
  2924. if (vm.active >= vm.filteredItems.length) {
  2925. vm.createNewBranch();
  2926. } else if (vm.active >= 0) {
  2927. vm.selectItem(vm.filteredItems[vm.active]);
  2928. }
  2929. }
  2930. if (event.keyCode === 27) {
  2931. // escape
  2932. event.preventDefault();
  2933. vm.menuVisible = false;
  2934. }
  2935. }
  2936. }
  2937. });
  2938. });
  2939. }
  2940. $('.commit-button').on('click', function (e) {
  2941. e.preventDefault();
  2942. $(this).parent().find('.commit-body').toggle();
  2943. });
  2944. function initNavbarContentToggle() {
  2945. const content = $('#navbar');
  2946. const toggle = $('#navbar-expand-toggle');
  2947. let isExpanded = false;
  2948. toggle.on('click', () => {
  2949. isExpanded = !isExpanded;
  2950. if (isExpanded) {
  2951. content.addClass('shown');
  2952. toggle.addClass('active');
  2953. } else {
  2954. content.removeClass('shown');
  2955. toggle.removeClass('active');
  2956. }
  2957. });
  2958. }
  2959. function initTopicbar() {
  2960. const mgrBtn = $('#manage_topic');
  2961. const editDiv = $('#topic_edit');
  2962. const viewDiv = $('#repo-topics');
  2963. const saveBtn = $('#save_topic');
  2964. const topicDropdown = $('#topic_edit .dropdown');
  2965. const topicForm = $('#topic_edit.ui.form');
  2966. const topicPrompts = getPrompts();
  2967. mgrBtn.on('click', () => {
  2968. viewDiv.hide();
  2969. editDiv.css('display', ''); // show Semantic UI Grid
  2970. });
  2971. function getPrompts() {
  2972. const hidePrompt = $('div.hide#validate_prompt');
  2973. const prompts = {
  2974. countPrompt: hidePrompt.children('#count_prompt').text(),
  2975. formatPrompt: hidePrompt.children('#format_prompt').text()
  2976. };
  2977. hidePrompt.remove();
  2978. return prompts;
  2979. }
  2980. saveBtn.on('click', () => {
  2981. const topics = $('input[name=topics]').val();
  2982. $.post(saveBtn.data('link'), {
  2983. _csrf: csrf,
  2984. topics
  2985. }, (_data, _textStatus, xhr) => {
  2986. if (xhr.responseJSON.status === 'ok') {
  2987. viewDiv.children('.topic').remove();
  2988. if (topics.length) {
  2989. const topicArray = topics.split(',');
  2990. const last = viewDiv.children('a').last();
  2991. for (let i = 0; i < topicArray.length; i++) {
  2992. const link = $('<a class="ui repo-topic small label topic"></a>');
  2993. link.attr('href', `${AppSubUrl}/explore/repos?q=${encodeURIComponent(topicArray[i])}&topic=1`);
  2994. link.text(topicArray[i]);
  2995. link.insertBefore(last);
  2996. }
  2997. }
  2998. editDiv.css('display', 'none');
  2999. viewDiv.show();
  3000. }
  3001. }).fail((xhr) => {
  3002. if (xhr.status === 422) {
  3003. if (xhr.responseJSON.invalidTopics.length > 0) {
  3004. topicPrompts.formatPrompt = xhr.responseJSON.message;
  3005. const {invalidTopics} = xhr.responseJSON;
  3006. const topicLables = topicDropdown.children('a.ui.label');
  3007. topics.split(',').forEach((value, index) => {
  3008. for (let i = 0; i < invalidTopics.length; i++) {
  3009. if (invalidTopics[i] === value) {
  3010. topicLables.eq(index).removeClass('green').addClass('red');
  3011. }
  3012. }
  3013. });
  3014. } else {
  3015. topicPrompts.countPrompt = xhr.responseJSON.message;
  3016. }
  3017. }
  3018. }).always(() => {
  3019. topicForm.form('validate form');
  3020. });
  3021. });
  3022. topicDropdown.dropdown({
  3023. allowAdditions: true,
  3024. forceSelection: false,
  3025. fields: {name: 'description', value: 'data-value'},
  3026. saveRemoteData: false,
  3027. label: {
  3028. transition: 'horizontal flip',
  3029. duration: 200,
  3030. variation: false,
  3031. blue: true,
  3032. basic: true,
  3033. },
  3034. className: {
  3035. label: 'ui small label'
  3036. },
  3037. apiSettings: {
  3038. url: `${AppSubUrl}/api/v1/topics/search?q={query}`,
  3039. throttle: 500,
  3040. cache: false,
  3041. onResponse(res) {
  3042. const formattedResponse = {
  3043. success: false,
  3044. results: [],
  3045. };
  3046. const stripTags = function (text) {
  3047. return text.replace(/<[^>]*>?/gm, '');
  3048. };
  3049. const query = stripTags(this.urlData.query.trim());
  3050. let found_query = false;
  3051. const current_topics = [];
  3052. topicDropdown.find('div.label.visible.topic,a.label.visible').each((_, e) => { current_topics.push(e.dataset.value) });
  3053. if (res.topics) {
  3054. let found = false;
  3055. for (let i = 0; i < res.topics.length; i++) {
  3056. // skip currently added tags
  3057. if (current_topics.includes(res.topics[i].topic_name)) {
  3058. continue;
  3059. }
  3060. if (res.topics[i].topic_name.toLowerCase() === query.toLowerCase()) {
  3061. found_query = true;
  3062. }
  3063. formattedResponse.results.push({description: res.topics[i].topic_name, 'data-value': res.topics[i].topic_name});
  3064. found = true;
  3065. }
  3066. formattedResponse.success = found;
  3067. }
  3068. if (query.length > 0 && !found_query) {
  3069. formattedResponse.success = true;
  3070. formattedResponse.results.unshift({description: query, 'data-value': query});
  3071. } else if (query.length > 0 && found_query) {
  3072. formattedResponse.results.sort((a, b) => {
  3073. if (a.description.toLowerCase() === query.toLowerCase()) return -1;
  3074. if (b.description.toLowerCase() === query.toLowerCase()) return 1;
  3075. if (a.description > b.description) return -1;
  3076. if (a.description < b.description) return 1;
  3077. return 0;
  3078. });
  3079. }
  3080. return formattedResponse;
  3081. },
  3082. },
  3083. onLabelCreate(value) {
  3084. value = value.toLowerCase().trim();
  3085. this.attr('data-value', value).contents().first().replaceWith(value);
  3086. return $(this);
  3087. },
  3088. onAdd(addedValue, _addedText, $addedChoice) {
  3089. addedValue = addedValue.toLowerCase().trim();
  3090. $($addedChoice).attr('data-value', addedValue);
  3091. $($addedChoice).attr('data-text', addedValue);
  3092. }
  3093. });
  3094. $.fn.form.settings.rules.validateTopic = function (_values, regExp) {
  3095. const topics = topicDropdown.children('a.ui.label');
  3096. const status = topics.length === 0 || topics.last().attr('data-value').match(regExp);
  3097. if (!status) {
  3098. topics.last().removeClass('green').addClass('red');
  3099. }
  3100. return status && topicDropdown.children('a.ui.label.red').length === 0;
  3101. };
  3102. topicForm.form({
  3103. on: 'change',
  3104. inline: true,
  3105. fields: {
  3106. topics: {
  3107. identifier: 'topics',
  3108. rules: [
  3109. {
  3110. type: 'validateTopic',
  3111. value: /^[a-z0-9][a-z0-9-]{0,35}$/,
  3112. prompt: topicPrompts.formatPrompt
  3113. },
  3114. {
  3115. type: 'maxCount[25]',
  3116. prompt: topicPrompts.countPrompt
  3117. }
  3118. ]
  3119. },
  3120. }
  3121. });
  3122. }
  3123. window.toggleDeadlineForm = function () {
  3124. $('#deadlineForm').fadeToggle(150);
  3125. };
  3126. window.setDeadline = function () {
  3127. const deadline = $('#deadlineDate').val();
  3128. window.updateDeadline(deadline);
  3129. };
  3130. window.updateDeadline = function (deadlineString) {
  3131. $('#deadline-err-invalid-date').hide();
  3132. $('#deadline-loader').addClass('loading');
  3133. let realDeadline = null;
  3134. if (deadlineString !== '') {
  3135. const newDate = Date.parse(deadlineString);
  3136. if (Number.isNaN(newDate)) {
  3137. $('#deadline-loader').removeClass('loading');
  3138. $('#deadline-err-invalid-date').show();
  3139. return false;
  3140. }
  3141. realDeadline = new Date(newDate);
  3142. }
  3143. $.ajax(`${$('#update-issue-deadline-form').attr('action')}/deadline`, {
  3144. data: JSON.stringify({
  3145. due_date: realDeadline,
  3146. }),
  3147. headers: {
  3148. 'X-Csrf-Token': csrf,
  3149. 'X-Remote': true,
  3150. },
  3151. contentType: 'application/json',
  3152. type: 'POST',
  3153. success() {
  3154. reload();
  3155. },
  3156. error() {
  3157. $('#deadline-loader').removeClass('loading');
  3158. $('#deadline-err-invalid-date').show();
  3159. }
  3160. });
  3161. };
  3162. window.deleteDependencyModal = function (id, type) {
  3163. $('.remove-dependency')
  3164. .modal({
  3165. closable: false,
  3166. duration: 200,
  3167. onApprove() {
  3168. $('#removeDependencyID').val(id);
  3169. $('#dependencyType').val(type);
  3170. $('#removeDependencyForm').trigger('submit');
  3171. }
  3172. }).modal('show');
  3173. };
  3174. function initIssueList() {
  3175. const repolink = $('#repolink').val();
  3176. const repoId = $('#repoId').val();
  3177. const crossRepoSearch = $('#crossRepoSearch').val();
  3178. const tp = $('#type').val();
  3179. let issueSearchUrl = `${AppSubUrl}/api/v1/repos/${repolink}/issues?q={query}&type=${tp}`;
  3180. if (crossRepoSearch === 'true') {
  3181. issueSearchUrl = `${AppSubUrl}/api/v1/repos/issues/search?q={query}&priority_repo_id=${repoId}&type=${tp}`;
  3182. }
  3183. $('#new-dependency-drop-list')
  3184. .dropdown({
  3185. apiSettings: {
  3186. url: issueSearchUrl,
  3187. onResponse(response) {
  3188. const filteredResponse = {success: true, results: []};
  3189. const currIssueId = $('#new-dependency-drop-list').data('issue-id');
  3190. // Parse the response from the api to work with our dropdown
  3191. $.each(response, (_i, issue) => {
  3192. // Don't list current issue in the dependency list.
  3193. if (issue.id === currIssueId) {
  3194. return;
  3195. }
  3196. filteredResponse.results.push({
  3197. name: `#${issue.number} ${htmlEscape(issue.title)
  3198. }<div class="text small dont-break-out">${htmlEscape(issue.repository.full_name)}</div>`,
  3199. value: issue.id
  3200. });
  3201. });
  3202. return filteredResponse;
  3203. },
  3204. cache: false,
  3205. },
  3206. fullTextSearch: true
  3207. });
  3208. $('.menu a.label-filter-item').each(function () {
  3209. $(this).on('click', function (e) {
  3210. if (e.altKey) {
  3211. e.preventDefault();
  3212. const href = $(this).attr('href');
  3213. const id = $(this).data('label-id');
  3214. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  3215. const newStr = 'labels=$1-$2$3&';
  3216. window.location = href.replace(new RegExp(regStr), newStr);
  3217. }
  3218. });
  3219. });
  3220. $('.menu .ui.dropdown.label-filter').on('keydown', (e) => {
  3221. if (e.altKey && e.keyCode === 13) {
  3222. const selectedItems = $('.menu .ui.dropdown.label-filter .menu .item.selected');
  3223. if (selectedItems.length > 0) {
  3224. const item = $(selectedItems[0]);
  3225. const href = item.attr('href');
  3226. const id = item.data('label-id');
  3227. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  3228. const newStr = 'labels=$1-$2$3&';
  3229. window.location = href.replace(new RegExp(regStr), newStr);
  3230. }
  3231. }
  3232. });
  3233. }
  3234. window.cancelCodeComment = function (btn) {
  3235. const form = $(btn).closest('form');
  3236. if (form.length > 0 && form.hasClass('comment-form')) {
  3237. form.addClass('hide');
  3238. form.parent().find('button.comment-form-reply').show();
  3239. } else {
  3240. form.closest('.comment-code-cloud').remove();
  3241. }
  3242. };
  3243. window.submitReply = function (btn) {
  3244. const form = $(btn).closest('form');
  3245. if (form.length > 0 && form.hasClass('comment-form')) {
  3246. form.trigger('submit');
  3247. }
  3248. };
  3249. window.onOAuthLoginClick = function () {
  3250. const oauthLoader = $('#oauth2-login-loader');
  3251. const oauthNav = $('#oauth2-login-navigator');
  3252. oauthNav.hide();
  3253. oauthLoader.removeClass('disabled');
  3254. setTimeout(() => {
  3255. // recover previous content to let user try again
  3256. // usually redirection will be performed before this action
  3257. oauthLoader.addClass('disabled');
  3258. oauthNav.show();
  3259. }, 5000);
  3260. };
  3261. // Pull SVGs via AJAX to workaround CORS issues with <use> tags
  3262. // https://css-tricks.com/ajaxing-svg-sprite/
  3263. $.get(`${window.config.StaticUrlPrefix}/img/svg/icons.svg`, (data) => {
  3264. const div = document.createElement('div');
  3265. div.style.display = 'none';
  3266. div.innerHTML = new XMLSerializer().serializeToString(data.documentElement);
  3267. document.body.insertBefore(div, document.body.childNodes[0]);
  3268. });