Skip to content

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

feat: edit variables as tokens in the variables dialog (#907)

Danila Poyarkov03b70328bf7e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f60522718..7e3ab19ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,10 +6,10 @@
- `SkiaRenderer.hitTestFrameTitle` no longer takes the selected IDs: it finds the name of any frame on the page or in a section under a point, selected or not.
- `SceneNode.booleanOperation` is a required key whose value may be `undefined`, like every other scene node field, so code that builds `SceneNode` objects itself must include it.
+- `useVariables().collections` from `@open-pencil/vue` returns copies of the document's collections instead of the graph's own objects, so components see modes added or renamed in place; change collections through the editor's actions rather than by mutating the returned objects. `addVariable` returns the new variable's ID.
- `sceneNodeToDesignDocument` from `@open-pencil/dom-css` takes an options object, `{ includeSourceIds, tokens }`, instead of a boolean third argument; `tokens: false` writes literal values instead of variable references.
- `randomHex`, `randomInt`, and `randomIndex` moved from `@open-pencil/core/random` and the `@open-pencil/core` barrel to `@open-pencil/scene-graph/random`.
- `Stroke` from `@open-pencil/scene-graph` extends `Fill`, so every stroke states a paint `type` that code constructing one must set to `'SOLID'`, and `copyStroke` deep-copies the paint fields a fill already copied.
-- `Stroke` from `@open-pencil/scene-graph` extends `Fill`, so every stroke states a paint `type` that code constructing one must set to `'SOLID'`, and `copyStroke` deep-copies the paint fields a fill already copied. Rendering, `.fig` round-trips, and the stroke panel still handle solid strokes only.
- The `design_to_tokens` AI and MCP tool writes a stylesheet of CSS custom properties built from the document's variables. Its `tailwind` format is a Tailwind v4 `@theme` instead of a JavaScript object, and the `json` format is removed. Names come from the variable's code syntax or from Tailwind namespaces (`--color-gray-50`) instead of the collection name, aliases stay `var()` references instead of resolving through the first mode, and non-default modes go under their condition (`[data-theme="dark"]` by default) instead of a class named after the mode. The result lists the tokens it left out under `issues`.
- The editor state's `remoteCursors` is now `presenceCursors`, typed `PresenceCursor[]` from `@open-pencil/core/canvas`, and each cursor has a `kind` of `'person'` or `'agent'`.
- `VariableBinding` and the `colorVariableBinding` paint field are gone from `@open-pencil/core`, `@open-pencil/core/kiwi`, and the Kiwi `Paint` type. `fig.kiwi` never defined the field, so only `.fig` files OpenPencil itself wrote before `colorVar` contain one; reopening such a file leaves the paint's colour unbound, and binding it again records it the way Figma does.
@@ -39,7 +39,8 @@
- See which layer the code is about in the Code tab's Design JSX and Tailwind JSX: the element around the cursor marks its opening and closing tag and shows its layer on the canvas as a tinted box, apart from canvas hover, and design issues are underlined on the property that causes them, including while you edit Design JSX live.
- Fix lint issues outside the app: `openpencil lint --fix -o fixed.fig` binds colors to the variable they match and rounds subpixel geometry, and the `lint` and `lint_fix` tools let MCP clients and AI chat check a page and apply those fixes, plus radius, spacing, text size, group-to-frame, and hidden-layer suggestions on request. Lint messages carry each fix as data in `fix` and `suggestions`.
- Mark layers with errors and warnings on the canvas while you work, and pin those outside the view to the canvas edge in their direction, with matching marks in the Layers panel and error and warning counts in the page list; hover a marker or pin for its issues or click it to open them in Lint, and turn markers on or off with View → Design issues.
-- Copy the document's variables as a CSS stylesheet or a Tailwind v4 theme from the variables dialog's collection menu, or print them with `openpencil tokens`. Each collection's default mode goes in `:root` (or `@theme`, with a `@custom-variant` per mode), other modes override under their condition, `[data-theme="dark"]` unless the mode names a selector or `@media` query, and aliases stay `var()` references that follow the mode. Variables CSS cannot express, such as booleans, are named instead of written.
+- Copy the document's variables as a CSS stylesheet or a Tailwind v4 theme from the variables dialog, or print them with `openpencil tokens`. Each collection's default mode goes in `:root` (or `@theme`, with a `@custom-variant` per mode), other modes override under their condition, `[data-theme="dark"]` unless the mode names a selector or `@media` query, and aliases stay `var()` references that follow the mode. Variables CSS cannot express, such as booleans, are named instead of written.
+- Edit variables as design tokens in the redesigned variables dialog, opened from View → Variables…, the command palette, or the Design panel, and expandable to most of the window. Collections and the groups inside them are listed in a sidebar with counts; picking a group, a type filter, or a search, which matches names, CSS names, descriptions, and values with the command palette's typo-tolerant matching, narrows the list, which shows each variable's type, CSS name, and a value per mode. Names and number or text values edit in place, rows reorder by dragging, and Shift- or Cmd-clicking selects several to duplicate, move into a group, or delete from the context menu, the Delete key, or the side panel. Selecting one edits its name, CSS name (checked against CSS before it is saved), unit, per-mode values or CSS expressions such as `clamp()`, scopes, description, and publishing, and points a value at another variable of the same type or detaches it again. The collection settings rename and delete the collection, add, rename, duplicate, delete, and choose the default mode, and choose when each mode applies in plain words, such as *System is in dark mode* or *Screen is narrower than 640px*, with the CSS it writes shown underneath and a custom selector or `@media`, `@supports`, or `@container` query when no preset fits. The active collection's stylesheet updates live below the list, and copying offers CSS or a Tailwind v4 theme. Undo and redo work in the dialog as they do on the canvas, with one step per change and one per color picker session, while a field with uncommitted text keeps its own undo. The dialog lays out by its own width: in a narrow window or on a phone it shows one mode at a time and opens a variable, the collection settings, or the stylesheet over the list.
- Follow collaborators and their AI agents from the avatars in the toolbar: an avatar counts that person's agents, hovering lists what each is doing and on which page, and clicking follows. A frame in their color and a “Following …” bar show whom you follow; Escape, clicking, scrolling, zooming, or switching pages stops it. Your own avatar renames your agents and leaves the room.
- See where the built-in AI chat is working: while it replies, a cursor whose outlined label shows a sparkle and a callsign such as *Fern* marks the layers it edits. In a shared room, collaborators see each other's agents in the color of the person running them.
- See which pages people and AI agents are working on: the Pages panel marks those pages in their colors and, on hover, shows who is there with what their agents are doing and a button to follow them; the command palette names who is there, and the chat offers **Go to page** while its reply works on a page you're not viewing. On phones, the room pill shows the people in the room as avatars beside the room's status.
@@ -96,6 +97,7 @@
- Show the blinking caret in a new, empty text layer before the first character is typed.
- Text saved to `.fig` or copied to Figma keeps its layout in Figma: it wraps at the layer's width with its alignment and line height, and keeps ligatures and contextual forms such as Inter's arrows, where Figma previously drew every saved OpenPencil text layer on one unwrapped line (#914).
- Release a document's memory when its tab closes. Every closed tab kept its scene, canvas, and editor panels alive until reload, so memory grew with each document opened and closed. Menus and shortcuts now also follow the active document, so Undo and Redo are offered according to its history rather than the first document opened.
+- Put a deleted variable back in its place in its collection when the deletion is undone, instead of at the end.
- Start Pi chats with OpenPencil's MCP tools when the Harness companion runs on Node 22.15 or later; the companion now installs the dependency Pi's MCP adapter needs and loads its TypeScript sources. A reopened Pi session starts fresh instead of failing to resume its in-memory sandbox, and npm output from Pi no longer mixes into the companion's protocol.
- Import HTML and CSS with the right shadow and border colors. A shadow whose color follows its lengths, as CSS usually writes it, and a `border` with a color function such as `rgb(226, 232, 240)` came in black. Every layer of a `box-shadow` list now imports, `inset` ones as inner shadows, and lengths in `%`, `em`, or `vh` are no longer read as pixels.
- Accept a CSS `box-shadow` list in design JSX's `shadow` prop: the color may come first, a fourth length sets the spread, several layers add several shadows, and `inset` makes an inner shadow. A color before the lengths or a spread made the shadow black.
diff --git a/bun.lock b/bun.lock
index 423d3bc65..9bdf6035d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -16,6 +16,7 @@
"@chenglou/pretext": "^0.0.7",
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
+ "@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
@@ -289,6 +290,7 @@
"dependencies": {
"@acemir/cssom": "^0.9.31",
"@open-pencil/emit": "workspace:*",
+ "css-tree": "^3.2.1",
"dedent": "^1.7.2",
"es-toolkit": "^1.52.0",
"js-base64": "^3.9.3",
@@ -299,6 +301,7 @@
},
"devDependencies": {
"@types/bun": "^1.3.14",
+ "@types/css-tree": "^3.2.0",
"tsdown": "^0.22.14",
"typescript": "~5.8.3",
},
@@ -2050,6 +2053,8 @@
"@types/chai": ["@types/[email protected]", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],
+ "@types/css-tree": ["@types/[email protected]", "", {}, "sha512-J5KXmk6BFIepOT7280FdFyNs4c5fh0Uee0otjKEvzchrRs38Ii9qminqc4ds0L19X8Zd/rT+brR9jkBthygjWw=="],
+
"@types/culori": ["@types/[email protected]", "", {}, "sha512-43M51r/22CjhbOXyGT361GZ9vncSVQ39u62x5eJdBQFviI8zWp2X5jzqg7k4M6PVgDQAClpy2bUe2dtwEgEDVQ=="],
"@types/debug": ["@types/[email protected]", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],
diff --git a/desktop/generated/menu.json b/desktop/generated/menu.json
index 059e0d557..0c6a0227d 100644
--- a/desktop/generated/menu.json
+++ b/desktop/generated/menu.json
@@ -179,6 +179,13 @@
{
"type": "separator"
},
+ {
+ "id": "variables",
+ "label": "Variables…"
+ },
+ {
+ "type": "separator"
+ },
{
"id": "view-rulers",
"label": "Rulers",
diff --git a/package.json b/package.json
index c92c0f957..93c3b6cb6 100644
--- a/package.json
+++ b/package.json
@@ -111,6 +111,7 @@
"@chenglou/pretext": "^0.0.7",
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
+ "@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index eb0d47bad..d4d1cf139 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -19,6 +19,7 @@ export { graphFromPageSnapshot } from './history/snapshot-graph'
export type { ClipboardPayload, ClipboardSnapshot } from './clipboard/copy'
export { resolvePasteTarget } from './clipboard/paste-target'
export type { Editor } from './create'
+export type { VariableTokenFields } from './variables'
export { reapplyInstanceComponentProperties } from './components/properties'
export { createGuideActions } from './guides'
export { createTextActions } from './text'
diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.ts
index 3bd8cfe1c..e6f79317e 100644
--- a/packages/core/src/editor/variables.ts
+++ b/packages/core/src/editor/variables.ts
@@ -1,4 +1,8 @@
+import { omit, omitBy } from 'es-toolkit/object'
+import { isEmptyObject } from 'es-toolkit/predicate'
+
import type {
+ TokenExpression,
Variable,
VariableCollection,
VariableType,
@@ -9,7 +13,56 @@ import { reconcileVariableLayouts } from '#core/layout/variables'
import type { EditorContext } from './types'
+/** What a variable means as a design token beyond its values: how CSS and code read it. */
+export type VariableTokenFields = Pick<
+ Variable,
+ 'unit' | 'expressions' | 'scopes' | 'codeSyntax' | 'description' | 'hiddenFromPublishing'
+>
+
+/** Every token field, unset ones included, so restoring it also clears what was added. */
+function tokenFields(variable: Variable): VariableTokenFields {
+ const { unit, expressions, scopes, codeSyntax, description, hiddenFromPublishing } = variable
+ return structuredClone({
+ unit,
+ expressions,
+ scopes,
+ codeSyntax,
+ description,
+ hiddenFromPublishing
+ })
+}
+
+/** A mode's value with the CSS expression written for it, which the value must keep matching. */
+interface ModeEntry {
+ value: VariableValue | undefined
+ expression: TokenExpression | undefined
+}
+
+function modeEntry(variable: Variable, modeId: string): ModeEntry {
+ return structuredClone({
+ value: variable.valuesByMode[modeId],
+ expression: variable.expressions?.[modeId]
+ })
+}
+
+function setModeEntry(variable: Variable, modeId: string, entry: ModeEntry) {
+ const { value, expression } = structuredClone(entry)
+ const values = omit(variable.valuesByMode, [modeId])
+ variable.valuesByMode = value === undefined ? values : { ...values, [modeId]: value }
+ const others = omit(variable.expressions ?? {}, [modeId])
+ const expressions: Record<string, TokenExpression> = expression
+ ? { ...others, [modeId]: expression }
+ : others
+ if (isEmptyObject(expressions)) delete variable.expressions
+ else variable.expressions = expressions
+}
+
export function createVariableActions(ctx: EditorContext) {
+ /**
+ * Re-resolves every bound layer, for changes to what variables resolve to. Adding, copying, or
+ * reordering variables changes no bound value, so those only request a render: re-resolving
+ * there would resize layers a file saved at a size their binding no longer gives.
+ */
function refreshVariables() {
reconcileVariableLayouts(ctx.graph)
ctx.requestRender()
@@ -77,14 +130,14 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Add collection',
forward: () => {
ctx.graph.addCollection(collection)
- refreshVariables()
+ ctx.requestRender()
},
inverse: () => {
ctx.graph.removeCollection(collection.id)
- refreshVariables()
+ ctx.requestRender()
}
})
- refreshVariables()
+ ctx.requestRender()
}
function removeCollection(id: string) {
@@ -117,20 +170,21 @@ export function createVariableActions(ctx: EditorContext) {
label: 'Add variable',
forward: () => {
ctx.graph.addVariable(variable)
- refreshVariables()
+ ctx.requestRender()
},
inverse: () => {
ctx.graph.removeVariable(variable.id)
- refreshVariables()
+ ctx.requestRender()
}
})
- refreshVariables()
+ ctx.requestRender()
}
function removeVariable(id: string) {
const variable = ctx.graph.variables.get(id)
if (!variable) return
const snapshot = structuredClone(variable)
+ const order = [...(ctx.graph.variableCollections.get(variable.collectionId)?.variableIds ?? [])]
ctx.graph.removeVariable(id)
ctx.undo.push({
label: 'Remove variable',
@@ -138,14 +192,76 @@ export function createVariableActions(ctx: EditorContext) {
ctx.graph.removeVariable(id)
refreshVariables()
},
+ // Undo puts the variable back where it was, not at the end of its collection.
inverse: () => {
- ctx.graph.addVariable(snapshot)
+ ctx.graph.addVariable(structuredClone(snapshot))
+ placeVariables(snapshot.collectionId, order)
refreshVariables()
}
})
refreshVariables()
}
+ /** Puts a collection's variables in `order`; ids it does not hold are ignored. */
+ function placeVariables(collectionId: string, order: readonly string[]) {
+ const collection = ctx.graph.variableCollections.get(collectionId)
+ if (!collection) return
+ const held = new Set(collection.variableIds)
+ const placed = order.filter((id) => held.has(id))
+ const rest = collection.variableIds.filter((id) => !placed.includes(id))
+ collection.variableIds = [...placed, ...rest]
+ }
+
+ /** Reorders a collection's variables in one undo step; the order is what files and lists show. */
+ function setVariableOrder(collectionId: string, order: readonly string[]) {
+ const collection = ctx.graph.variableCollections.get(collectionId)
+ if (!collection) return
+ const previous = [...collection.variableIds]
+ const next = [...order]
+ placeVariables(collectionId, next)
+ if (previous.join('\n') === collection.variableIds.join('\n')) return
+ ctx.undo.push({
+ label: 'Reorder variables',
+ forward: () => {
+ placeVariables(collectionId, next)
+ ctx.requestRender()
+ },
+ inverse: () => {
+ placeVariables(collectionId, previous)
+ ctx.requestRender()
+ }
+ })
+ ctx.requestRender()
+ }
+
+ /** Copies a variable, values and token fields included, right after the original. */
+ function duplicateVariable(id: string, name: string): string | undefined {
+ const source = ctx.graph.variables.get(id)
+ const collection = source && ctx.graph.variableCollections.get(source.collectionId)
+ if (!source || !collection) return undefined
+ const created = ctx.graph.createVariable(name, source.type, source.collectionId)
+ const copy: Variable = { ...structuredClone(source), id: created.id, name }
+ ctx.graph.addVariable(copy)
+ const before = [...collection.variableIds]
+ const order = before.filter((candidate) => candidate !== copy.id)
+ order.splice(order.indexOf(id) + 1, 0, copy.id)
+ placeVariables(collection.id, order)
+ ctx.undo.push({
+ label: 'Duplicate variable',
+ forward: () => {
+ ctx.graph.addVariable(structuredClone(copy))
+ placeVariables(collection.id, order)
+ ctx.requestRender()
+ },
+ inverse: () => {
+ ctx.graph.removeVariable(copy.id)
+ ctx.requestRender()
+ }
+ })
+ ctx.requestRender()
+ return copy.id
+ }
+
function renameVariable(id: string, newName: string) {
const variable = ctx.graph.variables.get(id)
if (!variable) return
@@ -301,29 +417,99 @@ export function createVariableActions(ctx: EditorContext) {
refreshVariables()
}
- function updateVariableValue(id: string, modeId: string, value: VariableValue) {
+ /**
+ * Sets one mode's value. Calls that share a `coalesceKey`, such as the steps of one color picker
+ * drag, undo together.
+ */
+ function updateVariableValue(
+ id: string,
+ modeId: string,
+ value: VariableValue,
+ coalesceKey?: string
+ ) {
const variable = ctx.graph.variables.get(id)
if (!variable) return
- const prevValue = structuredClone(variable.valuesByMode[modeId])
- const newValue = structuredClone(value)
- variable.valuesByMode[modeId] = newValue
+ const previous = modeEntry(variable, modeId)
+ // A number keeps its expression, which records the number it stands for; anything else drops it.
+ const expression = previous.expression
+ const next: ModeEntry = {
+ value: structuredClone(value),
+ expression:
+ typeof value === 'number' && expression ? { ...expression, resolved: value } : undefined
+ }
+ const apply = (entry: ModeEntry) => {
+ const target = ctx.graph.variables.get(id)
+ if (target) setModeEntry(target, modeId, entry)
+ refreshVariables()
+ }
+ apply(next)
ctx.undo.push({
label: 'Update variable value',
- forward: () => {
- const v = ctx.graph.variables.get(id)
- if (v) v.valuesByMode[modeId] = structuredClone(newValue)
- refreshVariables()
- },
- inverse: () => {
- const v = ctx.graph.variables.get(id)
- if (v) v.valuesByMode[modeId] = structuredClone(prevValue)
- refreshVariables()
+ forward: () => apply(next),
+ inverse: () => apply(previous),
+ coalesceKey
+ })
+ }
+
+ /** Change token fields in one undo step; a field set to `undefined` is cleared. */
+ function updateVariableToken(id: string, patch: Partial<VariableTokenFields>) {
+ const variable = ctx.graph.variables.get(id)
+ if (!variable) return
+ const previous = tokenFields(variable)
+ const next = structuredClone(patch)
+ const apply = (values: Partial<VariableTokenFields>) => {
+ const target = ctx.graph.variables.get(id)
+ if (!target) return
+ const { description, ...fields } = structuredClone(values)
+ // A cleared field is removed, not kept as a key set to `undefined`.
+ for (const key of Object.keys(fields) as Array<keyof typeof fields>) {
+ if (fields[key] === undefined) Reflect.deleteProperty(target, key)
}
+ Object.assign(
+ target,
+ omitBy(fields, (value) => value === undefined)
+ )
+ // Every variable has a description; clearing it leaves an empty one.
+ if ('description' in values) target.description = description ?? ''
+ ctx.requestRender()
+ }
+ apply(next)
+ ctx.undo.push({
+ label: 'Update variable token',
+ forward: () => apply(next),
+ inverse: () => apply(previous)
+ })
+ }
+
+ /** The selector or query a mode applies under; an empty condition restores the default. */
+ function setModeCondition(collectionId: string, modeId: string, condition: string | undefined) {
+ const mode = ctx.graph.variableCollections
+ .get(collectionId)
+ ?.modes.find((candidate) => candidate.modeId === modeId)
+ if (!mode) return
+ const previous = mode.condition
+ const next = condition?.trim() || undefined
+ if (next === previous) return
+ const apply = (value: string | undefined) => {
+ const target = ctx.graph.variableCollections
+ .get(collectionId)
+ ?.modes.find((candidate) => candidate.modeId === modeId)
+ if (target) target.condition = value
+ ctx.requestRender()
+ }
+ apply(next)
+ ctx.undo.push({
+ label: 'Set mode condition',
+ forward: () => apply(next),
+ inverse: () => apply(previous)
})
- refreshVariables()
}
return {
+ updateVariableToken,
+ setModeCondition,
+ duplicateVariable,
+ setVariableOrder,
getVariablesByType,
getVariable,
resolveColorVariable,
diff --git a/packages/core/tests/editor/undo/variable-bindings.test.ts b/packages/core/tests/editor/undo/variable/bindings.test.ts
similarity index 100%
rename from packages/core/tests/editor/undo/variable-bindings.test.ts
rename to packages/core/tests/editor/undo/variable/bindings.test.ts
diff --git a/packages/core/tests/editor/undo/variable-modes.test.ts b/packages/core/tests/editor/undo/variable/modes.test.ts
similarity index 100%
rename from packages/core/tests/editor/undo/variable-modes.test.ts
rename to packages/core/tests/editor/undo/variable/modes.test.ts
diff --git a/packages/core/tests/editor/undo/variable/tokens.test.ts b/packages/core/tests/editor/undo/variable/tokens.test.ts
new file mode 100644
index 000000000..5eaabf9e2
--- /dev/null
+++ b/packages/core/tests/editor/undo/variable/tokens.test.ts
@@ -0,0 +1,178 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+function themeEditor() {
+ const editor = createEditor()
+ editor.graph.addCollection({
+ id: 'theme',
+ name: 'Theme',
+ modes: [
+ { modeId: 'light', name: 'Light' },
+ { modeId: 'dark', name: 'Dark' }
+ ],
+ defaultModeId: 'light',
+ variableIds: []
+ })
+ editor.graph.addVariable({
+ id: 'gutter',
+ name: 'Gutter',
+ type: 'FLOAT',
+ collectionId: 'theme',
+ valuesByMode: { light: 24, dark: 24 },
+ description: '',
+ hiddenFromPublishing: false
+ })
+ return editor
+}
+
+describe('variable token undo', () => {
+ test('token fields change together and undo restores them', () => {
+ const editor = themeEditor()
+ const gutter = () => editor.graph.variables.get('gutter')
+
+ editor.updateVariableToken('gutter', {
+ unit: 'rem',
+ scopes: ['GAP'],
+ expressions: { light: { css: 'clamp(1rem, 4vw, 1.5rem)', resolved: 24 } },
+ description: 'Space between cards'
+ })
+ expect(gutter()).toMatchObject({
+ unit: 'rem',
+ scopes: ['GAP'],
+ expressions: { light: { css: 'clamp(1rem, 4vw, 1.5rem)', resolved: 24 } },
+ description: 'Space between cards'
+ })
+
+ editor.undo.undo()
+ expect(gutter()?.unit).toBeUndefined()
+ expect(gutter()?.scopes).toBeUndefined()
+ expect(gutter()?.expressions).toBeUndefined()
+ expect(gutter()?.description).toBe('')
+
+ editor.undo.redo()
+ expect(gutter()?.unit).toBe('rem')
+ })
+
+ test('clearing a field leaves the others and keeps a description', () => {
+ const editor = themeEditor()
+ editor.updateVariableToken('gutter', { unit: 'rem', description: 'Gap' })
+
+ editor.updateVariableToken('gutter', { unit: undefined, description: undefined })
+
+ expect(editor.graph.variables.get('gutter')).toMatchObject({ description: '' })
+ expect(editor.graph.variables.get('gutter')?.unit).toBeUndefined()
+ })
+
+ test('a mode condition is set, cleared by an empty value, and undone', () => {
+ const editor = themeEditor()
+ const dark = () =>
+ editor.graph.variableCollections.get('theme')?.modes.find((mode) => mode.modeId === 'dark')
+
+ editor.setModeCondition('theme', 'dark', ' @media (prefers-color-scheme: dark) ')
+ expect(dark()?.condition).toBe('@media (prefers-color-scheme: dark)')
+
+ editor.setModeCondition('theme', 'dark', '')
+ expect(dark()?.condition).toBeUndefined()
+
+ editor.undo.undo()
+ expect(dark()?.condition).toBe('@media (prefers-color-scheme: dark)')
+ editor.undo.undo()
+ expect(dark()?.condition).toBeUndefined()
+ })
+
+ test('hiding from publishing is a token field and undoes with the others', () => {
+ const editor = themeEditor()
+
+ editor.updateVariableToken('gutter', { hiddenFromPublishing: true })
+ expect(editor.graph.variables.get('gutter')?.hiddenFromPublishing).toBe(true)
+
+ editor.undo.undo()
+ expect(editor.graph.variables.get('gutter')?.hiddenFromPublishing).toBe(false)
+ })
+
+ test('a duplicate copies every field, sits after the original, and undoes', () => {
+ const editor = themeEditor()
+ editor.updateVariableToken('gutter', { unit: 'rem', scopes: ['GAP'] })
+
+ const copyId = editor.duplicateVariable('gutter', 'Gutter copy')
+ if (!copyId) throw new Error('the variable was not duplicated')
+ const copy = editor.graph.variables.get(copyId)
+
+ expect(copy).toMatchObject({
+ name: 'Gutter copy',
+ unit: 'rem',
+ scopes: ['GAP'],
+ valuesByMode: { light: 24, dark: 24 }
+ })
+ expect(editor.graph.variableCollections.get('theme')?.variableIds).toEqual(['gutter', copyId])
+
+ editor.undo.undo()
+ expect(editor.graph.variables.has(copyId)).toBe(false)
+ editor.undo.redo()
+ expect(editor.graph.variableCollections.get('theme')?.variableIds).toEqual(['gutter', copyId])
+ })
+
+ test('reordering variables is one undo step', () => {
+ const editor = themeEditor()
+ const other = editor.graph.createVariable('Other', 'FLOAT', 'theme', 4)
+ const order = () => editor.graph.variableCollections.get('theme')?.variableIds
+
+ editor.setVariableOrder('theme', [other.id, 'gutter'])
+ expect(order()).toEqual([other.id, 'gutter'])
+
+ editor.undo.undo()
+ expect(order()).toEqual(['gutter', other.id])
+ })
+
+ test('undoing a delete puts the variable back in its place', () => {
+ const editor = themeEditor()
+ const other = editor.graph.createVariable('Other', 'FLOAT', 'theme', 4)
+ const order = () => editor.graph.variableCollections.get('theme')?.variableIds
+
+ editor.removeVariable('gutter')
+ editor.undo.undo()
+
+ expect(order()).toEqual(['gutter', other.id])
+ })
+
+ test('value edits that share a coalesce key undo as one step', () => {
+ const editor = themeEditor()
+ const light = () => editor.graph.variables.get('gutter')?.valuesByMode.light
+
+ editor.updateVariableValue('gutter', 'light', 25, 'drag-1')
+ editor.updateVariableValue('gutter', 'light', 26, 'drag-1')
+ editor.updateVariableValue('gutter', 'light', 30, 'drag-2')
+
+ editor.undo.undo()
+ expect(light()).toBe(26)
+ editor.undo.undo()
+ expect(light()).toBe(24)
+ })
+
+ test('undoing a field that was unset removes it rather than leaving it undefined', () => {
+ const editor = themeEditor()
+ editor.updateVariableToken('gutter', { unit: 'rem' })
+ editor.undo.undo()
+
+ expect(Object.hasOwn(editor.graph.variables.get('gutter') ?? {}, 'unit')).toBe(false)
+ })
+
+ test('an expression follows its number, goes with an alias, and undoes with the value', () => {
+ const editor = themeEditor()
+ const gutter = () => editor.graph.variables.get('gutter')
+ const clamp = 'clamp(1rem, 4vw, 1.5rem)'
+ editor.updateVariableToken('gutter', { expressions: { light: { css: clamp, resolved: 24 } } })
+
+ editor.updateVariableValue('gutter', 'light', 20)
+ expect(gutter()?.expressions).toEqual({ light: { css: clamp, resolved: 20 } })
+
+ editor.updateVariableValue('gutter', 'light', { aliasId: 'other' })
+ expect(gutter()?.expressions).toBeUndefined()
+
+ editor.undo.undo()
+ expect(gutter()?.expressions).toEqual({ light: { css: clamp, resolved: 20 } })
+ editor.undo.undo()
+ expect(gutter()?.expressions).toEqual({ light: { css: clamp, resolved: 24 } })
+ })
+})
diff --git a/packages/core/tests/editor/variables/list-changes.test.ts b/packages/core/tests/editor/variables/list-changes.test.ts
new file mode 100644
index 000000000..ce5b9060e
--- /dev/null
+++ b/packages/core/tests/editor/variables/list-changes.test.ts
@@ -0,0 +1,47 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+/** A layer saved at 24 while its binding resolves to 40, as layers in imported files can be. */
+function drifted() {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Size')
+ const size = graph.createVariable('Icon/Large', 'FLOAT', collection.id, 40)
+ const avatar = graph.createNode('FRAME', graph.getPages()[0].id, {
+ width: 24,
+ height: 24,
+ boundVariables: { width: size.id }
+ })
+ return { editor: createEditor({ graph }), collection, size, avatar }
+}
+
+test('adding, copying, and reordering variables leaves bound layers as saved', () => {
+ const { editor, collection, size, avatar } = drifted()
+ const added = 'var:added'
+
+ editor.addVariable({
+ id: added,
+ name: 'New number',
+ type: 'FLOAT',
+ collectionId: collection.id,
+ valuesByMode: { [collection.defaultModeId]: 0 },
+ description: '',
+ hiddenFromPublishing: false
+ })
+ editor.duplicateVariable(size.id, 'Icon/Large copy')
+ editor.setVariableOrder(collection.id, [added, size.id])
+ editor.undo.undo()
+ editor.undo.undo()
+ editor.undo.undo()
+
+ expect(avatar.width).toBe(24)
+})
+
+test('a value edit resolves the layers bound to it', () => {
+ const { editor, collection, size, avatar } = drifted()
+
+ editor.updateVariableValue(size.id, collection.defaultModeId, 48)
+
+ expect(avatar.width).toBe(48)
+})
diff --git a/packages/docs/de/user-guide/variables.md b/packages/docs/de/user-guide/variables.md
index 214e39c00..891905682 100644
--- a/packages/docs/de/user-guide/variables.md
+++ b/packages/docs/de/user-guide/variables.md
@@ -5,34 +5,83 @@ description: Designvariablen, Sammlungen, Modi und Farbbindungen in OpenPencil.
# Variablen
-Variablen speichern wiederverwendbare Designtoken wie Farben und Abstände. Objekteigenschaften können daran gebunden werden. Ändert sich ein Variablenwert, werden alle verbundenen Objekte aktualisiert.
+Variablen speichern wiederverwendbare Designtoken wie Farben, Abstände und andere Eigenschaften, die an Objekte gebunden werden können. Ändert sich ein Variablenwert, werden alle Objekte aktualisiert, die ihn verwenden.
-## Variablen öffnen
+## Variablen-Dialog öffnen
-Wenn kein Objekt ausgewählt ist, zeigt der Bereich Design die Seiteneigenschaften. Das Einstellungssymbol im Bereich Variablen öffnet den Dialog.
+Der Dialog öffnet sich über **Ansicht → Variablen…**, über die Suche nach „Variablen“ in der Befehlspalette oder, wenn kein Objekt ausgewählt ist, im Bereich Variablen des Bereichs Design. **Erweitern** in der Ecke des Dialogs gibt ihm den größten Teil des Fensters.
-## Sammlungen und Modi
+Der Dialog listet links die Variablen der aktiven Sammlung auf, bearbeitet rechts die ausgewählte Variable oder die Sammlung und zeigt darunter das daraus entstehende Stylesheet. In einem schmalen Fenster oder auf dem Smartphone zeigt er jeweils einen Modus an. Eine Variable, die Sammlungseinstellungen oder das Stylesheet öffnen sich dann über der Liste mit einer Zurück-Schaltfläche.
-Variablen sind in Sammlungen organisiert. Jede Sammlung erscheint als Registerkarte und kann mehrere Modi wie Hell und Dunkel enthalten. Die Modi werden als Tabellenspalten dargestellt.
+## Sammlungen
-## Variablen bearbeiten
+Variablen sind in Sammlungen organisiert. In einem breiten Dialog stehen sie in einer Seitenleiste mit der Anzahl der Variablen je Sammlung; schmaler erscheinen sie als Registerkarten, auf dem Smartphone als Menü.
-- Variable erstellen;
-- Namen oder Wert durch Klick auf die Zelle ändern;
-- Liste über das Suchfeld filtern.
+- **Sammlung wechseln:** in der Seitenleiste oder auf der Registerkarte darauf klicken
+- **Sammlung erstellen:** neben **Sammlungen** auf **+** oder in der Werkzeugleiste auf die Ordner-Schaltfläche (**Sammlung erstellen**) klicken
+- **Umbenennen oder löschen:** Ist keine Variable ausgewählt, bearbeitet die rechte Seite die Sammlung: Dort lässt sich der Name ändern oder die Sammlung über das Menü **⋯** neben dem Namen löschen (**Sammlung löschen**)
-Farbwerte werden direkt in der Tabelle mit einem Farbfeld und einer Farbauswahl bearbeitet.
+## Modi
-Die Typen `FLOAT`, `STRING` und `BOOLEAN` sind im Datenmodell vorhanden, besitzen aber noch keine vollständige Bearbeitungsoberfläche.
+Jede Sammlung kann mehrere Modi enthalten (z. B. Hell und Dunkel). Die Modi erscheinen als Wertespalten in der Liste, und eine Variable hat für jeden Modus einen Wert. Verwaltet werden sie in den **Sammlungseinstellungen**:
-## Bindungen für Füllungen und Konturen
+- **Modus hinzufügen:** auf **+** neben **Modi** klicken
+- **Umbenennen:** den Namen des Modus bearbeiten
+- **Duplizieren, als Standard festlegen, löschen:** das Menü **⋯** neben dem Modus verwenden (**Modus duplizieren**, **Als Standard festlegen**, **Modus löschen**)
-Die Variablenauswahl in den Bereichen Füllung und Kontur verbindet eine Farbvariable mit der jeweiligen Farbeigenschaft.
+Der Standardmodus ist **Immer aktiv** und steht in `:root`. Jeder andere Modus hat **Gilt wenn**; das legt fest, wann der Modus im exportierten Stylesheet greift, und das CSS, das daraus entsteht, steht darunter:
-Das Öffnen eines Feldes oder der Auswahl verändert die Bindung nicht. Erst eine tatsächliche Wertänderung kann sie abhängig vom verwendeten Steuerelement lösen oder die Variable selbst ändern.
+| Gilt wenn | CSS |
+| --- | --- |
+| **manuell umgeschaltet wird** | ein Attribut, das nach Sammlung und Modus benannt ist, etwa `[data-theme="dark"]` für den Modus Dunkel einer Sammlung Theme |
+| **das System im Dunkelmodus ist** / **das System im Hellmodus ist** | `@media (prefers-color-scheme: dark)` / `light` |
+| **hoher Kontrast aktiv ist** | `@media (prefers-contrast: more)` |
+| **reduzierte Bewegung aktiv ist** | `@media (prefers-reduced-motion: reduce)` |
+| **der Bildschirm schmaler ist als** / **der Bildschirm breiter ist als** eine Breite | `@media (max-width: 640px)` / `min-width` |
+| **der Container schmaler ist als** / **der Container breiter ist als** eine Breite | `@container (max-width: 640px)` / `min-width` |
+| **Benutzerdefiniertes CSS** | ein beliebiger Selektor oder eine Abfrage mit `@media`, `@supports` oder `@container` |
+
+Auf der Arbeitsfläche zeigt eine Ebene einen Modus, sobald sie auf ihn gesetzt ist, unabhängig von der Bedingung. Im exportierten Code wird ein manuell umgeschalteter Modus aktiviert, indem sein Attribut an ein Element gesetzt wird; Ebenen, die auf ihn gesetzt sind, werden daher mit diesem Attribut exportiert. Ebenen, die auf einen Modus mit einer anderen Bedingung gesetzt sind, auch mit benutzerdefinierten Selektoren, werden mit festen Werten statt Tokens exportiert, weil das Stylesheet und nicht die Ebene entscheidet, wann dieser Modus gilt.
+
+## Variablen verwalten
+
+Variablen sind nach den Ordnern in ihren Namen gruppiert (`Brand/Primary` erscheint als *Primary* unter *Brand*) und zeigen ihren CSS-Namen sowie einen Wert pro Modus.
+
+- **Variable erstellen:** auf **Variable erstellen** (oder **+**) klicken und einen Typ wählen; die neue Variable wird zur Bearbeitung geöffnet
+- **Auswählen:** auf eine Zeile klicken oder mit den Pfeiltasten navigieren und die Eingabetaste drücken. Shift-Klick wählt einen Bereich aus, Cmd-Klick (Strg-Klick unter Windows und Linux) fügt eine Zeile hinzu oder entfernt sie
+- **Filtern:** in das Suchfeld tippen, um nach Namen, CSS-Name, Beschreibung oder Wert zu filtern, etwa `--color-brand`, einer Hex-Farbe oder der Variable, auf die ein Alias verweist, mit derselben fehlertoleranten Suche wie die Befehlspalette; in der Seitenleiste auf eine Gruppe klicken, um nur diese Gruppe und die darin enthaltenen Gruppen anzuzeigen, oder über die Filter-Schaltfläche (**Nach Typ filtern**) nur bestimmte Typen anzeigen
+- **Umbenennen oder direkt bearbeiten:** auf einen Namen oder einen Zahlen- oder Textwert in der Liste doppelklicken
+- **Rechtsklick:** die ausgewählten Variablen umbenennen, duplizieren (**Duplizieren**), in eine Gruppe oder eine neue Gruppe verschieben (**In Gruppe verschieben**, **Neue Gruppe…**) oder löschen (**Variablen löschen**); auch Delete oder Backspace löscht sie
+- **Neu anordnen:** eine Zeile ziehen; die Reihenfolge wird in der Datei gespeichert
+- **Mehrere ausgewählt:** die rechte Seite verschiebt sie in eine Gruppe, dupliziert sie oder löscht sie
+- **Rückgängig und Wiederholen:** Cmd+Z und Cmd+Shift+Z oder Cmd+Y (Strg unter Windows und Linux) wirken im Dialog wie auf der Arbeitsfläche, ein Schritt pro Änderung. Die Eingabetaste übernimmt ein Feld und kehrt zur Liste zurück; solange ein Feld noch nicht übernommenen Text enthält, macht Cmd+Z das Tippen rückgängig
+
+Die Auswahl einer Variable bearbeitet:
+
+- **Name** und **CSS-Name:** den CSS-Namen leer lassen, damit er aus Name und Geltungsbereichen abgeleitet wird, etwa `--color-brand-primary`. Den Namen ohne `--` eingeben; ein Name, den CSS nicht verwenden kann, wird markiert und nicht gespeichert
+- **Einheit:** bei Zahlen `px`, `rem`, `%`, `ms`, `s`, `deg` oder keine; Werte werden in dieser Einheit eingegeben
+- **Wert** oder **Werte:** einer pro Modus; eine Farbe öffnet die Farbauswahl. Die Variablen-Schaltfläche (**Variable verwenden**) neben einem Wert lässt ihn auf eine andere Variable desselben Typs verweisen, ein Alias, der dieser Variable folgt; **Variable lösen** macht daraus wieder den Wert, den er zeigte
+- **CSS-Ausdruck:** bei Zahlen ein Wert wie `clamp(1rem, 4vw, 1.5rem)`, der in CSS anstelle der Zahl geschrieben wird, während die Arbeitsfläche weiterhin die Zahl zeichnet
+- **Geltungsbereiche:** für welche Eigenschaften die Variable angeboten wird
+- **Beschreibung**
+- **Von Veröffentlichung ausblenden:** Dateien, die diese Datei als Bibliothek verwenden, sehen die Variable nicht
+
+## Stylesheet
+
+Unten im Dialog wird die aktive Sammlung als CSS-Custom-Properties angezeigt. Die Kopieren-Schaltfläche (**Alle Variablen als CSS kopieren**) kopiert die Variablen des gesamten Dokuments als CSS oder als Tailwind-v4-Theme (**Alle Variablen als Tailwind-Theme kopieren**), sodass Aliase auf andere Sammlungen aufgelöst werden.
+
+## Variablen an Füllungen binden
+
+Mit der Variablenauswahl im Bereich Füllung des Eigenschaftenbereichs lässt sich eine Farbvariable an die Füllung eines Objekts binden.
+
+- **Binden:** eine Farbvariable in der Auswahl wählen. Die Füllung zeigt ein violettes Etikett mit dem Variablennamen.
+- **Lösen:** auf die Schaltfläche zum Lösen am Etikett klicken, um die Bindung zu entfernen. Die Füllung kehrt zum aufgelösten Farbwert zurück.
+
+Ändert sich der Wert der Variable (oder wird der Modus gewechselt), werden alle gebundenen Füllungen automatisch aktualisiert.
## Hinweise
-- Sammlungen gruppieren zusammengehörige Token, etwa `Primitives` für Ausgangsfarben und `Semantic` für rollenbezogene Token.
-- Modi eignen sich für Themen wie Hell und Dunkel.
-- Aliase erlauben einer Variable, auf den Wert einer anderen Sammlung zu verweisen.
+- Sammlungen gruppieren zusammengehörige Token, etwa `Primitives` für Ausgangsfarben, `Semantic` für rollenbezogene Aliase und `Spacing` für Layoutwerte.
+- Modi eignen sich für Themen: Hell- und Dunkel-Werte lassen sich in derselben Sammlung definieren.
+- Variablen unterstützen Aliase: Eine Sammlung `Semantic` kann auf Werte einer Sammlung `Primitives` verweisen.
+- Wie Füllungen und die Farbauswahl funktionieren, steht unter [Formen zeichnen](./drawing-shapes).
diff --git a/packages/docs/es/user-guide/variables.md b/packages/docs/es/user-guide/variables.md
index 11870b114..8ac71b4ef 100644
--- a/packages/docs/es/user-guide/variables.md
+++ b/packages/docs/es/user-guide/variables.md
@@ -5,41 +5,83 @@ description: Crear variables, colecciones y modos, y vincularlas a propiedades d
# Variables
-Las variables almacenan valores reutilizables, como colores y espaciados. Una propiedad vinculada se actualiza cuando cambia la variable.
+Las variables almacenan tokens de diseño reutilizables, como colores, espaciados y otras propiedades, que se pueden vincular a objetos. Si cambias el valor de una variable, se actualizan todos los objetos que la usan.
-## Abrir el editor
+## Abrir el diálogo de variables
-Sin objetos seleccionados, la pestaña **Diseño** muestra las propiedades de la página. El icono de ajustes de la sección Variables abre el editor.
+Ábrelo desde **Ver → Variables…**, buscando «Variables» en la paleta de comandos o, sin objetos seleccionados, desde la sección Variables de la pestaña **Diseño**. **Expandir** en la esquina del diálogo le da la mayor parte de la ventana.
-## Colecciones y modos
+El diálogo muestra a la izquierda las variables de la colección activa, edita a la derecha la variable seleccionada o la colección, y muestra debajo la hoja de estilos que producen. En una ventana estrecha o en un teléfono muestra un modo a la vez, y una variable, los ajustes de la colección o la hoja de estilos se abren sobre la lista con un botón para volver.
-Una colección agrupa variables relacionadas. Cada colección puede tener modos, por ejemplo Claro y Oscuro, con un valor distinto por variable.
+## Colecciones
-- Un clic cambia de colección.
-- Doble clic en el nombre permite renombrarla.
-- Los botones de la cabecera crean colecciones y modos.
+Las variables se organizan en colecciones. En un diálogo ancho aparecen en una barra lateral con el número de variables de cada una; si es más estrecho, como pestañas, o como menú en el móvil.
-## Editar variables
+- **Cambiar de colección:** haz clic en ella en la barra lateral o en su pestaña
+- **Crear una colección:** haz clic en **+** junto a **Colecciones** o en el botón de carpeta de la barra de herramientas (**Crear colección**)
+- **Renombrar o eliminar:** sin ninguna variable seleccionada, la parte derecha edita la colección: cambia su nombre o elimínala desde el menú **⋯** junto al nombre (**Eliminar colección**)
-La tabla contiene el nombre, el tipo y una columna por modo. Haz clic en una celda para editarla.
+## Modos
-Tipos admitidos:
+Cada colección puede tener varios modos (por ejemplo, Claro y Oscuro). Los modos aparecen como columnas de valores en la lista, y una variable tiene un valor para cada modo. Se gestionan en los **Ajustes de la colección**:
-- color;
-- número;
-- texto;
-- booleano.
+- **Añadir un modo:** haz clic en **+** junto a **Modos**
+- **Renombrar:** edita el nombre del modo
+- **Duplicar, establecer como predeterminado, eliminar:** usa el menú **⋯** junto al modo (**Duplicar modo**, **Establecer como predeterminado**, **Eliminar modo**)
-Los colores se editan con un campo y un selector. Los números pueden representar dimensiones y espaciados.
+El modo predeterminado es **Siempre activo** y va en `:root`. Todos los demás modos tienen **Se aplica cuando**, que indica cuándo el modo toma el control en la hoja de estilos exportada; el CSS que escribe se muestra debajo:
-## Enlazar rellenos y contornos
+| Se aplica cuando | CSS |
+| --- | --- |
+| **se cambia manualmente** | un atributo con el nombre de la colección y del modo, como `[data-theme="dark"]` para el modo Oscuro de una colección Theme |
+| **el sistema está en modo oscuro** / **el sistema está en modo claro** | `@media (prefers-color-scheme: dark)` / `light` |
+| **el contraste alto está activado** | `@media (prefers-contrast: more)` |
+| **la reducción de movimiento está activada** | `@media (prefers-reduced-motion: reduce)` |
+| **la pantalla es más estrecha que** / **la pantalla es más ancha que** un ancho | `@media (max-width: 640px)` / `min-width` |
+| **el contenedor es más estrecho que** / **el contenedor es más ancho que** un ancho | `@container (max-width: 640px)` / `min-width` |
+| **CSS personalizado** | cualquier selector, o una consulta `@media`, `@supports` o `@container` |
-Abre el selector de variables desde el control de color y elige una variable compatible. El control muestra el enlace en lugar de copiar el valor. Cambiar el valor manualmente elimina el enlace solo en la primera modificación real, no al enfocar el campo.
+En el lienzo, una capa muestra un modo cuando la estableces en él, sea cual sea la condición. En el código exportado, un modo que se cambia manualmente se activa añadiendo su atributo a un elemento, así que las capas establecidas en él se exportan con ese atributo. Las capas establecidas en un modo con cualquier otra condición, incluidos los selectores personalizados, se exportan con valores literales en lugar de tokens, porque la hoja de estilos, y no la capa, decide cuándo se aplica ese modo.
-## Alias
+## Gestionar variables
-Una variable puede hacer referencia a otra. OpenPencil resuelve la cadena según el modo activo y detecta referencias circulares.
+Las variables se agrupan según las carpetas de sus nombres (`Brand/Primary` aparece como *Primary* dentro de *Brand*), con su nombre CSS y un valor por modo.
-## Importación y exportación
+- **Crear una variable:** haz clic en **Crear variable** (o en **+**) y elige un tipo; la nueva variable se abre para editarla
+- **Seleccionar:** haz clic en una fila, o muévete con las flechas y pulsa Intro. Con Shift y clic seleccionas un rango, y con Cmd y clic (Ctrl y clic en Windows y Linux) añades o quitas una fila
+- **Filtrar:** escribe en la barra de búsqueda para filtrar por nombre, nombre CSS, descripción o valor, como `--color-brand`, un color hexadecimal o la variable a la que apunta un alias, tolerando erratas como la paleta de comandos; haz clic en un grupo de la barra lateral para ver solo ese grupo y los grupos que contiene, o usa el botón de filtro (**Filtrar por tipo**) para ver solo algunos tipos
+- **Renombrar o editar en el lugar:** haz doble clic en un nombre, o en un valor numérico o de texto, de la lista
+- **Clic derecho:** renombra, duplica (**Duplicar**), mueve a un grupo o a uno nuevo (**Mover al grupo**, **Nuevo grupo…**) o elimina (**Eliminar variables**) las variables seleccionadas; Delete o Backspace también las elimina
+- **Reordenar:** arrastra una fila; el orden se conserva en el archivo
+- **Varias seleccionadas:** la parte derecha las mueve a un grupo, las duplica o las elimina
+- **Deshacer y rehacer:** Cmd+Z y Cmd+Mayús+Z o Cmd+Y (Ctrl en Windows y Linux) funcionan en el diálogo igual que en el lienzo, un paso por cambio. Intro confirma un campo y vuelve a la lista; mientras un campo tiene texto sin confirmar, Cmd+Z deshace lo escrito
-Las variables se conservan al importar y exportar `.fig`. La CLI también puede listarlas y modificarlas mediante la API compatible con plugins de Figma.
+Al seleccionar una variable se editan:
+
+- **Nombre** y **Nombre CSS:** deja el nombre CSS vacío para derivarlo del nombre y los ámbitos, por ejemplo `--color-brand-primary`. Escribe el nombre sin `--`; un nombre que CSS no puede usar se marca y no se guarda
+- **Unidad:** para números, `px`, `rem`, `%`, `ms`, `s`, `deg` o ninguna; los valores se introducen en esa unidad
+- **Valor** o **Valores:** uno por modo; un color abre el selector de color. El botón de variable (**Usar una variable**) junto a un valor lo hace apuntar a otra variable del mismo tipo, un alias que sigue a esa variable; **Desvincular variable** lo devuelve al valor que mostraba
+- **Expresión CSS:** para números, un valor como `clamp(1rem, 4vw, 1.5rem)` que se escribe en CSS en lugar del número, mientras el lienzo sigue dibujando el número
+- **Ámbitos:** para qué propiedades se ofrece la variable
+- **Descripción**
+- **Ocultar al publicar:** los archivos que usan este como biblioteca no ven la variable
+
+## Hoja de estilos
+
+La parte inferior del diálogo muestra la colección activa como propiedades personalizadas de CSS. El botón de copiar (**Copiar todas las variables como CSS**) copia las variables de todo el documento como CSS o como un tema de Tailwind v4 (**Copiar todas las variables como tema de Tailwind**), de modo que los alias a otras colecciones se resuelven.
+
+## Vincular variables a rellenos
+
+En la sección Relleno del panel de propiedades, usa el selector de variables para vincular una variable de color al relleno de un objeto.
+
+- **Vincular:** elige una variable de color en el selector. El relleno muestra una etiqueta morada con el nombre de la variable.
+- **Desvincular:** haz clic en el botón de desvincular de la etiqueta para quitar el vínculo. El relleno vuelve al valor de color resuelto.
+
+Cuando cambia el valor de la variable (o al cambiar de modo), todos los rellenos vinculados se actualizan automáticamente.
+
+## Consejos
+
+- Usa colecciones para agrupar tokens relacionados (por ejemplo, `Primitives` para colores base, `Semantic` para alias por función y `Spacing` para valores de maquetación).
+- Los modos son útiles para cambiar de tema: define valores Claro y Oscuro en la misma colección.
+- Las variables admiten alias: una colección `Semantic` puede hacer referencia a valores de una colección `Primitives`.
+- Consulta [Dibujar formas](./drawing-shapes) para ver cómo funcionan los rellenos y el selector de color.
diff --git a/packages/docs/fr/user-guide/variables.md b/packages/docs/fr/user-guide/variables.md
index a3034b6ca..42d140af8 100644
--- a/packages/docs/fr/user-guide/variables.md
+++ b/packages/docs/fr/user-guide/variables.md
@@ -5,36 +5,83 @@ description: Créer des variables, collections et modes, puis les lier aux propr
# Variables
-Les variables stockent des valeurs réutilisables, comme des couleurs et des espacements. Une propriété liée est mise à jour lorsque la variable change.
+Les variables stockent des tokens de design réutilisables, comme des couleurs, des espacements et d’autres propriétés, qui peuvent être liés à des objets. Lorsque la valeur d’une variable change, tous les objets qui l’utilisent sont mis à jour.
-## Ouvrir l’éditeur
+## Ouvrir la boîte de dialogue des variables
-Lorsqu’aucun objet n’est sélectionné, l’onglet **Design** affiche les propriétés de la page. L’icône des réglages de la section Variables ouvre l’éditeur.
+Ouvrez-la depuis **Affichage → Variables…**, en recherchant « Variables » dans la palette de commandes ou, lorsqu’aucun objet n’est sélectionné, depuis la section Variables de l’onglet **Design**. **Développer**, dans le coin de la boîte de dialogue, lui donne la majeure partie de la fenêtre.
-## Collections et modes
+La boîte de dialogue liste à gauche les variables de la collection active, modifie à droite la variable sélectionnée ou la collection, et affiche en dessous la feuille de style qu’elles produisent. Dans une fenêtre étroite ou sur téléphone, elle n’affiche qu’un mode à la fois, et une variable, les paramètres de la collection ou la feuille de style s’ouvrent par-dessus la liste avec un bouton de retour.
-Une collection regroupe des variables liées. Chaque collection peut avoir plusieurs modes, par exemple Clair et Sombre, avec une valeur différente par variable.
+## Collections
-- Un clic change de collection.
-- Un double clic sur le nom permet de la renommer.
-- Les boutons d’en-tête créent collections et modes.
+Les variables sont organisées en collections. Dans une boîte de dialogue large, elles sont listées dans une barre latérale avec le nombre de variables de chacune ; plus étroite, elles s’affichent sous forme d’onglets, ou d’un menu sur un téléphone.
-## Modifier les variables
+- **Changer de collection :** cliquez dessus dans la barre latérale ou sur son onglet
+- **Créer une collection :** cliquez sur **+** à côté de **Collections**, ou sur le bouton en forme de dossier dans la barre d’outils (**Créer une collection**)
+- **Renommer ou supprimer :** sans variable sélectionnée, la partie droite modifie la collection : changez son nom, ou supprimez-la depuis le menu **⋯** à côté du nom (**Supprimer la collection**)
-Le tableau contient le nom, le type et une colonne par mode. Cliquez sur une cellule pour la modifier.
+## Modes
-Types pris en charge : couleur, nombre, texte et booléen. Les couleurs se modifient avec un champ et un sélecteur.
+Chaque collection peut avoir plusieurs modes (par exemple Clair et Sombre). Les modes apparaissent sous forme de colonnes de valeurs dans la liste, et une variable a une valeur pour chaque mode. Ils se gèrent dans les **Paramètres de la collection** :
-## Lier remplissages et contours
+- **Ajouter un mode :** cliquez sur **+** à côté de **Modes**
+- **Renommer :** modifiez le nom du mode
+- **Dupliquer, définir par défaut, supprimer :** utilisez le menu **⋯** à côté du mode (**Dupliquer le mode**, **Définir par défaut**, **Supprimer le mode**)
-Ouvrez le sélecteur de variables depuis le contrôle de couleur et choisissez une variable compatible. Le contrôle affiche le lien au lieu de copier la valeur.
+Le mode par défaut est **Toujours actif** et va dans `:root`. Chaque autre mode a **S’applique quand**, qui indique quand le mode prend le relais dans la feuille de style exportée ; le CSS qu’il produit s’affiche en dessous :
-Ouvrir ou sélectionner le champ ne modifie pas le lien. Seule la première modification réelle peut le supprimer ou modifier directement la variable, selon le contrôle.
+| S’applique quand | CSS |
+| --- | --- |
+| **il est activé manuellement** | un attribut nommé d’après la collection et le mode, comme `[data-theme="dark"]` pour le mode Sombre d’une collection Theme |
+| **le système est en mode sombre** / **le système est en mode clair** | `@media (prefers-color-scheme: dark)` / `light` |
+| **le contraste élevé est activé** | `@media (prefers-contrast: more)` |
+| **la réduction des animations est activée** | `@media (prefers-reduced-motion: reduce)` |
+| **l’écran est plus étroit que** / **l’écran est plus large que** une largeur | `@media (max-width: 640px)` / `min-width` |
+| **le conteneur est plus étroit que** / **le conteneur est plus large que** une largeur | `@container (max-width: 640px)` / `min-width` |
+| **CSS personnalisé** | n’importe quel sélecteur, ou une requête `@media`, `@supports` ou `@container` |
-## Alias
+Sur le canevas, un calque affiche un mode lorsque vous l’y réglez, quelle que soit la condition. Dans le code exporté, un mode activé manuellement s’active en ajoutant son attribut à un élément ; les calques réglés dessus sont donc exportés avec cet attribut. Les calques réglés sur un mode ayant une autre condition, sélecteurs personnalisés compris, sont exportés avec des valeurs littérales plutôt que des tokens, car c’est la feuille de style, et non le calque, qui décide quand ce mode s’applique.
-Une variable peut en référencer une autre. OpenPencil résout la chaîne selon le mode actif et détecte les cycles.
+## Gérer les variables
-## Importation et exportation
+Les variables sont regroupées selon les dossiers de leurs noms (`Brand/Primary` apparaît comme *Primary* sous *Brand*), avec leur nom CSS et une valeur par mode.
-Les variables sont conservées lors des importations et exportations `.fig`. La CLI peut aussi les lister et les modifier via l’API compatible avec les plugins Figma.
+- **Créer une variable :** cliquez sur **Créer une variable** (ou sur **+**) et choisissez un type ; la nouvelle variable s’ouvre pour modification
+- **Sélectionner :** cliquez sur une ligne, ou déplacez-vous avec les flèches et appuyez sur Entrée. Maj-clic sélectionne une plage, et Cmd-clic (Ctrl-clic sous Windows et Linux) ajoute ou retire une ligne
+- **Filtrer :** saisissez du texte dans la barre de recherche pour filtrer par nom, nom CSS, description ou valeur, comme `--color-brand`, une couleur hexadécimale ou la variable visée par un alias, en tolérant les fautes de frappe comme la palette de commandes ; cliquez sur un groupe dans la barre latérale pour n’afficher que ce groupe et ceux qu’il contient, ou utilisez le bouton de filtre (**Filtrer par type**) pour n’afficher que certains types
+- **Renommer ou modifier sur place :** double-cliquez sur un nom, ou sur une valeur numérique ou textuelle, dans la liste
+- **Clic droit :** renommer, dupliquer (**Dupliquer**), déplacer vers un groupe ou un nouveau groupe (**Déplacer vers le groupe**, **Nouveau groupe…**) ou supprimer (**Supprimer les variables**) les variables sélectionnées ; Delete ou Backspace les supprime aussi
+- **Réorganiser :** faites glisser une ligne ; l’ordre est conservé dans le fichier
+- **Plusieurs sélectionnées :** la partie droite les déplace vers un groupe, les duplique ou les supprime
+- **Annuler et rétablir :** Cmd+Z et Cmd+Maj+Z ou Cmd+Y (Ctrl sous Windows et Linux) agissent dans la boîte de dialogue comme sur le canevas, une étape par modification. Entrée valide un champ et revient à la liste ; tant qu’un champ contient du texte non validé, Cmd+Z annule la saisie
+
+La sélection d’une variable permet de modifier :
+
+- **Nom** et **Nom CSS** : laissez le nom CSS vide pour le déduire du nom et des portées, par exemple `--color-brand-primary`. Saisissez le nom sans son `--` ; un nom que CSS ne peut pas utiliser est signalé et n’est pas enregistré
+- **Unité** : pour les nombres, `px`, `rem`, `%`, `ms`, `s`, `deg` ou aucune ; les valeurs sont saisies dans cette unité
+- **Valeur** ou **Valeurs** : une par mode ; une couleur ouvre le sélecteur de couleur. Le bouton de variable (**Utiliser une variable**) à côté d’une valeur la fait pointer vers une autre variable du même type, un alias qui suit cette variable ; **Détacher la variable** la ramène à la valeur qu’elle affichait
+- **Expression CSS** : pour les nombres, une valeur comme `clamp(1rem, 4vw, 1.5rem)` écrite en CSS à la place du nombre, tandis que le canevas continue de dessiner le nombre
+- **Portées** : les propriétés pour lesquelles la variable est proposée
+- **Description**
+- **Masquer de la publication** : les fichiers qui utilisent celui-ci comme bibliothèque ne voient pas la variable
+
+## Feuille de style
+
+Le bas de la boîte de dialogue affiche la collection active sous forme de propriétés personnalisées CSS. Le bouton de copie (**Copier toutes les variables en CSS**) copie les variables de tout le document en CSS ou sous forme de thème Tailwind v4 (**Copier toutes les variables en thème Tailwind**), de sorte que les alias vers d’autres collections sont résolus.
+
+## Lier des variables aux remplissages
+
+Dans la section Remplissage du panneau des propriétés, utilisez le sélecteur de variables pour lier une variable de couleur au remplissage d’un objet.
+
+- **Lier :** choisissez une variable de couleur dans le sélecteur. Le remplissage affiche une pastille violette avec le nom de la variable.
+- **Détacher :** cliquez sur le bouton de détachement de la pastille pour supprimer le lien. Le remplissage revient à la valeur de couleur résolue.
+
+Lorsque la valeur de la variable change (ou lors d’un changement de mode), tous les remplissages liés sont mis à jour automatiquement.
+
+## Conseils
+
+- Utilisez des collections pour regrouper des tokens liés (par exemple `Primitives` pour les couleurs brutes, `Semantic` pour les alias par rôle et `Spacing` pour les valeurs de mise en page).
+- Les modes sont utiles pour changer de thème : définissez les valeurs Clair et Sombre dans la même collection.
+- Les variables prennent en charge les alias : une collection `Semantic` peut référencer des valeurs d’une collection `Primitives`.
+- Consultez [Dessiner des formes](./drawing-shapes) pour le fonctionnement des remplissages et du sélecteur de couleur.
diff --git a/packages/docs/it/user-guide/variables.md b/packages/docs/it/user-guide/variables.md
index 976177831..96dda5a0f 100644
--- a/packages/docs/it/user-guide/variables.md
+++ b/packages/docs/it/user-guide/variables.md
@@ -5,36 +5,83 @@ description: Creare variabili, raccolte e modalità e collegarle alle proprietà
# Variabili
-Le variabili memorizzano valori riutilizzabili, come colori e spaziature. Una proprietà collegata viene aggiornata quando cambia la variabile.
+Le variabili memorizzano token di design riutilizzabili, come colori, spaziature e altre proprietà, che possono essere collegati agli oggetti. Quando cambia il valore di una variabile, si aggiornano tutti gli oggetti che la usano.
-## Aprire l’editor
+## Aprire la finestra delle variabili
-Quando non è selezionato alcun oggetto, la scheda **Design** mostra le proprietà della pagina. L’icona delle impostazioni nella sezione Variabili apre l’editor.
+Aprila da **Visualizza → Variabili…**, cercando «Variabili» nella palette dei comandi oppure, quando non è selezionato alcun oggetto, dalla sezione Variabili della scheda **Design**. **Espandi**, nell’angolo della finestra, le dà gran parte dello spazio disponibile.
-## Raccolte e modalità
+La finestra elenca a sinistra le variabili della raccolta attiva, modifica a destra la variabile selezionata o la raccolta e mostra sotto il foglio di stile che producono. In una finestra stretta o su telefono mostra una modalità alla volta, e una variabile, le impostazioni della raccolta o il foglio di stile si aprono sopra l’elenco con un pulsante per tornare indietro.
-Una raccolta raggruppa variabili correlate. Ogni raccolta può avere più modalità, per esempio Chiaro e Scuro, con un valore diverso per variabile.
+## Raccolte
-- Un clic cambia raccolta.
-- Un doppio clic sul nome permette di rinominarla.
-- I pulsanti nell’intestazione creano raccolte e modalità.
+Le variabili sono organizzate in raccolte. In una finestra larga sono elencate in una barra laterale con il numero di variabili di ciascuna; più stretta, diventano schede, oppure un menu su telefono.
-## Modificare le variabili
+- **Cambiare raccolta:** fai clic su di essa nella barra laterale o sulla sua scheda
+- **Creare una raccolta:** fai clic su **+** accanto a **Raccolte**, oppure sul pulsante a forma di cartella nella barra degli strumenti (**Crea raccolta**)
+- **Rinominare o eliminare:** senza alcuna variabile selezionata, la parte destra modifica la raccolta: cambia il nome, oppure eliminala dal menu **⋯** accanto al nome (**Elimina raccolta**)
-La tabella contiene nome, tipo e una colonna per modalità. Fai clic su una cella per modificarla.
+## Modalità
-Sono supportati colore, numero, testo e booleano. I colori si modificano con un campo e un selettore.
+Ogni raccolta può avere più modalità (per esempio Chiaro e Scuro). Le modalità compaiono come colonne di valori nell’elenco, e una variabile ha un valore per ciascuna modalità. Si gestiscono nelle **Impostazioni della raccolta**:
-## Collegare riempimenti e contorni
+- **Aggiungere una modalità:** fai clic su **+** accanto a **Modalità**
+- **Rinominare:** modifica il nome della modalità
+- **Duplicare, impostare come predefinita, eliminare:** usa il menu **⋯** accanto alla modalità (**Duplica modalità**, **Imposta come predefinita**, **Elimina modalità**)
-Apri il selettore delle variabili dal controllo colore e scegli una variabile compatibile. Il controllo mostra il collegamento invece di copiare il valore.
+La modalità predefinita è **Sempre attivo** e va in `:root`. Ogni altra modalità ha **Si applica quando**, che indica quando la modalità subentra nel foglio di stile esportato; il CSS che scrive è mostrato sotto:
-Aprire o selezionare il campo non modifica il collegamento. Solo la prima variazione reale può rimuoverlo o modificare direttamente la variabile, in base al controllo.
+| Si applica quando | CSS |
+| --- | --- |
+| **viene attivata manualmente** | un attributo che prende il nome dalla raccolta e dalla modalità, come `[data-theme="dark"]` per la modalità Scuro di una raccolta Theme |
+| **il sistema è in modalità scura** / **il sistema è in modalità chiara** | `@media (prefers-color-scheme: dark)` / `light` |
+| **il contrasto elevato è attivo** | `@media (prefers-contrast: more)` |
+| **la riduzione del movimento è attiva** | `@media (prefers-reduced-motion: reduce)` |
+| **lo schermo è più stretto di** / **lo schermo è più largo di** una larghezza | `@media (max-width: 640px)` / `min-width` |
+| **il contenitore è più stretto di** / **il contenitore è più largo di** una larghezza | `@container (max-width: 640px)` / `min-width` |
+| **CSS personalizzato** | qualsiasi selettore, oppure una query `@media`, `@supports` o `@container` |
-## Alias
+Sulla tela, un livello mostra una modalità quando lo imposti su di essa, qualunque sia la condizione. Nel codice esportato, una modalità attivata manualmente si attiva aggiungendo il suo attributo a un elemento, quindi i livelli impostati su di essa vengono esportati con quell’attributo. I livelli impostati su una modalità con qualsiasi altra condizione, selettori personalizzati compresi, vengono esportati con valori letterali invece dei token, perché è il foglio di stile, non il livello, a decidere quando quella modalità si applica.
-Una variabile può fare riferimento a un’altra. OpenPencil risolve la catena in base alla modalità attiva e rileva i cicli.
+## Gestire le variabili
-## Importazione ed esportazione
+Le variabili sono raggruppate in base alle cartelle nei loro nomi (`Brand/Primary` compare come *Primary* sotto *Brand*), con il nome CSS e un valore per modalità.
-Le variabili vengono conservate nell’importazione e nell’esportazione `.fig`. La CLI può anche elencarle e modificarle tramite l’API compatibile con i plugin Figma.
+- **Creare una variabile:** fai clic su **Crea variabile** (o su **+**) e scegli un tipo; la nuova variabile si apre per la modifica
+- **Selezionare:** fai clic su una riga, oppure spostati con le frecce e premi Invio. Maiusc-clic seleziona un intervallo, e Cmd-clic (Ctrl-clic su Windows e Linux) aggiunge o rimuove una riga
+- **Filtrare:** digita nella barra di ricerca per filtrare per nome, nome CSS, descrizione o valore, come `--color-brand`, un colore esadecimale o la variabile a cui punta un alias, tollerando gli errori di battitura come la tavolozza dei comandi; fai clic su un gruppo nella barra laterale per mostrare solo quel gruppo e quelli al suo interno, oppure usa il pulsante del filtro (**Filtra per tipo**) per mostrare solo alcuni tipi
+- **Rinominare o modificare sul posto:** fai doppio clic su un nome, o su un valore numerico o di testo, nell’elenco
+- **Clic destro:** rinomina, duplica (**Duplica**), sposta in un gruppo o in uno nuovo (**Sposta nel gruppo**, **Nuovo gruppo…**) oppure elimina (**Elimina variabili**) le variabili selezionate; anche Delete o Backspace le elimina
+- **Riordinare:** trascina una riga; l’ordine viene conservato nel file
+- **Più selezionate:** la parte destra le sposta in un gruppo, le duplica o le elimina
+- **Annulla e ripeti:** Cmd+Z e Cmd+Maiusc+Z o Cmd+Y (Ctrl su Windows e Linux) funzionano nella finestra come sulla tela, un passaggio per modifica. Invio conferma un campo e torna all’elenco; finché un campo contiene testo non confermato, Cmd+Z annulla la digitazione
+
+La selezione di una variabile permette di modificare:
+
+- **Nome** e **Nome CSS:** lascia vuoto il nome CSS per ricavarlo da nome e ambiti, ad esempio `--color-brand-primary`. Digita il nome senza `--`; un nome che CSS non può usare viene segnalato e non viene salvato
+- **Unità:** per i numeri, `px`, `rem`, `%`, `ms`, `s`, `deg` o nessuna; i valori si inseriscono in quell’unità
+- **Valore** o **Valori:** uno per modalità; un colore apre il selettore colore. Il pulsante della variabile (**Usa una variabile**) accanto a un valore lo fa puntare a un’altra variabile dello stesso tipo, un alias che segue quella variabile; **Scollega variabile** lo riporta al valore che mostrava
+- **Espressione CSS:** per i numeri, un valore come `clamp(1rem, 4vw, 1.5rem)` scritto in CSS al posto del numero, mentre il canvas continua a disegnare il numero
+- **Ambiti:** per quali proprietà viene proposta la variabile
+- **Descrizione**
+- **Nascondi dalla pubblicazione:** i file che usano questo come libreria non vedono la variabile
+
+## Foglio di stile
+
+La parte inferiore della finestra mostra la raccolta attiva come proprietà personalizzate CSS. Il pulsante di copia (**Copia tutte le variabili come CSS**) copia le variabili dell’intero documento come CSS o come tema Tailwind v4 (**Copia tutte le variabili come tema Tailwind**), così gli alias verso altre raccolte vengono risolti.
+
+## Collegare le variabili ai riempimenti
+
+Nella sezione Riempimento del pannello delle proprietà, usa il selettore delle variabili per collegare una variabile colore al riempimento di un oggetto.
+
+- **Collegare:** scegli una variabile colore dal selettore. Il riempimento mostra un’etichetta viola con il nome della variabile.
+- **Scollegare:** fai clic sul pulsante di scollegamento sull’etichetta per rimuovere il collegamento. Il riempimento torna al valore di colore risolto.
+
+Quando il valore della variabile cambia (o si cambia modalità), tutti i riempimenti collegati si aggiornano automaticamente.
+
+## Suggerimenti
+
+- Usa le raccolte per raggruppare token correlati (per esempio `Primitives` per i colori di base, `Semantic` per gli alias basati sul ruolo e `Spacing` per i valori di layout).
+- Le modalità sono utili per cambiare tema: definisci i valori Chiaro e Scuro nella stessa raccolta.
+- Le variabili supportano gli alias: una raccolta `Semantic` può fare riferimento a valori di una raccolta `Primitives`.
+- Consulta [Disegnare forme](./drawing-shapes) per capire come funzionano i riempimenti e il selettore colore.
diff --git a/packages/docs/pl/user-guide/variables.md b/packages/docs/pl/user-guide/variables.md
index d10beacbb..9b420a6e2 100644
--- a/packages/docs/pl/user-guide/variables.md
+++ b/packages/docs/pl/user-guide/variables.md
@@ -5,54 +5,83 @@ description: Zmienne projektu, kolekcje, tryby i powiązania kolorów w OpenPenc
# Zmienne
-Zmienne przechowują tokeny projektu przeznaczone do ponownego użycia: kolory, odstępy i inne wartości, które można powiązać z obiektami. Po zmianie zmiennej wszystkie powiązane obiekty zostają zaktualizowane.
+Zmienne przechowują tokeny projektu przeznaczone do ponownego użycia: kolory, odstępy i inne właściwości, które można powiązać z obiektami. Po zmianie wartości zmiennej wszystkie obiekty, które jej używają, zostają zaktualizowane.
-## Otwieranie edytora zmiennych
+## Otwieranie okna zmiennych
-Usuń zaznaczenie ze wszystkich obiektów. Karta „Projekt” pokaże właściwości strony, w tym sekcję „Zmienne”. Kliknij ikonę ustawień, aby otworzyć okno.
+Otwórz je z **Widok → Zmienne…**, wyszukując „Zmienne” w palecie poleceń albo, gdy żaden obiekt nie jest zaznaczony, z sekcji „Zmienne” na karcie „Projekt”. Przycisk **Rozwiń** w rogu okna daje mu większą część okna aplikacji.
+
+Okno wyświetla po lewej zmienne aktywnej kolekcji, po prawej umożliwia edycję zaznaczonej zmiennej lub kolekcji, a poniżej pokazuje arkusz stylów, który z nich powstaje. W wąskim oknie lub na telefonie pokazuje jeden tryb naraz, a zmienna, ustawienia kolekcji albo arkusz stylów otwierają się nad listą z przyciskiem powrotu.
## Kolekcje
-Zmienne są łączone w kolekcje. Każda kolekcja jest przedstawiona jako osobna karta.
+Zmienne są łączone w kolekcje. W szerokim oknie są wypisane na pasku bocznym wraz z liczbą zmiennych w każdej; w węższym są kartami, a na telefonie menu.
-- Kliknij kartę, aby przejść do kolekcji.
-- Kliknij jej nazwę dwukrotnie, aby ją zmienić.
+- **Przejście do kolekcji:** kliknij ją na pasku bocznym lub jej kartę
+- **Tworzenie kolekcji:** kliknij **+** obok **Kolekcje** albo przycisk z folderem na pasku narzędzi (**Utwórz kolekcję**)
+- **Zmiana nazwy lub usuwanie:** gdy żadna zmienna nie jest zaznaczona, prawa strona edytuje kolekcję: zmień jej nazwę albo usuń ją z menu **⋯** obok nazwy (**Usuń kolekcję**)
## Tryby
-Kolekcja może zawierać kilka trybów, na przykład Light i Dark. W tabeli każdy tryb zajmuje osobną kolumnę, a zmienna przechowuje wartość dla każdego trybu.
+Każda kolekcja może zawierać kilka trybów (na przykład Light i Dark). Tryby są wyświetlane na liście jako kolumny wartości, a zmienna ma wartość dla każdego trybu. Zarządza się nimi w sekcji **Ustawienia kolekcji**:
+
+- **Dodawanie trybu:** kliknij **+** obok pozycji **Tryby**
+- **Zmiana nazwy:** edytuj nazwę trybu
+- **Duplikowanie, ustawianie jako domyślnego, usuwanie:** użyj menu **⋯** obok trybu (**Duplikuj tryb**, **Ustaw jako domyślny**, **Usuń tryb**)
-### Dodawanie kolekcji i trybów
+Tryb domyślny jest **Zawsze włączony** i trafia do `:root`. Każdy inny tryb ma pole **Obowiązuje, gdy**, które określa, kiedy tryb przejmuje kontrolę w wyeksportowanym arkuszu stylów; wygenerowany CSS jest pokazany poniżej:
-Nową kolekcję tworzy się z paska narzędzi okna. Dodawaj tryby, aby przechowywać warianty motywu albo wartości dla różnych punktów przełamania układu.
+| Obowiązuje, gdy | CSS |
+| --- | --- |
+| **przełączono ręcznie** | atrybut nazwany od kolekcji i trybu, na przykład `[data-theme="dark"]` dla trybu Dark kolekcji Theme |
+| **system jest w trybie ciemnym** / **system jest w trybie jasnym** | `@media (prefers-color-scheme: dark)` / `light` |
+| **włączony jest wysoki kontrast** | `@media (prefers-contrast: more)` |
+| **włączone jest ograniczenie ruchu** | `@media (prefers-reduced-motion: reduce)` |
+| **ekran jest węższy niż** / **ekran jest szerszy niż** szerokość | `@media (max-width: 640px)` / `min-width` |
+| **kontener jest węższy niż** / **kontener jest szerszy niż** szerokość | `@container (max-width: 640px)` / `min-width` |
+| **Własny CSS** | dowolny selektor albo zapytanie `@media`, `@supports` lub `@container` |
+
+Na płótnie warstwa pokazuje tryb, gdy ustawisz ją na ten tryb, niezależnie od warunku. W wyeksportowanym kodzie tryb przełączany ręcznie włącza się przez dodanie jego atrybutu do elementu, więc warstwy ustawione na ten tryb są eksportowane z tym atrybutem. Warstwy ustawione na tryb z dowolnym innym warunkiem, także z własnymi selektorami, są eksportowane z wartościami dosłownymi zamiast tokenów, ponieważ o tym, kiedy tryb obowiązuje, decyduje arkusz stylów, a nie warstwa.
## Praca ze zmiennymi
-Tabela zawiera kolumnę „Nazwa” o zmiennej szerokości oraz po jednej kolumnie dla każdego trybu.
+Zmienne są grupowane według folderów w ich nazwach (`Brand/Primary` jest widoczna jako *Primary* w folderze *Brand*) i pokazują nazwę CSS oraz jedną wartość dla każdego trybu.
+
+- **Tworzenie zmiennej:** kliknij **Utwórz zmienną** (lub **+**) i wybierz typ; nowa zmienna otworzy się do edycji
+- **Zaznaczanie:** kliknij wiersz albo poruszaj się strzałkami i naciśnij Enter. Kliknięcie z Shift zaznacza zakres, a kliknięcie z Cmd (Ctrl w Windows i Linuksie) dodaje wiersz lub usuwa go z zaznaczenia
+- **Filtrowanie:** wpisz tekst w pasku wyszukiwania, aby filtrować według nazwy, nazwy CSS, opisu lub wartości, np. `--color-brand`, koloru szesnastkowego albo zmiennej, na którą wskazuje alias, z tolerancją literówek jak w palecie poleceń; kliknij grupę na pasku bocznym, aby pokazać tylko ją i grupy w niej zawarte, albo użyj przycisku filtra (**Filtruj według typu**), aby pokazać tylko niektóre typy
+- **Zmiana nazwy lub edycja w miejscu:** kliknij dwukrotnie nazwę albo wartość liczbową lub tekstową na liście
+- **Prawy przycisk myszy:** zmień nazwę, zduplikuj (**Duplikuj**), przenieś do grupy lub nowej grupy (**Przenieś do grupy**, **Nowa grupa…**) albo usuń (**Usuń zmienne**) zaznaczone zmienne; usuwa je też Delete lub Backspace
+- **Zmiana kolejności:** przeciągnij wiersz; kolejność jest zapisywana w pliku
+- **Zaznaczonych kilka:** prawa strona przenosi je do grupy, duplikuje albo usuwa
+- **Cofnij i ponów:** Cmd+Z oraz Cmd+Shift+Z lub Cmd+Y (Ctrl w systemach Windows i Linux) działają w oknie tak jak na kanwie, jeden krok na zmianę. Enter zatwierdza pole i wraca do listy; dopóki pole zawiera niezatwierdzony tekst, Cmd+Z cofa wpisywanie
-- **Utwórz:** kliknij **Utwórz zmienną**.
-- **Zmień nazwę:** kliknij komórkę z nazwą.
-- **Zmień wartość:** kliknij komórkę odpowiedniego trybu.
-- **Wyszukaj:** wpisz część nazwy w polu wyszukiwania.
+Zaznaczenie zmiennej pozwala edytować:
-### Zmienne kolorów
+- **Nazwa** i **Nazwa CSS:** pozostaw nazwę CSS pustą, aby utworzyć ją z nazwy i zakresów, na przykład `--color-brand-primary`. Wpisz nazwę bez `--`; nazwa, której CSS nie może użyć, jest oznaczana i nie jest zapisywana
+- **Jednostka:** dla liczb `px`, `rem`, `%`, `ms`, `s`, `deg` albo brak; wartości wpisuje się w tej jednostce
+- **Wartość** lub **Wartości:** po jednej dla każdego trybu; kolor otwiera wybór koloru. Przycisk zmiennej (**Użyj zmiennej**) obok wartości kieruje ją do innej zmiennej tego samego typu, czyli aliasu, który podąża za tą zmienną; **Odłącz zmienną** przywraca wartość, którą pokazywał
+- **Wyrażenie CSS:** dla liczb wartość taka jak `clamp(1rem, 4vw, 1.5rem)` zapisywana w CSS zamiast liczby, podczas gdy kanwa nadal rysuje liczbę
+- **Zakresy:** dla jakich właściwości zmienna jest proponowana
+- **Opis**
+- **Ukryj przy publikowaniu:** pliki, które używają tego jako biblioteki, nie widzą zmiennej
-Dla zmiennej koloru tabela pokazuje pole koloru. Kliknij próbkę, aby otworzyć wybór koloru.
+## Arkusz stylów
-Typy `FLOAT`, `STRING` i `BOOLEAN` istnieją w modelu danych, ale nie mają jeszcze pełnego interfejsu edycji.
+Dół okna pokazuje aktywną kolekcję jako właściwości niestandardowe CSS. Przycisk kopiowania (**Kopiuj wszystkie zmienne jako CSS**) kopiuje zmienne całego dokumentu jako CSS albo motyw Tailwind v4 (**Kopiuj wszystkie zmienne jako motyw Tailwind**), dzięki czemu aliasy do innych kolekcji są rozwiązywane.
-## Powiązania zalewów i obwiedni
+## Powiązywanie zmiennych z zalewami
-W panelu właściwości otwórz sekcję „Zalew” albo „Obwiednia” i wybierz zmienną koloru.
+W sekcji „Zalew” panelu właściwości użyj wyboru zmiennej, aby powiązać zmienną koloru z zalewem obiektu.
-- Wybierz zmienną, aby utworzyć powiązanie. Obok właściwości pojawi się fioletowa etykieta z jej nazwą.
-- Usuń powiązanie za pomocą osobnego działania w oknie wyboru. Bieżąca obliczona wartość zostanie zachowana.
+- **Powiązanie:** wybierz zmienną koloru z listy. Zalew pokazuje fioletową etykietę z nazwą zmiennej.
+- **Odłączenie:** kliknij przycisk odłączania na etykiecie, aby usunąć powiązanie. Zalew wraca do obliczonej wartości koloru.
-Otwarcie pola lub okna wyboru nie zmienia powiązania. Może ono zostać usunięte tylko przez jawne działanie albo faktyczną zmianę wartości — zależnie od zachowania elementu sterującego.
+Gdy wartość zmiennej się zmienia (albo po przełączeniu trybu), wszystkie powiązane zalewy aktualizują się automatycznie.
## Wskazówki
-- Łącz powiązane tokeny w kolekcje, na przykład `Primitives` dla kolorów źródłowych, `Semantic` dla tokenów znaczeniowych i `Spacing` dla odstępów.
-- Wartości Light i Dark jednego motywu wygodnie przechowywać jako tryby jednej kolekcji.
-- Zmienne obsługują aliasy: zmienna z `Semantic` może odwoływać się do wartości z `Primitives`.
+- Łącz powiązane tokeny w kolekcje, na przykład `Primitives` dla kolorów źródłowych, `Semantic` dla aliasów znaczeniowych i `Spacing` dla odstępów.
+- Tryby są przydatne do przełączania motywu: wartości Light i Dark można zdefiniować w tej samej kolekcji.
+- Zmienne obsługują aliasy: kolekcja `Semantic` może odwoływać się do wartości z kolekcji `Primitives`.
- Zalewy i wybór koloru opisano na stronie [Kształty](./drawing-shapes).
diff --git a/packages/docs/ru/user-guide/variables.md b/packages/docs/ru/user-guide/variables.md
index fa77612d7..fb60a22f2 100644
--- a/packages/docs/ru/user-guide/variables.md
+++ b/packages/docs/ru/user-guide/variables.md
@@ -5,56 +5,83 @@ description: Переменные дизайна, коллекции, режим
# Переменные
-Переменные хранят повторно используемые токены дизайна: цвета, интервалы и другие значения, которые можно связать со свойствами объектов. После изменения переменной все связанные объекты обновляются.
+Переменные хранят повторно используемые токены дизайна: цвета, интервалы и другие свойства, которые можно привязать к объектам. Если изменить значение переменной, обновятся все объекты, которые её используют.
-## Открытие редактора переменных
+## Открытие диалога переменных
-Снимите выделение со всех объектов. На вкладке «Дизайн» появятся свойства страницы, включая раздел «Переменные». Нажмите значок настроек, чтобы открыть диалог.
+Откройте его через **Вид → Переменные…**, найдите «Переменные» в палитре команд или, если ничего не выделено, откройте раздел «Переменные» на вкладке «Дизайн». Кнопка **Развернуть** в углу диалога отдаёт ему большую часть окна.
+
+Слева диалог показывает переменные активной коллекции, справа позволяет редактировать выбранную переменную или коллекцию, а внизу показывает таблицу стилей, которую они образуют. В узком окне или на телефоне он показывает один режим за раз, а переменная, настройки коллекции или таблица стилей открываются поверх списка с кнопкой «Назад».
## Коллекции
-Переменные объединяются в коллекции. Каждая коллекция представлена отдельной вкладкой.
+Переменные объединяются в коллекции. В широком диалоге они перечислены на боковой панели с числом переменных в каждой; в более узком — вкладками, а на телефоне — меню.
-- Щёлкните вкладку, чтобы перейти к коллекции.
-- Дважды щёлкните её имя, чтобы переименовать коллекцию.
+- **Переключить коллекцию:** щёлкните её на боковой панели или её вкладку
+- **Создать коллекцию:** нажмите **+** рядом с **Коллекции** или кнопку с папкой на панели инструментов (**Создать коллекцию**)
+- **Переименовать или удалить:** если переменная не выбрана, справа редактируется коллекция: измените её имя или удалите её через меню **⋯** рядом с именем (**Удалить коллекцию**)
## Режимы
-Коллекция может содержать несколько режимов, например Light и Dark. В таблице каждый режим занимает отдельный столбец, а переменная хранит значение для каждого режима.
+В каждой коллекции может быть несколько режимов (например, Light и Dark). Режимы отображаются в списке столбцами значений, а у переменной есть значение для каждого режима. Управлять ими можно в разделе **Настройки коллекции**:
+
+- **Добавить режим:** нажмите **+** рядом с разделом **Режимы**
+- **Переименовать:** измените имя режима
+- **Дублировать, сделать основным, удалить:** используйте меню **⋯** рядом с режимом (**Дублировать режим**, **Сделать основным**, **Удалить режим**)
+
+Основной режим — **Всегда включён**, он попадает в `:root`. У каждого другого режима есть **Применяется, когда**: это определяет, когда режим вступает в силу в экспортированной таблице стилей; получающийся CSS показан ниже:
-### Добавление коллекций и режимов
+| Применяется, когда | CSS |
+| --- | --- |
+| **переключено вручную** | атрибут, названный по коллекции и режиму, например `[data-theme="dark"]` для режима Dark коллекции Theme |
+| **система в тёмном режиме** / **система в светлом режиме** | `@media (prefers-color-scheme: dark)` / `light` |
+| **включён высокий контраст** | `@media (prefers-contrast: more)` |
+| **включено уменьшение движения** | `@media (prefers-reduced-motion: reduce)` |
+| **экран уже, чем** / **экран шире, чем** ширина | `@media (max-width: 640px)` / `min-width` |
+| **контейнер уже, чем** / **контейнер шире, чем** ширина | `@container (max-width: 640px)` / `min-width` |
+| **Свой CSS** | любой селектор или запрос `@media`, `@supports` либо `@container` |
-Новая коллекция создаётся на панели инструментов диалога. Режимы позволяют хранить варианты темы или значения для разных контрольных точек адаптивного макета.
+На холсте слой показывает режим, когда вы задали его слою, независимо от условия. В экспортированном коде режим, переключаемый вручную, включается добавлением его атрибута элементу, поэтому слои с этим режимом экспортируются с этим атрибутом. Слои с режимом с любым другим условием, включая собственные селекторы, экспортируются с буквальными значениями вместо токенов, потому что когда режим применяется, решает таблица стилей, а не слой.
## Работа с переменными
-В таблице есть изменяемый по ширине столбец «Имя» и по одному столбцу для каждого режима.
+Переменные группируются по папкам в их именах (`Brand/Primary` отображается как *Primary* в папке *Brand*) и показываются с именем CSS и значением для каждого режима.
-- **Создать:** нажмите **Создать переменную**.
-- **Переименовать:** щёлкните ячейку с именем.
-- **Изменить значение:** щёлкните ячейку нужного режима.
-- **Найти:** введите часть имени в поле поиска.
+- **Создать переменную:** нажмите **Создать переменную** (или **+**) и выберите тип; новая переменная откроется для редактирования
+- **Выбрать:** щёлкните строку или перемещайтесь стрелками и нажмите Enter. Щелчок с Shift выделяет диапазон, а щелчок с Cmd (Ctrl в Windows и Linux) добавляет строку или убирает её из выделения
+- **Фильтровать:** введите текст в строке поиска, чтобы отфильтровать по имени, CSS-имени, описанию или значению, например `--color-brand`, шестнадцатеричному цвету или переменной, на которую указывает алиас, с той же терпимостью к опечаткам, что и в палитре команд; щёлкните группу на боковой панели, чтобы показать только её и вложенные в неё группы, или нажмите кнопку фильтра (**Фильтр по типу**), чтобы показать только некоторые типы
+- **Переименовать или изменить на месте:** дважды щёлкните имя или числовое или текстовое значение в списке
+- **Правая кнопка мыши:** переименовать, дублировать (**Дублировать**), переместить в группу или в новую группу (**Переместить в группу**, **Новая группа…**) либо удалить (**Удалить переменные**) выбранные переменные; их удаляют также Delete и Backspace
+- **Изменить порядок:** перетащите строку; порядок сохраняется в файле
+- **Выбрано несколько:** справа их можно переместить в группу, дублировать или удалить
+- **Отмена и повтор:** Cmd+Z и Cmd+Shift+Z или Cmd+Y (Ctrl в Windows и Linux) работают в диалоге так же, как на холсте, по одному шагу на изменение. Enter применяет поле и возвращает к списку; пока в поле есть неприменённый текст, Cmd+Z отменяет ввод
-### Цветовые переменные
+При выборе переменной можно редактировать:
-Для цветовой переменной в таблице отображается поле цвета. Щёлкните образец, чтобы открыть выбор цвета.
+- **Имя** и **Имя CSS:** оставьте имя CSS пустым, чтобы получить его из имени и областей применения, например `--color-brand-primary`. Вводите имя без `--`; имя, которое CSS не может использовать, помечается и не сохраняется
+- **Единица:** для чисел `px`, `rem`, `%`, `ms`, `s`, `deg` или без единицы; значения вводятся в этой единице
+- **Значение** или **Значения:** по одному для каждого режима; цвет открывает выбор цвета. Кнопка переменной (**Использовать переменную**) рядом со значением направляет его на другую переменную того же типа — псевдоним, который следует за этой переменной; **Открепить переменную** возвращает значение, которое он показывал
+- **Выражение CSS:** для чисел значение вроде `clamp(1rem, 4vw, 1.5rem)`, которое записывается в CSS вместо числа, а холст продолжает рисовать число
+- **Области применения:** для каких свойств предлагается переменная
+- **Описание**
+- **Скрыть при публикации:** файлы, которые используют этот как библиотеку, не видят переменную
-Типы `FLOAT`, `STRING` и `BOOLEAN` существуют в модели данных, но пока не имеют полного интерфейса редактирования.
+## Таблица стилей
-## Привязка к заливке и обводке
+Внизу диалога активная коллекция показана как пользовательские свойства CSS. Кнопка копирования (**Копировать все переменные как CSS**) копирует переменные всего документа как CSS или как тему Tailwind v4 (**Копировать все переменные как тему Tailwind**), поэтому ссылки на другие коллекции разрешаются.
-На панели свойств откройте раздел «Заливка» или «Обводка» и выберите цветовую переменную.
+## Привязка переменных к заливке
-- Чтобы создать привязку, выберите переменную. Рядом со свойством появится фиолетовая подпись с её именем.
-- Чтобы удалить привязку, используйте отдельное действие в окне выбора. Текущее вычисленное значение сохранится.
+В разделе «Заливка» панели свойств используйте выбор переменной, чтобы привязать цветовую переменную к заливке объекта.
-Фокус поля и открытие выбора переменной не изменяют привязку. Она может быть удалена только при явном действии или фактическом изменении значения — в зависимости от поведения элемента управления.
+- **Привязать:** выберите цветовую переменную в списке. У заливки появится фиолетовая метка с именем переменной.
+- **Отвязать:** нажмите кнопку отвязки на метке, чтобы удалить привязку. Заливка вернётся к вычисленному значению цвета.
-После изменения переменной или переключения режима все связанные свойства обновляются автоматически.
+Когда значение переменной меняется (или при переключении режима), все привязанные заливки обновляются автоматически.
## Советы
-- Объединяйте связанные токены в коллекции, например `Primitives` для исходных цветов, `Semantic` для смысловых псевдонимов и `Spacing` для интервалов.
-- Значения Light и Dark одной темы удобно хранить как режимы одной коллекции.
-- Переменные поддерживают псевдонимы: переменная из `Semantic` может ссылаться на значение из `Primitives`.
-- Работа с заливками описана в разделе [Фигуры](./drawing-shapes).
+- Объединяйте связанные токены в коллекции, например `Primitives` для исходных цветов, `Semantic` для смысловых псевдонимов и `Spacing` для значений макета.
+- Режимы удобны для переключения тем: значения Light и Dark можно задать в одной коллекции.
+- Переменные поддерживают псевдонимы: коллекция `Semantic` может ссылаться на значения из коллекции `Primitives`.
+- Работа с заливками и выбором цвета описана в разделе [Фигуры](./drawing-shapes).
diff --git a/packages/docs/user-guide/variables.md b/packages/docs/user-guide/variables.md
index f1aa5b5c0..667e635f3 100644
--- a/packages/docs/user-guide/variables.md
+++ b/packages/docs/user-guide/variables.md
@@ -6,37 +6,69 @@ description: Design variables, collections, modes, and fill bindings in OpenPenc
# Variables
Variables store reusable design tokens — colors, spacing values, and other properties — that can be bound to nodes. Change a variable's value and every node using it updates.
+
## Opening the Variables Dialog
-With no nodes selected, the Design tab shows page-level properties including a Variables section with collection and variable counts. Click the settings icon to open the variables dialog.
+Open it from **View → Variables…**, by searching "Variables" in the command palette, or, with no nodes selected, from the Variables section of the Design tab. **Expand** in the dialog's corner gives it most of the window.
+
+The dialog lists the active collection's variables on the left, edits the selected variable or the collection on the right, and shows the stylesheet they produce below. In a narrow window or on a phone it shows one mode at a time, and a variable, the collection settings, or the stylesheet opens over the list with a back button.
## Collections
-Variables are organized into collections. Each collection appears as a tab in the dialog.
+Variables are organized into collections. In a wide dialog they are listed in a sidebar with how many variables each holds; narrower, they are tabs, or a menu on a phone.
-- **Switch collection** — click a tab
-- **Rename collection** — double-click the tab name
+- **Switch collection** — click it in the sidebar or its tab
+- **Create collection** — click **+** next to Collections, or the folder button in the toolbar
+- **Rename or delete** — with no variable selected, the right side edits the collection: change its name, or delete it from the **⋯** menu next to the name
## Modes
-Each collection can have multiple modes (e.g., Light and Dark). Modes appear as columns in the variables table. A variable has a value for each mode.
+Each collection can have multiple modes (e.g., Light and Dark). Modes appear as value columns in the list, and a variable has a value for each mode. Manage them in the collection settings:
+
+- **Add mode** — click **+** next to Modes
+- **Rename** — edit the mode's name
+- **Duplicate, set as default, delete** — use the **⋯** menu next to the mode
-### Adding Collections and Modes
+The default mode is **Always on** and goes in `:root`. Every other mode has **Applies when**, which says when the mode takes over in the exported stylesheet; the CSS it writes is shown underneath:
-Create a new collection from the dialog toolbar. Add modes to an existing collection to support theme variants or responsive breakpoints.
+| Applies when | CSS |
+| --- | --- |
+| **Switched manually** | an attribute named after the collection and mode, such as `[data-theme="dark"]` for a Theme collection's Dark mode |
+| **System is in dark mode** / **System is in light mode** | `@media (prefers-color-scheme: dark)` / `light` |
+| **High contrast is on** | `@media (prefers-contrast: more)` |
+| **Reduced motion is on** | `@media (prefers-reduced-motion: reduce)` |
+| **Screen is narrower than** / **Screen is wider than** a width | `@media (max-width: 640px)` / `min-width` |
+| **Container is narrower than** / **Container is wider than** a width | `@container (max-width: 640px)` / `min-width` |
+| **Custom CSS** | any selector, or a `@media`, `@supports`, or `@container` query |
+
+On the canvas, a layer shows a mode when you set the layer to it, whatever the condition. In exported code, a manually switched mode is turned on by adding its attribute to an element, so layers set to it export with that attribute. Layers set to a mode with any other condition, custom selectors included, export with literal values instead of tokens, because the stylesheet, not the layer, decides when that mode applies.
## Managing Variables
-The variables table uses resizable columns: Name, plus one column per mode.
+Variables are grouped by the folders in their names (`Brand/Primary` appears as *Primary* under *Brand*), with their CSS name and one value per mode.
+
+- **Create variable** — click **Create variable** (or **+**) and pick a type; the new variable opens for editing
+- **Select** — click a row, or move with the arrow keys and press Enter. Shift-click selects a range, and Cmd-click (Ctrl-click on Windows and Linux) adds or removes one
+- **Filter** — type in the search bar to filter by name, CSS name, description, or value, such as `--color-brand`, a hex color, or the variable an alias points at, forgiving typos as the command palette does; click a group in the sidebar to show only that group and the groups inside it, or use the filter button to show only some types
+- **Rename or edit in place** — double-click a name, or a number or text value, in the list
+- **Right-click** — rename, duplicate, move to a group (or a new one), or delete the selected variables; Delete or Backspace deletes them too
+- **Reorder** — drag a row; the order is kept in the file
+- **Several selected** — the right side moves them into a group, duplicates them, or deletes them
+- **Undo and redo** — Cmd+Z and Cmd+Shift+Z or Cmd+Y (Ctrl on Windows and Linux) work in the dialog as on the canvas, one step per change. Enter commits a field and returns to the list; while a field has text you have not committed, Cmd+Z undoes the typing
+
+Selecting a variable edits:
-- **Create variable** — click the "+ Create variable" button
-- **Edit name** — click the variable name cell to edit inline
-- **Edit value** — click any value cell to change it for that mode
-- **Search** — type in the search bar to filter variables by name
+- **Name** and **CSS name** — leave the CSS name empty to derive it from the name and scopes, such as `--color-brand-primary`. Type the name without its `--`; a name CSS cannot use is flagged and not saved
+- **Unit** — for numbers, `px`, `rem`, `%`, `ms`, `s`, `deg`, or none; values are entered in that unit
+- **Value** (or **Values**, one per mode) — a color opens the color picker. The variable button next to a value points it at another variable of the same type, an alias that follows that variable; **Detach variable** turns it back into the value it showed
+- **CSS expression** — for numbers, a value such as `clamp(1rem, 4vw, 1.5rem)` written instead of the number in CSS, while the canvas keeps drawing the number
+- **Scopes** — which properties the variable is offered for
+- **Description**
+- **Hide from publishing** — files that use this one as a library do not see the variable
-### Color Variables
+## Stylesheet
-Color variables display an inline color input with a picker. Click the swatch to open the color picker and select a new color.
+The bottom of the dialog shows the active collection as CSS custom properties. The copy button copies the whole document's variables as CSS or as a Tailwind v4 theme, so aliases to other collections resolve.
## Binding Variables to Fills
diff --git a/packages/dom-css/package.json b/packages/dom-css/package.json
index 9d8a15106..98494d213 100644
--- a/packages/dom-css/package.json
+++ b/packages/dom-css/package.json
@@ -72,12 +72,14 @@
},
"devDependencies": {
"@types/bun": "^1.3.14",
+ "@types/css-tree": "^3.2.0",
"tsdown": "^0.22.14",
"typescript": "~5.8.3"
},
"dependencies": {
"@acemir/cssom": "^0.9.31",
"@open-pencil/emit": "workspace:*",
+ "css-tree": "^3.2.1",
"dedent": "^1.7.2",
"es-toolkit": "^1.52.0",
"js-base64": "^3.9.3",
diff --git a/packages/dom-css/src/tokens/conditions.ts b/packages/dom-css/src/tokens/conditions.ts
new file mode 100644
index 000000000..210816249
--- /dev/null
+++ b/packages/dom-css/src/tokens/conditions.ts
@@ -0,0 +1,66 @@
+// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.
+import { parse, type CssNodePlain as CSSNodePlain, type FeaturePlain } from 'css-tree'
+
+/** What a feature is tested against: a keyword such as `dark`, or a length such as `640px`. */
+export type FeatureValue =
+ | { type: 'keyword'; name: string }
+ | { type: 'dimension'; value: number; unit: string }
+
+/** An at-rule that tests one feature: `@media (prefers-color-scheme: dark)`. */
+export interface FeatureCondition {
+ rule: 'media' | 'container'
+ /** `prefers-color-scheme`, lowercase. */
+ feature: string
+ value: FeatureValue
+}
+
+/** The one feature a prelude tests, when it tests exactly one and nothing else. */
+function onlyFeature(nodes: readonly CSSNodePlain[]): FeaturePlain | undefined {
+ const [node] = nodes
+ if (nodes.length !== 1) return undefined
+ if (node.type === 'Feature') return node
+ if (node.type === 'Condition') return onlyFeature(node.children)
+ if (node.type === 'MediaQueryList') return onlyFeature(node.children)
+ if (node.type === 'MediaQuery' && !node.modifier && !node.mediaType && node.condition)
+ return onlyFeature([node.condition])
+ return undefined
+}
+
+function featureValue(node: FeaturePlain['value']): FeatureValue | undefined {
+ if (node?.type === 'Identifier') return { type: 'keyword', name: node.name.toLowerCase() }
+ if (node?.type !== 'Dimension') return undefined
+ const value = Number(node.value)
+ return Number.isFinite(value)
+ ? { type: 'dimension', value, unit: node.unit.toLowerCase() }
+ : undefined
+}
+
+/**
+ * Reads a condition with css-tree, so spacing, case and comments do not change what it tests, and
+ * only what CSS calls whitespace separates its parts. Undefined for anything but one `@media` or
+ * unnamed `@container` rule testing one feature: a selector, `@media screen`, or
+ * `@media (a: b) and (c: d)`.
+ */
+export function parseFeatureCondition(css: string): FeatureCondition | undefined {
+ const errors: unknown[] = []
+ const sheet = parse(`${css}{}`, {
+ list: false,
+ positions: false,
+ onParseError: (error) => errors.push(error)
+ })
+ if (errors.length > 0 || sheet.type !== 'StyleSheet' || sheet.children.length !== 1)
+ return undefined
+ const [rule] = sheet.children
+ if (rule.type !== 'Atrule' || rule.prelude?.type !== 'AtrulePrelude') return undefined
+ const name = rule.name.toLowerCase()
+ if (name !== 'media' && name !== 'container') return undefined
+ const feature = onlyFeature(rule.prelude.children)
+ const value = feature && featureValue(feature.value)
+ return feature && value ? { rule: name, feature: feature.name.toLowerCase(), value } : undefined
+}
+
+/** The condition as the stylesheet writes it: `@media (max-width: 640px)`. */
+export function featureConditionCSS({ rule, feature, value }: FeatureCondition): string {
+ const written = value.type === 'keyword' ? value.name : `${value.value}${value.unit}`
+ return `@${rule} (${feature}: ${written})`
+}
diff --git a/packages/dom-css/src/tokens/index.ts b/packages/dom-css/src/tokens/index.ts
index f73045470..7c7aaade8 100644
--- a/packages/dom-css/src/tokens/index.ts
+++ b/packages/dom-css/src/tokens/index.ts
@@ -1,5 +1,7 @@
// Design tokens as CSS custom properties: names, namespaces, units, and the stylesheet.
+export { featureConditionCSS, parseFeatureCondition, type FeatureCondition } from './conditions'
export {
+ collectionVariables,
cssNameCodeSyntax,
deriveCSSName,
explicitCSSName,
@@ -11,6 +13,8 @@ export {
export {
buildTokenStylesheet,
defaultModeCondition,
+ loadTokenValidator,
+ modeAttribute,
tokenStylesheet,
type TokenStylesheet,
type TokenStylesheetFormat,
diff --git a/packages/dom-css/src/tokens/names.ts b/packages/dom-css/src/tokens/names.ts
index f464c8c45..e6be7ae88 100644
--- a/packages/dom-css/src/tokens/names.ts
+++ b/packages/dom-css/src/tokens/names.ts
@@ -94,7 +94,8 @@ export function explicitCSSName(variable: Variable): string | undefined {
}
/**
- * `Gray/50` as COLOR is `color-gray-50`; `Space/small` is `spacing-small`. Two tokens can derive
+ * `Gray/50` as COLOR is `color-gray-50`; `Space/small` is `spacing-small`. A group the next segment
+ * repeats is said once, so `Gap/gap-1` is `gap-1`, as kits that mirror Tailwind classes name them. Two tokens can derive
* the same name, so stylesheet output takes names from `variableCSSNames`, which makes them unique.
*/
export function deriveCSSName(variable: Variable): string {
@@ -103,7 +104,13 @@ export function deriveCSSName(variable: Variable): string {
if (segments.length > 1 && namespace && NAMESPACE_WORDS[segments[0] ?? ''] === namespace) {
segments.shift()
}
- const body = segments.join('-') || 'token'
+ const body =
+ segments
+ .filter((segment, index) => {
+ const next = segments.at(index + 1)
+ return next === undefined || (next !== segment && !next.startsWith(`${segment}-`))
+ })
+ .join('-') || 'token'
if (!namespace || body === namespace || body.startsWith(`${namespace}-`)) return body
return `${namespace}-${body}`
}
diff --git a/packages/dom-css/src/tokens/stylesheet.ts b/packages/dom-css/src/tokens/stylesheet.ts
index d7eba0318..fa86cbfe4 100644
--- a/packages/dom-css/src/tokens/stylesheet.ts
+++ b/packages/dom-css/src/tokens/stylesheet.ts
@@ -276,7 +276,7 @@ export function buildTokenStylesheet(
* object model package loads on first use; its browser build exports nothing, so it is never
* the browser path.
*/
-async function tokenValidator(): Promise<TokenValidator> {
+export async function loadTokenValidator(): Promise<TokenValidator> {
if (typeof CSSStyleSheet === 'function') return createTokenValidator(parseWithBrowser)
const headless = await import('./cssom-validator')
return headless.tokenValidator
@@ -286,5 +286,5 @@ export async function tokenStylesheet(
source: TokenSource,
options: TokenStylesheetOptions
): Promise<TokenStylesheet> {
- return buildTokenStylesheet(source, options, await tokenValidator())
+ return buildTokenStylesheet(source, options, await loadTokenValidator())
}
diff --git a/packages/dom-css/src/tokens/validate.ts b/packages/dom-css/src/tokens/validate.ts
index 6265aa955..ed6ef70a9 100644
--- a/packages/dom-css/src/tokens/validate.ts
+++ b/packages/dom-css/src/tokens/validate.ts
@@ -1,4 +1,5 @@
import type { CSSStyleSheetLike } from '@acemir/cssom'
+import valueParser from 'postcss-value-parser'
type Parse = (cssText: string) => CSSStyleSheetLike
@@ -22,16 +23,33 @@ function rules(sheet: CSSStyleSheetLike): ParsedRule[] {
* or condition that closes its rule early parses to a different number of rules and fails.
*/
export function createTokenValidator(parse: Parse) {
+ /** `--name: value` is one declaration whose value reads back unchanged. */
+ function declaration(name: string, value: string): boolean {
+ const parsed = rules(parse(`:root{--${name}:${value}}`))
+ const [rule] = parsed
+ return (
+ parsed.length === 1 &&
+ rule.style?.length === 1 &&
+ rule.style.getPropertyValue(`--${name}`).trim() === value.trim() &&
+ (rule.cssRules?.length ?? 0) === 0
+ )
+ }
+
return {
- /** `--name: value` is one declaration whose value reads back unchanged. */
- declaration(name: string, value: string): boolean {
- const parsed = rules(parse(`:root{--${name}:${value}}`))
- const [rule] = parsed
+ declaration,
+
+ /**
+ * A custom property name without its `--`: one word to the CSS value tokenizer, which splits
+ * on spaces, colons, commas and slashes, and one declaration to the parser. It starts with a
+ * letter, digit or underscore, so `--` is never doubled into `----`.
+ */
+ name(name: string): boolean {
+ const { nodes } = valueParser(`--${name}`)
return (
- parsed.length === 1 &&
- rule.style?.length === 1 &&
- rule.style.getPropertyValue(`--${name}`).trim() === value.trim() &&
- (rule.cssRules?.length ?? 0) === 0
+ /^\w/.test(name) &&
+ nodes.length === 1 &&
+ nodes[0]?.type === 'word' &&
+ declaration(name, '0')
)
},
diff --git a/packages/dom-css/tests/tokens/conditions.test.ts b/packages/dom-css/tests/tokens/conditions.test.ts
new file mode 100644
index 000000000..24976cdc5
--- /dev/null
+++ b/packages/dom-css/tests/tokens/conditions.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, test } from 'bun:test'
+
+import { featureConditionCSS, parseFeatureCondition } from '#dom-css/tokens/conditions'
+
+const narrow = {
+ rule: 'media',
+ feature: 'max-width',
+ value: { type: 'dimension', value: 640, unit: 'px' }
+} as const
+
+describe('feature conditions', () => {
+ test.each([
+ '@media (max-width: 640px)',
+ '@media(max-width:640px)',
+ ' @media ( max-width : 640px ) ',
+ '@media /* phones */ (max-width: 640px)',
+ '@MEDIA (Max-Width: 640PX)'
+ ])('%j tests one feature however it is spaced', (css) => {
+ expect(parseFeatureCondition(css)).toEqual(narrow)
+ })
+
+ test('reads keywords and container queries', () => {
+ expect(parseFeatureCondition('@media (prefers-color-scheme: dark)')).toEqual({
+ rule: 'media',
+ feature: 'prefers-color-scheme',
+ value: { type: 'keyword', name: 'dark' }
+ })
+ expect(parseFeatureCondition('@container (min-width: 37.5px)')).toEqual({
+ rule: 'container',
+ feature: 'min-width',
+ value: { type: 'dimension', value: 37.5, unit: 'px' }
+ })
+ })
+
+ test.each([
+ '@media\u00A0(max-width: 640px)',
+ '@media (max-width: 640px) and (orientation: landscape)',
+ '@media screen and (max-width: 640px)',
+ '@container card (min-width: 400px)',
+ '@supports (display: grid)',
+ '@media (max-width: 640px) {} .a',
+ '[data-theme="dark"]'
+ ])('%j is not one at-rule testing one feature', (css) => {
+ expect(parseFeatureCondition(css)).toBeUndefined()
+ })
+
+ test('a non-breaking space is not whitespace, so it joins the word after it, as in CSS', () => {
+ expect(parseFeatureCondition('@media (max-width:\u00A0640px)')?.value).toEqual({
+ type: 'keyword',
+ name: '\u00A0640px'
+ })
+ })
+
+ test('writes back as the stylesheet does', () => {
+ expect(featureConditionCSS(narrow)).toBe('@media (max-width: 640px)')
+ })
+})
diff --git a/packages/dom-css/tests/tokens/names.test.ts b/packages/dom-css/tests/tokens/names.test.ts
index 92e971dc6..1bb963710 100644
--- a/packages/dom-css/tests/tokens/names.test.ts
+++ b/packages/dom-css/tests/tokens/names.test.ts
@@ -56,6 +56,13 @@ describe('token CSS names', () => {
expect(tokenSlug('M3')).toBe('m3')
})
+ test('say a group once when the next segment repeats it, as Tailwind-class names do', () => {
+ expect(deriveCSSName(token('Gap/gap-1'))).toBe('gap-1')
+ expect(deriveCSSName(token('Gap/gap-1', { scopes: ['GAP'] }))).toBe('spacing-gap-1')
+ expect(deriveCSSName(token('Blue/Blue', { type: 'COLOR' }))).toBe('color-blue')
+ expect(deriveCSSName(token('Gap/gapless'))).toBe('gap-gapless')
+ })
+
test('read custom property names from code snippets only', () => {
expect(parseCSSName('var(--color-primary)')).toBe('color-primary')
expect(parseCSSName('var(--ui-bg, #fff)')).toBe('ui-bg')
diff --git a/packages/dom-css/tests/tokens/validate.test.ts b/packages/dom-css/tests/tokens/validate.test.ts
new file mode 100644
index 000000000..62ef1984b
--- /dev/null
+++ b/packages/dom-css/tests/tokens/validate.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, test } from 'bun:test'
+
+import { tokenValidator } from '#dom-css/tokens/cssom-validator'
+
+describe('token names', () => {
+ test.each(['color-primary', 'spacing_4', '2xl', 'text-type-title'])('%s is a name', (name) => {
+ expect(tokenValidator.name(name)).toBe(true)
+ })
+
+ // The headless parser also keeps `--a;b`; browsers, where names are typed, drop it.
+ test.each(['', '--', '-x', 'a b', 'a:b', 'a,b', 'a/b', 'a(b', 'a}b', 'a{b'])(
+ '%p is not',
+ (name) => {
+ expect(tokenValidator.name(name)).toBe(false)
+ }
+ )
+})
diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.json
index abbd9cb6d..2f759b7ce 100644
--- a/packages/vue/src/i18n/locales/de/menu.json
+++ b/packages/vue/src/i18n/locales/de/menu.json
@@ -64,6 +64,7 @@
"renameSelection": "Auswahl umbenennen…",
"rulers": "Lineale",
"settings": "Einstellungen…",
+ "variables": "Variablen…",
"splitRight": "Nach rechts teilen",
"splitDown": "Nach unten teilen",
"closeView": "Ansicht schließen",
diff --git a/packages/vue/src/i18n/locales/de/variables.json b/packages/vue/src/i18n/locales/de/variables.json
index cb41a69d3..310f91688 100644
--- a/packages/vue/src/i18n/locales/de/variables.json
+++ b/packages/vue/src/i18n/locales/de/variables.json
@@ -8,8 +8,89 @@
"addMode": "Modus hinzufügen",
"renameMode": "Modus umbenennen",
"duplicateMode": "Modus duplizieren",
- "deleteMode": "Modus loeschen",
+ "deleteMode": "Modus löschen",
"setDefaultMode": "Als Standard festlegen",
- "copyAsCSS": "Als CSS kopieren",
- "copyAsTailwindTheme": "Als Tailwind-Theme kopieren"
+ "copyAsCSS": "Alle Variablen als CSS kopieren",
+ "copyAsTailwindTheme": "Alle Variablen als Tailwind-Theme kopieren",
+ "deleteVariable": "Variable löschen",
+ "modeActions": "Aktionen für {mode}",
+ "collectionSettings": "Sammlungseinstellungen",
+ "noVariables": "Keine Variablen in dieser Sammlung",
+ "name": "Name",
+ "cssName": "CSS-Name",
+ "cssNameHint": "Leer lassen, um ihn aus Name und Geltungsbereichen abzuleiten.",
+ "unit": "Einheit",
+ "unitAuto": "Automatisch",
+ "values": "Werte",
+ "expression": "CSS-Ausdruck",
+ "expressionHint": "Wird in CSS anstelle des Werts geschrieben, z. B. clamp(1rem, 4vw, 1.5rem).",
+ "scopes": "Geltungsbereiche",
+ "description": "Beschreibung",
+ "collection": "Sammlung",
+ "defaultMode": "Standard",
+ "condition": "Bedingung",
+ "conditionHint": "Ein Selektor oder eine @media-, @supports- oder @container-Abfrage.",
+ "appliesWhen": "Gilt wenn",
+ "alwaysOn": "Immer aktiv",
+ "conditionManual": "manuell umgeschaltet wird",
+ "conditionDark": "das System im Dunkelmodus ist",
+ "conditionLight": "das System im Hellmodus ist",
+ "conditionContrast": "hoher Kontrast aktiv ist",
+ "conditionReducedMotion": "reduzierte Bewegung aktiv ist",
+ "conditionScreenNarrower": "der Bildschirm schmaler ist als",
+ "conditionScreenWider": "der Bildschirm breiter ist als",
+ "conditionContainerNarrower": "der Container schmaler ist als",
+ "conditionContainerWider": "der Container breiter ist als",
+ "conditionCustom": "Benutzerdefiniertes CSS",
+ "conditionManualHint": "Wählen Sie ihn pro Ebene auf der Arbeitsfläche. Fügen Sie im Code {attribute} zu einem Element hinzu.",
+ "conditionAutomaticHint": "Wird im Browser automatisch aktiv. Zur Vorschau auf der Arbeitsfläche eine Ebene auf diesen Modus setzen; darauf gesetzte Ebenen werden mit festen Werten exportiert.",
+ "conditionWidth": "Breite",
+ "collectionActions": "Sammlungsaktionen",
+ "value": "Wert",
+ "cssNameInvalid": "Verwenden Sie Buchstaben, Ziffern, Bindestriche und Unterstriche, beginnend mit einem Buchstaben oder einer Ziffer.",
+ "useVariable": "Variable verwenden",
+ "detachVariable": "Variable lösen",
+ "searchVariables": "Variablen suchen",
+ "noMatchingVariables": "Keine Variablen dieses Typs",
+ "hiddenFromPublishing": "Von Veröffentlichung ausblenden",
+ "hiddenFromPublishingHint": "Dateien, die diese Datei als Bibliothek verwenden, sehen sie nicht.",
+ "selectedCount": "{count} Variablen ausgewählt",
+ "duplicate": "Duplizieren",
+ "duplicateName": "{name} Kopie",
+ "moveToGroup": "In Gruppe verschieben",
+ "noGroup": "Keine Gruppe",
+ "newGroup": "Neue Gruppe…",
+ "groupName": "Gruppenname",
+ "move": "Verschieben",
+ "deleteVariables": "Variablen löschen",
+ "collections": "Sammlungen",
+ "groups": "Gruppen",
+ "allVariables": "Alle",
+ "filterByType": "Nach Typ filtern",
+ "copyStylesheet": "Stylesheet kopieren",
+ "expand": "Erweitern",
+ "collapse": "Einklappen",
+ "rowActions": "Aktionen für {name}",
+ "stylesheet": "Stylesheet",
+ "mode": "Modus",
+ "scopeAllFills": "Alle Füllungen",
+ "scopeFrameFill": "Frame-Füllung",
+ "scopeShapeFill": "Formfüllung",
+ "scopeTextFill": "Textfüllung",
+ "scopeStroke": "Kontur",
+ "scopeEffectColor": "Effektfarbe",
+ "scopeCornerRadius": "Eckenradius",
+ "scopeWidthHeight": "Breite und Höhe",
+ "scopeGap": "Abstand",
+ "scopeStrokeFloat": "Konturbreite",
+ "scopeOpacity": "Deckkraft",
+ "scopeEffectFloat": "Effektgröße",
+ "scopeFontStyle": "Schriftstärke",
+ "scopeFontSize": "Schriftgröße",
+ "scopeLineHeight": "Zeilenhöhe",
+ "scopeLetterSpacing": "Zeichenabstand",
+ "scopeParagraphSpacing": "Absatzabstand",
+ "scopeParagraphIndent": "Absatzeinzug",
+ "scopeTextContent": "Textinhalt",
+ "scopeFontFamily": "Schriftfamilie"
}
diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.json
index 1dd01ec16..8bdbf0d73 100644
--- a/packages/vue/src/i18n/locales/es/menu.json
+++ b/packages/vue/src/i18n/locales/es/menu.json
@@ -64,6 +64,7 @@
"renameSelection": "Renombrar selección…",
"rulers": "Reglas",
"settings": "Ajustes…",
+ "variables": "Variables…",
"splitRight": "Dividir a la derecha",
"splitDown": "Dividir hacia abajo",
"closeView": "Cerrar vista",
diff --git a/packages/vue/src/i18n/locales/es/variables.json b/packages/vue/src/i18n/locales/es/variables.json
index 7f5e26b96..4c9374e9f 100644
--- a/packages/vue/src/i18n/locales/es/variables.json
+++ b/packages/vue/src/i18n/locales/es/variables.json
@@ -3,13 +3,94 @@
"renameCollection": "Renombrar colección",
"deleteCollection": "Eliminar colección",
"localVariables": "Variables locales",
- "noVariableCollections": "No hay colecciones de variables",
+ "noVariableCollections": "Sin colecciones de variables",
"modes": "Modos",
- "addMode": "Agregar modo",
+ "addMode": "Añadir modo",
"renameMode": "Renombrar modo",
"duplicateMode": "Duplicar modo",
"deleteMode": "Eliminar modo",
"setDefaultMode": "Establecer como predeterminado",
- "copyAsCSS": "Copiar como CSS",
- "copyAsTailwindTheme": "Copiar como tema de Tailwind"
+ "copyAsCSS": "Copiar todas las variables como CSS",
+ "copyAsTailwindTheme": "Copiar todas las variables como tema de Tailwind",
+ "deleteVariable": "Eliminar variable",
+ "modeActions": "Acciones de {mode}",
+ "collectionSettings": "Ajustes de la colección",
+ "noVariables": "No hay variables en esta colección",
+ "name": "Nombre",
+ "cssName": "Nombre CSS",
+ "cssNameHint": "Déjalo vacío para derivarlo del nombre y los ámbitos.",
+ "unit": "Unidad",
+ "unitAuto": "Auto",
+ "values": "Valores",
+ "expression": "Expresión CSS",
+ "expressionHint": "Se escribe en CSS en lugar del valor, por ejemplo clamp(1rem, 4vw, 1.5rem).",
+ "scopes": "Ámbitos",
+ "description": "Descripción",
+ "collection": "Colección",
+ "defaultMode": "Predeterminado",
+ "condition": "Condición",
+ "conditionHint": "Un selector o una consulta @media, @supports o @container.",
+ "appliesWhen": "Se aplica cuando",
+ "alwaysOn": "Siempre activo",
+ "conditionManual": "se cambia manualmente",
+ "conditionDark": "el sistema está en modo oscuro",
+ "conditionLight": "el sistema está en modo claro",
+ "conditionContrast": "el contraste alto está activado",
+ "conditionReducedMotion": "la reducción de movimiento está activada",
+ "conditionScreenNarrower": "la pantalla es más estrecha que",
+ "conditionScreenWider": "la pantalla es más ancha que",
+ "conditionContainerNarrower": "el contenedor es más estrecho que",
+ "conditionContainerWider": "el contenedor es más ancho que",
+ "conditionCustom": "CSS personalizado",
+ "conditionManualHint": "Elígelo por capa en el lienzo. En el código, añade {attribute} a un elemento.",
+ "conditionAutomaticHint": "Se activa solo en el navegador. Para previsualizarlo en el lienzo, pon una capa en este modo; las capas con este modo se exportan con valores literales.",
+ "conditionWidth": "Ancho",
+ "collectionActions": "Acciones de la colección",
+ "value": "Valor",
+ "cssNameInvalid": "Usa letras, dígitos, guiones y guiones bajos, empezando por una letra o un dígito.",
+ "useVariable": "Usar una variable",
+ "detachVariable": "Desvincular variable",
+ "searchVariables": "Buscar variables",
+ "noMatchingVariables": "No hay variables de este tipo",
+ "hiddenFromPublishing": "Ocultar al publicar",
+ "hiddenFromPublishingHint": "Los archivos que usan este como biblioteca no la ven.",
+ "selectedCount": "{count} variables seleccionadas",
+ "duplicate": "Duplicar",
+ "duplicateName": "{name} copia",
+ "moveToGroup": "Mover al grupo",
+ "noGroup": "Sin grupo",
+ "newGroup": "Nuevo grupo…",
+ "groupName": "Nombre del grupo",
+ "move": "Mover",
+ "deleteVariables": "Eliminar variables",
+ "collections": "Colecciones",
+ "groups": "Grupos",
+ "allVariables": "Todas",
+ "filterByType": "Filtrar por tipo",
+ "copyStylesheet": "Copiar hoja de estilos",
+ "expand": "Expandir",
+ "collapse": "Contraer",
+ "rowActions": "Acciones de {name}",
+ "stylesheet": "Hoja de estilos",
+ "mode": "Modo",
+ "scopeAllFills": "Todos los rellenos",
+ "scopeFrameFill": "Relleno del marco",
+ "scopeShapeFill": "Relleno de la forma",
+ "scopeTextFill": "Relleno del texto",
+ "scopeStroke": "Trazo",
+ "scopeEffectColor": "Color del efecto",
+ "scopeCornerRadius": "Redondeado",
+ "scopeWidthHeight": "Anchura y altura",
+ "scopeGap": "Espaciado",
+ "scopeStrokeFloat": "Grosor del trazo",
+ "scopeOpacity": "Opacidad",
+ "scopeEffectFloat": "Tamaño del efecto",
+ "scopeFontStyle": "Peso de fuente",
+ "scopeFontSize": "Tamaño de fuente",
+ "scopeLineHeight": "Altura de línea",
+ "scopeLetterSpacing": "Espaciado entre letras",
+ "scopeParagraphSpacing": "Espaciado entre párrafos",
+ "scopeParagraphIndent": "Sangría de párrafo",
+ "scopeTextContent": "Contenido del texto",
+ "scopeFontFamily": "Familia tipográfica"
}
diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.json
index 2303cbde2..c9b96fe3b 100644
--- a/packages/vue/src/i18n/locales/fr/menu.json
+++ b/packages/vue/src/i18n/locales/fr/menu.json
@@ -64,6 +64,7 @@
"renameSelection": "Renommer la sélection…",
"rulers": "Règles",
"settings": "Paramètres…",
+ "variables": "Variables…",
"splitRight": "Diviser à droite",
"splitDown": "Diviser vers le bas",
"closeView": "Fermer la vue",
diff --git a/packages/vue/src/i18n/locales/fr/variables.json b/packages/vue/src/i18n/locales/fr/variables.json
index e3640f4f7..4b675d6d7 100644
--- a/packages/vue/src/i18n/locales/fr/variables.json
+++ b/packages/vue/src/i18n/locales/fr/variables.json
@@ -10,6 +10,87 @@
"duplicateMode": "Dupliquer le mode",
"deleteMode": "Supprimer le mode",
"setDefaultMode": "Définir par défaut",
- "copyAsCSS": "Copier en CSS",
- "copyAsTailwindTheme": "Copier comme thème Tailwind"
+ "copyAsCSS": "Copier toutes les variables en CSS",
+ "copyAsTailwindTheme": "Copier toutes les variables en thème Tailwind",
+ "deleteVariable": "Supprimer la variable",
+ "modeActions": "Actions pour {mode}",
+ "collectionSettings": "Paramètres de la collection",
+ "noVariables": "Aucune variable dans cette collection",
+ "name": "Nom",
+ "cssName": "Nom CSS",
+ "cssNameHint": "Laisser vide pour le déduire du nom et des portées.",
+ "unit": "Unité",
+ "unitAuto": "Auto",
+ "values": "Valeurs",
+ "expression": "Expression CSS",
+ "expressionHint": "Écrite à la place de la valeur en CSS, par exemple clamp(1rem, 4vw, 1.5rem).",
+ "scopes": "Portées",
+ "description": "Description",
+ "collection": "Collection",
+ "defaultMode": "Par défaut",
+ "condition": "Condition",
+ "conditionHint": "Un sélecteur ou une requête @media, @supports ou @container.",
+ "appliesWhen": "S’applique quand",
+ "alwaysOn": "Toujours actif",
+ "conditionManual": "il est activé manuellement",
+ "conditionDark": "le système est en mode sombre",
+ "conditionLight": "le système est en mode clair",
+ "conditionContrast": "le contraste élevé est activé",
+ "conditionReducedMotion": "la réduction des animations est activée",
+ "conditionScreenNarrower": "l’écran est plus étroit que",
+ "conditionScreenWider": "l’écran est plus large que",
+ "conditionContainerNarrower": "le conteneur est plus étroit que",
+ "conditionContainerWider": "le conteneur est plus large que",
+ "conditionCustom": "CSS personnalisé",
+ "conditionManualHint": "Choisissez-le par calque sur le canevas. Dans le code, ajoutez {attribute} à un élément.",
+ "conditionAutomaticHint": "S’active tout seul dans le navigateur. Pour le prévisualiser sur le canevas, réglez un calque sur ce mode ; les calques réglés dessus sont exportés avec des valeurs littérales.",
+ "conditionWidth": "Largeur",
+ "collectionActions": "Actions de la collection",
+ "value": "Valeur",
+ "cssNameInvalid": "Utilisez des lettres, des chiffres, des tirets et des tirets bas, en commençant par une lettre ou un chiffre.",
+ "useVariable": "Utiliser une variable",
+ "detachVariable": "Détacher la variable",
+ "searchVariables": "Rechercher des variables",
+ "noMatchingVariables": "Aucune variable de ce type",
+ "hiddenFromPublishing": "Masquer de la publication",
+ "hiddenFromPublishingHint": "Les fichiers qui utilisent celui-ci comme bibliothèque ne le voient pas.",
+ "selectedCount": "{count} variables sélectionnées",
+ "duplicate": "Dupliquer",
+ "duplicateName": "{name} copie",
+ "moveToGroup": "Déplacer vers le groupe",
+ "noGroup": "Aucun groupe",
+ "newGroup": "Nouveau groupe…",
+ "groupName": "Nom du groupe",
+ "move": "Déplacer",
+ "deleteVariables": "Supprimer les variables",
+ "collections": "Collections",
+ "groups": "Groupes",
+ "allVariables": "Toutes",
+ "filterByType": "Filtrer par type",
+ "copyStylesheet": "Copier la feuille de style",
+ "expand": "Développer",
+ "collapse": "Réduire",
+ "rowActions": "Actions de {name}",
+ "stylesheet": "Feuille de style",
+ "mode": "Mode",
+ "scopeAllFills": "Tous les remplissages",
+ "scopeFrameFill": "Remplissage du cadre",
+ "scopeShapeFill": "Remplissage de la forme",
+ "scopeTextFill": "Remplissage du texte",
+ "scopeStroke": "Contour",
+ "scopeEffectColor": "Couleur de l’effet",
+ "scopeCornerRadius": "Rayon d’angle",
+ "scopeWidthHeight": "Largeur et hauteur",
+ "scopeGap": "Espacement",
+ "scopeStrokeFloat": "Épaisseur du contour",
+ "scopeOpacity": "Opacité",
+ "scopeEffectFloat": "Taille de l’effet",
+ "scopeFontStyle": "Graisse",
+ "scopeFontSize": "Taille de police",
+ "scopeLineHeight": "Hauteur de ligne",
+ "scopeLetterSpacing": "Espacement des lettres",
+ "scopeParagraphSpacing": "Espacement des paragraphes",
+ "scopeParagraphIndent": "Retrait de paragraphe",
+ "scopeTextContent": "Contenu du texte",
+ "scopeFontFamily": "Famille de police"
}
diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.json
index af43a2c56..0969cdd81 100644
--- a/packages/vue/src/i18n/locales/it/menu.json
+++ b/packages/vue/src/i18n/locales/it/menu.json
@@ -64,6 +64,7 @@
"renameSelection": "Rinomina selezione…",
"rulers": "Righelli",
"settings": "Impostazioni…",
+ "variables": "Variabili…",
"splitRight": "Dividi a destra",
"splitDown": "Dividi in basso",
"closeView": "Chiudi vista",
diff --git a/packages/vue/src/i18n/locales/it/variables.json b/packages/vue/src/i18n/locales/it/variables.json
index 855ec03b7..68918557e 100644
--- a/packages/vue/src/i18n/locales/it/variables.json
+++ b/packages/vue/src/i18n/locales/it/variables.json
@@ -10,6 +10,87 @@
"duplicateMode": "Duplica modalità",
"deleteMode": "Elimina modalità",
"setDefaultMode": "Imposta come predefinita",
- "copyAsCSS": "Copia come CSS",
- "copyAsTailwindTheme": "Copia come tema Tailwind"
+ "copyAsCSS": "Copia tutte le variabili come CSS",
+ "copyAsTailwindTheme": "Copia tutte le variabili come tema Tailwind",
+ "deleteVariable": "Elimina variabile",
+ "modeActions": "Azioni per {mode}",
+ "collectionSettings": "Impostazioni della raccolta",
+ "noVariables": "Nessuna variabile in questa raccolta",
+ "name": "Nome",
+ "cssName": "Nome CSS",
+ "cssNameHint": "Lascia vuoto per ricavarlo da nome e ambiti.",
+ "unit": "Unità",
+ "unitAuto": "Auto",
+ "values": "Valori",
+ "expression": "Espressione CSS",
+ "expressionHint": "Scritta al posto del valore in CSS, ad esempio clamp(1rem, 4vw, 1.5rem).",
+ "scopes": "Ambiti",
+ "description": "Descrizione",
+ "collection": "Raccolta",
+ "defaultMode": "Predefinita",
+ "condition": "Condizione",
+ "conditionHint": "Un selettore o una query @media, @supports o @container.",
+ "appliesWhen": "Si applica quando",
+ "alwaysOn": "Sempre attivo",
+ "conditionManual": "viene attivata manualmente",
+ "conditionDark": "il sistema è in modalità scura",
+ "conditionLight": "il sistema è in modalità chiara",
+ "conditionContrast": "il contrasto elevato è attivo",
+ "conditionReducedMotion": "la riduzione del movimento è attiva",
+ "conditionScreenNarrower": "lo schermo è più stretto di",
+ "conditionScreenWider": "lo schermo è più largo di",
+ "conditionContainerNarrower": "il contenitore è più stretto di",
+ "conditionContainerWider": "il contenitore è più largo di",
+ "conditionCustom": "CSS personalizzato",
+ "conditionManualHint": "Sceglila per livello sulla tela. Nel codice, aggiungi {attribute} a un elemento.",
+ "conditionAutomaticHint": "Si attiva da sola nel browser. Per vederne l’anteprima sulla tela, imposta un livello su questa modalità; i livelli impostati su di essa vengono esportati con valori letterali.",
+ "conditionWidth": "Larghezza",
+ "collectionActions": "Azioni della raccolta",
+ "value": "Valore",
+ "cssNameInvalid": "Usa lettere, cifre, trattini e trattini bassi, iniziando con una lettera o una cifra.",
+ "useVariable": "Usa una variabile",
+ "detachVariable": "Scollega variabile",
+ "searchVariables": "Cerca variabili",
+ "noMatchingVariables": "Nessuna variabile di questo tipo",
+ "hiddenFromPublishing": "Nascondi dalla pubblicazione",
+ "hiddenFromPublishingHint": "I file che usano questo come libreria non lo vedono.",
+ "selectedCount": "{count} variabili selezionate",
+ "duplicate": "Duplica",
+ "duplicateName": "{name} copia",
+ "moveToGroup": "Sposta nel gruppo",
+ "noGroup": "Nessun gruppo",
+ "newGroup": "Nuovo gruppo…",
+ "groupName": "Nome del gruppo",
+ "move": "Sposta",
+ "deleteVariables": "Elimina variabili",
+ "collections": "Raccolte",
+ "groups": "Gruppi",
+ "allVariables": "Tutte",
+ "filterByType": "Filtra per tipo",
+ "copyStylesheet": "Copia foglio di stile",
+ "expand": "Espandi",
+ "collapse": "Comprimi",
+ "rowActions": "Azioni di {name}",
+ "stylesheet": "Foglio di stile",
+ "mode": "Modalità",
+ "scopeAllFills": "Tutti i riempimenti",
+ "scopeFrameFill": "Riempimento del frame",
+ "scopeShapeFill": "Riempimento della forma",
+ "scopeTextFill": "Riempimento del testo",
+ "scopeStroke": "Contorno",
+ "scopeEffectColor": "Colore dell’effetto",
+ "scopeCornerRadius": "Raggio degli angoli",
+ "scopeWidthHeight": "Larghezza e altezza",
+ "scopeGap": "Spaziatura",
+ "scopeStrokeFloat": "Spessore del contorno",
+ "scopeOpacity": "Opacità",
+ "scopeEffectFloat": "Dimensione dell’effetto",
+ "scopeFontStyle": "Peso del carattere",
+ "scopeFontSize": "Dimensione del carattere",
+ "scopeLineHeight": "Altezza riga",
+ "scopeLetterSpacing": "Spaziatura lettere",
+ "scopeParagraphSpacing": "Spaziatura paragrafi",
+ "scopeParagraphIndent": "Rientro del paragrafo",
+ "scopeTextContent": "Contenuto del testo",
+ "scopeFontFamily": "Famiglia di caratteri"
}
diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.json
index dbe661c6d..6ea4d1914 100644
--- a/packages/vue/src/i18n/locales/ja/menu.json
+++ b/packages/vue/src/i18n/locales/ja/menu.json
@@ -64,6 +64,7 @@
"renameSelection": "選択範囲の名前を変更…",
"rulers": "ルーラー",
"settings": "設定…",
+ "variables": "変数…",
"splitRight": "右に分割",
"splitDown": "下に分割",
"closeView": "ビューを閉じる",
diff --git a/packages/vue/src/i18n/locales/ja/variables.json b/packages/vue/src/i18n/locales/ja/variables.json
index 6379d0176..c6c6831f5 100644
--- a/packages/vue/src/i18n/locales/ja/variables.json
+++ b/packages/vue/src/i18n/locales/ja/variables.json
@@ -1,15 +1,96 @@
{
"createCollection": "コレクションを作成",
- "renameCollection": "コレクションの名前を変更",
+ "renameCollection": "コレクション名を変更",
"deleteCollection": "コレクションを削除",
"localVariables": "ローカル変数",
"noVariableCollections": "変数コレクションがありません",
"modes": "モード",
"addMode": "モードを追加",
- "renameMode": "モードの名前を変更",
+ "renameMode": "モード名を変更",
"duplicateMode": "モードを複製",
"deleteMode": "モードを削除",
"setDefaultMode": "デフォルトに設定",
- "copyAsCSS": "CSSとしてコピー",
- "copyAsTailwindTheme": "Tailwindテーマとしてコピー"
+ "copyAsCSS": "すべての変数を CSS としてコピー",
+ "copyAsTailwindTheme": "すべての変数を Tailwind テーマとしてコピー",
+ "deleteVariable": "変数を削除",
+ "modeActions": "{mode}のアクション",
+ "collectionSettings": "コレクションの設定",
+ "noVariables": "このコレクションに変数がありません",
+ "name": "名前",
+ "cssName": "CSS 名",
+ "cssNameHint": "空にすると、名前とスコープから自動的に決まります。",
+ "unit": "単位",
+ "unitAuto": "自動",
+ "values": "値",
+ "expression": "CSS 式",
+ "expressionHint": "CSS で値の代わりに記述されます。例: clamp(1rem, 4vw, 1.5rem)",
+ "scopes": "スコープ",
+ "description": "説明",
+ "collection": "コレクション",
+ "defaultMode": "デフォルト",
+ "condition": "条件",
+ "conditionHint": "セレクタ、または @media、@supports、@container クエリ。",
+ "appliesWhen": "適用条件",
+ "alwaysOn": "常にオン",
+ "conditionManual": "手動で切り替えたとき",
+ "conditionDark": "システムがダークモードのとき",
+ "conditionLight": "システムがライトモードのとき",
+ "conditionContrast": "ハイコントラストがオンのとき",
+ "conditionReducedMotion": "視差効果の軽減がオンのとき",
+ "conditionScreenNarrower": "画面の幅が次の値より狭いとき",
+ "conditionScreenWider": "画面の幅が次の値より広いとき",
+ "conditionContainerNarrower": "コンテナの幅が次の値より狭いとき",
+ "conditionContainerWider": "コンテナの幅が次の値より広いとき",
+ "conditionCustom": "カスタム CSS",
+ "conditionManualHint": "キャンバス上でレイヤーごとに選択します。コードでは、要素に {attribute} を追加します。",
+ "conditionAutomaticHint": "ブラウザーで自動的にオンになります。キャンバスでプレビューするには、レイヤーをこのモードに設定します。このモードのレイヤーは固定値で書き出されます。",
+ "conditionWidth": "幅",
+ "collectionActions": "コレクションのアクション",
+ "value": "値",
+ "cssNameInvalid": "英字、数字、ハイフン、アンダースコアを使用し、英字または数字で始めてください。",
+ "useVariable": "変数を使用",
+ "detachVariable": "変数をデタッチ",
+ "searchVariables": "変数を検索",
+ "noMatchingVariables": "このタイプの変数はありません",
+ "hiddenFromPublishing": "公開から非表示",
+ "hiddenFromPublishingHint": "これをライブラリとして使用するファイルには表示されません。",
+ "selectedCount": "{count} 個の変数を選択中",
+ "duplicate": "複製",
+ "duplicateName": "{name} のコピー",
+ "moveToGroup": "グループに移動",
+ "noGroup": "グループなし",
+ "newGroup": "新規グループ…",
+ "groupName": "グループ名",
+ "move": "移動",
+ "deleteVariables": "変数を削除",
+ "collections": "コレクション",
+ "groups": "グループ",
+ "allVariables": "すべて",
+ "filterByType": "タイプで絞り込む",
+ "copyStylesheet": "スタイルシートをコピー",
+ "expand": "展開",
+ "collapse": "折りたたむ",
+ "rowActions": "{name} のアクション",
+ "stylesheet": "スタイルシート",
+ "mode": "モード",
+ "scopeAllFills": "すべての塗り",
+ "scopeFrameFill": "フレームの塗り",
+ "scopeShapeFill": "シェイプの塗り",
+ "scopeTextFill": "テキストの塗り",
+ "scopeStroke": "線",
+ "scopeEffectColor": "エフェクトの色",
+ "scopeCornerRadius": "角丸",
+ "scopeWidthHeight": "幅と高さ",
+ "scopeGap": "間隔",
+ "scopeStrokeFloat": "線の太さ",
+ "scopeOpacity": "不透明度",
+ "scopeEffectFloat": "エフェクトのサイズ",
+ "scopeFontStyle": "フォントの太さ",
+ "scopeFontSize": "フォントサイズ",
+ "scopeLineHeight": "行の高さ",
+ "scopeLetterSpacing": "文字間隔",
+ "scopeParagraphSpacing": "段落の間隔",
+ "scopeParagraphIndent": "段落のインデント",
+ "scopeTextContent": "テキストの内容",
+ "scopeFontFamily": "フォントファミリー"
}
diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.json
index 9ff1cb933..f2824bb9c 100644
--- a/packages/vue/src/i18n/locales/pl/menu.json
+++ b/packages/vue/src/i18n/locales/pl/menu.json
@@ -64,6 +64,7 @@
"renameSelection": "Zmień nazwę zaznaczenia…",
"rulers": "Linijki",
"settings": "Ustawienia…",
+ "variables": "Zmienne…",
"splitRight": "Podziel w prawo",
"splitDown": "Podziel w dół",
"closeView": "Zamknij widok",
diff --git a/packages/vue/src/i18n/locales/pl/variables.json b/packages/vue/src/i18n/locales/pl/variables.json
index c914e20b9..b7c7cc9f1 100644
--- a/packages/vue/src/i18n/locales/pl/variables.json
+++ b/packages/vue/src/i18n/locales/pl/variables.json
@@ -10,6 +10,87 @@
"duplicateMode": "Duplikuj tryb",
"deleteMode": "Usuń tryb",
"setDefaultMode": "Ustaw jako domyślny",
- "copyAsCSS": "Kopiuj jako CSS",
- "copyAsTailwindTheme": "Kopiuj jako motyw Tailwind"
+ "copyAsCSS": "Kopiuj wszystkie zmienne jako CSS",
+ "copyAsTailwindTheme": "Kopiuj wszystkie zmienne jako motyw Tailwind",
+ "deleteVariable": "Usuń zmienną",
+ "modeActions": "Akcje dla: {mode}",
+ "collectionSettings": "Ustawienia kolekcji",
+ "noVariables": "Brak zmiennych w tej kolekcji",
+ "name": "Nazwa",
+ "cssName": "Nazwa CSS",
+ "cssNameHint": "Pozostaw puste, aby utworzyć ją z nazwy i zakresów.",
+ "unit": "Jednostka",
+ "unitAuto": "Auto",
+ "values": "Wartości",
+ "expression": "Wyrażenie CSS",
+ "expressionHint": "Zapisywane w CSS zamiast wartości, na przykład clamp(1rem, 4vw, 1.5rem).",
+ "scopes": "Zakresy",
+ "description": "Opis",
+ "collection": "Kolekcja",
+ "defaultMode": "Domyślny",
+ "condition": "Warunek",
+ "conditionHint": "Selektor lub zapytanie @media, @supports albo @container.",
+ "appliesWhen": "Obowiązuje, gdy",
+ "alwaysOn": "Zawsze włączony",
+ "conditionManual": "przełączono ręcznie",
+ "conditionDark": "system jest w trybie ciemnym",
+ "conditionLight": "system jest w trybie jasnym",
+ "conditionContrast": "włączony jest wysoki kontrast",
+ "conditionReducedMotion": "włączone jest ograniczenie ruchu",
+ "conditionScreenNarrower": "ekran jest węższy niż",
+ "conditionScreenWider": "ekran jest szerszy niż",
+ "conditionContainerNarrower": "kontener jest węższy niż",
+ "conditionContainerWider": "kontener jest szerszy niż",
+ "conditionCustom": "Własny CSS",
+ "conditionManualHint": "Wybierz go dla warstwy na kanwie. W kodzie dodaj {attribute} do elementu.",
+ "conditionAutomaticHint": "Włącza się sam w przeglądarce. Aby zobaczyć podgląd na kanwie, ustaw warstwę na ten tryb; warstwy z tym trybem są eksportowane z wartościami dosłownymi.",
+ "conditionWidth": "Szerokość",
+ "collectionActions": "Akcje kolekcji",
+ "value": "Wartość",
+ "cssNameInvalid": "Użyj liter, cyfr, myślników i podkreślników, zaczynając od litery lub cyfry.",
+ "useVariable": "Użyj zmiennej",
+ "detachVariable": "Odłącz zmienną",
+ "searchVariables": "Szukaj zmiennych",
+ "noMatchingVariables": "Brak zmiennych tego typu",
+ "hiddenFromPublishing": "Ukryj przy publikowaniu",
+ "hiddenFromPublishingHint": "Pliki używające tego pliku jako biblioteki jej nie widzą.",
+ "selectedCount": "Wybrane zmienne: {count}",
+ "duplicate": "Duplikuj",
+ "duplicateName": "{name} kopia",
+ "moveToGroup": "Przenieś do grupy",
+ "noGroup": "Bez grupy",
+ "newGroup": "Nowa grupa…",
+ "groupName": "Nazwa grupy",
+ "move": "Przesuń",
+ "deleteVariables": "Usuń zmienne",
+ "collections": "Kolekcje",
+ "groups": "Grupy",
+ "allVariables": "Wszystkie",
+ "filterByType": "Filtruj według typu",
+ "copyStylesheet": "Kopiuj arkusz stylów",
+ "expand": "Rozwiń",
+ "collapse": "Zwiń",
+ "rowActions": "Akcje dla {name}",
+ "stylesheet": "Arkusz stylów",
+ "mode": "Tryb",
+ "scopeAllFills": "Wszystkie wypełnienia",
+ "scopeFrameFill": "Wypełnienie ramki",
+ "scopeShapeFill": "Wypełnienie kształtu",
+ "scopeTextFill": "Wypełnienie tekstu",
+ "scopeStroke": "Obrys",
+ "scopeEffectColor": "Kolor efektu",
+ "scopeCornerRadius": "Promień narożnika",
+ "scopeWidthHeight": "Szerokość i wysokość",
+ "scopeGap": "Odstęp",
+ "scopeStrokeFloat": "Grubość obrysu",
+ "scopeOpacity": "Krycie",
+ "scopeEffectFloat": "Rozmiar efektu",
+ "scopeFontStyle": "Grubość czcionki",
+ "scopeFontSize": "Rozmiar czcionki",
+ "scopeLineHeight": "Wysokość wiersza",
+ "scopeLetterSpacing": "Odstępy między literami",
+ "scopeParagraphSpacing": "Odstęp między akapitami",
+ "scopeParagraphIndent": "Wcięcie akapitu",
+ "scopeTextContent": "Treść tekstu",
+ "scopeFontFamily": "Rodzina czcionek"
}
diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.json
index e5d124315..73c0c911d 100644
--- a/packages/vue/src/i18n/locales/ru/menu.json
+++ b/packages/vue/src/i18n/locales/ru/menu.json
@@ -64,6 +64,7 @@
"renameSelection": "Переименовать выделение…",
"rulers": "Линейки",
"settings": "Настройки…",
+ "variables": "Переменные…",
"splitRight": "Разделить вправо",
"splitDown": "Разделить вниз",
"closeView": "Закрыть вид",
diff --git a/packages/vue/src/i18n/locales/ru/variables.json b/packages/vue/src/i18n/locales/ru/variables.json
index 4162c6887..07291e485 100644
--- a/packages/vue/src/i18n/locales/ru/variables.json
+++ b/packages/vue/src/i18n/locales/ru/variables.json
@@ -9,7 +9,88 @@
"renameMode": "Переименовать режим",
"duplicateMode": "Дублировать режим",
"deleteMode": "Удалить режим",
- "setDefaultMode": "Установить по умолчанию",
- "copyAsCSS": "Копировать как CSS",
- "copyAsTailwindTheme": "Копировать как тему Tailwind"
+ "setDefaultMode": "Сделать основным",
+ "copyAsCSS": "Копировать все переменные как CSS",
+ "copyAsTailwindTheme": "Копировать все переменные как тему Tailwind",
+ "deleteVariable": "Удалить переменную",
+ "modeActions": "Действия для {mode}",
+ "collectionSettings": "Настройки коллекции",
+ "noVariables": "В этой коллекции нет переменных",
+ "name": "Имя",
+ "cssName": "Имя CSS",
+ "cssNameHint": "Оставьте пустым, чтобы получить его из имени и областей применения.",
+ "unit": "Единица",
+ "unitAuto": "Авто",
+ "values": "Значения",
+ "expression": "Выражение CSS",
+ "expressionHint": "Записывается в CSS вместо значения, например clamp(1rem, 4vw, 1.5rem).",
+ "scopes": "Области применения",
+ "description": "Описание",
+ "collection": "Коллекция",
+ "defaultMode": "По умолчанию",
+ "condition": "Условие",
+ "conditionHint": "Селектор или запрос @media, @supports либо @container.",
+ "appliesWhen": "Применяется, когда",
+ "alwaysOn": "Всегда включён",
+ "conditionManual": "переключено вручную",
+ "conditionDark": "система в тёмном режиме",
+ "conditionLight": "система в светлом режиме",
+ "conditionContrast": "включён высокий контраст",
+ "conditionReducedMotion": "включено уменьшение движения",
+ "conditionScreenNarrower": "экран уже, чем",
+ "conditionScreenWider": "экран шире, чем",
+ "conditionContainerNarrower": "контейнер уже, чем",
+ "conditionContainerWider": "контейнер шире, чем",
+ "conditionCustom": "Свой CSS",
+ "conditionManualHint": "Выбирайте для каждого слоя на холсте. В коде добавьте {attribute} к элементу.",
+ "conditionAutomaticHint": "Включается сам в браузере. Чтобы увидеть на холсте, задайте слою этот режим; слои с ним экспортируются с буквальными значениями.",
+ "conditionWidth": "Ширина",
+ "collectionActions": "Действия с коллекцией",
+ "value": "Значение",
+ "cssNameInvalid": "Используйте буквы, цифры, дефисы и подчёркивания; начинать нужно с буквы или цифры.",
+ "useVariable": "Использовать переменную",
+ "detachVariable": "Открепить переменную",
+ "searchVariables": "Поиск переменных",
+ "noMatchingVariables": "Нет переменных этого типа",
+ "hiddenFromPublishing": "Скрыть при публикации",
+ "hiddenFromPublishingHint": "Файлы, использующие этот файл как библиотеку, её не видят.",
+ "selectedCount": "Выбрано переменных: {count}",
+ "duplicate": "Дублировать",
+ "duplicateName": "{name} копия",
+ "moveToGroup": "Переместить в группу",
+ "noGroup": "Без группы",
+ "newGroup": "Новая группа…",
+ "groupName": "Название группы",
+ "move": "Переместить",
+ "deleteVariables": "Удалить переменные",
+ "collections": "Коллекции",
+ "groups": "Группы",
+ "allVariables": "Все",
+ "filterByType": "Фильтр по типу",
+ "copyStylesheet": "Копировать таблицу стилей",
+ "expand": "Развернуть",
+ "collapse": "Свернуть",
+ "rowActions": "Действия с {name}",
+ "stylesheet": "Таблица стилей",
+ "mode": "Режим",
+ "scopeAllFills": "Все заливки",
+ "scopeFrameFill": "Заливка фрейма",
+ "scopeShapeFill": "Заливка фигуры",
+ "scopeTextFill": "Заливка текста",
+ "scopeStroke": "Обводка",
+ "scopeEffectColor": "Цвет эффекта",
+ "scopeCornerRadius": "Радиус скругления",
+ "scopeWidthHeight": "Ширина и высота",
+ "scopeGap": "Отступ",
+ "scopeStrokeFloat": "Толщина обводки",
+ "scopeOpacity": "Непрозрачность",
+ "scopeEffectFloat": "Размер эффекта",
+ "scopeFontStyle": "Насыщенность шрифта",
+ "scopeFontSize": "Размер шрифта",
+ "scopeLineHeight": "Высота строки",
+ "scopeLetterSpacing": "Межбуквенный интервал",
+ "scopeParagraphSpacing": "Интервал между абзацами",
+ "scopeParagraphIndent": "Отступ абзаца",
+ "scopeTextContent": "Содержимое текста",
+ "scopeFontFamily": "Гарнитура шрифта"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.json
index f89fa56e2..0363951b3 100644
--- a/packages/vue/src/i18n/locales/zh-cn/menu.json
+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json
@@ -64,6 +64,7 @@
"renameSelection": "重命名所选内容…",
"rulers": "标尺",
"settings": "设置…",
+ "variables": "变量…",
"splitRight": "向右拆分",
"splitDown": "向下拆分",
"closeView": "关闭视图",
diff --git a/packages/vue/src/i18n/locales/zh-cn/variables.json b/packages/vue/src/i18n/locales/zh-cn/variables.json
index eb18e5384..967197927 100644
--- a/packages/vue/src/i18n/locales/zh-cn/variables.json
+++ b/packages/vue/src/i18n/locales/zh-cn/variables.json
@@ -10,6 +10,87 @@
"duplicateMode": "复制模式",
"deleteMode": "删除模式",
"setDefaultMode": "设为默认",
- "copyAsCSS": "复制为 CSS",
- "copyAsTailwindTheme": "复制为 Tailwind 主题"
+ "copyAsCSS": "将所有变量复制为 CSS",
+ "copyAsTailwindTheme": "将所有变量复制为 Tailwind 主题",
+ "deleteVariable": "删除变量",
+ "modeActions": "{mode}操作",
+ "collectionSettings": "集合设置",
+ "noVariables": "此集合中没有变量",
+ "name": "名称",
+ "cssName": "CSS 名称",
+ "cssNameHint": "留空则根据名称和范围自动生成。",
+ "unit": "单位",
+ "unitAuto": "自动",
+ "values": "值",
+ "expression": "CSS 表达式",
+ "expressionHint": "在 CSS 中替代该值,例如 clamp(1rem, 4vw, 1.5rem)。",
+ "scopes": "范围",
+ "description": "描述",
+ "collection": "集合",
+ "defaultMode": "默认",
+ "condition": "条件",
+ "conditionHint": "选择器,或 @media、@supports、@container 查询。",
+ "appliesWhen": "适用条件",
+ "alwaysOn": "始终开启",
+ "conditionManual": "手动切换时",
+ "conditionDark": "系统处于深色模式时",
+ "conditionLight": "系统处于浅色模式时",
+ "conditionContrast": "开启高对比度时",
+ "conditionReducedMotion": "开启减少动态效果时",
+ "conditionScreenNarrower": "屏幕窄于",
+ "conditionScreenWider": "屏幕宽于",
+ "conditionContainerNarrower": "容器窄于",
+ "conditionContainerWider": "容器宽于",
+ "conditionCustom": "自定义 CSS",
+ "conditionManualHint": "在画布上按图层选择。在代码中,为元素添加 {attribute}。",
+ "conditionAutomaticHint": "在浏览器中自动开启。要在画布上预览,请将图层设为此模式;设为此模式的图层将以字面值导出。",
+ "conditionWidth": "宽度",
+ "collectionActions": "集合操作",
+ "value": "值",
+ "cssNameInvalid": "请使用字母、数字、连字符和下划线,并以字母或数字开头。",
+ "useVariable": "使用变量",
+ "detachVariable": "分离变量",
+ "searchVariables": "搜索变量",
+ "noMatchingVariables": "没有此类型的变量",
+ "hiddenFromPublishing": "发布时隐藏",
+ "hiddenFromPublishingHint": "将此文件用作库的文件将看不到它。",
+ "selectedCount": "已选择 {count} 个变量",
+ "duplicate": "复制",
+ "duplicateName": "{name} 副本",
+ "moveToGroup": "移至分组",
+ "noGroup": "无分组",
+ "newGroup": "新建分组…",
+ "groupName": "分组名称",
+ "move": "移动",
+ "deleteVariables": "删除变量",
+ "collections": "集合",
+ "groups": "分组",
+ "allVariables": "全部",
+ "filterByType": "按类型筛选",
+ "copyStylesheet": "复制样式表",
+ "expand": "展开",
+ "collapse": "收起",
+ "rowActions": "{name} 的操作",
+ "stylesheet": "样式表",
+ "mode": "模式",
+ "scopeAllFills": "所有填充",
+ "scopeFrameFill": "画框填充",
+ "scopeShapeFill": "形状填充",
+ "scopeTextFill": "文本填充",
+ "scopeStroke": "描边",
+ "scopeEffectColor": "效果颜色",
+ "scopeCornerRadius": "圆角",
+ "scopeWidthHeight": "宽度和高度",
+ "scopeGap": "间距",
+ "scopeStrokeFloat": "描边宽度",
+ "scopeOpacity": "不透明度",
+ "scopeEffectFloat": "效果大小",
+ "scopeFontStyle": "字重",
+ "scopeFontSize": "字号",
+ "scopeLineHeight": "行高",
+ "scopeLetterSpacing": "字间距",
+ "scopeParagraphSpacing": "段落间距",
+ "scopeParagraphIndent": "段落缩进",
+ "scopeTextContent": "文本内容",
+ "scopeFontFamily": "字体"
}
diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.ts
index f9d9cc7cb..793a75762 100644
--- a/packages/vue/src/i18n/messages/menu.ts
+++ b/packages/vue/src/i18n/messages/menu.ts
@@ -31,6 +31,7 @@ export const menuMessageDefaults = {
profiler: 'Performance profiler',
language: 'Language',
settings: 'Settings…',
+ variables: 'Variables…',
rulers: 'Rulers',
multiplayerCursors: 'Multiplayer cursors',
designIssues: 'Design issues',
diff --git a/packages/vue/src/i18n/messages/variables.ts b/packages/vue/src/i18n/messages/variables.ts
index d22dce18b..ab35428a3 100644
--- a/packages/vue/src/i18n/messages/variables.ts
+++ b/packages/vue/src/i18n/messages/variables.ts
@@ -1,3 +1,5 @@
+import { params } from '@nanostores/i18n'
+
import { i18n } from '#vue/i18n/create'
export const variablesMessageDefaults = {
@@ -12,8 +14,92 @@ export const variablesMessageDefaults = {
duplicateMode: 'Duplicate mode',
deleteMode: 'Delete mode',
setDefaultMode: 'Set as default',
- copyAsCSS: 'Copy as CSS',
- copyAsTailwindTheme: 'Copy as Tailwind theme'
+ copyAsCSS: 'Copy all variables as CSS',
+ copyAsTailwindTheme: 'Copy all variables as a Tailwind theme',
+ deleteVariable: 'Delete variable',
+ modeActions: params('{mode} actions'),
+ collectionSettings: 'Collection settings',
+ noVariables: 'No variables in this collection',
+ name: 'Name',
+ cssName: 'CSS name',
+ cssNameHint: 'Leave empty to derive it from the name and scopes.',
+ unit: 'Unit',
+ unitAuto: 'Auto',
+ values: 'Values',
+ expression: 'CSS expression',
+ expressionHint: 'Written instead of the value in CSS, such as clamp(1rem, 4vw, 1.5rem).',
+ scopes: 'Scopes',
+ description: 'Description',
+ collection: 'Collection',
+ defaultMode: 'Default',
+ condition: 'Condition',
+ conditionHint: 'A selector, or a @media, @supports or @container query.',
+ appliesWhen: 'Applies when',
+ alwaysOn: 'Always on',
+ conditionManual: 'Switched manually',
+ conditionDark: 'System is in dark mode',
+ conditionLight: 'System is in light mode',
+ conditionContrast: 'High contrast is on',
+ conditionReducedMotion: 'Reduced motion is on',
+ conditionScreenNarrower: 'Screen is narrower than',
+ conditionScreenWider: 'Screen is wider than',
+ conditionContainerNarrower: 'Container is narrower than',
+ conditionContainerWider: 'Container is wider than',
+ conditionCustom: 'Custom CSS',
+ conditionManualHint: params(
+ 'Pick it per layer on the canvas. In code, add {attribute} to an element.'
+ ),
+ conditionAutomaticHint:
+ 'Turns on by itself in the browser. Preview it on the canvas by setting a layer to this mode; layers set to it export with literal values.',
+ conditionWidth: 'Width',
+ collectionActions: 'Collection actions',
+ value: 'Value',
+ cssNameInvalid: 'Use letters, digits, hyphens and underscores, starting with a letter or digit.',
+ useVariable: 'Use a variable',
+ detachVariable: 'Detach variable',
+ searchVariables: 'Search variables',
+ noMatchingVariables: 'No variables of this type',
+ hiddenFromPublishing: 'Hide from publishing',
+ hiddenFromPublishingHint: 'Files that use this one as a library do not see it.',
+ selectedCount: params('{count} variables selected'),
+ duplicate: 'Duplicate',
+ duplicateName: params('{name} copy'),
+ moveToGroup: 'Move to group',
+ noGroup: 'No group',
+ newGroup: 'New group…',
+ groupName: 'Group name',
+ move: 'Move',
+ deleteVariables: 'Delete variables',
+ collections: 'Collections',
+ groups: 'Groups',
+ allVariables: 'All',
+ filterByType: 'Filter by type',
+ copyStylesheet: 'Copy stylesheet',
+ expand: 'Expand',
+ collapse: 'Collapse',
+ rowActions: params('{name} actions'),
+ stylesheet: 'Stylesheet',
+ mode: 'Mode',
+ scopeAllFills: 'All fills',
+ scopeFrameFill: 'Frame fill',
+ scopeShapeFill: 'Shape fill',
+ scopeTextFill: 'Text fill',
+ scopeStroke: 'Stroke',
+ scopeEffectColor: 'Effect color',
+ scopeCornerRadius: 'Corner radius',
+ scopeWidthHeight: 'Width and height',
+ scopeGap: 'Gap',
+ scopeStrokeFloat: 'Stroke width',
+ scopeOpacity: 'Opacity',
+ scopeEffectFloat: 'Effect size',
+ scopeFontStyle: 'Font weight',
+ scopeFontSize: 'Font size',
+ scopeLineHeight: 'Line height',
+ scopeLetterSpacing: 'Letter spacing',
+ scopeParagraphSpacing: 'Paragraph spacing',
+ scopeParagraphIndent: 'Paragraph indent',
+ scopeTextContent: 'Text content',
+ scopeFontFamily: 'Font family'
} as const
export const variablesMessages = i18n('variables', variablesMessageDefaults)
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index 7a083ca2d..acbd2a97a 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -84,6 +84,7 @@ export {
useToolbarState
} from '#vue/primitives/Toolbar/useToolbarState'
export { useNodeFontStatus } from '#vue/shared/font-status/use'
+export { fuzzyFilter, fuzzySearch } from '#vue/shared/search/fuzzy'
export { usePropScrub } from '#vue/controls/prop-scrub/use'
export { toolCursor } from '#vue/editor/tool-cursor'
export {
diff --git a/packages/vue/src/primitives/CommandPalette/useCommandPalette.ts b/packages/vue/src/primitives/CommandPalette/useCommandPalette.ts
index e780c843c..d9382e012 100644
--- a/packages/vue/src/primitives/CommandPalette/useCommandPalette.ts
+++ b/packages/vue/src/primitives/CommandPalette/useCommandPalette.ts
@@ -1,7 +1,8 @@
import { groupBy, take } from 'es-toolkit/array'
-import Fuse from 'fuse.js'
import { computed, ref, type MaybeRefOrGetter, toValue } from 'vue'
+import { fuzzySearch } from '#vue/shared/search/fuzzy'
+
import type { CommandPaletteGroup, CommandPaletteItem, UseCommandPaletteOptions } from './types'
function searchItems(
@@ -15,14 +16,7 @@ function searchItems(
resultLimit
)
- return new Fuse(items, {
- keys: ['label', 'description', 'keywords'],
- threshold: 0.2,
- ignoreLocation: true
- })
- .search(query)
- .slice(0, resultLimit)
- .map((result) => result.item)
+ return fuzzySearch(items, ['label', 'description', 'keywords'], query).slice(0, resultLimit)
}
function filterGroups(
diff --git a/packages/vue/src/shared/search/fuzzy.ts b/packages/vue/src/shared/search/fuzzy.ts
new file mode 100644
index 000000000..ebe39c66f
--- /dev/null
+++ b/packages/vue/src/shared/search/fuzzy.ts
@@ -0,0 +1,23 @@
+import Fuse, { type FuseOptionKey } from 'fuse.js'
+
+/**
+ * How close a query must be, shared by every search in the editor: a typo is forgiven, and a
+ * match counts wherever it falls in the text rather than only near the start.
+ */
+const FUZZY_OPTIONS = { threshold: 0.2, ignoreLocation: true } as const
+
+/** The items that match `query`, best match first, for lists people pick from. */
+export function fuzzySearch<T>(items: readonly T[], keys: FuseOptionKey<T>[], query: string): T[] {
+ return new Fuse(items, { ...FUZZY_OPTIONS, keys }).search(query).map((result) => result.item)
+}
+
+/**
+ * The items that match `query` in their own order, for lists people arrange, such as variables
+ * grouped and reordered by hand. An empty query keeps every item.
+ */
+export function fuzzyFilter<T>(items: readonly T[], keys: FuseOptionKey<T>[], query: string): T[] {
+ const term = query.trim()
+ if (!term) return [...items]
+ const matched = new Set(fuzzySearch(items, keys, term))
+ return items.filter((item) => matched.has(item))
+}
diff --git a/packages/vue/src/variables/helpers.ts b/packages/vue/src/variables/helpers.ts
index 0760fce41..a8e2a7c9e 100644
--- a/packages/vue/src/variables/helpers.ts
+++ b/packages/vue/src/variables/helpers.ts
@@ -107,9 +107,10 @@ export function createVariableValueActions(
return 'New text'
}
- function addVariable(type: VariableType = 'COLOR') {
+ /** Adds a variable to the active collection and returns its id. */
+ function addVariable(type: VariableType = 'COLOR'): string | undefined {
const col = getActiveCollection()
- if (!col) return
+ if (!col) return undefined
const id = `var:${randomHex(8)}`
const valuesByMode: Record<string, VariableValue> = {}
@@ -126,6 +127,7 @@ export function createVariableValueActions(
description: '',
hiddenFromPublishing: false
})
+ return id
}
function removeVariable(id: string) {
diff --git a/packages/vue/src/variables/use.ts b/packages/vue/src/variables/use.ts
index 05b6beb35..8da0eac84 100644
--- a/packages/vue/src/variables/use.ts
+++ b/packages/vue/src/variables/use.ts
@@ -4,6 +4,7 @@ import type { Variable } from '@open-pencil/scene-graph'
import { useEditor } from '#vue/editor/context'
import { useSceneComputed } from '#vue/internal/scene-computed/use'
+import { fuzzyFilter } from '#vue/shared/search/fuzzy'
import { createVariableCollectionActions, createVariableValueActions } from '#vue/variables/helpers'
export function useVariables() {
@@ -14,7 +15,13 @@ export function useVariables() {
searchTerm.value = term
}
- const collections = useSceneComputed(() => editor.getCollections())
+ /**
+ * Snapshots, not the graph's own objects: the editor edits collections in place, so a component
+ * given the same object again would not see a mode added, renamed, or given a condition.
+ */
+ const collections = useSceneComputed(() =>
+ editor.getCollections().map((collection) => structuredClone(collection))
+ )
const activeCollectionId = ref(collections.value[0]?.id ?? '')
watch(collections, (cols) => {
@@ -27,9 +34,7 @@ export function useVariables() {
const variables = useSceneComputed(() => {
if (!activeCollectionId.value) return [] as Variable[]
const all = editor.getVariablesForCollection(activeCollectionId.value)
- if (!searchTerm.value) return all
- const q = searchTerm.value.toLowerCase()
- return all.filter((v) => v.name.toLowerCase().includes(q))
+ return fuzzyFilter(all, ['name', 'description'], searchTerm.value)
})
const collectionActions = createVariableCollectionActions(editor, activeCollectionId)
diff --git a/packages/vue/tests/shared/search/fuzzy.test.ts b/packages/vue/tests/shared/search/fuzzy.test.ts
new file mode 100644
index 000000000..6acf93d70
--- /dev/null
+++ b/packages/vue/tests/shared/search/fuzzy.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, test } from 'bun:test'
+
+import { fuzzyFilter, fuzzySearch } from '#vue/shared/search/fuzzy'
+
+const items = [
+ { name: 'Zoom to fit', keywords: 'view' },
+ { name: 'Zoom in', keywords: 'view' },
+ { name: 'Variables', keywords: 'tokens design tokens' }
+]
+
+describe('fuzzy search', () => {
+ test('ranks the closest match first and forgives a typo', () => {
+ expect(fuzzySearch(items, ['name'], 'zoom in').map((item) => item.name)[0]).toBe('Zoom in')
+ expect(fuzzySearch(items, ['name'], 'varibles').map((item) => item.name)).toEqual([
+ 'Variables'
+ ])
+ })
+
+ test('searches every key it is given', () => {
+ expect(fuzzySearch(items, ['name', 'keywords'], 'tokens').map((item) => item.name)).toEqual([
+ 'Variables'
+ ])
+ })
+
+ test('filtering keeps the list order and an empty query keeps everything', () => {
+ expect(fuzzyFilter(items, ['name'], 'zoom').map((item) => item.name)).toEqual([
+ 'Zoom to fit',
+ 'Zoom in'
+ ])
+ expect(fuzzyFilter(items, ['name'], ' ')).toEqual(items)
+ })
+})
diff --git a/src/AGENTS.md b/src/AGENTS.md
index c86badc44..95613adaf 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -36,6 +36,7 @@ The supported browser baseline lives in `src/app/shell/support/baseline.ts` and
- Browser and native menus share `src/app/shell/menu/schema.ts`; handle IDs in `use.ts` or editor commands, and regenerate `desktop/generated/menu.json` with `bun run generate:tauri-menu`.
- Motion policy lives in `src/app/shell/motion/`: resolve the persisted System/Off preference and OS reduction once. The root `data-motion` attribute and the Tailwind `motion-safe`/`motion-reduce` variants represent the effective policy, including portalled content. Use the policy-aware Motion adapters rather than repeating preference conditionals in components.
+- Canvas shortcuts stop while a dialog, menu, or listbox is open. A dialog that edits the document listens for undo and redo on its own content with `useDocumentShortcuts`, so keys in menus it portals never reach it; there is one history, the editor's (`src/app/shell/keyboard/document.ts`, `src/components/variables/VariablesDialog.vue`).
- Keep the app manifest in `vite/pwa.ts`; use `BrandMark` for in-app branding; never symlink web assets to desktop icons (`tools/AGENTS.md`, Brand assets).
## UI
@@ -51,6 +52,13 @@ The supported browser baseline lives in `src/app/shell/support/baseline.ts` and
- App dialogs compose the Reka-backed components under `src/components/ui/dialog/` and the typed theme in `src/theme/dialog.ts`. Do not repeat portal, overlay, content, header, or footer infrastructure in feature dialogs.
- SDK property primitives, binding fields, commands, and i18n: `packages/vue/AGENTS.md`.
+### Layout
+
+- Lay a component out by the space it is given, not the window: panels, dialogs, and inspectors appear in docks, split views, and phones alike. Restyle with named Tailwind container queries (`@container/name`, `@2xl/name:`) on the element whose width matters, which for a list beside an inspector is the list itself (`src/theme/tokens-panel.ts`, `src/theme/panel/properties-tabs.ts`).
+- When the width changes structure, such as a side inspector becoming a drill-in, measure the container with VueUse `useElementSize` and keep the threshold beside the theme (`TOKENS_PANEL_COMPACT_WIDTH`).
+- Viewport breakpoints (`md:`, `useViewportKind`) are for app-shell decisions only: dock placement, sheets versus popovers, full-screen dialogs (`src/theme/dialog/index.ts`).
+- Stories for adaptive components render fixed container widths as separate stories rather than relying on the viewport toolbar (`src/components/variables/TokensPanel.stories.ts`).
+
### Settings
- Compose Settings sections with `SettingsSection` and its `title`, `description`, `actions`, and default content slots. It owns heading association and internal spacing; `SettingsGroup` owns bordered row grouping. Do not repeat section, header, or spacing markup per feature.
diff --git a/src/app/editor/session/types.ts b/src/app/editor/session/types.ts
index f4a227f72..584d181bb 100644
--- a/src/app/editor/session/types.ts
+++ b/src/app/editor/session/types.ts
@@ -22,6 +22,7 @@ export function createInitialAppEditorState(pageId: string): AppEditorState {
cursorCanvasY: null,
nodeEditState: null,
renameSelectionOpen: false,
+ variablesOpen: false,
renameNodeId: null,
numberFieldFocused: false,
preparation: null,
@@ -43,6 +44,8 @@ export type AppEditorState = EditorState & {
cursorCanvasY: number | null
nodeEditState: NodeEditState | null
renameSelectionOpen: boolean
+ /** The variables dialog, opened from the Design panel, the View menu, or the palette. */
+ variablesOpen: boolean
renameNodeId: string | null
numberFieldFocused: boolean
preparation: EditorPreparation | null
diff --git a/src/app/editor/tokens/conditions.ts b/src/app/editor/tokens/conditions.ts
new file mode 100644
index 000000000..73325eae0
--- /dev/null
+++ b/src/app/editor/tokens/conditions.ts
@@ -0,0 +1,122 @@
+/**
+ * Plain-language presets for a mode's condition, so a designer picks "System is in dark mode"
+ * and the stylesheet still gets the exact CSS a developer expects. Presets only write the
+ * condition string a mode already stores; anything they do not recognize stays custom CSS.
+ */
+import { isEqual } from 'es-toolkit/predicate'
+
+import {
+ featureConditionCSS,
+ parseFeatureCondition,
+ type FeatureCondition
+} from '@open-pencil/dom-css/export'
+
+export const CONDITION_KINDS = [
+ 'manual',
+ 'dark',
+ 'light',
+ 'contrast',
+ 'reduced-motion',
+ 'screen-narrower',
+ 'screen-wider',
+ 'container-narrower',
+ 'container-wider',
+ 'custom'
+] as const
+export type ConditionKind = (typeof CONDITION_KINDS)[number]
+
+/** Presets that take a width in pixels. */
+export const WIDTH_CONDITION_KINDS = [
+ 'screen-narrower',
+ 'screen-wider',
+ 'container-narrower',
+ 'container-wider'
+] as const satisfies readonly ConditionKind[]
+type WidthConditionKind = (typeof WIDTH_CONDITION_KINDS)[number]
+
+export type ModeCondition =
+ | { kind: Exclude<ConditionKind, WidthConditionKind | 'custom'> }
+ | { kind: WidthConditionKind; width: number }
+ | { kind: 'custom'; css: string }
+
+/** The width a new width preset starts at. */
+export const DEFAULT_CONDITION_WIDTH = 640
+
+type FixedConditionKind = 'dark' | 'light' | 'contrast' | 'reduced-motion'
+
+function keyword(feature: string, name: string): FeatureCondition {
+ return { rule: 'media', feature, value: { type: 'keyword', name } }
+}
+
+const FIXED: Record<FixedConditionKind, FeatureCondition> = {
+ dark: keyword('prefers-color-scheme', 'dark'),
+ light: keyword('prefers-color-scheme', 'light'),
+ contrast: keyword('prefers-contrast', 'more'),
+ 'reduced-motion': keyword('prefers-reduced-motion', 'reduce')
+}
+
+const WIDTH: Record<WidthConditionKind, Pick<FeatureCondition, 'rule' | 'feature'>> = {
+ 'screen-narrower': { rule: 'media', feature: 'max-width' },
+ 'screen-wider': { rule: 'media', feature: 'min-width' },
+ 'container-narrower': { rule: 'container', feature: 'max-width' },
+ 'container-wider': { rule: 'container', feature: 'min-width' }
+}
+
+function isWidthKind(kind: ConditionKind): kind is WidthConditionKind {
+ return WIDTH_CONDITION_KINDS.some((candidate) => candidate === kind)
+}
+
+/** The preset a parsed condition is, if any: spacing, case and comments do not matter. */
+function presetOf(query: FeatureCondition): ModeCondition | undefined {
+ const fixed = Object.entries(FIXED).find(([, preset]) => isEqual(preset, query))
+ if (fixed) return { kind: fixed[0] as FixedConditionKind }
+ if (query.value.type !== 'dimension' || query.value.unit !== 'px') return undefined
+ const kind = WIDTH_CONDITION_KINDS.find(
+ (candidate) =>
+ WIDTH[candidate].rule === query.rule && WIDTH[candidate].feature === query.feature
+ )
+ return kind && { kind, width: query.value.value }
+}
+
+/** Reads a stored condition back into the preset that writes it, or custom CSS. */
+export function parseModeCondition(condition: string | undefined): ModeCondition {
+ const css = condition?.trim() ?? ''
+ if (!css) return { kind: 'manual' }
+ const query = parseFeatureCondition(css)
+ return (query && presetOf(query)) ?? { kind: 'custom', css }
+}
+
+/** The condition to store; `undefined` keeps the mode switched manually by its attribute. */
+export function modeConditionCSS(condition: ModeCondition): string | undefined {
+ switch (condition.kind) {
+ case 'manual':
+ return undefined
+ case 'custom':
+ return condition.css.trim() || undefined
+ case 'dark':
+ case 'light':
+ case 'contrast':
+ case 'reduced-motion':
+ return featureConditionCSS(FIXED[condition.kind])
+ default:
+ return featureConditionCSS({
+ ...WIDTH[condition.kind],
+ value: { type: 'dimension', value: condition.width, unit: 'px' }
+ })
+ }
+}
+
+/** Switching presets keeps what still applies: a width carries over between width presets. */
+export function changeConditionKind(current: ModeCondition, kind: ConditionKind): ModeCondition {
+ if (kind === 'custom') return { kind, css: modeConditionCSS(current) ?? '' }
+ if (isWidthKind(kind))
+ return { kind, width: 'width' in current ? current.width : DEFAULT_CONDITION_WIDTH }
+ return { kind }
+}
+
+/** Whether the browser turns the mode on by itself, rather than an attribute in the page. */
+export function isAutomaticCondition(condition: ModeCondition): boolean {
+ if (condition.kind === 'manual') return false
+ if (condition.kind === 'custom') return condition.css.trimStart().startsWith('@')
+ return true
+}
diff --git a/src/app/editor/tokens/dialog.ts b/src/app/editor/tokens/dialog.ts
new file mode 100644
index 000000000..9b022b59b
--- /dev/null
+++ b/src/app/editor/tokens/dialog.ts
@@ -0,0 +1,5 @@
+import type { EditorStore } from '@/app/editor/active-store'
+
+export function openVariablesDialog(store: EditorStore): void {
+ store.state.variablesOpen = true
+}
diff --git a/src/app/editor/tokens/model.ts b/src/app/editor/tokens/model.ts
new file mode 100644
index 000000000..4f795bc1a
--- /dev/null
+++ b/src/app/editor/tokens/model.ts
@@ -0,0 +1,269 @@
+import { compact, groupBy } from 'es-toolkit/array'
+
+import {
+ collectionVariables,
+ defaultModeCondition,
+ modeAttribute,
+ tokenNumberToCSS,
+ variableCSSNames,
+ variableUnit
+} from '@open-pencil/dom-css/export'
+import {
+ tokenNumberFromUnit,
+ tokenNumberInUnit,
+ type Color,
+ type SceneGraph,
+ type Variable,
+ type VariableCollection,
+ type VariableValue
+} from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
+import { fuzzyFilter } from '@open-pencil/vue'
+
+/** One mode's value as the stylesheet writes it, with what the panel previews beside it. */
+export interface TokenModeValue {
+ modeId: string
+ css: string
+ color?: Color
+ /** The aliased variable's name, when the value points at another token. */
+ alias?: string
+ /** A CSS expression written instead of the stored number, such as `clamp(…)`. */
+ expression?: string
+}
+
+export interface TokenRow {
+ variable: Variable
+ /** The name inside its group: `500` for `Blue/500`. */
+ label: string
+ cssName: string
+ values: TokenModeValue[]
+}
+
+export interface TokenGroup {
+ /** The name path above the rows, `Blue` for `Blue/500`; empty for top-level tokens. */
+ path: string
+ rows: TokenRow[]
+}
+
+function modeValue(
+ graph: SceneGraph,
+ variable: Variable,
+ modeId: string,
+ value: VariableValue | undefined
+): TokenModeValue {
+ const expression = variable.expressions?.[modeId]?.css
+ if (typeof value === 'object' && 'aliasId' in value) {
+ const target = graph.variables.get(value.aliasId)
+ // The column's own mode, so Dark previews what the alias gives in Dark.
+ const resolved = graph.resolveVariable(value.aliasId, modeId)
+ const color = typeof resolved === 'object' && 'r' in resolved ? resolved : undefined
+ return { modeId, css: target?.name ?? value.aliasId, alias: target?.name, color, expression }
+ }
+ if (typeof value === 'object') return { modeId, css: colorToHex(value), color: value, expression }
+ if (typeof value === 'number')
+ return { modeId, css: tokenNumberToCSS(value, variableUnit(variable)), expression }
+ return { modeId, css: value === undefined ? '' : String(value), expression }
+}
+
+function splitName(name: string): { path: string; label: string } {
+ const at = name.lastIndexOf('/')
+ return at === -1
+ ? { path: '', label: name }
+ : { path: name.slice(0, at), label: name.slice(at + 1) }
+}
+
+/** A collection's tokens grouped by their name path, with CSS names unique across the document. */
+export function tokenGroups(
+ graph: SceneGraph,
+ collection: VariableCollection,
+ variables: readonly Variable[]
+): TokenGroup[] {
+ const names = variableCSSNames(collectionVariables(graph))
+ const rows = variables.map((variable): TokenRow & { path: string } => {
+ const { path, label } = splitName(variable.name)
+ return {
+ variable,
+ path,
+ label,
+ cssName: names.get(variable.id) ?? variable.id,
+ values: collection.modes.map((mode) =>
+ modeValue(graph, variable, mode.modeId, variable.valuesByMode[mode.modeId])
+ )
+ }
+ })
+ return Object.entries(groupBy(rows, (row) => row.path)).map(([path, grouped]) => ({
+ path,
+ rows: grouped
+ }))
+}
+
+/** The condition a mode applies under when it names none, shown as the input's placeholder. */
+export function modeConditionPlaceholder(
+ collection: VariableCollection,
+ modeId: string
+): string | undefined {
+ if (modeId === collection.defaultModeId) return undefined
+ const mode = collection.modes.find((candidate) => candidate.modeId === modeId)
+ return mode && defaultModeCondition(collection, mode)
+}
+
+/** The attribute that turns a manual mode on, as an element carries it: `data-theme="dark"`. */
+export function modeAttributeText(collection: VariableCollection, modeId: string): string {
+ const mode = collection.modes.find((candidate) => candidate.modeId === modeId)
+ if (!mode) return ''
+ const { name, value } = modeAttribute(collection, mode)
+ return `${name}="${value}"`
+}
+
+/**
+ * A number or text value typed for a token, numbers in the token's unit (`1.5` for 24px in a
+ * `rem` token). Undefined when the text is not a number for a number token.
+ */
+export function parseTokenValueText(variable: Variable, text: string): VariableValue | undefined {
+ if (variable.type === 'STRING') return text
+ if (variable.type !== 'FLOAT') return undefined
+ const number = Number(text)
+ return text.trim() && Number.isFinite(number)
+ ? tokenNumberFromUnit(number, variableUnit(variable))
+ : undefined
+}
+
+/** A number or text value as it is typed back, numbers in the token's unit. */
+export function tokenValueText(variable: Variable, value: VariableValue | undefined): string {
+ if (typeof value === 'number')
+ return String(Number(tokenNumberInUnit(value, variableUnit(variable)).toFixed(6)))
+ return typeof value === 'object' ? '' : String(value ?? '')
+}
+
+/** The group paths a collection's tokens use, in list order, for "Move to group". */
+export function groupPaths(groups: readonly TokenGroup[]): string[] {
+ return groups.flatMap((group) => (group.path ? [group.path] : []))
+}
+
+/** What a token is found by: its name, its CSS name with `--`, its description, and its values. */
+interface TokenSearchEntry {
+ id: string
+ name: string
+ css: string
+ description: string
+ values: string[]
+}
+
+const TOKEN_SEARCH_KEYS = ['name', 'css', 'description', 'values'] satisfies Array<
+ keyof TokenSearchEntry
+>
+
+/**
+ * The tokens a search matches, with the same fuzzy matching as the command palette, so
+ * `--spacing`, `brand primary`, a hex color or an alias name all find what they name. Null when
+ * there is nothing to search for, so the list stays whole.
+ */
+export function searchTokenIds(rows: readonly TokenRow[], query: string): Set<string> | null {
+ if (!query.trim()) return null
+ const entries = rows.map((row): TokenSearchEntry => ({
+ id: row.variable.id,
+ name: row.variable.name,
+ css: `--${row.cssName}`,
+ description: row.variable.description,
+ values: row.values.flatMap((value) => compact([value.css, value.alias, value.expression]))
+ }))
+ return new Set(fuzzyFilter(entries, TOKEN_SEARCH_KEYS, query).map((entry) => entry.id))
+}
+
+/** One group in the sidebar: its path, its last segment, how deep it sits, and its tokens. */
+export interface GroupEntry {
+ path: string
+ label: string
+ depth: number
+ /** Tokens in the group and every group inside it. */
+ count: number
+}
+
+/** Every group and the groups that contain it, in list order, with counts that include nesting. */
+export function groupTree(groups: readonly TokenGroup[]): GroupEntry[] {
+ const entries = new Map<string, GroupEntry>()
+ for (const group of groups) {
+ if (!group.path) continue
+ const segments = group.path.split('/')
+ segments.forEach((segment, index) => {
+ const path = segments.slice(0, index + 1).join('/')
+ const entry = entries.get(path) ?? { path, label: segment, depth: index, count: 0 }
+ entry.count += group.rows.length
+ entries.set(path, entry)
+ })
+ }
+ return [...entries.values()]
+}
+
+/** Whether a token's group is `group` or sits inside it. */
+export function inGroup(path: string, group: string): boolean {
+ return path === group || path.startsWith(`${group}/`)
+}
+
+/** A token's name moved into `group`, keeping its own last segment: `Brand/Primary`. */
+export function nameInGroup(name: string, group: string): string {
+ const label = name.slice(name.lastIndexOf('/') + 1)
+ return group ? `${group}/${label}` : label
+}
+
+/**
+ * A collection's order after moving `sourceId` to `targetIndex` among the `visible` rows. Rows a
+ * search or filter hides keep their places, so dragging a filtered list never shuffles them.
+ */
+export function reorderedVariableIds(
+ order: readonly string[],
+ visible: readonly string[],
+ sourceId: string,
+ targetIndex: number
+): string[] {
+ const moved = visible.filter((id) => id !== sourceId)
+ moved.splice(targetIndex, 0, sourceId)
+ const shown = new Set(visible)
+ let next = 0
+ return order.map((id) => (shown.has(id) ? (moved[next++] ?? id) : id))
+}
+
+/** A variable a token can alias, labelled for the picker and grouped by its collection. */
+export interface AliasCandidate {
+ id: string
+ name: string
+ collection: string
+ color?: Color
+}
+
+/** Whether `fromId` reaches `targetId` through aliases in any mode. */
+function aliasesTo(
+ graph: SceneGraph,
+ fromId: string,
+ targetId: string,
+ seen = new Set<string>()
+): boolean {
+ if (fromId === targetId) return true
+ if (seen.has(fromId)) return false
+ seen.add(fromId)
+ const from = graph.variables.get(fromId)
+ return Object.values(from?.valuesByMode ?? {}).some(
+ (value) =>
+ typeof value === 'object' &&
+ 'aliasId' in value &&
+ aliasesTo(graph, value.aliasId, targetId, seen)
+ )
+}
+
+/**
+ * Variables of the same type a token can point at: never itself, and never one that already
+ * points back at it, which would make the two resolve to nothing.
+ */
+export function aliasCandidates(graph: SceneGraph, variable: Variable): AliasCandidate[] {
+ return [...graph.variables.values()].flatMap((candidate) => {
+ if (candidate.type !== variable.type || aliasesTo(graph, candidate.id, variable.id)) return []
+ return [
+ {
+ id: candidate.id,
+ name: candidate.name,
+ collection: graph.variableCollections.get(candidate.collectionId)?.name ?? '',
+ color: variable.type === 'COLOR' ? graph.resolveColorVariable(candidate.id) : undefined
+ }
+ ]
+ })
+}
diff --git a/src/app/editor/tokens/scopes.ts b/src/app/editor/tokens/scopes.ts
new file mode 100644
index 000000000..c59f63a15
--- /dev/null
+++ b/src/app/editor/tokens/scopes.ts
@@ -0,0 +1,22 @@
+import type { VariableScope, VariableType } from '@open-pencil/scene-graph'
+
+/** The scopes Figma offers for each variable type; scopes also pick a token's Tailwind namespace. */
+export const SCOPES_BY_TYPE: Record<VariableType, readonly VariableScope[]> = {
+ COLOR: ['ALL_FILLS', 'FRAME_FILL', 'SHAPE_FILL', 'TEXT_FILL', 'STROKE', 'EFFECT_COLOR'],
+ FLOAT: [
+ 'CORNER_RADIUS',
+ 'WIDTH_HEIGHT',
+ 'GAP',
+ 'STROKE_FLOAT',
+ 'OPACITY',
+ 'EFFECT_FLOAT',
+ 'FONT_STYLE',
+ 'FONT_SIZE',
+ 'LINE_HEIGHT',
+ 'LETTER_SPACING',
+ 'PARAGRAPH_SPACING',
+ 'PARAGRAPH_INDENT'
+ ],
+ STRING: ['TEXT_CONTENT', 'FONT_FAMILY', 'FONT_STYLE'],
+ BOOLEAN: []
+}
diff --git a/src/app/shell/keyboard/document.ts b/src/app/shell/keyboard/document.ts
new file mode 100644
index 000000000..b081bf899
--- /dev/null
+++ b/src/app/shell/keyboard/document.ts
@@ -0,0 +1,29 @@
+import { createKeybindingsHandler, type KeyBindingMap } from 'tinykeys'
+
+import { editorCommandMetadata, useEditorCommands, type EditorCommandId } from '@open-pencil/vue'
+
+import { isEditing } from '@/app/shell/keyboard/focus'
+
+const DOCUMENT_COMMANDS = ['edit.undo', 'edit.redo'] as const satisfies EditorCommandId[]
+
+/**
+ * A keydown listener for a dialog that edits the document, such as the variables dialog: undo
+ * and redo run on the editor's history, as on the canvas. Only keys pressed inside the dialog
+ * reach it, so a menu or picker it opens, which portals elsewhere, holds them back, and a text
+ * field keeps its own undo.
+ */
+export function useDocumentShortcuts(): (event: KeyboardEvent) => void {
+ const { runCommand } = useEditorCommands()
+ const bindings: KeyBindingMap = {}
+ for (const command of DOCUMENT_COMMANDS) {
+ for (const keys of [editorCommandMetadata(command).keybinding ?? []].flat()) {
+ bindings[keys] = (event) => {
+ if (isEditing(event)) return
+ event.preventDefault()
+ runCommand(command)
+ }
+ }
+ }
+ const handler = createKeybindingsHandler(bindings)
+ return (event) => handler(event)
+}
diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.ts
index e98b0909c..341049c8a 100644
--- a/src/app/shell/menu/app-menu.ts
+++ b/src/app/shell/menu/app-menu.ts
@@ -12,6 +12,7 @@ import IconSave from '~icons/lucide/save'
import IconSettings from '~icons/lucide/settings'
import IconType from '~icons/lucide/type'
import IconUndo from '~icons/lucide/undo-2'
+import IconVariables from '~icons/lucide/variable'
import IconZoomIn from '~icons/lucide/zoom-in'
import IconZoomOut from '~icons/lucide/zoom-out'
@@ -20,6 +21,7 @@ import type { CommandPaletteGroup, CommandPaletteItem, MenuEntry } from '@open-p
import { shortcutPlatform, useEditorCommands, useI18n } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
+import { openVariablesDialog } from '@/app/editor/tokens/dialog'
import { openSettingsDialog } from '@/app/settings/dialog'
import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'
import { appPreferences } from '@/app/settings/preferences/store'
@@ -56,6 +58,7 @@ const APP_MENU_ICONS: Record<AppMenuIcon, Component> = {
settings: IconSettings,
type: IconType,
undo: IconUndo,
+ variables: IconVariables,
'zoom-in': IconZoomIn,
'zoom-out': IconZoomOut
}
@@ -109,6 +112,7 @@ export function useAppMenu() {
language: 'language',
preferences: 'preferences',
settings: 'settings',
+ variables: 'variables',
'view-rulers': 'rulers',
'view-multiplayer-cursors': 'multiplayerCursors',
'view-design-issues': 'designIssues',
@@ -164,6 +168,7 @@ export function useAppMenu() {
if (activeTab.value) void closeTab(activeTab.value.id)
},
settings: openSettingsDialog,
+ variables: () => openVariablesDialog(store),
'export-png': () => exportSelection('png'),
'export-svg': () => exportSelection('svg'),
'export-pptx': () => exportSelection('pptx'),
diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.ts
index 252088011..91c0b5e41 100644
--- a/src/app/shell/menu/schema.ts
+++ b/src/app/shell/menu/schema.ts
@@ -13,6 +13,7 @@ export type AppMenuIcon =
| 'save'
| 'settings'
| 'type'
+ | 'variables'
| 'undo'
| 'zoom-in'
| 'zoom-out'
@@ -174,6 +175,15 @@ export const APP_MENU_SCHEMA = [
{ id: 'view-split-right', label: 'Split Right' },
{ id: 'view-split-down', label: 'Split Down' },
{ type: 'separator' },
+ {
+ id: 'variables',
+ label: 'Variables…',
+ palette: {
+ icon: 'variables',
+ keywords: ['tokens', 'design tokens', 'css variables', 'collections', 'modes', 'theme']
+ }
+ },
+ { type: 'separator' },
{ id: 'view-rulers', label: 'Rulers', checkbox: true },
{ id: 'view-multiplayer-cursors', label: 'Multiplayer Cursors', checkbox: true },
{ id: 'view-design-issues', label: 'Design Issues', checkbox: true, handler: 'shell' },
diff --git a/src/components/ColorPicker/ColorInput.vue b/src/components/ColorPicker/ColorInput.vue
index e03528674..b55ced3bd 100644
--- a/src/components/ColorPicker/ColorInput.vue
+++ b/src/components/ColorPicker/ColorInput.vue
@@ -20,7 +20,7 @@ const {
editable?: boolean
okhcl?: OkHCLControls | null
}>()
-const emit = defineEmits<{ update: [color: Color] }>()
+const emit = defineEmits<{ update: [color: Color]; openChange: [open: boolean] }>()
</script>
<template>
@@ -32,7 +32,12 @@ const emit = defineEmits<{ update: [color: Color] }>()
>
<template #default="{ editable: isEditable, hex, actions, okhcl: okhclControls }">
<div v-bind="attrs" class="flex items-center gap-1.5">
- <ColorPicker :color="color" :okhcl="okhclControls" @update="actions.updateColor($event)" />
+ <ColorPicker
+ :color="color"
+ :okhcl="okhclControls"
+ @update="actions.updateColor($event)"
+ @open-change="emit('openChange', $event)"
+ />
<input
v-if="isEditable"
data-test-id="color-hex-input"
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index c0d4cd3a5..7ff7c8579 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -1,10 +1,11 @@
<script setup lang="ts">
-import { computed, ref } from 'vue'
+import { computed } from 'vue'
import { useI18n, useSelectionState, useEditorCommands } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { COMPONENT_TYPES, nodeIcon } from '@/app/editor/icons'
+import { openVariablesDialog } from '@/app/editor/tokens/dialog'
import { openLibraryReview, useLibraryService } from '@/app/libraries'
import Tip from '@/components/ui/overlay/Tip.vue'
import PanelHeader from '@/components/ui/panel/PanelHeader.vue'
@@ -30,9 +31,7 @@ import SelectionActionsControl from './properties/SelectionActionsControl.vue'
import StrokeSection from './properties/stroke/StrokeSection.vue'
import TypographySection from './properties/TypographySection.vue'
import VariablesSection from './properties/VariablesSection.vue'
-import VariablesDialog from './variables/VariablesDialog.vue'
-const variablesOpen = ref(false)
const store = useEditorStore()
const libraryService = useLibraryService()
const activeTool = computed(() => store.state.activeTool)
@@ -186,9 +185,7 @@ const { panels } = useI18n()
class="scrollbar-thin flex-1 overflow-x-hidden overflow-y-auto pb-4"
>
<PageSection />
- <VariablesSection @open-dialog="variablesOpen = true" />
+ <VariablesSection @open-dialog="openVariablesDialog(store)" />
<ExportSection />
</div>
-
- <VariablesDialog v-model:open="variablesOpen" />
</template>
diff --git a/src/components/code-editor/CodeViewer.vue b/src/components/code-editor/CodeViewer.vue
index 9a7d46921..1f1a80c42 100644
--- a/src/components/code-editor/CodeViewer.vue
+++ b/src/components/code-editor/CodeViewer.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { css } from '@codemirror/lang-css'
import { javascript } from '@codemirror/lang-javascript'
import { json } from '@codemirror/lang-json'
import { foldGutter } from '@codemirror/language'
@@ -9,26 +10,37 @@ import { EditorView, highlightSpecialChars, keymap } from '@codemirror/view'
import { useTemplateRef, watch } from 'vue'
import { useCodeMirror } from '@/components/code-editor/useCodeMirror'
-import { codeEditorTheme, codeViewerTheme } from '@/theme/code/editor'
+import { codeEditorTheme, codeViewerFillTheme, codeViewerTheme } from '@/theme/code/editor'
-export type CodeViewerLanguage = 'json' | 'design-jsx' | 'javascript'
+export type CodeViewerLanguage = 'json' | 'design-jsx' | 'javascript' | 'css'
-const { code, language, label, original } = defineProps<{
+const {
+ code,
+ language,
+ label,
+ original,
+ fill = false
+} = defineProps<{
code: string
language: CodeViewerLanguage
label: string
/** Shows `code` as a unified diff against this text. Read at mount. */
original?: string
+ /** Take the parent's height instead of the 16rem cap. Read at mount. */
+ fill?: boolean
}>()
function languageExtension(language: CodeViewerLanguage): Extension {
- return language === 'json' ? json() : javascript({ jsx: true, typescript: true })
+ if (language === 'json') return json()
+ if (language === 'css') return css()
+ return javascript({ jsx: true, typescript: true })
}
const view = useCodeMirror(useTemplateRef('host'), {
doc: () => code,
label: () => label,
- theme: (dark) => [codeEditorTheme(dark), codeViewerTheme],
+ // Earlier extensions win in CodeMirror, so the fill theme goes before the 16rem cap.
+ theme: (dark) => [fill ? codeViewerFillTheme : [], codeEditorTheme(dark), codeViewerTheme],
extensions: [
EditorState.readOnly.of(true),
highlightSpecialChars(),
@@ -64,6 +76,7 @@ watch(
<div
ref="host"
data-slot="code-viewer"
- class="max-h-64 overflow-hidden rounded border border-border [&_.cm-scroller]:scrollbar-thin"
+ :data-fill="fill || undefined"
+ class="max-h-64 overflow-hidden rounded border border-border data-[fill]:max-h-none [&_.cm-scroller]:scrollbar-thin"
/>
</template>
diff --git a/src/components/editor/EditorWorkspace.vue b/src/components/editor/EditorWorkspace.vue
index 671f889c9..97646edbd 100644
--- a/src/components/editor/EditorWorkspace.vue
+++ b/src/components/editor/EditorWorkspace.vue
@@ -22,6 +22,7 @@ import MobileHud from '@/components/MobileHud/MobileHud.vue'
import PropertiesPanel from '@/components/PropertiesPanel.vue'
import Toolbar from '@/components/Toolbar/Toolbar.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
+import VariablesDialog from '@/components/variables/VariablesDialog.vue'
import splitterTheme from '@/theme/splitter'
const showChrome = appRuntimeConfig.showChrome
@@ -142,4 +143,6 @@ const { pending: roomPending } = useRoomActions()
<ActiveRoomOverlay />
</div>
</div>
+
+ <VariablesDialog />
</template>
diff --git a/src/components/settings/models/ModelsPanel.vue b/src/components/settings/models/ModelsPanel.vue
index 0a96255f2..30816f17e 100644
--- a/src/components/settings/models/ModelsPanel.vue
+++ b/src/components/settings/models/ModelsPanel.vue
@@ -1,6 +1,5 @@
<script setup lang="ts">
-import { templateRef } from '@vueuse/core'
-import { nextTick, ref, onUnmounted } from 'vue'
+import { ref, onUnmounted } from 'vue'
import { useI18n } from '@open-pencil/vue'
@@ -11,41 +10,21 @@ import ProfileEditor from '@/components/settings/models/ProfileEditor.vue'
import RoleAssignments from '@/components/settings/models/RoleAssignments.vue'
import AppButton from '@/components/ui/button/AppButton.vue'
import AppActionRow from '@/components/ui/list/AppActionRow.vue'
-import { modelPanelTransition } from '@/theme/settings/models'
+import PanelDrillIn from '@/components/ui/panel/PanelDrillIn.vue'
const { ai, collaboration, common } = useI18n()
const editing = defineModel<boolean>('editing', { default: false })
const editingProfileId = ref<string>()
-const editorLeaving = ref(false)
-const panel = templateRef<HTMLElement>('panel')
-let returnFocus: HTMLElement | null = null
-function captureFocus() {
- returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null
-}
-async function restoreFocus() {
- editorLeaving.value = false
- await nextTick()
- if (returnFocus?.isConnected) returnFocus.focus({ preventScroll: true })
- returnFocus = null
-}
-async function focusEditor() {
- await nextTick()
- panel.value
- ?.querySelector<HTMLInputElement>('[data-test-id="settings-model-editor"] input')
- ?.focus({ preventScroll: true })
-}
onUnmounted(() => {
editing.value = false
})
function addModel(): void {
- captureFocus()
editingProfileId.value = undefined
editing.value = true
}
function editModel(profileId: string): void {
- captureFocus()
editingProfileId.value = profileId
editing.value = true
}
@@ -59,7 +38,6 @@ function statusLabel(connectionId: string, providerID: string): string {
}
function closeEditor(): void {
- editorLeaving.value = true
editing.value = false
void refreshStatuses()
}
@@ -68,23 +46,17 @@ const { profiles, statusByConnection, refreshStatuses } = useModelSettings()
</script>
<template>
- <div ref="panel" class="relative flex min-h-0 flex-1 flex-col">
- <Transition
- v-bind="modelPanelTransition"
- @after-enter="focusEditor"
- @after-leave="restoreFocus"
- >
- <div v-if="editing" class="absolute inset-0 flex min-h-0 flex-col">
- <ProfileEditor
- :key="editingProfileId ?? 'new'"
- :profile-id="editingProfileId"
- @done="closeEditor"
- @deleted="closeEditor"
- />
- </div>
- </Transition>
+ <PanelDrillIn :open="editing" :back="common.back" :parent="ai.modelsTitle" @back="closeEditor">
+ <template #detail>
+ <ProfileEditor
+ :key="editingProfileId ?? 'new'"
+ :profile-id="editingProfileId"
+ @done="closeEditor"
+ @deleted="closeEditor"
+ />
+ </template>
- <SettingsPage v-show="!editing && !editorLeaving">
+ <SettingsPage>
<div class="flex flex-col gap-6">
<SettingsSection>
<template #title>{{ ai.modelsTitle }}</template>
@@ -168,5 +140,5 @@ const { profiles, statusByConnection, refreshStatuses } = useModelSettings()
<slot />
</div>
</SettingsPage>
- </div>
+ </PanelDrillIn>
</template>
diff --git a/src/components/ui/dialog/index.ts b/src/components/ui/dialog/index.ts
index 1ba07b2a8..672a1586c 100644
--- a/src/components/ui/dialog/index.ts
+++ b/src/components/ui/dialog/index.ts
@@ -2,6 +2,7 @@ export { default as AppAlertDialogRoot } from './AppAlertDialogRoot.vue'
export { default as AppConfirmationDialog } from './AppConfirmationDialog.vue'
export { default as AppDialog } from './AppDialog.vue'
export { default as AppDialogBody } from './AppDialogBody.vue'
+export { default as AppDialogClose } from './AppDialogClose.vue'
export { default as AppDialogFooter } from './AppDialogFooter.vue'
export { default as AppDialogHeader } from './AppDialogHeader.vue'
export { default as AppDialogRoot } from './AppDialogRoot.vue'
diff --git a/src/components/ui/input/AppInput.vue b/src/components/ui/input/AppInput.vue
index 8c33ba363..6a27e5c74 100644
--- a/src/components/ui/input/AppInput.vue
+++ b/src/components/ui/input/AppInput.vue
@@ -59,11 +59,12 @@ function inputClass() {
size,
state,
density,
+ // An instance's own input classes come last, so they can override the adornment padding.
class: [
- ui?.input,
!slots.leading && !slots.trailing ? normalizeClass(className) : '',
slots.leading ? 'pl-10' : '',
- slots.trailing ? 'pr-10 [&::-webkit-search-cancel-button]:appearance-none' : ''
+ slots.trailing ? 'pr-10 [&::-webkit-search-cancel-button]:appearance-none' : '',
+ ui?.input
]
})
}
diff --git a/src/components/ui/panel/PanelDrillIn.vue b/src/components/ui/panel/PanelDrillIn.vue
new file mode 100644
index 000000000..67128286d
--- /dev/null
+++ b/src/components/ui/panel/PanelDrillIn.vue
@@ -0,0 +1,98 @@
+<script setup lang="ts">
+import { tv } from 'tailwind-variants'
+import { nextTick, ref, useTemplateRef, watch } from 'vue'
+
+import AppButton from '@/components/ui/button/AppButton.vue'
+import type { ComponentUI } from '@/components/ui/types'
+import { drillInTransition } from '@/theme/motion/styles'
+import drillInTheme from '@/theme/panel/drill-in'
+
+/**
+ * A list with a detail view that slides in over it. The back control names the view it returns
+ * to, like "‹ Models"; focus moves to the detail's first field and back to what opened it.
+ */
+const { open, back, parent, ui } = defineProps<{
+ open: boolean
+ /** The accessible verb, "Back". */
+ back: string
+ /** What Back returns to, shown on the control: "Models". */
+ parent: string
+ ui?: ComponentUI<typeof drillInTheme>
+}>()
+const emit = defineEmits<{ back: [] }>()
+
+const styles = tv(drillInTheme)()
+const detail = useTemplateRef<HTMLElement>('detail')
+/**
+ * The list shows under the detail while it slides, then hides once covered. It is inert from the
+ * moment the detail opens, and a closing detail is inert while it slides away, so the two never
+ * share the tab order.
+ */
+const covered = ref(false)
+let returnFocus: HTMLElement | null = null
+
+watch(
+ () => open,
+ (isOpen) => {
+ if (isOpen && document.activeElement instanceof HTMLElement)
+ returnFocus = document.activeElement
+ }
+)
+
+const FIELD = '[data-slot="body"] :is(input:not([type="hidden"]), textarea, select):not([disabled])'
+
+/** The detail's first field, or its back control when it has none. */
+async function focusDetail() {
+ covered.value = true
+ await nextTick()
+ const target =
+ detail.value?.querySelector<HTMLElement>(FIELD) ??
+ detail.value?.querySelector<HTMLElement>('[data-slot="back"]')
+ target?.focus({ preventScroll: true })
+}
+
+function uncover(element: Element) {
+ if (element instanceof HTMLElement) element.inert = true
+ covered.value = false
+}
+
+async function restoreFocus() {
+ await nextTick()
+ if (returnFocus?.isConnected) returnFocus.focus({ preventScroll: true })
+ returnFocus = null
+}
+</script>
+
+<template>
+ <div :class="styles.root({ class: ui?.root })">
+ <Transition
+ v-bind="drillInTransition"
+ @after-enter="focusDetail"
+ @before-leave="uncover"
+ @after-leave="restoreFocus"
+ >
+ <div
+ v-if="open"
+ ref="detail"
+ data-slot="detail"
+ :class="styles.detail({ class: ui?.detail })"
+ >
+ <div data-slot="header" :class="styles.header({ class: ui?.header })">
+ <AppButton variant="ghost" size="sm" data-slot="back" @click="emit('back')">
+ <template #leading><icon-lucide-chevron-left class="size-4" /></template>
+ <span class="sr-only">{{ back }}:</span>
+ {{ parent }}
+ </AppButton>
+ <span class="flex-1" />
+ <slot name="actions" />
+ </div>
+ <div data-slot="body" :class="styles.body({ class: ui?.body })">
+ <slot name="detail" />
+ </div>
+ </div>
+ </Transition>
+ <div v-show="!covered" :inert="open" data-slot="base" :class="styles.base({ class: ui?.base })">
+ <slot />
+ </div>
+ </div>
+</template>
diff --git a/src/components/ui/panel/index.ts b/src/components/ui/panel/index.ts
index 07e942659..29f3ab25c 100644
--- a/src/components/ui/panel/index.ts
+++ b/src/components/ui/panel/index.ts
@@ -1,3 +1,4 @@
+export { default as PanelDrillIn } from './PanelDrillIn.vue'
export { default as PanelFieldGroup } from './PanelFieldGroup.vue'
export { default as PanelGrid } from './PanelGrid.vue'
export { default as PanelHeader } from './PanelHeader.vue'
diff --git a/src/components/ui/select/AppCombobox.vue b/src/components/ui/select/AppCombobox.vue
index 59d0854ef..4fb66f335 100644
--- a/src/components/ui/select/AppCombobox.vue
+++ b/src/components/ui/select/AppCombobox.vue
@@ -1,5 +1,4 @@
<script setup lang="ts">
-import Fuse from 'fuse.js'
import {
ComboboxAnchor,
ComboboxContent,
@@ -18,7 +17,7 @@ import {
import { tv } from 'tailwind-variants'
import { computed, ref } from 'vue'
-import { useRetainedPopup } from '@open-pencil/vue'
+import { fuzzySearch, useRetainedPopup } from '@open-pencil/vue'
import type { ComponentUI } from '@/components/ui/types'
import theme from '@/theme/select/combobox'
@@ -64,21 +63,13 @@ const { portalActive } = useRetainedPopup(open, () => updateOpen(false))
const styles = tv(theme)()
const selectedOption = computed(() => options.find((option) => option.value === modelValue.value))
-const searchIndex = computed(
- () =>
- new Fuse(options, {
- keys: ['label', 'value', 'description', 'meta'],
- threshold: 0.2,
- ignoreLocation: true
- })
-)
const filteredOptions = computed(() => {
const query = searchTerm.value.trim()
if (!query) return options.slice(0, resultLimit)
- return searchIndex.value
- .search(query)
- .slice(0, resultLimit)
- .map((result) => result.item)
+ return fuzzySearch(options, ['label', 'value', 'description', 'meta'], query).slice(
+ 0,
+ resultLimit
+ )
})
const groupedOptions = computed(() => {
const groups = new Map<string, AppComboboxOption[]>()
diff --git a/src/components/ui/select/AppPicker.vue b/src/components/ui/select/AppPicker.vue
index 29fec26ba..758362296 100644
--- a/src/components/ui/select/AppPicker.vue
+++ b/src/components/ui/select/AppPicker.vue
@@ -41,7 +41,6 @@ export interface AppPickerSlots {
</script>
<script setup lang="ts">
-import Fuse from 'fuse.js'
import {
ListboxContent,
ListboxFilter,
@@ -59,7 +58,7 @@ import {
import { tv } from 'tailwind-variants'
import { computed, ref, watch } from 'vue'
-import { useRetainedPopup } from '@open-pencil/vue'
+import { fuzzySearch, useRetainedPopup } from '@open-pencil/vue'
import AppButton from '@/components/ui/button/AppButton.vue'
import Tip from '@/components/ui/overlay/Tip.vue'
@@ -89,17 +88,9 @@ watch(open, (isOpen) => {
})
const styles = computed(() => tv(theme)({ density }))
-const index = computed(
- () =>
- new Fuse(items, {
- keys: ['label', 'description', 'group'],
- threshold: 0.2,
- ignoreLocation: true
- })
-)
const matches = computed(() => {
const term = query.value.trim()
- return term ? index.value.search(term).map((result) => result.item) : items
+ return term ? fuzzySearch(items, ['label', 'description', 'group'], term) : items
})
const groups = computed(() => {
const byGroup = new Map<string, AppPickerItem[]>()
diff --git a/src/components/variables/CollectionInspector.vue b/src/components/variables/CollectionInspector.vue
new file mode 100644
index 000000000..b6d137373
--- /dev/null
+++ b/src/components/variables/CollectionInspector.vue
@@ -0,0 +1,299 @@
+<script setup lang="ts">
+import {
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger
+} from 'reka-ui'
+import { tv } from 'tailwind-variants'
+import { computed, reactive, watch } from 'vue'
+
+import type { VariableCollection } from '@open-pencil/scene-graph'
+import { useI18n } from '@open-pencil/vue'
+
+import {
+ changeConditionKind,
+ isAutomaticCondition,
+ modeConditionCSS,
+ parseModeCondition,
+ type ConditionKind,
+ type ModeCondition
+} from '@/app/editor/tokens/conditions'
+import { modeAttributeText, modeConditionPlaceholder } from '@/app/editor/tokens/model'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import AppBadge from '@/components/ui/feedback/AppBadge.vue'
+import AppInput from '@/components/ui/input/AppInput.vue'
+import { useMenuUI } from '@/components/ui/menu/menu'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
+import { useConditionLabels } from '@/components/variables/useConditionLabels'
+import tokensPanelTheme from '@/theme/tokens-panel'
+
+const { collection, layout = 'side' } = defineProps<{
+ collection: VariableCollection
+ /** `full` fills the panel behind a back button on narrow screens. */
+ layout?: 'side' | 'full'
+}>()
+const emit = defineEmits<{
+ done: []
+ rename: [name: string]
+ remove: []
+ addMode: []
+ renameMode: [modeId: string, name: string]
+ duplicateMode: [modeId: string]
+ setDefaultMode: [modeId: string]
+ removeMode: [modeId: string]
+ setCondition: [modeId: string, condition: string]
+}>()
+
+const { variables } = useI18n()
+const { kindOptions } = useConditionLabels()
+const ui = computed(() => tv(tokensPanelTheme)({ layout }))
+const menu = useMenuUI({ content: 'w-44', item: 'justify-start gap-2' })
+const dangerItem = useMenuUI({ item: 'justify-start gap-2 text-error' }).item
+
+/** Text fields edit a draft and commit on change, like the token fields. */
+const draft = reactive({
+ name: '',
+ modeNames: {} as Record<string, string>,
+ custom: {} as Record<string, string>,
+ widths: {} as Record<string, string>
+})
+/**
+ * Drafts reset when the stored names or conditions change, not whenever the collection is
+ * re-read, so a selection change does not discard what is being typed.
+ */
+watch(
+ () =>
+ JSON.stringify([
+ collection.name,
+ collection.modes.map((mode) => [mode.modeId, mode.name, mode.condition ?? ''])
+ ]),
+ () => {
+ draft.name = collection.name
+ for (const mode of collection.modes) {
+ const condition = parseModeCondition(mode.condition)
+ draft.modeNames[mode.modeId] = mode.name
+ draft.custom[mode.modeId] = mode.condition ?? ''
+ draft.widths[mode.modeId] = 'width' in condition ? String(condition.width) : ''
+ }
+ },
+ { immediate: true }
+)
+
+function commitName() {
+ const name = draft.name.trim()
+ if (name && name !== collection.name) emit('rename', name)
+ else draft.name = collection.name
+}
+
+function mode(modeId: string) {
+ return collection.modes.find((candidate) => candidate.modeId === modeId)
+}
+
+function commitModeName(modeId: string) {
+ const name = (draft.modeNames[modeId] ?? '').trim()
+ const current = mode(modeId)?.name ?? ''
+ if (name && name !== current) emit('renameMode', modeId, name)
+ else draft.modeNames[modeId] = current
+}
+
+function condition(modeId: string): ModeCondition {
+ return parseModeCondition(mode(modeId)?.condition)
+}
+
+function save(modeId: string, next: ModeCondition) {
+ const css = modeConditionCSS(next) ?? ''
+ if (css !== (mode(modeId)?.condition ?? '')) emit('setCondition', modeId, css)
+}
+
+/** Custom CSS starts from what the mode writes now, the attribute selector when manual. */
+function setKind(modeId: string, kind: ConditionKind) {
+ const next = changeConditionKind(condition(modeId), kind)
+ if (next.kind === 'custom' && !next.css)
+ save(modeId, { kind: 'custom', css: modeConditionPlaceholder(collection, modeId) ?? '' })
+ else save(modeId, next)
+}
+
+function commitWidth(modeId: string) {
+ const current = condition(modeId)
+ const width = Number(draft.widths[modeId])
+ if ('width' in current && Number.isFinite(width) && width > 0) save(modeId, { ...current, width })
+ else draft.widths[modeId] = 'width' in current ? String(current.width) : ''
+}
+
+function commitCustom(modeId: string) {
+ save(modeId, { kind: 'custom', css: draft.custom[modeId] ?? '' })
+}
+
+/** The CSS a mode is written under, for developers, under the words designers pick. */
+function writtenAs(modeId: string): string {
+ return modeConditionCSS(condition(modeId)) ?? modeConditionPlaceholder(collection, modeId) ?? ''
+}
+
+/** What a designer needs to know about where the mode applies on the canvas and in code. */
+function hint(modeId: string): string {
+ const current = condition(modeId)
+ if (current.kind === 'manual')
+ return variables.value.conditionManualHint({
+ attribute: modeAttributeText(collection, modeId)
+ })
+ if (isAutomaticCondition(current)) return variables.value.conditionAutomaticHint
+ return variables.value.conditionHint
+}
+
+/** Enter commits the field and hands the keyboard back to the list, so undo reaches the document. */
+function done(event: KeyboardEvent) {
+ if (event.target instanceof HTMLElement) event.target.blur()
+ emit('done')
+}
+</script>
+
+<template>
+ <aside :class="ui.inspector()" data-test-id="collection-inspector">
+ <section :class="ui.section()">
+ <span :class="ui.label()">{{ variables.collection }}</span>
+ <div class="flex items-center gap-1">
+ <AppInput
+ v-model="draft.name"
+ size="sm"
+ class="min-w-0 flex-1"
+ :aria-label="variables.collection"
+ data-test-id="variables-collection-name"
+ @change="commitName"
+ @enter="done"
+ />
+ <DropdownMenuRoot>
+ <DropdownMenuTrigger as-child>
+ <IconButton
+ :label="variables.collectionActions"
+ data-test-id="variables-collection-menu"
+ >
+ <icon-lucide-ellipsis class="size-3.5" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent side="bottom" :side-offset="4" align="end" :class="menu.content">
+ <DropdownMenuItem
+ :class="dangerItem"
+ data-test-id="variables-delete-collection"
+ @select="emit('remove')"
+ >
+ <icon-lucide-trash-2 :class="menu.icon" />
+ {{ variables.deleteCollection }}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ </div>
+ </section>
+
+ <section :class="ui.section()">
+ <div class="flex items-center justify-between">
+ <h3 :class="ui.sectionTitle()">{{ variables.modes }}</h3>
+ <IconButton
+ :label="variables.addMode"
+ data-test-id="variables-add-mode"
+ @click="emit('addMode')"
+ >
+ <icon-lucide-plus class="size-3.5" />
+ </IconButton>
+ </div>
+ <div
+ v-for="item in collection.modes"
+ :key="item.modeId"
+ :class="ui.mode()"
+ data-test-id="variables-mode"
+ >
+ <div class="flex items-center gap-1">
+ <AppInput
+ v-model="draft.modeNames[item.modeId]"
+ size="sm"
+ class="min-w-0 flex-1"
+ :aria-label="variables.renameMode"
+ @change="commitModeName(item.modeId)"
+ @enter="done"
+ />
+ <AppBadge v-if="item.modeId === collection.defaultModeId">
+ {{ variables.defaultMode }}
+ </AppBadge>
+ <DropdownMenuRoot>
+ <DropdownMenuTrigger as-child>
+ <IconButton :label="variables.modeActions({ mode: item.name })">
+ <icon-lucide-ellipsis class="size-3.5" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent side="bottom" :side-offset="4" align="end" :class="menu.content">
+ <DropdownMenuItem :class="menu.item" @select="emit('duplicateMode', item.modeId)">
+ <icon-lucide-copy :class="menu.icon" />
+ {{ variables.duplicateMode }}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ v-if="item.modeId !== collection.defaultModeId"
+ :class="menu.item"
+ @select="emit('setDefaultMode', item.modeId)"
+ >
+ <icon-lucide-pin :class="menu.icon" />
+ {{ variables.setDefaultMode }}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator :class="menu.separator" />
+ <DropdownMenuItem
+ :class="dangerItem"
+ :disabled="collection.modes.length <= 1"
+ @select="emit('removeMode', item.modeId)"
+ >
+ <icon-lucide-trash-2 :class="menu.icon" />
+ {{ variables.deleteMode }}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ </div>
+
+ <template v-if="item.modeId === collection.defaultModeId">
+ <span :class="ui.label()">{{ variables.alwaysOn }}</span>
+ <code :class="ui.modeCSS()">:root</code>
+ </template>
+ <template v-else>
+ <span :class="ui.label()">{{ variables.appliesWhen }}</span>
+ <AppSelect
+ :model-value="condition(item.modeId).kind"
+ :options="kindOptions"
+ :label="`${item.name}: ${variables.appliesWhen}`"
+ :ui="{ trigger: 'w-full' }"
+ data-test-id="variables-mode-condition"
+ @update:model-value="setKind(item.modeId, $event)"
+ />
+ <AppInput
+ v-if="'width' in condition(item.modeId)"
+ v-model="draft.widths[item.modeId]"
+ type="number"
+ size="sm"
+ :aria-label="`${item.name}: ${variables.conditionWidth}`"
+ data-test-id="variables-mode-width"
+ @change="commitWidth(item.modeId)"
+ @enter="done"
+ >
+ <template #trailing><span :class="ui.hint()">px</span></template>
+ </AppInput>
+ <AppInput
+ v-if="condition(item.modeId).kind === 'custom'"
+ v-model="draft.custom[item.modeId]"
+ size="sm"
+ :aria-label="`${item.name}: ${variables.condition}`"
+ :placeholder="modeConditionPlaceholder(collection, item.modeId)"
+ :ui="{ input: 'font-mono' }"
+ @change="commitCustom(item.modeId)"
+ @enter="done"
+ />
+ <code v-else :class="ui.modeCSS()" data-test-id="variables-mode-css">{{
+ writtenAs(item.modeId)
+ }}</code>
+ <span :class="ui.hint()">{{ hint(item.modeId) }}</span>
+ </template>
+ </div>
+ </section>
+ </aside>
+</template>
diff --git a/src/components/variables/TokenAddMenu.vue b/src/components/variables/TokenAddMenu.vue
new file mode 100644
index 000000000..ffdb2756d
--- /dev/null
+++ b/src/components/variables/TokenAddMenu.vue
@@ -0,0 +1,72 @@
+<script setup lang="ts">
+import {
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuTrigger
+} from 'reka-ui'
+import { computed } from 'vue'
+
+import type { VariableType } from '@open-pencil/scene-graph'
+import { useI18n, variablesAddTestId, vTestId } from '@open-pencil/vue'
+
+import AppButton from '@/components/ui/button/AppButton.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import { useMenuUI } from '@/components/ui/menu/menu'
+import { VARIABLE_TYPE_ICONS, VARIABLE_TYPES } from '@/components/variables/type-icons'
+
+/** `labelled` spells out "Create variable" where the toolbar has room for it. */
+const { labelled = false } = defineProps<{ labelled?: boolean }>()
+const emit = defineEmits<{ add: [type: VariableType] }>()
+
+const { panels, variableTypes: text } = useI18n()
+const menu = useMenuUI({ content: 'w-48', item: 'justify-start gap-2' })
+
+const items = computed(() => {
+ const labels: Record<VariableType, { label: string; hint: string }> = {
+ COLOR: { label: text.value.color, hint: text.value.colorHint },
+ FLOAT: { label: text.value.number, hint: text.value.numberHint },
+ STRING: { label: text.value.text, hint: text.value.textHint },
+ BOOLEAN: { label: text.value.boolean, hint: text.value.booleanHint }
+ }
+ return VARIABLE_TYPES.map((type) => ({ type, icon: VARIABLE_TYPE_ICONS[type], ...labels[type] }))
+})
+</script>
+
+<template>
+ <DropdownMenuRoot>
+ <!-- Reka anchors the menu to the element it mounted with, so a new button needs a new trigger. -->
+ <DropdownMenuTrigger :key="String(labelled)" as-child>
+ <AppButton v-if="labelled" variant="soft" size="sm" data-test-id="variables-add-variable">
+ <template #leading><icon-lucide-plus class="size-3.5" /></template>
+ {{ panels.createVariable }}
+ </AppButton>
+ <IconButton
+ v-else
+ size="sm"
+ :label="panels.createVariable"
+ data-test-id="variables-add-variable"
+ >
+ <icon-lucide-plus class="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent side="bottom" :side-offset="4" align="end" :class="menu.content">
+ <DropdownMenuItem
+ v-for="item in items"
+ :key="item.type"
+ :class="menu.item"
+ v-test-id="variablesAddTestId(item.type)"
+ @select="emit('add', item.type)"
+ >
+ <component :is="item.icon" :class="menu.icon" />
+ <span class="flex min-w-0 flex-1 flex-col">
+ <span>{{ item.label }}</span>
+ <span class="truncate text-[10px] text-muted">{{ item.hint }}</span>
+ </span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+</template>
diff --git a/src/components/variables/TokenAliasPicker.vue b/src/components/variables/TokenAliasPicker.vue
new file mode 100644
index 000000000..d0cae515c
--- /dev/null
+++ b/src/components/variables/TokenAliasPicker.vue
@@ -0,0 +1,68 @@
+<script setup lang="ts">
+import { computed, ref } from 'vue'
+
+import { useI18n } from '@open-pencil/vue'
+
+import type { AliasCandidate } from '@/app/editor/tokens/model'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import FillSwatch from '@/components/ui/paint/FillSwatch.vue'
+import AppPicker, { type AppPickerItem } from '@/components/ui/select/AppPicker.vue'
+
+/** Points a mode's value at another variable, the way Figma's variable picker does. */
+const { candidates, selected, label } = defineProps<{
+ candidates: AliasCandidate[]
+ /** The variable the value points at now, checked in the list. */
+ selected?: string
+ /** The trigger's accessible name, naming the mode it sets. */
+ label: string
+}>()
+const emit = defineEmits<{ select: [variableId: string] }>()
+
+const { variables, common } = useI18n()
+const open = ref(false)
+
+const items = computed<AppPickerItem[]>(() =>
+ candidates.map((candidate) => ({
+ value: candidate.id,
+ label: candidate.name,
+ group: candidate.collection
+ }))
+)
+
+function color(id: string) {
+ return candidates.find((candidate) => candidate.id === id)?.color
+}
+</script>
+
+<template>
+ <AppPicker
+ v-model:open="open"
+ :heading="variables.useVariable"
+ :items="items"
+ :selected="selected"
+ :search-placeholder="variables.searchVariables"
+ :empty-label="variables.noMatchingVariables"
+ :close-label="common.close"
+ density="compact"
+ side="left"
+ @select="emit('select', $event)"
+ >
+ <template #trigger>
+ <IconButton :label="label" data-test-id="variables-use-variable">
+ <icon-lucide-variable class="size-3.5" />
+ </IconButton>
+ </template>
+ <template #leading="{ item }">
+ <FillSwatch
+ v-if="color(item.value)"
+ :fill="{
+ type: 'SOLID',
+ visible: true,
+ opacity: color(item.value)?.a ?? 1,
+ color: color(item.value) ?? { r: 0, g: 0, b: 0, a: 1 }
+ }"
+ :ui="{ root: 'size-3.5 shrink-0 rounded-sm' }"
+ />
+ </template>
+ </AppPicker>
+</template>
diff --git a/src/components/variables/TokenBulkInspector.vue b/src/components/variables/TokenBulkInspector.vue
new file mode 100644
index 000000000..017cebeb9
--- /dev/null
+++ b/src/components/variables/TokenBulkInspector.vue
@@ -0,0 +1,90 @@
+<script setup lang="ts">
+import { tv } from 'tailwind-variants'
+import { computed, onMounted, ref, useTemplateRef, type ComponentPublicInstance } from 'vue'
+
+import { useI18n } from '@open-pencil/vue'
+
+import AppButton from '@/components/ui/button/AppButton.vue'
+import AppInput from '@/components/ui/input/AppInput.vue'
+import tokensPanelTheme from '@/theme/tokens-panel'
+
+/** Actions for several selected tokens, and naming a new group for the selection. */
+const {
+ count,
+ focusGroup = false,
+ layout = 'side'
+} = defineProps<{
+ count: number
+ /** Opened from "New group…", so the group name takes focus. */
+ focusGroup?: boolean
+ /** `full` fills the panel behind a back button on narrow screens. */
+ layout?: 'side' | 'full'
+}>()
+const emit = defineEmits<{ moveToGroup: [group: string]; duplicate: []; remove: [] }>()
+
+const { variables } = useI18n()
+const ui = computed(() => tv(tokensPanelTheme)({ layout }))
+const group = ref('')
+const groupInput = useTemplateRef<ComponentPublicInstance>('groupInput')
+
+onMounted(() => {
+ if (!focusGroup) return
+ const element = groupInput.value?.$el
+ const input = element instanceof HTMLElement ? element.querySelector('input') : null
+ input?.focus()
+})
+
+/** Slashes nest groups, as in token names; empty segments are dropped. */
+function move() {
+ const path = group.value
+ .split('/')
+ .map((segment) => segment.trim())
+ .filter((segment) => segment !== '')
+ .join('/')
+ if (path) emit('moveToGroup', path)
+}
+</script>
+
+<template>
+ <aside :class="ui.inspector()" data-test-id="token-bulk-inspector">
+ <section :class="ui.section()">
+ <h3 :class="ui.sectionTitle()">{{ variables.selectedCount({ count }) }}</h3>
+ </section>
+ <section :class="ui.section()">
+ <label :class="ui.field()">
+ <span :class="ui.label()">{{ variables.moveToGroup }}</span>
+ <div class="flex items-center gap-1">
+ <AppInput
+ ref="groupInput"
+ v-model="group"
+ size="sm"
+ class="min-w-0 flex-1"
+ :placeholder="variables.groupName"
+ data-test-id="variables-group-name"
+ @keydown.enter="move"
+ />
+ <AppButton variant="soft" size="sm" :disabled="!group.trim()" @click="move">
+ {{ variables.move }}
+ </AppButton>
+ </div>
+ </label>
+ </section>
+ <section :class="ui.section()">
+ <AppButton variant="ghost" size="sm" class="self-start" @click="emit('duplicate')">
+ <template #leading><icon-lucide-copy class="size-3.5" /></template>
+ {{ variables.duplicate }}
+ </AppButton>
+ <AppButton
+ variant="ghost"
+ color="error"
+ size="sm"
+ class="self-start"
+ data-test-id="variables-delete-selected"
+ @click="emit('remove')"
+ >
+ <template #leading><icon-lucide-trash-2 class="size-3.5" /></template>
+ {{ variables.deleteVariables }}
+ </AppButton>
+ </section>
+ </aside>
+</template>
diff --git a/src/components/variables/TokenCellInput.vue b/src/components/variables/TokenCellInput.vue
new file mode 100644
index 000000000..6f8008895
--- /dev/null
+++ b/src/components/variables/TokenCellInput.vue
@@ -0,0 +1,51 @@
+<script setup lang="ts">
+import { tv } from 'tailwind-variants'
+import { onMounted, ref, useTemplateRef } from 'vue'
+
+import tokensPanelTheme from '@/theme/tokens-panel'
+
+/**
+ * Edits one cell of the token list in place. Enter or leaving the field commits, Escape cancels,
+ * and keys stay in the field instead of moving the list's highlight.
+ */
+const { value, label } = defineProps<{ value: string; label: string }>()
+const emit = defineEmits<{ commit: [text: string]; cancel: [] }>()
+
+const ui = tv(tokensPanelTheme)()
+const draft = ref(value)
+const input = useTemplateRef('input')
+let done = false
+
+onMounted(() => {
+ input.value?.focus()
+ input.value?.select()
+})
+
+function finish(commit: boolean) {
+ if (done) return
+ done = true
+ if (commit) emit('commit', draft.value)
+ else emit('cancel')
+}
+
+function onKeydown(event: KeyboardEvent) {
+ event.stopPropagation()
+ if (event.code === 'Enter' || event.code === 'NumpadEnter') finish(true)
+ else if (event.code === 'Escape') finish(false)
+}
+</script>
+
+<template>
+ <input
+ ref="input"
+ v-model="draft"
+ :aria-label="label"
+ :class="ui.cellInput()"
+ data-test-id="variables-cell-input"
+ @keydown="onKeydown"
+ @click.stop
+ @dblclick.stop
+ @pointerdown.stop
+ @blur="finish(true)"
+ />
+</template>
diff --git a/src/components/variables/TokenInspector.vue b/src/components/variables/TokenInspector.vue
new file mode 100644
index 000000000..d1335f575
--- /dev/null
+++ b/src/components/variables/TokenInspector.vue
@@ -0,0 +1,412 @@
+<script setup lang="ts">
+import { computedAsync } from '@vueuse/core'
+import { omit } from 'es-toolkit'
+import { tv } from 'tailwind-variants'
+import { computed, reactive, useId, watch } from 'vue'
+
+import type { VariableTokenFields } from '@open-pencil/core/editor'
+import {
+ cssNameCodeSyntax,
+ explicitCSSName,
+ loadTokenValidator,
+ parseCSSName,
+ variableUnit
+} from '@open-pencil/dom-css/export'
+import {
+ TOKEN_UNITS,
+ tokenNumberFromUnit,
+ tokenNumberInUnit,
+ type Color,
+ type TokenExpression,
+ type Variable,
+ type VariableCollection,
+ type VariableScope,
+ type VariableValue
+} from '@open-pencil/scene-graph'
+import { randomHex } from '@open-pencil/scene-graph/random'
+import { useI18n } from '@open-pencil/vue'
+
+import type { AliasCandidate, TokenRow } from '@/app/editor/tokens/model'
+import { SCOPES_BY_TYPE } from '@/app/editor/tokens/scopes'
+import ColorInput from '@/components/ColorPicker/ColorInput.vue'
+import BindingPill from '@/components/ui/binding/BindingPill.vue'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import AppInput from '@/components/ui/input/AppInput.vue'
+import AppTextarea from '@/components/ui/input/AppTextarea.vue'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
+import AppCheckbox from '@/components/ui/toggle/AppCheckbox.vue'
+import TokenAliasPicker from '@/components/variables/TokenAliasPicker.vue'
+import tokensPanelTheme from '@/theme/tokens-panel'
+
+const {
+ row,
+ collection,
+ aliasCandidates,
+ layout = 'side'
+} = defineProps<{
+ row: TokenRow
+ collection: VariableCollection
+ /** Variables of the same type a mode's value can point at. */
+ aliasCandidates: AliasCandidate[]
+ /** `full` fills the panel behind a back button on narrow screens. */
+ layout?: 'side' | 'full'
+}>()
+const emit = defineEmits<{
+ done: []
+ rename: [name: string]
+ updateToken: [patch: Partial<VariableTokenFields>]
+ updateValue: [modeId: string, value: VariableValue, coalesceKey?: string]
+ alias: [modeId: string, variableId: string]
+ detach: [modeId: string]
+ remove: []
+}>()
+
+const { variables } = useI18n()
+const ui = computed(() => tv(tokensPanelTheme)({ layout }))
+/**
+ * A copy per list refresh: the graph edits a variable in place, so the same object coming back
+ * would not tell the fields an inline rename or an undo changed it.
+ */
+const variable = computed(() => ({ ...row.variable }))
+
+const SCOPE_MESSAGES: Partial<Record<VariableScope, () => string>> = {
+ ALL_FILLS: () => variables.value.scopeAllFills,
+ FRAME_FILL: () => variables.value.scopeFrameFill,
+ SHAPE_FILL: () => variables.value.scopeShapeFill,
+ TEXT_FILL: () => variables.value.scopeTextFill,
+ STROKE: () => variables.value.scopeStroke,
+ EFFECT_COLOR: () => variables.value.scopeEffectColor,
+ CORNER_RADIUS: () => variables.value.scopeCornerRadius,
+ WIDTH_HEIGHT: () => variables.value.scopeWidthHeight,
+ GAP: () => variables.value.scopeGap,
+ STROKE_FLOAT: () => variables.value.scopeStrokeFloat,
+ OPACITY: () => variables.value.scopeOpacity,
+ EFFECT_FLOAT: () => variables.value.scopeEffectFloat,
+ FONT_STYLE: () => variables.value.scopeFontStyle,
+ FONT_SIZE: () => variables.value.scopeFontSize,
+ LINE_HEIGHT: () => variables.value.scopeLineHeight,
+ LETTER_SPACING: () => variables.value.scopeLetterSpacing,
+ PARAGRAPH_SPACING: () => variables.value.scopeParagraphSpacing,
+ PARAGRAPH_INDENT: () => variables.value.scopeParagraphIndent,
+ TEXT_CONTENT: () => variables.value.scopeTextContent,
+ FONT_FAMILY: () => variables.value.scopeFontFamily
+}
+
+const scopes = computed(() => SCOPES_BY_TYPE[variable.value.type])
+
+/** Numbers are edited in the token's unit, `1.5` for a 24px `rem` token, and stored as pixels. */
+const numberUnit = computed(() => variableUnit(variable.value))
+
+function displayValue(value: VariableValue | undefined): string {
+ if (typeof value === 'number')
+ return String(Number(tokenNumberInUnit(value, numberUnit.value).toFixed(6)))
+ return typeof value === 'object' ? '' : String(value ?? '')
+}
+
+const unitOptions = computed(() => [
+ { value: 'auto', label: variables.value.unitAuto },
+ ...TOKEN_UNITS.map((unit) => ({ value: unit, label: unit }))
+])
+
+const unit = computed({
+ get: () => variable.value.unit ?? 'auto',
+ set: (value: string) =>
+ emit('updateToken', { unit: TOKEN_UNITS.find((candidate) => candidate === value) })
+})
+
+/** Text fields edit a draft and commit on change, so typing makes one undo step, not many. */
+const draft = reactive({
+ name: '',
+ cssName: '',
+ description: '',
+ values: {} as Record<string, string>,
+ expressions: {} as Record<string, string>
+})
+
+function resetDraft(current: Variable) {
+ draft.name = current.name
+ draft.cssName = explicitCSSName(current) ?? ''
+ draft.description = current.description
+ for (const mode of collection.modes) {
+ draft.values[mode.modeId] = displayValue(current.valuesByMode[mode.modeId])
+ draft.expressions[mode.modeId] = current.expressions?.[mode.modeId]?.css ?? ''
+ }
+}
+/**
+ * Drafts reset when the token's stored fields change, by edit or undo, not whenever the list is
+ * re-read, so a scene change does not discard what is being typed.
+ */
+watch(
+ () => {
+ const { id, name, description, valuesByMode, expressions } = variable.value
+ return JSON.stringify([
+ id,
+ name,
+ explicitCSSName(variable.value),
+ description,
+ valuesByMode,
+ expressions
+ ])
+ },
+ () => resetDraft(variable.value),
+ { immediate: true }
+)
+
+function commitName() {
+ const name = draft.name.trim()
+ if (name && name !== variable.value.name) emit('rename', name)
+ else draft.name = variable.value.name
+}
+
+/** The browser's CSS parser decides what a custom property name may be. */
+const validator = computedAsync(loadTokenValidator, null)
+const cssNameErrorId = `${useId()}-css-name`
+/** The name typed, without the `--` the field shows, also when `--name` or `var(--name)` is pasted. */
+const typedCSSName = computed(() => {
+ const text = draft.cssName.trim()
+ return parseCSSName(text) ?? text
+})
+const cssNameInvalid = computed(() => {
+ const name = typedCSSName.value
+ return name !== '' && validator.value !== null && !validator.value.name(name)
+})
+
+function commitCSSName() {
+ const name = typedCSSName.value
+ draft.cssName = name
+ if (cssNameInvalid.value || name === (explicitCSSName(variable.value) ?? '')) return
+ emit('updateToken', {
+ codeSyntax: { ...variable.value.codeSyntax, WEB: name ? cssNameCodeSyntax(name) : undefined }
+ })
+}
+
+function commitDescription() {
+ if (draft.description !== variable.value.description)
+ emit('updateToken', { description: draft.description })
+}
+
+function commitValue(modeId: string) {
+ const text = draft.values[modeId] ?? ''
+ if (variable.value.type === 'FLOAT') {
+ const number = Number(text)
+ if (text.trim() && Number.isFinite(number))
+ emit('updateValue', modeId, tokenNumberFromUnit(number, numberUnit.value))
+ else resetDraft(variable.value)
+ return
+ }
+ emit('updateValue', modeId, text)
+}
+
+/** An expression replaces a number in CSS; the stored number stays what the canvas draws. */
+function commitExpression(modeId: string) {
+ const css = (draft.expressions[modeId] ?? '').trim()
+ const resolved = variable.value.valuesByMode[modeId]
+ const others = omit(variable.value.expressions ?? {}, [modeId])
+ const expressions: Record<string, TokenExpression> =
+ css && typeof resolved === 'number' ? { ...others, [modeId]: { css, resolved } } : others
+ emit('updateToken', {
+ expressions: Object.keys(expressions).length > 0 ? expressions : undefined
+ })
+}
+
+function hasScope(scope: VariableScope) {
+ return variable.value.scopes?.includes(scope) ?? false
+}
+
+function toggleScope(scope: VariableScope, on: boolean) {
+ const current = (variable.value.scopes ?? []).filter((candidate) => candidate !== 'ALL_SCOPES')
+ const next = on ? [...current, scope] : current.filter((candidate) => candidate !== scope)
+ emit('updateToken', { scopes: next.length > 0 ? next : undefined })
+}
+
+function alias(modeId: string) {
+ return row.values.find((value) => value.modeId === modeId)?.alias
+}
+
+function aliasId(modeId: string): string | undefined {
+ const value = variable.value.valuesByMode[modeId]
+ return typeof value === 'object' && 'aliasId' in value ? value.aliasId : undefined
+}
+
+/**
+ * The modes whose color picker is open, each with the key its drag shares, so one picker session
+ * is one undo step however many colors it passes through.
+ */
+const colorSessions = new Map<string, string>()
+
+function setPickerOpen(modeId: string, open: boolean) {
+ // A fresh key each time, so a session never merges into the last one, even across remounts.
+ if (open) colorSessions.set(modeId, `variable-color:${variable.value.id}:${randomHex(8)}`)
+ else colorSessions.delete(modeId)
+}
+
+function colorGesture(modeId: string): string | undefined {
+ return colorSessions.get(modeId)
+}
+
+/** With one mode the value needs no mode name above it. */
+const singleMode = computed(() => collection.modes.length === 1)
+
+function color(modeId: string): Color | undefined {
+ const value = variable.value.valuesByMode[modeId]
+ return typeof value === 'object' && 'r' in value ? value : undefined
+}
+
+/** Enter commits the field and hands the keyboard back to the list, so undo reaches the document. */
+function done(event: KeyboardEvent) {
+ if (event.target instanceof HTMLElement) event.target.blur()
+ emit('done')
+}
+
+/** A name the field refuses keeps the focus, so it can be corrected. */
+function cssNameDone(event: KeyboardEvent) {
+ if (!cssNameInvalid.value) done(event)
+}
+</script>
+
+<template>
+ <aside :class="ui.inspector()" data-test-id="token-inspector">
+ <section :class="ui.section()">
+ <label :class="ui.field()">
+ <span :class="ui.label()">{{ variables.name }}</span>
+ <AppInput v-model="draft.name" size="sm" @change="commitName" @enter="done" />
+ </label>
+ <label :class="ui.field()">
+ <span :class="ui.label()">{{ variables.cssName }}</span>
+ <AppInput
+ v-model="draft.cssName"
+ size="sm"
+ :placeholder="row.cssName"
+ :state="cssNameInvalid ? 'invalid' : 'idle'"
+ :aria-invalid="cssNameInvalid"
+ :aria-describedby="cssNameInvalid ? cssNameErrorId : undefined"
+ :ui="{ input: 'font-mono pl-7' }"
+ data-test-id="variables-css-name"
+ @change="commitCSSName"
+ @enter="cssNameDone"
+ >
+ <template #leading><span :class="ui.prefix()">--</span></template>
+ </AppInput>
+ <p v-if="cssNameInvalid" :id="cssNameErrorId" :class="ui.error()" role="alert">
+ {{ variables.cssNameInvalid }}
+ </p>
+ <span :class="ui.hint()">{{ variables.cssNameHint }}</span>
+ </label>
+ <label v-if="variable.type === 'FLOAT'" :class="ui.field()">
+ <span :class="ui.label()">{{ variables.unit }}</span>
+ <AppSelect v-model="unit" :options="unitOptions" />
+ </label>
+ </section>
+
+ <section :class="ui.section()">
+ <h3 :class="ui.sectionTitle()">{{ singleMode ? variables.value : variables.values }}</h3>
+ <div v-for="mode in collection.modes" :key="mode.modeId" :class="ui.field()">
+ <span v-if="!singleMode" :class="ui.label()">{{ mode.name }}</span>
+ <div :class="ui.valueRow()">
+ <div v-if="alias(mode.modeId)" :class="ui.valueControl()">
+ <BindingPill :label="alias(mode.modeId) ?? ''" />
+ <IconButton
+ :label="variables.detachVariable"
+ data-test-id="variables-detach-variable"
+ @click="emit('detach', mode.modeId)"
+ >
+ <icon-lucide-unlink class="size-3.5" />
+ </IconButton>
+ </div>
+ <ColorInput
+ v-else-if="color(mode.modeId)"
+ :color="color(mode.modeId) ?? { r: 0, g: 0, b: 0, a: 1 }"
+ editable
+ @update="emit('updateValue', mode.modeId, $event, colorGesture(mode.modeId))"
+ @open-change="setPickerOpen(mode.modeId, $event)"
+ />
+ <AppCheckbox
+ v-else-if="variable.type === 'BOOLEAN'"
+ :model-value="variable.valuesByMode[mode.modeId] === true"
+ :ariaLabel="mode.name"
+ @update:model-value="emit('updateValue', mode.modeId, $event)"
+ />
+ <AppInput
+ v-else
+ v-model="draft.values[mode.modeId]"
+ :type="variable.type === 'FLOAT' ? 'number' : 'text'"
+ size="sm"
+ @change="commitValue(mode.modeId)"
+ @enter="done"
+ >
+ <template v-if="variable.type === 'FLOAT' && numberUnit !== 'none'" #trailing>
+ <span :class="ui.hint()">{{ numberUnit }}</span>
+ </template>
+ </AppInput>
+ <TokenAliasPicker
+ :candidates="aliasCandidates"
+ :selected="aliasId(mode.modeId)"
+ :label="singleMode ? variables.useVariable : `${mode.name}: ${variables.useVariable}`"
+ @select="emit('alias', mode.modeId, $event)"
+ />
+ </div>
+ <AppInput
+ v-if="variable.type === 'FLOAT' && !alias(mode.modeId)"
+ v-model="draft.expressions[mode.modeId]"
+ size="sm"
+ :placeholder="variables.expression"
+ :ui="{ input: 'font-mono' }"
+ @change="commitExpression(mode.modeId)"
+ @enter="done"
+ />
+ </div>
+ <span v-if="variable.type === 'FLOAT'" :class="ui.hint()">{{
+ variables.expressionHint
+ }}</span>
+ </section>
+
+ <section v-if="scopes.length > 0" :class="ui.section()">
+ <h3 :class="ui.sectionTitle()">{{ variables.scopes }}</h3>
+ <label
+ v-for="scope in scopes"
+ :key="scope"
+ class="flex items-center gap-2 text-xs text-surface"
+ >
+ <AppCheckbox
+ :model-value="hasScope(scope)"
+ :ariaLabel="SCOPE_MESSAGES[scope]?.() ?? scope"
+ @update:model-value="toggleScope(scope, $event)"
+ />
+ {{ SCOPE_MESSAGES[scope]?.() ?? scope }}
+ </label>
+ </section>
+
+ <section :class="ui.section()">
+ <h3 :class="ui.sectionTitle()">{{ variables.description }}</h3>
+ <AppTextarea v-model="draft.description" :rows="2" @change="commitDescription" />
+ </section>
+
+ <section :class="ui.section()">
+ <label class="flex items-center gap-2 text-xs text-surface">
+ <AppCheckbox
+ :model-value="variable.hiddenFromPublishing"
+ :ariaLabel="variables.hiddenFromPublishing"
+ data-test-id="variables-hidden-from-publishing"
+ @update:model-value="emit('updateToken', { hiddenFromPublishing: $event })"
+ />
+ {{ variables.hiddenFromPublishing }}
+ </label>
+ <span :class="ui.hint()">{{ variables.hiddenFromPublishingHint }}</span>
+ </section>
+
+ <section :class="ui.section()">
+ <AppButton
+ variant="ghost"
+ color="error"
+ size="sm"
+ class="self-start"
+ data-test-id="variables-delete-variable"
+ @click="emit('remove')"
+ >
+ <template #leading><icon-lucide-trash-2 class="size-3.5" /></template>
+ {{ variables.deleteVariable }}
+ </AppButton>
+ </section>
+ </aside>
+</template>
diff --git a/src/components/variables/TokenOutput.vue b/src/components/variables/TokenOutput.vue
new file mode 100644
index 000000000..2d799296a
--- /dev/null
+++ b/src/components/variables/TokenOutput.vue
@@ -0,0 +1,94 @@
+<script setup lang="ts">
+import { computedAsync } from '@vueuse/core'
+import {
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuTrigger
+} from 'reka-ui'
+import { tv } from 'tailwind-variants'
+import { computed } from 'vue'
+
+import type { TokenStylesheetFormat } from '@open-pencil/dom-css/export'
+import { useEditor, useI18n, useSceneComputed } from '@open-pencil/vue'
+
+import CodeViewer from '@/components/code-editor/CodeViewer.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import { useMenuUI } from '@/components/ui/menu/menu'
+import tokensPanelTheme from '@/theme/tokens-panel'
+
+const { collectionId, layout = 'side' } = defineProps<{
+ collectionId: string
+ /** `full` fills the panel behind a back button on narrow screens. */
+ layout?: 'side' | 'full'
+}>()
+const emit = defineEmits<{ copy: [format: TokenStylesheetFormat] }>()
+
+const { variables } = useI18n()
+const ui = computed(() => tv(tokensPanelTheme)({ layout }))
+const menu = useMenuUI({ content: 'w-60', item: 'justify-start gap-2' })
+const editor = useEditor()
+
+/** A new list on every scene change, so the stylesheet follows edits. */
+const collectionVariables = useSceneComputed(() => [
+ ...editor.getVariablesForCollection(collectionId)
+])
+
+/**
+ * The panel previews plain CSS; Tailwind's `@theme` holds the same declarations, so the format is
+ * chosen where the stylesheet is copied rather than in a second view.
+ */
+const stylesheet = computedAsync(async () => {
+ const ids = new Set(collectionVariables.value.map((variable) => variable.id))
+ const { tokenStylesheet } = await import('@open-pencil/dom-css/export')
+ const { css } = await tokenStylesheet(editor.graph, {
+ format: 'css',
+ include: (variable) => ids.has(variable.id)
+ })
+ return css
+}, '')
+</script>
+
+<template>
+ <section :class="ui.output()" data-test-id="token-output">
+ <div class="flex items-center gap-2 px-4 py-1.5">
+ <span v-if="layout === 'side'" :class="ui.sectionTitle()">{{ variables.stylesheet }}</span>
+ <span class="flex-1" />
+ <DropdownMenuRoot>
+ <DropdownMenuTrigger as-child>
+ <IconButton :label="variables.copyStylesheet" data-test-id="variables-copy-stylesheet">
+ <icon-lucide-copy class="size-3.5" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent side="bottom" :side-offset="4" align="end" :class="menu.content">
+ <DropdownMenuItem
+ :class="menu.item"
+ data-test-id="variables-copy-css"
+ @select="emit('copy', 'css')"
+ >
+ <icon-lucide-braces :class="menu.icon" />
+ {{ variables.copyAsCSS }}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ :class="menu.item"
+ data-test-id="variables-copy-tailwind"
+ @select="emit('copy', 'tailwind')"
+ >
+ <icon-lucide-wind :class="menu.icon" />
+ {{ variables.copyAsTailwindTheme }}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ </div>
+ <CodeViewer
+ class="min-h-0 flex-1"
+ :code="stylesheet"
+ language="css"
+ :label="variables.stylesheet"
+ :fill="layout === 'full'"
+ />
+ </section>
+</template>
diff --git a/src/components/variables/TokenRowMenu.vue b/src/components/variables/TokenRowMenu.vue
new file mode 100644
index 000000000..64450c1f4
--- /dev/null
+++ b/src/components/variables/TokenRowMenu.vue
@@ -0,0 +1,103 @@
+<script setup lang="ts">
+import {
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuPortal,
+ ContextMenuRoot,
+ ContextMenuSeparator,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+ ContextMenuTrigger
+} from 'reka-ui'
+
+import { useI18n } from '@open-pencil/vue'
+
+import { useMenuUI } from '@/components/ui/menu/menu'
+
+/**
+ * Right-click actions for the selected tokens. The list selects the row under the pointer before
+ * the menu opens, so every action applies to what is highlighted.
+ */
+const { groups, single } = defineProps<{
+ /** Groups the tokens can move into, as their paths. */
+ groups: string[]
+ /** One token is selected, so it can be renamed in place. */
+ single: boolean
+}>()
+const emit = defineEmits<{
+ rename: []
+ duplicate: []
+ moveToGroup: [group: string]
+ newGroup: []
+ remove: []
+}>()
+
+const { variables, pages } = useI18n()
+const menu = useMenuUI({ content: 'w-52', item: 'justify-start gap-2' })
+const dangerItem = useMenuUI({ item: 'justify-start gap-2 text-error' }).item
+</script>
+
+<template>
+ <ContextMenuRoot>
+ <ContextMenuTrigger as-child>
+ <slot />
+ </ContextMenuTrigger>
+ <ContextMenuPortal>
+ <ContextMenuContent :class="menu.content" data-test-id="variables-row-menu">
+ <ContextMenuItem v-if="single" :class="menu.item" @select="emit('rename')">
+ <icon-lucide-pencil :class="menu.icon" />
+ {{ pages.rename }}
+ </ContextMenuItem>
+ <ContextMenuItem
+ :class="menu.item"
+ data-test-id="variables-duplicate"
+ @select="emit('duplicate')"
+ >
+ <icon-lucide-copy :class="menu.icon" />
+ {{ variables.duplicate }}
+ </ContextMenuItem>
+ <ContextMenuSub>
+ <ContextMenuSubTrigger :class="menu.subTrigger" data-test-id="variables-move-to-group">
+ <icon-lucide-folder-input :class="menu.icon" />
+ <span class="flex-1">{{ variables.moveToGroup }}</span>
+ <icon-lucide-chevron-right :class="menu.icon" />
+ </ContextMenuSubTrigger>
+ <ContextMenuPortal>
+ <ContextMenuSubContent :class="menu.content">
+ <ContextMenuItem :class="menu.item" @select="emit('moveToGroup', '')">
+ {{ variables.noGroup }}
+ </ContextMenuItem>
+ <ContextMenuItem
+ v-for="group in groups"
+ :key="group"
+ :class="menu.item"
+ @select="emit('moveToGroup', group)"
+ >
+ {{ group }}
+ </ContextMenuItem>
+ <ContextMenuSeparator :class="menu.separator" />
+ <ContextMenuItem
+ :class="menu.item"
+ data-test-id="variables-new-group"
+ @select="emit('newGroup')"
+ >
+ <icon-lucide-folder-plus :class="menu.icon" />
+ {{ variables.newGroup }}
+ </ContextMenuItem>
+ </ContextMenuSubContent>
+ </ContextMenuPortal>
+ </ContextMenuSub>
+ <ContextMenuSeparator :class="menu.separator" />
+ <ContextMenuItem
+ :class="dangerItem"
+ data-test-id="variables-delete-selected"
+ @select="emit('remove')"
+ >
+ <icon-lucide-trash-2 :class="menu.icon" />
+ {{ variables.deleteVariables }}
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenuPortal>
+ </ContextMenuRoot>
+</template>
diff --git a/src/components/variables/TokenSidebar.vue b/src/components/variables/TokenSidebar.vue
new file mode 100644
index 000000000..44e4cd4d5
--- /dev/null
+++ b/src/components/variables/TokenSidebar.vue
@@ -0,0 +1,85 @@
+<script setup lang="ts">
+import { tv } from 'tailwind-variants'
+
+import { useI18n } from '@open-pencil/vue'
+
+import type { GroupEntry } from '@/app/editor/tokens/model'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import tokensPanelTheme from '@/theme/tokens-panel'
+
+/**
+ * Collections and the groups inside the active one, each with how many tokens it holds. Picking
+ * a group narrows the list to it and the groups inside it.
+ */
+const { collections, groups, total } = defineProps<{
+ collections: Array<{ id: string; name: string; count: number }>
+ groups: GroupEntry[]
+ /** Tokens in the active collection, shown beside "All". */
+ total: number
+}>()
+const activeCollectionId = defineModel<string>('collectionId', { required: true })
+/** The group the list is narrowed to, or null for every token in the collection. */
+const activeGroup = defineModel<string | null>('group', { default: null })
+const emit = defineEmits<{ addCollection: [] }>()
+
+const { variables } = useI18n()
+const ui = tv(tokensPanelTheme)()
+</script>
+
+<template>
+ <nav :class="ui.sidebar()" :aria-label="variables.collections" data-test-id="tokens-sidebar">
+ <section :class="ui.sidebarSection()">
+ <div :class="ui.sidebarHeading()">
+ <h3 :class="ui.sectionTitle()">{{ variables.collections }}</h3>
+ <IconButton
+ :label="variables.createCollection"
+ data-test-id="variables-add-collection"
+ @click="emit('addCollection')"
+ >
+ <icon-lucide-plus class="size-3.5" />
+ </IconButton>
+ </div>
+ <button
+ v-for="item in collections"
+ :key="item.id"
+ type="button"
+ :class="ui.sidebarItem()"
+ :data-active="item.id === activeCollectionId || undefined"
+ :aria-current="item.id === activeCollectionId ? 'true' : undefined"
+ data-test-id="variables-collection-tab"
+ @click="activeCollectionId = item.id"
+ >
+ <span class="truncate">{{ item.name }}</span>
+ <span :class="ui.sidebarCount()">{{ item.count }}</span>
+ </button>
+ </section>
+
+ <section v-if="groups.length > 0" :class="ui.sidebarSection()">
+ <h3 :class="[ui.sectionTitle(), ui.sidebarHeading()]">{{ variables.groups }}</h3>
+ <button
+ type="button"
+ :class="ui.sidebarItem()"
+ :data-active="activeGroup === null || undefined"
+ :aria-current="activeGroup === null ? 'true' : undefined"
+ @click="activeGroup = null"
+ >
+ <span class="truncate">{{ variables.allVariables }}</span>
+ <span :class="ui.sidebarCount()">{{ total }}</span>
+ </button>
+ <button
+ v-for="group in groups"
+ :key="group.path"
+ type="button"
+ :class="ui.sidebarItem()"
+ :style="{ '--depth': group.depth }"
+ :data-active="activeGroup === group.path || undefined"
+ :aria-current="activeGroup === group.path ? 'true' : undefined"
+ data-test-id="variables-group"
+ @click="activeGroup = group.path"
+ >
+ <span :class="ui.sidebarGroupLabel()">{{ group.label }}</span>
+ <span :class="ui.sidebarCount()">{{ group.count }}</span>
+ </button>
+ </section>
+ </nav>
+</template>
diff --git a/src/components/variables/TokenTable.vue b/src/components/variables/TokenTable.vue
new file mode 100644
index 000000000..49134fa4e
--- /dev/null
+++ b/src/components/variables/TokenTable.vue
@@ -0,0 +1,279 @@
+<script setup lang="ts">
+import { ListboxContent, ListboxGroup, ListboxGroupLabel, ListboxItem, ListboxRoot } from 'reka-ui'
+import { tv } from 'tailwind-variants'
+import { computed, ref, useTemplateRef, type ComponentPublicInstance } from 'vue'
+
+import type { VariableCollection, VariableValue } from '@open-pencil/scene-graph'
+import { useFlatReorderDrag, useI18n } from '@open-pencil/vue'
+
+import {
+ parseTokenValueText,
+ tokenValueText,
+ type TokenGroup,
+ type TokenRow
+} from '@/app/editor/tokens/model'
+import BindingPill from '@/components/ui/binding/BindingPill.vue'
+import FillSwatch from '@/components/ui/paint/FillSwatch.vue'
+import TokenCellInput from '@/components/variables/TokenCellInput.vue'
+import TokenRowMenu from '@/components/variables/TokenRowMenu.vue'
+import { VARIABLE_TYPE_ICONS } from '@/components/variables/type-icons'
+import { useConditionLabels } from '@/components/variables/useConditionLabels'
+import tokensPanelTheme from '@/theme/tokens-panel'
+
+const { collection, groups, labels, modeIds, groupOptions } = defineProps<{
+ collection: VariableCollection
+ groups: TokenGroup[]
+ labels: { name: string; cssName: string; empty: string }
+ /** Modes to show values for; every mode by default. */
+ modeIds?: readonly string[]
+ /** Groups the "Move to group" menu offers. */
+ groupOptions: string[]
+}>()
+/** Click selects one token, Shift extends, and Cmd or Ctrl adds or removes one. */
+const selectedIds = defineModel<string[]>('selectedIds', { default: () => [] })
+const emit = defineEmits<{
+ rename: [id: string, name: string]
+ updateValue: [id: string, modeId: string, value: VariableValue]
+ duplicate: [ids: string[]]
+ moveToGroup: [ids: string[], group: string]
+ newGroup: [ids: string[]]
+ remove: [ids: string[]]
+ reorder: [sourceId: string, targetIndex: number, visibleIds: string[]]
+}>()
+
+const { variables } = useI18n()
+const ui = tv(tokensPanelTheme)()
+
+const modes = computed(() =>
+ modeIds ? collection.modes.filter((mode) => modeIds.includes(mode.modeId)) : collection.modes
+)
+
+/** The grid itself follows the panel's container width; only the mode count comes from here. */
+const columns = computed(() => ({ '--token-modes': modes.value.length }))
+
+const { summary } = useConditionLabels()
+
+/** When a mode applies, in words, under its name in the column header. */
+function condition(modeId: string) {
+ return summary(collection, modeId)
+}
+
+function modeName(modeId: string) {
+ return collection.modes.find((mode) => mode.modeId === modeId)?.name ?? ''
+}
+
+function shown<T extends { modeId: string }>(values: readonly T[]) {
+ return values.filter((value) => modes.value.some((mode) => mode.modeId === value.modeId))
+}
+
+const content = useTemplateRef<ComponentPublicInstance>('content')
+
+/**
+ * Takes the keyboard back after a field commits, so arrows, Delete and undo act on the list. The
+ * listbox root renders beside a hidden form input, so the focusable element is found from inside.
+ */
+function focus() {
+ const element = content.value?.$el
+ const listbox = element instanceof Element ? element.closest('[role="listbox"]') : null
+ if (listbox instanceof HTMLElement) listbox.focus({ preventScroll: true })
+}
+defineExpose({ focus })
+
+const rows = computed(() => groups.flatMap((group) => group.rows))
+const visibleIds = computed(() => rows.value.map((row) => row.variable.id))
+
+/** Where a Shift-click range starts: the last token clicked without Shift. */
+const anchorId = ref<string | null>(null)
+
+/**
+ * Pointer selection the way lists work elsewhere: Cmd or Ctrl adds or removes a token, Shift
+ * selects the range from the last click, and a plain click selects just one.
+ */
+function onSelect(event: CustomEvent<{ originalEvent: Event }>, id: string) {
+ const pointer = event.detail.originalEvent
+ if (!(pointer instanceof MouseEvent)) return
+ if (pointer.metaKey || pointer.ctrlKey) {
+ event.preventDefault()
+ anchorId.value = id
+ selectedIds.value = selectedIds.value.includes(id)
+ ? selectedIds.value.filter((selected) => selected !== id)
+ : [...selectedIds.value, id]
+ } else if (pointer.shiftKey && anchorId.value) {
+ event.preventDefault()
+ const from = visibleIds.value.indexOf(anchorId.value)
+ const to = visibleIds.value.indexOf(id)
+ if (from === -1 || to === -1) return
+ selectedIds.value = visibleIds.value.slice(Math.min(from, to), Math.max(from, to) + 1)
+ } else anchorId.value = id
+}
+
+/** A cell being edited in place: a token's name, or one mode's number or text value. */
+const editing = ref<{ id: string; modeId?: string } | null>(null)
+
+function isEditing(id: string, modeId?: string) {
+ return editing.value?.id === id && editing.value.modeId === modeId
+}
+
+function startRename(id: string) {
+ editing.value = { id }
+}
+
+function commitName(row: TokenRow, text: string) {
+ editing.value = null
+ const label = text.trim()
+ if (!label) return
+ const path = row.variable.name.slice(0, row.variable.name.length - row.label.length)
+ if (path + label !== row.variable.name) emit('rename', row.variable.id, path + label)
+}
+
+/** Numbers and text edit in place; colors, booleans and aliases open the inspector instead. */
+function editableValue(row: TokenRow, modeId: string) {
+ const value = row.variable.valuesByMode[modeId]
+ const aliased = typeof value === 'object' && 'aliasId' in value
+ return !aliased && (row.variable.type === 'FLOAT' || row.variable.type === 'STRING')
+}
+
+function startValueEdit(row: TokenRow, modeId: string) {
+ if (editableValue(row, modeId)) editing.value = { id: row.variable.id, modeId }
+}
+
+function commitValue(row: TokenRow, modeId: string, text: string) {
+ editing.value = null
+ const value = parseTokenValueText(row.variable, text)
+ if (value !== undefined && value !== row.variable.valuesByMode[modeId])
+ emit('updateValue', row.variable.id, modeId, value)
+}
+
+/** The row under the pointer joins the selection before its context menu opens. */
+function onContextMenu(event: MouseEvent) {
+ if (!(event.target instanceof Element)) return
+ const id = event.target.closest<HTMLElement>('[data-variable-id]')?.dataset.variableId
+ if (id && !selectedIds.value.includes(id)) selectedIds.value = [id]
+}
+
+function onKeydown(event: KeyboardEvent) {
+ if (editing.value || selectedIds.value.length === 0) return
+ if (event.code !== 'Delete' && event.code !== 'Backspace') return
+ event.preventDefault()
+ emit('remove', [...selectedIds.value])
+}
+
+const reorder = useFlatReorderDrag({
+ items: () => rows.value.map((row) => ({ id: row.variable.id })),
+ onMove: (sourceId, targetIndex) => emit('reorder', sourceId, targetIndex, visibleIds.value)
+})
+
+function dragTarget(id: string, element: Element | ComponentPublicInstance | null) {
+ const node = element instanceof Element ? element : element?.$el
+ reorder.setupItem(node instanceof HTMLElement ? node : null, () => ({ id }))
+}
+
+function dropEdge(id: string) {
+ if (reorder.instructionTargetId.value !== id) return undefined
+ return reorder.instruction.value?.operation === 'reorder-before' ? 'before' : 'after'
+}
+</script>
+
+<template>
+ <ListboxRoot
+ v-model="selectedIds"
+ multiple
+ selection-behavior="replace"
+ :class="ui.list()"
+ highlight-on-hover
+ :aria-label="collection.name"
+ data-test-id="token-list"
+ @keydown="onKeydown"
+ >
+ <div :class="ui.header()" :style="columns" aria-hidden="true">
+ <span>{{ labels.name }}</span>
+ <span :class="ui.headerCssColumn()">{{ labels.cssName }}</span>
+ <span v-for="mode in modes" :key="mode.modeId" :class="ui.modeHeader()">
+ <span class="text-surface">{{ mode.name }}</span>
+ <span
+ v-if="condition(mode.modeId)"
+ :class="ui.modeCondition()"
+ :data-code="condition(mode.modeId)?.code || undefined"
+ >
+ {{ condition(mode.modeId)?.text }}
+ </span>
+ </span>
+ </div>
+ <TokenRowMenu
+ :groups="groupOptions"
+ :single="selectedIds.length === 1"
+ @rename="selectedIds[0] && startRename(selectedIds[0])"
+ @duplicate="emit('duplicate', [...selectedIds])"
+ @move-to-group="emit('moveToGroup', [...selectedIds], $event)"
+ @new-group="emit('newGroup', [...selectedIds])"
+ @remove="emit('remove', [...selectedIds])"
+ >
+ <ListboxContent ref="content" @contextmenu.capture="onContextMenu">
+ <ListboxGroup v-for="group in groups" :key="group.path">
+ <ListboxGroupLabel v-if="group.path" :class="ui.group()">{{
+ group.path
+ }}</ListboxGroupLabel>
+ <ListboxItem
+ v-for="row in group.rows"
+ :key="row.variable.id"
+ :ref="(element) => dragTarget(row.variable.id, element)"
+ :value="row.variable.id"
+ :class="ui.row()"
+ :style="columns"
+ :data-variable-id="row.variable.id"
+ :data-drop="dropEdge(row.variable.id)"
+ :data-dragging="reorder.draggingId.value === row.variable.id || undefined"
+ data-test-id="variable-row"
+ @select="onSelect($event, row.variable.id)"
+ >
+ <span :class="ui.name()" @dblclick.stop="startRename(row.variable.id)">
+ <span :class="ui.nameLine()">
+ <component :is="VARIABLE_TYPE_ICONS[row.variable.type]" :class="ui.typeIcon()" />
+ <TokenCellInput
+ v-if="isEditing(row.variable.id)"
+ :value="row.label"
+ :label="variables.name"
+ @commit="commitName(row, $event)"
+ @cancel="editing = null"
+ />
+ <span v-else class="truncate">{{ row.label }}</span>
+ </span>
+ <span :class="ui.cssStacked()">--{{ row.cssName }}</span>
+ </span>
+ <span :class="ui.cssColumn()">--{{ row.cssName }}</span>
+ <span
+ v-for="value in shown(row.values)"
+ :key="value.modeId"
+ :class="ui.value()"
+ @dblclick.stop="startValueEdit(row, value.modeId)"
+ >
+ <TokenCellInput
+ v-if="isEditing(row.variable.id, value.modeId)"
+ :value="tokenValueText(row.variable, row.variable.valuesByMode[value.modeId])"
+ :label="modeName(value.modeId)"
+ @commit="commitValue(row, value.modeId, $event)"
+ @cancel="editing = null"
+ />
+ <template v-else>
+ <FillSwatch
+ v-if="value.color"
+ :fill="{
+ type: 'SOLID',
+ visible: true,
+ opacity: value.color.a,
+ color: value.color
+ }"
+ :ui="{ root: 'size-3.5 shrink-0 rounded-sm' }"
+ />
+ <span v-if="value.expression" :class="ui.expression()">{{ value.expression }}</span>
+ <BindingPill v-else-if="value.alias" :label="value.alias" />
+ <span v-else class="truncate">{{ value.css }}</span>
+ </template>
+ </span>
+ </ListboxItem>
+ </ListboxGroup>
+ <p v-if="groups.length === 0" :class="ui.empty()">{{ labels.empty }}</p>
+ </ListboxContent>
+ </TokenRowMenu>
+ </ListboxRoot>
+</template>
diff --git a/src/components/variables/TokenTypeFilter.vue b/src/components/variables/TokenTypeFilter.vue
new file mode 100644
index 000000000..f4f611d35
--- /dev/null
+++ b/src/components/variables/TokenTypeFilter.vue
@@ -0,0 +1,68 @@
+<script setup lang="ts">
+import {
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuItemIndicator,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuTrigger
+} from 'reka-ui'
+import { computed } from 'vue'
+
+import type { VariableType } from '@open-pencil/scene-graph'
+import { useI18n } from '@open-pencil/vue'
+
+import IconButton from '@/components/ui/button/IconButton.vue'
+import { useMenuUI } from '@/components/ui/menu/menu'
+import { VARIABLE_TYPE_ICONS, VARIABLE_TYPES } from '@/components/variables/type-icons'
+
+/** The variable types the list shows; none checked shows every type. */
+const types = defineModel<VariableType[]>({ default: () => [] })
+
+const { variables, variableTypes: text } = useI18n()
+const menu = useMenuUI({ content: 'w-44', item: 'justify-start gap-2' })
+
+const labels = computed<Record<VariableType, string>>(() => ({
+ COLOR: text.value.color,
+ FLOAT: text.value.number,
+ STRING: text.value.text,
+ BOOLEAN: text.value.boolean
+}))
+
+function toggle(type: VariableType, on: boolean) {
+ types.value = on ? [...types.value, type] : types.value.filter((candidate) => candidate !== type)
+}
+</script>
+
+<template>
+ <DropdownMenuRoot>
+ <DropdownMenuTrigger as-child>
+ <IconButton
+ size="sm"
+ :label="variables.filterByType"
+ :active="types.length > 0"
+ data-test-id="variables-type-filter"
+ >
+ <icon-lucide-list-filter class="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent side="bottom" :side-offset="4" align="end" :class="menu.content">
+ <DropdownMenuCheckboxItem
+ v-for="type in VARIABLE_TYPES"
+ :key="type"
+ :model-value="types.includes(type)"
+ :class="menu.item"
+ @select.prevent
+ @update:model-value="toggle(type, $event)"
+ >
+ <component :is="VARIABLE_TYPE_ICONS[type]" :class="menu.icon" />
+ <span class="flex-1">{{ labels[type] }}</span>
+ <DropdownMenuItemIndicator>
+ <icon-lucide-check :class="menu.icon" />
+ </DropdownMenuItemIndicator>
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+</template>
diff --git a/src/components/variables/TokensPanel.stories.ts b/src/components/variables/TokensPanel.stories.ts
new file mode 100644
index 000000000..dcfa57577
--- /dev/null
+++ b/src/components/variables/TokensPanel.stories.ts
@@ -0,0 +1,38 @@
+import type { Meta, StoryObj } from '@storybook/vue3-vite'
+
+import DesignSystem from './examples/DesignSystem.vue'
+
+const meta = {
+ title: 'Editor/Tokens Panel',
+ component: DesignSystem,
+ parameters: {
+ layout: 'centered',
+ docs: {
+ description: {
+ component:
+ 'Variables as design tokens: CSS names, units, per-mode values and expressions, mode conditions, and the stylesheet they produce.'
+ }
+ }
+ }
+} satisfies Meta<{ width?: number }>
+
+export default meta
+type Story = StoryObj<{ width?: number }>
+
+/** From 56rem the CSS name has its own column and the inspector sits beside the list. */
+export const DesignSystemTokens: Story = {}
+
+/** In a dialog-sized panel the CSS name moves under the token name; every mode still shows. */
+export const Medium: Story = { args: { width: 800 } }
+
+/**
+ * Below 40rem the list shows one mode and each detail opens behind Back. This follows the panel's
+ * width, so a narrow split view on a desktop window gets it too.
+ */
+export const Compact: Story = { args: { width: 380 } }
+
+/** On a phone the panel fills the screen and uses the compact layout. */
+export const Mobile: Story = {
+ globals: { viewport: { value: 'mobile2', isRotated: false } },
+ parameters: { layout: 'fullscreen' }
+}
diff --git a/src/components/variables/TokensPanel.vue b/src/components/variables/TokensPanel.vue
new file mode 100644
index 000000000..963f4fe94
--- /dev/null
+++ b/src/components/variables/TokensPanel.vue
@@ -0,0 +1,512 @@
+<script setup lang="ts">
+import { useElementSize } from '@vueuse/core'
+import { tv } from 'tailwind-variants'
+import { computed, ref, useTemplateRef, watch } from 'vue'
+
+import type { VariableTokenFields } from '@open-pencil/core/editor'
+import type { TokenStylesheetFormat } from '@open-pencil/dom-css/export'
+import type { VariableType, VariableValue } from '@open-pencil/scene-graph'
+import { useI18n, useSceneComputed, useVariables } from '@open-pencil/vue'
+
+import {
+ aliasCandidates,
+ groupTree,
+ inGroup,
+ searchTokenIds,
+ tokenGroups,
+ type TokenGroup
+} from '@/app/editor/tokens/model'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'
+import AppInput from '@/components/ui/input/AppInput.vue'
+import PanelDrillIn from '@/components/ui/panel/PanelDrillIn.vue'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
+import AppTabsList from '@/components/ui/tabs/AppTabsList.vue'
+import AppTabsRoot from '@/components/ui/tabs/AppTabsRoot.vue'
+import AppTabsTrigger from '@/components/ui/tabs/AppTabsTrigger.vue'
+import CollectionInspector from '@/components/variables/CollectionInspector.vue'
+import TokenAddMenu from '@/components/variables/TokenAddMenu.vue'
+import TokenBulkInspector from '@/components/variables/TokenBulkInspector.vue'
+import TokenInspector from '@/components/variables/TokenInspector.vue'
+import TokenOutput from '@/components/variables/TokenOutput.vue'
+import TokenSidebar from '@/components/variables/TokenSidebar.vue'
+import TokenTable from '@/components/variables/TokenTable.vue'
+import TokenTypeFilter from '@/components/variables/TokenTypeFilter.vue'
+import { useTokenActions } from '@/components/variables/useTokenActions'
+import { swapTransition } from '@/theme/motion/styles'
+import tokensPanelTheme, {
+ TOKENS_PANEL_COMPACT_WIDTH,
+ TOKENS_PANEL_SIDEBAR_WIDTH
+} from '@/theme/tokens-panel'
+
+const emit = defineEmits<{ copy: [format: TokenStylesheetFormat] }>()
+
+const { variables: messages, common } = useI18n()
+const ui = tv(tokensPanelTheme)()
+
+/**
+ * The panel lays out by its own width, not the window: inside a dialog, a split view, or a phone.
+ * Below the compact width the inspector opens over the list; from the sidebar width collections
+ * and groups move into a sidebar.
+ */
+const root = useTemplateRef('root')
+const { width } = useElementSize(root)
+const compact = computed(() => width.value > 0 && width.value < TOKENS_PANEL_COMPACT_WIDTH)
+const wide = computed(() => width.value >= TOKENS_PANEL_SIDEBAR_WIDTH)
+
+const ctx = useVariables()
+const { editor } = ctx
+const actions = useTokenActions(editor, (name) => messages.value.duplicateName({ name }))
+
+const selectedIds = ref<string[]>([])
+const table = useTemplateRef<{ focus: () => void }>('table')
+/** Tokens being put in a new group: the group name field opens for them. */
+const groupingIds = ref<string[] | null>(null)
+const groupFilter = ref<string | null>(null)
+const typeFilter = ref<VariableType[]>([])
+
+/**
+ * What the compact detail view shows. It stays set while the view slides out, so Back animates
+ * the view that was open instead of switching its content first.
+ */
+type CompactDetail =
+ | { kind: 'token'; id: string }
+ | { kind: 'bulk' }
+ | { kind: 'collection' }
+ | { kind: 'stylesheet' }
+const compactDetail = ref<CompactDetail | null>(null)
+const detailOpen = ref(false)
+/** The mode whose values the single compact column shows. */
+const shownModeId = ref('')
+
+/** Read through the scene-computed list, so mode and condition edits re-render. */
+const collection = computed(
+ () =>
+ ctx.collections.value.find((candidate) => candidate.id === ctx.activeCollectionId.value) ?? null
+)
+
+/** Every token in the collection, for the sidebar's counts and for lookups a filter must not hide. */
+const collectionVariables = useSceneComputed(() =>
+ collection.value ? [...editor.getVariablesForCollection(collection.value.id)] : []
+)
+const allGroups = computed(() =>
+ collection.value ? tokenGroups(editor.graph, collection.value, collectionVariables.value) : []
+)
+const groupEntries = computed(() => groupTree(allGroups.value))
+
+/** Tokens the search matches, or null when there is no search. */
+const searchMatches = computed(() =>
+ searchTokenIds(
+ allGroups.value.flatMap((group) => group.rows),
+ ctx.searchTerm.value
+ )
+)
+
+/** What the list shows: the search, then the sidebar's group and the type filter, in list order. */
+const groups = computed<TokenGroup[]>(() =>
+ allGroups.value.flatMap((group) => {
+ if (groupFilter.value !== null && !inGroup(group.path, groupFilter.value)) return []
+ const rows = group.rows.filter(
+ (row) =>
+ (searchMatches.value?.has(row.variable.id) ?? true) &&
+ (typeFilter.value.length === 0 || typeFilter.value.includes(row.variable.type))
+ )
+ return rows.length > 0 ? [{ ...group, rows }] : []
+ })
+)
+
+function rowFor(id: string | null | undefined) {
+ return allGroups.value.flatMap((group) => group.rows).find((row) => row.variable.id === id)
+}
+
+/** The token the inspector edits: the one selected token, or the one opened when compact. */
+const editedId = computed(() => {
+ if (compact.value)
+ return compactDetail.value?.kind === 'token' ? compactDetail.value.id : undefined
+ return selectedIds.value.length === 1 ? selectedIds.value[0] : undefined
+})
+const editedRow = computed(() => rowFor(editedId.value))
+const bulkIds = computed(
+ () => groupingIds.value ?? (selectedIds.value.length > 1 ? selectedIds.value : null)
+)
+const candidates = computed(() =>
+ editedRow.value ? aliasCandidates(editor.graph, editedRow.value.variable) : []
+)
+
+const collectionOptions = computed(() =>
+ ctx.collections.value.map((candidate) => ({ value: candidate.id, label: candidate.name }))
+)
+const sidebarCollections = computed(() =>
+ ctx.collections.value.map((candidate) => ({
+ id: candidate.id,
+ name: candidate.name,
+ count: candidate.variableIds.length
+ }))
+)
+const modeOptions = computed(() =>
+ (collection.value?.modes ?? []).map((mode) => ({ value: mode.modeId, label: mode.name }))
+)
+const tableLabels = computed(() => ({
+ name: messages.value.name,
+ cssName: messages.value.cssName,
+ empty: messages.value.noVariables
+}))
+
+watch(
+ collection,
+ (current) => {
+ if (!current?.modes.some((mode) => mode.modeId === shownModeId.value))
+ shownModeId.value = current?.defaultModeId ?? ''
+ },
+ { immediate: true }
+)
+
+/**
+ * Undo and redo change the document under the panel: tokens being grouped that no longer exist drop
+ * out, and a collection that no longer exists gives way to the first one left.
+ */
+watch(collectionVariables, (current) => {
+ const ids = new Set(current.map((variable) => variable.id))
+ if (groupingIds.value?.some((id) => !ids.has(id)))
+ groupingIds.value = groupingIds.value.filter((id) => ids.has(id))
+ if (compactDetail.value?.kind === 'token' && !ids.has(compactDetail.value.id)) closeDetail()
+})
+
+/**
+ * Only shown tokens stay selected, so a filter, a search or an undo never leaves a hidden token
+ * to be edited, moved or deleted.
+ */
+watch(groups, (current) => {
+ const shown = new Set(current.flatMap((group) => group.rows.map((row) => row.variable.id)))
+ if (selectedIds.value.some((id) => !shown.has(id)))
+ selectedIds.value = selectedIds.value.filter((id) => shown.has(id))
+})
+
+/** A group filter lets go once its group is gone, whether deleted, emptied or undone. */
+watch(groupEntries, (entries) => {
+ if (groupFilter.value !== null && !entries.some((entry) => entry.path === groupFilter.value))
+ groupFilter.value = null
+})
+
+watch(ctx.collections, (current) => {
+ if (current.some((candidate) => candidate.id === ctx.activeCollectionId.value)) return
+ ctx.activeCollectionId.value = current[0]?.id ?? ''
+})
+
+function focusList() {
+ if (!compact.value) table.value?.focus()
+}
+
+watch(ctx.activeCollectionId, () => {
+ groupFilter.value = null
+ closeDetail()
+})
+
+watch(selectedIds, (ids) => {
+ groupingIds.value = null
+ if (!compact.value || ids.length === 0) return
+ if (ids.length === 1) openDetail({ kind: 'token', id: ids[0] })
+ else openDetail({ kind: 'bulk' })
+})
+
+function openDetail(detail: CompactDetail) {
+ compactDetail.value = detail
+ detailOpen.value = true
+}
+
+function closeDetail() {
+ detailOpen.value = false
+ selectedIds.value = []
+ groupingIds.value = null
+}
+
+/** A new token is selected, with nothing hiding it, so its name is ready to edit. */
+function addToken(type: VariableType) {
+ ctx.searchTerm.value = ''
+ groupFilter.value = null
+ typeFilter.value = []
+ const id = ctx.addVariable(type)
+ if (id) selectedIds.value = [id]
+}
+
+function removeTokens(ids: readonly string[]) {
+ actions.remove(ids)
+ closeDetail()
+}
+
+function duplicateTokens(ids: readonly string[]) {
+ selectedIds.value = actions.duplicate(ids)
+}
+
+/** The list follows tokens into their new group when it is narrowed to one. */
+function moveToGroup(ids: readonly string[], group: string) {
+ actions.moveToGroup(ids, group)
+ if (groupFilter.value !== null) groupFilter.value = group || null
+ groupingIds.value = null
+}
+
+function startNewGroup(ids: string[]) {
+ groupingIds.value = ids
+ if (compact.value) openDetail({ kind: 'bulk' })
+}
+
+function reorder(sourceId: string, targetIndex: number, visibleIds: string[]) {
+ if (collection.value) actions.reorder(collection.value.id, sourceId, targetIndex, visibleIds)
+}
+
+function setCondition(modeId: string, condition: string) {
+ if (collection.value) editor.setModeCondition(collection.value.id, modeId, condition)
+}
+
+/** Props and listeners each inspector takes, the same beside the list and behind Back. */
+const tokenInspector = computed(() => {
+ const id = editedId.value
+ return {
+ aliasCandidates: candidates.value,
+ onRename: (name: string) => id && editor.renameVariable(id, name),
+ onUpdateToken: (patch: Partial<VariableTokenFields>) =>
+ id && editor.updateVariableToken(id, patch),
+ onUpdateValue: (modeId: string, value: VariableValue, coalesceKey?: string) =>
+ id && editor.updateVariableValue(id, modeId, value, coalesceKey),
+ onAlias: (modeId: string, aliasId: string) => id && actions.alias(id, modeId, aliasId),
+ onDetach: (modeId: string) => id && actions.detach(id, modeId),
+ onRemove: () => id && removeTokens([id]),
+ onDone: focusList
+ }
+})
+const bulkInspector = computed(() => {
+ const ids = bulkIds.value ?? []
+ return {
+ count: ids.length,
+ focusGroup: groupingIds.value !== null,
+ onMoveToGroup: (group: string) => moveToGroup(ids, group),
+ onDuplicate: () => duplicateTokens(ids),
+ onRemove: () => removeTokens(ids)
+ }
+})
+const collectionInspector = computed(() => {
+ const current = collection.value
+ return {
+ onRename: (name: string) => current && ctx.renameCollection(current.id, name),
+ onRemove: () => current && ctx.removeCollection(current.id),
+ onAddMode: ctx.addMode,
+ onRenameMode: ctx.renameMode,
+ onDuplicateMode: ctx.duplicateMode,
+ onSetDefaultMode: ctx.setDefaultMode,
+ onRemoveMode: ctx.removeMode,
+ onSetCondition: setCondition,
+ onDone: focusList
+ }
+})
+const tableActions = {
+ onRename: (id: string, name: string) => editor.renameVariable(id, name),
+ onUpdateValue: (id: string, modeId: string, value: VariableValue) =>
+ editor.updateVariableValue(id, modeId, value),
+ onDuplicate: duplicateTokens,
+ onMoveToGroup: moveToGroup,
+ onNewGroup: startNewGroup,
+ onRemove: removeTokens,
+ onReorder: reorder
+}
+const groupOptions = computed(() => groupEntries.value.map((entry) => entry.path))
+</script>
+
+<template>
+ <div ref="root" :class="ui.root()" data-test-id="tokens-panel">
+ <template v-if="!collection">
+ <div :class="ui.toolbar()">
+ <span class="flex-1" />
+ <slot name="actions" />
+ </div>
+ <AppPlaceholder :label="messages.noVariableCollections">
+ <template #icon>
+ <icon-lucide-folder class="size-5" />
+ </template>
+ <template #action>
+ <AppButton
+ variant="soft"
+ data-test-id="variables-create-collection"
+ @click="ctx.addCollection"
+ >
+ {{ messages.createCollection }}
+ </AppButton>
+ </template>
+ </AppPlaceholder>
+ </template>
+
+ <!-- Compact: the list, with tokens, the collection, or the stylesheet opening over it. -->
+ <PanelDrillIn
+ v-else-if="compact"
+ :open="detailOpen"
+ :back="common.back"
+ :parent="collection.name"
+ @back="closeDetail"
+ >
+ <template #actions>
+ <slot name="actions" />
+ </template>
+ <template #detail>
+ <TokenInspector
+ v-if="compactDetail?.kind === 'token' && editedRow"
+ v-bind="tokenInspector"
+ :row="editedRow"
+ :collection="collection"
+ layout="full"
+ />
+ <TokenBulkInspector
+ v-else-if="compactDetail?.kind === 'bulk'"
+ v-bind="bulkInspector"
+ layout="full"
+ />
+ <CollectionInspector
+ v-else-if="compactDetail?.kind === 'collection'"
+ v-bind="collectionInspector"
+ :collection="collection"
+ layout="full"
+ />
+ <TokenOutput
+ v-else
+ :collection-id="collection.id"
+ layout="full"
+ @copy="emit('copy', $event)"
+ />
+ </template>
+
+ <div class="flex shrink-0 flex-col gap-2 border-b border-border p-3">
+ <div class="flex items-center gap-1">
+ <AppSelect
+ v-model="ctx.activeCollectionId.value"
+ :options="collectionOptions"
+ :label="messages.collection"
+ :ui="{ trigger: 'min-w-0 flex-1' }"
+ />
+ <TokenAddMenu @add="addToken" />
+ <IconButton
+ size="sm"
+ :label="messages.createCollection"
+ data-test-id="variables-add-collection"
+ @click="ctx.addCollection"
+ >
+ <icon-lucide-folder-plus class="size-4" />
+ </IconButton>
+ <slot name="actions" />
+ </div>
+ <div class="flex items-center gap-2">
+ <AppInput
+ v-model="ctx.searchTerm.value"
+ type="search"
+ size="sm"
+ class="min-w-0 flex-1"
+ :placeholder="common.search"
+ :aria-label="common.search"
+ data-test-id="variables-search-input"
+ />
+ <AppSelect
+ v-if="modeOptions.length > 1"
+ v-model="shownModeId"
+ :options="modeOptions"
+ :label="messages.mode"
+ :ui="{ trigger: 'w-28 shrink-0' }"
+ />
+ <TokenTypeFilter v-model="typeFilter" />
+ <IconButton
+ :label="messages.collectionSettings"
+ data-test-id="variables-collection-settings"
+ @click="openDetail({ kind: 'collection' })"
+ >
+ <icon-lucide-settings-2 class="size-4" />
+ </IconButton>
+ <IconButton :label="messages.stylesheet" @click="openDetail({ kind: 'stylesheet' })">
+ <icon-lucide-braces class="size-4" />
+ </IconButton>
+ </div>
+ </div>
+ <TokenTable
+ v-model:selected-ids="selectedIds"
+ v-bind="tableActions"
+ :collection="collection"
+ :groups="groups"
+ :group-options="groupOptions"
+ :labels="tableLabels"
+ :mode-ids="[shownModeId]"
+ />
+ </PanelDrillIn>
+
+ <template v-else>
+ <div :class="ui.toolbar()">
+ <span v-if="wide" class="flex-1" />
+ <AppTabsRoot v-else v-model="ctx.activeCollectionId.value" class="min-w-0 flex-1">
+ <AppTabsList :label="messages.collection">
+ <AppTabsTrigger
+ v-for="candidate in ctx.collections.value"
+ :key="candidate.id"
+ :value="candidate.id"
+ data-test-id="variables-collection-tab"
+ >
+ {{ candidate.name }}
+ </AppTabsTrigger>
+ </AppTabsList>
+ </AppTabsRoot>
+ <AppInput
+ v-model="ctx.searchTerm.value"
+ type="search"
+ size="sm"
+ class="w-40"
+ :placeholder="common.search"
+ :aria-label="common.search"
+ data-test-id="variables-search-input"
+ />
+ <TokenTypeFilter v-model="typeFilter" />
+ <IconButton
+ v-if="!wide"
+ size="sm"
+ :label="messages.createCollection"
+ data-test-id="variables-add-collection"
+ @click="ctx.addCollection"
+ >
+ <icon-lucide-folder-plus class="size-4" />
+ </IconButton>
+ <TokenAddMenu :labelled="wide" @add="addToken" />
+ <slot name="actions" />
+ </div>
+ <div :class="ui.body()">
+ <TokenSidebar
+ v-if="wide"
+ v-model:collection-id="ctx.activeCollectionId.value"
+ v-model:group="groupFilter"
+ :collections="sidebarCollections"
+ :groups="groupEntries"
+ :total="collectionVariables.length"
+ @add-collection="ctx.addCollection"
+ />
+ <TokenTable
+ ref="table"
+ v-model:selected-ids="selectedIds"
+ v-bind="tableActions"
+ :collection="collection"
+ :groups="groups"
+ :group-options="groupOptions"
+ :labels="tableLabels"
+ />
+ <Transition v-bind="swapTransition" mode="out-in">
+ <TokenBulkInspector v-if="bulkIds" key="bulk" v-bind="bulkInspector" />
+ <TokenInspector
+ v-else-if="editedRow"
+ :key="editedRow.variable.id"
+ v-bind="tokenInspector"
+ :row="editedRow"
+ :collection="collection"
+ />
+ <CollectionInspector
+ v-else
+ key="collection"
+ v-bind="collectionInspector"
+ :collection="collection"
+ />
+ </Transition>
+ </div>
+ <TokenOutput :collection-id="collection.id" @copy="emit('copy', $event)" />
+ </template>
+ </div>
+</template>
diff --git a/src/components/variables/VariablesDialog.vue b/src/components/variables/VariablesDialog.vue
index 96767eb0c..c8b4a0899 100644
--- a/src/components/variables/VariablesDialog.vue
+++ b/src/components/variables/VariablesDialog.vue
@@ -1,430 +1,55 @@
<script setup lang="ts">
-import { FlexRender } from '@tanstack/vue-table'
-import { templateRef } from '@vueuse/core'
-import {
- ContextMenuContent,
- ContextMenuItem,
- ContextMenuPortal,
- ContextMenuRoot,
- ContextMenuSeparator,
- ContextMenuTrigger,
- DialogClose,
- DialogTitle,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuPortal,
- DropdownMenuRoot,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
- TabsContent,
- TabsList,
- TabsRoot,
- TabsTrigger
-} from 'reka-ui'
-import { tv } from 'tailwind-variants'
-import { watch, type Component } from 'vue'
-import IconHash from '~icons/lucide/hash'
-import IconPalette from '~icons/lucide/palette'
-import IconToggleLeft from '~icons/lucide/toggle-left'
-import IconType from '~icons/lucide/type'
-import IconX from '~icons/lucide/x'
+import { DialogTitle } from 'reka-ui'
+import { computed, ref } from 'vue'
-import type { VariableType } from '@open-pencil/scene-graph'
-import { variablesAddTestId, vTestId, useI18n, useVariablesEditor } from '@open-pencil/vue'
+import { useI18n } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { createTokenCopy } from '@/app/editor/tokens/copy'
-import ColorInput from '@/components/ColorPicker/ColorInput.vue'
-import AppButton from '@/components/ui/button/AppButton.vue'
+import { useDocumentShortcuts } from '@/app/shell/keyboard/document'
import IconButton from '@/components/ui/button/IconButton.vue'
-import { AppDialogRoot } from '@/components/ui/dialog'
-import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'
-import { useMenuUI } from '@/components/ui/menu/menu'
-import variableTableTheme from '@/theme/variable-table'
-
-const open = defineModel<boolean>('open', { default: false })
-const menuCls = useMenuUI({ content: 'w-40', item: 'justify-start gap-2' })
-const collectionMenuCls = useMenuUI({ content: 'w-56', item: 'justify-start gap-2' })
-const addVariableMenuCls = useMenuUI({ content: 'w-48' })
-const variableTable = tv(variableTableTheme)
-const tableStyles = variableTable()
-
-const variableTypeIcons: Record<VariableType, Component> = {
- COLOR: IconPalette,
- FLOAT: IconHash,
- STRING: IconType,
- BOOLEAN: IconToggleLeft
-}
-
-const { panels, variableTypes: variableTypeText, variables, common } = useI18n()
-
-const variableTypes: Array<{
- type: VariableType
- label: () => string
- description: () => string
-}> = [
- {
- type: 'COLOR',
- label: () => variableTypeText.value.color,
- description: () => variableTypeText.value.colorHint
- },
- {
- type: 'FLOAT',
- label: () => variableTypeText.value.number,
- description: () => variableTypeText.value.numberHint
- },
- {
- type: 'STRING',
- label: () => variableTypeText.value.text,
- description: () => variableTypeText.value.textHint
- },
- {
- type: 'BOOLEAN',
- label: () => variableTypeText.value.boolean,
- description: () => variableTypeText.value.booleanHint
+import { AppDialogClose, AppDialogRoot } from '@/components/ui/dialog'
+import TokensPanel from '@/components/variables/TokensPanel.vue'
+
+const store = useEditorStore()
+const open = computed({
+ get: () => store.state.variablesOpen,
+ set: (value: boolean) => {
+ store.state.variablesOpen = value
}
-]
-
-const copyTokens = createTokenCopy(useEditorStore())
-
-const ctx = useVariablesEditor({
- colorInput: ColorInput,
- icons: variableTypeIcons,
- fallbackIcon: IconToggleLeft,
- deleteIcon: IconX
-})
-const collectionInput = templateRef<HTMLInputElement>('collectionInput')
-const modeInput = templateRef<HTMLInputElement>('modeInput')
-
-watch(collectionInput, (input) => {
- void ctx.collectionRename.focusInput(input)
})
-watch(modeInput, (input) => {
- void ctx.modeRename.focusInput(input)
-})
-
-function getModeId(columnId: string): string | undefined {
- return columnId.startsWith('mode-') ? columnId.slice(5) : undefined
-}
-function modeId(columnId: string): string {
- return columnId.slice(5)
-}
+/** Undo and redo reach the document from inside the dialog, as they do on the canvas. */
+const onKeydown = useDocumentShortcuts()
-function modeLabelClass(defaultMode: boolean) {
- return variableTable({ defaultMode }).modeLabel()
-}
-
-function resizeHandleClass(resizing: boolean) {
- return variableTable({ resizing }).resizeHandle()
-}
+const { variables, common } = useI18n()
+/** Expanding gives a large design system most of the window; it is kept for this session. */
+const expanded = ref(false)
+const copyTokens = createTokenCopy(store)
</script>
<template>
<AppDialogRoot
v-model:open="open"
- height="tall"
- :ui="{ content: 'w-[800px] max-w-[90vw]' }"
+ :size="expanded ? 'screen' : 'xl'"
+ :height="expanded ? 'screen' : 'full'"
data-test-id="variables-dialog"
+ @keydown="onKeydown"
:aria-describedby="undefined"
>
<DialogTitle class="sr-only">{{ variables.localVariables }}</DialogTitle>
- <div v-if="!ctx.hasCollections.value" class="flex flex-1 flex-col">
- <div class="flex shrink-0 items-center justify-between border-b border-border px-4 py-3">
- <h2 class="text-sm font-semibold text-surface">{{ variables.localVariables }}</h2>
- <DialogClose
- :aria-label="common.close"
- class="flex size-6 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted hover:bg-hover hover:text-surface"
- >
- <icon-lucide-x class="size-4" />
- </DialogClose>
- </div>
- <AppPlaceholder :label="variables.noVariableCollections">
- <template #icon>
- <icon-lucide-folder class="size-5" />
- </template>
- <template #action>
- <AppButton
- variant="soft"
- data-test-id="variables-create-collection"
- @click="ctx.addCollection"
- >
- {{ variables.createCollection }}
- </AppButton>
- </template>
- </AppPlaceholder>
- </div>
-
- <template v-else>
- <TabsRoot v-model="ctx.activeCollectionId.value" class="flex flex-1 flex-col overflow-hidden">
- <div class="flex shrink-0 items-center border-b border-border">
- <TabsList class="flex flex-1 gap-0.5 overflow-x-auto px-3 py-1">
- <template v-for="col in ctx.collections.value" :key="col.id">
- <input
- v-if="ctx.collectionRename.editingId.value === col.id"
- ref="collectionInput"
- class="w-24 rounded border border-accent bg-input px-2 py-0.5 text-xs text-surface outline-none"
- :value="col.name"
- @blur="ctx.collectionRename.commit(col.id, $event)"
- @keydown="ctx.collectionRename.onKeydown"
- />
- <TabsTrigger
- v-else
- :value="col.id"
- data-test-id="variables-collection-tab"
- class="cursor-pointer rounded border-none px-2.5 py-1 text-xs whitespace-nowrap text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"
- @dblclick="ctx.startRenameCollection(col.id)"
- >
- {{ col.name }}
- </TabsTrigger>
- </template>
- </TabsList>
-
- <div class="flex items-center gap-1.5 px-3">
- <DropdownMenuRoot>
- <DropdownMenuTrigger as-child>
- <button
- data-test-id="variables-collection-menu"
- class="flex size-6 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted hover:bg-hover hover:text-surface"
- >
- <icon-lucide-ellipsis class="size-3.5" />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuPortal>
- <DropdownMenuContent
- side="bottom"
- :side-offset="4"
- align="start"
- :class="collectionMenuCls.content"
- >
- <DropdownMenuItem
- :class="collectionMenuCls.item"
- @select="ctx.startRenameCollection(ctx.activeCollectionId.value)"
- >
- <icon-lucide-pencil :class="collectionMenuCls.icon" />
- {{ variables.renameCollection }}
- </DropdownMenuItem>
- <DropdownMenuSeparator class="mx-1.5 my-1 h-px bg-border" />
- <DropdownMenuItem
- :class="collectionMenuCls.item"
- data-test-id="variables-copy-css"
- @select="copyTokens('css')"
- >
- <icon-lucide-braces :class="collectionMenuCls.icon" />
- {{ variables.copyAsCSS }}
- </DropdownMenuItem>
- <DropdownMenuItem
- :class="collectionMenuCls.item"
- data-test-id="variables-copy-tailwind"
- @select="copyTokens('tailwind')"
- >
- <icon-lucide-wind :class="collectionMenuCls.icon" />
- {{ variables.copyAsTailwindTheme }}
- </DropdownMenuItem>
- <DropdownMenuSeparator class="mx-1.5 my-1 h-px bg-border" />
- <DropdownMenuItem
- :class="collectionMenuCls.item"
- class="text-red-500"
- data-test-id="variables-delete-collection"
- @select="ctx.removeCollection(ctx.activeCollectionId.value)"
- >
- <icon-lucide-trash-2 :class="collectionMenuCls.icon" />
- {{ variables.deleteCollection }}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenuPortal>
- </DropdownMenuRoot>
- <div class="flex items-center gap-1 rounded border border-border px-2 py-0.5">
- <icon-lucide-search class="size-3 text-muted" />
- <input
- v-model="ctx.searchTerm.value"
- data-test-id="variables-search-input"
- class="w-24 border-none bg-transparent text-xs text-surface outline-none placeholder:text-muted"
- :placeholder="common.search"
- />
- </div>
- <IconButton
- :label="variables.createCollection"
- data-test-id="variables-add-collection"
- @click="ctx.addCollection"
- >
- <icon-lucide-folder-plus class="size-3.5" />
- </IconButton>
- <DialogClose
- :aria-label="common.close"
- class="flex size-6 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted hover:bg-hover hover:text-surface"
- >
- <icon-lucide-x class="size-4" />
- </DialogClose>
- </div>
- </div>
-
- <TabsContent
- v-for="col in ctx.collections.value"
- :key="col.id"
- :value="col.id"
- class="flex flex-1 flex-col overflow-hidden outline-none"
+ <TokensPanel @copy="copyTokens">
+ <template #actions>
+ <IconButton
+ :label="expanded ? variables.collapse : variables.expand"
+ data-test-id="variables-expand"
+ @click="expanded = !expanded"
>
- <div class="flex-1 overflow-auto">
- <table
- class="w-full min-w-full border-collapse"
- :style="{ width: `${ctx.table.getCenterTotalSize()}px` }"
- >
- <thead class="sticky top-0 z-10 bg-panel">
- <tr
- v-for="headerGroup in ctx.table.getHeaderGroups()"
- :key="headerGroup.id"
- class="border-b border-border"
- >
- <th
- v-for="header in headerGroup.headers"
- :key="header.id"
- class="relative px-4 py-2 text-left text-[11px] font-medium text-muted"
- :style="{ width: `${header.getSize()}px` }"
- >
- <template v-if="getModeId(header.column.id)">
- <input
- v-if="ctx.modeRename.editingId.value === getModeId(header.column.id)"
- ref="modeInput"
- class="-mx-1 w-full rounded border border-accent bg-input px-1 py-0 text-[11px] font-medium text-surface outline-none"
- :value="header.column.columnDef.header"
- @blur="ctx.modeRename.commit(modeId(header.column.id), $event)"
- @keydown="ctx.modeRename.onKeydown"
- />
- <ContextMenuRoot v-else>
- <ContextMenuTrigger as-child>
- <span
- :data-default="
- getModeId(header.column.id) === col.defaultModeId || undefined
- "
- :class="
- modeLabelClass(getModeId(header.column.id) === col.defaultModeId)
- "
- @dblclick="ctx.startRenameMode(modeId(header.column.id))"
- >
- {{ header.column.columnDef.header }}
- </span>
- </ContextMenuTrigger>
- <ContextMenuPortal>
- <ContextMenuContent :class="menuCls.content">
- <ContextMenuItem
- :class="menuCls.item"
- @select="ctx.startRenameMode(modeId(header.column.id))"
- >
- <icon-lucide-pencil :class="menuCls.icon" />
- {{ variables.renameMode }}
- </ContextMenuItem>
- <ContextMenuItem
- :class="menuCls.item"
- @select="ctx.duplicateMode(modeId(header.column.id))"
- >
- <icon-lucide-copy :class="menuCls.icon" />
- {{ variables.duplicateMode }}
- </ContextMenuItem>
- <ContextMenuItem
- v-if="getModeId(header.column.id) !== col.defaultModeId"
- :class="menuCls.item"
- @select="ctx.setDefaultMode(modeId(header.column.id))"
- >
- <icon-lucide-pin :class="menuCls.icon" />
- {{ variables.setDefaultMode }}
- </ContextMenuItem>
- <ContextMenuSeparator :class="menuCls.separator" />
- <ContextMenuItem
- :class="[menuCls.item, 'text-red-500']"
- :disabled="col.modes.length <= 1"
- @select="ctx.removeMode(modeId(header.column.id))"
- >
- <icon-lucide-trash-2 :class="menuCls.icon" />
- {{ variables.deleteMode }}
- </ContextMenuItem>
- </ContextMenuContent>
- </ContextMenuPortal>
- </ContextMenuRoot>
- </template>
- <FlexRender
- v-else-if="!header.isPlaceholder"
- :render="header.column.columnDef.header"
- :props="header.getContext()"
- />
- <div
- v-if="header.column.getCanResize()"
- :data-resizing="header.column.getIsResizing() || undefined"
- :class="resizeHandleClass(header.column.getIsResizing())"
- @mousedown="header.getResizeHandler()?.($event)"
- @touchstart="header.getResizeHandler()?.($event)"
- @dblclick="header.column.resetSize()"
- />
- </th>
- <th class="w-8 px-1 py-2">
- <IconButton
- :label="variables.addMode"
- data-test-id="variables-add-mode"
- @click="ctx.addMode"
- >
- <icon-lucide-plus class="size-3" />
- </IconButton>
- </th>
- </tr>
- </thead>
- <tbody>
- <tr
- v-for="row in ctx.table.getRowModel().rows"
- :key="row.id"
- data-test-id="variable-row"
- :class="tableStyles.row()"
- >
- <td
- v-for="cell in row.getVisibleCells()"
- :key="cell.id"
- class="px-4 py-1.5"
- :style="{ width: `${cell.column.getSize()}px` }"
- >
- <FlexRender :render="cell.column.columnDef.cell" :props="cell.getContext()" />
- </td>
- </tr>
- </tbody>
- </table>
- </div>
-
- <div
- class="flex w-full shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-2"
- >
- <span class="text-xs text-muted">{{ panels.createVariable }}</span>
- <DropdownMenuRoot>
- <DropdownMenuTrigger as-child>
- <AppButton variant="soft" data-test-id="variables-add-variable">
- <template #leading><icon-lucide-plus class="size-3.5" /></template>
- {{ panels.add }}
- <template #trailing><icon-lucide-chevron-down class="size-3" /></template>
- </AppButton>
- </DropdownMenuTrigger>
- <DropdownMenuPortal>
- <DropdownMenuContent
- side="top"
- :side-offset="8"
- align="end"
- :class="addVariableMenuCls.content"
- >
- <DropdownMenuItem
- v-for="item in variableTypes"
- :key="item.type"
- :class="menuCls.item"
- v-test-id="variablesAddTestId(item.type)"
- @select="ctx.addVariable(item.type)"
- >
- <component :is="variableTypeIcons[item.type]" :class="menuCls.icon" />
- <span class="flex min-w-0 flex-1 flex-col">
- <span>{{ item.label() }}</span>
- <span class="truncate text-[10px] text-muted">{{ item.description() }}</span>
- </span>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenuPortal>
- </DropdownMenuRoot>
- </div>
- </TabsContent>
- </TabsRoot>
- </template>
+ <icon-lucide-minimize-2 v-if="expanded" class="size-3.5" />
+ <icon-lucide-maximize-2 v-else class="size-3.5" />
+ </IconButton>
+ <AppDialogClose :ariaLabel="common.close" />
+ </template>
+ </TokensPanel>
</AppDialogRoot>
</template>
diff --git a/src/components/variables/examples/DesignSystem.vue b/src/components/variables/examples/DesignSystem.vue
new file mode 100644
index 000000000..021eaac39
--- /dev/null
+++ b/src/components/variables/examples/DesignSystem.vue
@@ -0,0 +1,161 @@
+<script setup lang="ts">
+import { shallowReactive } from 'vue'
+
+import { createDefaultEditorState, createEditor } from '@open-pencil/core/editor'
+import { SceneGraph, type Variable, type VariableValue } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
+import { provideEditor } from '@open-pencil/vue'
+
+import TokensPanel from '@/components/variables/TokensPanel.vue'
+
+/** The frame width in pixels, capped by the window; the panel lays out by this. */
+const { width = 1040 } = defineProps<{ width?: number }>()
+
+/** Reactive state, as the app session gives it, so edits re-render the panel. */
+const graph = new SceneGraph()
+const editor = createEditor({
+ graph,
+ state: shallowReactive(createDefaultEditorState(graph.getPages()[0].id))
+})
+
+function addVariable(
+ collectionId: string,
+ id: string,
+ name: string,
+ type: Variable['type'],
+ valuesByMode: Record<string, VariableValue>,
+ extra: Partial<Variable> = {}
+) {
+ graph.addVariable({
+ id,
+ name,
+ type,
+ collectionId,
+ valuesByMode,
+ description: '',
+ hiddenFromPublishing: false,
+ ...extra
+ })
+}
+
+graph.addCollection({
+ id: 'theme',
+ name: 'Theme',
+ modes: [
+ { modeId: 'light', name: 'Light' },
+ { modeId: 'dark', name: 'Dark' },
+ { modeId: 'contrast', name: 'Contrast', condition: '@media (prefers-contrast: more)' }
+ ],
+ defaultModeId: 'light',
+ variableIds: []
+})
+graph.addCollection({
+ id: 'primitives',
+ name: 'Primitives',
+ modes: [{ modeId: 'base', name: 'Base' }],
+ defaultModeId: 'base',
+ variableIds: []
+})
+graph.addCollection({
+ id: 'space',
+ name: 'Space',
+ modes: [
+ { modeId: 'comfortable', name: 'Comfortable' },
+ { modeId: 'compact', name: 'Compact', condition: '@media (max-width: 640px)' }
+ ],
+ defaultModeId: 'comfortable',
+ variableIds: []
+})
+
+for (const [id, name, hex] of [
+ ['blue-300', 'Blue/300', '#94C4FC'],
+ ['blue-500', 'Blue/500', '#3B82F5'],
+ ['blue-700', 'Blue/700', '#1D4ED8'],
+ ['gray-50', 'Gray/50', '#F9FAFB'],
+ ['gray-900', 'Gray/900', '#111827']
+] as const) {
+ addVariable('primitives', id, name, 'COLOR', { base: parseColor(hex) })
+}
+
+addVariable(
+ 'theme',
+ 'primary',
+ 'Brand/Primary',
+ 'COLOR',
+ {
+ light: { aliasId: 'blue-500' },
+ dark: { aliasId: 'blue-300' },
+ contrast: { aliasId: 'blue-700' }
+ },
+ { scopes: ['ALL_FILLS'], description: 'Buttons, links, and focus rings.' }
+)
+addVariable('theme', 'surface', 'Surface/Base', 'COLOR', {
+ light: parseColor('#FFFFFF'),
+ dark: parseColor('#111827'),
+ contrast: parseColor('#FFFFFF')
+})
+addVariable('theme', 'ink', 'Surface/Ink', 'COLOR', {
+ light: { aliasId: 'gray-900' },
+ dark: { aliasId: 'gray-50' },
+ contrast: parseColor('#000000')
+})
+
+addVariable(
+ 'space',
+ 'gutter',
+ 'Gutter',
+ 'FLOAT',
+ { comfortable: 24, compact: 16 },
+ { unit: 'rem', scopes: ['GAP'] }
+)
+addVariable(
+ 'space',
+ 'page',
+ 'Page/Inline',
+ 'FLOAT',
+ { comfortable: 32, compact: 16 },
+ {
+ scopes: ['WIDTH_HEIGHT'],
+ expressions: { comfortable: { css: 'clamp(1rem, 4vw, 2rem)', resolved: 32 } }
+ }
+)
+addVariable(
+ 'space',
+ 'radius',
+ 'Radius/Card',
+ 'FLOAT',
+ { comfortable: 12, compact: 8 },
+ {
+ scopes: ['CORNER_RADIUS']
+ }
+)
+addVariable(
+ 'space',
+ 'duration',
+ 'Motion/Fast',
+ 'FLOAT',
+ { comfortable: 150, compact: 150 },
+ {
+ unit: 'ms'
+ }
+)
+addVariable(
+ 'space',
+ 'font',
+ 'Font/Sans',
+ 'STRING',
+ { comfortable: 'Inter, system-ui, sans-serif', compact: 'Inter, system-ui, sans-serif' },
+ { scopes: ['FONT_FAMILY'] }
+)
+
+provideEditor(editor)
+</script>
+
+<template>
+ <div
+ class="flex h-[640px] w-[min(var(--frame-width),calc(100vw-4rem))] flex-col overflow-hidden rounded-lg border border-border bg-panel max-md:h-dvh max-md:w-full max-md:rounded-none max-md:border-0"
+ :style="{ '--frame-width': `${width}px` }"
+ >
+ <TokensPanel />
+ </div>
+</template>
diff --git a/src/components/variables/type-icons.ts b/src/components/variables/type-icons.ts
new file mode 100644
index 000000000..e44537aa8
--- /dev/null
+++ b/src/components/variables/type-icons.ts
@@ -0,0 +1,17 @@
+import type { Component } from 'vue'
+import IconHash from '~icons/lucide/hash'
+import IconPalette from '~icons/lucide/palette'
+import IconToggleLeft from '~icons/lucide/toggle-left'
+import IconType from '~icons/lucide/type'
+
+import type { VariableType } from '@open-pencil/scene-graph'
+
+/** One icon per variable type, shared by the add menu, the list rows, and the type filter. */
+export const VARIABLE_TYPE_ICONS: Record<VariableType, Component> = {
+ COLOR: IconPalette,
+ FLOAT: IconHash,
+ STRING: IconType,
+ BOOLEAN: IconToggleLeft
+}
+
+export const VARIABLE_TYPES: readonly VariableType[] = ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']
diff --git a/src/components/variables/useConditionLabels.ts b/src/components/variables/useConditionLabels.ts
new file mode 100644
index 000000000..3d1a84f7f
--- /dev/null
+++ b/src/components/variables/useConditionLabels.ts
@@ -0,0 +1,54 @@
+import { computed } from 'vue'
+
+import type { VariableCollection } from '@open-pencil/scene-graph'
+import { useI18n } from '@open-pencil/vue'
+
+import {
+ CONDITION_KINDS,
+ parseModeCondition,
+ type ConditionKind,
+ type ModeCondition
+} from '@/app/editor/tokens/conditions'
+import { modeConditionPlaceholder } from '@/app/editor/tokens/model'
+
+/** Plain-language names for mode conditions, shared by the collection inspector and the list. */
+export function useConditionLabels() {
+ const { variables } = useI18n()
+
+ const kindLabels = computed<Record<ConditionKind, string>>(() => ({
+ manual: variables.value.conditionManual,
+ dark: variables.value.conditionDark,
+ light: variables.value.conditionLight,
+ contrast: variables.value.conditionContrast,
+ 'reduced-motion': variables.value.conditionReducedMotion,
+ 'screen-narrower': variables.value.conditionScreenNarrower,
+ 'screen-wider': variables.value.conditionScreenWider,
+ 'container-narrower': variables.value.conditionContainerNarrower,
+ 'container-wider': variables.value.conditionContainerWider,
+ custom: variables.value.conditionCustom
+ }))
+
+ const kindOptions = computed(() =>
+ CONDITION_KINDS.map((kind) => ({ value: kind, label: kindLabels.value[kind] }))
+ )
+
+ /**
+ * One line for a column header: the preset in words, or the selector it writes. `code` marks
+ * CSS, which is set in the code font, from words, which are not.
+ */
+ function summary(
+ collection: VariableCollection,
+ modeId: string
+ ): { text: string; code: boolean } | undefined {
+ if (modeId === collection.defaultModeId) return undefined
+ const mode = collection.modes.find((candidate) => candidate.modeId === modeId)
+ const condition: ModeCondition = parseModeCondition(mode?.condition)
+ if (condition.kind === 'manual')
+ return { text: modeConditionPlaceholder(collection, modeId) ?? '', code: true }
+ if (condition.kind === 'custom') return { text: condition.css, code: true }
+ const label = kindLabels.value[condition.kind]
+ return { text: 'width' in condition ? `${label} ${condition.width}px` : label, code: false }
+ }
+
+ return { kindLabels, kindOptions, summary }
+}
diff --git a/src/components/variables/useTokenActions.ts b/src/components/variables/useTokenActions.ts
new file mode 100644
index 000000000..6c28088b0
--- /dev/null
+++ b/src/components/variables/useTokenActions.ts
@@ -0,0 +1,70 @@
+import type { Editor } from '@open-pencil/core/editor'
+
+import { nameInGroup, reorderedVariableIds } from '@/app/editor/tokens/model'
+
+/**
+ * What the token list does to several tokens at once. Each action is one undo step, however
+ * many tokens it touches.
+ */
+export function useTokenActions(editor: Editor, copyName: (name: string) => string) {
+ function variable(id: string) {
+ return editor.graph.variables.get(id)
+ }
+
+ /** Copies each token after its original and returns the copies, in order. */
+ function duplicate(ids: readonly string[]): string[] {
+ return editor.undo.runBatch('Duplicate variables', () =>
+ ids.flatMap((id) => {
+ const source = variable(id)
+ const copy = source && editor.duplicateVariable(id, copyName(source.name))
+ return copy ? [copy] : []
+ })
+ )
+ }
+
+ function moveToGroup(ids: readonly string[], group: string) {
+ editor.undo.runBatch('Move variables to group', () => {
+ for (const id of ids) {
+ const current = variable(id)
+ if (!current) continue
+ const name = nameInGroup(current.name, group)
+ if (name !== current.name) editor.renameVariable(id, name)
+ }
+ })
+ }
+
+ function remove(ids: readonly string[]) {
+ editor.undo.runBatch('Delete variables', () => {
+ for (const id of ids) editor.removeVariable(id)
+ })
+ }
+
+ /** Moves a token among the rows on screen; rows a search or filter hides keep their places. */
+ function reorder(
+ collectionId: string,
+ sourceId: string,
+ targetIndex: number,
+ visibleIds: readonly string[]
+ ) {
+ const order = editor.graph.variableCollections.get(collectionId)?.variableIds ?? []
+ editor.setVariableOrder(
+ collectionId,
+ reorderedVariableIds(order, visibleIds, sourceId, targetIndex)
+ )
+ }
+
+ function alias(id: string, modeId: string, aliasId: string) {
+ editor.updateVariableValue(id, modeId, { aliasId })
+ }
+
+ /** Detaching keeps what the alias resolved to, so nothing on the canvas changes. */
+ function detach(id: string, modeId: string) {
+ const value = variable(id)?.valuesByMode[modeId]
+ if (typeof value !== 'object' || !('aliasId' in value)) return
+ // In the edited mode, as the row shows it, not the mode the canvas happens to be in.
+ const resolved = editor.graph.resolveVariable(value.aliasId, modeId)
+ if (resolved !== undefined) editor.updateVariableValue(id, modeId, structuredClone(resolved))
+ }
+
+ return { duplicate, moveToGroup, remove, reorder, alias, detach }
+}
diff --git a/src/theme/code/editor.ts b/src/theme/code/editor.ts
index 66d14be1e..77d5ba210 100644
--- a/src/theme/code/editor.ts
+++ b/src/theme/code/editor.ts
@@ -103,6 +103,9 @@ export function codeEditorTheme(dark: boolean) {
}
/** Compact read-only code in chat tool calls, layered over `codeEditorTheme`. */
+/** For a viewer that fills its container rather than stopping at the 16rem cap. */
+export const codeViewerFillTheme = EditorView.theme({ '&': { maxHeight: 'none', height: '100%' } })
+
export const codeViewerTheme = EditorView.theme({
'&': { maxHeight: '16rem', fontSize: '10.5px', backgroundColor: 'var(--color-input)' },
'.cm-scroller': { lineHeight: '1.55' },
diff --git a/src/theme/dialog/index.ts b/src/theme/dialog/index.ts
index 4d3b37524..8f9d02744 100644
--- a/src/theme/dialog/index.ts
+++ b/src/theme/dialog/index.ts
@@ -21,12 +21,15 @@ export default {
sm: { content: 'w-[min(24rem,92vw)]' },
md: { content: 'w-[min(32rem,94vw)]' },
lg: { content: 'w-[min(46rem,94vw)]' },
- xl: { content: 'w-[min(64rem,96vw)]' }
+ xl: { content: 'w-[min(64rem,96vw)]' },
+ /** Nearly the whole window, for editors such as the variables dialog when expanded. */
+ screen: { content: 'w-[98vw]' }
},
height: {
auto: {},
tall: { content: 'h-[min(75vh,48rem)]' },
- full: { content: 'h-[min(90vh,56rem)]' }
+ full: { content: 'h-[min(90vh,56rem)]' },
+ screen: { content: 'h-[96vh] max-h-[96vh]' }
}
}
} as const
diff --git a/src/theme/motion/styles.ts b/src/theme/motion/styles.ts
index 74c3e5b86..2b7ff9e69 100644
--- a/src/theme/motion/styles.ts
+++ b/src/theme/motion/styles.ts
@@ -12,6 +12,24 @@ export const motionStyles = {
pulse: 'animate-pulse motion-reduce:animate-none'
} as const
+/** A detail view sliding in over its list and back out the way it came. */
+export const drillInTransition = {
+ enterActiveClass:
+ 'transition-[opacity,translate] duration-150 ease-out motion-reduce:transition-none',
+ enterFromClass: 'translate-x-3 opacity-0 motion-reduce:translate-x-0',
+ leaveActiveClass:
+ 'transition-[opacity,translate] duration-100 ease-in motion-reduce:transition-none',
+ leaveToClass: 'translate-x-3 opacity-0 motion-reduce:translate-x-0'
+} as const
+
+/** One view replacing another in place, such as an inspector switching to another item. */
+export const swapTransition = {
+ enterActiveClass: 'transition-opacity duration-150 ease-out motion-reduce:transition-none',
+ enterFromClass: 'opacity-0',
+ leaveActiveClass: 'transition-opacity duration-75 ease-in motion-reduce:transition-none',
+ leaveToClass: 'opacity-0'
+} as const
+
export const feedbackTransition = {
enterActiveClass: 'animate-in fade-in duration-150 motion-reduce:animate-none',
leaveActiveClass: 'animate-out fade-out duration-150 motion-reduce:animate-none'
diff --git a/src/theme/panel/drill-in.ts b/src/theme/panel/drill-in.ts
new file mode 100644
index 000000000..887639c47
--- /dev/null
+++ b/src/theme/panel/drill-in.ts
@@ -0,0 +1,9 @@
+export default {
+ slots: {
+ root: 'relative flex min-h-0 flex-1 flex-col',
+ base: 'flex min-h-0 flex-1 flex-col',
+ detail: 'absolute inset-0 z-10 flex min-h-0 flex-col bg-panel',
+ header: 'flex shrink-0 items-center gap-1 border-b border-border px-1.5 py-1',
+ body: 'flex min-h-0 flex-1 flex-col'
+ }
+} as const
diff --git a/src/theme/settings/models.ts b/src/theme/settings/models.ts
deleted file mode 100644
index 6749037de..000000000
--- a/src/theme/settings/models.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export const modelPanelTransition = {
- enterActiveClass:
- 'transition-[opacity,translate] duration-150 ease-out motion-reduce:transition-none',
- enterFromClass: 'opacity-0 translate-x-1 motion-reduce:translate-x-0',
- leaveActiveClass: 'transition-opacity duration-100 ease-in motion-reduce:transition-none',
- leaveToClass: 'opacity-0'
-} as const
diff --git a/src/theme/tokens-panel.ts b/src/theme/tokens-panel.ts
new file mode 100644
index 000000000..023a6b916
--- /dev/null
+++ b/src/theme/tokens-panel.ts
@@ -0,0 +1,78 @@
+/** Below this panel width (40rem) the inspector opens over the list instead of beside it. */
+export const TOKENS_PANEL_COMPACT_WIDTH = 640
+
+/** From this panel width (56rem) collections and groups move into a sidebar beside the list. */
+export const TOKENS_PANEL_SIDEBAR_WIDTH = 896
+
+/**
+ * The list is its own `tokens-list` container, so its columns follow the space left beside the
+ * inspector. Below 42rem (`@2xl`) the CSS name moves under the token name; the value columns
+ * repeat `--token-modes` times.
+ */
+const COLUMNS =
+ 'grid-cols-[minmax(0,1.4fr)_repeat(var(--token-modes),minmax(6rem,1fr))] @2xl/tokens-list:grid-cols-[minmax(8rem,1.1fr)_minmax(8rem,1fr)_repeat(var(--token-modes),minmax(7rem,1fr))]'
+
+export default {
+ slots: {
+ root: '@container/tokens flex min-h-0 flex-1 flex-col',
+ toolbar: 'flex shrink-0 items-center gap-1 border-b border-border px-3 py-1.5',
+ body: 'flex min-h-0 flex-1 overflow-hidden',
+ sidebar: 'flex w-52 shrink-0 flex-col gap-4 overflow-y-auto border-r border-border p-2',
+ sidebarSection: 'flex flex-col gap-0.5',
+ sidebarHeading: 'mb-1 flex items-center justify-between px-2',
+ sidebarItem:
+ 'flex cursor-pointer items-center gap-2 rounded py-1 pr-2 pl-[calc(0.5rem+var(--depth,0)*0.75rem)] text-left text-xs text-surface hover:bg-hover data-[active]:bg-hover data-[active]:font-medium',
+ sidebarGroupLabel: 'truncate',
+ sidebarCount: 'ml-auto text-[11px] text-muted tabular-nums',
+ list: '@container/tokens-list flex min-w-0 flex-1 flex-col overflow-auto',
+ inspector: 'flex shrink-0 flex-col gap-4 overflow-y-auto p-4',
+ output: 'flex shrink-0 flex-col border-t border-border',
+ header: `sticky top-0 z-10 grid items-center gap-3 border-b border-border bg-panel px-4 py-2 text-[11px] font-medium text-muted ${COLUMNS}`,
+ group: 'px-4 pt-3 pb-1 text-[11px] font-semibold text-muted',
+ row: `${COLUMNS} grid cursor-pointer items-center gap-3 px-4 py-1.5 text-xs text-surface outline-none transition-colors duration-100 hover:bg-hover data-[highlighted]:bg-hover data-[state=checked]:bg-hover data-[state=checked]:ring-1 data-[state=checked]:ring-accent/40 data-[state=checked]:ring-inset data-[dragging]:opacity-50 data-[drop=after]:shadow-[inset_0_-2px_0_var(--color-accent)] data-[drop=before]:shadow-[inset_0_2px_0_var(--color-accent)] motion-reduce:transition-none`,
+ name: 'flex min-w-0 flex-col truncate',
+ nameLine: 'flex min-w-0 items-center gap-1.5',
+ typeIcon: 'size-3 shrink-0 text-muted',
+ cssName: 'truncate font-mono text-[11px] text-muted',
+ /** The CSS name as its own column, from 42rem of list width. */
+ cssColumn: 'hidden truncate font-mono text-[11px] text-muted @2xl/tokens-list:block',
+ /** The CSS name column's title, in the header's own font like the others. */
+ headerCssColumn: 'hidden @2xl/tokens-list:block',
+ /** The CSS name under the token name, below 42rem of list width. */
+ cssStacked: 'truncate font-mono text-[11px] text-muted @2xl/tokens-list:hidden',
+ value:
+ 'flex min-w-0 animate-in items-center gap-1.5 truncate font-mono text-[11px] fade-in duration-150 motion-reduce:animate-none',
+ expression: 'truncate font-mono text-[11px] text-accent',
+ modeHeader: 'flex min-w-0 flex-col gap-0.5',
+ /** When a mode applies: words in the UI font, a selector or query in the code font. */
+ modeCondition:
+ 'truncate text-[11px] font-normal text-muted data-[code]:font-mono data-[code]:text-[10px] data-[code]:text-muted/80',
+ section: 'flex flex-col gap-2',
+ sectionTitle: 'text-[11px] font-semibold text-muted',
+ field: 'flex flex-col gap-1',
+ /** One mode in the collection inspector: its name, when it applies, and the CSS it writes. */
+ /** The CSS a mode is written under, wrapped rather than cut so it reads in full. */
+ modeCSS: 'font-mono text-[11px] break-all text-muted',
+ mode: 'flex flex-col gap-1.5 border-b border-border pb-3 last:border-b-0 last:pb-0',
+ label: 'text-[11px] text-muted',
+ hint: 'text-[10px] text-muted',
+ error: 'text-[10px] text-error',
+ /** The fixed `--` in front of a CSS name the user types. */
+ prefix: 'font-mono text-xs text-muted',
+ /** A list cell being edited in place. */
+ cellInput:
+ 'w-full min-w-0 rounded border border-accent bg-input px-1.5 py-0.5 text-xs text-surface outline-none',
+ /** A mode's value control beside the button that points it at a variable. */
+ valueRow: 'flex items-center gap-1 [&>*:first-child]:min-w-0 [&>*:first-child]:flex-1',
+ valueControl: 'flex min-w-0 items-center gap-1',
+ empty: 'px-4 py-8 text-center text-xs text-muted'
+ },
+ variants: {
+ /** Beside the token list on desktop; the whole panel, behind a back button, on mobile. */
+ layout: {
+ side: { inspector: 'w-64 border-l border-border @6xl/tokens:w-72', output: 'h-56' },
+ full: { inspector: 'min-h-0 w-full flex-1', output: 'min-h-0 flex-1 border-t-0' }
+ }
+ },
+ defaultVariants: { layout: 'side' }
+} as const
diff --git a/src/theme/variable-table.ts b/src/theme/variable-table.ts
deleted file mode 100644
index d0014f352..000000000
--- a/src/theme/variable-table.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-const variableTableTheme = {
- slots: {
- modeLabel: 'cursor-default',
- resizeHandle: 'absolute top-0 right-0 h-full w-1 cursor-col-resize touch-none select-none',
- row: 'group border-b border-border/30 hover:bg-hover/50'
- },
- variants: {
- defaultMode: {
- true: { modeLabel: 'text-surface' },
- false: {}
- },
- resizing: {
- true: { resizeHandle: 'bg-accent' },
- false: { resizeHandle: 'bg-transparent hover:bg-border' }
- }
- },
- defaultVariants: {
- defaultMode: false,
- resizing: false
- }
-}
-
-export type VariableTableTheme = typeof variableTableTheme
-export default variableTableTheme
diff --git a/tests/app/editor/tokens/conditions.test.ts b/tests/app/editor/tokens/conditions.test.ts
new file mode 100644
index 000000000..c5d9dea74
--- /dev/null
+++ b/tests/app/editor/tokens/conditions.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ changeConditionKind,
+ isAutomaticCondition,
+ modeConditionCSS,
+ parseModeCondition,
+ type ModeCondition
+} from '@/app/editor/tokens/conditions'
+
+describe('mode condition presets', () => {
+ test.each<[ModeCondition, string | undefined]>([
+ [{ kind: 'manual' }, undefined],
+ [{ kind: 'dark' }, '@media (prefers-color-scheme: dark)'],
+ [{ kind: 'light' }, '@media (prefers-color-scheme: light)'],
+ [{ kind: 'contrast' }, '@media (prefers-contrast: more)'],
+ [{ kind: 'reduced-motion' }, '@media (prefers-reduced-motion: reduce)'],
+ [{ kind: 'screen-narrower', width: 640 }, '@media (max-width: 640px)'],
+ [{ kind: 'screen-wider', width: 1024 }, '@media (min-width: 1024px)'],
+ [{ kind: 'container-narrower', width: 480 }, '@container (max-width: 480px)'],
+ [{ kind: 'container-wider', width: 37.5 }, '@container (min-width: 37.5px)'],
+ [{ kind: 'custom', css: '.dark' }, '.dark']
+ ])('%o writes %s and reads back', (condition, css) => {
+ expect(modeConditionCSS(condition)).toBe(css)
+ expect(parseModeCondition(css)).toEqual(condition)
+ })
+
+ test('reads hand-written conditions with other spacing as their preset', () => {
+ expect(parseModeCondition('@media(prefers-color-scheme:dark)')).toEqual({ kind: 'dark' })
+ expect(parseModeCondition(' @media ( max-width : 640px ) ')).toEqual({
+ kind: 'screen-narrower',
+ width: 640
+ })
+ })
+
+ test('keeps anything else as custom CSS', () => {
+ expect(parseModeCondition('@media (max-width: 40rem)')).toEqual({
+ kind: 'custom',
+ css: '@media (max-width: 40rem)'
+ })
+ expect(parseModeCondition('[data-theme="dark"]')).toEqual({
+ kind: 'custom',
+ css: '[data-theme="dark"]'
+ })
+ // A non-breaking space is not CSS whitespace, so this is not the dark preset.
+ expect(parseModeCondition('@media\u00A0(prefers-color-scheme: dark)').kind).toBe('custom')
+ })
+
+ test('an empty custom condition falls back to the manual attribute', () => {
+ expect(modeConditionCSS({ kind: 'custom', css: ' ' })).toBeUndefined()
+ })
+
+ test('switching presets carries the width and the written CSS', () => {
+ const narrow: ModeCondition = { kind: 'screen-narrower', width: 720 }
+ expect(changeConditionKind(narrow, 'container-wider')).toEqual({
+ kind: 'container-wider',
+ width: 720
+ })
+ expect(changeConditionKind({ kind: 'dark' }, 'screen-wider')).toEqual({
+ kind: 'screen-wider',
+ width: 640
+ })
+ expect(changeConditionKind(narrow, 'custom')).toEqual({
+ kind: 'custom',
+ css: '@media (max-width: 720px)'
+ })
+ })
+
+ test('only the attribute and custom selectors are switched by the page', () => {
+ expect(isAutomaticCondition({ kind: 'manual' })).toBe(false)
+ expect(isAutomaticCondition({ kind: 'custom', css: '.dark' })).toBe(false)
+ expect(isAutomaticCondition({ kind: 'custom', css: '@supports (color: oklch(0 0 0))' })).toBe(
+ true
+ )
+ expect(isAutomaticCondition({ kind: 'dark' })).toBe(true)
+ })
+})
diff --git a/tests/app/editor/tokens/model.test.ts b/tests/app/editor/tokens/model.test.ts
new file mode 100644
index 000000000..23c643970
--- /dev/null
+++ b/tests/app/editor/tokens/model.test.ts
@@ -0,0 +1,223 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type Variable, type VariableValue } from '@open-pencil/scene-graph'
+
+import {
+ aliasCandidates,
+ groupTree,
+ inGroup,
+ modeAttributeText,
+ nameInGroup,
+ parseTokenValueText,
+ reorderedVariableIds,
+ searchTokenIds,
+ tokenGroups,
+ tokenValueText,
+ type TokenGroup
+} from '@/app/editor/tokens/model'
+
+function graphWith(variables: Array<[string, Variable['type'], VariableValue]>) {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'c',
+ name: 'Theme',
+ modes: [{ modeId: 'm', name: 'Mode' }],
+ defaultModeId: 'm',
+ variableIds: []
+ })
+ for (const [id, type, value] of variables)
+ graph.addVariable({
+ id,
+ name: id,
+ type,
+ collectionId: 'c',
+ valuesByMode: { m: value },
+ description: '',
+ hiddenFromPublishing: false
+ })
+ return graph
+}
+
+function variable(graph: SceneGraph, id: string): Variable {
+ const found = graph.variables.get(id)
+ if (!found) throw new Error(`missing ${id}`)
+ return found
+}
+
+describe('groups', () => {
+ const row = { label: '', cssName: '', values: [] } as const
+ const groups = (paths: Array<[string, number]>): TokenGroup[] =>
+ paths.map(([path, count]) => ({
+ path,
+ rows: Array.from({ length: count }, (_, index) => ({
+ ...row,
+ variable: {
+ id: `${path}-${index}`,
+ name: '',
+ type: 'COLOR',
+ collectionId: 'c',
+ valuesByMode: {},
+ description: '',
+ hiddenFromPublishing: false
+ },
+ values: []
+ }))
+ }))
+
+ test('nest under their parents, which count everything inside them', () => {
+ expect(
+ groupTree(
+ groups([
+ ['', 1],
+ ['Text', 2],
+ ['Space/Inline', 3]
+ ])
+ )
+ ).toEqual([
+ { path: 'Text', label: 'Text', depth: 0, count: 2 },
+ { path: 'Space', label: 'Space', depth: 0, count: 3 },
+ { path: 'Space/Inline', label: 'Inline', depth: 1, count: 3 }
+ ])
+ })
+
+ test('a group holds its own tokens and those of groups inside it', () => {
+ expect(inGroup('Space/Inline', 'Space')).toBe(true)
+ expect(inGroup('Space', 'Space')).toBe(true)
+ expect(inGroup('Spacer', 'Space')).toBe(false)
+ })
+
+ test('moving a token keeps its own name', () => {
+ expect(nameInGroup('Brand/Primary', 'Theme/Brand')).toBe('Theme/Brand/Primary')
+ expect(nameInGroup('Brand/Primary', '')).toBe('Primary')
+ })
+})
+
+describe('typed values', () => {
+ const gutter: Variable = {
+ id: 'g',
+ name: 'Gutter',
+ type: 'FLOAT',
+ collectionId: 'c',
+ valuesByMode: { m: 24 },
+ description: '',
+ hiddenFromPublishing: false,
+ unit: 'rem'
+ }
+
+ test('numbers read and write in the token unit', () => {
+ expect(tokenValueText(gutter, 24)).toBe('1.5')
+ expect(parseTokenValueText(gutter, '2')).toBe(32)
+ expect(parseTokenValueText(gutter, 'wide')).toBeUndefined()
+ })
+})
+
+describe('token search', () => {
+ function rows() {
+ const graph = graphWith([
+ ['primary', 'COLOR', { r: 0.23, g: 0.51, b: 0.96, a: 1 }],
+ ['link', 'COLOR', { aliasId: 'primary' }],
+ ['gutter', 'FLOAT', 24]
+ ])
+ const brand = graph.variables.get('primary')
+ if (brand) {
+ brand.name = 'Brand/Primary'
+ brand.description = 'Buttons and focus rings'
+ }
+ const collection = graph.variableCollections.get('c')
+ if (!collection) throw new Error('missing collection')
+ return tokenGroups(graph, collection, [...graph.variables.values()]).flatMap(
+ (group) => group.rows
+ )
+ }
+
+ test.each<[string, string[]]>([
+ ['brand primary', ['primary', 'link']],
+ ['--color-brand', ['primary']],
+ ['#3B82F5', ['primary']],
+ ['focus rings', ['primary']],
+ ['Brand/Primary', ['primary', 'link']],
+ ['gutter', ['gutter']]
+ ])('%s finds %o', (query, ids) => {
+ expect([...(searchTokenIds(rows(), query) ?? [])].sort()).toEqual([...ids].sort())
+ })
+
+ test('an empty search filters nothing', () => {
+ expect(searchTokenIds(rows(), ' ')).toBeNull()
+ })
+})
+
+describe('alias previews', () => {
+ test('show what the alias gives in their own mode', () => {
+ const graph = new SceneGraph()
+ const theme = graph.createCollection('Theme')
+ const dark = graph.createMode(theme.id, 'Dark') ?? ''
+ const white = { r: 1, g: 1, b: 1, a: 1 }
+ const black = { r: 0, g: 0, b: 0, a: 1 }
+ const surface = graph.createVariable('Surface', 'COLOR', theme.id, white)
+ surface.valuesByMode[dark] = black
+ const card = graph.createVariable('Card', 'COLOR', theme.id, { aliasId: surface.id })
+ card.valuesByMode[dark] = { aliasId: surface.id }
+
+ const [row] = tokenGroups(graph, theme, [card]).flatMap((group) => group.rows)
+
+ expect(row.values.map((value) => value.color)).toEqual([white, black])
+ })
+})
+
+describe('mode attributes', () => {
+ test('a manual mode is turned on by the attribute its collection and name give', () => {
+ const graph = new SceneGraph()
+ const theme = graph.createCollection('Theme')
+ const dark = graph.createMode(theme.id, 'Dark') ?? ''
+
+ expect(modeAttributeText(theme, dark)).toBe('data-theme="dark"')
+ })
+})
+
+describe('reordering', () => {
+ test('moves a row among the visible ones', () => {
+ expect(reorderedVariableIds(['a', 'b', 'c'], ['a', 'b', 'c'], 'c', 0)).toEqual(['c', 'a', 'b'])
+ })
+
+ test('leaves rows a filter hides where they were', () => {
+ expect(reorderedVariableIds(['a', 'x', 'b', 'y', 'c'], ['a', 'b', 'c'], 'a', 2)).toEqual([
+ 'b',
+ 'x',
+ 'c',
+ 'y',
+ 'a'
+ ])
+ })
+})
+
+describe('alias candidates', () => {
+ test('offer variables of the same type, never the token itself', () => {
+ const graph = graphWith([
+ ['primary', 'COLOR', { r: 0, g: 0, b: 1, a: 1 }],
+ ['accent', 'COLOR', { r: 1, g: 0, b: 0, a: 1 }],
+ ['gap', 'FLOAT', 8]
+ ])
+
+ const candidates = aliasCandidates(graph, variable(graph, 'primary'))
+
+ expect(candidates.map((candidate) => candidate.id)).toEqual(['accent'])
+ expect(candidates[0]).toMatchObject({
+ name: 'accent',
+ collection: 'Theme',
+ color: { r: 1, g: 0, b: 0, a: 1 }
+ })
+ })
+
+ test('leave out variables that already point back at the token', () => {
+ const graph = graphWith([
+ ['base', 'FLOAT', 8],
+ ['middle', 'FLOAT', { aliasId: 'base' }],
+ ['top', 'FLOAT', { aliasId: 'middle' }],
+ ['other', 'FLOAT', 4]
+ ])
+
+ const candidates = aliasCandidates(graph, variable(graph, 'base'))
+
+ expect(candidates.map((candidate) => candidate.id)).toEqual(['other'])
+ })
+})
diff --git a/tests/e2e/variables/dialog.spec.ts b/tests/e2e/variables/dialog.spec.ts
index ae6534093..f358d652e 100644
--- a/tests/e2e/variables/dialog.spec.ts
+++ b/tests/e2e/variables/dialog.spec.ts
@@ -1,5 +1,4 @@
import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
-import { expectDefined } from '#tests/helpers/assert'
import { variablesAddTestId } from '#tests/helpers/test-ids'
const editor = useEditorSetup()
@@ -37,20 +36,15 @@ test('empty variables dialog offers to create a collection', async () => {
await expect(dialog).toBeHidden()
})
-test('variables dialog opens', async () => {
+test('variables dialog opens on the token list, collection, and stylesheet', async () => {
await createColorVariable('primary-color')
await openVariables().click()
const dialog = editor.page.getByTestId('variables-dialog')
await expect(dialog).toBeVisible()
- await expect(editor.page.locator('[data-default="true"]')).toHaveCount(1)
- const table = dialog.locator('table')
- const tableBox = expectDefined(await table.boundingBox(), 'variables table bounds')
- const scrollerBox = expectDefined(
- await table.locator('..').boundingBox(),
- 'table scroller bounds'
- )
- expect(tableBox.width).toBeGreaterThanOrEqual(scrollerBox.width)
+ await expect(variableRows()).toHaveCount(1)
+ await expect(dialog.getByTestId('collection-inspector').getByText('Default')).toBeVisible()
+ await expect(dialog.getByTestId('token-output')).toContainText('--color-primary-color: #FF0000')
editor.canvas.assertNoErrors()
})
@@ -106,17 +100,58 @@ test('add variable menu creates non-color variable types', async () => {
editor.canvas.assertNoErrors()
})
-test('click name cell activates editable input', async () => {
+test('selecting a variable edits it in the inspector', async () => {
await editor.page.getByTestId('variables-search-input').fill('')
await editor.canvas.waitForRender()
- const firstRow = variableRows().first()
- const nameCell = firstRow.locator('td').first()
- await nameCell.click()
- await editor.canvas.waitForRender()
+ await variableRows().filter({ hasText: 'primary-color' }).click()
+ const inspector = editor.page.getByTestId('token-inspector')
+ const name = inspector.getByRole('textbox', { name: 'Name', exact: true })
+ await expect(name).toHaveValue('primary-color')
+ await name.fill('brand-color')
+ await name.press('Enter')
+
+ await expect(variableRows().filter({ hasText: 'brand-color' })).toHaveCount(1)
+ editor.canvas.assertNoErrors()
+})
+
+test('deleting a variable removes its row', async () => {
+ await variableRows().filter({ hasText: 'New boolean' }).click()
+ const inspector = editor.page.getByTestId('token-inspector')
+ // The inspector swaps in for the newly selected token; act on it once it shows that token.
+ await expect(inspector.getByRole('textbox', { name: 'Name', exact: true })).toHaveValue(
+ 'New boolean'
+ )
+ await inspector.getByTestId('variables-delete-variable').click()
+
+ await expect(variableRows().filter({ hasText: 'New boolean' })).toHaveCount(0)
+ await expect(editor.page.getByTestId('collection-inspector')).toBeVisible()
+ editor.canvas.assertNoErrors()
+})
+
+test('a new mode is switched manually until a condition is picked', async () => {
+ const inspector = editor.page.getByTestId('collection-inspector')
+ await inspector.getByTestId('variables-add-mode').click()
+
+ const modes = inspector.getByTestId('variables-mode')
+ await expect(modes).toHaveCount(2)
+ const added = modes.nth(1)
+ await expect(added.getByTestId('variables-mode-css')).toHaveText(
+ '[data-test-collection="mode-2"]'
+ )
+ await expect(editor.page.getByTestId('token-list')).toContainText(
+ 'Mode 2[data-test-collection="mode-2"]'
+ )
- const editableInput = nameCell.locator('input, [contenteditable]').first()
- await expect(editableInput).toBeFocused()
+ await added.getByRole('combobox', { name: 'Mode 2: Applies when' }).click()
+ await editor.page.getByRole('option', { name: 'Screen is narrower than' }).click()
+ await expect(added.getByTestId('variables-mode-css')).toHaveText('@media (max-width: 640px)')
+ await added.getByRole('spinbutton', { name: 'Mode 2: Width' }).fill('480')
+ await added.getByRole('spinbutton', { name: 'Mode 2: Width' }).press('Enter')
+ await expect(added.getByTestId('variables-mode-css')).toHaveText('@media (max-width: 480px)')
+ await expect(editor.page.getByTestId('token-list')).toContainText(
+ 'Mode 2Screen is narrower than 480px'
+ )
editor.canvas.assertNoErrors()
})
@@ -128,12 +163,200 @@ test('color swatch opens color picker', async () => {
await openVariables().click()
await expect(editor.page.getByTestId('variables-dialog')).toBeVisible({ timeout: 3000 })
+ await variableRows().filter({ hasText: 'SwatchVar' }).click()
+ await expect(
+ editor.page.getByTestId('token-inspector').getByRole('textbox', { name: 'Name', exact: true })
+ ).toHaveValue('SwatchVar')
const swatch = editor.page
- .getByTestId('variable-row')
- .first()
+ .getByTestId('token-inspector')
.getByRole('button', { name: 'Edit color' })
+ .first()
await expect(swatch).toBeVisible({ timeout: 3000 })
await swatch.click()
await expect(editor.page.locator('[data-picker-content]')).toBeVisible({ timeout: 5000 })
editor.canvas.assertNoErrors()
})
+
+function inspectorName() {
+ return editor.page
+ .getByTestId('token-inspector')
+ .getByRole('textbox', { name: 'Name', exact: true })
+}
+
+test('the View menu opens the variables dialog', async () => {
+ const dialog = editor.page.getByTestId('variables-dialog')
+ // The color picker from the previous test takes the first Escape.
+ await editor.page.keyboard.press('Escape')
+ await expect(editor.page.locator('[data-picker-content]')).toBeHidden()
+ await dialog.getByRole('button', { name: 'Close', exact: true }).click()
+ await expect(dialog).toBeHidden()
+
+ await editor.page.locator('[role="menubar"] [role="menuitem"]', { hasText: 'View' }).click()
+ await editor.page.locator('[role="menu"] [role="menuitem"]', { hasText: 'Variables…' }).click()
+
+ await expect(dialog).toBeVisible()
+ editor.canvas.assertNoErrors()
+})
+
+test('a value points at another variable and detaches to what it showed', async () => {
+ await variableRows().filter({ hasText: 'SwatchVar' }).click()
+ await expect(inspectorName()).toHaveValue('SwatchVar')
+
+ await editor.page
+ .getByTestId('token-inspector')
+ .getByTestId('variables-use-variable')
+ .first()
+ .click()
+ await editor.page
+ .getByRole('dialog', { name: 'Use a variable' })
+ .getByRole('option', { name: /brand-color/ })
+ .click()
+ await expect(variableRows().filter({ hasText: 'SwatchVar' })).toContainText('brand-color')
+
+ await editor.page.getByTestId('variables-detach-variable').first().click()
+ await expect(variableRows().filter({ hasText: 'SwatchVar' })).toContainText('#FF0000')
+ editor.canvas.assertNoErrors()
+})
+
+test('a name is edited in place and a CSS name CSS cannot use is refused', async () => {
+ await variableRows().filter({ hasText: 'SwatchVar' }).getByText('SwatchVar').dblclick()
+ const cell = editor.page.getByTestId('variables-cell-input')
+ await cell.fill('Accent')
+ await cell.press('Enter')
+ await expect(variableRows().filter({ hasText: 'Accent' })).toHaveCount(1)
+
+ await expect(inspectorName()).toHaveValue('Accent')
+ const cssName = editor.page.getByTestId('variables-css-name')
+ await cssName.fill('not valid')
+ await expect(cssName).toHaveAttribute('aria-invalid', 'true')
+ await cssName.press('Enter')
+ await expect(editor.page.getByTestId('token-output')).not.toContainText('not valid')
+ // A refused name keeps the focus, so it can be corrected.
+ await expect(cssName).toBeFocused()
+
+ // A pasted `var(--…)` is read as the name inside it.
+ await cssName.fill('var(--accent-color)')
+ await cssName.press('Enter')
+ await expect(editor.page.getByTestId('token-output')).toContainText('--accent-color:')
+ editor.canvas.assertNoErrors()
+})
+
+test('several tokens are duplicated, grouped, and deleted together', async () => {
+ const before = await variableRows().count()
+ await variableRows().filter({ hasText: 'Accent' }).click()
+ await variableRows()
+ .filter({ hasText: 'brand-color' })
+ .click({ modifiers: ['ControlOrMeta'] })
+ await expect(editor.page.getByTestId('token-bulk-inspector')).toContainText(
+ '2 variables selected'
+ )
+
+ await variableRows().filter({ hasText: 'Accent' }).click({ button: 'right' })
+ await editor.page.getByTestId('variables-duplicate').click()
+ await expect(variableRows()).toHaveCount(before + 2)
+
+ await editor.page.getByTestId('variables-group-name').fill('Copies')
+ await editor.page.getByTestId('variables-group-name').press('Enter')
+ const group = editor.page.getByTestId('variables-group').filter({ hasText: 'Copies' })
+ await expect(group).toContainText('2')
+
+ await group.click()
+ await expect(variableRows()).toHaveCount(2)
+ await variableRows().first().click()
+ await variableRows()
+ .last()
+ .click({ modifiers: ['Shift'] })
+ await editor.page.keyboard.press('Delete')
+ await expect(group).toHaveCount(0)
+ editor.canvas.assertNoErrors()
+})
+
+test('undo and redo reach the document from inside the dialog', async () => {
+ // Deleting the last tokens of the filtered group above let the filter go.
+ await expect(variableRows().filter({ hasText: 'beta-spacing' })).toHaveCount(1)
+ await variableRows().filter({ hasText: 'beta-spacing' }).click()
+ await inspectorName().fill('gap-spacing')
+ await inspectorName().press('Enter')
+ // Enter commits and hands the keyboard back to the list, on the selected row.
+ await expect(variableRows().filter({ hasText: 'gap-spacing' })).toBeFocused()
+
+ await editor.page.keyboard.press('ControlOrMeta+KeyZ')
+ await expect(variableRows().filter({ hasText: 'beta-spacing' })).toHaveCount(1)
+ await editor.page.keyboard.press('ControlOrMeta+Shift+KeyZ')
+ await expect(variableRows().filter({ hasText: 'gap-spacing' })).toHaveCount(1)
+
+ const names = await variableRows().allTextContents()
+ await variableRows().filter({ hasText: 'gap-spacing' }).click()
+ await editor.page.keyboard.press('Delete')
+ await expect(variableRows().filter({ hasText: 'gap-spacing' })).toHaveCount(0)
+ await editor.page.keyboard.press('ControlOrMeta+KeyZ')
+ // The deleted variable comes back in its place, not at the end.
+ await expect(variableRows()).toHaveText(names)
+ editor.canvas.assertNoErrors()
+})
+
+test('a field with pending text keeps its own undo, and menus hold undo back', async () => {
+ await variableRows().filter({ hasText: 'gap-spacing' }).click()
+ await inspectorName().click()
+ await inspectorName().press('End')
+ await editor.page.keyboard.type('-draft')
+ await editor.page.keyboard.press('ControlOrMeta+KeyZ')
+ await expect(inspectorName()).toHaveValue('gap-spacing')
+ await expect(variableRows().filter({ hasText: 'gap-spacing' })).toHaveCount(1)
+ await inspectorName().blur()
+
+ await variableRows().filter({ hasText: 'gap-spacing' }).click({ button: 'right' })
+ await expect(editor.page.getByTestId('variables-row-menu')).toBeVisible()
+ await editor.page.keyboard.press('ControlOrMeta+KeyZ')
+ await expect(variableRows().filter({ hasText: 'gap-spacing' })).toHaveCount(1)
+ await editor.page.keyboard.press('Escape')
+ editor.canvas.assertNoErrors()
+})
+
+test('search finds variables by CSS name and by value', async () => {
+ const search = editor.page.getByTestId('variables-search-input')
+ const cssName = await variableRows()
+ .filter({ hasText: 'gap-spacing' })
+ .getByText(/^--/)
+ .first()
+ .textContent()
+
+ await search.fill(cssName ?? '')
+ await expect(variableRows()).toHaveCount(1)
+ await expect(variableRows()).toContainText('gap-spacing')
+
+ await variableRows().filter({ hasText: 'gap-spacing' }).click()
+ await expect(editor.page.getByTestId('token-inspector')).toBeVisible()
+
+ await search.fill('#FF0000')
+ await expect(variableRows().filter({ hasText: 'brand-color' })).toHaveCount(1)
+ await expect(variableRows().filter({ hasNotText: '#FF0000' })).toHaveCount(0)
+ // The search hid the selected token, so it is no longer selected or editable.
+ await expect(editor.page.getByTestId('token-inspector')).toBeHidden()
+ await expect(editor.page.getByTestId('collection-inspector')).toBeVisible()
+
+ await search.fill('')
+ editor.canvas.assertNoErrors()
+})
+
+test('the add menu opens under its button after the dialog changes width', async () => {
+ const viewport = editor.page.viewportSize()
+ if (!viewport) throw new Error('viewport size is not set')
+ const add = editor.page.getByTestId('variables-add-variable')
+ await editor.page.setViewportSize({ width: 800, height: viewport.height })
+ await expect(add).toHaveText('')
+ await editor.page.setViewportSize({ width: 1600, height: viewport.height })
+ await expect(add).toHaveText('Create variable')
+
+ await add.click()
+ const menu = editor.page.getByRole('menu')
+ await expect(menu).toBeVisible()
+ const button = await add.boundingBox()
+ const opened = await menu.boundingBox()
+ expect(opened?.y).toBeGreaterThan(button?.y ?? Infinity)
+ expect(opened?.x).toBeGreaterThan((button?.x ?? 0) - (opened?.width ?? 0))
+
+ await editor.page.keyboard.press('Escape')
+ await editor.page.setViewportSize(viewport)
+ editor.canvas.assertNoErrors()
+})
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index 4dbe203ed..b39c8946f 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -289,3 +289,13 @@ zh-cn:updates.unavailable
zh-cn:updates.upToDate
zh-cn:variables.copyAsCSS
zh-cn:variables.copyAsTailwindTheme
+ja:variables.cssName
+ja:variables.expression
+ja:variables.expressionHint
+ja:variables.conditionHint
+ja:variables.conditionCustom
+zh-cn:variables.cssName
+zh-cn:variables.expression
+zh-cn:variables.expressionHint
+zh-cn:variables.conditionHint
+zh-cn:variables.conditionCustom
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index 7ceba100e..621db7206 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -275,3 +275,16 @@ zh-cn:settings.mcp
zh-cn:storage.providerAmazonS3
zh-cn:storage.providerBackblaze
zh-cn:storage.providerR2
+de:variables.name
+de:variables.stylesheet
+es:variables.unitAuto
+fr:variables.unitAuto
+fr:variables.description
+fr:variables.collection
+fr:variables.condition
+fr:variables.mode
+it:variables.unitAuto
+pl:variables.unitAuto
+es:menu.variables
+fr:menu.variables
+fr:variables.collections