Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.js 109KB

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