import { useId, useRef, useState } from "react"; import { SendAction } from "@chopin/editor"; import { InfoIcon, LoaderIcon, PlusIcon, WarningIcon } from "@chopin/icons"; import { MentionPicker } from "../chat/mention-picker"; import { referenceOptionId } from "../chat/reference-picker"; import { ReferenceMenu } from "./reference-menu"; import { filterMentions, mentionTrigger } from "../chat/mentions"; import { addressedOutsideReferences, chatSendPayload, insertReference, reconcileReferenceDrafts, referenceTrigger, } from "../chat/references"; import { Transcript } from "../chat/transcript"; import type { Chat } from "@chopin/protocol"; import stopIcon from "../assets/icons/planner-stop.svg"; import resumeIcon from "../assets/icons/planner-resume.svg"; import type { ReferenceDraft, ReferenceTarget } from "../chat/references"; import type { ReferencePickerState } from "../chat/reference-picker"; import type { Scenario } from "./scenarios"; import { DraftInput } from "./draft-input"; import type { DraftInputHandle } from "./draft-input"; import { ModeSwitch } from "./mode-switch"; let documents: ReferenceTarget[] = [ { kind: "document", channelId: "exports", title: "Export formats", slug: "export-formats" }, { kind: "document", channelId: "access", title: "Access and permissions", slug: "access" }, ]; let initialText = (state: Scenario) => { if (state === "mention") return "@"; if (state === "reference" || state.startsWith("ref-")) return "Compare this with #"; if (state === "reference-selected") return "Compare this with #Export formats"; if (state === "multiline") { return "Could you revise the export section?\n\nInclude Markdown and PDF, and explain how comments are handled.\n\nKeep the first version small enough to review."; } if (["team", "chopin", "agent-off", "readonly", "archived", "connecting"].includes(state)) { return ""; } return "Could you outline the export options?"; }; export function ComposerPreview( { scenario, stayInMode = true, onSend }: { scenario: Scenario; stayInMode?: boolean; onSend?: (text: string, destination: string) => void; }, ) { let [text, setText] = useState(initialText(scenario)); let [mode, setMode] = useState( !["team", "draft", "agent-off", "readonly", "archived"].includes(scenario), ); let [phase, setPhase] = useState(scenario); let [queued, setQueued] = useState( scenario === "queued" ? [{ id: "queued-example", handle: "maggieappleton", text: "Include PDF export too." }] : [], ); let [refs, setRefs] = useState( scenario === "reference-selected" ? [{ ...documents[0]!, token: "#Export formats", start: 18, end: 33 }] : [], ); let [caret, setCaret] = useState(text.length); let [dismissed, setDismissed] = useState(false); let [active, setActive] = useState(0); let field = useRef(null); let focusFrame = useRef(undefined); let id = useId(); let mention = !dismissed ? mentionTrigger(text, caret) : undefined; let reference = !dismissed ? referenceTrigger(text, caret) : undefined; let options = mention ? filterMentions([ { kind: "planner", login: "chopin" }, { kind: "person", login: "maggieappleton" }, { kind: "person", login: "matt" }, ], mention.query) : []; let targets = documents.filter(item => item.title.toLowerCase().includes(reference?.query.toLowerCase() ?? "") ); let readonly = ["readonly", "archived"].includes(phase); let unavailable = readonly || ["offline", "connecting"].includes(phase); let sending = phase === "sending"; let agentOff = scenario === "agent-off"; let effectiveMode = !agentOff && (mode || addressedOutsideReferences(text, refs)); let pickerState: ReferencePickerState = phase === "ref-loading" ? { status: "loading", options: [] } : phase === "ref-error" ? { status: "error", options: [], error: new Error("Document search unavailable") } : phase === "ref-limit" ? { status: "limit", options: [] } : { status: "ready", options: phase === "ref-empty" ? [] : targets, truncated: phase === "ref-truncated", }; let count = mention ? options.length : pickerState.options.length; let pickerOpen = !unavailable && !sending && !!(mention || reference); let cue = phase === "error" ? "Message not sent." : agentOff ? "Chopin unavailable" : phase === "offline" ? "Connection lost" : phase === "connecting" ? "Synchronizing…" : sending ? "Sending…" : phase === "paused" ? "Chopin paused" : ["working", "queued"].includes(phase) ? "Chopin working" : ""; let focus = (at = caret) => { if (focusFrame.current !== undefined) cancelAnimationFrame(focusFrame.current); focusFrame.current = requestAnimationFrame(() => { focusFrame.current = undefined; field.current?.focus(); field.current?.setSelectionRange(at, at); }); }; let toggle = () => { if (unavailable || sending || agentOff) return; if (focusFrame.current !== undefined) cancelAnimationFrame(focusFrame.current); if (effectiveMode) { let next = text.replace(/(^|[^\w@])@chopin\b/gi, (match, before, offset) => { let start = offset + before.length; return refs.some(ref => start >= ref.start && start < ref.end) ? match : before; }); setRefs(reconcileReferenceDrafts(text, next, refs)); setText(next); setMode(false); } else setMode(true); setDismissed(true); field.current?.focus(); }; let choose = (index: number) => { if (mention && options[index]) { let option = options[index]!; let next = text.slice(0, mention.start) + `@${option.login} ` + text.slice(mention.end); setRefs(reconcileReferenceDrafts(text, next, refs, mention)); setText(next); if (option.kind === "planner") setMode(true); setCaret(mention.start + option.login.length + 2); focus(mention.start + option.login.length + 2); } else if (reference && pickerState.options[index]) { let next = insertReference(text, refs, reference, pickerState.options[index]!); setText(next.text); setRefs(next.references); setCaret(next.caret); focus(next.caret); } setDismissed(true); }; let submit = () => { if (!text.trim() || unavailable || sending || pickerOpen) return; let prefix = effectiveMode && !addressedOutsideReferences(text, refs) ? "@chopin " : ""; let payload = chatSendPayload( prefix + text, refs.map(ref => ({ ...ref, start: ref.start + prefix.length, end: ref.end + prefix.length, })), !agentOff, crypto.randomUUID(), ); if (!payload) return; setPhase("sending"); window.setTimeout(() => { if (["working", "queued"].includes(phase) && effectiveMode) { setQueued(current => [...current, { id: crypto.randomUUID(), handle: "maggieappleton", text: payload.text, }]); } else onSend?.(payload.text, payload.to); setText(""); setRefs([]); if (!stayInMode) setMode(false); setPhase( ["working", "queued"].includes(phase) ? effectiveMode ? "queued" : phase : effectiveMode ? "working" : "idle", ); focus(0); }, 650); }; return (
{queued.length > 0 && (
{ setQueued(current => current.filter(message => message.id !== key)); }} />
)} {(phase === "error" || agentOff || ["offline", "connecting"].includes(phase)) && (
{phase === "connecting" ? : phase === "offline" || phase === "error" ? (
)}
{pickerOpen && mention && options.length > 0 && ( choose(options.indexOf(option))} /> )} {pickerOpen && reference && ( choose(pickerState.options.indexOf(option))} /> )} {readonly ? (
{phase === "archived" ? "Document archived" : "Read-only access"}

{phase === "archived" ? "Restore this document to send messages." : "You need write access to send messages."}

) : ( <>
{ if (focusFrame.current !== undefined) cancelAnimationFrame(focusFrame.current); }} aria-label="Message" value={text} readOnly={unavailable || sending} aria-disabled={unavailable || sending} aria-invalid={phase === "error" || undefined} aria-describedby={cue ? `${id}-cue` : undefined} aria-autocomplete="list" role="combobox" aria-expanded={pickerOpen} aria-controls={pickerOpen ? `${id}-picker` : undefined} aria-activedescendant={pickerOpen && count ? referenceOptionId(`${id}-picker`, active % count) : undefined} placeholder={readonly ? "Conversation unavailable" : effectiveMode ? "Ask Chopin…" : "Message your collaborators…"} onSelect={event => setCaret(event.currentTarget.selectionStart)} onChange={event => { let next = event.currentTarget.value; setRefs( event.currentTarget.references ?? reconcileReferenceDrafts(text, next, refs), ); setText(next); setCaret(event.currentTarget.selectionStart); setDismissed(false); setActive(0); if (phase === "error" || phase.startsWith("ref-")) setPhase("idle"); }} onKeyDown={event => { if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Tab" && focusFrame.current !== undefined) { cancelAnimationFrame(focusFrame.current); } if ( event.key === "Tab" && event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey && !unavailable && !sending && !agentOff ) { event.preventDefault(); if (!event.repeat) toggle(); return; } if (pickerOpen) { if (event.key === "Escape") { event.preventDefault(); setDismissed(true); return; } if (count && ["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); setActive((active + (event.key === "ArrowDown" ? 1 : -1) + count) % count); return; } if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); if (count) choose(active % count); return; } } if (event.key === "Escape" && effectiveMode) { event.preventDefault(); toggle(); return; } if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); submit(); } }} />
{["working", "queued", "paused"].includes(phase) && ( )} {sending ? ( ) : ( )}
)}
{cue && phase !== "error" && !agentOff && !["offline", "connecting"].includes(phase) && ( {cue} )}
); }