fix(web): cite text inside inline HTML renders #17023
Closedjakeleventhal(GitHub profile, opens in a new tab)wants to merge 19 commits into
main fromrefs/pull/17023/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/chat/AssistantCitationSource.tsx line 36OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -28,3 +30,7 @@2830 citation: AssistantCitation;2931 onUnavailable: () => void;3032 }): () => void {33+ if (anchor.htmlRender) {34+ const frame = anchor.htmlRender;35+ const validate = () => {36+ if (!anchor.source.isConnected || !anchor.viewport.contains(frame)) onUnavailable();apps/web/src/components/files/BrowserDocumentFrame.tsx line 94OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -73,7 +74,21 @@7374 /** Receives the page's content height whenever it changes, so an inline frame can fit it. */7475 readonly onContentHeight?: (height: number) => void;76+ readonly selectionBridge?: boolean;7577 }) {7678 const theme = useHtmlRenderTheme();7779 const frameRef = useRef<HTMLIFrameElement>(null);7880 const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`);7981 const [loaded, setLoaded] = useState(false);82+ const [selectionSrc, setSelectionSrc] = useState<string>();83+ const [selectionError, setSelectionError] = useState(false);84+ useEffect(() => {85+ if (!props.selectionBridge) return;86+ const controller = new AbortController();87+ let blobUrl: string | undefined;88+ void fetch(src, { signal: controller.signal })89+ .then(async (response) => {90+ if (!response.ok) throw new Error("Could not load HTML render");91+ const html = await response.text();92+ if (controller.signal.aborted) return;93+ blobUrl = URL.createObjectURL(94+ new Blob([injectHtmlSelectionBridge(html)], { type: "text/html" }),packages/shared/src/htmlRenderSelectionScript.ts line 102Resolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +55,21 @@55+ let before = Math.max(0, a - 32);56+ let after = Math.min(normalized.length, b + 32);57+ const splitsPair = (offset) =>58+ /[\uD800-\uDBFF]/.test(normalized[offset - 1] || "") &&59+ /[\uDC00-\uDFFF]/.test(normalized[offset] || "");60+ if (splitsPair(before)) before++;61+ if (splitsPair(after)) after--;62+ return {63+ text: text.slice(start, end),64+ start: a,65+ end: b,66+ prefix: normalized.slice(before, a),67+ suffix: normalized.slice(b, after),68+ };69+ };70+ const capture = () => {71+ const selection = window.getSelection();72+ if (!selection || selection.isCollapsed || selection.rangeCount !== 1) return null;73+ const range = selection.getRangeAt(0);74+ const ancestor = (node) => (node.nodeType === 1 ? node : node.parentElement)?.closest(excluded);75+ if (ancestor(range.startContainer) || ancestor(range.endContainer)) return null;apps/web/src/components/chat/AssistantSelectionToolbar.tsx line 197Resolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -107,2 +115,21 @@107115 document.addEventListener("keydown", focusActions, true);108116 document.addEventListener("selectionchange", actions.selectionChanged);117+ const htmlSelection = (event: MessageEvent) => {118+ const params = htmlSelectionParams(event.data);119+ if (params === undefined) return;120+ const frame = [121+ ...viewport.querySelectorAll<HTMLIFrameElement>("iframe[data-html-selection-bridge]"),122+ ].find((frame) => frame.contentWindow === event.source);123+ const source = frame?.closest<HTMLElement>("[data-assistant-citation-source]");124+ const messageId = source?.dataset.assistantCitationSource;125+ if (!frame || !source || !messageId) return;126+ if (params === null) {127+ setSelection((previous) =>128+ document.activeElement === frame || previous?.sourceAnchor.htmlRender === frame129+ ? null130+ : previous,131+ );132+ return;133+ }134+ if (params.focus === true) {135+ if (document.activeElement === frame) toolbarRef.current?.focus({ preventScroll: true });
- apps/web/src/lib/htmlRenderSelectionBridge.js lines 219 to 230OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +210,21 @@210+ };211+ const start = rawOffset(at);212+ const end = rawOffset(at + needle.length);213+ const first = chunks.find((chunk) => chunk.end > start);214+ const last = chunks.findLast((chunk) => chunk.start < end);215+ if (!first || !last) {216+ post({ target: null, selector: quote });217+ return;218+ }219+ marked = document.createRange();220+ marked.setStart(first.node, Math.max(0, start - first.start));221+ marked.setEnd(last.node, Math.min(last.node.length, end - last.start));222+ if (action === "target") {223+ const bounds = marked.getBoundingClientRect();224+ if (bounds.top < 0 || bounds.bottom > window.innerHeight)225+ window.scrollBy(0, bounds.top - Math.min(80, window.innerHeight / 3));226+ }227+ if (window.CSS?.highlights && window.Highlight) {228+ CSS.highlights.set("t3-html-citation", new Highlight(marked));229+ }230+ post({ target: rect(marked), selector: quote });
- packages/shared/src/htmlRenderSelectionScript.ts lines 34 to 34Resolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +14,21 @@14+ let pointer = null;15+ let marked = null;16+ let commentQuote = null;17+ const post = (params) => window.parent.postMessage({ jsonrpc: "2.0", method, params }, "*");18+ const cancel = () => {19+ clearTimeout(timer);20+ pending = false;21+ active = false;22+ pointer = null;23+ post(null);24+ };25+ const stream = () => {26+ let text = "";27+ let separator = false;28+ const chunks = [];29+ const visit = (node) => {30+ if (node.nodeType === 3 && node.length) {31+ if (separator && text.length) text += "\n";32+ separator = false;33+ chunks.push({ node, start: text.length, end: text.length + node.length });34+ text += node.data;packages/shared/src/htmlRenderSelectionScript.ts lines 36 to 36OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +16,21 @@16+ let commentQuote = null;17+ const post = (params) => window.parent.postMessage({ jsonrpc: "2.0", method, params }, "*");18+ const cancel = () => {19+ clearTimeout(timer);20+ pending = false;21+ active = false;22+ pointer = null;23+ post(null);24+ };25+ const stream = () => {26+ let text = "";27+ let separator = false;28+ const chunks = [];29+ const visit = (node) => {30+ if (node.nodeType === 3 && node.length) {31+ if (separator && text.length) text += "\n";32+ separator = false;33+ chunks.push({ node, start: text.length, end: text.length + node.length });34+ text += node.data;35+ } else if (node.nodeType === 1 && !node.matches(excluded)) {36+ const block = node.matches(blocks) || node.tagName === "BR";packages/shared/src/htmlRenderSelectionScript.ts line 245OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +225,21 @@225+ if (offset <= count + length)226+ return match.index + (whitespace && offset > count ? match[0].length : offset - count);227+ count += length;228+ }229+ return text.length;230+ };231+ const start = rawOffset(at);232+ const end = rawOffset(at + needle.length);233+ const first = chunks.find((chunk) => chunk.end > start);234+ const last = chunks.findLast((chunk) => chunk.start < end);235+ if (!first || !last) {236+ reply(null);237+ return;238+ }239+ marked = document.createRange();240+ marked.setStart(first.node, Math.max(0, start - first.start));241+ marked.setEnd(last.node, Math.min(last.node.length, end - last.start));242+ if (action === "target") {243+ const bounds = marked.getBoundingClientRect();244+ if (bounds.top < 0 || bounds.bottom > window.innerHeight)245+ window.scrollBy(0, bounds.top - Math.min(80, window.innerHeight / 3));
- packages/shared/src/htmlRenderSelectionScript.ts lines 272 to 272OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +252,21 @@252+ const left = box.left + element.clientLeft;253+ if (254+ /^(auto|scroll|hidden)$/.test(style.overflowY) &&255+ element.scrollHeight > element.clientHeight256+ )257+ element.scrollTop +=258+ bounds.top < top259+ ? bounds.top - top260+ : Math.max(0, bounds.top + bounds.height - top - element.clientHeight);261+ if (262+ /^(auto|scroll|hidden)$/.test(style.overflowX) &&263+ element.scrollWidth > element.clientWidth264+ )265+ element.scrollLeft +=266+ bounds.left < left267+ ? bounds.left - left268+ : Math.max(0, bounds.left + bounds.width - left - element.clientWidth);269+ }270+ const bounds = marked.getBoundingClientRect();271+ if (bounds.top < 0 || bounds.bottom > window.innerHeight)272+ window.scrollBy(0, bounds.top - Math.min(80, window.innerHeight / 3));packages/shared/src/htmlRenderSelectionScript.ts lines 270 to 272OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +252,21 @@252+ const left = box.left + element.clientLeft;253+ if (254+ /^(auto|scroll|hidden)$/.test(style.overflowY) &&255+ element.scrollHeight > element.clientHeight256+ )257+ element.scrollTop +=258+ bounds.top < top259+ ? bounds.top - top260+ : Math.max(0, bounds.top + bounds.height - top - element.clientHeight);261+ if (262+ /^(auto|scroll|hidden)$/.test(style.overflowX) &&263+ element.scrollWidth > element.clientWidth264+ )265+ element.scrollLeft +=266+ bounds.left < left267+ ? bounds.left - left268+ : Math.max(0, bounds.left + bounds.width - left - element.clientWidth);269+ }270+ const bounds = marked.getBoundingClientRect();271+ if (bounds.top < 0 || bounds.bottom > window.innerHeight)272+ window.scrollBy(0, bounds.top - Math.min(80, window.innerHeight / 3));
- packages/shared/src/htmlRenderSelectionScript.ts lines 313 to 316Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +282,21 @@282+ : 0;283+ // Page CSS can request smooth scrolling; return geometry only after positioning.284+ if (dx || dy) window.scrollBy({ left: dx, top: dy, behavior: "instant" });285+ }286+ if (window.CSS?.highlights && window.Highlight)287+ CSS.highlights.set("t3-html-citation", new Highlight(marked));288+ reply(rect(marked));289+ };290+ // Only an open comment needs ongoing quote validation; coalesce page changes.291+ let validation;292+ const validateComment = () => {293+ if (!commentQuote || validation) return;294+ validation = requestAnimationFrame(() => {295+ validation = null;296+ if (commentQuote) markQuote(commentQuote, "mark");297+ });298+ };299+ const commentObserver = new MutationObserver(validateComment);300+ const commentResize = window.ResizeObserver ? new ResizeObserver(validateComment) : null;301+ window.addEventListener("resize", validateComment);302+ document.addEventListener("scroll", validateComment, true);
- packages/shared/src/htmlRenderSelectionScript.ts lines 168 to 168OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +148,21 @@148+ if (!active || event.button !== 0) return;149+ pointer = { x: event.clientX, y: event.clientY };150+ schedule(event.detail >= 2 ? 500 : 0);151+ });152+ document.addEventListener("selectionchange", () => {153+ if (active && !down && !pending) schedule();154+ });155+ document.addEventListener("keydown", (event) => {156+ if (event.key === "Escape") cancel();157+ else if (158+ event.key === "Tab" &&159+ !event.shiftKey &&160+ !event.altKey &&161+ !event.ctrlKey &&162+ !event.metaKey &&163+ active &&164+ capture()?.selector165+ ) {166+ event.preventDefault();167+ post({ focus: true });168+ } else if (event.shiftKey && event.key.startsWith("Arrow")) {
coderabbitai[bot](GitHub profile, opens in a new tab) approved these changes
- apps/web/src/components/chat/htmlRenderCitationSource.ts line 58Resolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +25,21 @@25+ const scrollNode = list.getScrollableNode();26+ if (!(scrollNode instanceof HTMLElement)) return;27+ let stopped = false;28+ let frame: HTMLIFrameElement | null = null;29+ let scrolling = false;30+ let expiry: ReturnType<typeof setTimeout> | undefined;31+ let responseTimeout: ReturnType<typeof setTimeout> | undefined;32+ const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;33+ const resolve = () => {34+ if (stopped || activation.dismissed || !root.isConnected || scrolling) return;35+ if (root.querySelector("[data-html-render-error]")) {36+ activation.dismissed = true;37+ request.onComplete();38+ toastManager.add({39+ type: "warning",40+ title: "Could not load the cited HTML",41+ description: "Reconnect to the environment and try again. The saved quote is unchanged.",42+ });43+ return;44+ }45+ frame = root.querySelector<HTMLIFrameElement>("iframe[data-html-selection-ready]");
- @@ -412,3 +412,4 @@412412 const asset = yield* resolveAsset(413413 suffix.slice(0, separatorIndex),414414 suffix.slice(separatorIndex + 1),415+ { htmlSelection: url.value.searchParams.get("t3-html-selection") === "1" },
maria-rcks closed this
maria-rcks reopened this
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
juliusmarminge added labelsbugfix
juliusmarminge added labelspr:needs-julius
juliusmarminge removed labelspr:needs-julius
juliusmarminge closed this
Sign in to join this conversation.







macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed