Skip to content

AI-native design editor. Open-source Figma alternative.

feat(storybook): generate a component for every component set (#1047)

Danila Poyarkovcfdb4e6e9d18
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7119b4cf8..c56a86528 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -97,7 +97,7 @@
- Import SVG markup with `figma.createNodeFromSvg(svg)` in the plugin API, as in Figma: it builds the same layers as pasting the SVG, on the current page at its origin.
- Detach an instance from its component with `detachInstance()` in the plugin API, as in Figma, from scripts run through `eval`.
- Run scripts written for Figma's dynamic-page mode that call `figma.getNodeByIdAsync()` or `getMainComponentAsync()`; both resolve to the same nodes as their synchronous forms.
-- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, titled by the document and, when several have components, its page, with a story and `select` controls per variant (a component with a behaviour gets boolean `checked`, `pressed`, `open`, and `disabled` controls instead, and each interaction state stays a story; with `--framework vue` or `--framework react`, a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea becomes a Reka UI or Radix UI component whose variants are compiled into state styles and whose text properties are string props with a text control, tabs and groups choosing a value named after each tab's or item's label, sliders, progress bars, and number fields binding a number within their range, text fields and textareas binding their text as a native input or textarea with the design's placeholder and filled look (React's number field is a native number input with its steppers wired, since Radix has none), each tab's trigger drawn with the chosen tab's look while it is active, and groups writing an item component they use once per item with the words each item shows; inside it, an instance of another generated component uses that component, also where a state draws it in place of another layer, operable from the value the design draws, and an icon is an `@iconify/vue` or `@iconify/react` component; with stories whose play function operates it), a design image per variant, an `openpencil://` link that opens the variant in OpenPencil, and the document's fonts as files every story file loads, warning about families no web font provider has (`--fonts none` leaves them out); each file opens with a `Default` story and tags its other stories `variant` and itself with its page, so Storybook's tag filter can show one story per component or hide a page; a rules file (`openpencil.stories.json`, or `--rules`) leaves components out, keeps `Default` alone, lays a set out as a gallery, or renames titles, matched by page and component name. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).
+- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, titled by the document and, when several have components, its page, with a story and `select` controls per variant (a component with a behaviour gets boolean `checked`, `pressed`, `open`, and `disabled` controls instead, and each interaction state stays a story; with `--framework vue` or `--framework react`, every component set and component becomes a Vue or React component whose variants are compiled into state styles, its variant, text, boolean, and slot properties its props and slots, and one with the behaviour of a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea a Reka UI or Radix UI component and whose text properties are string props with a text control, tabs and groups choosing a value named after each tab's or item's label, sliders, progress bars, and number fields binding a number within their range, text fields and textareas binding their text as a native input or textarea with the design's placeholder and filled look (React's number field is a native number input with its steppers wired, since Radix has none), each tab's trigger drawn with the chosen tab's look while it is active, and groups writing an item component they use once per item with the words each item shows; inside it, an instance of another generated component that draws as its variant does uses that component, also where a state draws it in place of another layer, operable from the value the design draws, and an icon is an `@iconify/vue` or `@iconify/react` component; with stories whose play function operates it), a design image per variant, an `openpencil://` link that opens the variant in OpenPencil, and the document's fonts and design variables as files every story file loads, warning about families no web font provider has (`--fonts none` leaves them out); each file opens with a `Default` story and tags its other stories `variant` and itself with its page, so Storybook's tag filter can show one story per component or hide a page; a rules file (`openpencil.stories.json`, or `--rules`) leaves components out, keeps `Default` alone, lays a set out as a gallery, keeps static stories in place of a generated component, or renames titles, matched by page and component name. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).
- Export HTML and Tailwind JSX from the app's export options and through the IO registry, and export Tailwind JSX from the CLI with `-f tailwind-jsx` (`-f jsx --style tailwind` still works). HTML export of a single layer now includes the layer itself, as other formats do. Vector shapes, booleans, stars, and polygons export as inline SVG with their fills, gradients, strokes, and shadows, in HTML, Tailwind JSX, and Storybook stories.
- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.
- Let AI and MCP agents verify and replay their edits with diff tools: `diff_visual` returns a pixel diff of two rendered nodes with the changed region, and `diff_apply` applies a `diff_create` or `diff_show` patch, including moved, added, and removed children, only when every node still matches it. The built-in AI chat enables `diff_create`, `diff_jsx`, and `diff_visual` by default.
diff --git a/packages/cli/src/commands/export/storybook/fonts.ts b/packages/cli/src/commands/export/storybook/fonts.ts
index c67e7504f..8881ccceb 100644
--- a/packages/cli/src/commands/export/storybook/fonts.ts
+++ b/packages/cli/src/commands/export/storybook/fonts.ts
@@ -22,15 +22,18 @@ export const storyFonts: WebFontFaceResolver = async (fonts, assetBasePath) => {
}
/**
- * The folder a document's font files go in, named by its path relative to the output, such as
- * `fonts/kit-design` for `../kit/design.fig`, so documents exported into one folder, even ones
- * with the same name, never share one; a one-page export adds the page.
+ * The folder a document's shared files, its fonts and design tokens, go in, named by its own
+ * folder and file name, such as `openpencil/kit-design` for `../kit/design.fig`, so documents of
+ * the same name in different folders exported together keep theirs apart; a one-page export
+ * adds the page.
*/
-export function fontFolder(source: string, page: string | undefined): string {
- const name = [source.replace(/\.[^./]*$/, ''), page ?? '']
+export function documentFolder(source: string, page: string | undefined): string {
+ const parts = source.split('/').filter((part) => part !== '..' && part !== '.')
+ const file = (parts.pop() ?? '').replace(/\.[^.]*$/, '')
+ const name = [parts.at(-1) ?? '', file, page ?? '']
.join('-')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
- return `fonts/${name || 'document'}`
+ return `openpencil/${name || 'document'}`
}
diff --git a/packages/cli/src/commands/export/storybook/index.ts b/packages/cli/src/commands/export/storybook/index.ts
index f673a571e..4416199d6 100644
--- a/packages/cli/src/commands/export/storybook/index.ts
+++ b/packages/cli/src/commands/export/storybook/index.ts
@@ -25,7 +25,7 @@ import { applyExportFontPolicy } from '#cli/commands/export/font-policy'
import { ok, printError } from '#cli/format'
import { loadDocument, populateWholeDocument, requirePage } from '#cli/headless'
-import { fontFolder, storyFonts } from './fonts'
+import { documentFolder, storyFonts } from './fonts'
import { readManifest, writeManifest, type StoryManifest, type StoryOwner } from './manifest'
import { readStoryRules, storyPlan } from './rules'
@@ -165,7 +165,7 @@ async function writeStories(
pageId,
plan: rules ? storyPlan(rules) : undefined,
fonts: args.fonts === 'none' ? undefined : storyFonts,
- fontFolder: fontFolder(source, args.page),
+ folder: documentFolder(source, args.page),
// Titled by the document, so stories of documents exported together stay apart.
document: basename(file, extname(file)),
linkPath: linkPath(file),
diff --git a/packages/cli/src/commands/export/storybook/manifest.ts b/packages/cli/src/commands/export/storybook/manifest.ts
index 0f9dcbc80..dba85be8b 100644
--- a/packages/cli/src/commands/export/storybook/manifest.ts
+++ b/packages/cli/src/commands/export/storybook/manifest.ts
@@ -9,15 +9,22 @@ import * as v from 'valibot'
*/
export const MANIFEST_FILE = '.openpencil-stories.json'
+/** Files the export writes directly in the output folder: stories and generated components. */
+const OWN_FILE = /^[^/]+\.(stories\.ts|vue|tsx|module\.css)$/
+/** A variant's design image, in its story's `<Name>.design/` folder. */
+const DESIGN_IMAGE = /^[^/]+\.design\/[^/]+\.png$/
+/** A document's shared files in `openpencil/<document>/`: its fonts and design tokens. */
+const SHARED_FILE =
+ /^openpencil\/[^/]+\/(fonts\.css|tokens\.css|fonts\/[^/]+\.(woff2|woff|otf|ttf))$/
+
/**
- * A story file or a design image directly under the output folder. The manifest is read
- * from disk and may have been edited, so nothing it lists may point anywhere else.
+ * A file the export writes: a story, a generated component and its stylesheet, a design image,
+ * or a document's fonts and tokens. The manifest is read from disk and may have been edited, so
+ * nothing it lists may point anywhere else.
*/
export function isGeneratedPath(path: string): boolean {
if (isAbsolute(path) || posix.normalize(path) !== path || path.startsWith('..')) return false
- const folder = posix.dirname(path)
- if (folder === '.') return path.endsWith('.stories.ts')
- return posix.dirname(folder) === '.' && folder.endsWith('.design') && path.endsWith('.png')
+ return OWN_FILE.test(path) || DESIGN_IMAGE.test(path) || SHARED_FILE.test(path)
}
const StoryOwnerSchema = v.object({ source: v.string(), page: v.string() })
@@ -25,7 +32,7 @@ const StoryOwnerSchema = v.object({ source: v.string(), page: v.string() })
const ManifestSchema = v.object({
version: v.literal(1),
files: v.record(
- v.pipe(v.string(), v.check(isGeneratedPath, 'Expected a story or design image path.')),
+ v.pipe(v.string(), v.check(isGeneratedPath, 'Expected a path the Storybook export writes.')),
StoryOwnerSchema
)
})
diff --git a/packages/cli/src/commands/export/storybook/rules.ts b/packages/cli/src/commands/export/storybook/rules.ts
index 12665d24d..3a606d6d4 100644
--- a/packages/cli/src/commands/export/storybook/rules.ts
+++ b/packages/cli/src/commands/export/storybook/rules.ts
@@ -11,12 +11,13 @@ export const RULES_FILE = 'openpencil.stories.json'
/**
* A rule for the story files whose `<page>/<name>` path matches its glob: which stories they
- * have, and a title template with `{document}`, `{page}`, `{name}`, and `{path}`, the title
- * they would have.
+ * have, whether a Vue or React export generates their component, and a title template with
+ * `{document}`, `{page}`, `{name}`, and `{path}`, the title they would have.
*/
const StoryRule = v.object({
match: v.pipe(v.string(), v.minLength(1)),
stories: v.optional(v.picklist(STORY_MODES)),
+ generate: v.optional(v.boolean()),
title: v.optional(v.pipe(v.string(), v.minLength(1)))
})
@@ -65,6 +66,7 @@ export function storyPlan(rules: StoryRules): (target: StoryTarget) => StoryPlan
for (const rule of rules.rules) {
if (!matchesGlob(path, rule.match)) continue
if (rule.stories) plan.stories = rule.stories
+ if (rule.generate !== undefined) plan.generate = rule.generate
if (rule.title) plan.title = fillTitle(rule.title, target)
}
return plan
diff --git a/packages/cli/tests/commands/export/storybook/fonts.test.ts b/packages/cli/tests/commands/export/storybook/fonts.test.ts
index 23688d016..bf5d94716 100644
--- a/packages/cli/tests/commands/export/storybook/fonts.test.ts
+++ b/packages/cli/tests/commands/export/storybook/fonts.test.ts
@@ -1,12 +1,17 @@
import { describe, expect, test } from 'bun:test'
-import { fontFolder } from '#cli/commands/export/storybook/fonts'
+import { documentFolder } from '#cli/commands/export/storybook/fonts'
-describe('Storybook font folders', () => {
+describe('Storybook document folders', () => {
test('differ for documents of the same name exported into one folder', () => {
- expect(fontFolder('../kit/design.fig', undefined)).toBe('fonts/kit-design')
- expect(fontFolder('../app/design.fig', undefined)).toBe('fonts/app-design')
+ expect(documentFolder('../kit/design.fig', undefined)).toBe('openpencil/kit-design')
+ expect(documentFolder('../app/design.fig', undefined)).toBe('openpencil/app-design')
// A one-page export keeps its page's fonts apart from the others'.
- expect(fontFolder('design.fig', 'Icons')).toBe('fonts/design-icons')
+ expect(documentFolder('design.fig', 'Icons')).toBe('openpencil/design-icons')
+ // However far the document is from the output, the name is its folder and file.
+ expect(documentFolder('../../../../work/kits/primitives.fig', undefined)).toBe(
+ 'openpencil/kits-primitives'
+ )
+ expect(documentFolder('v1.2/design.fig', undefined)).toBe('openpencil/v1-2-design')
})
})
diff --git a/packages/cli/tests/commands/export/storybook/manifest.test.ts b/packages/cli/tests/commands/export/storybook/manifest.test.ts
new file mode 100644
index 000000000..b9f5d3d1e
--- /dev/null
+++ b/packages/cli/tests/commands/export/storybook/manifest.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, test } from 'bun:test'
+
+import { isGeneratedPath } from '#cli/commands/export/storybook/manifest'
+
+describe('Storybook export manifest paths', () => {
+ test('are every file the export writes', () => {
+ for (const path of [
+ 'Button.stories.ts',
+ 'Button.vue',
+ 'Button.tsx',
+ 'Button.module.css',
+ 'Button.design/Default.png',
+ 'openpencil/kit-design/fonts.css',
+ 'openpencil/kit-design/tokens.css',
+ 'openpencil/kit-design/fonts/inter-400-normal.woff2'
+ ])
+ expect(isGeneratedPath(path)).toBe(true)
+ })
+
+ test('never reach outside the output folder or files the export does not write', () => {
+ for (const path of [
+ '../Button.stories.ts',
+ '/tmp/Button.vue',
+ 'src/../../Button.tsx',
+ 'components/Button.vue',
+ 'openpencil/kit/notes.txt',
+ 'Button.design/../../x.png'
+ ])
+ expect(isGeneratedPath(path)).toBe(false)
+ })
+})
diff --git a/packages/core/src/editor/components/variants/model.ts b/packages/core/src/editor/components/variants/model.ts
index cd59e1538..f298b411e 100644
--- a/packages/core/src/editor/components/variants/model.ts
+++ b/packages/core/src/editor/components/variants/model.ts
@@ -1,6 +1,12 @@
import { uniq } from 'es-toolkit/array'
-import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ compareCanvasPosition,
+ defaultVariant,
+ type ComponentPropertyDefinition,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
export type VariantConflict = {
values: Record<string, string>
@@ -33,10 +39,6 @@ export type VariantOptionAvailability = {
available: boolean
}
-function sortByCanvasPosition(a: SceneNode, b: SceneNode) {
- return a.y - b.y || a.x - b.x || a.name.localeCompare(b.name)
-}
-
export function getComponentSet(graph: SceneGraph, componentSetId: string): SceneNode | undefined {
const node = graph.getNode(componentSetId)
return node?.type === 'COMPONENT_SET' ? node : undefined
@@ -105,7 +107,7 @@ export function findVariantByValues(
values: Record<string, string>
): SceneNode | undefined {
return getComponentSetVariants(graph, componentSetId)
- .sort(sortByCanvasPosition)
+ .sort(compareCanvasPosition)
.find((variant) =>
Object.entries(values).every(
([propertyName, value]) => variant.componentPropertyValues[propertyName] === value
@@ -131,7 +133,8 @@ export function getDefaultVariantForComponentSet(
graph: SceneGraph,
componentSetId: string
): SceneNode | undefined {
- return getComponentSetVariants(graph, componentSetId).sort(sortByCanvasPosition)[0]
+ const set = getComponentSet(graph, componentSetId)
+ return set && defaultVariant(graph, set)
}
export function getComponentSetVariantConflicts(
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index d87b2e8ab..8e8730440 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -181,7 +181,7 @@ What the tags can't do, such as leaving components out or laying an icon set out
}
```
-A rule applies to every story file whose `<page>/<name>` path matches its glob, by the names in the document: the page's, and the component set's or component's, or the prefix of slash-named components, such as `Icons/icon`. Every matching rule applies in order, so a later rule overrides an earlier one, each field on its own. `stories` is `variants`, a story per variant or state, as without rules; `single`, the `Default` story alone; `gallery`, `Default` and a `Gallery` story laying every variant out with its name, for static stories; or `none`, which leaves the file out. `title` is the file's title, with `{document}`, `{page}`, `{name}`, and `{path}`, the title it would have, filled in; titles that end up the same are kept apart as titles always are. Rules match the document's names, never a renamed title, so renaming a file never changes which rules apply to it.
+A rule applies to every story file whose `<page>/<name>` path matches its glob, by the names in the document: the page's, and the component set's or component's, or the prefix of slash-named components, such as `Icons/icon`. Every matching rule applies in order, so a later rule overrides an earlier one, each field on its own. `generate: false` keeps static stories for a Vue or React export where it would generate a component, such as for an icon set. `stories` is `variants`, a story per variant or state, as without rules; `single`, the `Default` story alone; `gallery`, `Default` and a `Gallery` story laying every variant out with its name, for static stories; or `none`, which leaves the file out. `title` is the file's title, with `{document}`, `{page}`, `{name}`, and `{path}`, the title it would have, filled in; titles that end up the same are kept apart as titles always are. Rules match the document's names, never a renamed title, so renaming a file never changes which rules apply to it.
### Designs next to their stories
@@ -191,13 +191,13 @@ Pass several documents, or a quoted glob such as `'src/**/*.pen'` that OpenPenci
Stories are titled by the document's file name, and then the page when more than one page has components: `pricing.fig` gives `pricing/Plan picker`, so documents exported together keep their stories apart. Each variant of a component set becomes a story, and its variant properties become `select` controls, so switching a control shows the matching variant. A set with a behaviour gets the control's own props instead: a Switch or Checkbox has a `checked` boolean, a Toggle `pressed`, a Collapsible `open`, and `disabled` when the set draws a disabled state; hover, pressed, and focus stay stories of their own. Standalone components named with slashes, such as `Button/Primary` and `Button/Secondary`, are grouped into one `Button` file with a `Variant` control. A combination the design has no variant for throws a named error in Storybook rather than showing a different variant.
-Stories render the component as HTML with inline styles, like `-f html`, so they need no OpenPencil runtime; `--framework` (`react`, `vue`, or `html`) only changes the wrapper and the `Meta`/`StoryObj` import from `@storybook/react-vite`, `@storybook/vue3-vite`, or `@storybook/html-vite`. Text uses the document's font families: the export fetches their files from the web font providers the editor uses into `fonts/<document>/` with a `fonts.css` every story file imports, so stories draw in those fonts, never in a fallback first. A family no provider has, such as Menlo, falls back to the browser's fonts, which the export warns about; `--fonts none` ships no font files. Static stories don't export text, boolean, or instance-swap properties yet.
+Stories render the component as HTML with inline styles, like `-f html`, so they need no OpenPencil runtime; `--framework` (`react`, `vue`, or `html`) only changes the wrapper and the `Meta`/`StoryObj` import from `@storybook/react-vite`, `@storybook/vue3-vite`, or `@storybook/html-vite`. Text uses the document's font families: the export fetches their files from the web font providers the editor uses into `openpencil/<document>/` with a `fonts.css` every story file imports, so stories draw in those fonts, never in a fallback first. The document's design variables go there too, as custom properties in a `tokens.css` every story file imports, so styles bound to variables resolve as the design draws them. A family no provider has, such as Menlo, falls back to the browser's fonts, which the export warns about; `--fonts none` ships no font files. Static stories don't export text, boolean, or instance-swap properties yet.
-With `--framework vue` or `--framework react`, a component set or component whose behaviour is a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea becomes a real component instead: `<Name>.vue` built on Reka UI, or `<Name>.tsx` with a `<Name>.module.css` built on Radix UI's `radix-ui` package. Its variants are compiled into a stylesheet keyed on the states Reka and Radix set (`data-state`, `data-disabled`, hover, and focus), and every other variant property is a prop the component sets as a `data-*` attribute. In Vue its value is a `v-model` such as `checked` or `open`; in React the component takes the Radix root's props, such as `checked`, `defaultChecked`, and `onCheckedChange`. Its text properties are string props, defaulting to the design's words, which the layers bound to them draw, with a text control in its stories.
+With `--framework vue` or `--framework react`, every component set and standalone component becomes a real component instead, `<Name>.vue` or `<Name>.tsx` with a `<Name>.module.css`, except slash-named components grouped into one file, and any a rule sets `"generate": false` for, which keep static stories. A component without a behaviour is the design's own elements: its root is the element the design draws, a `div` for a frame, and it takes the root element's own props, such as `onClick` and `class`. Its variant properties are props it sets as `data-*` attributes, so a `State=hover` variant is a prop like any other; its boolean properties are boolean props that show or hide the layers bound to them; and its slot properties are content it shows in place of the design's, a named `<slot>` in Vue and a `ReactNode` prop in React, falling back to the design's content. A component whose behaviour is a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea is built on Reka UI or on Radix UI's `radix-ui` package, and its interaction states, such as hover and disabled, become real `:hover` and `data-disabled` styles. Its variants are compiled into a stylesheet keyed on the states Reka and Radix set (`data-state`, `data-disabled`, hover, and focus), and every other variant property is a prop the component sets as a `data-*` attribute. In Vue its value is a `v-model` such as `checked` or `open`; in React the component takes the Radix root's props, such as `checked`, `defaultChecked`, and `onCheckedChange`. Its text properties are string props, defaulting to the design's words, which the layers bound to them draw, with a text control in its stories.
Tabs take the open tab as `value` (`v-model:value`, or `defaultValue` and `onValueChange` in React), named by each trigger's words as a slug, such as `account` or `password`, and starting on the first; each trigger and its panel are Reka's or Radix's `Tabs` parts around the design's layers, every trigger drawn like the design's other triggers and taking the first trigger's look while its tab is active, and the stories get a `select` control and a story per tab. A Radio group, Toggle group, or Accordion writes two components: the group, which chooses one item the same way, starting on the item the design draws on, and `<Group>Item` from its items' component set, built as the group's item primitive (`RadioGroupItem`, `ToggleGroupItem`, or `AccordionItem` with its trigger in a header) and taking the `value` it stands for. The group uses it once per item in its items slot, with each item's value, named by its label property or else its words, and its text values. A Slider, Progress, or Number field binds its number as `value` (`v-model:value`, or `defaultValue` in React, a list for Radix's slider), within the range its behaviour sets, starting where the design does; the slider's range and thumb and the progress indicator drop the place the design draws them at, since the value sets it, and stories get a range control and a story at each end. A Text field or Textarea draws its text layer as a native `input` or `textarea` binding `value`, which in React takes the component's props; when the design draws the field filled and empty, the empty field's words are the placeholder and its look the placeholder's, and the filled look shows while the field has text. Reka UI's number field draws the input and steppers in Vue; Radix has none, so React's is a native number input whose steppers change it by a step and which settles within its range when left. Focus on a slider's thumb or a field's input draws the control's focus state. A Radio is only generated as a group's item; a Toggle or Collapsible used on its own still becomes its own component.
-Inside a generated component, an instance of another component generated in the same export uses that component rather than drawing its layers: `<Switch>` imported from `./Switch.vue` or `./Switch`, set to the variant, text, and `disabled` values the instance shows. A control the design draws on, such as a checked switch, starts on and stays operable: a local `ref` bound with `v-model` in Vue, `defaultChecked` in React. The parent only places it, so the control keeps its own look and state styles. Instances of components not exported, or exported only as static stories, are drawn as before. An icon placed from a set, unless its paths were edited, is Iconify's component, `<Icon icon="lucide:bell">` from `@iconify/vue` or `@iconify/react`, which loads the icon when shown.
+Inside a generated component, an instance of another component generated in the same export uses that component rather than drawing its layers: `<Switch>` imported from `./Switch.vue` or `./Switch`, set to the variant, text, and `disabled` values the instance shows. A control the design draws on, such as a checked switch, starts on and stays operable: a local `ref` bound with `v-model` in Vue, `defaultChecked` in React. The parent only places it, so the control keeps its own look and state styles. Only an instance that draws exactly as its variant, apart from its property values and where its parent places it, uses the component; one with edited text no property sets, a fill of its own, or other changes draws its own layers, so the story keeps what the design shows. Instances of components not exported, or exported only as static stories, are drawn as before. A variant property whose default the document leaves empty starts at the default variant, the one in the set's top-left corner, which opens its stories. An icon placed from a set, unless its paths were edited, is Iconify's component, `<Icon icon="lucide:bell">` from `@iconify/vue` or `@iconify/react`, which loads the icon when shown.
Its stories render the component, and a play function clicks the control and checks its state, so the Storybook project needs `reka-ui` or `radix-ui` installed, and `@iconify/vue` or `@iconify/react` when components hold icons.
diff --git a/packages/dom-css/src/behaviours/states/conditions.ts b/packages/dom-css/src/behaviours/states/conditions.ts
index f3ab2d6e2..2685849ac 100644
--- a/packages/dom-css/src/behaviours/states/conditions.ts
+++ b/packages/dom-css/src/behaviours/states/conditions.ts
@@ -1,6 +1,7 @@
import {
behaviourProperties,
readBehaviour,
+ variantDefaultValue,
type BehaviourKind,
type ComponentPropertyDefinition,
type SceneGraph,
@@ -57,10 +58,17 @@ function interactionCondition(set: SceneNode, states: NonNullable<BehaviourArgs[
}
}
-/** Any other variant property is a prop the generated component sets as `data-*`. */
-function propCondition(definition: ComponentPropertyDefinition): ValueCondition {
- return (value) =>
- value === definition.defaultValue ? null : { type: 'prop', name: definition.name, value }
+/**
+ * Any other variant property is a prop the generated component sets as `data-*`, at rest at
+ * its default value, the default variant's when the document leaves it empty.
+ */
+function propCondition(
+ graph: SceneGraph,
+ set: SceneNode,
+ definition: ComponentPropertyDefinition
+): ValueCondition {
+ const rest = variantDefaultValue(graph, set, definition)
+ return (value) => (value === rest ? null : { type: 'prop', name: definition.name, value })
}
/**
@@ -80,7 +88,7 @@ export function variantConditions(
const filled = args?.filled
if (filled?.property === definition.name)
return (value) => (value === filled.on ? { type: 'filled' } : null)
- return propCondition(definition)
+ return propCondition(graph, set, definition)
}
const byProperty = new Map(
behaviourProperties(graph, set)
diff --git a/packages/dom-css/src/behaviours/states/layers.ts b/packages/dom-css/src/behaviours/states/layers.ts
index 6ef7ddfc3..2f912459d 100644
--- a/packages/dom-css/src/behaviours/states/layers.ts
+++ b/packages/dom-css/src/behaviours/states/layers.ts
@@ -31,7 +31,7 @@ export interface VariantLayer {
}
/** Where the set places a variant, which is not the component's own style. */
-const PLACEMENT = ['position', 'left', 'top', 'right', 'bottom', 'inset']
+export const PLACEMENT = ['position', 'left', 'top', 'right', 'bottom', 'inset']
function textContent(element: DesignElement): string | null {
const texts = element.children.filter((child): child is DesignText => child.type === 'text')
@@ -92,6 +92,23 @@ function tabPanels(graph: SceneGraph, variant: SceneNode): Set<string> {
return new Set(panels?.childIds)
}
+/**
+ * The layers of a variant a boolean property shows or hides, which are projected however the
+ * variant draws them, since the generated component shows them from its prop.
+ */
+function visibilityBound(graph: SceneGraph, variant: SceneNode): Set<string> {
+ const bound = new Set<string>()
+ const visit = (node: SceneNode) => {
+ for (const child of graph.getChildren(node.id)) {
+ if (child.componentPropertyReferences.some((item) => item.field === 'VISIBLE'))
+ bound.add(child.id)
+ if (child.type !== 'INSTANCE') visit(child)
+ }
+ }
+ visit(variant)
+ return bound
+}
+
/** A variant projected to DOM, without where the set places it. */
export function projectVariant(
graph: SceneGraph,
@@ -101,7 +118,7 @@ export function projectVariant(
const document = sceneNodeToDesignDocument(graph, variant.id, {
includeSourceIds: false,
vectorElement,
- shown: tabPanels(graph, variant)
+ shown: new Set([...tabPanels(graph, variant), ...visibilityBound(graph, variant)])
})
const root = document.children.at(0)
if (root?.type !== 'element') return null
diff --git a/packages/dom-css/src/behaviours/states/model.ts b/packages/dom-css/src/behaviours/states/model.ts
index 8d03de019..7026c5371 100644
--- a/packages/dom-css/src/behaviours/states/model.ts
+++ b/packages/dom-css/src/behaviours/states/model.ts
@@ -43,6 +43,48 @@ function variantStyle(
return difference(element.base, { ...drawn, display })
}
+/** The value a variant draws a property with on a layer: its own, or none where it lacks it. */
+function drawnValue(
+ element: StateElement,
+ layer: VariantLayer | undefined,
+ property: string,
+ hiddenAtRest: boolean
+): string {
+ if (!layer) return property === 'display' ? 'none' : (element.base[property] ?? 'unset')
+ const drawn = layer.element.inlineStyle ?? {}
+ if (Object.hasOwn(drawn, property)) return drawn[property] ?? 'unset'
+ if (property === 'display' && hiddenAtRest) return 'revert'
+ return 'unset'
+}
+
+/**
+ * Makes each variant draw a layer as its own design does where a rule for fewer conditions
+ * also matches it. A rule for small buttons also matches the small, pressed one, so whatever
+ * it sets that the pressed one draws otherwise, such as words only small rest buttons show,
+ * the pressed one sets back, as a rule with more conditions, which wins.
+ */
+function settleCombined(
+ element: StateElement,
+ variants: readonly { conditions: StateCondition[]; layers: Map<string, VariantLayer> }[],
+ hiddenAtRest: boolean
+): void {
+ for (const variant of variants) {
+ const own = element.rules.find((rule) => isEqual(rule.conditions, variant.conditions))
+ const fix: DesignStyleDeclaration = {}
+ for (const rule of element.rules) {
+ if (!isPartOf(rule.conditions, variant.conditions)) continue
+ for (const property of Object.keys(rule.style)) {
+ if (own && Object.hasOwn(own.style, property)) continue
+ const layer = variant.layers.get(element.key)
+ fix[property] = drawnValue(element, layer, property, hiddenAtRest)
+ }
+ }
+ if (isEmptyObject(fix)) continue
+ if (own) own.style = { ...own.style, ...fix }
+ else element.rules.push({ conditions: variant.conditions, style: fix })
+ }
+}
+
const isPartOf = (part: StateCondition[], whole: StateCondition[]) =>
part.length < whole.length &&
part.every((condition) => whole.some((other) => isEqual(condition, other)))
@@ -104,13 +146,20 @@ export function stateStyles(
for (const variant of others) mergeVariant(root, variant.root, hiddenAtRest)
const elements = allElements(root)
- for (const variant of others) {
- const layers = layersByKey(variant.root)
+ const drawn = others.map((variant) => ({
+ conditions: variant.conditions,
+ layers: layersByKey(variant.root)
+ }))
+ for (const variant of drawn) {
for (const element of elements) {
- const style = variantStyle(element, layers.get(element.key), hiddenAtRest.has(element))
+ const layer = variant.layers.get(element.key)
+ const style = variantStyle(element, layer, hiddenAtRest.has(element))
if (!isEmptyObject(style)) element.rules.push({ conditions: variant.conditions, style })
}
}
- for (const element of elements) element.rules = pruneCombined(element.rules)
+ for (const element of elements) {
+ settleCombined(element, drawn, hiddenAtRest.has(element))
+ element.rules = pruneCombined(element.rules)
+ }
return { name: set.name, restId: rest.id, root }
}
diff --git a/packages/dom-css/src/export/components/drawn.ts b/packages/dom-css/src/export/components/drawn.ts
new file mode 100644
index 000000000..40cc393b9
--- /dev/null
+++ b/packages/dom-css/src/export/components/drawn.ts
@@ -0,0 +1,77 @@
+import { isEqual } from 'es-toolkit/predicate'
+
+import type {
+ ComponentPropertyReferenceField,
+ SceneGraph,
+ SceneNode
+} from '@open-pencil/scene-graph'
+
+/** What a layer draws, which an instance can change without a property. */
+const DRAWN = [
+ 'fills',
+ 'strokes',
+ 'effects',
+ 'opacity',
+ 'cornerRadius',
+ 'fontFamily',
+ 'fontSize',
+ 'fontWeight',
+ 'italic'
+] as const satisfies readonly (keyof SceneNode)[]
+
+/** How a layer lays out what it holds, which an instance can change without a property. */
+const LAYOUT = [
+ 'layoutMode',
+ 'itemSpacing',
+ 'paddingTop',
+ 'paddingRight',
+ 'paddingBottom',
+ 'paddingLeft',
+ 'primaryAxisAlign',
+ 'counterAxisAlign'
+] as const satisfies readonly (keyof SceneNode)[]
+
+const same = (a: SceneNode, b: SceneNode, fields: readonly (keyof SceneNode)[]) =>
+ fields.every((field) => isEqual(a[field], b[field]))
+
+const bound = (node: SceneNode, field: ComponentPropertyReferenceField) =>
+ node.componentPropertyReferences.some((reference) => reference.field === field)
+
+function childrenMatch(graph: SceneGraph, drawn: SceneNode, main: SceneNode): boolean {
+ const children = graph.getChildren(drawn.id)
+ const mains = graph.getChildren(main.id)
+ return (
+ children.length === mains.length &&
+ children.every((child, index) => {
+ const counterpart = mains.at(index)
+ return counterpart !== undefined && layerMatches(graph, child, counterpart)
+ })
+ )
+}
+
+/**
+ * Whether a layer of an instance draws as its main component's does, apart from what a
+ * property of the component sets: the text a text property shows and what a boolean property
+ * shows or hides, which the component's props pass on.
+ */
+function layerMatches(graph: SceneGraph, drawn: SceneNode, main: SceneNode): boolean {
+ if (drawn.type !== main.type) return false
+ if (!bound(main, 'VISIBLE') && drawn.visible !== main.visible) return false
+ if (drawn.type === 'TEXT' && !bound(main, 'TEXT') && drawn.text !== main.text) return false
+ if (drawn.type === 'INSTANCE' && drawn.componentId !== main.componentId) return false
+ return same(drawn, main, DRAWN) && same(drawn, main, LAYOUT) && childrenMatch(graph, drawn, main)
+}
+
+/**
+ * Whether an instance draws exactly as the variant it shows, so a generated component given
+ * its property values draws it: the same look, layout, words, and nested components, apart
+ * from where its parent places and sizes it. An instance with any other change, such as edited
+ * text no property sets or a fill of its own, draws its own layers instead.
+ */
+export function drawsAsMain(graph: SceneGraph, instance: SceneNode, main: SceneNode): boolean {
+ return (
+ same(instance, main, DRAWN) &&
+ same(instance, main, LAYOUT) &&
+ childrenMatch(graph, instance, main)
+ )
+}
diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
index fb9129e36..fc532e067 100644
--- a/packages/dom-css/src/export/components/model.ts
+++ b/packages/dom-css/src/export/components/model.ts
@@ -4,16 +4,17 @@ import { allElements } from '#dom-css/behaviours/states/layers'
import { ownerVariants, stateStyles } from '#dom-css/behaviours/states/model'
import { layerClassNames, propAttribute } from '#dom-css/behaviours/states/names'
import type { StateElement, StateStyles } from '#dom-css/behaviours/states/types'
+import { uniq } from 'es-toolkit/array'
import { camelCase } from 'es-toolkit/string'
import {
behaviourContract,
behaviourProperties,
- findLayerByPath,
layerPath,
readBehaviour,
slotPropertyId,
textBinding,
+ variantDefaultValue,
type Behaviour,
type SceneGraph,
type SceneNode
@@ -39,6 +40,14 @@ import {
type ItemBuilder,
type ItemKind
} from './groups'
+import {
+ booleanProps,
+ slotProps,
+ textProps,
+ type BooleanProp,
+ type SlotProp,
+ type TextProp
+} from './properties'
import {
referencedLayers,
type ComponentReference,
@@ -67,7 +76,11 @@ export const GENERATED_KINDS = [
] as const
/** What a generated component is: a control on its own, or a group's item. */
-export type GeneratedKind = (typeof GENERATED_KINDS)[number] | ItemKind
+/**
+ * What a generated component is: a control on its own, a group's item, or `plain`, a component
+ * without a behaviour, which takes its properties as props and has no control of its own.
+ */
+export type GeneratedKind = (typeof GENERATED_KINDS)[number] | ItemKind | 'plain'
/** A variant property the component takes as a prop and sets on its root as `data-*`. */
export interface VariantProp {
@@ -104,22 +117,15 @@ export interface ComponentElement {
attrs: Record<string, string>
/** On the root only. */
bindings: ComponentBinding[]
+ /** The boolean prop that shows the layer, which hides it while off. */
+ shownBy?: string
+ /** The slot prop whose content the layer shows in place of its own. */
+ slot?: string
/** The value a repeated part stands for, such as a tab trigger's tab. */
value?: string
children: ComponentNode[]
}
-/** A text property the component takes as a string prop and draws in the layers bound to it. */
-export interface TextProp {
- /** The prop's identifier. */
- name: string
- /** The text property's id, which instances assign values by. */
- id: string
- /** The text property's name. */
- property: string
- default: string
-}
-
/** A number the component binds two ways, within its range, starting where the design does. */
export interface RangeModel {
min: number
@@ -174,6 +180,8 @@ export interface ComponentModel {
disabled: boolean
props: VariantProp[]
texts: TextProp[]
+ booleans: BooleanProp[]
+ slots: SlotProp[]
/** The variant properties that draw its booleans and states, which references set. */
args: BehaviourArgs
}
@@ -189,6 +197,10 @@ interface TreeLabels {
repeated: Map<StateElement, RepeatedPart>
/** A field's text layer, drawn as its input, and the ones it replaces. */
input: InputLayers | null
+ /** The boolean prop that shows each bound layer. */
+ shownBy: Map<StateElement, string>
+ /** The slot prop each slot frame shows. */
+ slotOf: Map<StateElement, string>
}
function componentTree(
@@ -207,6 +219,8 @@ function componentTree(
className: labels.classes.get(node) ?? '',
attrs: node.attrs,
bindings: part === 'root' ? bindings : [],
+ shownBy: labels.shownBy.get(node),
+ slot: labels.slotOf.get(node),
// A bound text layer draws its prop in place of the design's words and their runs.
children: text
? [{ type: 'textProp', name: text }]
@@ -225,52 +239,6 @@ function childNode(element: StateElement, labels: TreeLabels): ComponentNode[] {
return [{ ...used, className }]
}
-/**
- * The set's text properties as props, and the layers bound to each. A layer is bound when it
- * is in any variant, found by the path every variant shares.
- */
-function textProps(
- graph: SceneGraph,
- set: SceneNode,
- elements: readonly StateElement[],
- taken: Set<string>,
- /** A field's text property, which its input shows rather than a prop. */
- input: string | undefined
-): { texts: TextProp[]; bound: Map<StateElement, string>; input: StateElement[] } {
- const definitions = behaviourProperties(graph, set).filter(
- (item) => item.type === 'TEXT' && item.id !== input
- )
- const texts = definitions.map((definition) => ({
- name: claimName(camelCase(identifierName(definition.name, 'Text')), taken),
- id: definition.id,
- property: definition.name,
- default: definition.defaultValue
- }))
- const byId = new Map(definitions.map((definition, i) => [definition.id, texts[i]]))
- const variants = ownerVariants(graph, set)
- const bound = new Map<StateElement, string>()
- const inputs: StateElement[] = []
- for (const element of elements) {
- // A key ends with the words a layer reads, which a text prop draws in every variant.
- const path = element.key.split('\0')[0] ?? ''
- for (const variant of variants) {
- const reference = findLayerByPath(graph, variant.id, path)?.componentPropertyReferences.find(
- (item) => item.field === 'TEXT'
- )
- if (reference && reference.propertyId === input) {
- inputs.push(element)
- break
- }
- const prop = reference && byId.get(reference.propertyId)
- if (prop) {
- bound.set(element, prop.name)
- break
- }
- }
- }
- return { texts, bound, input: inputs }
-}
-
/** A generated component's files, and what its stories need to know about it. */
export interface GeneratedComponent {
files: { path: string; content: string }[]
@@ -300,6 +268,7 @@ const BUTTON_PARTS: Record<GeneratedKind, readonly string[]> = {
numberField: ['increment', 'decrement'],
textField: [],
textarea: [],
+ plain: [],
radioGroupItem: ['root'],
toggleGroupItem: ['root'],
accordionItem: ['trigger']
@@ -387,8 +356,14 @@ function variantProps(
.map((definition) => ({
name: claimName(camelCase(identifierName(definition.name, 'Prop')), taken),
property: definition.name,
- options: definition.variantOptions ?? [],
- default: definition.defaultValue
+ // A document may record no options, which the variants' own values then are.
+ options: uniq([
+ ...(definition.variantOptions ?? []),
+ ...ownerVariants(graph, set).map(
+ (variant) => variant.componentPropertyValues[definition.name] ?? ''
+ )
+ ]).filter((option) => option !== ''),
+ default: variantDefaultValue(graph, set, definition)
}))
}
@@ -481,12 +456,15 @@ function borderBoxes(root: StateElement): void {
function drawnParts(
graph: SceneGraph,
set: SceneNode,
- behaviour: Behaviour,
+ behaviour: Behaviour | null,
kind: GeneratedKind,
root: StateElement
) {
- const parts = behaviourParts(graph, set, behaviour, root)
- const tabs = behaviour.kind === 'tabs' ? tabParts(parts) : null
+ // A component without a behaviour has no parts but its root.
+ const parts = behaviour
+ ? behaviourParts(graph, set, behaviour, root)
+ : new Map<StateElement, string>([[root, 'root']])
+ const tabs = behaviour?.kind === 'tabs' ? tabParts(parts) : null
const repeated = tabs?.repeated ?? new Map<StateElement, RepeatedPart>()
activeTriggers(repeated)
resetButtons(kind, parts, repeated)
@@ -501,9 +479,10 @@ function valueModels(
graph: SceneGraph,
set: SceneNode,
kind: GeneratedKind,
- behaviour: Behaviour,
+ behaviour: Behaviour | null,
args: BehaviourArgs
): { range: RangeModel | null; text: TextModel | null; inputProperty: string | undefined } {
+ if (!behaviour) return { range: null, text: null, inputProperty: undefined }
const valueText = inputValue(kind)
const inputProperty = valueText && textBinding(behaviour, valueText)
const definition = behaviourProperties(graph, set).find((item) => item.id === inputProperty)
@@ -520,30 +499,33 @@ export function componentModel(
options: ComponentModelOptions = {}
): ComponentModel | null {
const behaviour = readBehaviour(set)
- const kind = behaviour && generatedKind(behaviour.kind, options.itemOf)
+ // A component without a behaviour is plain: its properties are its props.
+ const kind = behaviour ? generatedKind(behaviour.kind, options.itemOf) : 'plain'
const styles = kind ? stateStyles(graph, set, options) : null
- const args = behaviourArgs(graph, set)
- if (!behaviour || !kind || !styles || !args) return null
+ const args = behaviourArgs(graph, set) ?? { booleans: new Map() }
+ if (!kind || !styles) return null
const name = options.name ?? identifierName(set.name, 'Component')
const { parts, tabs, repeated } = drawnParts(graph, set, behaviour, kind, styles.root)
// A group's items first, so its item component is used for them rather than a standalone one.
const variantIds = [styles.restId, ...ownerVariants(graph, set).map((variant) => variant.id)]
- const items = itemsOf(
- graph,
- behaviour,
- variantIds,
- parts,
- options,
- (itemOf) => (owner) =>
- componentModel(graph, owner, {
- ...options,
- name: options.itemName ?? `${name}Item`,
- itemName: undefined,
- itemOf
- })
- )
+ const items =
+ behaviour &&
+ itemsOf(
+ graph,
+ behaviour,
+ variantIds,
+ parts,
+ options,
+ (itemOf) => (owner) =>
+ componentModel(graph, owner, {
+ ...options,
+ name: options.itemName ?? `${name}Item`,
+ itemName: undefined,
+ itemOf
+ })
+ )
const choice = tabs?.choice ?? items?.choice ?? null
const { range, text, inputProperty } = valueModels(graph, set, kind, behaviour, args)
@@ -552,16 +534,28 @@ export function componentModel(
const props = variantProps(graph, set, args, taken)
const disabled = drawsDisabled(args)
const used = usedLayers(graph, styles.root, variantIds, items?.used, options.references)
- const texts = textProps(graph, set, allElements(styles.root), taken, inputProperty)
+ const elements = allElements(styles.root)
+ const texts = textProps(graph, set, elements, taken, inputProperty)
const input = inputLayers(texts.input)
numberInput(input, range)
+ const { booleans, shownBy } = booleanProps(graph, set, elements, taken)
+ const { slots, slotOf } = slotProps(graph, set, elements, taken, parts)
return {
name,
kind,
styles,
tree: componentTree(
styles.root,
- { parts, classes: layerClassNames(styles), texts: texts.bound, used, repeated, input },
+ {
+ parts,
+ classes: layerClassNames(styles),
+ texts: texts.bound,
+ used,
+ repeated,
+ input,
+ shownBy,
+ slotOf
+ },
rootBindings(model, !!options.itemOf, disabled, props)
),
model,
@@ -573,6 +567,8 @@ export function componentModel(
disabled,
props,
texts: texts.texts,
+ booleans,
+ slots,
args
}
}
diff --git a/packages/dom-css/src/export/components/properties.ts b/packages/dom-css/src/export/components/properties.ts
new file mode 100644
index 000000000..f9f59bdd3
--- /dev/null
+++ b/packages/dom-css/src/export/components/properties.ts
@@ -0,0 +1,172 @@
+import { ownerVariants } from '#dom-css/behaviours/states/model'
+import type { StateElement } from '#dom-css/behaviours/states/types'
+import { camelCase } from 'es-toolkit/string'
+
+import {
+ behaviourProperties,
+ findLayerByPath,
+ type ComponentPropertyReferenceField,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import { claimName, identifierName } from '../storybook/names'
+
+/** A text property the component takes as a string prop and draws in the layers bound to it. */
+export interface TextProp {
+ /** The prop's identifier. */
+ name: string
+ /** The text property's id, which instances assign values by. */
+ id: string
+ /** The text property's name. */
+ property: string
+ default: string
+}
+
+/** A boolean property the component takes as a prop, showing the layers bound to it while on. */
+export interface BooleanProp {
+ /** The prop's identifier. */
+ name: string
+ /** The boolean property's id, which instances assign values by. */
+ id: string
+ /** The boolean property's name. */
+ property: string
+ default: boolean
+}
+
+/**
+ * A slot property the component takes as content in place of the design's, which it shows
+ * when none is given.
+ */
+export interface SlotProp {
+ /** The prop's identifier, and the slot's name in Vue. */
+ name: string
+ /** The slot property's id. */
+ id: string
+ /** The slot property's name. */
+ property: string
+}
+
+/**
+ * The layers bound to a property through `field`, each with the prop it draws. A layer is
+ * bound when it is in any variant, found by the path every variant shares.
+ */
+function boundLayers(
+ graph: SceneGraph,
+ set: SceneNode,
+ elements: readonly StateElement[],
+ field: ComponentPropertyReferenceField,
+ props: ReadonlyMap<string, string>
+): Map<StateElement, string> {
+ const variants = ownerVariants(graph, set)
+ const bound = new Map<StateElement, string>()
+ for (const element of elements) {
+ const path = element.key.split('\0')[0] ?? ''
+ for (const variant of variants) {
+ const reference = findLayerByPath(graph, variant.id, path)?.componentPropertyReferences.find(
+ (item) => item.field === field
+ )
+ const prop = reference && props.get(reference.propertyId)
+ if (prop) {
+ bound.set(element, prop)
+ break
+ }
+ }
+ }
+ return bound
+}
+
+const propName = (property: string, taken: Set<string>, fallback: string) =>
+ claimName(camelCase(identifierName(property, fallback)), taken)
+
+/** The set's boolean properties as props, and the layers each shows while it is on. */
+export function booleanProps(
+ graph: SceneGraph,
+ set: SceneNode,
+ elements: readonly StateElement[],
+ taken: Set<string>
+): { booleans: BooleanProp[]; shownBy: Map<StateElement, string> } {
+ const booleans = behaviourProperties(graph, set)
+ .filter((definition) => definition.type === 'BOOLEAN')
+ .map((definition) => ({
+ name: propName(definition.name, taken, 'Shown'),
+ id: definition.id,
+ property: definition.name,
+ default: definition.defaultValue === 'true'
+ }))
+ const byId = new Map(booleans.map((prop) => [prop.id, prop.name]))
+ return { booleans, shownBy: boundLayers(graph, set, elements, 'VISIBLE', byId) }
+}
+
+/**
+ * The set's slot properties as props, and the frame each fills, except frames a behaviour
+ * draws its parts in, such as a switch's thumb, which stay its parts.
+ */
+export function slotProps(
+ graph: SceneGraph,
+ set: SceneNode,
+ elements: readonly StateElement[],
+ taken: Set<string>,
+ parts: ReadonlyMap<StateElement, string>
+): { slots: SlotProp[]; slotOf: Map<StateElement, string> } {
+ const definitions = behaviourProperties(graph, set).filter(
+ (definition) => definition.type === 'SLOT'
+ )
+ const frames = elements.filter((element) => !parts.has(element))
+ const slots = definitions.map((definition) => ({
+ name: propName(definition.name, taken, 'Content'),
+ id: definition.id,
+ property: definition.name
+ }))
+ const byId = new Map(slots.map((prop) => [prop.id, prop.name]))
+ const slotOf = boundLayers(graph, set, frames, 'SLOT_CONTENT', byId)
+ // A slot no layer draws has nowhere to show its content, so it is no prop.
+ const drawn = new Set(slotOf.values())
+ return { slots: slots.filter((slot) => drawn.has(slot.name)), slotOf }
+}
+
+/**
+ * The set's text properties as props, and the layers bound to each. A layer is bound when it
+ * is in any variant, found by the path every variant shares.
+ */
+export function textProps(
+ graph: SceneGraph,
+ set: SceneNode,
+ elements: readonly StateElement[],
+ taken: Set<string>,
+ /** A field's text property, which its input shows rather than a prop. */
+ input: string | undefined
+): { texts: TextProp[]; bound: Map<StateElement, string>; input: StateElement[] } {
+ const definitions = behaviourProperties(graph, set).filter(
+ (item) => item.type === 'TEXT' && item.id !== input
+ )
+ const texts = definitions.map((definition) => ({
+ name: claimName(camelCase(identifierName(definition.name, 'Text')), taken),
+ id: definition.id,
+ property: definition.name,
+ default: definition.defaultValue
+ }))
+ const byId = new Map(definitions.map((definition, i) => [definition.id, texts[i]]))
+ const variants = ownerVariants(graph, set)
+ const bound = new Map<StateElement, string>()
+ const inputs: StateElement[] = []
+ for (const element of elements) {
+ // A key ends with the words a layer reads, which a text prop draws in every variant.
+ const path = element.key.split('\0')[0] ?? ''
+ for (const variant of variants) {
+ const reference = findLayerByPath(graph, variant.id, path)?.componentPropertyReferences.find(
+ (item) => item.field === 'TEXT'
+ )
+ if (reference && reference.propertyId === input) {
+ inputs.push(element)
+ break
+ }
+ const prop = reference && byId.get(reference.propertyId)
+ if (prop) {
+ bound.set(element, prop.name)
+ break
+ }
+ }
+ }
+ return { texts, bound, input: inputs }
+}
diff --git a/packages/dom-css/src/export/components/react/fields.ts b/packages/dom-css/src/export/components/react/fields.ts
new file mode 100644
index 000000000..675daf974
--- /dev/null
+++ b/packages/dom-css/src/export/components/react/fields.ts
@@ -0,0 +1,129 @@
+import dedent from 'dedent'
+
+import { es, jsx } from '@open-pencil/emit'
+
+import { progressWidth } from '../fields'
+import type { ComponentElement, ComponentModel, GeneratedKind } from '../model'
+import { moduleClass, numeric, type MarkupUses } from './shared'
+
+/** Kinds whose native input takes the caller's props, rather than their root. */
+export const INPUT_PROPS: Partial<Record<GeneratedKind, 'input' | 'textarea'>> = {
+ textField: 'input',
+ textarea: 'textarea'
+}
+
+/** A number field's stepper parts, which change its value by a step. */
+export const STEPPERS: Record<string, { label: string; sign: '+' | '-' }> = {
+ increment: { label: 'Increase', sign: '+' },
+ decrement: { label: 'Decrease', sign: '-' }
+}
+
+/** What a part of a native or measured control needs: a stepper's step, an indicator's width. */
+export function partAttributes(node: ComponentElement, uses: MarkupUses): es.SyntaxNode[] {
+ const { range } = uses.component
+ if (!range || !node.part) return []
+ if (uses.kind === 'progress' && node.part === 'indicator') {
+ const style = progressWidth(range, es.identifier('value'))
+ return style ? [jsx.attribute('style', jsx.container(style))] : []
+ }
+ const stepper = uses.kind === 'numberField' ? STEPPERS[node.part] : undefined
+ if (!stepper) return []
+ return [
+ jsx.attribute('aria-label', jsx.stringValue(stepper.label)),
+ jsx.attribute('disabled', jsx.container(es.identifier('disabled'))),
+ jsx.attribute(
+ 'onClick',
+ jsx.container(es.parseExpression(`() => commit(value ${stepper.sign} ${String(range.step)})`))
+ )
+ ]
+}
+
+export const NUMBER_INPUT = [
+ ['type', jsx.stringValue('number')],
+ ['value', jsx.container(es.parseExpression("Number.isNaN(value) ? '' : value"))],
+ [
+ 'onChange',
+ jsx.container(es.parseExpression('(event) => setValue(event.target.valueAsNumber)'))
+ ],
+ ['onBlur', jsx.container(es.parseExpression('() => commit(value)'))]
+] as const
+
+/** A field's input: a number input that commits within its range, or the input or textarea. */
+export function inputElement(className: string, uses: MarkupUses, depth: number): es.SyntaxNode {
+ const { component } = uses
+ const classAttribute = jsx.attribute('className', jsx.container(moduleClass(className)))
+ const { range } = component
+ if (range)
+ return jsx.element(
+ 'input',
+ [
+ ...NUMBER_INPUT.map(([name, value]) => jsx.attribute(name, value)),
+ numeric('min', range.min),
+ numeric('max', range.max),
+ numeric('step', range.step),
+ jsx.attribute('disabled', jsx.container(es.identifier('disabled'))),
+ classAttribute
+ ],
+ [],
+ depth
+ )
+ const start = component.text?.default
+ const placeholder = component.text?.placeholder
+ return jsx.element(
+ INPUT_PROPS[uses.kind] ?? 'input',
+ [
+ ...(placeholder ? [jsx.attribute('placeholder', jsx.stringValue(placeholder))] : []),
+ ...(start ? [jsx.attribute('defaultValue', jsx.stringValue(start))] : []),
+ // The input takes the caller's props, such as `name` or `onChange`.
+ jsx.spread(es.identifier('props')),
+ classAttribute
+ ],
+ [],
+ depth
+ )
+}
+
+/** A destructured prop, with the default it takes when the caller leaves it out. */
+export interface Parameter {
+ name: string
+ default?: es.SyntaxNode
+}
+
+/** Props a kind reads itself: a progress bar's value, a number field's start and changes. */
+export function kindParameters(component: ComponentModel): Parameter[] {
+ const { range } = component
+ if (component.kind === 'progress' && range)
+ return [{ name: 'value', default: es.number(range.default) }]
+ if (component.kind === 'numberField' && range)
+ return [
+ { name: 'defaultValue', default: es.number(range.default) },
+ { name: 'onValueChange' },
+ { name: 'disabled' }
+ ]
+ return []
+}
+
+/**
+ * A number field's value: typed freely, and settled within its range when it loses focus or a
+ * stepper moves it, which is when the caller hears of it.
+ */
+export const NUMBER_STATE = (range: { min: number; max: number }) =>
+ es.fill(
+ es.parseModule(dedent`
+ const [value, setValue] = useState(defaultValue)
+ const commit = (next: number) => {
+ const settled = Number.isNaN(next) ? $min : Math.min($max, Math.max($min, next))
+ setValue(settled)
+ onValueChange?.(settled)
+ }
+ `),
+ { $min: es.number(range.min), $max: es.number(range.max) }
+ ).body
+
+/** The component function's statements before it returns, such as a number field's state. */
+export function prepend(declaration: es.SyntaxNode | undefined, statements: es.SyntaxNode[]): void {
+ const fn = es.child(declaration, 'declaration')
+ const body = es.child(fn, 'body')
+ if (!body || statements.length === 0) return
+ body.body = [...statements, ...es.children(body, 'body')]
+}
diff --git a/packages/dom-css/src/export/components/react.ts b/packages/dom-css/src/export/components/react/index.ts
similarity index 68%
rename from packages/dom-css/src/export/components/react.ts
rename to packages/dom-css/src/export/components/react/index.ts
index 2f2be4c11..2c3a46b45 100644
--- a/packages/dom-css/src/export/components/react.ts
+++ b/packages/dom-css/src/export/components/react/index.ts
@@ -6,7 +6,6 @@ import { camelCase, upperFirst } from 'es-toolkit/string'
import { es, jsx } from '@open-pencil/emit'
-import { progressWidth } from './fields'
import type {
ComponentElement,
ComponentGenerator,
@@ -14,8 +13,19 @@ import type {
ComponentModel,
ComponentNode,
GeneratedKind
-} from './model'
-import type { ComponentReference } from './references'
+} from '../model'
+import type { ComponentReference } from '../references'
+import {
+ INPUT_PROPS,
+ inputElement,
+ kindParameters,
+ NUMBER_STATE,
+ partAttributes,
+ prepend,
+ STEPPERS,
+ type Parameter
+} from './fields'
+import { moduleClass, numeric, type MarkupUses } from './shared'
/**
* The Radix primitive a kind renders, from the unified `radix-ui` package, and the component
@@ -52,19 +62,9 @@ const RADIX: Record<GeneratedKind, { namespace: string; parts: Record<string, st
// Radix has no number or text field; these are native inputs in the design's own elements.
numberField: null,
textField: null,
- textarea: null
-}
-
-/** Kinds whose native input takes the caller's props, rather than their root. */
-const INPUT_PROPS: Partial<Record<GeneratedKind, 'input' | 'textarea'>> = {
- textField: 'input',
- textarea: 'textarea'
-}
-
-/** A number field's stepper parts, which change its value by a step. */
-const STEPPERS: Record<string, { label: string; sign: '+' | '-' }> = {
- increment: { label: 'Increase', sign: '+' },
- decrement: { label: 'Decrease', sign: '-' }
+ textarea: null,
+ // A component without a behaviour is the design's own elements.
+ plain: null
}
/** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */
@@ -83,19 +83,6 @@ const HEADING_STYLE = jsx.container(
)
)
-const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
-
-/** `styles.thumb`, or `styles['switch-thumb']` for a class that isn't an identifier. */
-function moduleClass(className: string): es.SyntaxNode {
- return {
- type: 'MemberExpression',
- object: es.identifier('styles'),
- property: IDENTIFIER.test(className) ? es.identifier(className) : es.string(className),
- computed: !IDENTIFIER.test(className),
- optional: false
- }
-}
-
/** Several classes on one element, skipping a caller's that is absent. */
const CLASS_NAMES = es.parseExpression("$classes.filter(Boolean).join(' ')")
@@ -118,31 +105,26 @@ const disabledFlag = (kind: GeneratedKind) =>
kind === 'numberField' ? 'disabled || undefined' : 'props.disabled || undefined'
)
-/** What a component's markup uses, which its module imports. */
-interface MarkupUses {
- component: ComponentModel
- kind: GeneratedKind
- choice: ComponentModel['choice']
- /** Other generated components. */
- components: Set<string>
- icons: boolean
-}
-
/** The Iconify component, named apart from any component the design calls `Icon`. */
const ICONIFY = 'IconifyIcon'
/** `defaultChecked`: Radix's uncontrolled value, which a nested control starts from. */
const defaultOf = (model: string) => `default${upperFirst(model)}`
+/** A reference's prop value: a bare name for true, `{false}`, or a string. */
+function referenceValue(value: string | boolean): es.SyntaxNode | null {
+ if (value === true) return null
+ if (value === false) return jsx.container(jsx.literal(false))
+ return jsx.stringValue(value)
+}
+
function reference(node: ComponentReference, uses: MarkupUses, depth: number): es.SyntaxNode {
uses.components.add(node.component)
return jsx.element(
node.component,
[
jsx.attribute('className', jsx.container(moduleClass(node.className))),
- ...node.props.map((prop) =>
- jsx.attribute(prop.name, prop.value === true ? null : jsx.stringValue(prop.value))
- ),
+ ...node.props.map((prop) => jsx.attribute(prop.name, referenceValue(prop.value))),
...(node.model ? [jsx.attribute(defaultOf(node.model), null)] : [])
],
[],
@@ -184,9 +166,6 @@ function classNameOf(node: ComponentElement, root: boolean): es.SyntaxNode {
return only ?? es.fill(CLASS_NAMES, { $classes: es.array(classes) })
}
-const numeric = (name: string, value: number) =>
- jsx.attribute(name, jsx.container(es.number(value)))
-
/**
* What a root fixes before the caller's props: a group's single choice and its start, and a
* slider's or progress bar's range and the value it starts at.
@@ -208,7 +187,19 @@ function rootAttributes(uses: MarkupUses): es.SyntaxNode[] {
]
: []),
...(range && uses.kind === 'progress'
- ? [jsx.attribute('value', jsx.container(es.identifier('value'))), numeric('max', range.max)]
+ ? [
+ // Radix takes a value within its range, as the indicator draws one.
+ jsx.attribute(
+ 'value',
+ jsx.container(
+ es.fill(es.parseExpression('Math.min($max, Math.max($min, value))'), {
+ $min: es.number(range.min),
+ $max: es.number(range.max)
+ })
+ )
+ ),
+ numeric('max', range.max)
+ ]
: [])
]
}
@@ -228,71 +219,6 @@ function bindingAttributes(
})
}
-/** What a part of a native or measured control needs: a stepper's step, an indicator's width. */
-function partAttributes(node: ComponentElement, uses: MarkupUses): es.SyntaxNode[] {
- const { range } = uses.component
- if (!range || !node.part) return []
- if (uses.kind === 'progress' && node.part === 'indicator') {
- const style = progressWidth(range, es.identifier('value'))
- return style ? [jsx.attribute('style', jsx.container(style))] : []
- }
- const stepper = uses.kind === 'numberField' ? STEPPERS[node.part] : undefined
- if (!stepper) return []
- return [
- jsx.attribute('aria-label', jsx.stringValue(stepper.label)),
- jsx.attribute('disabled', jsx.container(es.identifier('disabled'))),
- jsx.attribute(
- 'onClick',
- jsx.container(es.parseExpression(`() => commit(value ${stepper.sign} ${String(range.step)})`))
- )
- ]
-}
-
-const NUMBER_INPUT = [
- ['type', jsx.stringValue('number')],
- ['value', jsx.container(es.parseExpression("Number.isNaN(value) ? '' : value"))],
- [
- 'onChange',
- jsx.container(es.parseExpression('(event) => setValue(event.target.valueAsNumber)'))
- ],
- ['onBlur', jsx.container(es.parseExpression('() => commit(value)'))]
-] as const
-
-/** A field's input: a number input that commits within its range, or the input or textarea. */
-function inputElement(className: string, uses: MarkupUses, depth: number): es.SyntaxNode {
- const { component } = uses
- const classAttribute = jsx.attribute('className', jsx.container(moduleClass(className)))
- const { range } = component
- if (range)
- return jsx.element(
- 'input',
- [
- ...NUMBER_INPUT.map(([name, value]) => jsx.attribute(name, value)),
- numeric('min', range.min),
- numeric('max', range.max),
- numeric('step', range.step),
- jsx.attribute('disabled', jsx.container(es.identifier('disabled'))),
- classAttribute
- ],
- [],
- depth
- )
- const start = component.text?.default
- const placeholder = component.text?.placeholder
- return jsx.element(
- INPUT_PROPS[uses.kind] ?? 'input',
- [
- ...(placeholder ? [jsx.attribute('placeholder', jsx.stringValue(placeholder))] : []),
- ...(start ? [jsx.attribute('defaultValue', jsx.stringValue(start))] : []),
- // The input takes the caller's props, such as `name` or `onChange`.
- jsx.spread(es.identifier('props')),
- classAttribute
- ],
- [],
- depth
- )
-}
-
function designElement(node: ComponentElement, uses: MarkupUses, depth: number): es.SyntaxNode {
const kind = uses.kind
const root = node.part === 'root'
@@ -313,23 +239,44 @@ function designElement(node: ComponentElement, uses: MarkupUses, depth: number):
]
// Words alone stay on the element's line, where a line break would add a space.
const only = node.children.length === 1 ? node.children[0]?.type : undefined
- const inline = only === 'text' || only === 'textProp'
+ const inline = !node.slot && (only === 'text' || only === 'textProp')
// Radix puts an accordion item's trigger in a header, which carries the heading level.
const header = kind === 'accordionItem' && node.part === 'trigger'
+ const childDepth = depth + (header ? 2 : 1)
+ const children = node.children.map((child) => element(child, uses, childDepth))
const drawn = jsx.element(
tagOf(node, kind),
attributes,
- node.children.map((child) => element(child, uses, depth + (header ? 2 : 1))),
+ node.slot ? [slotContent(node.slot, children, childDepth)] : children,
depth + (header ? 1 : 0),
inline
)
- if (!header) return drawn
- return jsx.element(
- `${PRIMITIVE('Accordion')}.Header`,
- [jsx.attribute('style', HEADING_STYLE)],
- [drawn],
- depth
- )
+ const shown = header
+ ? jsx.element(
+ `${PRIMITIVE('Accordion')}.Header`,
+ [jsx.attribute('style', HEADING_STYLE)],
+ [drawn],
+ depth
+ )
+ : drawn
+ return node.shownBy ? whenShown(node.shownBy, shown) : shown
+}
+
+const LOGICAL = (operator: '&&' | '??', left: es.SyntaxNode, right: es.SyntaxNode) => ({
+ type: 'LogicalExpression',
+ operator,
+ left,
+ right
+})
+
+/** `{content ?? <>…</>}`: what the caller passes for a slot, or the design's content. */
+function slotContent(slot: string, children: es.SyntaxNode[], depth: number): es.SyntaxNode {
+ return jsx.container(LOGICAL('??', es.identifier(slot), jsx.fragment(children, depth)))
+}
+
+/** `{showIcon && <…/>}`: a layer a boolean prop shows. */
+function whenShown(prop: string, drawn: es.SyntaxNode): es.SyntaxNode {
+ return jsx.container(LOGICAL('&&', es.identifier(prop), drawn))
}
const MODULE = es.parseModule(dedent`
@@ -373,9 +320,11 @@ const OWN_PROPS: Partial<Record<GeneratedKind, string>> = {
}
/** The root's own props, or a single choice group's. */
-function rootPropsType(kind: GeneratedKind): es.SyntaxNode {
+function rootPropsType(kind: GeneratedKind, tag: string): es.SyntaxNode {
const own = OWN_PROPS[kind]
if (own) return es.parseType(own)
+ // A component without a behaviour takes its root element's props.
+ if (kind === 'plain') return es.parseType(`ComponentProps<'${tag}'>`)
const radix = RADIX[kind]
if (!radix) return es.parseType("ComponentProps<'button'>")
const single = SINGLE_PROPS[kind]
@@ -390,8 +339,9 @@ function rootPropsType(kind: GeneratedKind): es.SyntaxNode {
/** The root's own props, extended with the component's variant props when it has any. */
function propsType(component: ComponentModel): es.SyntaxNode {
- const base = rootPropsType(component.kind)
- if (component.props.length === 0 && component.texts.length === 0) return base
+ const base = rootPropsType(component.kind, component.tree.tag)
+ const own = [component.props, component.texts, component.booleans, component.slots]
+ if (own.every((list) => list.length === 0)) return base
return {
type: 'TSIntersectionType',
types: [
@@ -406,32 +356,22 @@ function propsType(component: ComponentModel): es.SyntaxNode {
text.name,
es.parseType('string'),
true
+ ]),
+ ...component.booleans.map((prop): [string, es.SyntaxNode, boolean] => [
+ prop.name,
+ es.parseType('boolean'),
+ true
+ ]),
+ ...component.slots.map((slot): [string, es.SyntaxNode, boolean] => [
+ slot.name,
+ es.parseType('ReactNode'),
+ true
])
])
]
}
}
-/** A destructured prop, with the default it takes when the caller leaves it out. */
-interface Parameter {
- name: string
- default?: es.SyntaxNode
-}
-
-/** Props a kind reads itself: a progress bar's value, a number field's start and changes. */
-function kindParameters(component: ComponentModel): Parameter[] {
- const { range } = component
- if (component.kind === 'progress' && range)
- return [{ name: 'value', default: es.number(range.default) }]
- if (component.kind === 'numberField' && range)
- return [
- { name: 'defaultValue', default: es.number(range.default) },
- { name: 'onValueChange' },
- { name: 'disabled' }
- ]
- return []
-}
-
/**
* `{ size = 'Small', label = 'Save', ...props }`: variant and text props with their defaults,
* kept off the root, and the rest passed on.
@@ -442,7 +382,13 @@ function parameters(component: ComponentModel): es.SyntaxNode {
...[...component.props, ...component.texts].map((prop) => ({
name: prop.name,
default: es.string(prop.default)
- }))
+ })),
+ ...component.booleans.map((prop) => ({
+ name: prop.name,
+ default: es.parseExpression(String(prop.default))
+ })),
+ // Slots are kept off the root too, which would otherwise get them as attributes.
+ ...component.slots.map((slot) => ({ name: slot.name }))
]
if (own.length === 0) return es.identifier('props')
return {
@@ -465,32 +411,16 @@ function parameters(component: ComponentModel): es.SyntaxNode {
}
/**
- * A number field's value: typed freely, and settled within its range when it loses focus or a
- * stepper moves it, which is when the caller hears of it.
+ * `import { useState, type ComponentProps, type ReactNode } from 'react'` with only what the
+ * component uses: a number field's state, its root's props, and its slots' content.
*/
-const NUMBER_STATE = (range: { min: number; max: number }) =>
- es.fill(
- es.parseModule(dedent`
- const [value, setValue] = useState(defaultValue)
- const commit = (next: number) => {
- const settled = Number.isNaN(next) ? $min : Math.min($max, Math.max($min, next))
- setValue(settled)
- onValueChange?.(settled)
- }
- `),
- { $min: es.number(range.min), $max: es.number(range.max) }
- ).body
-
-const REACT_STATE_IMPORT = es.parseModule(
- "import { useState, type ComponentProps } from 'react'"
-).body
-
-/** The component function's statements before it returns, such as a number field's state. */
-function prepend(declaration: es.SyntaxNode | undefined, statements: es.SyntaxNode[]): void {
- const fn = es.child(declaration, 'declaration')
- const body = es.child(fn, 'body')
- if (!body || statements.length === 0) return
- body.body = [...statements, ...es.children(body, 'body')]
+function reactImport(uses: { state: boolean; props: boolean; slots: boolean }): es.SyntaxNode[] {
+ const types = [...(uses.props ? ['ComponentProps'] : []), ...(uses.slots ? ['ReactNode'] : [])]
+ if (!uses.state && types.length === 0) return []
+ const specifiers = uses.state
+ ? ['useState', ...types.map((name) => `type ${name}`)].join(', ')
+ : types.join(', ')
+ return es.parseModule(`import ${uses.state ? '' : 'type '}{ ${specifiers} } from 'react'`).body
}
/**
@@ -539,7 +469,7 @@ export const reactComponent: ComponentGenerator = async (component) => {
}).body
)
]
- const [typeImport, stylesImport, ...rest] = es.fill(MODULE, {
+ const [, stylesImport, ...rest] = es.fill(MODULE, {
$styles: es.string(`./${stylesPath}`),
$Props: es.identifier(`${component.name}Props`),
$Type: propsType(component),
@@ -550,12 +480,16 @@ export const reactComponent: ComponentGenerator = async (component) => {
const state =
component.kind === 'numberField' && component.range ? NUMBER_STATE(component.range) : []
prepend(rest.at(-1), state)
- // A single choice group's props come from Radix's own type, not `ComponentProps`.
- const reactImport = state.length > 0 ? REACT_STATE_IMPORT : [typeImport]
+ const react = reactImport({
+ state: state.length > 0,
+ // A single choice group's props come from Radix's own type, not `ComponentProps`.
+ props: !SINGLE_PROPS[component.kind],
+ slots: component.slots.length > 0
+ })
const program = {
type: 'Program',
sourceType: 'module',
- body: [...(SINGLE_PROPS[component.kind] ? [] : reactImport), ...imports, stylesImport, ...rest]
+ body: [...react, ...imports, stylesImport, ...rest]
}
const { css } = await stateStylesToCSS(component.styles)
const model = component.model
diff --git a/packages/dom-css/src/export/components/react/shared.ts b/packages/dom-css/src/export/components/react/shared.ts
new file mode 100644
index 000000000..cd6133260
--- /dev/null
+++ b/packages/dom-css/src/export/components/react/shared.ts
@@ -0,0 +1,29 @@
+import { es, jsx } from '@open-pencil/emit'
+
+import type { ComponentModel, GeneratedKind } from '../model'
+
+export const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
+
+/** `styles.thumb`, or `styles['switch-thumb']` for a class that isn't an identifier. */
+export function moduleClass(className: string): es.SyntaxNode {
+ return {
+ type: 'MemberExpression',
+ object: es.identifier('styles'),
+ property: IDENTIFIER.test(className) ? es.identifier(className) : es.string(className),
+ computed: !IDENTIFIER.test(className),
+ optional: false
+ }
+}
+
+/** What a component's markup uses, which its module imports. */
+export interface MarkupUses {
+ component: ComponentModel
+ kind: GeneratedKind
+ choice: ComponentModel['choice']
+ /** Other generated components. */
+ components: Set<string>
+ icons: boolean
+}
+
+export const numeric = (name: string, value: number) =>
+ jsx.attribute(name, jsx.container(es.number(value)))
diff --git a/packages/dom-css/src/export/components/references.ts b/packages/dom-css/src/export/components/references.ts
index a19677707..f06b76774 100644
--- a/packages/dom-css/src/export/components/references.ts
+++ b/packages/dom-css/src/export/components/references.ts
@@ -14,12 +14,13 @@ import {
type SceneNode
} from '@open-pencil/scene-graph'
+import { drawsAsMain } from './drawn'
import type { ComponentModel } from './model'
/** A prop a reference sets on the component it uses: a variant or text value, or `disabled`. */
export interface ReferenceProp {
name: string
- value: string | true
+ value: string | boolean
}
/**
@@ -50,7 +51,7 @@ export interface IconReference {
* a layer keeps its own look and state styles; the parent only places it.
*/
const PLACEMENT =
- /^(position|inset|left|top|right|bottom|(min-|max-)?(width|height)|margin(-.+)?|flex(-.+)?|align-self|justify-self|order|grid-(area|column|row)(-.+)?|transform(-origin)?|rotate|translate|scale|z-index)$/
+ /^(position|inset|left|top|right|bottom|(min-|max-)?(width|height)|margin(-.+)?|flex(-(grow|shrink|basis))?|align-self|justify-self|order|grid-(area|column|row)(-.+)?|transform(-origin)?|rotate|translate|scale|z-index)$/
/** Whether a declaration places a layer rather than drawing it. */
export const isPlacement = (property: string) => PLACEMENT.test(property)
@@ -132,6 +133,13 @@ export function referenceValues(
const value = shownText(graph, instance, text.id)
if (value !== undefined && value !== text.default) props.push({ name: text.name, value })
}
+ for (const prop of component.booleans) {
+ const assignments = instance.componentPropertyAssignments
+ const value = Object.hasOwn(assignments, prop.id)
+ ? assignments[prop.id] === 'true'
+ : prop.default
+ if (value !== prop.default) props.push({ name: prop.name, value })
+ }
return { props, model }
}
@@ -156,7 +164,10 @@ function usedLayer(
.find((found) => found !== undefined && layerKind(graph, found) === element.kind)
if (!node) return null
const main = node.type === 'INSTANCE' ? instanceMainComponent(graph, node) : undefined
- const component = main ? references.get(ownerId(graph, main)) : undefined
+ // An instance changed beyond its properties draws its own layers, which the component's
+ // props could not reproduce.
+ const component =
+ main && drawsAsMain(graph, node, main) ? references.get(ownerId(graph, main)) : undefined
if (component)
return {
type: 'reference',
diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.ts
index 0b5984109..9b87ca6b8 100644
--- a/packages/dom-css/src/export/components/vue.ts
+++ b/packages/dom-css/src/export/components/vue.ts
@@ -11,6 +11,7 @@ import { claimName } from '../storybook/names'
import { progressWidth } from './fields'
import type {
ComponentBinding,
+ ComponentElement,
ComponentGenerator,
ComponentModel,
ComponentNode,
@@ -68,7 +69,9 @@ const REKA: Record<
},
// Reka has no text field; the root is the design's own element around a native input.
textField: { parts: {} },
- textarea: { parts: {} }
+ textarea: { parts: {} },
+ // A component without a behaviour is the design's own elements.
+ plain: { parts: {} }
}
/** Kinds whose two-way value is their input's, which binds it rather than the root. */
@@ -161,7 +164,6 @@ interface TemplateUses {
/** The Iconify component, named apart from any component the design calls `Icon`. */
const ICONIFY = 'IconifyIcon'
-const TRUE = es.parseExpression('true')
function reference(node: ComponentReference, uses: TemplateUses): vue.VueNode {
uses.components.add(node.component)
@@ -172,13 +174,54 @@ function reference(node: ComponentReference, uses: TemplateUses): vue.VueNode {
return vue.element(node.component, [
vue.attribute('class', node.className),
...node.props.map((prop) =>
- prop.value === true ? vue.bound(prop.name, TRUE) : vue.attribute(prop.name, prop.value)
+ typeof prop.value === 'boolean'
+ ? vue.bound(prop.name, es.parseExpression(String(prop.value)))
+ : vue.attribute(prop.name, prop.value)
),
// The control stays operable, starting from the value the design draws.
...(model && node.model ? [vue.model(identifier(model), node.model)] : [])
])
}
+/** A design element's attributes: what shows it, its part's own, the design's, and bindings. */
+function elementAttributes(
+ node: ComponentElement,
+ uses: TemplateUses,
+ { native, button }: { native: boolean; button: boolean }
+): vue.VueAttribute[] {
+ const root = node.part === 'root'
+ return [
+ ...(node.shownBy ? [vue.renderIf(identifier(node.shownBy))] : []),
+ ...(button ? [vue.attribute('type', 'button')] : []),
+ ...(root ? [...(ROOT_ATTRIBUTES[uses.kind] ?? []), ...rangeAttributes(uses.component)] : []),
+ ...(uses.kind === 'progress' && node.part === 'indicator' ? progressStyle(uses.component) : []),
+ ...Object.entries(omit(node.attrs, ['class'])).map(([name, value]) =>
+ vue.attribute(name, value)
+ ),
+ vue.attribute('class', compact([node.attrs.class, node.className]).join(' ')),
+ ...(node.value === undefined ? [] : [vue.attribute('value', node.value)]),
+ ...node.bindings.flatMap((binding) => bindingAttributes(binding, uses, native))
+ ]
+}
+
+function designElement(node: ComponentElement, uses: TemplateUses): vue.VueNode {
+ const reka = node.part ? REKA[uses.kind].parts[node.part] : undefined
+ if (reka) uses.reka.add(reka)
+ const native = node.part === 'root' && !reka
+ const button = native && uses.kind === 'button'
+ const children = node.children.map((child) => templateNode(child, uses))
+ const element = vue.element(
+ reka ?? (button ? 'button' : node.tag),
+ elementAttributes(node, uses, { native, button }),
+ // A slot frame shows what the caller passes, or the design's content.
+ node.slot ? [vue.element('slot', [vue.attribute('name', node.slot)], children)] : children
+ )
+ // Reka puts an accordion item's trigger in a header, which carries the heading level.
+ if (uses.kind !== 'accordionItem' || node.part !== 'trigger') return element
+ uses.reka.add('AccordionHeader')
+ return vue.element('AccordionHeader', [vue.attribute('style', HEADING_STYLE)], [element])
+}
+
function templateNode(node: ComponentNode, uses: TemplateUses): vue.VueNode {
if (node.type === 'text') return vue.text(node.value)
if (node.type === 'textProp') return vue.interpolation(identifier(node.name))
@@ -191,32 +234,7 @@ function templateNode(node: ComponentNode, uses: TemplateUses): vue.VueNode {
vue.attribute('class', node.className)
])
}
- const reka = node.part ? REKA[uses.kind].parts[node.part] : undefined
- if (reka) uses.reka.add(reka)
- const root = node.part === 'root'
- const native = root && !reka
- const button = native && uses.kind === 'button'
- const element = vue.element(
- reka ?? (button ? 'button' : node.tag),
- [
- ...(button ? [vue.attribute('type', 'button')] : []),
- ...(root ? [...(ROOT_ATTRIBUTES[uses.kind] ?? []), ...rangeAttributes(uses.component)] : []),
- ...(uses.kind === 'progress' && node.part === 'indicator'
- ? progressStyle(uses.component)
- : []),
- ...Object.entries(omit(node.attrs, ['class'])).map(([name, value]) =>
- vue.attribute(name, value)
- ),
- vue.attribute('class', compact([node.attrs.class, node.className]).join(' ')),
- ...(node.value === undefined ? [] : [vue.attribute('value', node.value)]),
- ...node.bindings.flatMap((binding) => bindingAttributes(binding, uses, native))
- ],
- node.children.map((child) => templateNode(child, uses))
- )
- // Reka puts an accordion item's trigger in a header, which carries the heading level.
- if (uses.kind !== 'accordionItem' || node.part !== 'trigger') return element
- uses.reka.add('AccordionHeader')
- return vue.element('AccordionHeader', [vue.attribute('style', HEADING_STYLE)], [element])
+ return designElement(node, uses)
}
function propsType(component: ComponentModel): es.SyntaxNode {
@@ -229,12 +247,20 @@ function propsType(component: ComponentModel): es.SyntaxNode {
// A group's item always stands for a value, which has no default.
if (component.valueProp) members.unshift(['value', es.parseType('string'), false])
for (const text of component.texts) members.push([text.name, es.parseType('string'), true])
+ for (const prop of component.booleans) members.push([prop.name, es.parseType('boolean'), true])
return es.objectType(members)
}
/** `defineProps`, with `withDefaults` when any prop has a default to give. */
+/** Whether any prop has a default to give: `disabled`, a variant, a text, or a boolean. */
+const hasDefaults = (component: ComponentModel) =>
+ component.disabled ||
+ component.props.length > 0 ||
+ component.texts.length > 0 ||
+ component.booleans.length > 0
+
function propsDeclaration(component: ComponentModel): es.SyntaxNode[] {
- const optional = component.disabled || component.props.length > 0 || component.texts.length > 0
+ const optional = hasDefaults(component)
return optional
? es.fill(PROPS, { $Props: propsType(component), $defaults: propsDefaults(component) }).body
: es.fill(REQUIRED_PROPS, { $Props: propsType(component) }).body
@@ -244,7 +270,10 @@ function propsDefaults(component: ComponentModel): es.SyntaxNode {
return es.object([
...(component.disabled ? [['disabled', es.parseExpression('false')] as const] : []),
...component.props.map((prop) => [prop.name, es.string(prop.default)] as const),
- ...component.texts.map((text) => [text.name, es.string(text.default)] as const)
+ ...component.texts.map((text) => [text.name, es.string(text.default)] as const),
+ ...component.booleans.map(
+ (prop) => [prop.name, es.parseExpression(String(prop.default))] as const
+ )
])
}
@@ -326,13 +355,7 @@ function modelDeclaration(component: ComponentModel, uses: TemplateUses): es.Syn
}
function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {
- const props =
- component.valueProp ||
- component.disabled ||
- component.props.length > 0 ||
- component.texts.length > 0
- ? propsDeclaration(component)
- : []
+ const props = component.valueProp || hasDefaults(component) ? propsDeclaration(component) : []
const refs = uses.models.flatMap(
(item) => es.fill(MODEL_REF, { $name: identifier(item.name) }).body
)
@@ -352,6 +375,8 @@ export const vueComponent: ComponentGenerator = async (component) => {
const taken = new Set([
...component.props.map((prop) => prop.name),
...component.texts.map((text) => text.name),
+ ...component.booleans.map((prop) => prop.name),
+ ...component.slots.map((slot) => slot.name),
...(component.model ? [component.model] : []),
'disabled'
])
diff --git a/packages/dom-css/src/export/storybook/component.ts b/packages/dom-css/src/export/storybook/component.ts
index 0c33d98a2..c04159782 100644
--- a/packages/dom-css/src/export/storybook/component.ts
+++ b/packages/dom-css/src/export/storybook/component.ts
@@ -163,7 +163,11 @@ function restArgs(
...(model && rest ? [[model, rest] as [string, es.SyntaxNode]] : []),
...(component.disabled ? [['disabled', 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.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
+ ])
]
}
@@ -207,7 +211,8 @@ function argTypes(component: ComponentModel, model: string | null, list: boolean
...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])
])
}
@@ -217,10 +222,13 @@ function stories(
model: string | null,
list: boolean
): { name: string; story: es.SyntaxNode }[] {
- const taken = new Set<string>()
+ // 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 = taken.size > 0
+ const variant = !first
+ first = false
return {
name: claimName(identifierName(label, 'Story'), taken),
story: es.object([
@@ -259,6 +267,12 @@ function stories(
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]
+ ])
)
]
}
diff --git a/packages/dom-css/src/export/storybook/export.ts b/packages/dom-css/src/export/storybook/export.ts
index fb0d36648..57df3c142 100644
--- a/packages/dom-css/src/export/storybook/export.ts
+++ b/packages/dom-css/src/export/storybook/export.ts
@@ -1,5 +1,8 @@
+import { PLACEMENT } from '#dom-css/behaviours/states/layers'
+import { tokenStylesheet } from '#dom-css/tokens/stylesheet'
import type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'
import { compact } from 'es-toolkit/array'
+import { omit } from 'es-toolkit/object'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
@@ -61,10 +64,10 @@ export interface ExportStorybookOptions {
*/
fonts?: WebFontFaceResolver
/**
- * The folder the font files go in, which must differ for each document exported into the
- * same place; `fonts/<document>` by default.
+ * The folder a document's shared files go in, its fonts and design tokens, which must differ
+ * for each document exported into the same place; `openpencil/<document>` by default.
*/
- fontFolder?: string
+ folder?: string
}
/** How a story file shows its component: every variant, Default alone, a gallery, or not. */
@@ -86,6 +89,11 @@ export interface StoryTarget {
export interface StoryPlan {
stories?: StoryMode
title?: string
+ /**
+ * Whether a Vue or React export generates a component for the file, as it does by default,
+ * or keeps static stories of its variants.
+ */
+ generate?: boolean
}
export interface StorybookFile extends ExportHTMLFile {
@@ -127,7 +135,8 @@ function designLink(
/** Story export names, which also name the design images. */
function storyNames(group: StoryGroup): string[] {
- const taken = new Set<string>()
+ // Named apart from the module's own types, `Story` and `Args`.
+ const taken = new Set(['story', 'args'])
const key = (name: string) => name.toLowerCase()
return group.variants.map((variant, index) => {
// The first variant, the one the design shows at rest, is the file's Default story.
@@ -142,14 +151,19 @@ function storyLabel(group: StoryGroup, values: string[], index: number): string
}
/**
- * A variant drawn on its own, as a story shows it: its root hugs its content where the design
- * gives it no width, rather than filling the story's canvas, and sizes include padding and
+ * A variant drawn on its own, as a story shows it: its root, placed nowhere in particular, hugs
+ * its content where the design gives it no width, rather than filling the story's canvas, and sizes include padding and
* borders, which no page reset around the story says.
*/
function standalone(document: DesignDocument): DesignDocument {
const visit = (node: DesignNode, root: boolean) => {
if (node.type !== 'element') return
- const style: DesignStyleDeclaration = { ...node.inlineStyle }
+ // A variant's root drops where the set places it, which is not where the story draws it,
+ // and stays the containing block of the layers placed inside it.
+ const placed = root && Object.hasOwn(node.inlineStyle ?? {}, 'position')
+ const style: DesignStyleDeclaration = root
+ ? { ...omit({ ...node.inlineStyle }, PLACEMENT), ...(placed ? { position: 'relative' } : {}) }
+ : { ...node.inlineStyle }
const has = (property: string) => Object.hasOwn(style, property)
if ((has('width') || has('height')) && !has('box-sizing')) style['box-sizing'] = 'border-box'
if (root && !has('width')) style.width = 'fit-content'
@@ -209,6 +223,7 @@ interface StoryEntry {
group: StoryGroup
file: string
mode: Exclude<StoryMode, 'none'>
+ generate: boolean
}
/**
@@ -243,7 +258,8 @@ function storyEntries(
const file = claimName(identifierName(group.name, 'Component'), takenFiles, {
key: (name) => name.toLowerCase()
})
- if (!pageId || page.id === pageId) entries.push({ page, group, file, mode })
+ const generate = planned?.generate ?? true
+ if (!pageId || page.id === pageId) entries.push({ page, group, file, mode, generate })
}
}
return entries
@@ -276,8 +292,8 @@ function generatedModels(
itemName: itemNames.get(file)
})
const alone = new Map<string, ComponentModel>()
- for (const { group, file } of entries) {
- const component = group.set && model(group.set, file)
+ for (const { group, file, generate } of entries) {
+ const component = generate && group.set && model(group.set, file)
if (group.set && component) alone.set(group.set.id, component)
}
const models = new Map<string, ComponentModel>()
@@ -288,17 +304,25 @@ function generatedModels(
return models
}
+/** The folder a document's shared files go in, unless the caller names one. */
+function documentFolder(graph: SceneGraph, options: ExportStorybookOptions): string {
+ if (options.folder) return options.folder
+ const page = options.pageId ? graph.getNode(options.pageId)?.name : undefined
+ const named = compact([options.document ?? 'document', page]).map((name) => storyId(name))
+ return `openpencil/${named.join('-')}`
+}
+
/**
- * The font files the entries' text uses, in a folder of the document's own so documents
- * exported side by side keep theirs apart, and the stylesheet that loads them. Faces load
+ * The font files the entries' text uses, and the stylesheet that loads them. Faces load
* before text draws, so a story never shows a fallback font first.
*/
async function storyFonts(
graph: SceneGraph,
entries: readonly StoryEntry[],
- options: ExportStorybookOptions
-): Promise<{ stylesheet: string; files: ExportHTMLFile[] } | null> {
- if (!options.fonts) return null
+ options: ExportStorybookOptions,
+ folder: string
+): Promise<ExportHTMLFile[]> {
+ if (!options.fonts) return []
const requests = new Map<string, WebFontFaceRequest>()
for (const { group } of entries)
for (const variant of group.variants)
@@ -306,15 +330,21 @@ async function storyFonts(
sceneNodeToDesignDocument(graph, variant.node.id, { includeSourceIds: false })
))
requests.set(`${request.family}|${request.weight}|${request.style ?? 'normal'}`, request)
- if (requests.size === 0) return null
- const page = options.pageId ? graph.getNode(options.pageId)?.name : undefined
- const named = compact([options.document ?? 'document', page]).map((name) => storyId(name))
- const folder = options.fontFolder ?? `fonts/${named.join('-')}`
- const assets = await options.fonts([...requests.values()], folder)
- if (assets.length === 0) return null
+ if (requests.size === 0) return []
+ const assets = await options.fonts([...requests.values()], `${folder}/fonts`)
+ if (assets.length === 0) return []
const css = await fontFaceStylesheet(assets, { from: folder, display: 'block' })
- const stylesheet = `${folder}/fonts.css`
- return { stylesheet, files: [...assets, { path: stylesheet, content: css }] }
+ return [...assets, { path: `${folder}/fonts.css`, content: css }]
+}
+
+/**
+ * The document's design tokens as custom properties, which stories' styles refer to as
+ * `var(--…)` wherever the design binds a variable, so they resolve as the design draws them.
+ */
+async function storyTokens(graph: SceneGraph, folder: string): Promise<ExportHTMLFile[]> {
+ if (graph.variables.size === 0) return []
+ const { css } = await tokenStylesheet(graph, { format: 'css' })
+ return css ? [{ path: `${folder}/tokens.css`, content: css }] : []
}
/**
@@ -332,10 +362,15 @@ export async function exportStorybook(
files.push({ path, content, page: page.name })
const entries = storyEntries(graph, options)
- const fonts = await storyFonts(graph, entries, options)
+ const folder = documentFolder(graph, options)
+ const shared = [
+ ...(await storyFonts(graph, entries, options, folder)),
+ ...(await storyTokens(graph, folder))
+ ]
const firstPage = entries.at(0)?.page
- if (fonts && firstPage) for (const file of fonts.files) add(firstPage, file.path, file.content)
- const styles = fonts ? [`./${fonts.stylesheet}`] : []
+ if (firstPage) for (const file of shared) add(firstPage, file.path, file.content)
+ // Every story file loads the document's fonts and tokens.
+ const styles = shared.filter((file) => file.path.endsWith('.css')).map((file) => `./${file.path}`)
const generate = GENERATORS[framework]
const models = generate ? generatedModels(graph, entries, options.vectorElement) : new Map()
diff --git a/packages/dom-css/src/export/storybook/groups.ts b/packages/dom-css/src/export/storybook/groups.ts
index c626356b2..e6620e034 100644
--- a/packages/dom-css/src/export/storybook/groups.ts
+++ b/packages/dom-css/src/export/storybook/groups.ts
@@ -1,7 +1,7 @@
import { behaviourArgs } from '#dom-css/behaviours/args'
import { uniq } from 'es-toolkit/array'
-import { readBehaviour, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import { restingVariant, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'
import type { StoryProp } from './module'
@@ -22,8 +22,8 @@ export interface StoryGroup {
/** Layer the story file links to, when the group has a layer of its own. */
linkNode?: string
/**
- * The component set, or standalone component with a behaviour, the group shows, which may
- * generate a component of its own.
+ * The component set or standalone component the group shows, which may generate a component
+ * of its own; slash-named components grouped together have none.
*/
set?: SceneNode
}
@@ -54,13 +54,18 @@ function componentSetGroup(
set: SceneNode
): StoryGroup {
const definitions = set.componentPropertyDefinitions.filter((def) => def.type === 'VARIANT')
- const variants = graph
+ // The variant at its default values opens the file as its Default story.
+ const first = restingVariant(graph, set)
+ const components = graph
.getChildren(set.id)
.filter((child) => child.type === 'COMPONENT' && isExported(child))
- .map((component) => ({
- values: definitions.map((def) => component.componentPropertyValues[def.name] ?? ''),
- node: component
- }))
+ const variants = [
+ ...components.filter((component) => component === first),
+ ...components.filter((component) => component !== first)
+ ].map((component) => ({
+ values: definitions.map((def) => component.componentPropertyValues[def.name] ?? ''),
+ node: component
+ }))
const args = behaviourArgs(graph, set)
const props = definitions.map((def, index): StoryProp => {
const options = uniq([
@@ -96,8 +101,8 @@ function componentGroup(page: SceneNode, section: string, component: SceneNode):
props: [],
variants: [{ values: [], node: component }],
linkNode: component.name,
- // A standalone component with a behaviour, such as tabs, may generate a component too.
- ...(readBehaviour(component) ? { set: component } : {})
+ // A standalone component generates a component of its own too, as a set does.
+ set: component
}
}
diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.ts
index f6f0b44fa..97a28f291 100644
--- a/packages/dom-css/tests/behaviours/fixtures.ts
+++ b/packages/dom-css/tests/behaviours/fixtures.ts
@@ -657,3 +657,56 @@ export function textareaComponent() {
})
return { graph: fixture.graph, set: fixture.graph.getNode(fixture.set.id) ?? fixture.set }
}
+
+/**
+ * A component set without a behaviour: a badge in two tones with a label text property, an
+ * icon a boolean property shows, hidden at rest, and a slot whose content defaults to a note.
+ */
+export function plainBadgeSet() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const set = graph.createNode('COMPONENT_SET', page, {
+ name: 'Badge',
+ componentPropertyDefinitions: [
+ {
+ id: 'tone',
+ name: 'Tone',
+ type: 'VARIANT',
+ defaultValue: 'Neutral',
+ variantOptions: ['Neutral', 'Danger']
+ },
+ { id: 'label', name: 'Label', type: 'TEXT', defaultValue: 'New' },
+ { id: 'icon', name: 'Icon', type: 'BOOLEAN', defaultValue: 'false' },
+ { id: 'extra', name: 'Extra', type: 'SLOT', defaultValue: '' }
+ ]
+ })
+ for (const tone of ['Neutral', 'Danger']) {
+ const variant = graph.createNode('COMPONENT', set.id, {
+ name: `Tone=${tone}`,
+ componentPropertyValues: { Tone: tone },
+ width: 80,
+ height: 24,
+ fills: tone === 'Danger' ? COLORS.on : COLORS.off
+ })
+ graph.createNode('FRAME', variant.id, {
+ name: 'Dot',
+ width: 8,
+ height: 8,
+ visible: false,
+ componentPropertyReferences: [{ propertyId: 'icon', field: 'VISIBLE' }]
+ })
+ graph.createNode('TEXT', variant.id, {
+ name: 'Label',
+ text: 'New',
+ componentPropertyReferences: [{ propertyId: 'label', field: 'TEXT' }]
+ })
+ const extra = graph.createNode('FRAME', variant.id, {
+ name: 'Extra',
+ width: 20,
+ height: 20,
+ componentPropertyReferences: [{ propertyId: 'extra', field: 'SLOT_CONTENT' }]
+ })
+ graph.createNode('TEXT', extra.id, { name: 'Note', text: 'Note' })
+ }
+ return { graph, set: graph.getNode(set.id) ?? set }
+}
diff --git a/packages/dom-css/tests/behaviours/states.test.ts b/packages/dom-css/tests/behaviours/states.test.ts
index b362ab323..c5880d70d 100644
--- a/packages/dom-css/tests/behaviours/states.test.ts
+++ b/packages/dom-css/tests/behaviours/states.test.ts
@@ -5,11 +5,16 @@ import {
stateStyles,
stateStylesToCSS,
stateStylesToTailwind,
+ type StateCondition,
type StateElement,
+ type StateRule,
type StateStyles
} from '#dom-css/behaviours/states/index'
+import { allElements } from '#dom-css/behaviours/states/layers'
import { compileTailwindCSS } from '#dom-css/import/tailwind'
import type { DesignElement, DesignNode } from '#dom-css/types'
+import { sortBy } from 'es-toolkit/array'
+import { isEqual } from 'es-toolkit/predicate'
import { emptyBehaviour } from '@open-pencil/scene-graph'
@@ -136,6 +141,63 @@ describe('state styles', () => {
})
})
+test('rests on the top-left variant when the document records no default values', () => {
+ const fixture = buttonSet()
+ const { graph, set } = fixture
+ graph.updateNode(set.id, {
+ componentPropertyDefinitions: set.componentPropertyDefinitions.map((definition) => ({
+ ...definition,
+ defaultValue: ''
+ }))
+ })
+ // The small default variant sits in the top-left corner; the others below it.
+ const rest = graph
+ .getChildren(set.id)
+ .find((variant) => variant.name === 'Size=Small, Interaction=Default')
+ for (const [index, variant] of graph.getChildren(set.id).entries())
+ graph.updateNode(variant.id, { x: 0, y: variant === rest ? 0 : 100 + index * 50 })
+ expect(stateStyles(graph, graph.getNode(set.id) ?? set)?.restId).toBe(rest?.id)
+})
+
+/**
+ * The words a variant shows: each text layer's display once every rule its conditions meet
+ * applies, fewer conditions first, as the stylesheet orders them and the cascade resolves them.
+ */
+function shownWords(root: StateElement, conditions: StateCondition[]): string[] {
+ const meets = (rule: StateRule) =>
+ rule.conditions.every((condition) => conditions.some((other) => isEqual(condition, other)))
+ return allElements(root).flatMap((element) => {
+ const display = sortBy(element.rules.filter(meets), [(rule) => rule.conditions.length]).reduce(
+ (value, rule) => rule.style.display ?? value,
+ element.base.display
+ )
+ const words = element.children.find((child) => child.type === 'text')
+ return words && display !== 'none' ? [words.text] : []
+ })
+}
+
+test('shows each combined variant its own words, not those a part of it shows', () => {
+ const { graph, set } = componentSet(
+ 'Field',
+ { Size: ['Small', 'Large'], State: ['Rest', 'Done'] },
+ emptyBehaviour('button'),
+ (graph, variant, { Size, State }) => {
+ let text = 'Plain'
+ if (State === 'Done') text = 'Value'
+ else if (Size === 'Large') text = 'Placeholder'
+ graph.createNode('TEXT', variant, { name: 'Words', text })
+ }
+ )
+ const result = stateStyles(graph, set)
+ if (!result) throw new Error('No state styles')
+ const prop = (name: string, value: string): StateCondition => ({ type: 'prop', name, value })
+ expect(shownWords(result.root, [])).toEqual(['Plain'])
+ expect(shownWords(result.root, [prop('Size', 'Large')])).toEqual(['Placeholder'])
+ expect(shownWords(result.root, [prop('State', 'Done')])).toEqual(['Value'])
+ // Large and done meets the rule that shows the large field's placeholder, yet shows its value.
+ expect(shownWords(result.root, [prop('Size', 'Large'), prop('State', 'Done')])).toEqual(['Value'])
+})
+
test('has no state styles when no variant shows the rest state', () => {
// Only the checked variant is drawn; using it as the base would show it checked at rest.
const { graph, set } = componentSet(
diff --git a/packages/dom-css/tests/export/components/react.test.ts b/packages/dom-css/tests/export/components/react.test.ts
index 4a84e9463..78403087c 100644
--- a/packages/dom-css/tests/export/components/react.test.ts
+++ b/packages/dom-css/tests/export/components/react.test.ts
@@ -7,6 +7,7 @@ import {
accordionComponent,
badgeToggleSet,
numberFieldComponent,
+ plainBadgeSet,
progressComponent,
sliderComponent,
textareaComponent,
@@ -92,7 +93,48 @@ async function typeErrors(folder: string, name: string): Promise<string[]> {
const render = (component: ComponentType<Props>, props: Props = {}) =>
renderToStaticMarkup(createElement(component, props))
+describe('generated React plain components', () => {
+ test('take variant, text, boolean, and slot properties as props, and type-check', async () => {
+ const { component, folder } = await generate(plainBadgeSet())
+ expect(await typeErrors(folder, 'Badge')).toEqual([])
+ const rest = render(component)
+ expect(rest).toContain('data-tone="Neutral"')
+ // The icon the design hides at rest is an element only while its boolean is on.
+ const elements = (html: string) => html.match(/<div/g)?.length
+ expect(elements(rest)).toBe(2)
+ expect(elements(render(component, { icon: true }))).toBe(3)
+ expect(render(component, { tone: 'Danger', label: 'Hot' })).toMatch(
+ /data-tone="Danger"[\s\S]*Hot/
+ )
+ // A slot shows the design's content unless the caller passes its own.
+ expect(rest).toContain('Note')
+ const filled = render(component, { extra: createElement('b', null, 'Custom') })
+ expect(filled).toContain('<b>Custom</b>')
+ expect(filled).not.toContain('Note')
+ })
+})
+
describe('generated React form controls', () => {
+ test('import the types a number field with a slot uses, and type-check', async () => {
+ const fixture = numberFieldComponent()
+ const { graph, set } = fixture
+ graph.updateNode(set.id, {
+ componentPropertyDefinitions: [
+ ...set.componentPropertyDefinitions,
+ { id: 'hint', name: 'Hint', type: 'SLOT', defaultValue: '' }
+ ]
+ })
+ const hint = graph.createNode('FRAME', set.id, {
+ name: 'Hint',
+ width: 20,
+ height: 20,
+ componentPropertyReferences: [{ propertyId: 'hint', field: 'SLOT_CONTENT' }]
+ })
+ graph.createNode('TEXT', hint.id, { name: 'Note', text: '?' })
+ const { folder } = await generate(fixture)
+ expect(await typeErrors(folder, 'Quantity')).toEqual([])
+ })
+
test('type-check against Radix and React', async () => {
for (const fixture of [
sliderComponent(),
diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.ts
index 249fa954f..fcb34136e 100644
--- a/packages/dom-css/tests/export/components/vue.test.ts
+++ b/packages/dom-css/tests/export/components/vue.test.ts
@@ -9,6 +9,7 @@ import {
collapsibleSet,
labelledButtonSet,
numberFieldComponent,
+ plainBadgeSet,
progressComponent,
sliderComponent,
textareaComponent,
@@ -224,6 +225,28 @@ const styleOf = (files: { path: string; content: string | Uint8Array }[], path:
)?.[1] ?? ''
)
+describe('generated Vue plain components', () => {
+ test('take variant, text, and boolean properties as props, and slots as slots', async () => {
+ const { component } = await generate(plainBadgeSet())
+ const rest = await render(component)
+ expect(rest).toContain('data-tone="Neutral"')
+ expect(rest).toContain('New')
+ // The icon the design hides at rest shows only while its boolean is on.
+ expect(rest).not.toContain('badge__dot')
+ expect(await render(component, { icon: true })).toContain('badge__dot')
+ expect(await render(component, { tone: 'Danger', label: 'Hot' })).toMatch(
+ /data-tone="Danger"[\s\S]*Hot/
+ )
+ // A slot shows the design's content unless the caller passes its own.
+ expect(rest).toContain('Note')
+ const filled = await renderToString(
+ createSSRApp({ render: () => h(component, {}, { extra: () => h('b', 'Custom') }) })
+ )
+ expect(filled).toContain('<b>Custom</b>')
+ expect(filled).not.toContain('Note')
+ })
+})
+
describe('generated Vue form controls', () => {
test('a slider binds one number within its range, the thumb and range placed by Reka', async () => {
const { files, component } = await generate(sliderComponent())
diff --git a/packages/dom-css/tests/export/storybook/export.test.ts b/packages/dom-css/tests/export/storybook/export.test.ts
index ea1e573d1..cefe361d3 100644
--- a/packages/dom-css/tests/export/storybook/export.test.ts
+++ b/packages/dom-css/tests/export/storybook/export.test.ts
@@ -3,6 +3,7 @@ import { mkdtemp, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { BLUE_500, card, designSystem } from '#dom-css-tests/export/token-fixtures'
import { exportStorybook } from '#dom-css/index'
import { es } from '@open-pencil/emit'
@@ -156,6 +157,20 @@ describe('exportStorybook', () => {
expect(Object.keys(badge).filter((key) => key !== 'default')).toEqual(['Default'])
})
+ it('ships the design tokens its styles refer to, which every story file loads', async () => {
+ const graph = designSystem()
+ const page = graph.addPage('Library')
+ const badge = graph.createNode('COMPONENT', page.id, { name: 'Badge' })
+ card(graph, badge.id, BLUE_500)
+ const files = await exportStorybook(graph, { framework: 'html', document: 'Kit' })
+ const tokens = String(files.find((file) => file.path === 'openpencil/kit/tokens.css')?.content)
+ // The story refers to the variable; the tokens define it.
+ const story = String(files.find((file) => file.path === 'Badge.stories.ts')?.content)
+ expect(story).toContain('var(--color-primary)')
+ expect(tokens).toContain('--color-primary:')
+ expect(importSources(story)).toContain('./openpencil/kit/tokens.css')
+ })
+
it("ships the fonts its text uses in the document's folder, loaded before text draws", async () => {
const { graph } = buttonGraph()
const requested: { family: string; weight: number }[] = []
@@ -176,17 +191,17 @@ describe('exportStorybook', () => {
}
})
expect(requested.map((font) => font.family)).toEqual(['Inter'])
- const css = String(files.find((file) => file.path === 'fonts/kit/fonts.css')?.content)
- expect(files.map((file) => file.path)).toContain('fonts/kit/inter-400.woff2')
- expect(css).toContain('url("inter-400.woff2")')
+ const css = String(files.find((file) => file.path === 'openpencil/kit/fonts.css')?.content)
+ expect(files.map((file) => file.path)).toContain('openpencil/kit/fonts/inter-400.woff2')
+ expect(css).toContain('url("fonts/inter-400.woff2")')
expect(css).toContain('font-display: block')
const story = String(files.find((file) => file.path === 'Button.stories.ts')?.content)
- expect(importSources(story)).toContain('./fonts/kit/fonts.css')
+ expect(importSources(story)).toContain('./openpencil/kit/fonts.css')
// A caller exporting several documents into one place names each one's folder.
const named = await exportStorybook(graph, {
framework: 'html',
- fontFolder: 'fonts/kit-design',
+ folder: 'openpencil/kit-design',
fonts: (fonts, folder) =>
Promise.resolve(
fonts.map((font) => ({
@@ -198,7 +213,7 @@ describe('exportStorybook', () => {
}))
)
})
- expect(named.map((file) => file.path)).toContain('fonts/kit-design/fonts.css')
+ expect(named.map((file) => file.path)).toContain('openpencil/kit-design/fonts.css')
// With no font files found, nothing is written and stories import nothing.
const without = await exportStorybook(graph, {
@@ -206,7 +221,7 @@ describe('exportStorybook', () => {
fonts: () => Promise.resolve([])
})
expect(without.map((file) => file.path)).toEqual(['Button.stories.ts'])
- expect(importSources(String(without[0]?.content))).not.toContain('./fonts/kit/fonts.css')
+ expect(importSources(String(without[0]?.content))).not.toContain('./openpencil/kit/fonts.css')
})
it('gives a component with a behaviour its own props instead of variant selects', async () => {
@@ -310,6 +325,18 @@ describe('exportStorybook', () => {
// The dot is 20px with its border, as the design draws it.
const dot = /<div style="([^"]*width: 20px[^"]*)">/.exec(html)?.[1] ?? ''
expect(dot).toContain('box-sizing: border-box')
+
+ // A set's variant drops where the set places it.
+ const { graph: buttons, page: library } = buttonGraph()
+ for (const [index, variant] of buttons
+ .getChildren(buttons.getChildren(library.id)[0]?.id ?? '')
+ .entries())
+ buttons.updateNode(variant.id, { x: 20 + index * 100, y: 20 })
+ const [set] = await exportStorybook(buttons, { framework: 'html' })
+ const large = (await importStory(String(set?.content))).default.render({ Size: 'Large' })
+ const root = /^<div style="([^"]*)"/.exec(large)?.[1] ?? ''
+ expect(root).not.toMatch(/(^|; )(left|top):/)
+ expect(root).not.toContain('position: absolute')
})
it('groups slash-named components and keeps standalone ones apart', async () => {
@@ -343,10 +370,11 @@ describe('exportStorybook', () => {
expect(story.default.render({ Variant: 'Chip 2' })).toContain('width: 60px')
})
- it('emits framework-specific render wrappers', async () => {
+ it('emits framework-specific render wrappers for components it does not generate', async () => {
const { graph } = buttonGraph()
- const react = String((await exportStorybook(graph, { framework: 'react' }))[0]?.content)
- const vue = String((await exportStorybook(graph, { framework: 'vue' }))[0]?.content)
+ const plan = () => ({ generate: false })
+ const react = String((await exportStorybook(graph, { framework: 'react', plan }))[0]?.content)
+ const vue = String((await exportStorybook(graph, { framework: 'vue', plan }))[0]?.content)
expect(react).toContain("from '@storybook/react-vite'")
expect(react).toContain('dangerouslySetInnerHTML')
diff --git a/packages/emit/src/jsx.ts b/packages/emit/src/jsx.ts
index deb4d946b..ec632eca8 100644
--- a/packages/emit/src/jsx.ts
+++ b/packages/emit/src/jsx.ts
@@ -94,6 +94,16 @@ export function element(
}
}
+/** `<>…</>`: children without an element around them, laid out as an element's are. */
+export function fragment(children: SyntaxNode[], depth: number): SyntaxNode {
+ return {
+ type: 'JSXFragment',
+ openingFragment: { type: 'JSXOpeningFragment' },
+ closingFragment: { type: 'JSXClosingFragment' },
+ children: children.length === 0 ? [] : indented(children, depth)
+ }
+}
+
export function printJSX(node: SyntaxNode): string {
return print(node, tsx({ quotes: 'double' }), { indent: ' ' }).code
}
diff --git a/packages/emit/src/vue.ts b/packages/emit/src/vue.ts
index 4b76fca68..dd0986c49 100644
--- a/packages/emit/src/vue.ts
+++ b/packages/emit/src/vue.ts
@@ -15,6 +15,8 @@ export type VueAttribute =
| { type: 'bound'; name: string; expression: SyntaxNode }
/** `v-model="expression"`, or `v-model:argument` */
| { type: 'model'; argument?: string; expression: SyntaxNode }
+ /** `v-if="expression"`: the element renders only while the expression holds. */
+ | { type: 'if'; expression: SyntaxNode }
export interface VueElement {
type: 'element'
@@ -54,6 +56,8 @@ export const model = (expression: SyntaxNode, argument?: string): VueAttribute =
expression
})
+export const renderIf = (expression: SyntaxNode): VueAttribute => ({ type: 'if', expression })
+
export const element = (
tag: string,
attributes: VueAttribute[] = [],
@@ -71,6 +75,7 @@ function printAttribute(item: VueAttribute): string {
if (item.type === 'static') return `${item.name}="${escapeAttribute(item.value)}"`
const value = escapeAttribute(printExpression(item.expression))
if (item.type === 'bound') return `:${item.name}="${value}"`
+ if (item.type === 'if') return `v-if="${value}"`
return `${item.argument ? `v-model:${item.argument}` : 'v-model'}="${value}"`
}
diff --git a/packages/emit/tests/vue.test.ts b/packages/emit/tests/vue.test.ts
index 1f429c89f..92f26aeb9 100644
--- a/packages/emit/tests/vue.test.ts
+++ b/packages/emit/tests/vue.test.ts
@@ -119,3 +119,14 @@ describe('Vue templates', () => {
expect(descriptor.template?.content.trim()).toBe('<div />')
})
})
+
+describe('conditional elements', () => {
+ test('render with v-if, the condition escaped as an attribute', () => {
+ const node = vue.element('span', [
+ vue.renderIf(es.parseExpression('showIcon && size !== "small"'))
+ ])
+ expect(vue.printTemplate(node)).toBe(
+ '<span v-if="showIcon &amp;&amp; size !== &quot;small&quot;" />'
+ )
+ })
+})
diff --git a/packages/scene-graph/src/components/variants.ts b/packages/scene-graph/src/components/variants.ts
new file mode 100644
index 000000000..c85c51a07
--- /dev/null
+++ b/packages/scene-graph/src/components/variants.ts
@@ -0,0 +1,53 @@
+import type { SceneGraph } from '../index'
+import type { SceneNode } from '../types'
+
+/** Variants in reading order on the canvas: top to bottom, then left to right, then by name. */
+export function compareCanvasPosition(a: SceneNode, b: SceneNode): number {
+ return a.y - b.y || a.x - b.x || a.name.localeCompare(b.name)
+}
+
+/**
+ * A component set's default variant, the one an instance starts as: the variant in its
+ * top-left corner, as Figma defines it.
+ */
+export function defaultVariant(graph: SceneGraph, set: SceneNode): SceneNode | undefined {
+ return graph
+ .getChildren(set.id)
+ .filter((child) => child.type === 'COMPONENT')
+ .sort(compareCanvasPosition)[0]
+}
+
+/**
+ * The value a variant property starts at: its recorded default when that is one of its options,
+ * or else the default variant's, since a document may leave the recorded default empty.
+ */
+export function variantDefaultValue(
+ graph: SceneGraph,
+ set: SceneNode,
+ property: { name: string; defaultValue: string; variantOptions?: string[] }
+): string {
+ if (property.variantOptions?.includes(property.defaultValue)) return property.defaultValue
+ return defaultVariant(graph, set)?.componentPropertyValues[property.name] ?? property.defaultValue
+}
+
+/**
+ * The variant with every property at its default value: the recorded defaults when they name a
+ * variant, else the default variant, as a document that leaves them out draws it.
+ */
+export function restingVariant(graph: SceneGraph, set: SceneNode): SceneNode | undefined {
+ const properties = set.componentPropertyDefinitions.filter(
+ (definition) => definition.type === 'VARIANT'
+ )
+ const values = properties.map(
+ (property) => [property.name, variantDefaultValue(graph, set, property)] as const
+ )
+ return (
+ graph
+ .getChildren(set.id)
+ .find(
+ (child) =>
+ child.type === 'COMPONENT' &&
+ values.every(([name, value]) => child.componentPropertyValues[name] === value)
+ ) ?? defaultVariant(graph, set)
+ )
+}
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index d0c672e0f..8617bf121 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -14,6 +14,7 @@ export * from './transfer'
export * from './instance-overrides'
export * from './images'
export * from './components/properties'
+export * from './components/variants'
export * from './slots/frames'
export { instanceMainComponent } from './instances/main-component'
export { canCreateInstance } from './instances/cycles'
diff --git a/packages/scene-graph/tests/components/variants.test.ts b/packages/scene-graph/tests/components/variants.test.ts
new file mode 100644
index 000000000..b8d0494dc
--- /dev/null
+++ b/packages/scene-graph/tests/components/variants.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ defaultVariant,
+ restingVariant,
+ SceneGraph,
+ variantDefaultValue
+} from '@open-pencil/scene-graph'
+
+/** A set of sizes laid out with Large first in its children but Small in the top-left corner. */
+function sizes(defaultValue: string) {
+ const graph = new SceneGraph()
+ const definition = {
+ id: 'size',
+ name: 'Size',
+ type: 'VARIANT' as const,
+ defaultValue,
+ variantOptions: ['Small', 'Large']
+ }
+ const set = graph.createNode('COMPONENT_SET', graph.getPages()[0].id, {
+ name: 'Button',
+ componentPropertyDefinitions: [definition]
+ })
+ graph.createNode('COMPONENT', set.id, {
+ name: 'Size=Large',
+ x: 0,
+ y: 60,
+ componentPropertyValues: { Size: 'Large' }
+ })
+ graph.createNode('COMPONENT', set.id, {
+ name: 'Size=Small',
+ x: 0,
+ y: 0,
+ componentPropertyValues: { Size: 'Small' }
+ })
+ return { graph, set, definition }
+}
+
+describe('default variants', () => {
+ test('are the variant in the top-left corner, whatever the order of the children', () => {
+ const { graph, set } = sizes('')
+ expect(defaultVariant(graph, set)?.name).toBe('Size=Small')
+ })
+
+ test('give a property its default value when the document leaves it out', () => {
+ const empty = sizes('')
+ expect(variantDefaultValue(empty.graph, empty.set, empty.definition)).toBe('Small')
+ // A recorded default that is one of the options stands.
+ const recorded = sizes('Large')
+ expect(variantDefaultValue(recorded.graph, recorded.set, recorded.definition)).toBe('Large')
+ })
+
+ test('rest at the recorded defaults when they name a variant, else at the default variant', () => {
+ const recorded = sizes('Large')
+ expect(restingVariant(recorded.graph, recorded.set)?.name).toBe('Size=Large')
+ const empty = sizes('')
+ expect(restingVariant(empty.graph, empty.set)?.name).toBe('Size=Small')
+ })
+})
diff --git a/tests/engine/cli/export/storybook.test.ts b/tests/engine/cli/export/storybook.test.ts
index 6d35fb5ae..6b43f5466 100644
--- a/tests/engine/cli/export/storybook.test.ts
+++ b/tests/engine/cli/export/storybook.test.ts
@@ -10,7 +10,10 @@ import { cliSourcePath } from '#tests/helpers/paths'
import { makeSceneGraph } from '#tests/helpers/scene'
/** A Storybook export without font files, which come from the network these tests leave out. */
-const STORYBOOK = ['--format', 'storybook', '--fonts', 'none']
+const STORYBOOK_EXPORT = ['--format', 'storybook', '--fonts', 'none']
+
+/** Static stories, whose files and design images most of these tests manage. */
+const STORYBOOK = [...STORYBOOK_EXPORT, '--framework', 'html']
setDefaultTimeout(30_000)
@@ -41,8 +44,6 @@ test('export CLI writes Storybook stories with design images', async () => {
'export',
figPath,
...STORYBOOK,
- '--framework',
- 'vue',
'--font-policy',
'allow',
'--output',
@@ -53,7 +54,7 @@ test('export CLI writes Storybook stories with design images', async () => {
expect(exitCode).toBe(0)
expect(stdout).toContain('Exported 1 story files')
const story = await Bun.file(join(output, 'Badge.stories.ts')).text()
- expect(story).toContain("from '@storybook/vue3-vite'")
+ expect(story).toContain("from '@storybook/html-vite'")
// Titled by the document's file name; its one page with components adds no level.
expect(story).toContain("title: 'library/Badge'")
const manifest: unknown = JSON.parse(await Bun.file(join(output, MANIFEST)).text())
@@ -93,6 +94,31 @@ test('export CLI replaces stale generated stories and keeps hand-written ones',
expect(await Bun.file(join(output, 'Mine.stories.ts')).text()).toBe('export default {}\n')
})
+test('export CLI re-exports generated components into the folder it wrote them to', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))
+ const output = join(dir, 'stories')
+ const args = [
+ ...STORYBOOK_EXPORT,
+ '--framework',
+ 'react',
+ '--no-design-images',
+ '--output',
+ output
+ ]
+ for (const name of ['Old', 'New']) {
+ const { exitCode } = await runOpenPencilCLI([
+ 'export',
+ await writeComponentFixture(dir, [name]),
+ ...args
+ ])
+ expect(exitCode).toBe(0)
+ }
+ // The component and its stylesheet are the export's own, replaced like its stories.
+ expect(await Bun.file(join(output, 'New.tsx')).exists()).toBe(true)
+ expect(await Bun.file(join(output, 'Old.tsx')).exists()).toBe(false)
+ expect(await Bun.file(join(output, 'Old.module.css')).exists()).toBe(false)
+})
+
test('export CLI keeps stories of other documents and refuses to overwrite them', async () => {
const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))
const output = join(dir, 'stories')