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

index.js 108KB

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