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

index.js 101 kB

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