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 107KB

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