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

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