The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import type { LegendListRef } from "@legendapp/list/react"; |
| 2 | import type { AssistantCitation, MessageId, ScopedThreadRef } from "@t3tools/contracts"; |
| 3 | import { msg } from "gt-react"; |
| 4 | import { useEffect, useRef, type ReactNode, type RefObject } from "react"; |
| 5 | import { |
| 6 | resolveAssistantCitationRange, |
| 7 | type AssistantCitationSourceAnchor, |
| 8 | } from "~/lib/assistantTextSelection"; |
| 9 | import { m } from "~/i18n/messages"; |
| 10 | import { toastManager } from "../ui/toast"; |
| 11 | import { observeResize } from "~/lib/observeResize"; |
| 12 | |
| 13 | const CITATION_PULSE_DURATION_MS = 650; |
| 14 | const CITATION_HIGHLIGHT_HOLD_MS = 1575; |
| 15 | const CITATION_HIGHLIGHT_FADE_MS = 450; |
| 16 | const CITATION_HIGHLIGHT_TOTAL_MS = |
| 17 | 1.5 * CITATION_PULSE_DURATION_MS + CITATION_HIGHLIGHT_HOLD_MS + CITATION_HIGHLIGHT_FADE_MS; |
| 18 | const CITATION_HIGHLIGHT_OPACITY = "--assistant-citation-highlight-opacity"; |
| 19 | const CITATION_HIGHLIGHT_PEAK = 0.45; |
| 20 | const COMMENT_HIGHLIGHT_NAME = "t3-assistant-citation-comment"; |
| 21 | |
| 22 | export function observeAssistantCitationCommentSource({ |
| 23 | anchor, |
| 24 | citation, |
| 25 | onUnavailable, |
| 26 | }: { |
| 27 | anchor: AssistantCitationSourceAnchor; |
| 28 | citation: AssistantCitation; |
| 29 | onUnavailable: () => void; |
| 30 | }): () => void { |
| 31 | const { source, range, viewport } = anchor; |
| 32 | const registry = typeof CSS !== "undefined" ? CSS.highlights : undefined; |
| 33 | let highlight: Highlight | null = null; |
| 34 | let stopped = false; |
| 35 | const observer = new MutationObserver((records) => { |
| 36 | if (stopped) return; |
| 37 | const sourceChanged = records.some((record) => source.contains(record.target)); |
| 38 | validate(sourceChanged); |
| 39 | }); |
| 40 | const dispose = () => { |
| 41 | if (stopped) return; |
| 42 | stopped = true; |
| 43 | observer.disconnect(); |
| 44 | if (!highlight) return; |
| 45 | highlight.delete(range); |
| 46 | if (highlight.size === 0 && registry?.get(COMMENT_HIGHLIGHT_NAME) === highlight) { |
| 47 | registry.delete(COMMENT_HIGHLIGHT_NAME); |
| 48 | } |
| 49 | }; |
| 50 | const unavailable = () => { |
| 51 | if (stopped) return; |
| 52 | dispose(); |
| 53 | onUnavailable(); |
| 54 | }; |
| 55 | const validate = (sourceChanged: boolean): boolean => { |
| 56 | if (!source.isConnected || !viewport.contains(source)) { |
| 57 | unavailable(); |
| 58 | return false; |
| 59 | } |
| 60 | if ( |
| 61 | sourceChanged || |
| 62 | range.collapsed || |
| 63 | !source.contains(range.startContainer) || |
| 64 | !source.contains(range.endContainer) |
| 65 | ) { |
| 66 | const repaired = resolveAssistantCitationRange(source, citation); |
| 67 | if (!repaired) { |
| 68 | unavailable(); |
| 69 | return false; |
| 70 | } |
| 71 | range.setStart(repaired.startContainer, repaired.startOffset); |
| 72 | range.setEnd(repaired.endContainer, repaired.endOffset); |
| 73 | } |
| 74 | return true; |
| 75 | }; |
| 76 | |
| 77 | if (!validate(false)) return dispose; |
| 78 | if (typeof Highlight !== "undefined" && registry) { |
| 79 | const existing = registry.get(COMMENT_HIGHLIGHT_NAME); |
| 80 | highlight = existing ?? new Highlight(); |
| 81 | highlight.add(range); |
| 82 | if (!existing) registry.set(COMMENT_HIGHLIGHT_NAME, highlight); |
| 83 | } |
| 84 | observer.observe(viewport, { childList: true, subtree: true, characterData: true }); |
| 85 | return dispose; |
| 86 | } |
| 87 | |
| 88 | export interface AssistantCitationRequest { |
| 89 | citation: AssistantCitation; |
| 90 | key: string; |
| 91 | } |
| 92 | |
| 93 | /** Navigation owns activation state across virtual row remounts. */ |
| 94 | export interface AssistantCitationTarget extends AssistantCitationRequest { |
| 95 | activationRef: RefObject<{ |
| 96 | scrolled: boolean; |
| 97 | dismissed: boolean; |
| 98 | cancelScroll?: () => void; |
| 99 | pulse?: { startedAt: number; reducedMotion: boolean }; |
| 100 | }>; |
| 101 | onComplete: () => void; |
| 102 | } |
| 103 | |
| 104 | function observeAssistantCitationSource({ |
| 105 | root, |
| 106 | itemKey, |
| 107 | request, |
| 108 | list, |
| 109 | }: { |
| 110 | root: HTMLElement; |
| 111 | itemKey: string; |
| 112 | request: AssistantCitationTarget; |
| 113 | list: LegendListRef; |
| 114 | }) { |
| 115 | const activation = request.activationRef.current; |
| 116 | if (activation.dismissed) return; |
| 117 | const scrollNode = list.getScrollableNode(); |
| 118 | if (!(scrollNode instanceof HTMLElement)) return; |
| 119 | const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; |
| 120 | let highlighted: Highlight | null = null; |
| 121 | let ownedRange: Range | null = null; |
| 122 | let selected: { range: Range; snapshot: Range } | null = null; |
| 123 | let frame: number | null = null; |
| 124 | let scrolling = false; |
| 125 | let stopped = false; |
| 126 | let pulseAnimation: Animation | null = null; |
| 127 | let canReplaceSelection = !activation.scrolled; |
| 128 | const ownsSelection = (selection: Selection | null) => |
| 129 | selected !== null && |
| 130 | selection?.rangeCount === 1 && |
| 131 | selection.getRangeAt(0) === selected.range && |
| 132 | selected.range.startContainer === selected.snapshot.startContainer && |
| 133 | selected.range.startOffset === selected.snapshot.startOffset && |
| 134 | selected.range.endContainer === selected.snapshot.endContainer && |
| 135 | selected.range.endOffset === selected.snapshot.endOffset; |
| 136 | const clear = () => { |
| 137 | if (highlighted && CSS.highlights.get("t3-assistant-citation") === highlighted) { |
| 138 | CSS.highlights.delete("t3-assistant-citation"); |
| 139 | } |
| 140 | highlighted = null; |
| 141 | ownedRange = null; |
| 142 | const selection = selected ? root.ownerDocument.getSelection() : null; |
| 143 | if (selected && ownsSelection(selection)) selection?.removeRange(selected.range); |
| 144 | selected = null; |
| 145 | delete root.dataset.citationHighlighted; |
| 146 | }; |
| 147 | const finishHighlight = () => { |
| 148 | if (stopped) return; |
| 149 | activation.dismissed = true; |
| 150 | dispose(); |
| 151 | }; |
| 152 | const highlight = () => { |
| 153 | frame = null; |
| 154 | if (stopped || activation.dismissed || !root.isConnected || !scrollNode.contains(root)) { |
| 155 | clear(); |
| 156 | return; |
| 157 | } |
| 158 | if ( |
| 159 | activation.pulse && |
| 160 | performance.now() - activation.pulse.startedAt >= CITATION_HIGHLIGHT_TOTAL_MS |
| 161 | ) { |
| 162 | finishHighlight(); |
| 163 | return; |
| 164 | } |
| 165 | const state = list.getState(); |
| 166 | const index = state.indexByKey(itemKey); |
| 167 | if (index === undefined || !(state.sizeAtIndex(index) > 0)) return; |
| 168 | const range = resolveAssistantCitationRange(root, request.citation); |
| 169 | const rect = (range ?? root).getBoundingClientRect(); |
| 170 | if (rect.height <= 0 || scrollNode.clientHeight <= 0) { |
| 171 | clear(); |
| 172 | return; |
| 173 | } |
| 174 | if (!activation.scrolled) { |
| 175 | if (scrolling) return; |
| 176 | const scrollRect = scrollNode.getBoundingClientRect(); |
| 177 | const offset = Math.max( |
| 178 | 0, |
| 179 | Math.min( |
| 180 | scrollNode.scrollHeight - scrollNode.clientHeight, |
| 181 | state.scroll + rect.top - scrollRect.top - Math.min(120, scrollNode.clientHeight / 3), |
| 182 | ), |
| 183 | ); |
| 184 | if (Math.abs(offset - state.scroll) > 1) { |
| 185 | scrolling = true; |
| 186 | void list.scrollToOffset({ offset, animated: !reducedMotion }).then( |
| 187 | () => { |
| 188 | scrolling = false; |
| 189 | if (!stopped && !activation.dismissed) schedule(); |
| 190 | }, |
| 191 | () => { |
| 192 | scrolling = false; |
| 193 | if (stopped || activation.dismissed) return; |
| 194 | activation.dismissed = true; |
| 195 | clear(); |
| 196 | request.onComplete(); |
| 197 | toastManager.add({ |
| 198 | type: "warning", |
| 199 | title: m(msg("Could not open the cited response")), |
| 200 | description: m(msg("Click the citation to try again.")), |
| 201 | }); |
| 202 | }, |
| 203 | ); |
| 204 | return; |
| 205 | } |
| 206 | if (rect.bottom <= scrollRect.top || rect.top >= scrollRect.bottom) return; |
| 207 | activation.scrolled = true; |
| 208 | request.onComplete(); |
| 209 | // Screen readers follow focus, not scroll; leave someone already typing alone. |
| 210 | const active = root.ownerDocument.activeElement; |
| 211 | if ( |
| 212 | !(active instanceof HTMLElement) || |
| 213 | !(active.isContentEditable || active.matches("input, textarea, select")) |
| 214 | ) { |
| 215 | root.focus({ preventScroll: true }); |
| 216 | } |
| 217 | if (!range) { |
| 218 | toastManager.add({ |
| 219 | type: "warning", |
| 220 | title: m(msg("The quoted text has changed")), |
| 221 | description: m(msg("Showing the source response. The saved quote is unchanged.")), |
| 222 | }); |
| 223 | } |
| 224 | } |
| 225 | if (!range) { |
| 226 | finishHighlight(); |
| 227 | return; |
| 228 | } |
| 229 | if (typeof Highlight !== "undefined" && typeof CSS !== "undefined" && CSS.highlights) { |
| 230 | highlighted = new Highlight(range); |
| 231 | CSS.highlights.set("t3-assistant-citation", highlighted); |
| 232 | ownedRange = range; |
| 233 | root.dataset.citationHighlighted = "true"; |
| 234 | } else { |
| 235 | const selection = root.ownerDocument.getSelection(); |
| 236 | if (selection && (canReplaceSelection || ownsSelection(selection))) { |
| 237 | selection.removeAllRanges(); |
| 238 | selection.addRange(range); |
| 239 | selected = { range: selection.getRangeAt(0), snapshot: range.cloneRange() }; |
| 240 | canReplaceSelection = false; |
| 241 | ownedRange = range; |
| 242 | root.dataset.citationHighlighted = "true"; |
| 243 | } else { |
| 244 | finishHighlight(); |
| 245 | return; |
| 246 | } |
| 247 | } |
| 248 | if (!pulseAnimation) { |
| 249 | const pulse = (activation.pulse ??= { |
| 250 | startedAt: performance.now(), |
| 251 | reducedMotion, |
| 252 | }); |
| 253 | const at = (milliseconds: number) => milliseconds / CITATION_HIGHLIGHT_TOTAL_MS; |
| 254 | const holdEnd = at(CITATION_HIGHLIGHT_TOTAL_MS - CITATION_HIGHLIGHT_FADE_MS); |
| 255 | pulseAnimation = root.animate( |
| 256 | pulse.reducedMotion |
| 257 | ? [ |
| 258 | { offset: 0, [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK }, |
| 259 | { offset: holdEnd, [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK }, |
| 260 | { offset: 1, [CITATION_HIGHLIGHT_OPACITY]: 0 }, |
| 261 | ] |
| 262 | : [ |
| 263 | { offset: 0, [CITATION_HIGHLIGHT_OPACITY]: 0 }, |
| 264 | { |
| 265 | offset: at(CITATION_PULSE_DURATION_MS * 0.5), |
| 266 | [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK, |
| 267 | }, |
| 268 | { offset: at(CITATION_PULSE_DURATION_MS), [CITATION_HIGHLIGHT_OPACITY]: 0 }, |
| 269 | { |
| 270 | offset: at(CITATION_PULSE_DURATION_MS * 1.5), |
| 271 | [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK, |
| 272 | }, |
| 273 | { offset: holdEnd, [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK }, |
| 274 | { offset: 1, [CITATION_HIGHLIGHT_OPACITY]: 0 }, |
| 275 | ], |
| 276 | { duration: CITATION_HIGHLIGHT_TOTAL_MS, easing: "ease-in-out" }, |
| 277 | ); |
| 278 | pulseAnimation.id = "t3-assistant-citation-pulse"; |
| 279 | pulseAnimation.currentTime = Math.max(0, performance.now() - pulse.startedAt); |
| 280 | void pulseAnimation.finished.then(finishHighlight, () => {}); |
| 281 | } |
| 282 | }; |
| 283 | const schedule = () => { |
| 284 | if (frame !== null) cancelAnimationFrame(frame); |
| 285 | frame = requestAnimationFrame(highlight); |
| 286 | }; |
| 287 | const observer = new MutationObserver((records) => { |
| 288 | const rangeMoved = |
| 289 | ownedRange !== null && |
| 290 | (ownedRange.collapsed || |
| 291 | !root.contains(ownedRange.startContainer) || |
| 292 | !root.contains(ownedRange.endContainer)); |
| 293 | if (rangeMoved) { |
| 294 | canReplaceSelection ||= selected !== null && ownsSelection(root.ownerDocument.getSelection()); |
| 295 | clear(); |
| 296 | } |
| 297 | if ( |
| 298 | rangeMoved || |
| 299 | records.some( |
| 300 | (record) => |
| 301 | root.contains(record.target) || |
| 302 | [...record.addedNodes, ...record.removedNodes].some((node) => node.contains(root)), |
| 303 | ) |
| 304 | ) { |
| 305 | schedule(); |
| 306 | } |
| 307 | }); |
| 308 | observer.observe(scrollNode, { childList: true, characterData: true, subtree: true }); |
| 309 | const stopObservingResize = observeResize([root, scrollNode], schedule); |
| 310 | const state = list.getState(); |
| 311 | const unsubscribe = [ |
| 312 | state.listenToPosition(itemKey, schedule), |
| 313 | state.listen("totalSize", schedule), |
| 314 | state.listen("headerSize", schedule), |
| 315 | ]; |
| 316 | const cancelScroll = () => { |
| 317 | if (scrolling) { |
| 318 | scrolling = false; |
| 319 | void list.scrollToOffset({ |
| 320 | // Legend may defer reading the offset until after the user scrolls. |
| 321 | get offset() { |
| 322 | return scrollNode.scrollTop; |
| 323 | }, |
| 324 | animated: false, |
| 325 | }); |
| 326 | } |
| 327 | }; |
| 328 | activation.cancelScroll = cancelScroll; |
| 329 | schedule(); |
| 330 | const dispose = () => { |
| 331 | if (stopped) return; |
| 332 | stopped = true; |
| 333 | cancelScroll(); |
| 334 | pulseAnimation?.cancel(); |
| 335 | if (frame !== null) cancelAnimationFrame(frame); |
| 336 | observer.disconnect(); |
| 337 | stopObservingResize(); |
| 338 | for (const stop of unsubscribe) stop(); |
| 339 | if (activation.cancelScroll === cancelScroll) delete activation.cancelScroll; |
| 340 | clear(); |
| 341 | }; |
| 342 | return dispose; |
| 343 | } |
| 344 | |
| 345 | export function AssistantCitationSource({ |
| 346 | messageId, |
| 347 | threadRef, |
| 348 | itemKey, |
| 349 | request, |
| 350 | listRef, |
| 351 | children, |
| 352 | }: { |
| 353 | messageId: MessageId; |
| 354 | threadRef?: ScopedThreadRef; |
| 355 | itemKey: string; |
| 356 | request: AssistantCitationTarget | null; |
| 357 | listRef: RefObject<LegendListRef | null>; |
| 358 | children: ReactNode; |
| 359 | }) { |
| 360 | const rootRef = useRef<HTMLDivElement>(null); |
| 361 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes this message's DOM for a citation reveal request and scrolls the LegendList to it |
| 362 | useEffect(() => { |
| 363 | const root = rootRef.current; |
| 364 | const list = listRef.current; |
| 365 | if (!root || !list || !request || request.citation.messageId !== messageId) return; |
| 366 | return observeAssistantCitationSource({ root, itemKey, request, list }); |
| 367 | }, [itemKey, listRef, messageId, request]); |
| 368 | |
| 369 | return ( |
| 370 | <div |
| 371 | ref={rootRef} |
| 372 | tabIndex={-1} |
| 373 | className="outline-none" |
| 374 | data-assistant-citation-source={messageId} |
| 375 | data-assistant-citation-environment={threadRef?.environmentId} |
| 376 | data-assistant-citation-thread={threadRef?.threadId} |
| 377 | > |
| 378 | {children} |
| 379 | </div> |
| 380 | ); |
| 381 | } |