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

index.js 102 kB

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