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

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