gitea源码

TextExpander.ts 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import {matchEmoji, matchMention, matchIssue} from '../../utils/match.ts';
  2. import {emojiString} from '../emoji.ts';
  3. import {svg} from '../../svg.ts';
  4. import {parseIssueHref, parseRepoOwnerPathInfo} from '../../utils.ts';
  5. import {createElementFromAttrs, createElementFromHTML} from '../../utils/dom.ts';
  6. import {getIssueColor, getIssueIcon} from '../issue.ts';
  7. import {debounce} from 'perfect-debounce';
  8. import type TextExpanderElement from '@github/text-expander-element';
  9. import type {TextExpanderChangeEvent, TextExpanderResult} from '@github/text-expander-element';
  10. async function fetchIssueSuggestions(key: string, text: string): Promise<TextExpanderResult> {
  11. const issuePathInfo = parseIssueHref(window.location.href);
  12. if (!issuePathInfo.ownerName) {
  13. const repoOwnerPathInfo = parseRepoOwnerPathInfo(window.location.pathname);
  14. issuePathInfo.ownerName = repoOwnerPathInfo.ownerName;
  15. issuePathInfo.repoName = repoOwnerPathInfo.repoName;
  16. // then no issuePathInfo.indexString here, it is only used to exclude the current issue when "matchIssue"
  17. }
  18. if (!issuePathInfo.ownerName) return {matched: false};
  19. const matches = await matchIssue(issuePathInfo.ownerName, issuePathInfo.repoName, issuePathInfo.indexString, text);
  20. if (!matches.length) return {matched: false};
  21. const ul = createElementFromAttrs('ul', {class: 'suggestions'});
  22. for (const issue of matches) {
  23. const li = createElementFromAttrs(
  24. 'li', {role: 'option', class: 'tw-flex tw-gap-2', 'data-value': `${key}${issue.number}`},
  25. createElementFromHTML(svg(getIssueIcon(issue), 16, ['text', getIssueColor(issue)])),
  26. createElementFromAttrs('span', null, `#${issue.number}`),
  27. createElementFromAttrs('span', null, issue.title),
  28. );
  29. ul.append(li);
  30. }
  31. return {matched: true, fragment: ul};
  32. }
  33. export function initTextExpander(expander: TextExpanderElement) {
  34. if (!expander) return;
  35. const textarea = expander.querySelector<HTMLTextAreaElement>('textarea');
  36. // help to fix the text-expander "multiword+promise" bug: do not show the popup when there is no "#" before current line
  37. const shouldShowIssueSuggestions = () => {
  38. const posVal = textarea.value.substring(0, textarea.selectionStart);
  39. const lineStart = posVal.lastIndexOf('\n');
  40. const keyStart = posVal.lastIndexOf('#');
  41. return keyStart > lineStart;
  42. };
  43. const debouncedIssueSuggestions = debounce(async (key: string, text: string): Promise<TextExpanderResult> => {
  44. // https://github.com/github/text-expander-element/issues/71
  45. // Upstream bug: when using "multiword+promise", TextExpander will get wrong "key" position.
  46. // To reproduce, comment out the "shouldShowIssueSuggestions" check, use the "await sleep" below,
  47. // then use content "close #20\nclose #20\nclose #20" (3 lines), keep changing the last line `#20` part from the end (including removing the `#`)
  48. // There will be a JS error: Uncaught (in promise) IndexSizeError: Failed to execute 'setStart' on 'Range': The offset 28 is larger than the node's length (27).
  49. // check the input before the request, to avoid emitting empty query to backend (still related to the upstream bug)
  50. if (!shouldShowIssueSuggestions()) return {matched: false};
  51. // await sleep(Math.random() * 1000); // help to reproduce the text-expander bug
  52. const ret = await fetchIssueSuggestions(key, text);
  53. // check the input again to avoid text-expander using incorrect position (upstream bug)
  54. if (!shouldShowIssueSuggestions()) return {matched: false};
  55. return ret;
  56. }, 300); // to match onInputDebounce delay
  57. expander.addEventListener('text-expander-change', (e: TextExpanderChangeEvent) => {
  58. const {key, text, provide} = e.detail;
  59. if (key === ':') {
  60. const matches = matchEmoji(text);
  61. if (!matches.length) return provide({matched: false});
  62. const ul = document.createElement('ul');
  63. ul.classList.add('suggestions');
  64. for (const name of matches) {
  65. const emoji = emojiString(name);
  66. const li = document.createElement('li');
  67. li.setAttribute('role', 'option');
  68. li.setAttribute('data-value', emoji);
  69. li.textContent = `${emoji} ${name}`;
  70. ul.append(li);
  71. }
  72. provide({matched: true, fragment: ul});
  73. } else if (key === '@') {
  74. const matches = matchMention(text);
  75. if (!matches.length) return provide({matched: false});
  76. const ul = document.createElement('ul');
  77. ul.classList.add('suggestions');
  78. for (const {value, name, fullname, avatar} of matches) {
  79. const li = document.createElement('li');
  80. li.setAttribute('role', 'option');
  81. li.setAttribute('data-value', `${key}${value}`);
  82. const img = document.createElement('img');
  83. img.src = avatar;
  84. li.append(img);
  85. const nameSpan = document.createElement('span');
  86. nameSpan.classList.add('name');
  87. nameSpan.textContent = name;
  88. li.append(nameSpan);
  89. if (fullname && fullname.toLowerCase() !== name) {
  90. const fullnameSpan = document.createElement('span');
  91. fullnameSpan.classList.add('fullname');
  92. fullnameSpan.textContent = fullname;
  93. li.append(fullnameSpan);
  94. }
  95. ul.append(li);
  96. }
  97. provide({matched: true, fragment: ul});
  98. } else if (key === '#') {
  99. provide(debouncedIssueSuggestions(key, text));
  100. }
  101. });
  102. expander.addEventListener('text-expander-value', ({detail}: Record<string, any>) => {
  103. if (detail?.item) {
  104. // add a space after @mentions and #issue as it's likely the user wants one
  105. const suffix = ['@', '#'].includes(detail.key) ? ' ' : '';
  106. detail.value = `${detail.item.getAttribute('data-value')}${suffix}`;
  107. }
  108. });
  109. }