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

index.js 107KB

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