Skip to content

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

feat: write variables as a CSS token stylesheet (#856)

Danila Poyarkov01e58a3ad03b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2ab2adc51..cde128a78 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@
### Breaking changes
- `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.
- `encodeNodeChangeWithVariables`, `encodePaintWithVariableBinding`, and `encodeVarint` are removed from `@open-pencil/core` and `@open-pencil/core/kiwi`. They spliced a colour-variable binding into encoded bytes because the field had no schema entry; exports now write `colorVar`, which `fig.kiwi` defines, so nothing needs them. `parseVariableId` is unchanged.
@@ -26,6 +28,7 @@
- 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.
- 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, 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.
diff --git a/packages/cli/src/commands/tokens.ts b/packages/cli/src/commands/tokens.ts
new file mode 100644
index 000000000..923101dd8
--- /dev/null
+++ b/packages/cli/src/commands/tokens.ts
@@ -0,0 +1,52 @@
+import { defineCommand } from 'citty'
+
+import type { TokensResult } from '@open-pencil/core/rpc'
+
+import { fmtList } from '#cli/format'
+import { loadRPCData } from '#cli/rpc-data'
+
+import { variableCommandArgs } from './variables'
+
+export default defineCommand({
+ meta: {
+ description:
+ 'Print design variables as a stylesheet of CSS custom properties, or as a Tailwind v4 theme'
+ },
+ args: {
+ ...variableCommandArgs,
+ format: {
+ type: 'string',
+ description: 'css (:root and mode scopes) or tailwind (@theme, mode scopes and variants)',
+ default: 'css'
+ }
+ },
+ async run({ args }) {
+ const data = await loadRPCData<TokensResult>(
+ args.file,
+ 'tokens',
+ { format: args.format, collection: args.collection, type: args.type },
+ args
+ )
+
+ if (args.json) {
+ console.log(JSON.stringify(data, null, 2))
+ return
+ }
+
+ if (data.tokenCount === 0) {
+ console.error('No variables found.')
+ return
+ }
+
+ // The stylesheet goes to stdout so it can be redirected; what was left out goes to stderr.
+ process.stdout.write(data.css)
+ if (data.issues.length > 0) {
+ console.error(
+ fmtList(
+ data.issues.map((issue) => ({ header: issue })),
+ { compact: true }
+ )
+ )
+ }
+ }
+})
diff --git a/packages/cli/src/commands/variables.ts b/packages/cli/src/commands/variables.ts
index 055164e46..a20ba9bf4 100644
--- a/packages/cli/src/commands/variables.ts
+++ b/packages/cli/src/commands/variables.ts
@@ -6,19 +6,22 @@ import { appTargetOptions } from '#cli/app/target'
import { bold, entity, fmtList, fmtSummary } from '#cli/format'
import { loadRPCData } from '#cli/rpc-data'
+/** Document, filters, and output shared by the commands that read variables. */
+export const variableCommandArgs = {
+ file: {
+ type: 'positional',
+ description: 'Document file path (omit to connect to running app)',
+ required: false
+ },
+ collection: { type: 'string', description: 'Filter by collection name' },
+ type: { type: 'string', description: 'Filter by type: COLOR, FLOAT, STRING, BOOLEAN' },
+ ...appTargetOptions,
+ json: { type: 'boolean', description: 'Output as JSON' }
+} as const
+
export default defineCommand({
meta: { description: 'List design variables and collections' },
- args: {
- file: {
- type: 'positional',
- description: 'Document file path (omit to connect to running app)',
- required: false
- },
- collection: { type: 'string', description: 'Filter by collection name' },
- type: { type: 'string', description: 'Filter by type: COLOR, FLOAT, STRING, BOOLEAN' },
- ...appTargetOptions,
- json: { type: 'boolean', description: 'Output as JSON' }
- },
+ args: variableCommandArgs,
async run({ args }) {
const data = await loadRPCData<VariablesResult>(
args.file,
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 7b6b4dcb1..6cd79f303 100755
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -20,6 +20,7 @@ import pages from './commands/pages'
import query from './commands/query'
import selection from './commands/selection'
import settings from './commands/settings'
+import tokens from './commands/tokens'
import tool from './commands/tool'
import tree from './commands/tree'
import variables from './commands/variables'
@@ -54,6 +55,7 @@ const main = defineCommand({
selection,
settings,
tool,
+ tokens,
tree,
undo,
variables
diff --git a/packages/core/src/rpc/commands.ts b/packages/core/src/rpc/commands.ts
index da9e97180..dc5614f07 100644
--- a/packages/core/src/rpc/commands.ts
+++ b/packages/core/src/rpc/commands.ts
@@ -17,7 +17,7 @@ import {
treeCommand
} from './read-commands'
import type { RPCCommand } from './types'
-import { variablesCommand } from './variables-command'
+import { tokensCommand, variablesCommand } from './variables-command'
export type AutomationDocumentSummary = {
id: string
@@ -43,6 +43,7 @@ export const ALL_RPC_COMMANDS = [
queryCommand,
nodeCommand,
variablesCommand,
+ tokensCommand,
analyzeColorsCommand,
analyzeTypographyCommand,
analyzeSpacingCommand,
diff --git a/packages/core/src/rpc/index.ts b/packages/core/src/rpc/index.ts
index a47d50b37..da2b0aa05 100644
--- a/packages/core/src/rpc/index.ts
+++ b/packages/core/src/rpc/index.ts
@@ -13,6 +13,8 @@ export type {
NodeResult,
VariablesArgs,
VariablesResult,
+ TokensArgs,
+ TokensResult,
AnalyzeColorsArgs,
AnalyzeColorsResult,
AnalyzeTypographyArgs,
diff --git a/packages/core/src/rpc/variables-command.ts b/packages/core/src/rpc/variables-command.ts
index 377ac1946..40e7d946a 100644
--- a/packages/core/src/rpc/variables-command.ts
+++ b/packages/core/src/rpc/variables-command.ts
@@ -1,6 +1,8 @@
-import type { SceneGraph, Variable } from '@open-pencil/scene-graph'
+import type { SceneGraph, Variable, VariableType } from '@open-pencil/scene-graph'
import { colorToHex } from '@open-pencil/scene-graph/color'
+import { exportTokenStylesheet, type TokenExport } from '#core/tools/codegen/tokens'
+
import type { RPCCommand } from './types'
// ── variables ──
@@ -79,3 +81,35 @@ export const variablesCommand: RPCCommand<VariablesArgs, VariablesResult> = {
return result
}
}
+
+// ── tokens ──
+
+export interface TokensArgs {
+ format?: string
+ collection?: string
+ type?: string
+}
+
+export type TokensResult = TokenExport
+
+const VARIABLE_TYPES: readonly VariableType[] = ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']
+
+function variableType(value: string | undefined): VariableType | undefined {
+ if (!value) return undefined
+ const type = VARIABLE_TYPES.find((candidate) => candidate === value.toUpperCase())
+ if (!type) throw new Error(`Unknown variable type: ${value}. Use ${VARIABLE_TYPES.join(', ')}.`)
+ return type
+}
+
+export const tokensCommand: RPCCommand<TokensArgs, TokensResult> = {
+ name: 'tokens',
+ execute: (graph, args) => {
+ if (args.format && args.format !== 'css' && args.format !== 'tailwind')
+ throw new Error(`Unknown token format: ${args.format}. Use css or tailwind.`)
+ return exportTokenStylesheet(graph, {
+ format: args.format === 'tailwind' ? 'tailwind' : 'css',
+ collection: args.collection,
+ type: variableType(args.type)
+ })
+ }
+}
diff --git a/packages/core/src/tools/codegen/tokens.ts b/packages/core/src/tools/codegen/tokens.ts
index 1983dc866..3569c19f2 100644
--- a/packages/core/src/tools/codegen/tokens.ts
+++ b/packages/core/src/tools/codegen/tokens.ts
@@ -1,175 +1,56 @@
import * as v from 'valibot'
-import type { Variable, VariableCollection, VariableValue } from '@open-pencil/scene-graph'
-import { colorToHex } from '@open-pencil/scene-graph/color'
-import type { Color } from '@open-pencil/scene-graph/primitives'
+import type { SceneGraph, VariableType } from '@open-pencil/scene-graph'
import { defineTool } from '#core/tools/schema'
-function slugify(name: string): string {
- return name
- .replace(/\//g, '-')
- .replace(/\s+/g, '-')
- .replace(/[^a-zA-Z0-9-]/g, '')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '')
- .toLowerCase()
+export type TokenExportOptions = {
+ format: 'css' | 'tailwind'
+ /** Collection name, matched as a case-insensitive substring. */
+ collection?: string
+ type?: VariableType
}
-function toCamelCase(name: string): string {
- return slugify(name).replace(/-([a-z])/g, (_, c) => c.toUpperCase())
-}
-
-function isColor(value: VariableValue): value is Color {
- return typeof value === 'object' && 'r' in value && 'g' in value && 'b' in value
-}
-
-function isAlias(value: VariableValue): value is { aliasId: string } {
- return typeof value === 'object' && 'aliasId' in value
-}
-
-function resolveValue(
- value: VariableValue,
- variables: Map<string, Variable>,
- visited = new Set<string>()
-): VariableValue {
- if (!isAlias(value)) return value
- if (visited.has(value.aliasId)) return value
- visited.add(value.aliasId)
- const target = variables.get(value.aliasId)
- if (!target) return value
- const modeId = Object.keys(target.valuesByMode)[0]
- if (!modeId) return value
- return resolveValue(target.valuesByMode[modeId], variables, visited)
-}
-
-function formatCSSValue(value: VariableValue, variables: Map<string, Variable>): string {
- const resolved = resolveValue(value, variables)
- if (isColor(resolved)) return colorToHex(resolved)
- if (typeof resolved === 'number') return String(resolved)
- if (typeof resolved === 'string') return resolved
- if (typeof resolved === 'boolean') return resolved ? '1' : '0'
- if (isAlias(resolved)) return `/* unresolved alias: ${resolved.aliasId} */`
- return String(resolved)
-}
-
-interface TokenEntry {
- name: string
- cssVar: string
- type: string
- values: Partial<Record<string, string>>
-}
-
-function buildTokens(
- variables: Variable[],
- collections: VariableCollection[],
- allVars: Map<string, Variable>
-): { tokens: TokenEntry[]; modes: { id: string; name: string; collectionName: string }[] } {
- const collectionMap = new Map<string, VariableCollection>()
- for (const collection of collections) collectionMap.set(collection.id, collection)
-
- const modes: { id: string; name: string; collectionName: string }[] = []
- const seenModes = new Set<string>()
- for (const collection of collections) {
- for (const mode of collection.modes) {
- if (!seenModes.has(mode.modeId)) {
- seenModes.add(mode.modeId)
- modes.push({ id: mode.modeId, name: mode.name, collectionName: collection.name })
- }
- }
- }
-
- const tokens: TokenEntry[] = []
- for (const variable of variables) {
- const collection = collectionMap.get(variable.collectionId)
- const prefix = collection ? slugify(collection.name) : 'token'
- const cssVar = `--${prefix}-${slugify(variable.name)}`
-
- const values: Record<string, string> = {}
- for (const [modeId, value] of Object.entries(variable.valuesByMode)) {
- values[modeId] = formatCSSValue(value, allVars)
- }
-
- tokens.push({ name: variable.name, cssVar, type: variable.type, values })
- }
-
- return { tokens, modes }
-}
-
-function renderCSS(
- tokens: TokenEntry[],
- modes: { id: string; name: string; collectionName: string }[]
-): string {
- if (tokens.length === 0) return '/* No design tokens found */\n'
-
- const defaultModeId = modes[0]?.id ?? ''
- const lines: string[] = [':root {']
-
- for (const token of tokens) {
- const value = token.values[defaultModeId] ?? Object.values(token.values)[0] ?? ''
- lines.push(` ${token.cssVar}: ${value};`)
- }
- lines.push('}')
-
- for (const mode of modes.slice(1)) {
- const className = slugify(mode.name)
- lines.push('')
- lines.push(`/* ${mode.collectionName} / ${mode.name} */`)
- lines.push(`.${className} {`)
- for (const token of tokens) {
- const value = token.values[mode.id]
- if (value !== undefined) lines.push(` ${token.cssVar}: ${value};`)
- }
- lines.push('}')
- }
-
- return `${lines.join('\n')}\n`
-}
-
-function renderTailwindTheme(tokens: TokenEntry[], modes: { id: string; name: string }[]): string {
- const defaultModeId = modes[0]?.id ?? ''
- const colors: Record<string, string> = {}
- const spacing: Record<string, string> = {}
-
- for (const token of tokens) {
- const key = toCamelCase(token.name)
- const value = token.values[defaultModeId] ?? Object.values(token.values)[0] ?? ''
- if (token.type === 'COLOR') colors[key] = value
- else if (token.type === 'FLOAT') spacing[key] = `${value}px`
- }
-
- const theme: Record<string, unknown> = {}
- if (Object.keys(colors).length > 0) theme.colors = colors
- if (Object.keys(spacing).length > 0) theme.spacing = spacing
-
- return `// Auto-extracted from Figma design tokens
-export const designTokens = ${JSON.stringify(theme, null, 2)} as const
-`
-}
-
-function renderJSON(tokens: TokenEntry[], modes: { id: string; name: string }[]): string {
- const result: Record<string, Record<string, string>> = {}
-
- for (const mode of modes) {
- const modeTokens: Record<string, string> = {}
- for (const token of tokens) {
- const value = token.values[mode.id]
- if (value !== undefined) modeTokens[token.cssVar] = value
- }
- result[mode.name] = modeTokens
- }
-
- return JSON.stringify(result, null, 2)
+export type TokenExport = { css: string; tokenCount: number; issues: string[] }
+
+/** The document's variables as a token stylesheet, shared by the tool, the CLI, and the app. */
+export async function exportTokenStylesheet(
+ graph: SceneGraph,
+ options: TokenExportOptions
+): Promise<TokenExport> {
+ const query = options.collection?.toLowerCase()
+ const collectionIds = new Set(
+ [...graph.variableCollections.values()]
+ .filter((collection) => !query || collection.name.toLowerCase().includes(query))
+ .map((collection) => collection.id)
+ )
+ const ids = new Set(
+ [...graph.variables.values()]
+ .filter((variable) => collectionIds.has(variable.collectionId))
+ .filter((variable) => !options.type || variable.type === options.type)
+ .map((variable) => variable.id)
+ )
+ if (ids.size === 0) return { css: '', tokenCount: 0, issues: [] }
+
+ const { tokenStylesheet } = await import('@open-pencil/dom-css/export')
+ const { css, issues } = await tokenStylesheet(graph, {
+ format: options.format,
+ include: (variable) => ids.has(variable.id)
+ })
+ return { css, tokenCount: ids.size, issues: issues.map((issue) => issue.message) }
}
export const designToTokens = defineTool({
name: 'design_to_tokens',
description:
- 'Extract design tokens from Figma variables as CSS custom properties, Tailwind theme config, or JSON. Resolves aliases, handles multiple modes (light/dark).',
- execution: { kind: 'sync', mutation: 'none' },
+ 'Write the document variables as a stylesheet of CSS custom properties: defaults in :root, every other mode under its condition (a selector such as [data-theme="dark"] or an @media query), aliases as var() references. The tailwind format puts tokens with a Tailwind v4 namespace (--color-*, --spacing-*, --radius-*, --text-*, …) in @theme and adds a @custom-variant per mode. Issues lists tokens or modes that could not be written.',
+ execution: { kind: 'async', mutation: 'none' },
input: v.object({
format: v.optional(
- v.pipe(v.picklist(['css', 'tailwind', 'json']), v.description('Output format')),
+ v.pipe(
+ v.picklist(['css', 'tailwind']),
+ v.description('css: :root and mode scopes; tailwind: @theme, mode scopes and variants')
+ ),
'css'
),
collection: v.optional(
@@ -182,39 +63,8 @@ export const designToTokens = defineTool({
)
)
}),
- execute: (figma, args) => {
- const format = args.format
-
- let variables = figma.getLocalVariables()
- const collections = figma.getLocalVariableCollections()
- const allVars = new Map<string, Variable>()
- for (const variable of variables) allVars.set(variable.id, variable)
-
- if (args.collection) {
- const query = args.collection.toLowerCase()
- const matchingIds = new Set(
- collections
- .filter((collection) => collection.name.toLowerCase().includes(query))
- .map((collection) => collection.id)
- )
- variables = variables.filter((variable) => matchingIds.has(variable.collectionId))
- }
-
- if (args.type) {
- variables = variables.filter((variable) => variable.type === args.type)
- }
-
- if (variables.length === 0) {
- return { output: '/* No matching variables found */', tokenCount: 0 }
- }
-
- const { tokens, modes } = buildTokens(variables, collections, allVars)
-
- let output: string
- if (format === 'tailwind') output = renderTailwindTheme(tokens, modes)
- else if (format === 'json') output = renderJSON(tokens, modes)
- else output = renderCSS(tokens, modes)
-
- return { output, tokenCount: tokens.length, modeCount: modes.length }
+ execute: async (figma, args) => {
+ const { css, tokenCount, issues } = await exportTokenStylesheet(figma.graph, args)
+ return { output: css, tokenCount, issues }
}
})
diff --git a/packages/core/tests/rpc/variables-command.test.ts b/packages/core/tests/rpc/variables-command.test.ts
new file mode 100644
index 000000000..0b5c3b121
--- /dev/null
+++ b/packages/core/tests/rpc/variables-command.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'bun:test'
+
+import { executeRPCCommand, type TokensResult } from '@open-pencil/core/rpc'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function graphWithTokens(): SceneGraph {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Theme')
+ graph.createVariable('Primary', 'COLOR', collection.id, { r: 1, g: 0, b: 0, a: 1 })
+ graph.createVariable('Gap', 'FLOAT', collection.id, 8)
+ return graph
+}
+
+describe('tokens command', () => {
+ test('returns the stylesheet with its filters applied', async () => {
+ const result = (await executeRPCCommand(graphWithTokens(), 'tokens', {
+ format: 'css',
+ type: 'color'
+ })) as TokensResult
+ expect(result).toEqual({
+ css: ':root {\n --color-primary: #FF0000;\n}\n',
+ tokenCount: 1,
+ issues: []
+ })
+ })
+
+ test('rejects an unknown format or type', () => {
+ expect(() => executeRPCCommand(graphWithTokens(), 'tokens', { format: 'scss' })).toThrow(
+ 'Unknown token format: scss. Use css or tailwind.'
+ )
+ expect(() => executeRPCCommand(graphWithTokens(), 'tokens', { type: 'shadow' })).toThrow(
+ 'Unknown variable type: shadow. Use COLOR, FLOAT, STRING, BOOLEAN.'
+ )
+ })
+})
diff --git a/packages/core/tests/tools/codegen/tokens.test.ts b/packages/core/tests/tools/codegen/tokens.test.ts
new file mode 100644
index 000000000..a174b6703
--- /dev/null
+++ b/packages/core/tests/tools/codegen/tokens.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { designToTokens } from '#core/tools/codegen/tokens'
+
+const run = (figma: FigmaAPI, args: Parameters<typeof designToTokens.execute>[1]) =>
+ designToTokens.execute(figma, args)
+
+function themeTokens() {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const primitives = graph.createCollection('Primitives')
+ const blue = graph.createVariable('Blue/500', 'COLOR', primitives.id, {
+ r: 0.23,
+ g: 0.51,
+ b: 0.96,
+ a: 1
+ })
+ const theme = graph.createCollection('Theme')
+ graph.renameMode(theme.id, theme.defaultModeId, 'Light')
+ graph.addMode(theme.id, 'dark', 'Dark')
+ const primary = graph.createVariable('Primary', 'COLOR', theme.id, { aliasId: blue.id })
+ primary.valuesByMode.dark = { r: 0.58, g: 0.77, b: 0.99, a: 1 }
+ graph.createVariable('Gap', 'FLOAT', theme.id, 8)
+ return figma
+}
+
+describe('design_to_tokens', () => {
+ test('writes defaults, mode scopes, and aliases as references', async () => {
+ const result = await run(themeTokens(), { format: 'css' })
+ expect(result.output).toContain('--color-primary: var(--color-blue-500);')
+ expect(result.output).toContain('[data-theme="dark"] {\n --color-primary: #94C4FC;\n}')
+ expect(result.tokenCount).toBe(3)
+ expect(result.issues).toEqual([])
+ })
+
+ test('keeps references to tokens left out by a filter', async () => {
+ const result = await run(themeTokens(), { format: 'css', collection: 'theme', type: 'COLOR' })
+ expect(result.output).toContain('--color-primary: var(--color-blue-500);')
+ expect(result.output).not.toContain('--color-blue-500:')
+ expect(result.output).not.toContain('--gap')
+ expect(result.tokenCount).toBe(1)
+ })
+
+ test('writes a Tailwind v4 theme with a variant per mode', async () => {
+ const result = await run(themeTokens(), { format: 'tailwind' })
+ expect(result.output).toStartWith('@theme {')
+ expect(result.output).toContain(':root {\n --gap: 8px;\n}')
+ expect(result.output).toContain(
+ '@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));'
+ )
+ })
+})
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index e2a97b2e7..cdc0fd6b4 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -88,6 +88,34 @@ Standalone Tailwind output is compiled during export; it does not depend on the
HTML export is available in file mode.
+## Design Tokens
+
+Write the document's variables as CSS custom properties:
+
+```sh
+openpencil tokens design.fig > tokens.css
+openpencil tokens design.fig --format tailwind > theme.css
+openpencil tokens design.fig --collection Theme --type COLOR
+```
+
+Each collection's default mode goes in `:root`. Every other mode overrides the values that differ under its condition: `[data-theme="dark"]` for a Theme collection's Dark mode, or the selector or `@media` query the mode names. Aliases stay `var()` references and are declared again in each mode that changes what they point to, so switching `data-theme` on any element restyles everything built on it.
+
+```css
+:root {
+ --color-blue-500: #3B82F5;
+ --color-primary: var(--color-blue-500);
+}
+
+/* Theme: Dark */
+[data-theme="dark"] {
+ --color-primary: var(--color-blue-300);
+}
+```
+
+`--format tailwind` puts tokens with a Tailwind v4 namespace (`--color-*`, `--spacing-*`, `--radius-*`, `--text-*`, …) in `@theme`, so `bg-primary` and `rounded-card` work, and adds a `@custom-variant` per mode, so `dark:bg-surface` follows the same condition. Import the file after `@import "tailwindcss";`. Names come from the variable's code syntax when it names a custom property (`--x` or `var(--x)`), otherwise from its name and type: `Blue/500` as a color is `--color-blue-500`.
+
+Tokens that cannot be written, such as boolean variables or a condition that is not a selector or query, are listed on stderr and left out. The command works in file mode and against the running app.
+
## Storybook Export
Generate one CSF3 `.stories.ts` file per component set or component:
diff --git a/packages/docs/reference/cli.md b/packages/docs/reference/cli.md
index 9a05fa5d8..db2096be7 100644
--- a/packages/docs/reference/cli.md
+++ b/packages/docs/reference/cli.md
@@ -88,6 +88,21 @@ openpencil variables [file] [options]
| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` |
| `--json` | Output as JSON |
+## tokens
+
+Print design variables as a stylesheet of CSS custom properties. Default mode values go in `:root`; every other mode overrides them under its condition, `[data-<collection>="<mode>"]` unless the mode names a selector or `@media` query. Aliases stay `var()` references. Tokens or modes that cannot be written are listed on stderr.
+
+```sh
+openpencil tokens [file] [options]
+```
+
+| Option | Description |
+|--------|-------------|
+| `--format` | `css` (default), or `tailwind` for a Tailwind v4 `@theme` with a `@custom-variant` per mode |
+| `--collection` | Filter by collection name |
+| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` |
+| `--json` | Output `{ css, tokenCount, issues }` as JSON |
+
## export
Export to PNG, JPG, WEBP, SVG, JSX, HTML, `.fig`, or Storybook stories.
diff --git a/packages/dom-css/src/tokens/cssom-validator.ts b/packages/dom-css/src/tokens/cssom-validator.ts
new file mode 100644
index 000000000..e65f8536e
--- /dev/null
+++ b/packages/dom-css/src/tokens/cssom-validator.ts
@@ -0,0 +1,8 @@
+// Headless only: `./stylesheet` loads this module lazily where the browser's parser is missing.
+// A namespace import, read at call time: browser builds resolve the package to a script that
+// exports nothing, and a named import would fail those builds even though this never runs there.
+import * as cssom from '@acemir/cssom'
+
+import { createTokenValidator } from './validate'
+
+export const tokenValidator = createTokenValidator((cssText) => cssom.parse(cssText))
diff --git a/packages/dom-css/src/tokens/index.ts b/packages/dom-css/src/tokens/index.ts
index 1306c17e3..f73045470 100644
--- a/packages/dom-css/src/tokens/index.ts
+++ b/packages/dom-css/src/tokens/index.ts
@@ -1,10 +1,21 @@
-// Design tokens as CSS custom properties: names, namespaces, and units.
+// Design tokens as CSS custom properties: names, namespaces, units, and the stylesheet.
export {
cssNameCodeSyntax,
deriveCSSName,
explicitCSSName,
parseCSSName,
+ tokenSlug,
variableCSSNames,
variableNamespace
} from './names'
+export {
+ buildTokenStylesheet,
+ defaultModeCondition,
+ tokenStylesheet,
+ type TokenStylesheet,
+ type TokenStylesheetFormat,
+ type TokenStylesheetIssue,
+ type TokenStylesheetOptions
+} from './stylesheet'
+export { createTokenValidator, type TokenValidator } from './validate'
export { tokenNumberToCSS, variableUnit } from './values'
diff --git a/packages/dom-css/src/tokens/names.ts b/packages/dom-css/src/tokens/names.ts
index 6139b1ae7..8f04a1f33 100644
--- a/packages/dom-css/src/tokens/names.ts
+++ b/packages/dom-css/src/tokens/names.ts
@@ -1,5 +1,4 @@
import { compact } from 'es-toolkit/array'
-import { kebabCase } from 'es-toolkit/string'
import valueParser from 'postcss-value-parser'
import { themeNamespaces, type ThemeNamespace } from 'twirlwind'
@@ -37,13 +36,27 @@ const NAMESPACE_WORDS: Record<string, ThemeNamespace> = {
shadows: 'shadow'
}
+/**
+ * Lowercase words joined by `-`, keeping digits on their word, as Tailwind keys do: `Text/2xl`
+ * is `text-2xl`, `Heading/H1` is `heading-h1`, `brandPrimary` is `brand-primary`. es-toolkit's
+ * `kebabCase` splits digits off (`text-2-xl`), which no design system writes.
+ */
+export function tokenSlug(text: string): string {
+ const words = text
+ .normalize('NFKC')
+ .replaceAll(/(\p{Ll})(\p{Lu})/gu, '$1 $2')
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}]+/u)
+ return compact(words).join('-')
+}
+
/** The Tailwind namespace a token belongs to, from its type, its scopes, then its leading name segment. */
export function variableNamespace(variable: Variable): ThemeNamespace | undefined {
if (variable.type === 'COLOR') return 'color'
const fromScopes = new Set((variable.scopes ?? []).map((scope) => SCOPE_NAMESPACES[scope]))
const [only] = fromScopes
if (fromScopes.size === 1 && only) return only
- return NAMESPACE_WORDS[kebabCase(variable.name.split('/')[0] ?? '')]
+ return NAMESPACE_WORDS[tokenSlug(variable.name.split('/')[0] ?? '')]
}
/**
@@ -75,7 +88,7 @@ export function explicitCSSName(variable: Variable): string | undefined {
*/
export function deriveCSSName(variable: Variable): string {
const namespace = variableNamespace(variable)
- const segments = compact(variable.name.split('/').map((segment) => kebabCase(segment)))
+ const segments = compact(variable.name.split('/').map(tokenSlug))
if (segments.length > 1 && namespace && NAMESPACE_WORDS[segments[0] ?? ''] === namespace) {
segments.shift()
}
diff --git a/packages/dom-css/src/tokens/stylesheet.ts b/packages/dom-css/src/tokens/stylesheet.ts
new file mode 100644
index 000000000..43bd88d14
--- /dev/null
+++ b/packages/dom-css/src/tokens/stylesheet.ts
@@ -0,0 +1,286 @@
+import type {
+ SceneGraph,
+ Variable,
+ VariableCollection,
+ VariableCollectionMode,
+ VariableValue
+} from '@open-pencil/scene-graph'
+
+import { cssColor } from '../export/css'
+import { tokenSlug, variableCSSNames, variableNamespace } from './names'
+import { createTokenValidator, parseWithBrowser, type TokenValidator } from './validate'
+import { tokenNumberToCSS, variableUnit } from './values'
+
+export type TokenStylesheetFormat = 'css' | 'tailwind'
+
+export type TokenStylesheetIssue = {
+ message: string
+ variableId?: string
+ collectionId?: string
+ modeId?: string
+}
+
+export type TokenStylesheetOptions = {
+ format: TokenStylesheetFormat
+ /** Write only these tokens. Names still come from every token, so aliases outside resolve. */
+ include?: (variable: Variable) => boolean
+}
+
+export type TokenStylesheet = {
+ css: string
+ issues: TokenStylesheetIssue[]
+}
+
+type Declaration = { name: string; value: string }
+
+type ModeScope = {
+ collection: VariableCollection
+ mode: VariableCollectionMode
+ condition: string
+ declarations: Declaration[]
+}
+
+type TokenSource = Pick<SceneGraph, 'variables' | 'variableCollections'>
+
+function isAtRuleCondition(condition: string): boolean {
+ return condition.trim().startsWith('@')
+}
+
+/**
+ * A mode's name as an identifier. A name with no letters or digits falls back to its id, slugged
+ * too: Figma ids such as `1:2` are not valid in a selector value or a variant name as they are.
+ * Names that slug alike in one collection, such as `Dark` and `dark!`, are numbered in mode
+ * order, so each mode keeps its own selector and variant.
+ */
+function modeSlug(collection: VariableCollection, mode: VariableCollectionMode): string {
+ const plainSlug = ({ name, modeId }: VariableCollectionMode) =>
+ tokenSlug(name) || `mode-${tokenSlug(modeId) || 'unnamed'}`
+ const taken = new Set<string>()
+ for (const candidate of collection.modes) {
+ const base = plainSlug(candidate)
+ let slug = base
+ for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`
+ if (candidate.modeId === mode.modeId) return slug
+ taken.add(slug)
+ }
+ return plainSlug(mode)
+}
+
+/** The scope a mode applies in when it names none: `[data-theme="dark"]` for Theme / Dark. */
+export function defaultModeCondition(
+ collection: VariableCollection,
+ mode: VariableCollectionMode
+): string {
+ return `[data-${tokenSlug(collection.name) || 'mode'}="${modeSlug(collection, mode)}"]`
+}
+
+function quoteString(value: string): string {
+ return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\a ')}"`
+}
+
+/** One mode's value as CSS, or why it has none. */
+function modeValue(
+ variable: Variable,
+ value: VariableValue | undefined,
+ modeId: string,
+ names: ReadonlyMap<string, string>
+): string | { issue: string } {
+ const expression = variable.expressions?.[modeId]
+ if (expression) return expression.css
+ if (value === undefined) return { issue: 'has no value in this mode' }
+ if (typeof value === 'object' && 'aliasId' in value) {
+ const target = names.get(value.aliasId)
+ return target ? `var(--${target})` : { issue: 'aliases a variable that does not exist' }
+ }
+ if (variable.type === 'COLOR' && typeof value === 'object') return cssColor(value)
+ if (variable.type === 'FLOAT' && typeof value === 'number')
+ return tokenNumberToCSS(value, variableUnit(variable))
+ if (variable.type === 'STRING' && typeof value === 'string')
+ return variableNamespace(variable) === 'font' ? value : quoteString(value)
+ if (variable.type === 'BOOLEAN') return { issue: 'is a boolean, which CSS has no value for' }
+ return { issue: 'has a value that does not match its type' }
+}
+
+function aliasTarget(value: VariableValue | undefined): string | undefined {
+ return typeof value === 'object' && 'aliasId' in value ? value.aliasId : undefined
+}
+
+function block(selector: string, declarations: Declaration[], indent = ''): string {
+ const body = declarations.map(({ name, value }) => `${indent} --${name}: ${value};`).join('\n')
+ return `${indent}${selector} {\n${body}\n${indent}}`
+}
+
+function modeBlock(scope: ModeScope): string {
+ const comment = `/* ${scope.collection.name}: ${scope.mode.name} */`
+ if (!isAtRuleCondition(scope.condition))
+ return `${comment}\n${block(scope.condition, scope.declarations)}`
+ return `${comment}\n${scope.condition} {\n${block(':root', scope.declarations, ' ')}\n}`
+}
+
+/** `@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));` */
+function customVariant(name: string, condition: string): string {
+ const body = isAtRuleCondition(condition) ? condition : `&:where(${condition}, ${condition} *)`
+ return `@custom-variant ${name} (${body});`
+}
+
+/** Variants are named after their mode, prefixed with the collection where two modes share a name. */
+function variantNames(scopes: ModeScope[]): string[] {
+ const plain = scopes.map(({ collection, mode }) => modeSlug(collection, mode))
+ return plain.map((name, index) => {
+ const shared = plain.filter((other) => other === name).length > 1
+ const collection = scopes[index]?.collection.name ?? ''
+ return shared ? `${tokenSlug(collection)}-${name}` : name
+ })
+}
+
+/**
+ * Variables as a stylesheet of custom properties. The default mode of every collection is the
+ * base set, in `:root` or, for Tailwind, in `@theme` when the token has a Tailwind namespace;
+ * every other mode overrides the values that differ, under its condition. Aliases stay `var()`
+ * references and are declared again in each mode that changes what they point to.
+ */
+export function buildTokenStylesheet(
+ source: TokenSource,
+ { format, include = () => true }: TokenStylesheetOptions,
+ validate: TokenValidator
+): TokenStylesheet {
+ const issues: TokenStylesheetIssue[] = []
+ const collections = [...source.variableCollections.values()]
+ const all = collections.flatMap((collection) =>
+ collection.variableIds.flatMap((id) => {
+ const variable = source.variables.get(id)
+ return variable ? [variable] : []
+ })
+ )
+ const names = variableCSSNames(all)
+ const variables = all.filter(include)
+ const defaultModeOf = (variable: Variable) =>
+ source.variableCollections.get(variable.collectionId)?.defaultModeId ?? ''
+
+ function declare(
+ variable: Variable,
+ modeId: string,
+ value: VariableValue | undefined
+ ): Declaration | undefined {
+ const name = names.get(variable.id) ?? variable.id
+ const css = modeValue(variable, value, modeId, names)
+ if (typeof css !== 'string') {
+ issues.push({ message: `${variable.name} ${css.issue}`, variableId: variable.id, modeId })
+ return undefined
+ }
+ if (!validate.declaration(name, css)) {
+ issues.push({
+ message: `${variable.name} is not a valid CSS declaration: --${name}: ${css}`,
+ variableId: variable.id,
+ modeId
+ })
+ return undefined
+ }
+ return { name, value: css }
+ }
+
+ const defaults = new Map<string, Declaration>()
+ const theme: Declaration[] = []
+ const root: Declaration[] = []
+ for (const variable of variables) {
+ const modeId = defaultModeOf(variable)
+ const declaration = declare(variable, modeId, variable.valuesByMode[modeId])
+ if (!declaration) continue
+ defaults.set(variable.id, declaration)
+ if (format === 'tailwind' && variableNamespace(variable) !== undefined) theme.push(declaration)
+ else root.push(declaration)
+ }
+
+ /**
+ * What a mode's scope declares: the collection's values that differ from its default, and every
+ * alias, in any collection, whose chain reaches one of them. Custom properties inherit as
+ * computed values, so `--primary: var(--blue)` resolved at `:root` would keep the old blue
+ * unless it is declared again where `--blue` changes.
+ */
+ function modeDeclarations(
+ collection: VariableCollection,
+ mode: VariableCollectionMode
+ ): Declaration[] {
+ const own = (variable: Variable) => variable.collectionId === collection.id
+ const valueIn = (variable: Variable) =>
+ own(variable)
+ ? (variable.valuesByMode[mode.modeId] ?? variable.valuesByMode[collection.defaultModeId])
+ : variable.valuesByMode[defaultModeOf(variable)]
+ const inMode = new Map<string, Declaration>()
+ const scoped = new Map<string, Declaration>()
+ for (const variable of variables.filter(own)) {
+ const declaration = declare(variable, mode.modeId, valueIn(variable))
+ if (!declaration) continue
+ inMode.set(variable.id, declaration)
+ if (declaration.value !== defaults.get(variable.id)?.value)
+ scoped.set(variable.id, declaration)
+ }
+ for (let grew = true; grew;) {
+ grew = false
+ for (const variable of variables) {
+ const target = aliasTarget(valueIn(variable))
+ if (scoped.has(variable.id) || !target || !scoped.has(target)) continue
+ const declaration = inMode.get(variable.id) ?? defaults.get(variable.id)
+ if (!declaration) continue
+ scoped.set(variable.id, declaration)
+ grew = true
+ }
+ }
+ return variables.flatMap((variable) => {
+ const declaration = scoped.get(variable.id)
+ return declaration ? [declaration] : []
+ })
+ }
+
+ const scopes: ModeScope[] = []
+ for (const collection of collections) {
+ for (const mode of collection.modes) {
+ if (mode.modeId === collection.defaultModeId) continue
+ const condition = mode.condition ?? defaultModeCondition(collection, mode)
+ if (!validate.condition(condition)) {
+ issues.push({
+ message: `${collection.name}: ${mode.name} has a condition that is not a selector or a @media, @supports or @container query: ${condition}`,
+ collectionId: collection.id,
+ modeId: mode.modeId
+ })
+ continue
+ }
+ const declarations = modeDeclarations(collection, mode)
+ if (declarations.length > 0) scopes.push({ collection, mode, condition, declarations })
+ }
+ }
+
+ const sections: string[] = []
+ if (theme.length > 0) sections.push(block('@theme', theme))
+ if (root.length > 0) sections.push(block(':root', root))
+ sections.push(...scopes.map(modeBlock))
+ if (format === 'tailwind' && scopes.length > 0) {
+ const variants = variantNames(scopes)
+ sections.push(
+ scopes
+ .map((scope, index) =>
+ customVariant(variants[index] ?? modeSlug(scope.collection, scope.mode), scope.condition)
+ )
+ .join('\n')
+ )
+ }
+ return { css: sections.length > 0 ? `${sections.join('\n\n')}\n` : '', issues }
+}
+
+/**
+ * Browsers check token strings with their own CSS parser. Elsewhere, in the CLI and MCP, the CSS
+ * object model package loads on first use; its browser build exports nothing, so it is never
+ * the browser path.
+ */
+async function tokenValidator(): Promise<TokenValidator> {
+ if (typeof CSSStyleSheet === 'function') return createTokenValidator(parseWithBrowser)
+ const headless = await import('./cssom-validator')
+ return headless.tokenValidator
+}
+
+export async function tokenStylesheet(
+ source: TokenSource,
+ options: TokenStylesheetOptions
+): Promise<TokenStylesheet> {
+ return buildTokenStylesheet(source, options, await tokenValidator())
+}
diff --git a/packages/dom-css/src/tokens/validate.ts b/packages/dom-css/src/tokens/validate.ts
new file mode 100644
index 000000000..6265aa955
--- /dev/null
+++ b/packages/dom-css/src/tokens/validate.ts
@@ -0,0 +1,68 @@
+import type { CSSStyleSheetLike } from '@acemir/cssom'
+
+type Parse = (cssText: string) => CSSStyleSheetLike
+
+const AT_RULES = ['@media', '@supports', '@container'] as const
+
+/** What a rule looks like to the checks below; the object model's own types are wider. */
+type ParsedRule = {
+ cssRules?: unknown[]
+ selectorText?: string
+ style?: { length: number; getPropertyValue(property: string): string }
+}
+
+function rules(sheet: CSSStyleSheetLike): ParsedRule[] {
+ return sheet.cssRules.filter(
+ (rule): rule is ParsedRule => typeof rule === 'object' && rule !== null
+ )
+}
+
+/**
+ * Token strings come from documents, so each one is parsed in place before it is written. A value
+ * or condition that closes its rule early parses to a different number of rules and fails.
+ */
+export function createTokenValidator(parse: Parse) {
+ 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
+ return (
+ parsed.length === 1 &&
+ rule.style?.length === 1 &&
+ rule.style.getPropertyValue(`--${name}`).trim() === value.trim() &&
+ (rule.cssRules?.length ?? 0) === 0
+ )
+ },
+
+ /** A selector, or a `@media`, `@supports` or `@container` prelude, that wraps exactly one rule. */
+ condition(condition: string): boolean {
+ const trimmed = condition.trim()
+ if (trimmed.startsWith('@')) {
+ if (
+ !AT_RULES.some((rule) => trimmed.startsWith(`${rule} `) || trimmed.startsWith(`${rule}(`))
+ )
+ return false
+ const parsed = rules(parse(`${trimmed}{:root{--t:0}}`))
+ return parsed.length === 1 && parsed[0]?.cssRules?.length === 1
+ }
+ const parsed = rules(parse(`${trimmed}{--t:0}`))
+ const [rule] = parsed
+ return (
+ parsed.length === 1 &&
+ typeof rule.selectorText === 'string' &&
+ rule.style?.length === 1 &&
+ (rule.cssRules?.length ?? 0) === 0
+ )
+ }
+ }
+}
+
+export type TokenValidator = ReturnType<typeof createTokenValidator>
+
+/** The browser's own CSS parser, through a constructable stylesheet. */
+export function parseWithBrowser(cssText: string): CSSStyleSheetLike {
+ const sheet = new CSSStyleSheet()
+ sheet.replaceSync(cssText)
+ return { cssRules: [...sheet.cssRules] }
+}
diff --git a/packages/dom-css/tests/tokens/names.test.ts b/packages/dom-css/tests/tokens/names.test.ts
index 7efdabfc5..92e971dc6 100644
--- a/packages/dom-css/tests/tokens/names.test.ts
+++ b/packages/dom-css/tests/tokens/names.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'
import {
deriveCSSName,
parseCSSName,
+ tokenSlug,
tokenNumberToCSS,
variableCSSNames,
variableUnit
@@ -43,10 +44,16 @@ describe('token CSS names', () => {
expect(deriveCSSName(token('Mixed', { scopes: ['GAP', 'CORNER_RADIUS'] }))).toBe('mixed')
})
- test('keep characters outside ASCII, which custom properties allow, and fall back for none', () => {
+ test('keep letters outside ASCII, which custom properties allow, and fall back for none', () => {
expect(deriveCSSName(token('Цвет/фон', { type: 'COLOR' }))).toBe('color-цвет-фон')
- expect(deriveCSSName(token('🎨', { type: 'COLOR' }))).toBe('color-🎨')
- expect(deriveCSSName(token('!!!', { type: 'COLOR' }))).toBe('color-token')
+ expect(deriveCSSName(token('🎨', { type: 'COLOR' }))).toBe('color-token')
+ })
+
+ test('keep digits on their word, as Tailwind keys do', () => {
+ expect(deriveCSSName(token('Text/2xl', { scopes: ['FONT_SIZE'] }))).toBe('text-2xl')
+ expect(deriveCSSName(token('Heading/H1', { scopes: ['FONT_SIZE'] }))).toBe('text-heading-h1')
+ expect(deriveCSSName(token('brandPrimary', { type: 'COLOR' }))).toBe('color-brand-primary')
+ expect(tokenSlug('M3')).toBe('m3')
})
test('read custom property names from code snippets only', () => {
diff --git a/packages/dom-css/tests/tokens/stylesheet.test.ts b/packages/dom-css/tests/tokens/stylesheet.test.ts
new file mode 100644
index 000000000..0a0f38982
--- /dev/null
+++ b/packages/dom-css/tests/tokens/stylesheet.test.ts
@@ -0,0 +1,265 @@
+import { describe, expect, test } from 'bun:test'
+
+import dedent from 'dedent'
+
+import { compileTailwindCSS } from '@open-pencil/dom-css'
+import { tokenStylesheet } from '@open-pencil/dom-css/export'
+import { SceneGraph, type Variable, type VariableValue } from '@open-pencil/scene-graph'
+
+const BLUE_500 = { r: 0.23, g: 0.51, b: 0.96, a: 1 }
+const BLUE_300 = { r: 0.58, g: 0.77, b: 0.99, a: 1 }
+const WHITE = { r: 1, g: 1, b: 1, a: 1 }
+const INK = { r: 0.07, g: 0.09, b: 0.15, a: 1 }
+
+function add(
+ graph: SceneGraph,
+ collectionId: string,
+ id: string,
+ name: string,
+ type: Variable['type'],
+ valuesByMode: Record<string, VariableValue>,
+ extra: Partial<Variable> = {}
+): void {
+ graph.addVariable({
+ id,
+ name,
+ type,
+ collectionId,
+ valuesByMode,
+ description: '',
+ hiddenFromPublishing: false,
+ ...extra
+ })
+}
+
+/** Primitives, a Theme with Light and Dark, and a Space collection with Compact. */
+function designSystem(): SceneGraph {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'primitives',
+ name: 'Primitives',
+ modes: [{ modeId: 'base', name: 'Base' }],
+ defaultModeId: 'base',
+ variableIds: []
+ })
+ add(graph, 'primitives', 'blue-500', 'Blue/500', 'COLOR', { base: BLUE_500 })
+ add(graph, 'primitives', 'blue-300', 'Blue/300', 'COLOR', { base: BLUE_300 })
+ graph.addCollection({
+ id: 'theme',
+ name: 'Theme',
+ modes: [
+ { modeId: 'light', name: 'Light' },
+ { modeId: 'dark', name: 'Dark' }
+ ],
+ defaultModeId: 'light',
+ variableIds: []
+ })
+ add(graph, 'theme', 'primary', 'Primary', 'COLOR', {
+ light: { aliasId: 'blue-500' },
+ dark: { aliasId: 'blue-300' }
+ })
+ add(graph, 'theme', 'surface', 'Surface', 'COLOR', { light: WHITE, dark: INK })
+ graph.addCollection({
+ id: 'space',
+ name: 'Space',
+ modes: [
+ { modeId: 'comfortable', name: 'Comfortable' },
+ { modeId: 'compact', name: 'Compact', condition: '@media (max-width: 640px)' }
+ ],
+ defaultModeId: 'comfortable',
+ variableIds: []
+ })
+ add(
+ graph,
+ 'space',
+ 'gutter',
+ 'Gutter',
+ 'FLOAT',
+ { comfortable: 24, compact: 16 },
+ { unit: 'rem', scopes: ['GAP'] }
+ )
+ add(
+ graph,
+ 'space',
+ 'page',
+ 'Page',
+ 'FLOAT',
+ { comfortable: 32, compact: 32 },
+ {
+ scopes: ['WIDTH_HEIGHT'],
+ expressions: { comfortable: { css: 'clamp(1rem, 4vw, 2rem)', resolved: 32 } }
+ }
+ )
+ return graph
+}
+
+describe('token stylesheet', () => {
+ test('writes defaults to :root and every other mode under its condition', async () => {
+ const { css, issues } = await tokenStylesheet(designSystem(), { format: 'css' })
+ expect(issues).toEqual([])
+ expect(css).toBe(
+ dedent`
+ :root {
+ --color-blue-500: #3B82F5;
+ --color-blue-300: #94C4FC;
+ --color-primary: var(--color-blue-500);
+ --color-surface: #FFFFFF;
+ --spacing-gutter: 1.5rem;
+ --spacing-page: clamp(1rem, 4vw, 2rem);
+ }
+
+ /* Theme: Dark */
+ [data-theme="dark"] {
+ --color-primary: var(--color-blue-300);
+ --color-surface: #121726;
+ }
+
+ /* Space: Compact */
+ @media (max-width: 640px) {
+ :root {
+ --spacing-gutter: 1rem;
+ --spacing-page: 32px;
+ }
+ }
+ ` + '\n'
+ )
+ })
+
+ test('declares an alias again where a mode changes what it points to', async () => {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'brand',
+ name: 'Brand',
+ modes: [
+ { modeId: 'acme', name: 'Acme' },
+ { modeId: 'globex', name: 'Globex' }
+ ],
+ defaultModeId: 'acme',
+ variableIds: []
+ })
+ add(graph, 'brand', 'accent', 'Accent', 'COLOR', { acme: BLUE_500, globex: INK })
+ graph.addCollection({
+ id: 'semantic',
+ name: 'Semantic',
+ modes: [{ modeId: 'one', name: 'One' }],
+ defaultModeId: 'one',
+ variableIds: []
+ })
+ add(graph, 'semantic', 'link', 'Link', 'COLOR', { one: { aliasId: 'accent' } })
+ add(graph, 'semantic', 'focus', 'Focus', 'COLOR', { one: { aliasId: 'link' } })
+
+ const { css } = await tokenStylesheet(graph, { format: 'css' })
+
+ expect(css).toContain(dedent`
+ [data-brand="globex"] {
+ --color-accent: #121726;
+ --color-link: var(--color-accent);
+ --color-focus: var(--color-link);
+ }
+ `)
+ })
+
+ test('name a mode with no letters or digits after its id, made safe for selectors', async () => {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'theme',
+ name: 'Theme',
+ modes: [
+ { modeId: '1:1', name: 'Day' },
+ { modeId: '1:2', name: '🌙' }
+ ],
+ defaultModeId: '1:1',
+ variableIds: []
+ })
+ add(graph, 'theme', 'surface', 'Surface', 'COLOR', { '1:1': WHITE, '1:2': INK })
+
+ const { css, issues } = await tokenStylesheet(graph, { format: 'tailwind' })
+
+ expect(issues).toEqual([])
+ expect(css).toContain('[data-theme="mode-1-2"] {')
+ expect(css).toContain(
+ '@custom-variant mode-1-2 (&:where([data-theme="mode-1-2"], [data-theme="mode-1-2"] *));'
+ )
+ })
+
+ test('numbers modes whose names slug alike, so neither overrides the other', async () => {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'theme',
+ name: 'Theme',
+ modes: [
+ { modeId: 'light', name: 'Light' },
+ { modeId: 'dark', name: 'Dark' },
+ { modeId: 'dark-alt', name: 'dark!' }
+ ],
+ defaultModeId: 'light',
+ variableIds: []
+ })
+ add(graph, 'theme', 'surface', 'Surface', 'COLOR', {
+ light: WHITE,
+ dark: INK,
+ 'dark-alt': BLUE_500
+ })
+
+ const { css, issues } = await tokenStylesheet(graph, { format: 'tailwind' })
+
+ expect(issues).toEqual([])
+ expect(css).toContain('[data-theme="dark"] {\n --color-surface: #121726;')
+ expect(css).toContain('[data-theme="dark-2"] {\n --color-surface: #3B82F5;')
+ expect(css).toContain('@custom-variant dark (')
+ expect(css).toContain('@custom-variant dark-2 (')
+ })
+
+ test('reports and skips what cannot be written as CSS', async () => {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'misc',
+ name: 'Misc',
+ modes: [
+ { modeId: 'a', name: 'A' },
+ { modeId: 'b', name: 'B', condition: '.x } body { display: none' }
+ ],
+ defaultModeId: 'a',
+ variableIds: []
+ })
+ add(graph, 'misc', 'flag', 'Flag', 'BOOLEAN', { a: true, b: false })
+ add(
+ graph,
+ 'misc',
+ 'gap',
+ 'Gap',
+ 'FLOAT',
+ { a: 8, b: 4 },
+ {
+ expressions: { a: { css: '1px; } body { display: none', resolved: 8 } }
+ }
+ )
+ add(graph, 'misc', 'label', 'Label', 'STRING', { a: 'Say "hi"', b: 'Bye' })
+
+ const { css, issues } = await tokenStylesheet(graph, { format: 'css' })
+
+ expect(css).toBe(':root {\n --label: "Say \\"hi\\"";\n}\n')
+ expect(issues.map((issue) => issue.message)).toEqual([
+ 'Flag is a boolean, which CSS has no value for',
+ 'Gap is not a valid CSS declaration: --gap: 1px; } body { display: none',
+ 'Misc: B has a condition that is not a selector or a @media, @supports or @container query: .x } body { display: none'
+ ])
+ })
+
+ test('puts namespaced tokens in @theme, so Tailwind generates utilities and mode variants', async () => {
+ const { css, issues } = await tokenStylesheet(designSystem(), { format: 'tailwind' })
+ expect(issues).toEqual([])
+ expect(css).toStartWith('@theme {\n --color-blue-500: #3B82F5;')
+ expect(css).toContain(
+ '@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));'
+ )
+ expect(css).toContain('@custom-variant compact (@media (max-width: 640px));')
+
+ const compiled = await compileTailwindCSS(['bg-primary', 'gap-gutter', 'dark:bg-surface'], {
+ css
+ })
+ expect(compiled).toContain('background-color: var(--color-primary)')
+ expect(compiled).toContain('gap: var(--spacing-gutter)')
+ expect(compiled).toMatch(/:where\(\[data-theme="dark"\], \[data-theme="dark"\] \*\)/)
+ })
+})
diff --git a/packages/vue/src/i18n/locales/de/variables.json b/packages/vue/src/i18n/locales/de/variables.json
index 9774cbb1b..cb41a69d3 100644
--- a/packages/vue/src/i18n/locales/de/variables.json
+++ b/packages/vue/src/i18n/locales/de/variables.json
@@ -9,5 +9,7 @@
"renameMode": "Modus umbenennen",
"duplicateMode": "Modus duplizieren",
"deleteMode": "Modus loeschen",
- "setDefaultMode": "Als Standard festlegen"
+ "setDefaultMode": "Als Standard festlegen",
+ "copyAsCSS": "Als CSS kopieren",
+ "copyAsTailwindTheme": "Als Tailwind-Theme kopieren"
}
diff --git a/packages/vue/src/i18n/locales/es/variables.json b/packages/vue/src/i18n/locales/es/variables.json
index 26c600af2..7f5e26b96 100644
--- a/packages/vue/src/i18n/locales/es/variables.json
+++ b/packages/vue/src/i18n/locales/es/variables.json
@@ -9,5 +9,7 @@
"renameMode": "Renombrar modo",
"duplicateMode": "Duplicar modo",
"deleteMode": "Eliminar modo",
- "setDefaultMode": "Establecer como predeterminado"
+ "setDefaultMode": "Establecer como predeterminado",
+ "copyAsCSS": "Copiar como CSS",
+ "copyAsTailwindTheme": "Copiar como tema de Tailwind"
}
diff --git a/packages/vue/src/i18n/locales/fr/variables.json b/packages/vue/src/i18n/locales/fr/variables.json
index f55ec9a82..e3640f4f7 100644
--- a/packages/vue/src/i18n/locales/fr/variables.json
+++ b/packages/vue/src/i18n/locales/fr/variables.json
@@ -9,5 +9,7 @@
"renameMode": "Renommer le mode",
"duplicateMode": "Dupliquer le mode",
"deleteMode": "Supprimer le mode",
- "setDefaultMode": "Définir par défaut"
+ "setDefaultMode": "Définir par défaut",
+ "copyAsCSS": "Copier en CSS",
+ "copyAsTailwindTheme": "Copier comme thème Tailwind"
}
diff --git a/packages/vue/src/i18n/locales/it/variables.json b/packages/vue/src/i18n/locales/it/variables.json
index 4e59306e7..855ec03b7 100644
--- a/packages/vue/src/i18n/locales/it/variables.json
+++ b/packages/vue/src/i18n/locales/it/variables.json
@@ -9,5 +9,7 @@
"renameMode": "Rinomina modalità",
"duplicateMode": "Duplica modalità",
"deleteMode": "Elimina modalità",
- "setDefaultMode": "Imposta come predefinita"
+ "setDefaultMode": "Imposta come predefinita",
+ "copyAsCSS": "Copia come CSS",
+ "copyAsTailwindTheme": "Copia come tema Tailwind"
}
diff --git a/packages/vue/src/i18n/locales/ja/variables.json b/packages/vue/src/i18n/locales/ja/variables.json
index 2efbd5619..6379d0176 100644
--- a/packages/vue/src/i18n/locales/ja/variables.json
+++ b/packages/vue/src/i18n/locales/ja/variables.json
@@ -9,5 +9,7 @@
"renameMode": "モードの名前を変更",
"duplicateMode": "モードを複製",
"deleteMode": "モードを削除",
- "setDefaultMode": "デフォルトに設定"
+ "setDefaultMode": "デフォルトに設定",
+ "copyAsCSS": "CSSとしてコピー",
+ "copyAsTailwindTheme": "Tailwindテーマとしてコピー"
}
diff --git a/packages/vue/src/i18n/locales/pl/variables.json b/packages/vue/src/i18n/locales/pl/variables.json
index 6a443014e..c914e20b9 100644
--- a/packages/vue/src/i18n/locales/pl/variables.json
+++ b/packages/vue/src/i18n/locales/pl/variables.json
@@ -9,5 +9,7 @@
"renameMode": "Zmień nazwę trybu",
"duplicateMode": "Duplikuj tryb",
"deleteMode": "Usuń tryb",
- "setDefaultMode": "Ustaw jako domyślny"
+ "setDefaultMode": "Ustaw jako domyślny",
+ "copyAsCSS": "Kopiuj jako CSS",
+ "copyAsTailwindTheme": "Kopiuj jako motyw Tailwind"
}
diff --git a/packages/vue/src/i18n/locales/ru/variables.json b/packages/vue/src/i18n/locales/ru/variables.json
index 210b29456..4162c6887 100644
--- a/packages/vue/src/i18n/locales/ru/variables.json
+++ b/packages/vue/src/i18n/locales/ru/variables.json
@@ -9,5 +9,7 @@
"renameMode": "Переименовать режим",
"duplicateMode": "Дублировать режим",
"deleteMode": "Удалить режим",
- "setDefaultMode": "Установить по умолчанию"
+ "setDefaultMode": "Установить по умолчанию",
+ "copyAsCSS": "Копировать как CSS",
+ "copyAsTailwindTheme": "Копировать как тему Tailwind"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/variables.json b/packages/vue/src/i18n/locales/zh-cn/variables.json
index 10c5b0732..eb18e5384 100644
--- a/packages/vue/src/i18n/locales/zh-cn/variables.json
+++ b/packages/vue/src/i18n/locales/zh-cn/variables.json
@@ -9,5 +9,7 @@
"renameMode": "重命名模式",
"duplicateMode": "复制模式",
"deleteMode": "删除模式",
- "setDefaultMode": "设为默认"
+ "setDefaultMode": "设为默认",
+ "copyAsCSS": "复制为 CSS",
+ "copyAsTailwindTheme": "复制为 Tailwind 主题"
}
diff --git a/packages/vue/src/i18n/messages/variables.ts b/packages/vue/src/i18n/messages/variables.ts
index a9012e2eb..d22dce18b 100644
--- a/packages/vue/src/i18n/messages/variables.ts
+++ b/packages/vue/src/i18n/messages/variables.ts
@@ -11,7 +11,9 @@ export const variablesMessageDefaults = {
renameMode: 'Rename mode',
duplicateMode: 'Duplicate mode',
deleteMode: 'Delete mode',
- setDefaultMode: 'Set as default'
+ setDefaultMode: 'Set as default',
+ copyAsCSS: 'Copy as CSS',
+ copyAsTailwindTheme: 'Copy as Tailwind theme'
} as const
export const variablesMessages = i18n('variables', variablesMessageDefaults)
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index 425f5278b..5df7bbe4d 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -54,6 +54,7 @@ Common commands:
- `find` — find nodes by name/type
- `query` — XPath selectors for node search
- `variables` — list variables and collections
+- `tokens` — variables as a CSS custom-property stylesheet or Tailwind v4 theme
- `export` — export PNG/JPG/WEBP/SVG/PDF/JSX/.fig
- `convert` — convert between supported document formats
- `analyze` — colors, typography, spacing, repeated clusters
@@ -77,6 +78,7 @@ openpencil node --id 1:23 # app mode
openpencil selection --json
openpencil variables design.fig
openpencil variables --collection "Colors" --type COLOR
+openpencil tokens design.fig --format tailwind > theme.css
```
### Search and XPath query
diff --git a/src/app/editor/canvas/menu/actions.ts b/src/app/editor/canvas/menu/actions.ts
index 0c01c2bd3..23b1ebc40 100644
--- a/src/app/editor/canvas/menu/actions.ts
+++ b/src/app/editor/canvas/menu/actions.ts
@@ -1,4 +1,3 @@
-import { useClipboard } from '@vueuse/core'
import type { Ref } from 'vue'
import { nodeToXPath } from '@open-pencil/core/xpath'
@@ -6,11 +5,10 @@ import { nodeToXPath } from '@open-pencil/core/xpath'
import type { EditorStore } from '@/app/editor/active-store'
import { pasteClipboardToReplace } from '@/app/editor/clipboard/paste-to-replace'
import { executeClipboardCommand } from '@/app/editor/clipboard/system'
+import { createTextClipboard } from '@/app/editor/clipboard/text'
import { canVectorizeImageNode, vectorizeImageNode } from '@/app/editor/vectorize'
import { notificationMessages } from '@/app/i18n/notifications'
import { toast } from '@/app/shell/ui'
-import { writeTauriClipboardText } from '@/app/tauri/clipboard'
-import { isTauri } from '@/app/tauri/env'
function toArrayBuffer(data: Uint8Array): ArrayBuffer {
const bytes = new Uint8Array(data.length)
@@ -19,7 +17,7 @@ function toArrayBuffer(data: Uint8Array): ArrayBuffer {
}
export function createCanvasMenuActions(store: EditorStore, selectedIds: Ref<Set<string>>) {
- const { copy } = useClipboard()
+ const copyText = createTextClipboard()
function ids() {
return [...selectedIds.value]
@@ -35,13 +33,7 @@ export function createCanvasMenuActions(store: EditorStore, selectedIds: Ref<Set
}
async function clipboardWrite(text: string | null, label: string) {
- if (!text) return
- if (isTauri()) {
- await writeTauriClipboardText(text)
- } else {
- await copy(text)
- }
- toast.info(notificationMessages.get().copiedAs({ format: label }))
+ if (text) await copyText(text, label)
}
async function copyNodeId() {
diff --git a/src/app/editor/clipboard/text.ts b/src/app/editor/clipboard/text.ts
new file mode 100644
index 000000000..bea6576b1
--- /dev/null
+++ b/src/app/editor/clipboard/text.ts
@@ -0,0 +1,31 @@
+import { useClipboard } from '@vueuse/core'
+
+import { notificationMessages } from '@/app/i18n/notifications'
+import { toast } from '@/app/shell/ui'
+import { writeTauriClipboardText } from '@/app/tauri/clipboard'
+import { isTauri } from '@/app/tauri/env'
+
+/** Copy text through the native clipboard on desktop and the browser's elsewhere, then confirm. */
+export function createTextClipboard() {
+ const { copy } = useClipboard()
+ return async function copyText(text: string, label: string): Promise<void> {
+ if (isTauri()) await writeTauriClipboardText(text)
+ else await copy(text)
+ toast.info(notificationMessages.get().copiedAs({ format: label }))
+ }
+}
+
+/**
+ * Copy text that is still being produced. Browsers accept a clipboard write only during the
+ * user's click, so the write starts at once with a promise of the text; awaiting the text first
+ * can outlast that window in Safari and Firefox. A rejected promise copies nothing.
+ */
+export async function copyPendingText(text: Promise<string>, label: string): Promise<void> {
+ if (isTauri()) {
+ await writeTauriClipboardText(await text)
+ } else {
+ const blob = text.then((value) => new Blob([value], { type: 'text/plain' }))
+ await navigator.clipboard.write([new ClipboardItem({ 'text/plain': blob })])
+ }
+ toast.info(notificationMessages.get().copiedAs({ format: label }))
+}
diff --git a/src/app/editor/tokens/copy.ts b/src/app/editor/tokens/copy.ts
new file mode 100644
index 000000000..bb916e8e0
--- /dev/null
+++ b/src/app/editor/tokens/copy.ts
@@ -0,0 +1,56 @@
+import { uniq } from 'es-toolkit/array'
+
+import type { TokenStylesheetFormat, TokenStylesheetIssue } from '@open-pencil/dom-css/export'
+
+import type { EditorStore } from '@/app/editor/active-store'
+import { copyPendingText } from '@/app/editor/clipboard/text'
+import { notificationMessages } from '@/app/i18n/notifications'
+import { toast } from '@/app/shell/ui'
+
+const FORMAT_LABELS: Record<TokenStylesheetFormat, string> = {
+ css: 'CSS',
+ tailwind: 'Tailwind CSS'
+}
+
+/** The variable, or the collection and mode, an issue is about. */
+function issueSubject(store: EditorStore, issue: TokenStylesheetIssue): string {
+ const variable = issue.variableId ? store.graph.variables.get(issue.variableId) : undefined
+ if (variable) return variable.name
+ const collection = issue.collectionId
+ ? store.graph.variableCollections.get(issue.collectionId)
+ : undefined
+ const mode = collection?.modes.find((candidate) => candidate.modeId === issue.modeId)
+ return collection && mode ? `${collection.name}: ${mode.name}` : issue.message
+}
+
+class NothingToCopyError extends Error {
+ constructor() {
+ super('No variables could be written as CSS')
+ this.name = 'NothingToCopyError'
+ }
+}
+
+/** Copy the document's variables as a stylesheet, and name what had to be left out. */
+export function createTokenCopy(store: EditorStore) {
+ return async function copyTokens(format: TokenStylesheetFormat): Promise<void> {
+ // The stylesheet generator and its CSS parser load only when someone copies tokens. The
+ // clipboard write starts before either is ready, while the click still allows it.
+ const stylesheet = import('@open-pencil/dom-css/export').then(({ tokenStylesheet }) =>
+ tokenStylesheet(store.graph, { format })
+ )
+ const css = stylesheet.then((result) => {
+ if (!result.css) throw new NothingToCopyError()
+ return result.css
+ })
+ try {
+ await copyPendingText(css, FORMAT_LABELS[format])
+ } catch (error) {
+ // An empty stylesheet rejects the pending text; the browser reports that as its own error.
+ if ((await stylesheet).css) throw error
+ }
+ const { issues } = await stylesheet
+ if (issues.length === 0) return
+ const names = uniq(issues.map((issue) => issueSubject(store, issue)))
+ toast.warning(notificationMessages.get().tokensLeftOut({ names: names.join(', ') }))
+ }
+}
diff --git a/src/app/i18n/notifications/index.ts b/src/app/i18n/notifications/index.ts
index 76656ce8e..4ad411fda 100644
--- a/src/app/i18n/notifications/index.ts
+++ b/src/app/i18n/notifications/index.ts
@@ -10,6 +10,7 @@ export const notificationMessageDefaults = {
clipboardMissingDesignData: 'Clipboard does not contain design data.',
clipboardAccessBlocked: 'Clipboard access is blocked in this browser context.',
copiedAs: params('Copied as {format}.'),
+ tokensLeftOut: params('Left out of the stylesheet: {names}.'),
nodeID: 'node ID',
nodeIDs: 'node IDs',
xPath: 'XPath',
diff --git a/src/app/i18n/notifications/locales/de.json b/src/app/i18n/notifications/locales/de.json
index 384a03f4f..a7db823e5 100644
--- a/src/app/i18n/notifications/locales/de.json
+++ b/src/app/i18n/notifications/locales/de.json
@@ -26,5 +26,6 @@
"deepLinkPickerDismissed": "Link abgebrochen: Es wurde keine Datei ausgewählt.",
"deepLinkCancelled": "Link abgebrochen: Erwartet wurde eine Datei mit der Endung „{file}“.",
"deepLinkNodeNotFound": "Ebene „{node}“ wurde in „{file}“ nicht gefunden.",
- "openQueuedFilesFailed": "Die an OpenPencil übergebenen Dateien konnten nicht geöffnet werden: {error}"
+ "openQueuedFilesFailed": "Die an OpenPencil übergebenen Dateien konnten nicht geöffnet werden: {error}",
+ "tokensLeftOut": "Nicht im Stylesheet enthalten: {names}."
}
diff --git a/src/app/i18n/notifications/locales/es.json b/src/app/i18n/notifications/locales/es.json
index 3c117106b..be7182f03 100644
--- a/src/app/i18n/notifications/locales/es.json
+++ b/src/app/i18n/notifications/locales/es.json
@@ -26,5 +26,6 @@
"deepLinkPickerDismissed": "Enlace cancelado: no se eligió ningún archivo.",
"deepLinkCancelled": "Enlace cancelado: se esperaba un archivo que terminara en «{file}».",
"deepLinkNodeNotFound": "No se encontró la capa «{node}» en «{file}».",
- "openQueuedFilesFailed": "No se pudieron abrir los archivos entregados a OpenPencil: {error}"
+ "openQueuedFilesFailed": "No se pudieron abrir los archivos entregados a OpenPencil: {error}",
+ "tokensLeftOut": "No incluido en la hoja de estilos: {names}."
}
diff --git a/src/app/i18n/notifications/locales/fr.json b/src/app/i18n/notifications/locales/fr.json
index 1c3ea26da..397b8bb87 100644
--- a/src/app/i18n/notifications/locales/fr.json
+++ b/src/app/i18n/notifications/locales/fr.json
@@ -26,5 +26,6 @@
"deepLinkPickerDismissed": "Lien annulé : aucun fichier n’a été choisi.",
"deepLinkCancelled": "Lien annulé : un fichier se terminant par « {file} » était attendu.",
"deepLinkNodeNotFound": "Le calque « {node} » est introuvable dans « {file} ».",
- "openQueuedFilesFailed": "Impossible d’ouvrir les fichiers transmis à OpenPencil : {error}"
+ "openQueuedFilesFailed": "Impossible d’ouvrir les fichiers transmis à OpenPencil : {error}",
+ "tokensLeftOut": "Non inclus dans la feuille de style : {names}."
}
diff --git a/src/app/i18n/notifications/locales/it.json b/src/app/i18n/notifications/locales/it.json
index 6f886d14a..1a467072c 100644
--- a/src/app/i18n/notifications/locales/it.json
+++ b/src/app/i18n/notifications/locales/it.json
@@ -26,5 +26,6 @@
"deepLinkPickerDismissed": "Link annullato: non è stato scelto alcun file.",
"deepLinkCancelled": "Link annullato: era atteso un file che termina con «{file}».",
"deepLinkNodeNotFound": "Il livello «{node}» non è stato trovato in «{file}».",
- "openQueuedFilesFailed": "Impossibile aprire i file passati a OpenPencil: {error}"
+ "openQueuedFilesFailed": "Impossibile aprire i file passati a OpenPencil: {error}",
+ "tokensLeftOut": "Esclusi dal foglio di stile: {names}."
}
diff --git a/src/app/i18n/notifications/locales/ja.json b/src/app/i18n/notifications/locales/ja.json
index 76a66069d..e9c64e195 100644
--- a/src/app/i18n/notifications/locales/ja.json
+++ b/src/app/i18n/notifications/locales/ja.json
@@ -26,5 +26,6 @@
"deepLinkPickerDismissed": "リンクをキャンセルしました。ファイルが選択されていません。",
"deepLinkCancelled": "リンクをキャンセルしました。「{file}」で終わるファイルが必要です。",
"deepLinkNodeNotFound": "「{file}」にレイヤー「{node}」が見つかりませんでした。",
- "openQueuedFilesFailed": "OpenPencil に渡されたファイルを開けませんでした: {error}"
+ "openQueuedFilesFailed": "OpenPencil に渡されたファイルを開けませんでした: {error}",
+ "tokensLeftOut": "スタイルシートに含まれていません: {names}"
}
diff --git a/src/app/i18n/notifications/locales/pl.json b/src/app/i18n/notifications/locales/pl.json
index 8a1ed39ec..80837d0eb 100644
--- a/src/app/i18n/notifications/locales/pl.json
+++ b/src/app/i18n/notifications/locales/pl.json
@@ -26,5 +26,6 @@
"deepLinkPickerDismissed": "Link anulowany: nie wybrano żadnego pliku.",
"deepLinkCancelled": "Link anulowany: oczekiwano pliku kończącego się na „{file}”.",
"deepLinkNodeNotFound": "Nie znaleziono warstwy „{node}” w „{file}”.",
- "openQueuedFilesFailed": "Nie udało się otworzyć plików przekazanych do OpenPencil: {error}"
+ "openQueuedFilesFailed": "Nie udało się otworzyć plików przekazanych do OpenPencil: {error}",
+ "tokensLeftOut": "Pominięte w arkuszu stylów: {names}."
}
diff --git a/src/app/i18n/notifications/locales/ru.json b/src/app/i18n/notifications/locales/ru.json
index 9d9243cf8..e7c53e96a 100644
--- a/src/app/i18n/notifications/locales/ru.json
+++ b/src/app/i18n/notifications/locales/ru.json
@@ -26,5 +26,6 @@
"deepLinkPickerDismissed": "Ссылка отменена: файл не выбран.",
"deepLinkCancelled": "Ссылка отменена: ожидался файл с окончанием «{file}».",
"deepLinkNodeNotFound": "Слой «{node}» не найден в «{file}».",
- "openQueuedFilesFailed": "Не удалось открыть файлы, переданные OpenPencil: {error}"
+ "openQueuedFilesFailed": "Не удалось открыть файлы, переданные OpenPencil: {error}",
+ "tokensLeftOut": "Не вошли в таблицу стилей: {names}."
}
diff --git a/src/app/i18n/notifications/locales/zh-cn.json b/src/app/i18n/notifications/locales/zh-cn.json
index 0ff48e37c..c20fc47db 100644
--- a/src/app/i18n/notifications/locales/zh-cn.json
+++ b/src/app/i18n/notifications/locales/zh-cn.json
@@ -26,5 +26,6 @@
"deepLinkPickerDismissed": "已取消链接:未选择任何文件。",
"deepLinkCancelled": "已取消链接:需要以“{file}”结尾的文件。",
"deepLinkNodeNotFound": "在“{file}”中未找到图层“{node}”。",
- "openQueuedFilesFailed": "无法打开传递给 OpenPencil 的文件:{error}"
+ "openQueuedFilesFailed": "无法打开传递给 OpenPencil 的文件:{error}",
+ "tokensLeftOut": "未写入样式表:{names}"
}
diff --git a/src/components/variables/VariablesDialog.vue b/src/components/variables/VariablesDialog.vue
index 62fecbc1b..96767eb0c 100644
--- a/src/components/variables/VariablesDialog.vue
+++ b/src/components/variables/VariablesDialog.vue
@@ -32,6 +32,8 @@ import IconX from '~icons/lucide/x'
import type { VariableType } from '@open-pencil/scene-graph'
import { variablesAddTestId, vTestId, useI18n, useVariablesEditor } 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 IconButton from '@/components/ui/button/IconButton.vue'
@@ -42,6 +44,7 @@ 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()
@@ -82,6 +85,8 @@ const variableTypes: Array<{
}
]
+const copyTokens = createTokenCopy(useEditorStore())
+
const ctx = useVariablesEditor({
colorInput: ColorInput,
icons: variableTypeIcons,
@@ -190,23 +195,40 @@ function resizeHandleClass(resizing: boolean) {
side="bottom"
:side-offset="4"
align="start"
- :class="menuCls.content"
+ :class="collectionMenuCls.content"
>
<DropdownMenuItem
- :class="menuCls.item"
+ :class="collectionMenuCls.item"
@select="ctx.startRenameCollection(ctx.activeCollectionId.value)"
>
- <icon-lucide-pencil :class="menuCls.icon" />
+ <icon-lucide-pencil :class="collectionMenuCls.icon" />
{{ variables.renameCollection }}
</DropdownMenuItem>
<DropdownMenuSeparator class="mx-1.5 my-1 h-px bg-border" />
<DropdownMenuItem
- :class="menuCls.item"
+ :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="menuCls.icon" />
+ <icon-lucide-trash-2 :class="collectionMenuCls.icon" />
{{ variables.deleteCollection }}
</DropdownMenuItem>
</DropdownMenuContent>
diff --git a/tests/e2e/dom-css/tokens.spec.ts b/tests/e2e/dom-css/tokens.spec.ts
new file mode 100644
index 000000000..d2cbfb22f
--- /dev/null
+++ b/tests/e2e/dom-css/tokens.spec.ts
@@ -0,0 +1,31 @@
+import { browserTokenStylesheet } from '#tests/helpers/dom-css-browser'
+
+import { expect, test } from '../fixtures'
+
+test.describe('@open-pencil/dom-css token stylesheet in a browser', () => {
+ test("checks token values and conditions with the browser's CSS parser", async ({ page }) => {
+ const { css, issues } = await browserTokenStylesheet(page)
+
+ expect(css).toBe(
+ [
+ ':root {',
+ ' --color-surface: #FFFFFF;',
+ ' --spacing-gutter: clamp(1rem, 4vw, 2rem);',
+ '}',
+ '',
+ '/* Theme: Dark */',
+ '[data-theme="dark"] {',
+ ' --color-surface: #000000;',
+ ' --spacing-gutter: 24px;',
+ // Gap's default value was left out, so its Dark value differs from an empty base.
+ ' --gap: 8px;',
+ '}',
+ ''
+ ].join('\n')
+ )
+ expect(issues).toEqual([
+ 'Gap is not a valid CSS declaration: --gap: 1px; } body { display: none',
+ 'Theme: Evil has a condition that is not a selector or a @media, @supports or @container query: .x } body { display: none'
+ ])
+ })
+})
diff --git a/tests/helpers/dom-css-browser.ts b/tests/helpers/dom-css-browser.ts
index 23dac25aa..bf0de3e82 100644
--- a/tests/helpers/dom-css-browser.ts
+++ b/tests/helpers/dom-css-browser.ts
@@ -16,6 +16,73 @@ async function ensureAppPage(page: Page) {
}
}
+/**
+ * The token stylesheet for a small theme, written in the page so values and conditions are
+ * checked by the browser's own CSS parser: valid ones kept, ones that close their rule left out.
+ */
+export async function browserTokenStylesheet(page: Page) {
+ await ensureAppPage(page)
+ return page.evaluate(
+ async ({ exportModule, graphModule }) => {
+ const { tokenStylesheet } = await import(exportModule)
+ const { SceneGraph } = await import(graphModule)
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'theme',
+ name: 'Theme',
+ modes: [
+ { modeId: 'light', name: 'Light' },
+ { modeId: 'dark', name: 'Dark' },
+ { modeId: 'evil', name: 'Evil', condition: '.x } body { display: none' }
+ ],
+ defaultModeId: 'light',
+ variableIds: []
+ })
+ const add = (id: string, name: string, type: string, values: object, extra = {}) =>
+ graph.addVariable({
+ id,
+ name,
+ type,
+ collectionId: 'theme',
+ valuesByMode: values,
+ description: '',
+ hiddenFromPublishing: false,
+ ...extra
+ })
+ add('surface', 'Surface', 'COLOR', {
+ light: { r: 1, g: 1, b: 1, a: 1 },
+ dark: { r: 0, g: 0, b: 0, a: 1 },
+ evil: { r: 1, g: 0, b: 0, a: 1 }
+ })
+ add(
+ 'gutter',
+ 'Gutter',
+ 'FLOAT',
+ { light: 24, dark: 24, evil: 24 },
+ {
+ scopes: ['GAP'],
+ expressions: { light: { css: 'clamp(1rem, 4vw, 2rem)', resolved: 24 } }
+ }
+ )
+ add(
+ 'gap',
+ 'Gap',
+ 'FLOAT',
+ { light: 8, dark: 8, evil: 8 },
+ {
+ expressions: { light: { css: '1px; } body { display: none', resolved: 8 } }
+ }
+ )
+ const { css, issues } = await tokenStylesheet(graph, { format: 'css' })
+ return { css, issues: issues.map((issue: { message: string }) => issue.message) }
+ },
+ {
+ exportModule: '/@id/@open-pencil/dom-css/export',
+ graphModule: '/@id/@open-pencil/scene-graph'
+ }
+ )
+}
+
export async function setStyledContent(page: Page, css: string, body: string) {
await page.setContent(`
<style>${css}</style>
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index ed194a1b0..084a0f2d2 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -140,6 +140,8 @@ ja:updates.downloading
ja:updates.installed
ja:updates.unavailable
ja:updates.upToDate
+ja:variables.copyAsCSS
+ja:variables.copyAsTailwindTheme
zh-cn:ai.apiKey
zh-cn:ai.apiType
zh-cn:ai.baseURL
@@ -279,3 +281,5 @@ zh-cn:updates.downloading
zh-cn:updates.installed
zh-cn:updates.unavailable
zh-cn:updates.upToDate
+zh-cn:variables.copyAsCSS
+zh-cn:variables.copyAsTailwindTheme