Skip to content

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

fix: keep instance names, variable bindings, and variable edits in Figma (#1131)

Danila Poyarkov83fca9ee9821
diff --git a/changes/1131/fixed.md b/changes/1131/fixed.md
new file mode 100644
index 000000000..b14892303
--- /dev/null
+++ b/changes/1131/fixed.md
@@ -0,0 +1,6 @@
+- Fill and stroke bindings to variables made in OpenPencil survive a paste into Figma, which keeps them as remote variables as it does for variables copied from another Figma file.
+- Instances pasted into Figma keep their names and no longer carry their component's library identity.
+- Saving an opened `.fig` file writes a variable's new value into every layer that uses it, through an alias too, so Figma shows the edit. Before, layers bound through an alias, or any layer read from the file, kept the color Figma had saved.
+- The Variables panel marks collections copied from a library. Edits to them are saved and show in Figma, but Figma doesn't show variables or modes added to them; the panel warns on such a variable.
+- CLI `eval` and the CLI tools measure text in the document they edit, so text with line breaks or a fixed width gets its real height.
+- The Variables dialog keeps variable names in view in a collection with more modes than fit, such as Tokens in Preline UI files, and scrolls sideways instead. Before, the name column shrank to nothing and its header ran into the first mode's.
diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.ts
index da56b20e6..771e460c3 100644
--- a/packages/cli/src/commands/eval.ts
+++ b/packages/cli/src/commands/eval.ts
@@ -9,6 +9,7 @@ import { printError } from '#cli/format'
import {
documentWriteOptions,
loadDocument,
+ measureTextHeadlessly,
populateWholeDocument,
writeFigDocument
} from '#cli/headless'
@@ -70,6 +71,7 @@ export default defineCommand({
const file = requireFile(args.file)
const graph = await loadDocument(file)
populateWholeDocument(graph)
+ await measureTextHeadlessly()
const figma = new FigmaAPI(graph)
let result: unknown
diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.ts
index 42d6d8924..25b6d5df1 100644
--- a/packages/cli/src/headless.ts
+++ b/packages/cli/src/headless.ts
@@ -1,9 +1,10 @@
import { readFile, writeFile } from 'node:fs/promises'
+import { SkiaRenderer } from '@open-pencil/core/canvas'
import { BUILTIN_IO_FORMATS, IORegistry, initCanvasKit } from '@open-pencil/core/io'
import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formats/fig'
import { headlessHTMLReader } from '@open-pencil/core/io/formats/html/import'
-import { computeAllLayouts } from '@open-pencil/core/layout'
+import { computeAllLayouts, installTextMeasurer } from '@open-pencil/core/layout'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { printError } from '#cli/format'
@@ -22,6 +23,28 @@ export async function loadDocument(filePath: string): Promise<SceneGraph> {
return graph
}
+let textMeasurer: Promise<void> | null = null
+
+/**
+ * Measure text a script or tool lays out with CanvasKit and the fonts it loads, as the app
+ * does, instead of the estimate that knows neither line breaks nor wrapping. The document as
+ * loaded keeps the layout its file gives it; only edits made afterwards are measured.
+ */
+export function measureTextHeadlessly(): Promise<void> {
+ textMeasurer ??= (async () => {
+ const ck = await initCanvasKit()
+ const surface = ck.MakeSurface(1, 1)
+ if (!surface) throw new Error('CanvasKit could not make a surface to measure text')
+ const renderer = new SkiaRenderer(ck, surface)
+ await renderer.loadFonts()
+ installTextMeasurer((node, maxWidth) => renderer.measureTextNode(node, maxWidth))
+ })().catch((error: unknown) => {
+ textMeasurer = null
+ throw error
+ })
+ return textMeasurer
+}
+
/** `--write` and `--output` for commands that change a headless document. */
export const documentWriteOptions = {
write: { type: 'boolean', alias: 'w', description: 'Write changes back to the input file' },
diff --git a/packages/cli/src/tool-data.ts b/packages/cli/src/tool-data.ts
index 145bb6ea9..b11966a78 100644
--- a/packages/cli/src/tool-data.ts
+++ b/packages/cli/src/tool-data.ts
@@ -9,7 +9,7 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { isAppMode, requireFile, rpc } from '#cli/app/client'
import { appTargetRPCArgs, type AppTargetCLIArgs } from '#cli/app/target'
-import { loadDocument, populateWholeDocument } from '#cli/headless'
+import { loadDocument, measureTextHeadlessly, populateWholeDocument } from '#cli/headless'
/** A Figma API over a headless document, with CanvasKit raster export and pixel decoding. */
export async function createHeadlessFigma(graph: SceneGraph): Promise<FigmaAPI> {
@@ -38,6 +38,7 @@ export async function runToolData(
if (!tool) throw new Error(`Unknown tool: ${name}`)
const graph = await loadDocument(requireFile(file))
populateWholeDocument(graph)
+ await measureTextHeadlessly()
const figma = await createHeadlessFigma(graph)
return { result: await tool.execute(figma, args), graph }
}
diff --git a/packages/cli/tests/commands/eval.test.ts b/packages/cli/tests/commands/eval.test.ts
index 1ef4ecb41..c255f63b0 100644
--- a/packages/cli/tests/commands/eval.test.ts
+++ b/packages/cli/tests/commands/eval.test.ts
@@ -22,6 +22,36 @@ async function cli(args: string[], stdin?: string) {
}
describe('eval CLI', () => {
+ test('measures the text a script writes, its line breaks and wrapping included', async () => {
+ const script = `
+ await figma.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ const line = figma.createText()
+ line.characters = 'one'
+ const lines = figma.createText()
+ lines.characters = 'one\\ntwo\\nthree'
+ const paragraph = figma.createText()
+ paragraph.characters = 'A paragraph that wraps over several lines'
+ paragraph.resize(80, 20)
+ paragraph.textAutoResize = 'HEIGHT'
+ return { line: line.height, lines: lines.height, paragraph: paragraph.height }
+ `
+ const result = await cli(
+ ['eval', join(FIXTURES, 'circle-text.fig'), '--stdin', '--json'],
+ script
+ )
+ expect(result.exitCode).toBe(0)
+ const heights = v.parse(
+ v.pipe(
+ v.string(),
+ v.parseJson(),
+ v.object({ line: v.number(), lines: v.number(), paragraph: v.number() })
+ ),
+ result.stdout
+ )
+ expect(heights.lines).toBeGreaterThan(heights.line * 2)
+ expect(heights.paragraph).toBeGreaterThan(heights.line * 2)
+ })
+
test('saves a script’s edits laid out, though the script never read them back', async () => {
const out = join(await mkdtemp(join(tmpdir(), 'open-pencil-eval-')), 'badge.fig')
// A hugging badge whose label a property shortens: its saved width fits the new label.
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index 36f2acd3a..da0a104e8 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -4,7 +4,13 @@ export { parseFigmaClipboard, figmaNodesBounds } from '@open-pencil/fig/clipboar
import { placeSlotContent, type FigNodeChangeExportRuntime } from '@open-pencil/fig/node-change'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import type { GUID, NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/codec'
-import { ownsSlotContent, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import {
+ derivedAssetKey,
+ derivedAssetVersion,
+ ownsSlotContent,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'
import {
@@ -26,6 +32,7 @@ import {
makeCanvasNodeChange,
buildFontDigestMap
} from './kiwi/fig/node-change/serialize'
+import { cloneSceneGraphForFigExport } from './kiwi/fig/parse/transfer'
export async function prefetchFigmaSchema(): Promise<void> {
await initCodec()
@@ -51,12 +58,53 @@ export function importClipboardNodes(
return operation.plan.rootIds
}
+/**
+ * The document as the clipboard writes it. Figma names the variables and collections a paste
+ * uses by key, and keeps a binding to one it knows only by key as a remote variable, as it does
+ * for its own clipboard; variables made in OpenPencil have no key, so they take one derived from
+ * their ID here, for this copy only. Figma keeps the first value it pasted for a key and version,
+ * so the version follows their content and an edited variable pastes with its new value.
+ */
+function clipboardGraph(graph: SceneGraph): SceneGraph {
+ const unkeyed =
+ [...graph.variables.values()].some((variable) => !variable.key) ||
+ [...graph.variableCollections.values()].some((collection) => !collection.key)
+ if (!unkeyed) return graph
+ const copy = cloneSceneGraphForFigExport(graph)
+ copy.variableCollections = new Map(
+ [...graph.variableCollections].map(([id, collection]) => [
+ id,
+ collection.key
+ ? collection
+ : {
+ ...collection,
+ key: derivedAssetKey(`collection:${id}`),
+ version: derivedAssetVersion(JSON.stringify(collection))
+ }
+ ])
+ )
+ copy.variables = new Map(
+ [...graph.variables].map(([id, variable]) => [
+ id,
+ variable.key
+ ? variable
+ : {
+ ...variable,
+ key: derivedAssetKey(`variable:${id}`),
+ version: derivedAssetVersion(JSON.stringify(variable))
+ }
+ ])
+ )
+ return copy
+}
+
export function buildFigmaClipboardHTML(
nodes: SceneNode[],
graph: SceneGraph
): Promise<string | null> {
- return withFigExportRuntime(graph, undefined, (runtime) =>
- writeFigmaClipboardHTML(nodes, graph, runtime)
+ const written = clipboardGraph(graph)
+ return withFigExportRuntime(written, undefined, (runtime) =>
+ writeFigmaClipboardHTML(nodes, written, runtime)
)
}
diff --git a/packages/core/src/io/formats/fig/patch/export.ts b/packages/core/src/io/formats/fig/patch/export.ts
index c1e16a0db..f27ed1dd9 100644
--- a/packages/core/src/io/formats/fig/patch/export.ts
+++ b/packages/core/src/io/formats/fig/patch/export.ts
@@ -9,6 +9,7 @@ import { nameImagesForFigma, type FigNodeChangeExportRuntime } from '@open-penci
import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
import {
computeImageHash,
+ layersUsingVariables,
ownsSlotContent,
type SceneGraph,
type SceneNode
@@ -115,19 +116,19 @@ function addComponentInstances(
}
}
-/** Records carry the values of the variables they use, and the modes they set. */
+/**
+ * Records carry the values of the variables they use, through aliases and on their characters
+ * too, and the modes they set. Figma draws those saved values until it resolves the binding again.
+ */
function addVariableUsers(
graph: SceneGraph,
changes: ArchiveChangeSummary,
add: (id: string) => unknown
): void {
- for (const node of graph.nodes.values()) {
- const usesChanged = Object.values(node.boundVariables).some((id) =>
- changes.changedVariables.has(id)
- )
- const setsModes = changes.collectionsChanged && Object.keys(node.variableModes).length > 0
- if (usesChanged || setsModes) add(node.id)
- }
+ for (const node of layersUsingVariables(graph, changes.changedVariables)) add(node.id)
+ if (!changes.collectionsChanged) return
+ for (const node of graph.nodes.values())
+ if (Object.keys(node.variableModes).length > 0) add(node.id)
}
/** Siblings keep the positions the archive saved; one that cannot moves, and so is written. */
diff --git a/packages/core/src/io/formats/fig/variable-export.ts b/packages/core/src/io/formats/fig/variable-export.ts
index edd3d74a8..734d063eb 100644
--- a/packages/core/src/io/formats/fig/variable-export.ts
+++ b/packages/core/src/io/formats/fig/variable-export.ts
@@ -195,7 +195,8 @@ export function appendVariableNodeChanges(
})
),
pluginData: collectionPluginDataNodeChange(collection, modeKey),
- key: collection.key
+ key: collection.key,
+ version: collection.version
})
for (const id of collection.variableIds) {
const variable = graph.variables.get(id)
@@ -208,7 +209,10 @@ export function appendVariableNodeChanges(
phase: 'CREATED',
strokeAlign: 'CENTER',
strokeJoin: 'BEVEL',
- variableSetID: { guid },
+ // A collection with a library key is named by it, as Figma names a library's.
+ variableSetID: collection.key
+ ? { assetRef: { key: collection.key, version: collection.version } }
+ : { guid },
variableResolvedType: variable.type,
variableDataValues: {
entries: Object.entries(variable.valuesByMode).map(([mode, value]) => ({
diff --git a/packages/core/tests/clipboard/figma/instance-records.test.ts b/packages/core/tests/clipboard/figma/instance-records.test.ts
new file mode 100644
index 000000000..e6cf0615e
--- /dev/null
+++ b/packages/core/tests/clipboard/figma/instance-records.test.ts
@@ -0,0 +1,48 @@
+import { beforeAll, expect, setDefaultTimeout, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
+
+import { buildFigmaClipboardHTML, parseFigmaClipboard } from '@open-pencil/core'
+import { createEditor } from '@open-pencil/core/editor'
+import { parseFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { symbolOverridesOf } from '@open-pencil/fig/instance-overrides'
+
+setDefaultTimeout(120_000)
+
+beforeAll(async () => {
+ await initCodec()
+})
+
+/** Fields Figma writes on a component's record and never on an instance's. */
+const COMPONENT_ONLY = [
+ 'componentKey',
+ 'sourceLibraryKey',
+ 'publishID',
+ 'publishedVersion',
+ 'isSymbolPublishable',
+ 'variantPropSpecs',
+ 'componentPropDefs'
+]
+
+test('copied instances carry no component identity, and a rename sits where Figma reads it', async () => {
+ const graph = await parseFigFile(readFixtureArrayBuffer('gold-preview.fig'), {
+ populate: 'first-page'
+ })
+ const list = expectDefined([...graph.nodes.values()].find((node) => node.name === 'Checked List'))
+ const [first] = graph.getChildren(list.id)
+ createEditor({ graph }).updateNodeWithUndo(first.id, { name: 'Lists renamed' }, 'Rename')
+
+ const html = expectDefined(await buildFigmaClipboardHTML([list], graph))
+ const { nodes } = expectDefined(await parseFigmaClipboard(html))
+ const instances = nodes.filter((record) => record.type === 'INSTANCE')
+ expect(instances.length).toBeGreaterThan(0)
+ for (const record of instances)
+ expect(COMPONENT_ONLY.filter((field) => field in record)).toEqual([])
+
+ // Figma names an instance from the override on its own path, not from its record.
+ const renamed = expectDefined(instances.find((record) => record.name === 'Lists renamed'))
+ const own = symbolOverridesOf(renamed).find((override) => override.guidPath?.guids?.length === 1)
+ expect(own?.name).toBe('Lists renamed')
+})
diff --git a/packages/core/tests/clipboard/figma/variable-keys.test.ts b/packages/core/tests/clipboard/figma/variable-keys.test.ts
new file mode 100644
index 000000000..56892624b
--- /dev/null
+++ b/packages/core/tests/clipboard/figma/variable-keys.test.ts
@@ -0,0 +1,74 @@
+import { beforeAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { buildFigmaClipboardHTML, parseFigmaClipboard } from '@open-pencil/core'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+beforeAll(async () => {
+ await initCodec()
+})
+
+function boundRectangle() {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Brand')
+ const red = graph.createVariable('Brand/Red', 'COLOR', collection.id, { r: 1, g: 0, b: 0, a: 1 })
+ const rect = graph.createNode('RECTANGLE', graph.getPages()[0].id, {
+ name: 'Swatch',
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ ],
+ boundVariables: { 'fills/0/color': red.id }
+ })
+ return { graph, rect }
+}
+
+async function copied(graph: SceneGraph, rect: ReturnType<typeof boundRectangle>['rect']) {
+ const { nodes } = expectDefined(
+ await parseFigmaClipboard(expectDefined(await buildFigmaClipboardHTML([rect], graph)))
+ )
+ return {
+ swatch: expectDefined(nodes.find((record) => record.name === 'Swatch')),
+ variable: expectDefined(nodes.find((record) => record.type === 'VARIABLE')),
+ collection: expectDefined(nodes.find((record) => record.type === 'VARIABLE_SET'))
+ }
+}
+
+test('copies a variable made in OpenPencil by key, as Figma copies its own', async () => {
+ const { graph, rect } = boundRectangle()
+ const { swatch, variable, collection } = await copied(graph, rect)
+
+ // Figma keeps a binding to a variable it knows by key as a remote variable on paste.
+ const alias = expectDefined(swatch.fillPaints?.[0]?.colorVar?.value?.alias?.assetRef)
+ expect([variable.key, variable.version]).toEqual([alias.key, alias.version])
+ const set = expectDefined(variable.variableSetID?.assetRef)
+ expect([collection.key, collection.version]).toEqual([set.key, set.version])
+ expect(alias.key).toMatch(/^[0-9a-f]{40}$/)
+ // The document itself is left without keys, and copying again names the variable the same.
+ expect([...graph.variables.values()].every((candidate) => !candidate.key)).toBe(true)
+ expect((await copied(graph, rect)).variable.key).toBe(alias.key)
+})
+
+test('an edited variable copies with a new version, which Figma reads its new value by', async () => {
+ const { graph, rect } = boundRectangle()
+ const first = (await copied(graph, rect)).variable
+ expect((await copied(graph, rect)).variable.version).toBe(first.version)
+
+ const [variable] = graph.variables.values()
+ const collection = expectDefined(graph.variableCollections.get(variable.collectionId))
+ graph.variables.set(variable.id, {
+ ...variable,
+ valuesByMode: { [collection.defaultModeId]: { r: 0, g: 0, b: 1, a: 1 } }
+ })
+ const edited = (await copied(graph, rect)).variable
+ expect(edited.key).toBe(first.key)
+ expect(edited.version).not.toBe(first.version)
+ expect(edited.version).toMatch(/^\d+:\d+$/)
+})
diff --git a/packages/core/tests/io/formats/fig/patch/fields.test.ts b/packages/core/tests/io/formats/fig/patch/fields.test.ts
index 53a3c8a57..b0df095fe 100644
--- a/packages/core/tests/io/formats/fig/patch/fields.test.ts
+++ b/packages/core/tests/io/formats/fig/patch/fields.test.ts
@@ -110,3 +110,23 @@ test('a mode added to a collection of library aliases keeps the file as Figma sa
for (const entry of entries) expect(entry.variableData?.value?.alias?.guid).toBeUndefined()
}
})
+
+test('layers using an edited variable, through an alias too, save the color it resolves to', async () => {
+ const { bytes, graph } = await openGoldPreview()
+ const blue = expectDefined(
+ [...graph.variables.values()].find((variable) => variable.name === 'Colors/Blue/500')
+ )
+ const collection = expectDefined(graph.variableCollections.get(blue.collectionId))
+ const editor = createEditor({ graph })
+ for (const mode of collection.modes)
+ editor.updateVariableValue(blue.id, mode.modeId, { r: 1, g: 0, b: 0, a: 1 })
+
+ const saved = recordsOf(bytes)
+ const after = recordsOf(await exportFigFile(graph))
+ // Figma draws the color a paint saves until it resolves the binding again, so the file must
+ // carry the new one; this layer binds Theme/Default/Primary 500, which aliases the blue.
+ const vector = expectDefined([...after.values()].find((record) => record.name === 'Vector 2191'))
+ expect(vector.fillPaints?.[0]?.color).toEqual({ r: 1, g: 0, b: 0, a: 1 })
+ const fields = uniq([...changes(saved, after).values()].flat())
+ expect(fields.toSorted()).toEqual(['fillPaints', 'variableDataValues'])
+})
diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.ts
index ee4e4d958..279543516 100644
--- a/packages/fig/src/document/variables.ts
+++ b/packages/fig/src/document/variables.ts
@@ -82,7 +82,8 @@ export function materializeVariableResources(
variableIds: [],
modeAttribute: readModeAttribute(resource),
pluginData: pluginData.length > 0 ? pluginData : undefined,
- key: typeof resource.key === 'string' ? resource.key : undefined
+ key: typeof resource.key === 'string' ? resource.key : undefined,
+ version: typeof resource.version === 'string' ? resource.version : undefined
})
}
addVariables(graph, resources, report)
diff --git a/packages/fig/src/instance-overrides/fields.ts b/packages/fig/src/instance-overrides/fields.ts
index 55c9277c3..77967a24d 100644
--- a/packages/fig/src/instance-overrides/fields.ts
+++ b/packages/fig/src/instance-overrides/fields.ts
@@ -153,3 +153,21 @@ export const LAYOUT_DISTANCE_FIELDS: Readonly<Record<string, RawFieldOfKind<'lay
Object.fromEntries(
rawFieldsOfKind('layout-distance').map((raw) => [OVERRIDE_FIELDS[raw].scene[0], raw])
)
+
+/**
+ * A component's own identity, which an instance does not take from it: Figma writes these on
+ * component records only, and on an instance only its own override key and symbol version.
+ * Measured over `gold-preview`, `material3`, `slots`, and `variable-override-precedence`:
+ * 26,211 instance records, none carrying the rest.
+ */
+export const COMPONENT_IDENTITY_FIELDS = [
+ 'componentKey',
+ 'sourceLibraryKey',
+ 'publishID',
+ 'publishedVersion',
+ 'sharedSymbolVersion',
+ 'isSymbolPublishable',
+ 'variantPropSpecs',
+ 'componentPropDefs',
+ 'overrideKey'
+] as const
diff --git a/packages/fig/src/instance-overrides/interpret.ts b/packages/fig/src/instance-overrides/interpret.ts
index 1ff634740..d5b80b342 100644
--- a/packages/fig/src/instance-overrides/interpret.ts
+++ b/packages/fig/src/instance-overrides/interpret.ts
@@ -1,3 +1,5 @@
+import { omit } from 'es-toolkit/object'
+
import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
@@ -15,6 +17,7 @@ import {
declareSourceVariableBindingUnits
} from './bindings/variables'
import { applyDerivedEntry } from './derived-symbol-data'
+import { COMPONENT_IDENTITY_FIELDS } from './fields'
import {
ownLayers,
type AssignmentGroup,
@@ -531,7 +534,8 @@ function interpretRoot(
overrideKey: readOverrideKey(source.overrideKey),
// The record is the top layer of its own root: its fields are placed state.
properties: {
- ...base?.properties,
+ // The component's look carries over; its identity does not.
+ ...(base && omit(base.properties, COMPONENT_IDENTITY_FIELDS)),
...source,
...(effective && source.symbolData
? { symbolData: { ...source.symbolData, symbolID: effective } }
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index 8c2bc7213..f76b20a73 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -413,17 +413,20 @@ function applyRawFigmaNodeFields(
// For paint arrays on imported nodes, the raw NC data preserves the
// original opacity/color.a split (e.g. opacity=0 for invisible strokes).
// The scene model may lose this distinction for instance children whose
- // strokes are resolved from component overrides. Prefer the raw data.
+ // strokes are resolved from component overrides. Prefer the raw data,
+ // except for a bound color: Figma draws the color a paint saves, so it
+ // takes what its variable resolves to now.
if ((key === 'fillPaints' || key === 'strokePaints') && node.source.id) {
const paints = materialized[key]
- nc[key] = paints?.map((paint, index) =>
- applyColorVariableBinding(
- context,
- node,
- paint,
- `${key === 'fillPaints' ? 'fills' : 'strokes'}/${index}/color`
- )
- )
+ const current = key === 'fillPaints' ? node.fills : node.strokes
+ nc[key] = paints?.map((paint, index) => {
+ const field = `${key === 'fillPaints' ? 'fills' : 'strokes'}/${index}/color`
+ const bound = applyColorVariableBinding(context, node, paint, field)
+ const resolved = node.boundVariables[field] ? current[index] : undefined
+ return resolved
+ ? { ...bound, color: context.safeColor(resolved.color), opacity: resolved.opacity }
+ : bound
+ })
continue
}
if (
diff --git a/packages/scene-graph/src/asset-keys.ts b/packages/scene-graph/src/asset-keys.ts
new file mode 100644
index 000000000..b6f2a8d20
--- /dev/null
+++ b/packages/scene-graph/src/asset-keys.ts
@@ -0,0 +1,25 @@
+import { sha1 } from '@noble/hashes/legacy.js'
+import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'
+
+/**
+ * A key shaped as Figma's asset keys, 40 hex digits, derived from `seed` so the same seed always
+ * gives the same key. The Figma clipboard names variables and collections by key; one made in
+ * OpenPencil has none, so copying it gives it this one, and copying it again gives the same.
+ */
+export function derivedAssetKey(seed: string): string {
+ return bytesToHex(sha1(utf8ToBytes(seed)))
+}
+
+/** Largest part of a Figma GUID, which Figma reads as a signed 32-bit integer. */
+const MAX_GUID_PART = 0x7fffffff
+
+/**
+ * A version shaped as Figma's asset versions, `session:local`, derived from `content` so that
+ * copying an unchanged asset again gives the same version and copying a changed one gives another.
+ * Figma keeps the first value it pasted for a key and version, so a version that stayed the same
+ * across an edit would bring the old value back.
+ */
+export function derivedAssetVersion(content: string): string {
+ const view = new DataView(sha1(utf8ToBytes(content)).buffer)
+ return `${view.getUint32(0) & MAX_GUID_PART}:${view.getUint32(4) & MAX_GUID_PART}`
+}
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index ce6469578..84e2b3da5 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -12,6 +12,7 @@ export { TRANSFORM_FIELDS, SIZE_FIELDS } from './fields/geometry'
export { TEXT_METRIC_FIELDS, TEXT_SHAPING_FIELDS, TEXT_LAYOUT_FIELDS } from './fields/text'
export * from './transfer'
export * from './instance-overrides'
+export * from './asset-keys'
export * from './images'
export * from './components/properties'
export * from './components/variants'
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 1ee0c9396..312ce0978 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -876,6 +876,8 @@ export interface VariableCollection {
* belongs to the library: Figma lists it with the library's, not the file's own.
*/
key?: string
+ /** Published library version, which references by key carry with it. */
+ version?: string
}
/** Whether a collection is a library's copy, which takes no variables or modes of the file's. */
diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.ts
index a46a63bd9..ea3bc3a06 100644
--- a/packages/scene-graph/src/variables/bindings.ts
+++ b/packages/scene-graph/src/variables/bindings.ts
@@ -229,15 +229,23 @@ function subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {
return nodes
}
-function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {
- if (!scope) return graph.getAllNodes()
- if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)
- const variables = variablesResolvingThrough(graph, scope.variables)
+/**
+ * The layers a change to these variables reaches: those binding one of them, or a variable that
+ * aliases one, on the layer itself or on its characters.
+ */
+export function layersUsingVariables(graph: SceneGraph, ids: Iterable<string>): SceneNode[] {
+ const variables = variablesResolvingThrough(graph, ids)
return [...graph.getAllNodes()].filter((node) =>
boundVariableIds(node).some((id) => variables.has(id))
)
}
+function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {
+ if (!scope) return graph.getAllNodes()
+ if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)
+ return layersUsingVariables(graph, scope.variables)
+}
+
/**
* Resolve live numeric, text, and visibility bindings, numbers in scene units, without authoring
* instance overrides. A scope limits it to the layers a change can reach, so layers whose saved
diff --git a/packages/vue/src/i18n/locales/de/variables.json b/packages/vue/src/i18n/locales/de/variables.json
index 54d76f7a3..421e76a69 100644
--- a/packages/vue/src/i18n/locales/de/variables.json
+++ b/packages/vue/src/i18n/locales/de/variables.json
@@ -98,6 +98,9 @@
"scopeFontFamily": "Schriftfamilie",
"exportDesignTokens": "Als Design-Tokens exportieren",
"importDesignTokens": "Design-Tokens importieren",
+ "libraryCollection": "Bibliothek",
+ "libraryCollectionHint": "Aus einer Bibliothek kopiert. Änderungen werden in dieser Datei gespeichert und in Figma angezeigt.",
+ "addedToLibraryCollection": "Hier hinzugefügt. Figma zeigt keine Variablen, die der Sammlung einer Bibliothek hinzugefügt wurden.",
"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",
diff --git a/packages/vue/src/i18n/locales/es/variables.json b/packages/vue/src/i18n/locales/es/variables.json
index ee9994766..ebf94dc14 100644
--- a/packages/vue/src/i18n/locales/es/variables.json
+++ b/packages/vue/src/i18n/locales/es/variables.json
@@ -98,6 +98,9 @@
"scopeFontFamily": "Familia tipográfica",
"exportDesignTokens": "Exportar como design tokens",
"importDesignTokens": "Importar design tokens",
+ "libraryCollection": "Biblioteca",
+ "libraryCollectionHint": "Copiada de una biblioteca. Los cambios se guardan en este archivo y se ven en Figma.",
+ "addedToLibraryCollection": "Añadida aquí. Figma no muestra las variables añadidas a la colección de una biblioteca.",
"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",
diff --git a/packages/vue/src/i18n/locales/fr/variables.json b/packages/vue/src/i18n/locales/fr/variables.json
index 44bb753d2..63c57ed64 100644
--- a/packages/vue/src/i18n/locales/fr/variables.json
+++ b/packages/vue/src/i18n/locales/fr/variables.json
@@ -98,6 +98,9 @@
"scopeFontFamily": "Famille de police",
"exportDesignTokens": "Exporter en design tokens",
"importDesignTokens": "Importer des design tokens",
+ "libraryCollection": "Bibliothèque",
+ "libraryCollectionHint": "Copiée d'une bibliothèque. Les modifications sont enregistrées dans ce fichier et visibles dans Figma.",
+ "addedToLibraryCollection": "Ajoutée ici. Figma n'affiche pas les variables ajoutées à la collection d'une bibliothèque.",
"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",
diff --git a/packages/vue/src/i18n/locales/it/variables.json b/packages/vue/src/i18n/locales/it/variables.json
index 6c1ef7a40..9cb1857af 100644
--- a/packages/vue/src/i18n/locales/it/variables.json
+++ b/packages/vue/src/i18n/locales/it/variables.json
@@ -98,6 +98,9 @@
"scopeFontFamily": "Famiglia di caratteri",
"exportDesignTokens": "Esporta come design token",
"importDesignTokens": "Importa design token",
+ "libraryCollection": "Libreria",
+ "libraryCollectionHint": "Copiata da una libreria. Le modifiche vengono salvate in questo file e si vedono in Figma.",
+ "addedToLibraryCollection": "Aggiunta qui. Figma non mostra le variabili aggiunte alla raccolta di una libreria.",
"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à",
diff --git a/packages/vue/src/i18n/locales/ja/variables.json b/packages/vue/src/i18n/locales/ja/variables.json
index 4107d9d5d..20f45797d 100644
--- a/packages/vue/src/i18n/locales/ja/variables.json
+++ b/packages/vue/src/i18n/locales/ja/variables.json
@@ -98,6 +98,9 @@
"scopeFontFamily": "フォントファミリー",
"exportDesignTokens": "デザイントークンとして書き出す",
"importDesignTokens": "デザイントークンを読み込む",
+ "libraryCollection": "ライブラリ",
+ "libraryCollectionHint": "ライブラリからコピーされています。編集はこのファイルに保存され、Figma にも表示されます。",
+ "addedToLibraryCollection": "ここで追加されました。ライブラリのコレクションに追加された変数は Figma に表示されません。",
"importTokensDescription": "各コレクションとモードの読み込み先を選びます。同じ名前の変数は更新され、削除されるものはありません。",
"importNewCollection": "新しいコレクション",
"importNewMode": "新しいモード",
diff --git a/packages/vue/src/i18n/locales/pl/variables.json b/packages/vue/src/i18n/locales/pl/variables.json
index 84a907240..7f93a35a2 100644
--- a/packages/vue/src/i18n/locales/pl/variables.json
+++ b/packages/vue/src/i18n/locales/pl/variables.json
@@ -98,6 +98,9 @@
"scopeFontFamily": "Rodzina czcionek",
"exportDesignTokens": "Eksportuj jako tokeny projektowe",
"importDesignTokens": "Importuj tokeny projektowe",
+ "libraryCollection": "Biblioteka",
+ "libraryCollectionHint": "Skopiowana z biblioteki. Zmiany są zapisywane w tym pliku i widoczne w Figmie.",
+ "addedToLibraryCollection": "Dodana tutaj. Figma nie pokazuje zmiennych dodanych do kolekcji biblioteki.",
"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",
diff --git a/packages/vue/src/i18n/locales/ru/variables.json b/packages/vue/src/i18n/locales/ru/variables.json
index ee0970404..1010dd9c4 100644
--- a/packages/vue/src/i18n/locales/ru/variables.json
+++ b/packages/vue/src/i18n/locales/ru/variables.json
@@ -98,6 +98,9 @@
"scopeFontFamily": "Гарнитура шрифта",
"exportDesignTokens": "Экспортировать как дизайн-токены",
"importDesignTokens": "Импортировать дизайн-токены",
+ "libraryCollection": "Библиотека",
+ "libraryCollectionHint": "Скопирована из библиотеки. Изменения сохраняются в этом файле и видны в Figma.",
+ "addedToLibraryCollection": "Добавлена здесь. Figma не показывает переменные, добавленные в коллекцию библиотеки.",
"importTokensDescription": "Выберите, куда попадёт каждая коллекция и каждый режим. Переменные с тем же именем обновятся; ничего не удаляется.",
"importNewCollection": "Новая коллекция",
"importNewMode": "Новый режим",
diff --git a/packages/vue/src/i18n/locales/zh-cn/variables.json b/packages/vue/src/i18n/locales/zh-cn/variables.json
index 0c4819116..3a8a3731b 100644
--- a/packages/vue/src/i18n/locales/zh-cn/variables.json
+++ b/packages/vue/src/i18n/locales/zh-cn/variables.json
@@ -98,6 +98,9 @@
"scopeFontFamily": "字体",
"exportDesignTokens": "导出为设计令牌",
"importDesignTokens": "导入设计令牌",
+ "libraryCollection": "库",
+ "libraryCollectionHint": "从库中复制。编辑会保存在此文件中,并显示在 Figma 里。",
+ "addedToLibraryCollection": "在这里添加。Figma 不会显示添加到库集合中的变量。",
"importTokensDescription": "选择每个集合和模式导入到哪里。同名变量会被更新,不会删除任何内容。",
"importNewCollection": "新集合",
"importNewMode": "新模式",
diff --git a/packages/vue/src/i18n/messages/variables.ts b/packages/vue/src/i18n/messages/variables.ts
index f7b0b28ed..4b2af272f 100644
--- a/packages/vue/src/i18n/messages/variables.ts
+++ b/packages/vue/src/i18n/messages/variables.ts
@@ -105,6 +105,10 @@ export const variablesMessageDefaults = {
scopeFontFamily: 'Font family',
exportDesignTokens: 'Export as design tokens',
importDesignTokens: 'Import design tokens',
+ libraryCollection: 'Library',
+ libraryCollectionHint: 'Copied from a library. Edits are saved in this file and show in Figma.',
+ addedToLibraryCollection:
+ "Added here. Figma doesn't show variables added to a library's collection.",
importTokensDescription:
'Choose where each collection and mode goes. Variables with the same name are updated; nothing is deleted.',
importNewCollection: 'New collection',
diff --git a/src/components/variables/CollectionInspector.vue b/src/components/variables/CollectionInspector.vue
index 49aa3555d..b176a4bc2 100644
--- a/src/components/variables/CollectionInspector.vue
+++ b/src/components/variables/CollectionInspector.vue
@@ -11,7 +11,11 @@ import { tv } from 'tailwind-variants'
import { computed, reactive, useId, watch } from 'vue'
import { defaultModeAttributeName } from '@open-pencil/dom-css/export'
-import { isModeAttributeName, type VariableCollection } from '@open-pencil/scene-graph'
+import {
+ isLibraryCollection,
+ isModeAttributeName,
+ type VariableCollection
+} from '@open-pencil/scene-graph'
import { useI18n } from '@open-pencil/vue'
import {
@@ -27,6 +31,7 @@ import IconButton from '@/components/ui/button/IconButton.vue'
import AppBadge from '@/components/ui/feedback/AppBadge.vue'
import AppInput from '@/components/ui/input/AppInput.vue'
import { useMenuUI } from '@/components/ui/menu/menu'
+import Tip from '@/components/ui/overlay/Tip.vue'
import AppSelect from '@/components/ui/select/AppSelect.vue'
import { useConditionLabels } from '@/components/variables/useConditionLabels'
import tokensPanelTheme from '@/theme/tokens-panel'
@@ -184,7 +189,12 @@ function attributeDone(event: KeyboardEvent) {
<template>
<aside :class="ui.inspector()" data-test-id="collection-inspector">
<section :class="ui.section()">
- <span :class="ui.label()">{{ variables.collection }}</span>
+ <span :class="ui.label()" class="flex items-center gap-1.5">
+ {{ variables.collection }}
+ <Tip v-if="isLibraryCollection(collection)" :label="variables.libraryCollectionHint">
+ <AppBadge>{{ variables.libraryCollection }}</AppBadge>
+ </Tip>
+ </span>
<div class="flex items-center gap-1">
<AppInput
v-model="draft.name"
diff --git a/src/components/variables/TokenSidebar.vue b/src/components/variables/TokenSidebar.vue
index 44e4cd4d5..af3916cbc 100644
--- a/src/components/variables/TokenSidebar.vue
+++ b/src/components/variables/TokenSidebar.vue
@@ -5,6 +5,8 @@ import { useI18n } from '@open-pencil/vue'
import type { GroupEntry } from '@/app/editor/tokens/model'
import IconButton from '@/components/ui/button/IconButton.vue'
+import AppBadge from '@/components/ui/feedback/AppBadge.vue'
+import Tip from '@/components/ui/overlay/Tip.vue'
import tokensPanelTheme from '@/theme/tokens-panel'
/**
@@ -12,7 +14,8 @@ import tokensPanelTheme from '@/theme/tokens-panel'
* a group narrows the list to it and the groups inside it.
*/
const { collections, groups, total } = defineProps<{
- collections: Array<{ id: string; name: string; count: number }>
+ /** `library` marks a collection copied from a library. */
+ collections: Array<{ id: string; name: string; count: number; library: boolean }>
groups: GroupEntry[]
/** Tokens in the active collection, shown beside "All". */
total: number
@@ -50,6 +53,9 @@ const ui = tv(tokensPanelTheme)()
@click="activeCollectionId = item.id"
>
<span class="truncate">{{ item.name }}</span>
+ <Tip v-if="item.library" :label="variables.libraryCollectionHint">
+ <AppBadge>{{ variables.libraryCollection }}</AppBadge>
+ </Tip>
<span :class="ui.sidebarCount()">{{ item.count }}</span>
</button>
</section>
diff --git a/src/components/variables/TokenTable.vue b/src/components/variables/TokenTable.vue
index 262db4880..70e458bd7 100644
--- a/src/components/variables/TokenTable.vue
+++ b/src/components/variables/TokenTable.vue
@@ -3,7 +3,11 @@ import { ListboxContent, ListboxGroup, ListboxGroupLabel, ListboxItem, ListboxRo
import { tv } from 'tailwind-variants'
import { computed, ref, useTemplateRef, type ComponentPublicInstance } from 'vue'
-import type { VariableCollection, VariableValue } from '@open-pencil/scene-graph'
+import {
+ isLibraryCollection,
+ type VariableCollection,
+ type VariableValue
+} from '@open-pencil/scene-graph'
import { useFlatReorderDrag, useI18n } from '@open-pencil/vue'
import {
@@ -13,6 +17,7 @@ import {
type TokenRow
} from '@/app/editor/tokens/model'
import BindingPill from '@/components/ui/binding/BindingPill.vue'
+import Tip from '@/components/ui/overlay/Tip.vue'
import FillSwatch from '@/components/ui/paint/FillSwatch.vue'
import TokenCellInput from '@/components/variables/TokenCellInput.vue'
import TokenRowMenu from '@/components/variables/TokenRowMenu.vue'
@@ -43,6 +48,8 @@ const emit = defineEmits<{
const { variables } = useI18n()
const ui = tv(tokensPanelTheme)()
+/** Figma does not show a variable the file adds to a library's collection; such a row says so. */
+const libraryCollection = computed(() => isLibraryCollection(collection))
const modes = computed(() =>
modeIds ? collection.modes.filter((mode) => modeIds.includes(mode.modeId)) : collection.modes
@@ -240,6 +247,19 @@ function dropEdge(id: string) {
@cancel="editing = null"
/>
<span v-else class="truncate">{{ row.label }}</span>
+ <Tip
+ v-if="libraryCollection && !row.variable.key"
+ :label="variables.addedToLibraryCollection"
+ >
+ <span
+ role="img"
+ :aria-label="variables.addedToLibraryCollection"
+ class="flex shrink-0 text-issue-warning"
+ data-test-id="variable-added-to-library"
+ >
+ <icon-lucide-triangle-alert class="size-3" aria-hidden="true" />
+ </span>
+ </Tip>
</span>
<span :class="ui.cssStacked()">--{{ row.cssName }}</span>
</span>
diff --git a/src/components/variables/TokensPanel.stories.ts b/src/components/variables/TokensPanel.stories.ts
index 22afcc7bc..86045f215 100644
--- a/src/components/variables/TokensPanel.stories.ts
+++ b/src/components/variables/TokensPanel.stories.ts
@@ -14,14 +14,20 @@ const meta = {
}
}
}
-} satisfies Meta<{ width?: number }>
+} satisfies Meta<{ width?: number; library?: boolean }>
export default meta
-type Story = StoryObj<{ width?: number }>
+type Story = StoryObj<{ width?: number; library?: boolean }>
/** From 56rem the CSS name has its own column and the inspector sits beside the list. */
export const DesignSystemTokens: Story = {}
+/**
+ * A collection copied from a library carries a Library badge and stays editable. Surface/Ink was
+ * added in the file, which Figma does not show in a library's collection, and its row says so.
+ */
+export const FromLibrary: Story = { args: { library: true } }
+
/** In a dialog-sized panel the CSS name moves under the token name; every mode still shows. */
export const Medium: Story = { args: { width: 800 } }
diff --git a/src/components/variables/TokensPanel.vue b/src/components/variables/TokensPanel.vue
index 2c02ef5be..55a1431c2 100644
--- a/src/components/variables/TokensPanel.vue
+++ b/src/components/variables/TokensPanel.vue
@@ -5,7 +5,11 @@ import { computed, ref, useTemplateRef, watch } from 'vue'
import type { VariableTokenFields } from '@open-pencil/core/editor'
import type { TokenStylesheetFormat } from '@open-pencil/dom-css/export'
-import type { VariableType, VariableValue } from '@open-pencil/scene-graph'
+import {
+ isLibraryCollection,
+ type VariableType,
+ type VariableValue
+} from '@open-pencil/scene-graph'
import { useI18n, useSceneComputed, useVariables } from '@open-pencil/vue'
import {
@@ -141,7 +145,8 @@ const sidebarCollections = computed(() =>
ctx.collections.value.map((candidate) => ({
id: candidate.id,
name: candidate.name,
- count: candidate.variableIds.length
+ count: candidate.variableIds.length,
+ library: isLibraryCollection(candidate)
}))
)
const modeOptions = computed(() =>
diff --git a/src/components/variables/examples/DesignSystem.vue b/src/components/variables/examples/DesignSystem.vue
index 021eaac39..9fe7b5bfd 100644
--- a/src/components/variables/examples/DesignSystem.vue
+++ b/src/components/variables/examples/DesignSystem.vue
@@ -8,8 +8,11 @@ import { provideEditor } from '@open-pencil/vue'
import TokensPanel from '@/components/variables/TokensPanel.vue'
-/** The frame width in pixels, capped by the window; the panel lays out by this. */
-const { width = 1040 } = defineProps<{ width?: number }>()
+/**
+ * The frame width in pixels, capped by the window; the panel lays out by this. `library` makes
+ * the theme a collection copied from a library, as Figma files that use one carry it.
+ */
+const { width = 1040, library = false } = defineProps<{ width?: number; library?: boolean }>()
/** Reactive state, as the app session gives it, so edits re-render the panel. */
const graph = new SceneGraph()
@@ -38,6 +41,11 @@ function addVariable(
})
}
+/** A library variable's key, in the library story; Surface/Ink is one the file added. */
+function libraryKey(key: string): Partial<Variable> {
+ return library ? { key, version: '290407:24243' } : {}
+}
+
graph.addCollection({
id: 'theme',
name: 'Theme',
@@ -47,7 +55,8 @@ graph.addCollection({
{ modeId: 'contrast', name: 'Contrast', condition: '@media (prefers-contrast: more)' }
],
defaultModeId: 'light',
- variableIds: []
+ variableIds: [],
+ ...(library && { key: '44d54909789ec00cd81859bdc9584faf9cf0de97', version: '290407:23953' })
})
graph.addCollection({
id: 'primitives',
@@ -87,13 +96,24 @@ addVariable(
dark: { aliasId: 'blue-300' },
contrast: { aliasId: 'blue-700' }
},
- { scopes: ['ALL_FILLS'], description: 'Buttons, links, and focus rings.' }
+ {
+ scopes: ['ALL_FILLS'],
+ description: 'Buttons, links, and focus rings.',
+ ...libraryKey('309597cc79582813865d705981904aab5709be5e')
+ }
+)
+addVariable(
+ 'theme',
+ 'surface',
+ 'Surface/Base',
+ 'COLOR',
+ {
+ light: parseColor('#FFFFFF'),
+ dark: parseColor('#111827'),
+ contrast: parseColor('#FFFFFF')
+ },
+ libraryKey('e42910ebf15692f34d8cf880b1d9ccd2c591b3bd')
)
-addVariable('theme', 'surface', 'Surface/Base', 'COLOR', {
- light: parseColor('#FFFFFF'),
- dark: parseColor('#111827'),
- contrast: parseColor('#FFFFFF')
-})
addVariable('theme', 'ink', 'Surface/Ink', 'COLOR', {
light: { aliasId: 'gray-900' },
dark: { aliasId: 'gray-50' },
diff --git a/src/theme/tokens-panel.ts b/src/theme/tokens-panel.ts
index c0c8538ba..92e0a869e 100644
--- a/src/theme/tokens-panel.ts
+++ b/src/theme/tokens-panel.ts
@@ -7,10 +7,11 @@ export const TOKENS_PANEL_SIDEBAR_WIDTH = 896
/**
* The list is its own `tokens-list` container, so its columns follow the space left beside the
* inspector. Below 42rem (`@2xl`) the CSS name moves under the token name; the value columns
- * repeat `--token-modes` times.
+ * repeat `--token-modes` times. The name keeps a width of its own, so a collection with more
+ * modes than fit scrolls sideways instead of hiding its names.
*/
const COLUMNS =
- 'grid-cols-[minmax(0,1.4fr)_repeat(var(--token-modes),minmax(6rem,1fr))] @2xl/tokens-list:grid-cols-[minmax(8rem,1.1fr)_minmax(8rem,1fr)_repeat(var(--token-modes),minmax(7rem,1fr))]'
+ 'grid-cols-[minmax(8rem,1.4fr)_repeat(var(--token-modes),minmax(6rem,1fr))] @2xl/tokens-list:grid-cols-[minmax(8rem,1.1fr)_minmax(8rem,1fr)_repeat(var(--token-modes),minmax(7rem,1fr))]'
export default {
slots: {
@@ -27,9 +28,9 @@ export default {
list: '@container/tokens-list flex min-w-0 flex-1 flex-col overflow-auto',
inspector: 'flex shrink-0 flex-col gap-4 overflow-y-auto p-4',
output: 'flex shrink-0 flex-col border-t border-border',
- header: `sticky top-0 z-10 grid items-center gap-3 border-b border-border bg-panel px-4 py-2 text-[11px] font-medium text-muted ${COLUMNS}`,
+ header: `sticky top-0 z-10 grid min-w-min items-center gap-3 border-b border-border bg-panel px-4 py-2 text-[11px] font-medium text-muted ${COLUMNS}`,
group: 'px-4 pt-3 pb-1 text-[11px] font-semibold text-muted',
- row: `${COLUMNS} grid cursor-pointer items-center gap-3 px-4 py-1.5 text-xs text-surface outline-none transition-colors duration-100 hover:bg-hover data-[highlighted]:bg-hover data-[state=checked]:bg-hover data-[state=checked]:ring-1 data-[state=checked]:ring-accent/40 data-[state=checked]:ring-inset data-[dragging]:opacity-50 data-[drop=after]:shadow-[inset_0_-2px_0_var(--color-accent)] data-[drop=before]:shadow-[inset_0_2px_0_var(--color-accent)] motion-reduce:transition-none`,
+ row: `${COLUMNS} grid min-w-min cursor-pointer items-center gap-3 px-4 py-1.5 text-xs text-surface outline-none transition-colors duration-100 hover:bg-hover data-[highlighted]:bg-hover data-[state=checked]:bg-hover data-[state=checked]:ring-1 data-[state=checked]:ring-accent/40 data-[state=checked]:ring-inset data-[dragging]:opacity-50 data-[drop=after]:shadow-[inset_0_-2px_0_var(--color-accent)] data-[drop=before]:shadow-[inset_0_2px_0_var(--color-accent)] motion-reduce:transition-none`,
name: 'flex min-w-0 flex-col truncate',
nameLine: 'flex min-w-0 items-center gap-1.5',
typeIcon: 'size-3 shrink-0 text-muted',
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index 724b19893..0800a7ad1 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -419,11 +419,15 @@ ja:variables.expression
ja:variables.expressionHint
ja:variables.conditionHint
ja:variables.conditionCustom
+ja:variables.libraryCollectionHint
+ja:variables.addedToLibraryCollection
zh-cn:variables.cssName
zh-cn:variables.expression
zh-cn:variables.expressionHint
zh-cn:variables.conditionHint
zh-cn:variables.conditionCustom
+zh-cn:variables.libraryCollectionHint
+zh-cn:variables.addedToLibraryCollection
zh-cn:panels.shaderPreset
zh-cn:panels.invalidShaderPreset
zh-cn:panels.shaderNeedsWebGPU