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

index.js 102KB

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