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

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