Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion COMPONENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<MessageContent>` 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. |
Expand Down
122 changes: 122 additions & 0 deletions src/__tests__/components/MessageComposer.controlled.test.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<>
<MessageComposer value={value} onValueChange={setValue} onSend={onSend} sendLabel="Send" />
<button type="button" onClick={() => setValue('escrito por el padre')}>
write
</button>
<output data-testid="mirror">{value}</output>
</>
)
}

it('renders the value the parent writes, without an input event', async () => {
const user = userEvent.setup()
render(<Host />)
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(<Host />)
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(<Host initial=" listo " onSend={onSend} />)
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(<MessageComposer value="fijo" onValueChange={() => {}} 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(<MessageComposer onSend={onSend} onValueChange={onValueChange} sendLabel="Send" />)
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: <span>★</span>, label: 'Redactar', onClick: vi.fn() }

it('disables only the item that asks for it', () => {
render(
<MessageComposer
onSend={vi.fn()}
toolbarItems={[{ ...base, disabled: true }, { ...base, id: 'y', label: 'Otro' }]}
/>
)
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(<MessageComposer onSend={vi.fn()} disabled toolbarItems={[base]} />)
expect(screen.getByTitle('Redactar')).toBeDisabled()
})

it('shows the label as text only with showLabel', () => {
const { rerender } = render(<MessageComposer onSend={vi.fn()} toolbarItems={[base]} />)
expect(screen.getByTitle('Redactar')).not.toHaveTextContent('Redactar')
rerender(<MessageComposer onSend={vi.fn()} toolbarItems={[{ ...base, showLabel: true }]} />)
expect(screen.getByTitle('Redactar')).toHaveTextContent('Redactar')
})

it('forwards data-* attributes and the item className', () => {
render(
<MessageComposer
onSend={vi.fn()}
toolbarItems={[{ ...base, className: 'acento', dataAttributes: { 'data-tour': 'composer-instruct' } }]}
/>
)
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(<MessageComposer onSend={vi.fn()} inputContainerClassName="borrador" textareaClassName="ta-borrador" />)
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')
})
})
80 changes: 73 additions & 7 deletions src/components/messaging/inputs/MessageComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
useEffect,
useId,
useCallback,
useLayoutEffect,
type CSSProperties,
type FormEvent,
type KeyboardEvent,
Expand Down Expand Up @@ -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 */
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
Expand Down Expand Up @@ -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;

Expand All @@ -225,7 +283,7 @@ export function MessageComposer({
}
}
},
[canSend, message, isBusy, onSend]
[canSend, message, isBusy, onSend, setMessage]
);

// Enter to send, Shift+Enter for newline
Expand Down Expand Up @@ -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 ─────────────────────────────
Expand Down Expand Up @@ -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` }}
/>
Expand Down Expand Up @@ -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 && <span>{item.label}</span>}
</button>
))}

Expand Down
40 changes: 40 additions & 0 deletions src/stories/messaging/MessageComposer.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -510,3 +510,43 @@ export const AllowEmptySend = () => {
</div>
);
};

/**
* 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 (
<div className="max-w-lg">
<MessageComposer
value={value}
onValueChange={(next) => {
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: <Sparkles className="w-[18px] h-[18px]" />,
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);
},
},
]}
/>
</div>
);
};
Loading