From 366146b24a9a50c293d4c8118c8e2162d211f332 Mon Sep 17 00:00:00 2001 From: A-PachecoT Date: Sat, 21 Nov 2026 12:08:31 -0500 Subject: [PATCH] =?UTF-8?q?feat(MessageComposer):=20texto=20controlado=20y?= =?UTF-8?q?=20opciones=20por=20=C3=ADtem,=20opcionales=20y=20aditivas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - value/onValueChange: texto controlado por el padre (sin value, el estado propio de siempre). - ComposerToolbarItem: disabled, showLabel, className, dataAttributes. - inputContainerClassName / textareaClassName para teñir la caja. Ningún default cambia: sin las props nuevas el render y el comportamiento son los de hoy (los 31 tests existentes siguen verdes sin tocarlos; 10 tests nuevos). Lo pide el compositor IA de Tracta (borrador de la IA escrito en la caja de escritorio sin el setter nativo). El ADR de André 2026-07-24 (el render de la burbuja de chat se queda local, .cofoundy/context/decisions/2026-07-24-chat-ui-stays-local.md en tracta) trata de la burbuja, no del compositor: el escritorio ya usa este MessageComposer. --- COMPONENTS.md | 2 +- .../MessageComposer.controlled.test.tsx | 122 ++++++++++++++++++ .../messaging/inputs/MessageComposer.tsx | 80 +++++++++++- .../messaging/MessageComposer.stories.tsx | 40 ++++++ 4 files changed, 236 insertions(+), 8 deletions(-) create mode 100644 src/__tests__/components/MessageComposer.controlled.test.tsx diff --git a/COMPONENTS.md b/COMPONENTS.md index da871d4..b35089c 100644 --- a/COMPONENTS.md +++ b/COMPONENTS.md @@ -156,7 +156,7 @@ Generic messaging primitives (used by Tracta; reusable for any chat surface). | `MessageMedia` | Media attachment renderer (image / file / audio). | | **`StreamingMarkdown`** | **NEW (v0.5.1)** — Per-char wave reveal for LLM streaming. Walks hast tree, emits flat spans keyed by source offset. Drops to `` when content > 5000 chars or `prefers-reduced-motion`. | | `InboxMessage`, `InboxMessageList` | Composed message list (Tracta). | -| `MessageComposer` | Multi-modal input (text + attachments + toolbar + quick actions). `busy` swaps Send for Stop while an automatic reply is in flight — the textarea stays live. | +| `MessageComposer` | Multi-modal input (text + attachments + toolbar + quick actions). `busy` swaps Send for Stop while an automatic reply is in flight — the textarea stays live. Optional `value`/`onValueChange` make the text controlled; toolbar items take `disabled`, `showLabel`, `className`, `dataAttributes`; `inputContainerClassName`/`textareaClassName` style the box. | | `AIBadge` | "AI" inline pill (mark AI-generated content). | | **`ToolInvocation`** | **NEW (2026-10-12)** — Collapsible card for one tool call of an AI turn: `name`, one-line `summary`, `state` (`input-streaming` · `input-available` · `output-available` · `output-error`), `input` (flat object → key/value list, else JSON), `output` (text · JSON string pretty-printed, a truncated one stays text · object · ReactNode), `errorText`, `defaultOpen` (folded by default), `labels` (English defaults, all overridable). Reference: Vercel AI Elements «Tool». Helpers: `ToolInvocationStatus`, `ToolValue`. | | `ToolInvocationGroup` | Folds several `ToolInvocation` of one turn behind «AI ran N actions» (`labels.title(n)` to localize); flags the error count. | diff --git a/src/__tests__/components/MessageComposer.controlled.test.tsx b/src/__tests__/components/MessageComposer.controlled.test.tsx new file mode 100644 index 0000000..8e1e52a --- /dev/null +++ b/src/__tests__/components/MessageComposer.controlled.test.tsx @@ -0,0 +1,122 @@ +import { describe, it, expect, vi } from 'vitest' +import { useState } from 'react' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MessageComposer } from '../../components/messaging/inputs/MessageComposer' + +/** + * The optional, additive props: controlled text, per-item `disabled`, visible + * item labels, `data-*` on items, and classes for the box and the textarea. + * + * Each block pairs the new behaviour with the default it must NOT change, so + * "the prop works" can't be confused with "the default moved". + */ +describe('MessageComposer — controlled value', () => { + function Host({ initial = '', onSend = vi.fn() }: { initial?: string; onSend?: (m: string) => void }) { + const [value, setValue] = useState(initial) + return ( + <> + + + {value} + + ) + } + + it('renders the value the parent writes, without an input event', async () => { + const user = userEvent.setup() + render() + await user.click(screen.getByRole('button', { name: 'write' })) + expect(screen.getByPlaceholderText('Type a message...')).toHaveValue('escrito por el padre') + expect(screen.getByRole('button', { name: /send/i })).toBeEnabled() + }) + + it('reports typing through onValueChange', async () => { + const user = userEvent.setup() + render() + await user.type(screen.getByPlaceholderText('Type a message...'), 'hola') + expect(screen.getByTestId('mirror')).toHaveTextContent('hola') + }) + + it('sends the controlled text and asks the parent to clear it', async () => { + const user = userEvent.setup() + const onSend = vi.fn() + render() + await user.click(screen.getByRole('button', { name: /send/i })) + expect(onSend).toHaveBeenCalledWith('listo') + expect(screen.getByTestId('mirror')).toHaveTextContent('') + expect(screen.getByPlaceholderText('Type a message...')).toHaveValue('') + }) + + it('a controlled value the parent refuses to clear stays put', async () => { + const user = userEvent.setup() + const onSend = vi.fn() + render( {}} onSend={onSend} sendLabel="Send" />) + await user.click(screen.getByRole('button', { name: /send/i })) + expect(onSend).toHaveBeenCalledWith('fijo') + expect(screen.getByPlaceholderText('Type a message...')).toHaveValue('fijo') + }) + + it('uncontrolled (default) still owns its text and clears itself on send', async () => { + const user = userEvent.setup() + const onSend = vi.fn() + const onValueChange = vi.fn() + render() + const ta = screen.getByPlaceholderText('Type a message...') + await user.type(ta, 'hola{Enter}') + expect(onSend).toHaveBeenCalledWith('hola') + expect(ta).toHaveValue('') + expect(onValueChange).toHaveBeenLastCalledWith('') + }) +}) + +describe('MessageComposer — toolbar item options', () => { + const base = { id: 'x', icon: ★, label: 'Redactar', onClick: vi.fn() } + + it('disables only the item that asks for it', () => { + render( + + ) + expect(screen.getByTitle('Redactar')).toBeDisabled() + expect(screen.getByTitle('Otro')).toBeEnabled() + }) + + it('the composer-wide disabled still wins over an item that is not disabled', () => { + render() + expect(screen.getByTitle('Redactar')).toBeDisabled() + }) + + it('shows the label as text only with showLabel', () => { + const { rerender } = render() + expect(screen.getByTitle('Redactar')).not.toHaveTextContent('Redactar') + rerender() + expect(screen.getByTitle('Redactar')).toHaveTextContent('Redactar') + }) + + it('forwards data-* attributes and the item className', () => { + render( + + ) + const btn = screen.getByTitle('Redactar') + expect(btn).toHaveAttribute('data-tour', 'composer-instruct') + expect(btn).toHaveClass('acento') + }) +}) + +describe('MessageComposer — box and textarea classes', () => { + it('appends the classes without dropping the defaults', () => { + render() + const ta = screen.getByPlaceholderText('Type a message...') + expect(ta).toHaveClass('ta-borrador', 'w-full') + const box = ta.closest('form')!.parentElement! + expect(box).toHaveClass('borrador', 'rounded-xl') + }) +}) diff --git a/src/components/messaging/inputs/MessageComposer.tsx b/src/components/messaging/inputs/MessageComposer.tsx index 6fb3c38..8dce758 100644 --- a/src/components/messaging/inputs/MessageComposer.tsx +++ b/src/components/messaging/inputs/MessageComposer.tsx @@ -6,6 +6,7 @@ import { useEffect, useId, useCallback, + useLayoutEffect, type CSSProperties, type FormEvent, type KeyboardEvent, @@ -38,6 +39,20 @@ export interface ComposerToolbarItem { onClick: () => void; /** Hide this item in certain modes */ hideInModes?: string[]; + /** + * Disable just this item. Default `false`. The whole-composer `disabled` + * still wins: an inert composer disables every item, as before. + */ + disabled?: boolean; + /** Render `label` as visible text next to the icon (default: icon only, label as tooltip). */ + showLabel?: boolean; + /** Extra classes for this item's button (e.g. an accent color). */ + className?: string; + /** + * `data-*` attributes forwarded to the button — anchors for guided tours or + * tests (`{ "data-tour": "composer-instruct" }`). + */ + dataAttributes?: Record<`data-${string}`, string>; } /** @deprecated Use ComposerMode + ComposerToolbarItem instead */ @@ -68,6 +83,20 @@ export interface MessageComposerProps { /** Extra toolbar items (emoji picker, template picker, etc.) rendered before attach */ toolbarItems?: ComposerToolbarItem[]; + /* ─── Controlled text (optional) ─── */ + /** + * The textarea text, controlled by the parent. Omit it and the composer keeps + * its own state exactly as before (uncontrolled is the default). + * + * Controlled is for a parent that WRITES the text — a restored draft, a text + * generated for the operator to review — without going around React through + * the native value setter. On send the composer asks to clear it through + * `onValueChange("")`; it never clears a controlled value by itself. + */ + value?: string; + /** Every change of the text: typing, and the `""` after a send. Called in both modes. */ + onValueChange?: (value: string) => void; + /* ─── Basics ─── */ placeholder?: string; disabled?: boolean; @@ -117,6 +146,10 @@ export interface MessageComposerProps { quickActions?: QuickAction[]; className?: string; + /** Extra classes for the bordered input box that wraps textarea + toolbar (e.g. a different background). */ + inputContainerClassName?: string; + /** Extra classes for the textarea itself. */ + textareaClassName?: string; } /** @@ -154,8 +187,21 @@ export function MessageComposer({ busyLabel, quickActions, className, + inputContainerClassName, + textareaClassName, + value, + onValueChange, }: MessageComposerProps) { - const [message, setMessage] = useState(""); + const isControlled = value !== undefined; + const [uncontrolledMessage, setUncontrolledMessage] = useState(""); + const message = isControlled ? value : uncontrolledMessage; + const setMessage = useCallback( + (next: string) => { + if (!isControlled) setUncontrolledMessage(next); + onValueChange?.(next); + }, + [isControlled, onValueChange] + ); const [stopping, setStopping] = useState(false); const textareaRef = useRef(null); const fileInputRef = useRef(null); @@ -205,9 +251,21 @@ export function MessageComposer({ const newHeight = Math.min(textarea.scrollHeight, maxHeight); textarea.style.height = `${newHeight}px`; }, - [maxHeight] + [maxHeight, setMessage] ); + // A controlled value can change without an input event (the parent wrote it): + // the textarea has to grow to fit it. Uncontrolled keeps resizing on input only. + useLayoutEffect(() => { + if (!isControlled) return; + const textarea = textareaRef.current; + if (!textarea) return; + textarea.style.height = "auto"; + if (message) { + textarea.style.height = `${Math.min(textarea.scrollHeight, maxHeight)}px`; + } + }, [isControlled, message, maxHeight]); + // There is something to send: text, or whatever the parent has queued. const canSend = (message.trim().length > 0 || allowEmptySend) && !disabled; @@ -225,7 +283,7 @@ export function MessageComposer({ } } }, - [canSend, message, isBusy, onSend] + [canSend, message, isBusy, onSend, setMessage] ); // Enter to send, Shift+Enter for newline @@ -327,7 +385,8 @@ export function MessageComposer({ "mx-3 mb-3 mt-2 rounded-xl border transition-colors", isAccented ? "border-[var(--chat-warning)]/40 bg-[var(--chat-warning)]/5" - : "border-[var(--chat-border)] bg-[var(--chat-input-bg,var(--chat-card-hover))]" + : "border-[var(--chat-border)] bg-[var(--chat-input-bg,var(--chat-card-hover))]", + inputContainerClassName )} > {/* ─── Estado: la IA está redactando ───────────────────────────── @@ -376,7 +435,8 @@ export function MessageComposer({ "text-[var(--chat-foreground)] text-sm", "placeholder:text-[var(--chat-muted)]", "focus:outline-none", - "disabled:opacity-50 disabled:cursor-not-allowed" + "disabled:opacity-50 disabled:cursor-not-allowed", + textareaClassName )} style={{ maxHeight: `${maxHeight}px` }} /> @@ -424,11 +484,17 @@ export function MessageComposer({ key={item.id} type="button" onClick={item.onClick} - disabled={disabled} - className="p-1.5 rounded-lg text-[var(--chat-muted)] hover:text-[var(--chat-foreground)] hover:bg-[var(--chat-border)]/50 transition-colors disabled:opacity-50" + disabled={disabled || item.disabled} + className={cn( + "p-1.5 rounded-lg text-[var(--chat-muted)] hover:text-[var(--chat-foreground)] hover:bg-[var(--chat-border)]/50 transition-colors disabled:opacity-50", + item.showLabel && "inline-flex items-center gap-1.5 px-2 text-xs font-medium", + item.className + )} title={item.label} + {...item.dataAttributes} > {item.icon} + {item.showLabel && {item.label}} ))} diff --git a/src/stories/messaging/MessageComposer.stories.tsx b/src/stories/messaging/MessageComposer.stories.tsx index 8eb3d93..19eb881 100644 --- a/src/stories/messaging/MessageComposer.stories.tsx +++ b/src/stories/messaging/MessageComposer.stories.tsx @@ -510,3 +510,43 @@ export const AllowEmptySend = () => { ); }; + +/** + * Controlled text + per-item options (`value`/`onValueChange`, `disabled`, + * `showLabel`, `dataAttributes`, `inputContainerClassName`). The parent writes + * a draft into the box and tints it; typing by hand turns it back into the + * operator's own text. + */ +export const ControlledDraft = () => { + const [value, setValue] = useState(""); + const [isDraft, setIsDraft] = useState(false); + return ( +
+ { + setValue(next); + setIsDraft(false); + }} + onSend={() => setIsDraft(false)} + sendLabel="Enviar" + placeholder="Escribe un mensaje..." + inputContainerClassName={isDraft ? "bg-[var(--chat-primary)]/10" : undefined} + toolbarItems={[ + { + id: "draft", + icon: , + label: "Redactar", + showLabel: true, + disabled: !value.trim() || isDraft, + dataAttributes: { "data-tour": "composer-instruct" }, + onClick: () => { + setValue(`¡Hola! ${value.trim()}. Cualquier cosa, me escribes por aquí.`); + setIsDraft(true); + }, + }, + ]} + /> +
+ ); +};