Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.js 107KB

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