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

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