"use client" /** * AskLeoComposer — ChatGPT-style composer: * - Compact: one row (`+ | input | mic`, send appears on focus). * - Wrapped: full-width text (grows to ~8 rows, then scrolls), icons on a footer row. * - Autosize via scrollHeight (no grow-wrap / field-sizing conflicts). */ import * as React from "react" import { AnimatePresence, motion, useReducedMotion } from "motion/react" import { DictationSoundwave } from "@/components/dictation-soundwave" import { useLeoAmbience } from "@/components/leo-ambience-context" import { LeoSearchBarWash } from "@/components/leo-search-bar-wash" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { Kbd } from "@/components/ui/kbd" import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip" import { SearchRecentsPopover } from "@/components/search-recents-popover" import { LEO_DEEP_FILL_CLASS, LeoIcon, type LeoIconMotionState, } from "@/components/ui/leo-icon" import { useSpeechDictation } from "@/hooks/use-speech-dictation" import type { DedicatedSearchRecentsController } from "@/lib/dedicated-search-recents" import { processDictationTranscript } from "@/lib/dictation-transcript" import { cn } from "@/lib/utils" /** * 32px, the same height as every other control in the app. * * The composer's round buttons were the last 36px holdouts, and because they are * the tallest thing in the row they, not the text, set the pill's height: the * chat box stood 58px tall around a 24px line of type. At 32 they still clear the * 24px target floor with room to spare. */ const GHOST_ICON_BTN = "icon-button-chrome size-8 shrink-0 rounded-full hover:bg-accent hover:text-interactive-hover-foreground" /** Matches `--exxat-composer-max-height: 13rem` in exxat-composer.css (~8–9 text rows). */ const COMPOSER_MAX_ROWS = 8 const COMPOSER_MAX_HEIGHT_FALLBACK_PX = 208 const PHRASE_EASE = [0.22, 1, 0.36, 1] as const export interface AskLeoComposerSearchRecents { recents: Pick onSelect: (query: string) => void } export interface AskLeoComposerProps { value: string onChange: (value: string) => void onSubmit?: (message: string) => void /** * Whether submitting empties the field. True for a conversation, where the * message leaves the composer and becomes a turn in the transcript. False for * a search bar, where the query is the state of the results below it and has * to stay legible and editable after the search runs. */ clearOnSubmit?: boolean placeholder?: string animatedPlaceholders?: string[] animatedPlaceholderIntervalMs?: number animatedPlaceholderMaxLines?: 1 | 2 leadingSlot?: "attachments" | "ai-mark" inputLabel?: string submitButtonAriaLabel?: string submitAppearance?: "send" | "search" onExpandedChange?: (expanded: boolean) => void searchRecents?: AskLeoComposerSearchRecents dictationDisabled?: boolean isAnalyzing?: boolean /** In-flight search (Library AI search). Shows a spinner on the submit control. */ isSearching?: boolean /** * Library / mode-switch Leo search — prefs-driven wash, double-click opens * Leo appearance settings. */ searchBarAmbience?: boolean /** * Host actions rendered inside the pill, ahead of dictation and submit. * For a named action the composer itself does not own (LeoAssistBar's * rewrite action and its overflow). */ inlineActions?: React.ReactNode onStop?: () => void composerShellClassName?: string shellMaxWidth?: "2xl" | "full" className?: string } // ── Pure helpers (kept out of the component so branches do not stack up) ────── interface ComposerLayoutMetrics { overflowing: boolean showFade: boolean wrapped: boolean /** When true, an already-wrapped composer stays wrapped. */ sticky: boolean /** False when there was no textarea to measure. */ measured: boolean } function measureEmptyComposer( textarea: HTMLTextAreaElement, lineHeight: number, singleLineHeightRef: React.MutableRefObject, ): ComposerLayoutMetrics { textarea.style.minHeight = "0" textarea.style.height = `${lineHeight}px` singleLineHeightRef.current = lineHeight return { overflowing: false, showFade: false, wrapped: false, sticky: false, measured: true } } function measureFilledComposer( textarea: HTMLTextAreaElement, text: string, lineHeight: number, maxHeightPx: number, singleLineHeightRef: React.MutableRefObject, ): ComposerLayoutMetrics { textarea.style.minHeight = "0" textarea.style.height = "0px" // Force reflow so scrollHeight is not the previous inflated height. void textarea.offsetHeight const scrollHeight = textarea.scrollHeight const cappedHeight = Math.min(Math.max(scrollHeight, lineHeight), maxHeightPx) textarea.style.height = `${cappedHeight}px` const overflowing = scrollHeight > maxHeightPx + 1 if (overflowing) textarea.scrollTop = textarea.scrollHeight const showFade = overflowing && textarea.scrollTop > 4 if (text.includes("\n")) { return { overflowing, showFade, wrapped: true, sticky: false, measured: true } } const lineCount = Math.max(1, Math.round(scrollHeight / lineHeight)) const baseline = singleLineHeightRef.current || lineHeight // Expand to the wrapped footer layout only when a second row appears. const wrappedNow = lineCount > 1 || scrollHeight > baseline + 2 // Stay wrapped once multiline — full-width reflow can collapse line count // back to 1 and would otherwise flip to compact with centered icons. return { overflowing, showFade, wrapped: wrappedNow, sticky: true, measured: true } } function measureComposerLayout( textarea: HTMLTextAreaElement | null, text: string, singleLineHeightRef: React.MutableRefObject, maxHeightPxRef: React.MutableRefObject, ): ComposerLayoutMetrics { if (!textarea) { return { overflowing: false, showFade: false, wrapped: text.includes("\n"), sticky: false, measured: false, } } const lineHeight = parseFloat(getComputedStyle(textarea).lineHeight) || 24 const maxHeightPx = lineHeight * COMPOSER_MAX_ROWS maxHeightPxRef.current = maxHeightPx // Empty field must stay one row. Measuring scrollHeight while the docked // rail is still settling can report the full panel height and inflate the // chatbox into a tall empty card (and flip overflow chrome on). if (!text.trim()) return measureEmptyComposer(textarea, lineHeight, singleLineHeightRef) return measureFilledComposer(textarea, text, lineHeight, maxHeightPx, singleLineHeightRef) } function normalizePhrases(list: string[] | undefined): string[] { return (list ?? []).flatMap(s => { const trimmed = s.trim() return trimmed ? [trimmed] : [] }) } interface PlaceholderFlags { phraseCount: number value: string isWrapped: boolean isListening: boolean isSearching: boolean } // Dictation takes the placeholder over with "Listening…", and a search that // is running is showing its own query, so neither wants suggestions rotating // underneath. Two strings at one spot read as garbled text, not as a state. function shouldShowAnimatedPlaceholder(f: PlaceholderFlags): boolean { const blocked = f.isWrapped || f.isListening || f.isSearching return f.phraseCount > 0 && !f.value.trim() && !blocked } function resolvePlaceholder(isListening: boolean, animated: boolean, placeholder: string): string { if (isListening) return "Listening…" return animated ? " " : placeholder } function shouldShowSend(f: { userActivated: boolean isFocused: boolean canSend: boolean isListening: boolean isAnalyzing: boolean isSearching: boolean }): boolean { const engaged = (f.userActivated && f.isFocused) || f.canSend const idle = !f.isListening && !f.isAnalyzing && !f.isSearching return engaged && idle } function shouldOpenRecentsOnFocus(f: { isListening: boolean isSearching: boolean isAnalyzing: boolean value: string recentCount: number }): boolean { const idle = !f.isListening && !f.isSearching && !f.isAnalyzing return idle && !f.value.trim() && f.recentCount > 0 } interface LeoVisualState { leoBusy: boolean showSearchBarWash: boolean clipPillForWash: boolean leoMarkState: LeoIconMotionState } function deriveLeoVisualState(f: { isSearching: boolean isAnalyzing: boolean searchBarAmbience: boolean previewThinking: boolean searchBarWash: boolean washMode: string isFocused: boolean userActivated: boolean }): LeoVisualState { const thinkingPreview = f.searchBarAmbience && f.previewThinking const leoBusy = f.isSearching || f.isAnalyzing || thinkingPreview // The thinking wash belongs to the search bar only. The Ask Leo chatbox // shows work through the status marker instead, so a composer that is not // a search bar never paints a wash. const showSearchBarWash = f.searchBarAmbience && f.searchBarWash && (f.isSearching || f.isAnalyzing || f.previewThinking) // Only the in-pill wash needs clipping. Idle pills stay overflow-visible so // recents and popovers are not trapped. const clipPillForWash = showSearchBarWash && f.washMode === "inside" const engaged = f.isFocused || f.userActivated const leoMarkState: LeoIconMotionState = leoBusy ? "working" : engaged ? "invited" : "rest" return { leoBusy, showSearchBarWash, clipPillForWash, leoMarkState } } function composerGridClass(f: { clipPillForWash: boolean isWrapped: boolean shellMaxWidth: "2xl" | "full" isListening: boolean composerShellClassName?: string }): string { return cn( "exxat-composer-grid relative grid w-full cursor-text rounded-3xl border border-solid bg-clip-padding p-2 shadow-md transition-[background-color,border-color,box-shadow] duration-200 ease-in-out", // Clip in-bar Leo wash to the pill; stay overflow-visible when idle // so popovers / recents are not trapped. Outside wash paints on a // sibling halo so the pill itself can stay overflow-visible. f.clipPillForWash ? "overflow-hidden" : "overflow-visible", f.isWrapped ? "exxat-composer-grid--wrapped" : "exxat-composer-grid--compact items-center", f.shellMaxWidth === "2xl" && "mx-auto max-w-2xl", "exxat-composer-idle", f.isListening && "exxat-composer-dictating", f.composerShellClassName, ) } function isEditableTarget(target: HTMLElement | null | undefined): boolean { const tag = target?.tagName return tag === "INPUT" || tag === "TEXTAREA" || Boolean(target?.isContentEditable) } function isDictationHotkey(e: KeyboardEvent): boolean { if (e.metaKey || e.ctrlKey || e.altKey) return false if (isEditableTarget(e.target as HTMLElement | null)) return false return e.key === "m" || e.key === "M" } function setForwardedRef(ref: React.ForwardedRef, node: T | null) { if (typeof ref === "function") ref(node) else if (ref) (ref as React.MutableRefObject).current = node } const PLACEHOLDER_BOX_CLASS: Record<1 | 2, string> = { 1: "min-h-[1.5rem] items-center", 2: "min-h-[2.5rem] items-start", } const PLACEHOLDER_TEXT_CLASS: Record<1 | 2, string> = { 1: "truncate", 2: "line-clamp-2 whitespace-normal break-words", } function isPlainEnter(e: React.KeyboardEvent): boolean { return e.key === "Enter" && !e.shiftKey } const INTERACTIVE_SELECTOR = "button, a, input, textarea, [role='button']" function routeShellMouseDown( e: React.MouseEvent, activate: () => void, inputRef: React.RefObject, ) { const target = e.target as HTMLElement if (target.closest(INTERACTIVE_SELECTOR)) { if (target.closest("textarea")) activate() return } e.preventDefault() activate() inputRef.current?.focus() } interface SubmitContext { value: string busy: boolean clearOnSubmit: boolean onSubmit?: (message: string) => void onChange: (value: string) => void cancelDictation: () => void resetLayout: () => void deactivate: () => void } function submitComposer(e: React.FormEvent, ctx: SubmitContext) { e.preventDefault() if (ctx.busy) return ctx.cancelDictation() const trimmed = ctx.value.trim() if (!trimmed) return ctx.onSubmit?.(trimmed) if (!ctx.clearOnSubmit) return ctx.onChange("") ctx.resetLayout() ctx.deactivate() } function primaryCellClass(isWrapped: boolean): string { return cn( "exxat-composer-primary relative z-[2] min-w-0", isWrapped ? "px-2 pb-0.5 pt-0.5" : "px-1.5 py-0.5", ) } function scrollWrapClass(isOverflowing: boolean, showBottomFade: boolean): string { return cn( "exxat-composer-scroll relative min-w-0 w-full", isOverflowing && "exxat-composer-scroll--overflow", showBottomFade && "exxat-composer-scroll--fade-top", ) } function textareaClass(isOverflowing: boolean, animated: boolean): string { return cn( "exxat-composer-input placeholder-aa block w-full resize-none overflow-x-hidden overflow-y-auto border-0 bg-transparent p-0 text-base leading-[1.5] text-foreground outline-none placeholder:text-placeholder-foreground", isOverflowing && "overscroll-y-contain", animated && "placeholder:text-transparent", ) } // ── Hooks ───────────────────────────────────────────────────────────────────── function useComposerLayout(value: string, onExpandedChange?: (expanded: boolean) => void) { const [isWrapped, setIsWrapped] = React.useState(false) const [isOverflowing, setIsOverflowing] = React.useState(false) const [showBottomFade, setShowBottomFade] = React.useState(false) const innerRef = React.useRef(null) const singleLineHeightRef = React.useRef(24) const maxHeightPxRef = React.useRef(COMPOSER_MAX_HEIGHT_FALLBACK_PX) const onExpandedChangeRef = React.useRef(onExpandedChange) React.useEffect(() => { onExpandedChangeRef.current = onExpandedChange }) const applyWrapped = React.useCallback((next: boolean | ((prev: boolean) => boolean)) => { setIsWrapped(prev => { const resolved = typeof next === "function" ? next(prev) : next if (resolved !== prev) onExpandedChangeRef.current?.(resolved) return resolved }) }, []) const syncComposerLayout = React.useCallback( (text: string) => { const m = measureComposerLayout(innerRef.current, text, singleLineHeightRef, maxHeightPxRef) if (m.measured) { setIsOverflowing(m.overflowing) setShowBottomFade(m.showFade) } applyWrapped(m.sticky ? wasWrapped => m.wrapped || wasWrapped : m.wrapped) }, [applyWrapped], ) const updateScrollFade = React.useCallback(() => { const textarea = innerRef.current if (!textarea) return const overflowing = textarea.scrollHeight > maxHeightPxRef.current + 1 const atBottom = textarea.scrollTop + textarea.clientHeight >= textarea.scrollHeight - 4 setShowBottomFade(overflowing && !atBottom) }, []) React.useLayoutEffect(() => { syncComposerLayout(value) }, [value, isWrapped, syncComposerLayout]) const resetLayout = React.useCallback(() => { setIsWrapped(false) setIsOverflowing(false) setShowBottomFade(false) if (innerRef.current) innerRef.current.style.height = "0px" }, []) return { isWrapped, isOverflowing, showBottomFade, innerRef, syncComposerLayout, updateScrollFade, resetLayout, } } function useComposerDictation(opts: { value: string onChange: (value: string) => void blocked: boolean onBegin: () => void }) { const { value, onChange, blocked, onBegin } = opts const [dictationError, setDictationError] = React.useState(null) const dictationBaseRef = React.useRef("") const appendDictation = React.useCallback( (chunk: string, isFinal: boolean) => { if (!chunk && !isFinal) return const next = processDictationTranscript(dictationBaseRef.current, chunk, isFinal) if (isFinal) dictationBaseRef.current = next onChange(next) }, [onChange], ) const { isSupported: dictationSupported, isListening, waveformLevels, start: startDictation, stop: stopDictation, } = useSpeechDictation({ onTranscript: appendDictation, onError: () => { setDictationError("Could not capture speech. Check microphone permissions and try again.") }, }) const beginDictation = React.useCallback(() => { if (!dictationSupported || blocked) return onBegin() setDictationError(null) dictationBaseRef.current = value void startDictation() }, [blocked, dictationSupported, onBegin, startDictation, value]) const finishDictation = React.useCallback(() => { stopDictation() }, [stopDictation]) const cancelDictation = () => { if (isListening) stopDictation({ playRelease: false }) } React.useEffect(() => { if (blocked && isListening) stopDictation({ playRelease: false }) }, [blocked, isListening, stopDictation]) const hotkey = (e: KeyboardEvent) => { if (!isDictationHotkey(e) || !dictationSupported || blocked) return e.preventDefault() if (isListening) finishDictation() else beginDictation() } const hotkeyRef = React.useRef<(e: KeyboardEvent) => void>(() => {}) React.useEffect(() => { hotkeyRef.current = hotkey }) React.useEffect(() => { const listener = (e: KeyboardEvent) => hotkeyRef.current(e) window.addEventListener("keydown", listener) return () => window.removeEventListener("keydown", listener) }, []) return { dictationError, dictationSupported, isListening, waveformLevels, beginDictation, finishDictation, cancelDictation, } } function useRecentItems(searchRecents: AskLeoComposerSearchRecents | undefined) { const [recentItems, setRecentItems] = React.useState([]) React.useEffect(() => { if (!searchRecents) return const sync = () => setRecentItems(searchRecents.recents.read()) sync() return searchRecents.recents.subscribe(sync) }, [searchRecents]) return recentItems } function usePhraseRotation(show: boolean, count: number, intervalMs: number) { const [phraseIndex, setPhraseIndex] = React.useState(0) React.useEffect(() => { if (!show) return const id = window.setInterval(() => { setPhraseIndex(i => (i + 1) % count) }, intervalMs) return () => window.clearInterval(id) }, [show, count, intervalMs]) React.useEffect(() => { if (!show) setPhraseIndex(0) }, [show]) return phraseIndex } /** * `exit` is a function variant so it can read `custom` at the moment the * phrase leaves: `true` means the next suggestion is taking its place and * the two crossfade, `false` means the placeholder itself is over (someone * typed, dictated, or the field wrapped) and it has to disappear at once. */ function usePhraseMotion(reduceMotion: boolean | null) { return React.useMemo( () => ({ enter: { opacity: 0, y: reduceMotion ? 0 : 3 }, visible: { opacity: 1, y: 0, transition: { duration: reduceMotion ? 0 : 0.32, ease: PHRASE_EASE }, }, exit: (rotating: boolean) => { const instant = reduceMotion || !rotating return { opacity: 0, y: instant ? 0 : -3, transition: { duration: instant ? 0 : 0.32, ease: PHRASE_EASE }, } }, }), [reduceMotion], ) } // ── Sub-components ──────────────────────────────────────────────────────────── function AiMarkLeading({ isSearching, state }: { isSearching: boolean; state: LeoIconMotionState }) { return ( {isSearching ? "Searching" : "AI search"} ) } function AttachmentsLeading({ fileInputRef }: { fileInputRef: React.RefObject }) { return (