Skip to content

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

fix(dom-css): give a Vue field's input the caller's attributes (#1731)

Danila Poyarkov9b91153aef8c
diff --git a/changes/1731/fixed.md b/changes/1731/fixed.md
new file mode 100644
index 000000000..314bf8128
--- /dev/null
+++ b/changes/1731/fixed.md
@@ -0,0 +1 @@
+- A Vue text field or textarea exported as code puts the attributes it is given, such as `name`, `required`, or `aria-invalid`, on its input rather than its wrapper, as the React components do (#1731).
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index 2716e6d9f..2fd06bb97 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -197,7 +197,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` (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. A form control whose set draws an invalid state takes an `invalid` prop, which sets `aria-invalid` on the control a person fills in (a field's input, or the root of a switch, checkbox, or radio) and `data-invalid` on the root, which its invalid styles key on. 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. A form control whose set draws an invalid state takes an `invalid` prop, which sets `aria-invalid` on the control a person fills in (a field's input, or the root of a switch, checkbox, or radio) and `data-invalid` on the root, which its invalid styles key on. 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`. A text field or textarea puts the attributes it is given, such as `name`, `required`, or `aria-invalid`, on its input, and a `class` on its root, in both frameworks. 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/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
index 1aaa4b91a..ecfccd6d8 100644
--- a/packages/dom-css/src/export/components/model.ts
+++ b/packages/dom-css/src/export/components/model.ts
@@ -167,6 +167,18 @@ export type ComponentNode =
| ComponentReference
| IconReference
+/**
+ * Whether a field's markup always draws its input, which then takes the caller's attributes. A
+ * field whose text is not bound yet has none, and an input inside a slot is replaced when the
+ * caller fills the slot; the root takes the attributes then.
+ */
+export function drawsInput(node: ComponentElement): boolean {
+ return node.children.some(
+ (child) =>
+ child.type === 'input' || (child.type === 'element' && !child.slot && drawsInput(child))
+ )
+}
+
/** One component generated from a component set with a behaviour. */
export interface ComponentModel {
/** The component's identifier and file name. */
diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.ts
index d5d489a50..9f95964ad 100644
--- a/packages/dom-css/src/export/components/vue.ts
+++ b/packages/dom-css/src/export/components/vue.ts
@@ -11,6 +11,7 @@ import type { ShaderComponent } from '@open-pencil/scene-graph/shaders'
import { claimName } from '../storybook/names'
import { progressWidth } from './fields'
import {
+ drawsInput,
FIELD_KINDS,
type ComponentBinding,
type ComponentElement,
@@ -85,9 +86,26 @@ const REKA: Record<
plain: { parts: {} }
}
-/** Kinds whose two-way value is their input's, which binds it rather than the root. */
+/**
+ * Kinds whose two-way value is their input's, which binds it rather than the root. Their input
+ * takes the caller's attributes too, such as `name` or `required`, and the root only `class`,
+ * as the React components spread the caller's props on the input.
+ */
const INPUT_MODEL: ReadonlySet<GeneratedKind> = new Set(['textField', 'textarea'])
+/** Whether the caller's attributes go to the field's input: it is a field, and draws one. */
+const attrsToInput = (component: ComponentModel) =>
+ INPUT_MODEL.has(component.kind) && drawsInput(component.tree)
+
+/** The caller's attributes but `class`, which the root takes, for a field's input. */
+const INPUT_ATTRS = es.parseExpression('{ ...$attrs, class: undefined }')
+
+/** The caller's `class`, which a field's root takes since its attributes go to the input. */
+const ROOT_CLASS = es.parseExpression('$attrs.class')
+
+/** The caller's attributes reach the input rather than falling through to the root. */
+const NO_ATTRS_FALLTHROUGH = es.parseModule('defineOptions({ inheritAttrs: false })')
+
/** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */
const ROOT_ATTRIBUTES: Partial<Record<GeneratedKind, vue.VueAttribute[]>> = {
toggleGroup: [vue.attribute('type', 'single')],
@@ -110,8 +128,8 @@ const INVALID_FLAG = es.parseExpression('invalid || undefined')
const ariaInvalid = () => vue.bound('aria-invalid', INVALID_FLAG)
/**
- * A field's input reads an `aria-invalid` the caller set too: the caller's attributes fall
- * through to the root, so the input would not otherwise see it.
+ * A field's input keeps an `aria-invalid` the caller set while `invalid` is off, which the
+ * binding after the caller's attributes would otherwise replace.
*/
const INPUT_ARIA_INVALID = es.parseExpression("invalid || $attrs['aria-invalid']")
const inputAriaInvalid = () => vue.bound('aria-invalid', INPUT_ARIA_INVALID)
@@ -184,6 +202,8 @@ function inputNode(className: string, uses: TemplateUses): vue.VueElement {
vue.attribute('class', uses.classOf(className)),
...(component.model ? [vue.model(identifier(component.model))] : []),
...(placeholder ? [vue.attribute('placeholder', placeholder)] : []),
+ // The caller's attributes, such as `name` or a placeholder of its own, after the design's.
+ vue.spread(INPUT_ATTRS),
...(component.disabled ? [vue.bound('disabled', identifier('disabled'))] : []),
...(component.invalid ? [inputAriaInvalid()] : [])
])
@@ -248,6 +268,7 @@ function elementAttributes(
vue.attribute(name, value)
),
vue.attribute('class', compact([node.attrs.class, uses.classOf(node.className)]).join(' ')),
+ ...(root && attrsToInput(uses.component) ? [vue.bound('class', ROOT_CLASS)] : []),
...(node.value === undefined ? [] : [vue.attribute('value', node.value)]),
...(node.disabled ? [vue.bound('disabled', es.parseExpression('true'))] : []),
...node.bindings.flatMap((binding) => bindingAttributes(binding, uses, native))
@@ -448,10 +469,17 @@ function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {
const refs = uses.models.flatMap(
(item) => es.fill(MODEL_REF, { $name: identifier(item.name) }).body
)
+ const options = attrsToInput(component) ? NO_ATTRS_FALLTHROUGH.body : []
return {
type: 'Program',
sourceType: 'module',
- body: [...scriptImports(uses), ...props, ...modelDeclaration(component, uses), ...refs]
+ body: [
+ ...scriptImports(uses),
+ ...options,
+ ...props,
+ ...modelDeclaration(component, uses),
+ ...refs
+ ]
}
}
diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.ts
index 31cc1c9b7..88e151e50 100644
--- a/packages/dom-css/tests/export/components/vue.test.ts
+++ b/packages/dom-css/tests/export/components/vue.test.ts
@@ -7,6 +7,7 @@ import {
accordionComponent,
buttonSet,
collapsibleSet,
+ componentSet,
invalidCheckboxSet,
labelledButtonSet,
numberFieldComponent,
@@ -30,6 +31,8 @@ import { createSSRApp, h, type Component } from 'vue'
import { compileScript, parse } from 'vue/compiler-sfc'
import { renderToString } from 'vue/server-renderer'
+import { emptyBehaviour } from '@open-pencil/scene-graph/behaviours'
+
/** The packages generated code imports, linked so it resolves them as an app would. */
const APP_PACKAGES = ['vue', 'reka-ui', '@iconify/vue', 'storybook', 'shaders']
@@ -369,6 +372,82 @@ describe('generated Vue form controls', () => {
expect(placeholder?.color).toBe('#9CA3B0')
})
+ // As the React field spreads its props on the input and gives its root the caller's className.
+ test("a field's input takes the caller's attributes, and its root the caller's class", async () => {
+ for (const fixture of [textFieldSet(), textFieldSet({ invalid: true }), textareaComponent()]) {
+ const { component } = await generate(fixture)
+ const html = await render(component, {
+ name: 'email',
+ required: true,
+ placeholder: '[email protected]',
+ 'aria-invalid': 'true',
+ class: 'wide'
+ })
+ const root = /^<div[^>]*>/.exec(html)?.[0] ?? ''
+ const input = /<(?:input|textarea)[^>]*>/.exec(html)?.[0] ?? ''
+ expect(root).toContain('wide')
+ expect(root).not.toContain('name=')
+ expect(root).not.toContain('aria-invalid')
+ expect(input).toContain('name="email"')
+ expect(input).toContain('required')
+ expect(input).toContain('aria-invalid="true"')
+ expect(input).not.toContain('wide')
+ if (fixture.set.name === 'Email') expect(input).toContain('placeholder="[email protected]"')
+ }
+ })
+
+ test('a field with no text bound yet draws no input, and its root takes the attributes', async () => {
+ const fixture = componentSet(
+ 'Message',
+ { Size: ['Default'] },
+ emptyBehaviour('textarea'),
+ (graph, variant) => {
+ graph.createNode('TEXT', variant, { name: 'Hint', text: 'Tell us more' })
+ }
+ )
+ const { files, component } = await generate(fixture)
+ expect(fileText(files, 'Message.vue')).not.toContain('inheritAttrs')
+ const html = await render(component, { 'data-testid': 'message', class: 'wide' })
+ expect(html).toMatch(/^<div[^>]*data-testid="message"/)
+ expect(html).toMatch(/^<div[^>]*class="[^"]*wide/)
+ })
+
+ test('a field whose input sits in a slot keeps its attributes on the root', async () => {
+ const fixture = componentSet(
+ 'Message',
+ { Size: ['Default'] },
+ { ...emptyBehaviour('textarea'), texts: { value: { propertyId: 'message' } } },
+ (graph, variant) => {
+ const body = graph.createNode('FRAME', variant, {
+ name: 'Body',
+ width: 200,
+ height: 60,
+ componentPropertyReferences: [{ propertyId: 'body', field: 'SLOT_CONTENT' }]
+ })
+ graph.createNode('TEXT', body.id, {
+ name: 'Value',
+ text: 'Tell us more',
+ componentPropertyReferences: [{ propertyId: 'message', field: 'TEXT' }]
+ })
+ }
+ )
+ fixture.graph.updateNode(fixture.set.id, {
+ componentPropertyDefinitions: [
+ ...fixture.set.componentPropertyDefinitions,
+ { id: 'message', name: 'Message', type: 'TEXT', defaultValue: 'Tell us more' },
+ { id: 'body', name: 'Body', type: 'SLOT', defaultValue: '' }
+ ]
+ })
+ const { files, component } = await generate(fixture)
+ const source = fileText(files, 'Message.vue')
+ // The slot's own content replaces the input, so the attributes stay where Vue puts them.
+ expect(source).toContain('<slot name="body">')
+ expect(source).not.toContain('inheritAttrs')
+ expect(await render(component, { 'data-testid': 'message' })).toMatch(
+ /^<div[^>]*data-testid="message"/
+ )
+ })
+
test('a textarea starts with its words', async () => {
const { component } = await generate(textareaComponent())
expect(await render(component)).toMatch(/<textarea[^>]*>Tell us more<\/textarea>/)
diff --git a/packages/emit/src/vue.ts b/packages/emit/src/vue.ts
index 7e069b301..90aa16d21 100644
--- a/packages/emit/src/vue.ts
+++ b/packages/emit/src/vue.ts
@@ -17,6 +17,11 @@ export type VueAttribute =
| { type: 'model'; argument?: string; expression: SyntaxNode }
/** `v-if="expression"`: the element renders only while the expression holds. */
| { type: 'if'; expression: SyntaxNode }
+ /**
+ * `v-bind="expression"`: every attribute of an object, such as `$attrs`. Attributes after it
+ * override its own of the same name, as Vue merges them in order.
+ */
+ | { type: 'spread'; expression: SyntaxNode }
export interface VueElement {
type: 'element'
@@ -58,6 +63,8 @@ export const model = (expression: SyntaxNode, argument?: string): VueAttribute =
export const renderIf = (expression: SyntaxNode): VueAttribute => ({ type: 'if', expression })
+export const spread = (expression: SyntaxNode): VueAttribute => ({ type: 'spread', expression })
+
export const element = (
tag: string,
attributes: VueAttribute[] = [],
@@ -76,6 +83,7 @@ function printAttribute(item: VueAttribute): string {
const value = escapeAttribute(printExpression(item.expression))
if (item.type === 'bound') return `:${item.name}="${value}"`
if (item.type === 'if') return `v-if="${value}"`
+ if (item.type === 'spread') return `v-bind="${value}"`
return `${item.argument ? `v-model:${item.argument}` : 'v-model'}="${value}"`
}
diff --git a/packages/emit/tests/vue.test.ts b/packages/emit/tests/vue.test.ts
index c0c739e18..53e3ff082 100644
--- a/packages/emit/tests/vue.test.ts
+++ b/packages/emit/tests/vue.test.ts
@@ -153,3 +153,15 @@ describe('conditional elements', () => {
)
})
})
+
+describe('spread attributes', () => {
+ test('bind an object with v-bind, before the attributes that override it', () => {
+ const node = vue.element('input', [
+ vue.spread(es.parseExpression('{ ...$attrs, class: undefined }')),
+ vue.attribute('class', 'field')
+ ])
+ expect(vue.printTemplate(node)).toBe(
+ '<input v-bind="({ ...$attrs, class: undefined })" class="field" />'
+ )
+ })
+})