Skip to content

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

feat(code): show the selection as HTML, Vue, and React with CSS or Tailwind (#1062)

Danila Poyarkov980920991172
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eafcce8c5..0a41f71ce 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -48,6 +48,7 @@
### Added
+- See the selection as a Vue or React component in the Code tab, as the Storybook export generates them: a component set with its variants as props and its behaviour's Reka UI or Radix parts, any other layer as a plain component of the elements it draws, with shaders playing through `shaders/vue` or `shaders/react`. HTML there now shows the selection as markup, images as file paths, and still rewrites it live when edited; with nothing selected it keeps the starter for writing new layers. A CSS/Tailwind switch styles HTML and components with a readable stylesheet or with Tailwind utilities, their states as variants such as `data-[state=checked]:`, and edited HTML is built with Tailwind's utilities; React with Tailwind replaces the Tailwind JSX format. In HTML, Vue, and React, as in Design JSX, the element around the cursor marks its layer on the canvas and design issues are underlined on the layer's class. `export -f storybook --css tailwind` styles the exported Vue and React components the same way.
- Talk with the people in a shared room in a voice call, as in Figma: the headphones beside the avatars start or join it, a ring marks who is in the call and lights up while they speak, and the call's popover chooses the microphone and, where the browser allows, the speakers. Audio goes peer to peer, and only to the people in the call.
- Take a layer out of its auto layout with **Ignore auto layout** at the top of the Position section, as in Figma: the layer stays where it is, its siblings close the gap in the same undo step, and it keeps its sizing, so a Fill layer fills again when it returns.
- Round a rectangle's corners on the canvas, as in Figma: while the pointer is over a selected rectangle at least 108 screen pixels across, a handle sits inside each corner. Dragging one sets every corner while they are equal and only that corner while they differ, <kbd>⌥</kbd> swaps the two, and <kbd>⇧</kbd> rounds to tens; a label beside the pointer shows the radius.
diff --git a/packages/cli/src/commands/export/index.ts b/packages/cli/src/commands/export/index.ts
index 0725cfb5f..09942ac47 100644
--- a/packages/cli/src/commands/export/index.ts
+++ b/packages/cli/src/commands/export/index.ts
@@ -318,7 +318,8 @@ export default defineCommand({
},
css: {
type: 'string',
- description: 'HTML CSS output: inline or tailwind (default: inline)',
+ description:
+ 'CSS output: inline or tailwind; for Storybook, how Vue and React components are styled (default: inline)',
default: 'inline'
},
assets: {
diff --git a/packages/cli/src/commands/export/storybook/index.ts b/packages/cli/src/commands/export/storybook/index.ts
index 4416199d6..1e8b6b6c5 100644
--- a/packages/cli/src/commands/export/storybook/index.ts
+++ b/packages/cli/src/commands/export/storybook/index.ts
@@ -38,6 +38,8 @@ interface StorybookArgs {
page?: string
node?: string
framework: string
+ /** `tailwind` styles Vue and React components with utilities rather than a stylesheet. */
+ css: string
'design-images': boolean
'font-policy': string
watch?: boolean
@@ -162,6 +164,7 @@ async function writeStories(
const source = toPosix(relative(outputDir, resolve(file)))
const files = await exportStorybook(graph, {
framework,
+ styling: args.css === 'tailwind' ? 'tailwind' : 'css',
pageId,
plan: rules ? storyPlan(rules) : undefined,
fonts: args.fonts === 'none' ? undefined : storyFonts,
@@ -288,6 +291,10 @@ export async function exportStorybookFromFile(args: StorybookArgs): Promise<void
)
process.exit(1)
}
+ if (args.css !== 'inline' && args.css !== 'tailwind') {
+ printError(`Invalid Storybook CSS output "${args.css}". Use inline or tailwind.`)
+ process.exit(1)
+ }
let documents: string[]
try {
documents = await resolveDocuments(args)
diff --git a/packages/docs/overview/features.md b/packages/docs/overview/features.md
index 295e23d75..4e98dc9af 100644
--- a/packages/docs/overview/features.md
+++ b/packages/docs/overview/features.md
@@ -29,7 +29,7 @@ Context-sensitive Design | Code | AI | Lint tabs:
- **Typography** — font picker with virtual scroll and search, weight, size, alignment, style buttons
- **Layout** — auto-layout controls when enabled
- **Export** — scale, format (PNG/JPG/WEBP/SVG), live preview
-- **Code** — Design JSX and Tailwind JSX for the selection, with live two-way Design JSX editing that patches your code as layers change; the element around the cursor outlines its layer on the canvas, and design issues are underlined on the property that causes them
+- **Code** — Design JSX, HTML, and Vue and React components for the selection, styled with CSS or Tailwind, with live two-way Design JSX editing that patches your code as layers change; the element around the cursor outlines its layer on the canvas, and design issues are underlined on the property that causes them
- **Lint** — live design lint for the page or selection: low contrast, small touch targets, unbound colors, off-scale spacing, with issue markers on the canvas and one-click variable binding ([Checking Designs](/user-guide/checking-designs))
## Rendering
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index 4f3793918..7445bdc45 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -147,6 +147,7 @@ Generate one CSF3 `.stories.ts` file per component set or component:
```sh
openpencil export design.fig -f storybook # React stories in ./design-stories/
openpencil export design.fig -f storybook --framework vue -o src/stories
+openpencil export design.fig -f storybook --css tailwind # components styled with Tailwind
openpencil export design.fig -f storybook --framework html --page "Components"
openpencil export design.pen -f storybook -o src/stories --watch # re-export on every save
openpencil export 'src/**/*.pen' -f storybook --beside --watch # stories next to each design
@@ -193,7 +194,7 @@ Stories are titled by the document's file name, and then the page when more than
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`, 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.
+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` (with `--css tailwind`, Tailwind utilities in its markup, its states as variants such as `data-[state=checked]:`, for a project that builds Tailwind v4), 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.
diff --git a/packages/docs/user-guide/checking-designs.md b/packages/docs/user-guide/checking-designs.md
index 1d0e8a7ba..895ea04f5 100644
--- a/packages/docs/user-guide/checking-designs.md
+++ b/packages/docs/user-guide/checking-designs.md
@@ -47,7 +47,7 @@ Turn markers and Layers panel marks on or off with **View → Design issues**, o
## In the Code Panel
-The Code tab underlines errors and warnings on the Design JSX or Tailwind JSX of their layers, on the property that causes the issue when there is one, such as `size={10}` for small text. Hover the underline to read the issue. The underlines follow your edits while you change the code live.
+The Code tab underlines errors and warnings on the Design JSX, HTML, Vue, or React of their layers, on the property that causes the issue when there is one, such as `size={10}` for small text, or the class that styles the layer. Hover the underline to read the issue. The underlines follow your edits while you change the code live.
## Rules
diff --git a/packages/dom-css/src/behaviours/states/css.ts b/packages/dom-css/src/behaviours/states/css.ts
index 3dc6484eb..29b1193fe 100644
--- a/packages/dom-css/src/behaviours/states/css.ts
+++ b/packages/dom-css/src/behaviours/states/css.ts
@@ -41,7 +41,8 @@ function designNode(node: StateNode, classes: Map<StateElement, string>): Design
type: 'element',
tagName: node.tagName,
attrs: { ...node.attrs, class: className },
- children: node.children.map((child) => designNode(child, classes))
+ children: node.children.map((child) => designNode(child, classes)),
+ shader: node.shader
}
return element
}
@@ -74,16 +75,49 @@ export async function stateStylesToCSS(styles: StateStyles): Promise<StateStyles
})
}
}
- // Loaded only when a stylesheet is written; the CSS object model is not bundled for browsers.
- const { CSSStyleSheet } = await import('@acemir/cssom')
- const sheet = new CSSStyleSheet()
+ const sheet = await writableStyleSheet()
for (const rule of sortBy(rules, [(item) => item.order])) {
- const index = sheet.insertRule(`${rule.selector} {}`, sheet.cssRules.length)
+ const index = sheet.insertRule(`${rule.selector} {}`)
for (const [property, value] of Object.entries(rule.style))
- sheet.cssRules[index]?.style.setProperty(property, value)
+ sheet.setProperty(index, property, value)
}
return {
document: { type: 'document', children: [designNode(styles.root, classes)] },
- css: sheet.toString()
+ css: sheet.text()
+ }
+}
+
+/** A stylesheet rules are inserted into and printed from. */
+interface WritableStyleSheet {
+ /** Parses `rule` at the end, throwing on an invalid selector, and returns its index. */
+ insertRule(rule: string): number
+ setProperty(index: number, property: string, value: string): void
+ text(): string
+}
+
+/**
+ * The browser's own CSS object model where there is one, and otherwise `@acemir/cssom`, loaded
+ * only when a stylesheet is written. That package's browser build only defines a global and
+ * exports nothing, so a browser bundle cannot use it.
+ */
+async function writableStyleSheet(): Promise<WritableStyleSheet> {
+ if (typeof globalThis.CSSStyleSheet === 'function') {
+ const sheet = new globalThis.CSSStyleSheet()
+ return {
+ insertRule: (rule) => sheet.insertRule(rule, sheet.cssRules.length),
+ setProperty: (index, property, value) => {
+ const rule = sheet.cssRules[index]
+ if (rule instanceof CSSStyleRule) rule.style.setProperty(property, value)
+ },
+ text: () => Array.from(sheet.cssRules, (rule) => rule.cssText).join('\n')
+ }
+ }
+ const { CSSStyleSheet } = await import('@acemir/cssom')
+ const sheet = new CSSStyleSheet()
+ return {
+ insertRule: (rule) => sheet.insertRule(rule, sheet.cssRules.length),
+ setProperty: (index, property, value) =>
+ sheet.cssRules[index]?.style.setProperty(property, value),
+ text: () => sheet.toString()
}
}
diff --git a/packages/dom-css/src/behaviours/states/index.ts b/packages/dom-css/src/behaviours/states/index.ts
index d13eaacee..12ea3d2f4 100644
--- a/packages/dom-css/src/behaviours/states/index.ts
+++ b/packages/dom-css/src/behaviours/states/index.ts
@@ -1,4 +1,4 @@
export { stateStyles } from './model'
export type { StateCondition, StateElement, StateNode, StateRule, StateStyles } from './types'
export { conditionSelector, stateStylesToCSS, type StateStylesheet } from './css'
-export { stateStylesToTailwind, type StateTailwindOptions } from './tailwind'
+export { stateStylesToTailwind, stateTailwindClasses, type StateTailwindOptions } from './tailwind'
diff --git a/packages/dom-css/src/behaviours/states/layers.ts b/packages/dom-css/src/behaviours/states/layers.ts
index 2f912459d..b5d29676a 100644
--- a/packages/dom-css/src/behaviours/states/layers.ts
+++ b/packages/dom-css/src/behaviours/states/layers.ts
@@ -159,6 +159,7 @@ export function stateElement(layer: VariantLayer): StateElement {
attrs: { ...layer.element.attrs },
base: { ...layer.element.inlineStyle },
rules: [],
+ shader: layer.element.shader,
children: layer.children.map((child) => (child.type === 'text' ? child : stateElement(child)))
}
}
diff --git a/packages/dom-css/src/behaviours/states/model.ts b/packages/dom-css/src/behaviours/states/model.ts
index 7026c5371..76d7d615c 100644
--- a/packages/dom-css/src/behaviours/states/model.ts
+++ b/packages/dom-css/src/behaviours/states/model.ts
@@ -2,7 +2,7 @@ import type { SceneGraphToDesignOptions } from '#dom-css/export/projection'
import type { DesignStyleDeclaration } from '#dom-css/types'
import { isEmptyObject, isEqual } from 'es-toolkit/predicate'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { findLayerByPath, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { variantConditions } from './conditions'
import {
@@ -109,11 +109,11 @@ function pruneCombined(rules: StateRule[]): StateRule[] {
}
/**
- * The variants a behaviour's owner draws: a set's components, or a standalone component, such
- * as a radio group or tabs, which is its own only variant.
+ * The variants a layer draws: a set's components, or any other layer, such as a standalone
+ * component or a frame exported as a component, which is its own only variant.
*/
export function ownerVariants(graph: SceneGraph, owner: SceneNode): SceneNode[] {
- if (owner.type === 'COMPONENT') return [owner]
+ if (owner.type !== 'COMPONENT_SET') return [owner]
return graph.getChildren(owner.id).filter((child) => child.type === 'COMPONENT')
}
@@ -163,3 +163,12 @@ export function stateStyles(
}
return { name: set.name, restId: rest.id, root }
}
+
+/** The layer of the rest variant an element of the merged markup draws, if it has one. */
+export function restLayerOf(
+ graph: SceneGraph,
+ styles: StateStyles,
+ element: StateElement
+): string | undefined {
+ return findLayerByPath(graph, styles.restId, element.key.split('\0')[0] ?? '')?.id
+}
diff --git a/packages/dom-css/src/behaviours/states/tailwind.ts b/packages/dom-css/src/behaviours/states/tailwind.ts
index 31bcb4b0c..50711d094 100644
--- a/packages/dom-css/src/behaviours/states/tailwind.ts
+++ b/packages/dom-css/src/behaviours/states/tailwind.ts
@@ -1,5 +1,6 @@
import { splitWhitespace } from '#dom-css/export/html'
import type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'
+import { compact } from 'es-toolkit/array'
import { twirl } from 'twirlwind'
import { cssName, propAttribute } from './names'
@@ -61,16 +62,15 @@ function testedGroup(
return isRoot ? null : groups.root
}
-function designNode(
- node: StateNode,
+/** The utilities a layer takes: its group names, its rest style, and each rule behind its variants. */
+function elementUtilities(
+ node: StateElement,
groups: Groups,
isRoot: boolean,
options: StateTailwindOptions
-): DesignNode {
- if (node.type === 'text') return node
+): string[] {
const anchor = groups.anchors.get(node)
- const classes = [
- ...(node.attrs.class ? splitWhitespace(node.attrs.class) : []),
+ return [
...(isRoot ? [`group/${groups.root}`] : []),
...(anchor ? [`group/${anchor}`] : []),
...utilities(node.base, options),
@@ -85,11 +85,22 @@ function designNode(
return utilities(rule.style, options).map((utility) => `${prefix}${utility}`)
})
]
+}
+
+function designNode(node: StateNode, classes: Map<StateElement, string>): DesignNode {
+ if (node.type === 'text') return node
return {
type: 'element',
tagName: node.tagName,
- attrs: { ...node.attrs, class: classes.join(' ') },
- children: node.children.map((child) => designNode(child, groups, false, options))
+ attrs: {
+ ...node.attrs,
+ class: compact([
+ ...(node.attrs.class ? splitWhitespace(node.attrs.class) : []),
+ classes.get(node)
+ ]).join(' ')
+ },
+ children: node.children.map((child) => designNode(child, classes)),
+ shader: node.shader
}
}
@@ -107,15 +118,31 @@ function anchorGroups(root: StateElement, group: string): Map<StateElement, stri
}
/**
- * The state styles as Tailwind utilities on each element: rest utilities, and each variant's
+ * Each element's Tailwind utilities for the state styles: rest utilities, and each variant's
* changes behind the variants that show it. More stacked variants make a more specific
* selector, so a combined variant wins over each of its parts.
*/
-export function stateStylesToTailwind(
+export function stateTailwindClasses(
styles: StateStyles,
options: StateTailwindOptions = {}
-): DesignDocument {
+): Map<StateElement, string> {
const root = cssName(styles.name, 'component')
const groups = { root, anchors: anchorGroups(styles.root, root) }
- return { type: 'document', children: [designNode(styles.root, groups, true, options)] }
+ const classes = new Map<StateElement, string>()
+ const visit = (node: StateNode, isRoot: boolean) => {
+ if (node.type === 'text') return
+ classes.set(node, elementUtilities(node, groups, isRoot, options).join(' '))
+ for (const child of node.children) visit(child, false)
+ }
+ visit(styles.root, true)
+ return classes
+}
+
+/** The state styles as Tailwind utilities on each element of the merged markup. */
+export function stateStylesToTailwind(
+ styles: StateStyles,
+ options: StateTailwindOptions = {}
+): DesignDocument {
+ const classes = stateTailwindClasses(styles, options)
+ return { type: 'document', children: [designNode(styles.root, classes)] }
}
diff --git a/packages/dom-css/src/behaviours/states/types.ts b/packages/dom-css/src/behaviours/states/types.ts
index 6f4eac673..d016fe25a 100644
--- a/packages/dom-css/src/behaviours/states/types.ts
+++ b/packages/dom-css/src/behaviours/states/types.ts
@@ -1,4 +1,4 @@
-import type { DesignStyleDeclaration, DesignText } from '#dom-css/types'
+import type { DesignElement, DesignStyleDeclaration, DesignText } from '#dom-css/types'
/**
* What must hold on a control's root for a variant to show. Reka and Radix set `data-state`
@@ -40,6 +40,8 @@ export interface StateElement {
attrs: Record<string, string>
base: DesignStyleDeclaration
rules: StateRule[]
+ /** The shader the layer fills with at rest, as the projection keeps it. */
+ shader?: DesignElement['shader']
children: StateNode[]
}
diff --git a/packages/dom-css/src/export/bundle.ts b/packages/dom-css/src/export/bundle.ts
index 12b588ef8..f3d415d19 100644
--- a/packages/dom-css/src/export/bundle.ts
+++ b/packages/dom-css/src/export/bundle.ts
@@ -331,7 +331,8 @@ function extensionForMime(mime: string): string {
return 'png'
}
-function extractImageAssets(
+/** Inline images moved into files under `assetBasePath`, the HTML pointing at them. */
+export function extractImageAssets(
html: string,
assetBasePath: string
): { html: string; files: ExportHTMLFile[] } {
diff --git a/packages/dom-css/src/export/components/layers.ts b/packages/dom-css/src/export/components/layers.ts
new file mode 100644
index 000000000..262e9a409
--- /dev/null
+++ b/packages/dom-css/src/export/components/layers.ts
@@ -0,0 +1,120 @@
+import { stateStylesToCSS } from '#dom-css/behaviours/states/css'
+import { restLayerOf, stateStyles } from '#dom-css/behaviours/states/model'
+import { stateStylesToTailwind } from '#dom-css/behaviours/states/tailwind'
+import type { StateElement, StateNode, StateStyles } from '#dom-css/behaviours/states/types'
+import type { DesignDocument, DesignElement, DesignNode } from '#dom-css/types'
+import { zip } from 'es-toolkit/array'
+
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { extractImageAssets, type ExportHTMLFile } from '../bundle'
+import { serializedElements, serializeHTML } from '../html'
+import type { SceneGraphToDesignOptions } from '../projection'
+import { claimName, identifierName } from '../storybook/names'
+import { componentModel, type ComponentGeneratorOptions, type GeneratedComponent } from './model'
+import { reactComponent } from './react'
+import { vueComponent } from './vue'
+
+/** The frameworks a layer can be generated as a component for. */
+export const LAYER_COMPONENT_FRAMEWORKS = ['vue', 'react'] as const
+export type LayerComponentFramework = (typeof LAYER_COMPONENT_FRAMEWORKS)[number]
+
+/** A layer as a component: its name and the files that make it up. */
+export interface LayerComponent {
+ name: string
+ layerId: string
+ files: GeneratedComponent['files']
+}
+
+/**
+ * Each layer as a Vue or React component, as the Storybook export generates a component set's:
+ * a component set with its variants as props and its behaviour's parts, and any other layer as
+ * a plain component of the elements it draws. Names stay distinct across the layers.
+ */
+export async function layerComponents(
+ graph: SceneGraph,
+ layerIds: readonly string[],
+ framework: LayerComponentFramework,
+ options: Pick<SceneGraphToDesignOptions, 'vectorElement'> & ComponentGeneratorOptions = {}
+): Promise<LayerComponent[]> {
+ const generate = framework === 'vue' ? vueComponent : reactComponent
+ const taken = new Set<string>()
+ const components: LayerComponent[] = []
+ for (const layerId of layerIds) {
+ const layer = graph.getNode(layerId)
+ if (!layer) continue
+ const name = claimName(identifierName(layer.name, 'Component'), taken)
+ const model = componentModel(graph, layer, { ...options, name })
+ if (!model) continue
+ const { files } = await generate(model, { styling: options.styling })
+ components.push({ name, layerId, files })
+ }
+ return components
+}
+
+/** Layers as HTML and the stylesheet that styles it, and the images it points at. */
+export interface LayerMarkup {
+ html: string
+ /** The layer each element of `html` draws, in the order they open, `null` for none. */
+ layerIds: (string | null)[]
+ css: string
+ images: ExportHTMLFile[]
+}
+
+/** The state element each element of markup built from it draws, which it builds one for one. */
+function drawnBy(
+ state: StateNode,
+ design: DesignNode,
+ found: Map<DesignElement, StateElement>
+): void {
+ if (state.type === 'text' || design.type === 'text') return
+ found.set(design, state)
+ for (const [child, built] of zip(state.children, design.children)) drawnBy(child, built, found)
+}
+
+/** The layer of each element `serializeHTML` writes for the document, in the order they open. */
+function markupLayers(graph: SceneGraph, styles: StateStyles, document: DesignDocument) {
+ const states = new Map<DesignElement, StateElement>()
+ for (const root of document.children) drawnBy(styles.root, root, states)
+ return serializedElements(document).map((element) => {
+ const state = element && states.get(element)
+ return (state && restLayerOf(graph, styles, state)) ?? null
+ })
+}
+
+/**
+ * Layers as indented HTML with a readable class per layer and one stylesheet, as the generated
+ * components draw them, or with Tailwind utilities in place of the classes and no stylesheet.
+ * Images are files under `assetBasePath` rather than inlined.
+ */
+export async function layerMarkup(
+ graph: SceneGraph,
+ layerIds: readonly string[],
+ options: Pick<SceneGraphToDesignOptions, 'vectorElement'> &
+ ComponentGeneratorOptions & { assetBasePath?: string } = {}
+): Promise<LayerMarkup> {
+ const taken = new Set<string>()
+ const html: string[] = []
+ const layers: (string | null)[] = []
+ const css: string[] = []
+ for (const layerId of layerIds) {
+ const layer = graph.getNode(layerId)
+ const styles = layer && stateStyles(graph, layer, options)
+ if (!layer || !styles) continue
+ // Two layers named alike would share class names, and their rules would collide.
+ const name = claimName(styles.name, taken, { separator: ' ' })
+ const named = { ...styles, name }
+ const sheet =
+ options.styling === 'tailwind'
+ ? { document: stateStylesToTailwind(named), css: '' }
+ : await stateStylesToCSS(named)
+ html.push(serializeHTML(sheet.document, { indent: true }))
+ layers.push(...markupLayers(graph, named, sheet.document))
+ if (sheet.css) css.push(sheet.css)
+ }
+ const { html: page, files } = extractImageAssets(
+ html.join('\n\n'),
+ options.assetBasePath ?? 'assets'
+ )
+ return { html: page, layerIds: layers, css: css.join('\n'), images: files }
+}
diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
index c7dfa7ab3..d62cd12c6 100644
--- a/packages/dom-css/src/export/components/model.ts
+++ b/packages/dom-css/src/export/components/model.ts
@@ -1,7 +1,7 @@
import { behaviourArgs, type BehaviourArgs } from '#dom-css/behaviours/args'
import { BUTTON_RESET } from '#dom-css/behaviours/reset'
import { allElements } from '#dom-css/behaviours/states/layers'
-import { ownerVariants, stateStyles } from '#dom-css/behaviours/states/model'
+import { ownerVariants, restLayerOf, 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'
@@ -17,8 +17,7 @@ import {
variantDefaultValue,
type Behaviour,
type SceneGraph,
- type SceneNode,
- type ShaderPreset
+ type SceneNode
} from '@open-pencil/scene-graph'
import type { SceneGraphToDesignOptions } from '../projection'
@@ -30,8 +29,7 @@ import {
inputValue,
numberInput,
rangeModel,
- textModel,
- type InputLayers
+ textModel
} from './fields'
import {
groupItems,
@@ -57,7 +55,9 @@ import {
type UsedLayer
} from './references'
import { activeTriggers, tabParts, type ChoiceModel, type RepeatedPart } from './repeats'
-import { shaderLayer, shaderLayers, type ShaderLayer } from './shaders'
+import { shaderLayers, type ShaderLayer } from './shaders'
+import type { ComponentStyling } from './styling'
+import { componentTree } from './tree'
/** Kinds generated as components so far; the rest keep static stories. */
export const GENERATED_KINDS = [
@@ -123,6 +123,8 @@ export interface ComponentElement {
shownBy?: string
/** The slot prop whose content the layer shows in place of its own. */
slot?: string
+ /** The layer of the rest variant it draws, which code links back to. */
+ layerId?: string
/** The value a repeated part stands for, such as a tab trigger's tab. */
value?: string
/** The shader the layer fills with, which plays behind its content. */
@@ -153,7 +155,7 @@ export type ComponentNode =
/** The value of a text prop, drawn where the design binds a text layer to it. */
| { type: 'textProp'; name: string }
/** A field's input, drawn where the design binds its text layer to the field's text. */
- | { type: 'input'; className: string }
+ | { type: 'input'; className: string; layerId?: string }
| ComponentReference
| IconReference
@@ -190,66 +192,13 @@ export interface ComponentModel {
args: BehaviourArgs
}
-interface TreeLabels {
- parts: Map<StateElement, string>
- classes: Map<StateElement, string>
- /** The text prop each bound text layer draws, by layer. */
- texts: Map<StateElement, string>
- /** Layers that use another component or an icon in place of drawing themselves. */
- used: Map<StateElement, UsedLayer>
- /** Layers drawn once per value, such as tab triggers and panels. */
- 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>
- /** The shader each layer fills with. */
- shaders: Map<StateElement, ShaderPreset>
-}
-
-function componentTree(
- node: StateElement,
- labels: TreeLabels,
- bindings: ComponentBinding[]
-): ComponentElement {
- const repeated = labels.repeated.get(node)
- const part = repeated?.part ?? labels.parts.get(node) ?? null
- const text = labels.texts.get(node)
- const className = labels.classes.get(node) ?? ''
- return {
- type: 'element',
- part,
- ...(repeated ? { value: repeated.value } : {}),
- tag: node.tagName,
- className,
- attrs: node.attrs,
- bindings: part === 'root' ? bindings : [],
- shownBy: labels.shownBy.get(node),
- slot: labels.slotOf.get(node),
- shader: shaderLayer(node, className, labels.shaders.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 }]
- : node.children.flatMap((child) =>
- child.type === 'text' ? [{ type: 'text', value: child.text }] : childNode(child, labels)
- )
- }
-}
-
-function childNode(element: StateElement, labels: TreeLabels): ComponentNode[] {
- const className = labels.classes.get(element) ?? ''
- if (labels.input?.element === element) return [{ type: 'input', className }]
- if (labels.input?.replaced.includes(element)) return []
- const used = labels.used.get(element)
- if (!used) return [componentTree(element, labels, [])]
- return [{ ...used, className }]
-}
-
/** A generated component's files, and what its stories need to know about it. */
export interface GeneratedComponent {
- files: { path: string; content: string }[]
+ /**
+ * The component's files. A file of JSX lists the layer each of its JSX elements draws, in the
+ * order they open, `null` for an element no layer drew, such as a shader's canvas.
+ */
+ files: { path: string; content: string; layerIds?: (string | null)[] }[]
/** How stories import it: its path next to them, and whether it's a named export. */
entry: { path: string; named: boolean }
/** The prop a story sets the value with, if the component has one. */
@@ -258,7 +207,16 @@ export interface GeneratedComponent {
valueList?: boolean
}
-export type ComponentGenerator = (component: ComponentModel) => Promise<GeneratedComponent>
+/** How a generator writes a component. */
+export interface ComponentGeneratorOptions {
+ /** A stylesheet beside the component, by default, or Tailwind utilities in its markup. */
+ styling?: ComponentStyling
+}
+
+export type ComponentGenerator = (
+ component: ComponentModel,
+ options?: ComponentGeneratorOptions
+) => Promise<GeneratedComponent>
/** Parts each kind renders as a native button, which the reset clears for the design. */
const BUTTON_PARTS: Record<GeneratedKind, readonly string[]> = {
@@ -563,7 +521,8 @@ export function componentModel(
input,
shownBy,
slotOf,
- shaders: shaderLayers(graph, styles.restId, elements)
+ shaders: shaderLayers(graph, styles.restId, elements),
+ layerOf: (element) => restLayerOf(graph, styles, element)
},
rootBindings(model, !!options.itemOf, disabled, props)
),
diff --git a/packages/dom-css/src/export/components/react/fields.ts b/packages/dom-css/src/export/components/react/fields.ts
index 675daf974..1a5841c8b 100644
--- a/packages/dom-css/src/export/components/react/fields.ts
+++ b/packages/dom-css/src/export/components/react/fields.ts
@@ -4,7 +4,7 @@ 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'
+import { classValue, 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'>> = {
@@ -51,7 +51,7 @@ export const NUMBER_INPUT = [
/** 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 classAttribute = jsx.attribute('className', classValue(uses.classOf(className)))
const { range } = component
if (range)
return jsx.element(
diff --git a/packages/dom-css/src/export/components/react/index.ts b/packages/dom-css/src/export/components/react/index.ts
index 42e3961b6..01a2982b5 100644
--- a/packages/dom-css/src/export/components/react/index.ts
+++ b/packages/dom-css/src/export/components/react/index.ts
@@ -26,6 +26,7 @@ import {
shaderImport,
type ShaderLayer
} from '../shaders'
+import { componentClasses } from '../styling'
import {
INPUT_PROPS,
inputElement,
@@ -36,7 +37,7 @@ import {
STEPPERS,
type Parameter
} from './fields'
-import { moduleClass, numeric, type MarkupUses } from './shared'
+import { classValue, drawing, elementLayers, moduleClass, numeric, type MarkupUses } from './shared'
/**
* The Radix primitive a kind renders, from the unified `radix-ui` package, and the component
@@ -131,15 +132,19 @@ function referenceValue(value: string | boolean): es.SyntaxNode | null {
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, referenceValue(prop.value))),
- ...(node.model ? [jsx.attribute(defaultOf(node.model), null)] : [])
- ],
- [],
- depth
+ return drawing(
+ jsx.element(
+ node.component,
+ [
+ jsx.attribute('className', classValue(uses.classOf(node.className))),
+ ...node.props.map((prop) => jsx.attribute(prop.name, referenceValue(prop.value))),
+ ...(node.model ? [jsx.attribute(defaultOf(node.model), null)] : [])
+ ],
+ [],
+ depth
+ ),
+ node.layerId,
+ uses
)
}
@@ -147,17 +152,22 @@ function element(node: ComponentNode, uses: MarkupUses, depth: number): es.Synta
if (node.type === 'text') return jsx.text(node.value)
if (node.type === 'textProp') return jsx.container(es.identifier(node.name))
if (node.type === 'reference') return reference(node, uses, depth)
- if (node.type === 'input') return inputElement(node.className, uses, depth)
+ if (node.type === 'input')
+ return drawing(inputElement(node.className, uses, depth), node.layerId, uses)
if (node.type === 'icon') {
uses.icons = true
- return jsx.element(
- ICONIFY,
- [
- jsx.attribute('icon', jsx.stringValue(node.icon)),
- jsx.attribute('className', jsx.container(moduleClass(node.className)))
- ],
- [],
- depth
+ return drawing(
+ jsx.element(
+ ICONIFY,
+ [
+ jsx.attribute('icon', jsx.stringValue(node.icon)),
+ jsx.attribute('className', classValue(uses.classOf(node.className)))
+ ],
+ [],
+ depth
+ ),
+ node.layerId,
+ uses
)
}
return designElement(node, uses, depth)
@@ -167,10 +177,10 @@ function element(node: ComponentNode, uses: MarkupUses, depth: number): es.Synta
* The design's own classes, the state styles' module class, and on the root the caller's,
* which the spread would otherwise lose to the generated one.
*/
-function classNameOf(node: ComponentElement, root: boolean): es.SyntaxNode {
+function classNameOf(node: ComponentElement, root: boolean, uses: MarkupUses): es.SyntaxNode {
const classes = [
...(node.attrs.class ? [es.string(node.attrs.class)] : []),
- moduleClass(node.className),
+ uses.classOf(node.className),
...(root ? [es.parseExpression('props.className')] : [])
]
const only = classes.length === 1 ? classes.at(0) : undefined
@@ -247,7 +257,7 @@ function shaderCanvas(shader: ShaderLayer, uses: MarkupUses, depth: number): es.
return jsx.element(
SHADER_CANVAS,
[
- jsx.attribute('className', jsx.container(moduleClass(shader.className))),
+ jsx.attribute('className', classValue(uses.classOf(shader.className))),
jsx.attribute('disableTelemetry', null)
],
drawnEffects(shader.preset.components).map(effect(depth + 1)),
@@ -276,7 +286,7 @@ function designElement(node: ComponentElement, uses: MarkupUses, depth: number):
jsx.attribute(name, jsx.stringValue(value))
),
...partAttributes(node, uses),
- jsx.attribute('className', jsx.container(classNameOf(node, root))),
+ jsx.attribute('className', classValue(classNameOf(node, root, uses))),
...bindingAttributes(node, kind, native)
]
const inline = wordsOnly(node)
@@ -285,12 +295,16 @@ function designElement(node: ComponentElement, uses: MarkupUses, depth: number):
const childDepth = depth + (header ? 2 : 1)
const content = node.children.map((child) => element(child, uses, childDepth))
const shader = node.shader ? [shaderCanvas(node.shader, uses, childDepth)] : []
- const drawn = jsx.element(
- tagOf(node, kind),
- attributes,
- [...shader, ...(node.slot ? [slotContent(node.slot, content, childDepth)] : content)],
- depth + (header ? 1 : 0),
- inline
+ const drawn = drawing(
+ jsx.element(
+ tagOf(node, kind),
+ attributes,
+ [...shader, ...(node.slot ? [slotContent(node.slot, content, childDepth)] : content)],
+ depth + (header ? 1 : 0),
+ inline
+ ),
+ node.layerId,
+ uses
)
const shown = header
? jsx.element(
@@ -483,14 +497,20 @@ function valueArg(
* `radix-ui` package, its variants' state styles in a CSS module, and props that extend the
* Radix root's with its other variant properties.
*/
-export const reactComponent: ComponentGenerator = async (component) => {
+export const reactComponent: ComponentGenerator = async (component, options = {}) => {
+ const styling = options.styling ?? 'css'
const radix = RADIX[component.kind]
const stylesPath = `${component.name}.module.css`
+ const classOf = componentClasses(component, styling)
const uses: MarkupUses = {
component,
+ // Styled with Tailwind, a layer's utilities are written out; otherwise its module class.
+ classOf: (className) =>
+ styling === 'css' ? moduleClass(className) : es.string(classOf(className)),
kind: component.kind,
choice: component.choice,
components: new Set(),
+ layers: new WeakMap(),
icons: false,
shaders: new Set()
}
@@ -532,17 +552,34 @@ export const reactComponent: ComponentGenerator = async (component) => {
const program = {
type: 'Program',
sourceType: 'module',
- body: [...react, ...imports, stylesImport, ...rest]
+ body: [...react, ...imports, ...(styling === 'css' ? [stylesImport] : []), ...rest]
}
- const { css } = await stateStylesToCSS(component.styles)
+ // Tailwind styles the markup itself; a CSS module is written beside it otherwise.
+ const stylesheet =
+ styling === 'css'
+ ? [
+ {
+ path: stylesPath,
+ content: compact([
+ (await stateStylesToCSS(component.styles)).css,
+ shaderCSS(component.tree)
+ ]).join('\n')
+ }
+ ]
+ : []
const model = component.model
// A group's items are their own component, which the group's markup uses.
- const item = component.item ? await reactComponent(component.item) : null
+ const item = component.item ? await reactComponent(component.item, options) : null
return {
files: [
...(item?.files ?? []),
- { path: `${component.name}.tsx`, content: `${jsx.printModule(program)}\n` },
- { path: stylesPath, content: compact([css, shaderCSS(component.tree)]).join('\n') }
+ {
+ path: `${component.name}.tsx`,
+ content: `${jsx.printModule(program)}\n`,
+ // The template is filled with copies, so the body, which holds all the JSX, is read.
+ layerIds: elementLayers(body, uses.layers)
+ },
+ ...stylesheet
],
entry: { path: `./${component.name}`, named: true },
...valueArg(component.kind, model)
diff --git a/packages/dom-css/src/export/components/react/shared.ts b/packages/dom-css/src/export/components/react/shared.ts
index d483e138d..743f7d65e 100644
--- a/packages/dom-css/src/export/components/react/shared.ts
+++ b/packages/dom-css/src/export/components/react/shared.ts
@@ -23,9 +23,49 @@ export interface MarkupUses {
/** Other generated components. */
components: Set<string>
icons: boolean
+ /** A layer's class as the component is styled: its CSS module class, or its utilities. */
+ classOf: (className: string) => es.SyntaxNode
+ /** The layer each JSX element draws, which code links back to. */
+ layers: WeakMap<es.SyntaxNode, string>
/** Effects of the `shaders` library its layers fill with. */
shaders: Set<string>
}
export const numeric = (name: string, value: number) =>
jsx.attribute(name, jsx.container(es.number(value)))
+
+/** A `className` value: a plain string as an attribute string, anything else in braces. */
+export function classValue(value: es.SyntaxNode): es.SyntaxNode {
+ return value.type === 'Literal' && typeof value.value === 'string'
+ ? jsx.stringValue(value.value)
+ : jsx.container(value)
+}
+
+/** `element`, recorded as drawing `layerId`, so code can link back to that layer. */
+export function drawing(
+ element: es.SyntaxNode,
+ layerId: string | undefined,
+ uses: MarkupUses
+): es.SyntaxNode {
+ if (layerId) uses.layers.set(element, layerId)
+ return element
+}
+
+/** The layer of each JSX element in `program`, in the order the elements open. */
+export function elementLayers(
+ program: es.SyntaxNode,
+ layers: WeakMap<es.SyntaxNode, string>
+): (string | null)[] {
+ const found: (string | null)[] = []
+ const visit = (value: unknown) => {
+ if (Array.isArray(value)) {
+ for (const item of value) visit(item)
+ return
+ }
+ if (!es.isNode(value)) return
+ if (value.type === 'JSXElement') found.push(layers.get(value) ?? null)
+ for (const item of Object.values(value)) visit(item)
+ }
+ visit(program)
+ return found
+}
diff --git a/packages/dom-css/src/export/components/references.ts b/packages/dom-css/src/export/components/references.ts
index f06b76774..1e1d6200d 100644
--- a/packages/dom-css/src/export/components/references.ts
+++ b/packages/dom-css/src/export/components/references.ts
@@ -29,6 +29,8 @@ export interface ReferenceProp {
*/
export interface ComponentReference {
type: 'reference'
+ /** The layer it draws, which code links back to. */
+ layerId?: string
/** The component's identifier and file name. */
component: string
/** The class the parent's state styles place it by. */
@@ -41,6 +43,8 @@ export interface ComponentReference {
/** An icon from a set, drawn by the framework's Iconify component. */
export interface IconReference {
type: 'icon'
+ /** The layer it draws, which code links back to. */
+ layerId?: string
/** `prefix:name`. */
icon: string
className: string
diff --git a/packages/dom-css/src/export/components/shaders.ts b/packages/dom-css/src/export/components/shaders.ts
index ae5de7322..140914445 100644
--- a/packages/dom-css/src/export/components/shaders.ts
+++ b/packages/dom-css/src/export/components/shaders.ts
@@ -99,7 +99,7 @@ export function shaderEffectAttributes(component: ShaderComponent): es.SyntaxNod
export const SHADER_CANVAS = 'ShaderCanvas'
/** The elements of a component's tree that fill with a shader. */
-function shaderElements(node: ComponentNode): ComponentElement[] {
+export function shaderElements(node: ComponentNode): ComponentElement[] {
if (node.type !== 'element') return []
return [...(node.shader ? [node] : []), ...node.children.flatMap(shaderElements)]
}
diff --git a/packages/dom-css/src/export/components/styling.ts b/packages/dom-css/src/export/components/styling.ts
new file mode 100644
index 000000000..3a0746aae
--- /dev/null
+++ b/packages/dom-css/src/export/components/styling.ts
@@ -0,0 +1,31 @@
+import { layerClassNames } from '#dom-css/behaviours/states/names'
+import { stateTailwindClasses } from '#dom-css/behaviours/states/tailwind'
+
+import type { ComponentModel } from './model'
+import { shaderElements } from './shaders'
+
+/** How a generated component is styled: a stylesheet, or Tailwind utilities in its markup. */
+export const COMPONENT_STYLINGS = ['css', 'tailwind'] as const
+export type ComponentStyling = (typeof COMPONENT_STYLINGS)[number]
+
+/** Where a layer's shader plays: filling the layer, beneath its content, inside its corners. */
+export const SHADER_UTILITIES = 'pointer-events-none absolute inset-0 -z-10 rounded-[inherit]'
+
+/**
+ * The class each of a component's readable class names stands for. Styled with a stylesheet, a
+ * class is itself; with Tailwind it is the layer's utilities, its states behind their variants,
+ * and a shader canvas's placement.
+ */
+export function componentClasses(
+ component: ComponentModel,
+ styling: ComponentStyling
+): (className: string) => string {
+ if (styling === 'css') return (className) => className
+ const readable = layerClassNames(component.styles)
+ const utilities = stateTailwindClasses(component.styles)
+ const byClass = new Map<string, string>()
+ for (const [element, className] of readable) byClass.set(className, utilities.get(element) ?? '')
+ for (const { shader } of shaderElements(component.tree))
+ if (shader) byClass.set(shader.className, SHADER_UTILITIES)
+ return (className) => byClass.get(className) ?? className
+}
diff --git a/packages/dom-css/src/export/components/tree.ts b/packages/dom-css/src/export/components/tree.ts
new file mode 100644
index 000000000..712c1c2df
--- /dev/null
+++ b/packages/dom-css/src/export/components/tree.ts
@@ -0,0 +1,72 @@
+import type { StateElement } from '#dom-css/behaviours/states/types'
+
+import type { ShaderPreset } from '@open-pencil/scene-graph'
+
+import type { InputLayers } from './fields'
+import type { ComponentBinding, ComponentElement, ComponentNode } from './model'
+import type { UsedLayer } from './references'
+import type { RepeatedPart } from './repeats'
+import { shaderLayer } from './shaders'
+
+/** What each layer of the rest variant is to the component, gathered before its tree is built. */
+export interface TreeLabels {
+ parts: Map<StateElement, string>
+ classes: Map<StateElement, string>
+ /** The text prop each bound text layer draws, by layer. */
+ texts: Map<StateElement, string>
+ /** Layers that use another component or an icon in place of drawing themselves. */
+ used: Map<StateElement, UsedLayer>
+ /** Layers drawn once per value, such as tab triggers and panels. */
+ 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>
+ /** The shader each layer fills with. */
+ shaders: Map<StateElement, ShaderPreset>
+ /** The layer of the rest variant each element draws. */
+ layerOf: (element: StateElement) => string | undefined
+}
+
+export function componentTree(
+ node: StateElement,
+ labels: TreeLabels,
+ bindings: ComponentBinding[]
+): ComponentElement {
+ const repeated = labels.repeated.get(node)
+ const layerId = labels.layerOf(node)
+ const part = repeated?.part ?? labels.parts.get(node) ?? null
+ const text = labels.texts.get(node)
+ const className = labels.classes.get(node) ?? ''
+ return {
+ type: 'element',
+ part,
+ ...(repeated ? { value: repeated.value } : {}),
+ tag: node.tagName,
+ className,
+ layerId,
+ attrs: node.attrs,
+ bindings: part === 'root' ? bindings : [],
+ shownBy: labels.shownBy.get(node),
+ slot: labels.slotOf.get(node),
+ shader: shaderLayer(node, className, labels.shaders.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 }]
+ : node.children.flatMap((child) =>
+ child.type === 'text' ? [{ type: 'text', value: child.text }] : childNode(child, labels)
+ )
+ }
+}
+
+function childNode(element: StateElement, labels: TreeLabels): ComponentNode[] {
+ const className = labels.classes.get(element) ?? ''
+ const layerId = labels.layerOf(element)
+ if (labels.input?.element === element) return [{ type: 'input', className, layerId }]
+ if (labels.input?.replaced.includes(element)) return []
+ const used = labels.used.get(element)
+ if (!used) return [componentTree(element, labels, [])]
+ return [{ ...used, className, layerId }]
+}
diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.ts
index ca70821da..dc453687d 100644
--- a/packages/dom-css/src/export/components/vue.ts
+++ b/packages/dom-css/src/export/components/vue.ts
@@ -27,6 +27,7 @@ import {
shaderImport,
type ShaderLayer
} from './shaders'
+import { componentClasses } from './styling'
/** The Reka UI components a kind renders, by part, and the prop its model binds. */
const REKA: Record<
@@ -139,16 +140,26 @@ function progressStyle(component: ComponentModel): vue.VueAttribute[] {
return style ? [vue.bound('style', style)] : []
}
+/** `element`, recorded as drawing `layerId`, so code can link back to that layer. */
+function drawing(
+ element: vue.VueElement,
+ layerId: string | undefined,
+ uses: TemplateUses
+): vue.VueElement {
+ if (layerId) uses.layers.set(element, layerId)
+ return element
+}
+
/** A field's input: Reka's for a number field, else a native input or textarea. */
-function inputNode(className: string, uses: TemplateUses): vue.VueNode {
+function inputNode(className: string, uses: TemplateUses): vue.VueElement {
const { component } = uses
if (component.kind === 'numberField') {
uses.reka.add('NumberFieldInput')
- return vue.element('NumberFieldInput', [vue.attribute('class', className)])
+ return vue.element('NumberFieldInput', [vue.attribute('class', uses.classOf(className))])
}
const placeholder = component.text?.placeholder
return vue.element(component.kind === 'textarea' ? 'textarea' : 'input', [
- vue.attribute('class', className),
+ vue.attribute('class', uses.classOf(className)),
...(component.model ? [vue.model(identifier(component.model))] : []),
...(placeholder ? [vue.attribute('placeholder', placeholder)] : []),
...(component.disabled ? [vue.bound('disabled', identifier('disabled'))] : [])
@@ -166,6 +177,10 @@ interface TemplateUses {
/** Other generated components. */
components: Set<string>
icons: boolean
+ /** The class a layer's readable class name stands for, as the component is styled. */
+ classOf: (className: string) => string
+ /** The layer each element draws, which code links back to. */
+ layers: WeakMap<vue.VueElement, string>
/** Effects of the `shaders` library its layers fill with. */
shaders: Set<string>
/** A ref per nested control drawn on, which its `v-model` binds. */
@@ -176,14 +191,14 @@ interface TemplateUses {
/** The Iconify component, named apart from any component the design calls `Icon`. */
const ICONIFY = 'IconifyIcon'
-function reference(node: ComponentReference, uses: TemplateUses): vue.VueNode {
+function reference(node: ComponentReference, uses: TemplateUses): vue.VueElement {
uses.components.add(node.component)
const model = node.model
? claimName(`${camelCase(node.component)}${upperFirst(node.model)}`, uses.taken)
: null
if (model) uses.models.push({ name: model })
return vue.element(node.component, [
- vue.attribute('class', node.className),
+ vue.attribute('class', uses.classOf(node.className)),
...node.props.map((prop) =>
typeof prop.value === 'boolean'
? vue.bound(prop.name, es.parseExpression(String(prop.value)))
@@ -209,7 +224,7 @@ function elementAttributes(
...Object.entries(omit(node.attrs, ['class'])).map(([name, value]) =>
vue.attribute(name, value)
),
- vue.attribute('class', compact([node.attrs.class, node.className]).join(' ')),
+ vue.attribute('class', compact([node.attrs.class, uses.classOf(node.className)]).join(' ')),
...(node.value === undefined ? [] : [vue.attribute('value', node.value)]),
...node.bindings.flatMap((binding) => bindingAttributes(binding, uses, native))
]
@@ -231,28 +246,35 @@ function shaderCanvas(shader: ShaderLayer, uses: TemplateUses): vue.VueNode {
}
return vue.element(
SHADER_CANVAS,
- [vue.attribute('class', shader.className), vue.bound('disable-telemetry', es.json(true))],
+ [
+ vue.attribute('class', uses.classOf(shader.className)),
+ vue.bound('disable-telemetry', es.json(true))
+ ],
drawnEffects(shader.preset.components).map(effect)
)
}
-function designElement(node: ComponentElement, uses: TemplateUses): vue.VueNode {
+function designElement(node: ComponentElement, uses: TemplateUses): vue.VueElement {
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 content = node.children.map((child) => templateNode(child, uses))
const children = node.shader ? [shaderCanvas(node.shader, uses), ...content] : content
- 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
- ? [
- ...(node.shader ? [shaderCanvas(node.shader, uses)] : []),
- vue.element('slot', [vue.attribute('name', node.slot)], content)
- ]
- : children
+ const element = drawing(
+ 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
+ ? [
+ ...(node.shader ? [shaderCanvas(node.shader, uses)] : []),
+ vue.element('slot', [vue.attribute('name', node.slot)], content)
+ ]
+ : children
+ ),
+ node.layerId,
+ 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
@@ -263,14 +285,15 @@ function designElement(node: ComponentElement, uses: TemplateUses): vue.VueNode
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))
- if (node.type === 'reference') return reference(node, uses)
- if (node.type === 'input') return inputNode(node.className, uses)
+ if (node.type === 'reference') return drawing(reference(node, uses), node.layerId, uses)
+ if (node.type === 'input') return drawing(inputNode(node.className, uses), node.layerId, uses)
if (node.type === 'icon') {
uses.icons = true
- return vue.element(ICONIFY, [
+ const icon = vue.element(ICONIFY, [
vue.attribute('icon', node.icon),
- vue.attribute('class', node.className)
+ vue.attribute('class', uses.classOf(node.className))
])
+ return drawing(icon, node.layerId, uses)
}
return designElement(node, uses)
}
@@ -410,7 +433,8 @@ function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {
* scoped stylesheet, its parts as Reka components, and its props from the behaviour and its
* other variant properties.
*/
-export const vueComponent: ComponentGenerator = async (component) => {
+export const vueComponent: ComponentGenerator = async (component, options = {}) => {
+ const styling = options.styling ?? 'css'
const taken = new Set([
...component.props.map((prop) => prop.name),
...component.texts.map((text) => text.name),
@@ -421,6 +445,8 @@ export const vueComponent: ComponentGenerator = async (component) => {
])
const uses: TemplateUses = {
component,
+ classOf: componentClasses(component, styling),
+ layers: new WeakMap(),
kind: component.kind,
sliderValues:
component.kind === 'slider' && component.model ? claimName('values', taken) : null,
@@ -433,20 +459,26 @@ export const vueComponent: ComponentGenerator = async (component) => {
taken
}
const template = templateNode(component.tree, uses)
- const { css } = await stateStylesToCSS(component.styles)
+ // Tailwind styles the markup itself; a stylesheet is written beside it otherwise.
+ const style =
+ styling === 'css'
+ ? compact([(await stateStylesToCSS(component.styles)).css, shaderCSS(component.tree)]).join(
+ '\n'
+ )
+ : undefined
const path = `${component.name}.vue`
// A group's items are their own component, which the group's template uses.
- const item = component.item ? await vueComponent(component.item) : null
+ const item = component.item ? await vueComponent(component.item, options) : null
+ const sfc = { script: script(component, uses), template, style }
return {
files: [
...(item?.files ?? []),
{
path,
- content: vue.printComponent({
- script: script(component, uses),
- template,
- style: compact([css, shaderCSS(component.tree)]).join('\n')
- })
+ content: vue.printComponent(sfc),
+ layerIds: vue
+ .componentElements(sfc)
+ .map((element) => (element && uses.layers.get(element)) ?? null)
}
],
entry: { path: `./${path}`, named: false },
diff --git a/packages/dom-css/src/export/html.ts b/packages/dom-css/src/export/html.ts
index 3d6c09d00..957caf474 100644
--- a/packages/dom-css/src/export/html.ts
+++ b/packages/dom-css/src/export/html.ts
@@ -6,6 +6,12 @@ export interface SerializeHTMLOptions {
style?: 'inline' | 'tailwind'
/** Custom properties declared in `@theme`; a `var()` naming one becomes its utility. */
themeVariables?: readonly string[]
+ /**
+ * Put each child of an element that holds only elements on its own indented line, for code
+ * people read. Text keeps its whitespace; whitespace between elements in a projected layer
+ * changes nothing, since its children are placed by flex, grid, or absolute position.
+ */
+ indent?: boolean
}
const VOID_ELEMENTS = new Set([
@@ -108,17 +114,46 @@ function shaderFrame(node: DesignElement): string {
return frame ? `<img src="${escapeAttr(frame)}" alt="" style="${SHADER_FRAME_STYLE}">` : ''
}
-function serializeElement(node: DesignElement, options: SerializeHTMLOptions): string {
+function serializeElement(
+ node: DesignElement,
+ options: SerializeHTMLOptions,
+ depth: number
+): string {
// SVG names such as `linearGradient` keep their case, as an SVG parser needs them.
const tagName = node.tagName
const attrs = serializeAttrs(node, options)
if (VOID_ELEMENTS.has(tagName.toLowerCase())) return `<${tagName}${attrs}>`
- const children = node.children.map((child) => serializeNode(child, options)).join('')
- return `<${tagName}${attrs}>${shaderFrame(node)}${children}</${tagName}>`
+ const children = [
+ shaderFrame(node),
+ ...node.children.map((child) => serializeNode(child, options, depth + 1))
+ ].filter((child) => child !== '')
+ const block =
+ options.indent && children.length > 0 && node.children.every((child) => child.type !== 'text')
+ if (!block) return `<${tagName}${attrs}>${children.join('')}</${tagName}>`
+ const inner = ' '.repeat(depth + 1)
+ const outer = ' '.repeat(depth)
+ return `<${tagName}${attrs}>\n${children.map((child) => inner + child).join('\n')}\n${outer}</${tagName}>`
+}
+
+export function serializeNode(
+ node: DesignNode,
+ options: SerializeHTMLOptions = {},
+ depth = 0
+): string {
+ return node.type === 'text' ? serializeText(node) : serializeElement(node, options, depth)
}
-export function serializeNode(node: DesignNode, options: SerializeHTMLOptions = {}): string {
- return node.type === 'text' ? serializeText(node) : serializeElement(node, options)
+/**
+ * The elements `serializeHTML` writes, in the order they open: the document's own, and `null`
+ * for a shader's still frame, which it adds in front of its layer's content.
+ */
+export function serializedElements(document: DesignDocument): (DesignElement | null)[] {
+ const visit = (node: DesignNode): (DesignElement | null)[] => {
+ if (node.type === 'text') return []
+ if (VOID_ELEMENTS.has(node.tagName.toLowerCase())) return [node]
+ return [node, ...(node.shader?.frame ? [null] : []), ...node.children.flatMap(visit)]
+ }
+ return document.children.flatMap(visit)
}
export function serializeHTML(
@@ -129,5 +164,7 @@ export function serializeHTML(
...options,
themeVariables: options.themeVariables ?? document.tokens?.themeVariables()
}
- return document.children.map((node) => serializeNode(node, resolved)).join('')
+ return document.children
+ .map((node) => serializeNode(node, resolved))
+ .join(options.indent ? '\n' : '')
}
diff --git a/packages/dom-css/src/export/index.ts b/packages/dom-css/src/export/index.ts
index c5b0ffc98..b10d674ea 100644
--- a/packages/dom-css/src/export/index.ts
+++ b/packages/dom-css/src/export/index.ts
@@ -13,6 +13,15 @@ export {
type TailwindJSXWithLayers
} from './tailwind-jsx'
export { serializeHTML } from './html'
+export {
+ LAYER_COMPONENT_FRAMEWORKS,
+ layerComponents,
+ layerMarkup,
+ type LayerComponent,
+ type LayerComponentFramework,
+ type LayerMarkup
+} from './components/layers'
+export { COMPONENT_STYLINGS, type ComponentStyling } from './components/styling'
export * from '../tokens'
export * from '../behaviours'
export type {
diff --git a/packages/dom-css/src/export/storybook/export.ts b/packages/dom-css/src/export/storybook/export.ts
index 57df3c142..6cd2538a2 100644
--- a/packages/dom-css/src/export/storybook/export.ts
+++ b/packages/dom-css/src/export/storybook/export.ts
@@ -16,6 +16,7 @@ import {
import { componentModel, type ComponentGenerator, type ComponentModel } from '../components/model'
import { reactComponent } from '../components/react'
import type { ComponentReferences } from '../components/references'
+import type { ComponentStyling } from '../components/styling'
import { vueComponent } from '../components/vue'
import { serializeHTML, serializeNode } from '../html'
import { sceneNodeToDesignDocument, type VectorElementRenderer } from '../projection'
@@ -39,6 +40,11 @@ const GENERATORS: Partial<Record<StorybookFramework, ComponentGenerator>> = {
export interface ExportStorybookOptions {
framework?: StorybookFramework
+ /**
+ * How Vue and React components are styled: a stylesheet beside each, by default, or Tailwind
+ * utilities in their markup, which needs Tailwind set up in the Storybook project.
+ */
+ styling?: ComponentStyling
/** Limit the export to one page. Defaults to every page. */
pageId?: string
/**
@@ -377,7 +383,7 @@ export async function exportStorybook(
for (const { page, group, file, mode } of entries) {
const component = group.set && models.get(group.set.id)
if (generate && component) {
- const generated = await generate(component)
+ const generated = await generate(component, { styling: options.styling })
for (const item of generated.files) add(page, item.path, item.content)
const design = designLink({ linkPath: options.linkPath, uniqueNames }, group.linkNode)
add(
diff --git a/packages/dom-css/src/export/tailwind-jsx.ts b/packages/dom-css/src/export/tailwind-jsx.ts
index ed1d247e9..5af62e3e8 100644
--- a/packages/dom-css/src/export/tailwind-jsx.ts
+++ b/packages/dom-css/src/export/tailwind-jsx.ts
@@ -3,6 +3,7 @@ import type { SceneGraph, ShaderComponent, ShaderPreset } from '@open-pencil/sce
import type { DesignDocument, DesignElement, DesignNode } from '../types'
import { shaderEffectAttributes } from './components/shaders'
+import { SHADER_UTILITIES } from './components/styling'
import { mergeClassNames, serializeTailwindClasses } from './html'
import { sceneNodeToDesignDocument, type SceneGraphToDesignOptions } from './projection'
@@ -42,9 +43,6 @@ function attributes(node: DesignElement, themeVariables: readonly string[]): Syn
)
}
-/** Where a layer's shader plays: filling the layer, beneath its content, inside its corners. */
-const SHADER_CLASSES = 'pointer-events-none absolute inset-0 -z-10 rounded-[inherit]'
-
/**
* A layer's shader as the `shaders` library's `<Shader>`, each effect a child with the preset's
* props, with telemetry off as every OpenPencil export has it.
@@ -62,7 +60,7 @@ function shaderElement(preset: ShaderPreset, depth: number): SyntaxNode {
return jsx.element(
'Shader',
[
- jsx.attribute('className', jsx.stringValue(SHADER_CLASSES)),
+ jsx.attribute('className', jsx.stringValue(SHADER_UTILITIES)),
jsx.attribute('disableTelemetry', null)
],
preset.components.map(effect(depth + 1)),
diff --git a/packages/dom-css/tests/export/components/layers.test.ts b/packages/dom-css/tests/export/components/layers.test.ts
new file mode 100644
index 000000000..a6f831788
--- /dev/null
+++ b/packages/dom-css/tests/export/components/layers.test.ts
@@ -0,0 +1,163 @@
+import { describe, expect, test } from 'bun:test'
+
+import { switchSet } from '#dom-css-tests/behaviours/fixtures'
+import { fileText } from '#dom-css-tests/helpers'
+import { layerComponents, layerMarkup } from '#dom-css/export'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function card(graph: SceneGraph, name: string) {
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, {
+ name,
+ x: 300,
+ y: 200,
+ width: 240,
+ height: 120,
+ layoutMode: 'VERTICAL',
+ itemSpacing: 8,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }]
+ })
+ graph.createNode('TEXT', frame.id, { name: 'Title', text: 'Pro' })
+ return frame
+}
+
+describe('layers as components', () => {
+ test('a frame is a plain component of the elements it draws', async () => {
+ const graph = new SceneGraph()
+ const frame = card(graph, 'Pricing card')
+
+ const [vue] = await layerComponents(graph, [frame.id], 'vue')
+ const [react] = await layerComponents(graph, [frame.id], 'react')
+
+ expect(vue?.name).toBe('PricingCard')
+ const sfc = fileText(vue?.files ?? [], 'PricingCard.vue')
+ expect(sfc).not.toContain('<script')
+ expect(sfc).toContain('<span class="pricing-card__title">Pro</span>')
+ expect(sfc).toContain('gap: 8px')
+ // Where the frame sits on the canvas is not the component's.
+ expect(sfc).not.toContain('300px')
+ expect(react?.files.map((file) => file.path)).toEqual([
+ 'PricingCard.tsx',
+ 'PricingCard.module.css'
+ ])
+ expect(fileText(react?.files ?? [], 'PricingCard.tsx')).toContain(
+ 'export function PricingCard(props: PricingCardProps)'
+ )
+ })
+
+ test('a component set keeps its behaviour', async () => {
+ const { graph, set } = switchSet()
+
+ const [vue] = await layerComponents(graph, [set.id], 'vue')
+
+ expect(fileText(vue?.files ?? [], `${vue?.name}.vue`)).toContain('SwitchRoot')
+ })
+
+ test('a component lists the layer each element draws, in the order they open', async () => {
+ const { graph, set } = switchSet()
+ const rest = graph.getNode(set.childIds[0])
+ if (!rest) throw new Error('The switch has no variants')
+ const drawn = [rest.id, rest.childIds[0]]
+
+ for (const styling of ['css', 'tailwind'] as const) {
+ const [react] = await layerComponents(graph, [set.id], 'react', { styling })
+ expect(react?.files.find((file) => file.path.endsWith('.tsx'))?.layerIds).toEqual(drawn)
+ // The script, template, and style blocks around a Vue template draw no layer.
+ const [vue] = await layerComponents(graph, [set.id], 'vue', { styling })
+ expect(vue?.files[0]?.layerIds).toEqual([
+ null,
+ null,
+ ...drawn,
+ ...(styling === 'css' ? [null] : [])
+ ])
+ expect((await layerMarkup(graph, [set.id], { styling })).layerIds).toEqual(drawn)
+ }
+ })
+
+ test('styled with Tailwind, a component has no stylesheet', async () => {
+ const graph = new SceneGraph()
+ const frame = card(graph, 'Pricing card')
+
+ const [vue] = await layerComponents(graph, [frame.id], 'vue', { styling: 'tailwind' })
+ const [react] = await layerComponents(graph, [frame.id], 'react', { styling: 'tailwind' })
+
+ expect(fileText(vue?.files ?? [], 'PricingCard.vue')).not.toContain('<style')
+ expect(fileText(vue?.files ?? [], 'PricingCard.vue')).toContain('flex flex-col')
+ expect(react?.files.map((file) => file.path)).toEqual(['PricingCard.tsx'])
+ })
+
+ test('layers with the same name get distinct component names', async () => {
+ const graph = new SceneGraph()
+ const first = card(graph, 'Card')
+ const second = card(graph, 'Card')
+
+ const components = await layerComponents(graph, [first.id, second.id], 'react')
+
+ expect(components.map((component) => component.name)).toEqual(['Card', 'Card2'])
+ })
+})
+
+describe('layers as HTML and CSS', () => {
+ test('markup is indented with a class per layer, styled by one stylesheet', async () => {
+ const graph = new SceneGraph()
+ const frame = card(graph, 'Pricing card')
+
+ const { html, css } = await layerMarkup(graph, [frame.id])
+
+ expect(html).toBe(
+ '<div class="pricing-card">\n <span class="pricing-card__title">Pro</span>\n</div>'
+ )
+ expect(css).toContain('.pricing-card {')
+ expect(css).toContain('.pricing-card .pricing-card__title {')
+ })
+
+ test('styled with Tailwind, the markup carries utilities and there is no stylesheet', async () => {
+ const graph = new SceneGraph()
+ const frame = card(graph, 'Pricing card')
+
+ const { html, css } = await layerMarkup(graph, [frame.id], { styling: 'tailwind' })
+
+ expect(html).toMatch(/^<div class="[^"]*\bflex flex-col\b[^"]*\bgap-2\b[^"]*bg-white/)
+ expect(html).toContain('\n <span class="')
+ expect(css).toBe('')
+ })
+
+ test('layers named alike keep their rules apart', async () => {
+ const graph = new SceneGraph()
+ const first = card(graph, 'Card')
+ const second = card(graph, 'Card')
+
+ const { html } = await layerMarkup(graph, [first.id, second.id])
+
+ expect(html).toContain('<div class="card">')
+ expect(html).toContain('<div class="card-2">')
+ })
+
+ test('images are files the markup points at, not inline data', async () => {
+ const graph = new SceneGraph()
+ const bytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
+ const hash = 'a'.repeat(40)
+ graph.images.set(hash, bytes)
+ const photo = graph.createNode('RECTANGLE', graph.getPages()[0].id, {
+ name: 'Photo',
+ width: 80,
+ height: 60,
+ fills: [
+ {
+ type: 'IMAGE',
+ imageHash: hash,
+ imageScaleMode: 'FILL',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true
+ }
+ ]
+ })
+
+ const { html, images } = await layerMarkup(graph, [photo.id], { assetBasePath: 'card.assets' })
+
+ expect(html).toContain('src="card.assets/images/image-1.png"')
+ expect(html).not.toContain('data:image')
+ expect(images.map((image) => image.content)).toEqual([bytes])
+ })
+})
diff --git a/packages/dom-css/tests/export/components/react.test.ts b/packages/dom-css/tests/export/components/react.test.ts
index 82cba6562..670c31084 100644
--- a/packages/dom-css/tests/export/components/react.test.ts
+++ b/packages/dom-css/tests/export/components/react.test.ts
@@ -23,6 +23,7 @@ import {
} from '#dom-css-tests/behaviours/fixtures'
import { shaderBackdropSet, shaderHeroSet } from '#dom-css-tests/export/components/shader-fixtures'
import { cssRules, fileText } from '#dom-css-tests/helpers'
+import type { ComponentStyling } from '#dom-css/export'
import { exportStorybook } from '#dom-css/index'
import { createElement, type ComponentType } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
@@ -53,8 +54,8 @@ afterAll(() => rm(output, { recursive: true, force: true }))
type Props = Record<string, unknown>
/** Exports a fixture's set to React stories and loads the component and stories it writes. */
-async function generate(fixture: ReturnType<typeof switchSet>) {
- const files = await exportStorybook(fixture.graph, { framework: 'react' })
+async function generate(fixture: ReturnType<typeof switchSet>, styling?: ComponentStyling) {
+ const files = await exportStorybook(fixture.graph, { framework: 'react', styling })
const name = fixture.set.name
// Bun caches a folder's listing once it imports from it, so each export gets its own.
const folder = await mkdtemp(join(output, `${name}-`))
@@ -116,6 +117,37 @@ describe('generated React plain components', () => {
})
})
+describe('generated React components styled with Tailwind', () => {
+ test('carry their states as variants in place of a CSS module, and type-check', async () => {
+ const { files, component, folder } = await generate(switchSet(), 'tailwind')
+ const source = fileText(files, 'Switch.tsx')
+
+ expect(files.map((file) => file.path).sort()).toEqual(['Switch.stories.ts', 'Switch.tsx'])
+ expect(await typeErrors(folder, 'Switch')).toEqual([])
+ expect(source).not.toContain('styles')
+ // The root names its group, which the thumb's checked look keys on.
+ expect(source).toMatch(/"group\/switch [^"]*data-\[state=checked\]:bg-\[#4F45E6\]/)
+ expect(source).toContain('group-data-[state=checked]/switch:left-5')
+ const on = render(component, { defaultChecked: true })
+ expect(on).toContain('data-state="checked"')
+ expect(on).toMatch(/class="group\/switch [^"]*"/)
+ // A class the caller passes joins the utilities rather than replacing them.
+ expect(render(component, { className: 'custom' })).toMatch(/class="group\/switch [^"]* custom"/)
+ })
+
+ test('play a shader behind the layer, placed by utilities', async () => {
+ const { files, folder } = await generate(shaderHeroSet(), 'tailwind')
+ const source = fileText(files, 'Hero.tsx')
+
+ expect(await typeErrors(folder, 'Hero')).toEqual([])
+ expect(source).toContain(
+ '<ShaderCanvas className="pointer-events-none absolute inset-0 -z-10 rounded-[inherit]" disableTelemetry>'
+ )
+ // The layer holds the shader in its own stacking context.
+ expect(source).toMatch(/"group\/hero relative [^"]*\bisolate\b/)
+ })
+})
+
describe('generated React shader fills', () => {
test('play the shader behind the layer, with telemetry off, and type-check', async () => {
const { files, folder } = await generate(shaderHeroSet())
diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.ts
index f2b4bf2a6..39d7b5141 100644
--- a/packages/dom-css/tests/export/components/vue.test.ts
+++ b/packages/dom-css/tests/export/components/vue.test.ts
@@ -22,6 +22,7 @@ import {
} from '#dom-css-tests/behaviours/fixtures'
import { shaderBackdropSet, shaderHeroSet } from '#dom-css-tests/export/components/shader-fixtures'
import { cssRules, fileText } from '#dom-css-tests/helpers'
+import type { ComponentStyling } from '#dom-css/export'
import { exportStorybook } from '#dom-css/index'
import { createSSRApp, h, type Component } from 'vue'
import { compileScript, parse } from 'vue/compiler-sfc'
@@ -41,8 +42,8 @@ for (const name of APP_PACKAGES)
afterAll(() => rm(output, { recursive: true, force: true }))
/** Exports a fixture's set to Vue stories and loads the component and stories it writes. */
-async function generate(fixture: ReturnType<typeof switchSet>) {
- const files = await exportStorybook(fixture.graph, { framework: 'vue' })
+async function generate(fixture: ReturnType<typeof switchSet>, styling?: ComponentStyling) {
+ const files = await exportStorybook(fixture.graph, { framework: 'vue', styling })
const source = (suffix: string) =>
String(files.find((file) => file.path.endsWith(suffix))?.content)
const name = fixture.set.name
@@ -226,6 +227,30 @@ const styleOf = (files: { path: string; content: string | Uint8Array }[], path:
)?.[1] ?? ''
)
+describe('generated Vue components styled with Tailwind', () => {
+ test('carry their states as variants in place of a style block', async () => {
+ const { files, component } = await generate(switchSet(), 'tailwind')
+ const sfc = fileText(files, 'Switch.vue')
+
+ expect(sfc).not.toContain('<style')
+ expect(sfc).toMatch(
+ /<SwitchRoot class="group\/switch [^"]*data-\[state=checked\]:bg-\[#4F45E6\]/
+ )
+ expect(sfc).toContain('group-data-[state=checked]/switch:left-5')
+ const on = await render(component, { checked: true })
+ expect(on).toContain('data-state="checked"')
+ expect(on).toMatch(/class="group\/switch [^"]*"/)
+ })
+
+ test('play a shader behind the layer, placed by utilities', async () => {
+ const { files } = await generate(shaderHeroSet(), 'tailwind')
+
+ expect(fileText(files, 'Hero.vue')).toMatch(
+ /<Shader[^>]* class="pointer-events-none absolute inset-0 -z-10 rounded-\[inherit\]"/
+ )
+ })
+})
+
describe('generated Vue plain components', () => {
test('take variant, text, and boolean properties as props, and slots as slots', async () => {
const { component } = await generate(plainBadgeSet())
diff --git a/packages/emit/README.md b/packages/emit/README.md
index e82bafe62..05364bc87 100644
--- a/packages/emit/README.md
+++ b/packages/emit/README.md
@@ -33,6 +33,9 @@ es.printModule(module) // export const title = 'Checkout';
```ts
import { es, vue } from '@open-pencil/emit'
-const template = vue.element('SwitchRoot', [vue.attribute('class', 'switch'), vue.model(es.identifier('checked'))])
+const template = vue.element('SwitchRoot', [
+ vue.attribute('class', 'switch'),
+ vue.model(es.identifier('checked'))
+])
vue.printTemplate(template) // <SwitchRoot class="switch" v-model="checked" />
```
diff --git a/packages/emit/package.json b/packages/emit/package.json
index ae4a7c77b..33f57afd1 100644
--- a/packages/emit/package.json
+++ b/packages/emit/package.json
@@ -1,9 +1,22 @@
{
"name": "@open-pencil/emit",
"version": "0.15.1",
+ "description": "How OpenPencil exporters emit source: JavaScript, TypeScript, and JSX built as ESTree and printed with esrap.",
"license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/open-pencil/open-pencil.git",
+ "directory": "packages/emit"
+ },
+ "files": [
+ "dist",
+ "src",
+ "README.md"
+ ],
"type": "module",
- "description": "How OpenPencil exporters emit source: JavaScript, TypeScript, and JSX built as ESTree and printed with esrap.",
+ "sideEffects": false,
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
"imports": {
"#emit/*": {
"types": "./src/*",
@@ -19,14 +32,10 @@
"default": "./dist/index.js"
}
},
- "main": "./dist/index.js",
- "types": "./dist/index.d.ts",
- "sideEffects": false,
- "files": [
- "dist",
- "src",
- "README.md"
- ],
+ "publishConfig": {
+ "access": "public",
+ "provenance": true
+ },
"scripts": {
"build": "bunx tsdown --config tsdown.config.ts",
"check": "bun run typecheck && bun run build && bun run smoke:dist",
@@ -45,14 +54,5 @@
"tsdown": "^0.22.14",
"typescript": "~5.8.3",
"vue": "^3.5.43"
- },
- "repository": {
- "type": "git",
- "url": "git+https://github.com/open-pencil/open-pencil.git",
- "directory": "packages/emit"
- },
- "publishConfig": {
- "access": "public",
- "provenance": true
}
}
diff --git a/packages/emit/src/vue.ts b/packages/emit/src/vue.ts
index dd0986c49..7e069b301 100644
--- a/packages/emit/src/vue.ts
+++ b/packages/emit/src/vue.ts
@@ -127,10 +127,36 @@ export interface VueComponent {
const rawBlock = (tag: string, content: string) =>
`<${tag}>\n${content.trim().replace(/<\/(?=script|style)/gi, '<\\/')}\n</${tag.split(' ')[0]}>`
+/** Whether a component's script has anything to write, so it gets a script block. */
+const hasScript = (script: SyntaxNode) => printModule(script).trim() !== ''
+
+function templateElements(node: VueNode): VueElement[] {
+ return node.type === 'element' ? [node, ...node.children.flatMap(templateElements)] : []
+}
+
+/**
+ * The elements `printComponent` writes, in the order they open: the template's own, between
+ * `null`s for the script, template, and style blocks that hold them.
+ */
+export function componentElements({
+ script,
+ template,
+ style
+}: VueComponent): (VueElement | null)[] {
+ return [
+ ...(hasScript(script) ? [null] : []),
+ null,
+ ...templateElements(template),
+ ...(style ? [null] : [])
+ ]
+}
+
/** A single-file component: script setup, template, and scoped style. */
export function printComponent({ script, template, style }: VueComponent): string {
+ const code = printModule(script)
+ // A component with nothing to import or declare has no script block.
const blocks = [
- rawBlock('script setup lang="ts"', printModule(script)),
+ ...(code.trim() ? [rawBlock('script setup lang="ts"', code)] : []),
`<template>\n${printNode(template, 1)}\n</template>`,
...(style ? [rawBlock('style scoped', style)] : [])
]
diff --git a/packages/emit/tests/vue.test.ts b/packages/emit/tests/vue.test.ts
index 92f26aeb9..c0c739e18 100644
--- a/packages/emit/tests/vue.test.ts
+++ b/packages/emit/tests/vue.test.ts
@@ -118,6 +118,29 @@ describe('Vue templates', () => {
])
expect(descriptor.template?.content.trim()).toBe('<div />')
})
+
+ test('leave out the script block when there is nothing to import or declare', () => {
+ const source = vue.printComponent({
+ script: es.parseModule(''),
+ template: vue.element('div')
+ })
+ expect(parse(source).descriptor.scriptSetup).toBeNull()
+ })
+
+ test('list the elements a component opens, in order, the blocks as null', () => {
+ const thumb = vue.element('SwitchThumb')
+ const root = vue.element('SwitchRoot', [], [thumb])
+ const sfc = { script: es.parseModule('const on = true'), template: root, style: '.a {}' }
+ const source = vue.printComponent(sfc)
+
+ const elements = vue.componentElements(sfc)
+ expect(elements).toEqual([null, null, root, thumb, null])
+ // One for each tag the source opens: script, template, the template's own, and style.
+ expect(source.match(/<[A-Za-z]/g)).toHaveLength(elements.length)
+ expect(vue.componentElements({ ...sfc, script: es.parseModule(''), style: undefined })).toEqual(
+ [null, root, thumb]
+ )
+ })
})
describe('conditional elements', () => {
diff --git a/packages/emit/tsdown.config.ts b/packages/emit/tsdown.config.ts
index 19391dd50..a76e67c4b 100644
--- a/packages/emit/tsdown.config.ts
+++ b/packages/emit/tsdown.config.ts
@@ -28,7 +28,8 @@ export default defineConfig({
const cleanId = id.split('?')[0]
const parts = cleanId.split(/[\\/]/g)
const srcIndex = parts.lastIndexOf('src')
- const file = srcIndex >= 0 ? parts.slice(srcIndex + 1).join('/') : parts.at(-1) ?? 'chunk'
+ const file =
+ srcIndex >= 0 ? parts.slice(srcIndex + 1).join('/') : (parts.at(-1) ?? 'chunk')
return `chunks/${file.replace(/\.(ts|tsx)$/, '')}`
}
}
diff --git a/packages/vue/src/i18n/locales/de/code.json b/packages/vue/src/i18n/locales/de/code.json
index 7b1ac09c0..637cbd7bc 100644
--- a/packages/vue/src/i18n/locales/de/code.json
+++ b/packages/vue/src/i18n/locales/de/code.json
@@ -3,8 +3,12 @@
"jsxUpToDate": "Aktuell",
"source": "Codequelle",
"sourceDesignJSX": "Design JSX",
- "sourceTailwindJSX": "Tailwind JSX",
- "sourceHTMLCSS": "HTML/CSS",
+ "sourceHTML": "HTML",
+ "sourceVue": "Vue",
+ "sourceReact": "React",
+ "styling": "Styling",
+ "stylingCSS": "CSS",
+ "stylingTailwind": "Tailwind",
"editorDesignLabel": "Design JSX",
"editorHTMLCSSLabel": "HTML und CSS",
"updating": "Wird aktualisiert…",
@@ -14,7 +18,7 @@
"reset": "Zurücksetzen",
"noSelection": "Wähle eine Ebene aus, um ihren Code zu sehen",
"noSelectionDesignJSX": "Oder schreibe Design JSX, um der Seite neue Ebenen hinzuzufügen.",
- "noSelectionTailwindJSX": "Tailwind JSX wird für die ausgewählten Ebenen erzeugt.",
+ "noSelectionComponents": "{framework}-Komponenten werden für die ausgewählten Ebenen erzeugt.",
"writeJSX": "JSX schreiben",
"canvasChangedExpression": "Auf der Arbeitsfläche jetzt {value}; der Ausdruck bleibt, wie er geschrieben ist.",
"canvasChangedOrder": "Auf der Arbeitsfläche sind diese Ebenen jetzt anders angeordnet; der Code bleibt, wie er geschrieben ist."
diff --git a/packages/vue/src/i18n/locales/es/code.json b/packages/vue/src/i18n/locales/es/code.json
index 49b2009c3..9899b8d20 100644
--- a/packages/vue/src/i18n/locales/es/code.json
+++ b/packages/vue/src/i18n/locales/es/code.json
@@ -3,8 +3,12 @@
"jsxUpToDate": "Actualizado",
"source": "Fuente del código",
"sourceDesignJSX": "Design JSX",
- "sourceTailwindJSX": "Tailwind JSX",
- "sourceHTMLCSS": "HTML/CSS",
+ "sourceHTML": "HTML",
+ "sourceVue": "Vue",
+ "sourceReact": "React",
+ "styling": "Estilos",
+ "stylingCSS": "CSS",
+ "stylingTailwind": "Tailwind",
"editorDesignLabel": "Design JSX",
"editorHTMLCSSLabel": "HTML y CSS",
"updating": "Actualizando…",
@@ -14,7 +18,7 @@
"reset": "Restablecer",
"noSelection": "Selecciona una capa para ver su código",
"noSelectionDesignJSX": "O escribe Design JSX para añadir capas nuevas a la página.",
- "noSelectionTailwindJSX": "Tailwind JSX se genera para las capas seleccionadas.",
+ "noSelectionComponents": "Los componentes de {framework} se generan para las capas seleccionadas.",
"writeJSX": "Escribir JSX",
"canvasChangedExpression": "El lienzo tiene ahora {value}; la expresión se mantiene tal como está escrita.",
"canvasChangedOrder": "El lienzo ordena ahora estas capas de otra forma; el código se mantiene tal como está escrito."
diff --git a/packages/vue/src/i18n/locales/fr/code.json b/packages/vue/src/i18n/locales/fr/code.json
index 4993220cd..6c43cc497 100644
--- a/packages/vue/src/i18n/locales/fr/code.json
+++ b/packages/vue/src/i18n/locales/fr/code.json
@@ -3,8 +3,12 @@
"jsxUpToDate": "À jour",
"source": "Source du code",
"sourceDesignJSX": "Design JSX",
- "sourceTailwindJSX": "Tailwind JSX",
- "sourceHTMLCSS": "HTML/CSS",
+ "sourceHTML": "HTML",
+ "sourceVue": "Vue",
+ "sourceReact": "React",
+ "styling": "Style",
+ "stylingCSS": "CSS",
+ "stylingTailwind": "Tailwind",
"editorDesignLabel": "Design JSX",
"editorHTMLCSSLabel": "HTML et CSS",
"updating": "Mise à jour…",
@@ -14,7 +18,7 @@
"reset": "Réinitialiser",
"noSelection": "Sélectionnez un calque pour voir son code",
"noSelectionDesignJSX": "Ou écrivez du Design JSX pour ajouter de nouveaux calques à la page.",
- "noSelectionTailwindJSX": "Le Tailwind JSX est généré pour les calques sélectionnés.",
+ "noSelectionComponents": "Les composants {framework} sont générés pour les calques sélectionnés.",
"writeJSX": "Écrire du JSX",
"canvasChangedExpression": "Le canevas indique maintenant {value} ; l’expression reste telle qu’écrite.",
"canvasChangedOrder": "Le canevas ordonne maintenant ces calques autrement ; le code reste tel qu’écrit."
diff --git a/packages/vue/src/i18n/locales/it/code.json b/packages/vue/src/i18n/locales/it/code.json
index fd55eb4a6..9beddd300 100644
--- a/packages/vue/src/i18n/locales/it/code.json
+++ b/packages/vue/src/i18n/locales/it/code.json
@@ -3,8 +3,12 @@
"jsxUpToDate": "Aggiornato",
"source": "Sorgente del codice",
"sourceDesignJSX": "Design JSX",
- "sourceTailwindJSX": "Tailwind JSX",
- "sourceHTMLCSS": "HTML/CSS",
+ "sourceHTML": "HTML",
+ "sourceVue": "Vue",
+ "sourceReact": "React",
+ "styling": "Stile",
+ "stylingCSS": "CSS",
+ "stylingTailwind": "Tailwind",
"editorDesignLabel": "Design JSX",
"editorHTMLCSSLabel": "HTML e CSS",
"updating": "Aggiornamento…",
@@ -14,7 +18,7 @@
"reset": "Reimposta",
"noSelection": "Seleziona un livello per vederne il codice",
"noSelectionDesignJSX": "Oppure scrivi Design JSX per aggiungere nuovi livelli alla pagina.",
- "noSelectionTailwindJSX": "Il Tailwind JSX viene generato per i livelli selezionati.",
+ "noSelectionComponents": "I componenti {framework} vengono generati per i livelli selezionati.",
"writeJSX": "Scrivi JSX",
"canvasChangedExpression": "Sulla tela ora è {value}; l’espressione resta com’è scritta.",
"canvasChangedOrder": "Sulla tela questi livelli ora sono in un altro ordine; il codice resta com’è scritto."
diff --git a/packages/vue/src/i18n/locales/ja/code.json b/packages/vue/src/i18n/locales/ja/code.json
index b556a3ed2..c809df350 100644
--- a/packages/vue/src/i18n/locales/ja/code.json
+++ b/packages/vue/src/i18n/locales/ja/code.json
@@ -3,8 +3,12 @@
"jsxUpToDate": "最新です",
"source": "コードソース",
"sourceDesignJSX": "Design JSX",
- "sourceTailwindJSX": "Tailwind JSX",
- "sourceHTMLCSS": "HTML/CSS",
+ "sourceHTML": "HTML",
+ "sourceVue": "Vue",
+ "sourceReact": "React",
+ "styling": "スタイル",
+ "stylingCSS": "CSS",
+ "stylingTailwind": "Tailwind",
"editorDesignLabel": "Design JSX",
"editorHTMLCSSLabel": "HTML と CSS",
"updating": "更新中…",
@@ -14,7 +18,7 @@
"reset": "リセット",
"noSelection": "レイヤーを選択するとコードが表示されます",
"noSelectionDesignJSX": "または Design JSX を書いて、ページに新しいレイヤーを追加できます。",
- "noSelectionTailwindJSX": "Tailwind JSX は選択したレイヤーから生成されます。",
+ "noSelectionComponents": "選択したレイヤーから {framework} コンポーネントを生成します。",
"writeJSX": "JSX を書く",
"canvasChangedExpression": "キャンバスでは {value} になりました。式は書かれたまま残しています。",
"canvasChangedOrder": "キャンバスではこれらのレイヤーの順序が変わりました。コードは書かれたまま残しています。"
diff --git a/packages/vue/src/i18n/locales/pl/code.json b/packages/vue/src/i18n/locales/pl/code.json
index 31778b682..b2f6fcac2 100644
--- a/packages/vue/src/i18n/locales/pl/code.json
+++ b/packages/vue/src/i18n/locales/pl/code.json
@@ -3,8 +3,12 @@
"jsxUpToDate": "Aktualne",
"source": "Źródło kodu",
"sourceDesignJSX": "Design JSX",
- "sourceTailwindJSX": "Tailwind JSX",
- "sourceHTMLCSS": "HTML/CSS",
+ "sourceHTML": "HTML",
+ "sourceVue": "Vue",
+ "sourceReact": "React",
+ "styling": "Stylowanie",
+ "stylingCSS": "CSS",
+ "stylingTailwind": "Tailwind",
"editorDesignLabel": "Design JSX",
"editorHTMLCSSLabel": "HTML i CSS",
"updating": "Aktualizowanie…",
@@ -14,7 +18,7 @@
"reset": "Resetuj",
"noSelection": "Zaznacz warstwę, aby zobaczyć jej kod",
"noSelectionDesignJSX": "Albo napisz Design JSX, aby dodać nowe warstwy do strony.",
- "noSelectionTailwindJSX": "Tailwind JSX jest generowany dla zaznaczonych warstw.",
+ "noSelectionComponents": "Komponenty {framework} są generowane dla zaznaczonych warstw.",
"writeJSX": "Napisz JSX",
"canvasChangedExpression": "Na płótnie jest teraz {value}; wyrażenie pozostaje bez zmian.",
"canvasChangedOrder": "Na płótnie te warstwy są teraz w innej kolejności; kod pozostaje bez zmian."
diff --git a/packages/vue/src/i18n/locales/ru/code.json b/packages/vue/src/i18n/locales/ru/code.json
index 6ea5b2716..534c427c2 100644
--- a/packages/vue/src/i18n/locales/ru/code.json
+++ b/packages/vue/src/i18n/locales/ru/code.json
@@ -3,8 +3,12 @@
"jsxUpToDate": "Актуально",
"source": "Источник кода",
"sourceDesignJSX": "Design JSX",
- "sourceTailwindJSX": "Tailwind JSX",
- "sourceHTMLCSS": "HTML/CSS",
+ "sourceHTML": "HTML",
+ "sourceVue": "Vue",
+ "sourceReact": "React",
+ "styling": "Стили",
+ "stylingCSS": "CSS",
+ "stylingTailwind": "Tailwind",
"editorDesignLabel": "Design JSX",
"editorHTMLCSSLabel": "HTML и CSS",
"updating": "Обновление…",
@@ -14,7 +18,7 @@
"reset": "Сбросить",
"noSelection": "Выделите слой, чтобы увидеть его код",
"noSelectionDesignJSX": "Или напишите Design JSX, чтобы добавить на страницу новые слои.",
- "noSelectionTailwindJSX": "Tailwind JSX создаётся для выделенных слоёв.",
+ "noSelectionComponents": "Компоненты {framework} создаются для выбранных слоёв.",
"writeJSX": "Написать JSX",
"canvasChangedExpression": "На холсте теперь {value}; выражение оставлено как написано.",
"canvasChangedOrder": "На холсте эти слои теперь в другом порядке; код оставлен как написан."
diff --git a/packages/vue/src/i18n/locales/zh-cn/code.json b/packages/vue/src/i18n/locales/zh-cn/code.json
index 02618c532..fef8b792f 100644
--- a/packages/vue/src/i18n/locales/zh-cn/code.json
+++ b/packages/vue/src/i18n/locales/zh-cn/code.json
@@ -3,8 +3,12 @@
"jsxUpToDate": "已是最新",
"source": "代码来源",
"sourceDesignJSX": "Design JSX",
- "sourceTailwindJSX": "Tailwind JSX",
- "sourceHTMLCSS": "HTML/CSS",
+ "sourceHTML": "HTML",
+ "sourceVue": "Vue",
+ "sourceReact": "React",
+ "styling": "样式",
+ "stylingCSS": "CSS",
+ "stylingTailwind": "Tailwind",
"editorDesignLabel": "Design JSX",
"editorHTMLCSSLabel": "HTML 和 CSS",
"updating": "正在更新…",
@@ -14,7 +18,7 @@
"reset": "重置",
"noSelection": "选择图层以查看其代码",
"noSelectionDesignJSX": "也可以编写 Design JSX,向页面添加新图层。",
- "noSelectionTailwindJSX": "Tailwind JSX 会为所选图层生成。",
+ "noSelectionComponents": "为所选图层生成 {framework} 组件。",
"writeJSX": "编写 JSX",
"canvasChangedExpression": "画布上现在是 {value};表达式保持原样。",
"canvasChangedOrder": "画布上这些图层的顺序已改变;代码保持原样。"
diff --git a/packages/vue/src/i18n/messages/code.ts b/packages/vue/src/i18n/messages/code.ts
index 37e603d9a..d38498dfa 100644
--- a/packages/vue/src/i18n/messages/code.ts
+++ b/packages/vue/src/i18n/messages/code.ts
@@ -5,8 +5,12 @@ import { i18n } from '#vue/i18n/create'
export const codeMessageDefaults = {
source: 'Code source',
sourceDesignJSX: 'Design JSX',
- sourceTailwindJSX: 'Tailwind JSX',
- sourceHTMLCSS: 'HTML/CSS',
+ sourceHTML: 'HTML',
+ sourceVue: 'Vue',
+ sourceReact: 'React',
+ styling: 'Styling',
+ stylingCSS: 'CSS',
+ stylingTailwind: 'Tailwind',
editorDesignLabel: 'Design JSX',
editorHTMLCSSLabel: 'HTML and CSS',
updating: 'Updating…',
@@ -20,7 +24,7 @@ export const codeMessageDefaults = {
canvasChangedOrder: 'The canvas now orders these layers differently; the code stays as written.',
noSelection: 'Select a layer to see its code',
noSelectionDesignJSX: 'Or write Design JSX to add new layers to the page.',
- noSelectionTailwindJSX: 'Tailwind JSX is generated for the selected layers.',
+ noSelectionComponents: params('{framework} components are generated for the selected layers.'),
writeJSX: 'Write JSX'
} as const
diff --git a/src/app/code/dom-preview.ts b/src/app/code/dom-preview.ts
index 08a906129..8cf49072c 100644
--- a/src/app/code/dom-preview.ts
+++ b/src/app/code/dom-preview.ts
@@ -1,5 +1,9 @@
import { sceneGraphFromStyledHTML } from '@open-pencil/core/io/formats/html/layers'
-import { browserHTMLToDesignDocument } from '@open-pencil/dom-css/browser'
+import {
+ browserHTMLToDesignDocument,
+ browserTailwindHTMLToDesignDocument
+} from '@open-pencil/dom-css/browser'
+import type { ComponentStyling } from '@open-pencil/dom-css/export'
import type { SceneGraph } from '@open-pencil/scene-graph'
import type { EditorStore } from '@/app/editor/active-store'
@@ -20,13 +24,33 @@ export function createDOMCodeSession(store: EditorStore): DOMCodeSession {
}
}
+/** Every class the markup names, which Tailwind builds its utilities for. */
+function classNames(html: string): string[] {
+ const parsed = new DOMParser().parseFromString(html, 'text/html')
+ return [...parsed.querySelectorAll('[class]')].flatMap((element) => [...element.classList])
+}
+
+/** Tailwind's own stylesheet, loaded with the first Tailwind preview rather than with the app. */
+async function loadTailwindStylesheet(): Promise<string> {
+ const { default: css } = await import('tailwindcss/index.css?raw')
+ return css
+}
+
+async function designDocument(source: string, styling: ComponentStyling) {
+ if (styling === 'css') return browserHTMLToDesignDocument(source)
+ return browserTailwindHTMLToDesignDocument(source, classNames(source), {
+ loadStylesheet: loadTailwindStylesheet
+ })
+}
+
export async function previewDOMCode(
store: EditorStore,
session: DOMCodeSession,
- source: string
+ source: string,
+ styling: ComponentStyling
): Promise<{ ok: true } | { ok: false; error: string }> {
try {
- const graph = sceneGraphFromStyledHTML(await browserHTMLToDesignDocument(source), {
+ const graph = sceneGraphFromStyledHTML(await designDocument(source, styling), {
pageName: 'Code preview'
})
const pageId = graph.getPages()[0]?.id ?? graph.rootId
diff --git a/src/app/code/generated.ts b/src/app/code/generated.ts
index a5c2756e6..0915cd56d 100644
--- a/src/app/code/generated.ts
+++ b/src/app/code/generated.ts
@@ -1,5 +1,11 @@
+import { vectorElement } from '@open-pencil/core/io'
import { selectionToJSXWithLayers } from '@open-pencil/design-jsx'
-import { sceneNodesToTailwindJSXWithLayers } from '@open-pencil/dom-css/export'
+import {
+ layerComponents,
+ layerMarkup,
+ type ComponentStyling,
+ type LayerComponent
+} from '@open-pencil/dom-css/export'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { starterSourceFor, type CodeSource } from '@/app/code/templates'
@@ -10,14 +16,45 @@ export interface GeneratedCode {
layerIds: ReadonlyArray<string | null>
}
-/** Code shown for the selection: editable Design JSX, or read-only Tailwind JSX. */
-export function generatedCodeFor(
- source: Exclude<CodeSource, 'html-css'>,
+/** Sources generated as the panel opens them, which take a moment: components and HTML. */
+export type AsyncCodeSource = Exclude<CodeSource, 'design-jsx'>
+
+/** Design JSX for the selection, or the starter for writing new layers. */
+export function generatedDesignJSX(graph: SceneGraph, nodeIds: string[]): GeneratedCode {
+ if (nodeIds.length === 0) return { code: starterSourceFor('design-jsx'), layerIds: [] }
+ return selectionToJSXWithLayers(nodeIds, graph)
+}
+
+/** Each file of each component under a comment naming it, as a project would hold them. */
+function componentFiles(files: readonly LayerComponent['files'][number][]): GeneratedCode {
+ const code = files
+ .map(({ path, content }) => {
+ const text = typeof content === 'string' ? content : new TextDecoder().decode(content)
+ if (path.endsWith('.vue')) return `<!-- ${path} -->\n${text}`
+ return path.endsWith('.css') ? `/* ${path} */\n${text}` : `// ${path}\n${text}`
+ })
+ .join('\n')
+ return { code, layerIds: files.flatMap((file) => file.layerIds ?? []) }
+}
+
+/**
+ * Code generated for the selection that takes a moment to make: Vue and React components, as
+ * the Storybook export generates them, and the same markup as HTML, images as the files they
+ * would be written to rather than inlined. Each is styled with a stylesheet or with Tailwind.
+ */
+export async function generatedCodeAsync(
+ source: AsyncCodeSource,
+ styling: ComponentStyling,
graph: SceneGraph,
nodeIds: string[]
-): GeneratedCode {
- if (nodeIds.length === 0) return { code: starterSourceFor(source), layerIds: [] }
- return source === 'tailwind-jsx'
- ? sceneNodesToTailwindJSXWithLayers(graph, nodeIds)
- : selectionToJSXWithLayers(nodeIds, graph)
+): Promise<GeneratedCode> {
+ if (source === 'html-css') {
+ const { html, css, layerIds } = await layerMarkup(graph, nodeIds, { vectorElement, styling })
+ // The stylesheet's own element comes first and draws no layer.
+ return css
+ ? { code: `<style>\n${css}\n</style>\n\n${html}`, layerIds: [null, ...layerIds] }
+ : { code: html, layerIds }
+ }
+ const components = await layerComponents(graph, nodeIds, source, { vectorElement, styling })
+ return componentFiles(components.flatMap((component) => component.files))
}
diff --git a/src/app/code/layers/issues.ts b/src/app/code/layers/issues.ts
index a45772f15..923dd53a9 100644
--- a/src/app/code/layers/issues.ts
+++ b/src/app/code/layers/issues.ts
@@ -46,9 +46,11 @@ function designJSXProps(issue: DesignIssue): readonly string[] {
}
}
-/** Tailwind carries every visual value in `className`; names come from `data-name`. */
-function tailwindProps(issue: DesignIssue): readonly string[] {
- return issue.ruleId === 'no-default-names' ? ['data-name'] : ['className']
+/** Generated markup's class holds its layer's name and styles, or its Tailwind utilities. */
+const CLASS_PROPS: Record<Exclude<CodeSource, 'design-jsx'>, readonly string[]> = {
+ 'html-css': ['class'],
+ vue: ['class'],
+ react: ['className']
}
/**
@@ -60,7 +62,6 @@ export function codeLayerIssues(
source: CodeSource,
messages: DesignCheckMessages
): LayerIssue[] {
- if (source === 'html-css') return []
return issues
.filter((issue) => issue.severity !== 'info')
.map((issue) => {
@@ -70,7 +71,7 @@ export function codeLayerIssues(
nodeId: issue.nodeId,
severity: issue.severity,
message: detail ? `${title} · ${detail}` : title,
- props: source === 'tailwind-jsx' ? tailwindProps(issue) : designJSXProps(issue)
+ props: source === 'design-jsx' ? designJSXProps(issue) : CLASS_PROPS[source]
}
})
}
diff --git a/src/app/code/styling.ts b/src/app/code/styling.ts
new file mode 100644
index 000000000..53997a7c2
--- /dev/null
+++ b/src/app/code/styling.ts
@@ -0,0 +1,18 @@
+import { useLocalStorage } from '@vueuse/core'
+import { computed } from 'vue'
+
+import { COMPONENT_STYLINGS, type ComponentStyling } from '@open-pencil/dom-css/export'
+
+const stored = useLocalStorage<string>('open-pencil:code-styling', 'css')
+
+function isStyling(value: string): value is ComponentStyling {
+ return COMPONENT_STYLINGS.some((styling) => styling === value)
+}
+
+/** How the Code tab styles generated HTML and components, remembered across sessions. */
+export const codeStyling = computed<ComponentStyling>({
+ get: () => (isStyling(stored.value) ? stored.value : 'css'),
+ set: (value) => {
+ stored.value = value
+ }
+})
diff --git a/src/app/code/templates.ts b/src/app/code/templates.ts
index 520ad334a..169c0cbc1 100644
--- a/src/app/code/templates.ts
+++ b/src/app/code/templates.ts
@@ -1,4 +1,6 @@
-export type CodeSource = 'design-jsx' | 'tailwind-jsx' | 'html-css'
+import type { ComponentStyling } from '@open-pencil/dom-css/export'
+
+export type CodeSource = 'design-jsx' | 'html-css' | 'vue' | 'react'
export const DESIGN_JSX_STARTER_SOURCE = '<Frame name="New frame" w={320} h={240} fill="#ffffff" />'
@@ -12,6 +14,9 @@ export const HTML_CSS_STARTER_SOURCE = `<style>
<div class="card">Hello</div>`
-export function starterSourceFor(language: CodeSource): string {
- return language === 'html-css' ? HTML_CSS_STARTER_SOURCE : DESIGN_JSX_STARTER_SOURCE
+export const HTML_TAILWIND_STARTER_SOURCE = '<div class="rounded-xl bg-white p-4">Hello</div>'
+
+export function starterSourceFor(language: CodeSource, styling: ComponentStyling = 'css'): string {
+ if (language !== 'html-css') return DESIGN_JSX_STARTER_SOURCE
+ return styling === 'tailwind' ? HTML_TAILWIND_STARTER_SOURCE : HTML_CSS_STARTER_SOURCE
}
diff --git a/src/components/CodePanel.vue b/src/components/CodePanel.vue
index 3e8af606e..f65b7da0e 100644
--- a/src/components/CodePanel.vue
+++ b/src/components/CodePanel.vue
@@ -23,7 +23,7 @@ import {
resetDOMCodePreview,
type DOMCodeSession
} from '@/app/code/dom-preview'
-import { generatedCodeFor, type GeneratedCode } from '@/app/code/generated'
+import { generatedCodeAsync, generatedDesignJSX } from '@/app/code/generated'
import { useCodeLayers } from '@/app/code/layers/use'
import {
createDesignJSXEditSession,
@@ -33,12 +33,14 @@ import {
type DesignJSXEditSession,
type DesignJSXLayerLine
} from '@/app/code/live-preview'
+import { codeStyling } from '@/app/code/styling'
import { starterSourceFor, type CodeSource } from '@/app/code/templates'
import { useEditorStore } from '@/app/editor/active-store'
import AppButton from '@/components/ui/button/AppButton.vue'
import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'
import Tip from '@/components/ui/overlay/Tip.vue'
import AppSelect from '@/components/ui/select/AppSelect.vue'
+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
import statusTheme from '@/theme/feedback/status'
const CodeEditor = defineAsyncComponent(() => import('@/components/code-editor/CodeEditor.vue'))
@@ -123,13 +125,27 @@ const codeLayers = useCodeLayers(source)
const sourceOptions = computed(() => [
{ value: 'design-jsx' as const, label: code.value.sourceDesignJSX },
- { value: 'tailwind-jsx' as const, label: code.value.sourceTailwindJSX },
- { value: 'html-css' as const, label: code.value.sourceHTMLCSS }
+ { value: 'html-css' as const, label: code.value.sourceHTML },
+ { value: 'vue' as const, label: code.value.sourceVue },
+ { value: 'react' as const, label: code.value.sourceReact }
])
-const readOnly = computed(() => source.value === 'tailwind-jsx')
-const editorLabel = computed(() =>
- source.value === 'html-css' ? code.value.editorHTMLCSSLabel : code.value.editorDesignLabel
-)
+const stylingOptions = computed(() => [
+ { value: 'css', label: code.value.stylingCSS },
+ { value: 'tailwind', label: code.value.stylingTailwind }
+])
+/** Components are generated; Design JSX and HTML are edited into layers. */
+const readOnly = computed(() => source.value === 'vue' || source.value === 'react')
+const editorLabel = computed(() => {
+ if (source.value === 'html-css') return code.value.editorHTMLCSSLabel
+ if (source.value === 'vue') return code.value.sourceVue
+ if (source.value === 'react') return code.value.sourceReact
+ return code.value.editorDesignLabel
+})
+/** What the empty state says each generated source shows for a selection. */
+const emptyDescription = computed(() => {
+ if (source.value === 'design-jsx') return code.value.noSelectionDesignJSX
+ return code.value.noSelectionComponents({ framework: editorLabel.value })
+})
const statusTone = computed(() => {
if (status.value === 'error') return 'error'
if (status.value === 'updated') return 'success'
@@ -193,7 +209,7 @@ async function runPreview(version: number): Promise<void> {
let previewLayers: DesignJSXLayerLine[] | null = null
try {
if (source.value === 'html-css') {
- result = await previewDOMCode(store, beginDOMSession(), draft.value)
+ result = await previewDOMCode(store, beginDOMSession(), draft.value, codeStyling.value)
} else {
const session = beginDesignSession()
const preview = session
@@ -264,33 +280,58 @@ async function resetDraft(): Promise<void> {
error.value = ''
status.value = 'idle'
edited.value = false
- if (source.value === 'html-css') draft.value = starterSourceFor('html-css')
- else showCanvas(source.value)
+ showCanvas(source.value)
}
-async function changeSource(next: CodeSource): Promise<void> {
- if (next === source.value) return
+/** Keeps what the current code previewed, then shows the selection in another format or styling. */
+async function regenerate(change: () => void): Promise<void> {
await commitCurrentSession()
- source.value = next
+ change()
edited.value = false
error.value = ''
status.value = 'idle'
- if (next === 'html-css') {
- codeLayers.showGenerated(null)
- draft.value = starterSourceFor(next)
- } else {
- showCanvas(next)
- }
+ showCanvas(source.value)
+}
+
+function changeSource(next: CodeSource): Promise<void> | undefined {
+ if (next === source.value) return
+ return regenerate(() => (source.value = next))
+}
+
+function changeStyling(next: string): Promise<void> | undefined {
+ if (next === codeStyling.value || (next !== 'css' && next !== 'tailwind')) return
+ return regenerate(() => (codeStyling.value = next))
}
const selectionKey = computed(() => [...store.state.selectedIds].join(','))
+/** Generations of components and HTML in flight; only the latest shows. */
+let generation = 0
+
/** Shows the code generated for the selection, replacing whatever the editor held. */
-function showCanvas(next: Exclude<CodeSource, 'html-css'>) {
- const generated: GeneratedCode = generatedCodeFor(next, store.graph, [...store.state.selectedIds])
+function showCanvas(next: CodeSource) {
+ const selected = [...store.state.selectedIds]
followedSelection = selectionKey.value
- codeLayers.showGenerated(generated)
- draft.value = generated.code
+ if (next === 'design-jsx') {
+ const generated = generatedDesignJSX(store.graph, selected)
+ codeLayers.showGenerated(generated)
+ draft.value = generated.code
+ return
+ }
+ const current = ++generation
+ if (selected.length === 0) {
+ codeLayers.showGenerated(null)
+ if (next === 'html-css') draft.value = starterSourceFor(next, codeStyling.value)
+ return
+ }
+ const styling = codeStyling.value
+ void generatedCodeAsync(next, styling, store.graph, selected).then((generated) => {
+ if (current !== generation || source.value !== next || codeStyling.value !== styling)
+ return generated
+ codeLayers.showGenerated(generated)
+ draft.value = generated.code
+ return generated
+ })
}
/**
@@ -300,8 +341,10 @@ function showCanvas(next: Exclude<CodeSource, 'html-css'>) {
*/
function followCanvas(live = false) {
const current = source.value
- if (!editorActive.value || current === 'html-css' || previewing > 0) return
+ if (!editorActive.value || previewing > 0) return
if (selectionKey.value !== followedSelection) {
+ // HTML/CSS written for the last selection is kept as it was previewed.
+ if (current === 'html-css' && edited.value) void commitCurrentSession()
if (designSession.value) designSession.value = null
edited.value = false
}
@@ -309,6 +352,8 @@ function followCanvas(live = false) {
showCanvas(current)
return
}
+ // HTML/CSS someone wrote stays as written: unlike Design JSX, it has no links to patch.
+ if (current === 'html-css') return
// A live preview leaves the scene version alone, so it is followed whatever the version.
if (!live && store.state.sceneVersion === previewedVersion) return
codeEditor.value?.patchFromLayers()
@@ -352,7 +397,16 @@ watch(
:ui="{ trigger: 'h-7 min-w-0 flex-1 text-[11px]' }"
@update:model-value="changeSource"
/>
- <Tip v-if="source !== 'html-css'" :label="code.copyJSXReference">
+ <SegmentedControl
+ v-if="source !== 'design-jsx'"
+ :model-value="codeStyling"
+ :options="stylingOptions"
+ :label="code.styling"
+ data-test-id="code-panel-styling"
+ :ui="{ root: 'shrink-0' }"
+ @update:model-value="changeStyling"
+ />
+ <Tip v-if="source === 'design-jsx'" :label="code.copyJSXReference">
<AppButton
color="neutral"
variant="ghost"
@@ -370,9 +424,7 @@ watch(
<AppPlaceholder
v-if="showEmptyState"
:label="code.noSelection"
- :description="
- source === 'design-jsx' ? code.noSelectionDesignJSX : code.noSelectionTailwindJSX
- "
+ :description="emptyDescription"
:fill="false"
:ui="{ root: 'pt-10' }"
data-test-id="code-panel-empty"
diff --git a/src/components/code-editor/CodeEditor.vue b/src/components/code-editor/CodeEditor.vue
index 741f4b822..1ad59fef0 100644
--- a/src/components/code-editor/CodeEditor.vue
+++ b/src/components/code-editor/CodeEditor.vue
@@ -79,7 +79,7 @@ const RUNTIME_TYPES = new Map(
let externalUpdate = false
function languageExtensions(language: CodeEditorLanguage): Extension {
- if (language === 'html-css') return html()
+ if (language === 'html-css' || language === 'vue') return html()
return [
javascript({ jsx: true, typescript: true }),
...(language === 'design-jsx' ? designJSXExtensions() : [])
diff --git a/src/components/code-editor/layers/issues.ts b/src/components/code-editor/layers/issues.ts
index 698cc44b0..6f7cd8191 100644
--- a/src/components/code-editor/layers/issues.ts
+++ b/src/components/code-editor/layers/issues.ts
@@ -6,7 +6,13 @@ import { designJSXPropertyNames } from '@open-pencil/design-jsx'
import type { LayerIssue } from '@/app/code/layers/issues'
-import { layerLinkConfig, linkedElements, setLayerLinks, type LinkedElement } from './links'
+import {
+ ELEMENT_NODES,
+ layerLinkConfig,
+ linkedElements,
+ setLayerLinks,
+ type LinkedElement
+} from './links'
import { staleAttributes } from './stale'
export const setLayerIssues = StateEffect.define<readonly LayerIssue[]>()
@@ -39,8 +45,8 @@ function attributeRange(
to: element.openTo,
enter(node) {
// Ancestors contain the element; only nested elements' attributes belong to others.
- if (node.name === 'JSXElement' && node.from > element.from) return false
- if (node.name !== 'JSXAttribute') return undefined
+ if (ELEMENT_NODES.has(node.name) && node.from > element.from) return false
+ if (node.name !== 'JSXAttribute' && node.name !== 'Attribute') return undefined
const name = node.node.firstChild
const rank = name ? names.indexOf(state.doc.sliceString(name.from, name.to)) : -1
if (rank !== -1) matches.push({ from: node.from, to: node.to, rank })
diff --git a/src/components/code-editor/layers/links.ts b/src/components/code-editor/layers/links.ts
index 7b9de387d..5b7403c7b 100644
--- a/src/components/code-editor/layers/links.ts
+++ b/src/components/code-editor/layers/links.ts
@@ -73,9 +73,13 @@ const TAG_NAMES = new Set([
'JSXIdentifier',
'JSXBuiltin',
'JSXMemberExpression',
- 'JSXNamespacedName'
+ 'JSXNamespacedName',
+ 'TagName'
])
+/** Elements of JSX, and of HTML, which generated HTML and Vue templates are written in. */
+export const ELEMENT_NODES = new Set(['JSXElement', 'Element'])
+
interface ParsedElement {
from: number
to: number
@@ -89,7 +93,12 @@ interface ParsedElement {
}
function openingTag(element: SyntaxNode): SyntaxNode | null {
- return element.getChild('JSXOpenTag') ?? element.getChild('JSXSelfClosingTag')
+ return (
+ element.getChild('JSXOpenTag') ??
+ element.getChild('JSXSelfClosingTag') ??
+ element.getChild('OpenTag') ??
+ element.getChild('SelfClosingTag')
+ )
}
function tagName(tag: SyntaxNode): SyntaxNode | null {
@@ -99,7 +108,7 @@ function tagName(tag: SyntaxNode): SyntaxNode | null {
return null
}
-/** JSX elements in pre-order, the order in which exporters write layers. */
+/** Elements in pre-order, the order in which exporters write layers. */
function parseElements(state: EditorState, from = 0, to = state.doc.length): ParsedElement[] {
const tree = ensureSyntaxTree(state, state.doc.length, 250) ?? syntaxTree(state)
const elements: ParsedElement[] = []
@@ -108,11 +117,11 @@ function parseElements(state: EditorState, from = 0, to = state.doc.length): Par
to,
enter(node) {
if (node.from < from || node.to > to) return
- if (node.name !== 'JSXElement') return
+ if (!ELEMENT_NODES.has(node.name)) return
const tag = openingTag(node.node)
const name = tag && tagName(tag)
if (!tag || !name) return
- const closeTag = node.node.getChild('JSXCloseTag')
+ const closeTag = node.node.getChild('JSXCloseTag') ?? node.node.getChild('CloseTag')
const closeName = closeTag && tagName(closeTag)
elements.push({
from: node.from,
diff --git a/tests/e2e/code/layer-links.spec.ts b/tests/e2e/code/layer-links.spec.ts
index 97e9d560f..401b55c5b 100644
--- a/tests/e2e/code/layer-links.spec.ts
+++ b/tests/e2e/code/layer-links.spec.ts
@@ -127,6 +127,26 @@ test('design issues are underlined on the property that causes them', async () =
await expect(warning).toHaveText('size={10}')
})
+for (const [format, swatch, finePrint] of [
+ ['React', 'styles.card__swatch', 'className={styles["card__fine-print"]}'],
+ ['Vue', 'class="card__swatch"', 'class="card__fine-print"'],
+ ['HTML', '<div class="card__swatch">', 'class="card__fine-print"']
+] as const) {
+ test(`generated ${format} links its elements and issues to their layers`, async () => {
+ await buildScene(editor.page)
+ await openCode(editor.page)
+ await editor.page.getByTestId('code-panel-source').click()
+ await editor.page.getByRole('option', { name: format, exact: true }).click()
+
+ // Clicks the class, which is inside the element whatever the indentation.
+ await codeLine(editor.page, swatch).getByText('card__swatch').click()
+ await expect.poll(() => focusedLayer(editor.page)).toBe('Swatch')
+ // Generated markup names each layer by its class, which carries the offending style.
+ const warning = editor.page.locator('[data-slot="code-editor"] .cm-lintRange-warning')
+ await expect(warning).toHaveText(finePrint)
+ })
+}
+
test('links follow the code after a live edit', async () => {
await buildScene(editor.page)
await openCode(editor.page)
diff --git a/tests/e2e/code/panel.spec.ts b/tests/e2e/code/panel.spec.ts
index 76e2a6474..64b281192 100644
--- a/tests/e2e/code/panel.spec.ts
+++ b/tests/e2e/code/panel.spec.ts
@@ -150,7 +150,7 @@ test('HTML/CSS live preview commits as one undoable session', async () => {
await editor.canvas.drawRect(80, 80, 120, 90)
const originalId = await getFirstSelectedNodeId(editor.page)
await openCodePanel()
- await selectSource('HTML/CSS')
+ await selectSource('HTML')
await codeEditor().fill('<div style="width: 180px; height: 90px">First</div>')
await expect.poll(() => hasNode(editor.page, originalId)).toBe(false)
await codeEditor().fill('<div style="width: 220px; height: 110px">Final</div>')
@@ -172,7 +172,7 @@ test('switching source formats commits the current live session', async () => {
await openCodePanel()
await codeEditor().fill('<Frame name="Committed on switch" />')
await waitForNodeNamed(editor.page, 'Committed on switch')
- await selectSource('HTML/CSS')
+ await selectSource('HTML')
await expect(codeEditor()).toContainText('<style>')
await expect.poll(() => getUndoLabel(editor.page)).toBe('Edit JSX')
await editor.page.keyboard.press('Meta+z')
@@ -192,7 +192,7 @@ test('Reset before debounce cancels the pending preview', async () => {
test('HTML/CSS uses the same editor and live reloads the canvas', async () => {
await openCodePanel()
- await selectSource('HTML/CSS')
+ await selectSource('HTML')
await expect(codePanel().locator('[data-slot="code-editor"]')).toHaveCount(1)
await expect(codeEditor()).toHaveAttribute('aria-label', 'HTML and CSS')
await codeEditor().fill(
@@ -203,13 +203,63 @@ test('HTML/CSS uses the same editor and live reloads the canvas', async () => {
expect(importedNodes.some((node) => node.type !== 'DOCUMENT' && node.type !== 'PAGE')).toBe(true)
})
-test('Tailwind JSX is generated read-only in the same editor', async () => {
+test('HTML/CSS shows the selection as markup with its stylesheet', async () => {
await editor.canvas.drawRect(100, 100, 200, 150)
await openCodePanel()
- await selectSource('Tailwind JSX')
- await expect(editor.page.getByTestId('code-panel-status')).toContainText('Generated, read only')
- // It still takes a cursor, which marks the layer of the element around it.
- await expect(codeEditor()).toHaveAttribute('aria-readonly', 'true')
+ await selectSource('HTML')
+ // The layer's class names its rule, rather than the starter for writing new layers.
+ await expect(codeEditor()).toContainText(
+ /<style>\.(\S+) \{ width: 200px; height: 150px;.*<div class="\1">/
+ )
+ // It stays editable, to rewrite the selection as HTML.
+ await expect(codeEditor()).toHaveAttribute('aria-readonly', 'false')
+})
+
+for (const [label, generated] of [
+ ['Vue', /<!-- (\w+)\.vue -->.*<template>.*<\/template>/],
+ ['React', /\/\/ (\w+)\.tsx.*export function \1\(/]
+] as const) {
+ test(`${label} generates the selection as a component, read-only`, async () => {
+ await editor.canvas.drawRect(100, 100, 200, 150)
+ await openCodePanel()
+ await selectSource(label)
+ await expect(codeEditor()).toContainText(generated)
+ await expect(editor.page.getByTestId('code-panel-status')).toContainText('Generated, read only')
+ await expect(codeEditor()).toHaveAttribute('aria-readonly', 'true')
+ })
+}
+
+async function selectStyling(label: string) {
+ await editor.page.getByTestId('code-panel-styling').getByRole('button', { name: label }).click()
+}
+
+test('Tailwind styles generated components and HTML with utilities, remembered', async () => {
+ await editor.canvas.drawRect(100, 100, 200, 150)
+ await openCodePanel()
+ await expect(editor.page.getByTestId('code-panel-styling')).toHaveCount(0)
+ await selectSource('React')
+ await selectStyling('Tailwind')
+ await expect(codeEditor()).toContainText(
+ /\/\/ (\w+)\.tsx.*className=\{\[\s*"[^"]*w-50 h-\[150px\]/
+ )
+ await expect(codeEditor()).not.toContainText('.module.css')
+
+ await selectSource('HTML')
+ await expect(codeEditor()).toContainText(/^<div class="[^"]*w-50 h-\[150px\]/)
+ await expect(codeEditor()).not.toContainText('<style>')
+ // Written HTML is built with Tailwind's utilities, as the canvas shows them.
+ await codeEditor().fill('<div class="w-60 h-30 p-4 bg-red-500">Tailwind</div>')
+ await expect
+ .poll(() => getCodeNodeSummaries(editor.page))
+ .toContainEqual(expect.objectContaining({ width: 240, height: 120 }))
+
+ await editor.page.reload()
+ await editor.canvas.waitForInit()
+ await editor.canvas.drawRect(100, 100, 200, 150)
+ await openCodePanel()
+ await selectSource('Vue')
+ await expect(codeEditor()).toContainText(/<template>.*class="[^"]*w-50/)
+ await selectStyling('CSS')
})
test('copy button works and shows confirmation', async () => {
diff --git a/tests/engine/cli/export/storybook.test.ts b/tests/engine/cli/export/storybook.test.ts
index 6b43f5466..29c767302 100644
--- a/tests/engine/cli/export/storybook.test.ts
+++ b/tests/engine/cli/export/storybook.test.ts
@@ -119,6 +119,38 @@ test('export CLI re-exports generated components into the folder it wrote them t
expect(await Bun.file(join(output, 'Old.module.css')).exists()).toBe(false)
})
+test('export CLI --css tailwind styles components with utilities instead of a stylesheet', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))
+ const figPath = await writeComponentFixture(dir, ['Badge'])
+ const output = join(dir, 'stories')
+ const args = [...STORYBOOK_EXPORT, '--framework', 'react', '--no-design-images']
+
+ const invalid = await runOpenPencilCLI([
+ 'export',
+ figPath,
+ ...args,
+ '--css',
+ 'sass',
+ '--output',
+ output
+ ])
+ expect(invalid.exitCode).toBe(1)
+ expect(invalid.stderr).toContain('Use inline or tailwind')
+
+ const { exitCode } = await runOpenPencilCLI([
+ 'export',
+ figPath,
+ ...args,
+ '--css',
+ 'tailwind',
+ '--output',
+ output
+ ])
+ expect(exitCode).toBe(0)
+ expect(await outputEntries(output)).toEqual(['Badge.stories.ts', 'Badge.tsx'])
+ expect(await Bun.file(join(output, 'Badge.tsx')).text()).toContain('"group/badge w-8 h-4')
+})
+
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')
diff --git a/tests/helpers/code-panel.ts b/tests/helpers/code-panel.ts
index 80cea2ae2..8ea9533f2 100644
--- a/tests/helpers/code-panel.ts
+++ b/tests/helpers/code-panel.ts
@@ -4,6 +4,8 @@ export type CodeNodeSummary = {
type: string
name: string
text: string
+ width: number
+ height: number
}
export function getFirstSelectedNodeId(page: Page): Promise<string | null> {
@@ -51,7 +53,9 @@ export function getCodeNodeSummaries(page: Page): Promise<CodeNodeSummary[]> {
return [...store.graph.getAllNodes()].map((node) => ({
type: node.type,
name: node.name,
- text: node.text
+ text: node.text,
+ width: node.width,
+ height: node.height
}))
})
}
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index 39972d822..26cb4be08 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -114,7 +114,6 @@ ja:automation.webmcpUnsupported
ja:code.copyJSXReference
ja:code.editorHTMLCSSLabel
ja:code.noSelectionDesignJSX
-ja:code.noSelectionTailwindJSX
ja:code.writeJSX
ja:collaboration.invalidRoomLink
ja:collaboration.joinRoomDescription
@@ -313,7 +312,6 @@ zh-cn:automation.webmcpUnsupported
zh-cn:code.copyJSXReference
zh-cn:code.editorHTMLCSSLabel
zh-cn:code.noSelectionDesignJSX
-zh-cn:code.noSelectionTailwindJSX
zh-cn:code.writeJSX
zh-cn:collaboration.invalidRoomLink
zh-cn:collaboration.joinRoomDescription
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index 0b14aaae7..60db14ae2 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -12,8 +12,12 @@ de:automation.status
de:automation.version
de:code.editorDesignLabel
de:code.sourceDesignJSX
-de:code.sourceHTMLCSS
-de:code.sourceTailwindJSX
+de:code.sourceHTML
+de:code.sourceVue
+de:code.sourceReact
+de:code.styling
+de:code.stylingCSS
+de:code.stylingTailwind
de:common.ok
de:diagnostics.categoryMCP
de:diagnostics.categoryRenderer
@@ -75,8 +79,11 @@ es:ai.toolError
es:automation.statusError
es:code.editorDesignLabel
es:code.sourceDesignJSX
-es:code.sourceHTMLCSS
-es:code.sourceTailwindJSX
+es:code.sourceHTML
+es:code.sourceVue
+es:code.sourceReact
+es:code.stylingCSS
+es:code.stylingTailwind
es:common.tokens
es:diagnostics.categoryMCP
es:diagnostics.durationMs
@@ -114,8 +121,11 @@ fr:automation.port
fr:automation.version
fr:code.editorDesignLabel
fr:code.sourceDesignJSX
-fr:code.sourceHTMLCSS
-fr:code.sourceTailwindJSX
+fr:code.sourceHTML
+fr:code.sourceVue
+fr:code.sourceReact
+fr:code.stylingCSS
+fr:code.stylingTailwind
fr:collaboration.microphone
fr:common.ok
fr:diagnostics.categoryDocument
@@ -184,8 +194,11 @@ it:ai.completions
it:ai.responses
it:code.editorDesignLabel
it:code.sourceDesignJSX
-it:code.sourceHTMLCSS
-it:code.sourceTailwindJSX
+it:code.sourceHTML
+it:code.sourceVue
+it:code.sourceReact
+it:code.stylingCSS
+it:code.stylingTailwind
it:common.ok
it:diagnostics.categoryMCP
it:diagnostics.categoryRenderer
@@ -219,8 +232,11 @@ it:storage.providerBackblaze
it:storage.providerR2
ja:code.editorDesignLabel
ja:code.sourceDesignJSX
-ja:code.sourceHTMLCSS
-ja:code.sourceTailwindJSX
+ja:code.sourceHTML
+ja:code.sourceVue
+ja:code.sourceReact
+ja:code.stylingCSS
+ja:code.stylingTailwind
ja:diagnostics.categoryAI
ja:diagnostics.categoryMCP
ja:diagnostics.durationMs
@@ -241,8 +257,11 @@ pl:ai.responses
pl:automation.port
pl:code.editorDesignLabel
pl:code.sourceDesignJSX
-pl:code.sourceHTMLCSS
-pl:code.sourceTailwindJSX
+pl:code.sourceHTML
+pl:code.sourceVue
+pl:code.sourceReact
+pl:code.stylingCSS
+pl:code.stylingTailwind
pl:common.ok
pl:diagnostics.categoryAI
pl:diagnostics.categoryMCP
@@ -271,8 +290,11 @@ ru:ai.completions
ru:ai.responses
ru:code.editorDesignLabel
ru:code.sourceDesignJSX
-ru:code.sourceHTMLCSS
-ru:code.sourceTailwindJSX
+ru:code.sourceHTML
+ru:code.sourceVue
+ru:code.sourceReact
+ru:code.stylingCSS
+ru:code.stylingTailwind
ru:diagnostics.categoryMCP
ru:panels.ai
ru:panels.colorFormatHsb
@@ -288,8 +310,11 @@ zh-cn:ai.completions
zh-cn:ai.responses
zh-cn:code.editorDesignLabel
zh-cn:code.sourceDesignJSX
-zh-cn:code.sourceHTMLCSS
-zh-cn:code.sourceTailwindJSX
+zh-cn:code.sourceHTML
+zh-cn:code.sourceVue
+zh-cn:code.sourceReact
+zh-cn:code.stylingCSS
+zh-cn:code.stylingTailwind
zh-cn:diagnostics.categoryAI
zh-cn:diagnostics.categoryMCP
zh-cn:panels.ai