Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(web): ground KaTeX selections as LaTeX

Bingxi Zhao (Frank)8702997186b8
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index 21b2981da..e6600fb99 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -128,6 +128,7 @@ import {
} from "@/lib/book-references";
import {
normalizeSelectedText,
+ textFromDomSelection,
type SelectionTutorContext,
} from "@/lib/selection-tutor";
@@ -1812,7 +1813,7 @@ export default function ChatPage() {
setSelectionTutorPrompt(null);
return;
}
- const text = normalizeSelectedText(selection.toString());
+ const text = textFromDomSelection(selection);
if (text.length < 2) {
setSelectionTutorPrompt(null);
return;
@@ -1880,6 +1881,26 @@ export default function ChatPage() {
window.getSelection()?.removeAllRanges();
}, [selectionTutorPrompt, state.language, state.sessionId]);
+ const handleMessagesCopy = useCallback(
+ (event: React.ClipboardEvent<HTMLDivElement>) => {
+ const selection = window.getSelection();
+ const container = messagesContainerRef.current;
+ if (!selection || !container || selection.isCollapsed) return;
+ if (
+ !selection.rangeCount ||
+ !container.contains(selection.getRangeAt(0).commonAncestorContainer)
+ ) {
+ return;
+ }
+ const remapped = textFromDomSelection(selection);
+ const raw = normalizeSelectedText(selection.toString());
+ if (!remapped || remapped === raw) return;
+ event.clipboardData.setData("text/plain", remapped);
+ event.preventDefault();
+ },
+ [messagesContainerRef],
+ );
+
const handleClosePreview = useCallback(() => {
setPreviewSource(null);
}, []);
@@ -2476,6 +2497,7 @@ export default function ChatPage() {
handleMessagesScroll();
}}
onClick={handleMessagesClick}
+ onCopy={handleMessagesCopy}
onMouseUp={handleMessagesSelection}
onKeyUp={handleMessagesSelection}
// `both-edges` reserves the scrollbar gutter on both sides so
diff --git a/web/lib/selection-tutor.ts b/web/lib/selection-tutor.ts
index 47d880b72..d8763e7bd 100644
--- a/web/lib/selection-tutor.ts
+++ b/web/lib/selection-tutor.ts
@@ -58,3 +58,127 @@ export function buildSelectionTutorConfig(
},
};
}
+
+/** Wrap KaTeX's raw TeX annotation in the Markdown math delimiters we store. */
+export function wrapLatexSource(tex: string, display: boolean): string {
+ const body = tex.trim();
+ if (!body) return "";
+ return display ? `$$${body}$$` : `$${body}$`;
+}
+
+/** Read the original TeX embedded by KaTeX's default htmlAndMathml output. */
+export function extractTexAnnotation(root: ParentNode): string | null {
+ const annotation = root.querySelector(
+ 'annotation[encoding="application/x-tex"]',
+ );
+ const text = annotation?.textContent?.trim() ?? "";
+ return text || null;
+}
+
+/** Test helper for the annotation emitted by KaTeX renderToString. */
+export function extractTexAnnotationFromHtml(html: string): string | null {
+ const match = html.match(
+ /<annotation\b[^>]*\bencoding\s*=\s*["']application\/x-tex["'][^>]*>([\s\S]*?)<\/annotation>/i,
+ );
+ if (!match) return null;
+ return decodeXmlText(match[1]).trim() || null;
+}
+
+/**
+ * Prefer original LaTeX over rendered KaTeX glyphs in a DOM selection.
+ * Rendered Unicode cannot be grounded reliably against stored Markdown.
+ */
+export function textFromDomSelection(selection: Selection | null): string {
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
+ return "";
+ }
+ return normalizeSelectedText(
+ rewriteRangePreferringKatexLatex(selection.getRangeAt(0)),
+ );
+}
+
+function rewriteRangePreferringKatexLatex(range: Range): string {
+ const roots = intersectingKatexRoots(range);
+ if (roots.length === 0) return range.toString();
+
+ if (roots.length === 1) {
+ const root = roots[0];
+ const start = nodeElement(range.startContainer);
+ const end = nodeElement(range.endContainer);
+ if (start && end && root.contains(start) && root.contains(end)) {
+ const tex = extractTexAnnotation(root);
+ if (tex) return wrapLatexSource(tex, isDisplayKatex(root));
+ }
+ }
+
+ const holder = document.createElement("div");
+ holder.appendChild(range.cloneContents());
+ const cloned = Array.from(
+ holder.querySelectorAll(".katex-display, .katex"),
+ ).filter(
+ (element) =>
+ !(
+ element.classList.contains("katex") &&
+ element.closest(".katex-display")
+ ),
+ );
+
+ cloned.forEach((element, index) => {
+ const live = roots[index] ?? null;
+ const tex =
+ (live ? extractTexAnnotation(live) : null) ||
+ extractTexAnnotation(element);
+ if (!tex) return;
+ element.replaceWith(
+ document.createTextNode(
+ wrapLatexSource(tex, isDisplayKatex(live ?? element)),
+ ),
+ );
+ });
+
+ return holder.textContent ?? range.toString();
+}
+
+function intersectingKatexRoots(range: Range): Element[] {
+ const scope = nodeElement(range.commonAncestorContainer);
+ if (!scope) return [];
+ const searchRoot =
+ scope.closest("[data-chat-message-id], .md-renderer, .prose") ?? scope;
+ return Array.from(
+ searchRoot.querySelectorAll(".katex-display, .katex"),
+ ).filter((element) => {
+ if (
+ element.classList.contains("katex") &&
+ element.closest(".katex-display")
+ ) {
+ return false;
+ }
+ try {
+ return range.intersectsNode(element);
+ } catch {
+ return false;
+ }
+ });
+}
+
+function isDisplayKatex(root: Element): boolean {
+ return (
+ root.classList.contains("katex-display") ||
+ Boolean(root.closest(".katex-display"))
+ );
+}
+
+function nodeElement(node: Node): Element | null {
+ return node.nodeType === Node.ELEMENT_NODE
+ ? (node as Element)
+ : node.parentElement;
+}
+
+function decodeXmlText(value: string): string {
+ return value
+ .replace(/&lt;/g, "<")
+ .replace(/&gt;/g, ">")
+ .replace(/&quot;/g, '"')
+ .replace(/&apos;/g, "'")
+ .replace(/&amp;/g, "&");
+}
diff --git a/web/tests/selection-tutor.test.ts b/web/tests/selection-tutor.test.ts
index 4ab6cdb84..b1b27366c 100644
--- a/web/tests/selection-tutor.test.ts
+++ b/web/tests/selection-tutor.test.ts
@@ -2,8 +2,10 @@ import test from "node:test";
import assert from "node:assert/strict";
import {
buildSelectionTutorConfig,
+ extractTexAnnotationFromHtml,
normalizeSelectedText,
selectionTutorKey,
+ wrapLatexSource,
} from "../lib/selection-tutor";
test("normalizes selected chat text without flattening paragraphs", () => {
@@ -43,3 +45,25 @@ test("builds selected text context with its containing message", () => {
},
);
});
+
+test("wrapLatexSource matches Markdown math delimiters", () => {
+ assert.equal(wrapLatexSource("a^2", false), "$a^2$");
+ assert.equal(
+ wrapLatexSource("I(\\theta) = a^2", true),
+ "$$I(\\theta) = a^2$$",
+ );
+});
+
+test("KaTeX annotation remaps to math that grounds in Markdown source", () => {
+ const tex = "I(\\theta) = a^2 \\cdot P(\\theta) \\cdot (1 - P(\\theta))";
+ const html = `<span class="katex"><span class="katex-mathml"><math><semantics><annotation encoding="application/x-tex">${tex}</annotation></semantics></math></span><span class="katex-html">I(θ)=a²</span></span>`;
+ assert.equal(extractTexAnnotationFromHtml(html), tex);
+
+ const source = `$$${tex}$$`;
+ const selected = wrapLatexSource(
+ extractTexAnnotationFromHtml(html) ?? "",
+ true,
+ );
+ assert.equal(selected, source);
+ assert.ok(source.includes(selected));
+});