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 { |
| 2 | ASSISTANT_CITATION_MAX_TEXT_LENGTH, |
| 3 | MessageId, |
| 4 | type AssistantCitation, |
| 5 | type ScopedThreadRef, |
| 6 | } from "@t3tools/contracts"; |
| 7 | import { useGT } from "gt-react"; |
| 8 | import { QuoteIcon } from "lucide-react"; |
| 9 | import { use, useEffect, useLayoutEffect, useRef, useState } from "react"; |
| 10 | import { createPortal } from "react-dom"; |
| 11 | import { |
| 12 | captureAssistantTextSelection, |
| 13 | type AssistantCitationSourceAnchor, |
| 14 | } from "~/lib/assistantTextSelection"; |
| 15 | import { |
| 16 | isSelectionRectVisible, |
| 17 | observeSelectionActions, |
| 18 | resolveSelectionActionPosition, |
| 19 | type SelectionActionPoint, |
| 20 | } from "~/lib/selectionActions"; |
| 21 | import { Button } from "../ui/button"; |
| 22 | import { BackgroundThreadContext } from "./backgroundThread"; |
| 23 | |
| 24 | export function AssistantSelectionToolbar({ |
| 25 | viewport, |
| 26 | threadRef, |
| 27 | onCite, |
| 28 | }: { |
| 29 | viewport: HTMLElement | null; |
| 30 | threadRef: ScopedThreadRef; |
| 31 | onCite: (citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor) => boolean; |
| 32 | }) { |
| 33 | const [selection, setSelection] = useState<{ |
| 34 | citation: AssistantCitation; |
| 35 | position: SelectionActionPoint; |
| 36 | sourceAnchor: AssistantCitationSourceAnchor; |
| 37 | } | null>(null); |
| 38 | const toolbarRef = useRef<HTMLButtonElement>(null); |
| 39 | const actionsRef = useRef<ReturnType<typeof observeSelectionActions> | null>(null); |
| 40 | const backgroundThread = use(BackgroundThreadContext); |
| 41 | const gt = useGT(); |
| 42 | |
| 43 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the toolbar DOM node and clamps its position inside the window before paint |
| 44 | useLayoutEffect(() => { |
| 45 | const toolbar = toolbarRef.current; |
| 46 | if (!toolbar || !selection) return; |
| 47 | const rect = toolbar.getBoundingClientRect(); |
| 48 | toolbar.style.left = `${Math.max(8, Math.min(selection.position.x, window.innerWidth - rect.width - 8))}px`; |
| 49 | toolbar.style.top = `${Math.max(8, Math.min(selection.position.y, window.innerHeight - rect.height - 8))}px`; |
| 50 | }, [selection]); |
| 51 | |
| 52 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to document selectionchange and keydown to track text selections in the viewport |
| 53 | useEffect(() => { |
| 54 | if (!viewport) return; |
| 55 | const clear = () => setSelection(null); |
| 56 | const update = (pointer: SelectionActionPoint | null) => { |
| 57 | const nativeSelection = window.getSelection(); |
| 58 | const captured = captureAssistantTextSelection(viewport, nativeSelection); |
| 59 | const messageId = captured?.source.dataset.assistantCitationSource; |
| 60 | if (!captured || !messageId) { |
| 61 | clear(); |
| 62 | return; |
| 63 | } |
| 64 | const rect = captured.range.getBoundingClientRect(); |
| 65 | const viewportRect = viewport.getBoundingClientRect(); |
| 66 | if (!isSelectionRectVisible(rect, [viewportRect])) { |
| 67 | clear(); |
| 68 | return; |
| 69 | } |
| 70 | // A selection can cross blocks with different clipping ancestors. |
| 71 | const common = captured.range.commonAncestorContainer; |
| 72 | const walker = document.createTreeWalker(common, NodeFilter.SHOW_TEXT); |
| 73 | let node = common.nodeType === Node.TEXT_NODE ? common : walker.nextNode(); |
| 74 | let visible = false; |
| 75 | for (; node && !visible; node = walker.nextNode()) { |
| 76 | if (!captured.range.intersectsNode(node)) continue; |
| 77 | if (node.parentElement && getComputedStyle(node.parentElement).userSelect === "none") |
| 78 | continue; |
| 79 | const fragment = document.createRange(); |
| 80 | fragment.selectNodeContents(node); |
| 81 | if (node === captured.range.startContainer) { |
| 82 | fragment.setStart(node, captured.range.startOffset); |
| 83 | } |
| 84 | if (node === captured.range.endContainer) { |
| 85 | fragment.setEnd(node, captured.range.endOffset); |
| 86 | } |
| 87 | if (!fragment.toString().trim()) continue; |
| 88 | const lines = Array.from(fragment.getClientRects()); |
| 89 | if (!lines.some((line) => isSelectionRectVisible(line, [viewportRect]))) continue; |
| 90 | const clips: Pick<DOMRect, "left" | "right" | "top" | "bottom">[] = [viewportRect]; |
| 91 | for ( |
| 92 | let element = node.parentElement; |
| 93 | element && element !== viewport; |
| 94 | element = element.parentElement |
| 95 | ) { |
| 96 | const style = getComputedStyle(element); |
| 97 | const clipX = style.overflowX !== "visible"; |
| 98 | const clipY = style.overflowY !== "visible"; |
| 99 | if (!clipX && !clipY) continue; |
| 100 | const bounds = element.getBoundingClientRect(); |
| 101 | const left = bounds.left + element.clientLeft; |
| 102 | const top = bounds.top + element.clientTop; |
| 103 | clips.push({ |
| 104 | left: clipX ? left : -Infinity, |
| 105 | right: clipX ? left + element.clientWidth : Infinity, |
| 106 | top: clipY ? top : -Infinity, |
| 107 | bottom: clipY ? top + element.clientHeight : Infinity, |
| 108 | }); |
| 109 | } |
| 110 | visible = lines.some((line) => isSelectionRectVisible(line, clips)); |
| 111 | } |
| 112 | if (!visible) { |
| 113 | clear(); |
| 114 | return; |
| 115 | } |
| 116 | const rects = captured.range.getClientRects(); |
| 117 | const pointerOnText = |
| 118 | pointer !== null && |
| 119 | Array.from(rects).some( |
| 120 | (line) => |
| 121 | pointer.x >= line.left - 8 && |
| 122 | pointer.x <= line.right + 8 && |
| 123 | pointer.y >= line.top - 8 && |
| 124 | pointer.y <= line.bottom + 8, |
| 125 | ); |
| 126 | setSelection({ |
| 127 | sourceAnchor: { source: captured.source, range: captured.range, viewport }, |
| 128 | citation: { |
| 129 | version: 1, |
| 130 | ...threadRef, |
| 131 | messageId: MessageId.make(messageId), |
| 132 | ...captured.selector, |
| 133 | }, |
| 134 | position: resolveSelectionActionPosition({ |
| 135 | bounds: viewportRect, |
| 136 | selectionRect: rects.item(rects.length - 1) ?? rect, |
| 137 | pointer: pointerOnText ? pointer : null, |
| 138 | viewport: { width: window.innerWidth, height: window.innerHeight }, |
| 139 | }), |
| 140 | }); |
| 141 | }; |
| 142 | const actions = observeSelectionActions({ |
| 143 | element: viewport, |
| 144 | getActionElement: () => toolbarRef.current, |
| 145 | restoreAfterScroll: true, |
| 146 | onSelection: update, |
| 147 | onDismiss: clear, |
| 148 | }); |
| 149 | actionsRef.current = actions; |
| 150 | const focusActions = (event: KeyboardEvent) => { |
| 151 | const toolbar = toolbarRef.current; |
| 152 | if ( |
| 153 | event.key !== "Tab" || |
| 154 | event.shiftKey || |
| 155 | event.altKey || |
| 156 | event.ctrlKey || |
| 157 | event.metaKey || |
| 158 | event.isComposing || |
| 159 | event.defaultPrevented || |
| 160 | !toolbar || |
| 161 | toolbar.contains(event.target as Node) |
| 162 | ) { |
| 163 | return; |
| 164 | } |
| 165 | if (toolbar.disabled) return; |
| 166 | event.preventDefault(); |
| 167 | event.stopPropagation(); |
| 168 | toolbar.focus({ preventScroll: true }); |
| 169 | }; |
| 170 | // Tab belongs to the foreground chat; a background timeline only follows its selection. |
| 171 | if (!backgroundThread) document.addEventListener("keydown", focusActions, true); |
| 172 | document.addEventListener("selectionchange", actions.selectionChanged); |
| 173 | return () => { |
| 174 | document.removeEventListener("keydown", focusActions, true); |
| 175 | document.removeEventListener("selectionchange", actions.selectionChanged); |
| 176 | actions.dispose(); |
| 177 | actionsRef.current = null; |
| 178 | }; |
| 179 | }, [backgroundThread, threadRef, viewport]); |
| 180 | |
| 181 | if (!selection) return null; |
| 182 | const tooLong = selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH; |
| 183 | const dismiss = () => { |
| 184 | actionsRef.current?.cancel(); |
| 185 | setSelection(null); |
| 186 | }; |
| 187 | const cite = () => { |
| 188 | if (tooLong || !onCite(selection.citation, selection.sourceAnchor)) return false; |
| 189 | window.getSelection()?.removeAllRanges(); |
| 190 | dismiss(); |
| 191 | return true; |
| 192 | }; |
| 193 | return createPortal( |
| 194 | <Button |
| 195 | ref={toolbarRef} |
| 196 | type="button" |
| 197 | size="xs" |
| 198 | variant="glass" |
| 199 | disabled={tooLong} |
| 200 | aria-label={tooLong ? gt("Selection is too long to cite") : gt("Cite selection in composer")} |
| 201 | className="fixed z-50 max-w-[calc(100vw-1rem)]" |
| 202 | style={{ left: selection.position.x, top: selection.position.y }} |
| 203 | onPointerDown={(event) => event.preventDefault()} |
| 204 | onClick={cite} |
| 205 | onKeyDown={(event) => { |
| 206 | event.stopPropagation(); |
| 207 | if (event.key === "Escape" && !event.nativeEvent.isComposing) { |
| 208 | event.preventDefault(); |
| 209 | dismiss(); |
| 210 | } |
| 211 | }} |
| 212 | > |
| 213 | <QuoteIcon aria-hidden="true" className="size-3.5" /> |
| 214 | {tooLong |
| 215 | ? gt("Shorten selection") |
| 216 | : gt("Cite", { $context: "verb, button that quotes the selected text" })} |
| 217 | </Button>, |
| 218 | document.body, |
| 219 | ); |
| 220 | } |