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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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 wrapper = document.getElementById('allow-edits-from-maintainers');
  262. if (!wrapper) return;
  263. wrapper.querySelector('input[type="checkbox"]')?.addEventListener('change', async (e) => {
  264. const checked = e.target.checked;
  265. const url = `${wrapper.getAttribute('data-url')}/set_allow_maintainer_edit`;
  266. wrapper.classList.add('is-loading');
  267. e.target.disabled = true;
  268. try {
  269. const response = await POST(url, {data: {allow_maintainer_edit: checked}});
  270. if (!response.ok) {
  271. throw new Error('Failed to update maintainer edit permission');
  272. }
  273. } catch (error) {
  274. console.error(error);
  275. showTemporaryTooltip(wrapper, wrapper.getAttribute('data-prompt-error'));
  276. } finally {
  277. wrapper.classList.remove('is-loading');
  278. e.target.disabled = false;
  279. }
  280. });
  281. }
  282. export function initRepoIssueReferenceRepositorySearch() {
  283. $('.issue_reference_repository_search')
  284. .dropdown({
  285. apiSettings: {
  286. url: `${appSubUrl}/repo/search?q={query}&limit=20`,
  287. onResponse(response) {
  288. const filteredResponse = {success: true, results: []};
  289. $.each(response.data, (_r, repo) => {
  290. filteredResponse.results.push({
  291. name: htmlEscape(repo.repository.full_name),
  292. value: repo.repository.full_name,
  293. });
  294. });
  295. return filteredResponse;
  296. },
  297. cache: false,
  298. },
  299. onChange(_value, _text, $choice) {
  300. const $form = $choice.closest('form');
  301. if (!$form.length) return;
  302. $form[0].setAttribute('action', `${appSubUrl}/${_text}/issues/new`);
  303. },
  304. fullTextSearch: true,
  305. });
  306. }
  307. export function initRepoIssueWipTitle() {
  308. $('.title_wip_desc > a').on('click', (e) => {
  309. e.preventDefault();
  310. const $issueTitle = $('#issue_title');
  311. $issueTitle.trigger('focus');
  312. const value = $issueTitle.val().trim().toUpperCase();
  313. const wipPrefixes = $('.title_wip_desc').data('wip-prefixes');
  314. for (const prefix of wipPrefixes) {
  315. if (value.startsWith(prefix.toUpperCase())) {
  316. return;
  317. }
  318. }
  319. $issueTitle.val(`${wipPrefixes[0]} ${$issueTitle.val()}`);
  320. });
  321. }
  322. export async function updateIssuesMeta(url, action, issue_ids, id) {
  323. try {
  324. const response = await POST(url, {data: new URLSearchParams({action, issue_ids, id})});
  325. if (!response.ok) {
  326. throw new Error('Failed to update issues meta');
  327. }
  328. } catch (error) {
  329. console.error(error);
  330. }
  331. }
  332. export function initRepoIssueComments() {
  333. if (!$('.repository.view.issue .timeline').length) return;
  334. $('.re-request-review').on('click', async function (e) {
  335. e.preventDefault();
  336. const url = $(this).data('update-url');
  337. const issueId = $(this).data('issue-id');
  338. const id = $(this).data('id');
  339. const isChecked = $(this).hasClass('checked');
  340. await updateIssuesMeta(url, isChecked ? 'detach' : 'attach', issueId, id);
  341. window.location.reload();
  342. });
  343. document.addEventListener('click', (e) => {
  344. const urlTarget = document.querySelector(':target');
  345. if (!urlTarget) return;
  346. const urlTargetId = urlTarget.id;
  347. if (!urlTargetId) return;
  348. if (!/^(issue|pull)(comment)?-\d+$/.test(urlTargetId)) return;
  349. if (!e.target.closest(`#${urlTargetId}`)) {
  350. const scrollPosition = $(window).scrollTop();
  351. window.location.hash = '';
  352. $(window).scrollTop(scrollPosition);
  353. window.history.pushState(null, null, ' ');
  354. }
  355. });
  356. }
  357. export async function handleReply($el) {
  358. hideElem($el);
  359. const $form = $el.closest('.comment-code-cloud').find('.comment-form');
  360. $form.removeClass('tw-hidden');
  361. const $textarea = $form.find('textarea');
  362. let editor = getComboMarkdownEditor($textarea);
  363. if (!editor) {
  364. // FIXME: the initialization of the dropzone is not consistent.
  365. // When the page is loaded, the dropzone is initialized by initGlobalDropzone, but the editor is not initialized.
  366. // When the form is submitted and partially reload, none of them is initialized.
  367. const dropzone = $form.find('.dropzone')[0];
  368. if (!dropzone.dropzone) initDropzone(dropzone);
  369. editor = await initComboMarkdownEditor($form.find('.combo-markdown-editor'));
  370. }
  371. editor.focus();
  372. return editor;
  373. }
  374. export function initRepoPullRequestReview() {
  375. if (window.location.hash && window.location.hash.startsWith('#issuecomment-')) {
  376. // set scrollRestoration to 'manual' when there is a hash in url, so that the scroll position will not be remembered after refreshing
  377. if (window.history.scrollRestoration !== 'manual') {
  378. window.history.scrollRestoration = 'manual';
  379. }
  380. const commentDiv = document.querySelector(window.location.hash);
  381. if (commentDiv) {
  382. // get the name of the parent id
  383. const groupID = commentDiv.closest('div[id^="code-comments-"]')?.getAttribute('id');
  384. if (groupID && groupID.startsWith('code-comments-')) {
  385. const id = groupID.slice(14);
  386. const ancestorDiffBox = commentDiv.closest('.diff-file-box');
  387. // on pages like conversation, there is no diff header
  388. const diffHeader = ancestorDiffBox?.querySelector('.diff-file-header');
  389. // offset is for scrolling
  390. let offset = 30;
  391. if (diffHeader) {
  392. offset += $('.diff-detail-box').outerHeight() + $(diffHeader).outerHeight();
  393. }
  394. document.getElementById(`show-outdated-${id}`).classList.add('tw-hidden');
  395. document.getElementById(`code-comments-${id}`).classList.remove('tw-hidden');
  396. document.getElementById(`code-preview-${id}`).classList.remove('tw-hidden');
  397. document.getElementById(`hide-outdated-${id}`).classList.remove('tw-hidden');
  398. // if the comment box is folded, expand it
  399. if (ancestorDiffBox.getAttribute('data-folded') === 'true') {
  400. setFileFolding(ancestorDiffBox, ancestorDiffBox.querySelector('.fold-file'), false);
  401. }
  402. window.scrollTo({
  403. top: $(commentDiv).offset().top - offset,
  404. behavior: 'instant',
  405. });
  406. }
  407. }
  408. }
  409. $(document).on('click', '.show-outdated', function (e) {
  410. e.preventDefault();
  411. const id = $(this).data('comment');
  412. $(this).addClass('tw-hidden');
  413. $(`#code-comments-${id}`).removeClass('tw-hidden');
  414. $(`#code-preview-${id}`).removeClass('tw-hidden');
  415. $(`#hide-outdated-${id}`).removeClass('tw-hidden');
  416. });
  417. $(document).on('click', '.hide-outdated', function (e) {
  418. e.preventDefault();
  419. const id = $(this).data('comment');
  420. $(this).addClass('tw-hidden');
  421. $(`#code-comments-${id}`).addClass('tw-hidden');
  422. $(`#code-preview-${id}`).addClass('tw-hidden');
  423. $(`#show-outdated-${id}`).removeClass('tw-hidden');
  424. });
  425. $(document).on('click', 'button.comment-form-reply', async function (e) {
  426. e.preventDefault();
  427. await handleReply($(this));
  428. });
  429. const $reviewBox = $('.review-box-panel');
  430. if ($reviewBox.length === 1) {
  431. const _promise = initComboMarkdownEditor($reviewBox.find('.combo-markdown-editor'));
  432. }
  433. // The following part is only for diff views
  434. if (!$('.repository.pull.diff').length) return;
  435. const $reviewBtn = $('.js-btn-review');
  436. const $panel = $reviewBtn.parent().find('.review-box-panel');
  437. const $closeBtn = $panel.find('.close');
  438. if ($reviewBtn.length && $panel.length) {
  439. const tippy = createTippy($reviewBtn[0], {
  440. content: $panel[0],
  441. placement: 'bottom',
  442. trigger: 'click',
  443. maxWidth: 'none',
  444. interactive: true,
  445. hideOnClick: true,
  446. });
  447. $closeBtn.on('click', (e) => {
  448. e.preventDefault();
  449. tippy.hide();
  450. });
  451. }
  452. $(document).on('click', '.add-code-comment', async function (e) {
  453. if ($(e.target).hasClass('btn-add-single')) return; // https://github.com/go-gitea/gitea/issues/4745
  454. e.preventDefault();
  455. const isSplit = $(this).closest('.code-diff').hasClass('code-diff-split');
  456. const side = $(this).data('side');
  457. const idx = $(this).data('idx');
  458. const path = $(this).closest('[data-path]').data('path');
  459. const $tr = $(this).closest('tr');
  460. const lineType = $tr.data('line-type');
  461. let $ntr = $tr.next();
  462. if (!$ntr.hasClass('add-comment')) {
  463. $ntr = $(`
  464. <tr class="add-comment" data-line-type="${lineType}">
  465. ${isSplit ? `
  466. <td class="add-comment-left" colspan="4"></td>
  467. <td class="add-comment-right" colspan="4"></td>
  468. ` : `
  469. <td class="add-comment-left add-comment-right" colspan="5"></td>
  470. `}
  471. </tr>`);
  472. $tr.after($ntr);
  473. }
  474. const $td = $ntr.find(`.add-comment-${side}`);
  475. const $commentCloud = $td.find('.comment-code-cloud');
  476. if (!$commentCloud.length && !$ntr.find('button[name="pending_review"]').length) {
  477. try {
  478. const response = await GET(this.closest('[data-new-comment-url]')?.getAttribute('data-new-comment-url'));
  479. const html = await response.text();
  480. $td.html(html);
  481. $td.find("input[name='line']").val(idx);
  482. $td.find("input[name='side']").val(side === 'left' ? 'previous' : 'proposed');
  483. $td.find("input[name='path']").val(path);
  484. initDropzone($td.find('.dropzone')[0]);
  485. const editor = await initComboMarkdownEditor($td.find('.combo-markdown-editor'));
  486. editor.focus();
  487. } catch (error) {
  488. console.error(error);
  489. }
  490. }
  491. });
  492. }
  493. export function initRepoIssueReferenceIssue() {
  494. // Reference issue
  495. $(document).on('click', '.reference-issue', function (event) {
  496. const $this = $(this);
  497. const content = $(`#${$this.data('target')}`).text();
  498. const poster = $this.data('poster-username');
  499. const reference = toAbsoluteUrl($this.data('reference'));
  500. const $modal = $($this.data('modal'));
  501. $modal.find('textarea[name="content"]').val(`${content}\n\n_Originally posted by @${poster} in ${reference}_`);
  502. $modal.modal('show');
  503. event.preventDefault();
  504. });
  505. }
  506. export function initRepoIssueWipToggle() {
  507. // Toggle WIP
  508. $('.toggle-wip a, .toggle-wip button').on('click', async (e) => {
  509. e.preventDefault();
  510. const toggleWip = e.currentTarget.closest('.toggle-wip');
  511. const title = toggleWip.getAttribute('data-title');
  512. const wipPrefix = toggleWip.getAttribute('data-wip-prefix');
  513. const updateUrl = toggleWip.getAttribute('data-update-url');
  514. try {
  515. const params = new URLSearchParams();
  516. params.append('title', title?.startsWith(wipPrefix) ? title.slice(wipPrefix.length).trim() : `${wipPrefix.trim()} ${title}`);
  517. const response = await POST(updateUrl, {data: params});
  518. if (!response.ok) {
  519. throw new Error('Failed to toggle WIP status');
  520. }
  521. window.location.reload();
  522. } catch (error) {
  523. console.error(error);
  524. }
  525. });
  526. }
  527. async function pullrequest_targetbranch_change(update_url) {
  528. const targetBranch = $('#pull-target-branch').data('branch');
  529. const $branchTarget = $('#branch_target');
  530. if (targetBranch === $branchTarget.text()) {
  531. window.location.reload();
  532. return false;
  533. }
  534. try {
  535. await POST(update_url, {data: new URLSearchParams({target_branch: targetBranch})});
  536. } catch (error) {
  537. console.error(error);
  538. } finally {
  539. window.location.reload();
  540. }
  541. }
  542. export function initRepoIssueTitleEdit() {
  543. // Edit issue title
  544. const $issueTitle = $('#issue-title');
  545. const $editInput = $('#edit-title-input input');
  546. const editTitleToggle = function () {
  547. toggleElem($issueTitle);
  548. toggleElem($('.not-in-edit'));
  549. toggleElem($('#edit-title-input'));
  550. toggleElem($('#pull-desc'));
  551. toggleElem($('#pull-desc-edit'));
  552. toggleElem($('.in-edit'));
  553. toggleElem($('.new-issue-button'));
  554. $('#issue-title-wrapper').toggleClass('edit-active');
  555. $editInput[0].focus();
  556. $editInput[0].select();
  557. return false;
  558. };
  559. $('#edit-title').on('click', editTitleToggle);
  560. $('#cancel-edit-title').on('click', editTitleToggle);
  561. $('#save-edit-title').on('click', editTitleToggle).on('click', async function () {
  562. const pullrequest_target_update_url = this.getAttribute('data-target-update-url');
  563. if (!$editInput.val().length || $editInput.val() === $issueTitle.text()) {
  564. $editInput.val($issueTitle.text());
  565. await pullrequest_targetbranch_change(pullrequest_target_update_url);
  566. } else {
  567. try {
  568. const params = new URLSearchParams();
  569. params.append('title', $editInput.val());
  570. const response = await POST(this.getAttribute('data-update-url'), {data: params});
  571. const data = await response.json();
  572. $editInput.val(data.title);
  573. $issueTitle.text(data.title);
  574. if (pullrequest_target_update_url) {
  575. await pullrequest_targetbranch_change(pullrequest_target_update_url); // it will reload the window
  576. } else {
  577. window.location.reload();
  578. }
  579. } catch (error) {
  580. console.error(error);
  581. }
  582. }
  583. return false;
  584. });
  585. }
  586. export function initRepoIssueBranchSelect() {
  587. const changeBranchSelect = function () {
  588. const $selectionTextField = $('#pull-target-branch');
  589. const baseName = $selectionTextField.data('basename');
  590. const branchNameNew = $(this).data('branch');
  591. const branchNameOld = $selectionTextField.data('branch');
  592. // Replace branch name to keep translation from HTML template
  593. $selectionTextField.html($selectionTextField.html().replace(
  594. `${baseName}:${branchNameOld}`,
  595. `${baseName}:${branchNameNew}`,
  596. ));
  597. $selectionTextField.data('branch', branchNameNew); // update branch name in setting
  598. };
  599. $('#branch-select > .item').on('click', changeBranchSelect);
  600. }
  601. export function initSingleCommentEditor($commentForm) {
  602. // pages:
  603. // * normal new issue/pr page, no status-button
  604. // * issue/pr view page, with comment form, has status-button
  605. const opts = {};
  606. const statusButton = document.getElementById('status-button');
  607. if (statusButton) {
  608. opts.onContentChanged = (editor) => {
  609. const statusText = statusButton.getAttribute(editor.value().trim() ? 'data-status-and-comment' : 'data-status');
  610. statusButton.textContent = statusText;
  611. };
  612. }
  613. initComboMarkdownEditor($commentForm.find('.combo-markdown-editor'), opts);
  614. }
  615. export function initIssueTemplateCommentEditors($commentForm) {
  616. // pages:
  617. // * new issue with issue template
  618. const $comboFields = $commentForm.find('.combo-editor-dropzone');
  619. const initCombo = async ($combo) => {
  620. const $dropzoneContainer = $combo.find('.form-field-dropzone');
  621. const $formField = $combo.find('.form-field-real');
  622. const $markdownEditor = $combo.find('.combo-markdown-editor');
  623. const editor = await initComboMarkdownEditor($markdownEditor, {
  624. onContentChanged: (editor) => {
  625. $formField.val(editor.value());
  626. },
  627. });
  628. $formField.on('focus', async () => {
  629. // deactivate all markdown editors
  630. showElem($commentForm.find('.combo-editor-dropzone .form-field-real'));
  631. hideElem($commentForm.find('.combo-editor-dropzone .combo-markdown-editor'));
  632. hideElem($commentForm.find('.combo-editor-dropzone .form-field-dropzone'));
  633. // activate this markdown editor
  634. hideElem($formField);
  635. showElem($markdownEditor);
  636. showElem($dropzoneContainer);
  637. await editor.switchToUserPreference();
  638. editor.focus();
  639. });
  640. };
  641. for (const el of $comboFields) {
  642. initCombo($(el));
  643. }
  644. }
  645. // This function used to show and hide archived label on issue/pr
  646. // page in the sidebar where we select the labels
  647. // If we have any archived label tagged to issue and pr. We will show that
  648. // archived label with checked classed otherwise we will hide it
  649. // with the help of this function.
  650. // This function runs globally.
  651. export function initArchivedLabelHandler() {
  652. if (!document.querySelector('.archived-label-hint')) return;
  653. for (const label of document.querySelectorAll('[data-is-archived]')) {
  654. toggleElem(label, label.classList.contains('checked'));
  655. }
  656. }