Skip to content

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

feat: import and export W3C design tokens (#964)

Danila Poyarkov7ee621ec417d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1a3db3497..294139da1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -55,6 +55,7 @@
- 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. The view glides after whoever you follow, a frame in their color and a “Following …” bar show whom you follow, and Escape, clicking, scrolling, zooming, or switching pages stops it. Your own agents, the AI chat and MCP clients alike, are followed automatically while they work; turn this off with the crosshair button at the top of the AI panel. Your own avatar renames your agents and leaves the room.
- See where AI agents are working: the built-in AI chat, ACP and Pi harness chats, and every MCP client each show a cursor whose outlined label shows a sparkle and a callsign such as *Fern*, at the layers they read or edit, and an MCP agent leaves when its session ends. While the chat streams JSX, its cursor moves through the elements as they appear and outlines them. People's and agents' cursors glide to each new position instead of jumping. In a shared room, collaborators see each other's agents in the color of the person running them.
- 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.
+- Import and export variables, text styles, and effect styles as W3C design tokens. **Export as design tokens** in the variables dialog's copy menu and `openpencil tokens --format dtcg --out <folder>` write one file per collection mode in the shape Figma imports, typography and shadow tokens for styles, and a DTCG resolver for tools such as Style Dictionary. **Import design tokens** reads files from Figma, a resolver with its files, Tokens Studio themes, or a zip of them, shows where each collection and mode goes before anything changes, updates variables and styles by name without deleting any, and undoes in one step; agents and MCP clients import with the `import_design_tokens` tool, and `design_to_tokens` takes `format: "dtcg"`.
- 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. Manually switched modes use an attribute named after the collection, such as `data-theme`, or one the collection names to match an existing codebase; it is saved in `.fig` files and used by exported code. 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.
- 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.
diff --git a/packages/cli/src/commands/tokens.ts b/packages/cli/src/commands/tokens.ts
index 923101dd8..27e2c6372 100644
--- a/packages/cli/src/commands/tokens.ts
+++ b/packages/cli/src/commands/tokens.ts
@@ -1,3 +1,6 @@
+import { mkdir, writeFile } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+
import { defineCommand } from 'citty'
import type { TokensResult } from '@open-pencil/core/rpc'
@@ -10,14 +13,20 @@ 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'
+ 'Print design variables as a stylesheet of CSS custom properties or a Tailwind v4 theme, or write them as W3C design token files'
},
args: {
...variableCommandArgs,
format: {
type: 'string',
- description: 'css (:root and mode scopes) or tailwind (@theme, mode scopes and variants)',
+ description:
+ 'css (:root and mode scopes), tailwind (@theme, mode scopes and variants), or dtcg (W3C design token files: one per collection mode, styles, and a resolver; needs --out)',
default: 'css'
+ },
+ out: {
+ type: 'string',
+ alias: 'o',
+ description: 'Folder to write dtcg token files into'
}
},
async run({ args }) {
@@ -33,13 +42,21 @@ export default defineCommand({
return
}
- if (data.tokenCount === 0) {
+ if (data.files) {
+ if (!args.out) throw new Error('The dtcg format writes several files: pass --out <folder>.')
+ for (const file of data.files) {
+ const path = join(args.out, file.path)
+ await mkdir(dirname(path), { recursive: true })
+ await writeFile(path, `${JSON.stringify(file.content, null, 2)}\n`)
+ }
+ console.error(`Wrote ${data.files.length} files to ${args.out}`)
+ } else 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.files) process.stdout.write(data.css)
if (data.issues.length > 0) {
console.error(
fmtList(
diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.ts
index 6fda698a4..a25f90dda 100644
--- a/packages/cli/src/headless.ts
+++ b/packages/cli/src/headless.ts
@@ -42,10 +42,11 @@ export function populateWholeDocument(graph: SceneGraph): boolean {
return changed
}
-function pageNameFromArgs(args: unknown): string | undefined {
+/** A string argument of an RPC command, such as its `page` or `format`. */
+function stringArg(args: unknown, key: string): string | undefined {
if (!args || typeof args !== 'object' || Array.isArray(args)) return undefined
- const page = (args as { page?: unknown }).page
- return typeof page === 'string' ? page : undefined
+ const value: unknown = Reflect.get(args, key)
+ return typeof value === 'string' ? value : undefined
}
function populateRequestedPage(graph: SceneGraph, pageName?: string): void {
@@ -56,12 +57,14 @@ function populateRequestedPage(graph: SceneGraph, pageName?: string): void {
export function prepareDocumentForRPC(graph: SceneGraph, command: string, args?: unknown): void {
if (command === 'pages' || command === 'variables') return
+ // A stylesheet holds only variables, which load with the document; pages can take minutes.
+ if (command === 'tokens' && stringArg(args, 'format') !== 'dtcg') return
if (command === 'tree') {
- populateRequestedPage(graph, pageNameFromArgs(args))
+ populateRequestedPage(graph, stringArg(args, 'page'))
return
}
if (command === 'find' || command === 'query') {
- const pageName = pageNameFromArgs(args)
+ const pageName = stringArg(args, 'page')
if (pageName) populateRequestedPage(graph, pageName)
else populateWholeDocument(graph)
return
diff --git a/packages/core/package.json b/packages/core/package.json
index cbd670838..407144098 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -118,6 +118,11 @@
"import": "./dist/io/formats/raster/index.js",
"default": "./dist/io/formats/raster/index.js"
},
+ "./io/formats/design-tokens": {
+ "types": "./dist/io/formats/design-tokens/index.d.ts",
+ "import": "./dist/io/formats/design-tokens/index.js",
+ "default": "./dist/io/formats/design-tokens/index.js"
+ },
"./io/formats/svg": {
"types": "./dist/io/formats/svg/index.d.ts",
"import": "./dist/io/formats/svg/index.js",
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index c271e60a9..b0d24c2b1 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -32,6 +32,7 @@ import { createClipboardActions } from './clipboard'
import { createColorSpaceActions } from './color-space'
import { createComponentSyncScheduler } from './component-sync'
import { createComponentActions } from './components'
+import { createDesignTokenActions } from './design-tokens'
import { createGraphEventSubscription } from './graph-events'
import { createGraphReadActions } from './graph-reads'
import { createGuideActions } from './guides'
@@ -250,6 +251,7 @@ export function createEditor(options?: EditorOptions) {
const text = createTextActions(ctx)
const nodes = createNodeActions(ctx)
const variables = createVariableActions(ctx)
+ const designTokens = createDesignTokenActions(ctx, variables, nodes)
const vectorize = createVectorizeActions(ctx)
const alignment = createAlignmentActions(ctx)
const preview = createPlayActions(ctx)
@@ -387,6 +389,7 @@ export function createEditor(options?: EditorOptions) {
// Variables
...variables,
+ ...designTokens,
// Text editing
...text,
diff --git a/packages/core/src/editor/design-tokens.ts b/packages/core/src/editor/design-tokens.ts
new file mode 100644
index 000000000..c926e5349
--- /dev/null
+++ b/packages/core/src/editor/design-tokens.ts
@@ -0,0 +1,88 @@
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+// Not the format's barrel: the editor always loads this file, and the exporter is loaded on demand.
+import {
+ applyTokenImport,
+ styleNodeProps,
+ styleNodeType,
+ type TokenImportResult,
+ type TokenImportTarget
+} from '#core/io/formats/design-tokens/apply'
+import type { TokenImportPlan } from '#core/io/formats/design-tokens/plan'
+
+import type { createNodeActions } from './nodes'
+import type { EditorContext } from './types'
+import type { createVariableActions } from './variables'
+
+type VariableActions = ReturnType<typeof createVariableActions>
+type NodeActions = ReturnType<typeof createNodeActions>
+
+export function createDesignTokenActions(
+ ctx: EditorContext,
+ variables: VariableActions,
+ nodes: NodeActions
+) {
+ /** A new style node, which redo makes again with the same ids so layers stay attached. */
+ function addStyle(
+ style: Parameters<TokenImportTarget['addStyle']>[0],
+ fields: Partial<SceneNode>
+ ) {
+ const node = ctx.graph.createNode(
+ styleNodeType(style),
+ ctx.state.currentPageId,
+ styleNodeProps(style, fields)
+ )
+ node.source.id = crypto.randomUUID()
+ const snapshot = structuredClone(node)
+ const parentId = node.parentId
+ ctx.undo.push({
+ label: 'Add style',
+ forward: () => {
+ ctx.graph.createNodeWithId(snapshot.id, snapshot.type, parentId, structuredClone(snapshot))
+ ctx.requestRender()
+ },
+ inverse: () => {
+ ctx.graph.deleteNode(snapshot.id)
+ ctx.requestRender()
+ }
+ })
+ return node
+ }
+
+ /** The import's changes made through the editor's actions, each one undoable. */
+ const target: Omit<TokenImportTarget, 'graph'> = {
+ addCollection: (name) => {
+ const collection = ctx.graph.createCollection(name)
+ variables.addCollection(collection)
+ return collection
+ },
+ addMode: (collectionId, name) => variables.addMode(collectionId, name),
+ renameMode: (collectionId, modeId, name) => variables.renameMode(collectionId, modeId, name),
+ setDefaultMode: (collectionId, modeId) => variables.setDefaultMode(collectionId, modeId),
+ setModeCondition: (collectionId, modeId, condition) =>
+ variables.setModeCondition(collectionId, modeId, condition),
+ setModeAttribute: (collectionId, name) => variables.setModeAttribute(collectionId, name),
+ addVariable: (planned, collectionId) => {
+ const variable = ctx.graph.createVariable(planned.name, planned.type, collectionId)
+ variables.addVariable(variable)
+ return variable
+ },
+ setValue: (variableId, modeId, value) =>
+ variables.updateVariableValue(variableId, modeId, value),
+ setTokenFields: (variableId, fields) => variables.updateVariableToken(variableId, fields),
+ addStyle,
+ updateNode: (nodeId, changes) => nodes.updateNodeWithUndo(nodeId, changes, 'Update style'),
+ bindVariable: (nodeId, field, variableId) => nodes.bindVariable(nodeId, field, variableId)
+ }
+
+ /** Applies an import plan as one undo step; nothing is deleted. */
+ function importDesignTokens(plan: TokenImportPlan): TokenImportResult {
+ return ctx.undo.runBatch('Import design tokens', () => {
+ const result = applyTokenImport({ ...target, graph: ctx.graph }, plan)
+ ctx.requestRender()
+ return result
+ })
+ }
+
+ return { importDesignTokens }
+}
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index f0c5063c9..bdb907a7f 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -23,6 +23,7 @@ export { resolvePlayState, type InstanceState } from './play/states'
export type { PlayState } from './play/actions'
export type { Editor } from './create'
export type { VariableTokenFields } from './variables'
+export type { TokenImportResult } from '#core/io/formats/design-tokens'
export { reapplyInstanceComponentProperties } from './components/properties'
export { createGuideActions } from './guides'
export { createTextActions } from './text'
diff --git a/packages/core/src/figma-api/effects.ts b/packages/core/src/figma-api/effects.ts
index 7d420268b..a71a299ab 100644
--- a/packages/core/src/figma-api/effects.ts
+++ b/packages/core/src/figma-api/effects.ts
@@ -107,6 +107,13 @@ export function parseFigmaEffects(value: unknown): Effect[] {
return result.output.map(toSceneEffect)
}
+/** `value` as scene effects when it holds valid Figma effects, or null. */
+export function tryParseFigmaEffects(value: unknown): Effect[] | null {
+ if (unsupportedEffect(value)) return null
+ const result = v.safeParse(effectsSchema, value)
+ return result.success ? result.output.map(toSceneEffect) : null
+}
+
function toSceneEffect(effect: FigmaEffect): Effect {
if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {
return {
diff --git a/packages/core/src/io/formats/design-tokens/apply.ts b/packages/core/src/io/formats/design-tokens/apply.ts
new file mode 100644
index 000000000..07b06ffe7
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/apply.ts
@@ -0,0 +1,318 @@
+import { compact } from 'es-toolkit/array'
+import { pick } from 'es-toolkit/object'
+import { isEmptyObject, isEqual } from 'es-toolkit/predicate'
+
+import {
+ findInstanceAncestor,
+ type CodeSyntaxPlatform,
+ type SceneGraph,
+ type SceneNode,
+ type TokenExpression,
+ type TokenUnit,
+ type Variable,
+ type VariableCollection,
+ type VariableScope,
+ type VariableValue
+} from '@open-pencil/scene-graph'
+import { copyEffects } from '@open-pencil/scene-graph/copy'
+import { randomHex } from '@open-pencil/scene-graph/random'
+
+import { reconcileVariableLayouts } from '#core/layout/variables'
+
+import type { AliasTarget, PlannedCollection, PlannedVariable, TokenImportPlan } from './plan'
+import type { PlannedStyle } from './plan-styles'
+
+/** Token fields an import sets; `undefined` clears one. */
+export interface ImportedTokenFields {
+ unit?: TokenUnit
+ scopes?: VariableScope[]
+ codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>
+ hiddenFromPublishing?: boolean
+ description?: string
+ expressions?: Record<string, TokenExpression>
+}
+
+/**
+ * The changes an import makes, so the editor can make them undoable and a headless document can
+ * make them directly. Each adds to or changes the document; none deletes.
+ */
+export interface TokenImportTarget {
+ graph: SceneGraph
+ addCollection(name: string): VariableCollection
+ addMode(collectionId: string, name: string): string | undefined
+ renameMode(collectionId: string, modeId: string, name: string): void
+ setDefaultMode(collectionId: string, modeId: string): void
+ setModeCondition(collectionId: string, modeId: string, condition: string): void
+ setModeAttribute(collectionId: string, name: string): void
+ addVariable(planned: PlannedVariable, collectionId: string): Variable
+ setValue(variableId: string, modeId: string, value: VariableValue): void
+ setTokenFields(variableId: string, fields: ImportedTokenFields): void
+ addStyle(style: PlannedStyle, fields: Partial<SceneNode>): SceneNode
+ updateNode(nodeId: string, changes: Partial<SceneNode>): void
+ bindVariable(nodeId: string, field: string, variableId: string): void
+}
+
+export interface TokenImportResult {
+ collectionIds: string[]
+ variableIds: string[]
+ styleNodeIds: string[]
+}
+
+/** Text fields a text style gives the layers that use it. */
+const TEXT_STYLE_FIELDS = [
+ 'fontFamily',
+ 'fontWeight',
+ 'italic',
+ 'fontSize',
+ 'lineHeight',
+ 'letterSpacing',
+ 'textDecoration',
+ 'textCase'
+] as const satisfies ReadonlyArray<keyof SceneNode>
+
+function targetCollection(target: TokenImportTarget, planned: PlannedCollection): string {
+ if (planned.target.kind === 'existing') return planned.target.collectionId
+ return target.addCollection(planned.target.name).id
+}
+
+/** Mode ids by planned mode: matched ones, a new collection's first renamed, or new ones. */
+function targetModes(
+ target: TokenImportTarget,
+ planned: PlannedCollection,
+ collectionId: string
+): string[] {
+ const collection = target.graph.variableCollections.get(collectionId)
+ let unclaimed = planned.target.kind === 'new' ? (collection?.defaultModeId ?? null) : null
+ const modeIds = planned.modes.map((mode) => {
+ if (mode.target.kind === 'existing') return mode.target.modeId
+ if (unclaimed) {
+ const modeId = unclaimed
+ unclaimed = null
+ target.renameMode(collectionId, modeId, mode.target.name)
+ return modeId
+ }
+ return target.addMode(collectionId, mode.target.name) ?? ''
+ })
+ planned.modes.forEach((mode, index) => {
+ if (mode.condition) target.setModeCondition(collectionId, modeIds[index], mode.condition)
+ })
+ if (planned.target.kind === 'new') {
+ const defaultIndex = planned.modes.findIndex((mode) => mode.isDefault)
+ if (defaultIndex > 0) target.setDefaultMode(collectionId, modeIds[defaultIndex])
+ if (planned.modeAttribute) target.setModeAttribute(collectionId, planned.modeAttribute)
+ }
+ return modeIds
+}
+
+function aliasId(target: AliasTarget, created: ReadonlyArray<ReadonlyArray<Variable>>) {
+ if (target.kind === 'variable') return target.variableId
+ return created.at(target.collection)?.at(target.variable)?.id
+}
+
+function plannedValue(
+ value: NonNullable<PlannedVariable['values'][number]>,
+ created: ReadonlyArray<ReadonlyArray<Variable>>
+): VariableValue | undefined {
+ if (value.kind === 'literal') return value.value
+ const id = aliasId(value.target, created)
+ return id ? { aliasId: id } : undefined
+}
+
+function applyVariables(target: TokenImportTarget, plan: TokenImportPlan) {
+ const collectionIds = plan.collections.map((planned) => targetCollection(target, planned))
+ const modeIds = plan.collections.map((planned, index) =>
+ targetModes(target, planned, collectionIds[index])
+ )
+ // Every variable exists before any value is set, so aliases can point at later ones.
+ const created = plan.collections.map((planned, index) =>
+ planned.variables.map((variable) =>
+ variable.existingId
+ ? (target.graph.variables.get(variable.existingId) ??
+ target.addVariable(variable, collectionIds[index]))
+ : target.addVariable(variable, collectionIds[index])
+ )
+ )
+ plan.collections.forEach((planned, collectionIndex) => {
+ planned.variables.forEach((variable, variableIndex) => {
+ const made = created[collectionIndex][variableIndex]
+ const modes = modeIds[collectionIndex]
+ variable.values.forEach((value, modeIndex) => {
+ const next = value && plannedValue(value, created)
+ const modeId = modes[modeIndex]
+ if (next !== undefined && modeId && !isEqual(made.valuesByMode[modeId], next))
+ target.setValue(made.id, modeId, next)
+ })
+ const expressions = Object.fromEntries(
+ variable.expressions.flatMap((css, modeIndex) => {
+ const resolved = made.valuesByMode[modes[modeIndex]]
+ return css && typeof resolved === 'number' ? [[modes[modeIndex], { css, resolved }]] : []
+ })
+ )
+ const fields: ImportedTokenFields = {
+ unit: variable.unit,
+ scopes: variable.scopes,
+ codeSyntax: variable.codeSyntax,
+ hiddenFromPublishing: variable.hiddenFromPublishing ?? false,
+ description: variable.description ?? made.description
+ }
+ if (Object.keys(expressions).length > 0) fields.expressions = expressions
+ target.setTokenFields(made.id, fields)
+ })
+ })
+ return { collectionIds, created }
+}
+
+/** The fields a style gives each layer that uses it, with the reference that keeps it attached. */
+function consumerPatch(style: SceneNode, kind: PlannedStyle['kind']): Partial<SceneNode> {
+ if (kind === 'EFFECT')
+ return { effects: copyEffects(style.effects), effectStyleId: style.source.id }
+ const fields: Partial<SceneNode> = { textStyleId: style.source.id }
+ for (const field of TEXT_STYLE_FIELDS) Object.assign(fields, { [field]: style[field] })
+ return fields
+}
+
+/** The fields of `changes` that differ from what `node` holds, or null when none do. */
+function changedFields(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode> | null {
+ const changed = Object.fromEntries(
+ Object.entries(changes).filter(([key, value]) => !isEqual(node[key as keyof SceneNode], value))
+ )
+ return isEmptyObject(changed) ? null : changed
+}
+
+/**
+ * Layers that use a style and hold its values themselves. Layers inside an instance follow their
+ * component instead, and changing them would make overrides of what should stay inherited.
+ */
+function refKeyOf(kind: PlannedStyle['kind']) {
+ return kind === 'TEXT' ? ('textStyleId' as const) : ('effectStyleId' as const)
+}
+
+function styleConsumers(graph: SceneGraph, style: SceneNode, kind: PlannedStyle['kind']) {
+ const refKey = refKeyOf(kind)
+ return [...graph.getAllNodes()].filter(
+ (node) =>
+ node[refKey] === style.source.id &&
+ node.id !== style.id &&
+ !findInstanceAncestor(graph, node.id)
+ )
+}
+
+function applyStyles(
+ target: TokenImportTarget,
+ plan: TokenImportPlan,
+ created: ReadonlyArray<ReadonlyArray<Variable>>
+): string[] {
+ return plan.styles.map((style) => {
+ const existing = style.existingNodeId ? target.graph.getNode(style.existingNodeId) : undefined
+ const node = existing ?? target.addStyle(style, { ...style.fields, name: style.name })
+ const own = existing && changedFields(existing, style.fields)
+ if (own) target.updateNode(node.id, own)
+ for (const [field, alias] of Object.entries(style.bindings)) {
+ const variableId = aliasId(alias, created)
+ if (variableId && node.boundVariables[field] !== variableId)
+ target.bindVariable(node.id, field, variableId)
+ }
+ if (own && node.source.id) {
+ const patch = consumerPatch(node, style.kind)
+ for (const consumer of styleConsumers(target.graph, node, style.kind)) {
+ const changes = changedFields(consumer, patch)
+ // The style reference always goes along, or changing styled fields would detach it.
+ if (changes)
+ target.updateNode(consumer.id, { ...changes, ...pick(patch, [refKeyOf(style.kind)]) })
+ }
+ }
+ return node.id
+ })
+}
+
+/**
+ * Applies an import plan: collections and modes first, then every variable, then their values,
+ * so an alias can point at a variable the same import adds, and last the styles, whose bindings
+ * and the layers that use them follow. Nothing is deleted.
+ */
+export function applyTokenImport(
+ target: TokenImportTarget,
+ plan: TokenImportPlan
+): TokenImportResult {
+ const { collectionIds, created } = applyVariables(target, plan)
+ const styleNodeIds = applyStyles(target, plan, created)
+ return {
+ collectionIds,
+ variableIds: compact(created.flat().map((variable) => variable.id)),
+ styleNodeIds
+ }
+}
+
+/** A style node: hidden from the layer list, found by its style id, as `.fig` styles are. */
+export function styleNodeProps(
+ style: PlannedStyle,
+ fields: Partial<SceneNode>
+): Partial<SceneNode> {
+ return { ...fields, sharedStyleType: style.kind, internalOnly: true }
+}
+
+export function styleNodeType(style: PlannedStyle) {
+ return style.kind === 'TEXT' ? ('TEXT' as const) : ('RECTANGLE' as const)
+}
+
+/** The changes made directly on a graph, without history. */
+function graphTokenImportTarget(
+ graph: SceneGraph,
+ pageId: string,
+ changed: Set<string>
+): TokenImportTarget {
+ const collection = (id: string) => graph.variableCollections.get(id)
+ return {
+ graph,
+ addCollection: (name) => graph.createCollection(name),
+ addMode: (collectionId, name) => graph.createMode(collectionId, name),
+ renameMode: (collectionId, modeId, name) => graph.renameMode(collectionId, modeId, name),
+ setDefaultMode: (collectionId, modeId) => graph.setDefaultMode(collectionId, modeId),
+ setModeCondition: (collectionId, modeId, condition) => {
+ const mode = collection(collectionId)?.modes.find((entry) => entry.modeId === modeId)
+ if (mode) mode.condition = condition
+ },
+ setModeAttribute: (collectionId, name) => {
+ const found = collection(collectionId)
+ if (found) found.modeAttribute = name
+ },
+ addVariable: (planned, collectionId) =>
+ graph.createVariable(planned.name, planned.type, collectionId),
+ setValue: (variableId, modeId, value) => {
+ const variable = graph.variables.get(variableId)
+ if (!variable) return
+ variable.valuesByMode[modeId] = structuredClone(value)
+ changed.add(variableId)
+ },
+ setTokenFields: (variableId, fields) => {
+ const variable = graph.variables.get(variableId)
+ if (!variable) return
+ for (const [key, value] of Object.entries(fields))
+ if (value === undefined) Reflect.deleteProperty(variable, key)
+ else Object.assign(variable, { [key]: structuredClone(value) })
+ },
+ addStyle: (style, fields) => {
+ const node = graph.createNode(styleNodeType(style), pageId, styleNodeProps(style, fields))
+ node.source.id = `style:${randomHex(12)}`
+ return node
+ },
+ updateNode: (nodeId, changes) => graph.updateNode(nodeId, changes),
+ bindVariable: (nodeId, field, variableId) => graph.bindVariable(nodeId, field, variableId)
+ }
+}
+
+/**
+ * Imports straight into a graph, for scripts, tools, and the CLI working on a document without
+ * an editor; the layers bound to variables whose values changed are resolved and laid out
+ * afterwards.
+ */
+export function importTokensIntoGraph(
+ graph: SceneGraph,
+ pageId: string,
+ plan: TokenImportPlan
+): TokenImportResult {
+ const changed = new Set<string>()
+ const result = applyTokenImport(graphTokenImportTarget(graph, pageId, changed), plan)
+ if (changed.size > 0) reconcileVariableLayouts(graph, { variables: changed })
+ return result
+}
diff --git a/packages/core/src/io/formats/design-tokens/decode.ts b/packages/core/src/io/formats/design-tokens/decode.ts
new file mode 100644
index 000000000..46f4df3bb
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/decode.ts
@@ -0,0 +1,286 @@
+import * as v from 'valibot'
+
+import {
+ CODE_SYNTAX_PLATFORMS,
+ ROOT_FONT_SIZE_PX,
+ TOKEN_UNITS,
+ VARIABLE_SCOPES,
+ type Color,
+ type CodeSyntaxPlatform,
+ type TokenUnit,
+ type VariableScope,
+ type VariableType
+} from '@open-pencil/scene-graph'
+import { parseDisplayableColor } from '@open-pencil/scene-graph/color'
+import { parseCSSNumber } from '@open-pencil/scene-graph/css'
+
+import type { ReadToken } from './read'
+import { OPENPENCIL_EXTENSION } from './types'
+
+/** A `{group.token}` reference, as its path segments. */
+export function referencePath(value: unknown): string[] | null {
+ if (typeof value !== 'string' || !value.startsWith('{') || !value.endsWith('}')) return null
+ const inner = value.slice(1, -1)
+ return inner && !/[{}]/.test(inner) ? inner.split('.') : null
+}
+
+/** CSS Color 4 spaces DTCG names, as `color()` takes them. */
+const PREDEFINED_SPACES = new Set([
+ 'srgb',
+ 'srgb-linear',
+ 'display-p3',
+ 'a98-rgb',
+ 'prophoto-rgb',
+ 'rec2020',
+ 'xyz-d65',
+ 'xyz-d50'
+])
+/** Spaces CSS writes as functions; HSL and HWB take percentages, as DTCG stores them. */
+const FUNCTION_SPACES: Record<string, (components: string[]) => string> = {
+ hsl: ([h, s, l]) => `hsl(${h} ${s}% ${l}%`,
+ hwb: ([h, w, b]) => `hwb(${h} ${w}% ${b}%`,
+ lab: (components) => `lab(${components.join(' ')}`,
+ lch: (components) => `lch(${components.join(' ')}`,
+ oklab: (components) => `oklab(${components.join(' ')}`,
+ oklch: (components) => `oklch(${components.join(' ')}`
+}
+
+const ColorObjectSchema = v.object({
+ colorSpace: v.string(),
+ components: v.pipe(v.array(v.union([v.number(), v.literal('none')])), v.length(3)),
+ alpha: v.optional(v.number()),
+ hex: v.optional(v.string())
+})
+
+/**
+ * A DTCG color in sRGB. The 2025.10 object form names its space; it is written as CSS and read
+ * by culori, then mapped into sRGB. Earlier drafts wrote any CSS color string, which reads the
+ * same way.
+ */
+export function decodeColor(value: unknown): Color | null {
+ if (typeof value === 'string') return parseDisplayableColor(value)
+ const parsed = v.safeParse(ColorObjectSchema, value)
+ if (!parsed.success) return null
+ const { colorSpace, components, alpha = 1, hex } = parsed.output
+ const parts = components.map(String)
+ const open = PREDEFINED_SPACES.has(colorSpace)
+ ? `color(${colorSpace} ${parts.join(' ')}`
+ : FUNCTION_SPACES[colorSpace]?.(parts)
+ if (!open) return hex ? parseDisplayableColor(hex) : null
+ return parseDisplayableColor(`${open} / ${alpha})`)
+}
+
+const DimensionSchema = v.object({ value: v.number(), unit: v.picklist(['px', 'rem']) })
+const DurationSchema = v.object({ value: v.number(), unit: v.picklist(['ms', 's']) })
+
+/** A length in canvas pixels and the unit it was written in. */
+export function decodeDimension(value: unknown): { value: number; unit: TokenUnit } | null {
+ const parsed = v.safeParse(DimensionSchema, value)
+ if (parsed.success) {
+ const { value: number, unit } = parsed.output
+ return { value: unit === 'rem' ? number * ROOT_FONT_SIZE_PX : number, unit }
+ }
+ const px = typeof value === 'string' ? parseCSSNumber(value) : null
+ if (px === null) return null
+ return {
+ value: px,
+ unit: typeof value === 'string' && value.trim().endsWith('rem') ? 'rem' : 'px'
+ }
+}
+
+/** Font weight keywords DTCG allows, by the weight they stand for. */
+const FONT_WEIGHTS: Record<string, number> = {
+ thin: 100,
+ hairline: 100,
+ 'extra-light': 200,
+ 'ultra-light': 200,
+ light: 300,
+ normal: 400,
+ regular: 400,
+ book: 400,
+ medium: 500,
+ 'semi-bold': 600,
+ 'demi-bold': 600,
+ bold: 700,
+ 'extra-bold': 800,
+ 'ultra-bold': 800,
+ black: 900,
+ heavy: 900,
+ 'extra-black': 950,
+ 'ultra-black': 950
+}
+
+export function decodeFontWeight(value: unknown): number | null {
+ if (typeof value === 'number') return value >= 1 && value <= 1000 ? value : null
+ return typeof value === 'string' ? (FONT_WEIGHTS[value.toLowerCase()] ?? null) : null
+}
+
+/** The most preferred family of a single name or a fallback list. */
+export function decodeFontFamily(value: unknown): string | null {
+ const first = Array.isArray(value) ? value[0] : value
+ return typeof first === 'string' && first.trim() ? first.trim() : null
+}
+
+const OwnFieldsSchema = v.object({
+ unit: v.optional(v.picklist(TOKEN_UNITS)),
+ expression: v.optional(v.string()),
+ scopes: v.optional(v.array(v.picklist(VARIABLE_SCOPES))),
+ codeSyntax: v.optional(v.record(v.picklist(CODE_SYNTAX_PLATFORMS), v.string())),
+ hiddenFromPublishing: v.optional(v.boolean())
+})
+const FigmaAliasSchema = v.object({
+ targetVariableName: v.optional(v.string()),
+ targetVariableSetName: v.optional(v.string())
+})
+
+/** A value that is the variable's own, or one it points at in another token. */
+export type DecodedValue =
+ | { kind: 'literal'; value: Color | number | string | boolean }
+ | { kind: 'alias'; path: readonly string[]; collection?: string; name?: string }
+
+/** What a token makes of a variable. An alias without a type takes its target's. */
+export interface DecodedVariable {
+ type: VariableType | undefined
+ value: DecodedValue
+ unit?: TokenUnit
+ expression?: string
+ scopes?: VariableScope[]
+ codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>
+ hiddenFromPublishing?: boolean
+ description?: string
+ /**
+ * Whether the token carries OpenPencil's own fields. Its unit, scopes, and code syntax then
+ * replace a variable's, missing ones included; other tools' tokens leave them as they are.
+ */
+ own: boolean
+}
+
+/** Why a token does not become a variable. */
+export type DecodeFailure = 'unsupported-type' | 'invalid-value'
+
+function isFigmaBoolean(token: ReadToken): boolean {
+ return token.extensions['com.figma.type'] === 'boolean'
+}
+
+/** A token's type as a variable type, or undefined for an alias that must take its target's. */
+export function variableTypeOf(token: ReadToken): VariableType | DecodeFailure | undefined {
+ switch (token.type) {
+ case 'color':
+ return 'COLOR'
+ case 'dimension':
+ case 'duration':
+ case 'fontWeight':
+ return 'FLOAT'
+ case 'number':
+ return isFigmaBoolean(token) ? 'BOOLEAN' : 'FLOAT'
+ case 'boolean':
+ return 'BOOLEAN'
+ case 'fontFamily':
+ case 'string':
+ return 'STRING'
+ case undefined:
+ return referencePath(token.value) ? undefined : 'unsupported-type'
+ default:
+ return 'unsupported-type'
+ }
+}
+
+type Literal = { value: Color | number | string | boolean; unit?: TokenUnit }
+
+/** A `number` token's value, or a boolean Figma writes as a number or as `true`/`false`. */
+function decodeNumber(token: ReadToken): Literal | null {
+ const { value } = token
+ if (isFigmaBoolean(token))
+ return typeof value === 'boolean' || value === 0 || value === 1
+ ? { value: Boolean(value) }
+ : null
+ return typeof value === 'number' && Number.isFinite(value) ? { value } : null
+}
+
+/**
+ * A literal's value in the unit its variable keeps: a duration written in seconds, as Figma
+ * requires, goes back into a variable that holds milliseconds.
+ */
+function valueInUnit(literal: Literal, unit: TokenUnit | undefined): Literal['value'] {
+ const { value } = literal
+ if (typeof value !== 'number') return value
+ if (literal.unit === 's' && unit === 'ms') return Number((value * 1000).toPrecision(12))
+ if (literal.unit === 'ms' && unit === 's') return Number((value / 1000).toPrecision(12))
+ return value
+}
+
+/** A literal in the shape its type takes, with the unit it was written in. */
+function decodeLiteral(token: ReadToken): Literal | null {
+ const { value } = token
+ switch (token.type) {
+ case 'color': {
+ const color = decodeColor(value)
+ return color && { value: color }
+ }
+ case 'dimension':
+ return decodeDimension(value)
+ case 'duration': {
+ const parsed = v.safeParse(DurationSchema, value)
+ return parsed.success ? parsed.output : null
+ }
+ case 'fontWeight': {
+ const weight = decodeFontWeight(value)
+ return weight === null ? null : { value: weight }
+ }
+ case 'fontFamily': {
+ const family = decodeFontFamily(value)
+ return family === null ? null : { value: family }
+ }
+ case 'boolean':
+ return typeof value === 'boolean' ? { value } : null
+ case 'number':
+ return decodeNumber(token)
+ case 'string':
+ return typeof value === 'string' ? { value } : null
+ default:
+ return null
+ }
+}
+
+/** Scopes a token type implies when the token does not list its own. */
+function impliedScopes(token: ReadToken): VariableScope[] | undefined {
+ if (token.type === 'fontFamily') return ['FONT_FAMILY']
+ if (token.type === 'fontWeight') return ['FONT_STYLE']
+ return undefined
+}
+
+/** A token as a variable value and OpenPencil's own token fields. */
+export function decodeVariableToken(token: ReadToken): DecodedVariable | DecodeFailure {
+ const type = variableTypeOf(token)
+ if (type === 'unsupported-type' || type === 'invalid-value') return type
+ const own = v.safeParse(OwnFieldsSchema, token.extensions[OPENPENCIL_EXTENSION])
+ const fields = own.success ? own.output : {}
+ const reference = referencePath(token.value)
+ let value: DecodedValue
+ let unit = fields.unit
+ if (reference) {
+ const figma = v.safeParse(FigmaAliasSchema, token.extensions['com.figma.aliasData'])
+ value = {
+ kind: 'alias',
+ path: reference,
+ collection: figma.success ? figma.output.targetVariableSetName : undefined,
+ name: figma.success ? figma.output.targetVariableName : undefined
+ }
+ } else {
+ const literal = decodeLiteral(token)
+ if (!literal) return 'invalid-value'
+ unit ??= literal.unit === 'px' ? undefined : literal.unit
+ value = { kind: 'literal', value: valueInUnit(literal, unit) }
+ }
+ return {
+ type,
+ value,
+ unit: type === 'FLOAT' ? unit : undefined,
+ expression: fields.expression,
+ scopes: fields.scopes ?? impliedScopes(token),
+ codeSyntax: fields.codeSyntax,
+ hiddenFromPublishing: fields.hiddenFromPublishing,
+ description: token.description,
+ own: own.success
+ }
+}
diff --git a/packages/core/src/io/formats/design-tokens/export.ts b/packages/core/src/io/formats/design-tokens/export.ts
new file mode 100644
index 000000000..8022c1166
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/export.ts
@@ -0,0 +1,234 @@
+import { compact } from 'es-toolkit/array'
+import { omitBy } from 'es-toolkit/object'
+import { isEmptyObject } from 'es-toolkit/predicate'
+
+import type {
+ SceneGraph,
+ Variable,
+ VariableCollection,
+ VariableCollectionMode
+} from '@open-pencil/scene-graph'
+
+import { fileSegment, placeTokens, tokenPath, tokenReference, tokenTree } from './paths'
+import { styleTokens, withOriginalName, type TokenReferences } from './styles'
+import {
+ OPENPENCIL_EXTENSION,
+ RESOLVER_VERSION,
+ type DesignToken,
+ type DesignTokenFile,
+ type DesignTokenIssue
+} from './types'
+import { literalTokenValue, variableTokenType } from './values'
+
+export interface DesignTokenExport {
+ files: DesignTokenFile[]
+ issues: DesignTokenIssue[]
+}
+
+/** The resolver document's file name, as DTCG recommends. */
+export const RESOLVER_FILE = 'tokens.resolver.json'
+/** The composite tokens' file, apart from the mode files because Figma's import refuses them. */
+export const STYLES_FILE = 'styles.tokens.json'
+
+/** Names made distinct by numbering repeats: `Theme`, `Theme 2`. */
+function distinct(names: readonly string[], reserved: readonly string[] = []): string[] {
+ const taken = new Set(reserved)
+ return names.map((name) => {
+ let candidate = name
+ for (let count = 2; taken.has(candidate); count++) candidate = `${name} ${count}`
+ taken.add(candidate)
+ return candidate
+ })
+}
+
+/** The resolver set that holds the styles file, a name no collection may take there. */
+const STYLES_SET = 'Styles'
+
+/** A JSON pointer segment: `~` and `/` are escaped as RFC 6901 requires. */
+function pointerSegment(name: string): string {
+ return name.replaceAll('~', '~0').replaceAll('/', '~1')
+}
+
+interface ExportContext {
+ graph: SceneGraph
+ references: TokenReferences
+ collectionOf: ReadonlyMap<string, VariableCollection>
+ issues: DesignTokenIssue[]
+}
+
+/** OpenPencil's own token fields, which DTCG has no place for. */
+function openPencilFields(variable: Variable, modeId: string) {
+ const fields = omitBy(
+ {
+ unit: variable.unit,
+ expression: variable.expressions?.[modeId]?.css,
+ scopes: variable.scopes,
+ codeSyntax: variable.codeSyntax,
+ hiddenFromPublishing: variable.hiddenFromPublishing || undefined
+ },
+ (value) => value === undefined
+ )
+ return isEmptyObject(fields) ? {} : { [OPENPENCIL_EXTENSION]: fields }
+}
+
+/**
+ * A variable's value in one mode as a token. An alias is a `{group.token}` reference; one to
+ * another collection also names its target in `com.figma.aliasData`, the way Figma resolves it.
+ */
+function variableToken(
+ context: ExportContext,
+ collection: VariableCollection,
+ mode: VariableCollectionMode,
+ variable: Variable
+): DesignToken | undefined {
+ const where = { collection: collection.name, mode: mode.name, token: variable.name }
+ if (!Object.hasOwn(variable.valuesByMode, mode.modeId)) {
+ context.issues.push({ kind: 'missing-value', ...where })
+ return undefined
+ }
+ const value = variable.valuesByMode[mode.modeId]
+ const figma: Record<string, unknown> = {}
+ let $value: unknown
+ if (typeof value === 'object' && 'aliasId' in value) {
+ const path = context.references.get(value.aliasId)
+ const target = context.graph.variables.get(value.aliasId)
+ const targetCollection = context.collectionOf.get(value.aliasId)
+ if (!path || !target || !targetCollection) {
+ context.issues.push({ kind: 'missing-alias', ...where })
+ return undefined
+ }
+ $value = tokenReference(path)
+ if (targetCollection.id !== collection.id)
+ figma['com.figma.aliasData'] = {
+ targetVariableName: target.name,
+ targetVariableSetName: targetCollection.name
+ }
+ } else {
+ $value = literalTokenValue(variable, value)
+ }
+ if (variable.type === 'BOOLEAN') figma['com.figma.type'] = 'boolean'
+ const $extensions = { ...figma, ...openPencilFields(variable, mode.modeId) }
+ const token: DesignToken = { $type: variableTokenType(variable), $value }
+ if (variable.description) token.$description = variable.description
+ if (!isEmptyObject($extensions)) token.$extensions = $extensions
+ return token
+}
+
+/** What a mode file says about its collection and mode, for OpenPencil to read back. */
+function modeExtension(collection: VariableCollection, mode: VariableCollectionMode) {
+ return {
+ [OPENPENCIL_EXTENSION]: omitBy(
+ {
+ collection: collection.name,
+ mode: mode.name,
+ default: mode.modeId === collection.defaultModeId,
+ condition: mode.condition,
+ modeAttribute: collection.modeAttribute
+ },
+ (value) => value === undefined
+ )
+ }
+}
+
+interface CollectionFiles {
+ collection: VariableCollection
+ name: string
+ modes: Array<{ name: string; path: string; isDefault: boolean }>
+}
+
+/** The resolver: one modifier per collection with several modes, one set per single-mode one. */
+function resolverDocument(collections: readonly CollectionFiles[], stylesPath: string | null) {
+ const sets: Record<string, unknown> = {}
+ const modifiers: Record<string, unknown> = {}
+ const resolutionOrder: Array<{ $ref: string }> = []
+ for (const { name, modes } of collections) {
+ if (modes.length === 1) {
+ sets[name] = { sources: [{ $ref: modes[0].path }] }
+ resolutionOrder.push({ $ref: `#/sets/${pointerSegment(name)}` })
+ continue
+ }
+ modifiers[name] = {
+ contexts: Object.fromEntries(modes.map((mode) => [mode.name, [{ $ref: mode.path }]])),
+ default: modes.find((mode) => mode.isDefault)?.name ?? modes[0].name
+ }
+ resolutionOrder.push({ $ref: `#/modifiers/${pointerSegment(name)}` })
+ }
+ if (stylesPath) {
+ sets[STYLES_SET] = { sources: [{ $ref: stylesPath }] }
+ resolutionOrder.push({ $ref: `#/sets/${STYLES_SET}` })
+ }
+ const resolver: Record<string, unknown> = { version: RESOLVER_VERSION }
+ if (!isEmptyObject(sets)) resolver.sets = sets
+ if (!isEmptyObject(modifiers)) resolver.modifiers = modifiers
+ resolver.resolutionOrder = resolutionOrder
+ return resolver
+}
+
+/**
+ * The document's variables and styles as W3C design tokens: one file per collection mode, which
+ * Figma imports as a mode, a file of typography and shadow tokens from text and effect styles,
+ * and a resolver document that combines them. OpenPencil's own fields ride in
+ * `$extensions["dev.openpencil"]`, so reading the export back loses nothing.
+ */
+export function exportDesignTokens(graph: SceneGraph): DesignTokenExport {
+ const issues: DesignTokenIssue[] = []
+ const collections = [...graph.variableCollections.values()]
+ const references = new Map<string, string[]>()
+ const collectionOf = new Map<string, VariableCollection>()
+ const placedByCollection = new Map<string, Array<{ variable: Variable; path: string[] }>>()
+ for (const collection of collections) {
+ const variables = compact(collection.variableIds.map((id) => graph.variables.get(id)))
+ const { placed, duplicates } = placeTokens(
+ variables.map((variable) => ({ key: variable, path: tokenPath(variable.name) }))
+ )
+ for (const variable of duplicates)
+ issues.push({ kind: 'duplicate-path', collection: collection.name, token: variable.name })
+ placedByCollection.set(
+ collection.id,
+ [...placed].map(([variable, path]) => ({ variable, path }))
+ )
+ for (const [variable, path] of placed) {
+ references.set(variable.id, path)
+ collectionOf.set(variable.id, collection)
+ }
+ }
+ const context: ExportContext = { graph, references, collectionOf, issues }
+ const files: DesignTokenFile[] = []
+ const styles = styleTokens(graph, references)
+ issues.push(...styles.issues)
+ const stylesPath = styles.tokens.length > 0 ? STYLES_FILE : null
+ const folders = distinct(collections.map((collection) => fileSegment(collection.name)))
+ const collectionNames = distinct(
+ collections.map((collection) => collection.name),
+ stylesPath ? [STYLES_SET] : []
+ )
+ const collectionFiles = collections.map((collection, index): CollectionFiles => {
+ const fileNames = distinct(collection.modes.map((mode) => fileSegment(mode.name)))
+ const modeNames = distinct(collection.modes.map((mode) => mode.name))
+ const modes = collection.modes.map((mode, modeIndex) => {
+ const path = `${folders[index]}/${fileNames[modeIndex]}.tokens.json`
+ const tokens = (placedByCollection.get(collection.id) ?? []).flatMap(
+ ({ variable, path: tokenAt }) => {
+ const token = variableToken(context, collection, mode, variable)
+ return token
+ ? [{ path: tokenAt, token: withOriginalName(token, variable.name, tokenAt) }]
+ : []
+ }
+ )
+ files.push({
+ path,
+ content: { ...tokenTree(tokens), $extensions: modeExtension(collection, mode) }
+ })
+ return {
+ name: modeNames[modeIndex],
+ path,
+ isDefault: mode.modeId === collection.defaultModeId
+ }
+ })
+ return { collection, name: collectionNames[index], modes }
+ })
+ if (stylesPath) files.push({ path: stylesPath, content: tokenTree(styles.tokens) })
+ if (files.length > 0)
+ files.push({ path: RESOLVER_FILE, content: resolverDocument(collectionFiles, stylesPath) })
+ return { files, issues }
+}
diff --git a/packages/core/src/io/formats/design-tokens/index.ts b/packages/core/src/io/formats/design-tokens/index.ts
new file mode 100644
index 000000000..b913da308
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/index.ts
@@ -0,0 +1,46 @@
+export { exportDesignTokens, RESOLVER_FILE, STYLES_FILE, type DesignTokenExport } from './export'
+export {
+ designTokenIssueMessage,
+ OPENPENCIL_EXTENSION,
+ RESOLVER_VERSION,
+ type DesignToken,
+ type DesignTokenFile,
+ type DesignTokenGroup,
+ type DesignTokenIssue,
+ type DesignTokenType
+} from './types'
+export {
+ readDesignTokens,
+ type DesignTokenBundle,
+ type DesignTokenReadIssue,
+ type DesignTokenSourceFile,
+ type ReadCollection,
+ type ReadMode,
+ type ReadToken
+} from './read'
+export {
+ defaultTokenImportOptions,
+ planTokenImport,
+ type AliasTarget,
+ type CollectionImportChoice,
+ type CollectionTarget,
+ type ImportSkip,
+ type ImportSkipReason,
+ type ModeTarget,
+ type PlannedCollection,
+ type PlannedMode,
+ type PlannedValue,
+ type PlannedVariable,
+ type TokenImportOptions,
+ type TokenImportPlan
+} from './plan'
+export type { PlannedStyle } from './plan-styles'
+export {
+ applyTokenImport,
+ importTokensIntoGraph,
+ styleNodeProps,
+ styleNodeType,
+ type ImportedTokenFields,
+ type TokenImportResult,
+ type TokenImportTarget
+} from './apply'
diff --git a/packages/core/src/io/formats/design-tokens/paths.ts b/packages/core/src/io/formats/design-tokens/paths.ts
new file mode 100644
index 000000000..9c6e6ea21
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/paths.ts
@@ -0,0 +1,88 @@
+import { compact } from 'es-toolkit/array'
+import { isPlainObject } from 'es-toolkit/predicate'
+
+/**
+ * A name segment as a DTCG token name, which cannot hold `{`, `}`, or `.`, nor start with `$`:
+ * those characters become `-`. A name that changed keeps its original in OpenPencil's extension.
+ */
+function tokenSegment(segment: string): string {
+ return segment.replaceAll(/[{}.]/g, '-').replace(/^\$+/, '') || 'token'
+}
+
+/** `Brand/Primary` as the token path `["Brand", "Primary"]`. */
+export function tokenPath(name: string): string[] {
+ const segments = compact(name.split('/').map((segment) => segment.trim())).map(tokenSegment)
+ return segments.length > 0 ? segments : ['token']
+}
+
+/** A token path back as a layer-panel name: `["Brand", "Primary"]` is `Brand/Primary`. */
+export function pathName(path: readonly string[]): string {
+ return path.filter((segment) => segment !== '$root').join('/')
+}
+
+/**
+ * A name as a file name: path separators and characters file systems refuse become `-`, and
+ * leading dots go, so no name such as `..` reaches outside the export's folder.
+ */
+export function fileSegment(name: string): string {
+ // eslint-disable-next-line no-control-regex -- Control characters are what file systems refuse.
+ const safe = name.replaceAll(/[/\\:*?"<>|\u0000-\u001F]/g, '-').replace(/^[.\s]+/, '')
+ return safe.trim() || 'Untitled'
+}
+
+/** Where each entry sits in the tree, by key: a path that is also a group's sits at `$root`. */
+export interface TokenPlacement<Key> {
+ placed: Map<Key, string[]>
+ /** Entries whose path another entry already took. */
+ duplicates: Key[]
+}
+
+/**
+ * Places tokens by path. DTCG has no token that is also a group, so a token whose path other
+ * tokens extend, such as `Space` beside `Space/Small`, becomes that group's `$root` token.
+ */
+export function placeTokens<Key>(
+ entries: ReadonlyArray<{ key: Key; path: readonly string[] }>
+): TokenPlacement<Key> {
+ const groups = new Set<string>()
+ for (const { path } of entries)
+ for (let length = 1; length < path.length; length++)
+ groups.add(path.slice(0, length).join('\u0000'))
+ const placed = new Map<Key, string[]>()
+ const taken = new Set<string>()
+ const duplicates: Key[] = []
+ for (const { key, path } of entries) {
+ const position = groups.has(path.join('\u0000')) ? [...path, '$root'] : [...path]
+ const id = position.join('\u0000')
+ if (taken.has(id)) {
+ duplicates.push(key)
+ continue
+ }
+ taken.add(id)
+ placed.set(key, position)
+ }
+ return { placed, duplicates }
+}
+
+/** Nests tokens into groups by their placed paths. */
+export function tokenTree(
+ tokens: ReadonlyArray<{ path: readonly string[]; token: unknown }>
+): Record<string, unknown> {
+ const root: Record<string, unknown> = {}
+ for (const { path, token } of tokens) {
+ let group = root
+ for (const segment of path.slice(0, -1)) {
+ const next = group[segment]
+ const child: Record<string, unknown> = isPlainObject(next) ? next : {}
+ group[segment] = child
+ group = child
+ }
+ group[path.at(-1) ?? 'token'] = token
+ }
+ return root
+}
+
+/** A `{group.token}` reference to a placed path. */
+export function tokenReference(path: readonly string[]): string {
+ return `{${path.join('.')}}`
+}
diff --git a/packages/core/src/io/formats/design-tokens/plan-styles.ts b/packages/core/src/io/formats/design-tokens/plan-styles.ts
new file mode 100644
index 000000000..0bb456325
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/plan-styles.ts
@@ -0,0 +1,236 @@
+import { isEqual, isPlainObject } from 'es-toolkit/predicate'
+import * as v from 'valibot'
+
+import {
+ getSharedStyles,
+ type Color,
+ type Effect,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import { tryParseFigmaEffects } from '#core/figma-api/effects'
+
+import {
+ decodeColor,
+ decodeDimension,
+ decodeFontFamily,
+ decodeFontWeight,
+ referencePath
+} from './decode'
+import type { AliasTarget, ImportSkip, ResolvedReference } from './plan'
+import type { DesignTokenBundle, ReadToken } from './read'
+import { isShadow, shadowTokenValue, typographyValue } from './styles'
+import { OPENPENCIL_EXTENSION } from './types'
+
+/** A text or effect style the import makes or updates. */
+export interface PlannedStyle {
+ kind: 'TEXT' | 'EFFECT'
+ name: string
+ /** The style updated, or null for one the import makes. */
+ existingNodeId: string | null
+ fields: Partial<SceneNode>
+ /** Text style fields bound to variables. */
+ bindings: Partial<Record<TextBindingField, AliasTarget>>
+}
+
+type TextBindingField = 'fontFamily' | 'fontSize' | 'letterSpacing' | 'lineHeight'
+const TEXT_BINDING_FIELDS: readonly TextBindingField[] = [
+ 'fontFamily',
+ 'fontSize',
+ 'letterSpacing',
+ 'lineHeight'
+]
+
+const OwnTextSchema = v.object({
+ text: v.object({
+ fontFamily: v.string(),
+ fontWeight: v.number(),
+ italic: v.boolean(),
+ fontSize: v.number(),
+ lineHeight: v.nullable(v.number()),
+ letterSpacing: v.number(),
+ textDecoration: v.picklist(['NONE', 'UNDERLINE', 'STRIKETHROUGH']),
+ textCase: v.picklist(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'])
+ }),
+ bindings: v.optional(v.record(v.string(), v.string()))
+})
+const OwnEffectsSchema = v.object({ effects: v.array(v.unknown()) })
+
+/** The composite types that become styles. */
+const STYLE_KINDS: Partial<Record<string, PlannedStyle['kind']>> = {
+ typography: 'TEXT',
+ shadow: 'EFFECT'
+}
+
+type Resolve = (path: readonly string[]) => ResolvedReference | undefined
+type Alias = (path: readonly string[]) => AliasTarget | undefined
+
+/** A field's value: its own, or what the token it references holds, decoded the same way. */
+function fieldValue<T>(
+ raw: unknown,
+ resolve: Resolve,
+ decode: (value: unknown) => T | null
+): T | null {
+ const path = referencePath(raw)
+ if (!path) return decode(raw)
+ const resolved = resolve(path)
+ if (!resolved) return null
+ return decode(resolved.kind === 'token' ? resolved.token.value : resolved.value)
+}
+
+const pixels = (value: unknown) =>
+ typeof value === 'number' ? value : (decodeDimension(value)?.value ?? null)
+
+/**
+ * OpenPencil's own fields for a style token, while its `$value` still says what they would write.
+ * Other tools keep extensions they do not read, so a `$value` edited there no longer matches, and
+ * the edit wins over the exact fields.
+ */
+function ownText(token: ReadToken) {
+ const own = v.safeParse(OwnTextSchema, token.extensions[OPENPENCIL_EXTENSION])
+ if (!own.success) return null
+ const { text, bindings = {} } = own.output
+ return { ...own.output, current: isEqual(token.value, typographyValue(text, bindings)) }
+}
+
+/** A typography token as text style fields, preferring the exact fields OpenPencil wrote. */
+function textFields(token: ReadToken, resolve: Resolve): Partial<SceneNode> | null {
+ const own = ownText(token)
+ if (own?.current) return { ...own.text }
+ const fields = decodedTextFields(token, resolve)
+ // Italic, decoration, and case have no place in `$value`, so the extension's still apply.
+ return fields && own ? { ...own.text, ...fields } : fields
+}
+
+function decodedTextFields(token: ReadToken, resolve: Resolve): Partial<SceneNode> | null {
+ if (!isPlainObject(token.value)) return null
+ const value = token.value
+ const fontFamily = fieldValue(value.fontFamily, resolve, decodeFontFamily)
+ const fontSize = fieldValue(value.fontSize, resolve, pixels)
+ if (fontFamily === null || fontSize === null) return null
+ const multiplier = fieldValue(value.lineHeight, resolve, (raw) =>
+ typeof raw === 'number' ? raw : null
+ )
+ const lineHeightPx = multiplier === null ? fieldValue(value.lineHeight, resolve, pixels) : null
+ return {
+ fontFamily,
+ fontSize,
+ fontWeight: fieldValue(value.fontWeight, resolve, decodeFontWeight) ?? 400,
+ lineHeight: multiplier !== null ? multiplier * fontSize : lineHeightPx,
+ letterSpacing: fieldValue(value.letterSpacing, resolve, pixels) ?? 0
+ }
+}
+
+/** Text style fields bound to variables: OpenPencil's recorded bindings, or the token's references. */
+function textBindings(token: ReadToken, alias: Alias): PlannedStyle['bindings'] {
+ const own = ownText(token)
+ let references: Record<string, unknown> = {}
+ if (own?.current) references = own.bindings ?? {}
+ else if (isPlainObject(token.value)) references = token.value
+ const bindings: PlannedStyle['bindings'] = {}
+ for (const field of TEXT_BINDING_FIELDS) {
+ const path = referencePath(references[field])
+ const target = path && alias(path)
+ if (target) bindings[field] = target
+ }
+ return bindings
+}
+
+/** One shadow of a shadow token, or the shadows a referenced shadow token holds. */
+function shadowEffects(raw: unknown, resolve: Resolve, depth = 0): Effect[] | null {
+ const path = referencePath(raw)
+ if (path) {
+ const resolved = depth < 16 ? resolve(path) : undefined
+ return resolved?.kind === 'token' ? shadowList(resolved.token.value, resolve, depth + 1) : null
+ }
+ if (!isPlainObject(raw)) return null
+ const color = fieldValue<Color>(raw.color, resolve, (value) =>
+ isPlainObject(value) && typeof value.r === 'number' ? (value as Color) : decodeColor(value)
+ )
+ const length = (key: string) => fieldValue(raw[key], resolve, pixels) ?? 0
+ if (!color) return null
+ return [
+ {
+ type: raw.inset === true ? 'INNER_SHADOW' : 'DROP_SHADOW',
+ color,
+ offset: { x: length('offsetX'), y: length('offsetY') },
+ radius: length('blur'),
+ spread: length('spread'),
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ ]
+}
+
+function shadowList(value: unknown, resolve: Resolve, depth = 0): Effect[] | null {
+ const entries = Array.isArray(value) ? value : [value]
+ const effects: Effect[] = []
+ for (const entry of entries) {
+ const shadows = shadowEffects(entry, resolve, depth)
+ if (!shadows) return null
+ effects.push(...shadows)
+ }
+ return effects.length > 0 ? effects : null
+}
+
+/**
+ * Shadows edited in another tool, in place of the visible shadows OpenPencil wrote. Effects
+ * `$value` cannot hold, such as blurs and hidden shadows, keep their places; extra shadows go last.
+ */
+function replaceShadows(exact: readonly Effect[], shadows: readonly Effect[]): Effect[] {
+ const queue = [...shadows]
+ const effects = exact.flatMap((effect) => {
+ if (!isShadow(effect) || !effect.visible) return [effect]
+ const next = queue.shift()
+ return next ? [next] : []
+ })
+ return [...effects, ...queue]
+}
+
+/** A shadow token as effects, preferring the exact effects OpenPencil wrote. */
+function effectFields(token: ReadToken, resolve: Resolve): Partial<SceneNode> | null {
+ const own = v.safeParse(OwnEffectsSchema, token.extensions[OPENPENCIL_EXTENSION])
+ // Extension effects that do not read fall back to the token's own shadows.
+ const exact = own.success ? tryParseFigmaEffects(own.output.effects) : null
+ if (exact && isEqual(token.value, shadowTokenValue(exact))) return { effects: exact }
+ const shadows = shadowList(token.value, resolve)
+ if (!shadows) return null
+ return { effects: exact ? replaceShadows(exact, shadows) : shadows }
+}
+
+/** Typography tokens as text styles and shadow tokens as effect styles, matched by name. */
+export function planStyles(
+ graph: SceneGraph,
+ bundle: DesignTokenBundle,
+ resolve: Resolve,
+ alias: Alias
+): { styles: PlannedStyle[]; skipped: ImportSkip[] } {
+ const textStyles = getSharedStyles(graph, 'text')
+ const effectStyles = getSharedStyles(graph, 'effect')
+ const styles: PlannedStyle[] = []
+ const skipped: ImportSkip[] = []
+ for (const token of bundle.composites) {
+ const kind = STYLE_KINDS[token.type ?? '']
+ if (!kind) {
+ skipped.push({ name: token.name, collection: undefined, reason: 'unsupported-type' })
+ continue
+ }
+ const fields = kind === 'TEXT' ? textFields(token, resolve) : effectFields(token, resolve)
+ if (!fields) {
+ skipped.push({ name: token.name, collection: undefined, reason: 'invalid-value' })
+ continue
+ }
+ const existing = (kind === 'TEXT' ? textStyles : effectStyles).find(
+ (style) => style.name === token.name
+ )
+ styles.push({
+ kind,
+ name: token.name,
+ existingNodeId: existing?.nodeId ?? null,
+ fields,
+ bindings: kind === 'TEXT' ? textBindings(token, alias) : {}
+ })
+ }
+ return { styles, skipped }
+}
diff --git a/packages/core/src/io/formats/design-tokens/plan.ts b/packages/core/src/io/formats/design-tokens/plan.ts
new file mode 100644
index 000000000..4c133a3bd
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/plan.ts
@@ -0,0 +1,487 @@
+import { compact } from 'es-toolkit/array'
+
+import type {
+ CodeSyntaxPlatform,
+ SceneGraph,
+ TokenUnit,
+ Variable,
+ VariableCollection,
+ VariableScope,
+ VariableType,
+ VariableValue
+} from '@open-pencil/scene-graph'
+
+import {
+ decodeVariableToken,
+ referencePath,
+ type DecodedValue,
+ type DecodedVariable,
+ type DecodeFailure
+} from './decode'
+import { pathName } from './paths'
+import { planStyles, type PlannedStyle } from './plan-styles'
+import type { DesignTokenBundle, ReadCollection, ReadToken } from './read'
+
+/** Where an imported collection goes: a new collection, an existing one, or nowhere. */
+export type CollectionTarget =
+ | { kind: 'new'; name: string }
+ | { kind: 'existing'; collectionId: string }
+ | { kind: 'skip' }
+
+/** Where an imported mode's values go within its target collection. */
+export type ModeTarget =
+ | { kind: 'new'; name: string }
+ | { kind: 'existing'; modeId: string }
+ | { kind: 'skip' }
+
+/** The user's choice for one collection of the bundle, its modes in the bundle's order. */
+export interface CollectionImportChoice {
+ target: CollectionTarget
+ modes: ModeTarget[]
+}
+
+export interface TokenImportOptions {
+ collections: CollectionImportChoice[]
+ /** Add tokens no variable matches yet; matching ones are updated either way. */
+ addMissing: boolean
+ /** Make text and effect styles from typography and shadow tokens. */
+ styles: boolean
+}
+
+/** Why a token or value was left out. */
+export type ImportSkipReason =
+ | DecodeFailure
+ | 'type-mismatch'
+ | 'missing-alias'
+ | 'not-added'
+ | 'mixed-types'
+
+export interface ImportSkip {
+ name: string
+ collection: string | undefined
+ reason: ImportSkipReason
+}
+
+/** What a reference comes to: a token the import read, or a value already in the document. */
+export type ResolvedReference =
+ | { kind: 'token'; token: ReadToken }
+ | { kind: 'value'; value: VariableValue }
+
+/** A variable an alias points at: one already in the document, or one this import plans. */
+export type AliasTarget =
+ | { kind: 'variable'; variableId: string }
+ | { kind: 'planned'; collection: number; variable: number }
+
+export type PlannedValue =
+ | { kind: 'literal'; value: Exclude<DecodedValue, { kind: 'alias' }>['value'] }
+ | { kind: 'alias'; target: AliasTarget }
+
+export interface PlannedVariable {
+ name: string
+ type: VariableType
+ /** The variable updated, or null for one the import adds. */
+ existingId: string | null
+ /** Values by planned mode; undefined leaves that mode as it is. */
+ values: Array<PlannedValue | undefined>
+ expressions: Array<string | undefined>
+ unit?: TokenUnit
+ scopes?: VariableScope[]
+ codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>
+ hiddenFromPublishing?: boolean
+ description?: string
+}
+
+export interface PlannedMode {
+ name: string
+ target: Exclude<ModeTarget, { kind: 'skip' }>
+ isDefault: boolean
+ condition: string | undefined
+}
+
+export interface PlannedCollection {
+ name: string
+ target: Exclude<CollectionTarget, { kind: 'skip' }>
+ modes: PlannedMode[]
+ modeAttribute: string | undefined
+ variables: PlannedVariable[]
+}
+
+export interface TokenImportPlan {
+ collections: PlannedCollection[]
+ styles: PlannedStyle[]
+ skipped: ImportSkip[]
+ counts: { added: number; updated: number; skipped: number }
+}
+
+/** Collections and modes matched by name; anything without a match is new. */
+export function defaultTokenImportOptions(
+ graph: SceneGraph,
+ bundle: DesignTokenBundle
+): TokenImportOptions {
+ const existing = [...graph.variableCollections.values()]
+ const claimed = new Set<string>()
+ return {
+ collections: bundle.collections.map((collection): CollectionImportChoice => {
+ const match = existing.find(
+ (candidate) => candidate.name === collection.name && !claimed.has(candidate.id)
+ )
+ if (match) claimed.add(match.id)
+ if (!match) {
+ return {
+ target: { kind: 'new', name: collection.name },
+ modes: collection.modes.map((mode) => ({ kind: 'new', name: mode.name }))
+ }
+ }
+ return {
+ target: { kind: 'existing', collectionId: match.id },
+ modes: collection.modes.map((mode): ModeTarget => {
+ const modeMatch = match.modes.find((candidate) => candidate.name === mode.name)
+ return modeMatch
+ ? { kind: 'existing', modeId: modeMatch.modeId }
+ : { kind: 'new', name: mode.name }
+ })
+ }
+ }),
+ addMissing: true,
+ styles: true
+ }
+}
+
+/** A collection's tokens by name, one per mode, in the order they first appear. */
+function tokensByName(collection: ReadCollection, modes: readonly number[]) {
+ const names = new Map<string, Array<ReadToken | undefined>>()
+ modes.forEach((modeIndex, planned) => {
+ for (const token of collection.modes[modeIndex].tokens) {
+ const row = names.get(token.name) ?? Array.from({ length: modes.length }, () => undefined)
+ row[planned] = token
+ names.set(token.name, row)
+ }
+ })
+ return names
+}
+
+interface Planner {
+ graph: SceneGraph
+ bundle: DesignTokenBundle
+ collections: PlannedCollection[]
+ /** By collection, token path joined with `.` to the planned variable's index. */
+ paths: Array<Map<string, number>>
+ existingByCollection: Array<VariableCollection | undefined>
+ skipped: ImportSkip[]
+ /** Lookups built once, on first use: large design systems resolve thousands of references. */
+ indexes?: PlannerIndexes
+}
+
+interface PlannerIndexes {
+ /** The document's variables by name. */
+ variables: Map<string, Variable[]>
+ /** The first planned collection with each name: its index and its variables' indexes by name. */
+ planned: Map<string, { index: number; variables: Map<string, number> }>
+ /** Tokens by path in each collection's default mode, then composites, first one winning. */
+ literals: Map<string, ReadToken>
+}
+
+function indexesOf(planner: Planner): PlannerIndexes {
+ if (planner.indexes) return planner.indexes
+ const variables = new Map<string, Variable[]>()
+ for (const variable of planner.graph.variables.values())
+ variables.set(variable.name, [...(variables.get(variable.name) ?? []), variable])
+ const planned = new Map<string, { index: number; variables: Map<string, number> }>()
+ planner.collections.forEach((collection, index) => {
+ if (planned.has(collection.name)) return
+ const variables = new Map(collection.variables.map((variable, at) => [variable.name, at]))
+ planned.set(collection.name, { index, variables })
+ })
+ const literals = new Map<string, ReadToken>()
+ for (const collection of planner.bundle.collections) {
+ const mode = collection.modes.find((entry) => entry.isDefault) ?? collection.modes.at(0)
+ for (const token of mode?.tokens ?? []) {
+ const key = token.path.join('.')
+ if (!literals.has(key)) literals.set(key, token)
+ }
+ }
+ for (const token of planner.bundle.composites) {
+ const key = token.path.join('.')
+ if (!literals.has(key)) literals.set(key, token)
+ }
+ planner.indexes = { variables, planned, literals }
+ return planner.indexes
+}
+
+/** A collection's variables by name, the first of any repeated name winning. */
+function variablesByName(graph: SceneGraph, collection: VariableCollection | undefined) {
+ const byName = new Map<string, Variable>()
+ for (const variable of compact(
+ (collection?.variableIds ?? []).map((id) => graph.variables.get(id))
+ ))
+ if (!byName.has(variable.name)) byName.set(variable.name, variable)
+ return byName
+}
+
+/**
+ * The variable an alias names. Figma's alias data names the collection and variable outright;
+ * otherwise the path is looked up in the token's own collection, the other imported ones, and
+ * then among the document's variables by name.
+ */
+function aliasTarget(
+ planner: Planner,
+ from: number,
+ value: Extract<DecodedValue, { kind: 'alias' }>
+): AliasTarget | undefined {
+ const planned = (collection: number, variable: number): AliasTarget => ({
+ kind: 'planned',
+ collection,
+ variable
+ })
+ const indexes = indexesOf(planner)
+ if (value.collection && value.name) {
+ const collection = indexes.planned.get(value.collection)
+ const variable = collection?.variables.get(value.name)
+ if (collection && variable !== undefined) return planned(collection.index, variable)
+ const existing = indexes.variables
+ .get(value.name)
+ ?.find(
+ (candidate) =>
+ planner.graph.variableCollections.get(candidate.collectionId)?.name === value.collection
+ )
+ // A named target that is not there, say in a collection left out, is missing: the same
+ // path in another collection is a different variable.
+ return existing ? { kind: 'variable', variableId: existing.id } : undefined
+ }
+ const key = value.path.join('.')
+ const order = [from, ...planner.paths.keys()].filter(
+ (index, at, all) => all.indexOf(index) === at
+ )
+ for (const index of order) {
+ const variable = planner.paths[index]?.get(key)
+ if (variable !== undefined) return planned(index, variable)
+ }
+ const existing = indexes.variables.get(pathName(value.path))?.at(0)
+ return existing ? { kind: 'variable', variableId: existing.id } : undefined
+}
+
+function targetType(planner: Planner, target: AliasTarget): VariableType | undefined {
+ if (target.kind === 'variable') return planner.graph.variables.get(target.variableId)?.type
+ return planner.collections[target.collection]?.variables[target.variable]?.type
+}
+
+/**
+ * A variable with its token fields from the first token that declares a type. An existing
+ * variable keeps its type, and a token that declares another is a mismatch; untyped aliases take
+ * their target's type in the second pass.
+ */
+function plannedVariable(
+ name: string,
+ existing: Variable | undefined,
+ decoded: ReadonlyArray<DecodedVariable | undefined>
+): PlannedVariable {
+ const first = decoded.find((entry) => entry?.type !== undefined)
+ const fields = first ?? decoded.find((entry) => entry !== undefined)
+ return {
+ name,
+ type: first?.type ?? existing?.type ?? 'STRING',
+ existingId: existing?.id ?? null,
+ values: [],
+ expressions: decoded.map((entry) => entry?.expression),
+ ...tokenFields(fields, existing),
+ description: fields?.description
+ }
+}
+
+/**
+ * A variable's unit, scopes, and code syntax. OpenPencil's tokens state them, so theirs replace
+ * the variable's; other tools' tokens leave an updated variable's own where they say nothing.
+ */
+function tokenFields(fields: DecodedVariable | undefined, existing: Variable | undefined) {
+ const kept = fields?.own ? undefined : existing
+ return {
+ unit: fields?.unit ?? kept?.unit,
+ scopes: fields?.scopes ?? kept?.scopes,
+ codeSyntax: fields?.codeSyntax ?? kept?.codeSyntax,
+ hiddenFromPublishing: fields?.hiddenFromPublishing ?? kept?.hiddenFromPublishing
+ }
+}
+
+/** First pass: which variables each collection plans, typed from tokens that declare a type. */
+function planVariables(
+ planner: Planner,
+ index: number,
+ collection: ReadCollection,
+ modeIndexes: readonly number[],
+ addMissing: boolean
+): Array<{ variable: PlannedVariable; decoded: Array<DecodedVariable | undefined> }> {
+ const planned = planner.collections[index]
+ const paths = new Map<string, number>()
+ planner.paths[index] = paths
+ const rows: Array<{ variable: PlannedVariable; decoded: Array<DecodedVariable | undefined> }> = []
+ const existingByName = variablesByName(planner.graph, planner.existingByCollection[index])
+ for (const [name, tokens] of tokensByName(collection, modeIndexes)) {
+ const decoded = tokens.map((token) => (token ? decodeVariableToken(token) : undefined))
+ const failure = decoded.find((entry) => typeof entry === 'string')
+ const usable = decoded.map((entry) => (typeof entry === 'string' ? undefined : entry))
+ if (usable.every((entry) => entry === undefined)) {
+ planner.skipped.push({
+ name,
+ collection: collection.name,
+ reason: failure ?? 'invalid-value'
+ })
+ continue
+ }
+ const existing = existingByName.get(name)
+ if (!existing && !addMissing) {
+ planner.skipped.push({ name, collection: collection.name, reason: 'not-added' })
+ continue
+ }
+ const variable = plannedVariable(name, existing, usable)
+ if (existing && variable.type !== existing.type) {
+ planner.skipped.push({ name, collection: collection.name, reason: 'type-mismatch' })
+ continue
+ }
+ for (const token of compact(tokens)) paths.set(token.path.join('.'), planned.variables.length)
+ planned.variables.push(variable)
+ rows.push({ variable, decoded: usable })
+ }
+ return rows
+}
+
+/** Second pass: values, with aliases resolved now that every planned variable exists. */
+function planValues(planner: Planner, index: number, rows: ReturnType<typeof planVariables>): void {
+ const collection = planner.collections[index]
+ for (const { variable, decoded } of rows) {
+ let typed = variable.existingId !== null || decoded.some((entry) => entry?.type !== undefined)
+ variable.values = decoded.map((entry) => {
+ if (!entry) return undefined
+ if (entry.value.kind === 'literal') {
+ if (entry.type !== variable.type) {
+ planner.skipped.push({
+ name: variable.name,
+ collection: collection.name,
+ reason: 'mixed-types'
+ })
+ return undefined
+ }
+ return { kind: 'literal', value: entry.value.value }
+ }
+ const target = aliasTarget(planner, index, entry.value)
+ const type = target && targetType(planner, target)
+ if (!target || !type) {
+ planner.skipped.push({
+ name: variable.name,
+ collection: collection.name,
+ reason: 'missing-alias'
+ })
+ return undefined
+ }
+ if (!typed) {
+ variable.type = type
+ typed = true
+ }
+ if (type !== variable.type) {
+ planner.skipped.push({
+ name: variable.name,
+ collection: collection.name,
+ reason: 'mixed-types'
+ })
+ return undefined
+ }
+ return { kind: 'alias', target }
+ })
+ }
+}
+
+/**
+ * What importing a bundle with these choices would do, without doing it: the collections, modes,
+ * and variables it adds or updates, the styles it makes, and what it skips and why. Nothing is
+ * deleted; a token that matches a variable by name in the target collection updates it.
+ */
+export function planTokenImport(
+ graph: SceneGraph,
+ bundle: DesignTokenBundle,
+ options: TokenImportOptions
+): TokenImportPlan {
+ const planner: Planner = {
+ graph,
+ bundle,
+ collections: [],
+ paths: [],
+ existingByCollection: [],
+ skipped: []
+ }
+ const chosen = bundle.collections.flatMap((collection, bundleIndex) => {
+ const choice = options.collections.at(bundleIndex)
+ if (!choice || choice.target.kind === 'skip') return []
+ const modeIndexes = collection.modes.flatMap((_, modeIndex) =>
+ choice.modes[modeIndex]?.kind === 'skip' ? [] : [modeIndex]
+ )
+ if (modeIndexes.length === 0) return []
+ const target = choice.target
+ planner.collections.push({
+ name: collection.name,
+ target,
+ modes: modeIndexes.map((modeIndex): PlannedMode => {
+ const mode = collection.modes[modeIndex]
+ const modeTarget = choice.modes.at(modeIndex)
+ return {
+ name: mode.name,
+ target:
+ modeTarget && modeTarget.kind !== 'skip'
+ ? modeTarget
+ : { kind: 'new', name: mode.name },
+ isDefault: mode.isDefault,
+ condition: mode.condition
+ }
+ }),
+ modeAttribute: collection.modeAttribute,
+ variables: []
+ })
+ planner.existingByCollection.push(
+ target.kind === 'existing' ? graph.variableCollections.get(target.collectionId) : undefined
+ )
+ return [{ collection, modeIndexes }]
+ })
+ const rows = chosen.map(({ collection, modeIndexes }, index) =>
+ planVariables(planner, index, collection, modeIndexes, options.addMissing)
+ )
+ rows.forEach((collectionRows, index) => planValues(planner, index, collectionRows))
+ const styles = options.styles
+ ? planStyles(
+ planner.graph,
+ bundle,
+ (path) => resolveLiteral(planner, path),
+ (path) => aliasTarget(planner, 0, { kind: 'alias', path })
+ )
+ : { styles: [], skipped: [] }
+ const skipped = [...planner.skipped, ...styles.skipped]
+ const variables = planner.collections.flatMap((collection) => collection.variables)
+ const updated =
+ variables.filter((variable) => variable.existingId !== null).length +
+ styles.styles.filter((style) => style.existingNodeId !== null).length
+ const added = variables.length + styles.styles.length - updated
+ return {
+ collections: planner.collections,
+ styles: styles.styles,
+ skipped,
+ counts: { added, updated, skipped: skipped.length }
+ }
+}
+
+/**
+ * The literal a reference comes to in its collection's default mode, following aliases, for
+ * style fields that take values rather than bindings.
+ */
+function resolveLiteral(
+ planner: Planner,
+ path: readonly string[],
+ depth = 0
+): ResolvedReference | undefined {
+ if (depth > 16) return undefined
+ const indexes = indexesOf(planner)
+ const token = indexes.literals.get(path.join('.'))
+ if (token) {
+ const next = referencePath(token.value)
+ return next ? resolveLiteral(planner, next, depth + 1) : { kind: 'token', token }
+ }
+ const existing = indexes.variables.get(pathName(path))?.at(0)
+ const value = existing && planner.graph.resolveVariable(existing.id)
+ return value === undefined ? undefined : { kind: 'value', value }
+}
diff --git a/packages/core/src/io/formats/design-tokens/read.ts b/packages/core/src/io/formats/design-tokens/read.ts
new file mode 100644
index 000000000..2c7bac28c
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/read.ts
@@ -0,0 +1,361 @@
+import { isPlainObject } from 'es-toolkit/predicate'
+import * as v from 'valibot'
+
+import { pathName } from './paths'
+import { OPENPENCIL_EXTENSION } from './types'
+
+/** A file the user picked: its path within the folder or archive, and its text. */
+export interface DesignTokenSourceFile {
+ path: string
+ text: string
+}
+
+/** A token as read: where it sits, its declared or inherited type, and what it carries. */
+export interface ReadToken {
+ /** Placed path, `$root` included, as references name it. */
+ path: string[]
+ /** Layer-panel name: the original OpenPencil kept, or the path joined with `/`. */
+ name: string
+ type: string | undefined
+ value: unknown
+ description: string | undefined
+ extensions: Record<string, unknown>
+}
+
+export interface ReadMode {
+ name: string
+ tokens: ReadToken[]
+ isDefault: boolean
+ condition: string | undefined
+}
+
+export interface ReadCollection {
+ name: string
+ modes: ReadMode[]
+ modeAttribute: string | undefined
+}
+
+export type DesignTokenReadIssue =
+ | { kind: 'invalid-file'; file: string }
+ | { kind: 'missing-file'; file: string; from: string }
+
+/** What a set of token files holds: collections of modes, and composite tokens for styles. */
+export interface DesignTokenBundle {
+ collections: ReadCollection[]
+ /** Typography, shadow, and other composite tokens, which become styles or are skipped. */
+ composites: ReadToken[]
+ issues: DesignTokenReadIssue[]
+}
+
+const COMPOSITE_TYPES = new Set([
+ 'typography',
+ 'shadow',
+ 'border',
+ 'gradient',
+ 'transition',
+ 'strokeStyle',
+ 'cubicBezier'
+])
+
+const DocumentSchema = v.pipe(v.string(), v.parseJson(), v.record(v.string(), v.unknown()))
+type Document = v.InferOutput<typeof DocumentSchema>
+
+const SourceSchema = v.union([v.object({ $ref: v.string() }), v.record(v.string(), v.unknown())])
+const ResolverSchema = v.object({
+ version: v.string(),
+ sets: v.optional(v.record(v.string(), v.object({ sources: v.array(SourceSchema) }))),
+ modifiers: v.optional(
+ v.record(
+ v.string(),
+ v.object({
+ contexts: v.record(v.string(), v.array(SourceSchema)),
+ default: v.optional(v.string())
+ })
+ )
+ ),
+ resolutionOrder: v.array(v.unknown())
+})
+const ThemesSchema = v.array(
+ v.object({
+ name: v.string(),
+ group: v.optional(v.string()),
+ selectedTokenSets: v.optional(v.record(v.string(), v.string()), {})
+ })
+)
+const ModeExtensionSchema = v.object({
+ collection: v.optional(v.string()),
+ mode: v.optional(v.string()),
+ default: v.optional(v.boolean()),
+ condition: v.optional(v.string()),
+ modeAttribute: v.optional(v.string())
+})
+const NameExtensionSchema = v.object({ name: v.optional(v.string()) })
+
+function extensionsOf(node: Record<string, unknown>): Record<string, unknown> {
+ return isPlainObject(node.$extensions) ? node.$extensions : {}
+}
+
+/** The collection and mode a file says it holds, which OpenPencil writes into each mode file. */
+function modeInfo(parsed: Record<string, unknown> | undefined) {
+ const own = v.safeParse(ModeExtensionSchema, parsed && extensionsOf(parsed)[OPENPENCIL_EXTENSION])
+ return own.success ? own.output : {}
+}
+
+/** Tokens in a document, groups flattened, each with the type it declares or inherits. */
+export function documentTokens(parsed: Record<string, unknown>): ReadToken[] {
+ const tokens: ReadToken[] = []
+ const visit = (group: Record<string, unknown>, path: string[], inherited?: string) => {
+ const type = typeof group.$type === 'string' ? group.$type : inherited
+ for (const [key, child] of Object.entries(group)) {
+ if ((key.startsWith('$') && key !== '$root') || !isPlainObject(child)) continue
+ const at = [...path, key]
+ if (!('$value' in child)) {
+ visit(child, at, type)
+ continue
+ }
+ const extensions = extensionsOf(child)
+ const own = v.safeParse(NameExtensionSchema, extensions[OPENPENCIL_EXTENSION])
+ tokens.push({
+ path: at,
+ name: (own.success ? own.output.name : undefined) ?? pathName(at),
+ type: typeof child.$type === 'string' ? child.$type : type,
+ value: child.$value,
+ description: typeof child.$description === 'string' ? child.$description : undefined,
+ extensions
+ })
+ }
+ }
+ visit(parsed, [])
+ return tokens
+}
+
+/** `a/b/c.tokens.json` is `c`; `.tokens`, `.tokens.json`, and `.json` all go. */
+function baseName(path: string): string {
+ const file = path.split('/').at(-1) ?? path
+ return file.replace(/\.tokens(\.json)?$|\.json$/i, '')
+}
+
+function folderOf(path: string): string {
+ return path.split('/').slice(0, -1).join('/')
+}
+
+/** A `$ref` as a path among the picked files, relative to the file it appears in. */
+function resolveRef(from: string, ref: string): string {
+ const segments = [...folderOf(from).split('/'), ...ref.split('/')]
+ const resolved: string[] = []
+ for (const segment of segments) {
+ if (segment === '' || segment === '.') continue
+ if (segment === '..') resolved.pop()
+ else resolved.push(segment)
+ }
+ return resolved.join('/')
+}
+
+/**
+ * The picked file a `$ref` names: by its path relative to the resolver, or, when files were
+ * picked without their folders, the one picked file with that name.
+ */
+function findRef(reader: Reader, from: string, ref: string): string {
+ const path = resolveRef(from, ref)
+ if (reader.documents.has(path)) return path
+ const name = path.split('/').at(-1)
+ const matches = [...reader.documents.keys()].filter((key) => key.split('/').at(-1) === name)
+ return matches.length === 1 ? matches[0] : path
+}
+
+function isResolver(parsed: Document): boolean {
+ return 'resolutionOrder' in parsed && 'version' in parsed
+}
+
+interface Reader {
+ documents: Map<string, Document>
+ used: Set<string>
+ issues: DesignTokenReadIssue[]
+}
+
+/** The tokens of a resolver's sources, later sources overriding earlier ones by path. */
+function sourceTokens(
+ reader: Reader,
+ from: string,
+ sources: ReadonlyArray<v.InferOutput<typeof SourceSchema>>
+): { tokens: ReadToken[]; info: ReturnType<typeof modeInfo> } {
+ const byPath = new Map<string, ReadToken>()
+ let info: ReturnType<typeof modeInfo> = {}
+ for (const source of sources) {
+ let parsed: Record<string, unknown> | undefined
+ if (typeof source.$ref === 'string') {
+ const path = findRef(reader, from, source.$ref)
+ parsed = reader.documents.get(path)
+ if (!parsed) reader.issues.push({ kind: 'missing-file', file: path, from })
+ reader.used.add(path)
+ } else {
+ parsed = source
+ }
+ if (parsed && !info.collection) info = modeInfo(parsed)
+ for (const token of parsed ? documentTokens(parsed) : [])
+ byPath.set(token.path.join('.'), token)
+ }
+ return { tokens: [...byPath.values()], info }
+}
+
+function mode(name: string, tokens: ReadToken[], isDefault: boolean): ReadMode {
+ return { name, tokens, isDefault, condition: undefined }
+}
+
+/** A resolver: each modifier a collection of its contexts, each set a single-mode collection. */
+function readResolver(reader: Reader, path: string, parsed: Document): ReadCollection[] {
+ const result = v.safeParse(ResolverSchema, parsed)
+ if (!result.success) {
+ reader.issues.push({ kind: 'invalid-file', file: path })
+ return []
+ }
+ const { sets = {}, modifiers = {} } = result.output
+ // The collection and mode names a source file records win over the resolver's own labels,
+ // which an export makes distinct when two collections share a name.
+ const collections: ReadCollection[] = Object.entries(sets).map(([name, set]) => {
+ const { tokens, info } = sourceTokens(reader, path, set.sources)
+ return {
+ name: info.collection ?? name,
+ modes: [{ name: info.mode ?? 'Mode 1', tokens, isDefault: true, condition: info.condition }],
+ modeAttribute: info.modeAttribute
+ }
+ })
+ for (const [name, modifier] of Object.entries(modifiers)) {
+ const contexts = Object.entries(modifier.contexts)
+ const defaultName = modifier.default ?? contexts[0]?.[0]
+ const modes = contexts.map(([context, sources]) => ({
+ context,
+ ...sourceTokens(reader, path, sources)
+ }))
+ collections.push({
+ name: modes.find((entry) => entry.info.collection)?.info.collection ?? name,
+ modes: modes.map(({ context, tokens, info }) => ({
+ name: info.mode ?? context,
+ tokens,
+ isDefault: context === defaultName,
+ condition: info.condition
+ })),
+ modeAttribute: modes.find((entry) => entry.info.modeAttribute)?.info.modeAttribute
+ })
+ }
+ return collections
+}
+
+/**
+ * Tokens Studio themes, as Penpot also exports them: each theme group a collection whose modes
+ * are its themes, built from the sets each theme enables. Sets no theme enables, usually
+ * primitives the themes refer to, become collections of their own.
+ */
+function readThemes(
+ themes: v.InferOutput<typeof ThemesSchema>,
+ setDocument: (name: string) => Record<string, unknown> | undefined
+): ReadCollection[] {
+ const groups = new Map<string, ReadMode[]>()
+ const enabled = new Set<string>()
+ for (const theme of themes) {
+ const sets = Object.entries(theme.selectedTokenSets)
+ .filter(([, state]) => state === 'enabled')
+ .map(([name]) => name)
+ for (const name of sets) enabled.add(name)
+ const byPath = new Map<string, ReadToken>()
+ for (const name of sets)
+ for (const token of documentTokens(setDocument(name) ?? {}))
+ byPath.set(token.path.join('.'), token)
+ const group = theme.group ?? 'Themes'
+ const modes = groups.get(group) ?? []
+ modes.push(mode(theme.name, [...byPath.values()], modes.length === 0))
+ groups.set(group, modes)
+ }
+ const referenced = new Set(
+ themes.flatMap((theme) =>
+ Object.keys(theme.selectedTokenSets).filter((name) => !enabled.has(name))
+ )
+ )
+ const collections: ReadCollection[] = [...referenced].map((name) => ({
+ name,
+ modes: [mode('Mode 1', documentTokens(setDocument(name) ?? {}), true)],
+ modeAttribute: undefined
+ }))
+ for (const [name, modes] of groups) collections.push({ name, modes, modeAttribute: undefined })
+ return collections
+}
+
+/** Plain token files: grouped into collections by what they say or by folder, one mode per file. */
+function readModeFiles(paths: readonly string[], reader: Reader): ReadCollection[] {
+ const collections = new Map<string, ReadCollection>()
+ for (const path of paths) {
+ const parsed = reader.documents.get(path)
+ if (!parsed) continue
+ const info = modeInfo(parsed)
+ // Files group by folder, since two collections may share a name; loose files by the
+ // collection they name, or into one.
+ const folder = folderOf(path)
+ const key = folder || info.collection || ''
+ const name = info.collection ?? (folder.split('/').at(-1) || 'Tokens')
+ const collection = collections.get(key) ?? { name, modes: [], modeAttribute: undefined }
+ collection.modeAttribute ??= info.modeAttribute
+ collection.modes.push({
+ name: info.mode ?? baseName(path),
+ tokens: documentTokens(parsed),
+ isDefault: info.default ?? collection.modes.length === 0,
+ condition: info.condition
+ })
+ collections.set(key, collection)
+ }
+ return [...collections.values()]
+}
+
+/** Composite tokens move to the styles side; collections keep the rest, and empty ones go. */
+function splitComposites(collections: readonly ReadCollection[]) {
+ const composites = new Map<string, ReadToken>()
+ const kept = collections
+ .map((collection) => ({
+ ...collection,
+ modes: collection.modes.map((entry) => ({
+ ...entry,
+ tokens: entry.tokens.filter((token) => {
+ if (!COMPOSITE_TYPES.has(token.type ?? '')) return true
+ composites.set(token.path.join('.'), token)
+ return false
+ })
+ }))
+ }))
+ .filter((collection) => collection.modes.some((entry) => entry.tokens.length > 0))
+ return { collections: kept, composites: [...composites.values()] }
+}
+
+/**
+ * Reads token files into collections and modes. A resolver document, a Tokens Studio `$themes`
+ * file, or OpenPencil's mode extension says how files combine; otherwise each file is a mode of a
+ * collection named after its folder, as Figma imports one mode per file.
+ */
+export function readDesignTokens(files: readonly DesignTokenSourceFile[]): DesignTokenBundle {
+ const reader: Reader = { documents: new Map(), used: new Set(), issues: [] }
+ for (const file of files) {
+ const result = v.safeParse(DocumentSchema, file.text)
+ if (result.success) reader.documents.set(file.path, result.output)
+ else reader.issues.push({ kind: 'invalid-file', file: file.path })
+ }
+ const collections: ReadCollection[] = []
+ for (const [path, parsed] of reader.documents) {
+ if (!isResolver(parsed)) continue
+ reader.used.add(path)
+ collections.push(...readResolver(reader, path, parsed))
+ }
+ for (const [path, parsed] of reader.documents) {
+ const themes = v.safeParse(ThemesSchema, baseName(path) === '$themes' ? parsed : parsed.$themes)
+ if (reader.used.has(path) || !themes.success) continue
+ reader.used.add(path)
+ const inline = baseName(path) !== '$themes'
+ const setDocument = (name: string) => {
+ if (inline) return isPlainObject(parsed[name]) ? parsed[name] : undefined
+ const setPath = resolveRef(path, `${name}.json`)
+ reader.used.add(setPath)
+ return reader.documents.get(setPath)
+ }
+ collections.push(...readThemes(themes.output, setDocument))
+ }
+ const remaining = [...reader.documents.keys()].filter((path) => !reader.used.has(path))
+ collections.push(...readModeFiles(remaining, reader))
+ return { ...splitComposites(collections), issues: reader.issues }
+}
diff --git a/packages/core/src/io/formats/design-tokens/styles.ts b/packages/core/src/io/formats/design-tokens/styles.ts
new file mode 100644
index 000000000..c3bcfc892
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/styles.ts
@@ -0,0 +1,169 @@
+import { isEmptyObject, isPlainObject } from 'es-toolkit/predicate'
+
+import type { Effect, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import { toFigmaEffect } from '#core/figma-api/effects'
+
+import { pathName, placeTokens, tokenPath, tokenReference } from './paths'
+import { OPENPENCIL_EXTENSION, type DesignToken, type DesignTokenIssue } from './types'
+import { colorTokenValue, dimensionTokenValue, trimNumber } from './values'
+
+/** Where a variable's token sits, for references to it. */
+export type TokenReferences = ReadonlyMap<string, readonly string[]>
+
+/** Figma's auto line height, written as the multiplier browsers use for `normal`. */
+const AUTO_LINE_HEIGHT = 1.2
+
+const TEXT_BINDING_FIELDS = ['fontFamily', 'fontSize', 'letterSpacing', 'lineHeight'] as const
+
+function bindingReferences(
+ node: SceneNode,
+ references: TokenReferences
+): Partial<Record<(typeof TEXT_BINDING_FIELDS)[number], string>> {
+ const bound = TEXT_BINDING_FIELDS.flatMap((field) => {
+ const variableId = node.boundVariables[field]
+ const path = variableId ? references.get(variableId) : undefined
+ return path ? [[field, tokenReference(path)] as const] : []
+ })
+ return Object.fromEntries(bound)
+}
+
+export type TypographyFields = Pick<
+ SceneNode,
+ 'fontFamily' | 'fontSize' | 'fontWeight' | 'lineHeight' | 'letterSpacing'
+>
+
+/** A typography token's `$value`: bound fields as references to their variables' tokens. */
+export function typographyValue(
+ text: TypographyFields,
+ bound: Partial<Record<(typeof TEXT_BINDING_FIELDS)[number], string>>
+) {
+ const lineHeight =
+ text.lineHeight === null || text.fontSize <= 0
+ ? AUTO_LINE_HEIGHT
+ : trimNumber(text.lineHeight / text.fontSize)
+ return {
+ fontFamily: bound.fontFamily ?? text.fontFamily,
+ fontSize: bound.fontSize ?? dimensionTokenValue(text.fontSize),
+ fontWeight: text.fontWeight,
+ lineHeight,
+ letterSpacing: bound.letterSpacing ?? dimensionTokenValue(text.letterSpacing)
+ }
+}
+
+/** A text style as a typography token; its own fields ride along so OpenPencil reads it back exactly. */
+function typographyToken(node: SceneNode, references: TokenReferences): DesignToken {
+ const bound = bindingReferences(node, references)
+ return {
+ $type: 'typography',
+ $value: typographyValue(node, bound),
+ $extensions: {
+ [OPENPENCIL_EXTENSION]: {
+ text: {
+ fontFamily: node.fontFamily,
+ fontWeight: node.fontWeight,
+ italic: node.italic,
+ fontSize: node.fontSize,
+ lineHeight: node.lineHeight,
+ letterSpacing: node.letterSpacing,
+ textDecoration: node.textDecoration,
+ textCase: node.textCase
+ },
+ ...(isEmptyObject(bound) ? {} : { bindings: bound })
+ }
+ }
+ }
+}
+
+export function isShadow(effect: Effect): boolean {
+ return effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
+}
+
+function shadowValue(effect: Effect) {
+ return {
+ color: colorTokenValue(effect.color),
+ offsetX: dimensionTokenValue(effect.offset.x),
+ offsetY: dimensionTokenValue(effect.offset.y),
+ blur: dimensionTokenValue(effect.radius),
+ spread: dimensionTokenValue(effect.spread),
+ ...(effect.type === 'INNER_SHADOW' ? { inset: true } : {})
+ }
+}
+
+/** A shadow token's `$value`: the visible shadows of `effects`, or undefined when there are none. */
+export function shadowTokenValue(effects: readonly Effect[]) {
+ const values = effects.filter((effect) => isShadow(effect) && effect.visible).map(shadowValue)
+ if (values.length === 0) return undefined
+ return values.length === 1 ? values[0] : values
+}
+
+/**
+ * An effect style's shadows as a shadow token. Effects a shadow token cannot express, such as
+ * blurs or hidden shadows, ride along whole in OpenPencil's extension, in the plugin API's shape;
+ * a style with no visible shadow has no token.
+ */
+function shadowToken(node: SceneNode): DesignToken | undefined {
+ const $value = shadowTokenValue(node.effects)
+ if ($value === undefined) return undefined
+ const exact = node.effects.every(
+ (effect) =>
+ isShadow(effect) &&
+ effect.visible &&
+ (effect.blendMode ?? 'NORMAL') === 'NORMAL' &&
+ effect.showShadowBehindNode !== true
+ )
+ return {
+ $type: 'shadow',
+ $value,
+ ...(exact
+ ? {}
+ : { $extensions: { [OPENPENCIL_EXTENSION]: { effects: node.effects.map(toFigmaEffect) } } })
+ }
+}
+
+/** Text and effect styles as typography and shadow tokens, nested by their names. */
+export function styleTokens(
+ graph: SceneGraph,
+ references: TokenReferences
+): { tokens: Array<{ path: string[]; token: DesignToken }>; issues: DesignTokenIssue[] } {
+ const issues: DesignTokenIssue[] = []
+ const styles = [...graph.getAllNodes()].filter(
+ (node) =>
+ (node.sharedStyleType === 'TEXT' || node.sharedStyleType === 'EFFECT') &&
+ node.source.id !== null
+ )
+ const candidates = styles.flatMap((node) => {
+ const token =
+ node.sharedStyleType === 'TEXT' ? typographyToken(node, references) : shadowToken(node)
+ if (!token) {
+ issues.push({ kind: 'unsupported-effect', style: node.name })
+ return []
+ }
+ return [{ key: { node, token }, path: tokenPath(node.name) }]
+ })
+ const { placed, duplicates } = placeTokens(candidates)
+ for (const { node } of duplicates)
+ issues.push({ kind: 'duplicate-path', collection: 'Styles', token: node.name })
+ const tokens = [...placed].map(([{ node, token }, path]) => ({
+ path,
+ token: withOriginalName(token, node.name, path)
+ }))
+ return { tokens, issues }
+}
+
+/** Keeps a name the token path could not hold, such as one with a `.`, in OpenPencil's extension. */
+export function withOriginalName(
+ token: DesignToken,
+ name: string,
+ path: readonly string[]
+): DesignToken {
+ if (pathName(path) === name) return token
+ const own = token.$extensions?.[OPENPENCIL_EXTENSION]
+ return {
+ ...token,
+ $extensions: {
+ ...token.$extensions,
+ [OPENPENCIL_EXTENSION]: { ...(isPlainObject(own) ? own : {}), name }
+ }
+ }
+}
diff --git a/packages/core/src/io/formats/design-tokens/types.ts b/packages/core/src/io/formats/design-tokens/types.ts
new file mode 100644
index 000000000..b2310226c
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/types.ts
@@ -0,0 +1,57 @@
+/**
+ * W3C Design Tokens (DTCG 2025.10) as OpenPencil reads and writes them: one token file per
+ * collection mode, a resolver document tying them together, and a file of composite style tokens.
+ */
+
+/** The `$type` values OpenPencil writes, plus `string`, which Figma reads and writes. */
+export type DesignTokenType =
+ | 'color'
+ | 'dimension'
+ | 'duration'
+ | 'number'
+ | 'fontFamily'
+ | 'fontWeight'
+ | 'string'
+ | 'typography'
+ | 'shadow'
+
+/** A token as written: its value and the metadata DTCG and tools attach to it. */
+export interface DesignToken {
+ $type: DesignTokenType
+ $value: unknown
+ $description?: string
+ $extensions?: Record<string, unknown>
+}
+
+/** A token document or group: tokens and nested groups by name, and `$` properties. */
+export type DesignTokenGroup = { [name: string]: unknown }
+
+/** A file of the export, by its path relative to the export's root. */
+export interface DesignTokenFile {
+ path: string
+ content: DesignTokenGroup
+}
+
+/** Why a token, mode, or style was left out or changed; the names are as the document has them. */
+export type DesignTokenIssue =
+ | { kind: 'missing-value'; collection: string; mode: string; token: string }
+ | { kind: 'missing-alias'; collection: string; mode: string; token: string }
+ | { kind: 'duplicate-path'; collection: string; token: string }
+ | { kind: 'unsupported-effect'; style: string }
+
+/** An issue as one line of text, for the CLI and tool output. */
+export function designTokenIssueMessage(issue: DesignTokenIssue): string {
+ if (issue.kind === 'missing-value')
+ return `${issue.collection} / ${issue.mode}: ${issue.token} has no value in this mode`
+ if (issue.kind === 'missing-alias')
+ return `${issue.collection} / ${issue.mode}: ${issue.token} points at a variable that is gone`
+ if (issue.kind === 'duplicate-path')
+ return `${issue.collection}: ${issue.token} has the same token path as another variable`
+ return `${issue.style}: an effect style with no visible shadow has no token`
+}
+
+/** The key OpenPencil's own token data is kept under in `$extensions`. */
+export const OPENPENCIL_EXTENSION = 'dev.openpencil'
+
+/** The resolver document version DTCG 2025.10 requires. */
+export const RESOLVER_VERSION = '2025-11-01'
diff --git a/packages/core/src/io/formats/design-tokens/values.ts b/packages/core/src/io/formats/design-tokens/values.ts
new file mode 100644
index 000000000..57942f709
--- /dev/null
+++ b/packages/core/src/io/formats/design-tokens/values.ts
@@ -0,0 +1,65 @@
+import { variableUnit } from '@open-pencil/dom-css/export'
+import type { Color, TokenUnit, Variable } from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
+
+import type { DesignTokenType } from './types'
+
+/** Six decimals hold every value the canvas draws without float noise such as `0.30000000000000004`. */
+export function trimNumber(value: number): number {
+ return Number(value.toFixed(6))
+}
+
+/** A string token that names fonts and nothing else. */
+function namesFontFamily(variable: Variable): boolean {
+ const scopes = variable.scopes ?? []
+ return scopes.length > 0 && scopes.every((scope) => scope === 'FONT_FAMILY')
+}
+
+/**
+ * The DTCG type a variable is written as, chosen so Figma can import it: lengths are
+ * `dimension` in px, times `duration` in s, other numbers and booleans `number`, and text that
+ * names fonts `fontFamily`, other text `string`.
+ */
+export function variableTokenType(variable: Variable): DesignTokenType {
+ if (variable.type === 'COLOR') return 'color'
+ if (variable.type === 'BOOLEAN') return 'number'
+ if (variable.type === 'STRING') return namesFontFamily(variable) ? 'fontFamily' : 'string'
+ const unit = variableUnit(variable)
+ if (unit === 'px' || unit === 'rem') return 'dimension'
+ if (unit === 'ms' || unit === 's') return 'duration'
+ return 'number'
+}
+
+/** A color as DTCG 2025.10 writes it: sRGB components, alpha, and the hex code tools display. */
+export function colorTokenValue(color: Color) {
+ return {
+ colorSpace: 'srgb',
+ components: [trimNumber(color.r), trimNumber(color.g), trimNumber(color.b)],
+ alpha: trimNumber(color.a),
+ hex: colorToHex(color).toLowerCase()
+ }
+}
+
+/** A canvas length in px, which is how lengths are stored and how Figma reads them. */
+export function dimensionTokenValue(px: number) {
+ return { value: trimNumber(px), unit: 'px' }
+}
+
+/** A time in s, the one duration unit Figma reads; `ms` tokens are stored in milliseconds. */
+function durationTokenValue(value: number, unit: TokenUnit) {
+ return { value: trimNumber(unit === 'ms' ? value / 1000 : value), unit: 's' }
+}
+
+/** A variable's own value in the shape its token type takes. */
+export function literalTokenValue(
+ variable: Variable,
+ value: Color | number | string | boolean
+): unknown {
+ if (typeof value === 'object') return colorTokenValue(value)
+ if (typeof value === 'boolean') return value ? 1 : 0
+ if (typeof value === 'string') return value
+ const type = variableTokenType(variable)
+ if (type === 'dimension') return dimensionTokenValue(value)
+ if (type === 'duration') return durationTokenValue(value, variableUnit(variable))
+ return trimNumber(value)
+}
diff --git a/packages/core/src/rpc/variables-command.ts b/packages/core/src/rpc/variables-command.ts
index 40e7d946a..2ff5730a2 100644
--- a/packages/core/src/rpc/variables-command.ts
+++ b/packages/core/src/rpc/variables-command.ts
@@ -101,11 +101,25 @@ function variableType(value: string | undefined): VariableType | undefined {
return type
}
+/** W3C design token files instead of a stylesheet, for `--format dtcg`. */
+async function designTokenFiles(graph: SceneGraph): Promise<TokensResult> {
+ const { designTokenIssueMessage, exportDesignTokens } =
+ await import('#core/io/formats/design-tokens')
+ const { files, issues } = exportDesignTokens(graph)
+ return {
+ css: '',
+ tokenCount: graph.variables.size,
+ issues: issues.map(designTokenIssueMessage),
+ files
+ }
+}
+
export const tokensCommand: RPCCommand<TokensArgs, TokensResult> = {
name: 'tokens',
execute: (graph, args) => {
+ if (args.format === 'dtcg') return designTokenFiles(graph)
if (args.format && args.format !== 'css' && args.format !== 'tailwind')
- throw new Error(`Unknown token format: ${args.format}. Use css or tailwind.`)
+ throw new Error(`Unknown token format: ${args.format}. Use css, tailwind, or dtcg.`)
return exportTokenStylesheet(graph, {
format: args.format === 'tailwind' ? 'tailwind' : 'css',
collection: args.collection,
diff --git a/packages/core/src/tools/codegen.ts b/packages/core/src/tools/codegen.ts
index b48f7fe4c..38de3a8b7 100644
--- a/packages/core/src/tools/codegen.ts
+++ b/packages/core/src/tools/codegen.ts
@@ -1,2 +1,2 @@
export { designToComponentMap } from './codegen/component-map'
-export { designToTokens } from './codegen/tokens'
+export { designToTokens, importDesignTokens } from './codegen/tokens'
diff --git a/packages/core/src/tools/codegen/tokens.ts b/packages/core/src/tools/codegen/tokens.ts
index 3569c19f2..8cb969884 100644
--- a/packages/core/src/tools/codegen/tokens.ts
+++ b/packages/core/src/tools/codegen/tokens.ts
@@ -2,6 +2,7 @@ import * as v from 'valibot'
import type { SceneGraph, VariableType } from '@open-pencil/scene-graph'
+import type { DesignTokenFile } from '#core/io/formats/design-tokens'
import { defineTool } from '#core/tools/schema'
export type TokenExportOptions = {
@@ -11,7 +12,13 @@ export type TokenExportOptions = {
type?: VariableType
}
-export type TokenExport = { css: string; tokenCount: number; issues: string[] }
+export type TokenExport = {
+ css: string
+ tokenCount: number
+ issues: string[]
+ /** W3C design token files, for the `dtcg` format. */
+ files?: DesignTokenFile[]
+}
/** The document's variables as a token stylesheet, shared by the tool, the CLI, and the app. */
export async function exportTokenStylesheet(
@@ -43,13 +50,15 @@ export async function exportTokenStylesheet(
export const designToTokens = defineTool({
name: 'design_to_tokens',
description:
- '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.',
+ '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. The dtcg format returns W3C design token files instead: one per collection mode, text and effect styles as typography and shadow tokens, and a resolver document; collection and type filters do not apply to it. 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']),
- v.description('css: :root and mode scopes; tailwind: @theme, mode scopes and variants')
+ v.picklist(['css', 'tailwind', 'dtcg']),
+ v.description(
+ 'css: :root and mode scopes; tailwind: @theme, mode scopes and variants; dtcg: W3C design token files'
+ )
),
'css'
),
@@ -64,7 +73,55 @@ export const designToTokens = defineTool({
)
}),
execute: async (figma, args) => {
- const { css, tokenCount, issues } = await exportTokenStylesheet(figma.graph, args)
+ if (args.format === 'dtcg') {
+ const { designTokenIssueMessage, exportDesignTokens } =
+ await import('#core/io/formats/design-tokens')
+ const { files, issues } = exportDesignTokens(figma.graph)
+ return { files, issues: issues.map(designTokenIssueMessage) }
+ }
+ const { css, tokenCount, issues } = await exportTokenStylesheet(figma.graph, {
+ ...args,
+ format: args.format
+ })
return { output: css, tokenCount, issues }
}
})
+
+export const importDesignTokens = defineTool({
+ name: 'import_design_tokens',
+ description:
+ 'Import W3C design token (DTCG) files into the document as variables, and typography and shadow tokens as text and effect styles. Pass each file with its path: a file per mode grouped by folder (as Figma exports modes), a .resolver.json with the files it refers to, or a Tokens Studio file with $themes. Collections and modes with the same names as existing ones are updated, variables are matched by name, and nothing is deleted. Returns what was added, updated, and skipped and why.',
+ execution: { kind: 'async', mutation: 'document' },
+ input: v.object({
+ files: v.pipe(
+ v.array(v.object({ path: v.string(), text: v.string() })),
+ v.minLength(1),
+ v.description('Token files, each with its path (folders name collections) and JSON text')
+ ),
+ add_missing: v.optional(
+ v.pipe(v.boolean(), v.description('Add tokens that match no variable (default true)')),
+ true
+ ),
+ styles: v.optional(
+ v.pipe(v.boolean(), v.description('Make text and effect styles (default true)')),
+ true
+ )
+ }),
+ execute: async (figma, args) => {
+ const tokens = await import('#core/io/formats/design-tokens')
+ const bundle = tokens.readDesignTokens(args.files)
+ const options = {
+ ...tokens.defaultTokenImportOptions(figma.graph, bundle),
+ addMissing: args.add_missing,
+ styles: args.styles
+ }
+ const plan = tokens.planTokenImport(figma.graph, bundle, options)
+ tokens.importTokensIntoGraph(figma.graph, figma.currentPageId, plan)
+ return {
+ ...plan.counts,
+ collections: plan.collections.map((collection) => collection.name),
+ skipped: plan.skipped,
+ issues: bundle.issues
+ }
+ }
+})
diff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.ts
index f5f1f4b20..a55e62d56 100644
--- a/packages/core/src/tools/registry-extended.ts
+++ b/packages/core/src/tools/registry-extended.ts
@@ -9,7 +9,7 @@ import {
lint,
lintFix
} from './analyze'
-import { designToComponentMap, designToTokens } from './codegen'
+import { designToComponentMap, designToTokens, importDesignTokens } from './codegen'
import {
createComponent,
createInstance,
@@ -209,5 +209,6 @@ export const EXTENDED_TOOLS: ToolDef[] = [
diffApply,
// Codegen
designToTokens,
+ importDesignTokens,
designToComponentMap
]
diff --git a/packages/core/tests/canvas/component-set.test.ts b/packages/core/tests/canvas/component-set.test.ts
index 4f4f83d9c..712f0b562 100644
--- a/packages/core/tests/canvas/component-set.test.ts
+++ b/packages/core/tests/canvas/component-set.test.ts
@@ -1,12 +1,13 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
import { SkiaRenderer } from '#core/canvas/renderer'
import { getCanvasKit } from '#core/canvaskit'
import { renderNodesToImage } from '#core/io/formats/raster/render'
-import { SceneGraph } from '@open-pencil/scene-graph'
-
let ck: Awaited<ReturnType<typeof getCanvasKit>>
beforeAll(async () => {
diff --git a/packages/core/tests/canvas/constraint-resize.test.ts b/packages/core/tests/canvas/constraint-resize.test.ts
index 5473cf941..1d74ea2ae 100644
--- a/packages/core/tests/canvas/constraint-resize.test.ts
+++ b/packages/core/tests/canvas/constraint-resize.test.ts
@@ -1,13 +1,13 @@
-import { resolve } from 'node:path'
import { expect, test } from 'bun:test'
+import { resolve } from 'node:path'
import { SkiaRenderer } from '@open-pencil/core'
import { initCanvasKit, renderNodesToImage } from '@open-pencil/core/io'
import { materializeDocument } from '@open-pencil/fig'
import { expectDefined } from '../helpers/assert'
-import { FIXTURES } from '../helpers/fig/fixtures'
import { absoluteConstraintRecords } from '../helpers/fig/absolute-constraints'
+import { FIXTURES } from '../helpers/fig/fixtures'
test('absolute resize constraints match native Figma pixels', async () => {
const { graph, sources } = materializeDocument(absoluteConstraintRecords())
@@ -38,9 +38,7 @@ test('absolute resize constraints match native Figma pixels', async () => {
})
)
const native = new Uint8Array(
- await Bun.file(
- resolve(FIXTURES, 'absolute-constraint-figma.png')
- ).arrayBuffer()
+ await Bun.file(resolve(FIXTURES, 'absolute-constraint-figma.png')).arrayBuffer()
)
expect(decode(png)).toEqual(decode(native))
} finally {
diff --git a/packages/core/tests/canvas/instance-scale.test.ts b/packages/core/tests/canvas/instance-scale.test.ts
index 105e50b69..d349a7a66 100644
--- a/packages/core/tests/canvas/instance-scale.test.ts
+++ b/packages/core/tests/canvas/instance-scale.test.ts
@@ -1,5 +1,5 @@
-import { resolve } from 'node:path'
import { expect, test } from 'bun:test'
+import { resolve } from 'node:path'
import { SkiaRenderer } from '@open-pencil/core'
import { createEditor } from '@open-pencil/core/editor'
@@ -9,13 +9,13 @@ import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { rescaleNodeTree } from '@open-pencil/scene-graph'
import { expectDefined } from '../helpers/assert'
-import { inheritedNestedBindingRecords } from '../helpers/fig/nested-binding'
import {
CapturedFigRecords,
FIXTURES,
NestedLayoutScaleFixture,
readFixture
} from '../helpers/fig/fixtures'
+import { inheritedNestedBindingRecords } from '../helpers/fig/nested-binding'
const fixture = readFixture('nested-layout-scale.json', NestedLayoutScaleFixture)
diff --git a/packages/core/tests/canvas/issues/layout.test.ts b/packages/core/tests/canvas/issues/layout.test.ts
index 11b800def..b4be8bb93 100644
--- a/packages/core/tests/canvas/issues/layout.test.ts
+++ b/packages/core/tests/canvas/issues/layout.test.ts
@@ -66,7 +66,11 @@ describe('issue marker layout', () => {
height: 50
})
- const placed = layoutIssueMarkers(graph, [warning(outside.id), warning(overflowing.id)], options)
+ const placed = layoutIssueMarkers(
+ graph,
+ [warning(outside.id), warning(overflowing.id)],
+ options
+ )
expect(placed.map((marker) => marker.nodeIds)).toEqual([[overflowing.id]])
expect(placed[0]?.anchor).toEqual({ x: 300, y: 200 })
diff --git a/packages/core/tests/canvas/text/derived.test.ts b/packages/core/tests/canvas/text/derived.test.ts
index f951ae482..7ca99cf12 100644
--- a/packages/core/tests/canvas/text/derived.test.ts
+++ b/packages/core/tests/canvas/text/derived.test.ts
@@ -1,12 +1,13 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
import { SkiaRenderer } from '#core/canvas/renderer'
import { getCanvasKit } from '#core/canvaskit'
import { renderNodesToImage } from '#core/io/formats/raster/render'
-import { SceneGraph } from '@open-pencil/scene-graph'
-
let ck: Awaited<ReturnType<typeof getCanvasKit>>
beforeAll(async () => {
diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.ts
index 8c2718162..2036f8ef9 100644
--- a/packages/core/tests/canvas/text/shape.test.ts
+++ b/packages/core/tests/canvas/text/shape.test.ts
@@ -1,15 +1,16 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
-import { withFigExportRuntime } from '#core/canvas/text/shape'
-import { getCanvasKit } from '#core/canvaskit'
-import { fontManager } from '#core/text/fonts'
-import { getGlyphOutlineMetricsSync } from '#core/text/opentype'
import type { ShapedText } from '@open-pencil/fig/node-change'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { SceneNode } from '@open-pencil/scene-graph'
+import { withFigExportRuntime } from '#core/canvas/text/shape'
+import { getCanvasKit } from '#core/canvaskit'
+import { fontManager } from '#core/text/fonts'
+import { getGlyphOutlineMetricsSync } from '#core/text/opentype'
+
const SENTENCE = 'A sentence long enough that it has to wrap onto a second line.'
async function shape(props: Partial<SceneNode>): Promise<ShapedText | null> {
diff --git a/packages/core/tests/clipboard/figma/replacement-import.test.ts b/packages/core/tests/clipboard/figma/replacement-import.test.ts
index f9f2c74a4..219633930 100644
--- a/packages/core/tests/clipboard/figma/replacement-import.test.ts
+++ b/packages/core/tests/clipboard/figma/replacement-import.test.ts
@@ -1,13 +1,13 @@
import { expect, test } from 'bun:test'
+import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
+
import { SceneGraph } from '@open-pencil/scene-graph'
import { prepareClipboardImport } from '#core/clipboard/fig-import'
-import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
const fixture = readFixture('nested-binding-ownership-records.json', CapturedFigRecords)
-
test('replacement clipboard preparation imports real nested component bindings', () => {
const graph = new SceneGraph()
const operation = prepareClipboardImport(
diff --git a/packages/core/tests/clipboard/openpencil.test.ts b/packages/core/tests/clipboard/openpencil.test.ts
index 4fc6076b5..926920872 100644
--- a/packages/core/tests/clipboard/openpencil.test.ts
+++ b/packages/core/tests/clipboard/openpencil.test.ts
@@ -38,7 +38,10 @@ describe('OpenPencil clipboard parsing', () => {
],
[
'a node with an unknown type',
- JSON.stringify({ format: 'openpencil/v1', nodes: [{ id: '0:1', type: 'WIDGET', x: 5, y: 6 }] })
+ JSON.stringify({
+ format: 'openpencil/v1',
+ nodes: [{ id: '0:1', type: 'WIDGET', x: 5, y: 6 }]
+ })
],
[
'a malformed child',
diff --git a/packages/core/tests/design-jsx/export-round-trip.test.ts b/packages/core/tests/design-jsx/export-round-trip.test.ts
index 05c5a2dee..1d83ac274 100644
--- a/packages/core/tests/design-jsx/export-round-trip.test.ts
+++ b/packages/core/tests/design-jsx/export-round-trip.test.ts
@@ -1,13 +1,13 @@
import { describe, expect, it, test } from 'bun:test'
+
+import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
+import { findByName, PROPERTY_CASES } from '#core-tests/helpers/property-cases'
import { pick } from 'es-toolkit'
import { renderJSX } from '@open-pencil/core/design-jsx'
import { sceneNodeToJSX } from '@open-pencil/design-jsx'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
-import { findByName, PROPERTY_CASES } from '#core-tests/helpers/property-cases'
-
describe('attribute string round-trip', () => {
it.each([
// Unescaped, this name would inject `w={999}` into the exported frame.
diff --git a/packages/core/tests/design-jsx/grid.test.ts b/packages/core/tests/design-jsx/grid.test.ts
index 9b845ceae..027dd53ea 100644
--- a/packages/core/tests/design-jsx/grid.test.ts
+++ b/packages/core/tests/design-jsx/grid.test.ts
@@ -1,10 +1,10 @@
import { expect, test } from 'bun:test'
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
import { renderJSX } from '@open-pencil/core/design-jsx'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { getNodeOrThrow } from '#core-tests/helpers/assert'
-
test('a repeat() grid places its cells in equal columns, not collapsed ones', async () => {
const graph = new SceneGraph()
const cells = Array.from({ length: 14 }, (_, i) => `<Frame name="C${i}" w={20} h={36} />`)
diff --git a/packages/core/tests/design-jsx/renderer.test.ts b/packages/core/tests/design-jsx/renderer.test.ts
index 38fc18bb3..440cfafc8 100644
--- a/packages/core/tests/design-jsx/renderer.test.ts
+++ b/packages/core/tests/design-jsx/renderer.test.ts
@@ -7,8 +7,18 @@ import { SceneGraph } from '@open-pencil/scene-graph'
describe('renderTree onNode', () => {
test('reports every element with the layer rendered from it', async () => {
const graph = new SceneGraph()
- const text: TreeNode = { type: 'text', props: { name: 'Title' }, children: ['Hi'], source: { line: 2 } }
- const root: TreeNode = { type: 'frame', props: { name: 'Card' }, children: [text], source: { line: 1 } }
+ const text: TreeNode = {
+ type: 'text',
+ props: { name: 'Title' },
+ children: ['Hi'],
+ source: { line: 2 }
+ }
+ const root: TreeNode = {
+ type: 'frame',
+ props: { name: 'Card' },
+ children: [text],
+ source: { line: 1 }
+ }
const seen: Array<[number | undefined, string]> = []
const result = await renderTree(graph, root, {
diff --git a/packages/core/tests/editor/clipboard/binding-corruption.test.ts b/packages/core/tests/editor/clipboard/binding-corruption.test.ts
index 01bef975e..1d00fed49 100644
--- a/packages/core/tests/editor/clipboard/binding-corruption.test.ts
+++ b/packages/core/tests/editor/clipboard/binding-corruption.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, test } from 'bun:test'
+import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
+
import { SceneGraph } from '@open-pencil/core'
import { collectSubtrees } from '@open-pencil/core/editor/clipboard/subtree-history'
import { createInstanceOverrideState } from '@open-pencil/scene-graph'
-import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
-
function pageId(graph: SceneGraph): string {
return graph.getPages()[0].id
}
diff --git a/packages/core/tests/editor/clipboard/delete.test.ts b/packages/core/tests/editor/clipboard/delete.test.ts
index 8ceeb257a..1c5d1d971 100644
--- a/packages/core/tests/editor/clipboard/delete.test.ts
+++ b/packages/core/tests/editor/clipboard/delete.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, test } from 'bun:test'
-import { createEditor } from '@open-pencil/core/editor'
-import { computeAllLayouts } from '@open-pencil/core/layout'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { autoFrame, rect } from '#core-tests/helpers/layout'
+import { createEditor } from '@open-pencil/core/editor'
+import { computeAllLayouts } from '@open-pencil/core/layout'
+
describe('deleteSelected', () => {
test('reflows fixed vertical auto-layout siblings', () => {
const editor = createEditor()
diff --git a/packages/core/tests/editor/clipboard/fig-transfer-history.test.ts b/packages/core/tests/editor/clipboard/fig-transfer-history.test.ts
index 3c1144027..a79e42c51 100644
--- a/packages/core/tests/editor/clipboard/fig-transfer-history.test.ts
+++ b/packages/core/tests/editor/clipboard/fig-transfer-history.test.ts
@@ -1,14 +1,14 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
+
import { buildFigmaClipboardHTML } from '@open-pencil/core/clipboard'
import { createEditor } from '@open-pencil/core/editor'
import { initCodec } from '@open-pencil/core/kiwi'
import { materializeFigFragment } from '@open-pencil/fig'
import { CommittedGraphEventError } from '@open-pencil/scene-graph'
-import { expectDefined } from '#core-tests/helpers/assert'
-import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
-
const fixture = readFixture('nested-binding-ownership-records.json', CapturedFigRecords)
for (const failObserver of [false, true]) {
diff --git a/packages/core/tests/editor/clipboard/figma-images.test.ts b/packages/core/tests/editor/clipboard/figma-images.test.ts
index 785d884fc..911127f26 100644
--- a/packages/core/tests/editor/clipboard/figma-images.test.ts
+++ b/packages/core/tests/editor/clipboard/figma-images.test.ts
@@ -1,12 +1,12 @@
import { beforeAll, describe, expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { initCodec } from '@open-pencil/core'
import { buildFigmaClipboardHTML } from '@open-pencil/core/clipboard'
import { createEditor } from '@open-pencil/core/editor'
import type { ClipboardImageResolution } from '@open-pencil/core/editor'
-import { expectDefined } from '#core-tests/helpers/assert'
-
const IMAGE_HASH_A = '1111111111111111111111111111111111111111'
const IMAGE_HASH_B = '2222222222222222222222222222222222222222'
diff --git a/packages/core/tests/editor/clipboard/import-nodes/components.test.ts b/packages/core/tests/editor/clipboard/import-nodes/components.test.ts
index 70923e9e8..d3f240647 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/components.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/components.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from 'bun:test'
-import { importClipboardNodes } from '@open-pencil/core'
-import type { NodeChange } from '@open-pencil/core'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createClipboardGraph } from '#core-tests/helpers/clipboard'
+import { importClipboardNodes } from '@open-pencil/core'
+import type { NodeChange } from '@open-pencil/core'
+
describe('importClipboardNodes: components', () => {
it('maps SYMBOL type to COMPONENT with auto-layout', () => {
const { graph, pageId } = createClipboardGraph()
diff --git a/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts b/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts
index 6ebcbfd3b..5194bee56 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/filtering.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from 'bun:test'
-import { importClipboardNodes } from '@open-pencil/core'
-import type { NodeChange } from '@open-pencil/core'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createClipboardGraph } from '#core-tests/helpers/clipboard'
+import { importClipboardNodes } from '@open-pencil/core'
+import type { NodeChange } from '@open-pencil/core'
+
describe('importClipboardNodes: filtering', () => {
it('skips VARIABLE_SET and VARIABLE nodes', () => {
const { graph, pageId } = createClipboardGraph()
diff --git a/packages/core/tests/editor/clipboard/import-nodes/hierarchy.test.ts b/packages/core/tests/editor/clipboard/import-nodes/hierarchy.test.ts
index f897b4efe..c3bc13d55 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/hierarchy.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/hierarchy.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from 'bun:test'
-import { importClipboardNodes } from '@open-pencil/core'
-import type { NodeChange } from '@open-pencil/core'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createClipboardGraph } from '#core-tests/helpers/clipboard'
+import { importClipboardNodes } from '@open-pencil/core'
+import type { NodeChange } from '@open-pencil/core'
+
describe('importClipboardNodes: hierarchy', () => {
it('imports nested frames with children', () => {
const { graph, pageId } = createClipboardGraph()
diff --git a/packages/core/tests/editor/clipboard/import-nodes/instance-linkage.test.ts b/packages/core/tests/editor/clipboard/import-nodes/instance-linkage.test.ts
index 1010ba50b..66e75791d 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/instance-linkage.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/instance-linkage.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, it } from 'bun:test'
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
import { importClipboardNodes } from '@open-pencil/core'
import type { NodeChange } from '@open-pencil/core'
import { linkImportedInstanceChildren } from '@open-pencil/fig/node-change'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { getNodeOrThrow } from '#core-tests/helpers/assert'
-
describe('importClipboardNodes: instance child linkage', () => {
it('links serialized instance children so a later component sync does not duplicate them', () => {
const graph = new SceneGraph()
diff --git a/packages/core/tests/editor/clipboard/import-nodes/styling.test.ts b/packages/core/tests/editor/clipboard/import-nodes/styling.test.ts
index 9173b5701..04dcf4fd1 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/styling.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/styling.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from 'bun:test'
-import { importClipboardNodes } from '@open-pencil/core'
-import type { NodeChange } from '@open-pencil/core'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createClipboardGraph } from '#core-tests/helpers/clipboard'
+import { importClipboardNodes } from '@open-pencil/core'
+import type { NodeChange } from '@open-pencil/core'
+
describe('importClipboardNodes: styling', () => {
it('preserves fills and strokes', () => {
const { graph, pageId } = createClipboardGraph()
diff --git a/packages/core/tests/editor/clipboard/import-nodes/text/metrics.test.ts b/packages/core/tests/editor/clipboard/import-nodes/text/metrics.test.ts
index 93937b7ce..d5c454ae9 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/text/metrics.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/text/metrics.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from 'bun:test'
-import { importClipboardNodes } from '@open-pencil/core'
-import type { NodeChange } from '@open-pencil/core'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createClipboardGraph } from '#core-tests/helpers/clipboard'
+import { importClipboardNodes } from '@open-pencil/core'
+import type { NodeChange } from '@open-pencil/core'
+
describe('importClipboardNodes: text metrics', () => {
it('imports fontWeight from fontName.style via styleToWeight', () => {
const { graph, pageId } = createClipboardGraph()
diff --git a/packages/core/tests/editor/clipboard/import-nodes/undo/redo.test.ts b/packages/core/tests/editor/clipboard/import-nodes/undo/redo.test.ts
index 7c6556d65..e2f7377d2 100644
--- a/packages/core/tests/editor/clipboard/import-nodes/undo/redo.test.ts
+++ b/packages/core/tests/editor/clipboard/import-nodes/undo/redo.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from 'bun:test'
-import { importClipboardNodes } from '@open-pencil/core'
-import type { NodeChange, SceneNode } from '@open-pencil/core'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createClipboardGraph } from '#core-tests/helpers/clipboard'
+import { importClipboardNodes } from '@open-pencil/core'
+import type { NodeChange, SceneNode } from '@open-pencil/core'
+
describe('importClipboardNodes: undo redo', () => {
it('undo removes all imported nodes including children', () => {
const { graph, pageId } = createClipboardGraph()
diff --git a/packages/core/tests/editor/clipboard/placement.test.ts b/packages/core/tests/editor/clipboard/placement.test.ts
index 31cbb0d00..68c074d1a 100644
--- a/packages/core/tests/editor/clipboard/placement.test.ts
+++ b/packages/core/tests/editor/clipboard/placement.test.ts
@@ -36,10 +36,17 @@ describe('duplicate placement', () => {
test('duplicates a layer on top of the original', () => {
const page = setup()
const frame = node('FRAME', page, { width: 200, height: 200 })
- for (const original of [node('RECTANGLE', page, { x: 100, y: 100 }), node('FRAME', frame.id, { x: 50, y: 50 })]) {
+ for (const original of [
+ node('RECTANGLE', page, { x: 100, y: 100 }),
+ node('FRAME', frame.id, { x: 50, y: 50 })
+ ]) {
editor.select([original.id])
editor.duplicateSelected()
- expect(selected()).toMatchObject({ parentId: original.parentId, x: original.x, y: original.y })
+ expect(selected()).toMatchObject({
+ parentId: original.parentId,
+ x: original.x,
+ y: original.y
+ })
}
})
diff --git a/packages/core/tests/editor/components/behaviours.test.ts b/packages/core/tests/editor/components/behaviours.test.ts
index 287ea9aff..6411175a7 100644
--- a/packages/core/tests/editor/components/behaviours.test.ts
+++ b/packages/core/tests/editor/components/behaviours.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, test } from 'bun:test'
-import { createEditor } from '@open-pencil/core/editor'
import { expectDefined } from '#core-tests/helpers/assert'
+
+import { createEditor } from '@open-pencil/core/editor'
import {
emptyBehaviour,
missingBindings,
@@ -12,7 +13,9 @@ import {
describe('setBehaviour', () => {
test('adds, edits, and removes as single undo steps', () => {
const editor = createEditor()
- const set = editor.graph.createNode('COMPONENT_SET', editor.state.currentPageId, { name: 'Switch' })
+ const set = editor.graph.createNode('COMPONENT_SET', editor.state.currentPageId, {
+ name: 'Switch'
+ })
editor.setBehaviour(set.id, emptyBehaviour('switch'))
expect(editor.undo.undoLabel).toBe('Add behaviour')
editor.setBehaviour(set.id, { ...emptyBehaviour('switch'), parts: { thumb: 'x' } })
@@ -59,9 +62,7 @@ describe('completing a behaviour', () => {
editor.undo.undo()
expect(editor.undo.undoLabel).toBe(undoDepth)
- expect(editor.graph.getChildren(component.id).map((child) => child.type)).toEqual([
- 'RECTANGLE'
- ])
+ expect(editor.graph.getChildren(component.id).map((child) => child.type)).toEqual(['RECTANGLE'])
expect(behaviour()?.texts).toEqual({})
expect(editor.graph.getNode(component.id)?.componentPropertyDefinitions).toEqual([])
})
@@ -70,15 +71,15 @@ describe('completing a behaviour', () => {
const { editor, component } = bareComponent('textField')
const label = editor.graph.createNode('TEXT', component.id, { name: 'Label', text: 'Email' })
const id = expectDefined(editor.addBehaviourText(component.id, 'value', 'Text'), 'property id')
- expect(editor.graph.getChildren(component.id).filter((child) => child.type === 'TEXT')).toHaveLength(
- 1
- )
+ expect(
+ editor.graph.getChildren(component.id).filter((child) => child.type === 'TEXT')
+ ).toHaveLength(1)
expect(editor.graph.getNode(label.id)?.componentPropertyReferences).toEqual([
{ propertyId: id, field: 'TEXT' }
])
- expect(
- editor.graph.getNode(component.id)?.componentPropertyDefinitions[0]?.defaultValue
- ).toBe('Email')
+ expect(editor.graph.getNode(component.id)?.componentPropertyDefinitions[0]?.defaultValue).toBe(
+ 'Email'
+ )
})
test('a switch set gets Off and On variants of each variant in one step', () => {
@@ -116,7 +117,10 @@ describe('completing a behaviour', () => {
test('a lone slider gets state variants as a new set that keeps its behaviour, in one step', () => {
const { editor, component } = bareComponent('slider')
- const track = expectDefined(editor.addBehaviourPart(component.id, 'track', 'Track'), 'property id')
+ const track = expectDefined(
+ editor.addBehaviourPart(component.id, 'track', 'Track'),
+ 'property id'
+ )
const page = editor.state.currentPageId
const undoDepth = editor.undo.undoLabel
@@ -162,7 +166,9 @@ describe('completing a behaviour', () => {
editor.setBehaviour(set.id, emptyBehaviour('switch'))
editor.addBehaviourVariant(set.id, 'value', 'State')
editor.addBehaviourStates(set.id)
- const names = editor.graph.getNode(set.id)?.componentPropertyDefinitions.map((item) => item.name)
+ const names = editor.graph
+ .getNode(set.id)
+ ?.componentPropertyDefinitions.map((item) => item.name)
expect(names).toEqual(['State', 'Interaction'])
expect(editor.graph.getChildren(set.id)).toHaveLength(10)
})
@@ -172,7 +178,11 @@ describe('completing a behaviour', () => {
const id = expectDefined(editor.addBehaviourVariant(component.id, 'value', 'On'), 'property id')
const set = editor.graph.getNode(component.parentId ?? '')
expect(set?.type).toBe('COMPONENT_SET')
- expect(set && readBehaviour(set)?.booleans.value).toEqual({ propertyId: id, on: 'On', off: 'Off' })
+ expect(set && readBehaviour(set)?.booleans.value).toEqual({
+ propertyId: id,
+ on: 'On',
+ off: 'Off'
+ })
})
test('a part added to a set is one slot in every variant', () => {
@@ -183,7 +193,9 @@ describe('completing a behaviour', () => {
const id = expectDefined(editor.addBehaviourPart(set.id, 'thumb', 'Thumb'), 'property id')
const slots = editor.graph
.getChildren(set.id)
- .map((variant) => editor.graph.getChildren(variant.id).find((child) => child.name === 'Thumb'))
+ .map((variant) =>
+ editor.graph.getChildren(variant.id).find((child) => child.name === 'Thumb')
+ )
expect(slots).toHaveLength(5)
for (const slot of slots)
expect(slot?.componentPropertyReferences).toEqual([{ propertyId: id, field: 'SLOT_CONTENT' }])
diff --git a/packages/core/tests/editor/components/combine-variants.test.ts b/packages/core/tests/editor/components/combine-variants.test.ts
index 3868f949c..e1a7ca3c6 100644
--- a/packages/core/tests/editor/components/combine-variants.test.ts
+++ b/packages/core/tests/editor/components/combine-variants.test.ts
@@ -8,7 +8,12 @@ import { FigmaAPI } from '@open-pencil/core/figma-api'
function components(editor: ReturnType<typeof createEditor>) {
const page = editor.state.currentPageId
- const a = editor.graph.createNode('COMPONENT', page, { name: 'v=a', x: 200, width: 60, height: 60 })
+ const a = editor.graph.createNode('COMPONENT', page, {
+ name: 'v=a',
+ x: 200,
+ width: 60,
+ height: 60
+ })
const b = editor.graph.createNode('COMPONENT', page, {
name: 'v=b',
x: 300,
diff --git a/packages/core/tests/editor/components/slots/content.test.ts b/packages/core/tests/editor/components/slots/content.test.ts
index 28bb826ff..6f1e36e35 100644
--- a/packages/core/tests/editor/components/slots/content.test.ts
+++ b/packages/core/tests/editor/components/slots/content.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { createEditor } from '@open-pencil/core/editor'
import { ownsSlotContent, slotPropertyId, type SceneNode } from '@open-pencil/scene-graph'
-import { expectDefined } from '#core-tests/helpers/assert'
-
/** A Card component whose `Body` slot holds `Default`, an instance of it, and a free layer. */
function setup() {
const editor = createEditor()
diff --git a/packages/core/tests/editor/components/sync-layout-scope.test.ts b/packages/core/tests/editor/components/sync-layout-scope.test.ts
index 5b5aca81c..3e9b32394 100644
--- a/packages/core/tests/editor/components/sync-layout-scope.test.ts
+++ b/packages/core/tests/editor/components/sync-layout-scope.test.ts
@@ -1,10 +1,11 @@
import { describe, expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { computeAllLayouts } from '@open-pencil/core/layout'
import { SceneGraph } from '@open-pencil/scene-graph'
import { createComponentSyncScheduler } from '#core/editor/component-sync'
-import { expectDefined } from '#core-tests/helpers/assert'
function createGraph() {
const graph = new SceneGraph()
diff --git a/packages/core/tests/editor/components/transitive-sync.test.ts b/packages/core/tests/editor/components/transitive-sync.test.ts
index 8b4615888..41ce4c073 100644
--- a/packages/core/tests/editor/components/transitive-sync.test.ts
+++ b/packages/core/tests/editor/components/transitive-sync.test.ts
@@ -1,10 +1,10 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { createEditor } from '@open-pencil/core/editor'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { expectDefined } from '#core-tests/helpers/assert'
-
test('component edits propagate across definition dependencies and undo/redo', async () => {
const graph = new SceneGraph()
const page = graph.getPages()[0].id
diff --git a/packages/core/tests/editor/design-tokens.test.ts b/packages/core/tests/editor/design-tokens.test.ts
new file mode 100644
index 000000000..be88acd22
--- /dev/null
+++ b/packages/core/tests/editor/design-tokens.test.ts
@@ -0,0 +1,258 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { getSharedStyles, SceneGraph, type Variable } from '@open-pencil/scene-graph'
+
+import {
+ defaultTokenImportOptions,
+ exportDesignTokens,
+ planTokenImport,
+ readDesignTokens,
+ type DesignTokenSourceFile
+} from '#core/io/formats/design-tokens'
+
+const blue = { r: 0, g: 0.4, b: 0.8, a: 1 }
+const white = { r: 1, g: 1, b: 1, a: 1 }
+
+function designSystem() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const primitives = graph.createCollection('Primitives')
+ const brand = graph.createVariable('Blue/500', 'COLOR', primitives.id, blue)
+ const theme = graph.createCollection('Theme')
+ graph.renameMode(theme.id, theme.defaultModeId, 'Light')
+ const dark = graph.createMode(theme.id, 'Dark') ?? ''
+ const accent = graph.createVariable('Accent', 'COLOR', theme.id, { aliasId: brand.id })
+ accent.valuesByMode[dark] = white
+ const gutter = graph.createVariable('Space/Gutter', 'FLOAT', theme.id, 24)
+ gutter.unit = 'rem'
+ gutter.expressions = { [theme.defaultModeId]: { css: 'clamp(1rem, 4vw, 1.5rem)', resolved: 24 } }
+ graph.createVariable('Flags/Rounded', 'BOOLEAN', theme.id, true)
+ const fast = graph.createVariable('Motion/Fast', 'FLOAT', theme.id, 150)
+ fast.unit = 'ms'
+ const family = graph.createVariable('Font/Body', 'STRING', theme.id, 'Inter')
+ family.scopes = ['FONT_FAMILY']
+ const heading = graph.createNode('TEXT', page, {
+ name: 'Heading/H1',
+ fontFamily: 'Inter',
+ fontWeight: 700,
+ fontSize: 32,
+ lineHeight: 40,
+ sharedStyleType: 'TEXT',
+ internalOnly: true,
+ boundVariables: { fontFamily: family.id }
+ })
+ heading.source.id = 'style:heading'
+ return graph
+}
+
+function exported(graph: SceneGraph): DesignTokenSourceFile[] {
+ return exportDesignTokens(graph).files.map((file) => ({
+ path: file.path,
+ text: JSON.stringify(file.content)
+ }))
+}
+
+function importInto(graph: SceneGraph, files: DesignTokenSourceFile[]) {
+ const editor = createEditor({ graph })
+ const bundle = readDesignTokens(files)
+ const plan = planTokenImport(graph, bundle, defaultTokenImportOptions(graph, bundle))
+ return { editor, plan, result: editor.importDesignTokens(plan) }
+}
+
+function variableNamed(graph: SceneGraph, name: string): Variable {
+ const found = [...graph.variables.values()].find((variable) => variable.name === name)
+ if (!found) throw new Error(`missing ${name}`)
+ return found
+}
+
+describe('design token import', () => {
+ test('an export reads back into an empty document as it was', () => {
+ const graph = new SceneGraph()
+ const { plan } = importInto(graph, exported(designSystem()))
+
+ expect(plan.counts).toEqual({ added: 7, updated: 0, skipped: 0 })
+ const theme = [...graph.variableCollections.values()].find((entry) => entry.name === 'Theme')
+ expect(theme?.modes.map((mode) => mode.name)).toEqual(['Light', 'Dark'])
+ const [light, dark] = theme?.modes.map((mode) => mode.modeId) ?? []
+ const accent = variableNamed(graph, 'Accent')
+ expect(accent.valuesByMode[light]).toEqual({ aliasId: variableNamed(graph, 'Blue/500').id })
+ expect(accent.valuesByMode[dark]).toEqual(white)
+ expect(variableNamed(graph, 'Space/Gutter')).toMatchObject({
+ unit: 'rem',
+ valuesByMode: { [light]: 24 },
+ expressions: { [light]: { css: 'clamp(1rem, 4vw, 1.5rem)', resolved: 24 } }
+ })
+ // Written in seconds for Figma, read back into milliseconds.
+ expect(variableNamed(graph, 'Motion/Fast')).toMatchObject({
+ unit: 'ms',
+ valuesByMode: { [light]: 150 }
+ })
+ expect(variableNamed(graph, 'Flags/Rounded')).toMatchObject({
+ type: 'BOOLEAN',
+ valuesByMode: { [light]: true }
+ })
+
+ const [style] = getSharedStyles(graph, 'text')
+ const node = graph.getNode(style.nodeId)
+ expect(node).toMatchObject({
+ name: 'Heading/H1',
+ fontSize: 32,
+ lineHeight: 40,
+ fontWeight: 700
+ })
+ expect(node?.boundVariables.fontFamily).toBe(variableNamed(graph, 'Font/Body').id)
+ })
+
+ test('the whole import undoes in one step', () => {
+ const graph = new SceneGraph()
+ const { editor } = importInto(graph, exported(designSystem()))
+
+ editor.undo.undo()
+
+ expect(graph.variableCollections.size).toBe(0)
+ expect(graph.variables.size).toBe(0)
+ expect(getSharedStyles(graph, 'text')).toEqual([])
+ })
+
+ test('importing into a document updates variables by name and adds the rest', () => {
+ const graph = new SceneGraph()
+ const theme = graph.createCollection('Theme')
+ graph.renameMode(theme.id, theme.defaultModeId, 'Light')
+ const accent = graph.createVariable('Accent', 'COLOR', theme.id, { r: 1, g: 0, b: 0, a: 1 })
+ const keep = graph.createVariable('Kept', 'FLOAT', theme.id, 3)
+
+ const { plan } = importInto(graph, exported(designSystem()))
+
+ expect(graph.variables.get(accent.id)?.valuesByMode[theme.defaultModeId]).toEqual({
+ aliasId: variableNamed(graph, 'Blue/500').id
+ })
+ expect(graph.variables.get(keep.id)?.valuesByMode[theme.defaultModeId]).toBe(3)
+ expect(theme.modes.map((mode) => mode.name)).toEqual(['Light', 'Dark'])
+ expect(plan.counts.updated).toBe(1)
+ })
+
+ test('a token that names a variable of another type is skipped, not converted', () => {
+ const graph = new SceneGraph()
+ const theme = graph.createCollection('Theme')
+ graph.renameMode(theme.id, theme.defaultModeId, 'Light')
+ const accent = graph.createVariable('Accent', 'FLOAT', theme.id, 4)
+
+ const { plan } = importInto(graph, exported(designSystem()))
+
+ expect(plan.skipped).toContainEqual({
+ name: 'Accent',
+ collection: 'Theme',
+ reason: 'type-mismatch'
+ })
+ expect(graph.variables.get(accent.id)?.valuesByMode[theme.defaultModeId]).toBe(4)
+ })
+
+ test('tokens from another tool leave an updated variable’s unit, scopes, and code syntax', () => {
+ const graph = new SceneGraph()
+ const theme = graph.createCollection('Theme')
+ const space = graph.createVariable('Space', 'FLOAT', theme.id, 16)
+ space.unit = 'rem'
+ space.scopes = ['GAP']
+ space.codeSyntax = { WEB: '--space' }
+
+ importInto(graph, [
+ {
+ path: 'Theme/Mode 1.tokens.json',
+ text: JSON.stringify({ Space: { $type: 'number', $value: 24 } })
+ }
+ ])
+
+ expect(graph.variables.get(space.id)).toMatchObject({
+ unit: 'rem',
+ scopes: ['GAP'],
+ codeSyntax: { WEB: '--space' },
+ valuesByMode: { [theme.defaultModeId]: 24 }
+ })
+ })
+
+ test('updating a text style updates the layers that use it', () => {
+ const graph = designSystem()
+ const [style] = getSharedStyles(graph, 'text')
+ const layer = graph.createNode('TEXT', graph.getPages()[0].id, {
+ text: 'Title',
+ fontFamily: 'Inter',
+ fontSize: 32,
+ textStyleId: style.id
+ })
+ // Edited in another tool, which keeps OpenPencil's extension as it was.
+ const files = exported(designSystem()).map((file) =>
+ file.path === 'styles.tokens.json'
+ ? {
+ ...file,
+ text: file.text.replace(
+ '"fontSize":{"value":32,"unit":"px"}',
+ '"fontSize":{"value":40,"unit":"px"}'
+ )
+ }
+ : file
+ )
+
+ importInto(graph, files)
+
+ expect(graph.getNode(layer.id)).toMatchObject({ fontSize: 40, textStyleId: style.id })
+ })
+
+ test('a style token as OpenPencil wrote it keeps the exact fields its value cannot hold', () => {
+ const graph = new SceneGraph()
+ const source = designSystem()
+ const [heading] = getSharedStyles(source, 'text')
+ const node = source.getNode(heading.nodeId)
+ if (node) node.textCase = 'UPPER'
+
+ importInto(graph, exported(source))
+
+ const [style] = getSharedStyles(graph, 'text')
+ expect(graph.getNode(style.nodeId)).toMatchObject({ textCase: 'UPPER', lineHeight: 40 })
+ })
+
+ test('an edited shadow takes the place of the exact one, and the blur keeps its own', () => {
+ const source = new SceneGraph()
+ const shadow = (radius: number) => ({
+ type: 'DROP_SHADOW' as const,
+ color: { r: 0, g: 0, b: 0, a: 0.25 },
+ offset: { x: 0, y: 4 },
+ radius,
+ spread: 0,
+ visible: true
+ })
+ const card = source.createNode('RECTANGLE', source.getPages()[0].id, {
+ name: 'Card',
+ sharedStyleType: 'EFFECT',
+ internalOnly: true,
+ effects: [
+ shadow(12),
+ {
+ type: 'LAYER_BLUR',
+ color: { r: 0, g: 0, b: 0, a: 0 },
+ offset: { x: 0, y: 0 },
+ radius: 6,
+ spread: 0,
+ visible: true
+ },
+ shadow(2)
+ ]
+ })
+ card.source.id = 'style:card'
+ const files = exported(source).map((file) =>
+ file.path === 'styles.tokens.json'
+ ? { ...file, text: file.text.replace('"blur":{"value":12', '"blur":{"value":20') }
+ : file
+ )
+
+ const graph = new SceneGraph()
+ importInto(graph, files)
+
+ const [style] = getSharedStyles(graph, 'effect')
+ expect(graph.getNode(style.nodeId)?.effects).toMatchObject([
+ { type: 'DROP_SHADOW', radius: 20 },
+ { type: 'LAYER_BLUR', radius: 6 },
+ { type: 'DROP_SHADOW', radius: 2 }
+ ])
+ })
+})
diff --git a/packages/core/tests/editor/graph/events-integration.test.ts b/packages/core/tests/editor/graph/events-integration.test.ts
index 442c54d0d..c92e979ab 100644
--- a/packages/core/tests/editor/graph/events-integration.test.ts
+++ b/packages/core/tests/editor/graph/events-integration.test.ts
@@ -2,10 +2,7 @@ import { describe, expect, mock, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
-import {
- createGraphEventSubscription,
- type GraphEventRenderer
-} from '#core/editor/graph-events'
+import { createGraphEventSubscription, type GraphEventRenderer } from '#core/editor/graph-events'
function createRenderer() {
const invalidated: string[] = []
diff --git a/packages/core/tests/editor/history/snapshot-graph.test.ts b/packages/core/tests/editor/history/snapshot-graph.test.ts
index 19b0f02a6..b155eb7df 100644
--- a/packages/core/tests/editor/history/snapshot-graph.test.ts
+++ b/packages/core/tests/editor/history/snapshot-graph.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { createEditor, graphFromPageSnapshot } from '@open-pencil/core/editor'
import {
comparePNGs,
@@ -8,8 +10,6 @@ import {
renderRegionToImage
} from '@open-pencil/core/io/formats/raster'
-import { expectDefined } from '#core-tests/helpers/assert'
-
function setup() {
const editor = createEditor()
const pageId = editor.state.currentPageId
diff --git a/packages/core/tests/editor/play/states.test.ts b/packages/core/tests/editor/play/states.test.ts
index 774b5e87d..45a670ec1 100644
--- a/packages/core/tests/editor/play/states.test.ts
+++ b/packages/core/tests/editor/play/states.test.ts
@@ -16,7 +16,13 @@ function switchCard() {
const set = graph.createNode('COMPONENT_SET', pageId, {
name: 'Switch',
componentPropertyDefinitions: [
- { id: 'state', name: 'State', type: 'VARIANT', defaultValue: 'Off', variantOptions: ['Off', 'On'] },
+ {
+ id: 'state',
+ name: 'State',
+ type: 'VARIANT',
+ defaultValue: 'Off',
+ variantOptions: ['Off', 'On']
+ },
{
id: 'interaction',
name: 'Interaction',
diff --git a/packages/core/tests/editor/reveal.test.ts b/packages/core/tests/editor/reveal.test.ts
index a1270e0ea..d455b3175 100644
--- a/packages/core/tests/editor/reveal.test.ts
+++ b/packages/core/tests/editor/reveal.test.ts
@@ -11,7 +11,12 @@ function setup() {
describe('revealNodes', () => {
test('leaves the viewport alone when the layers are already in view', () => {
const { editor, pageId } = setup()
- const card = editor.graph.createNode('FRAME', pageId, { x: 100, y: 100, width: 200, height: 100 })
+ const card = editor.graph.createNode('FRAME', pageId, {
+ x: 100,
+ y: 100,
+ width: 200,
+ height: 100
+ })
editor.revealNodes([card.id])
@@ -20,7 +25,12 @@ describe('revealNodes', () => {
test('centers off-screen layers that fit without changing zoom', () => {
const { editor, pageId } = setup()
- const card = editor.graph.createNode('FRAME', pageId, { x: 2000, y: 1000, width: 200, height: 100 })
+ const card = editor.graph.createNode('FRAME', pageId, {
+ x: 2000,
+ y: 1000,
+ width: 200,
+ height: 100
+ })
editor.revealNodes([card.id])
diff --git a/packages/core/tests/editor/selection/alignment.test.ts b/packages/core/tests/editor/selection/alignment.test.ts
index b14b8afd7..c356ce136 100644
--- a/packages/core/tests/editor/selection/alignment.test.ts
+++ b/packages/core/tests/editor/selection/alignment.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from 'bun:test'
-import { SceneGraph } from '@open-pencil/core'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createRect, firstPageId } from '#core-tests/helpers/scene'
+import { SceneGraph } from '@open-pencil/core'
+
describe('single-node alignment to parent', () => {
function setup() {
const graph = new SceneGraph()
diff --git a/packages/core/tests/editor/selection/flip.test.ts b/packages/core/tests/editor/selection/flip.test.ts
index f8d213f9f..1388e3722 100644
--- a/packages/core/tests/editor/selection/flip.test.ts
+++ b/packages/core/tests/editor/selection/flip.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from 'bun:test'
-import { SceneGraph } from '@open-pencil/core'
-
import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
import { createRect, firstPageId } from '#core-tests/helpers/scene'
+import { SceneGraph } from '@open-pencil/core'
+
describe('flip', () => {
test('flipX defaults to false', () => {
const graph = new SceneGraph()
diff --git a/packages/core/tests/editor/selection/properties.test.ts b/packages/core/tests/editor/selection/properties.test.ts
index e18ae266a..3a6a8c8dd 100644
--- a/packages/core/tests/editor/selection/properties.test.ts
+++ b/packages/core/tests/editor/selection/properties.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from 'bun:test'
-import { SceneGraph } from '@open-pencil/core'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createRect, firstPageId } from '#core-tests/helpers/scene'
+import { SceneGraph } from '@open-pencil/core'
+
describe('multi-node property merging', () => {
test('same values merge to single value', () => {
const graph = new SceneGraph()
diff --git a/packages/core/tests/editor/structure/flatten.test.ts b/packages/core/tests/editor/structure/flatten.test.ts
index c399d4e1e..8215e2007 100644
--- a/packages/core/tests/editor/structure/flatten.test.ts
+++ b/packages/core/tests/editor/structure/flatten.test.ts
@@ -80,7 +80,9 @@ describe('flattenSelected', () => {
width: 40,
height: 30,
fills: [{ type: 'SOLID', color: TRANSPARENT, opacity: 1, visible: true }],
- strokes: [{ type: 'SOLID', color: BLACK, weight: 8, opacity: 1, visible: true, align: 'CENTER' }]
+ strokes: [
+ { type: 'SOLID', color: BLACK, weight: 8, opacity: 1, visible: true, align: 'CENTER' }
+ ]
})
editor.select([rect.id])
@@ -108,7 +110,9 @@ describe('flattenSelected', () => {
width: 40,
height: 30,
fills: [{ type: 'SOLID', color: TRANSPARENT, opacity: 1, visible: true }],
- strokes: [{ type: 'SOLID', color: BLACK, weight: 8, opacity: 1, visible: true, align: 'CENTER' }]
+ strokes: [
+ { type: 'SOLID', color: BLACK, weight: 8, opacity: 1, visible: true, align: 'CENTER' }
+ ]
})
editor.select([rect.id])
editor.groupSelected()
@@ -366,7 +370,9 @@ describe('flattenSelected', () => {
width: 50,
height: 40,
fills: [],
- strokes: [{ type: 'SOLID', color: BLACK, opacity: 1, visible: true, weight: 8, align: 'CENTER' }]
+ strokes: [
+ { type: 'SOLID', color: BLACK, opacity: 1, visible: true, weight: 8, align: 'CENTER' }
+ ]
})
editor.select([rect.id])
diff --git a/packages/core/tests/editor/structure/state.test.ts b/packages/core/tests/editor/structure/state.test.ts
index a49430e42..24073af25 100644
--- a/packages/core/tests/editor/structure/state.test.ts
+++ b/packages/core/tests/editor/structure/state.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, test } from 'bun:test'
-import { createEditor } from '@open-pencil/core/editor'
-import { computeAllLayouts } from '@open-pencil/core/layout'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { rect } from '#core-tests/helpers/layout'
+import { createEditor } from '@open-pencil/core/editor'
+import { computeAllLayouts } from '@open-pencil/core/layout'
+
describe('structure state actions', () => {
test('toggleNodeVisibility reflows HUG auto-layout instance slots', async () => {
const editor = createEditor()
diff --git a/packages/core/tests/editor/undo/create-instance.test.ts b/packages/core/tests/editor/undo/create-instance.test.ts
index 0ee3881ca..50c52da62 100644
--- a/packages/core/tests/editor/undo/create-instance.test.ts
+++ b/packages/core/tests/editor/undo/create-instance.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { createEditor } from '@open-pencil/core/editor'
import { getAxisAlignedWorldBounds } from '@open-pencil/scene-graph/coordinate'
-import { expectDefined } from '#core-tests/helpers/assert'
-
describe('create instance undo/redo', () => {
test('places a nested component beside its world bounds on the page', () => {
const editor = createEditor()
diff --git a/packages/core/tests/editor/undo/create-shape.test.ts b/packages/core/tests/editor/undo/create-shape.test.ts
index 4f8f2901f..338a2349a 100644
--- a/packages/core/tests/editor/undo/create-shape.test.ts
+++ b/packages/core/tests/editor/undo/create-shape.test.ts
@@ -1,9 +1,9 @@
import { describe, test, expect } from 'bun:test'
-import { createEditor } from '@open-pencil/core/editor'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
+import { createEditor } from '@open-pencil/core/editor'
+
describe('create shape undo/redo', () => {
test('batched create+resize undoes in one step', () => {
const editor = createEditor()
diff --git a/packages/core/tests/editor/undo/group-resize.test.ts b/packages/core/tests/editor/undo/group-resize.test.ts
index fe9f26e38..370bb4d35 100644
--- a/packages/core/tests/editor/undo/group-resize.test.ts
+++ b/packages/core/tests/editor/undo/group-resize.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, test } from 'bun:test'
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
import { createEditor } from '@open-pencil/core/editor'
import type { VectorNetwork } from '@open-pencil/scene-graph'
import { createResizeSnapshot } from '@open-pencil/scene-graph/resize'
-import { getNodeOrThrow } from '#core-tests/helpers/assert'
-
const originalVectorNetwork: VectorNetwork = {
vertices: [
{ x: 0, y: 0 },
diff --git a/packages/core/tests/editor/undo/variable/bindings.test.ts b/packages/core/tests/editor/undo/variable/bindings.test.ts
index 8ec50f23c..6352a1e50 100644
--- a/packages/core/tests/editor/undo/variable/bindings.test.ts
+++ b/packages/core/tests/editor/undo/variable/bindings.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, test } from 'bun:test'
-import { createEditor } from '@open-pencil/core/editor'
-
import { getNodeOrThrow } from '#core-tests/helpers/assert'
+import { createEditor } from '@open-pencil/core/editor'
+
function pageId(editor: ReturnType<typeof createEditor>): string {
return editor.graph.getPages()[0].id
}
diff --git a/packages/core/tests/editor/variables/value-bindings.test.ts b/packages/core/tests/editor/variables/value-bindings.test.ts
index c0e7c08bc..e9ed0f5cd 100644
--- a/packages/core/tests/editor/variables/value-bindings.test.ts
+++ b/packages/core/tests/editor/variables/value-bindings.test.ts
@@ -1,10 +1,10 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { createEditor } from '@open-pencil/core/editor'
import { SceneGraph, setInstanceOverride } from '@open-pencil/scene-graph'
-import { expectDefined } from '#core-tests/helpers/assert'
-
function boundText() {
const graph = new SceneGraph()
const copy = graph.createCollection('Copy')
diff --git a/packages/core/tests/figma-api/create-defaults.test.ts b/packages/core/tests/figma-api/create-defaults.test.ts
index 448d927e1..b18f40cee 100644
--- a/packages/core/tests/figma-api/create-defaults.test.ts
+++ b/packages/core/tests/figma-api/create-defaults.test.ts
@@ -13,7 +13,9 @@ const BLACK = [0, 0, 0]
function solid(paints: readonly { type: string; color?: { r: number; g: number; b: number } }[]) {
return paints.map((paint) =>
- paint.color ? [paint.color.r, paint.color.g, paint.color.b].map((v) => Math.round(v * 100) / 100) : paint.type
+ paint.color
+ ? [paint.color.r, paint.color.g, paint.color.b].map((v) => Math.round(v * 100) / 100)
+ : paint.type
)
}
diff --git a/packages/core/tests/figma-api/effects.test.ts b/packages/core/tests/figma-api/effects.test.ts
index 12eb30f1a..6af4ca687 100644
--- a/packages/core/tests/figma-api/effects.test.ts
+++ b/packages/core/tests/figma-api/effects.test.ts
@@ -101,14 +101,23 @@ describe('node.effects', () => {
['an infinite radius', [{ ...shadow, radius: Number.POSITIVE_INFINITY }]],
['an infinite offset', [{ ...shadow, offset: { x: Number.POSITIVE_INFINITY, y: 0 } }]],
['an infinite spread', [{ ...shadow, spread: Number.NEGATIVE_INFINITY }]],
- ['an infinite blur radius', [{ type: 'LAYER_BLUR', radius: Number.POSITIVE_INFINITY, visible: true }]],
+ [
+ 'an infinite blur radius',
+ [{ type: 'LAYER_BLUR', radius: Number.POSITIVE_INFINITY, visible: true }]
+ ],
['an unknown type', [{ type: 'NOT_AN_EFFECT' }]],
['a foreground blur', [{ type: 'FOREGROUND_BLUR', radius: 4, visible: true }]],
['an unknown key', [{ ...shadow, foo: 1 }]],
['a shadow without blendMode', [{ ...shadow, blendMode: undefined }]],
['an unknown blendMode', [{ ...shadow, blendMode: 'NOPE' }]],
- ['showShadowBehindNode on an inner shadow', [{ ...shadow, type: 'INNER_SHADOW', showShadowBehindNode: true }]],
- ['shadow fields on a blur', [{ type: 'LAYER_BLUR', radius: 4, visible: true, color, offset: { x: 0, y: 0 }, spread: 0 }]],
+ [
+ 'showShadowBehindNode on an inner shadow',
+ [{ ...shadow, type: 'INNER_SHADOW', showShadowBehindNode: true }]
+ ],
+ [
+ 'shadow fields on a blur',
+ [{ type: 'LAYER_BLUR', radius: 4, visible: true, color, offset: { x: 0, y: 0 }, spread: 0 }]
+ ],
['a color without alpha', [{ ...shadow, color: { r: 0, g: 0, b: 0 } }]],
['a color channel above 1', [{ ...shadow, color: { r: 2, g: 0, b: 0, a: 1 } }]],
['an incomplete offset', [{ ...shadow, offset: { x: 0 } }]],
@@ -116,7 +125,9 @@ describe('node.effects', () => {
])('rejects %s without changing the node', (_name, value) => {
const rect = assign([shadow])
const before = rect.effects
- expect(() => Reflect.set(rect, 'effects', value)).toThrow('Property "effects" failed validation')
+ expect(() => Reflect.set(rect, 'effects', value)).toThrow(
+ 'Property "effects" failed validation'
+ )
expect(rect.effects).toEqual(before)
})
diff --git a/packages/core/tests/figma-api/group-coordinates.test.ts b/packages/core/tests/figma-api/group-coordinates.test.ts
index e9ca238a7..a8192276d 100644
--- a/packages/core/tests/figma-api/group-coordinates.test.ts
+++ b/packages/core/tests/figma-api/group-coordinates.test.ts
@@ -26,12 +26,7 @@ function setup() {
return { figma, frame, group, a, b, rect }
}
-const box = (node: Rect) => [
- node.x,
- node.y,
- node.width,
- node.height
-]
+const box = (node: Rect) => [node.x, node.y, node.width, node.height]
describe('group children in the plugin API', () => {
test('report positions and transforms in the container', () => {
diff --git a/packages/core/tests/figma-api/slots.test.ts b/packages/core/tests/figma-api/slots.test.ts
index 25ccb161d..f146cd242 100644
--- a/packages/core/tests/figma-api/slots.test.ts
+++ b/packages/core/tests/figma-api/slots.test.ts
@@ -147,7 +147,12 @@ describe('swapping an instance', () => {
const instance = outer('Outer A', 'Card').createInstance()
const nestedSlot = () => instance.children[0]?.children.find(isSlot)
nestedSlot()?.appendChild(Object.assign(api.createText(), { name: 'Filled' }))
- return { instance, nestedSlot, same: outer('Outer B', 'Card'), other: outer('Outer C', innerName) }
+ return {
+ instance,
+ nestedSlot,
+ same: outer('Outer B', 'Card'),
+ other: outer('Outer C', innerName)
+ }
}
// Recorded in live Figma: nested slot content follows a nested instance of the same name.
diff --git a/packages/core/tests/figma-api/transform-parity.test.ts b/packages/core/tests/figma-api/transform-parity.test.ts
index 7a6e22397..691766750 100644
--- a/packages/core/tests/figma-api/transform-parity.test.ts
+++ b/packages/core/tests/figma-api/transform-parity.test.ts
@@ -9,8 +9,7 @@ import type { Rect } from '@open-pencil/scene-graph/primitives'
const round = (value: number) => Math.round(value * 1000) / 1000
const rounded = (rows: readonly (readonly number[])[]) => rows.map((row) => row.map(round))
-const box = (rect: Rect) =>
- [rect.x, rect.y, rect.width, rect.height].map(round)
+const box = (rect: Rect) => [rect.x, rect.y, rect.width, rect.height].map(round)
function rectangle() {
const figma = new FigmaAPI(new SceneGraph())
diff --git a/packages/core/tests/helpers/fig/fixtures.ts b/packages/core/tests/helpers/fig/fixtures.ts
index be2cedcc3..ebf72f089 100644
--- a/packages/core/tests/helpers/fig/fixtures.ts
+++ b/packages/core/tests/helpers/fig/fixtures.ts
@@ -1,6 +1,8 @@
import { existsSync, readFileSync } from 'node:fs'
import { resolve } from 'node:path'
+import * as v from 'valibot'
+
import {
parseFigFile,
type ParseFigFileOptions,
@@ -8,10 +10,8 @@ import {
type SceneNode
} from '@open-pencil/core'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import * as v from 'valibot'
import { FIXTURES } from '../paths'
-
import { collectAllNodes } from './traversal'
export { FIXTURES }
diff --git a/packages/core/tests/helpers/paths.ts b/packages/core/tests/helpers/paths.ts
index d4c7c3231..22b786ab4 100644
--- a/packages/core/tests/helpers/paths.ts
+++ b/packages/core/tests/helpers/paths.ts
@@ -15,5 +15,8 @@ export const FIXTURES = join(workspaceRoot(), 'tests/fixtures')
/** A file inside this package, for assets that are not modules. */
export function corePackagePath(...segments: string[]): string {
- return join(dirname(Bun.resolveSync('@open-pencil/core/package.json', import.meta.dir)), ...segments)
+ return join(
+ dirname(Bun.resolveSync('@open-pencil/core/package.json', import.meta.dir)),
+ ...segments
+ )
}
diff --git a/packages/core/tests/helpers/property-cases.ts b/packages/core/tests/helpers/property-cases.ts
index 1b7293f8b..44bba29fb 100644
--- a/packages/core/tests/helpers/property-cases.ts
+++ b/packages/core/tests/helpers/property-cases.ts
@@ -12,7 +12,15 @@ function solidFill(color = RED, fields: Partial<Fill> = {}): Fill {
}
function stroke(fields: Partial<Stroke> = {}): Stroke {
- return { type: 'SOLID', color: BLUE, weight: 1, opacity: 1, visible: true, align: 'INSIDE', ...fields }
+ return {
+ type: 'SOLID',
+ color: BLUE,
+ weight: 1,
+ opacity: 1,
+ visible: true,
+ align: 'INSIDE',
+ ...fields
+ }
}
export interface RoundTripCase {
@@ -137,7 +145,14 @@ export const PROPERTY_CASES: RoundTripCase[] = [
}),
leafCase('single stroke with every option', 'RECTANGLE', {
strokes: [
- stroke({ type: 'SOLID', weight: 3, align: 'OUTSIDE', dashPattern: [4, 2], cap: 'ROUND', join: 'BEVEL' })
+ stroke({
+ type: 'SOLID',
+ weight: 3,
+ align: 'OUTSIDE',
+ dashPattern: [4, 2],
+ cap: 'ROUND',
+ join: 'BEVEL'
+ })
]
}),
leafCase('node-level stroke cap and join under a stroke without its own', 'RECTANGLE', {
diff --git a/packages/core/tests/io/formats/design-tokens/export.test.ts b/packages/core/tests/io/formats/design-tokens/export.test.ts
new file mode 100644
index 000000000..11c2a9aaf
--- /dev/null
+++ b/packages/core/tests/io/formats/design-tokens/export.test.ts
@@ -0,0 +1,211 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { exportDesignTokens, RESOLVER_FILE, STYLES_FILE } from '#core/io/formats/design-tokens'
+
+const blue = { r: 0, g: 0.4, b: 0.8, a: 1 }
+const white = { r: 1, g: 1, b: 1, a: 1 }
+
+function designSystem() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const primitives = graph.createCollection('Primitives')
+ const brand = graph.createVariable('Blue/500', 'COLOR', primitives.id, blue)
+ const theme = graph.createCollection('Theme')
+ const light = theme.defaultModeId
+ graph.renameMode(theme.id, light, 'Light')
+ const dark = graph.createMode(theme.id, 'Dark') ?? ''
+ const accent = graph.createVariable('Accent', 'COLOR', theme.id, { aliasId: brand.id })
+ accent.valuesByMode[dark] = white
+ accent.description = 'Buttons and links'
+ const gutter = graph.createVariable('Space', 'FLOAT', theme.id, 24)
+ gutter.unit = 'rem'
+ graph.createVariable('Space/Small', 'FLOAT', theme.id, 8)
+ const fast = graph.createVariable('Motion/Fast', 'FLOAT', theme.id, 150)
+ fast.unit = 'ms'
+ graph.createVariable('Flags/Rounded', 'BOOLEAN', theme.id, true)
+ const family = graph.createVariable('Font/Body', 'STRING', theme.id, 'Inter')
+ family.scopes = ['FONT_FAMILY']
+ graph.createVariable('Ratio 1.5', 'FLOAT', theme.id, 1.5)
+
+ const heading = graph.createNode('TEXT', page, {
+ name: 'Heading/H1',
+ fontFamily: 'Inter',
+ fontWeight: 700,
+ fontSize: 32,
+ lineHeight: 40,
+ letterSpacing: -0.5,
+ sharedStyleType: 'TEXT',
+ internalOnly: true,
+ boundVariables: { fontFamily: family.id }
+ })
+ heading.source.id = 'style:heading'
+ const card = graph.createNode('RECTANGLE', page, {
+ name: 'Elevation/Card',
+ sharedStyleType: 'EFFECT',
+ internalOnly: true,
+ effects: [
+ {
+ type: 'DROP_SHADOW',
+ color: { r: 0, g: 0, b: 0, a: 0.25 },
+ offset: { x: 0, y: 4 },
+ radius: 12,
+ spread: 0,
+ visible: true
+ }
+ ]
+ })
+ card.source.id = 'style:card'
+ return graph
+}
+
+function file(graph: SceneGraph, path: string) {
+ const found = exportDesignTokens(graph).files.find((entry) => entry.path === path)
+ if (!found) throw new Error(`missing ${path}`)
+ return found.content
+}
+
+describe('design token export', () => {
+ test('writes one file per mode, the styles, and a resolver', () => {
+ expect(exportDesignTokens(designSystem()).files.map((entry) => entry.path)).toEqual([
+ 'Primitives/Mode 1.tokens.json',
+ 'Theme/Light.tokens.json',
+ 'Theme/Dark.tokens.json',
+ STYLES_FILE,
+ RESOLVER_FILE
+ ])
+ })
+
+ test('writes values the way Figma imports them', () => {
+ const light = file(designSystem(), 'Theme/Light.tokens.json')
+
+ expect(light.Accent).toEqual({
+ $type: 'color',
+ $value: '{Blue.500}',
+ $description: 'Buttons and links',
+ $extensions: {
+ 'com.figma.aliasData': {
+ targetVariableName: 'Blue/500',
+ targetVariableSetName: 'Primitives'
+ }
+ }
+ })
+ expect(light.Space).toEqual({
+ $root: {
+ $type: 'dimension',
+ $value: { value: 24, unit: 'px' },
+ $extensions: { 'dev.openpencil': { unit: 'rem' } }
+ },
+ Small: { $type: 'dimension', $value: { value: 8, unit: 'px' } }
+ })
+ expect(light.Motion).toEqual({
+ Fast: {
+ $type: 'duration',
+ $value: { value: 0.15, unit: 's' },
+ $extensions: { 'dev.openpencil': { unit: 'ms' } }
+ }
+ })
+ expect(light.Flags).toEqual({
+ Rounded: { $type: 'number', $value: 1, $extensions: { 'com.figma.type': 'boolean' } }
+ })
+ expect(light.Font).toEqual({
+ Body: {
+ $type: 'fontFamily',
+ $value: 'Inter',
+ $extensions: { 'dev.openpencil': { scopes: ['FONT_FAMILY'] } }
+ }
+ })
+ })
+
+ test('keeps a name a token path cannot hold, and the mode it belongs to', () => {
+ const dark = file(designSystem(), 'Theme/Dark.tokens.json')
+
+ expect(dark['Ratio 1-5']).toEqual({
+ $type: 'dimension',
+ $value: { value: 1.5, unit: 'px' },
+ $extensions: { 'dev.openpencil': { name: 'Ratio 1.5' } }
+ })
+ expect(dark.Accent).toMatchObject({
+ $value: { colorSpace: 'srgb', components: [1, 1, 1], alpha: 1, hex: '#ffffff' }
+ })
+ expect(dark.$extensions).toEqual({
+ 'dev.openpencil': { collection: 'Theme', mode: 'Dark', default: false }
+ })
+ })
+
+ test('writes text and effect styles as typography and shadow tokens', () => {
+ const styles = file(designSystem(), STYLES_FILE)
+
+ expect(styles.Heading).toMatchObject({
+ H1: {
+ $type: 'typography',
+ $value: {
+ fontFamily: '{Font.Body}',
+ fontSize: { value: 32, unit: 'px' },
+ fontWeight: 700,
+ lineHeight: 1.25,
+ letterSpacing: { value: -0.5, unit: 'px' }
+ }
+ }
+ })
+ expect(styles.Elevation).toEqual({
+ Card: {
+ $type: 'shadow',
+ $value: {
+ color: { colorSpace: 'srgb', components: [0, 0, 0], alpha: 0.25, hex: '#000000' },
+ offsetX: { value: 0, unit: 'px' },
+ offsetY: { value: 4, unit: 'px' },
+ blur: { value: 12, unit: 'px' },
+ spread: { value: 0, unit: 'px' }
+ }
+ }
+ })
+ })
+
+ test('a collection named like the styles set gets a name of its own in the resolver', () => {
+ const graph = designSystem()
+ const styles = graph.createCollection('Styles')
+ graph.createVariable('Gap', 'FLOAT', styles.id, 4)
+
+ const resolver = exportDesignTokens(graph).files.find((file) => file.path === RESOLVER_FILE)
+ const content = resolver?.content as { sets?: object } | undefined
+
+ expect(Object.keys(content?.sets ?? {})).toEqual(['Primitives', 'Styles 2', 'Styles'])
+ })
+
+ test('without styles, a collection named Styles keeps its name in the resolver', () => {
+ const graph = new SceneGraph()
+ const styles = graph.createCollection('Styles')
+ graph.createVariable('Gap', 'FLOAT', styles.id, 4)
+
+ const resolver = exportDesignTokens(graph).files.find((file) => file.path === RESOLVER_FILE)
+ const content = resolver?.content as { sets?: object } | undefined
+
+ expect(Object.keys(content?.sets ?? {})).toEqual(['Styles'])
+ })
+
+ test('the resolver switches collections with several modes and layers the rest', () => {
+ expect(file(designSystem(), RESOLVER_FILE)).toEqual({
+ version: '2025-11-01',
+ sets: {
+ Primitives: { sources: [{ $ref: 'Primitives/Mode 1.tokens.json' }] },
+ Styles: { sources: [{ $ref: STYLES_FILE }] }
+ },
+ modifiers: {
+ Theme: {
+ contexts: {
+ Light: [{ $ref: 'Theme/Light.tokens.json' }],
+ Dark: [{ $ref: 'Theme/Dark.tokens.json' }]
+ },
+ default: 'Light'
+ }
+ },
+ resolutionOrder: [
+ { $ref: '#/sets/Primitives' },
+ { $ref: '#/modifiers/Theme' },
+ { $ref: '#/sets/Styles' }
+ ]
+ })
+ })
+})
diff --git a/packages/core/tests/io/formats/design-tokens/import.test.ts b/packages/core/tests/io/formats/design-tokens/import.test.ts
new file mode 100644
index 000000000..cd4acf480
--- /dev/null
+++ b/packages/core/tests/io/formats/design-tokens/import.test.ts
@@ -0,0 +1,290 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import {
+ defaultTokenImportOptions,
+ planTokenImport,
+ readDesignTokens,
+ type DesignTokenSourceFile
+} from '#core/io/formats/design-tokens'
+
+function files(entries: Record<string, unknown>): DesignTokenSourceFile[] {
+ return Object.entries(entries).map(([path, content]) => ({
+ path,
+ text: typeof content === 'string' ? content : JSON.stringify(content)
+ }))
+}
+
+function plan(input: DesignTokenSourceFile[]) {
+ const graph = new SceneGraph()
+ const bundle = readDesignTokens(input)
+ return { bundle, plan: planTokenImport(graph, bundle, defaultTokenImportOptions(graph, bundle)) }
+}
+
+describe('reading token files', () => {
+ test('a file per mode makes a collection named after its folder', () => {
+ const bundle = readDesignTokens(
+ files({
+ 'Brand/Light.tokens.json': { color: { $type: 'color', bg: { $value: '#ffffff' } } },
+ 'Brand/Dark.tokens.json': { color: { $type: 'color', bg: { $value: '#000000' } } }
+ })
+ )
+
+ expect(bundle.collections.map((collection) => collection.name)).toEqual(['Brand'])
+ expect(bundle.collections[0].modes.map((mode) => [mode.name, mode.tokens[0].name])).toEqual([
+ ['Light', 'color/bg'],
+ ['Dark', 'color/bg']
+ ])
+ })
+
+ test('a resolver makes a collection of each modifier and of each set', () => {
+ const bundle = readDesignTokens(
+ files({
+ 'tokens.resolver.json': {
+ version: '2025-11-01',
+ sets: { Core: { sources: [{ $ref: 'core.json' }] } },
+ modifiers: {
+ Theme: {
+ contexts: { light: [{ $ref: 'light.json' }], dark: [{ $ref: 'dark.json' }] },
+ default: 'dark'
+ }
+ },
+ resolutionOrder: [{ $ref: '#/sets/Core' }, { $ref: '#/modifiers/Theme' }]
+ },
+ 'core.json': { space: { $type: 'dimension', md: { $value: { value: 1, unit: 'rem' } } } },
+ 'light.json': { surface: { $type: 'color', $value: '{palette.white}' } },
+ 'dark.json': { surface: { $type: 'color', $value: '{palette.black}' } }
+ })
+ )
+
+ expect(bundle.collections.map((collection) => collection.name)).toEqual(['Core', 'Theme'])
+ expect(bundle.collections[1].modes.map((mode) => [mode.name, mode.isDefault])).toEqual([
+ ['light', false],
+ ['dark', true]
+ ])
+ })
+
+ test('a resolver finds files picked without their folders by name', () => {
+ const bundle = readDesignTokens(
+ files({
+ 'tokens.resolver.json': {
+ version: '2025-11-01',
+ sets: { Core: { sources: [{ $ref: 'Core/Mode 1.tokens.json' }] } },
+ resolutionOrder: [{ $ref: '#/sets/Core' }]
+ },
+ 'Mode 1.tokens.json': { gap: { $type: 'number', $value: 4 } }
+ })
+ )
+
+ expect(bundle.issues).toEqual([])
+ expect(bundle.collections[0].modes[0].tokens.map((token) => token.name)).toEqual(['gap'])
+ })
+
+ test('Tokens Studio themes become modes of their group, and the sets they refer to collections', () => {
+ const bundle = readDesignTokens(
+ files({
+ 'tokens.json': {
+ core: { blue: { $type: 'color', $value: '#0066cc' } },
+ light: { accent: { $type: 'color', $value: '{blue}' } },
+ dark: { accent: { $type: 'color', $value: '#ffffff' } },
+ $themes: [
+ {
+ name: 'Light',
+ group: 'Theme',
+ selectedTokenSets: { core: 'source', light: 'enabled' }
+ },
+ { name: 'Dark', group: 'Theme', selectedTokenSets: { core: 'source', dark: 'enabled' } }
+ ]
+ }
+ })
+ )
+
+ expect(bundle.collections.map((collection) => collection.name)).toEqual(['core', 'Theme'])
+ expect(bundle.collections[1].modes.map((mode) => mode.name)).toEqual(['Light', 'Dark'])
+ })
+
+ test('a file that is not JSON is reported and the rest still read', () => {
+ const bundle = readDesignTokens(
+ files({ 'broken.json': '{', 'ok.tokens.json': { gap: { $type: 'number', $value: 4 } } })
+ )
+
+ expect(bundle.issues).toEqual([{ kind: 'invalid-file', file: 'broken.json' }])
+ expect(bundle.collections).toHaveLength(1)
+ })
+})
+
+describe('planning an import', () => {
+ test('values from other tools convert into canvas units and sRGB', () => {
+ const { plan: result } = plan(
+ files({
+ 'Tokens/Default.tokens.json': {
+ space: { $type: 'dimension', md: { $value: { value: 1.5, unit: 'rem' } } },
+ brand: { $type: 'color', $value: { colorSpace: 'oklch', components: [0.6, 0.15, 250] } },
+ weight: { $type: 'fontWeight', $value: 'semi-bold' },
+ quick: { $type: 'duration', $value: { value: 150, unit: 'ms' } }
+ }
+ })
+ )
+
+ const byName = Object.fromEntries(
+ result.collections[0].variables.map((variable) => [variable.name, variable])
+ )
+ expect(byName['space/md']).toMatchObject({
+ type: 'FLOAT',
+ unit: 'rem',
+ values: [{ value: 24 }]
+ })
+ expect(byName.weight).toMatchObject({ values: [{ value: 600 }], scopes: ['FONT_STYLE'] })
+ expect(byName.quick).toMatchObject({ unit: 'ms', values: [{ value: 150 }] })
+ expect(byName.brand.values[0]).toMatchObject({ kind: 'literal' })
+ })
+
+ test('an untyped alias takes the type of what it points at', () => {
+ const { plan: result } = plan(
+ files({
+ 'Tokens/Default.tokens.json': {
+ base: { $type: 'color', $value: '#0066cc' },
+ link: { $value: '{base}' }
+ }
+ })
+ )
+
+ expect(
+ result.collections[0].variables.map((variable) => [variable.name, variable.type])
+ ).toEqual([
+ ['base', 'COLOR'],
+ ['link', 'COLOR']
+ ])
+ expect(result.collections[0].variables[1].values).toEqual([
+ { kind: 'alias', target: { kind: 'planned', collection: 0, variable: 0 } }
+ ])
+ })
+
+ test('a token that is also a group keeps its name through `$root`', () => {
+ const { plan: result } = plan(
+ files({
+ 'Tokens/Default.tokens.json': {
+ space: {
+ $type: 'number',
+ $root: { $value: 8 },
+ small: { $value: 4 },
+ half: { $value: '{space.$root}' }
+ }
+ }
+ })
+ )
+
+ expect(result.collections[0].variables.map((variable) => variable.name)).toEqual([
+ 'space',
+ 'space/small',
+ 'space/half'
+ ])
+ })
+
+ test('an alias to a collection whose name repeats points into the first one', () => {
+ const token = (path: string, value: unknown, extensions: Record<string, unknown> = {}) => ({
+ path: path.split('.'),
+ name: path,
+ type: 'color',
+ value,
+ description: undefined,
+ extensions
+ })
+ const theme = (tokens: ReturnType<typeof token>[]) => ({
+ name: 'Theme',
+ modeAttribute: undefined,
+ modes: [{ name: 'Light', isDefault: true, condition: undefined, tokens }]
+ })
+ const bundle = {
+ collections: [
+ theme([token('brand', '#0066cc')]),
+ theme([token('other', '#ffffff'), token('extra', '#000000')]),
+ {
+ ...theme([
+ token('link', '{brand}', {
+ 'com.figma.aliasData': { targetVariableName: 'brand', targetVariableSetName: 'Theme' }
+ })
+ ]),
+ name: 'Links'
+ }
+ ],
+ composites: [],
+ issues: []
+ }
+ const graph = new SceneGraph()
+
+ const result = planTokenImport(graph, bundle, defaultTokenImportOptions(graph, bundle))
+
+ expect(result.collections[2].variables[0].values).toEqual([
+ { kind: 'alias', target: { kind: 'planned', collection: 0, variable: 0 } }
+ ])
+ })
+
+ test('an alias to a collection left out is missing, not bound to the same path elsewhere', () => {
+ const graph = new SceneGraph()
+ const other = graph.createCollection('Other')
+ graph.createVariable('blue/500', 'COLOR', other.id, { r: 1, g: 0, b: 0, a: 1 })
+ const bundle = readDesignTokens(
+ files({
+ 'Primitives/Value.tokens.json': { blue: { 500: { $type: 'color', $value: '#3b82f6' } } },
+ 'Theme/Light.tokens.json': {
+ accent: {
+ $type: 'color',
+ $value: '{blue.500}',
+ $extensions: {
+ 'com.figma.aliasData': {
+ targetVariableName: 'blue/500',
+ targetVariableSetName: 'Primitives'
+ }
+ }
+ }
+ }
+ })
+ )
+ const options = defaultTokenImportOptions(graph, bundle)
+ options.collections[0].target = { kind: 'skip' }
+
+ const result = planTokenImport(graph, bundle, options)
+
+ expect(result.skipped).toContainEqual({
+ name: 'accent',
+ collection: 'Theme',
+ reason: 'missing-alias'
+ })
+ })
+
+ test('composite tokens other than typography and shadow are skipped with a reason', () => {
+ const { plan: result } = plan(
+ files({
+ 'styles.tokens.json': {
+ card: {
+ $type: 'border',
+ $value: { color: '#000', width: { value: 1, unit: 'px' }, style: 'solid' }
+ },
+ lift: {
+ $type: 'shadow',
+ $value: {
+ color: '#00000040',
+ offsetX: { value: 0, unit: 'px' },
+ offsetY: { value: 2, unit: 'px' },
+ blur: { value: 4, unit: 'px' },
+ spread: { value: 0, unit: 'px' }
+ }
+ }
+ }
+ })
+ )
+
+ expect(result.skipped).toEqual([
+ { name: 'card', collection: undefined, reason: 'unsupported-type' }
+ ])
+ expect(result.styles).toMatchObject([
+ {
+ kind: 'EFFECT',
+ name: 'lift',
+ fields: { effects: [{ type: 'DROP_SHADOW', offset: { x: 0, y: 2 }, radius: 4 }] }
+ }
+ ])
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts b/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts
index 069c290e5..95ee9af7b 100644
--- a/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts
+++ b/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts
@@ -1,16 +1,16 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
+import { inheritedNestedBindingRecords } from '#core-tests/helpers/fig/nested-binding'
+import * as v from 'valibot'
+
import { createEditor } from '@open-pencil/core/editor'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
import { cloneInstanceOverrideState } from '@open-pencil/scene-graph'
-import * as v from 'valibot'
-
-import { expectDefined } from '#core-tests/helpers/assert'
-import { inheritedNestedBindingRecords } from '#core-tests/helpers/fig/nested-binding'
-import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
/** Only the component-edit measurements this file asserts against are read from the oracle. */
const AuthoringOracle = v.looseObject({
@@ -26,9 +26,7 @@ const oracle = readFixture('nested-binding-authoring.json', AuthoringOracle)
const fixture = readFixture('nested-binding-ownership-records.json', CapturedFigRecords)
function document(inherited = false) {
- const changes = inherited
- ? inheritedNestedBindingRecords()
- : structuredClone(fixture.nodeChanges)
+ const changes = inherited ? inheritedNestedBindingRecords() : structuredClone(fixture.nodeChanges)
const result = materializeDocument(
changes,
fixture.blobs.map((value) => Uint8Array.fromBase64(value)),
diff --git a/packages/core/tests/io/formats/fig/export/binding/import.test.ts b/packages/core/tests/io/formats/fig/export/binding/import.test.ts
index 2839f73f1..ade7143b7 100644
--- a/packages/core/tests/io/formats/fig/export/binding/import.test.ts
+++ b/packages/core/tests/io/formats/fig/export/binding/import.test.ts
@@ -1,14 +1,14 @@
import { expect, test } from 'bun:test'
+import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
+
import { createEditor } from '@open-pencil/core/editor'
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
-import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
const fixture = readFixture('nested-binding-ownership-records.json', CapturedFigRecords)
-
test('binding patches keep unrelated inherited fields in their original units', () => {
const changes = structuredClone(fixture.nodeChanges)
const inner = changes.find((node) => node.guid?.sessionID === 1 && node.guid.localID === 2)
diff --git a/packages/core/tests/io/formats/fig/export/color-variable-binding.test.ts b/packages/core/tests/io/formats/fig/export/color-variable-binding.test.ts
index 0e24e7fe2..a0786cd59 100644
--- a/packages/core/tests/io/formats/fig/export/color-variable-binding.test.ts
+++ b/packages/core/tests/io/formats/fig/export/color-variable-binding.test.ts
@@ -1,5 +1,6 @@
import { beforeAll, describe, expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
import { inflateSync, unzipSync } from 'fflate'
import { exportFigFile, initCodec, SceneGraph } from '@open-pencil/core'
@@ -7,8 +8,6 @@ import { parseFigKiwiContainer } from '@open-pencil/kiwi/fig/parse'
import { ByteBuffer, compileSchema, decodeBinarySchema } from '@open-pencil/kiwi/schema-runtime'
import type { Color, GUID } from '@open-pencil/scene-graph/primitives'
-import { expectDefined } from '#core-tests/helpers/assert'
-
interface DecodedPaint {
color?: Color
opacity?: number
@@ -97,7 +96,7 @@ describe('Figma export colour variable bindings', () => {
}
})
- test('writes bound fields resolved for each node\'s mode, as Figma draws the stored value', async () => {
+ test("writes bound fields resolved for each node's mode, as Figma draws the stored value", async () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
const theme = graph.createCollection('Theme')
diff --git a/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts b/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts
index cb4876f8d..6108ca511 100644
--- a/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts
+++ b/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts
@@ -1,15 +1,15 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
+import { inheritedNestedBindingRecords } from '#core-tests/helpers/fig/nested-binding'
+
import { createEditor } from '@open-pencil/core/editor'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
-import { expectDefined } from '#core-tests/helpers/assert'
-import { inheritedNestedBindingRecords } from '#core-tests/helpers/fig/nested-binding'
-import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
-
const fixture = readFixture('nested-binding-ownership-records.json', CapturedFigRecords)
test('a placed binding does not freeze an unrelated inherited binding', async () => {
diff --git a/packages/core/tests/io/formats/fig/export/gold-edit.test.ts b/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
index 30da38f12..45cd63ff5 100644
--- a/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
+++ b/packages/core/tests/io/formats/fig/export/gold-edit.test.ts
@@ -1,13 +1,13 @@
import { expect, test } from 'bun:test'
+import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
+
import { createEditor } from '@open-pencil/core/editor'
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
-
test('Gold document exposes effective Boolean assignments and supports editor undo/redo', async () => {
const parsed = parseFigBuffer(readFixtureArrayBuffer('gold-preview.fig'))
const diagnostics: unknown[] = []
diff --git a/packages/core/tests/io/formats/fig/export/layout-edit-export.test.ts b/packages/core/tests/io/formats/fig/export/layout-edit-export.test.ts
index 21404b106..84c541ab7 100644
--- a/packages/core/tests/io/formats/fig/export/layout-edit-export.test.ts
+++ b/packages/core/tests/io/formats/fig/export/layout-edit-export.test.ts
@@ -1,12 +1,12 @@
import { expect, test } from 'bun:test'
+import { guid } from '#core-tests/helpers/fig/guid'
+
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import { guid } from '#core-tests/helpers/fig/guid'
-
test('retained implicit layout survives import but does not override an explicit sizing edit', async () => {
await initCodec()
const changes: NodeChange[] = [
diff --git a/packages/core/tests/io/formats/fig/export/layout-scale.test.ts b/packages/core/tests/io/formats/fig/export/layout-scale.test.ts
index 910d0319c..7c9274a7f 100644
--- a/packages/core/tests/io/formats/fig/export/layout-scale.test.ts
+++ b/packages/core/tests/io/formats/fig/export/layout-scale.test.ts
@@ -1,5 +1,7 @@
import { expect, test } from 'bun:test'
+import { NestedLayoutScaleFixture, readFixture } from '#core-tests/helpers/fig/fixtures'
+
import { createEditor } from '@open-pencil/core/editor'
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
@@ -8,11 +10,9 @@ import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
import { symbolOverridesOf } from '@open-pencil/fig/instance-overrides'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { hasInstanceOverride } from '@open-pencil/scene-graph'
-import { NestedLayoutScaleFixture, readFixture } from '#core-tests/helpers/fig/fixtures'
const fixture = readFixture('nested-layout-scale.json', NestedLayoutScaleFixture)
-
function assembly(phase: 'before' | 'edited') {
return materializeDocument(
[{ guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT' }, ...fixture[phase]] as NodeChange[],
diff --git a/packages/core/tests/io/formats/fig/export/live-variable-scale.test.ts b/packages/core/tests/io/formats/fig/export/live-variable-scale.test.ts
index e6e4160c5..2ba796c46 100644
--- a/packages/core/tests/io/formats/fig/export/live-variable-scale.test.ts
+++ b/packages/core/tests/io/formats/fig/export/live-variable-scale.test.ts
@@ -1,13 +1,13 @@
import { expect, test } from 'bun:test'
+import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
+
import { createEditor } from '@open-pencil/core/editor'
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
-
function tagsInInput(graph: SceneGraph, rootId: string): SceneNode {
const found: SceneNode[] = []
const visit = (id: string) => {
diff --git a/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts b/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts
index addfb0047..c38f177bf 100644
--- a/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts
+++ b/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts
@@ -1,13 +1,13 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { exportFigFile, FigmaAPI, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
import { parseFigBuffer } from '@open-pencil/fig'
import type { SymbolData } from '@open-pencil/fig/instance-overrides'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
-import { expectDefined } from '#core-tests/helpers/assert'
-
/** The Kiwi codec types only `symbolID`; the rest of the symbol payload is read through here. */
const symbolDataOf = (record: NodeChange): SymbolData | undefined =>
record.symbolData as SymbolData | undefined
diff --git a/packages/core/tests/io/formats/fig/export/rescale-export.test.ts b/packages/core/tests/io/formats/fig/export/rescale-export.test.ts
index 39341c846..74608ea33 100644
--- a/packages/core/tests/io/formats/fig/export/rescale-export.test.ts
+++ b/packages/core/tests/io/formats/fig/export/rescale-export.test.ts
@@ -1,5 +1,8 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
+
import { createEditor } from '@open-pencil/core/editor'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { exportFigFile } from '@open-pencil/core/io'
@@ -8,9 +11,6 @@ import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
import { symbolDataOf } from '@open-pencil/fig/instance-overrides'
import { setInstanceOverride } from '@open-pencil/scene-graph'
-import { expectDefined } from '#core-tests/helpers/assert'
-import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
-
const fixture = readFixture('nested-binding-ownership-records.json', CapturedFigRecords)
for (const scale of [0.5, 2]) {
diff --git a/packages/core/tests/io/formats/fig/export/self-size-export.test.ts b/packages/core/tests/io/formats/fig/export/self-size-export.test.ts
index 1552d884a..4da10e0fc 100644
--- a/packages/core/tests/io/formats/fig/export/self-size-export.test.ts
+++ b/packages/core/tests/io/formats/fig/export/self-size-export.test.ts
@@ -1,13 +1,13 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
import { parseFigBuffer } from '@open-pencil/fig'
import { symbolDataOf } from '@open-pencil/fig/instance-overrides'
import { SceneGraph, setInstanceOverride, rescaleNodeTree } from '@open-pencil/scene-graph'
-import { expectDefined } from '#core-tests/helpers/assert'
-
test('serializes self size claims against the instance main component', async () => {
await initCodec()
const graph = new SceneGraph()
diff --git a/packages/core/tests/io/formats/fig/import/stale-overrides.test.ts b/packages/core/tests/io/formats/fig/import/stale-overrides.test.ts
index 079db58fd..db6448409 100644
--- a/packages/core/tests/io/formats/fig/import/stale-overrides.test.ts
+++ b/packages/core/tests/io/formats/fig/import/stale-overrides.test.ts
@@ -1,14 +1,14 @@
import { afterEach, expect, test } from 'bun:test'
+import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
+import { HEAVY_TEST_TIMEOUT_MS, runsHeavyTests } from '#core-tests/helpers/test-utils'
+
import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'
import { parseFigBuffer } from '@open-pencil/fig'
import { readerDiagnostics, registerReaderSession } from '#core/kiwi/fig/session/document-state'
import { openReaderSession } from '#core/kiwi/fig/session/reader'
-import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
-import { HEAVY_TEST_TIMEOUT_MS, runsHeavyTests } from '#core-tests/helpers/test-utils'
-
// Each full material3.fig graph takes gigabytes, and the collector does not run on its own
// between steps, so release them explicitly.
afterEach(() => {
diff --git a/packages/core/tests/io/formats/fig/instance/component-sync.test.ts b/packages/core/tests/io/formats/fig/instance/component-sync.test.ts
index 677540b72..7c780a74f 100644
--- a/packages/core/tests/io/formats/fig/instance/component-sync.test.ts
+++ b/packages/core/tests/io/formats/fig/instance/component-sync.test.ts
@@ -1,5 +1,7 @@
import { expect, test } from 'bun:test'
+import { guid } from '#core-tests/helpers/fig/guid'
+
import { FigmaAPI } from '@open-pencil/core'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
@@ -7,8 +9,6 @@ import { interpretInstance, materializeInstance } from '@open-pencil/fig/instanc
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { guid } from '#core-tests/helpers/fig/guid'
-
test('nested instances retain their outer source-child correspondence during sync', () => {
const source: NodeChange[] = [
{ guid: guid(1), type: 'SYMBOL' },
diff --git a/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts b/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts
index c16383995..815e00203 100644
--- a/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts
+++ b/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts
@@ -1,12 +1,12 @@
import { expect, test } from 'bun:test'
+import { guid } from '#core-tests/helpers/fig/guid'
+
import { FigmaAPI } from '@open-pencil/core'
import { interpretInstance, materializeInstance } from '@open-pencil/fig/instance-overrides'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { guid } from '#core-tests/helpers/fig/guid'
-
test('text overrides discard inherited glyph data but accept occurrence-derived replacement data', () => {
const changes = [
{ guid: guid(1), type: 'SYMBOL' },
diff --git a/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts b/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts
index f7703d055..d66a9905d 100644
--- a/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts
+++ b/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts
@@ -1,14 +1,21 @@
import { expect, test } from 'bun:test'
-import { interpretInstance, linkInstanceSourceChildren, mapInstanceSourceChildren, materializeComponentClosure, materializeInstance, type InstanceOccurrence } from '@open-pencil/fig/instance-overrides'
+import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
+
import { FigmaAPI } from '@open-pencil/core'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
import { parseFigBuffer } from '@open-pencil/fig'
+import {
+ interpretInstance,
+ linkInstanceSourceChildren,
+ mapInstanceSourceChildren,
+ materializeComponentClosure,
+ materializeInstance,
+ type InstanceOccurrence
+} from '@open-pencil/fig/instance-overrides'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
-
function named(node: InstanceOccurrence, name: string): InstanceOccurrence {
const child = node.children.find((candidate) => candidate.properties.name === name)
if (!child) throw new Error(`Missing ${name} under ${node.properties.name}`)
diff --git a/packages/core/tests/io/formats/fig/instance/source-children.test.ts b/packages/core/tests/io/formats/fig/instance/source-children.test.ts
index 112cea6be..252e51ca3 100644
--- a/packages/core/tests/io/formats/fig/instance/source-children.test.ts
+++ b/packages/core/tests/io/formats/fig/instance/source-children.test.ts
@@ -1,14 +1,20 @@
import { expect, test } from 'bun:test'
-import { interpretComponent, interpretInstance, linkInstanceSourceChildren, mapInstanceSourceChildren, materializeInstance } from '@open-pencil/fig/instance-overrides'
+import { guid } from '#core-tests/helpers/fig/guid'
+
import { FigmaAPI } from '@open-pencil/core'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
+import {
+ interpretComponent,
+ interpretInstance,
+ linkInstanceSourceChildren,
+ mapInstanceSourceChildren,
+ materializeInstance
+} from '@open-pencil/fig/instance-overrides'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { guid } from '#core-tests/helpers/fig/guid'
-
test('derives repeated nested child correspondence from materialized component occurrences', async () => {
const changes: NodeChange[] = [
{ guid: guid(1), type: 'SYMBOL' },
diff --git a/packages/core/tests/io/formats/fig/roundtrip/basic.test.ts b/packages/core/tests/io/formats/fig/roundtrip/basic.test.ts
index cd64f468e..3912b193a 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/basic.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/basic.test.ts
@@ -1,5 +1,8 @@
import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+import { collectAllNodes, countByType } from '#core-tests/helpers/fig/traversal'
+
import {
exportFigFile,
initCodec,
@@ -9,9 +12,6 @@ import {
} from '@open-pencil/core'
import { populateFigPage } from '@open-pencil/core/io/formats/fig'
-import { expectDefined } from '#core-tests/helpers/assert'
-import { collectAllNodes, countByType } from '#core-tests/helpers/fig/traversal'
-
setDefaultTimeout(60_000)
describe('roundtrip: export → re-import', () => {
diff --git a/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts b/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts
index 91e729af3..46a6963e2 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts
@@ -51,7 +51,9 @@ describe('.fig round trip of behaviours', () => {
booleans: { filled: { propertyId: 'filled', on: 'Yes', off: 'No' } },
states: guessInteractionStates('interaction', ['Default', 'Focus'])
})
- expect(missingBindings(editor.graph, set, readBehaviour(set) ?? emptyBehaviour('button'))).toEqual([])
+ expect(
+ missingBindings(editor.graph, set, readBehaviour(set) ?? emptyBehaviour('button'))
+ ).toEqual([])
const reopened = await parseFigFile((await exportFigFile(editor.graph)).slice().buffer)
const owner = [...reopened.nodes.values()].find((node) => node.name === 'Field')
diff --git a/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts b/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts
index 1c7d87f4b..2f613d518 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts
@@ -2,15 +2,14 @@ import { beforeAll, describe, expect, test } from 'bun:test'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
-import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
-import { fontManager } from '@open-pencil/core/text'
-import { parseFigBuffer } from '@open-pencil/fig'
-
import { expectDefined } from '#core-tests/helpers/assert'
-import { HEAVY_TEST_TIMEOUT_MS } from '#core-tests/helpers/test-utils'
-
import { FIXTURES } from '#core-tests/helpers/fig/fixtures'
import { corePackagePath } from '#core-tests/helpers/paths'
+import { HEAVY_TEST_TIMEOUT_MS } from '#core-tests/helpers/test-utils'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { fontManager } from '@open-pencil/core/text'
+import { parseFigBuffer } from '@open-pencil/fig'
const INTER_ASSETS = corePackagePath('assets')
diff --git a/packages/core/tests/io/formats/fig/roundtrip/group.test.ts b/packages/core/tests/io/formats/fig/roundtrip/group.test.ts
index 854eeb8ac..67abdc785 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/group.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/group.test.ts
@@ -1,9 +1,9 @@
import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
-import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
-
import { collectAllNodes } from '#core-tests/helpers/fig/traversal'
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+
setDefaultTimeout(60_000)
describe('roundtrip: GROUP survives export → re-import', () => {
diff --git a/packages/core/tests/io/formats/fig/roundtrip/slots.test.ts b/packages/core/tests/io/formats/fig/roundtrip/slots.test.ts
index 56264122a..b9deabe43 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/slots.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/slots.test.ts
@@ -1,5 +1,7 @@
import { beforeAll, describe, expect, test } from 'bun:test'
+import { FIXTURES } from '#core-tests/helpers/fig/fixtures'
+
import {
exportFigFile,
initCodec,
@@ -11,8 +13,6 @@ import { parseFigBuffer } from '@open-pencil/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { slotPropertyId } from '@open-pencil/scene-graph'
-import { FIXTURES } from '#core-tests/helpers/fig/fixtures'
-
let original: SceneGraph
let reopened: SceneGraph
let records: NodeChange[]
@@ -48,7 +48,9 @@ beforeAll(async () => {
if (!untouched) throw new Error('Missing Page 1')
original.updateNode(untouched.id, { name: 'Page 1 (edited)' })
const exported = await exportFigFile(original)
- expect(exported).not.toEqual(new Uint8Array(await Bun.file(`${FIXTURES}/slots.fig`).arrayBuffer()))
+ expect(exported).not.toEqual(
+ new Uint8Array(await Bun.file(`${FIXTURES}/slots.fig`).arrayBuffer())
+ )
records = parseFigBuffer(exported.slice().buffer).nodeChanges
reopened = await parseFigFile(exported.slice().buffer)
})
@@ -61,9 +63,7 @@ describe('slots round trip', () => {
})
test('slot properties are written as SLOT definitions with their settings', () => {
- const definitions = records.flatMap(
- (record) => (record as SlotRecord).componentPropDefs ?? []
- )
+ const definitions = records.flatMap((record) => (record as SlotRecord).componentPropDefs ?? [])
const slots = definitions.filter((definition) => definition.type === 'SLOT')
// Card empty slot, Card default content, List, Panel, and Panel's two variants. Figma
// links a variant's definition to the set's through `parentPropDefId`; the exporter
diff --git a/packages/core/tests/io/formats/fig/roundtrip/stroke-geometry.test.ts b/packages/core/tests/io/formats/fig/roundtrip/stroke-geometry.test.ts
index b2a37241f..1fb04884a 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/stroke-geometry.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/stroke-geometry.test.ts
@@ -1,10 +1,10 @@
import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
+import { collectAllNodes } from '#core-tests/helpers/fig/traversal'
+
import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { collectAllNodes } from '#core-tests/helpers/fig/traversal'
-
setDefaultTimeout(60_000)
describe('roundtrip: stroke geometry without strokes', () => {
diff --git a/packages/core/tests/io/formats/fig/roundtrip/stroke-paints.test.ts b/packages/core/tests/io/formats/fig/roundtrip/stroke-paints.test.ts
index a06a20105..885aa6319 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/stroke-paints.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/stroke-paints.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, setDefaultTimeout, test } from 'bun:test'
-import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
-
import { expectDefined } from '#core-tests/helpers/assert'
import { collectAllNodes } from '#core-tests/helpers/fig/traversal'
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+
setDefaultTimeout(60_000)
const STOPS = [
diff --git a/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts b/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts
index e1758a5b4..c8ab4e5f7 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, setDefaultTimeout, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+import { parseFixture } from '#core-tests/helpers/fig/fixtures'
+import { runsHeavyTests } from '#core-tests/helpers/test-utils'
+
import {
exportFigFile,
FigmaAPI,
@@ -10,10 +14,6 @@ import {
} from '@open-pencil/core'
import type { Color } from '@open-pencil/scene-graph'
-import { expectDefined } from '#core-tests/helpers/assert'
-import { parseFixture } from '#core-tests/helpers/fig/fixtures'
-import { runsHeavyTests } from '#core-tests/helpers/test-utils'
-
setDefaultTimeout(60_000)
describe('variable roundtrip', () => {
diff --git a/packages/core/tests/io/formats/fig/session/document-state.test.ts b/packages/core/tests/io/formats/fig/session/document-state.test.ts
index b019a540b..5e1de9f0e 100644
--- a/packages/core/tests/io/formats/fig/session/document-state.test.ts
+++ b/packages/core/tests/io/formats/fig/session/document-state.test.ts
@@ -1,5 +1,7 @@
import { expect, test } from 'bun:test'
+import { inertPopulationWorker } from '#core-tests/helpers/fig/population-worker'
+
import { createEditor } from '@open-pencil/core/editor'
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
@@ -19,7 +21,6 @@ import {
} from '#core/kiwi/fig/session/document-state'
import type { FigSessionPopulateRequest, FigSessionResponse } from '#core/kiwi/fig/session/protocol'
import { openReaderSession } from '#core/kiwi/fig/session/reader'
-import { inertPopulationWorker } from '#core-tests/helpers/fig/population-worker'
test('rejected worker response cannot mark an unloaded page loaded in recovery', async () => {
await initCodec()
diff --git a/packages/core/tests/io/formats/fig/session/property-driven-text.test.ts b/packages/core/tests/io/formats/fig/session/property-driven-text.test.ts
index 1facce083..94d082956 100644
--- a/packages/core/tests/io/formats/fig/session/property-driven-text.test.ts
+++ b/packages/core/tests/io/formats/fig/session/property-driven-text.test.ts
@@ -1,12 +1,12 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
import { createFigDocumentSession, materializeFigArchive } from '@open-pencil/fig'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
-import { expectDefined } from '#core-tests/helpers/assert'
-
/**
* The component lives on one page and the instance that assigns its properties on another, so
* loading the second page alone has to interpret the assignments and keep them: the resumed
diff --git a/packages/core/tests/io/formats/fig/session/unavailable-reader.test.ts b/packages/core/tests/io/formats/fig/session/unavailable-reader.test.ts
index 794364d43..1f04d821f 100644
--- a/packages/core/tests/io/formats/fig/session/unavailable-reader.test.ts
+++ b/packages/core/tests/io/formats/fig/session/unavailable-reader.test.ts
@@ -1,12 +1,13 @@
import { expect, test } from 'bun:test'
+import { inertPopulationWorker } from '#core-tests/helpers/fig/population-worker'
+
import { createEditor } from '@open-pencil/core/editor'
import {
registerFigPopulationWorker,
releaseFigPopulationWorker
} from '#core/kiwi/fig/population/client'
-import { inertPopulationWorker } from '#core-tests/helpers/fig/population-worker'
test('new live pages do not require unavailable reader recovery', async () => {
const editor = createEditor()
diff --git a/packages/core/tests/io/formats/fig/session/worker-reader.test.ts b/packages/core/tests/io/formats/fig/session/worker-reader.test.ts
index acac83fb6..7d2499c01 100644
--- a/packages/core/tests/io/formats/fig/session/worker-reader.test.ts
+++ b/packages/core/tests/io/formats/fig/session/worker-reader.test.ts
@@ -14,10 +14,9 @@ test.each(['first-page', 'none'] as const)(
graph.createNode('TEXT', graph.getPages()[0].id, { text: 'First' })
graph.createNode('TEXT', graph.addPage('Second').id, { text: 'Second' })
const bytes = await exportFigFile(graph)
- const worker = new Worker(
- import.meta.resolve('#core/kiwi/fig/session/worker'),
- { type: 'module' }
- )
+ const worker = new Worker(import.meta.resolve('#core/kiwi/fig/session/worker'), {
+ type: 'module'
+ })
const channel = new MessageChannel()
const messages: FigSessionResponse[] = []
let notify: (() => void) | undefined
diff --git a/packages/core/tests/lint/fixes.test.ts b/packages/core/tests/lint/fixes.test.ts
index bc94b4929..bc10121b2 100644
--- a/packages/core/tests/lint/fixes.test.ts
+++ b/packages/core/tests/lint/fixes.test.ts
@@ -117,7 +117,11 @@ describe('suggestions', () => {
test('snap radius to the nearest scale value, or full radius for a pill', () => {
const graph = new SceneGraph()
const pageId = graph.getPages()[0].id
- const card = graph.createNode('RECTANGLE', pageId, { width: 200, height: 100, cornerRadius: 10 })
+ const card = graph.createNode('RECTANGLE', pageId, {
+ width: 200,
+ height: 100,
+ cornerRadius: 10
+ })
const pill = graph.createNode('RECTANGLE', pageId, { width: 80, height: 28, cornerRadius: 14 })
const suggestions = new Map(
diff --git a/packages/core/tests/lint/rules.test.ts b/packages/core/tests/lint/rules.test.ts
index b28657813..ceb6305af 100644
--- a/packages/core/tests/lint/rules.test.ts
+++ b/packages/core/tests/lint/rules.test.ts
@@ -126,7 +126,11 @@ describe('touch-target-size', () => {
const pageId = graph.getPages()[0].id
graph.createNode('RECTANGLE', pageId, { name: 'Rectangle', width: 1, height: 80 })
graph.createNode('FRAME', pageId, { name: 'Tablet preview', width: 20, height: 20 })
- const iconButton = graph.createNode('FRAME', pageId, { name: 'IconButton2', width: 32, height: 32 })
+ const iconButton = graph.createNode('FRAME', pageId, {
+ name: 'IconButton2',
+ width: 32,
+ height: 32
+ })
expect(lint(graph, 'touch-target-size').map((message) => message.nodeId)).toEqual([
iconButton.id
diff --git a/packages/core/tests/rpc/variables-command.test.ts b/packages/core/tests/rpc/variables-command.test.ts
index 0b5c3b121..a0f9f8b12 100644
--- a/packages/core/tests/rpc/variables-command.test.ts
+++ b/packages/core/tests/rpc/variables-command.test.ts
@@ -24,9 +24,16 @@ describe('tokens command', () => {
})
})
+ test('writes W3C design token files for the dtcg format', async () => {
+ const result = (await executeRPCCommand(graphWithTokens(), 'tokens', {
+ format: 'dtcg'
+ })) as TokensResult
+ expect(result.files?.map((file) => file.path)).toContain('tokens.resolver.json')
+ })
+
test('rejects an unknown format or type', () => {
expect(() => executeRPCCommand(graphWithTokens(), 'tokens', { format: 'scss' })).toThrow(
- 'Unknown token format: scss. Use css or tailwind.'
+ 'Unknown token format: scss. Use css, tailwind, or dtcg.'
)
expect(() => executeRPCCommand(graphWithTokens(), 'tokens', { type: 'shadow' })).toThrow(
'Unknown variable type: shadow. Use COLOR, FLOAT, STRING, BOOLEAN.'
diff --git a/packages/core/tests/tools/ai-adapter.test.ts b/packages/core/tests/tools/ai-adapter.test.ts
index 53458602d..99d0b1932 100644
--- a/packages/core/tests/tools/ai-adapter.test.ts
+++ b/packages/core/tests/tools/ai-adapter.test.ts
@@ -122,7 +122,10 @@ describe('AI adapter tool log', () => {
})
test('logs a returned error as a failure, like a thrown one', async () => {
- const { entries } = await runLogged(() => ({ id: '999:999', error: 'Node "999:999" not found' }))
+ const { entries } = await runLogged(() => ({
+ id: '999:999',
+ error: 'Node "999:999" not found'
+ }))
expect(entries).toMatchObject([{ error: 'Node "999:999" not found', cause: undefined }])
})
diff --git a/packages/core/tests/tools/analyze/diff/apply.test.ts b/packages/core/tests/tools/analyze/diff/apply.test.ts
index 3d8dd8b8b..1eb400971 100644
--- a/packages/core/tests/tools/analyze/diff/apply.test.ts
+++ b/packages/core/tests/tools/analyze/diff/apply.test.ts
@@ -1,13 +1,13 @@
import { describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+import { findByName, PROPERTY_CASES } from '#core-tests/helpers/property-cases'
import { pick } from 'es-toolkit'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { ALL_TOOLS } from '@open-pencil/core/tools'
import { createDefaultNode, SceneGraph } from '@open-pencil/scene-graph'
-import { expectDefined } from '#core-tests/helpers/assert'
-import { findByName, PROPERTY_CASES } from '#core-tests/helpers/property-cases'
-
function tool(name: string) {
return expectDefined(
ALL_TOOLS.find((candidate) => candidate.name === name),
diff --git a/packages/core/tests/tools/analyze/diff/changes.test.ts b/packages/core/tests/tools/analyze/diff/changes.test.ts
index f00eee976..9b63ecf60 100644
--- a/packages/core/tests/tools/analyze/diff/changes.test.ts
+++ b/packages/core/tests/tools/analyze/diff/changes.test.ts
@@ -1,12 +1,12 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { createEditor, graphFromPageSnapshot } from '@open-pencil/core/editor'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { ALL_TOOLS } from '@open-pencil/core/tools'
import { sceneNodeToJSX } from '@open-pencil/design-jsx'
-import { expectDefined } from '#core-tests/helpers/assert'
-
type ChangesResult = { diff?: string | null; message?: string; error?: string }
const diffChanges = expectDefined(
diff --git a/packages/core/tests/tools/analyze/diff/engine.test.ts b/packages/core/tests/tools/analyze/diff/engine.test.ts
index 537db1c26..b4670f1b5 100644
--- a/packages/core/tests/tools/analyze/diff/engine.test.ts
+++ b/packages/core/tests/tools/analyze/diff/engine.test.ts
@@ -1,16 +1,13 @@
import { describe, expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
import { formatOperations, parseOperations } from '#core/tools/analyze/diff/format'
import { deltaOperations, type DiffOperation } from '#core/tools/analyze/diff/operations'
-import {
- diffProjections,
- projectTree,
- type DiffMatch
-} from '#core/tools/analyze/diff/projection'
-import { expectDefined } from '#core-tests/helpers/assert'
+import { diffProjections, projectTree, type DiffMatch } from '#core/tools/analyze/diff/projection'
/** Operations for what `edit` changes; a projection is plain data, so it snapshots the tree. */
function operations(graph: SceneGraph, rootId: string, match: DiffMatch, edit: () => void) {
@@ -39,7 +36,13 @@ describe('diff engine', () => {
const child = expectDefined(root.children[0], 'child')
expect(operations(graph, root.id, 'id', () => (child.name = 'Renamed'))).toEqual([
- { kind: 'update', path: '/Card/A', id: child.id, removed: ['name="A"'], added: ['name="Renamed"'] }
+ {
+ kind: 'update',
+ path: '/Card/A',
+ id: child.id,
+ removed: ['name="A"'],
+ added: ['name="Renamed"']
+ }
])
})
@@ -48,10 +51,7 @@ describe('diff engine', () => {
const child = expectDefined(root.children[0], 'child')
const ops = operations(graph, root.id, 'path', () => (child.name = 'Renamed'))
- expect(ops.map((op) => op.kind).toSorted()).toEqual([
- 'add',
- 'remove'
- ])
+ expect(ops.map((op) => op.kind).toSorted()).toEqual(['add', 'remove'])
})
test('a reordered child is one move, not a change to every sibling', () => {
@@ -77,7 +77,13 @@ describe('diff engine', () => {
describe('patch format', () => {
test('parses what it prints', () => {
const ops: DiffOperation[] = [
- { kind: 'update', path: '/Card', id: '1:2', removed: ['w={1}'], added: ['w={2}', 'clipsContent'] },
+ {
+ kind: 'update',
+ path: '/Card',
+ id: '1:2',
+ removed: ['w={1}'],
+ added: ['w={2}', 'clipsContent']
+ },
{ kind: 'move', path: '/Card/Badge', id: '1:3', index: 0 },
// Names that look like header endings still parse, because headers anchor on the end.
{ kind: 'remove', path: '/Card/Old #9:9 removed', id: '1:4' },
diff --git a/packages/core/tests/tools/analyze/diff/jsx.test.ts b/packages/core/tests/tools/analyze/diff/jsx.test.ts
index 0a32226f1..5571e3754 100644
--- a/packages/core/tests/tools/analyze/diff/jsx.test.ts
+++ b/packages/core/tests/tools/analyze/diff/jsx.test.ts
@@ -1,10 +1,10 @@
import { expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { createEditor, graphFromPageSnapshot } from '@open-pencil/core/editor'
import { diffPageLayersJSX } from '@open-pencil/core/tools'
-import { expectDefined } from '#core-tests/helpers/assert'
-
test('reports top-level layers changed deep in their subtree, added, or removed', () => {
const editor = createEditor()
const pageId = editor.state.currentPageId
diff --git a/packages/core/tests/tools/analyze/diff/tools.test.ts b/packages/core/tests/tools/analyze/diff/tools.test.ts
index 29cacd266..a0e4dffb9 100644
--- a/packages/core/tests/tools/analyze/diff/tools.test.ts
+++ b/packages/core/tests/tools/analyze/diff/tools.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, test } from 'bun:test'
+import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
+
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { ALL_TOOLS, diffDocuments } from '@open-pencil/core/tools'
import { SceneGraph, type Color } from '@open-pencil/scene-graph'
-import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
-
type DiffResult = { diff?: string | null; message?: string; error?: string }
type ApplyResult = {
error?: string
@@ -86,7 +86,9 @@ describe('diff_create and diff_apply', () => {
const copy = card.clone()
copy.opacity = 0.5
- await run<ApplyResult>(figma, 'diff_apply', { patch: await createPatch(figma, card.id, copy.id) })
+ await run<ApplyResult>(figma, 'diff_apply', {
+ patch: await createPatch(figma, card.id, copy.id)
+ })
expect(getNodeOrThrow(graph, card.id).opacity).toBe(0.5)
expect(card.getPluginData('note')).toBe('kept')
})
diff --git a/packages/core/tests/tools/analyze/diff/visual.test.ts b/packages/core/tests/tools/analyze/diff/visual.test.ts
index 3e3b5b894..ee6956b7f 100644
--- a/packages/core/tests/tools/analyze/diff/visual.test.ts
+++ b/packages/core/tests/tools/analyze/diff/visual.test.ts
@@ -1,5 +1,7 @@
import { beforeAll, describe, expect, test } from 'bun:test'
+import { expectDefined } from '#core-tests/helpers/assert'
+
import { FigmaAPI } from '@open-pencil/core/figma-api'
import {
createCanvasKitRasterCodec,
@@ -10,8 +12,6 @@ import { ALL_TOOLS } from '@open-pencil/core/tools'
import { SceneGraph, type Color } from '@open-pencil/scene-graph'
import type { Rect } from '@open-pencil/scene-graph/primitives'
-import { expectDefined } from '#core-tests/helpers/assert'
-
type VisualDiff = {
error?: string
mimeType?: string
diff --git a/packages/core/tests/tools/analyze/lint.test.ts b/packages/core/tests/tools/analyze/lint.test.ts
index 8a3acd747..0622cd425 100644
--- a/packages/core/tests/tools/analyze/lint.test.ts
+++ b/packages/core/tests/tools/analyze/lint.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, test } from 'bun:test'
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
import { FigmaAPI } from '@open-pencil/core'
import { ALL_TOOLS } from '@open-pencil/core/tools'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { getNodeOrThrow } from '#core-tests/helpers/assert'
-
function tool(name: string) {
const def = ALL_TOOLS.find((candidate) => candidate.name === name)
if (!def) throw new Error(`Missing tool ${name}`)
diff --git a/packages/core/tests/tools/codegen/tokens.test.ts b/packages/core/tests/tools/codegen/tokens.test.ts
index 52fb4d914..92f859dd5 100644
--- a/packages/core/tests/tools/codegen/tokens.test.ts
+++ b/packages/core/tests/tools/codegen/tokens.test.ts
@@ -13,8 +13,7 @@ interface TokensToolResult extends Omit<TokenExport, 'css'> {
const run = async (
figma: FigmaAPI,
args: Parameters<typeof designToTokens.execute>[1]
-): Promise<TokensToolResult> =>
- (await designToTokens.execute(figma, args)) as TokensToolResult
+): Promise<TokensToolResult> => (await designToTokens.execute(figma, args)) as TokensToolResult
function themeTokens() {
const graph = new SceneGraph()
diff --git a/packages/docs/de/user-guide/variables.md b/packages/docs/de/user-guide/variables.md
index b0cefc722..8e0e4a451 100644
--- a/packages/docs/de/user-guide/variables.md
+++ b/packages/docs/de/user-guide/variables.md
@@ -71,6 +71,15 @@ Die Auswahl einer Variable bearbeitet:
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.
+## Design-Tokens importieren und exportieren
+
+Variablen und Stile wandern als [W3C-Design-Tokens](https://www.designtokens.org/) zwischen OpenPencil, Figma und Code:
+
+- **Exportieren:** Wähle im Kopiermenü des Stylesheets **Als Design-Tokens exportieren**. Das ZIP enthält je Modus einer Sammlung eine Datei, die Figma als Modus importiert, Text- und Effektstile als Typografie- und Schatten-Tokens sowie einen Resolver, der alles für Werkzeuge wie Style Dictionary zusammenführt
+- **Importieren:** Klicke in der Werkzeugleiste auf **Design-Tokens importieren** und wähle Token-Dateien oder ein ZIP. Dateien aus Figma, ein Resolver mit den Dateien, die er nennt, und Tokens-Studio-Themes funktionieren
+- **Ziel wählen:** Bevor sich etwas ändert, zeigt der Dialog jede gefundene Sammlung und jeden Modus und wohin sie gehen: in eine neue Sammlung oder einen neuen Modus, in einen vorhandenen oder nirgendwohin. Variablen und Stile mit demselben Namen werden aktualisiert, der Rest wird hinzugefügt; nichts wird gelöscht. Er zählt, was hinzugefügt, aktualisiert und übersprungen wird, und nennt für jedes übersprungene Token den Grund
+- Der Import ist ein Schritt: **Rückgängig** nimmt ihn ganz zurück
+
## 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.
diff --git a/packages/docs/es/user-guide/variables.md b/packages/docs/es/user-guide/variables.md
index 107e36681..4ddeabe90 100644
--- a/packages/docs/es/user-guide/variables.md
+++ b/packages/docs/es/user-guide/variables.md
@@ -71,6 +71,15 @@ Al seleccionar una variable se editan:
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.
+## Importar y exportar design tokens
+
+Las variables y los estilos pasan entre OpenPencil, Figma y el código como [design tokens del W3C](https://www.designtokens.org/):
+
+- **Exportar:** en el menú de copia de la hoja de estilos, elige **Exportar como design tokens**. El zip contiene un archivo por cada modo de colección, que Figma importa como modo; los estilos de texto y de efecto como tokens de tipografía y de sombra; y un resolver que lo combina todo para herramientas como Style Dictionary
+- **Importar:** haz clic en **Importar design tokens** en la barra de herramientas y elige archivos de tokens o un zip. Funcionan los archivos de Figma, un resolver con los archivos que nombra y los temas de Tokens Studio
+- **Elegir el destino:** antes de cambiar nada, el diálogo muestra cada colección y modo que encontró y adónde va: a una colección o un modo nuevos, a uno existente o a ninguna parte. Las variables y los estilos con el mismo nombre se actualizan y el resto se añade; no se elimina nada. Cuenta lo que se añadirá, actualizará y omitirá, y explica por qué se omitió cada token
+- La importación es un solo paso: **Deshacer** la revierte entera
+
## 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.
diff --git a/packages/docs/fr/user-guide/variables.md b/packages/docs/fr/user-guide/variables.md
index 85539ef8a..6bc7ec115 100644
--- a/packages/docs/fr/user-guide/variables.md
+++ b/packages/docs/fr/user-guide/variables.md
@@ -71,6 +71,15 @@ La sélection d’une variable permet de modifier :
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.
+## Importer et exporter des design tokens
+
+Les variables et les styles circulent entre OpenPencil, Figma et le code sous forme de [design tokens W3C](https://www.designtokens.org/) :
+
+- **Exporter :** dans le menu de copie de la feuille de style, choisissez **Exporter en design tokens**. Le zip contient un fichier par mode de collection, que Figma importe comme un mode ; les styles de texte et d’effet en tokens de typographie et d’ombre ; et un resolver qui les combine pour des outils comme Style Dictionary
+- **Importer :** cliquez sur **Importer des design tokens** dans la barre d’outils et choisissez des fichiers de tokens ou un zip. Les fichiers de Figma, un resolver avec les fichiers qu’il nomme et les thèmes Tokens Studio fonctionnent
+- **Choisir la destination :** avant tout changement, la boîte de dialogue montre chaque collection et chaque mode trouvés et où ils vont : dans une nouvelle collection ou un nouveau mode, dans un existant, ou nulle part. Les variables et les styles de même nom sont mis à jour et le reste est ajouté ; rien n’est supprimé. Elle compte ce qui sera ajouté, mis à jour et ignoré, et indique pourquoi chaque token ignoré a été écarté
+- L’import est une seule étape : **Annuler** le reprend en entier
+
## 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.
diff --git a/packages/docs/it/user-guide/variables.md b/packages/docs/it/user-guide/variables.md
index d62c90c4a..7821f1375 100644
--- a/packages/docs/it/user-guide/variables.md
+++ b/packages/docs/it/user-guide/variables.md
@@ -71,6 +71,15 @@ La selezione di una variabile permette di modificare:
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.
+## Importare ed esportare design token
+
+Variabili e stili passano tra OpenPencil, Figma e il codice come [design token W3C](https://www.designtokens.org/):
+
+- **Esportare:** nel menu di copia del foglio di stile scegli **Esporta come design token**. Lo zip contiene un file per ogni modalità di raccolta, che Figma importa come modalità; gli stili di testo ed effetto come token di tipografia e ombra; e un resolver che li combina per strumenti come Style Dictionary
+- **Importare:** fai clic su **Importa design token** nella barra degli strumenti e scegli file di token o uno zip. Funzionano i file di Figma, un resolver con i file che nomina e i temi di Tokens Studio
+- **Scegliere la destinazione:** prima che cambi qualcosa, la finestra mostra ogni raccolta e modalità trovata e dove va: in una nuova raccolta o modalità, in una esistente o da nessuna parte. Variabili e stili con lo stesso nome vengono aggiornati e il resto viene aggiunto; nulla viene eliminato. Conta cosa verrà aggiunto, aggiornato e saltato, e spiega perché ogni token saltato è stato escluso
+- L’importazione è un solo passaggio: **Annulla** la ritira tutta
+
## 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.
diff --git a/packages/docs/pl/user-guide/variables.md b/packages/docs/pl/user-guide/variables.md
index e2511646f..4dc36e738 100644
--- a/packages/docs/pl/user-guide/variables.md
+++ b/packages/docs/pl/user-guide/variables.md
@@ -71,6 +71,15 @@ Zaznaczenie zmiennej pozwala edytować:
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.
+## Import i eksport tokenów projektowych
+
+Zmienne i style przechodzą między OpenPencil, Figmą i kodem jako [tokeny projektowe W3C](https://www.designtokens.org/):
+
+- **Eksport:** w menu kopiowania arkusza stylów wybierz **Eksportuj jako tokeny projektowe**. Archiwum zip zawiera po jednym pliku na każdy tryb kolekcji, który Figma importuje jako tryb; style tekstu i efektów jako tokeny typografii i cieni; oraz resolver, który łączy je dla narzędzi takich jak Style Dictionary
+- **Import:** kliknij **Importuj tokeny projektowe** na pasku narzędzi i wybierz pliki tokenów lub zip. Działają pliki z Figmy, resolver z plikami, które wskazuje, oraz motywy Tokens Studio
+- **Wybór miejsca:** zanim cokolwiek się zmieni, okno pokazuje każdą znalezioną kolekcję i tryb oraz to, dokąd trafią: do nowej kolekcji lub trybu, do istniejącego albo nigdzie. Zmienne i style o tej samej nazwie są aktualizowane, a reszta dodawana; nic nie jest usuwane. Okno podaje, co zostanie dodane, zaktualizowane i pominięte, oraz dlaczego pominięto każdy token
+- Import to jeden krok: **Cofnij** wycofuje go w całości
+
## Powiązywanie zmiennych z zalewami
W sekcji „Zalew” panelu właściwości użyj wyboru zmiennej, aby powiązać zmienną koloru z zalewem obiektu.
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index a7cccd4b6..f70c71d97 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -122,6 +122,24 @@ Each collection's default mode goes in `:root`. Every other mode overrides the v
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.
+### W3C design tokens
+
+`--format dtcg` writes the variables and styles as [W3C design tokens](https://www.designtokens.org/tr/2025.10/format/) into a folder:
+
+```sh
+openpencil tokens design.fig --format dtcg --out tokens
+```
+
+Each collection mode is one file, `Theme/Light.tokens.json` and `Theme/Dark.tokens.json`, in the shape Figma imports as a mode: lengths in `px`, times in `s`, booleans as numbers marked `com.figma.type`, and aliases to another collection naming it in `com.figma.aliasData`. Text and effect styles become typography and shadow tokens in `styles.tokens.json`, kept apart because Figma's import refuses composite tokens. `tokens.resolver.json` is a DTCG resolver that switches each collection's modes and layers the rest, for tools such as Style Dictionary. OpenPencil's own fields, such as a token's `rem` unit, CSS name, scopes, or `clamp()` expression, and each mode's condition, ride in `$extensions["dev.openpencil"]`, so the export reads back exactly.
+
+Import token files into a document with the `import_design_tokens` tool, passing each file's path and text:
+
+```sh
+openpencil tool call import_design_tokens design.fig --args-file tokens.json --write
+```
+
+It reads a file per mode grouped by folder, a resolver with the files it refers to, or a Tokens Studio file with `$themes`. Collections and modes with existing names, and variables and styles by name, are updated; the rest is added, and nothing is deleted. The result lists what was added, updated, and skipped, with the reason for each skip.
+
## 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 db2096be7..0acd2511d 100644
--- a/packages/docs/reference/cli.md
+++ b/packages/docs/reference/cli.md
@@ -98,7 +98,8 @@ openpencil tokens [file] [options]
| Option | Description |
|--------|-------------|
-| `--format` | `css` (default), or `tailwind` for a Tailwind v4 `@theme` with a `@custom-variant` per mode |
+| `--format` | `css` (default), `tailwind` for a Tailwind v4 `@theme` with a `@custom-variant` per mode, or `dtcg` for W3C design token files |
+| `--out`, `-o` | Folder the `dtcg` files are written to; required for that format |
| `--collection` | Filter by collection name |
| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` |
| `--json` | Output `{ css, tokenCount, issues }` as JSON |
diff --git a/packages/docs/ru/user-guide/variables.md b/packages/docs/ru/user-guide/variables.md
index ff6d27d7e..ec8f4228b 100644
--- a/packages/docs/ru/user-guide/variables.md
+++ b/packages/docs/ru/user-guide/variables.md
@@ -71,6 +71,15 @@ description: Переменные дизайна, коллекции, режим
Внизу диалога активная коллекция показана как пользовательские свойства CSS. Кнопка копирования (**Копировать все переменные как CSS**) копирует переменные всего документа как CSS или как тему Tailwind v4 (**Копировать все переменные как тему Tailwind**), поэтому ссылки на другие коллекции разрешаются.
+## Импорт и экспорт дизайн-токенов
+
+Переменные и стили переходят между OpenPencil, Figma и кодом как [дизайн-токены W3C](https://www.designtokens.org/):
+
+- **Экспорт:** в меню копирования таблицы стилей выберите **Экспортировать как дизайн-токены**. В zip-архиве по файлу на каждый режим коллекции, который Figma импортирует как режим; стили текста и эффектов как токены типографики и теней; и resolver, который объединяет их для инструментов вроде Style Dictionary
+- **Импорт:** нажмите **Импортировать дизайн-токены** на панели инструментов и выберите файлы токенов или zip. Подходят файлы из Figma, resolver с файлами, на которые он ссылается, и темы Tokens Studio
+- **Куда импортировать:** до каких-либо изменений диалог показывает каждую найденную коллекцию и режим и то, куда они попадут: в новую коллекцию или режим, в существующие или никуда. Переменные и стили с тем же именем обновляются, остальное добавляется; ничего не удаляется. Диалог считает, что будет добавлено, обновлено и пропущено, и объясняет, почему пропущен каждый токен
+- Импорт — один шаг: **Отменить** возвращает всё обратно
+
## Привязка переменных к заливке
В разделе «Заливка» панели свойств используйте выбор переменной, чтобы привязать цветовую переменную к заливке объекта.
diff --git a/packages/docs/user-guide/variables.md b/packages/docs/user-guide/variables.md
index 392711ea3..1c0c62e35 100644
--- a/packages/docs/user-guide/variables.md
+++ b/packages/docs/user-guide/variables.md
@@ -71,6 +71,15 @@ Selecting a variable edits:
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.
+## Importing and Exporting Design Tokens
+
+Variables and styles move between OpenPencil, Figma, and code as [W3C design tokens](https://www.designtokens.org/):
+
+- **Export:** in the stylesheet's copy menu, choose **Export as design tokens**. The zip holds one file per collection mode, which Figma imports as a mode; text and effect styles as typography and shadow tokens; and a resolver that combines them for tools such as Style Dictionary
+- **Import:** click **Import design tokens** in the toolbar and pick token files or a zip. Files from Figma, a resolver with the files it names, and Tokens Studio themes all work
+- **Choose where it goes:** before anything changes, the dialog shows each collection and mode it found and where it goes: a new collection or mode, an existing one, or nowhere. Variables and styles with the same name are updated and the rest is added; nothing is deleted. It counts what will be added, updated, and skipped, and lists why each skipped token was left out
+- The import is one step: **Undo** takes it all back
+
## Binding Variables to Fills
In the Fill section of the properties panel, use the variable picker to bind a color variable to a node's fill.
diff --git a/packages/scene-graph/src/color/management.ts b/packages/scene-graph/src/color/management.ts
index 3fe6ee0ec..effccc7fc 100644
--- a/packages/scene-graph/src/color/management.ts
+++ b/packages/scene-graph/src/color/management.ts
@@ -1,4 +1,4 @@
-import { converter, formatCss, formatRgb, inGamut, toGamut } from 'culori'
+import { converter, formatCss, formatRgb, inGamut, parse, toGamut } from 'culori'
import type { Color } from '../primitives'
import type { DocumentColorSpace, Fill, SceneNode, Stroke } from '../types'
@@ -149,6 +149,20 @@ export function resolveOkHCLForPreview(
}
}
+/**
+ * A CSS color in any space, mapped into sRGB the way CSS maps out-of-gamut colors: by reducing
+ * chroma in OKLCH, so a Display P3 red becomes the nearest sRGB red, not a clipped one. A missing
+ * (`none`) component reads as zero. Null when `input` is not a color.
+ */
+export function parseDisplayableColor(input: string): Color | null {
+ const parsed = parse(input)
+ if (!parsed) return null
+ // Mapping through OKLCH shifts colors already in sRGB by float noise, so only map the rest.
+ const rgb = isDisplayableRGB(parsed) ? toRGB(parsed) : toDisplayableRGB(parsed)
+ // culori leaves a `none` channel out, which normalizing reads as zero.
+ return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })
+}
+
export function resolveRGBAForPreview(
color: Color,
options?: ColorPreviewOptions
diff --git a/packages/vue/src/i18n/locales/de/variables.json b/packages/vue/src/i18n/locales/de/variables.json
index 899620cfb..54d76f7a3 100644
--- a/packages/vue/src/i18n/locales/de/variables.json
+++ b/packages/vue/src/i18n/locales/de/variables.json
@@ -95,5 +95,25 @@
"scopeParagraphSpacing": "Absatzabstand",
"scopeParagraphIndent": "Absatzeinzug",
"scopeTextContent": "Textinhalt",
- "scopeFontFamily": "Schriftfamilie"
+ "scopeFontFamily": "Schriftfamilie",
+ "exportDesignTokens": "Als Design-Tokens exportieren",
+ "importDesignTokens": "Design-Tokens importieren",
+ "importTokensDescription": "Wähle, wohin jede Sammlung und jeder Modus geht. Variablen mit demselben Namen werden aktualisiert; nichts wird gelöscht.",
+ "importNewCollection": "Neue Sammlung",
+ "importNewMode": "Neuer Modus",
+ "importSkipTarget": "Nicht importieren",
+ "importAddMissing": "Tokens hinzufügen, die es noch nicht gibt",
+ "importStyles": "Text- und Effektstile anlegen ({count})",
+ "importSummary": "{added} hinzufügen · {updated} aktualisieren · {skipped} übersprungen",
+ "importSkippedTitle": "Übersprungen",
+ "importReasonUnsupportedType": "für seinen Typ gibt es keine Variable und keinen Stil",
+ "importReasonInvalidValue": "sein Wert ist nicht lesbar",
+ "importReasonTypeMismatch": "eine Variable eines anderen Typs hat diesen Namen",
+ "importReasonMissingAlias": "er verweist auf ein Token, das es nicht gibt",
+ "importReasonNotAdded": "keine Variable hat diesen Namen",
+ "importReasonMixedTypes": "seine Modi haben verschiedene Typen",
+ "importInvalidFile": "{file} ist keine Design-Token-Datei",
+ "importMissingFile": "{file}, auf die {from} verweist, wurde nicht ausgewählt",
+ "importNothing": "Diese Dateien enthalten keine Design-Tokens.",
+ "importAction": "Importieren"
}
diff --git a/packages/vue/src/i18n/locales/es/variables.json b/packages/vue/src/i18n/locales/es/variables.json
index 756ad17ce..ee9994766 100644
--- a/packages/vue/src/i18n/locales/es/variables.json
+++ b/packages/vue/src/i18n/locales/es/variables.json
@@ -95,5 +95,25 @@
"scopeParagraphSpacing": "Espaciado entre párrafos",
"scopeParagraphIndent": "Sangría de párrafo",
"scopeTextContent": "Contenido del texto",
- "scopeFontFamily": "Familia tipográfica"
+ "scopeFontFamily": "Familia tipográfica",
+ "exportDesignTokens": "Exportar como design tokens",
+ "importDesignTokens": "Importar design tokens",
+ "importTokensDescription": "Elige adónde va cada colección y cada modo. Las variables con el mismo nombre se actualizan; no se elimina nada.",
+ "importNewCollection": "Nueva colección",
+ "importNewMode": "Nuevo modo",
+ "importSkipTarget": "No importar",
+ "importAddMissing": "Añadir los tokens que aún no existen",
+ "importStyles": "Crear estilos de texto y de efecto ({count})",
+ "importSummary": "{added} por añadir · {updated} por actualizar · {skipped} omitidos",
+ "importSkippedTitle": "Omitidos",
+ "importReasonUnsupportedType": "su tipo no tiene variable ni estilo",
+ "importReasonInvalidValue": "no se puede leer su valor",
+ "importReasonTypeMismatch": "una variable de otro tipo tiene este nombre",
+ "importReasonMissingAlias": "apunta a un token que no existe",
+ "importReasonNotAdded": "ninguna variable tiene este nombre",
+ "importReasonMixedTypes": "sus modos tienen tipos distintos",
+ "importInvalidFile": "{file} no es un archivo de design tokens",
+ "importMissingFile": "No se eligió {file}, al que hace referencia {from}",
+ "importNothing": "Estos archivos no contienen design tokens.",
+ "importAction": "Importar"
}
diff --git a/packages/vue/src/i18n/locales/fr/variables.json b/packages/vue/src/i18n/locales/fr/variables.json
index 60a62570f..44bb753d2 100644
--- a/packages/vue/src/i18n/locales/fr/variables.json
+++ b/packages/vue/src/i18n/locales/fr/variables.json
@@ -95,5 +95,25 @@
"scopeParagraphSpacing": "Espacement des paragraphes",
"scopeParagraphIndent": "Retrait de paragraphe",
"scopeTextContent": "Contenu du texte",
- "scopeFontFamily": "Famille de police"
+ "scopeFontFamily": "Famille de police",
+ "exportDesignTokens": "Exporter en design tokens",
+ "importDesignTokens": "Importer des design tokens",
+ "importTokensDescription": "Choisissez où va chaque collection et chaque mode. Les variables de même nom sont mises à jour ; rien n’est supprimé.",
+ "importNewCollection": "Nouvelle collection",
+ "importNewMode": "Nouveau mode",
+ "importSkipTarget": "Ne pas importer",
+ "importAddMissing": "Ajouter les tokens qui n’existent pas encore",
+ "importStyles": "Créer des styles de texte et d’effet ({count})",
+ "importSummary": "{added} à ajouter · {updated} à mettre à jour · {skipped} ignorés",
+ "importSkippedTitle": "Ignorés",
+ "importReasonUnsupportedType": "son type n’a ni variable ni style",
+ "importReasonInvalidValue": "sa valeur est illisible",
+ "importReasonTypeMismatch": "une variable d’un autre type porte ce nom",
+ "importReasonMissingAlias": "il renvoie à un token absent",
+ "importReasonNotAdded": "aucune variable ne porte ce nom",
+ "importReasonMixedTypes": "ses modes ont des types différents",
+ "importInvalidFile": "{file} n’est pas un fichier de design tokens",
+ "importMissingFile": "{file}, auquel {from} renvoie, n’a pas été choisi",
+ "importNothing": "Ces fichiers ne contiennent aucun design token.",
+ "importAction": "Importer"
}
diff --git a/packages/vue/src/i18n/locales/it/variables.json b/packages/vue/src/i18n/locales/it/variables.json
index 3b89a47e2..6c1ef7a40 100644
--- a/packages/vue/src/i18n/locales/it/variables.json
+++ b/packages/vue/src/i18n/locales/it/variables.json
@@ -95,5 +95,25 @@
"scopeParagraphSpacing": "Spaziatura paragrafi",
"scopeParagraphIndent": "Rientro del paragrafo",
"scopeTextContent": "Contenuto del testo",
- "scopeFontFamily": "Famiglia di caratteri"
+ "scopeFontFamily": "Famiglia di caratteri",
+ "exportDesignTokens": "Esporta come design token",
+ "importDesignTokens": "Importa design token",
+ "importTokensDescription": "Scegli dove va ogni raccolta e ogni modalità. Le variabili con lo stesso nome vengono aggiornate; nulla viene eliminato.",
+ "importNewCollection": "Nuova raccolta",
+ "importNewMode": "Nuova modalità",
+ "importSkipTarget": "Non importare",
+ "importAddMissing": "Aggiungi i token che non esistono ancora",
+ "importStyles": "Crea stili di testo ed effetto ({count})",
+ "importSummary": "{added} da aggiungere · {updated} da aggiornare · {skipped} saltati",
+ "importSkippedTitle": "Saltati",
+ "importReasonUnsupportedType": "il suo tipo non ha variabile né stile",
+ "importReasonInvalidValue": "il suo valore non è leggibile",
+ "importReasonTypeMismatch": "una variabile di un altro tipo ha questo nome",
+ "importReasonMissingAlias": "punta a un token che non c’è",
+ "importReasonNotAdded": "nessuna variabile ha questo nome",
+ "importReasonMixedTypes": "le sue modalità hanno tipi diversi",
+ "importInvalidFile": "{file} non è un file di design token",
+ "importMissingFile": "{file}, a cui rimanda {from}, non è stato scelto",
+ "importNothing": "Questi file non contengono design token.",
+ "importAction": "Importa"
}
diff --git a/packages/vue/src/i18n/locales/ja/variables.json b/packages/vue/src/i18n/locales/ja/variables.json
index 507c2d89d..4107d9d5d 100644
--- a/packages/vue/src/i18n/locales/ja/variables.json
+++ b/packages/vue/src/i18n/locales/ja/variables.json
@@ -95,5 +95,25 @@
"scopeParagraphSpacing": "段落の間隔",
"scopeParagraphIndent": "段落のインデント",
"scopeTextContent": "テキストの内容",
- "scopeFontFamily": "フォントファミリー"
+ "scopeFontFamily": "フォントファミリー",
+ "exportDesignTokens": "デザイントークンとして書き出す",
+ "importDesignTokens": "デザイントークンを読み込む",
+ "importTokensDescription": "各コレクションとモードの読み込み先を選びます。同じ名前の変数は更新され、削除されるものはありません。",
+ "importNewCollection": "新しいコレクション",
+ "importNewMode": "新しいモード",
+ "importSkipTarget": "読み込まない",
+ "importAddMissing": "まだないトークンを追加する",
+ "importStyles": "テキストスタイルとエフェクトスタイルを作成 ({count})",
+ "importSummary": "追加 {added} · 更新 {updated} · スキップ {skipped}",
+ "importSkippedTitle": "スキップ",
+ "importReasonUnsupportedType": "型に対応する変数やスタイルがない",
+ "importReasonInvalidValue": "値を読み取れない",
+ "importReasonTypeMismatch": "別の型の変数が同じ名前を使っている",
+ "importReasonMissingAlias": "存在しないトークンを参照している",
+ "importReasonNotAdded": "同じ名前の変数がない",
+ "importReasonMixedTypes": "モードごとに型が異なる",
+ "importInvalidFile": "{file} はデザイントークンのファイルではありません",
+ "importMissingFile": "{from} が参照する {file} が選ばれていません",
+ "importNothing": "これらのファイルにデザイントークンはありません。",
+ "importAction": "読み込む"
}
diff --git a/packages/vue/src/i18n/locales/pl/variables.json b/packages/vue/src/i18n/locales/pl/variables.json
index fc8e2518d..84a907240 100644
--- a/packages/vue/src/i18n/locales/pl/variables.json
+++ b/packages/vue/src/i18n/locales/pl/variables.json
@@ -95,5 +95,25 @@
"scopeParagraphSpacing": "Odstęp między akapitami",
"scopeParagraphIndent": "Wcięcie akapitu",
"scopeTextContent": "Treść tekstu",
- "scopeFontFamily": "Rodzina czcionek"
+ "scopeFontFamily": "Rodzina czcionek",
+ "exportDesignTokens": "Eksportuj jako tokeny projektowe",
+ "importDesignTokens": "Importuj tokeny projektowe",
+ "importTokensDescription": "Wybierz, dokąd trafi każda kolekcja i każdy tryb. Zmienne o tej samej nazwie zostaną zaktualizowane; nic nie zostanie usunięte.",
+ "importNewCollection": "Nowa kolekcja",
+ "importNewMode": "Nowy tryb",
+ "importSkipTarget": "Nie importuj",
+ "importAddMissing": "Dodaj tokeny, których jeszcze nie ma",
+ "importStyles": "Utwórz style tekstu i efektów ({count})",
+ "importSummary": "do dodania: {added} · do aktualizacji: {updated} · pominięte: {skipped}",
+ "importSkippedTitle": "Pominięte",
+ "importReasonUnsupportedType": "jego typ nie ma zmiennej ani stylu",
+ "importReasonInvalidValue": "nie da się odczytać jego wartości",
+ "importReasonTypeMismatch": "zmienna innego typu ma tę nazwę",
+ "importReasonMissingAlias": "wskazuje token, którego nie ma",
+ "importReasonNotAdded": "żadna zmienna nie ma tej nazwy",
+ "importReasonMixedTypes": "jego tryby mają różne typy",
+ "importInvalidFile": "{file} nie jest plikiem tokenów projektowych",
+ "importMissingFile": "Nie wybrano pliku {file}, do którego odwołuje się {from}",
+ "importNothing": "Te pliki nie zawierają tokenów projektowych.",
+ "importAction": "Importuj"
}
diff --git a/packages/vue/src/i18n/locales/ru/variables.json b/packages/vue/src/i18n/locales/ru/variables.json
index 7f81f8bac..ee0970404 100644
--- a/packages/vue/src/i18n/locales/ru/variables.json
+++ b/packages/vue/src/i18n/locales/ru/variables.json
@@ -95,5 +95,25 @@
"scopeParagraphSpacing": "Интервал между абзацами",
"scopeParagraphIndent": "Отступ абзаца",
"scopeTextContent": "Содержимое текста",
- "scopeFontFamily": "Гарнитура шрифта"
+ "scopeFontFamily": "Гарнитура шрифта",
+ "exportDesignTokens": "Экспортировать как дизайн-токены",
+ "importDesignTokens": "Импортировать дизайн-токены",
+ "importTokensDescription": "Выберите, куда попадёт каждая коллекция и каждый режим. Переменные с тем же именем обновятся; ничего не удаляется.",
+ "importNewCollection": "Новая коллекция",
+ "importNewMode": "Новый режим",
+ "importSkipTarget": "Не импортировать",
+ "importAddMissing": "Добавить токены, которых ещё нет",
+ "importStyles": "Создать стили текста и эффектов ({count})",
+ "importSummary": "добавить: {added} · обновить: {updated} · пропущено: {skipped}",
+ "importSkippedTitle": "Пропущено",
+ "importReasonUnsupportedType": "для его типа нет ни переменной, ни стиля",
+ "importReasonInvalidValue": "его значение не читается",
+ "importReasonTypeMismatch": "переменная другого типа носит это имя",
+ "importReasonMissingAlias": "он ссылается на несуществующий токен",
+ "importReasonNotAdded": "нет переменной с таким именем",
+ "importReasonMixedTypes": "у его режимов разные типы",
+ "importInvalidFile": "{file} — не файл дизайн-токенов",
+ "importMissingFile": "Не выбран {file}, на который ссылается {from}",
+ "importNothing": "В этих файлах нет дизайн-токенов.",
+ "importAction": "Импортировать"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/variables.json b/packages/vue/src/i18n/locales/zh-cn/variables.json
index 87da6273c..0c4819116 100644
--- a/packages/vue/src/i18n/locales/zh-cn/variables.json
+++ b/packages/vue/src/i18n/locales/zh-cn/variables.json
@@ -95,5 +95,25 @@
"scopeParagraphSpacing": "段落间距",
"scopeParagraphIndent": "段落缩进",
"scopeTextContent": "文本内容",
- "scopeFontFamily": "字体"
+ "scopeFontFamily": "字体",
+ "exportDesignTokens": "导出为设计令牌",
+ "importDesignTokens": "导入设计令牌",
+ "importTokensDescription": "选择每个集合和模式导入到哪里。同名变量会被更新,不会删除任何内容。",
+ "importNewCollection": "新集合",
+ "importNewMode": "新模式",
+ "importSkipTarget": "不导入",
+ "importAddMissing": "添加尚不存在的令牌",
+ "importStyles": "创建文字和效果样式({count})",
+ "importSummary": "待添加 {added} · 待更新 {updated} · 已跳过 {skipped}",
+ "importSkippedTitle": "已跳过",
+ "importReasonUnsupportedType": "其类型没有对应的变量或样式",
+ "importReasonInvalidValue": "无法读取其值",
+ "importReasonTypeMismatch": "同名变量的类型不同",
+ "importReasonMissingAlias": "引用的令牌不存在",
+ "importReasonNotAdded": "没有同名变量",
+ "importReasonMixedTypes": "各模式的类型不一致",
+ "importInvalidFile": "{file} 不是设计令牌文件",
+ "importMissingFile": "未选择 {from} 引用的 {file}",
+ "importNothing": "这些文件中没有设计令牌。",
+ "importAction": "导入"
}
diff --git a/packages/vue/src/i18n/messages/variables.ts b/packages/vue/src/i18n/messages/variables.ts
index 566808122..f7b0b28ed 100644
--- a/packages/vue/src/i18n/messages/variables.ts
+++ b/packages/vue/src/i18n/messages/variables.ts
@@ -102,7 +102,28 @@ export const variablesMessageDefaults = {
scopeParagraphSpacing: 'Paragraph spacing',
scopeParagraphIndent: 'Paragraph indent',
scopeTextContent: 'Text content',
- scopeFontFamily: 'Font family'
+ scopeFontFamily: 'Font family',
+ exportDesignTokens: 'Export as design tokens',
+ importDesignTokens: 'Import design tokens',
+ importTokensDescription:
+ 'Choose where each collection and mode goes. Variables with the same name are updated; nothing is deleted.',
+ importNewCollection: 'New collection',
+ importNewMode: 'New mode',
+ importSkipTarget: 'Don’t import',
+ importAddMissing: 'Add tokens that don’t exist yet',
+ importStyles: params('Make text and effect styles ({count})'),
+ importSummary: params('{added} to add · {updated} to update · {skipped} skipped'),
+ importSkippedTitle: 'Skipped',
+ importReasonUnsupportedType: 'its type has no variable or style',
+ importReasonInvalidValue: 'its value can’t be read',
+ importReasonTypeMismatch: 'a variable of another type has this name',
+ importReasonMissingAlias: 'it points at a token that isn’t there',
+ importReasonNotAdded: 'no variable has this name',
+ importReasonMixedTypes: 'its modes have different types',
+ importInvalidFile: params('{file} isn’t a design token file'),
+ importMissingFile: params('{file}, which {from} refers to, wasn’t picked'),
+ importNothing: 'These files hold no design tokens.',
+ importAction: 'Import'
} as const
export const variablesMessages = i18n('variables', variablesMessageDefaults)
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index 3498d991a..7e2f71385 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -54,7 +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
+- `tokens` — variables as a CSS custom-property stylesheet, a Tailwind v4 theme, or W3C design token files (`--format dtcg --out <folder>`)
- `export` — export PNG/JPG/WEBP/SVG/PDF/JSX/.fig
- `convert` — convert between supported document formats
- `analyze` — colors, typography, spacing, repeated clusters
@@ -79,6 +79,7 @@ openpencil selection --json
openpencil variables design.fig
openpencil variables --collection "Colors" --type COLOR
openpencil tokens design.fig --format tailwind > theme.css
+openpencil tokens design.fig --format dtcg --out tokens # W3C design tokens; import_design_tokens reads them back
```
### Search and XPath query
diff --git a/src/app/editor/tokens/design-tokens.ts b/src/app/editor/tokens/design-tokens.ts
new file mode 100644
index 000000000..e4851faa0
--- /dev/null
+++ b/src/app/editor/tokens/design-tokens.ts
@@ -0,0 +1,70 @@
+import { uniq } from 'es-toolkit/array'
+import { strFromU8, strToU8, unzipSync, zipSync, type Zippable } from 'fflate'
+
+import type {
+ DesignTokenIssue,
+ DesignTokenSourceFile
+} from '@open-pencil/core/io/formats/design-tokens'
+
+import { saveExportedFile } from '@/app/document/export/files'
+import { downloadBlob } from '@/app/document/io/browser'
+import type { EditorStore } from '@/app/editor/active-store'
+import { notificationMessages } from '@/app/i18n/notifications'
+import { toast } from '@/app/shell/ui'
+
+/** Files a token import reads: JSON token files, or archives of them. */
+export const DESIGN_TOKEN_FILE_ACCEPT = '.json,.tokens,.zip'
+
+function isTokenFile(path: string): boolean {
+ return /\.(json|tokens)$/i.test(path) && !path.split('/').some((part) => part.startsWith('.'))
+}
+
+function issueName(issue: DesignTokenIssue): string {
+ return issue.kind === 'unsupported-effect' ? issue.style : issue.token
+}
+
+/**
+ * Saves the document's variables and styles as W3C design tokens: a zip of one file per
+ * collection mode, the styles, and the resolver that combines them.
+ */
+export async function exportDesignTokenArchive(store: EditorStore): Promise<void> {
+ const { exportDesignTokens } = await import('@open-pencil/core/io/formats/design-tokens')
+ const { files, issues } = exportDesignTokens(store.graph)
+ const entries: Zippable = {}
+ for (const file of files)
+ entries[file.path] = strToU8(`${JSON.stringify(file.content, null, 2)}\n`)
+ await saveExportedFile(
+ zipSync(entries),
+ `${store.state.documentName || 'Design'} tokens.zip`,
+ 'Design tokens',
+ '.zip',
+ 'application/zip',
+ downloadBlob
+ )
+ if (issues.length === 0) return
+ const names = uniq(issues.map(issueName)).join(', ')
+ toast.warning(notificationMessages.get().designTokensLeftOut({ names }))
+}
+
+/**
+ * Picked files as token sources: JSON as it is, archives unpacked. A folder's files keep their
+ * paths inside it, which is how a resolver's `$ref`s and per-folder collections find them.
+ */
+export async function readDesignTokenFiles(
+ files: readonly File[]
+): Promise<DesignTokenSourceFile[]> {
+ const sources: DesignTokenSourceFile[] = []
+ for (const file of files) {
+ const path = file.webkitRelativePath || file.name
+ if (/\.zip$/i.test(file.name)) {
+ const archive = unzipSync(new Uint8Array(await file.arrayBuffer()), {
+ filter: (entry) => isTokenFile(entry.name)
+ })
+ for (const [name, bytes] of Object.entries(archive))
+ sources.push({ path: name, text: strFromU8(bytes) })
+ } else if (isTokenFile(path)) {
+ sources.push({ path, text: await file.text() })
+ }
+ }
+ return sources
+}
diff --git a/src/app/i18n/notifications/index.ts b/src/app/i18n/notifications/index.ts
index 4ad411fda..4e1eef887 100644
--- a/src/app/i18n/notifications/index.ts
+++ b/src/app/i18n/notifications/index.ts
@@ -11,6 +11,8 @@ export const notificationMessageDefaults = {
clipboardAccessBlocked: 'Clipboard access is blocked in this browser context.',
copiedAs: params('Copied as {format}.'),
tokensLeftOut: params('Left out of the stylesheet: {names}.'),
+ designTokensLeftOut: params('Left out of the design tokens: {names}.'),
+ designTokensImported: params('Imported {count} design tokens.'),
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 a7db823e5..1aea28d8a 100644
--- a/src/app/i18n/notifications/locales/de.json
+++ b/src/app/i18n/notifications/locales/de.json
@@ -27,5 +27,7 @@
"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}",
- "tokensLeftOut": "Nicht im Stylesheet enthalten: {names}."
+ "tokensLeftOut": "Nicht im Stylesheet enthalten: {names}.",
+ "designTokensLeftOut": "Nicht in den Design-Tokens enthalten: {names}.",
+ "designTokensImported": "{count} Design-Tokens importiert."
}
diff --git a/src/app/i18n/notifications/locales/es.json b/src/app/i18n/notifications/locales/es.json
index be7182f03..4e7a38316 100644
--- a/src/app/i18n/notifications/locales/es.json
+++ b/src/app/i18n/notifications/locales/es.json
@@ -27,5 +27,7 @@
"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}",
- "tokensLeftOut": "No incluido en la hoja de estilos: {names}."
+ "tokensLeftOut": "No incluido en la hoja de estilos: {names}.",
+ "designTokensLeftOut": "No incluidos en los design tokens: {names}.",
+ "designTokensImported": "Se importaron {count} design tokens."
}
diff --git a/src/app/i18n/notifications/locales/fr.json b/src/app/i18n/notifications/locales/fr.json
index 397b8bb87..e9aae8966 100644
--- a/src/app/i18n/notifications/locales/fr.json
+++ b/src/app/i18n/notifications/locales/fr.json
@@ -27,5 +27,7 @@
"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}",
- "tokensLeftOut": "Non inclus dans la feuille de style : {names}."
+ "tokensLeftOut": "Non inclus dans la feuille de style : {names}.",
+ "designTokensLeftOut": "Exclus des design tokens : {names}.",
+ "designTokensImported": "{count} design tokens importés."
}
diff --git a/src/app/i18n/notifications/locales/it.json b/src/app/i18n/notifications/locales/it.json
index 1a467072c..3e456b9bb 100644
--- a/src/app/i18n/notifications/locales/it.json
+++ b/src/app/i18n/notifications/locales/it.json
@@ -27,5 +27,7 @@
"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}",
- "tokensLeftOut": "Esclusi dal foglio di stile: {names}."
+ "tokensLeftOut": "Esclusi dal foglio di stile: {names}.",
+ "designTokensLeftOut": "Esclusi dai design token: {names}.",
+ "designTokensImported": "Importati {count} design token."
}
diff --git a/src/app/i18n/notifications/locales/ja.json b/src/app/i18n/notifications/locales/ja.json
index e9c64e195..a03e68c31 100644
--- a/src/app/i18n/notifications/locales/ja.json
+++ b/src/app/i18n/notifications/locales/ja.json
@@ -27,5 +27,7 @@
"deepLinkCancelled": "リンクをキャンセルしました。「{file}」で終わるファイルが必要です。",
"deepLinkNodeNotFound": "「{file}」にレイヤー「{node}」が見つかりませんでした。",
"openQueuedFilesFailed": "OpenPencil に渡されたファイルを開けませんでした: {error}",
- "tokensLeftOut": "スタイルシートに含まれていません: {names}"
+ "tokensLeftOut": "スタイルシートに含まれていません: {names}",
+ "designTokensLeftOut": "デザイントークンに含まれていません: {names}",
+ "designTokensImported": "{count} 個のデザイントークンを読み込みました。"
}
diff --git a/src/app/i18n/notifications/locales/pl.json b/src/app/i18n/notifications/locales/pl.json
index 80837d0eb..704619a2a 100644
--- a/src/app/i18n/notifications/locales/pl.json
+++ b/src/app/i18n/notifications/locales/pl.json
@@ -27,5 +27,7 @@
"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}",
- "tokensLeftOut": "Pominięte w arkuszu stylów: {names}."
+ "tokensLeftOut": "Pominięte w arkuszu stylów: {names}.",
+ "designTokensLeftOut": "Pominięte w tokenach projektowych: {names}.",
+ "designTokensImported": "Zaimportowano tokeny projektowe: {count}."
}
diff --git a/src/app/i18n/notifications/locales/ru.json b/src/app/i18n/notifications/locales/ru.json
index e7c53e96a..41864b6a8 100644
--- a/src/app/i18n/notifications/locales/ru.json
+++ b/src/app/i18n/notifications/locales/ru.json
@@ -27,5 +27,7 @@
"deepLinkCancelled": "Ссылка отменена: ожидался файл с окончанием «{file}».",
"deepLinkNodeNotFound": "Слой «{node}» не найден в «{file}».",
"openQueuedFilesFailed": "Не удалось открыть файлы, переданные OpenPencil: {error}",
- "tokensLeftOut": "Не вошли в таблицу стилей: {names}."
+ "tokensLeftOut": "Не вошли в таблицу стилей: {names}.",
+ "designTokensLeftOut": "Не вошли в дизайн-токены: {names}.",
+ "designTokensImported": "Импортировано дизайн-токенов: {count}."
}
diff --git a/src/app/i18n/notifications/locales/zh-cn.json b/src/app/i18n/notifications/locales/zh-cn.json
index c20fc47db..992ecfe5b 100644
--- a/src/app/i18n/notifications/locales/zh-cn.json
+++ b/src/app/i18n/notifications/locales/zh-cn.json
@@ -27,5 +27,7 @@
"deepLinkCancelled": "已取消链接:需要以“{file}”结尾的文件。",
"deepLinkNodeNotFound": "在“{file}”中未找到图层“{node}”。",
"openQueuedFilesFailed": "无法打开传递给 OpenPencil 的文件:{error}",
- "tokensLeftOut": "未写入样式表:{names}"
+ "tokensLeftOut": "未写入样式表:{names}",
+ "designTokensLeftOut": "未写入设计令牌:{names}",
+ "designTokensImported": "已导入 {count} 个设计令牌。"
}
diff --git a/src/components/variables/TokenImportDialog.vue b/src/components/variables/TokenImportDialog.vue
new file mode 100644
index 000000000..a8add084d
--- /dev/null
+++ b/src/components/variables/TokenImportDialog.vue
@@ -0,0 +1,293 @@
+<script setup lang="ts">
+import { computed, ref, watch } from 'vue'
+
+import type { TokenImportResult } from '@open-pencil/core/editor'
+import {
+ defaultTokenImportOptions,
+ planTokenImport,
+ type CollectionTarget,
+ type DesignTokenBundle,
+ type DesignTokenReadIssue,
+ type ImportSkipReason,
+ type ModeTarget,
+ type TokenImportOptions
+} from '@open-pencil/core/io/formats/design-tokens'
+import { useI18n } from '@open-pencil/vue'
+
+import { useEditorStore } from '@/app/editor/active-store'
+import { notificationMessages } from '@/app/i18n/notifications'
+import { toast } from '@/app/shell/ui'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'
+import { AppDialog } from '@/components/ui/dialog'
+import AppAlert from '@/components/ui/feedback/AppAlert.vue'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
+import AppCheckbox from '@/components/ui/toggle/AppCheckbox.vue'
+
+const { bundle } = defineProps<{ bundle: DesignTokenBundle | null }>()
+const emit = defineEmits<{ imported: [result: TokenImportResult] }>()
+const open = defineModel<boolean>('open', { default: false })
+
+const store = useEditorStore()
+const { variables, common } = useI18n()
+
+const options = ref<TokenImportOptions | null>(null)
+watch(
+ () => bundle,
+ (current) => {
+ options.value = current ? defaultTokenImportOptions(store.graph, current) : null
+ },
+ { immediate: true }
+)
+
+/** Whether a choice names a collection or mode the document no longer has, as after an undo. */
+function isStale(choices: TokenImportOptions): boolean {
+ return choices.collections.some(({ target, modes }) => {
+ if (target.kind !== 'existing') return false
+ const collection = store.graph.variableCollections.get(target.collectionId)
+ if (!collection) return true
+ return modes.some(
+ (mode) =>
+ mode.kind === 'existing' &&
+ !collection.modes.some((candidate) => candidate.modeId === mode.modeId)
+ )
+ })
+}
+
+// The plan reads the document, so it follows every change to it, and choices that went stale
+// start over from the defaults.
+watch(
+ () => store.state.sceneVersion,
+ () => {
+ if (bundle && options.value && isStale(options.value))
+ options.value = defaultTokenImportOptions(store.graph, bundle)
+ }
+)
+
+function currentPlan() {
+ return bundle && options.value ? planTokenImport(store.graph, bundle, options.value) : null
+}
+
+const plan = computed(() => {
+ void store.state.sceneVersion
+ return currentPlan()
+})
+const existingCollections = computed(() => {
+ void store.state.sceneVersion
+ return [...store.graph.variableCollections.values()]
+})
+const styleCount = computed(
+ () =>
+ bundle?.composites.filter((token) => token.type === 'typography' || token.type === 'shadow')
+ .length ?? 0
+)
+
+/** Select values: `new`, `skip`, or `existing:<id>`. */
+function targetValue(target: CollectionTarget | ModeTarget): string {
+ if (target.kind === 'existing')
+ return `existing:${'collectionId' in target ? target.collectionId : target.modeId}`
+ return target.kind
+}
+
+function collectionOptions() {
+ return [
+ { value: 'new', label: variables.value.importNewCollection },
+ ...existingCollections.value.map((collection) => ({
+ value: `existing:${collection.id}`,
+ label: collection.name
+ })),
+ { value: 'skip', label: variables.value.importSkipTarget }
+ ]
+}
+
+function modeOptions(index: number) {
+ const target = options.value?.collections[index]?.target
+ const existing =
+ target?.kind === 'existing'
+ ? store.graph.variableCollections.get(target.collectionId)
+ : undefined
+ return [
+ { value: 'new', label: variables.value.importNewMode },
+ ...(existing?.modes ?? []).map((mode) => ({
+ value: `existing:${mode.modeId}`,
+ label: mode.name
+ })),
+ { value: 'skip', label: variables.value.importSkipTarget }
+ ]
+}
+
+/** Picking a collection matches its modes by name again, as the default choices do. */
+function setCollection(index: number, value: string) {
+ const choice = options.value?.collections[index]
+ const source = bundle?.collections[index]
+ if (!choice || !source) return
+ if (value === 'skip' || value === 'new') {
+ choice.target = value === 'skip' ? { kind: 'skip' } : { kind: 'new', name: source.name }
+ choice.modes = source.modes.map((mode) => ({ kind: 'new', name: mode.name }))
+ return
+ }
+ const collectionId = value.slice('existing:'.length)
+ const existing = store.graph.variableCollections.get(collectionId)
+ choice.target = { kind: 'existing', collectionId }
+ choice.modes = source.modes.map((mode): ModeTarget => {
+ const match = existing?.modes.find((candidate) => candidate.name === mode.name)
+ return match ? { kind: 'existing', modeId: match.modeId } : { kind: 'new', name: mode.name }
+ })
+}
+
+function setMode(index: number, modeIndex: number, value: string) {
+ const choice = options.value?.collections[index]
+ const name = bundle?.collections[index]?.modes[modeIndex]?.name ?? ''
+ if (!choice) return
+ if (value === 'skip') choice.modes[modeIndex] = { kind: 'skip' }
+ else if (value === 'new') choice.modes[modeIndex] = { kind: 'new', name }
+ else choice.modes[modeIndex] = { kind: 'existing', modeId: value.slice('existing:'.length) }
+}
+
+const REASONS: Record<ImportSkipReason, () => string> = {
+ 'unsupported-type': () => variables.value.importReasonUnsupportedType,
+ 'invalid-value': () => variables.value.importReasonInvalidValue,
+ 'type-mismatch': () => variables.value.importReasonTypeMismatch,
+ 'missing-alias': () => variables.value.importReasonMissingAlias,
+ 'not-added': () => variables.value.importReasonNotAdded,
+ 'mixed-types': () => variables.value.importReasonMixedTypes
+}
+
+function issueText(issue: DesignTokenReadIssue): string {
+ return issue.kind === 'invalid-file'
+ ? variables.value.importInvalidFile({ file: issue.file })
+ : variables.value.importMissingFile({ file: issue.file, from: issue.from })
+}
+
+const changes = computed(() =>
+ plan.value ? plan.value.counts.added + plan.value.counts.updated : 0
+)
+const empty = computed(
+ () => !bundle || (bundle.collections.length === 0 && bundle.composites.length === 0)
+)
+
+function importTokens() {
+ // Planned again against the document as it is now, not as it was when the plan was shown.
+ const fresh = currentPlan()
+ if (!fresh) return
+ const count = fresh.counts.added + fresh.counts.updated
+ if (count === 0) return
+ const result = store.importDesignTokens(fresh)
+ toast.info(notificationMessages.get().designTokensImported({ count }))
+ open.value = false
+ emit('imported', result)
+}
+</script>
+
+<template>
+ <AppDialog
+ v-model:open="open"
+ size="md"
+ :heading="variables.importDesignTokens"
+ :description="variables.importTokensDescription"
+ :close-label="common.close"
+ :ui="{ footer: 'justify-between' }"
+ data-test-id="variables-import-dialog"
+ >
+ <div class="flex flex-col gap-3 text-xs">
+ <p v-if="empty" class="text-muted">{{ variables.importNothing }}</p>
+
+ <AppAlert
+ v-for="issue in bundle?.issues ?? []"
+ :key="`${issue.kind}:${issue.file}`"
+ tone="warning"
+ :heading="issueText(issue)"
+ />
+
+ <div
+ v-if="options && bundle?.collections.length"
+ class="max-h-72 overflow-y-auto rounded-lg border border-border"
+ >
+ <section
+ v-for="(collection, index) in bundle.collections"
+ :key="`${index}:${collection.name}`"
+ class="border-b border-border py-1 last:border-b-0"
+ data-test-id="variables-import-collection"
+ >
+ <div class="grid grid-cols-[minmax(0,1fr)_auto_10rem] items-center gap-2 px-3 py-1">
+ <span class="truncate font-medium text-surface">{{ collection.name }}</span>
+ <icon-lucide-arrow-right class="size-3 text-muted" aria-hidden="true" />
+ <AppSelect
+ :model-value="targetValue(options.collections[index].target)"
+ :options="collectionOptions()"
+ :label="collection.name"
+ @update:model-value="setCollection(index, $event)"
+ />
+ </div>
+ <template v-if="options.collections[index].target.kind !== 'skip'">
+ <div
+ v-for="(mode, modeIndex) in collection.modes"
+ :key="`${modeIndex}:${mode.name}`"
+ class="grid grid-cols-[minmax(0,1fr)_auto_10rem] items-center gap-2 py-1 pr-3 pl-6"
+ >
+ <span class="truncate text-muted">{{ mode.name }}</span>
+ <icon-lucide-arrow-right class="size-3 text-muted" aria-hidden="true" />
+ <AppSelect
+ :model-value="targetValue(options.collections[index].modes[modeIndex])"
+ :options="modeOptions(index)"
+ :label="`${collection.name}: ${mode.name}`"
+ @update:model-value="setMode(index, modeIndex, $event)"
+ />
+ </div>
+ </template>
+ </section>
+ </div>
+
+ <div v-if="options && !empty" class="flex flex-col gap-2">
+ <label class="flex items-center gap-2">
+ <AppCheckbox v-model="options.addMissing" :ariaLabel="variables.importAddMissing" />
+ {{ variables.importAddMissing }}
+ </label>
+ <label v-if="styleCount > 0" class="flex items-center gap-2">
+ <AppCheckbox
+ v-model="options.styles"
+ :ariaLabel="variables.importStyles({ count: styleCount })"
+ />
+ {{ variables.importStyles({ count: styleCount }) }}
+ </label>
+ </div>
+
+ <AppCollapsible v-if="plan?.skipped.length">
+ <template #label>
+ {{ variables.importSkippedTitle }}
+ <span class="text-muted">{{ plan.skipped.length }}</span>
+ </template>
+ <ul class="mt-2 max-h-32 overflow-y-auto rounded-lg border border-border">
+ <li
+ v-for="(skip, index) in plan.skipped"
+ :key="`${index}:${skip.name}`"
+ class="flex items-baseline justify-between gap-3 border-b border-border px-3 py-1.5 last:border-b-0"
+ >
+ <span class="truncate text-surface">{{ skip.name }}</span>
+ <span class="shrink-0 text-muted">{{ REASONS[skip.reason]() }}</span>
+ </li>
+ </ul>
+ </AppCollapsible>
+ </div>
+
+ <template #footer>
+ <span class="text-xs text-muted" data-test-id="variables-import-summary">
+ {{ plan && !empty ? variables.importSummary(plan.counts) : '' }}
+ </span>
+ <div class="flex gap-2">
+ <AppButton color="neutral" variant="ghost" @click="open = false">
+ {{ common.cancel }}
+ </AppButton>
+ <AppButton
+ color="primary"
+ variant="solid"
+ :disabled="changes === 0"
+ data-test-id="variables-import-confirm"
+ @click="importTokens"
+ >
+ {{ variables.importAction }}
+ </AppButton>
+ </div>
+ </template>
+ </AppDialog>
+</template>
diff --git a/src/components/variables/TokenOutput.vue b/src/components/variables/TokenOutput.vue
index 2d799296a..3aef28f94 100644
--- a/src/components/variables/TokenOutput.vue
+++ b/src/components/variables/TokenOutput.vue
@@ -5,6 +5,7 @@ import {
DropdownMenuItem,
DropdownMenuPortal,
DropdownMenuRoot,
+ DropdownMenuSeparator,
DropdownMenuTrigger
} from 'reka-ui'
import { tv } from 'tailwind-variants'
@@ -23,7 +24,7 @@ const { collectionId, layout = 'side' } = defineProps<{
/** `full` fills the panel behind a back button on narrow screens. */
layout?: 'side' | 'full'
}>()
-const emit = defineEmits<{ copy: [format: TokenStylesheetFormat] }>()
+const emit = defineEmits<{ copy: [format: TokenStylesheetFormat]; export: [] }>()
const { variables } = useI18n()
const ui = computed(() => tv(tokensPanelTheme)({ layout }))
@@ -79,6 +80,15 @@ const stylesheet = computedAsync(async () => {
<icon-lucide-wind :class="menu.icon" />
{{ variables.copyAsTailwindTheme }}
</DropdownMenuItem>
+ <DropdownMenuSeparator :class="menu.separator" />
+ <DropdownMenuItem
+ :class="menu.item"
+ data-test-id="variables-export-tokens"
+ @select="emit('export')"
+ >
+ <icon-lucide-file-archive :class="menu.icon" />
+ {{ variables.exportDesignTokens }}
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenuPortal>
</DropdownMenuRoot>
diff --git a/src/components/variables/TokensPanel.vue b/src/components/variables/TokensPanel.vue
index 0a5b25bae..2c02ef5be 100644
--- a/src/components/variables/TokensPanel.vue
+++ b/src/components/variables/TokensPanel.vue
@@ -40,7 +40,7 @@ import tokensPanelTheme, {
TOKENS_PANEL_SIDEBAR_WIDTH
} from '@/theme/tokens-panel'
-const emit = defineEmits<{ copy: [format: TokenStylesheetFormat] }>()
+const emit = defineEmits<{ copy: [format: TokenStylesheetFormat]; export: [] }>()
const { variables: messages, common } = useI18n()
const ui = tv(tokensPanelTheme)()
@@ -375,6 +375,7 @@ const groupOptions = computed(() => groupEntries.value.map((entry) => entry.path
:collection-id="collection.id"
layout="full"
@copy="emit('copy', $event)"
+ @export="emit('export')"
/>
</template>
@@ -511,7 +512,11 @@ const groupOptions = computed(() => groupEntries.value.map((entry) => entry.path
/>
</Transition>
</div>
- <TokenOutput :collection-id="collection.id" @copy="emit('copy', $event)" />
+ <TokenOutput
+ :collection-id="collection.id"
+ @copy="emit('copy', $event)"
+ @export="emit('export')"
+ />
</template>
</div>
</template>
diff --git a/src/components/variables/VariablesDialog.vue b/src/components/variables/VariablesDialog.vue
index c8b4a0899..9ef62ece2 100644
--- a/src/components/variables/VariablesDialog.vue
+++ b/src/components/variables/VariablesDialog.vue
@@ -1,12 +1,21 @@
<script setup lang="ts">
+import { useFileDialog } from '@vueuse/core'
import { DialogTitle } from 'reka-ui'
-import { computed, ref } from 'vue'
+import { computed, defineAsyncComponent, ref, shallowRef } from 'vue'
+import type { DesignTokenBundle } from '@open-pencil/core/io/formats/design-tokens'
import { useI18n } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { createTokenCopy } from '@/app/editor/tokens/copy'
+import {
+ DESIGN_TOKEN_FILE_ACCEPT,
+ exportDesignTokenArchive,
+ readDesignTokenFiles
+} from '@/app/editor/tokens/design-tokens'
+import { notificationMessages } from '@/app/i18n/notifications'
import { useDocumentShortcuts } from '@/app/shell/keyboard/document'
+import { toast } from '@/app/shell/ui'
import IconButton from '@/components/ui/button/IconButton.vue'
import { AppDialogClose, AppDialogRoot } from '@/components/ui/dialog'
import TokensPanel from '@/components/variables/TokensPanel.vue'
@@ -26,6 +35,37 @@ 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)
+
+const TokenImportDialog = defineAsyncComponent(
+ () => import('@/components/variables/TokenImportDialog.vue')
+)
+const importBundle = shallowRef<DesignTokenBundle | null>(null)
+const importOpen = ref(false)
+
+function reportFailure(error: unknown) {
+ toast.error(
+ notificationMessages
+ .get()
+ .operationFailed({ error: error instanceof Error ? error.message : String(error) })
+ )
+}
+
+/** Token files, a folder's worth, or a zip of them; the import dialog shows what they would do. */
+const tokenFiles = useFileDialog({ accept: DESIGN_TOKEN_FILE_ACCEPT, multiple: true, reset: true })
+tokenFiles.onChange((files) => {
+ if (!files?.length) return
+ const picked = [...files]
+ void (async () => {
+ const sources = await readDesignTokenFiles(picked)
+ const { readDesignTokens } = await import('@open-pencil/core/io/formats/design-tokens')
+ importBundle.value = readDesignTokens(sources)
+ importOpen.value = true
+ })().catch(reportFailure)
+})
+
+function exportTokens() {
+ exportDesignTokenArchive(store).catch(reportFailure)
+}
</script>
<template>
@@ -38,8 +78,15 @@ const copyTokens = createTokenCopy(store)
:aria-describedby="undefined"
>
<DialogTitle class="sr-only">{{ variables.localVariables }}</DialogTitle>
- <TokensPanel @copy="copyTokens">
+ <TokensPanel @copy="copyTokens" @export="exportTokens">
<template #actions>
+ <IconButton
+ :label="variables.importDesignTokens"
+ data-test-id="variables-import-tokens"
+ @click="tokenFiles.open()"
+ >
+ <icon-lucide-file-input class="size-3.5" />
+ </IconButton>
<IconButton
:label="expanded ? variables.collapse : variables.expand"
data-test-id="variables-expand"
@@ -51,5 +98,6 @@ const copyTokens = createTokenCopy(store)
<AppDialogClose :ariaLabel="common.close" />
</template>
</TokensPanel>
+ <TokenImportDialog v-if="importBundle" v-model:open="importOpen" :bundle="importBundle" />
</AppDialogRoot>
</template>
diff --git a/tests/e2e/variables/import.spec.ts b/tests/e2e/variables/import.spec.ts
new file mode 100644
index 000000000..deb500947
--- /dev/null
+++ b/tests/e2e/variables/import.spec.ts
@@ -0,0 +1,58 @@
+import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetup()
+
+const theme = (background: string) =>
+ JSON.stringify({
+ color: {
+ $type: 'color',
+ background: { $value: background },
+ surface: { $value: '{color.background}' }
+ },
+ space: { md: { $type: 'dimension', $value: { value: 1, unit: 'rem' } } }
+ })
+
+test('design token files import as a collection with a mode per file', async () => {
+ await editor.page
+ .getByRole('region', { name: 'Variables' })
+ .getByRole('button', { name: 'Open variables' })
+ .click()
+ const dialog = editor.page.getByTestId('variables-dialog')
+ await expect(dialog).toBeVisible()
+
+ const chooser = editor.page.waitForEvent('filechooser')
+ await dialog.getByTestId('variables-import-tokens').click()
+ await (
+ await chooser
+ ).setFiles([
+ {
+ name: 'Light.tokens.json',
+ mimeType: 'application/json',
+ buffer: Buffer.from(theme('#ffffff'))
+ },
+ {
+ name: 'Dark.tokens.json',
+ mimeType: 'application/json',
+ buffer: Buffer.from(theme('#09090b'))
+ }
+ ])
+
+ const importDialog = editor.page.getByTestId('variables-import-dialog')
+ await expect(importDialog.getByTestId('variables-import-summary')).toHaveText(
+ '3 to add · 0 to update · 0 skipped'
+ )
+ await importDialog.getByTestId('variables-import-confirm').click()
+ await expect(importDialog).toBeHidden()
+
+ await expect(dialog.getByTestId('variable-row')).toHaveCount(3)
+ const stylesheet = dialog.getByTestId('token-output')
+ await expect(stylesheet).toContainText('--spacing-md: 1rem')
+ // Each file is a mode: the second one's value goes under its condition.
+ await expect(stylesheet).toContainText(/="dark"\][^}]*--color-background: #09090b/i)
+
+ // The whole import is one step on the document's history.
+ await dialog.getByTestId('variable-row').first().click()
+ await editor.page.keyboard.press('ControlOrMeta+KeyZ')
+ await expect(dialog.getByTestId('variable-row')).toHaveCount(0)
+ editor.canvas.assertNoErrors()
+})