diff --git a/apps/docs/demo/sequences/new-pet.seq.ts b/apps/docs/demo/sequences/new-pet.seq.ts index 8a19966..3de4374 100644 --- a/apps/docs/demo/sequences/new-pet.seq.ts +++ b/apps/docs/demo/sequences/new-pet.seq.ts @@ -17,6 +17,7 @@ export default sequence({ }), }, }) + // #endregion flow .step('Add the pet', addPet) // keeps the id the store gave it .step('Fetch it back', (ctx) => getPet.with({ @@ -27,4 +28,3 @@ export default sequence({ }, }), ) -// #endregion flow diff --git a/apps/docs/public/llms.txt b/apps/docs/public/llms.txt index e3da6ba..03b4f4f 100644 --- a/apps/docs/public/llms.txt +++ b/apps/docs/public/llms.txt @@ -155,6 +155,7 @@ export default sequence({ - `request.with({ ... })` changes a request for one step (for example its `assert`, or the values it sends). - Also: `.input(name, ctx => controls)` asks a person for values, `.each(name, items, make)` repeats a request per item, `.check(name, fn)` asserts on the flow's state, `.use(otherFlow)` includes another flow. - Controls are `c.number`, `c.text`, `c.select`, `c.multiselect`, `c.boolean`, `c.date`, `c.object`, `c.array`. A flow also runs unattended in CI and as a monitor, so every input and every `.input()` control needs a default that makes sense with nobody to ask. +- Several values for one thing (travelers, line items): `c.object({ name: c.text(...), gender: c.select([...]) }, { label: 'Traveler 1' })` is a group, and `c.array(item, { min: 1, max: 10, label: 'Travelers' })` is a list whose length a person sets. The form shows groups with the same fields as one table with a row for each, so declare them with one helper (`const traveler = (label: string) => c.object({ ... }, { label })`). A list with no value starts at `min` items, each made from its own defaults. Read them as `{{traveler1.name}}` or `{{travelers[0].name}}`, or `ctx.inputs.travelers` (`.each(name, ctx => ctx.inputs.travelers, ...)` makes a request for each). A flat key with a dot (`'traveler1.name'`) is not a path: use a group. - For generated data: `import { faker } from '@specbook/core/faker'` and use it in a default, for example `c.text({ default: () => faker.person.fullName() })`. It is typed, and `specbook init` adds `@faker-js/faker` to `package.json` (`npm install` fetches it). A `{{faker.person.firstName}}` placeholder (`faker..`, no arguments) also works in a field. - Each step is also a request you can run alone. diff --git a/apps/docs/src/content/docs/reference/cli.mdx b/apps/docs/src/content/docs/reference/cli.mdx index 58151f1..a6e13bc 100644 --- a/apps/docs/src/content/docs/reference/cli.mdx +++ b/apps/docs/src/content/docs/reference/cli.mdx @@ -29,7 +29,7 @@ description: Every command and what it does. | `--timeout ms`, `--global-timeout ms` | Limit each request (default: the config's `timeoutMs`, else 30000; `0` waits), and the whole run. | | `--safe` | Refuses requests that may change data. Use it against production. | | `--reporter list\|json\|junit\|github\|ndjson[:path]` | Chooses reporters. Repeat the flag to use several. | -| `--input k=v`, `--var k=v` | Sets a flow input, or a variable. Repeat either. A variable can override an address. | +| `--input k=v`, `--var k=v` | Sets a flow input, or a variable. Repeat either. A variable can override an address. The value is read as JSON when it is, so a list is `--input 'travelers=[{"name":"Ada"}]'`. | | `--secrets-file ` | Reads secrets from a dotenv file. | | `--trace on-failure\|always\|off` | When to keep a step's request and response. The default is `on-failure`. | | `--quiet` | Prints only failures and the summary. | diff --git a/apps/docs/src/content/docs/reference/embed.mdx b/apps/docs/src/content/docs/reference/embed.mdx index 5c8452d..700a2aa 100644 --- a/apps/docs/src/content/docs/reference/embed.mdx +++ b/apps/docs/src/content/docs/reference/embed.mdx @@ -18,7 +18,7 @@ A plain element gets a Play button beside it. A button or link that carries the | `data-specbook-try="service/Operation"` | Opens a request. A bare `Operation` works when the build has one service. A request file such as `requests/petstore/find-pets.req.ts` opens that request, with its checks. | | `data-specbook-flow="id"` | Opens a flow by its id. | | `data-specbook-example="name"` | Starts from a named example. | -| `data-specbook-inputs='{"quantity":2}'` | Sets a flow's inputs, over their defaults. | +| `data-specbook-inputs='{"quantity":2}'` | Sets a flow's inputs, over their defaults. A group or a list is given as an object or an array, and what it leaves out keeps its default. | | `data-specbook-env="demo"` | Chooses the environment. Set it on an element or on any ancestor, so a page can set it once. | | `data-specbook-tab="docs"` | Opens on the Docs tab instead of Try. | | `data-specbook-auto-run` | Runs as soon as the panel opens. Never against production. | diff --git a/apps/docs/src/pages/test.astro b/apps/docs/src/pages/test.astro index a932cb2..bfeec12 100644 --- a/apps/docs/src/pages/test.astro +++ b/apps/docs/src/pages/test.astro @@ -53,6 +53,18 @@ import { capture } from '../lib/captures'

+
+

+ Inputs can repeat, too. Declare a traveler as a c.object and a booking's travelers as a{' '} + c.array with a minimum and a maximum. QA sets how many there are and gets a row for each, + and CI can pass the whole list with --input travelers=[…]. +

+

+ Try it on the demo site ↗ +

+

Give QA a portal

diff --git a/apps/example/sequences/ui-demo.seq.ts b/apps/example/sequences/ui-demo.seq.ts new file mode 100644 index 0000000..d789de2 --- /dev/null +++ b/apps/example/sequences/ui-demo.seq.ts @@ -0,0 +1,46 @@ +import { c, sequence } from '@specbook/core' +import { faker } from '@specbook/core/faker' + +// A flow with no request: it exists to show what QA gets from the inputs. Change how many travelers, press the die to make +// another name for one traveler, or Generate all for a new set, then Run to see the checks. +export default sequence({ + id: 'ui-demo', + title: 'Dynamic inputs', + group: 'UI', + description: + 'A demo of generated inputs, with no request to send. A booking starts with two travelers (1 to 10): set how many, make a first and last name for each with the dice or Generate all, choose a gender, say which one is the primary traveler, and give a date of birth if you want to. Run only checks what was entered.', + tags: ['demo'], + inputs: { + travelers: c.array( + c.object({ + firstName: c.text({ default: () => faker.person.firstName() }), + lastName: c.text({ default: () => faker.person.lastName() }), + gender: c.select(['female', 'male', 'other'] as const), + role: c.select(['primary', 'companion'] as const, { default: 'companion' }), + dateOfBirth: c.date({ description: 'Optional.' }), + }), + { + min: 1, + max: 10, + label: 'Travelers', + // the first is the primary traveler; each one is made from the defaults above, with its own generated names + default: () => [{ role: 'primary' }, {}], + }, + ), + }, +}) + .check('Every traveler has a first and last name', (ctx, { assert }) => { + for (const t of ctx.inputs.travelers) + assert.ok(t.firstName.trim() !== '' && t.lastName.trim() !== '', 'a traveler has a name') + }) + .check('Exactly one traveler is primary', (ctx, { assert }) => { + const primary = ctx.inputs.travelers.filter((t) => t.role === 'primary').length + assert.is(primary, 1, `${primary} travelers are primary`) + }) + .check('A date of birth, when given, is a date', (ctx, { assert }) => { + for (const t of ctx.inputs.travelers) + assert.ok( + !t.dateOfBirth || !Number.isNaN(Date.parse(t.dateOfBirth)), + 'a date of birth is a date', + ) + }) diff --git a/packages/cli/agent-guide.md b/packages/cli/agent-guide.md index d6c0c81..0b123db 100644 --- a/packages/cli/agent-guide.md +++ b/packages/cli/agent-guide.md @@ -155,6 +155,7 @@ export default sequence({ - `request.with({ ... })` changes a request for one step (for example its `assert`, or the values it sends). - Also: `.input(name, ctx => controls)` asks a person for values, `.each(name, items, make)` repeats a request per item, `.check(name, fn)` asserts on the flow's state, `.use(otherFlow)` includes another flow. - Controls are `c.number`, `c.text`, `c.select`, `c.multiselect`, `c.boolean`, `c.date`, `c.object`, `c.array`. A flow also runs unattended in CI and as a monitor, so every input and every `.input()` control needs a default that makes sense with nobody to ask. +- Several values for one thing (travelers, line items): `c.object({ name: c.text(...), gender: c.select([...]) }, { label: 'Traveler 1' })` is a group, and `c.array(item, { min: 1, max: 10, label: 'Travelers' })` is a list whose length a person sets. The form shows groups with the same fields as one table with a row for each, so declare them with one helper (`const traveler = (label: string) => c.object({ ... }, { label })`). A list with no value starts at `min` items, each made from its own defaults. Read them as `{{traveler1.name}}` or `{{travelers[0].name}}`, or `ctx.inputs.travelers` (`.each(name, ctx => ctx.inputs.travelers, ...)` makes a request for each). A flat key with a dot (`'traveler1.name'`) is not a path: use a group. - For generated data: `import { faker } from '@specbook/core/faker'` and use it in a default, for example `c.text({ default: () => faker.person.fullName() })`. It is typed, and `specbook init` adds `@faker-js/faker` to `package.json` (`npm install` fetches it). A `{{faker.person.firstName}}` placeholder (`faker..`, no arguments) also works in a field. - Each step is also a request you can run alone. diff --git a/packages/core/src/controls.ts b/packages/core/src/controls.ts index 846ebbf..905496a 100644 --- a/packages/core/src/controls.ts +++ b/packages/core/src/controls.ts @@ -81,13 +81,25 @@ export const c = { kind: 'multiselect', opts: { ...o, options }, }), - object: (shape: S): Control> => ({ + /** A group of fields; its `label` heads the row when objects of the same shape are shown as one table. */ + object: ( + shape: S, + o: { label?: string; description?: string } = {}, + ): Control> => ({ kind: 'object', - opts: { shape }, + opts: { ...o, shape }, }), + /** A list of `min` to `max` items, each made from the item's own defaults when nothing is given. */ array: ( item: Control, - o: { default?: T[]; min?: number; max?: number } = {}, + o: { + /** the starting list, or a function that makes it; an item may name only some fields, the rest start from their own defaults */ + default?: Default[]> + min?: number + max?: number + label?: string + description?: string + } = {}, ): Control => ({ kind: 'array', opts: { ...o, item } }), } @@ -141,17 +153,20 @@ export function resolveControl(name: string, ctl: Control, given: unknown): unkn const shape = ctl.opts.shape as Controls const g = (given ?? {}) as Record return Object.fromEntries( - Object.entries(shape).map(([k, v]) => [k, resolveControl(k, v, g[k])]), + Object.entries(shape).map(([k, v]) => [k, resolveControl(`${name}.${k}`, v, g[k])]), ) } case 'array': { - const v = (given ?? ctl.opts.default ?? []) as unknown[] const { min, max } = ctl.opts + // nothing given: the list starts at its minimum, each item made from its own defaults + const v = (given ?? + startingValue(ctl.opts.default) ?? + Array.from({ length: min ?? 0 })) as unknown[] if (min !== undefined && v.length < min) throw new ControlError(`"${name}" needs at least ${min} items`) if (max !== undefined && v.length > max) throw new ControlError(`"${name}" allows at most ${max} items`) - return v.map((item) => resolveControl(name, ctl.opts.item, item)) + return v.map((item, i) => resolveControl(`${name}[${i}]`, ctl.opts.item, item)) } case 'boolean': return given ?? startingValue(ctl.opts.default) ?? false @@ -171,22 +186,59 @@ export function resolveControls( ) } +/** Serializable description of one control, for a UI to render an input step. */ +function describeControl(name: string, ctl: Control): Record { + const text = (k: string) => (typeof ctl.opts[k] === 'string' ? { [k]: ctl.opts[k] } : {}) + const meta = { ...text('label'), ...text('description') } + if (ctl.kind === 'select' || ctl.kind === 'multiselect') { + const labelFn = ctl.opts.label as ((o: unknown) => string) | undefined + const options = (ctl.opts.options as unknown[]).map((o) => ({ + label: labelFn ? labelFn(o) : String(optionValue(ctl, o)), + value: optionValue(ctl, o), + })) + let initial: unknown + try { + initial = resolveControl(name, ctl, undefined) + } catch { + /* no options: nothing to start from */ + } + return { + kind: ctl.kind, + options, + ...(initial !== undefined ? { default: initial } : {}), + ...meta, + } + } + if (ctl.kind === 'object') + return { + kind: 'object', + shape: Object.fromEntries( + Object.entries(ctl.opts.shape as Controls).map(([k, v]) => [k, describeControl(k, v)]), + ), + ...meta, + } + if (ctl.kind === 'array') + return { + kind: 'array', + item: describeControl(name, ctl.opts.item), + default: startingValue(ctl.opts.default), + min: ctl.opts.min, + max: ctl.opts.max, + ...meta, + } + return { + kind: ctl.kind, + default: startingValue(ctl.opts.default), + generated: isGenerated(ctl), + ...(ctl.opts.min !== undefined ? { min: ctl.opts.min } : {}), + ...(ctl.opts.max !== undefined ? { max: ctl.opts.max } : {}), + ...meta, + } +} + /** Serializable description for a UI to render an input step. */ export function describeControls(controls: Controls) { return Object.fromEntries( - Object.entries(controls).map(([k, ctl]) => { - if (ctl.kind === 'select' || ctl.kind === 'multiselect') { - const labelFn = ctl.opts.label as ((o: unknown) => string) | undefined - const options = (ctl.opts.options as unknown[]).map((o) => ({ - label: labelFn ? labelFn(o) : String(optionValue(ctl, o)), - value: optionValue(ctl, o), - })) - return [k, { kind: ctl.kind, options }] - } - return [ - k, - { kind: ctl.kind, default: startingValue(ctl.opts.default), generated: isGenerated(ctl) }, - ] - }), + Object.entries(controls).map(([k, ctl]) => [k, describeControl(k, ctl)]), ) } diff --git a/packages/core/test/controls.test.ts b/packages/core/test/controls.test.ts index 9b22641..ca3048b 100644 --- a/packages/core/test/controls.test.ts +++ b/packages/core/test/controls.test.ts @@ -58,6 +58,56 @@ describe('controls', () => { const d = describeControls({ f: c.select([{ id: 1, n: 'A' }], { label: (o) => o.n, value: (o) => o.id }), }) - expect(d.f).toEqual({ kind: 'select', options: [{ label: 'A', value: 1 }] }) + expect(d.f).toEqual({ kind: 'select', options: [{ label: 'A', value: 1 }], default: 1 }) + }) + it('a list with no value given starts at its minimum, each item from its own defaults', () => { + let n = 0 + const t = c.array(c.object({ name: c.text({ default: () => `P${++n}` }) }), { min: 2, max: 3 }) + expect(resolveControls({ t })).toEqual({ t: [{ name: 'P1' }, { name: 'P2' }] }) + expect(resolveControls({ t: c.array(c.text(), {}) })).toEqual({ t: [] }) + }) + it('names the path of a value that is wrong', () => { + const t = c.array(c.object({ gender: c.select(['F', 'M'] as const) }), { min: 1 }) + expect(() => resolveControls({ t }, { t: [{ gender: 'F' }, { gender: 'Z' }] })).toThrow( + /t\[1\]\.gender/, + ) + expect(() => + resolveControls({ g: c.object({ x: c.select(['a'] as const) }) }, { g: { x: 'b' } }), + ).toThrow(/g\.x/) + }) + it('describes groups and lists with their shape, labels and limits', () => { + const d = describeControls({ + who: c.object({ name: c.text({ label: 'Name', default: 'x' }) }, { label: 'Traveler 1' }), + all: c.array(c.object({ n: c.number({ min: 1 }) }), { min: 1, max: 4, label: 'Travelers' }), + }) + expect(d.who).toMatchObject({ + kind: 'object', + label: 'Traveler 1', + shape: { name: { kind: 'text', label: 'Name', default: 'x' } }, + }) + expect(d.all).toMatchObject({ + kind: 'array', + min: 1, + max: 4, + label: 'Travelers', + item: { kind: 'object', shape: { n: { kind: 'number', min: 1 } } }, + }) + }) + it('a list can start from a function that names only some fields of each item', () => { + let n = 0 + const t = c.array( + c.object({ + name: c.text({ default: () => `P${++n}` }), + role: c.text({ default: 'companion' }), + }), + { min: 1, default: () => [{ role: 'primary' }, {}] }, + ) + expect(resolveControls({ t })).toEqual({ + t: [ + { name: 'P1', role: 'primary' }, + { name: 'P2', role: 'companion' }, + ], + }) + expect(describeControls({ t }).t).toMatchObject({ default: [{ role: 'primary' }, {}] }) }) }) diff --git a/packages/core/test/runner.test.ts b/packages/core/test/runner.test.ts index 34aa284..f427aa5 100644 --- a/packages/core/test/runner.test.ts +++ b/packages/core/test/runner.test.ts @@ -315,6 +315,7 @@ describe('runSequence', () => { { label: 'X1', value: 'a' }, { label: 'X2', value: 'b' }, ], + default: 'a', }, }) expect(calls.at(-1)?.url).toBe('/book/b') @@ -907,3 +908,15 @@ describe('OAuth client credentials', () => { expect(r.steps[0]?.error).toContain('has no usable token address') }) }) + +describe('a flow whose list input has a minimum', () => { + it('runs on its defaults: the list starts at its minimum', async () => { + const seq = sequence({ + id: 'lists', + title: 'Lists', + inputs: { people: c.array(c.object({ name: c.text({ default: 'Ada' }) }), { min: 2 }) }, + }) + const r = await runSequence(seq, {} as never) + expect(r.status).not.toBe('error') + }) +}) diff --git a/packages/ui/src/components/Fields.tsx b/packages/ui/src/components/Fields.tsx index 6ae85a8..fb4e3a8 100644 --- a/packages/ui/src/components/Fields.tsx +++ b/packages/ui/src/components/Fields.tsx @@ -1,4 +1,5 @@ -import type { JSX } from 'preact' +import { resolveControl } from '@specbook/core' +import { short } from '../panel/short' /** Normalised field description, built from either a Control or a described input control. */ export interface FieldSpec { @@ -31,9 +32,17 @@ function baseSpec(ctl: any, o: any): FieldSpec { case 'multiselect': { const value = (x: unknown) => (typeof o.value === 'function' ? o.value(x) : x) const label = (x: unknown) => (typeof o.label === 'function' ? o.label(x) : String(value(x))) + let initial: unknown + try { + // what the CLI starts from, so the form and `specbook test` agree on a default that is not the first option + initial = resolveControl('', ctl, undefined) + } catch { + /* no options */ + } return { kind: ctl.kind, options: (o.options as unknown[]).map((x) => ({ label: label(x), value: value(x) })), + ...(initial !== undefined ? { default: initial } : {}), } } case 'object': @@ -74,15 +83,20 @@ export function defaultFor(spec: FieldSpec): unknown { if (spec.generate) return generateFor(spec) switch (spec.kind) { case 'select': - return spec.options?.[0]?.value + return spec.default ?? spec.options?.[0]?.value case 'multiselect': - return [] + return spec.default ?? [] case 'object': return Object.fromEntries( Object.entries(spec.shape ?? {}).map(([k, s]) => [k, defaultFor(s)]), ) - case 'array': - return spec.default ?? [] + case 'array': { + const item = spec.item as FieldSpec + // a given list is filled item by item; none starts at its minimum, each item from its own defaults + const list = typeof spec.default === 'function' ? spec.default() : spec.default + if (Array.isArray(list)) return list.map((x) => withDefaults(item, x)) + return Array.from({ length: spec.min ?? 0 }, () => defaultFor(item)) + } case 'boolean': return spec.default ?? false case 'number': @@ -92,146 +106,96 @@ export function defaultFor(spec: FieldSpec): unknown { } } -interface FieldProps { - name: string - spec: FieldSpec - value: unknown - onChange: (v: unknown) => void +const isObject = (v: unknown): v is Record => + typeof v === 'object' && v !== null && !Array.isArray(v) + +/** A value made whole: what is missing comes from the defaults (a preset of one field of a group leaves the others). */ +export function withDefaults(spec: FieldSpec, given: unknown): unknown { + if (given === undefined) return defaultFor(spec) + if (spec.kind === 'object') { + if (!isObject(given)) return defaultFor(spec) + return { + ...given, + ...Object.fromEntries( + Object.entries(spec.shape ?? {}).map(([k, s]) => [k, withDefaults(s, given[k])]), + ), + } + } + if (spec.kind === 'array') { + if (!Array.isArray(given)) return defaultFor(spec) + const item = spec.item as FieldSpec + const list = given.map((x) => withDefaults(item, x)) + while (spec.min !== undefined && list.length < spec.min) list.push(defaultFor(item)) + return list + } + return given } -const same = (a: unknown, b: unknown) => a === b || JSON.stringify(a) === JSON.stringify(b) +/** Every input at its start: the preset where it gave one, the default elsewhere; a key of the preset no input has is kept. */ +export function startValues( + specs: Record, + preset: Record = {}, +): Record { + return { + ...preset, + ...Object.fromEntries(Object.entries(specs).map(([k, s]) => [k, withDefaults(s, preset[k])])), + } +} -export function Field({ name, spec, value, onChange }: FieldProps): JSX.Element { - const wrap = (body: JSX.Element) => ( -
- {name} - {body} -
+/** Whether a field, or anything inside it, makes its own starting value. */ +export function anyGenerated(spec: FieldSpec): boolean { + return Boolean( + spec.generate || + (spec.shape && Object.values(spec.shape).some(anyGenerated)) || + (spec.item && anyGenerated(spec.item)), ) - switch (spec.kind) { - case 'number': - return wrap( - onChange(Number((e.target as HTMLInputElement).value))} - />, - ) - case 'boolean': - return wrap( - onChange((e.target as HTMLInputElement).checked)} - />, - ) - case 'date': - return wrap( - onChange((e.target as HTMLInputElement).value)} - />, - ) - case 'select': { - const idx = Math.max( - 0, - (spec.options ?? []).findIndex((o) => same(o.value, value)), - ) - return wrap( - , - ) - } - case 'multiselect': { - const current = (value as unknown[]) ?? [] - return wrap( -
- {(spec.options ?? []).map((o) => ( - - ))} -
, - ) - } - case 'object': { - const obj = (value ?? {}) as Record - return wrap( -
- {Object.entries(spec.shape ?? {}).map(([k, s]) => ( - onChange({ ...obj, [k]: v })} - /> - ))} -
, - ) - } - case 'array': { - const list = (value as unknown[]) ?? [] - const item = spec.item as FieldSpec - return wrap( -
- {list.map((v, i) => ( -
- onChange(list.map((x, j) => (j === i ? nv : x)))} - /> - -
- ))} - -
, - ) +} + +/** How many generated values a field holds right now. */ +export function generatedCount(spec: FieldSpec, value: unknown): number { + if (spec.generate) return 1 + if (spec.kind === 'object' && isObject(value)) + return Object.entries(spec.shape ?? {}).reduce( + (n, [k, s]) => n + generatedCount(s, value[k]), + 0, + ) + if (spec.kind === 'array' && Array.isArray(value) && spec.item) { + const item = spec.item + return value.reduce((n: number, x) => n + generatedCount(item, x), 0) + } + return 0 +} + +/** Another value for every generated field inside this one; what was typed into the others stays. */ +export function regenerate(spec: FieldSpec, value: unknown): unknown { + if (spec.generate) return generateFor(spec) + if (spec.kind === 'object' && isObject(value)) + return { + ...value, + ...Object.fromEntries( + Object.entries(spec.shape ?? {}).map(([k, s]) => [k, regenerate(s, value[k])]), + ), } - default: - return wrap( - onChange((e.target as HTMLInputElement).value)} - />, - ) + if (spec.kind === 'array' && Array.isArray(value) && spec.item) { + const item = spec.item + return value.map((x) => regenerate(item, x)) } + return value +} + +/** The inputs in a line: `currency usd · travelers 3 · amount 2000 +1`. */ +export function summarize( + specs: Record, + values: Record, + shown = 3, +): string { + const bits = Object.entries(specs).map(([name, spec]) => { + const label = spec.label ?? name + const v = values[name] + if (spec.kind === 'array') return `${label} ${Array.isArray(v) ? v.length : 0}` + if (spec.kind === 'object') return label + return `${label} ${short(v)}` + }) + const more = bits.length - shown + return bits.slice(0, shown).join(' · ') + (more > 0 ? ` +${more}` : '') } diff --git a/packages/ui/src/media.ts b/packages/ui/src/media.ts new file mode 100644 index 0000000..2736b0f --- /dev/null +++ b/packages/ui/src/media.ts @@ -0,0 +1,21 @@ +import { useEffect, useState } from 'preact/hooks' + +/** The widths the panel's layout changes at; keep them in step with panel.css. */ +export const NARROW = '(max-width: 900px)' // the flow panel is one column +export const PHONE = '(max-width: 820px)' // the panel fills the screen, and a step opens as a sheet + +/** Whether a media query matches now, and again when it changes. */ +export function useMedia(query: string): boolean { + const [matches, setMatches] = useState( + () => typeof matchMedia === 'function' && matchMedia(query).matches, + ) + useEffect(() => { + if (typeof matchMedia !== 'function') return + const mq = matchMedia(query) + const change = () => setMatches(mq.matches) + change() + mq.addEventListener('change', change) + return () => mq.removeEventListener('change', change) + }, [query]) + return matches +} diff --git a/packages/ui/src/panel/ControlsGrid.tsx b/packages/ui/src/panel/ControlsGrid.tsx index fedbf63..06d4c3d 100644 --- a/packages/ui/src/panel/ControlsGrid.tsx +++ b/packages/ui/src/panel/ControlsGrid.tsx @@ -1,5 +1,12 @@ -import { useState } from 'preact/hooks' -import { defaultFor, type FieldSpec, generateFor } from '../components/Fields' +import { useRef, useState } from 'preact/hooks' +import { + anyGenerated, + defaultFor, + type FieldSpec, + generatedCount, + generateFor, + regenerate, +} from '../components/Fields' import { Combo } from './Combo' interface Props { @@ -147,19 +154,272 @@ function Die() { ) } +const isObject = (v: unknown): v is Record => + typeof v === 'object' && v !== null && !Array.isArray(v) + +interface Column { + /** the field of an object this column shows; none for a list of plain values */ + key?: string + label: string + spec: FieldSpec +} + +export type Block = + | { kind: 'fields'; names: string[] } + | { kind: 'objects'; names: string[]; columns: Column[] } + | { kind: 'list'; name: string; columns: Column[] } + +const columnsOf = (spec: FieldSpec): Column[] => + spec.kind === 'object' && spec.shape + ? Object.entries(spec.shape).map(([key, s]) => ({ key, label: s.label ?? key, spec: s })) + : [{ label: spec.label ?? 'Value', spec }] + +const signature = (spec: FieldSpec) => + Object.entries(spec.shape ?? {}) + .map(([k, s]) => `${k}:${s.kind}`) + .join(',') + +/** + * How the inputs are laid out, in the order they were declared: plain inputs are rows of one table, neighbouring groups + * (`c.object`) that have the same fields are the rows of one table, and a list (`c.array`) is a table of its own. + */ +export function blocksOf(specs: Record): Block[] { + const blocks: Block[] = [] + for (const [name, spec] of Object.entries(specs)) { + const last = blocks[blocks.length - 1] + if (spec.kind === 'array' && spec.item) { + blocks.push({ kind: 'list', name, columns: columnsOf(spec.item) }) + } else if (spec.kind === 'object' && spec.shape && Object.keys(spec.shape).length > 0) { + if ( + last?.kind === 'objects' && + signature(specs[last.names[0] as string] as FieldSpec) === signature(spec) + ) + last.names.push(name) + else blocks.push({ kind: 'objects', names: [name], columns: columnsOf(spec) }) + } else if (last?.kind === 'fields') last.names.push(name) + else blocks.push({ kind: 'fields', names: [name] }) + } + return blocks +} + +/** A value and, when it has a generator, the die that makes another. */ +function GenCell({ + name, + spec, + value, + onChange, + die = true, +}: { + name: string + spec: FieldSpec + value: unknown + onChange: (v: unknown) => void + /** whether the cell has a die of its own; a field in a row of a group is made again by the row's die */ + die?: boolean +}) { + const own = die && spec.generate + return ( +
+ + {own && ( + + )} +
+ ) +} + +interface Row { + heading: string + path: string + spec: FieldSpec + value: unknown + onChange: (v: unknown) => void + onRemove?: () => void + removeDisabled?: boolean +} + +/** Rows of one shape: a heading and a die for the row, then a cell for each field. Cards on a narrow screen. */ +function GroupTable({ + caption, + columns, + rows, + count, +}: { + caption?: string + columns: Column[] + rows: Row[] + count?: { name: string; value: number; min?: number; max?: number; onChange: (n: number) => void } +}) { + const countRef = useRef(null) + return ( +
+ {(caption || count) && ( +
+ {caption} + {count && ( + + )} +
+ )} + + + + + ))} + + + + {rows.map((row, i) => ( + + + {columns.map((col) => { + const spec = col.key ? (row.spec.shape?.[col.key] ?? col.spec) : row.spec + const obj = isObject(row.value) ? row.value : {} + const value = col.key ? obj[col.key] : row.value + const name = col.key ? `${row.path}.${col.key}` : row.path + return ( + + ) + })} + + ))} + +
+ {columns.map((col) => ( + {col.label}
+ {row.heading} + + {anyGenerated(row.spec) && ( + + )} + {row.onRemove && ( + + )} + + + + row.onChange(col.key ? { ...obj, [col.key]: v } : v)} + /> +
+
+ ) +} + +/** A list of groups: how many, and a row for each. Rows taken off by lowering the count come back if it is raised again. */ +function ListBlock({ + name, + spec, + columns, + value, + onChange, +}: { + name: string + spec: FieldSpec + columns: Column[] + value: unknown + onChange: (v: unknown) => void +}) { + const trimmed = useRef([]) + const item = spec.item as FieldSpec + const list = Array.isArray(value) ? value : [] + const min = spec.min ?? 0 + const setCount = (asked: number) => { + const n = Math.max(min, Math.min(spec.max ?? Number.POSITIVE_INFINITY, Math.round(asked))) + if (n < list.length) { + trimmed.current = [...list.slice(n), ...trimmed.current] + onChange(list.slice(0, n)) + } else if (n > list.length) { + const more = Array.from({ length: n - list.length }, () => + trimmed.current.length > 0 ? trimmed.current.shift() : defaultFor(item), + ) + onChange([...list, ...more]) + } else onChange([...list]) + } + return ( + ({ + heading: `#${i + 1}`, + path: `${name}[${i}]`, + spec: item, + value: v, + onChange: (nv) => onChange(list.map((x, j) => (j === i ? nv : x))), + onRemove: () => onChange(list.filter((_, j) => j !== i)), + removeDisabled: list.length <= min, + }))} + /> + ) +} + /** * A flow's controls (inputs, or the choices of an input step) as the same spreadsheet the request - * parameters use: name, value, description. + * parameters use: name, value, description. Groups and lists are tables of their own. */ export function ControlsGrid({ title, specs, values, onChange }: Props) { const names = Object.keys(specs) if (names.length === 0) return null - const generated = names.filter((n) => specs[n]?.generate) + const generated = names.reduce((n, k) => n + generatedCount(specs[k] as FieldSpec, values[k]), 0) + const set = (name: string) => (v: unknown) => onChange({ ...values, [name]: v }) return (

{title} - {generated.length > 1 && ( + {generated > 1 && ( )}

- - - - - - - - - - - - - - - {names.map((name) => { - const spec = specs[name] as FieldSpec - return ( - - - - + {blocksOf(specs).map((block) => { + if (block.kind === 'list') { + const spec = specs[block.name] as FieldSpec + return ( + + ) + } + if (block.kind === 'objects') + return ( + { + const spec = specs[name] as FieldSpec + return { + heading: spec.label ?? name, + path: name, + spec, + value: values[name], + onChange: set(name), + } + })} + /> + ) + return ( +
NameValueDescription
- - {spec.label ?? name} - - -
- onChange({ ...values, [name]: v })} - /> - {spec.generate && ( - - )} -
-
- {hint(spec)} {spec.description} -
+ + + + + + + + + + - ) - })} - -
NameValueDescription
+ + + {block.names.map((name) => { + const spec = specs[name] as FieldSpec + return ( + + + + {spec.label ?? name} + + + + + + + {hint(spec)} {spec.description} + + + ) + })} + + + ) + })}
) } diff --git a/packages/ui/src/panel/Host.tsx b/packages/ui/src/panel/Host.tsx index 7f6e9bc..be9fb43 100644 --- a/packages/ui/src/panel/Host.tsx +++ b/packages/ui/src/panel/Host.tsx @@ -1,10 +1,23 @@ +import { useEffect, useState } from 'preact/hooks' import type { SequenceInfo, Variant } from '../engine' import type { PanelTab } from '../nav' import { OperationDocs } from './OperationDocs' import { Panel } from './Panel' import { type OpInfo, RequestPanel } from './RequestPanel' -import { SequenceDocs } from './SequenceDocs' -import { SequencePanel } from './SequencePanel' + +/** + * A flow's views are fetched when a flow is opened: opening one request does not pay for the form of a flow's inputs + * (the embed's first click is measured, in bytes). + */ +function useLoaded(load: () => Promise, wanted: boolean): T | undefined { + const [loaded, setLoaded] = useState() + useEffect(() => { + if (wanted) void load().then(setLoaded) + }, [wanted]) + return loaded +} +const loadSequencePanel = () => import('./SequencePanel') +const loadSequenceDocs = () => import('./SequenceDocs') type Props = { onClose: () => void @@ -28,6 +41,8 @@ type Props = { /** Lazy entry for everything the side panel needs, so the catalog carries no editor code. */ export function Host(p: Props) { const tab = p.tab ?? 'try' + const panelView = useLoaded(loadSequencePanel, p.kind === 'seq' && tab !== 'docs') + const docsView = useLoaded(loadSequenceDocs, p.kind === 'seq' && tab === 'docs') const tabs = (
{( @@ -64,11 +79,11 @@ export function Host(p: Props) {
{tabs}
- {tab === 'docs' ? ( - - ) : ( - - )} + {tab === 'docs' + ? docsView && + : panelView && ( + + )}
diff --git a/packages/ui/src/panel/Panel.tsx b/packages/ui/src/panel/Panel.tsx index 47456bd..5d5ddc2 100644 --- a/packages/ui/src/panel/Panel.tsx +++ b/packages/ui/src/panel/Panel.tsx @@ -82,8 +82,11 @@ export function Panel({ // a dropdown field needs its list visible too, and picking from it needs no keyboard: it is moved // only when it is down where the keyboard would be, and not as far const dropdown = field.getAttribute('role') === 'combobox' - const want = top + height * (dropdown ? 0.3 : 0.2) - if (at > top + height * (dropdown ? 0.55 : 0.4) || at < top) box.scrollTop += at - want + // a bar kept at the top of the scroller (the flow's Run row) is not where a field can go + const bar = parseFloat(getComputedStyle(box).scrollPaddingTop) || 0 + const floor = Math.max(top, box.getBoundingClientRect().top + bar + 8) + const want = Math.max(top + height * (dropdown ? 0.3 : 0.2), floor) + if (at > top + height * (dropdown ? 0.55 : 0.4) || at < floor) box.scrollTop += at - want } const focusin = (e: Event) => { const field = e.target as HTMLElement diff --git a/packages/ui/src/panel/SequenceDocs.tsx b/packages/ui/src/panel/SequenceDocs.tsx index 648f469..ed36c24 100644 --- a/packages/ui/src/panel/SequenceDocs.tsx +++ b/packages/ui/src/panel/SequenceDocs.tsx @@ -14,6 +14,53 @@ const KIND: Record = { const showValue = (v: unknown) => (typeof v === 'string' ? v : show(v)) +interface ControlRow { + name: string + kind: string + initial: string + description?: string + depth: number +} + +/** + * A control as the rows of the table: a group or a list is its own row, then a row for each of its fields + * (`traveler1.name`, `travelers[].name`). A generated default is said to be generated, never made here. + */ +function controlRows(name: string, spec: FieldSpec, depth = 0): ControlRow[] { + const limits = + spec.min !== undefined || spec.max !== undefined ? ` ${spec.min ?? ''}–${spec.max ?? ''}` : '' + const self = { + name, + description: spec.description, + depth, + } + if (spec.kind === 'object') + return [ + { ...self, kind: 'group', initial: '' }, + ...Object.entries(spec.shape ?? {}).flatMap(([k, s]) => + controlRows(`${name}.${k}`, s, depth + 1), + ), + ] + if (spec.kind === 'array') { + const item = spec.item as FieldSpec + return [ + { ...self, kind: `list${limits}`, initial: '' }, + ...(item.kind === 'object' + ? Object.entries(item.shape ?? {}).flatMap(([k, s]) => + controlRows(`${name}[].${k}`, s, depth + 1), + ) + : controlRows(`${name}[]`, item, depth + 1)), + ] + } + return [ + { + ...self, + kind: spec.kind + limits, + initial: spec.generate ? 'generated' : showValue(defaultFor(spec)), + }, + ] +} + /** * What a sequence does, as documentation: its description (markdown), an optional markdown page from * `docs/*.md` with `sequence: ` frontmatter, the controls it takes and the operation behind each step. @@ -24,9 +71,8 @@ export function SequenceDocs({ info }: { info: SequenceInfo }) { const inputs = useMemo( () => - Object.entries((seq.meta.inputs ?? {}) as Record).map(([name, c]) => { - const spec: FieldSpec = specFromControl(c) - return { name, spec, initial: defaultFor(spec) } + Object.entries((seq.meta.inputs ?? {}) as Record).flatMap(([name, c]) => { + return controlRows(name, specFromControl(c)) }), [seq], ) @@ -58,16 +104,14 @@ export function SequenceDocs({ info }: { info: SequenceInfo }) { {inputs.map((p) => ( - + {p.name} - {p.spec.kind} - - - {showValue(p.initial)} + {p.kind} - {p.spec.description} + {p.initial && {p.initial}} + {p.description} ))} diff --git a/packages/ui/src/panel/SequencePanel.tsx b/packages/ui/src/panel/SequencePanel.tsx index bd2f6a6..32c5318 100644 --- a/packages/ui/src/panel/SequencePanel.tsx +++ b/packages/ui/src/panel/SequencePanel.tsx @@ -2,8 +2,16 @@ import type { RunResult, StepResult } from '@specbook/core' import { useEffect, useMemo, useRef, useState } from 'preact/hooks' import type { Security } from '../auth-options' import { EnvBadge } from '../components/EnvBadge' -import { defaultFor, type FieldSpec, specFromControl } from '../components/Fields' +import { + anyGenerated, + defaultFor, + type FieldSpec, + specFromControl, + startValues, + summarize, +} from '../components/Fields' import type { SequenceInfo } from '../engine' +import { NARROW, useMedia } from '../media' import { engine } from '../runtime' import { env, fakerInUse, locale, seed, version } from '../store' import { announcement, describeRun } from './announce' @@ -29,6 +37,12 @@ const ICON = { pending: '', } +/** + * What was typed into each flow, kept while the panel is away (the Docs tab) or on another flow. Memory only. Generated + * values depend on the seed and the locale, so a form kept under other ones is not the form to come back to. + */ +const kept = new Map>() + /** |timeline|request|: the journey on the left, the selected step's exchange on the right. */ export function SequencePanel({ info, @@ -84,8 +98,12 @@ export function SequencePanel({ // a phone shows the selected step's request and response as a sheet over the timeline const [sheet, setSheet] = useState(false) const [error, setError] = useState() + // the Inputs stop of the timeline: on a wide screen it is the view of the right pane, on a narrow one the form unfolds under it + const keptKey = `${info.file}|${seed.value}|${locale.value}` + const [inputsOpen, setInputsOpen] = useState(true) + const narrow = useMedia(NARROW) - const hasGenerated = Object.values(specs).some((s) => s.generate) + const hasGenerated = Object.values(specs).some(anyGenerated) // a flow with inputs can run on their defaults alone, as `specbook test` does const hasInputs = Object.keys(specs).length > 0 || seq.nodes.some((n) => n.kind === 'input') @@ -100,27 +118,29 @@ export function SequencePanel({ const freshInputs = async () => { if (hasGenerated) await engine.fakerReady(version.value, locale.value, seed.value).catch(() => {}) - return Object.fromEntries(Object.entries(specs).map(([k, v]) => [k, defaultFor(v)])) + return startValues(specs, preset) } useEffect(() => { let current = true - const start = (v: Record) => ({ ...v, ...(preset ?? {}) }) - setInputs(start(Object.fromEntries(Object.entries(specs).map(([k, v]) => [k, defaultFor(v)])))) - // generated values need faker: fill them in as soon as it is ready - if (hasGenerated) - void freshInputs().then((v) => { - if (!current) return - setInputs(start(v)) - if (autoRun) void run({ inputs: start(v), headless: true }) - }) - else if (autoRun) - void run({ - inputs: start( - Object.fromEntries(Object.entries(specs).map(([k, v]) => [k, defaultFor(v)])), - ), - headless: true, - }) + const saved = kept.get(keptKey) + if (saved) { + // back on a flow that was being filled in: what was typed is still there, and nothing runs by itself + setInputs(startValues(specs, saved)) + if (hasGenerated) + void engine.fakerReady(version.value, locale.value, seed.value).catch(() => {}) + } else { + setInputs(startValues(specs, preset)) + // generated values need faker: fill them in as soon as it is ready + if (hasGenerated) + void freshInputs().then((v) => { + if (!current) return + setInputs(v) + if (autoRun) void run({ inputs: v, headless: true }) + }) + else if (autoRun) void run({ inputs: startValues(specs, preset), headless: true }) + } + setInputsOpen(true) setResult(undefined) setLive({}) setPause(undefined) @@ -129,10 +149,22 @@ export function SequencePanel({ } }, [info.file]) + useEffect(() => { + if (Object.keys(inputs).length > 0) kept.set(keptKey, inputs) + }, [inputs]) + const planned = seq.nodes.map((n) => n.name) - const rows: { name: string; step?: StepResult }[] = result - ? result.steps.filter((s) => s.kind !== 'auth').map((s) => ({ name: s.name, step: s })) - : planned.map((n) => ({ name: n })) + // inputs that could not be made into values end the run before any step: the timeline stays as planned + const bad0 = result?.steps[0] + const inputsFailed = + result?.steps.length === 1 && + bad0?.kind === 'input' && + bad0.name === 'inputs' && + bad0.status === 'error' + const rows: { name: string; step?: StepResult }[] = + result && !inputsFailed + ? result.steps.filter((s) => s.kind !== 'auth').map((s) => ({ name: s.name, step: s })) + : planned.map((n) => ({ name: n })) const current = rows[picked]?.step /** ends the run that is going: what is out is stopped, and nothing after it starts */ @@ -155,6 +187,8 @@ export function SequencePanel({ setLive({}) setPicked(0) setSheet(false) + // a narrow screen shows the run: the form folds away + if (narrow) setInputsOpen(false) try { const r = await engine.run(seq, { env: env.value, @@ -171,7 +205,7 @@ export function SequencePanel({ ? undefined : ({ name, controls }) => new Promise((resolve) => { - const c = controls as Record + const c = controls as unknown as Record setLive((l) => ({ ...l, [name]: 'paused' })) setChoice(Object.fromEntries(Object.entries(c).map(([k, v]) => [k, defaultFor(v)]))) setPause({ @@ -186,11 +220,22 @@ export function SequencePanel({ }) setResult(r) announcement.value = describeRun(r) - // a run that did not pass shows its first failing step, not its first step - const bad = r.steps - .filter((s) => s.kind !== 'auth') - .findIndex((s) => s.status === 'fail' || s.status === 'error') - if (bad >= 0) setPicked(bad) + const first = r.steps[0] + if ( + r.steps.length === 1 && + first?.kind === 'input' && + first.name === 'inputs' && + first.status === 'error' + ) + setInputsOpen(true) + else { + // a run that did not pass shows its first failing step, not its first step + const bad = r.steps + .filter((s) => s.kind !== 'auth') + .findIndex((s) => s.status === 'fail' || s.status === 'error') + setInputsOpen(false) + if (bad >= 0) setPicked(bad) + } } catch (e) { setError(e instanceof Error ? e.message : String(e)) } finally { @@ -200,14 +245,36 @@ export function SequencePanel({ } } + // the Run row sticks to the top of a narrow screen: what scrolls to the top of the screen must clear it + const left = useRef(null) + const runRow = useRef(null) + useEffect(() => { + const row = runRow.current + const box = left.current + if (!row || !box || typeof ResizeObserver === 'undefined') return + const measure = () => box.style.setProperty('--seq-run-h', `${row.offsetHeight}px`) + measure() + const watch = new ResizeObserver(measure) + watch.observe(row) + return () => watch.disconnect() + }, []) + const overall = result?.status + const hasForm = Object.keys(specs).length > 0 + // the form is drawn in one place: under its stop on a narrow screen, in the right pane on a wide one + const form = ( +
+ +
+ ) + const formInRight = !narrow && hasForm && (inputsOpen || !current) + const inputsError = inputsFailed ? bad0?.error : undefined return (
-
+
- -
+
@@ -248,12 +315,36 @@ export function SequencePanel({
{error &&

{error}

}
    + {hasForm && ( +
  1. + + {inputsError &&
    {inputsError}
    } + {narrow && inputsOpen &&
    {form}
    } +
  2. + )} {rows.map((row, i) => { const step = row.step const status = step?.status ?? live[row.name] ?? 'pending' const failed = step?.assertions.filter((a) => !a.pass) ?? [] return ( -
  3. +
  4. {ICON[status as keyof typeof ICON] || i + 1}
-
- {current && ( +
+ {formInRight &&
{form}
} + {!formInRight && current && ( )} - {!current && ( + {!formInRight && !current && (
Nothing run yet Press Run, then pick a step to see its request and response.
)} - {current && ( + {!formInRight && current && ( .label { - font-weight: 600; - font-size: 12px; - } - .nested { - border-left: 2px solid var(--sb-border); - padding-left: var(--sb-space-3); - } .method { font: 700 11px var(--sb-font-mono); padding: 1px 6px; diff --git a/packages/ui/src/styles/panel.css b/packages/ui/src/styles/panel.css index f269670..664de5c 100644 --- a/packages/ui/src/styles/panel.css +++ b/packages/ui/src/styles/panel.css @@ -1760,6 +1760,45 @@ overflow: auto; } } + .seq-inputs { + padding: var(--sb-space-4); + overflow: auto; + } + .seq-form { + min-width: 0; + margin: 0; + padding: 0; + border: 0; + } + /* one column: the form is under its stop, the right pane has nothing to say before a step is picked, and the Run row + stays in reach while a long form scrolls (what a step tap or a focused field scrolls to clears it) */ + @media (max-width: 900px) { + .seq-right.empty { + display: none; + } + /* no padding above the scroller's content: the pinned row sits flush with the top, and nothing scrolls through a gap + above it. The space the padding gave is a spacer that scrolls away, so the layout at rest is unchanged. (A margin on + the row would not do: a pinned element's margin is part of what is pinned.) */ + .sequence-panel .seq-left { + padding-top: 0; + scroll-padding-top: var(--seq-run-h, 0px); + } + .seq-left::before { + content: ""; + display: block; + height: var(--sb-space-4); + } + .seq-left .seq-run { + position: sticky; + top: 0; + z-index: 3; + margin-inline: calc(-1 * var(--sb-space-4)); + margin-block-end: 0; + padding: var(--sb-space-2) var(--sb-space-4); + background: var(--sb-bg); + border-bottom: 1px solid var(--sb-border); + } + } .seq-left { min-height: 0; overflow: auto; @@ -1849,6 +1888,133 @@ min-height: 44px; } } + /* groups and lists: a table whose rows are the groups, cards when the form is not wide enough for the columns */ + .group-block { + margin-bottom: var(--sb-space-3); + } + .controls-grid > table { + margin-bottom: var(--sb-space-3); + } + .group-head { + display: flex; + align-items: center; + gap: var(--sb-space-3); + margin: var(--sb-space-2) 0; + } + .group-caption { + font-weight: 600; + } + .group-count { + display: inline-flex; + align-items: center; + gap: 6px; + } + .group-count .cell { + width: 72px; + border: 1px solid var(--sb-border); + border-radius: var(--sb-radius-control); + } + .group-table { + table-layout: auto; + } + .group-table th.g-row { + width: 9rem; + text-transform: none; + letter-spacing: 0; + font-size: 12.5px; + white-space: nowrap; + } + .group-table tbody th.g-row { + color: var(--sb-text); + border-bottom: 1px solid var(--sb-border); + } + .group-table tbody tr:last-child th.g-row { + border-bottom: 0; + } + .group-table td.g-val { + border-left: 1px solid var(--sb-border); + } + .group-table .g-label { + display: none; + } + .group-table .g-heading { + margin-right: 6px; + } + .group-table .g-actions { + display: inline-flex; + align-items: center; + gap: 2px; + float: right; + } + .group-table .gen { + width: 24px; + height: 24px; + margin-right: 0; + } + .gen:disabled { + opacity: 0.4; + cursor: not-allowed; + } + @container (max-width: 720px) { + .grid .group-table, + .group-table tbody { + display: block; + border: 0; + border-radius: 0; + } + .group-table thead { + display: none; + } + .group-table tr { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); + margin-bottom: var(--sb-space-2); + background: var(--sb-surface); + border: 1px solid var(--sb-border); + border-radius: var(--sb-radius-control); + overflow: hidden; + } + .group-table tbody th.g-row { + display: flex; + align-items: center; + justify-content: space-between; + grid-column: 1 / -1; + width: auto; + } + .group-table .g-actions { + float: none; + } + .group-table td.g-val { + display: block; + height: auto; + min-width: 0; + padding: 4px 8px 8px; + border: 0; + } + .group-table .g-label { + display: block; + padding-bottom: 2px; + font-size: 11px; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--sb-text-muted); + } + .group-table .cell { + height: 34px; + border: 1px solid var(--sb-border); + border-radius: var(--sb-radius-control); + } + .group-table .gen { + width: 34px; + height: 34px; + } + } + @media (pointer: coarse) { + .group-table .gen { + width: 44px; + height: 44px; + } + } .multi-cell { display: flex; flex-wrap: wrap; @@ -1881,20 +2047,6 @@ height: 100%; min-height: 0; } - .seq-left .controls { - padding: var(--sb-space-3) var(--sb-space-4); - margin-bottom: var(--sb-space-3); - background: var(--sb-surface); - border: 1px solid var(--sb-border); - border-radius: var(--sb-radius-card); - } - .seq-left .controls h3 { - margin: 0 0 var(--sb-space-2); - font-size: 11px; - text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--sb-text-muted); - } .seq-run { display: flex; align-items: center; diff --git a/packages/ui/test/browser/app.test.tsx b/packages/ui/test/browser/app.test.tsx index 7d5d86c..a7869c4 100644 --- a/packages/ui/test/browser/app.test.tsx +++ b/packages/ui/test/browser/app.test.tsx @@ -80,7 +80,7 @@ describe('docs and play panel', () => { $(`.flows-title:has(.method.${kind})`) as HTMLButtonElement // the list keeps its scrollbar's space whether or not it has one, so folding does not make it jump expect(getComputedStyle($('.list-col') as Element).scrollbarGutter).toContain('stable') - expect(root.querySelectorAll('.flow-row').length).toBe(5) + expect(root.querySelectorAll('.flow-row').length).toBe(6) expect(title('flow').getAttribute('aria-expanded')).toBe('true') title('flow').click() await waitFor(() => expect(root.querySelectorAll('.flow-row').length).toBe(0)) @@ -94,12 +94,12 @@ describe('docs and play panel', () => { await waitFor(() => expect(root.querySelectorAll('.req-row').length).toBe(requests)) } title('flow').click() - await waitFor(() => expect(root.querySelectorAll('.flow-row').length).toBe(5)) + await waitFor(() => expect(root.querySelectorAll('.flow-row').length).toBe(6)) }) it('is a list of APIs and flows, and ⌘K jumps straight into the panel', async () => { await mount() - expect(root.querySelectorAll('.flow-row').length).toBe(5) + expect(root.querySelectorAll('.flow-row').length).toBe(6) // flows are one section with a single FLOW badge; ungrouped ones are under Default (no sub-heading) expect($('.flows .flows-title .method.flow')?.textContent).toBe('FLOW') expect(root.querySelectorAll('.flows .method.flow').length).toBe(1) diff --git a/packages/ui/test/browser/embed.test.ts b/packages/ui/test/browser/embed.test.ts index fe6b9bc..b512ee3 100644 --- a/packages/ui/test/browser/embed.test.ts +++ b/packages/ui/test/browser/embed.test.ts @@ -380,4 +380,26 @@ describe('embed', () => { await page.viewport(w, h) } }) + + it('shows a flow its inputs in the right pane of the dialog on a desktop, within the dialog', async () => { + const [w, h] = [window.innerWidth, window.innerHeight] + await page.viewport(1280, 800) + try { + await openFlow( + '

Checkout

', + ) + await settled() + await vi.waitFor(() => expect(q('.seq-right .seq-inputs .controls-grid')).not.toBeNull()) + expect(q('.seq-left .controls-grid')).toBeNull() + const pane = (q('.seq-right') as HTMLElement).getBoundingClientRect() + const panel = (q('.panel') as HTMLElement).getBoundingClientRect() + expect(pane.right).toBeLessThanOrEqual(panel.right) + const grid = q('.seq-inputs') as HTMLElement + expect(grid.scrollWidth).toBeLessThanOrEqual(grid.clientWidth) + // the description column has room here, which the rail never had + expect(getComputedStyle(q('.controls-grid .g-doc') as HTMLElement).display).not.toBe('none') + } finally { + await page.viewport(w, h) + } + }) }) diff --git a/packages/ui/test/browser/inputs.test.tsx b/packages/ui/test/browser/inputs.test.tsx new file mode 100644 index 0000000..eabd1dd --- /dev/null +++ b/packages/ui/test/browser/inputs.test.tsx @@ -0,0 +1,259 @@ +import { c, defineOperation, sequence } from '@specbook/core' +import { faker } from '@specbook/core/faker' +import { render } from 'preact' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { page } from 'vitest/browser' +import { SequencePanel } from '../../src/panel/SequencePanel' +import { env, locale, seed } from '../../src/store' +import 'prism-code-editor/layout.css' +import '../../src/styles/tokens.css' +import '../../src/styles/app.css' +import '../../src/styles/panel.css' + +const GetOrderById = defineOperation<{ + params: { path: { orderId: number } } + body: never + responses: { 200: { id: number } } +}>({ service: 'petstore', id: 'GetOrderById', method: 'GET', path: '/store/order/{orderId}' }) +const look = GetOrderById.request({ path: { orderId: 5 } }) + +const traveler = (label?: string) => + c.object( + { + name: c.text({ default: () => faker.person.fullName() }), + gender: c.select(['F', 'M', 'X'] as const), + dob: c.date({ default: '1990-01-01' }), + }, + { label }, + ) + +const groups = sequence({ + id: 'groups', + title: 'Two travelers', + inputs: { + currency: c.select(['usd', 'eur'] as const), + traveler1: traveler('Traveler 1'), + traveler2: traveler('Traveler 2'), + }, +}).step('Look it up', look) + +const list = sequence({ + id: 'list', + title: 'Travelers', + inputs: { travelers: c.array(traveler(), { min: 1, max: 4, label: 'Travelers' }) }, +}).step('Look it up', look) + +describe('the Inputs stop and the forms of groups and lists', () => { + let root: HTMLElement + beforeEach(() => { + root = document.createElement('div') + root.style.cssText = 'width:100%;height:700px' + document.body.append(root) + env.value = 'mock' + }) + afterEach(() => { + render(null, root) + document.body.innerHTML = '' + env.value = 'mock' + locale.value = undefined + seed.value = undefined + }) + const $ = (sel: string) => root.querySelector(sel) as T | null + const $$ = (sel: string) => [...root.querySelectorAll(sel)] + const field = (name: string) => $(`input[aria-label="${name}"]`) + const button = (text: string) => + $$('button').find((b) => b.textContent?.includes(text)) as HTMLButtonElement + const type = (el: HTMLInputElement, v: string, event = 'input') => { + el.value = v + el.dispatchEvent(new Event(event, { bubbles: true })) + } + // a person's next action comes after the form has drawn what was typed + const tick = () => new Promise((r) => setTimeout(r, 50)) + const ready = () => + vi.waitFor( + () => + expect(field('traveler1.name')?.value || field('travelers[0].name')?.value).toBeTruthy(), + { + timeout: 20_000, + }, + ) + const show = ( + seq: Parameters[0]['info']['seq'], + file: string, + preset?: Record, + ) => render(, root) + const viewport = async (w: number, h: number, body: () => Promise) => { + const [ow, oh] = [window.innerWidth, window.innerHeight] + await page.viewport(w, h) + try { + await body() + } finally { + await page.viewport(ow, oh) + } + } + + it('on a wide screen the form is the right pane until a step is picked, and comes back with what was typed', async () => { + await viewport(1280, 800, async () => { + show(groups, 'groups-wide.seq.ts') + await ready() + expect($('.seq-right .seq-inputs .controls-grid')).not.toBeNull() + expect($('.seq-left .controls-grid')).toBeNull() + expect($('.jin-head')?.getAttribute('aria-current')).toBe('step') + type(field('traveler1.name') as HTMLInputElement, 'Ada Lovelace') + // the stop says what the run starts from + await vi.waitFor(() => expect($('.jin-sum')?.textContent).toContain('currency')) + + button('▶ Run').click() + await vi.waitFor(() => expect($('.step-exchange')).not.toBeNull(), { timeout: 20_000 }) + expect($('.seq-inputs')).toBeNull() + expect($('.jin-head')?.getAttribute('aria-current')).toBeNull() + + $('.jin-head')?.click() + await vi.waitFor(() => expect($('.seq-right .seq-inputs')).not.toBeNull()) + expect(field('traveler1.name')?.value).toBe('Ada Lovelace') + }) + }) + + it('draws neighbouring groups of the same fields as one table, a row each, and regenerates only what is generated', async () => { + await viewport(1280, 800, async () => { + show(groups, 'groups-table.seq.ts') + await ready() + expect($$('.group-table')).toHaveLength(1) + expect($$('.group-table tbody tr')).toHaveLength(2) + expect($$('.group-table tbody th .g-heading').map((h) => h.textContent)).toEqual([ + 'Traveler 1', + 'Traveler 2', + ]) + expect($$('.group-table thead th').map((h) => h.textContent)).toEqual([ + '', + 'name', + 'gender', + 'dob', + ]) + // one die for the row, none inside it: what QA does not like they type over + expect($$('.group-table .cell-gen')).toHaveLength(0) + expect( + $$('.group-table button[aria-label^="Generate"]').map((b) => b.getAttribute('aria-label')), + ).toEqual(['Generate traveler1', 'Generate traveler2']) + const before = field('traveler1.name')?.value + type(field('traveler1.dob') as HTMLInputElement, '2000-02-02') + await tick() + ;($('button[aria-label="Generate traveler1"]') as HTMLButtonElement).click() + await vi.waitFor(() => expect(field('traveler1.name')?.value).not.toBe(before)) + expect(field('traveler1.dob')?.value).toBe('2000-02-02') + }) + }) + + it('a list has a count, clamped to its limits, and gives back the rows it trimmed', async () => { + await viewport(1280, 800, async () => { + show(list, 'list.seq.ts') + await ready() + const count = () => field('travelers count') as HTMLInputElement + expect($$('.group-table tbody tr')).toHaveLength(1) + expect(($('button[aria-label="Remove travelers[0]"]') as HTMLButtonElement).disabled).toBe( + true, + ) + + type(count(), '3', 'change') + await vi.waitFor(() => expect($$('.group-table tbody tr')).toHaveLength(3)) + // new rows start from generated values + expect(field('travelers[2].name')?.value).toBeTruthy() + type(count(), '10', 'change') + await vi.waitFor(() => expect($$('.group-table tbody tr')).toHaveLength(4)) + expect(count().value).toBe('4') + + type(field('travelers[3].name') as HTMLInputElement, 'Kept Name') + await tick() + type(count(), '2', 'change') + await vi.waitFor(() => expect($$('.group-table tbody tr')).toHaveLength(2)) + type(count(), '4', 'change') + await vi.waitFor(() => expect($$('.group-table tbody tr')).toHaveLength(4)) + expect(field('travelers[3].name')?.value).toBe('Kept Name') + + ;($('button[aria-label="Remove travelers[1]"]') as HTMLButtonElement).click() + await vi.waitFor(() => expect($$('.group-table tbody tr')).toHaveLength(3)) + expect(field('travelers[2].name')?.value).toBe('Kept Name') + }) + }) + + it('Run with defaults works on a list that has a minimum and nothing given', async () => { + await viewport(1280, 800, async () => { + show(list, 'list-defaults.seq.ts') + await ready() + button('Run with defaults').click() + await vi.waitFor(() => expect($('.badge.pass')).not.toBeNull(), { timeout: 20_000 }) + }) + }) + + it('a preset of one field of a group leaves the rest of the group at its defaults', async () => { + await viewport(1280, 800, async () => { + show(groups, 'groups-preset.seq.ts', { traveler2: { name: 'Preset Person' } }) + await vi.waitFor(() => expect(field('traveler2.name')?.value).toBe('Preset Person'), { + timeout: 20_000, + }) + expect(field('traveler2.dob')?.value).toBe('1990-01-01') + expect(field('traveler1.name')?.value).toBeTruthy() + }) + }) + + it('on a phone the form unfolds under its stop as cards, folds away for a run, and keeps Run in reach', async () => { + await viewport(390, 844, async () => { + show(list, 'list-phone.seq.ts') + await ready() + expect($('.jin-form .controls-grid')).not.toBeNull() + expect(getComputedStyle($('.seq-right') as HTMLElement).display).toBe('none') + expect($('.jin-head')?.getAttribute('aria-expanded')).toBe('true') + // each group is a card: a label over each control, no header row + expect(getComputedStyle($('.group-table thead') as HTMLElement).display).toBe('none') + expect(getComputedStyle($('.group-table .g-label') as HTMLElement).display).toBe('block') + type($('input[aria-label="travelers count"]') as HTMLInputElement, '4', 'change') + await vi.waitFor(() => expect($$('.group-table tbody tr')).toHaveLength(4)) + expect(document.documentElement.scrollWidth).toBeLessThanOrEqual(window.innerWidth) + for (const el of $$('.group-table button, .group-table input')) { + const r = el.getBoundingClientRect() + expect(r.right, el.getAttribute('aria-label') ?? '').toBeLessThanOrEqual(window.innerWidth) + } + + // scrolled to the bottom of a long form, Run is still on screen + const left = $('.seq-left') as HTMLElement + left.scrollTop = left.scrollHeight + await new Promise((r) => requestAnimationFrame(() => r(null))) + // pinned flush with the top of what scrolls: nothing shows through a gap above it + const row = ($('.seq-left .seq-run') as HTMLElement).getBoundingClientRect() + expect(Math.abs(row.top - left.getBoundingClientRect().top)).toBeLessThan(1) + const run = button('▶ Run').getBoundingClientRect() + expect(run.top).toBeGreaterThanOrEqual(0) + expect(run.bottom).toBeLessThanOrEqual(window.innerHeight) + + button('▶ Run').click() + await vi.waitFor(() => expect($('.jstep.pass')).not.toBeNull(), { timeout: 20_000 }) + expect($('.jin-form')).toBeNull() + $('.jin-head')?.click() + await vi.waitFor(() => expect($('.jin-form .controls-grid')).not.toBeNull()) + }) + }) + + it('keeps what was typed while the panel is away, as on the Docs tab', async () => { + await viewport(1280, 800, async () => { + show(groups, 'groups-away.seq.ts') + await ready() + type(field('traveler2.name') as HTMLInputElement, 'Still Here') + await tick() + render(null, root) + show(groups, 'groups-away.seq.ts') + await vi.waitFor(() => expect(field('traveler2.name')?.value).toBe('Still Here')) + }) + }) + + it('inputs that cannot be used are said once, under the stop, and the timeline stays as planned', async () => { + await viewport(1280, 800, async () => { + show(groups, 'groups-bad.seq.ts', { currency: 'zzz' }) + await ready() + button('▶ Run').click() + await vi.waitFor(() => expect($('.jin .error-text')).not.toBeNull(), { timeout: 20_000 }) + expect($('.jin .error-text')?.textContent).toContain('currency') + expect($$('.jstep')).toHaveLength(1) + expect($('.seq-right .seq-inputs')).not.toBeNull() + }) + }) +}) diff --git a/packages/ui/test/embed-static/embed-static.test.ts b/packages/ui/test/embed-static/embed-static.test.ts index 5b419ed..7111f59 100644 --- a/packages/ui/test/embed-static/embed-static.test.ts +++ b/packages/ui/test/embed-static/embed-static.test.ts @@ -334,7 +334,7 @@ describe('the embed on a page with a strict policy', () => { } }) - it('does not shift a page that has a scrollbar when the panel opens or closes', async () => { + it('does not shift a page that has a scrollbar when the panel opens or closes', async (ctx) => { // Playwright hides scrollbars by default, and a page with none cannot shift const classic = await chromium.launch({ ignoreDefaultArgs: ['--hide-scrollbars'] }) try { @@ -344,7 +344,8 @@ describe('the embed on a page with a strict policy', () => { const edge = () => page.evaluate(() => document.getElementById('centred')?.getBoundingClientRect().left) const bar = await page.evaluate(() => innerWidth - document.documentElement.clientWidth) - expect(bar, 'this browser draws a scrollbar').toBeGreaterThan(0) + // a machine whose scrollbars float over the page (macOS without a mouse) has nothing to shift + if (bar === 0) ctx.skip('this browser draws scrollbars that take no room') const before = await edge() await page.locator('specbook-play').first().locator('button').click() await page.locator('specbook-panel .panel').waitFor() diff --git a/packages/ui/test/inputs.test.ts b/packages/ui/test/inputs.test.ts new file mode 100644 index 0000000..7bcb19d --- /dev/null +++ b/packages/ui/test/inputs.test.ts @@ -0,0 +1,134 @@ +import { c } from '@specbook/core' +import { describe, expect, it } from 'vitest' +import { + anyGenerated, + defaultFor, + generatedCount, + regenerate, + specFromControl, + startValues, + summarize, + withDefaults, +} from '../src/components/Fields' +import { blocksOf } from '../src/panel/ControlsGrid' + +let n = 0 +const person = c.object({ + name: c.text({ default: () => `P${++n}` }), + gender: c.select(['F', 'M', 'X'] as const, { default: 'M' }), + note: c.text({ default: 'hi' }), +}) +const people = c.array(person, { min: 2, max: 4, label: 'Travelers' }) + +describe('input values of groups and lists', () => { + it('a select starts where the CLI starts, not always at its first option', () => { + expect(defaultFor(specFromControl(c.select(['a', 'b'] as const, { default: 'b' })))).toBe('b') + expect(defaultFor(specFromControl(c.select(['a', 'b'] as const, { default: 1 })))).toBe('b') + }) + + it('a list starts at its minimum, each item from its own defaults', () => { + const v = defaultFor(specFromControl(people)) as { name: string; gender: string }[] + expect(v).toHaveLength(2) + expect(v[0]?.gender).toBe('M') + expect(v[0]?.name).not.toBe(v[1]?.name) + }) + + it('a list can start from a function: two items, each filled from its own defaults', () => { + const t = c.array(person, { min: 1, default: () => [{ gender: 'F' }, {}] }) + const v = defaultFor(specFromControl(t)) as { name: string; gender: string }[] + expect(v).toHaveLength(2) + expect(v.map((p) => p.gender)).toEqual(['F', 'M']) + expect(v[0]?.name).not.toBe(v[1]?.name) + }) + + it('a preset of one field of a group leaves the others at their defaults, and extra keys are kept', () => { + const specs = { who: specFromControl(person), extra: specFromControl(c.text()) } + const v = startValues(specs, { who: { name: 'Ada' }, unknown: 1 }) as { + who: { name: string; gender: string; note: string } + unknown: number + } + expect(v.who).toEqual({ name: 'Ada', gender: 'M', note: 'hi' }) + expect(v.unknown).toBe(1) + }) + + it('a preset list is filled per item and padded to the minimum', () => { + const spec = specFromControl(people) + const v = withDefaults(spec, [{ name: 'Ada' }]) as { name: string; gender: string }[] + expect(v).toHaveLength(2) + expect(v[0]).toMatchObject({ name: 'Ada', gender: 'M' }) + }) + + it('finds generated fields inside groups and lists, and regenerates only those', () => { + const spec = specFromControl(people) + expect(anyGenerated(spec)).toBe(true) + expect(anyGenerated(specFromControl(c.object({ a: c.text() })))).toBe(false) + const v = [ + { name: 'x', gender: 'F', note: 'typed' }, + { name: 'y', gender: 'X', note: 'typed' }, + ] + expect(generatedCount(spec, v)).toBe(2) + const out = regenerate(spec, v) as typeof v + expect(out.map((p) => p.gender)).toEqual(['F', 'X']) + expect(out.map((p) => p.note)).toEqual(['typed', 'typed']) + expect(out[0]?.name).not.toBe('x') + }) + + it('summarizes the inputs in a line', () => { + const specs = { + currency: specFromControl(c.select(['usd'] as const)), + people: specFromControl(people), + a: specFromControl(c.text()), + b: specFromControl(c.text()), + } + expect(summarize(specs, { currency: 'usd', people: [1, 2], a: 'x', b: 'y' })).toBe( + 'currency usd · Travelers 2 · a x +1', + ) + }) +}) + +describe('how inputs are laid out', () => { + const who = (label: string) => + specFromControl(c.object({ name: c.text(), gender: c.select(['F', 'M'] as const) }, { label })) + const text = () => specFromControl(c.text()) + + it('plain inputs are the rows of one table, groups of the same fields are the rows of another', () => { + const blocks = blocksOf({ a: text(), b: text(), t1: who('One'), t2: who('Two'), c: text() }) + expect(blocks.map((b) => [b.kind, 'names' in b ? b.names : b.name])).toEqual([ + ['fields', ['a', 'b']], + ['objects', ['t1', 't2']], + ['fields', ['c']], + ]) + }) + + it('an input between two groups, or other fields, makes them separate tables', () => { + expect(blocksOf({ t1: who('1'), x: text(), t2: who('2') }).map((b) => b.kind)).toEqual([ + 'objects', + 'fields', + 'objects', + ]) + const other = specFromControl(c.object({ name: c.text(), age: c.number() })) + expect(blocksOf({ t1: who('1'), t2: other }).map((b) => b.kind)).toEqual(['objects', 'objects']) + }) + + it('a lone group is a table of one row, with a column for each field', () => { + const [b] = blocksOf({ t1: who('One') }) + expect(b?.kind).toBe('objects') + expect(b && 'columns' in b ? b.columns.map((col) => col.label) : []).toEqual(['name', 'gender']) + }) + + it('a list is a table of its own; of plain values it is one column', () => { + const people = specFromControl(c.array(c.object({ name: c.text() }))) + const tags = specFromControl(c.array(c.text(), { label: 'Tags' })) + const blocks = blocksOf({ people, tags }) + expect(blocks.map((b) => b.kind)).toEqual(['list', 'list']) + expect( + blocks[1] && 'columns' in blocks[1] ? blocks[1].columns.map((x) => x.label) : [], + ).toEqual(['Value']) + }) + + it('a group with no fields is an ordinary row', () => { + expect(blocksOf({ empty: specFromControl(c.object({})) }).map((b) => b.kind)).toEqual([ + 'fields', + ]) + }) +})