Files
chatkit/dist/react/DictationField.js
T
CatoandClaude fd7031ea04 feat(composer, field): one box — Composer and DictationField are two shapes of one implementation (0.43.0) (#111)
The four steps 0.41 left in the README are done:
- One frame: TypingBox (typing.tsx) draws the voice bar, box, strip, text,
  tools row and the take's problem for both. The field's tools row is the
  composer's ck-tools, so its paperclip and microphone are bare icons like
  the composer's (they were bordered circles). Frame and text share one set
  of rules in styles.css; each shape keeps only its differences.
- One text hookup: useTypingText (dictation + appendTranscript +
  clipToMaxLength + the latest-text ref).
- One submit-key rule: submitKeyAction in composer.ts, exported.
- Same controls on both: Composer `attachments`; DictationField
  `handleRef` (DictationFieldHandle) and `attachExtras`.

Public APIs are additive. All existing tests unchanged; new unit, render
and browser checks (390px, 320px dark, desktop).


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-15 16:50:56 +01:00

201 lines
11 KiB
JavaScript

"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useId, useImperativeHandle, useRef, useState, } from "react";
import { clipToMaxLength, submitKeyAction } from "../composer.js";
import { useAutoGrow } from "./hooks.js";
import { useFieldFocus } from "./field-focus.js";
import { DEFAULT_TYPING_ATTACH_LABELS, DEFAULT_TYPING_VOICE_LABELS, MicButton, PaperclipButton, TypingBox, addFilesThroughPaperclip, mergeAttachLabels, submitKeyOf, useTypingAttach, useTypingText, } from "./typing.js";
export const DEFAULT_DICTATION_FIELD_LABELS = {
// The microphone's and the paperclip's words are every box's (typing.tsx).
...DEFAULT_TYPING_VOICE_LABELS,
improve: "Improve",
improveWhat: "What should change?",
improveApply: "Change it",
improveWorking: "Working on it…",
improveFailed: "That did not work just now. Your text is unchanged; try again, or edit it by hand.",
improved: "Changed by writing help.",
undo: "Undo",
...DEFAULT_TYPING_ATTACH_LABELS,
};
/**
* ANY text box a person types words into: the microphone is part of it.
*
* This is the rule from AGENTS.md ("The experience belongs to the package")
* made a component: a field made by hand in an app has no microphone, 14px
* text that makes iOS zoom the page, and no way to take a failed take back —
* so there is one, and it is this. `Composer` is the same thing for a
* conversation (it also sends); this is for everything else: a note, a title,
* a bio, a message to a seller.
*
* Controlled. Dictation appends to what is there. With `improve`, a field that
* has text offers one more control: pick a suggestion or say or type what to
* change, the text is replaced, and Undo puts it back until the next edit.
*/
export function DictationField({ value, onValueChange, label, ariaLabel, id, placeholder, multiline = true, rows = 3, maxLength, disabled = false, required, name, autoFocus, readOnly = false, invalid = false, error, onKeyDown, onSubmit, onFocus, onBlur, inputProps, voice = {}, improve, attach = false, attachments: attachmentsGiven, attachExtras, handleRef, hint, inputRef, labels: overrides, className, }) {
const labels = {
...DEFAULT_DICTATION_FIELD_LABELS,
...overrides,
dictation: { ...DEFAULT_DICTATION_FIELD_LABELS.dictation, ...overrides?.dictation },
...mergeAttachLabels(DEFAULT_DICTATION_FIELD_LABELS, overrides),
};
const autoId = useId();
const fieldId = id ?? `ck-field-${autoId}`;
// The words and the microphone that adds to them: every box's (typing.tsx).
// `valueRef` is the latest text, for a take that finishes after more typing.
const { textRef: valueRef, setText: set, dictation, } = useTypingText({
text: value,
commit: onValueChange,
voice,
maxLength,
onSaid: () => setUndo(null),
});
const areaRef = useRef(null);
useAutoGrow(areaRef, multiline ? value : "");
const voiceOn = voice !== false && dictation.supported && !readOnly;
const listening = dictation.status === "listening";
const transcribing = dictation.status === "transcribing";
// The paperclip, the same as the composer's (typing.tsx). Never on a
// read-only field: there is nothing to add to.
const paperclip = useTypingAttach({
attach: readOnly ? false : attach,
controller: attachmentsGiven,
notes: labels.attachNotes,
dictation,
voiceOn: voice !== false,
disabled,
});
const attachOn = paperclip.on;
const [open, setOpen] = useState(false);
const [working, setWorking] = useState(false);
// Improve at work disables its own box and button, so focus falls off them
// with nowhere to go: the person is still in the field, waiting.
const focus = useFieldFocus({
busy: dictation.status !== "idle" || working,
onFocus,
onBlur,
});
// An error with no words (`error=""` from a `?? ""`, a `0` from `n && msg`)
// is no error: colour must never be the only sign.
const hasError = error !== undefined && error !== null && error !== false && error !== "" && error !== 0;
const isInvalid = invalid || hasError;
const hintId = hint ? `${fieldId}-hint` : undefined;
const errorId = hasError ? `${fieldId}-error` : undefined;
const describedBy = [inputProps?.["aria-describedby"], errorId, hintId].filter(Boolean).join(" ") || undefined;
const [failed, setFailed] = useState(false);
const [instruction, setInstruction] = useState("");
const [undo, setUndo] = useState(null);
const run = async (what) => {
if (!improve || working || !what.trim())
return;
setWorking(true);
setFailed(false);
const before = valueRef.current;
try {
const next = await improve.run(before, what.trim());
if (typeof next === "string" && next.trim()) {
setUndo(before);
set(clipToMaxLength(next, maxLength));
setOpen(false);
setInstruction("");
}
else
setFailed(true);
}
catch {
setFailed(true);
}
finally {
setWorking(false);
}
};
const canImprove = Boolean(improve) && !readOnly && value.trim().length > 0;
const common = {
id: fieldId,
className: "ck-field-input",
style: undefined,
value,
placeholder: listening ? labels.listening : placeholder,
maxLength,
required,
name,
autoFocus,
readOnly: readOnly || undefined,
disabled: disabled || transcribing,
"aria-label": label ? undefined : (ariaLabel ?? placeholder),
"aria-invalid": isInvalid ? true : undefined,
"aria-describedby": describedBy,
// The app's own paste handler runs first; the paperclip's only when on.
...(attachOn
? {
onPaste: (e) => {
inputProps?.onPaste?.(e);
if (!e.defaultPrevented)
paperclip.onPaste(e);
},
}
: {}),
};
const locked = disabled || readOnly;
const busy = dictation.status !== "idle";
const handleKeyDown = (e) => {
onKeyDown?.(e);
if (!onSubmit || e.defaultPrevented)
return;
// The one submit-key rule (composer.ts). A key that would submit and may
// not is still the package's: in a one-line field the browser would
// otherwise send the native form, mid-take, without the words.
const action = submitKeyAction(submitKeyOf(e), {
shape: multiline ? "multiline" : "single",
busy,
locked,
});
if (action === "type")
return;
e.preventDefault();
if (action === "submit")
onSubmit();
};
const extras = readOnly ? [] : (attachExtras ?? []);
const fieldRef = useRef(null);
// The handle submits with the CURRENT props, never the first render's.
const submitRef = useRef(async () => { });
useEffect(() => {
submitRef.current = async () => {
if (!onSubmit || locked || busy)
return;
onSubmit();
};
});
useImperativeHandle(handleRef, () => ({
setText: (next) => {
if (readOnly)
return;
setUndo(null);
set(clipToMaxLength(next, maxLength));
},
addFiles: (files) => addFilesThroughPaperclip(paperclip, files),
focus: () => fieldRef.current?.focus(),
submit: () => submitRef.current(),
}));
const onChange = (next) => {
setUndo(null);
set(next);
};
const setRefs = (el) => {
fieldRef.current = el;
if (multiline)
areaRef.current = el;
if (typeof inputRef === "function")
inputRef(el);
else if (inputRef)
inputRef.current = el;
};
const input = multiline ? (_jsx("textarea", { ...inputProps, ...common, ref: setRefs, rows: rows, onChange: (e) => onChange(e.target.value), onKeyDown: handleKeyDown })) : (_jsx("input", { ...inputProps, ...common, ref: setRefs, type: "text", enterKeyHint: inputProps?.enterKeyHint ?? "done", onChange: (e) => onChange(e.target.value), onKeyDown: handleKeyDown }));
return (_jsx(TypingBox, { wrapRef: focus.wrapRef, wrapClassName: ["ck-field-wrap", isInvalid && "ck-field-invalid", className]
.filter(Boolean)
.join(" "), onWrapFocus: focus.onFocus, onWrapBlur: focus.onBlur, frameClassName: "ck-field-frame", boxClassName: multiline ? "ck-field" : "ck-field ck-field-single", dictation: dictation, voiceLabels: labels, paperclip: paperclip, removeLabel: labels.remove, above: label && (_jsx("label", { className: "ck-field-label", htmlFor: fieldId, children: label })), input: input, tools: _jsxs("div", { className: "ck-field-actions ck-tools", children: [_jsx(PaperclipButton, { paperclip: paperclip, extras: extras, disabled: disabled, labels: labels }), canImprove && (_jsx("button", { type: "button", className: "ck-field-improve", "aria-expanded": open, disabled: disabled || working, onClick: () => setOpen((o) => !o), children: labels.improve })), voiceOn && _jsx(MicButton, { dictation: dictation, disabled: disabled, labels: labels })] }), below: _jsxs(_Fragment, { children: [errorId && (_jsx("p", { id: errorId, className: "ck-field-error", role: "alert", children: error })), open && improve && !readOnly && (_jsxs("div", { className: "ck-field-improve-panel", children: [improve.suggestions && improve.suggestions.length > 0 && (_jsx("div", { className: "ck-field-suggestions", role: "group", children: improve.suggestions.map((s) => (_jsx("button", { type: "button", className: "ck-field-suggestion", disabled: working, onClick: () => void run(s), children: s }, s))) })), _jsxs("div", { className: "ck-field-improve-row", children: [_jsx(DictationField, { value: instruction, onValueChange: setInstruction, multiline: false, placeholder: labels.improveWhat, ariaLabel: labels.improveWhat, voice: voice, disabled: working, labels: overrides, onSubmit: () => void run(instruction) }), _jsx("button", { type: "button", className: "ck-field-apply", disabled: working || !instruction.trim(), onClick: () => void run(instruction), children: working ? labels.improveWorking : labels.improveApply })] }), failed && (_jsx("p", { className: "ck-problem", role: "alert", children: _jsx("span", { children: labels.improveFailed }) }))] })), undo !== null && !readOnly && (_jsxs("p", { className: "ck-field-undo", role: "status", children: [_jsx("span", { children: labels.improved }), _jsx("button", { type: "button", className: "ck-problem-retry", onClick: () => {
set(undo);
setUndo(null);
}, children: labels.undo })] }))] }), after: hint && (_jsx("div", { id: hintId, className: "ck-field-hint", children: hint })) }));
}
//# sourceMappingURL=DictationField.js.map