"use client"; import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; import { forwardRef, useEffect, useLayoutEffect, 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 (`value`) or uncontrolled (`defaultValue` + `name`, posted by a * native form). `ref`, `name`, `onChange(event)` and `onBlur(event)` make it * a drop-in for react-hook-form's `register()` and `Controller`. * 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 const DictationField = forwardRef(function DictationField(props, ref) { return _jsx(Field, { ...props, forwardedRef: ref }); }); const eventOf = (type, el) => ({ type, target: el, currentTarget: el }); function Field({ value: valueGiven, defaultValue, onValueChange, onChange: onChangeEvent, 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, forwardedRef, }) { 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}`; // Uncontrolled: the text box keeps its own words (so a native form posts // and resets them, and a form library may write them), mirrored here for // the microphone, Improve and the height. const controlled = valueGiven !== undefined; const [own, setOwn] = useState(defaultValue ?? ""); const value = controlled ? valueGiven : own; const fieldRef = useRef(null); const changeRef = useRef({ onValueChange, onChangeEvent, controlled }); useLayoutEffectSafe(() => { changeRef.current = { onValueChange, onChangeEvent, controlled }; }); // Words that did not come from a keystroke: put them in the box first, so // an event's `target.value` is already the new text. const commit = (next) => { const { onValueChange: text, onChangeEvent: event, controlled: held } = changeRef.current; const el = fieldRef.current; // Controlled with no event listener: React writes the box from `value`. if (el && (!held || event) && el.value !== next) el.value = next; if (!held) setOwn(next); text?.(next); if (el) event?.(eventOf("change", el)); }; // 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, 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: onBlur ? () => { const el = fieldRef.current; if (el) onBlur(eventOf("blur", el)); } : undefined, }); // Uncontrolled: something else may have written the box (a form library's // reset, autofill). Read it back before the person adds to it. const syncFromBox = () => { const el = fieldRef.current; if (!controlled && el && el.value !== valueRef.current) { valueRef.current = el.value; setOwn(el.value); } }; // A native form reset puts the box back to `defaultValue`; follow it. useEffect(() => { const form = fieldRef.current?.form; if (!form) return; const onReset = () => setTimeout(() => { setUndo(null); const el = fieldRef.current; if (!el) return; if (!controlled) syncFromBox(); else if (el.value !== valueRef.current) commit(el.value); }, 0); form.addEventListener("reset", onReset); return () => form.removeEventListener("reset", onReset); }); // 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, ...(controlled ? { value } : { defaultValue: defaultValue ?? "" }), 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 ?? []); // 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(), })); // A keystroke: the box already holds the words; the app gets the real event. const onChange = (e) => { const next = e.target.value; setUndo(null); valueRef.current = next; if (!controlled) setOwn(next); onValueChange?.(next); onChangeEvent?.(e); }; const setRefs = (el) => { fieldRef.current = el; if (multiline) areaRef.current = el; for (const r of [inputRef, forwardedRef]) { if (typeof r === "function") r(el); else if (r) r.current = el; } }; const input = multiline ? (_jsx("textarea", { ...inputProps, ...common, ref: setRefs, rows: rows, onChange: onChange, onKeyDown: handleKeyDown })) : (_jsx("input", { ...inputProps, ...common, ref: setRefs, type: "text", enterKeyHint: inputProps?.enterKeyHint ?? "done", onChange: onChange, onKeyDown: handleKeyDown })); return (_jsx(TypingBox, { wrapRef: focus.wrapRef, wrapClassName: ["ck-field-wrap", isInvalid && "ck-field-invalid", className] .filter(Boolean) .join(" "), onWrapFocus: () => { syncFromBox(); 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 })) })); } // The server has no layout; an effect is enough there. const useLayoutEffectSafe = typeof window === "undefined" ? useEffect : useLayoutEffect; //# sourceMappingURL=DictationField.js.map