You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 106KB

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