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

repo-issue.js 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. import $ from 'jquery';
  2. import {htmlEscape} from 'escape-goat';
  3. import {showTemporaryTooltip, createTippy} from '../modules/tippy.js';
  4. import {hideElem, showElem, toggleElem} from '../utils/dom.js';
  5. import {setFileFolding} from './file-fold.js';
  6. import {getComboMarkdownEditor, initComboMarkdownEditor} from './comp/ComboMarkdownEditor.js';
  7. import {toAbsoluteUrl} from '../utils.js';
  8. import {initDropzone} from './common-global.js';
  9. import {POST, GET} from '../modules/fetch.js';
  10. const {appSubUrl} = window.config;
  11. export function initRepoIssueTimeTracking() {
  12. $(document).on('click', '.issue-add-time', () => {
  13. $('.issue-start-time-modal').modal({
  14. duration: 200,
  15. onApprove() {
  16. $('#add_time_manual_form').trigger('submit');
  17. },
  18. }).modal('show');
  19. $('.issue-start-time-modal input').on('keydown', (e) => {
  20. if ((e.keyCode || e.key) === 13) {
  21. $('#add_time_manual_form').trigger('submit');
  22. }
  23. });
  24. });
  25. $(document).on('click', '.issue-start-time, .issue-stop-time', () => {
  26. $('#toggle_stopwatch_form').trigger('submit');
  27. });
  28. $(document).on('click', '.issue-cancel-time', () => {
  29. $('#cancel_stopwatch_form').trigger('submit');
  30. });
  31. $(document).on('click', 'button.issue-delete-time', function () {
  32. const sel = `.issue-delete-time-modal[data-id="${$(this).data('id')}"]`;
  33. $(sel).modal({
  34. duration: 200,
  35. onApprove() {
  36. $(`${sel} form`).trigger('submit');
  37. },
  38. }).modal('show');
  39. });
  40. }
  41. async function updateDeadline(deadlineString) {
  42. hideElem('#deadline-err-invalid-date');
  43. document.getElementById('deadline-loader')?.classList.add('is-loading');
  44. let realDeadline = null;
  45. if (deadlineString !== '') {
  46. const newDate = Date.parse(deadlineString);
  47. if (Number.isNaN(newDate)) {
  48. document.getElementById('deadline-loader')?.classList.remove('is-loading');
  49. showElem('#deadline-err-invalid-date');
  50. return false;
  51. }
  52. realDeadline = new Date(newDate);
  53. }
  54. try {
  55. const response = await POST(document.getElementById('update-issue-deadline-form').getAttribute('action'), {
  56. data: {due_date: realDeadline},
  57. });
  58. if (response.ok) {
  59. window.location.reload();
  60. } else {
  61. throw new Error('Invalid response');
  62. }
  63. } catch (error) {
  64. console.error(error);
  65. document.getElementById('deadline-loader').classList.remove('is-loading');
  66. showElem('#deadline-err-invalid-date');
  67. }
  68. }
  69. export function initRepoIssueDue() {
  70. $(document).on('click', '.issue-due-edit', () => {
  71. toggleElem('#deadlineForm');
  72. });
  73. $(document).on('click', '.issue-due-remove', () => {
  74. updateDeadline('');
  75. });
  76. $(document).on('submit', '.issue-due-form', () => {
  77. updateDeadline($('#deadlineDate').val());
  78. return false;
  79. });
  80. }
  81. /**
  82. * @param {HTMLElement} item
  83. */
  84. function excludeLabel(item) {
  85. const href = item.getAttribute('href');
  86. const id = item.getAttribute('data-label-id');
  87. const regStr = `labels=((?:-?[0-9]+%2c)*)(${id})((?:%2c-?[0-9]+)*)&`;
  88. const newStr = 'labels=$1-$2$3&';
  89. window.location = href.replace(new RegExp(regStr), newStr);
  90. }
  91. export function initRepoIssueSidebarList() {
  92. const repolink = $('#repolink').val();
  93. const repoId = $('#repoId').val();
  94. const crossRepoSearch = $('#crossRepoSearch').val();
  95. const tp = $('#type').val();
  96. let issueSearchUrl = `${appSubUrl}/${repolink}/issues/search?q={query}&type=${tp}`;
  97. if (crossRepoSearch === 'true') {
  98. issueSearchUrl = `${appSubUrl}/issues/search?q={query}&priority_repo_id=${repoId}&type=${tp}`;
  99. }
  100. $('#new-dependency-drop-list')
  101. .dropdown({
  102. apiSettings: {
  103. url: issueSearchUrl,
  104. onResponse(response) {
  105. const filteredResponse = {success: true, results: []};
  106. const currIssueId = $('#new-dependency-drop-list').data('issue-id');
  107. // Parse the response from the api to work with our dropdown
  108. $.each(response, (_i, issue) => {
  109. // Don't list current issue in the dependency list.
  110. if (issue.id === currIssueId) {
  111. return;
  112. }
  113. filteredResponse.results.push({
  114. name: `#${issue.number} ${htmlEscape(issue.title)
  115. }<div class="text small gt-word-break">${htmlEscape(issue.repository.full_name)}</div>`,
  116. value: issue.id,
  117. });
  118. });
  119. return filteredResponse;
  120. },
  121. cache: false,
  122. },
  123. fullTextSearch: true,
  124. });
  125. $('.menu a.label-filter-item').each(function () {
  126. $(this).on('click', function (e) {
  127. if (e.altKey) {
  128. e.preventDefault();
  129. excludeLabel(this);
  130. }
  131. });
  132. });
  133. $('.menu .ui.dropdown.label-filter').on('keydown', (e) => {
  134. if (e.altKey && e.keyCode === 13) {
  135. const selectedItem = document.querySelector('.menu .ui.dropdown.label-filter .menu .item.selected');
  136. if (selectedItem) {
  137. excludeLabel(selectedItem);
  138. }
  139. }
  140. });
  141. $('.ui.dropdown.label-filter, .ui.dropdown.select-label').dropdown('setting', {'hideDividers': 'empty'}).dropdown('refreshItems');
  142. }
  143. export function initRepoIssueCommentDelete() {
  144. // Delete comment
  145. $(document).on('click', '.delete-comment', async function () {
  146. const $this = $(this);
  147. if (window.confirm($this.data('locale'))) {
  148. try {
  149. const response = await POST($this.data('url'));
  150. if (!response.ok) throw new Error('Failed to delete comment');
  151. const $conversationHolder = $this.closest('.conversation-holder');
  152. const $parentTimelineItem = $this.closest('.timeline-item');
  153. const $parentTimelineGroup = $this.closest('.timeline-item-group');
  154. // Check if this was a pending comment.
  155. if ($conversationHolder.find('.pending-label').length) {
  156. const counter = document.querySelector('#review-box .review-comments-counter');
  157. let num = parseInt(counter?.getAttribute('data-pending-comment-number')) - 1 || 0;
  158. num = Math.max(num, 0);
  159. counter.setAttribute('data-pending-comment-number', num);
  160. counter.textContent = String(num);
  161. }
  162. $(`#${$this.data('comment-id')}`).remove();
  163. if ($conversationHolder.length && !$conversationHolder.find('.comment').length) {
  164. const path = $conversationHolder.data('path');
  165. const side = $conversationHolder.data('side');
  166. const idx = $conversationHolder.data('idx');
  167. const lineType = $conversationHolder.closest('tr').data('line-type');
  168. if (lineType === 'same') {
  169. $(`[data-path="${path}"] .add-code-comment[data-idx="${idx}"]`).removeClass('tw-invisible');
  170. } else {
  171. $(`[data-path="${path}"] .add-code-comment[data-side="${side}"][data-idx="${idx}"]`).removeClass('tw-invisible');
  172. }
  173. $conversationHolder.remove();
  174. }
  175. // Check if there is no review content, move the time avatar upward to avoid overlapping the content below.
  176. if (!$parentTimelineGroup.find('.timeline-item.comment').length && !$parentTimelineItem.find('.conversation-holder').length) {
  177. const $timelineAvatar = $parentTimelineGroup.find('.timeline-avatar');
  178. $timelineAvatar.removeClass('timeline-avatar-offset');
  179. }
  180. } catch (error) {
  181. console.error(error);
  182. }
  183. }
  184. return false;
  185. });
  186. }
  187. export function initRepoIssueDependencyDelete() {
  188. // Delete Issue dependency
  189. $(document).on('click', '.delete-dependency-button', (e) => {
  190. const id = e.currentTarget.getAttribute('data-id');
  191. const type = e.currentTarget.getAttribute('data-type');
  192. $('.remove-dependency').modal({
  193. closable: false,
  194. duration: 200,
  195. onApprove: () => {
  196. $('#removeDependencyID').val(id);
  197. $('#dependencyType').val(type);
  198. $('#removeDependencyForm').trigger('submit');
  199. },
  200. }).modal('show');
  201. });
  202. }
  203. export function initRepoIssueCodeCommentCancel() {
  204. // Cancel inline code comment
  205. $(document).on('click', '.cancel-code-comment', (e) => {
  206. const $form = $(e.currentTarget).closest('form');
  207. if ($form.length > 0 && $form.hasClass('comment-form')) {
  208. $form.addClass('tw-hidden');
  209. showElem($form.closest('.comment-code-cloud').find('button.comment-form-reply'));
  210. } else {
  211. $form.closest('.comment-code-cloud').remove();
  212. }
  213. });
  214. }
  215. export function initRepoPullRequestUpdate() {
  216. // Pull Request update button
  217. const $pullUpdateButton = $('.update-button > button');
  218. $pullUpdateButton.on('click', async function (e) {
  219. e.preventDefault();
  220. const $this = $(this);
  221. const redirect = $this.data('redirect');
  222. $this.addClass('is-loading');
  223. let response;
  224. try {
  225. response = await POST($this.data('do'));
  226. } catch (error) {
  227. console.error(error);
  228. } finally {
  229. $this.removeClass('is-loading');
  230. }
  231. let data;
  232. try {
  233. data = await response?.json(); // the response is probably not a JSON
  234. } catch (error) {
  235. console.error(error);
  236. }
  237. if (data?.redirect) {
  238. window.location.href = data.redirect;
  239. } else if (redirect) {
  240. window.location.href = redirect;
  241. } else {
  242. window.location.reload();
  243. }
  244. });
  245. $('.update-button > .dropdown').dropdown({
  246. onChange(_text, _value, $choice) {
  247. const $url = $choice.data('do');
  248. if ($url) {
  249. $pullUpdateButton.find('.button-text').text($choice.text());
  250. $pullUpdateButton.data('do', $url);
  251. }
  252. },
  253. });
  254. }
  255. export function initRepoPullRequestMergeInstruction() {
  256. $('.show-instruction').on('click', () => {
  257. toggleElem($('.instruct-content'));
  258. });
  259. }
  260. export function initRepoPullRequestAllowMaintainerEdit() {
  261. const checkbox = document.getElementById('allow-edits-from-maintainers');
  262. if (!checkbox) return;
  263. const $checkbox = $(checkbox);
  264. const promptError = checkbox.getAttribute('data-prompt-error');
  265. $checkbox.checkbox({
  266. 'onChange': async () => {
  267. const checked = $checkbox.checkbox('is checked');
  268. let url = checkbox.getAttribute('data-url');
  269. url += '/set_allow_maintainer_edit';
  270. $checkbox.checkbox('set disabled');
  271. try {
  272. const response = await POST(url, {
  273. data: {allow_maintainer_edit: checked},
  274. });
  275. if (!response.ok) {
  276. throw new Error('Failed to update maintainer edit permission');
  277. }
  278. } catch (error) {
  279. console.error(error);
  280. showTemporaryTooltip(checkbox, promptError);
  281. } finally {
  282. $checkbox.checkbox('set enabled');
  283. }
  284. },
  285. });
  286. }
  287. export function initRepoIssueReferenceRepositorySearch() {
  288. $('.issue_reference_repository_search')
  289. .dropdown({
  290. apiSettings: {
  291. url: `${appSubUrl}/repo/search?q={query}&limit=20`,
  292. onResponse(response) {
  293. const filteredResponse = {success: true, results: []};
  294. $.each(response.data, (_r, repo) => {
  295. filteredResponse.results.push({
  296. name: htmlEscape(repo.repository.full_name),
  297. value: repo.repository.full_name,
  298. });
  299. });
  300. return filteredResponse;
  301. },
  302. cache: false,
  303. },
  304. onChange(_value, _text, $choice) {
  305. const $form = $choice.closest('form');
  306. if (!$form.length) return;
  307. $form[0].setAttribute('action', `${appSubUrl}/${_text}/issues/new`);
  308. },
  309. fullTextSearch: true,
  310. });
  311. }
  312. export function initRepoIssueWipTitle() {
  313. $('.title_wip_desc > a').on('click', (e) => {
  314. e.preventDefault();
  315. const $issueTitle = $('#issue_title');
  316. $issueTitle.trigger('focus');
  317. const value = $issueTitle.val().trim().toUpperCase();
  318. const wipPrefixes = $('.title_wip_desc').data('wip-prefixes');
  319. for (const prefix of wipPrefixes) {
  320. if (value.startsWith(prefix.toUpperCase())) {
  321. return;
  322. }
  323. }
  324. $issueTitle.val(`${wipPrefixes[0]} ${$issueTitle.val()}`);
  325. });
  326. }
  327. export async function updateIssuesMeta(url, action, issue_ids, id) {
  328. try {
  329. const response = await POST(url, {data: new URLSearchParams({action, issue_ids, id})});
  330. if (!response.ok) {
  331. throw new Error('Failed to update issues meta');
  332. }
  333. } catch (error) {
  334. console.error(error);
  335. }
  336. }
  337. export function initRepoIssueComments() {
  338. if (!$('.repository.view.issue .timeline').length) return;
  339. $('.re-request-review').on('click', async function (e) {
  340. e.preventDefault();
  341. const url = $(this).data('update-url');
  342. const issueId = $(this).data('issue-id');
  343. const id = $(this).data('id');
  344. const isChecked = $(this).hasClass('checked');
  345. await updateIssuesMeta(url, isChecked ? 'detach' : 'attach', issueId, id);
  346. window.location.reload();
  347. });
  348. document.addEventListener('click', (e) => {
  349. const urlTarget = document.querySelector(':target');
  350. if (!urlTarget) return;
  351. const urlTargetId = urlTarget.id;
  352. if (!urlTargetId) return;
  353. if (!/^(issue|pull)(comment)?-\d+$/.test(urlTargetId)) return;
  354. if (!e.target.closest(`#${urlTargetId}`)) {
  355. const scrollPosition = $(window).scrollTop();
  356. window.location.hash = '';
  357. $(window).scrollTop(scrollPosition);
  358. window.history.pushState(null, null, ' ');
  359. }
  360. });
  361. }
  362. export async function handleReply($el) {
  363. hideElem($el);
  364. const $form = $el.closest('.comment-code-cloud').find('.comment-form');
  365. $form.removeClass('tw-hidden');
  366. const $textarea = $form.find('textarea');
  367. let editor = getComboMarkdownEditor($textarea);
  368. if (!editor) {
  369. // FIXME: the initialization of the dropzone is not consistent.
  370. // When the page is loaded, the dropzone is initialized by initGlobalDropzone, but the editor is not initialized.
  371. // When the form is submitted and partially reload, none of them is initialized.
  372. const dropzone = $form.find('.dropzone')[0];
  373. if (!dropzone.dropzone) initDropzone(dropzone);
  374. editor = await initComboMarkdownEditor($form.find('.combo-markdown-editor'));
  375. }
  376. editor.focus();
  377. return editor;
  378. }
  379. export function initRepoPullRequestReview() {
  380. if (window.location.hash && window.location.hash.startsWith('#issuecomment-')) {
  381. // set scrollRestoration to 'manual' when there is a hash in url, so that the scroll position will not be remembered after refreshing
  382. if (window.history.scrollRestoration !== 'manual') {
  383. window.history.scrollRestoration = 'manual';
  384. }
  385. const commentDiv = document.querySelector(window.location.hash);
  386. if (commentDiv) {
  387. // get the name of the parent id
  388. const groupID = commentDiv.closest('div[id^="code-comments-"]')?.getAttribute('id');
  389. if (groupID && groupID.startsWith('code-comments-')) {
  390. const id = groupID.slice(14);
  391. const ancestorDiffBox = commentDiv.closest('.diff-file-box');
  392. // on pages like conversation, there is no diff header
  393. const diffHeader = ancestorDiffBox?.querySelector('.diff-file-header');
  394. // offset is for scrolling
  395. let offset = 30;
  396. if (diffHeader) {
  397. offset += $('.diff-detail-box').outerHeight() + $(diffHeader).outerHeight();
  398. }
  399. document.getElementById(`show-outdated-${id}`).classList.add('tw-hidden');
  400. document.getElementById(`code-comments-${id}`).classList.remove('tw-hidden');
  401. document.getElementById(`code-preview-${id}`).classList.remove('tw-hidden');
  402. document.getElementById(`hide-outdated-${id}`).classList.remove('tw-hidden');
  403. // if the comment box is folded, expand it
  404. if (ancestorDiffBox.getAttribute('data-folded') === 'true') {
  405. setFileFolding(ancestorDiffBox, ancestorDiffBox.querySelector('.fold-file'), false);
  406. }
  407. window.scrollTo({
  408. top: $(commentDiv).offset().top - offset,
  409. behavior: 'instant',
  410. });
  411. }
  412. }
  413. }
  414. $(document).on('click', '.show-outdated', function (e) {
  415. e.preventDefault();
  416. const id = $(this).data('comment');
  417. $(this).addClass('tw-hidden');
  418. $(`#code-comments-${id}`).removeClass('tw-hidden');
  419. $(`#code-preview-${id}`).removeClass('tw-hidden');
  420. $(`#hide-outdated-${id}`).removeClass('tw-hidden');
  421. });
  422. $(document).on('click', '.hide-outdated', function (e) {
  423. e.preventDefault();
  424. const id = $(this).data('comment');
  425. $(this).addClass('tw-hidden');
  426. $(`#code-comments-${id}`).addClass('tw-hidden');
  427. $(`#code-preview-${id}`).addClass('tw-hidden');
  428. $(`#show-outdated-${id}`).removeClass('tw-hidden');
  429. });
  430. $(document).on('click', 'button.comment-form-reply', async function (e) {
  431. e.preventDefault();
  432. await handleReply($(this));
  433. });
  434. const $reviewBox = $('.review-box-panel');
  435. if ($reviewBox.length === 1) {
  436. const _promise = initComboMarkdownEditor($reviewBox.find('.combo-markdown-editor'));
  437. }
  438. // The following part is only for diff views
  439. if (!$('.repository.pull.diff').length) return;
  440. const $reviewBtn = $('.js-btn-review');
  441. const $panel = $reviewBtn.parent().find('.review-box-panel');
  442. const $closeBtn = $panel.find('.close');
  443. if ($reviewBtn.length && $panel.length) {
  444. const tippy = createTippy($reviewBtn[0], {
  445. content: $panel[0],
  446. placement: 'bottom',
  447. trigger: 'click',
  448. maxWidth: 'none',
  449. interactive: true,
  450. hideOnClick: true,
  451. });
  452. $closeBtn.on('click', (e) => {
  453. e.preventDefault();
  454. tippy.hide();
  455. });
  456. }
  457. $(document).on('click', '.add-code-comment', async function (e) {
  458. if ($(e.target).hasClass('btn-add-single')) return; // https://github.com/go-gitea/gitea/issues/4745
  459. e.preventDefault();
  460. const isSplit = $(this).closest('.code-diff').hasClass('code-diff-split');
  461. const side = $(this).data('side');
  462. const idx = $(this).data('idx');
  463. const path = $(this).closest('[data-path]').data('path');
  464. const $tr = $(this).closest('tr');
  465. const lineType = $tr.data('line-type');
  466. let $ntr = $tr.next();
  467. if (!$ntr.hasClass('add-comment')) {
  468. $ntr = $(`
  469. <tr class="add-comment" data-line-type="${lineType}">
  470. ${isSplit ? `
  471. <td class="add-comment-left" colspan="4"></td>
  472. <td class="add-comment-right" colspan="4"></td>
  473. ` : `
  474. <td class="add-comment-left add-comment-right" colspan="5"></td>
  475. `}
  476. </tr>`);
  477. $tr.after($ntr);
  478. }
  479. const $td = $ntr.find(`.add-comment-${side}`);
  480. const $commentCloud = $td.find('.comment-code-cloud');
  481. if (!$commentCloud.length && !$ntr.find('button[name="pending_review"]').length) {
  482. try {
  483. const response = await GET(this.closest('[data-new-comment-url]')?.getAttribute('data-new-comment-url'));
  484. const html = await response.text();
  485. $td.html(html);
  486. $td.find("input[name='line']").val(idx);
  487. $td.find("input[name='side']").val(side === 'left' ? 'previous' : 'proposed');
  488. $td.find("input[name='path']").val(path);
  489. initDropzone($td.find('.dropzone')[0]);
  490. const editor = await initComboMarkdownEditor($td.find('.combo-markdown-editor'));
  491. editor.focus();
  492. } catch (error) {
  493. console.error(error);
  494. }
  495. }
  496. });
  497. }
  498. export function initRepoIssueReferenceIssue() {
  499. // Reference issue
  500. $(document).on('click', '.reference-issue', function (event) {
  501. const $this = $(this);
  502. const content = $(`#${$this.data('target')}`).text();
  503. const poster = $this.data('poster-username');
  504. const reference = toAbsoluteUrl($this.data('reference'));
  505. const $modal = $($this.data('modal'));
  506. $modal.find('textarea[name="content"]').val(`${content}\n\n_Originally posted by @${poster} in ${reference}_`);
  507. $modal.modal('show');
  508. event.preventDefault();
  509. });
  510. }
  511. export function initRepoIssueWipToggle() {
  512. // Toggle WIP
  513. $('.toggle-wip a, .toggle-wip button').on('click', async (e) => {
  514. e.preventDefault();
  515. const toggleWip = e.currentTarget.closest('.toggle-wip');
  516. const title = toggleWip.getAttribute('data-title');
  517. const wipPrefix = toggleWip.getAttribute('data-wip-prefix');
  518. const updateUrl = toggleWip.getAttribute('data-update-url');
  519. try {
  520. const params = new URLSearchParams();
  521. params.append('title', title?.startsWith(wipPrefix) ? title.slice(wipPrefix.length).trim() : `${wipPrefix.trim()} ${title}`);
  522. const response = await POST(updateUrl, {data: params});
  523. if (!response.ok) {
  524. throw new Error('Failed to toggle WIP status');
  525. }
  526. window.location.reload();
  527. } catch (error) {
  528. console.error(error);
  529. }
  530. });
  531. }
  532. async function pullrequest_targetbranch_change(update_url) {
  533. const targetBranch = $('#pull-target-branch').data('branch');
  534. const $branchTarget = $('#branch_target');
  535. if (targetBranch === $branchTarget.text()) {
  536. window.location.reload();
  537. return false;
  538. }
  539. try {
  540. await POST(update_url, {data: new URLSearchParams({target_branch: targetBranch})});
  541. } catch (error) {
  542. console.error(error);
  543. } finally {
  544. window.location.reload();
  545. }
  546. }
  547. export function initRepoIssueTitleEdit() {
  548. // Edit issue title
  549. const $issueTitle = $('#issue-title');
  550. const $editInput = $('#edit-title-input input');
  551. const editTitleToggle = function () {
  552. toggleElem($issueTitle);
  553. toggleElem($('.not-in-edit'));
  554. toggleElem($('#edit-title-input'));
  555. toggleElem($('#pull-desc'));
  556. toggleElem($('#pull-desc-edit'));
  557. toggleElem($('.in-edit'));
  558. toggleElem($('.new-issue-button'));
  559. $('#issue-title-wrapper').toggleClass('edit-active');
  560. $editInput[0].focus();
  561. $editInput[0].select();
  562. return false;
  563. };
  564. $('#edit-title').on('click', editTitleToggle);
  565. $('#cancel-edit-title').on('click', editTitleToggle);
  566. $('#save-edit-title').on('click', editTitleToggle).on('click', async function () {
  567. const pullrequest_target_update_url = this.getAttribute('data-target-update-url');
  568. if (!$editInput.val().length || $editInput.val() === $issueTitle.text()) {
  569. $editInput.val($issueTitle.text());
  570. await pullrequest_targetbranch_change(pullrequest_target_update_url);
  571. } else {
  572. try {
  573. const params = new URLSearchParams();
  574. params.append('title', $editInput.val());
  575. const response = await POST(this.getAttribute('data-update-url'), {data: params});
  576. const data = await response.json();
  577. $editInput.val(data.title);
  578. $issueTitle.text(data.title);
  579. if (pullrequest_target_update_url) {
  580. await pullrequest_targetbranch_change(pullrequest_target_update_url); // it will reload the window
  581. } else {
  582. window.location.reload();
  583. }
  584. } catch (error) {
  585. console.error(error);
  586. }
  587. }
  588. return false;
  589. });
  590. }
  591. export function initRepoIssueBranchSelect() {
  592. const changeBranchSelect = function () {
  593. const $selectionTextField = $('#pull-target-branch');
  594. const baseName = $selectionTextField.data('basename');
  595. const branchNameNew = $(this).data('branch');
  596. const branchNameOld = $selectionTextField.data('branch');
  597. // Replace branch name to keep translation from HTML template
  598. $selectionTextField.html($selectionTextField.html().replace(
  599. `${baseName}:${branchNameOld}`,
  600. `${baseName}:${branchNameNew}`,
  601. ));
  602. $selectionTextField.data('branch', branchNameNew); // update branch name in setting
  603. };
  604. $('#branch-select > .item').on('click', changeBranchSelect);
  605. }
  606. export function initSingleCommentEditor($commentForm) {
  607. // pages:
  608. // * normal new issue/pr page, no status-button
  609. // * issue/pr view page, with comment form, has status-button
  610. const opts = {};
  611. const statusButton = document.getElementById('status-button');
  612. if (statusButton) {
  613. opts.onContentChanged = (editor) => {
  614. const statusText = statusButton.getAttribute(editor.value().trim() ? 'data-status-and-comment' : 'data-status');
  615. statusButton.textContent = statusText;
  616. };
  617. }
  618. initComboMarkdownEditor($commentForm.find('.combo-markdown-editor'), opts);
  619. }
  620. export function initIssueTemplateCommentEditors($commentForm) {
  621. // pages:
  622. // * new issue with issue template
  623. const $comboFields = $commentForm.find('.combo-editor-dropzone');
  624. const initCombo = async ($combo) => {
  625. const $dropzoneContainer = $combo.find('.form-field-dropzone');
  626. const $formField = $combo.find('.form-field-real');
  627. const $markdownEditor = $combo.find('.combo-markdown-editor');
  628. const editor = await initComboMarkdownEditor($markdownEditor, {
  629. onContentChanged: (editor) => {
  630. $formField.val(editor.value());
  631. },
  632. });
  633. $formField.on('focus', async () => {
  634. // deactivate all markdown editors
  635. showElem($commentForm.find('.combo-editor-dropzone .form-field-real'));
  636. hideElem($commentForm.find('.combo-editor-dropzone .combo-markdown-editor'));
  637. hideElem($commentForm.find('.combo-editor-dropzone .form-field-dropzone'));
  638. // activate this markdown editor
  639. hideElem($formField);
  640. showElem($markdownEditor);
  641. showElem($dropzoneContainer);
  642. await editor.switchToUserPreference();
  643. editor.focus();
  644. });
  645. };
  646. for (const el of $comboFields) {
  647. initCombo($(el));
  648. }
  649. }
  650. // This function used to show and hide archived label on issue/pr
  651. // page in the sidebar where we select the labels
  652. // If we have any archived label tagged to issue and pr. We will show that
  653. // archived label with checked classed otherwise we will hide it
  654. // with the help of this function.
  655. // This function runs globally.
  656. export function initArchivedLabelHandler() {
  657. if (!document.querySelector('.archived-label-hint')) return;
  658. for (const label of document.querySelectorAll('[data-is-archived]')) {
  659. toggleElem(label, label.classList.contains('checked'));
  660. }
  661. }