conversationFindHighlightDom.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import type { ConversationFindMatch } from "@/v4/conversationFindIndex.js";
  2. export const FIND_HIGHLIGHT_NAME = "zcode-v4-conversation-find";
  3. export const ACTIVE_FIND_HIGHLIGHT_NAME = "zcode-v4-conversation-find-active";
  4. export const SEARCH_RESULT_HIGHLIGHT_NAME = "zcode-v4-conversation-search-result";
  5. const FIND_STYLE_ID = "zcode-v4-conversation-find-highlight-style";
  6. const FIND_HIGHLIGHT_STYLE = `
  7. ::highlight(${FIND_HIGHLIGHT_NAME}) {
  8. background-color: var(--color-find-highlight, #fde68a);
  9. color: var(--color-foreground);
  10. }
  11. ::highlight(${ACTIVE_FIND_HIGHLIGHT_NAME}) {
  12. background-color: var(--color-find-highlight-active, #facc15);
  13. color: var(--color-foreground);
  14. }
  15. ::highlight(${SEARCH_RESULT_HIGHLIGHT_NAME}) {
  16. background-color: var(--color-find-highlight-active, #facc15);
  17. color: var(--color-foreground);
  18. }
  19. `;
  20. interface CssHighlightRegistryLike {
  21. set: (name: string, highlight: unknown) => void;
  22. delete: (name: string) => void;
  23. }
  24. type CssHighlightLike = { priority?: number };
  25. type HighlightConstructor = new (...ranges: Range[]) => unknown;
  26. export function ensureConversationFindHighlightStyle() {
  27. if (typeof document === "undefined") {
  28. return;
  29. }
  30. const style =
  31. document.getElementById(FIND_STYLE_ID) ?? document.createElement("style");
  32. style.id = FIND_STYLE_ID;
  33. if (style.textContent !== FIND_HIGHLIGHT_STYLE) {
  34. // 开发态 HMR 会复用旧 style 节点;内容变化时必须同步更新。
  35. style.textContent = FIND_HIGHLIGHT_STYLE;
  36. }
  37. if (!style.isConnected) {
  38. document.head.append(style);
  39. }
  40. }
  41. function getCssHighlightSupport(): {
  42. highlights: CssHighlightRegistryLike;
  43. Highlight: HighlightConstructor;
  44. } | null {
  45. if (typeof window === "undefined" || typeof CSS === "undefined") {
  46. return null;
  47. }
  48. const highlights = (CSS as unknown as { highlights?: CssHighlightRegistryLike }).highlights;
  49. const Highlight = (window as unknown as { Highlight?: HighlightConstructor }).Highlight;
  50. if (!highlights || !Highlight) {
  51. return null;
  52. }
  53. return { highlights, Highlight };
  54. }
  55. function createHighlight(
  56. Highlight: HighlightConstructor,
  57. ranges: Range[],
  58. priority: number,
  59. ): unknown {
  60. const highlight = new Highlight(...ranges) as CssHighlightLike;
  61. highlight.priority = priority;
  62. return highlight;
  63. }
  64. function shouldSkipTextNode(textNode: Text): boolean {
  65. const parent = textNode.parentElement;
  66. if (!parent) {
  67. return true;
  68. }
  69. return Boolean(
  70. parent.closest(
  71. 'button,input,textarea,select,[contenteditable="true"],[data-conversation-find-ignore="true"]',
  72. ),
  73. );
  74. }
  75. function collectTextRangesInElement(
  76. element: HTMLElement,
  77. normalizedQuery: string,
  78. ): Range[] {
  79. const ranges: Range[] = [];
  80. const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, {
  81. acceptNode(node) {
  82. if (!(node instanceof Text) || shouldSkipTextNode(node)) {
  83. return NodeFilter.FILTER_REJECT;
  84. }
  85. return node.data.toLocaleLowerCase().includes(normalizedQuery)
  86. ? NodeFilter.FILTER_ACCEPT
  87. : NodeFilter.FILTER_SKIP;
  88. },
  89. });
  90. let currentNode = walker.nextNode();
  91. while (currentNode) {
  92. const textNode = currentNode as Text;
  93. const normalizedText = textNode.data.toLocaleLowerCase();
  94. let searchStart = 0;
  95. while (searchStart < normalizedText.length) {
  96. const matchIndex = normalizedText.indexOf(normalizedQuery, searchStart);
  97. if (matchIndex === -1) {
  98. break;
  99. }
  100. const range = document.createRange();
  101. range.setStart(textNode, matchIndex);
  102. range.setEnd(textNode, matchIndex + normalizedQuery.length);
  103. ranges.push(range);
  104. searchStart = matchIndex + normalizedQuery.length;
  105. }
  106. currentNode = walker.nextNode();
  107. }
  108. return ranges;
  109. }
  110. function getMountedRowElement(
  111. root: HTMLElement,
  112. rowId: number,
  113. ): HTMLElement | null {
  114. return root.querySelector<HTMLElement>(`[data-row-id="${rowId}"]`);
  115. }
  116. export function getMountedConversationFindRange(
  117. root: HTMLElement,
  118. query: string,
  119. match: ConversationFindMatch,
  120. ): Range | null {
  121. const normalizedQuery = query.trim().toLocaleLowerCase();
  122. if (!normalizedQuery) {
  123. return null;
  124. }
  125. const rowElement = getMountedRowElement(root, match.rowId);
  126. if (!rowElement) {
  127. return null;
  128. }
  129. const rowRanges = collectTextRangesInElement(rowElement, normalizedQuery);
  130. return rowRanges[match.rowMatchIndex] ?? null;
  131. }
  132. export function applyConversationFindHighlights({
  133. root,
  134. query,
  135. matches,
  136. activeMatch,
  137. }: {
  138. root: HTMLElement;
  139. query: string;
  140. matches: readonly ConversationFindMatch[];
  141. activeMatch: ConversationFindMatch | null;
  142. }): Range | null {
  143. ensureConversationFindHighlightStyle();
  144. const support = getCssHighlightSupport();
  145. if (!support) {
  146. return null;
  147. }
  148. const ranges = matches
  149. .map((match) => getMountedConversationFindRange(root, query, match))
  150. .filter((range): range is Range => range !== null);
  151. const activeRange = activeMatch
  152. ? getMountedConversationFindRange(root, query, activeMatch)
  153. : null;
  154. support.highlights.set(
  155. FIND_HIGHLIGHT_NAME,
  156. createHighlight(support.Highlight, ranges, 0),
  157. );
  158. support.highlights.set(
  159. ACTIVE_FIND_HIGHLIGHT_NAME,
  160. createHighlight(support.Highlight, activeRange ? [activeRange] : [], 1),
  161. );
  162. return activeRange;
  163. }
  164. export function applySearchResultHighlight({
  165. root,
  166. query,
  167. match,
  168. }: {
  169. root: HTMLElement;
  170. query: string;
  171. match: ConversationFindMatch;
  172. }): Range | null {
  173. ensureConversationFindHighlightStyle();
  174. const support = getCssHighlightSupport();
  175. if (!support) {
  176. return null;
  177. }
  178. const range = getMountedConversationFindRange(root, query, match);
  179. support.highlights.set(
  180. SEARCH_RESULT_HIGHLIGHT_NAME,
  181. createHighlight(support.Highlight, range ? [range] : [], 2),
  182. );
  183. return range;
  184. }
  185. export function scrollConversationFindRangeIntoView(range: Range) {
  186. const container = range.commonAncestorContainer;
  187. const element = container instanceof Element ? container : container.parentElement;
  188. element?.scrollIntoView({ block: "center", behavior: "smooth" });
  189. }
  190. export function clearConversationFindHighlights() {
  191. const support = getCssHighlightSupport();
  192. support?.highlights.delete(FIND_HIGHLIGHT_NAME);
  193. support?.highlights.delete(ACTIVE_FIND_HIGHLIGHT_NAME);
  194. }
  195. export function clearSearchResultHighlight() {
  196. getCssHighlightSupport()?.highlights.delete(SEARCH_RESULT_HIGHLIGHT_NAME);
  197. }