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

index.js 106KB

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