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

index.js 105KB

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