From 12d43d69597cddba3c912d1e2541e93459881cdb Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Thu, 22 Oct 2026 13:59:59 -0700 Subject: [PATCH] fix(app): polish the components lab from Kit's feedback (#58228) --- .../app/src/components-lab/catalog.test.ts | 10 + packages/app/src/components-lab/catalog.ts | 12 +- packages/app/src/components-lab/lab.tsx | 229 ++++++++++++++---- .../app/src/components-lab/motion.test.ts | 17 ++ packages/app/src/components-lab/motion.ts | 103 ++++++++ .../app/src/composer/composer.stories.tsx | 85 +++++-- .../src/providers/models/select-dialog.tsx | 18 +- .../composer/activity-chips.stories.tsx | 33 ++- .../composer/composer-docks.stories.tsx | 21 +- packages/ui/package.json | 1 + packages/ui/src/motion-tuning-fields.ts | 42 ++++ packages/ui/src/motion-tuning-panel.ts | 53 +--- packages/ui/src/motion-tuning.ts | 1 + 13 files changed, 473 insertions(+), 152 deletions(-) create mode 100644 packages/app/src/components-lab/motion.test.ts create mode 100644 packages/app/src/components-lab/motion.ts create mode 100644 packages/ui/src/motion-tuning-fields.ts diff --git a/packages/app/src/components-lab/catalog.test.ts b/packages/app/src/components-lab/catalog.test.ts index bb2716c2765..ff5ffcf7605 100644 --- a/packages/app/src/components-lab/catalog.test.ts +++ b/packages/app/src/components-lab/catalog.test.ts @@ -46,3 +46,13 @@ describe("labFields", () => { expect(knobArgs(fields, stateArgs(entry, 1))).toEqual({ size: "normal", queued: 3, question: false, label: "Send" }) }) }) + +test("starts each knob at the first state's value", () => { + const entry = labEntry( + "spinner.stories.tsx", + { default: { args: { variant: "radar" } }, Today: { args: { variant: "today" } }, Radar: {} }, + "export const Today = {}\nexport const Radar = {}", + ) + + expect(labFields(entry).variant).toEqual(text("today")) +}) diff --git a/packages/app/src/components-lab/catalog.ts b/packages/app/src/components-lab/catalog.ts index c9c296c1915..28a58f5ec0c 100644 --- a/packages/app/src/components-lab/catalog.ts +++ b/packages/app/src/components-lab/catalog.ts @@ -23,7 +23,8 @@ type StoryObject = { args?: StoryArgs argTypes?: { [key: string]: ArgType } render?: StoryRender - parameters?: { layout?: string } + // `motion` names the Knobs (by id, group or card) the story uses, so the inspector shows them beside its args. + parameters?: { layout?: string; motion?: readonly string[] } } export type StoryModule = { [name: string]: StoryObject | StoryRender | string[] | undefined } @@ -39,6 +40,7 @@ export type LabEntry = { argTypes: { [key: string]: ArgType } render?: StoryRender fullscreen: boolean + motion: readonly string[] states: LabState[] } @@ -74,6 +76,7 @@ export function labEntry(file: string, module: StoryModule, source: string): Lab }, render: meta.render, fullscreen: meta.parameters?.layout === "fullscreen", + motion: meta.parameters?.motion ?? [], states, } } @@ -89,8 +92,9 @@ export function stateArgs(entry: LabEntry, index: number) { } /** - * A knob for every arg the meta or a state sets, typed by its argType or else by its value. Text and object args keep - * the story's values: knobs has no text field. + * A knob for every arg the meta or a state sets, typed by its argType or else by its value. Each starts at the first + * state's value, which the panel's default preset shows. Text and object args keep the story's values: knobs has no + * text field. */ export function labFields(entry: LabEntry) { const keys = new Set([ @@ -102,7 +106,7 @@ export function labFields(entry: LabEntry) { return Object.fromEntries( [...keys].flatMap((key): [string, Field][] => { const type = entry.argTypes[key] - const value = entry.args[key] ?? entry.states.find((state) => key in state.args)?.args[key] + const value = stateArgs(entry, 0)[key] ?? entry.states.find((state) => key in state.args)?.args[key] const control = isText(type?.control) ? { type: type.control } : (type?.control ?? {}) const [first, ...rest] = type?.options ?? [] diff --git a/packages/app/src/components-lab/lab.tsx b/packages/app/src/components-lab/lab.tsx index bf821be6c7b..71c4d825a9f 100644 --- a/packages/app/src/components-lab/lab.tsx +++ b/packages/app/src/components-lab/lab.tsx @@ -20,7 +20,7 @@ import { createStore, reconcile } from "solid-js/store" import { Dynamic, insert } from "solid-js/web" import { DialogProvider } from "@opencode/ui/context/dialog" import { useTheme } from "@opencode/ui/theme" -import { motionGlobals } from "@opencode/ui/motion-tuning" +import { motionGlobals, motionTuning } from "@opencode/ui/motion-tuning" import { choice, defineControls, matchesCombo, toolbar, type Field } from "knobs" import { canvas, commandPalette, restyle, split, toast, type CommandPalette } from "knobs/ui" import { Tree } from "knobs/ui/solid" @@ -46,6 +46,7 @@ import { type StoryArgs, type StoryModule, } from "./catalog" +import { applyMotionPatch, motionFields, motionValues, sameMotion, storyMotion } from "./motion" // How long Play holds each state at full speed. Slow motion doubles it while the motion itself runs 4× longer, so // a transition still finishes and Play keeps moving. @@ -111,32 +112,56 @@ export default function ComponentsLab() { const [scheme, setScheme] = createSignal<"dark" | "light">("dark") let palette: CommandPalette | undefined let toggle: ((id: string) => void) | undefined + let focusTree: ((id?: string) => void) | undefined + // While browsing the tree by keys, a story that focuses something as it mounts (a dialog, a field) would take the + // keys away. A press or Tab anywhere ends browsing; a few returns at most, so a story that traps focus still wins. + let browsing = 0 + // The key behind the latest selection; none for a press. + let key: string | undefined const entries = () => catalog()?.entries ?? [] const grid = () => params.view === "grid" const selected = createMemo(() => (grid() ? undefined : entries().find((entry) => entry.file === params.story))) - const open = (file: string) => setParams({ story: file, view: undefined }) + + const open = (file: string) => { + browsing = stories.contains(document.activeElement) ? 3 : 0 + setParams({ story: file, view: undefined }) + } const rows = createMemo(() => folder(entries(), [])) const search = () => { - palette?.dispose() - palette = commandPalette({ + if (palette?.isOpen) return palette.close() + + palette ??= commandPalette({ hotkey: false, recents: false, placeholder: language.t("lab.search"), look: { theme: scheme() }, - commands: entries().map((entry) => ({ - id: entry.file, - label: entry.title.split("/").join(" / "), - hint: fileName(entry.file), - keywords: entry.states.map((state) => state.name), - run: () => open(entry.file), - })), + commands: () => + entries().map((entry) => ({ + id: entry.file, + label: entry.title.split("/").join(" / "), + hint: fileName(entry.file), + keywords: entry.states.map((state) => state.name), + run: () => open(entry.file), + })), }) palette.open() } + // The palette takes its look when it's made. + createEffect( + on( + scheme, + () => { + palette?.dispose() + palette = undefined + }, + { defer: true }, + ), + ) + // Ahead of the app's own palette, which listens on the document. makeEventListener( window, @@ -181,15 +206,21 @@ export default function ComponentsLab() { label={language.t("lab.components")} expanded={rows().map((row) => row.id)} selection={params.story ? [params.story] : []} + // Digits pick the story's states. + typeahead={(key) => !/^[1-9]$/.test(key)} onReady={(tree) => { // Opens the folders down to the story in the address, and later ones picked from the palette. createEffect(() => params.story && tree.reveal(params.story)) toggle = (id) => tree.expand(id, !tree.isExpanded(id)) + focusTree = (id) => tree.focus(id) }} + // Moving by keys selects as it goes, so a folder opens and closes only by a click, Enter, Space or ←/→. onSelect={(_, primary) => { if (!primary?.startsWith("folder:")) return primary && open(primary) - toggle?.(primary) + + if (key === undefined || key === " ") toggle?.(primary) }} + onActivate={(id) => (id.startsWith("folder:") ? toggle?.(id) : open(id))} /> )) @@ -219,6 +250,21 @@ export default function ComponentsLab() { )) + makeEventListener(window, "pointerdown", () => ((browsing = 0), (key = undefined)), { capture: true }) + makeEventListener( + window, + "keydown", + (event) => { + key = event.key + + if (event.key === "Tab") browsing = 0 + }, + { capture: true }, + ) + makeEventListener(stage, "focusin", () => { + if (browsing-- > 0) focusTree?.(params.story) + }) + let element!: HTMLDivElement onMount(() => { @@ -280,17 +326,22 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" // Switching to a state that shares the current render function keeps the mounted instance, so its transitions play. const render = () => entry.states[index()]?.render ?? entry.render ?? fallback let timer: ReturnType | undefined + // The state Play is moving to. Any other change is a hand's, and a hand's change stops Play. + let advancing: number | undefined - // A state is a variant: its chip, `[` and `]` and Play all apply it, so the panel shows where it is. + // A state is a variant: its chip, a digit, `[` and `]` and Play all apply it, so the panel shows where it is. const preset = (next: number): void => store.preset(next === 0 ? "default" : (names[next] ?? "default")) const step = (by: number) => preset((index() + by + names.length) % names.length) + const pause = () => clearTimeout(timer) + const play = () => { clearTimeout(timer) timer = setTimeout( () => { - step(1) + advancing = (index() + 1) % names.length + preset(advancing) play() }, (hold * (motionGlobals.slow.value ? 2 : 1)) / motionGlobals.speed.value, @@ -303,7 +354,11 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" first === undefined || rest.length === 0 ? {} : { - state: choice(first, [first, ...rest], { variants: true }), + state: choice(first, [first, ...rest], { + variants: true, + // The digit that picks each of the first nine. + labels: Object.fromEntries(names.slice(0, 9).map((name, offset) => [name, `${offset + 1} ${name}`])), + }), play: toolbar( [ { @@ -325,52 +380,110 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" ), } - const store = defineControls( - "components-lab", - { ...states, ...fields }, - { - storage: null, - persist: "none", - // Beta is a production build, where knobs resolves its production entry: the panel mounts only when shipped. - ship: () => import("knobs/panel"), - defaultLabel: first, - presets: Object.fromEntries( - entry.states.slice(1).map((state, offset) => [state.name, knobArgs(fields, stateArgs(entry, offset + 1))]), - ), - onChange: (patch, values, meta) => { - if (!("state" in patch)) return setArgs(patch) + // The story's Knobs join its args here, so the inspector is the one place for its controls. Registering a knob or a + // replay button (as the story mounts) rebuilds it where it was. + let motion = storyMotion(entry.motion) + const [shown, setShown] = createSignal(motion, { equals: sameMotion }) - // One batch, so a state with its own render function never renders with the previous state's args. - const next = Math.max(0, names.indexOf(String(values.state))) - batch(() => { - setArgs(reconcile(stateArgs(entry, next))) - setIndex(next) - }) + const inspect = () => { + const own = motionFields(motion, (values) => store.set(values)) - // Undo or a reset moved the state: bring the other knobs to the state's args too. - if (meta.source !== "preset") queueMicrotask(() => preset(next)) + return defineControls( + "components-lab", + { ...states, ...fields, ...own }, + { + storage: null, + persist: "none", + // Beta is a production build, where knobs resolves its production entry: the panel mounts only when shipped. + ship: () => import("knobs/panel"), + defaultLabel: first && rest.length > 0 ? `1 ${first}` : first, + presets: Object.fromEntries( + entry.states.slice(1).map((state, offset) => [state.name, knobArgs(fields, stateArgs(entry, offset + 1))]), + ), + onChange: (patch, values, meta) => { + // A state leaves the Knobs where they are: they're the story's tuning, not part of a state. + if (meta.source === "preset") queueMicrotask(() => store.sync(motionValues(motion))) + else applyMotionPatch(motion, patch) + + if (!("state" in patch)) { + if (meta.source !== "preset") pause() + + return setArgs(Object.fromEntries(Object.entries(patch).filter(([key]) => key in fields))) + } + + // One batch, so a state with its own render function never renders with the previous state's args. + const next = Math.max(0, names.indexOf(String(values.state))) + + if (next !== advancing) pause() + advancing = undefined + batch(() => { + setArgs(reconcile(stateArgs(entry, next))) + setIndex(next) + }) + + // Undo or a reset moved the state: bring the other knobs to the state's args too. + if (meta.source !== "preset") queueMicrotask(() => preset(next)) + }, }, - }, + ) + } + + let store!: ReturnType + + createEffect(() => { + motion = shown() + store = untrack(inspect) + store.sync(motionValues(motion)) + onCleanup( + store.mount(props.inspector, { + theme: props.scheme, + header: { title: false, buttons: ["undo", "redo", "reset"] }, + variants: false, + session: false, + empty: language.t("lab.noControls"), + }), + ) + + // Applied rather than matched, so the state's chip stays lit while the Knobs, which no state sets, move. + if (rest.length > 0) untrack(() => preset(index())) + }) + + // Coalesced: a story registers its replay buttons one by one. + let queued = false + onCleanup( + motionTuning.subscribe(() => { + if (queued) return + queued = true + queueMicrotask(() => { + queued = false + const next = storyMotion(entry.motion) + + if (!sameMotion(next, motion)) return setShown(next) + store.sync(motionValues(motion)) + }) + }), ) onCleanup(() => clearTimeout(timer)) - onCleanup( - store.mount(props.inspector, { - theme: props.scheme, - header: { title: false, buttons: ["undo", "redo", "reset"] }, - variants: false, - session: false, - empty: language.t("lab.noControls"), - }), - ) + makeEventListener(window, "keydown", (event) => { + const digit = Number(event.key) + + if (names.length < 2 || !Number.isInteger(digit) || digit < 1 || digit > Math.min(9, names.length)) return + + if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey || typing(event.target)) return + event.preventDefault() + preset(digit - 1) + }) return ( // Contained layout makes the canvas hold its stories' dialogs, which the provider below portals into it. + // A press inside the story (its own replay buttons, a dock) stops Play rather than being undone by it.
@@ -407,7 +520,13 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" function Workspace(props: { children: JSX.Element }) { const servers = useServers() const global = useGlobal() - const healthy = () => servers.list.find((conn) => global.servers.health[ServerConnection.key(conn)]?.healthy) + + // Kept once picked while the server stays listed: a new pick remounts the story, losing whatever it was showing. + const healthy = createMemo((picked?: ServerConnection.Any) => + picked && servers.list.some((conn) => ServerConnection.key(conn) === ServerConnection.key(picked)) + ? picked + : servers.list.find((conn) => global.servers.health[ServerConnection.key(conn)]?.healthy), + ) return ( @@ -423,8 +542,16 @@ function Workspace(props: { children: JSX.Element }) { function Project(props: { children: JSX.Element }) { const server = useServer() + // The list puts the most recently active project first, and on a busy server that changes every few seconds. The + // story keeps the project it started in, so another session's activity never remounts it. + const directory = createMemo((picked?: string) => { + const list = server.ctx.projects.list() + + return picked && list.some((project) => project.worktree === picked) ? picked : list[0]?.worktree + }) + return ( - + {(directory) => ( @@ -568,6 +695,10 @@ function folderOf(entry: LabEntry) { return entry.file.match(/ui\/src\/([^/]+)\//)?.[1] ?? "" } +function typing(target: EventTarget | null) { + return target instanceof HTMLElement && (target.isContentEditable || !!target.closest("input, textarea, select")) +} + function pane(content: () => JSX.Element) { const element = document.createElement("div") diff --git a/packages/app/src/components-lab/motion.test.ts b/packages/app/src/components-lab/motion.test.ts new file mode 100644 index 00000000000..a734c219905 --- /dev/null +++ b/packages/app/src/components-lab/motion.test.ts @@ -0,0 +1,17 @@ +import { expect, test } from "bun:test" +import { motionTuning } from "@opencode/ui/motion-tuning" +import { sameMotion, storyMotion } from "./motion" + +test("a remounted story's replay buttons rebuild the inspector, though their ids match", () => { + const register = () => motionTuning.action({ id: "lab.test.replay", label: "Replay", group: "Lab test", run() {} }) + const unmount = register() + const first = storyMotion(["Lab test"]) + + expect(sameMotion(first, storyMotion(["Lab test"]))).toBe(true) + + unmount() + const remount = register() + + expect(sameMotion(first, storyMotion(["Lab test"]))).toBe(false) + remount() +}) diff --git a/packages/app/src/components-lab/motion.ts b/packages/app/src/components-lab/motion.ts new file mode 100644 index 00000000000..e5010abcb6e --- /dev/null +++ b/packages/app/src/components-lab/motion.ts @@ -0,0 +1,103 @@ +import { motionGlobals, motionPresets, motionTuning, type MotionKnob } from "@opencode/ui/motion-tuning" +import { applyMotion, motionField } from "@opencode/ui/motion-tuning-fields" +import type { DurationOptions } from "@opencode/ui/motion" +import { action, toolbar, type Field, type Values } from "knobs" + +/** + * The Knobs a story names in `parameters.motion` (ids, groups or cards) and their replay buttons. Speed and slow motion + * come along when there is motion to time. + */ +export function storyMotion(names: readonly string[]) { + const named = (item: { id: string; group: string; card?: string }) => + [item.id, item.group, item.card].some((key) => key !== undefined && names.includes(key)) + + const knobs = motionTuning.list().filter((item) => item.kind !== "mode" && named(item) && (item.when?.() ?? true)) + const actions = motionTuning.actions().filter(named) + const timed = actions.length > 0 || knobs.some((item) => item.kind === "spring" || item.kind === "easing") + + return { knobs, actions, globals: timed ? [motionGlobals.speed, motionGlobals.slow] : [] } +} + +export type StoryMotion = ReturnType + +/** + * Whether the inspector built from `a` still fits `b`. Compared by instance: a remounted story registers its replay + * buttons again under the same ids, with callbacks bound to the new mount. + */ +export function sameMotion(a: StoryMotion, b: StoryMotion) { + const left = [...a.knobs, ...a.actions, ...a.globals] + const right = [...b.knobs, ...b.actions, ...b.globals] + + return left.length === right.length && left.every((item, index) => item === right[index]) +} + +/** + * One card per group (or card): buttons for its spring presets, its knobs and its replay buttons, then speed and slow + * motion. `apply` sets the values a preset button names. + */ +export function motionFields( + motion: StoryMotion, + apply: (values: { [key: string]: DurationOptions }) => void, +): { [key: string]: Field } { + return Object.fromEntries([ + ...Object.entries(springPresets(motion)).map(([group, list]) => [ + `presets.${group}`, + toolbar( + list.map((item) => ({ id: item.name, label: item.name, run: () => apply(item.values) })), + { group, labels: true }, + ), + ]), + ...motion.knobs.map((item) => [ + key(item), + motionField(item, { label: item.label, group: item.card ?? item.group }), + ]), + ...motion.actions.map((item) => [ + `replay.${item.id}`, + action(item.label, { group: item.group, subsection: "Replay", run: item.run }), + ]), + ...motion.globals.map((item) => [key(item), motionField(item, { label: item.label, group: item.group })]), + ]) +} + +export function motionValues(motion: StoryMotion) { + return Object.fromEntries([...motion.knobs, ...motion.globals].map((item) => [key(item), item.value])) +} + +/** Applies the motion keys of a change from the inspector. */ +export function applyMotionPatch(motion: StoryMotion, patch: Partial>) { + ;[...motion.knobs, ...motion.globals].forEach((item) => { + // SAFETY: each key's field was made from its knob by `motionField`, so its value is that knob's kind. + const value = patch[key(item)] as MotionKnob["value"] | undefined + + if (value !== undefined) applyMotion(item, value) + }) +} + +const presets = ["snappy", "smooth", "calm"] as const + +// Apart from the story's own args. +function key(item: MotionKnob) { + return `motion.${item.id}` +} + +// The Shipped, Snappy, Smooth and Calm values of each card's springs. +function springPresets(motion: StoryMotion) { + const springs = motion.knobs.flatMap((item) => (item.kind === "spring" ? [item] : [])) + + return Object.fromEntries( + [...new Set(springs.map((item) => item.card ?? item.group))].map((group) => { + const own = springs.filter((item) => (item.card ?? item.group) === group) + + return [ + group, + [ + { name: "Shipped", values: Object.fromEntries(own.map((item) => [key(item), item.initial])) }, + ...presets.map((preset) => ({ + name: motionPresets[preset], + values: Object.fromEntries(own.map((item) => [key(item), item.presets[preset]])), + })), + ], + ] + }), + ) +} diff --git a/packages/app/src/composer/composer.stories.tsx b/packages/app/src/composer/composer.stories.tsx index 9be5af3997f..ffb89cc6a30 100644 --- a/packages/app/src/composer/composer.stories.tsx +++ b/packages/app/src/composer/composer.stories.tsx @@ -1,4 +1,4 @@ -import { Show, createMemo, onMount, type JSX } from "solid-js" +import { Show, createEffect, createMemo, on, onMount, type JSX } from "solid-js" import { createStore } from "solid-js/store" import type { ModelSelection } from "@/providers/models/selection" import { STORY_MODEL, emptySessionDocument, pendingAndQueuedDocument } from "@opencode/session-ui/storybook" @@ -52,7 +52,7 @@ function ComposerStory(props: { comments?: ComposerPersistedState["context"]["items"] working?: boolean stopping?: boolean - suggestions?: "command" | "context" + suggestions?: "command" | "context" | "none" failure?: boolean label?: string inspectRequest?: boolean @@ -271,12 +271,42 @@ function ComposerStory(props: { model: { selection: modelSelection, paid: true, loading: false }, } satisfies ComposerModel - onMount(() => { - if (props.suggestions === "command") model.openCommands() + const suggest = (kind: typeof props.suggestions) => { + if (kind === "command") return model.openCommands() - if (props.suggestions === "context") model.openContext() + if (kind === "context") return model.openContext() + + model.dispatch({ type: "popover.close" }) + } + + onMount(() => { + if (props.suggestions === "command" || props.suggestions === "context") suggest(props.suggestions) }) + // The components lab keeps this story mounted across states that differ only in args, so the composer follows them + // in place and its own transitions play. The prompt is compared by value: the lab updates its args store in place. + // One effect, so the prompt lands before the suggestions open on it: an empty draft opens them inline, typing the + // trigger, so a change of either starts over from the state's prompt. + createEffect( + on( + () => [JSON.stringify(props.prompt ?? null), props.suggestions] as const, + ([json, kind]) => { + const prompt: ComposerPersistedState["prompt"] = JSON.parse(json) ?? text("") + + setDraft({ prompt, cursor: promptLength(prompt) }) + suggest(kind) + }, + { defer: true }, + ), + ) + createEffect( + on( + () => props.label, + (label) => setStory("activity", label ?? "Ready"), + { defer: true }, + ), + ) + return (
[ { type: "text", content, start: 0, end: content.length }, ] +type FlowArgs = { + prompt?: ComposerPersistedState["prompt"] + working: boolean + stopping: boolean + failure: boolean + label: string + suggestions: "command" | "context" | "none" +} + export default { title: "OpenCode/Composer/Flow", component: Composer, parameters: { layout: "centered" }, + // States that only change the composer's props share this render, so moving between them keeps one composer. + args: { working: false, stopping: false, failure: false, label: "Ready", suggestions: "none" }, + argTypes: { suggestions: { control: "select", options: ["none", "command", "context"] } }, + render: (args: FlowArgs) => , } -export const EmptyDraft = { render: () => } +export const EmptyDraft = {} export const PromptHistory = { args: { many: false }, @@ -311,11 +354,9 @@ export const PromptHistory = { ), } -export const TextDraft = { render: () => } +export const TextDraft = { args: { prompt: text("Explain this change") } } -export const MultilineDraft = { - render: () => , -} +export const MultilineDraft = { args: { prompt: text("Review the implementation\nThen run the focused tests") } } export const MixedAttachments = { render: () => ( @@ -390,11 +431,11 @@ export const BrowserElementComment = { ), } -export const ModelAndVariant = { render: () => } +export const ModelAndVariant = { args: { prompt: text("Compare both variants") } } -export const SlashSuggestions = { render: () => } +export const SlashSuggestions = { args: { suggestions: "command" } } -export const ContextSuggestions = { render: () => } +export const ContextSuggestions = { args: { suggestions: "context" } } function ConstrainedCommandSuggestionsStory() { let boundary: HTMLDivElement | undefined @@ -417,29 +458,23 @@ export const DetachedCommandSuggestionBoundary = { }, } -export const RunningAndStopping = { render: () => } +export const RunningAndStopping = { args: { working: true, stopping: true, label: "Session is running" } } -export const SteeringFollowUp = { - render: () => , -} +export const SteeringFollowUp = { args: { prompt: text("Use this correction at the next boundary"), working: true } } -export const FailedSubmissionRestoration = { - render: () => , -} +export const FailedSubmissionRestoration = { args: { prompt: text("Preserve this draft on failure"), failure: true } } export const NewSessionFirstPrompt = { - render: () => ( - - ), + args: { prompt: text("Create the Session and implement the change"), label: "New Session draft" }, } export const ActiveSessionFollowUp = { - render: () => , + args: { prompt: text("Now add focused coverage"), label: "Active Session follow-up" }, } export const RightToLeft = { globals: { direction: "rtl" }, - render: () => , + args: { prompt: text("راجع src/app.tsx ثم شغّل bun test") }, } export const NarrowLayout = { diff --git a/packages/app/src/providers/models/select-dialog.tsx b/packages/app/src/providers/models/select-dialog.tsx index 99de9447437..dc4dd7dfdec 100644 --- a/packages/app/src/providers/models/select-dialog.tsx +++ b/packages/app/src/providers/models/select-dialog.tsx @@ -701,8 +701,22 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState const box = row.closest('[data-slot="dialog-container"]')?.getBoundingClientRect() if (!box) return - const left = language.direction() === "rtl" ? box.left - 4 - 200 : box.right + 4 - setStore({ flyout: id, warm: true, position: { left, top: row.getBoundingClientRect().top - 2 } }) + // Beside the dialog's end edge, else its start edge, else over the dialog: always inside the layer that holds it. + const bounds = row.closest("[data-dialog-layer]")?.getBoundingClientRect() + const fits = (x: number) => !bounds || (x >= bounds.left && x + 200 <= bounds.right) + const end = language.direction() === "rtl" ? box.left - 4 - 200 : box.right + 4 + const start = language.direction() === "rtl" ? box.right + 4 : box.left - 4 - 200 + const over = bounds ? Math.max(bounds.left, Math.min(end, bounds.right - 200)) : end + const left = fits(end) ? end : fits(start) ? start : over + const top = row.getBoundingClientRect().top - 2 + setStore({ flyout: id, warm: true, position: { left, top } }) + + // A fixed element is placed against the viewport unless an ancestor contains it, as a component preview that holds + // its dialogs does. Correct by where it landed, before it paints. + const placed = flyoutRef?.isConnected ? flyoutRef.getBoundingClientRect() : undefined + + if (placed && (placed.left !== left || placed.top !== top)) + setStore("position", { left: left * 2 - placed.left, top: top * 2 - placed.top }) } const hover = (id: string, row: HTMLElement) => { diff --git a/packages/app/src/session/composer/activity-chips.stories.tsx b/packages/app/src/session/composer/activity-chips.stories.tsx index 7ff19e56a74..1704719bc45 100644 --- a/packages/app/src/session/composer/activity-chips.stories.tsx +++ b/packages/app/src/session/composer/activity-chips.stories.tsx @@ -8,7 +8,6 @@ import { largeCompletedDocument, } from "@opencode/session-ui/storybook" import { timelinePresets } from "@opencode/session-ui/timeline/detail" -import { mountMotionPanel } from "@opencode/ui/motion-tuning-panel" import { createEffect, createMemo, on, onCleanup, onMount } from "solid-js" import { createStore } from "solid-js/store" import { SessionPreview } from "@/session/story-model" @@ -232,6 +231,8 @@ export default { }, parameters: { layout: "fullscreen", + // The activity chip experiments, shown in the components lab's inspector. + motion: ["activity.chip", "activity.chip.corners"], docs: { description: { component: @@ -255,29 +256,23 @@ export const ManySubagents = { args: { stage: 4, subagents: 12, shells: 2 } } export const Live = { render: () => } -// The real composer and activity lane, with the same experiment controls as the app's Knobs workspace. +// The real composer and activity lane, to try the activity chip experiments on. export const Experiments = { render: () => , } function ExperimentPreview() { - let panel!: HTMLDivElement - onMount(() => onCleanup(mountMotionPanel(panel, { section: "Experiments" }))) - return ( -
- - subagentItem(i)), - shells: [shellItem(0), shellItem(1)], - }} - /> - -
-
+ + subagentItem(i)), + shells: [shellItem(0), shellItem(1)], + }} + /> + ) } diff --git a/packages/app/src/session/composer/composer-docks.stories.tsx b/packages/app/src/session/composer/composer-docks.stories.tsx index 4872b00cb79..d145ff41fe4 100644 --- a/packages/app/src/session/composer/composer-docks.stories.tsx +++ b/packages/app/src/session/composer/composer-docks.stories.tsx @@ -6,7 +6,6 @@ import { } from "@opencode/session-ui/storybook" import { SessionTimeline } from "@opencode/session-ui/timeline" import { motionTuning } from "@opencode/ui/motion-tuning" -import { mountMotionPanel } from "@opencode/ui/motion-tuning-panel" import { QueryClient, QueryClientProvider } from "@tanstack/solid-query" import { createEffect, on, onCleanup } from "solid-js" import { createStore } from "solid-js/store" @@ -42,24 +41,27 @@ const websearchRequest: FormInfo = { fields: [{ key: "choice", type: "string", required: true, custom: false }], } -// The real composer region with its docks, queue and subagent bar, driven by the story's args or by the replay -// buttons in the Motion panel beside it. Answering, dismissing and Esc close docks the way they do in the app. +// The real composer region with its docks, queue and subagent bar, driven by the story's args or by its replay +// buttons (the components lab shows them under the Composer docks Knobs). Answering, dismissing and Esc close docks the way they do in the app. function ComposerDocksPreview(props: DockArgs) { const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } }) + const [state, setState] = createStore({ ...props, rows: prompts.slice(0, props.queue).map((_, index) => index), revision: 0, searchProvider: "exa", }) + // Grows or trims the queue to `count`, adding the prompts not queued yet. const queueTo = (count: number) => setState("rows", (rows) => - [...rows, ...prompts.map((_, index) => index).filter((index) => !rows.includes(index))].slice( + [...rows, ...prompts.flatMap((_, index) => (rows.includes(index) ? [] : [index]))].slice( 0, Math.max(0, Math.min(prompts.length, count)), ), ) + const dequeue = (id: string) => setState("rows", (rows) => rows.filter((index) => `queued_${index}` !== id)) createEffect( @@ -75,6 +77,7 @@ function ComposerDocksPreview(props: DockArgs) { const replay = (id: string, label: string, run: () => void) => onCleanup(motionTuning.action({ id: `docks.${id}`, label, group: "Composer docks", run })) + replay("question", "Question", () => setState({ question: true, revision: state.revision + 1 })) replay("permission", "Permission", () => setState("permission", true)) replay("websearch", "Web search", () => setState("websearch", true)) @@ -102,8 +105,10 @@ function ComposerDocksPreview(props: DockArgs) { }) const blocked = () => state.question || state.permission || state.websearch + // A permission decision also reports a response submit, so only a submit without a decision answers the question. let deciding = false + const region = { state: { questionRequest: () => @@ -188,10 +193,6 @@ function ComposerDocksPreview(props: DockArgs) { /> -
) @@ -203,10 +204,12 @@ export default { component: ComposerDocksPreview, parameters: { layout: "fullscreen", + // The components lab shows these Knobs and their replay buttons in its inspector. + motion: ["Composer docks"], docs: { description: { component: - "Request docks, the queue and the subagent bar around the composer. Toggle the args, or use the replay buttons in the Motion panel, to open and close each dock and tune its motion live.", + "Request docks, the queue and the subagent bar around the composer. Toggle the args, or use the Replay buttons under the Composer docks Knobs, to open and close each dock and tune its motion live.", }, }, }, diff --git a/packages/ui/package.json b/packages/ui/package.json index 1fd5692b246..54aa0366b1d 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -59,6 +59,7 @@ "./motion/solid": "./src/motion/solid.ts", "./motion-tuning": "./src/motion-tuning.ts", "./motion-tuning-panel": "./src/motion-tuning-panel.ts", + "./motion-tuning-fields": "./src/motion-tuning-fields.ts", "./progress-circle": "./src/feedback/progress-circle/progress-circle.tsx", "./project-avatar": "./src/data-display/project-avatar/project-avatar.tsx", "./radio": "./src/forms/radio/radio.tsx", diff --git a/packages/ui/src/motion-tuning-fields.ts b/packages/ui/src/motion-tuning-fields.ts new file mode 100644 index 00000000000..2f3daf43c38 --- /dev/null +++ b/packages/ui/src/motion-tuning-fields.ts @@ -0,0 +1,42 @@ +import { choice, easing, knob, spring, toggle } from "knobs" +import type { DurationOptions } from "./motion" +import { motionTuning, type Bezier, type MotionKnob } from "./motion-tuning" + +/** The knobs field that edits a motion knob, defaulting to its shipped value. */ +export function motionField(item: MotionKnob, meta: { label: string; group?: string; tab?: string }) { + if (item.kind === "spring") return spring(item.initial, meta) + + if (item.kind === "toggle" || item.kind === "mode") return toggle(item.initial, meta) + + if (item.kind === "easing") return easing(item.initial, meta) + + if (item.kind === "choice") return choice(item.initial, item.options, { ...meta, labels: item.labels }) + + return knob(item.initial, { ...meta, min: item.min, max: item.max, step: item.step, unit: item.unit }) +} + +/** Applies a value from a knob's field (see `motionField`) to the knob. */ +export function applyMotion(item: MotionKnob, value: MotionKnob["value"]) { + if (item.kind === "spring") { + // SAFETY: a spring knob's field is a spring field. + return motionTuning.set(item, value as DurationOptions) + } + + if (item.kind === "easing") { + // SAFETY: an easing knob's field is an easing field. + return motionTuning.set(item, [...(value as Bezier)] as Bezier) + } + + if (item.kind === "toggle" || item.kind === "mode") { + // SAFETY: a toggle knob's field is a toggle field. + return motionTuning.set(item, value as boolean) + } + + if (item.kind === "choice") { + // SAFETY: a choice knob's field is a choice field. + return motionTuning.set(item, value as string) + } + + // SAFETY: a number knob's field is a number field. + motionTuning.set(item, value as number) +} diff --git a/packages/ui/src/motion-tuning-panel.ts b/packages/ui/src/motion-tuning-panel.ts index 4b961c44a9b..a473b129500 100644 --- a/packages/ui/src/motion-tuning-panel.ts +++ b/packages/ui/src/motion-tuning-panel.ts @@ -1,5 +1,4 @@ -import type { DurationOptions } from "./motion" -import { motionPresets, motionTuning, type Bezier, type MotionKnob, type MotionPreset } from "./motion-tuning" +import { motionPresets, motionTuning, type MotionKnob, type MotionPreset } from "./motion-tuning" const global = "Global" @@ -28,51 +27,17 @@ export function mountMotionPanel( } async function start() { - const { action, choice, defineControls, easing, knob, spring, toggle } = await import("knobs") + const [{ action, defineControls }, { applyMotion, motionField }] = await Promise.all([ + import("knobs"), + import("./motion-tuning-fields"), + ]) - const field = (item: MotionKnob) => { - const meta = { + const field = (item: MotionKnob) => + motionField(item, { label: item.label, group: item.card ?? item.group, tab: item.group === global ? undefined : item.group, - } - - if (item.kind === "spring") return spring(item.initial, meta) - - // Modes never reach here as rows; they sit in the preset strip. - if (item.kind === "toggle" || item.kind === "mode") return toggle(item.initial, meta) - - if (item.kind === "easing") return easing(item.initial, meta) - - if (item.kind === "choice") return choice(item.initial, item.options, { ...meta, labels: item.labels }) - - return knob(item.initial, { ...meta, min: item.min, max: item.max, step: item.step, unit: item.unit ?? "×" }) - } - - const apply = (item: MotionKnob, value: MotionKnob["value"]) => { - if (item.kind === "spring") { - // SAFETY: a spring knob's field is a spring field. - return motionTuning.set(item, value as DurationOptions) - } - - if (item.kind === "easing") { - // SAFETY: an easing knob's field is an easing field. - return motionTuning.set(item, [...(value as Bezier)] as Bezier) - } - - if (item.kind === "toggle" || item.kind === "mode") { - // SAFETY: a toggle knob's field is a toggle field. - return motionTuning.set(item, value as boolean) - } - - if (item.kind === "choice") { - // SAFETY: a choice knob's field is a choice field. - return motionTuning.set(item, value as string) - } - - // SAFETY: a number knob's field is a number field. - motionTuning.set(item, value as number) - } + }) // Knobs whose `when` doesn't hold are left out; a change to it rebuilds the panel like a new knob would. const shown = () => motionTuning.list().filter((item) => item.when?.() ?? true) @@ -142,7 +107,7 @@ export function mountMotionPanel( // SAFETY: each field was made from its knob above, so its value is that knob's kind. const value = patch[item.id] as MotionKnob["value"] | undefined - if (value !== undefined) apply(item, value) + if (value !== undefined) applyMotion(item, value) }), }, ) diff --git a/packages/ui/src/motion-tuning.ts b/packages/ui/src/motion-tuning.ts index 9057f501c0f..6b51d358f83 100644 --- a/packages/ui/src/motion-tuning.ts +++ b/packages/ui/src/motion-tuning.ts @@ -218,6 +218,7 @@ const speed = register({ min: 0.25, max: 4, step: 0.05, + unit: "×", }) const slow = register({