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

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