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

index.js 100 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297
  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. $('.ui.fold-code').on('click', (e) => {
  1699. const $foldButton = $(e.target);
  1700. if ($foldButton.hasClass('fa-chevron-down')) {
  1701. $(e.target).parent().next().slideUp('fast', () => {
  1702. $foldButton.removeClass('fa-chevron-down').addClass('fa-chevron-right');
  1703. });
  1704. } else {
  1705. $(e.target).parent().next().slideDown('fast', () => {
  1706. $foldButton.removeClass('fa-chevron-right').addClass('fa-chevron-down');
  1707. });
  1708. }
  1709. });
  1710. function insertBlobExcerpt(e) {
  1711. const $blob = $(e.target);
  1712. const $row = $blob.parent().parent();
  1713. $.get(`${$blob.data('url')}?${$blob.data('query')}&anchor=${$blob.data('anchor')}`, (blob) => {
  1714. $row.replaceWith(blob);
  1715. $(`[data-anchor="${$blob.data('anchor')}"]`).on('click', (e) => { insertBlobExcerpt(e); });
  1716. });
  1717. }
  1718. $('.ui.blob-excerpt').on('click', (e) => { insertBlobExcerpt(e); });
  1719. }
  1720. function initU2FAuth() {
  1721. if ($('#wait-for-key').length === 0) {
  1722. return;
  1723. }
  1724. u2fApi.ensureSupport()
  1725. .then(() => {
  1726. $.getJSON(`${suburl}/user/u2f/challenge`).success((req) => {
  1727. u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
  1728. .then(u2fSigned)
  1729. .catch((err) => {
  1730. if (err === undefined) {
  1731. u2fError(1);
  1732. return;
  1733. }
  1734. u2fError(err.metaData.code);
  1735. });
  1736. });
  1737. }).catch(() => {
  1738. // Fallback in case browser do not support U2F
  1739. window.location.href = `${suburl}/user/two_factor`;
  1740. });
  1741. }
  1742. function u2fSigned(resp) {
  1743. $.ajax({
  1744. url: `${suburl}/user/u2f/sign`,
  1745. type: 'POST',
  1746. headers: { 'X-Csrf-Token': csrf },
  1747. data: JSON.stringify(resp),
  1748. contentType: 'application/json; charset=utf-8',
  1749. }).done((res) => {
  1750. window.location.replace(res);
  1751. }).fail(() => {
  1752. u2fError(1);
  1753. });
  1754. }
  1755. function u2fRegistered(resp) {
  1756. if (checkError(resp)) {
  1757. return;
  1758. }
  1759. $.ajax({
  1760. url: `${suburl}/user/settings/security/u2f/register`,
  1761. type: 'POST',
  1762. headers: { 'X-Csrf-Token': csrf },
  1763. data: JSON.stringify(resp),
  1764. contentType: 'application/json; charset=utf-8',
  1765. success() {
  1766. reload();
  1767. },
  1768. fail() {
  1769. u2fError(1);
  1770. }
  1771. });
  1772. }
  1773. function checkError(resp) {
  1774. if (!('errorCode' in resp)) {
  1775. return false;
  1776. }
  1777. if (resp.errorCode === 0) {
  1778. return false;
  1779. }
  1780. u2fError(resp.errorCode);
  1781. return true;
  1782. }
  1783. function u2fError(errorType) {
  1784. const u2fErrors = {
  1785. browser: $('#unsupported-browser'),
  1786. 1: $('#u2f-error-1'),
  1787. 2: $('#u2f-error-2'),
  1788. 3: $('#u2f-error-3'),
  1789. 4: $('#u2f-error-4'),
  1790. 5: $('.u2f-error-5')
  1791. };
  1792. u2fErrors[errorType].removeClass('hide');
  1793. Object.keys(u2fErrors).forEach((type) => {
  1794. if (type !== errorType) {
  1795. u2fErrors[type].addClass('hide');
  1796. }
  1797. });
  1798. $('#u2f-error').modal('show');
  1799. }
  1800. function initU2FRegister() {
  1801. $('#register-device').modal({ allowMultiple: false });
  1802. $('#u2f-error').modal({ allowMultiple: false });
  1803. $('#register-security-key').on('click', (e) => {
  1804. e.preventDefault();
  1805. u2fApi.ensureSupport()
  1806. .then(u2fRegisterRequest)
  1807. .catch(() => {
  1808. u2fError('browser');
  1809. });
  1810. });
  1811. }
  1812. function u2fRegisterRequest() {
  1813. $.post(`${suburl}/user/settings/security/u2f/request_register`, {
  1814. _csrf: csrf,
  1815. name: $('#nickname').val()
  1816. }).success((req) => {
  1817. $('#nickname').closest('div.field').removeClass('error');
  1818. $('#register-device').modal('show');
  1819. if (req.registeredKeys === null) {
  1820. req.registeredKeys = [];
  1821. }
  1822. u2fApi.register(req.appId, req.registerRequests, req.registeredKeys, 30)
  1823. .then(u2fRegistered)
  1824. .catch((reason) => {
  1825. if (reason === undefined) {
  1826. u2fError(1);
  1827. return;
  1828. }
  1829. u2fError(reason.metaData.code);
  1830. });
  1831. }).fail((xhr) => {
  1832. if (xhr.status === 409) {
  1833. $('#nickname').closest('div.field').addClass('error');
  1834. }
  1835. });
  1836. }
  1837. function initWipTitle() {
  1838. $('.title_wip_desc > a').click((e) => {
  1839. e.preventDefault();
  1840. const $issueTitle = $('#issue_title');
  1841. $issueTitle.focus();
  1842. const value = $issueTitle.val().trim().toUpperCase();
  1843. for (const i in wipPrefixes) {
  1844. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  1845. return;
  1846. }
  1847. }
  1848. $issueTitle.val(`${wipPrefixes[0]} ${$issueTitle.val()}`);
  1849. });
  1850. }
  1851. function initTemplateSearch() {
  1852. const $repoTemplate = $('#repo_template');
  1853. const checkTemplate = function () {
  1854. const $templateUnits = $('#template_units');
  1855. const $nonTemplate = $('#non_template');
  1856. if ($repoTemplate.val() !== '') {
  1857. $templateUnits.show();
  1858. $nonTemplate.hide();
  1859. } else {
  1860. $templateUnits.hide();
  1861. $nonTemplate.show();
  1862. }
  1863. };
  1864. $repoTemplate.change(checkTemplate);
  1865. checkTemplate();
  1866. const changeOwner = function () {
  1867. $('#repo_template_search')
  1868. .dropdown({
  1869. apiSettings: {
  1870. url: `${suburl}/api/v1/repos/search?q={query}&template=true&priority_owner_id=${$('#uid').val()}`,
  1871. onResponse(response) {
  1872. const filteredResponse = { success: true, results: [] };
  1873. filteredResponse.results.push({
  1874. name: '',
  1875. value: ''
  1876. });
  1877. // Parse the response from the api to work with our dropdown
  1878. $.each(response.data, (_r, repo) => {
  1879. filteredResponse.results.push({
  1880. name: htmlEncode(repo.full_name),
  1881. value: repo.id
  1882. });
  1883. });
  1884. return filteredResponse;
  1885. },
  1886. cache: false,
  1887. },
  1888. fullTextSearch: true
  1889. });
  1890. };
  1891. $('#uid').change(changeOwner);
  1892. changeOwner();
  1893. }
  1894. $(document).ready(() => {
  1895. csrf = $('meta[name=_csrf]').attr('content');
  1896. suburl = $('meta[name=_suburl]').attr('content');
  1897. // Show exact time
  1898. $('.time-since').each(function () {
  1899. $(this)
  1900. .addClass('poping up')
  1901. .attr('data-content', $(this).attr('title'))
  1902. .attr('data-variation', 'inverted tiny')
  1903. .attr('title', '');
  1904. });
  1905. // Semantic UI modules.
  1906. $('.dropdown:not(.custom)').dropdown();
  1907. $('.jump.dropdown').dropdown({
  1908. action: 'hide',
  1909. onShow() {
  1910. $('.poping.up').popup('hide');
  1911. }
  1912. });
  1913. $('.slide.up.dropdown').dropdown({
  1914. transition: 'slide up'
  1915. });
  1916. $('.upward.dropdown').dropdown({
  1917. direction: 'upward'
  1918. });
  1919. $('.ui.accordion').accordion();
  1920. $('.ui.checkbox').checkbox();
  1921. $('.ui.progress').progress({
  1922. showActivity: false
  1923. });
  1924. $('.poping.up').popup();
  1925. $('.top.menu .poping.up').popup({
  1926. onShow() {
  1927. if ($('.top.menu .menu.transition').hasClass('visible')) {
  1928. return false;
  1929. }
  1930. }
  1931. });
  1932. $('.tabular.menu .item').tab();
  1933. $('.tabable.menu .item').tab();
  1934. $('.toggle.button').click(function () {
  1935. $($(this).data('target')).slideToggle(100);
  1936. });
  1937. // make table <tr> element clickable like a link
  1938. $('tr[data-href]').click(function () {
  1939. window.location = $(this).data('href');
  1940. });
  1941. // Highlight JS
  1942. if (typeof hljs !== 'undefined') {
  1943. const nodes = [].slice.call(document.querySelectorAll('pre code') || []);
  1944. for (let i = 0; i < nodes.length; i++) {
  1945. hljs.highlightBlock(nodes[i]);
  1946. }
  1947. }
  1948. // Dropzone
  1949. const $dropzone = $('#dropzone');
  1950. if ($dropzone.length > 0) {
  1951. const filenameDict = {};
  1952. new Dropzone('#dropzone', {
  1953. url: $dropzone.data('upload-url'),
  1954. headers: { 'X-Csrf-Token': csrf },
  1955. maxFiles: $dropzone.data('max-file'),
  1956. maxFilesize: $dropzone.data('max-size'),
  1957. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  1958. addRemoveLinks: true,
  1959. dictDefaultMessage: $dropzone.data('default-message'),
  1960. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  1961. dictFileTooBig: $dropzone.data('file-too-big'),
  1962. dictRemoveFile: $dropzone.data('remove-file'),
  1963. init() {
  1964. this.on('success', (file, data) => {
  1965. filenameDict[file.name] = data.uuid;
  1966. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  1967. $('.files').append(input);
  1968. });
  1969. this.on('removedfile', (file) => {
  1970. if (file.name in filenameDict) {
  1971. $(`#${filenameDict[file.name]}`).remove();
  1972. }
  1973. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  1974. $.post($dropzone.data('remove-url'), {
  1975. file: filenameDict[file.name],
  1976. _csrf: $dropzone.data('csrf')
  1977. });
  1978. }
  1979. });
  1980. },
  1981. });
  1982. }
  1983. // Emojify
  1984. emojify.setConfig({
  1985. img_dir: `${suburl}/vendor/plugins/emojify/images`,
  1986. ignore_emoticons: true
  1987. });
  1988. const hasEmoji = document.getElementsByClassName('has-emoji');
  1989. for (let i = 0; i < hasEmoji.length; i++) {
  1990. emojify.run(hasEmoji[i]);
  1991. for (let j = 0; j < hasEmoji[i].childNodes.length; j++) {
  1992. if (hasEmoji[i].childNodes[j].nodeName === 'A') {
  1993. emojify.run(hasEmoji[i].childNodes[j]);
  1994. }
  1995. }
  1996. }
  1997. // Clipboard JS
  1998. const clipboard = new Clipboard('.clipboard');
  1999. clipboard.on('success', (e) => {
  2000. e.clearSelection();
  2001. $(`#${e.trigger.getAttribute('id')}`).popup('destroy');
  2002. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'));
  2003. $(`#${e.trigger.getAttribute('id')}`).popup('show');
  2004. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'));
  2005. });
  2006. clipboard.on('error', (e) => {
  2007. $(`#${e.trigger.getAttribute('id')}`).popup('destroy');
  2008. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'));
  2009. $(`#${e.trigger.getAttribute('id')}`).popup('show');
  2010. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'));
  2011. });
  2012. // Helpers.
  2013. $('.delete-button').click(showDeletePopup);
  2014. $('.add-all-button').click(showAddAllPopup);
  2015. $('.delete-branch-button').click(showDeletePopup);
  2016. $('.undo-button').click(function () {
  2017. const $this = $(this);
  2018. $.post($this.data('url'), {
  2019. _csrf: csrf,
  2020. id: $this.data('id')
  2021. }).done((data) => {
  2022. window.location.href = data.redirect;
  2023. });
  2024. });
  2025. $('.show-panel.button').click(function () {
  2026. $($(this).data('panel')).show();
  2027. });
  2028. $('.show-modal.button').click(function () {
  2029. $($(this).data('modal')).modal('show');
  2030. });
  2031. $('.delete-post.button').click(function () {
  2032. const $this = $(this);
  2033. $.post($this.data('request-url'), {
  2034. _csrf: csrf
  2035. }).done(() => {
  2036. window.location.href = $this.data('done-url');
  2037. });
  2038. });
  2039. // Set anchor.
  2040. $('.markdown').each(function () {
  2041. const headers = {};
  2042. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  2043. let node = $(this);
  2044. const val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  2045. let name = val;
  2046. if (headers[val] > 0) {
  2047. name = `${val}-${headers[val]}`;
  2048. }
  2049. if (headers[val] === undefined) {
  2050. headers[val] = 1;
  2051. } else {
  2052. headers[val] += 1;
  2053. }
  2054. node = node.wrap(`<div id="${name}" class="anchor-wrap" ></div>`);
  2055. node.append(`<a class="anchor" href="#${name}"><span class="octicon octicon-link"></span></a>`);
  2056. });
  2057. });
  2058. $('.issue-checkbox').click(() => {
  2059. const numChecked = $('.issue-checkbox').children('input:checked').length;
  2060. if (numChecked > 0) {
  2061. $('#issue-filters').addClass('hide');
  2062. $('#issue-actions').removeClass('hide');
  2063. } else {
  2064. $('#issue-filters').removeClass('hide');
  2065. $('#issue-actions').addClass('hide');
  2066. }
  2067. });
  2068. $('.issue-action').click(function () {
  2069. let { action } = this.dataset;
  2070. let { elementId } = this.dataset;
  2071. const issueIDs = $('.issue-checkbox').children('input:checked').map(function () {
  2072. return this.dataset.issueId;
  2073. }).get().join();
  2074. const { url } = this.dataset;
  2075. if (elementId === '0' && url.substr(-9) === '/assignee') {
  2076. elementId = '';
  2077. action = 'clear';
  2078. }
  2079. updateIssuesMeta(url, action, issueIDs, elementId).then(() => {
  2080. // NOTICE: This reset of checkbox state targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2081. if (action === 'close' || action === 'open') {
  2082. // uncheck all checkboxes
  2083. $('.issue-checkbox input[type="checkbox"]').each((_, e) => { e.checked = false; });
  2084. }
  2085. reload();
  2086. });
  2087. });
  2088. // NOTICE: This event trigger targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2089. // trigger ckecked event, if checkboxes are checked on load
  2090. $('.issue-checkbox input[type="checkbox"]:checked').first().each((_, e) => {
  2091. e.checked = false;
  2092. $(e).click();
  2093. });
  2094. buttonsClickOnEnter();
  2095. searchUsers();
  2096. searchTeams();
  2097. searchRepositories();
  2098. initCommentForm();
  2099. initInstall();
  2100. initRepository();
  2101. initMigration();
  2102. initWikiForm();
  2103. initEditForm();
  2104. initEditor();
  2105. initOrganization();
  2106. initWebhook();
  2107. initAdmin();
  2108. initCodeView();
  2109. initVueApp();
  2110. initTeamSettings();
  2111. initCtrlEnterSubmit();
  2112. initNavbarContentToggle();
  2113. initTopicbar();
  2114. initU2FAuth();
  2115. initU2FRegister();
  2116. initIssueList();
  2117. initWipTitle();
  2118. initPullRequestReview();
  2119. initRepoStatusChecker();
  2120. initTemplateSearch();
  2121. // Repo clone url.
  2122. if ($('#repo-clone-url').length > 0) {
  2123. switch (localStorage.getItem('repo-clone-protocol')) {
  2124. case 'ssh':
  2125. if ($('#repo-clone-ssh').click().length === 0) {
  2126. $('#repo-clone-https').click();
  2127. }
  2128. break;
  2129. default:
  2130. $('#repo-clone-https').click();
  2131. break;
  2132. }
  2133. }
  2134. const routes = {
  2135. 'div.user.settings': initUserSettings,
  2136. 'div.repository.settings.collaboration': initRepositoryCollaboration
  2137. };
  2138. let selector;
  2139. for (selector in routes) {
  2140. if ($(selector).length > 0) {
  2141. routes[selector]();
  2142. break;
  2143. }
  2144. }
  2145. const $cloneAddr = $('#clone_addr');
  2146. $cloneAddr.change(() => {
  2147. const $repoName = $('#repo_name');
  2148. if ($cloneAddr.val().length > 0 && $repoName.val().length === 0) { // Only modify if repo_name input is blank
  2149. $repoName.val($cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]);
  2150. }
  2151. });
  2152. });
  2153. function changeHash(hash) {
  2154. if (window.history.pushState) {
  2155. window.history.pushState(null, null, hash);
  2156. } else {
  2157. window.location.hash = hash;
  2158. }
  2159. }
  2160. function deSelect() {
  2161. if (window.getSelection) {
  2162. window.getSelection().removeAllRanges();
  2163. } else {
  2164. document.selection.empty();
  2165. }
  2166. }
  2167. function selectRange($list, $select, $from) {
  2168. $list.removeClass('active');
  2169. if ($from) {
  2170. let a = parseInt($select.attr('rel').substr(1));
  2171. let b = parseInt($from.attr('rel').substr(1));
  2172. let c;
  2173. if (a !== b) {
  2174. if (a > b) {
  2175. c = a;
  2176. a = b;
  2177. b = c;
  2178. }
  2179. const classes = [];
  2180. for (let i = a; i <= b; i++) {
  2181. classes.push(`.L${i}`);
  2182. }
  2183. $list.filter(classes.join(',')).addClass('active');
  2184. changeHash(`#L${a}-L${b}`);
  2185. return;
  2186. }
  2187. }
  2188. $select.addClass('active');
  2189. changeHash(`#${$select.attr('rel')}`);
  2190. }
  2191. $(() => {
  2192. // Warn users that try to leave a page after entering data into a form.
  2193. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  2194. if ($('.user.signin').length === 0) {
  2195. $('form:not(.ignore-dirty)').areYouSure();
  2196. }
  2197. // Parse SSH Key
  2198. $('#ssh-key-content').on('change paste keyup', function () {
  2199. const arrays = $(this).val().split(' ');
  2200. const $title = $('#ssh-key-title');
  2201. if ($title.val() === '' && arrays.length === 3 && arrays[2] !== '') {
  2202. $title.val(arrays[2]);
  2203. }
  2204. });
  2205. });
  2206. function showDeletePopup() {
  2207. const $this = $(this);
  2208. let filter = '';
  2209. if ($this.attr('id')) {
  2210. filter += `#${$this.attr('id')}`;
  2211. }
  2212. const dialog = $(`.delete.modal${filter}`);
  2213. dialog.find('.name').text($this.data('name'));
  2214. dialog.modal({
  2215. closable: false,
  2216. onApprove() {
  2217. if ($this.data('type') === 'form') {
  2218. $($this.data('form')).submit();
  2219. return;
  2220. }
  2221. $.post($this.data('url'), {
  2222. _csrf: csrf,
  2223. id: $this.data('id')
  2224. }).done((data) => {
  2225. window.location.href = data.redirect;
  2226. });
  2227. }
  2228. }).modal('show');
  2229. return false;
  2230. }
  2231. function showAddAllPopup() {
  2232. const $this = $(this);
  2233. let filter = '';
  2234. if ($this.attr('id')) {
  2235. filter += `#${$this.attr('id')}`;
  2236. }
  2237. const dialog = $(`.addall.modal${filter}`);
  2238. dialog.find('.name').text($this.data('name'));
  2239. dialog.modal({
  2240. closable: false,
  2241. onApprove() {
  2242. if ($this.data('type') === 'form') {
  2243. $($this.data('form')).submit();
  2244. return;
  2245. }
  2246. $.post($this.data('url'), {
  2247. _csrf: csrf,
  2248. id: $this.data('id')
  2249. }).done((data) => {
  2250. window.location.href = data.redirect;
  2251. });
  2252. }
  2253. }).modal('show');
  2254. return false;
  2255. }
  2256. function initVueComponents() {
  2257. const vueDelimeters = ['${', '}'];
  2258. Vue.component('repo-search', {
  2259. delimiters: vueDelimeters,
  2260. props: {
  2261. searchLimit: {
  2262. type: Number,
  2263. default: 10
  2264. },
  2265. suburl: {
  2266. type: String,
  2267. required: true
  2268. },
  2269. uid: {
  2270. type: Number,
  2271. required: true
  2272. },
  2273. organizations: {
  2274. type: Array,
  2275. default: []
  2276. },
  2277. isOrganization: {
  2278. type: Boolean,
  2279. default: true
  2280. },
  2281. canCreateOrganization: {
  2282. type: Boolean,
  2283. default: false
  2284. },
  2285. organizationsTotalCount: {
  2286. type: Number,
  2287. default: 0
  2288. },
  2289. moreReposLink: {
  2290. type: String,
  2291. default: ''
  2292. }
  2293. },
  2294. data() {
  2295. return {
  2296. tab: 'repos',
  2297. repos: [],
  2298. reposTotalCount: 0,
  2299. reposFilter: 'all',
  2300. searchQuery: '',
  2301. isLoading: false,
  2302. repoTypes: {
  2303. all: {
  2304. count: 0,
  2305. searchMode: '',
  2306. },
  2307. forks: {
  2308. count: 0,
  2309. searchMode: 'fork',
  2310. },
  2311. mirrors: {
  2312. count: 0,
  2313. searchMode: 'mirror',
  2314. },
  2315. sources: {
  2316. count: 0,
  2317. searchMode: 'source',
  2318. },
  2319. collaborative: {
  2320. count: 0,
  2321. searchMode: 'collaborative',
  2322. },
  2323. }
  2324. };
  2325. },
  2326. computed: {
  2327. showMoreReposLink() {
  2328. return this.repos.length > 0 && this.repos.length < this.repoTypes[this.reposFilter].count;
  2329. },
  2330. searchURL() {
  2331. return `${this.suburl}/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&q=${this.searchQuery
  2332. }&limit=${this.searchLimit}&mode=${this.repoTypes[this.reposFilter].searchMode
  2333. }${this.reposFilter !== 'all' ? '&exclusive=1' : ''}`;
  2334. },
  2335. repoTypeCount() {
  2336. return this.repoTypes[this.reposFilter].count;
  2337. }
  2338. },
  2339. mounted() {
  2340. this.searchRepos(this.reposFilter);
  2341. const self = this;
  2342. Vue.nextTick(() => {
  2343. self.$refs.search.focus();
  2344. });
  2345. },
  2346. methods: {
  2347. changeTab(t) {
  2348. this.tab = t;
  2349. },
  2350. changeReposFilter(filter) {
  2351. this.reposFilter = filter;
  2352. this.repos = [];
  2353. this.repoTypes[filter].count = 0;
  2354. this.searchRepos(filter);
  2355. },
  2356. showRepo(repo, filter) {
  2357. switch (filter) {
  2358. case 'sources':
  2359. return repo.owner.id === this.uid && !repo.mirror && !repo.fork;
  2360. case 'forks':
  2361. return repo.owner.id === this.uid && !repo.mirror && repo.fork;
  2362. case 'mirrors':
  2363. return repo.mirror;
  2364. case 'collaborative':
  2365. return repo.owner.id !== this.uid && !repo.mirror;
  2366. default:
  2367. return true;
  2368. }
  2369. },
  2370. searchRepos(reposFilter) {
  2371. const self = this;
  2372. this.isLoading = true;
  2373. const searchedMode = this.repoTypes[reposFilter].searchMode;
  2374. const searchedURL = this.searchURL;
  2375. const searchedQuery = this.searchQuery;
  2376. $.getJSON(searchedURL, (result, _textStatus, request) => {
  2377. if (searchedURL === self.searchURL) {
  2378. self.repos = result.data;
  2379. const count = request.getResponseHeader('X-Total-Count');
  2380. if (searchedQuery === '' && searchedMode === '') {
  2381. self.reposTotalCount = count;
  2382. }
  2383. self.repoTypes[reposFilter].count = count;
  2384. }
  2385. }).always(() => {
  2386. if (searchedURL === self.searchURL) {
  2387. self.isLoading = false;
  2388. }
  2389. });
  2390. },
  2391. repoClass(repo) {
  2392. if (repo.fork) {
  2393. return 'octicon octicon-repo-forked';
  2394. } if (repo.mirror) {
  2395. return 'octicon octicon-repo-clone';
  2396. } if (repo.private) {
  2397. return 'octicon octicon-lock';
  2398. }
  2399. return 'octicon octicon-repo';
  2400. }
  2401. }
  2402. });
  2403. }
  2404. function initCtrlEnterSubmit() {
  2405. $('.js-quick-submit').keydown(function (e) {
  2406. if (((e.ctrlKey && !e.altKey) || e.metaKey) && (e.keyCode === 13 || e.keyCode === 10)) {
  2407. $(this).closest('form').submit();
  2408. }
  2409. });
  2410. }
  2411. function initVueApp() {
  2412. const el = document.getElementById('app');
  2413. if (!el) {
  2414. return;
  2415. }
  2416. initVueComponents();
  2417. new Vue({
  2418. delimiters: ['${', '}'],
  2419. el,
  2420. data: {
  2421. searchLimit: document.querySelector('meta[name=_search_limit]').content,
  2422. suburl: document.querySelector('meta[name=_suburl]').content,
  2423. uid: document.querySelector('meta[name=_context_uid]').content,
  2424. },
  2425. });
  2426. }
  2427. window.timeAddManual = function () {
  2428. $('.mini.modal')
  2429. .modal({
  2430. duration: 200,
  2431. onApprove() {
  2432. $('#add_time_manual_form').submit();
  2433. }
  2434. }).modal('show');
  2435. };
  2436. window.toggleStopwatch = function () {
  2437. $('#toggle_stopwatch_form').submit();
  2438. };
  2439. window.cancelStopwatch = function () {
  2440. $('#cancel_stopwatch_form').submit();
  2441. };
  2442. window.initHeatmap = function (appElementId, heatmapUser, locale) {
  2443. const el = document.getElementById(appElementId);
  2444. if (!el) {
  2445. return;
  2446. }
  2447. locale = locale || {};
  2448. locale.contributions = locale.contributions || 'contributions';
  2449. locale.no_contributions = locale.no_contributions || 'No contributions';
  2450. const vueDelimeters = ['${', '}'];
  2451. Vue.component('activity-heatmap', {
  2452. delimiters: vueDelimeters,
  2453. props: {
  2454. user: {
  2455. type: String,
  2456. required: true
  2457. },
  2458. suburl: {
  2459. type: String,
  2460. required: true
  2461. },
  2462. locale: {
  2463. type: Object,
  2464. required: true
  2465. }
  2466. },
  2467. data() {
  2468. return {
  2469. isLoading: true,
  2470. colorRange: [],
  2471. endDate: null,
  2472. values: [],
  2473. totalContributions: 0,
  2474. };
  2475. },
  2476. mounted() {
  2477. this.colorRange = [
  2478. this.getColor(0),
  2479. this.getColor(1),
  2480. this.getColor(2),
  2481. this.getColor(3),
  2482. this.getColor(4),
  2483. this.getColor(5)
  2484. ];
  2485. this.endDate = new Date();
  2486. this.loadHeatmap(this.user);
  2487. },
  2488. methods: {
  2489. loadHeatmap(userName) {
  2490. const self = this;
  2491. $.get(`${this.suburl}/api/v1/users/${userName}/heatmap`, (chartRawData) => {
  2492. const chartData = [];
  2493. for (let i = 0; i < chartRawData.length; i++) {
  2494. self.totalContributions += chartRawData[i].contributions;
  2495. chartData[i] = { date: new Date(chartRawData[i].timestamp * 1000), count: chartRawData[i].contributions };
  2496. }
  2497. self.values = chartData;
  2498. self.isLoading = false;
  2499. });
  2500. },
  2501. getColor(idx) {
  2502. const el = document.createElement('div');
  2503. el.className = `heatmap-color-${idx}`;
  2504. document.body.appendChild(el);
  2505. const color = getComputedStyle(el).backgroundColor;
  2506. document.body.removeChild(el);
  2507. return color;
  2508. }
  2509. },
  2510. 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" />'
  2511. });
  2512. new Vue({
  2513. delimiters: vueDelimeters,
  2514. el,
  2515. data: {
  2516. suburl: document.querySelector('meta[name=_suburl]').content,
  2517. heatmapUser,
  2518. locale
  2519. },
  2520. });
  2521. };
  2522. function initFilterBranchTagDropdown(selector) {
  2523. $(selector).each(function () {
  2524. const $dropdown = $(this);
  2525. const $data = $dropdown.find('.data');
  2526. const data = {
  2527. items: [],
  2528. mode: $data.data('mode'),
  2529. searchTerm: '',
  2530. noResults: '',
  2531. canCreateBranch: false,
  2532. menuVisible: false,
  2533. active: 0
  2534. };
  2535. $data.find('.item').each(function () {
  2536. data.items.push({
  2537. name: $(this).text(),
  2538. url: $(this).data('url'),
  2539. branch: $(this).hasClass('branch'),
  2540. tag: $(this).hasClass('tag'),
  2541. selected: $(this).hasClass('selected')
  2542. });
  2543. });
  2544. $data.remove();
  2545. new Vue({
  2546. delimiters: ['${', '}'],
  2547. el: this,
  2548. data,
  2549. beforeMount() {
  2550. const vm = this;
  2551. this.noResults = vm.$el.getAttribute('data-no-results');
  2552. this.canCreateBranch = vm.$el.getAttribute('data-can-create-branch') === 'true';
  2553. document.body.addEventListener('click', (event) => {
  2554. if (vm.$el.contains(event.target)) {
  2555. return;
  2556. }
  2557. if (vm.menuVisible) {
  2558. Vue.set(vm, 'menuVisible', false);
  2559. }
  2560. });
  2561. },
  2562. watch: {
  2563. menuVisible(visible) {
  2564. if (visible) {
  2565. this.focusSearchField();
  2566. }
  2567. }
  2568. },
  2569. computed: {
  2570. filteredItems() {
  2571. const vm = this;
  2572. const items = vm.items.filter((item) => {
  2573. return ((vm.mode === 'branches' && item.branch) || (vm.mode === 'tags' && item.tag))
  2574. && (!vm.searchTerm || item.name.toLowerCase().indexOf(vm.searchTerm.toLowerCase()) >= 0);
  2575. });
  2576. vm.active = (items.length === 0 && vm.showCreateNewBranch ? 0 : -1);
  2577. return items;
  2578. },
  2579. showNoResults() {
  2580. return this.filteredItems.length === 0 && !this.showCreateNewBranch;
  2581. },
  2582. showCreateNewBranch() {
  2583. const vm = this;
  2584. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') {
  2585. return false;
  2586. }
  2587. return vm.items.filter((item) => item.name.toLowerCase() === vm.searchTerm.toLowerCase()).length === 0;
  2588. }
  2589. },
  2590. methods: {
  2591. selectItem(item) {
  2592. const prev = this.getSelected();
  2593. if (prev !== null) {
  2594. prev.selected = false;
  2595. }
  2596. item.selected = true;
  2597. window.location.href = item.url;
  2598. },
  2599. createNewBranch() {
  2600. if (!this.showCreateNewBranch) {
  2601. return;
  2602. }
  2603. this.$refs.newBranchForm.submit();
  2604. },
  2605. focusSearchField() {
  2606. const vm = this;
  2607. Vue.nextTick(() => {
  2608. vm.$refs.searchField.focus();
  2609. });
  2610. },
  2611. getSelected() {
  2612. for (let i = 0, j = this.items.length; i < j; ++i) {
  2613. if (this.items[i].selected) return this.items[i];
  2614. }
  2615. return null;
  2616. },
  2617. getSelectedIndexInFiltered() {
  2618. for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
  2619. if (this.filteredItems[i].selected) return i;
  2620. }
  2621. return -1;
  2622. },
  2623. scrollToActive() {
  2624. let el = this.$refs[`listItem${this.active}`];
  2625. if (!el || el.length === 0) {
  2626. return;
  2627. }
  2628. if (Array.isArray(el)) {
  2629. el = el[0];
  2630. }
  2631. const cont = this.$refs.scrollContainer;
  2632. if (el.offsetTop < cont.scrollTop) {
  2633. cont.scrollTop = el.offsetTop;
  2634. } else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
  2635. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  2636. }
  2637. },
  2638. keydown(event) {
  2639. const vm = this;
  2640. if (event.keyCode === 40) {
  2641. // arrow down
  2642. event.preventDefault();
  2643. if (vm.active === -1) {
  2644. vm.active = vm.getSelectedIndexInFiltered();
  2645. }
  2646. if (vm.active + (vm.showCreateNewBranch ? 0 : 1) >= vm.filteredItems.length) {
  2647. return;
  2648. }
  2649. vm.active++;
  2650. vm.scrollToActive();
  2651. }
  2652. if (event.keyCode === 38) {
  2653. // arrow up
  2654. event.preventDefault();
  2655. if (vm.active === -1) {
  2656. vm.active = vm.getSelectedIndexInFiltered();
  2657. }
  2658. if (vm.active <= 0) {
  2659. return;
  2660. }
  2661. vm.active--;
  2662. vm.scrollToActive();
  2663. }
  2664. if (event.keyCode === 13) {
  2665. // enter
  2666. event.preventDefault();
  2667. if (vm.active >= vm.filteredItems.length) {
  2668. vm.createNewBranch();
  2669. } else if (vm.active >= 0) {
  2670. vm.selectItem(vm.filteredItems[vm.active]);
  2671. }
  2672. }
  2673. if (event.keyCode === 27) {
  2674. // escape
  2675. event.preventDefault();
  2676. vm.menuVisible = false;
  2677. }
  2678. }
  2679. }
  2680. });
  2681. });
  2682. }
  2683. $('.commit-button').click(function (e) {
  2684. e.preventDefault();
  2685. $(this).parent().find('.commit-body').toggle();
  2686. });
  2687. function initNavbarContentToggle() {
  2688. const content = $('#navbar');
  2689. const toggle = $('#navbar-expand-toggle');
  2690. let isExpanded = false;
  2691. toggle.click(() => {
  2692. isExpanded = !isExpanded;
  2693. if (isExpanded) {
  2694. content.addClass('shown');
  2695. toggle.addClass('active');
  2696. } else {
  2697. content.removeClass('shown');
  2698. toggle.removeClass('active');
  2699. }
  2700. });
  2701. }
  2702. function initTopicbar() {
  2703. const mgrBtn = $('#manage_topic');
  2704. const editDiv = $('#topic_edit');
  2705. const viewDiv = $('#repo-topics');
  2706. const saveBtn = $('#save_topic');
  2707. const topicDropdown = $('#topic_edit .dropdown');
  2708. const topicForm = $('#topic_edit.ui.form');
  2709. const topicPrompts = getPrompts();
  2710. mgrBtn.click(() => {
  2711. viewDiv.hide();
  2712. editDiv.css('display', ''); // show Semantic UI Grid
  2713. });
  2714. function getPrompts() {
  2715. const hidePrompt = $('div.hide#validate_prompt');
  2716. const prompts = {
  2717. countPrompt: hidePrompt.children('#count_prompt').text(),
  2718. formatPrompt: hidePrompt.children('#format_prompt').text()
  2719. };
  2720. hidePrompt.remove();
  2721. return prompts;
  2722. }
  2723. saveBtn.click(() => {
  2724. const topics = $('input[name=topics]').val();
  2725. $.post(saveBtn.data('link'), {
  2726. _csrf: csrf,
  2727. topics
  2728. }, (_data, _textStatus, xhr) => {
  2729. if (xhr.responseJSON.status === 'ok') {
  2730. viewDiv.children('.topic').remove();
  2731. if (topics.length) {
  2732. const topicArray = topics.split(',');
  2733. const last = viewDiv.children('a').last();
  2734. for (let i = 0; i < topicArray.length; i++) {
  2735. $(`<div class="ui small label topic" style="cursor:pointer;">${topicArray[i]}</div>`).insertBefore(last);
  2736. }
  2737. }
  2738. editDiv.css('display', 'none');
  2739. viewDiv.show();
  2740. }
  2741. }).fail((xhr) => {
  2742. if (xhr.status === 422) {
  2743. if (xhr.responseJSON.invalidTopics.length > 0) {
  2744. topicPrompts.formatPrompt = xhr.responseJSON.message;
  2745. const { invalidTopics } = xhr.responseJSON;
  2746. const topicLables = topicDropdown.children('a.ui.label');
  2747. topics.split(',').forEach((value, index) => {
  2748. for (let i = 0; i < invalidTopics.length; i++) {
  2749. if (invalidTopics[i] === value) {
  2750. topicLables.eq(index).removeClass('green').addClass('red');
  2751. }
  2752. }
  2753. });
  2754. } else {
  2755. topicPrompts.countPrompt = xhr.responseJSON.message;
  2756. }
  2757. }
  2758. }).always(() => {
  2759. topicForm.form('validate form');
  2760. });
  2761. });
  2762. topicDropdown.dropdown({
  2763. allowAdditions: true,
  2764. forceSelection: false,
  2765. fields: { name: 'description', value: 'data-value' },
  2766. saveRemoteData: false,
  2767. label: {
  2768. transition: 'horizontal flip',
  2769. duration: 200,
  2770. variation: false,
  2771. blue: true,
  2772. basic: true,
  2773. },
  2774. className: {
  2775. label: 'ui small label'
  2776. },
  2777. apiSettings: {
  2778. url: `${suburl}/api/v1/topics/search?q={query}`,
  2779. throttle: 500,
  2780. cache: false,
  2781. onResponse(res) {
  2782. const formattedResponse = {
  2783. success: false,
  2784. results: [],
  2785. };
  2786. const stripTags = function (text) {
  2787. return text.replace(/<[^>]*>?/gm, '');
  2788. };
  2789. const query = stripTags(this.urlData.query.trim());
  2790. let found_query = false;
  2791. const current_topics = [];
  2792. topicDropdown.find('div.label.visible.topic,a.label.visible').each((_, e) => { current_topics.push(e.dataset.value); });
  2793. if (res.topics) {
  2794. let found = false;
  2795. for (let i = 0; i < res.topics.length; i++) {
  2796. // skip currently added tags
  2797. if (current_topics.indexOf(res.topics[i].topic_name) !== -1) {
  2798. continue;
  2799. }
  2800. if (res.topics[i].topic_name.toLowerCase() === query.toLowerCase()) {
  2801. found_query = true;
  2802. }
  2803. formattedResponse.results.push({ description: res.topics[i].topic_name, 'data-value': res.topics[i].topic_name });
  2804. found = true;
  2805. }
  2806. formattedResponse.success = found;
  2807. }
  2808. if (query.length > 0 && !found_query) {
  2809. formattedResponse.success = true;
  2810. formattedResponse.results.unshift({ description: query, 'data-value': query });
  2811. } else if (query.length > 0 && found_query) {
  2812. formattedResponse.results.sort((a, b) => {
  2813. if (a.description.toLowerCase() === query.toLowerCase()) return -1;
  2814. if (b.description.toLowerCase() === query.toLowerCase()) return 1;
  2815. if (a.description > b.description) return -1;
  2816. if (a.description < b.description) return 1;
  2817. return 0;
  2818. });
  2819. }
  2820. return formattedResponse;
  2821. },
  2822. },
  2823. onLabelCreate(value) {
  2824. value = value.toLowerCase().trim();
  2825. this.attr('data-value', value).contents().first().replaceWith(value);
  2826. return $(this);
  2827. },
  2828. onAdd(addedValue, _addedText, $addedChoice) {
  2829. addedValue = addedValue.toLowerCase().trim();
  2830. $($addedChoice).attr('data-value', addedValue);
  2831. $($addedChoice).attr('data-text', addedValue);
  2832. }
  2833. });
  2834. $.fn.form.settings.rules.validateTopic = function (_values, regExp) {
  2835. const topics = topicDropdown.children('a.ui.label');
  2836. const status = topics.length === 0 || topics.last().attr('data-value').match(regExp);
  2837. if (!status) {
  2838. topics.last().removeClass('green').addClass('red');
  2839. }
  2840. return status && topicDropdown.children('a.ui.label.red').length === 0;
  2841. };
  2842. topicForm.form({
  2843. on: 'change',
  2844. inline: true,
  2845. fields: {
  2846. topics: {
  2847. identifier: 'topics',
  2848. rules: [
  2849. {
  2850. type: 'validateTopic',
  2851. value: /^[a-z0-9][a-z0-9-]{1,35}$/,
  2852. prompt: topicPrompts.formatPrompt
  2853. },
  2854. {
  2855. type: 'maxCount[25]',
  2856. prompt: topicPrompts.countPrompt
  2857. }
  2858. ]
  2859. },
  2860. }
  2861. });
  2862. }
  2863. window.toggleDeadlineForm = function () {
  2864. $('#deadlineForm').fadeToggle(150);
  2865. };
  2866. window.setDeadline = function () {
  2867. const deadline = $('#deadlineDate').val();
  2868. window.updateDeadline(deadline);
  2869. };
  2870. window.updateDeadline = function (deadlineString) {
  2871. $('#deadline-err-invalid-date').hide();
  2872. $('#deadline-loader').addClass('loading');
  2873. let realDeadline = null;
  2874. if (deadlineString !== '') {
  2875. const newDate = Date.parse(deadlineString);
  2876. if (Number.isNaN(newDate)) {
  2877. $('#deadline-loader').removeClass('loading');
  2878. $('#deadline-err-invalid-date').show();
  2879. return false;
  2880. }
  2881. realDeadline = new Date(newDate);
  2882. }
  2883. $.ajax(`${$('#update-issue-deadline-form').attr('action')}/deadline`, {
  2884. data: JSON.stringify({
  2885. due_date: realDeadline,
  2886. }),
  2887. headers: {
  2888. 'X-Csrf-Token': csrf,
  2889. 'X-Remote': true,
  2890. },
  2891. contentType: 'application/json',
  2892. type: 'POST',
  2893. success() {
  2894. reload();
  2895. },
  2896. error() {
  2897. $('#deadline-loader').removeClass('loading');
  2898. $('#deadline-err-invalid-date').show();
  2899. }
  2900. });
  2901. };
  2902. window.deleteDependencyModal = function (id, type) {
  2903. $('.remove-dependency')
  2904. .modal({
  2905. closable: false,
  2906. duration: 200,
  2907. onApprove() {
  2908. $('#removeDependencyID').val(id);
  2909. $('#dependencyType').val(type);
  2910. $('#removeDependencyForm').submit();
  2911. }
  2912. }).modal('show');
  2913. };
  2914. function initIssueList() {
  2915. const repolink = $('#repolink').val();
  2916. const repoId = $('#repoId').val();
  2917. const crossRepoSearch = $('#crossRepoSearch').val();
  2918. let issueSearchUrl = `${suburl}/api/v1/repos/${repolink}/issues?q={query}`;
  2919. if (crossRepoSearch === 'true') {
  2920. issueSearchUrl = `${suburl}/api/v1/repos/issues/search?q={query}&priority_repo_id=${repoId}`;
  2921. }
  2922. $('#new-dependency-drop-list')
  2923. .dropdown({
  2924. apiSettings: {
  2925. url: issueSearchUrl,
  2926. onResponse(response) {
  2927. const filteredResponse = { success: true, results: [] };
  2928. const currIssueId = $('#new-dependency-drop-list').data('issue-id');
  2929. // Parse the response from the api to work with our dropdown
  2930. $.each(response, (_i, issue) => {
  2931. // Don't list current issue in the dependency list.
  2932. if (issue.id === currIssueId) {
  2933. return;
  2934. }
  2935. filteredResponse.results.push({
  2936. name: `#${issue.number} ${htmlEncode(issue.title)
  2937. }<div class="text small dont-break-out">${htmlEncode(issue.repository.full_name)}</div>`,
  2938. value: issue.id
  2939. });
  2940. });
  2941. return filteredResponse;
  2942. },
  2943. cache: false,
  2944. },
  2945. fullTextSearch: true
  2946. });
  2947. $('.menu a.label-filter-item').each(function () {
  2948. $(this).click(function (e) {
  2949. if (e.altKey) {
  2950. e.preventDefault();
  2951. const href = $(this).attr('href');
  2952. const id = $(this).data('label-id');
  2953. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  2954. const newStr = 'labels=$1-$2$3&';
  2955. window.location = href.replace(new RegExp(regStr), newStr);
  2956. }
  2957. });
  2958. });
  2959. $('.menu .ui.dropdown.label-filter').keydown((e) => {
  2960. if (e.altKey && e.keyCode === 13) {
  2961. const selectedItems = $('.menu .ui.dropdown.label-filter .menu .item.selected');
  2962. if (selectedItems.length > 0) {
  2963. const item = $(selectedItems[0]);
  2964. const href = item.attr('href');
  2965. const id = item.data('label-id');
  2966. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  2967. const newStr = 'labels=$1-$2$3&';
  2968. window.location = href.replace(new RegExp(regStr), newStr);
  2969. }
  2970. }
  2971. });
  2972. }
  2973. window.cancelCodeComment = function (btn) {
  2974. const form = $(btn).closest('form');
  2975. if (form.length > 0 && form.hasClass('comment-form')) {
  2976. form.addClass('hide');
  2977. form.parent().find('button.comment-form-reply').show();
  2978. } else {
  2979. form.closest('.comment-code-cloud').remove();
  2980. }
  2981. };
  2982. window.onOAuthLoginClick = function () {
  2983. const oauthLoader = $('#oauth2-login-loader');
  2984. const oauthNav = $('#oauth2-login-navigator');
  2985. oauthNav.hide();
  2986. oauthLoader.removeClass('disabled');
  2987. setTimeout(() => {
  2988. // recover previous content to let user try again
  2989. // usually redirection will be performed before this action
  2990. oauthLoader.addClass('disabled');
  2991. oauthNav.show();
  2992. }, 5000);
  2993. };