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

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