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

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