您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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