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

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