mirror of
https://github.com/bitbaum/chatkit.git
synced 2026-12-04 12:27:33 +01:00
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>
187 lines
11 KiB
JavaScript
187 lines
11 KiB
JavaScript
"use client";
|
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
import { useEffect, useId, useRef, useState, } from "react";
|
|
import { appendTranscript, clipToMaxLength } from "../composer.js";
|
|
import { useDictation } from "./use-dictation.js";
|
|
import { useAutoGrow } from "./hooks.js";
|
|
import { useFieldFocus } from "./field-focus.js";
|
|
import { VoiceBar, VoiceProblem } from "./Voice.js";
|
|
import { AttachMenu } from "./AttachMenu.js";
|
|
import { AttachmentStrip, DEFAULT_TYPING_ATTACH_LABELS, DEFAULT_TYPING_VOICE_LABELS, MicButton, mergeAttachLabels, useTypingAttach, } 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, 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 latest text, for a take that finishes after more typing.
|
|
const valueRef = useRef(value);
|
|
useEffect(() => {
|
|
valueRef.current = value;
|
|
});
|
|
const set = (next) => {
|
|
valueRef.current = next;
|
|
onValueChange(next);
|
|
};
|
|
const areaRef = useRef(null);
|
|
useAutoGrow(areaRef, multiline ? value : "");
|
|
const dictation = useDictation({
|
|
...(voice || {}),
|
|
onText: (said) => {
|
|
setUndo(null);
|
|
set(clipToMaxLength(appendTranscript(valueRef.current, said), maxLength));
|
|
},
|
|
});
|
|
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 handleKeyDown = (e) => {
|
|
onKeyDown?.(e);
|
|
if (!onSubmit || e.defaultPrevented || e.key !== "Enter")
|
|
return;
|
|
// An Enter that confirms an IME composition (Japanese, Chinese, Korean)
|
|
// is the person choosing a word, not sending.
|
|
if (e.nativeEvent.isComposing || e.keyCode === 229)
|
|
return;
|
|
const chord = e.metaKey || e.ctrlKey;
|
|
if (multiline && !chord)
|
|
return; // a new line
|
|
// From here the key is the package's: in a one-line field the browser
|
|
// would otherwise send the native form, mid-take, without the words.
|
|
e.preventDefault();
|
|
if (disabled || readOnly || dictation.status !== "idle")
|
|
return;
|
|
if (!multiline && (e.shiftKey || e.altKey))
|
|
return;
|
|
onSubmit();
|
|
};
|
|
const onChange = (next) => {
|
|
setUndo(null);
|
|
set(next);
|
|
};
|
|
const setRefs = (el) => {
|
|
if (multiline)
|
|
areaRef.current = el;
|
|
if (typeof inputRef === "function")
|
|
inputRef(el);
|
|
else if (inputRef)
|
|
inputRef.current = el;
|
|
};
|
|
return (_jsxs("div", { ref: focus.wrapRef, className: ["ck-field-wrap", isInvalid && "ck-field-invalid", className]
|
|
.filter(Boolean)
|
|
.join(" "), onFocus: focus.onFocus, onBlur: focus.onBlur, children: [label && (_jsx("label", { className: "ck-field-label", htmlFor: fieldId, children: label })), _jsxs("div", { className: "ck-field-frame", children: [_jsx(VoiceBar, { dictation: dictation, labels: labels }), _jsxs("div", { className: multiline ? "ck-field" : "ck-field ck-field-single", onDragOver: attachOn ? paperclip.onDragOver : undefined, onDrop: attachOn ? paperclip.onDrop : undefined, children: [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 })), attachOn && (_jsx(AttachmentStrip, { attachments: paperclip.attachments, remove: labels.remove })), _jsxs("div", { className: "ck-field-actions", children: [attachOn && (_jsx(AttachMenu, { onFiles: paperclip.onFiles, disabled: disabled || paperclip.attachments.full, labels: { attach: labels.attach, ...labels.attachMenu }, sources: paperclip.sources, accept: paperclip.accept })), 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 })] })] })] }), 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 })] })), _jsx(VoiceProblem, { dictation: dictation, labels: labels }), hint && (_jsx("div", { id: hintId, className: "ck-field-hint", children: hint }))] }));
|
|
}
|
|
//# sourceMappingURL=DictationField.js.map
|