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

index.js 120KB

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