import dedent from 'dedent' import { compact } from 'es-toolkit/array' import { es } from '@open-pencil/emit' import type { ComponentModel, ComponentNode, GeneratedComponent, GeneratedKind } from '../components/model' import { stylesheets } from './module' import { claimName, identifierName, VARIANT_TAG } from './names' /** Tells readers the file is generated; nothing parses it. */ const HEADER = '// Generated by OpenPencil. Re-export to update; edits are overwritten.' const MODULE = es.parseModule(dedent` import type { Meta, StoryObj } from '$storybook' import { expect } from 'storybook/test' const meta = { title: $title, tags: $tags, component: $Component, parameters: $parameters, args: $args, argTypes: $argTypes } satisfies Meta export default meta type Story = StoryObj `) const IMPORT_DEFAULT = es.parseModule(`import $Component from '$path'`) const IMPORT_NAMED = es.parseModule(`import { $Component } from '$path'`) const STORY = es.parseModule(`export const $name: Story = $story`) /** * What clicking a control does, as Reka marks it: the role to find it by, the element that * changes, and the `data-state` it ends in. */ const INTERACTIONS: Partial> = { switch: { role: 'switch', state: 'checked' }, checkbox: { role: 'checkbox', state: 'checked' }, toggle: { role: 'button', state: 'on' }, collapsible: { role: 'button', state: 'open' } } const PLAY = es.parseExpression(dedent` async ({ canvas, userEvent }) => { const control = canvas.getByRole($role) await userEvent.click(control) await expect(control).toHaveAttribute('data-state', $state) } `) /** A slider's Home key moves it to its minimum, as Reka and Radix both handle it. */ const SLIDER_PLAY = es.parseExpression(dedent` async ({ canvas, userEvent }) => { const thumb = canvas.getByRole('slider') thumb.focus() await userEvent.keyboard('{Home}') await expect(thumb).toHaveAttribute('aria-valuenow', $min) } `) /** * A stepper steps a number field. Both Reka's and the native field's steppers are named by * what they do, where a key would only step Reka's input, not a native number input. */ const NUMBER_PLAY = es.parseExpression(dedent` async ({ canvas, userEvent }) => { await userEvent.click(canvas.getByRole('button', { name: $stepper })) await expect(canvas.getByRole('spinbutton')).toHaveDisplayValue($value) } `) /** Whether the component draws a part, such as a number field's increment. */ function drawsPart(node: ComponentNode, part: string): boolean { return ( node.type === 'element' && (node.part === part || node.children.some((child) => drawsPart(child, part))) ) } /** Typing replaces a text field's words. */ const TEXT_PLAY = es.parseExpression(dedent` async ({ canvas, userEvent }) => { const field = canvas.getByRole('textbox') await userEvent.clear(field) await userEvent.type(field, 'Hello') await expect(field).toHaveValue('Hello') } `) /** The play function that operates a generated component, if it has one. */ function playOf(component: ComponentModel): es.SyntaxNode | undefined { const interaction = INTERACTIONS[component.kind] if (interaction) return es.fill(PLAY, { $role: es.string(interaction.role), $state: es.string(interaction.state) }) const { range } = component if (component.kind === 'slider' && range) return es.fill(SLIDER_PLAY, { $min: es.string(String(range.min)) }) if (component.kind === 'numberField' && range) { const up = range.default + range.step <= range.max const part = up ? 'increment' : 'decrement' if (!drawsPart(component.tree, part)) return undefined return es.fill(NUMBER_PLAY, { $stepper: es.string(up ? 'Increase' : 'Decrease'), $value: es.string(String(up ? range.default + range.step : range.default - range.step)) }) } if (component.kind === 'textField' || component.kind === 'textarea') return TEXT_PLAY return undefined } export interface ComponentStoriesData { /** The Storybook renderer package the stories import their types from. */ storybook: string title: string /** Tags on the whole file, which its stories inherit. */ tags: string[] /** Stylesheets the file imports, such as the fonts its text uses. */ styles: string[] /** Only the Default story, as a plan can ask for. */ single?: boolean component: ComponentModel generated: Pick /** Design links for the whole file, as `parameters.design` entries. */ design: { name: string; type: string; url: string }[] } const FALSE = es.parseExpression('false') const TRUE = es.parseExpression('true') /** A number model's value as its prop takes it: on its own, or in a list for a slider. */ const numberArg = (value: number, list: boolean) => list ? es.array([es.number(value)]) : es.number(value) /** * A model's value at rest: off, the option a choice starts on, none for an open choice, the * number a range starts at, or the words a field starts with. */ function restValue(component: ComponentModel, list: boolean): es.SyntaxNode | null { if (component.range) return numberArg(component.range.default, list) if (component.text) return es.string(component.text.default) if (!component.choice) return FALSE return component.choice.default === null ? null : es.string(component.choice.default) } function restArgs( component: ComponentModel, model: string | null, list: boolean ): [string, es.SyntaxNode][] { const rest = restValue(component, list) return [ ...(model && rest ? [[model, rest] as [string, es.SyntaxNode]] : []), ...(component.disabled ? [['disabled', FALSE] as [string, es.SyntaxNode]] : []), ...(component.invalid ? [['invalid', FALSE] as [string, es.SyntaxNode]] : []), ...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, es.string(prop.default)]), ...component.texts.map((text): [string, es.SyntaxNode] => [text.name, es.string(text.default)]), ...component.booleans.map((prop): [string, es.SyntaxNode] => [ prop.name, prop.default ? TRUE : FALSE ]) ] } /** The control a model's value gets: a choice's options, a range, text, or a boolean. */ function modelControl(component: ComponentModel, list: boolean): es.SyntaxNode { const control = (type: string) => es.object([['control', es.string(type)]]) const { choice, range } = component if (choice) return es.object([ ['control', es.string('select')], ['options', es.array(choice.options.map(es.string))] ]) // A slider's list of values is edited as one, not as a range. if (range && list) return control('object') if (range) return es.object([ [ 'control', es.object([ ['type', es.string('range')], ['min', es.number(range.min)], ['max', es.number(range.max)], ['step', es.number(range.step)] ]) ] ]) return control(component.text ? 'text' : 'boolean') } function argTypes(component: ComponentModel, model: string | null, list: boolean): es.SyntaxNode { const boolean = es.object([['control', es.string('boolean')]]) const select = (options: readonly string[]) => es.object([ ['control', es.string('select')], ['options', es.array(options.map(es.string))] ]) return es.object([ ...(model ? [[model, modelControl(component, list)] as [string, es.SyntaxNode]] : []), ...(component.disabled ? [['disabled', boolean] as [string, es.SyntaxNode]] : []), ...(component.invalid ? [['invalid', boolean] as [string, es.SyntaxNode]] : []), ...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, select(prop.options)]), ...component.texts.map((text): [string, es.SyntaxNode] => [ text.name, es.object([['control', es.string('text')]]) ]), ...component.booleans.map((prop): [string, es.SyntaxNode] => [prop.name, boolean]) ]) } /** A story per state worth seeing: at rest, each boolean on, each flag, and each prop value. */ function stories( component: ComponentModel, model: string | null, list: boolean ): { name: string; story: es.SyntaxNode }[] { // Stories are named apart from the component the file imports and the module's own names. const taken = new Set([component.name, 'meta', 'Story']) let first = true const story = (label: string, args: [string, es.SyntaxNode][], play?: es.SyntaxNode) => { // Every story after the first, Default, is another state, tagged so Storybook can hide it. const variant = !first first = false return { name: claimName(identifierName(label, 'Story'), taken), story: es.object([ ...(variant ? [['tags', es.array([es.string(VARIANT_TAG)])] as [string, es.SyntaxNode]] : []), ...(args.length > 0 ? [['args', es.object(args)] as [string, es.SyntaxNode]] : []), ...(play ? [['play', play] as [string, es.SyntaxNode]] : []) ]) } } const { range } = component const boolean = !component.choice && !range && !component.text return [ story('Default', [], playOf(component)), ...(component.model && model && boolean ? [story(component.model, [[model, TRUE]])] : []), // A range gets a story at each end it does not start at. ...(range && model ? ( [ ['Minimum', range.min], ['Maximum', range.max] ] as const ) .filter(([, value]) => value !== range.default) .map(([label, value]) => story(label, [[model, numberArg(value, list)]])) : []), // A choice gets a story per option it does not start on, such as each other tab. ...(component.choice && model ? component.choice.options .filter((option) => option !== component.choice?.default) .map((option) => story(option, [[model, es.string(option)]])) : []), ...(component.disabled ? [story('Disabled', [['disabled', TRUE]])] : []), ...(component.invalid ? [story('Invalid', [['invalid', TRUE]])] : []), ...component.props.flatMap((prop) => prop.options .filter((option) => option !== prop.default) .map((option) => story(option, [[prop.name, es.string(option)]])) ), // A boolean gets a story drawn the other way, such as an icon shown that is hidden at rest. ...component.booleans.map((prop) => story(`${prop.property} ${prop.default ? 'off' : 'on'}`, [ [prop.name, prop.default ? FALSE : TRUE] ]) ) ] } /** CSF3 stories for a generated component, with a play function that operates it. */ export function printComponentStories(data: ComponentStoriesData): string { const { component } = data const parameters = data.design.length > 0 ? es.object([ [ 'design', es.array( data.design.map((entry) => es.object([ ['name', es.string(entry.name)], ['type', es.string(entry.type)], ['url', es.string(entry.url)] ]) ) ) ] ]) : es.OMIT const { entry, valueArg: model } = data.generated const list = data.generated.valueList ?? false const body = es.fill(MODULE, { $storybook: es.string(data.storybook), $Component: es.identifier(component.name), $title: es.string(data.title), $tags: es.array(data.tags.map(es.string)), $parameters: parameters, $args: es.object(restArgs(component, model, list)), $argTypes: argTypes(component, model, list) }).body const componentImport = es.fill(entry.named ? IMPORT_NAMED : IMPORT_DEFAULT, { $Component: es.identifier(component.name), $path: es.string(entry.path) }).body const all = stories(component, model, list) const exported = (data.single ? all.slice(0, 1) : all).flatMap( (item) => es.fill(STORY, { $name: es.identifier(item.name), $story: item.story }).body ) // Only a control with a play function uses `expect`. const [types, expectImport, ...rest] = body const imports = playOf(component) ? [types, expectImport] : [types] const module = es.printModule({ type: 'Program', sourceType: 'module', body: compact([ ...imports, ...stylesheets(data.styles), ...componentImport, ...rest, ...exported ]) }) return `${HEADER}\n${module}\n` }