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 { scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 2 | import type { AssistantCitation, ResponseContextRecord } from "@t3tools/contracts"; |
| 3 | import { |
| 4 | assistantCitationLabel, |
| 5 | serializeAssistantCitation, |
| 6 | } from "@t3tools/shared/assistantCitations"; |
| 7 | import { Link, useNavigate } from "@tanstack/react-router"; |
| 8 | import { useGT } from "gt-react"; |
| 9 | import { PencilIcon, QuoteIcon } from "lucide-react"; |
| 10 | import { |
| 11 | useEffect, |
| 12 | useEffectEvent, |
| 13 | useRef, |
| 14 | useState, |
| 15 | type MouseEvent as ReactMouseEvent, |
| 16 | type ReactNode, |
| 17 | } from "react"; |
| 18 | import { |
| 19 | findAssistantCitationSourceAnchor, |
| 20 | type AssistantCitationSourceAnchor, |
| 21 | } from "~/lib/assistantTextSelection"; |
| 22 | import { |
| 23 | assistantCitationNavigation, |
| 24 | assistantCitationRoute, |
| 25 | } from "../../lib/assistantCitationNavigation"; |
| 26 | import { cn } from "~/lib/utils"; |
| 27 | import { useQuietThreadShell } from "~/state/entities"; |
| 28 | import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip"; |
| 29 | import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; |
| 30 | import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor"; |
| 31 | import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal"; |
| 32 | import { observeAssistantCitationCommentSource } from "./AssistantCitationSource"; |
| 33 | import { composerFloatingLayerProps } from "./composerEventScope"; |
| 34 | import { textDirection } from "~/textDirection"; |
| 35 | |
| 36 | function useCitationSourceLinkProps(citation: AssistantCitation) { |
| 37 | const navigate = useNavigate(); |
| 38 | const sourceThread = useQuietThreadShell( |
| 39 | scopeThreadRef(citation.environmentId, citation.threadId), |
| 40 | ); |
| 41 | return { |
| 42 | ...assistantCitationRoute(citation, sourceThread), |
| 43 | "data-markdown-copy": serializeAssistantCitation(citation), |
| 44 | onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => { |
| 45 | if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { |
| 46 | return; |
| 47 | } |
| 48 | event.preventDefault(); |
| 49 | void navigate(assistantCitationNavigation(citation, sourceThread)); |
| 50 | }, |
| 51 | }; |
| 52 | } |
| 53 | |
| 54 | const flat = (text: string) => text.replace(/\s+/g, " "); |
| 55 | |
| 56 | /** |
| 57 | * The card a response shows as inside a message. Clicking it goes to the source; a comment follows |
| 58 | * as text. `leading` and `trailing` say it starts or ends its block, which already has spacing. |
| 59 | */ |
| 60 | function ResponseCard({ |
| 61 | citation, |
| 62 | copyMarkdown, |
| 63 | cardCopyMarkdown = copyMarkdown, |
| 64 | label, |
| 65 | title, |
| 66 | preview, |
| 67 | comment, |
| 68 | leading, |
| 69 | trailing, |
| 70 | }: { |
| 71 | citation: AssistantCitation; |
| 72 | copyMarkdown: string; |
| 73 | cardCopyMarkdown?: string; |
| 74 | label: string; |
| 75 | title?: string | undefined; |
| 76 | preview: ReactNode; |
| 77 | comment?: string | undefined; |
| 78 | leading: boolean; |
| 79 | trailing: boolean; |
| 80 | }) { |
| 81 | const linkProps = useCitationSourceLinkProps(citation); |
| 82 | return ( |
| 83 | // One copy boundary for the card and its comment, so a copied card carries the comment once. |
| 84 | <span |
| 85 | data-markdown-copy={copyMarkdown} |
| 86 | className={cn("block", !leading && "mt-[0.65rem]", !trailing && "mb-[0.65rem]")} |
| 87 | > |
| 88 | <Link |
| 89 | {...linkProps} |
| 90 | // A selection inside the card's boundary copies the card here and the comment as text. |
| 91 | data-markdown-copy={cardCopyMarkdown} |
| 92 | // The response is findable in its own message; here it is clamped and mostly hidden. |
| 93 | data-thread-find-ignore |
| 94 | aria-label={label} |
| 95 | // The message's markdown styles colour and underline links; a card is neither. |
| 96 | className="block min-w-0 rounded-lg bg-black/10 px-2.5 py-1.5 text-start text-sm text-muted-foreground! no-underline! wrap-break-word hover:bg-black/14 focus-visible:outline-2 focus-visible:outline-ring dark:bg-black/35 dark:hover:bg-black/50" |
| 97 | > |
| 98 | {title ? ( |
| 99 | <span className="block truncate text-xs font-medium text-foreground/80" dir="auto"> |
| 100 | {title} |
| 101 | </span> |
| 102 | ) : null} |
| 103 | <span className="line-clamp-2" dir={textDirection(citation.text)}> |
| 104 | {preview} |
| 105 | </span> |
| 106 | </Link> |
| 107 | {comment ? ( |
| 108 | <span className="mt-1.5 block whitespace-pre-wrap" dir={textDirection(comment)}> |
| 109 | {comment} |
| 110 | </span> |
| 111 | ) : null} |
| 112 | </span> |
| 113 | ); |
| 114 | } |
| 115 | |
| 116 | /** A passage quoted from a response, with its surrounding context and the user's comment. */ |
| 117 | export function AssistantCitationEmbed({ |
| 118 | citation, |
| 119 | leading, |
| 120 | trailing, |
| 121 | }: { |
| 122 | citation: AssistantCitation; |
| 123 | leading: boolean; |
| 124 | trailing: boolean; |
| 125 | }) { |
| 126 | const gt = useGT(); |
| 127 | const wholeResponse = citation.prefix === "" && citation.suffix === ""; |
| 128 | const { comment, ...quoted } = citation; |
| 129 | return ( |
| 130 | <ResponseCard |
| 131 | citation={citation} |
| 132 | copyMarkdown={serializeAssistantCitation(citation)} |
| 133 | cardCopyMarkdown={serializeAssistantCitation(quoted)} |
| 134 | label={gt("Go to quoted response: {label}", { label: assistantCitationLabel(quoted) })} |
| 135 | comment={comment} |
| 136 | leading={leading} |
| 137 | trailing={trailing} |
| 138 | preview={ |
| 139 | wholeResponse ? ( |
| 140 | flat(citation.text) |
| 141 | ) : ( |
| 142 | <> |
| 143 | {citation.prefix ? `…${flat(citation.prefix)}` : null} |
| 144 | <mark className="rounded-sm bg-foreground/12 px-0.5 text-foreground"> |
| 145 | {flat(citation.text)} |
| 146 | </mark> |
| 147 | {citation.suffix ? `${flat(citation.suffix)}…` : null} |
| 148 | </> |
| 149 | ) |
| 150 | } |
| 151 | /> |
| 152 | ); |
| 153 | } |
| 154 | |
| 155 | /** The response a message replies to: its subagents, when it had any, and how it starts. */ |
| 156 | export function ResponseReplyCard({ |
| 157 | record, |
| 158 | copyMarkdown, |
| 159 | leading, |
| 160 | trailing, |
| 161 | }: { |
| 162 | record: ResponseContextRecord; |
| 163 | copyMarkdown: string; |
| 164 | leading: boolean; |
| 165 | trailing: boolean; |
| 166 | }) { |
| 167 | const gt = useGT(); |
| 168 | return ( |
| 169 | <ResponseCard |
| 170 | citation={record.citation} |
| 171 | copyMarkdown={copyMarkdown} |
| 172 | label={gt("Go to the response this replies to: {label}", { label: record.label })} |
| 173 | title={record.subagents?.map((subagent) => subagent.title).join(", ")} |
| 174 | preview={flat(record.citation.text)} |
| 175 | leading={leading} |
| 176 | trailing={trailing} |
| 177 | /> |
| 178 | ); |
| 179 | } |
| 180 | |
| 181 | /** The citation chip in the composer, with its comment editor. */ |
| 182 | export function AssistantCitationChip({ |
| 183 | citation, |
| 184 | commentEditor, |
| 185 | }: { |
| 186 | citation: AssistantCitation; |
| 187 | commentEditor?: { |
| 188 | open: boolean; |
| 189 | sourceAnchor?: AssistantCitationSourceAnchor | undefined; |
| 190 | onOpenChange: (open: boolean) => void; |
| 191 | onCancel?: () => void; |
| 192 | onSave: (comment: string) => boolean; |
| 193 | onSaveAndSend?: (comment: string) => boolean; |
| 194 | onDraftChange?: (comment: string) => void; |
| 195 | onRestoreFocus?: () => void; |
| 196 | }; |
| 197 | }) { |
| 198 | const gt = useGT(); |
| 199 | const sourceLinkProps = useCitationSourceLinkProps(citation); |
| 200 | const commentInputRef = useRef<HTMLTextAreaElement>(null); |
| 201 | const commentPopupRef = useRef<HTMLDivElement>(null); |
| 202 | const draftCommentRef = useRef<string | null>(null); |
| 203 | const [voiceSetupOpen, setVoiceSetupOpen] = useState(false); |
| 204 | const [unavailableSourceAnchor, setUnavailableSourceAnchor] = |
| 205 | useState<AssistantCitationSourceAnchor | null>(null); |
| 206 | const commentOpen = commentEditor?.open ?? false; |
| 207 | const sourceAnchor = commentEditor?.sourceAnchor; |
| 208 | const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor; |
| 209 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drops the uncommitted comment draft held in a ref once the parent closes the comment editor |
| 210 | useEffect(() => { |
| 211 | if (!commentOpen) draftCommentRef.current = null; |
| 212 | }, [commentOpen]); |
| 213 | const settleDraftOnClose = (reason: string): boolean => { |
| 214 | const dismissal = resolveAssistantCitationCommentDismissal({ |
| 215 | reason, |
| 216 | draft: draftCommentRef.current, |
| 217 | savedComment: citation.comment, |
| 218 | }); |
| 219 | if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true; |
| 220 | return dismissal.kind !== "keep-open"; |
| 221 | }; |
| 222 | const onSourceUnavailable = useEffectEvent(() => { |
| 223 | if (!sourceAnchor) return; |
| 224 | if (settleDraftOnClose("none")) { |
| 225 | commentEditor?.onOpenChange(false); |
| 226 | } else { |
| 227 | setUnavailableSourceAnchor(sourceAnchor); |
| 228 | } |
| 229 | }); |
| 230 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes the cited DOM source while the comment editor is open and reacts when it disappears |
| 231 | useEffect(() => { |
| 232 | if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return; |
| 233 | const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation); |
| 234 | if (!anchor) return; |
| 235 | return observeAssistantCitationCommentSource({ |
| 236 | anchor, |
| 237 | citation, |
| 238 | onUnavailable: onSourceUnavailable, |
| 239 | }); |
| 240 | }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]); |
| 241 | const popupAnchor = activeSourceAnchor |
| 242 | ? { |
| 243 | contextElement: activeSourceAnchor.source, |
| 244 | getBoundingClientRect: () => { |
| 245 | const rects = activeSourceAnchor.range.getClientRects(); |
| 246 | const rect = |
| 247 | rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect(); |
| 248 | // Code blocks and tables scroll sideways inside the message, so the cited |
| 249 | // text can end in their hidden overflow. Base UI only shifts the popup while |
| 250 | // it still touches the anchor, so clamp the anchor to the message's width. |
| 251 | const bounds = activeSourceAnchor.source.getBoundingClientRect(); |
| 252 | const left = Math.min(Math.max(rect.left, bounds.left), bounds.right); |
| 253 | const right = Math.max(Math.min(rect.right, bounds.right), left); |
| 254 | return new DOMRect(left, rect.top, right - left, rect.height); |
| 255 | }, |
| 256 | } |
| 257 | : undefined; |
| 258 | const label = assistantCitationLabel(citation); |
| 259 | const composerSourceLink = ( |
| 260 | <Link |
| 261 | {...sourceLinkProps} |
| 262 | className="inline-flex min-w-0 items-center gap-[0.2em] self-baseline text-inherit no-underline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-current rounded-sm" |
| 263 | aria-label={gt("View cited assistant text: {label}", { label })} |
| 264 | > |
| 265 | <QuoteIcon aria-hidden="true" /> |
| 266 | <ContextChipLabel className="max-w-[16em]" dir={textDirection(label)}> |
| 267 | {label} |
| 268 | </ContextChipLabel> |
| 269 | </Link> |
| 270 | ); |
| 271 | return ( |
| 272 | <ContextChip |
| 273 | kind="citation" |
| 274 | contentEditable={false} |
| 275 | data-assistant-citation-chip="true" |
| 276 | data-markdown-copy={serializeAssistantCitation(citation)} |
| 277 | > |
| 278 | {composerSourceLink} |
| 279 | {commentEditor ? ( |
| 280 | <Popover |
| 281 | open={commentEditor.open && !voiceSetupOpen} |
| 282 | onOpenChange={(open, eventDetails) => { |
| 283 | if (!open && !settleDraftOnClose(eventDetails.reason)) { |
| 284 | eventDetails.cancel(); |
| 285 | return; |
| 286 | } |
| 287 | commentEditor.onOpenChange(open); |
| 288 | }} |
| 289 | > |
| 290 | <PopoverTrigger |
| 291 | aria-label={ |
| 292 | citation.comment ? gt("Edit citation comment") : gt("Add comment to citation") |
| 293 | } |
| 294 | data-citation-comment-trigger="true" |
| 295 | render={<ContextChipAction />} |
| 296 | > |
| 297 | <PencilIcon aria-hidden="true" /> |
| 298 | </PopoverTrigger> |
| 299 | {commentEditor.open ? ( |
| 300 | <PopoverPopup |
| 301 | // The editor stays mounted while its voice setup dialog replaces the popover. |
| 302 | keepMounted |
| 303 | {...composerFloatingLayerProps} |
| 304 | side={activeSourceAnchor ? "bottom" : "top"} |
| 305 | align="end" |
| 306 | anchor={popupAnchor} |
| 307 | initialFocus={() => { |
| 308 | const input = commentInputRef.current; |
| 309 | if (input) { |
| 310 | input.focus({ preventScroll: true }); |
| 311 | input.setSelectionRange(input.value.length, input.value.length); |
| 312 | // Moving the caret doesn't scroll a long comment to it. |
| 313 | input.scrollTop = input.scrollHeight; |
| 314 | } |
| 315 | return false; |
| 316 | }} |
| 317 | finalFocus={ |
| 318 | commentEditor.onRestoreFocus |
| 319 | ? () => { |
| 320 | const activeElement = document.activeElement; |
| 321 | if ( |
| 322 | activeElement === document.body || |
| 323 | (activeElement !== null && commentPopupRef.current?.contains(activeElement)) |
| 324 | ) { |
| 325 | commentEditor.onRestoreFocus?.(); |
| 326 | } |
| 327 | return false; |
| 328 | } |
| 329 | : undefined |
| 330 | } |
| 331 | ref={commentPopupRef} |
| 332 | aria-label={gt("Edit citation comment")} |
| 333 | width="md" |
| 334 | padding="compact" |
| 335 | onPointerDown={(event) => event.stopPropagation()} |
| 336 | > |
| 337 | <AssistantCitationCommentEditor |
| 338 | key={serializeAssistantCitation(citation)} |
| 339 | citation={citation} |
| 340 | inputRef={commentInputRef} |
| 341 | onVoiceSetupOpenChange={setVoiceSetupOpen} |
| 342 | onDraftChange={(comment) => { |
| 343 | draftCommentRef.current = comment; |
| 344 | commentEditor.onDraftChange?.(comment); |
| 345 | }} |
| 346 | onSubmit={(comment) => { |
| 347 | if (!commentEditor.onSave(comment)) return false; |
| 348 | commentEditor.onOpenChange(false); |
| 349 | return true; |
| 350 | }} |
| 351 | {...(commentEditor.onSaveAndSend |
| 352 | ? { |
| 353 | onSubmitAndSend: (comment: string) => { |
| 354 | if (!commentEditor.onSaveAndSend?.(comment)) return false; |
| 355 | commentEditor.onOpenChange(false); |
| 356 | return true; |
| 357 | }, |
| 358 | } |
| 359 | : {})} |
| 360 | onCancel={() => { |
| 361 | if (commentEditor.onCancel) { |
| 362 | commentEditor.onCancel(); |
| 363 | } else { |
| 364 | commentEditor.onOpenChange(false); |
| 365 | } |
| 366 | }} |
| 367 | /> |
| 368 | </PopoverPopup> |
| 369 | ) : null} |
| 370 | </Popover> |
| 371 | ) : null} |
| 372 | </ContextChip> |
| 373 | ); |
| 374 | } |