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.

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