選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 107KB

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