Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/composer-mic-control.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-kit": minor
---

`Composer` can host the hold-to-talk `MicButton` (#3727). The new optional `micControl` prop places a caller-drawn mic in the mic slot. The field grows from 46px to 54px to fit the 44px target, and on a multi-line draft attach, the mic and Send sit on the last line. While `micControl` is set, `mic`, `onMic` and `micLabel` are ignored. Without it, the composer is unchanged.
1 change: 1 addition & 0 deletions api-report/ui-kit.txt
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,7 @@ signatures (every public export and the types it is made of)
micLabel?: string;
micTip?: boolean;
micUnavailable?: string;
micControl?: ReactNode;
maxRows?: number;
}
ComposerRecall (packages/ui-kit/src/chrome/Composer.tsx)
Expand Down
14 changes: 14 additions & 0 deletions docs/integration-contract/package-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -4905,6 +4905,20 @@ an `aria-hidden` pointer tooltip; an inert trigger, including a dictating
composer's, has neither. Existing props and defaults are otherwise unchanged,
and no wire schema changes. `api-report/` records the added prop.

<a id="composer-mic-control-additive-0450-3727"></a>

## Composer mic control (additive, 0.45.0, #3727)

`ComposerProps` in `@schlessera/brain-ui-kit` gains optional
`micControl?: ReactNode`, a caller-drawn mic (the kit's `MicButton`) in the
`send` and `plain` field's mic slot. When it is set, `mic`, `onMic`,
`micLabel`, `micTip` and `micUnavailable` are ignored, the slot takes the
control's 44px target with -4px
block margins (a 54px field), and the field aligns its controls to the last
line of a multi-line draft. The `voice` variant keeps its own disc. Omitted,
the composer renders exactly as before. No wire schema changes.
`api-report/` records the added prop.


## Prospective trust policy data (additive, #3607)

Expand Down
50 changes: 43 additions & 7 deletions packages/ui-kit/src/chrome/Composer.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { CSSProperties, ChangeEvent, KeyboardEvent } from "react";
import type { CSSProperties, ChangeEvent, KeyboardEvent, ReactNode } from "react";
import { useId } from "react";

import { Icon, type IconName } from "../primitives/Icon.js";
Expand Down Expand Up @@ -152,6 +152,14 @@ export interface ComposerProps {
* its accessible description and tooltip, and a tap or key does nothing.
*/
micUnavailable?: string;
/**
* A caller-drawn mic (`MicButton`) in the mic slot (#3727). When set,
* `mic`, `onMic`, `micLabel`, `micTip` and `micUnavailable` are ignored;
* the slot gets margin-block -4px and the field aligns its controls to the
* last line. Absent = today, pixel for pixel. Drawn in the `send` and
* `plain` field; the `voice` variant keeps its own hold-to-talk disc.
*/
micControl?: ReactNode;
/** Rows the field may grow to, on ⇧⏎ or on soft wrap, before it scrolls. Five when omitted. */
maxRows?: number;
}
Expand Down Expand Up @@ -183,6 +191,16 @@ const LINE_RATIO = 1.45;
const LINE = FONT_SIZE * LINE_RATIO;
const CEILING = 96;

/**
* Beside a caller's mic (#3727) the field's controls sit on its last line,
* centred on the mic. The mic slot is 36px tall (its 44px target with -4px
* block margins), so a 28px control rises 4px and the last line of text rises
* by half of what the slot has over one line.
*/
const MIC_SLOT = 36;
const LIFT = (MIC_SLOT - 28) / 2;
const TEXT_LIFT = (MIC_SLOT - LINE) / 2;

/** Each state's placeholder and hint; `why` is the offline reason. */
const STATE: Record<ComposerState, { ph: string; hint: string; why?: string }> = {
ready: { ph: "Ask your brain anything…", hint: "⌘K for commands · ⏎ to send · ⇧⏎ for a new line" },
Expand All @@ -207,7 +225,10 @@ export function Composer(p: ComposerProps) {
const recall = p.recall ?? [];

const showAttach = p.attach !== false && v !== "plain";
const showMic = p.mic !== false && (v === "send" || v === "plain");
const inField = v === "send" || v === "plain";
// A caller's mic replaces the kit's, and every prop of the kit's mic stops applying.
const micControl = inField && p.micControl != null && p.micControl !== false;
const showMic = !micControl && p.mic !== false && inField;
const voiceReasonId = useId();
const voiceUnavailable = p.micUnavailable !== undefined;
const voiceAct = Boolean(p.onMic) || voiceUnavailable;
Expand Down Expand Up @@ -244,7 +265,9 @@ export function Composer(p: ComposerProps) {
flex: 1,
minWidth: 0,
display: "flex",
alignItems: "center",
// A caller's 44px mic makes the field 54px tall; its controls then sit on
// the last line of a multi-line draft, as Send does in any chat.
alignItems: micControl ? "flex-end" : "center",
gap: 8,
background: color.surface,
// The edge lifts a step while a run is live: the field is busy, not idle.
Expand Down Expand Up @@ -274,6 +297,7 @@ export function Composer(p: ComposerProps) {
// `auto`, not the source's `hidden`: a clipped single-line SPAN is fine,
// a clipped input takes the caret off-screen as you type.
overflow: "auto",
...(micControl ? { marginBottom: TEXT_LIFT } : null),
};

const disc = (size: number, fill: string, glow: boolean): CSSProperties => ({
Expand All @@ -300,6 +324,10 @@ export function Composer(p: ComposerProps) {

const stopAct = Boolean(p.onStop);

// Beside a caller's mic, the 28px controls sit on the last line, centred on
// the mic. Spread only then, so the default field is unchanged.
const lastLine: CSSProperties | undefined = micControl ? { marginBottom: LIFT } : undefined;

const mono = (weight: number, size: number): string => `${weight} ${size}px/1.5 ${font.mono}`;
const oneLine: CSSProperties = { whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" };

Expand All @@ -325,7 +353,7 @@ export function Composer(p: ComposerProps) {
<div style={{ display: "flex", alignItems: "flex-end", gap: 10 }}>
<div style={field} className="bk-field">
{showAttach ? (
<IconButton icon="attach" label={p.attachLabel || ATTACH_LABEL} haspopup="menu" tip onClick={dictating ? undefined : p.onAttach} />
<IconButton icon="attach" label={p.attachLabel || ATTACH_LABEL} haspopup="menu" tip lift={lastLine} onClick={dictating ? undefined : p.onAttach} />
) : null}
<textarea
data-composer=""
Expand All @@ -340,10 +368,17 @@ export function Composer(p: ComposerProps) {
onChange={editable ? (e: ChangeEvent<HTMLTextAreaElement>) => p.onChange?.(e.target.value) : undefined}
onKeyDown={onKeyDown}
/>
{micControl ? (
// The 44px target, drawn 36px tall: -4px above and below keep the
// field at 54px with the whole target still inside its border.
<span data-composer-mic="" style={{ display: "flex", flex: "none", marginBlock: -4 }}>
{p.micControl}
</span>
) : null}
{showMic ? <IconButton icon="mic" label={p.micLabel ?? (dictating ? "Stop dictation" : "Dictate")} tip={p.micTip === true && !dictating} unavailable={dictating ? undefined : p.micUnavailable} targetSize={dictating ? 44 : 28} onClick={p.onMic} /> : null}
{showStop ? (
<span
style={{ ...disc(28, accent.red.fill, false), cursor: stopAct ? "pointer" : "default" }}
style={{ ...disc(28, accent.red.fill, false), cursor: stopAct ? "pointer" : "default", ...lastLine }}
className={stopAct ? "bk-control" : undefined}
role={stopAct ? "button" : undefined}
aria-label={stopAct ? "Stop generating" : undefined}
Expand All @@ -356,7 +391,7 @@ export function Composer(p: ComposerProps) {
) : null}
{showSend ? (
<span
style={sendStyle}
style={lastLine ? { ...sendStyle, ...lastLine } : sendStyle}
className={sendAct && !sendDisabled ? "bk-control" : undefined}
role={sendAct ? "button" : undefined}
aria-label={sendAct ? (sendDisabled ? "Send — unavailable" : "Send") : undefined}
Expand Down Expand Up @@ -500,7 +535,7 @@ function resetTip(trigger: HTMLElement, left: boolean) {
* keystroke: Escape, or opening the menu, hides it until the pointer leaves or
* focus moves away. An inert trigger — a dictating composer — has no tooltip.
*/
function IconButton(props: { icon: "attach" | "mic"; label: string; haspopup?: "menu"; tip?: boolean; unavailable?: string; targetSize?: number; onClick?: () => void }) {
function IconButton(props: { icon: "attach" | "mic"; label: string; haspopup?: "menu"; tip?: boolean; unavailable?: string; targetSize?: number; lift?: CSSProperties; onClick?: () => void }) {
const reasonId = useId();
const unavailable = props.unavailable;
// Unavailable still names itself and explains why, so it stays reachable.
Expand All @@ -524,6 +559,7 @@ function IconButton(props: { icon: "attach" | "mic"; label: string; haspopup?: "
cursor: unavailable !== undefined ? "not-allowed" : act ? "pointer" : "default",
opacity: unavailable !== undefined ? 0.45 : undefined,
"--hv-bg": token("hover-veil-strong"),
...props.lift,
} as CSSProperties
}
className={act ? (tip ? "bk-control bk-tip-host" : "bk-control") : undefined}
Expand Down
175 changes: 175 additions & 0 deletions packages/ui-kit/stories/chrome/ComposerMic.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import preview from "#.storybook/preview";
import type { ReactElement, ReactNode } from "react";
import { expect } from "storybook/test";

import { Composer } from "../../src/chrome/Composer.js";
import { overflowing, stage, wide } from "../_stage.js";
import { COMPOSER_MIC_TITLES, PROVIDER, REVIEW, composerWithMic, type ComposerMicId } from "./_composer-mic.js";

/**
* The hold-to-talk `MicButton` in the real composer (#3727, signed off on the
* issue with rulings M1 and M2): the caller passes it as `micControl`, and the
* row stays attach · text · mic · send.
*
* The mic's 44px target sits in the field with -4px block margins, so the
* field is 54px rather than 46px. Attach and Send sit on the last line of a
* multi-line draft. The hold hint and "Talk live…" are the mic's own: they
* float above the field and never move the layout.
*
* D1 rest, S1 holding with the hint, S1 with "Talk live…" focused, D6 review
* (plain editable text, no uncertain mark and no hint-line cue, M2) and the
* offline "Record on this device" mic, which has no hold (M1).
*/
const meta = preview.meta({
title: "Chrome/Composer with MicButton",
component: Composer,
decorators: [stage],
parameters: { stageWidth: 390 },
});

/** Room above the field for the hint and "Talk live…", which overlay whatever is there. */
const above = (children: ReactNode): ReactElement => <div style={{ width: "100%", paddingTop: 56 }}>{children}</div>;

const field = (root: HTMLElement) => root.querySelector<HTMLElement>(".bk-field")!;
const centre = (el: Element) => {
const box = el.getBoundingClientRect();
return box.top + box.height / 2;
};

/** D1: the mic takes the mic slot, and the field grows from 46px to 54px. */
export const Idle = meta.story({
render: () => composerWithMic("D1"),
play: async ({ canvas, canvasElement }) => {
await expect(field(canvasElement).getBoundingClientRect().height, "54px field").toBe(54);
const names = canvas.getAllByRole("button").map((b) => b.getAttribute("aria-label") ?? b.textContent?.trim());
await expect(names, "row order attach · Talk live… · mic · send, then the chip").toEqual([
"Attach — photo, camera, files",
"Talk live…",
"Dictate",
"Send",
`Model — ${PROVIDER}`,
]);
const mic = canvas.getByRole("button", { name: "Dictate" });
const box = mic.getBoundingClientRect();
await expect([box.width, box.height], "the 44px target").toEqual([44, 44]);
const outer = field(canvasElement).getBoundingClientRect();
await expect(box.top >= outer.top && box.bottom <= outer.bottom, "the target stays inside the border").toBe(true);
const disc = centre(canvasElement.querySelector(".bk-voice-mic-disc")!);
for (const name of ["Attach — photo, camera, files", "Send"]) {
await expect(Math.abs(centre(canvas.getByRole("button", { name })) - disc), `${name} centred on the mic`).toBeLessThanOrEqual(0.5);
}
await expect(Math.abs(centre(canvas.getByRole("textbox")) - disc), "one line centred on the mic").toBeLessThanOrEqual(1);
await expect(canvas.queryByText("Keep holding to talk live")).toBeNull();
},
});

/** S1 at 320px: the hint floats above the field, and the row does not overflow. */
export const HoldingWithHint = meta.story({
parameters: { stageWidth: 320 },
render: () => above(composerWithMic("S1")),
play: async ({ canvas, canvasElement }) => {
const hint = canvas.getByText("Keep holding to talk live");
await expect(hint).toBeVisible();
await expect(field(canvasElement).getBoundingClientRect().height, "the hint never moves the layout").toBe(54);
await expect(hint.getBoundingClientRect().bottom, "above the field").toBeLessThanOrEqual(field(canvasElement).getBoundingClientRect().top);
const mic = canvas.getByRole("button", { name: "Dictate" }).getBoundingClientRect();
await expect(Math.round(hint.getBoundingClientRect().right), "MicButton's own position: right-aligned to the mic").toBe(Math.round(mic.right));
await expect(overflowing(canvasElement, "*:not(.bk-voice-talk-live *)")).toEqual([]);
for (const row of canvasElement.querySelectorAll<HTMLElement>(".bk-field, [data-composer-hint]")) {
await expect(row.scrollWidth, "no row overflow at 320").toBeLessThanOrEqual(row.clientWidth);
}
// 292 − padding 20 − attach 28 − mic 44 − send 28 − three 8px gaps, less the 1px border each side.
await expect(Math.round(canvas.getByRole("textbox").getBoundingClientRect().width), "the text keeps its width at 320").toBe(146);
},
});

/** S1 from the keyboard: "Talk live…" shows where the hint would, in the tab order between the text and the mic. */
export const TalkLiveFocused = meta.story({
render: () => above(composerWithMic("S1-talk-live")),
play: async ({ canvas, canvasElement, userEvent }) => {
const order = ["Attach — photo, camera, files", "Message", "Talk live…", "Dictate", "Send", `Model — ${PROVIDER}`];
const reached: string[] = [];
for (let i = 0; i < order.length; i++) {
await userEvent.tab();
const el = document.activeElement as HTMLElement;
reached.push(el.tagName === "TEXTAREA" ? "Message" : (el.getAttribute("aria-label") ?? el.textContent?.trim() ?? ""));
}
await expect(reached, "Attach → text → Talk live… → Dictate → Send → model chip").toEqual(order);
await userEvent.tab({ shift: true });
await userEvent.tab({ shift: true });
await userEvent.tab({ shift: true });
const talk = canvas.getByRole("button", { name: "Talk live…" });
await expect(talk).toHaveFocus();
await expect(talk.getBoundingClientRect().height, "44px when focused").toBeGreaterThanOrEqual(44);
await expect(talk.getBoundingClientRect().bottom, "above the field").toBeLessThanOrEqual(field(canvasElement).getBoundingClientRect().top);
await expect(canvas.queryByText("Keep holding to talk live"), "only one of the two").toBeNull();
await expect(field(canvasElement).getBoundingClientRect().height).toBe(54);
},
});

/** D6: plain editable dictated words, focus in the text with the caret at the end; "Dictate more" and a live Send. */
export const ReviewOneLine = meta.story({
render: () => composerWithMic("D6"),
play: async ({ canvas, canvasElement }) => {
const text = canvas.getByRole<HTMLTextAreaElement>("textbox");
await expect(text).not.toHaveAttribute("readonly");
text.focus();
text.setSelectionRange(REVIEW.length, REVIEW.length);
await expect(text).toHaveFocus();
await expect([text.selectionStart, text.selectionEnd], "caret at the end").toEqual([REVIEW.length, REVIEW.length]);
await expect(canvas.getByRole("button", { name: "Dictate more" })).toBeVisible();
await expect(canvas.getByRole("button", { name: "Send" })).not.toHaveAttribute("aria-disabled");
// M2: no uncertain-word mark and no hint-line cue.
await expect(canvasElement.querySelector(".bk-uncertain")).toBeNull();
await expect(canvasElement.querySelector("[data-composer-hint]")?.textContent).toContain("⏎ to send");
},
});

/** D6 on three lines: attach, mic and Send sit on the last line. */
export const ReviewThreeLines = meta.story({
render: () => composerWithMic("D6-three-lines"),
play: async ({ canvas, canvasElement }) => {
const text = canvas.getByRole("textbox");
const box = field(canvasElement).getBoundingClientRect();
await expect(Math.round(text.getBoundingClientRect().height), "three lines, no scroll").toBe(Math.round(3 * 13.5 * 1.45));
await expect(text.scrollHeight).toBeLessThanOrEqual(text.clientHeight);
await expect(box.height, "taller than one line").toBeGreaterThan(54);
const lastLine = text.getBoundingClientRect().bottom - (13.5 * 1.45) / 2;
const disc = centre(canvasElement.querySelector(".bk-voice-mic-disc")!);
await expect(Math.abs(disc - lastLine), "the mic on the last line").toBeLessThanOrEqual(1);
for (const name of ["Attach — photo, camera, files", "Send"]) {
await expect(Math.abs(centre(canvas.getByRole("button", { name })) - disc), `${name} on the last line`).toBeLessThanOrEqual(0.5);
}
},
});

/** M1: offline, the mic is "Record on this device", with no hold, no hint and no "Talk live…". */
export const OfflineLocalRecording = meta.story({
render: () => composerWithMic("offline"),
play: async ({ canvas, canvasElement }) => {
const mic = canvas.getByRole("button", { name: "Record on this device" });
await expect(mic).toHaveAttribute("data-phase", "idle");
await expect(canvas.queryByRole("button", { name: "Talk live…" })).toBeNull();
await expect(canvas.getByRole("button", { name: "Send — unavailable" })).toHaveAttribute("aria-disabled", "true");
await expect(canvas.getByText("needs the host · your draft is kept")).toBeVisible();
await expect(field(canvasElement).getBoundingClientRect().height).toBe(54);
},
});

/** Every state, one per cell, as the visual baselines capture them. */
export const AllStates = meta.story({
parameters: wide,
render: () => (
<div style={{ display: "flex", flexDirection: "column", gap: 16, width: "100%", maxWidth: 720 }}>
{(Object.keys(COMPOSER_MIC_TITLES) as ComposerMicId[]).map((id) => (
<section key={id} data-state={id} aria-label={COMPOSER_MIC_TITLES[id]} style={{ width: "100%", paddingTop: id.startsWith("S1") ? 56 : 0 }}>
{composerWithMic(id)}
</section>
))}
</div>
),
play: async ({ canvasElement }) => {
await expect(canvasElement.querySelectorAll("[data-state]")).toHaveLength(6);
await expect(canvasElement.querySelector(".bk-uncertain"), "M2: no mark anywhere").toBeNull();
},
});
Loading
Loading