Files
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

244 lines
12 KiB
JavaScript

"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
* The one way a person types, shared by `Composer` and `DictationField`.
*
* Both boxes carry the same microphone and, when the app asks, the same
* paperclip: the same sheet (Camera · Photos · Files), the same staging with
* the same limits and notes, the same paste-to-attach, the same drop, the same
* strip of staged previews with Remove, and a recording that arrives as a file
* transcribed into the words rather than staged. Everything here is wiring the
* two components used to keep twice; it lives once, so they cannot drift.
*
* Since 0.43 the whole box is here too: the frame (`TypingBox`), the text and
* the microphone that adds to it (`useTypingText`), and the submit key
* (`submitKeyAction` in composer.ts). `Composer` and `DictationField` are two
* shapes of this one box: they differ only in what they put in its slots.
*
* Internal: not exported from the package. The public pieces stay where they
* were (`AttachMenu`, `useAttachments`, `AttachOptions`, `submitKeyAction`).
*/
import { useEffect, useRef, } from "react";
import { appendTranscript, clipToMaxLength } from "../composer.js";
import { DEFAULT_DICTATION_MESSAGES, isAudioFile } from "../dictation.js";
import { DEFAULT_ATTACHMENT_NOTES, } from "../attachments.js";
import { useAttachments } from "./use-attachments.js";
import { useDictation, } from "./use-dictation.js";
import { AttachMenu, DEFAULT_ATTACH_MENU_LABELS, } from "./AttachMenu.js";
import { VoiceBar, VoiceProblem } from "./Voice.js";
import { IconFile, IconMic, IconSpinner, IconX } from "./icons.js";
export const DEFAULT_TYPING_VOICE_LABELS = {
voice: "Speak instead of typing",
voiceStop: "Stop recording",
cancelRecording: "Cancel recording",
confirmRecording: "Done — use what I said",
listening: "Listening…",
transcribing: "Transcribing…",
dismiss: "Dismiss",
retryTake: "Try again",
dictation: DEFAULT_DICTATION_MESSAGES,
};
export const DEFAULT_TYPING_ATTACH_LABELS = {
attach: DEFAULT_ATTACH_MENU_LABELS.attach,
attachMenu: {
title: DEFAULT_ATTACH_MENU_LABELS.title,
close: DEFAULT_ATTACH_MENU_LABELS.close,
sources: DEFAULT_ATTACH_MENU_LABELS.sources,
},
remove: (name) => `Remove ${name}`,
attachNotes: DEFAULT_ATTACHMENT_NOTES,
};
/** The nested attach labels with an app's overrides, one level deep each. */
export function mergeAttachLabels(defaults, overrides) {
return {
attachNotes: { ...defaults.attachNotes, ...overrides?.attachNotes },
attachMenu: {
...defaults.attachMenu,
...overrides?.attachMenu,
sources: { ...defaults.attachMenu.sources, ...overrides?.attachMenu?.sources },
},
};
}
/**
* The paperclip's behaviour for a box: one implementation for `Composer` and
* `DictationField`. `controller` is an `AttachmentsController` the APP owns
* (`useAttachments`), so it can read the staged files at its own submit and
* clear them after; without one the box stages into its own.
*/
export function useTypingAttach({ attach, controller, notes, dictation, voiceOn, disabled, }) {
const options = typeof attach === "object" ? attach : undefined;
const own = useAttachments(options ?? {}, notes);
const attachments = controller ?? own;
const on = attach !== false;
const take = options?.take;
// The paperclip takes recordings too (through Files), when there is
// somewhere to send them. A voice memo is not an attachment the model reads —
// it is words the person said, so it goes to the same server leg as the mic
// and lands in the box. Recordings are transcribed in the order picked;
// everything else is staged.
const takesAudio = voiceOn && dictation.canTranscribeFile;
const onFiles = (files) => {
if (!files)
return;
const all = Array.from(files);
if (all.length === 0)
return;
if (take) {
take(all);
return;
}
const audio = takesAudio ? all.filter(isAudioFile) : [];
const rest = all.filter((f) => !audio.includes(f));
if (rest.length > 0)
attachments.addFiles(rest);
if (audio.length > 0) {
void (async () => {
for (const file of audio)
await dictation.transcribeFile(file);
})();
}
};
const onPaste = (e) => {
if (!on)
return;
if (take) {
// Whatever the clipboard holds as a file is the app's to take;
// pasted text stays text.
const pasted = Array.from(e.clipboardData.files);
if (pasted.length > 0) {
e.preventDefault();
take(pasted);
}
return;
}
if (attachments.addFromPaste(e))
e.preventDefault();
};
// Only files are taken; dragged text lands in the text box as the browser
// always did.
const onDragOver = (e) => {
if (on && !disabled && e.dataTransfer.types.includes("Files"))
e.preventDefault();
};
const onDrop = (e) => {
if (!on || disabled || e.dataTransfer.files.length === 0)
return;
e.preventDefault();
onFiles(e.dataTransfer.files);
};
return {
on,
attachments,
take,
sources: options?.sources,
accept: options?.accept,
onFiles,
onPaste,
onDragOver,
onDrop,
};
}
/** The staged files: a thumbnail or a name, each with Remove; and the note
* that says why a file did not attach. */
export function AttachmentStrip({ attachments, remove, }) {
if (attachments.attachments.length === 0 && !attachments.note)
return null;
return (_jsxs("div", { className: "ck-attach-strip", children: [attachments.attachments.map((a) => {
const key = attachments.keyOf(a);
return (_jsxs("div", { className: "ck-attach-item", children: [a.kind === "image" && a.previewUrl ? (_jsx("img", { src: a.previewUrl, alt: a.name, className: "ck-attach-thumb" })) : (_jsxs("span", { className: "ck-attach-file", children: [_jsx(IconFile, {}), _jsx("span", { className: "ck-truncate", children: a.name })] })), _jsx("button", { type: "button", className: "ck-attach-remove", onClick: () => attachments.remove(key), "aria-label": remove(a.name), title: remove(a.name), children: _jsx(IconX, {}) })] }, key));
}), attachments.note && (_jsx("button", { type: "button", className: "ck-note", onClick: attachments.clearNote, children: attachments.note }))] }));
}
/** THE microphone button: one look, one set of states, in every box. */
export function MicButton({ dictation, disabled, labels, }) {
const listening = dictation.status === "listening";
const transcribing = dictation.status === "transcribing";
return (_jsx("button", { type: "button", className: listening ? "ck-icon-btn ck-mic ck-mic-on" : "ck-icon-btn ck-mic", onClick: dictation.toggle, disabled: disabled || transcribing, "aria-label": listening ? labels.voiceStop : labels.voice, "aria-pressed": listening, title: listening ? labels.voiceStop : labels.voice, children: transcribing ? _jsx(IconSpinner, {}) : _jsx(IconMic, {}) }));
}
/** A key press as the submit rule reads it (`submitKeyAction`). */
export function submitKeyOf(e) {
return {
key: e.key,
shiftKey: e.shiftKey,
altKey: e.altKey,
metaKey: e.metaKey,
ctrlKey: e.ctrlKey,
isComposing: e.nativeEvent.isComposing,
keyCode: e.keyCode,
};
}
/** `handleRef`'s `addFiles`: what the paperclip would do with these files. */
export function addFilesThroughPaperclip(paperclip, files) {
if (!paperclip.on)
return;
if (paperclip.take)
paperclip.take(Array.from(files));
else
paperclip.attachments.addFiles(files);
}
/**
* The text of a box and the microphone that adds to it: one hookup for every
* box. What was said joins the words with one space (`appendTranscript`) and
* stays within `maxLength` (`clipToMaxLength`); a take that ends after more
* typing joins the LATEST words, never the ones the take started on.
*
* `commit` applies a new text (the box's own state, the app's
* `onValueChange`); `setText` is the only way the box changes its words.
*/
export function useTypingText({ text, commit, voice, maxLength, onSaid, }) {
// Mirrored so a take or an async send reads the CURRENT words, not the ones
// 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;
commit(resolved);
};
const dictation = useDictation({
...(voice || {}),
onText: (said) => {
onSaid?.();
setText(clipToMaxLength(appendTranscript(textRef.current, said), maxLength));
},
});
return { textRef, setText, dictation };
}
/** THE paperclip button: the same sheet, sources and app rows in every box. */
export function PaperclipButton({ paperclip, extras, disabled, labels, }) {
if (!paperclip.on && extras.length === 0)
return null;
return (_jsx(AttachMenu, { onFiles: paperclip.onFiles, disabled: disabled || (paperclip.attachments.full && extras.length === 0), labels: { attach: labels.attach, ...labels.attachMenu }, sources: paperclip.on ? paperclip.sources : [], accept: paperclip.accept, rows: extras }));
}
/**
* THE box a person types in, drawn once for `Composer` and `DictationField`:
*
* wrap
* above (composer: suggestion chips; field: its label)
* frame
* voice bar (covers the box while a take is live)
* box (a dropped file is a file picked)
* header (composer: modes, the app's header)
* strip (staged files, when `stagedPosition` is "above")
* input (the textarea or one-line input)
* strip (staged files, below: the default)
* tools (the tools row: paperclip, microphone, the rest)
* footer
* below (field: its error, Improve's panel, Undo)
* the take's problem, in words
* after (field: its hint)
*
* The class names are each shape's public hooks (`ck-composer…`, `ck-field…`)
* and stay as they were; the tools row is `ck-tools` in both, so a tool looks
* the same in every box.
*/
export function TypingBox({ wrapClassName, wrapRef, onWrapFocus, onWrapBlur, frameClassName, boxClassName, dictation, voiceLabels, paperclip, removeLabel, stagedPosition = "below", above, header, input, tools, footer, below, after, }) {
const strip = paperclip.on && (_jsx(AttachmentStrip, { attachments: paperclip.attachments, remove: removeLabel }));
return (_jsxs("div", { ref: wrapRef, className: wrapClassName, onFocus: onWrapFocus, onBlur: onWrapBlur, children: [above, _jsxs("div", { className: frameClassName, children: [_jsx(VoiceBar, { dictation: dictation, labels: voiceLabels }), _jsxs("div", { className: boxClassName,
// 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 text
// box as the browser always did.
onDragOver: paperclip.onDragOver, onDrop: paperclip.onDrop, children: [header, stagedPosition === "above" && strip, input, stagedPosition === "below" && strip, tools, footer] })] }), below, _jsx(VoiceProblem, { dictation: dictation, labels: voiceLabels }), after] }));
}
//# sourceMappingURL=typing.js.map