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

index.js 109KB

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