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

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