Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/AI chat: fix highlights in preview
Adorian Doran9f61b45ccc6e
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatPreview.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatPreview.tsxindex cf0912c663..a640354859 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatPreview.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatPreview.tsx@@ -1,17 +1,31 @@import "./ChatPreview.css";+import { useLayoutEffect, useRef } from "preact/hooks";+import ChatMessage from "./ChatMessage.js";+import { materializeChatHighlights } from "./chat_highlights_static.js";import type { StoredMessage } from "./llm_chat_types.js";/*** Read-only render of a stored conversation, used by the note preview renderer (collection- * tiles, etc. — see content_renderer). Reuses {@link ChatMessage} so markdown, tool calls,- * thinking, citations and attachments render exactly as in the live timeline — but with no+ * tiles, tooltips, printing — see content_renderer). Reuses {@link ChatMessage} so markdown, tool+ * calls, thinking, citations and attachments render exactly as in the live timeline — but with no* input bar, context menu, scroll button, or read-only notice: just the conversation.*/export default function ChatPreview({ messages }: { messages: StoredMessage[] }) {+ const containerRef = useRef<HTMLDivElement>(null);++ // The live chat paints highlights over ranges, which leaves nothing in the markup for a preview+ // to show (or a tooltip to serialize, or a printer to print). Re-apply them here as elements.+ // A layout effect, so the marks are in place before the tooltip snapshots the preview.+ useLayoutEffect(() => {+ if (containerRef.current) {+ materializeChatHighlights(containerRef.current, messages);+ }+ }, [messages]);+return (- <div className="llm-chat-preview">+ <div className="llm-chat-preview" ref={containerRef}>{messages.map((message) => (<ChatMessage key={message.id} message={message} />))}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.css b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.cssindex b5729dc5df..8699513cfd 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.css@@ -4,3 +4,15 @@background-color: var(--chat-highlight-background-color, #ffe066);color: var(--chat-highlight-text-color, #1a1a1a);}++/* The same highlight as an element, for the read-only previews: they consume the rendered markup+ rather than the live document, so their highlights are materialized as <mark> (see+ chat_highlights_static.ts) and the ::highlight() rule above — which only ever targets ranges —+ does not reach them. print-color-adjust keeps the fill when the preview is printed, since print+ engines drop backgrounds by default. */+mark.chat-highlight {+ background-color: var(--chat-highlight-background-color, #ffe066);+ color: var(--chat-highlight-text-color, #1a1a1a);+ print-color-adjust: exact;+ -webkit-print-color-adjust: exact;+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.tsindex 0bffb92a96..2f481f6615 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts@@ -6,7 +6,7 @@ import type NoteContext from "../../../components/note_context.js";import { t } from "../../../services/i18n.js";import { randomString } from "../../../services/utils.js";import type { ChatContextMenuItemsProvider } from "./chat_context_menu.js";-import { createAnchorFromSelection, resolveAnchorRange } from "./chat_highlights_anchor.js";+import { createAnchorFromSelection, findMessageContentRoot, resolveAnchorRange } from "./chat_highlights_anchor.js";import type { HighlightAnchor } from "./llm_chat_types.js";import type { UseLlmChatReturn } from "./useLlmChat.js";@@ -190,15 +190,6 @@ function releaseRangeMap(ref: { current: RangeMap }) {}}-function findMessageContentRoot(container: HTMLElement, messageId: string): HTMLElement | null {- // Match on the parsed dataset value rather than an attribute selector: persisted/imported chats- // may carry ids with characters that would make a selector invalid and throw.- for (const el of container.querySelectorAll<HTMLElement>("[data-message-id]")) {- if (el.dataset.messageId === messageId) return el.querySelector<HTMLElement>(".llm-chat-message-content");- }- return null;-}-/** The id of the smallest highlight (of `messageId`) painted under the given viewport point, if any. */function highlightAtPoint(ranges: RangeMap, messageId: string, x: number, y: number): string | null {const caret = caretFromPoint(document, x, y);diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.tsindex a30014e408..a2af6baa30 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.ts@@ -60,6 +60,16 @@ export function createAnchorFromSelection(root: HTMLElement, range: Range): Omit};}+/** The prose root of a rendered message — the element a message's anchors resolve against. */+export function findMessageContentRoot(container: HTMLElement, messageId: string): HTMLElement | null {+ // Match on the parsed dataset value rather than an attribute selector: persisted/imported chats+ // may carry ids with characters that would make a selector invalid and throw.+ for (const el of container.querySelectorAll<HTMLElement>("[data-message-id]")) {+ if (el.dataset.messageId === messageId) return el.querySelector<HTMLElement>(".llm-chat-message-content");+ }+ return null;+}+/** Resolve a stored anchor to a live {@link Range} within `root`, or `null` if it can't be located. */export function resolveAnchorRange(root: HTMLElement, anchor: HighlightAnchor): Range | null {const projection = buildProseProjection(root);diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_static.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_static.spec.tsnew file mode 100644index 0000000000..d56bc0f448--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_static.spec.ts@@ -0,0 +1,104 @@+import { beforeEach, describe, expect, it } from "vitest";++import { materializeChatHighlights } from "./chat_highlights_static.js";+import type { HighlightAnchor, StoredMessage } from "./llm_chat_types.js";++/** A rendered preview whose single message carries the given markdown-rendered HTML. */+function buildPreview(html: string) {+ const container = document.createElement("div");+ container.innerHTML = `+ <div class="llm-chat-message-wrapper" data-message-id="m1">+ <div class="llm-chat-message">+ <div class="llm-chat-message-content">+ <div class="llm-chat-markdown">${html}</div>+ </div>+ </div>+ </div>`;+ return container;+}++function buildMessage(...highlights: HighlightAnchor[]): StoredMessage {+ return {+ id: "m1",+ role: "assistant",+ content: "irrelevant — the anchors resolve against the rendered DOM",+ createdAt: "2026-01-01T00:00:00.000Z",+ highlights+ };+}++/** An anchor over `quotedText`, located by the offsets it was created at. */+function anchor(id: string, start: number, quotedText: string): HighlightAnchor {+ return { id, start, end: start + quotedText.length, quotedText };+}++let container: HTMLElement;++describe("materializeChatHighlights", () => {+ beforeEach(() => {+ container = buildPreview("<p>The quick brown fox</p>");+ });++ it("wraps the highlighted prose in a mark carrying the anchor id", () => {+ materializeChatHighlights(container, [buildMessage(anchor("h1", 4, "quick"))]);++ const marks = container.querySelectorAll("mark.chat-highlight");+ expect(marks).toHaveLength(1);+ expect(marks[0].textContent).toBe("quick");+ expect((marks[0] as HTMLElement).dataset.highlightId).toBe("h1");+ // The surrounding prose is preserved intact.+ expect(container.querySelector("p")?.textContent).toBe("The quick brown fox");+ });++ it("wraps each text node of a highlight that spans element boundaries", () => {+ container = buildPreview("<p>plain <strong>bold</strong> tail</p>");++ // "in bold ta" — starts inside the leading text, crosses <strong>, ends in the trailing text.+ materializeChatHighlights(container, [buildMessage(anchor("h1", 2, "ain bold ta"))]);++ const marks = container.querySelectorAll("mark.chat-highlight");+ expect(marks).toHaveLength(3);+ expect([...marks].map(m => m.textContent)).toEqual(["ain ", "bold", " ta"]);+ // The bold run stays bold: the mark is nested inside it, not wrapped around it.+ expect(container.querySelector("strong > mark.chat-highlight")).not.toBeNull();+ expect(container.querySelector("p")?.textContent).toBe("plain bold tail");+ });++ it("relocates an anchor whose offsets drifted, and drops one whose text is gone", () => {+ // Stale offsets, but the quoted text (with its context) still identifies the run.+ const drifted = { ...anchor("h1", 999, "brown"), prefix: "quick ", suffix: " fox" };+ const orphaned = anchor("h2", 0, "text from a regenerated message");++ materializeChatHighlights(container, [buildMessage(drifted, orphaned)]);++ const marks = container.querySelectorAll("mark.chat-highlight");+ expect(marks).toHaveLength(1);+ expect(marks[0].textContent).toBe("brown");+ });++ it("is idempotent: re-running replaces the marks instead of nesting them", () => {+ const message = buildMessage(anchor("h1", 4, "quick"));++ materializeChatHighlights(container, [message]);+ materializeChatHighlights(container, [message]);++ expect(container.querySelectorAll("mark.chat-highlight")).toHaveLength(1);+ expect(container.querySelector("mark.chat-highlight > mark")).toBeNull();+ expect(container.querySelector("p")?.textContent).toBe("The quick brown fox");+ });++ it("removes the marks when the message no longer has highlights", () => {+ materializeChatHighlights(container, [buildMessage(anchor("h1", 4, "quick"))]);+ materializeChatHighlights(container, [buildMessage()]);++ expect(container.querySelectorAll("mark.chat-highlight")).toHaveLength(0);+ expect(container.querySelector("p")?.textContent).toBe("The quick brown fox");+ });++ it("ignores highlights whose message is not in the preview (e.g. beyond a tooltip's cap)", () => {+ const missing: StoredMessage = { ...buildMessage(anchor("h1", 4, "quick")), id: "not-rendered" };++ expect(() => materializeChatHighlights(container, [missing])).not.toThrow();+ expect(container.querySelectorAll("mark.chat-highlight")).toHaveLength(0);+ });+});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_static.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_static.tsnew file mode 100644index 0000000000..1c39ac6245--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_static.ts@@ -0,0 +1,101 @@+import "./chat_highlights.css";++import { findMessageContentRoot, resolveAnchorRange } from "./chat_highlights_anchor.js";+import type { StoredMessage } from "./llm_chat_types.js";++/**+ * Paints a chat's stored highlights as real markup, for the read-only preview surfaces.+ *+ * The live chat paints highlights with the CSS Custom Highlight API (see {@link useChatHighlights}):+ * they exist only as `Range` objects in a document-global registry, deliberately leaving the+ * Preact-owned message DOM untouched. That makes them invisible to every context that consumes the+ * rendered markup rather than the live document — the note tooltip (which serializes the preview to+ * an HTML string), collection tiles, and printing (where `::highlight()` painting is not reliably+ * rendered anyway).+ *+ * So for previews the same anchors are resolved against the preview's own DOM and wrapped in+ * `<mark class="chat-highlight">` elements, which survive serialization, printing, and sanitization.+ * Idempotent: any previously materialized marks are unwrapped first, so a re-render can't nest them.+ */+export function materializeChatHighlights(container: HTMLElement, messages: StoredMessage[]) {+ clearMaterializedHighlights(container);++ for (const message of messages) {+ if (!message.highlights?.length) continue;++ const root = findMessageContentRoot(container, message.id);+ if (!root) continue;++ for (const anchor of message.highlights) {+ // Resolved one at a time: wrapping splits text nodes, so each anchor re-reads the prose+ // (whose *text* is unchanged by wrapping — a <mark> contributes its own text back).+ const range = resolveAnchorRange(root, anchor);+ // Orphaned (e.g. the message was regenerated) — drop it rather than mis-paint.+ if (!range) continue;+ wrapRangeInMarks(range, anchor.id);+ }+ }+}++export const HIGHLIGHT_MARK_CLASS = "chat-highlight";++/** Unwrap previously materialized marks, restoring the DOM to plain prose. */+function clearMaterializedHighlights(container: HTMLElement) {+ for (const mark of container.querySelectorAll<HTMLElement>(`mark.${HIGHLIGHT_MARK_CLASS}`)) {+ const parent = mark.parentNode;+ if (!parent) continue;+ mark.replaceWith(...mark.childNodes);+ // Re-merge the text nodes the original wrap split apart, so offsets resolve over whole runs.+ parent.normalize();+ }+}++/**+ * Wrap every text node the range covers in its own `<mark>`. A highlight routinely spans element+ * boundaries (`**bold** words`), where `Range.surroundContents` throws on partial containment — so+ * the range is applied node by node, splitting the boundary text nodes to the exact offsets.+ */+function wrapRangeInMarks(range: Range, anchorId: string) {+ for (const text of textNodesInRange(range)) {+ const start = text === range.startContainer ? range.startOffset : 0;+ const end = text === range.endContainer ? range.endOffset : text.data.length;+ if (end <= start) continue;++ // splitText leaves `text` holding [0, end); splitting again at `start` yields exactly the+ // covered run, with the untouched remainders left behind as siblings.+ let covered = text;+ if (end < covered.data.length) covered.splitText(end);+ if (start > 0) covered = covered.splitText(start);++ const mark = covered.ownerDocument.createElement("mark");+ mark.className = HIGHLIGHT_MARK_CLASS;+ mark.dataset.highlightId = anchorId;+ covered.replaceWith(mark);+ mark.appendChild(covered);+ }+}++/**+ * The text nodes a range covers, in document order. Anchors always resolve to text-node boundaries+ * (they are built from a projection of text nodes), so walking from the start container to the end+ * container is enough — no element-boundary cases to consider.+ */+function textNodesInRange(range: Range): Text[] {+ const root = range.commonAncestorContainer;+ if (root.nodeType === Node.TEXT_NODE) {+ return [root as Text];+ }++ const walker = root.ownerDocument?.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ if (!walker) return [];++ const nodes: Text[] = [];+ let covering = false;+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const text = node as Text;+ if (text === range.startContainer) covering = true;+ if (covering) nodes.push(text);+ if (text === range.endContainer) break;+ }+ return nodes;+}