Files
chatkit/dist/react/Composer.js
T
CatoandClaude f7401fc7fa release: v0.40.0 (DictationField gets the composer's paperclip; one way a person types) (#109)
DictationField takes `attach?: boolean | AttachOptions` and an app-owned
`attachments?: AttachmentsController`: the same paperclip sheet, paste,
drop, staged previews with Remove and limits as Composer. Off by default.

The paperclip wiring, staged strip, mic button and the shared voice and
attach labels move into one internal module (src/react/typing.tsx) used by
both Composer and DictationField. Composer's behaviour and API unchanged.
README gains the Composer-vs-DictationField rule and the plan for the rest
of the unification.


Claude-Session: https://claude.ai/code/session_019MDtmv1SAs6YZn4FrewbXR

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-15 14:23:48 +01:00

146 lines
9.6 KiB
JavaScript

"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useImperativeHandle, useRef, useState, } from "react";
import { appendTranscript, composerCanSend, composerOutgoingText, shouldClearDraft, } from "../composer.js";
import { useDictation } from "./use-dictation.js";
import { VoiceBar, VoiceProblem } from "./Voice.js";
import { useAutoGrow } from "./hooks.js";
import { AttachMenu } from "./AttachMenu.js";
import { AttachmentStrip, DEFAULT_TYPING_ATTACH_LABELS, DEFAULT_TYPING_VOICE_LABELS, MicButton, mergeAttachLabels, useTypingAttach, } from "./typing.js";
import { IconArrowUp, IconSpinner, IconStop } from "./icons.js";
export const DEFAULT_COMPOSER_LABELS = {
send: "Send",
stop: "Stop generating",
// The microphone's and the paperclip's words are every box's (typing.tsx).
...DEFAULT_TYPING_VOICE_LABELS,
...DEFAULT_TYPING_ATTACH_LABELS,
queue: "Queue a message…",
};
/**
* THE composer: write words — or say them, or paste a screenshot — and send
* them. Enter sends, Shift+Enter breaks the line, an IME composition never
* sends half a word. 16px text, so iOS never zooms the page on focus.
*
* Extracted from loki `components/composer/Composer.tsx` (itself the merge of
* four composers in one app), with heidi's microphone and orangecat's lessons.
*/
export function Composer({ onSend, placeholder, ariaLabel, disabled = false, sendBlockedReason = null, emptyAction, sending = false, onStop, attachmentOnlyText, heldAttachments = 0, queue = false, attach = false, attachExtras, handleRef, voice = {}, modes, mode, onModeChange, onEmptySlash, value, onValueChange, defaultValue = "", inputRef, density = "comfortable", layout = "stacked", attachmentsAlone = false, above, header, tools, trailing, footer, hint, stagedPosition = "below", labels: labelOverrides, autoFocus, }) {
const labels = {
...DEFAULT_COMPOSER_LABELS,
...labelOverrides,
dictation: { ...DEFAULT_COMPOSER_LABELS.dictation, ...labelOverrides?.dictation },
...mergeAttachLabels(DEFAULT_COMPOSER_LABELS, labelOverrides),
};
const [ownText, setOwnText] = useState(defaultValue);
const controlled = value !== undefined;
const text = controlled ? value : ownText;
// Mirrored so an async send compares against the CURRENT draft, not the one
// its closure captured. Written in an effect, never during render.
const textRef = useRef(text);
useEffect(() => {
textRef.current = text;
});
const setText = (next) => {
const resolved = typeof next === "function" ? next(textRef.current) : next;
textRef.current = resolved;
if (!controlled)
setOwnText(resolved);
onValueChange?.(resolved);
};
const localRef = useRef(null);
const textareaRef = inputRef ?? localRef;
useAutoGrow(textareaRef, text);
const dictation = useDictation({
...(voice || {}),
onText: (said) => setText((prev) => appendTranscript(prev, said)),
});
const voiceOn = voice !== false && dictation.supported;
const listening = dictation.status === "listening";
const transcribing = dictation.status === "transcribing";
// The paperclip, the same as every other box's (typing.tsx). `take`: the
// app takes the files itself, nothing is staged here.
const paperclip = useTypingAttach({
attach,
notes: labels.attachNotes,
dictation,
voiceOn: voice !== false,
disabled,
});
const { on: attachOn, attachments, take, onFiles } = paperclip;
const attachCount = (attachOn ? attachments.attachments.length : 0) + Math.max(0, heldAttachments);
// A message of only attachments may go out wordless: to the rule below that
// is "the app has said what such a message means", and it means nothing.
const wordless = attachmentsAlone && !attachmentOnlyText;
const canSend = composerCanSend({
text,
attachmentCount: attachCount,
attachmentOnlyText: wordless ? "\u2060" : attachmentOnlyText,
sending,
disabled,
blocked: Boolean(sendBlockedReason),
queue,
});
const submit = async () => {
if (!canSend)
return;
const sent = text;
const outgoing = composerOutgoingText(sent, attachCount, wordless ? undefined : attachmentOnlyText);
const result = await onSend(outgoing, attachOn ? attachments.toWire() : []);
if (!shouldClearDraft(result))
return;
// Only clear what was sent: words typed while a slow send was in flight
// are the next message.
if (textRef.current === sent)
setText("");
attachments.clear();
};
// The handle presses the CURRENT Send, never the one its first render saw.
const submitRef = useRef(submit);
useEffect(() => {
submitRef.current = submit;
});
useImperativeHandle(handleRef, () => ({
setText: (next) => setText(next),
addFiles: (files) => {
if (!attachOn)
return;
if (take)
take(Array.from(files));
else
attachments.addFiles(files);
},
focus: () => textareaRef.current?.focus(),
submit: () => submitRef.current(),
}));
const showModes = Boolean(modes && modes.length > 1);
const inline = layout === "inline";
const extras = attachExtras ?? [];
// One microphone, drawn where the layout puts it: among the tools of a
// stacked box, beside Send in an inline one (where the thumb is).
const mic = _jsx(MicButton, { dictation: dictation, disabled: disabled, labels: labels });
return (_jsxs("div", { className: "ck-composer-wrap", children: [above, _jsxs("div", { className: "ck-composer-frame", children: [_jsx(VoiceBar, { dictation: dictation, labels: labels }), _jsxs("div", { className: [
"ck-composer",
density === "compact" ? "ck-composer-compact" : "",
inline ? "ck-composer-inline" : "",
]
.filter(Boolean)
.join(" "),
// A file dragged onto the box is a file picked: the same path, the
// same limits. Only files are taken; dragged text lands in the
// textarea as the browser always did.
onDragOver: paperclip.onDragOver, onDrop: paperclip.onDrop, children: [showModes && (_jsx("div", { className: "ck-modes", role: "group", children: modes.map((m) => (_jsx("button", { type: "button", className: "ck-mode", "aria-pressed": m.id === mode, title: m.hint, onClick: () => onModeChange?.(m.id), children: m.label }, m.id))) })), header, attachOn && stagedPosition === "above" && (_jsx(AttachmentStrip, { attachments: attachments, remove: labels.remove })), _jsx("textarea", { ref: textareaRef, className: "ck-input", rows: 1, value: text, autoFocus: autoFocus, disabled: disabled || transcribing, placeholder: listening ? labels.listening : sending && queue ? labels.queue : placeholder, "aria-label": ariaLabel ?? placeholder, enterKeyHint: "send", onChange: (e) => {
const next = e.target.value;
if (onEmptySlash && next === "/" && text === "") {
onEmptySlash();
return;
}
setText(next);
}, onPaste: paperclip.onPaste, onKeyDown: (e) => {
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
void submit();
}
} }), attachOn && stagedPosition === "below" && (_jsx(AttachmentStrip, { attachments: attachments, remove: labels.remove })), _jsxs("div", { className: "ck-actions", children: [_jsxs("div", { className: "ck-tools", children: [(attachOn || extras.length > 0) && (_jsx(AttachMenu, { onFiles: onFiles, disabled: disabled || (attachments.full && extras.length === 0), labels: { attach: labels.attach, ...labels.attachMenu }, sources: attachOn ? paperclip.sources : [], accept: paperclip.accept, rows: extras })), voiceOn && !inline && mic, tools, hint && _jsx("span", { className: "ck-hint", children: hint })] }), _jsxs("div", { className: "ck-submit", children: [trailing, voiceOn && inline && mic, sending && onStop ? (_jsxs(_Fragment, { children: [queue && canSend && (_jsx("button", { type: "button", className: "ck-send", onClick: () => void submit(), "aria-label": labels.send, title: labels.send, children: _jsx(IconArrowUp, {}) })), _jsx("button", { type: "button", className: "ck-send ck-send-stop", onClick: onStop, "aria-label": labels.stop, title: labels.stop, children: _jsx(IconStop, {}) })] })) : (!listening &&
(emptyAction && !canSend && !sending && !text.trim() ? (_jsx("button", { type: "button", className: "ck-send ck-send-empty", disabled: disabled, onClick: emptyAction.onPress, "aria-label": emptyAction.label, title: emptyAction.label, children: emptyAction.icon })) : (_jsx("button", { type: "button", className: "ck-send", disabled: !canSend, onClick: () => void submit(), "aria-label": labels.send, title: sendBlockedReason ?? labels.send, children: sending ? _jsx(IconSpinner, {}) : _jsx(IconArrowUp, {}) }))))] })] }), footer] })] }), _jsx(VoiceProblem, { dictation: dictation, labels: labels })] }));
}
//# sourceMappingURL=Composer.js.map