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=[…].
+
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(
-
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({