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

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