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

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