The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { type AssistantCitation } from "@t3tools/contracts"; |
| 2 | |
| 3 | import { mathWrapperOf } from "../markdown-clipboard"; |
| 4 | |
| 5 | export { |
| 6 | createAssistantTextSelector, |
| 7 | findAssistantCitationText, |
| 8 | } from "@t3tools/shared/assistantCitations"; |
| 9 | import { |
| 10 | createAssistantTextSelector, |
| 11 | findAssistantCitationText, |
| 12 | splitsSurrogatePair, |
| 13 | type AssistantTextSelector, |
| 14 | } from "@t3tools/shared/assistantCitations"; |
| 15 | export type { AssistantTextSelector } from "@t3tools/shared/assistantCitations"; |
| 16 | |
| 17 | export type AssistantCitationSourceAnchor = { |
| 18 | source: HTMLElement; |
| 19 | range: Range; |
| 20 | viewport: HTMLElement; |
| 21 | }; |
| 22 | |
| 23 | export function findAssistantCitationSourceAnchor( |
| 24 | document: Document, |
| 25 | citation: AssistantCitation, |
| 26 | ): AssistantCitationSourceAnchor | null { |
| 27 | const source = [ |
| 28 | ...document.querySelectorAll<HTMLElement>("[data-assistant-citation-source]"), |
| 29 | ].find( |
| 30 | (element) => |
| 31 | element.dataset.assistantCitationSource === citation.messageId && |
| 32 | element.dataset.assistantCitationEnvironment === citation.environmentId && |
| 33 | element.dataset.assistantCitationThread === citation.threadId, |
| 34 | ); |
| 35 | const viewport = source?.closest<HTMLElement>("[data-assistant-citation-viewport]"); |
| 36 | if (!source || !viewport) return null; |
| 37 | const range = resolveAssistantCitationRange(source, citation); |
| 38 | return range ? { source, range, viewport } : null; |
| 39 | } |
| 40 | |
| 41 | const CONTROL_SELECTOR = "button, input, textarea, select, [role=button], [contenteditable]"; |
| 42 | const EXCLUDED_SELECTOR = `${CONTROL_SELECTOR}, [hidden], [aria-hidden=true], script, style, template, noscript, svg`; |
| 43 | const BLOCK_SELECTOR = |
| 44 | "address, article, aside, blockquote, dd, div, dl, dt, figcaption, figure, footer, h1, h2, h3, h4, h5, h6, header, hr, li, main, nav, ol, p, pre, section, table, td, th, tr, ul"; |
| 45 | |
| 46 | /** A text node, or a whole rendered formula standing for its TeX. */ |
| 47 | type TextChunk = { node: Text | Element; start: number; end: number }; |
| 48 | |
| 49 | const isText = (node: Node): node is Text => node.nodeType === 3; |
| 50 | |
| 51 | function readAssistantText(root: HTMLElement) { |
| 52 | const parts: string[] = []; |
| 53 | const chunks: TextChunk[] = []; |
| 54 | let length = 0; |
| 55 | let separator = false; |
| 56 | |
| 57 | const append = (node: Text | Element, text: string) => { |
| 58 | if (separator && length > 0) { |
| 59 | parts.push("\n"); |
| 60 | length += 1; |
| 61 | } |
| 62 | separator = false; |
| 63 | chunks.push({ node, start: length, end: length + text.length }); |
| 64 | parts.push(text); |
| 65 | length += text.length; |
| 66 | }; |
| 67 | |
| 68 | const visit = (node: Node) => { |
| 69 | if (node.nodeType === 3) { |
| 70 | const text = node as Text; |
| 71 | if (text.length > 0) append(text, text.data); |
| 72 | return; |
| 73 | } |
| 74 | if (node.nodeType !== 1) return; |
| 75 | const element = node as Element; |
| 76 | if (element.matches(EXCLUDED_SELECTOR)) return; |
| 77 | const block = element.matches(BLOCK_SELECTOR); |
| 78 | if (block || element.tagName === "BR") separator = true; |
| 79 | if (element.matches("[data-markdown-math]")) { |
| 80 | append(element, element.getAttribute("data-markdown-copy")?.trim() ?? ""); |
| 81 | } else { |
| 82 | for (const child of element.childNodes) visit(child); |
| 83 | } |
| 84 | if (block) separator = true; |
| 85 | }; |
| 86 | |
| 87 | visit(root); |
| 88 | return { text: parts.join(""), chunks }; |
| 89 | } |
| 90 | |
| 91 | function excludedAncestor(node: Node): Element | null { |
| 92 | const element = node.nodeType === 1 ? (node as Element) : node.parentElement; |
| 93 | return element?.closest(EXCLUDED_SELECTOR) ?? null; |
| 94 | } |
| 95 | |
| 96 | function isUsableRange(root: HTMLElement, range: Range): boolean { |
| 97 | if ( |
| 98 | range.collapsed || |
| 99 | !root.contains(range.startContainer) || |
| 100 | !root.contains(range.endContainer) || |
| 101 | excludedAncestor(range.startContainer) !== null || |
| 102 | excludedAncestor(range.endContainer) !== null |
| 103 | ) { |
| 104 | return false; |
| 105 | } |
| 106 | return true; |
| 107 | } |
| 108 | |
| 109 | function isUnselectable(text: Text): boolean { |
| 110 | const element = mathWrapperOf(text.parentElement) ?? text.parentElement; |
| 111 | const view = element?.ownerDocument?.defaultView; |
| 112 | return !!element && !!view && view.getComputedStyle(element).userSelect === "none"; |
| 113 | } |
| 114 | |
| 115 | function selectedTextBoundary(range: Range, node: Node, last: boolean): Text | null { |
| 116 | if (!range.intersectsNode(node)) return null; |
| 117 | if (node.nodeType === 3) { |
| 118 | const text = node as Text; |
| 119 | const start = node === range.startContainer ? range.startOffset : 0; |
| 120 | const end = node === range.endContainer ? range.endOffset : text.length; |
| 121 | // Triple-click ranges include unselected text from unselectable rows and the next response. |
| 122 | return start < end && !isUnselectable(text) ? text : null; |
| 123 | } |
| 124 | for ( |
| 125 | let child = last ? node.lastChild : node.firstChild; |
| 126 | child !== null; |
| 127 | child = last ? child.previousSibling : child.nextSibling |
| 128 | ) { |
| 129 | const boundary = selectedTextBoundary(range, child, last); |
| 130 | if (boundary !== null) return boundary; |
| 131 | } |
| 132 | return null; |
| 133 | } |
| 134 | |
| 135 | export function captureAssistantTextSelection( |
| 136 | viewport: HTMLElement, |
| 137 | selection: Selection | null, |
| 138 | ): { source: HTMLElement; selector: AssistantTextSelector; range: Range } | null { |
| 139 | if (selection === null || selection.isCollapsed || selection.rangeCount !== 1) return null; |
| 140 | const range = selection.getRangeAt(0).cloneRange(); |
| 141 | const first = selectedTextBoundary(range, range.commonAncestorContainer, false); |
| 142 | const last = selectedTextBoundary(range, range.commonAncestorContainer, true); |
| 143 | if (first === null || last === null) return null; |
| 144 | const source = first.parentElement?.closest<HTMLElement>("[data-assistant-citation-source]"); |
| 145 | if (!source || !viewport.contains(source)) return null; |
| 146 | |
| 147 | // Paragraph selection can end at the next block's offset 0 or a parent |
| 148 | // boundary. Validate the text actually selected, not that empty endpoint. |
| 149 | // An endpoint inside a formula's glyphs takes in the whole formula. |
| 150 | const startFormula = mathWrapperOf(first.parentElement); |
| 151 | const endFormula = mathWrapperOf(last.parentElement); |
| 152 | if (startFormula) range.setStartBefore(startFormula); |
| 153 | else range.setStart(first, first === range.startContainer ? range.startOffset : 0); |
| 154 | if (endFormula) range.setEndAfter(endFormula); |
| 155 | else range.setEnd(last, last === range.endContainer ? range.endOffset : last.length); |
| 156 | if (!isUsableRange(source, range)) return null; |
| 157 | |
| 158 | const stream = readAssistantText(source); |
| 159 | let rawStart: number | null = null; |
| 160 | let rawEnd = 0; |
| 161 | for (const chunk of stream.chunks) { |
| 162 | if (!range.intersectsNode(chunk.node)) continue; |
| 163 | const start = range.startContainer === chunk.node ? range.startOffset : 0; |
| 164 | const end = range.endContainer === chunk.node ? range.endOffset : chunk.end - chunk.start; |
| 165 | if (start === end) continue; |
| 166 | rawStart ??= chunk.start + start; |
| 167 | rawEnd = chunk.start + end; |
| 168 | } |
| 169 | if (rawStart === null) return null; |
| 170 | const selector = createAssistantTextSelector(stream.text, rawStart, rawEnd); |
| 171 | return selector === null ? null : { source, selector, range }; |
| 172 | } |
| 173 | |
| 174 | /** How much of a response a reply carries: enough to recognise it, not to resend it. */ |
| 175 | const RESPONSE_OPENING_LENGTH = 300; |
| 176 | |
| 177 | /** The opening of a response. Falls back to the raw text when the source is virtualized away or |
| 178 | * renders no text, as in an image-only response. */ |
| 179 | export function captureAssistantMessageOpening( |
| 180 | source: HTMLElement | null, |
| 181 | fallbackText: string, |
| 182 | ): AssistantTextSelector | null { |
| 183 | const rendered = source ? readAssistantText(source).text : ""; |
| 184 | const text = rendered.trim() ? rendered : fallbackText; |
| 185 | const rawStart = text.length - text.trimStart().length; |
| 186 | let rawEnd = Math.min(text.trimEnd().length, rawStart + RESPONSE_OPENING_LENGTH); |
| 187 | if (splitsSurrogatePair(text, rawEnd)) rawEnd -= 1; |
| 188 | return createAssistantTextSelector(text, rawStart, rawEnd); |
| 189 | } |
| 190 | |
| 191 | function rawTextOffset(text: string, normalizedOffset: number): number { |
| 192 | let offset = 0; |
| 193 | for (const match of text.matchAll(/\s+|\S+/g)) { |
| 194 | const whitespace = /\s/.test(match[0][0]!); |
| 195 | const length = whitespace ? 1 : match[0].length; |
| 196 | if (normalizedOffset <= offset + length) { |
| 197 | return ( |
| 198 | match.index + |
| 199 | (whitespace && normalizedOffset > offset ? match[0].length : normalizedOffset - offset) |
| 200 | ); |
| 201 | } |
| 202 | offset += length; |
| 203 | } |
| 204 | return text.length; |
| 205 | } |
| 206 | |
| 207 | export function resolveAssistantCitationRange( |
| 208 | root: HTMLElement, |
| 209 | selector: AssistantTextSelector, |
| 210 | ): Range | null { |
| 211 | if (excludedAncestor(root) !== null) return null; |
| 212 | const stream = readAssistantText(root); |
| 213 | const match = findAssistantCitationText(stream.text, selector); |
| 214 | if (match === null) return null; |
| 215 | |
| 216 | const start = rawTextOffset(stream.text, match.start); |
| 217 | const end = rawTextOffset(stream.text, match.end); |
| 218 | const first = stream.chunks.find((chunk) => chunk.end > start); |
| 219 | const last = stream.chunks.findLast((chunk) => chunk.start < end); |
| 220 | if (first === undefined || last === undefined) return null; |
| 221 | |
| 222 | const range = root.ownerDocument.createRange(); |
| 223 | // A match that touches a formula covers the formula as rendered. |
| 224 | if (isText(first.node)) range.setStart(first.node, Math.max(0, start - first.start)); |
| 225 | else range.setStartBefore(first.node); |
| 226 | if (isText(last.node)) range.setEnd(last.node, Math.min(last.node.length, end - last.start)); |
| 227 | else range.setEndAfter(last.node); |
| 228 | return isUsableRange(root, range) ? range : null; |
| 229 | } |