您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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