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

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