Skip to content

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

feat: add Figma's styles and fill plugin API gaps (#1678)

Danila Poyarkov7a5af44f1f03
diff --git a/bun.lock b/bun.lock
index 3d27b3238..259b12284 100644
--- a/bun.lock
+++ b/bun.lock
@@ -278,6 +278,7 @@
"name": "@open-pencil/core",
"version": "0.17.0-beta.1",
"dependencies": {
+ "@figma/plugin-typings": "^1.140.0",
"@iconify/utils": "^3.1.4",
"@open-pencil/design-jsx": "workspace:*",
"@open-pencil/dom-css": "workspace:*",
diff --git a/changes/1678/added.md b/changes/1678/added.md
new file mode 100644
index 000000000..ae56e9f96
--- /dev/null
+++ b/changes/1678/added.md
@@ -0,0 +1,2 @@
+- Scripts create, find, apply, edit, and remove paint, text, effect, and grid styles through Figma's plugin API: `figma.createPaintStyle()` and its siblings, `getLocalPaintStylesAsync()` and its siblings, `getStyleByIdAsync()`, and `set…StyleIdAsync()` on layers. A change to a style reaches every layer and text range that uses it, and removing one leaves them its values.
+- Scripts read and set more of Figma's plugin API: `guides`, `horizontalPadding` and `verticalPadding`, `booleanOperation`, a text's underline style, `leadingTrim`, and `openTypeFeatures`, component `description`, `instances`, and `getInstancesAsync()`, a set's `defaultVariant` and `variantGroupProperties`, `removeOverrides()`, `setFillsAsync()` and `setStrokesAsync()`, `getTopLevelFrame()`, and `documentColorProfile`.
diff --git a/changes/1678/breaking.md b/changes/1678/breaking.md
new file mode 100644
index 000000000..5864ff6ec
--- /dev/null
+++ b/changes/1678/breaking.md
@@ -0,0 +1 @@
+- `sharedStylePatch` and `sharedStyleDetachPatch` move from `@open-pencil/vue/controls/shared-style` to `@open-pencil/scene-graph/shared-styles`.
diff --git a/changes/1678/fixed.md b/changes/1678/fixed.md
new file mode 100644
index 000000000..71da5392b
--- /dev/null
+++ b/changes/1678/fixed.md
@@ -0,0 +1,4 @@
+- A component set's default variant is the one Figma picks: variants whose rows overlap read left to right, others top to bottom.
+- Scripts refuse a style ID the document does not hold, as Figma does, instead of attaching it.
+- Plugin API underline getters read the underlined characters' value over partly underlined text, and text and paint setters word their errors as current Figma does.
+- `@open-pencil/core/figma-api` types resolve Figma's node, paint, and style types for packages that use them, without bringing in Figma's plugin sandbox globals.
diff --git a/packages/core/package.json b/packages/core/package.json
index 4ce4d80b8..8edabf8b4 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -182,6 +182,7 @@
"typecheck": "tsc --noEmit -p tsconfig.test.json"
},
"dependencies": {
+ "@figma/plugin-typings": "^1.140.0",
"@iconify/utils": "^3.1.4",
"@open-pencil/design-jsx": "workspace:*",
"@open-pencil/dom-css": "workspace:*",
diff --git a/packages/core/src/editor/guides.ts b/packages/core/src/editor/guides.ts
index 6306c9d4a..17206a5af 100644
--- a/packages/core/src/editor/guides.ts
+++ b/packages/core/src/editor/guides.ts
@@ -1,6 +1,6 @@
import { uniq } from 'es-toolkit/array'
-import type { CanvasGuide } from '@open-pencil/scene-graph/guides'
+import { newGuideId, type CanvasGuide } from '@open-pencil/scene-graph/guides'
import type { EditorContext } from './types'
@@ -20,10 +20,6 @@ function replaceGuides(ctx: EditorContext, ownerId: string, guides: CanvasGuide[
ctx.requestRender()
}
-function newGuideId(): string {
- return `guide:${crypto.randomUUID()}`
-}
-
export function createGuideActions(ctx: EditorContext) {
function addGuide(ownerId: string, axis: CanvasGuide['axis'], position: number): string | null {
const node = owner(ctx, ownerId)
diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.ts
index 633f15f90..b76cb7d58 100644
--- a/packages/core/src/figma-api/accessor-utils.ts
+++ b/packages/core/src/figma-api/accessor-utils.ts
@@ -119,8 +119,27 @@ export function updateNode(
changes: Partial<SceneNode>
): void {
assertProxyEditable(target, internals)
- const g = graph(target, internals)
- const id = nodeId(target, internals)
+ applyLayerChanges(
+ graph(target, internals),
+ nodeId(target, internals),
+ changes,
+ hostFitOptions(target, internals)
+ )
+}
+
+/**
+ * Changes a layer as the plugin API's setters do: auto-sizing text measures its new content, a
+ * vector's regions take its new fills, an edit to a style's fields leaves the style, overrides
+ * record only what changed, and the groups around a moved or resized layer refit. A change that
+ * follows the layer's source, such as a style it uses, records no override.
+ */
+export function applyLayerChanges(
+ g: SceneGraph,
+ id: string,
+ changes: Partial<SceneNode>,
+ fitOptions: GroupFitOptions,
+ recordOverrides = true
+): void {
const applied = Object.fromEntries(
Object.keys(changes)
.filter((key) => Reflect.get(changes, key) !== undefined)
@@ -128,19 +147,16 @@ export function updateNode(
) as Partial<SceneNode>
if (Object.keys(applied).length === 0) return
const before = g.getNode(id)
- // Auto-sizing text measures its new content, and a vector's regions take its new fills, as the
- // editor's updates do.
Object.assign(applied, textAutoResizeChanges(before, applied))
if (before) Object.assign(applied, regionFillChanges(before, applied))
- // An edit to a style's fields leaves that style, as the editor's updates do.
const edit = before ? styleDetachmentChanges(before, applied) : applied
// Figma overrides only what an edit changes, so setting a layer's own value claims nothing.
const changed = Object.keys(edit).filter(
(key) => !before || !isEqual(Reflect.get(edit, key), Reflect.get(before, key))
)
g.updateNode(id, edit)
- recordInstanceOverride(g, id, changed)
+ if (recordOverrides) recordInstanceOverride(g, id, changed)
if (Object.keys(edit).some((key) => GEOMETRY_FIELDS.has(key))) {
- fitGroupsAround(g, g.getNode(id)?.parentId, hostFitOptions(target, internals))
+ fitGroupsAround(g, g.getNode(id)?.parentId, fitOptions)
}
}
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index d20752d80..ef7d383e3 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -29,7 +29,7 @@ import {
} from '#core/figma-api/accessor-utils'
import { invalid, numberProblem } from '#core/figma-api/accessors/text/messages'
import { flushPendingLayout } from '#core/figma-api/pending-layout'
-import type { NodeProxyHost } from '#core/figma-api/proxy'
+import type { FigmaNodeProxy, NodeProxyHost } from '#core/figma-api/proxy'
import { computeAbsoluteRenderBounds } from '#core/figma-api/render-bounds'
import {
containerTransform,
@@ -252,10 +252,37 @@ export function installBasicNodeProxyAccessors(
if (node.parentId && findInstanceAncestor(scene, node.parentId))
throw new Error('This property cannot be overridden in an instance: size')
rescaleNodeTree(scene, node.id, scale)
+ },
+ getTopLevelFrame(this: ProxyThis): FigmaNodeProxy | undefined {
+ const top = topLevelFrame(graph(this, internals), raw(this, internals))
+ return top ? (this[internals.api] as NodeProxyHost).wrapNode(top.id) : undefined
}
})
}
+/** The layers `getTopLevelFrame` can return; a shape or boolean is never one. */
+const TOP_LEVEL_FRAME_TYPES: ReadonlySet<SceneNode['type']> = new Set([
+ 'FRAME',
+ 'GROUP',
+ 'SECTION',
+ 'COMPONENT',
+ 'COMPONENT_SET',
+ 'INSTANCE'
+])
+
+/**
+ * The container a layer sits in at the top of its page or section: the nearest of the layer and
+ * its ancestors that is a frame, group, section, component, or instance directly under a page or
+ * section. A shape directly on a page has none (Figma desktop 126).
+ */
+function topLevelFrame(scene: SceneGraph, node: SceneNode): SceneNode | undefined {
+ return scene.closest(node.id, (current) => {
+ const parent = current.parentId ? scene.getNode(current.parentId) : undefined
+ const topLevel = parent?.type === 'CANVAS' || parent?.type === 'SECTION'
+ return topLevel && TOP_LEVEL_FRAME_TYPES.has(current.type)
+ })
+}
+
/** Every layer below a node, which a resize may place by its constraints. */
function descendants(scene: SceneGraph, node: SceneNode): SceneNode[] {
return scene.getChildren(node.id).flatMap((child) => [child, ...descendants(scene, child)])
diff --git a/packages/core/src/figma-api/accessors/component.ts b/packages/core/src/figma-api/accessors/component.ts
new file mode 100644
index 000000000..de643c37a
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/component.ts
@@ -0,0 +1,104 @@
+import type { ComponentSetNode } from '@figma/plugin-typings/plugin-api-standalone'
+import { compact, uniq } from 'es-toolkit/array'
+
+import type { SceneNode } from '@open-pencil/scene-graph'
+import { defaultVariant } from '@open-pencil/scene-graph/components'
+
+import {
+ graph,
+ raw,
+ updateNode,
+ type NodeProxyInternals,
+ type ProxyThis
+} from '#core/figma-api/accessor-utils'
+import { invalid, received } from '#core/figma-api/accessors/text/messages'
+import type { FigmaNodeProxy, NodeProxyHost } from '#core/figma-api/proxy'
+
+function wrap(target: ProxyThis, internals: NodeProxyInternals, id: string): FigmaNodeProxy {
+ return (target[internals.api] as NodeProxyHost).wrapNode(id)
+}
+
+function instancesOf(target: ProxyThis, internals: NodeProxyInternals): FigmaNodeProxy[] {
+ const id = raw(target, internals).id
+ return graph(target, internals)
+ .getInstances(id)
+ .map((instance) => wrap(target, internals, instance.id))
+}
+
+/**
+ * The members Figma's `ComponentNode` and `ComponentSetNode` add: a description, a component's
+ * instances, and a set's default variant and variant values. Installed on the proxies of those
+ * nodes alone, as Figma has them on no other node.
+ */
+export function installComponentNodeAccessors(
+ target: object,
+ internals: NodeProxyInternals,
+ type: SceneNode['type']
+): void {
+ if (type !== 'COMPONENT' && type !== 'COMPONENT_SET') return
+ Object.defineProperty(target, 'description', {
+ get(this: ProxyThis): string {
+ return raw(this, internals).symbolDescription
+ },
+ set(this: ProxyThis, value: unknown) {
+ if (typeof value !== 'string') {
+ throw invalid(
+ 'set_description',
+ `Expected string, received ${received(value)}`,
+ 'description'
+ )
+ }
+ updateNode(this, internals, { symbolDescription: value })
+ }
+ })
+ if (type === 'COMPONENT') {
+ Object.defineProperties(target, {
+ instances: {
+ get(this: ProxyThis): FigmaNodeProxy[] {
+ return instancesOf(this, internals)
+ }
+ },
+ // Async, so a removed component rejects rather than throwing.
+ getInstancesAsync: {
+ async value(this: ProxyThis): Promise<FigmaNodeProxy[]> {
+ return instancesOf(this, internals)
+ }
+ }
+ })
+ return
+ }
+ Object.defineProperties(target, {
+ defaultVariant: {
+ get(this: ProxyThis): FigmaNodeProxy | null {
+ const variant = defaultVariant(graph(this, internals), raw(this, internals))
+ return variant ? wrap(this, internals, variant.id) : null
+ }
+ },
+ // Figma's deprecated reading of the variant properties: each one's values, in order.
+ variantGroupProperties: {
+ get(this: ProxyThis): ComponentSetNode['variantGroupProperties'] {
+ const set = raw(this, internals)
+ const variants = graph(this, internals)
+ .getChildren(set.id)
+ .filter((child) => child.type === 'COMPONENT')
+ return Object.fromEntries(
+ set.componentPropertyDefinitions
+ .filter((definition) => definition.type === 'VARIANT')
+ .map((definition) => [
+ definition.name,
+ // A file may leave the options out; the variants still hold their values.
+ {
+ values: definition.variantOptions
+ ? [...definition.variantOptions]
+ : uniq(
+ compact(
+ variants.map((variant) => variant.componentPropertyValues[definition.name])
+ )
+ )
+ }
+ ])
+ )
+ }
+ }
+ })
+}
diff --git a/packages/core/src/figma-api/accessors/guides.ts b/packages/core/src/figma-api/accessors/guides.ts
new file mode 100644
index 000000000..5d1811664
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/guides.ts
@@ -0,0 +1,78 @@
+import type { Guide } from '@figma/plugin-typings/plugin-api-standalone'
+
+import type { SceneNode } from '@open-pencil/scene-graph'
+import { newGuideId, type CanvasGuide } from '@open-pencil/scene-graph/guides'
+
+import {
+ raw,
+ updateNode,
+ type NodeProxyInternals,
+ type ProxyThis
+} from '#core/figma-api/accessor-utils'
+import { invalid, numberProblem, received } from '#core/figma-api/accessors/text/messages'
+
+const METHOD = 'set_guides'
+
+/** The layers Figma keeps guides for; installed on their proxies alone, as Figma has them. */
+const GUIDE_OWNER_TYPES: ReadonlySet<SceneNode['type']> = new Set([
+ 'CANVAS',
+ 'FRAME',
+ 'COMPONENT',
+ 'COMPONENT_SET',
+ 'INSTANCE'
+])
+
+function parseGuide(value: unknown, index: number): Guide {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw invalid(
+ METHOD,
+ `Expected object, received ${received(value)} at index ${index}`,
+ 'guides'
+ )
+ }
+ const { axis, offset } = value as { axis?: unknown; offset?: unknown }
+ if (axis !== 'X' && axis !== 'Y') {
+ throw invalid(METHOD, `Invalid option: expected one of "X"|"Y" at [${index}].axis`, 'guides')
+ }
+ const problem = numberProblem(offset, ` at [${index}].offset`)
+ if (problem) throw invalid(METHOD, problem, 'guides')
+ return { axis, offset: offset as number }
+}
+
+/**
+ * `guides` on pages and frames, as Figma keeps them for each (Figma desktop 126). A guide set at
+ * an index that had one keeps that guide's identity, so a saved file updates it in place.
+ */
+export function installGuideAccessors(
+ target: object,
+ internals: NodeProxyInternals,
+ type: SceneNode['type']
+): void {
+ if (!GUIDE_OWNER_TYPES.has(type)) return
+ Object.defineProperty(target, 'guides', {
+ get(this: ProxyThis): readonly Guide[] {
+ return Object.freeze(
+ raw(this, internals).guides.map((guide) =>
+ Object.freeze({ axis: guide.axis === 'x' ? 'X' : 'Y', offset: guide.position } as const)
+ )
+ )
+ },
+ set(this: ProxyThis, value: unknown) {
+ if (!Array.isArray(value)) {
+ throw invalid(METHOD, `Expected array, received ${received(value)}`, 'guides')
+ }
+ const parsed = value.map(parseGuide)
+ const current = raw(this, internals).guides
+ const guides = parsed.map(({ axis, offset }, index): CanvasGuide => {
+ const { id, figGuid } = current.at(index) ?? { id: newGuideId() }
+ return {
+ id,
+ axis: axis === 'X' ? 'x' : 'y',
+ position: offset,
+ ...(figGuid ? { figGuid } : {})
+ }
+ })
+ updateNode(this, internals, { guides })
+ }
+ })
+}
diff --git a/packages/core/src/figma-api/accessors/layout.ts b/packages/core/src/figma-api/accessors/layout.ts
index ef906b078..38137afdd 100644
--- a/packages/core/src/figma-api/accessors/layout.ts
+++ b/packages/core/src/figma-api/accessors/layout.ts
@@ -21,13 +21,20 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
+import { invalid, numberProblem, received } from '#core/figma-api/accessors/text/messages'
/** A guide in Figma's plugin shape, whether it was set that way or read from a file. */
function figmaLayoutGrid(grid: LayoutGrid): Readonly<LayoutGrid> {
const visible = grid.visible ?? true
const color = { ...(grid.color ?? { r: 1, g: 0, b: 0, a: 0.1 }) }
if (grid.pattern === 'GRID')
- return Object.freeze({ pattern: 'GRID', sectionSize: grid.sectionSize ?? 10, visible, color })
+ return Object.freeze({
+ pattern: 'GRID',
+ sectionSize: grid.sectionSize ?? 10,
+ visible,
+ color,
+ boundVariables: {}
+ })
const rows = grid.pattern === 'ROWS' || (grid.pattern !== 'COLUMNS' && grid.axis === 'Y')
const alignment = grid.alignment ?? grid.type ?? 'STRETCH'
return Object.freeze({
@@ -39,7 +46,8 @@ function figmaLayoutGrid(grid: LayoutGrid): Readonly<LayoutGrid> {
...(alignment === 'STRETCH' ? {} : { sectionSize: grid.sectionSize ?? 0 }),
offset: grid.offset ?? 0,
visible,
- color
+ color,
+ boundVariables: {}
})
}
@@ -67,7 +75,10 @@ export function installLayoutNodeProxyAccessors(
return Object.freeze(raw(this, internals).layoutGrids.map(figmaLayoutGrid))
},
set(this: ProxyThis, value: readonly LayoutGrid[]) {
- if (!Array.isArray(value)) throw new TypeError('layoutGrids must be an array')
+ if (!Array.isArray(value)) {
+ const problem = `Expected array, received ${received(value)}`
+ throw invalid('set_layoutGrids', problem, 'layoutGrids')
+ }
// An Auto count is stored as the archive stores it, so it survives copies and saves.
const grids = structuredClone([...value]).map((grid) =>
isAutoGridCount(grid.count) ? { ...grid, count: AUTO_LAYOUT_GRID_COUNT } : grid
@@ -79,10 +90,13 @@ export function installLayoutNodeProxyAccessors(
counterAxisAlignItems: mappedAccessor(internals, 'counterAxisAlign'),
itemSpacing: simpleAccessor(internals, 'itemSpacing'),
counterAxisSpacing: simpleAccessor(internals, 'counterAxisSpacing'),
- paddingTop: simpleAccessor(internals, 'paddingTop'),
- paddingRight: simpleAccessor(internals, 'paddingRight'),
- paddingBottom: simpleAccessor(internals, 'paddingBottom'),
- paddingLeft: simpleAccessor(internals, 'paddingLeft'),
+ paddingTop: padding(internals, 'paddingTop', ['paddingTop']),
+ paddingRight: padding(internals, 'paddingRight', ['paddingRight']),
+ paddingBottom: padding(internals, 'paddingBottom', ['paddingBottom']),
+ paddingLeft: padding(internals, 'paddingLeft', ['paddingLeft']),
+ // Figma's deprecated pairs read their first side and set both (Figma desktop 126).
+ horizontalPadding: padding(internals, 'horizontalPadding', ['paddingLeft', 'paddingRight']),
+ verticalPadding: padding(internals, 'verticalPadding', ['paddingTop', 'paddingBottom']),
layoutWrap: mappedAccessor(internals, 'layoutWrap'),
primaryAxisSizingMode: axisSizingModeAccessor(internals, 'primaryAxisSizing'),
counterAxisSizingMode: axisSizingModeAccessor(internals, 'counterAxisSizing'),
@@ -218,6 +232,28 @@ function layoutSizingAccessor(
}
}
+type PaddingSide = 'paddingTop' | 'paddingRight' | 'paddingBottom' | 'paddingLeft'
+
+/** A padding that reads its first side and sets each of `sides` to a finite number of 0 or more. */
+function padding(
+ internals: NodeProxyInternals,
+ property: string,
+ sides: readonly [PaddingSide, ...PaddingSide[]]
+): PropertyDescriptor {
+ return {
+ get(this: ProxyThis): number {
+ return raw(this, internals)[sides[0]]
+ },
+ set(this: ProxyThis, value: unknown) {
+ const problem =
+ numberProblem(value) ??
+ ((value as number) < 0 ? 'Too small: expected number to be >=0' : null)
+ if (problem) throw invalid(`set_${property}`, problem, property)
+ updateNode(this, internals, Object.fromEntries(sides.map((side) => [side, value])))
+ }
+ }
+}
+
function simpleAccessor(internals: NodeProxyInternals, field: keyof SceneNode): PropertyDescriptor {
return {
get(this: ProxyThis): unknown {
diff --git a/packages/core/src/figma-api/accessors/shape.ts b/packages/core/src/figma-api/accessors/shape.ts
index 450b8b2af..2f74467e0 100644
--- a/packages/core/src/figma-api/accessors/shape.ts
+++ b/packages/core/src/figma-api/accessors/shape.ts
@@ -1,6 +1,10 @@
import type { ArcData, SceneNode } from '@open-pencil/scene-graph'
+import { fitEnclosingGroups } from '@open-pencil/scene-graph/group-bounds'
import {
+ graph,
+ hostFitOptions,
+ nodeId,
raw,
updateNode,
type NodeProxyInternals,
@@ -11,6 +15,10 @@ import { invalid, numberProblem, received } from '#core/figma-api/accessors/text
/** Figma caps a polygon or star at this many points, past which it keeps the cap. */
const MAX_POINT_COUNT = 60
+type BooleanOperation = NonNullable<SceneNode['booleanOperation']>
+
+const BOOLEAN_OPERATIONS = new Set<BooleanOperation>(['UNION', 'INTERSECT', 'SUBTRACT', 'EXCLUDE'])
+
const ARC_FIELDS = ['startingAngle', 'endingAngle', 'innerRadius'] as const
/** Figma's complaint about a ratio outside 0 to 1, or null. */
@@ -59,9 +67,9 @@ function parseArcData(value: unknown): ArcData {
const WHOLE_ELLIPSE: ArcData = { startingAngle: 0, endingAngle: 2 * Math.PI, innerRadius: 0 }
/**
- * The members of Figma's `PolygonNode`, `StarNode`, and `EllipseNode` that shape them: a point
- * count, a star's inner radius, and an ellipse's arc. Installed on the proxies of those nodes
- * alone, as Figma has them on no other node.
+ * The members of Figma's `PolygonNode`, `StarNode`, `EllipseNode`, and `BooleanOperationNode`
+ * that shape them: a point count, a star's inner radius, an ellipse's arc, and a boolean's
+ * operation. Installed on the proxies of those nodes alone, as Figma has them on no other node.
*/
export function installShapeNodeProxyAccessors(
target: object,
@@ -88,6 +96,29 @@ export function installShapeNodeProxyAccessors(
}
})
}
+ if (type === 'BOOLEAN_OPERATION') {
+ Object.defineProperty(target, 'booleanOperation', {
+ get(this: ProxyThis): BooleanOperation {
+ return raw(this, internals).booleanOperation ?? 'UNION'
+ },
+ set(this: ProxyThis, value: unknown) {
+ if (!BOOLEAN_OPERATIONS.has(value as BooleanOperation)) {
+ throw invalid(
+ 'set_booleanOperation',
+ 'Invalid option: expected one of "UNION"|"INTERSECT"|"SUBTRACT"|"EXCLUDE"',
+ 'booleanOperation'
+ )
+ }
+ updateNode(this, internals, { booleanOperation: value as BooleanOperation })
+ // The result's bounds change with the operation, and the groups around it follow.
+ fitEnclosingGroups(
+ graph(this, internals),
+ [nodeId(this, internals)],
+ hostFitOptions(this, internals)
+ )
+ }
+ })
+ }
if (type === 'ELLIPSE') {
Object.defineProperty(target, 'arcData', {
get(this: ProxyThis): Readonly<ArcData> {
diff --git a/packages/core/src/figma-api/accessors/sticky.ts b/packages/core/src/figma-api/accessors/sticky.ts
index 9cb6e1fe9..04e34ab9f 100644
--- a/packages/core/src/figma-api/accessors/sticky.ts
+++ b/packages/core/src/figma-api/accessors/sticky.ts
@@ -23,7 +23,9 @@ import type { FigmaNodeProxy, NodeProxyHost } from '#core/figma-api/proxy'
*/
export function pluginChildren(sceneGraph: SceneGraph, id: string): SceneNode[] {
const node = sceneGraph.getNode(id)
- return node && isGeneratedFrame(node) ? [] : sceneGraph.getChildren(id)
+ if (node && isGeneratedFrame(node)) return []
+ // Pages and layers the document keeps out of view, such as its styles, are no plugin's.
+ return sceneGraph.getChildren(id).filter((child) => !child.internalOnly)
}
function sublayers(target: ProxyThis, internals: NodeProxyInternals) {
diff --git a/packages/core/src/figma-api/accessors/styles.ts b/packages/core/src/figma-api/accessors/styles.ts
new file mode 100644
index 000000000..5585843f3
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/styles.ts
@@ -0,0 +1,116 @@
+import { upperFirst } from 'es-toolkit/string'
+
+import type { SceneNode, SharedStyleKind } from '@open-pencil/scene-graph'
+import { sharedStyleRefKey } from '@open-pencil/scene-graph/shared-styles'
+
+import {
+ graph,
+ raw,
+ strokeOwner,
+ updateNode,
+ type NodeProxyInternals,
+ type ProxyThis
+} from '#core/figma-api/accessor-utils'
+import { invalid, received } from '#core/figma-api/accessors/text/messages'
+import { bindStylePaints, STYLE_NOT_FOUND, styleChanges } from '#core/figma-api/styles/apply'
+import { getTextStyle } from '#core/figma-api/text/style'
+
+/** Layers with frames' layout guides, which a grid style gives. */
+const GRID_STYLE_TYPES = new Set<SceneNode['type']>([
+ 'FRAME',
+ 'COMPONENT',
+ 'COMPONENT_SET',
+ 'INSTANCE'
+])
+
+/** The kinds of style a layer of `type` takes, as Figma's node types have them. */
+function styleKinds(type: SceneNode['type'], isDocument: boolean): SharedStyleKind[] {
+ if (isDocument || type === 'CANVAS') return []
+ const kinds: SharedStyleKind[] = type === 'GROUP' ? [] : ['fill', 'stroke']
+ kinds.push('effect')
+ if (GRID_STYLE_TYPES.has(type)) kinds.push('grid')
+ if (type === 'TEXT') kinds.push('text')
+ return kinds
+}
+
+/**
+ * Gives `target` the style, or refuses it with `refusal`. A stroke style goes to the layer that
+ * draws the strokes, a connector's line, and the layer binds to the variables its paints follow.
+ */
+function applyStyle(
+ target: ProxyThis,
+ internals: NodeProxyInternals,
+ kind: SharedStyleKind,
+ styleId: string,
+ refusal: string
+): void {
+ const holder = kind === 'stroke' ? strokeOwner(target, internals) : target
+ const scene = graph(target, internals)
+ const changes = styleChanges(scene, raw(holder, internals), kind, styleId)
+ if (!changes) throw new Error(refusal)
+ updateNode(holder, internals, changes)
+ bindStylePaints(scene, raw(holder, internals), kind, styleId)
+}
+
+function styleMembers(internals: NodeProxyInternals, kind: SharedStyleKind, mixed: symbol) {
+ const field = sharedStyleRefKey(kind)
+ return {
+ [field]: {
+ get(this: ProxyThis): string | symbol {
+ const node = raw(this, internals)
+ // Characters of a text can each use a text or fill style of their own.
+ if (node.type === 'TEXT' && (kind === 'text' || kind === 'fill')) {
+ return getTextStyle(node, kind === 'text' ? 'textStyleId' : 'fillStyleId', mixed) as
+ | string
+ | symbol
+ }
+ if (kind === 'stroke') return raw(strokeOwner(this, internals), internals)[field] ?? ''
+ return node[field] ?? ''
+ },
+ set(this: ProxyThis, value: unknown) {
+ const method = `set_${field}`
+ if (typeof value !== 'string') {
+ throw invalid(method, `Expected string, received ${received(value)}`, field)
+ }
+ applyStyle(this, internals, kind, value, `in ${method}: ${STYLE_NOT_FOUND}`)
+ }
+ },
+ // Figma takes anything but a string without a word, and rejects a style it cannot find.
+ [`set${upperFirst(field)}Async`]: {
+ async value(this: ProxyThis, value: unknown): Promise<void> {
+ if (typeof value === 'string') applyStyle(this, internals, kind, value, STYLE_NOT_FOUND)
+ }
+ }
+ }
+}
+
+/**
+ * The style references of a layer: `fillStyleId`, `strokeStyleId`, `effectStyleId`,
+ * `gridStyleId`, and `textStyleId`, each with its async setter, on the layers Figma has them on
+ * (Figma desktop 126). Setting one gives the layer the style's values; an empty ID takes the
+ * style off and keeps them.
+ */
+export function installStyleReferenceAccessors(
+ target: object,
+ internals: NodeProxyInternals,
+ type: SceneNode['type'],
+ isDocument: boolean,
+ mixed: symbol
+): void {
+ for (const kind of styleKinds(type, isDocument))
+ Object.defineProperties(target, styleMembers(internals, kind, mixed))
+ if (isDocument || !GRID_STYLE_TYPES.has(type)) return
+ // Figma's deprecated name for a frame's fill style.
+ Object.defineProperty(target, 'backgroundStyleId', {
+ get(this: ProxyThis): string {
+ return raw(this, internals).fillStyleId ?? ''
+ },
+ set(this: ProxyThis, value: unknown) {
+ const method = 'set_backgroundStyleId'
+ if (typeof value !== 'string') {
+ throw invalid(method, `Expected string, received ${received(value)}`, 'backgroundStyleId')
+ }
+ applyStyle(this, internals, 'fill', value, `in ${method}: ${STYLE_NOT_FOUND}`)
+ }
+ })
+}
diff --git a/packages/core/src/figma-api/accessors/text/decoration.ts b/packages/core/src/figma-api/accessors/text/decoration.ts
new file mode 100644
index 000000000..a37170e8d
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/text/decoration.ts
@@ -0,0 +1,130 @@
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import {
+ raw,
+ updateNode,
+ type NodeProxyInternals,
+ type ProxyThis
+} from '#core/figma-api/accessor-utils'
+import { assertTextFontsLoaded } from '#core/figma-api/fonts/loaded'
+import { getTextStyle, rangeHasUnderline } from '#core/figma-api/text/style'
+import { textStyleChanges, type TextStylePatch } from '#core/text/character-style'
+
+import { invalid, received } from './messages'
+import { DECORATION_STYLES, decorationColorFills, enumValue, lengthOrAuto, sized } from './values'
+
+/** The text properties that style an underline, as Figma names them. */
+export type DecorationField =
+ | 'textDecorationStyle'
+ | 'textDecorationOffset'
+ | 'textDecorationThickness'
+ | 'textDecorationColor'
+ | 'textDecorationSkipInk'
+
+/** How Figma names each property in its messages. */
+const NAMES: Record<DecorationField, string> = {
+ textDecorationStyle: 'style',
+ textDecorationOffset: 'offset',
+ textDecorationThickness: 'thickness',
+ textDecorationColor: 'color',
+ textDecorationSkipInk: 'skip ink'
+}
+
+/** What a value gives the characters it styles, checked as Figma checks it for `property`. */
+const PATCHES: Record<
+ DecorationField,
+ (method: string, value: unknown, property: string) => TextStylePatch
+> = {
+ textDecorationStyle: (method, value, property) => ({
+ textDecorationStyle: enumValue(method, value, DECORATION_STYLES, property)
+ }),
+ // Kept in pixels, so a percent gives characters of each size their own length.
+ textDecorationOffset: (method, value, property) => {
+ const length = sized(lengthOrAuto(method, value, property))
+ return (fontSize) => ({ textUnderlineOffset: length(fontSize) })
+ },
+ textDecorationThickness: (method, value, property) => {
+ const length = sized(lengthOrAuto(method, value, property))
+ return (fontSize) => ({ textDecorationThickness: length(fontSize) })
+ },
+ textDecorationColor: (method, value) => ({
+ textDecorationFills: decorationColorFills(method, value)
+ }),
+ textDecorationSkipInk: (method, value, property) => {
+ if (typeof value !== 'boolean')
+ throw invalid(method, `Expected boolean, received ${received(value)}`, property)
+ return { textDecorationSkipInk: value }
+ }
+}
+
+/** Underline styles apply to underlined text only; Figma refuses a range with none. */
+function assertUnderlined(
+ method: string,
+ field: DecorationField,
+ node: SceneNode,
+ start: number,
+ end: number
+): void {
+ if (!rangeHasUnderline(node, start, end)) {
+ throw new Error(
+ `in ${method}: Cannot set text decoration ${NAMES[field]} on a non-underlined text range`
+ )
+ }
+}
+
+/** The style a `setRangeTextDecoration*` method gives `text[start, end)`. */
+export function rangeDecorationPatch(
+ field: DecorationField,
+ method: string,
+ node: SceneNode,
+ start: number,
+ end: number,
+ value: unknown
+): TextStylePatch {
+ const patch = PATCHES[field](method, value, 'value')
+ assertUnderlined(method, field, node, start, end)
+ return patch
+}
+
+/**
+ * The node's underline style setters, which give every character the value. Each refuses text
+ * with no underline, as the range methods do, except skip ink, which Figma keeps for an underline
+ * added later (Figma desktop 126).
+ */
+function decorationAccessor(
+ internals: NodeProxyInternals,
+ field: DecorationField,
+ mixed: symbol
+): PropertyDescriptor {
+ return {
+ get(this: ProxyThis): unknown {
+ return getTextStyle(raw(this, internals), field, mixed)
+ },
+ set(this: ProxyThis, value: unknown) {
+ const method = `set_${field}`
+ const node = raw(this, internals)
+ const patch = PATCHES[field](method, value, field)
+ if (field !== 'textDecorationSkipInk')
+ assertUnderlined(method, field, node, 0, node.text.length)
+ // The colour is a paint, which Figma takes with the text's fonts unloaded.
+ if (field !== 'textDecorationColor') assertTextFontsLoaded(method, node)
+ const changes =
+ typeof patch === 'function'
+ ? textStyleChanges(node, patch(node.fontSize), patch)
+ : textStyleChanges(node, patch)
+ updateNode(this, internals, changes)
+ }
+ }
+}
+
+export function installTextDecorationAccessors(
+ prototype: object,
+ internals: NodeProxyInternals,
+ mixed: symbol
+): void {
+ const fields = Object.keys(NAMES) as DecorationField[]
+ Object.defineProperties(
+ prototype,
+ Object.fromEntries(fields.map((field) => [field, decorationAccessor(internals, field, mixed)]))
+ )
+}
diff --git a/packages/core/src/figma-api/accessors/text/hyperlink.ts b/packages/core/src/figma-api/accessors/text/hyperlink.ts
index 93bc3d105..791f32332 100644
--- a/packages/core/src/figma-api/accessors/text/hyperlink.ts
+++ b/packages/core/src/figma-api/accessors/text/hyperlink.ts
@@ -1,6 +1,6 @@
import type { HyperlinkTarget, NodeType, SceneGraph } from '@open-pencil/scene-graph'
-import { invalid, received } from './messages'
+import { invalid, invalidOption, noneMatched, received } from './messages'
const HYPERLINK_TYPES = new Set(['URL', 'NODE'])
@@ -23,26 +23,31 @@ const LINK_TARGETS = new Set<NodeType>([
/**
* A link Figma takes: a URL it supports or a layer it can show, or `null` to remove one. An
- * empty URL removes the link, as in Figma.
+ * empty URL removes the link, as in Figma. Figma names the value `hyperlink` in the range
+ * method's messages and `value` in the node setter's.
*/
export function hyperlinkTarget(
method: string,
value: unknown,
- graph: SceneGraph
+ graph: SceneGraph,
+ property: string
): HyperlinkTarget | null {
if (value === null) return null
- if (typeof value !== 'object' || Array.isArray(value)) {
- throw invalid(method, `Expected object, received ${received(value)}`)
- }
- const target = value as Partial<Record<keyof HyperlinkTarget, unknown>>
- if (!HYPERLINK_TYPES.has(target.type as string)) {
+ // Figma checks a link against a target and against null, and reports both.
+ const refuse: (problem: string) => never = (problem) => {
throw invalid(
method,
- `Invalid enum value. Expected 'URL' | 'NODE', received '${String(target.type)}' at .type`
+ noneMatched([problem, `Expected null, received ${received(value)}`]),
+ property
)
}
+ if (typeof value !== 'object' || Array.isArray(value))
+ refuse(`Expected object, received ${received(value)}`)
+ const target = value as Partial<Record<keyof HyperlinkTarget, unknown>>
+ if (!HYPERLINK_TYPES.has(target.type as string))
+ refuse(invalidOption(HYPERLINK_TYPES, ' at .type'))
if (typeof target.value !== 'string') {
- throw invalid(method, `Expected string, received ${received(target.value)} at .value`)
+ refuse(`Expected string, received ${received(target.value)} at .value`)
}
if (target.type === 'URL') {
if (target.value === '') return null
diff --git a/packages/core/src/figma-api/accessors/text/index.ts b/packages/core/src/figma-api/accessors/text/index.ts
index a65837cde..3e5bfadc1 100644
--- a/packages/core/src/figma-api/accessors/text/index.ts
+++ b/packages/core/src/figma-api/accessors/text/index.ts
@@ -1,5 +1,6 @@
import type {
HyperlinkTarget,
+ LeadingTrim,
SceneNode,
TextCase,
TextParagraphSpacingField
@@ -27,8 +28,12 @@ import {
import { getTextStyle, type TextSegmentField } from '#core/figma-api/text/style'
import { styleRunsWithPatch, textStyleChanges } from '#core/text/character-style'
+import { installTextDecorationAccessors } from './decoration'
import { hyperlinkTarget } from './hyperlink'
import { fontNameStyle } from './ranges'
+import { DECORATIONS, enumValue, fontSizeValue, textCaseValue } from './values'
+
+const LEADING_TRIMS = new Set<LeadingTrim>(['CAP_HEIGHT', 'NONE'])
/**
* Getter/setter pair for a spacing Figma keeps at zero or more. It reads `mixed` while paragraphs
@@ -118,22 +123,15 @@ export function installTextNodeProxyAccessors(
'fontName',
mixed,
(node, value) => {
- const style = fontNameStyle('set_fontName', node, 0, value)
+ const style = fontNameStyle('set_fontName', node, 0, value, 'fontName')
assertFontLoaded('set_fontName', node, style)
return style
},
false
),
- fontSize: characterStyle<number>(internals, 'fontSize', mixed, (_node, fontSize) => ({
- fontSize
+ fontSize: characterStyle<number>(internals, 'fontSize', mixed, (_node, value) => ({
+ fontSize: fontSizeValue('set_fontSize', value, 'fontSize')
})),
- textStyleId: characterStyle<string>(
- internals,
- 'textStyleId',
- mixed,
- (_node, value) => ({ textStyleId: value || null }),
- false
- ),
// A weight is a face of its own, which has to be loaded as a new font does.
fontWeight: characterStyle<number>(internals, 'fontWeight', mixed, (node, fontWeight) => {
const style = { fontWeight, fontStyle: null }
@@ -157,8 +155,8 @@ export function installTextNodeProxyAccessors(
mixed,
(_node, value) => ({ lineHeight: lineHeightValue(value) })
),
- textCase: characterStyle<TextCase>(internals, 'textCase', mixed, (_node, textCase) => ({
- textCase
+ textCase: characterStyle<TextCase>(internals, 'textCase', mixed, (_node, value) => ({
+ textCase: textCaseValue('set_textCase', value, 'textCase')
})),
hyperlink: {
get(this: ProxyThis): unknown {
@@ -166,7 +164,7 @@ export function installTextNodeProxyAccessors(
},
set(this: ProxyThis, value: HyperlinkTarget | null) {
const node = raw(this, internals)
- const hyperlink = hyperlinkTarget('set_hyperlink', value, graph(this, internals))
+ const hyperlink = hyperlinkTarget('set_hyperlink', value, graph(this, internals), 'value')
const styleRuns = styleRunsWithPatch(node, 0, node.text.length, { hyperlink })
updateNode(this, internals, { styleRuns })
}
@@ -175,14 +173,37 @@ export function installTextNodeProxyAccessors(
internals,
'textDecoration',
mixed,
- (_node, textDecoration) => ({ textDecoration })
+ (_node, value) => ({
+ textDecoration: enumValue('set_textDecoration', value, DECORATIONS, 'textDecoration')
+ })
),
maxLines: field(internals, 'maxLines'),
listSpacing: spacing(internals, 'listSpacing', mixed),
paragraphSpacing: spacing(internals, 'paragraphSpacing', mixed),
paragraphIndent: spacing(internals, 'paragraphIndent', mixed),
hangingList: field(internals, 'hangingList'),
+ leadingTrim: {
+ get(this: ProxyThis): LeadingTrim {
+ return raw(this, internals).leadingTrim
+ },
+ set(this: ProxyThis, value: unknown) {
+ const leadingTrim = enumValue('set_leadingTrim', value, LEADING_TRIMS, 'leadingTrim')
+ assertTextFontsLoaded('set_leadingTrim', raw(this, internals))
+ updateNode(this, internals, { leadingTrim })
+ }
+ },
+ // Figma reads the features characters set; assigning to it does nothing, as in Figma.
+ openTypeFeatures: {
+ get(this: ProxyThis): unknown {
+ const features = getTextStyle(raw(this, internals), 'openTypeFeatures', mixed)
+ return typeof features === 'symbol' ? features : Object.freeze(features)
+ },
+ set() {
+ // Figma ignores the assignment without an error.
+ }
+ },
textTruncation: field(internals, 'textTruncation'),
autoRename: field(internals, 'autoRename', false)
})
+ installTextDecorationAccessors(prototype, internals, mixed)
}
diff --git a/packages/core/src/figma-api/accessors/text/messages.ts b/packages/core/src/figma-api/accessors/text/messages.ts
index 8d7eec183..4fd8d4d81 100644
--- a/packages/core/src/figma-api/accessors/text/messages.ts
+++ b/packages/core/src/figma-api/accessors/text/messages.ts
@@ -1,19 +1,55 @@
+// Figma's validation messages, worded as its plugin API words them (Figma desktop 126).
+
/** Figma's message for a value its schema rejects. */
export function invalid(method: string, problem: string, property = 'value'): Error {
return new Error(`in ${method}: Property "${property}" failed validation: ${problem}`)
}
export function received(value: unknown): string {
- if (typeof value === 'number' && Number.isNaN(value)) return 'nan'
+ // Figma names NaN and the infinities rather than calling them numbers.
+ if (typeof value === 'number' && !Number.isFinite(value)) return String(value)
if (Array.isArray(value)) return 'array'
return value === null ? 'null' : typeof value
}
-/** Figma's complaint about `value` as a number at `at`, or null when it is one. */
+/** Figma's complaint about `value` as a finite number at `at`, or null when it is one. */
export function numberProblem(value: unknown, at = ''): string | null {
- if (typeof value === 'number' && !Number.isNaN(value)) return null
+ if (typeof value === 'number' && Number.isFinite(value)) return null
if (value === undefined) return `Required value missing${at}`
- // Shape and size setters spell it as JavaScript does, unlike the text ones `received` follows.
- const kind = Number.isNaN(value) ? 'NaN' : received(value)
- return `Expected number, received ${kind}${at}`
+ return `Expected number, received ${received(value)}${at}`
+}
+
+/** A value outside a fixed list of options. */
+export function invalidOption(options: Iterable<string>, at = ''): string {
+ return `Invalid option: expected one of ${[...options].map((option) => `"${option}"`).join('|')}${at}`
+}
+
+export function tooSmall(minimum: number, at = ''): string {
+ return `Too small: expected number to be >=${minimum}${at}`
+}
+
+export function tooBig(maximum: number, at = ''): string {
+ return `Too big: expected number to be <=${maximum}${at}`
+}
+
+/** A literal value, such as a paint type, that the input does not match. */
+export function invalidLiteral(expected: string, at = ''): string {
+ return `Invalid input: expected "${expected}"${at}`
+}
+
+/** Keys an object Figma checks strictly does not know, or null when there are none. */
+export function unrecognizedKeys(
+ value: object,
+ known: ReadonlySet<string>,
+ at = ''
+): string | null {
+ const unknown = Object.keys(value).filter((key) => !known.has(key))
+ if (unknown.length === 0) return null
+ const names = unknown.map((key) => `"${key}"`).join(', ')
+ return `${unknown.length === 1 ? 'Unrecognized key' : 'Unrecognized keys'}: ${names}${at}`
+}
+
+/** A choice between shapes that none of them matches, each listing its own problem. */
+export function noneMatched(problems: readonly string[]): string {
+ return `Expected one of the following, but none matched:\n${problems.map((problem) => ` ${problem}`).join('\n')}`
}
diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.ts
index 8d188d3ae..7871221e2 100644
--- a/packages/core/src/figma-api/accessors/text/ranges.ts
+++ b/packages/core/src/figma-api/accessors/text/ranges.ts
@@ -1,18 +1,16 @@
+import type { TextListOptions } from '@figma/plugin-typings/plugin-api-standalone'
import { uniqBy } from 'es-toolkit/array'
import type {
CharacterStyleOverride,
- Fill,
HyperlinkTarget,
SceneGraph,
SceneNode,
TextBindableField,
TextCase,
TextDecoration,
- TextDecorationStyle,
- TextLength
+ TextDecorationStyle
} from '@open-pencil/scene-graph'
-import { textLengthPixels } from '@open-pencil/scene-graph/text'
import {
assertProxyEditable,
@@ -33,7 +31,7 @@ import {
readVariationSettings,
type FigmaVariationSettings
} from '#core/figma-api/fonts/variations'
-import { parseFigmaPaints, type FigmaPaint } from '#core/figma-api/paints'
+import type { FigmaPaint } from '#core/figma-api/paints'
import {
getRangeIndentation,
getRangeListOptions,
@@ -47,7 +45,6 @@ import {
assertTextRange,
getRangeTextStyle,
getStyledTextSegments,
- rangeHasUnderline,
type FigmaDecorationColor,
type FigmaTextLength,
type StyledTextSegment,
@@ -62,93 +59,21 @@ import {
} from '#core/text/character-style'
import { textStyleName } from '#core/text/font/names'
+import { rangeDecorationPatch, type DecorationField } from './decoration'
import { hyperlinkTarget } from './hyperlink'
-import { invalid, received } from './messages'
+import { invalid, received, unrecognizedKeys } from './messages'
import { installTextReferenceMethods } from './references'
-
-const DECORATIONS = new Set<TextDecoration>(['NONE', 'UNDERLINE', 'STRIKETHROUGH'])
-const DECORATION_STYLES = new Set<TextDecorationStyle>(['SOLID', 'DOTTED', 'WAVY'])
-const LENGTH_UNITS = new Set(['PIXELS', 'PERCENT'])
-const TEXT_CASES = new Set<TextCase>(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'])
-/** Text cases Figma takes that OpenPencil cannot draw yet. */
-const SMALL_CAPS = new Set(['SMALL_CAPS', 'SMALL_CAPS_FORCED'])
-const PAINT_TYPES = new Set([
- 'SOLID',
- 'SHADER',
- 'GRADIENT_LINEAR',
- 'GRADIENT_RADIAL',
- 'GRADIENT_ANGULAR',
- 'GRADIENT_DIAMOND',
- 'IMAGE',
- 'VIDEO'
-])
-const SOLID_PAINT_KEYS = new Set([
- 'type',
- 'color',
- 'opacity',
- 'visible',
- 'blendMode',
- 'boundVariables'
-])
-
-function numberProblem(value: unknown, at = ''): string | null {
- if (value === undefined) return `Required value missing${at}`
- if (typeof value !== 'number' || Number.isNaN(value)) {
- return `Expected number, received ${received(value)}${at}`
- }
- return null
-}
-
-/** A length in pixels for a font size: a percent is of the size of the characters it styles. */
-type SizedLength<T> = (fontSize: number) => T
-
-function lengthFor(value: { unit: 'PIXELS' | 'PERCENT'; value: number }): TextLength {
- return { unit: value.unit, value: value.value }
-}
-
-/** `length` in pixels at the size of the characters it styles, for fields kept in pixels. */
-function sized(length: TextLength | null): SizedLength<number | null> {
- return (fontSize) => length && textLengthPixels(length, fontSize)
-}
-
-/** A letter spacing Figma takes: pixels or percent, never automatic. */
-function letterSpacingLength(method: string, value: unknown): TextLength {
- const length = value as Partial<FigmaTextLength & { value: number }> | null
- if (!length || typeof length !== 'object') {
- throw invalid(method, `Expected object, received ${received(value)}`)
- }
- if (!LENGTH_UNITS.has(String(length.unit))) {
- throw invalid(
- method,
- `Invalid enum value. Expected 'PIXELS' | 'PERCENT', received '${String(length.unit)}' at .unit`
- )
- }
- const problem = numberProblem(length.value, ' at .value')
- if (problem) throw invalid(method, problem)
- return lengthFor(length as { unit: 'PIXELS' | 'PERCENT'; value: number })
-}
-
-/** A length that may also be automatic, as line heights and decoration sizes are. */
-function lengthOrAuto(method: string, value: unknown): TextLength | null {
- const length = value as Partial<FigmaTextLength & { value: number }> | null
- if (!length || typeof length !== 'object') {
- throw invalid(method, `Expected object, received ${received(value)}`)
- }
- if (length.unit === 'AUTO') return null
- if (!LENGTH_UNITS.has(String(length.unit))) {
- throw invalid(
- method,
- `Invalid discriminator value. Expected 'PIXELS' | 'PERCENT' | 'AUTO' at .unit`
- )
- }
- const problem = numberProblem(length.value, ' at .value')
- if (problem) throw invalid(method, problem)
- return lengthFor(length as { unit: 'PIXELS' | 'PERCENT'; value: number })
-}
-
-function stringProblem(value: unknown, at: string): string | null {
- return typeof value === 'string' ? null : `Expected string, received ${received(value)} at ${at}`
-}
+import {
+ DECORATIONS,
+ enumValue,
+ fillsFromPaints,
+ fontSizeValue,
+ lengthOrAuto,
+ letterSpacingLength,
+ stringProblem,
+ textCaseValue,
+ variationSettingsProblem
+} from './values'
/** The font Figma reads for the character at `index`, as a font name left out reads from. */
/** The font of the character at `index`, and the axes it sets itself. */
@@ -172,21 +97,25 @@ function currentFont(node: SceneNode, index: number): CurrentFont {
* A font name Figma takes: a family, and a style and variation settings that may be left out, as
* in `FontNameInput`. What is left out reads from the font of the character at `start`.
*/
+const FONT_NAME_KEYS = new Set(['family', 'style', 'variationSettings'])
+
export function fontNameStyle(
method: string,
node: SceneNode,
start: number,
- value: unknown
+ value: unknown,
+ property = 'value'
): CharacterStyleOverride {
if (!value || typeof value !== 'object') {
- throw invalid(method, `Expected object, received ${received(value)}`)
+ throw invalid(method, `Expected object, received ${received(value)}`, property)
}
const fontName = value as Partial<Record<keyof FigmaFontName, unknown>>
const problem =
stringProblem(fontName.family, '.family') ??
(fontName.style === undefined ? null : stringProblem(fontName.style, '.style')) ??
- variationSettingsProblem(fontName.variationSettings)
- if (problem) throw invalid(method, problem)
+ variationSettingsProblem(fontName.variationSettings) ??
+ unrecognizedKeys(value, FONT_NAME_KEYS)
+ if (problem) throw invalid(method, problem, property)
return fontNameInputStyle(
method,
{
@@ -198,123 +127,6 @@ export function fontNameStyle(
)
}
-/** Variation settings Figma takes: numbers by axis tag. */
-function variationSettingsProblem(value: unknown): string | null {
- if (value === undefined) return null
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
- return `Expected object, received ${received(value)} at .variationSettings`
- }
- for (const [tag, setting] of Object.entries(value)) {
- const problem = numberProblem(setting, ` at .variationSettings.${tag}`)
- if (problem) return problem
- }
- return null
-}
-
-/** A number from 0 to 1, as Figma takes colour channels and opacity. */
-function unitProblem(value: unknown, at: string): string | null {
- const problem = numberProblem(value, ` at ${at}`)
- if (problem) return problem
- if ((value as number) < 0) return `Number must be greater than or equal to 0 at ${at}`
- if ((value as number) > 1) return `Number must be less than or equal to 1 at ${at}`
- return null
-}
-
-/** A solid paint's colour and opacity as Figma checks them; a colour's alpha may be left out. */
-function solidPaintProblem(paint: { color?: unknown; opacity?: unknown }, at: string) {
- const { color, opacity } = paint
- if (color === undefined) return `Required value missing at ${at}.color`
- if (!color || typeof color !== 'object') {
- return `Expected object, received ${received(color)} at ${at}.color`
- }
- const channels = color as Partial<Record<'r' | 'g' | 'b' | 'a', unknown>>
- for (const channel of ['r', 'g', 'b', 'a'] as const) {
- if (channel === 'a' && channels.a === undefined) continue
- const problem = unitProblem(channels[channel], `${at}.color.${channel}`)
- if (problem) return problem
- }
- return opacity === undefined ? null : unitProblem(opacity, `${at}.opacity`)
-}
-
-function paintProblem(paint: unknown, index: number): string | null {
- if (!paint || typeof paint !== 'object') {
- return `Expected object, received ${received(paint)} at index ${index}`
- }
- const { type } = paint as { type?: unknown }
- if (!PAINT_TYPES.has(type as string)) {
- return `Invalid discriminator value. Expected ${[...PAINT_TYPES].map((name) => `'${name}'`).join(' | ')} at [${index}].type`
- }
- return type === 'SOLID' ? solidPaintProblem(paint, `[${index}]`) : null
-}
-
-function fillsFromPaints(method: string, value: unknown): CharacterStyleOverride['fills'] {
- if (!Array.isArray(value)) throw invalid(method, `Expected array, received ${received(value)}`)
- for (const [index, paint] of value.entries()) {
- const problem = paintProblem(paint, index)
- if (problem) throw invalid(method, problem)
- }
- return parseFigmaPaints(value, method, 'value')
-}
-
-/**
- * A decoration colour Figma takes: `AUTO`, or a solid paint. A paint matching but for keys it
- * does not know reports only those; any other is reported against both choices.
- */
-function decorationColorFills(method: string, value: unknown): Fill[] {
- const color = (value as { value?: unknown } | null)?.value
- if (color === 'AUTO') return []
- const issues: string[] = []
- if (!color || typeof color !== 'object') {
- issues.push(`Expected object, received ${received(color)} at .value`)
- } else {
- const paint = color as Partial<Record<'type' | 'color', unknown>>
- if (paint.type !== 'SOLID')
- issues.push('Invalid literal value, expected "SOLID" at .value.type')
- if (paint.color === undefined) issues.push('Required value missing at .value.color')
- else if (!paint.color || typeof paint.color !== 'object') {
- issues.push(`Expected object, received ${received(paint.color)} at .value.color`)
- }
- const unknown = Object.keys(paint).filter((key) => !SOLID_PAINT_KEYS.has(key))
- if (unknown.length > 0) {
- const keys = unknown.map((key) => `'${key}'`).join(', ')
- if (issues.length === 0) {
- throw invalid(
- method,
- `Unrecognized key(s) in object: ${keys} at .value`,
- 'textDecorationColor'
- )
- }
- issues.push(`Unrecognized key(s) in object: ${keys} at .value`)
- }
- }
- if (issues.length === 0) {
- // A solid paint whose channels are out of range fails on them alone.
- const problem = solidPaintProblem(color as { color?: unknown; opacity?: unknown }, '.value')
- if (problem) throw invalid(method, problem, 'textDecorationColor')
- return parseFigmaPaints([color], method, 'textDecorationColor')
- }
- const paintIssues =
- issues.length === 1
- ? ` ${issues[0]}`
- : ` Multiple issues:\n${issues.map((issue) => ` ${issue}`).join('\n')}`
- throw invalid(
- method,
- `Expected one of the following, but none matched:\n${paintIssues}\n` +
- ' Invalid literal value, expected "AUTO" at .value',
- 'textDecorationColor'
- )
-}
-
-function enumValue<T extends string>(method: string, value: unknown, allowed: ReadonlySet<T>): T {
- if (!(allowed as ReadonlySet<unknown>).has(value)) {
- throw invalid(
- method,
- `Invalid enum value. Expected ${[...allowed].map((name) => `'${name}'`).join(' | ')}, received '${String(value)}'`
- )
- }
- return value as T
-}
-
type RangeSetter = (
method: string,
node: SceneNode,
@@ -324,30 +136,17 @@ type RangeSetter = (
graph: SceneGraph
) => TextStylePatch
-/** Decoration styles only apply to underlined text; Figma rejects a range with none. */
-function underlineStyle(
- name: string,
- patch: (method: string, value: unknown) => TextStylePatch
-): RangeSetter {
- return (method, node, start, end, value) => {
- const style = patch(method, value)
- if (!rangeHasUnderline(node, start, end)) {
- throw new Error(
- `in ${method}: Cannot set text decoration ${name} on a non-underlined text range`
- )
- }
- return style
- }
+/** A `setRangeTextDecoration*` method's setter. */
+function underlineStyle(field: DecorationField): RangeSetter {
+ return (method, node, start, end, value) =>
+ rangeDecorationPatch(field, method, node, start, end, value)
}
/** Range setters by method, each returning the style it gives the range. */
const RANGE_SETTERS: Record<string, RangeSetter> = {
- setRangeFontSize: (method, _node, _start, _end, value) => {
- const problem = numberProblem(value)
- if (problem) throw invalid(method, problem)
- if ((value as number) < 1) throw invalid(method, 'Number must be greater than or equal to 1')
- return { fontSize: value as number }
- },
+ setRangeFontSize: (method, _node, _start, _end, value) => ({
+ fontSize: fontSizeValue(method, value)
+ }),
setRangeFontName: (method, node, start, _end, value) => {
const style = fontNameStyle(method, node, start, value)
assertFontLoaded(method, node, style)
@@ -366,39 +165,16 @@ const RANGE_SETTERS: Record<string, RangeSetter> = {
setRangeTextDecoration: (method, _node, _start, _end, value) => ({
textDecoration: enumValue(method, value, DECORATIONS)
}),
- setRangeTextDecorationStyle: underlineStyle('style', (method, value) => ({
- textDecorationStyle: enumValue(method, value, DECORATION_STYLES)
- })),
- setRangeTextDecorationOffset: underlineStyle('offset', (method, value) => {
- const length = sized(lengthOrAuto(method, value))
- return (fontSize) => ({ textUnderlineOffset: length(fontSize) })
- }),
- setRangeTextDecorationThickness: underlineStyle('thickness', (method, value) => {
- const length = sized(lengthOrAuto(method, value))
- return (fontSize) => ({ textDecorationThickness: length(fontSize) })
- }),
- setRangeTextDecorationColor: underlineStyle('color', (method, value) => ({
- textDecorationFills: decorationColorFills(method, value)
- })),
- setRangeTextDecorationSkipInk: underlineStyle('skip ink', (method, value) => {
- if (typeof value !== 'boolean')
- throw invalid(method, `Expected boolean, received ${received(value)}`)
- return { textDecorationSkipInk: value }
+ setRangeTextDecorationStyle: underlineStyle('textDecorationStyle'),
+ setRangeTextDecorationOffset: underlineStyle('textDecorationOffset'),
+ setRangeTextDecorationThickness: underlineStyle('textDecorationThickness'),
+ setRangeTextDecorationColor: underlineStyle('textDecorationColor'),
+ setRangeTextDecorationSkipInk: underlineStyle('textDecorationSkipInk'),
+ setRangeTextCase: (method, _node, _start, _end, value) => ({
+ textCase: textCaseValue(method, value, 'textCase')
}),
- setRangeTextCase: (method, _node, _start, _end, value) => {
- if (SMALL_CAPS.has(value as string)) {
- throw new Error(`in ${method}: OpenPencil does not support the ${String(value)} text case`)
- }
- if (!TEXT_CASES.has(value as TextCase)) {
- throw invalid(
- method,
- `Invalid enum value. Expected ${[...TEXT_CASES, ...SMALL_CAPS].map((name) => `'${name}'`).join(' | ')}, received '${String(value)}'`
- )
- }
- return { textCase: value as TextCase }
- },
setRangeHyperlink: (method, _node, _start, _end, value, graph) => ({
- hyperlink: hyperlinkTarget(method, value, graph)
+ hyperlink: hyperlinkTarget(method, value, graph, 'hyperlink')
})
}
diff --git a/packages/core/src/figma-api/accessors/text/references.ts b/packages/core/src/figma-api/accessors/text/references.ts
index 4f6f8e9f4..810ef132f 100644
--- a/packages/core/src/figma-api/accessors/text/references.ts
+++ b/packages/core/src/figma-api/accessors/text/references.ts
@@ -5,6 +5,7 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
+import { STYLE_NOT_FOUND } from '#core/figma-api/styles/apply'
import { setRangeParagraphSpacing } from '#core/figma-api/text'
import {
assertTextBindableField,
@@ -35,19 +36,27 @@ export function installTextReferenceMethods(
mixed: symbol
): void {
for (const [method, kind] of Object.entries(SHARED_STYLE_SETTERS)) {
- const set = function (this: ProxyThis, start: number, end: number, styleId: unknown) {
+ // The async methods reject with Figma's message alone, as its own do.
+ const set = function (
+ this: ProxyThis,
+ start: number,
+ end: number,
+ styleId: unknown,
+ async = false
+ ) {
const node = raw(this, internals)
if (typeof styleId !== 'string') {
throw invalid(method, `Expected string, received ${received(styleId)}`, 'styleId')
}
assertTextRange(method, node, start, end)
const patch = rangeSharedStylePatch(graph(this, internals), kind, styleId)
+ if (!patch) throw new Error(async ? STYLE_NOT_FOUND : `in ${method}: ${STYLE_NOT_FOUND}`)
updateNode(this, internals, { styleRuns: styleRunsWithPatch(node, start, end, patch) })
}
methods[method] = {
value: method.endsWith('Async')
? async function (this: ProxyThis, start: number, end: number, styleId: unknown) {
- set.call(this, start, end, styleId)
+ set.call(this, start, end, styleId, true)
}
: set
}
diff --git a/packages/core/src/figma-api/accessors/text/values.ts b/packages/core/src/figma-api/accessors/text/values.ts
new file mode 100644
index 000000000..404d23481
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/text/values.ts
@@ -0,0 +1,207 @@
+import type {
+ CharacterStyleOverride,
+ Fill,
+ TextCase,
+ TextDecoration,
+ TextDecorationStyle,
+ TextLength
+} from '@open-pencil/scene-graph'
+import { textLengthPixels } from '@open-pencil/scene-graph/text'
+
+import { parseFigmaPaints } from '#core/figma-api/paints'
+
+import {
+ invalid,
+ invalidLiteral,
+ invalidOption,
+ noneMatched,
+ numberProblem,
+ received,
+ tooBig,
+ tooSmall,
+ unrecognizedKeys
+} from './messages'
+
+// The values text setters take, checked as Figma checks them, with its messages.
+
+export const DECORATIONS = new Set<TextDecoration>(['NONE', 'UNDERLINE', 'STRIKETHROUGH'])
+export const DECORATION_STYLES = new Set<TextDecorationStyle>(['SOLID', 'DOTTED', 'WAVY'])
+const LENGTH_UNITS = new Set(['PIXELS', 'PERCENT'])
+const LENGTH_KEYS = new Set(['unit', 'value'])
+const TEXT_CASES = new Set<TextCase>(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'])
+/** Text cases Figma takes that OpenPencil cannot draw yet. */
+const SMALL_CAPS = new Set(['SMALL_CAPS', 'SMALL_CAPS_FORCED'])
+const SOLID_PAINT_KEYS = new Set([
+ 'type',
+ 'color',
+ 'opacity',
+ 'visible',
+ 'blendMode',
+ 'boundVariables'
+])
+
+function isLengthUnit(unit: unknown): unit is 'PIXELS' | 'PERCENT' {
+ return typeof unit === 'string' && LENGTH_UNITS.has(unit)
+}
+
+/** A length in pixels for a font size: a percent is of the size of the characters it styles. */
+export type SizedLength<T> = (fontSize: number) => T
+
+/** `length` in pixels at the size of the characters it styles, for fields kept in pixels. */
+export function sized(length: TextLength | null): SizedLength<number | null> {
+ return (fontSize) => length && textLengthPixels(length, fontSize)
+}
+
+/** A font size Figma takes: a number of at least 1. */
+export function fontSizeValue(method: string, value: unknown, property = 'value'): number {
+ const problem = numberProblem(value) ?? ((value as number) < 1 ? tooSmall(1) : null)
+ if (problem) throw invalid(method, problem, property)
+ return value as number
+}
+
+/** A `{ unit, value }` length, its unit one of `units`; Figma knows no other keys. */
+function length(
+ method: string,
+ value: unknown,
+ property: string,
+ unitProblem: (unit: unknown) => string | null
+): TextLength {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw invalid(method, `Expected object, received ${received(value)}`, property)
+ }
+ const { unit, value: amount } = value as { unit?: unknown; value?: unknown }
+ const problem =
+ unitProblem(unit) ?? numberProblem(amount, ' at .value') ?? unrecognizedKeys(value, LENGTH_KEYS)
+ if (problem) throw invalid(method, problem, property)
+ return { unit: unit as TextLength['unit'], value: amount as number }
+}
+
+/** A letter spacing Figma takes: pixels or percent, never automatic. */
+export function letterSpacingLength(
+ method: string,
+ value: unknown,
+ property = 'value'
+): TextLength {
+ return length(method, value, property, (unit) =>
+ isLengthUnit(unit) ? null : invalidOption(LENGTH_UNITS, ' at .unit')
+ )
+}
+
+/** A length that may also be automatic, as line heights and decoration sizes are. */
+export function lengthOrAuto(
+ method: string,
+ value: unknown,
+ property = 'value'
+): TextLength | null {
+ if (value && typeof value === 'object' && (value as { unit?: unknown }).unit === 'AUTO') {
+ const problem = unrecognizedKeys(value, new Set(['unit']))
+ if (problem) throw invalid(method, problem, property)
+ return null
+ }
+ return length(method, value, property, (unit) =>
+ isLengthUnit(unit) ? null : 'Expected .unit to be one of the following: PIXELS, PERCENT, AUTO'
+ )
+}
+
+export function stringProblem(value: unknown, at: string): string | null {
+ return typeof value === 'string' ? null : `Expected string, received ${received(value)} at ${at}`
+}
+
+/** Variation settings Figma takes: numbers by axis tag. */
+export function variationSettingsProblem(value: unknown): string | null {
+ if (value === undefined) return null
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ return `Expected record, received ${received(value)} at .variationSettings`
+ }
+ for (const [tag, setting] of Object.entries(value)) {
+ const problem = numberProblem(setting, ` at .variationSettings.${tag}`)
+ if (problem) return problem
+ }
+ return null
+}
+
+/** A number from 0 to 1, as Figma takes colour channels and opacity. */
+function unitProblem(value: unknown, at: string): string | null {
+ const problem = numberProblem(value, ` at ${at}`)
+ if (problem) return problem
+ if ((value as number) < 0) return tooSmall(0, ` at ${at}`)
+ if ((value as number) > 1) return tooBig(1, ` at ${at}`)
+ return null
+}
+
+/** A solid paint's colour and opacity as Figma checks them; a colour's alpha may be left out. */
+function solidPaintProblem(paint: { color?: unknown; opacity?: unknown }, at: string) {
+ const { color, opacity } = paint
+ const channels = color as Partial<Record<'r' | 'g' | 'b' | 'a', unknown>>
+ for (const channel of ['r', 'g', 'b', 'a'] as const) {
+ if (channel === 'a' && channels.a === undefined) continue
+ const problem = unitProblem(channels[channel], `${at}.color.${channel}`)
+ if (problem) return problem
+ }
+ return opacity === undefined ? null : unitProblem(opacity, `${at}.opacity`)
+}
+
+/** A range's fills, checked as `fills` checks them. */
+export function fillsFromPaints(method: string, value: unknown): CharacterStyleOverride['fills'] {
+ return parseFigmaPaints(value, method, 'value')
+}
+
+/**
+ * A decoration colour Figma takes: `AUTO`, or a solid paint. A solid paint wrong only in its
+ * values or its keys reports just that; any other input is reported against both choices.
+ */
+export function decorationColorFills(method: string, value: unknown): Fill[] {
+ const color = (value as { value?: unknown } | null)?.value
+ if (color === 'AUTO') return []
+ const issues: string[] = []
+ if (!color || typeof color !== 'object') {
+ issues.push(`Expected object, received ${received(color)} at .value`)
+ } else {
+ const paint = color as Partial<Record<'type' | 'color', unknown>>
+ if (paint.type !== 'SOLID') issues.push(invalidLiteral('SOLID', ' at .value.type'))
+ if (paint.color === undefined) issues.push('Required value missing at .value.color')
+ else if (!paint.color || typeof paint.color !== 'object') {
+ issues.push(`Expected object, received ${received(paint.color)} at .value.color`)
+ }
+ const unknown = unrecognizedKeys(paint, SOLID_PAINT_KEYS, ' at .value')
+ if (unknown && issues.length === 0) throw invalid(method, unknown, 'textDecorationColor')
+ if (unknown) issues.push(unknown)
+ }
+ if (issues.length === 0) {
+ const problem = solidPaintProblem(color as { color?: unknown; opacity?: unknown }, '.value')
+ if (problem) throw invalid(method, problem, 'textDecorationColor')
+ return parseFigmaPaints([color], method, 'textDecorationColor')
+ }
+ const paintProblem =
+ issues.length === 1
+ ? issues[0]
+ : `Multiple issues:\n${issues.map((issue) => ` ${issue}`).join('\n')}`
+ throw invalid(
+ method,
+ noneMatched([paintProblem, invalidLiteral('AUTO', ' at .value')]),
+ 'textDecorationColor'
+ )
+}
+
+/** A text case Figma takes; it takes small caps too, which OpenPencil cannot draw yet. */
+export function textCaseValue(method: string, value: unknown, property = 'value'): TextCase {
+ if (SMALL_CAPS.has(value as string)) {
+ throw new Error(`in ${method}: OpenPencil does not support the ${String(value)} text case`)
+ }
+ if (!TEXT_CASES.has(value as TextCase)) {
+ throw invalid(method, invalidOption([...TEXT_CASES, ...SMALL_CAPS]), property)
+ }
+ return value as TextCase
+}
+
+export function enumValue<T extends string>(
+ method: string,
+ value: unknown,
+ allowed: ReadonlySet<T>,
+ property = 'value'
+): T {
+ if (!(allowed as ReadonlySet<unknown>).has(value)) {
+ throw invalid(method, invalidOption(allowed), property)
+ }
+ return value as T
+}
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index 51e6c9bd2..a944f993a 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -17,32 +17,6 @@ import { getTextStyle } from '#core/figma-api/text/style'
import { paintBindings, setPaintBindings } from '#core/figma-api/variables/bindings'
import { textStyleChanges } from '#core/text/character-style'
-function styleReference(
- internals: NodeProxyInternals,
- field: 'fillStyleId' | 'strokeStyleId' | 'effectStyleId' | 'gridStyleId',
- mixed: symbol
-): PropertyDescriptor {
- return {
- get(this: ProxyThis): string | symbol {
- const node = raw(this, internals)
- // Characters of a text can each use a fill style of their own.
- if (field === 'fillStyleId' && node.type === 'TEXT') {
- return getTextStyle(node, 'fillStyleId', mixed) as string | symbol
- }
- return node[field] ?? ''
- },
- set(this: ProxyThis, value: string) {
- const node = raw(this, internals)
- const changes = { [field]: value || null }
- updateNode(
- this,
- internals,
- field === 'fillStyleId' && node.type === 'TEXT' ? textStyleChanges(node, changes) : changes
- )
- }
- }
-}
-
/**
* `node`'s fills as Figma's plugin API reads them, bound colours resolved and carrying the
* variable they are bound to.
@@ -64,6 +38,45 @@ export function figmaStrokes(sceneGraph: SceneGraph, node: SceneNode): FigmaPain
return strokes.map((stroke, index) => toFigmaPaint(stroke, bound.get(index)))
}
+function setFills(
+ target: ProxyThis,
+ internals: NodeProxyInternals,
+ value: readonly FigmaPaint[],
+ method: string
+): void {
+ const node = raw(target, internals)
+ const fills = parseFigmaPaints(value, method)
+ updateNode(
+ target,
+ internals,
+ node.type === 'TEXT' ? textStyleChanges(node, { fills }) : { fills }
+ )
+ setPaintBindings(graph(target, internals), raw(target, internals), 'fills', value)
+}
+
+/** Figma paints carry no geometry; a stroke takes the weight and alignment the node keeps. */
+function setStrokes(
+ target: ProxyThis,
+ internals: NodeProxyInternals,
+ value: readonly FigmaPaint[],
+ method: string
+): void {
+ const owner = strokeOwner(target, internals)
+ const geometry = newStrokeGeometry(raw(owner, internals))
+ const strokes = parseFigmaPaints(value, method, 'strokes').map((paint): Stroke => ({
+ ...paint,
+ weight: geometry.weight,
+ align: geometry.align
+ }))
+ const kept = newStrokeGeometry({
+ strokes,
+ strokeWeight: geometry.weight,
+ strokeAlign: geometry.align
+ })
+ updateNode(owner, internals, { strokes, strokeWeight: kept.weight, strokeAlign: kept.align })
+ setPaintBindings(graph(target, internals), raw(owner, internals), 'strokes', value)
+}
+
export function installVisualNodeProxyAccessors(
prototype: object,
internals: NodeProxyInternals,
@@ -87,14 +100,7 @@ export function installVisualNodeProxyAccessors(
return typeof fills === 'symbol' ? fills : Object.freeze(fills as FigmaPaint[])
},
set(this: ProxyThis, value: readonly FigmaPaint[]) {
- const node = raw(this, internals)
- const fills = parseFigmaPaints(value)
- updateNode(
- this,
- internals,
- node.type === 'TEXT' ? textStyleChanges(node, { fills }) : { fills }
- )
- setPaintBindings(graph(this, internals), raw(this, internals), 'fills', value)
+ setFills(this, internals, value, 'set_fills')
}
},
strokes: {
@@ -102,27 +108,22 @@ export function installVisualNodeProxyAccessors(
const owner = raw(strokeOwner(this, internals), internals)
return Object.freeze(figmaStrokes(graph(this, internals), owner))
},
- // Figma paints carry no geometry; a stroke takes the node's weight and alignment, which
- // outlast its strokes.
set(this: ProxyThis, value: readonly FigmaPaint[]) {
- const owner = strokeOwner(this, internals)
- const geometry = newStrokeGeometry(raw(owner, internals))
- const strokes = parseFigmaPaints(value, 'set_strokes', 'strokes').map((paint): Stroke => ({
- ...paint,
- weight: geometry.weight,
- align: geometry.align
- }))
- const kept = newStrokeGeometry({
- strokes,
- strokeWeight: geometry.weight,
- strokeAlign: geometry.align
- })
- updateNode(owner, internals, {
- strokes,
- strokeWeight: kept.weight,
- strokeAlign: kept.align
- })
- setPaintBindings(graph(this, internals), raw(owner, internals), 'strokes', value)
+ setStrokes(this, internals, value, 'set_strokes')
+ }
+ },
+ // Figma loads a pattern's source first; every node here is loaded, so these check and set as
+ // `fills` and `strokes` do, throwing before they return.
+ setFillsAsync: {
+ value(this: ProxyThis, value: readonly FigmaPaint[]): Promise<void> {
+ setFills(this, internals, value, 'setFillsAsync')
+ return Promise.resolve()
+ }
+ },
+ setStrokesAsync: {
+ value(this: ProxyThis, value: readonly FigmaPaint[]): Promise<void> {
+ setStrokes(this, internals, value, 'setStrokesAsync')
+ return Promise.resolve()
}
},
effects: {
@@ -134,10 +135,6 @@ export function installVisualNodeProxyAccessors(
}
},
// Applied shared styles, as Figma exposes them; an assignment inside an instance is an override.
- fillStyleId: styleReference(internals, 'fillStyleId', mixed),
- strokeStyleId: styleReference(internals, 'strokeStyleId', mixed),
- effectStyleId: styleReference(internals, 'effectStyleId', mixed),
- gridStyleId: styleReference(internals, 'gridStyleId', mixed),
opacity: {
get(this: ProxyThis): number {
return raw(this, internals).opacity
diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.ts
index c8d08104f..5c95c6f8d 100644
--- a/packages/core/src/figma-api/compatibility.ts
+++ b/packages/core/src/figma-api/compatibility.ts
@@ -1,4 +1,32 @@
-/// <reference types="@figma/plugin-typings" />
+import type {
+ BooleanOperationNode,
+ ComponentNode,
+ ComponentPropertyDefinitions,
+ ComponentSetNode,
+ DocumentNode,
+ Effect,
+ EffectStyle,
+ FrameNode,
+ GradientPaint,
+ GridStyle,
+ ImagePaint,
+ InstanceNode,
+ PageNode,
+ Paint,
+ PaintStyle,
+ PatternPaint,
+ PluginAPI,
+ SceneNode,
+ SceneNodeMixin,
+ SlotNode,
+ SolidPaint,
+ TextNode,
+ TextStyle,
+ Variable,
+ VariableCollection,
+ VariablesAPI,
+ VideoPaint
+} from '@figma/plugin-typings/plugin-api-standalone'
import type { FigmaAPI } from './index'
import type {
@@ -9,6 +37,12 @@ import type {
} from './node-types'
import type { OpenPencilPaint } from './paints'
import type { FigmaNodeProxy } from './proxy'
+import type {
+ FigmaEffectStyle,
+ FigmaGridStyle,
+ FigmaPaintStyle,
+ FigmaTextStyle
+} from './styles/handles'
import type {
FIGMA_API_HOST_MEMBERS,
FIGMA_API_INCOMPLETE_MEMBERS,
@@ -205,6 +239,10 @@ type TextMixedKeys =
| 'listSpacing'
| 'paragraphSpacing'
| 'paragraphIndent'
+ | 'textDecorationStyle'
+ | 'textDecorationOffset'
+ | 'textDecorationThickness'
+ | 'textDecorationSkipInk'
type TextMixedMatch = Expect<
Extends<
{ [K in TextMixedKeys]: WithoutMixed<FigmaNodeProxy[K]> },
@@ -315,3 +353,101 @@ const _collectionExtras: None<
> = {}
/** `figma.variables` members Figma's do not have. */
const _variablesAPIExtras: None<Exclude<keyof FigmaVariablesAPI, keyof VariablesAPI>> = {}
+
+// --- Members by node type: each takes and gives what Figma's node types declare ---
+
+type FrameKeys =
+ | 'guides'
+ | 'horizontalPadding'
+ | 'verticalPadding'
+ | 'gridStyleId'
+ | 'backgroundStyleId'
+ | 'setFillStyleIdAsync'
+ | 'setStrokeStyleIdAsync'
+ | 'setEffectStyleIdAsync'
+ | 'setGridStyleIdAsync'
+type FrameMembersMatch = Expect<
+ Extends<Pick<FigmaNodeProxy, FrameKeys>, Pick<FrameNode, FrameKeys>>
+>
+const _frameMembersMatch: FrameMembersMatch = true
+
+type TextNodeKeys = 'leadingTrim' | 'setTextStyleIdAsync'
+type TextNodeMembersMatch = Expect<
+ Extends<Pick<FigmaNodeProxy, TextNodeKeys>, Pick<TextNode, TextNodeKeys>>
+>
+const _textNodeMembersMatch: TextNodeMembersMatch = true
+
+type ShapeMembersMatch = Expect<
+ Extends<
+ Pick<FigmaNodeProxy, 'booleanOperation'> &
+ Pick<FigmaComponentNode, 'description'> &
+ Pick<FigmaComponentSetNode, 'variantGroupProperties'> &
+ Pick<FigmaInstanceNode, 'removeOverrides'> &
+ Pick<FigmaNodeProxy, 'documentColorProfile'>,
+ Pick<BooleanOperationNode, 'booleanOperation'> &
+ Pick<ComponentNode, 'description'> &
+ Pick<ComponentSetNode, 'variantGroupProperties'> &
+ Pick<InstanceNode, 'removeOverrides'> &
+ Pick<DocumentNode, 'documentColorProfile'>
+ >
+>
+const _shapeMembersMatch: ShapeMembersMatch = true
+
+// --- Styles: each style's members are Figma's, apart from consumers, which read node proxies ---
+
+type BaseStyleKeys =
+ | 'id'
+ | 'type'
+ | 'name'
+ | 'description'
+ | 'remote'
+ | 'key'
+ | 'documentationLinks'
+ | 'boundVariables'
+ | 'remove'
+type StyleMatch<Ours, Figma> = Extends<
+ Pick<Ours, BaseStyleKeys & keyof Ours>,
+ Pick<Figma, BaseStyleKeys & keyof Figma>
+>
+const _paintStyleMatch: Expect<StyleMatch<FigmaPaintStyle, PaintStyle>> = true
+const _effectStyleMatch: Expect<StyleMatch<FigmaEffectStyle, EffectStyle>> = true
+const _gridStyleMatch: Expect<StyleMatch<FigmaGridStyle, GridStyle>> = true
+const _textStyleMatch: Expect<StyleMatch<FigmaTextStyle, TextStyle>> = true
+
+// A paint style's paints are those `fills` reads; a text style's fields are never mixed.
+type StylePaintsMatch = Expect<
+ Extends<Exclude<FigmaPaintStyle['paints'][number], OpenPencilPaint>, Paint>
+>
+const _stylePaintsMatch: StylePaintsMatch = true
+type TextStyleKeys =
+ | 'fontSize'
+ | 'fontName'
+ | 'lineHeight'
+ | 'letterSpacing'
+ | 'textCase'
+ | 'textDecoration'
+ | 'leadingTrim'
+ | 'paragraphSpacing'
+ | 'paragraphIndent'
+ | 'listSpacing'
+ | 'hangingList'
+type TextStyleFieldsMatch = Expect<
+ Extends<Pick<FigmaTextStyle, TextStyleKeys>, Pick<TextStyle, TextStyleKeys>>
+>
+const _textStyleFieldsMatch: TextStyleFieldsMatch = true
+
+type StringKeys<T> = Extract<keyof T, string>
+/** Text style members live Figma has (desktop 126) that its typings do not declare yet. */
+type UntypedTextStyleKeys =
+ | 'textDecorationStyle'
+ | 'textDecorationOffset'
+ | 'textDecorationThickness'
+ | 'textDecorationColor'
+ | 'textDecorationSkipInk'
+/** Style members Figma's styles do not have. */
+const _paintStyleExtras: None<Exclude<StringKeys<FigmaPaintStyle>, keyof PaintStyle>> = {}
+const _textStyleExtras: None<
+ Exclude<StringKeys<FigmaTextStyle>, keyof TextStyle | UntypedTextStyleKeys>
+> = {}
+const _effectStyleExtras: None<Exclude<StringKeys<FigmaEffectStyle>, keyof EffectStyle>> = {}
+const _gridStyleExtras: None<Exclude<StringKeys<FigmaGridStyle>, keyof GridStyle>> = {}
diff --git a/packages/core/src/figma-api/effects.ts b/packages/core/src/figma-api/effects.ts
index 70558d857..88cd07a19 100644
--- a/packages/core/src/figma-api/effects.ts
+++ b/packages/core/src/figma-api/effects.ts
@@ -3,8 +3,11 @@ import * as v from 'valibot'
import type { BlendMode, Effect } from '@open-pencil/scene-graph'
import { TRANSPARENT } from '#core/constants'
+import { invalid, received } from '#core/figma-api/accessors/text/messages'
+/** Blend modes in the order Figma lists them in its messages. */
const BLEND_MODE_KEYS = {
+ PASS_THROUGH: true,
NORMAL: true,
DARKEN: true,
MULTIPLY: true,
@@ -22,8 +25,7 @@ const BLEND_MODE_KEYS = {
HUE: true,
SATURATION: true,
COLOR: true,
- LUMINOSITY: true,
- PASS_THROUGH: true
+ LUMINOSITY: true
} satisfies Record<BlendMode, true>
export const BLEND_MODES = Object.keys(BLEND_MODE_KEYS) as BlendMode[]
@@ -98,14 +100,17 @@ function unsupportedEffect(value: unknown): string | null {
* Throws with the first problem, as Figma's `effects` setter does.
*/
export function parseFigmaEffects(value: unknown): Effect[] {
+ const method = 'set_effects'
+ if (!Array.isArray(value)) {
+ throw invalid(method, `Expected array, received ${received(value)}`, 'effects')
+ }
const unsupported = unsupportedEffect(value)
- if (unsupported) throw new Error(`Property "effects" failed validation: ${unsupported}`)
+ if (unsupported) throw invalid(method, unsupported, 'effects')
const result = v.safeParse(effectsSchema, value)
if (!result.success) {
const [issue] = result.issues
- throw new Error(
- `Property "effects" failed validation: ${issue.message} at ${issuePath(issue.path) || 'effects'}`
- )
+ const at = issuePath(issue.path) || 'effects'
+ throw invalid(method, `${issue.message} at ${at}`, 'effects')
}
return result.output.map(toSceneEffect)
}
diff --git a/packages/core/src/figma-api/fonts/names.ts b/packages/core/src/figma-api/fonts/names.ts
index bc4764d1e..27cd24114 100644
--- a/packages/core/src/figma-api/fonts/names.ts
+++ b/packages/core/src/figma-api/fonts/names.ts
@@ -1,5 +1,6 @@
+import type { Font, FontName, FontNameInput } from '@figma/plugin-typings/plugin-api-standalone'
+
import type { FontVariation } from '@open-pencil/scene-graph'
-import type { FontFamilyStyle } from '@open-pencil/scene-graph/font-style'
import { parseFontStyle } from '@open-pencil/scene-graph/font-style'
import {
@@ -10,15 +11,11 @@ import {
import { faceForStyle } from '#core/text/font/names'
/** A font as Figma reads one; a variable font's also lists every axis it is drawn at. */
-export type FigmaFontName = FontFamilyStyle & { variationSettings?: FigmaVariationSettings }
-export type FigmaFont = { fontName: FigmaFontName }
+export type FigmaFontName = FontName
+export type FigmaFont = Font
/** A font to apply, as Figma takes one: `style` may be left out for the axes to pick it. */
-export interface FigmaFontNameInput {
- family: string
- style?: string
- variationSettings?: FigmaVariationSettings
-}
+export type FigmaFontNameInput = FontNameInput
/** The font a character has before a new one is set over it. */
export interface CurrentFont {
diff --git a/packages/core/src/figma-api/fonts/variations.ts b/packages/core/src/figma-api/fonts/variations.ts
index a11aa43f5..1f3dc20fa 100644
--- a/packages/core/src/figma-api/fonts/variations.ts
+++ b/packages/core/src/figma-api/fonts/variations.ts
@@ -1,3 +1,5 @@
+import type { FontVariationSettings } from '@figma/plugin-typings/plugin-api-standalone'
+
import type { FontVariation } from '@open-pencil/scene-graph'
import { parseFontStyle } from '@open-pencil/scene-graph/font-style'
@@ -9,7 +11,8 @@ import {
} from '#core/text/font/variation'
/** Variable font axis values by axis tag, as `FontName.variationSettings` holds them. */
-export type FigmaVariationSettings = Record<string, number>
+/** Figma's `FontVariationSettings`: a value by axis tag. */
+export type FigmaVariationSettings = FontVariationSettings
/** Figma lists axis tags in code unit order, so `GRAD` comes before `opsz`. */
function byCodeUnit(a: string, b: string): number {
diff --git a/packages/core/src/figma-api/images.ts b/packages/core/src/figma-api/images.ts
index d9415af6f..64d5a86ca 100644
--- a/packages/core/src/figma-api/images.ts
+++ b/packages/core/src/figma-api/images.ts
@@ -1,4 +1,4 @@
-/// <reference types="@figma/plugin-typings" />
+import type { Image } from '@figma/plugin-typings/plugin-api-standalone'
import type { SceneGraph } from '@open-pencil/scene-graph'
import {
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index f5bab7a81..08b8faedb 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -1,3 +1,16 @@
+import type {
+ BaseNode,
+ BooleanOperationNode,
+ ChildrenMixin,
+ ComponentNode,
+ ComponentSetNode,
+ GroupNode,
+ Image,
+ PageNode,
+ SceneNode,
+ UtilAPI,
+ VectorNode
+} from '@figma/plugin-typings/plugin-api-standalone'
import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
import type { SceneGraph, SceneNode as CoreSceneNode, NodeType } from '@open-pencil/scene-graph'
@@ -47,6 +60,7 @@ import type {
import { startPendingLayout } from './pending-layout'
import { FigmaNodeProxy, INTERNAL_ID, MIXED, type FigmaFont, type NodeProxyHost } from './proxy'
import { newShapeWithText } from './shape-with-text'
+import { FigmaStyleMethods } from './styles/api'
import type { ExportImageOptions } from './types'
import { figmaUtil } from './util'
import { FigmaVariablesAPI } from './variables'
@@ -99,11 +113,12 @@ export type { FigmaVariationSettings } from './fonts/variations'
// TODO(figma-api): Implement the full official PluginAPI interface once our compatibility
// layer covers all required node-specific return types and unsupported APIs are modeled explicitly.
-export class FigmaAPI implements NodeProxyHost {
+export class FigmaAPI extends FigmaStyleMethods implements NodeProxyHost {
readonly graph: SceneGraph
private _currentPageId: string
private _selection: FigmaNodeProxy[] = []
private _nodeCache = new Map<string, FigmaNodeProxy>()
+ private _nodeTypes = new Map<string, string | undefined>()
private _pageProxies = new WeakSet<FigmaNodeProxy>()
private _renderer: SkiaRenderer | null = null
private _unbindRendererEvents: (() => void) | null = null
@@ -120,6 +135,7 @@ export class FigmaAPI implements NodeProxyHost {
readonly #fetch: images.ImageFetch
constructor(graph: SceneGraph, options: FigmaAPIOptions = {}) {
+ super()
this.graph = graph
this.#fetch = options.fetch ?? ((input, init) => fetch(input, init))
this.variables = new FigmaVariablesAPI(graph)
@@ -166,10 +182,13 @@ export class FigmaAPI implements NodeProxyHost {
}
wrapNode(id: string): FigmaNodeProxy {
+ const type = this.graph.getNode(id)?.type
let proxy = this._nodeCache.get(id)
- if (!proxy) {
+ // A node that changed type, such as a detached instance, gets the members of its new type.
+ if (!proxy || this._nodeTypes.get(id) !== type) {
proxy = new FigmaNodeProxy(id, this.graph, this)
this._nodeCache.set(id, proxy)
+ this._nodeTypes.set(id, type)
}
return proxy
}
diff --git a/packages/core/src/figma-api/members.ts b/packages/core/src/figma-api/members.ts
new file mode 100644
index 000000000..5b9a5ecd7
--- /dev/null
+++ b/packages/core/src/figma-api/members.ts
@@ -0,0 +1,255 @@
+import type {
+ BooleanOperationNode,
+ ComponentSetNode,
+ DocumentNode,
+ Guide,
+ LeadingTrim,
+ MinimalFillsMixin,
+ TextDecorationOffset,
+ TextDecorationStyle,
+ TextDecorationThickness
+} from '@figma/plugin-typings/plugin-api-standalone'
+
+import type {
+ ArcData,
+ HyperlinkTarget,
+ LayoutGrid,
+ LayoutMode,
+ NodeType,
+ SceneNode
+} from '@open-pencil/scene-graph'
+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
+
+import type { TextRangeMethods } from './accessors/text/ranges'
+import type { VariableNodeMembers } from './accessors/variables'
+import type { FigmaVectorNetwork, FigmaVectorPath } from './accessors/vector'
+import type { FigmaDevStatusValue } from './dev-status'
+import type { FigmaEffect } from './effects'
+import type { FigmaFontName } from './fonts/names'
+import type { FigmaInstanceOverride } from './overrides'
+import type { FigmaPaint } from './paints'
+import type { PluginDataMethods } from './plugin-data'
+import type { FigmaNodeProxy } from './proxy'
+import type { FigmaLetterSpacing, FigmaLineHeight } from './text'
+import type { FigmaDecorationColor } from './text/style'
+import type { FigmaTransform } from './types'
+
+/** A style reference's async setter, as Figma types it. */
+type StyleIdSetter = MinimalFillsMixin['setFillStyleIdAsync']
+
+/**
+ * The members of Figma's node types that `FigmaNodeProxy` gives scripts. Accessors install them
+ * at runtime, on the prototype or, for members Figma has on some node types alone, on each
+ * proxy; this class only declares their types.
+ */
+export abstract class FigmaNodeMembers {
+ declare readonly id: string
+ /** A slot frame reads as `'SLOT'`, as Figma's `SlotNode` does. */
+ declare readonly type: NodeType | 'SLOT'
+ declare name: string
+ declare readonly removed: boolean
+ declare x: number
+ declare y: number
+ declare readonly width: number
+ declare readonly height: number
+ declare rotation: number
+ declare relativeTransform: FigmaTransform
+ declare resize: (width: number, height: number) => void
+ declare resizeWithoutConstraints: (width: number, height: number) => void
+ declare rescale: (scale: number) => void
+ declare readonly absoluteTransform: FigmaTransform
+ declare readonly absoluteBoundingBox: Rect
+ declare readonly absoluteRenderBounds: Rect | null
+
+ declare fills: readonly FigmaPaint[] | symbol
+ declare strokes: readonly FigmaPaint[]
+ declare effects: readonly FigmaEffect[]
+ declare opacity: number
+ declare visible: boolean
+ declare locked: boolean
+ declare devStatus: FigmaDevStatusValue | undefined
+ declare blendMode: string
+ declare clipsContent: boolean
+ declare cornerRadius: number | symbol
+ declare topLeftRadius: number
+ declare topRightRadius: number
+ declare bottomLeftRadius: number
+ declare bottomRightRadius: number
+ declare cornerSmoothing: number
+
+ declare layoutMode: LayoutMode
+ declare layoutGrids: readonly LayoutGrid[]
+ declare primaryAxisAlignItems: string
+ declare counterAxisAlignItems: string
+ declare itemSpacing: number
+ declare counterAxisSpacing: number
+ declare paddingTop: number
+ declare paddingRight: number
+ declare paddingBottom: number
+ declare paddingLeft: number
+ declare horizontalPadding: number
+ declare verticalPadding: number
+ declare guides: readonly Guide[]
+ declare layoutWrap: string
+ declare primaryAxisSizingMode: string
+ declare counterAxisSizingMode: string
+ declare counterAxisAlignContent: string
+ declare itemReverseZIndex: boolean
+ declare strokesIncludedInLayout: boolean
+ declare layoutPositioning: string
+ declare layoutGrow: number
+ declare layoutAlign: string
+ declare layoutSizingHorizontal: string
+ declare layoutSizingVertical: string
+ declare constraints: { horizontal: string; vertical: string }
+ declare minWidth: number | null
+ declare maxWidth: number | null
+ declare minHeight: number | null
+ declare maxHeight: number | null
+ declare readonly targetAspectRatio: Vector | null
+ /** @deprecated Figma's alias for whether `targetAspectRatio` is set. */
+ declare constrainProportions: boolean
+ declare lockAspectRatio: () => void
+ declare unlockAspectRatio: () => void
+ declare pointCount: number
+ declare innerRadius: number
+ declare arcData: Readonly<ArcData>
+ declare booleanOperation: BooleanOperationNode['booleanOperation']
+ declare description: string
+ declare readonly instances: FigmaNodeProxy[]
+ declare getInstancesAsync: () => Promise<FigmaNodeProxy[]>
+ declare readonly defaultVariant: FigmaNodeProxy | null
+ declare readonly variantGroupProperties: ComponentSetNode['variantGroupProperties']
+ declare readonly documentColorProfile: DocumentNode['documentColorProfile']
+ declare getTopLevelFrame: () => FigmaNodeProxy | undefined
+ declare setFillsAsync: (paints: readonly FigmaPaint[]) => Promise<void>
+ declare setStrokesAsync: (paints: readonly FigmaPaint[]) => Promise<void>
+ declare vectorPaths: readonly FigmaVectorPath[]
+ declare vectorNetwork: FigmaVectorNetwork
+ declare setVectorNetworkAsync: (vectorNetwork: FigmaVectorNetwork) => Promise<void>
+ declare handleMirroring: SceneNode['handleMirroring'] | symbol
+ declare getPluginData: PluginDataMethods['getPluginData']
+ declare setPluginData: PluginDataMethods['setPluginData']
+ declare getPluginDataKeys: PluginDataMethods['getPluginDataKeys']
+ declare getSharedPluginData: PluginDataMethods['getSharedPluginData']
+ declare setSharedPluginData: PluginDataMethods['setSharedPluginData']
+ declare getSharedPluginDataKeys: PluginDataMethods['getSharedPluginDataKeys']
+ declare readonly explicitVariableModes: VariableNodeMembers['explicitVariableModes']
+ declare readonly resolvedVariableModes: VariableNodeMembers['resolvedVariableModes']
+ declare setExplicitVariableModeForCollection: VariableNodeMembers['setExplicitVariableModeForCollection']
+ declare clearExplicitVariableModeForCollection: VariableNodeMembers['clearExplicitVariableModeForCollection']
+ declare readonly boundVariables: VariableNodeMembers['boundVariables']
+ declare setBoundVariable: VariableNodeMembers['setBoundVariable']
+ declare readonly overrides: FigmaInstanceOverride[] | undefined
+ /** A sticky note's body or a shape's label, a sticky's author line, and whether it is wide. */
+ declare readonly text: FigmaNodeProxy | undefined
+ declare readonly authorName: string | undefined
+ declare authorVisible: boolean | undefined
+ declare isWideWidth: boolean | undefined
+ declare shapeType: ShapeWithTextType | undefined
+ /** On pages alone, as in Figma. */
+ declare loadAsync: () => Promise<void>
+ declare resetOverrides: () => void
+ declare removeOverrides: () => void
+
+ declare strokeWeight: number
+ declare strokeAlign: string
+ declare dashPattern: readonly number[]
+ declare strokeCap: string
+ declare strokeJoin: string
+ declare strokeMiterLimit: number
+ declare strokeTopWeight: number
+ declare strokeBottomWeight: number
+ declare strokeLeftWeight: number
+ declare strokeRightWeight: number
+
+ declare characters: string
+ declare fontSize: number | symbol
+ declare fontName: FigmaFontName | symbol
+ declare fontWeight: number | symbol
+ declare textAlignHorizontal: string
+ declare textAlignVertical: string
+ declare textAutoResize: string
+ declare letterSpacing: FigmaLetterSpacing | symbol
+ declare lineHeight: FigmaLineHeight | symbol
+ declare textCase: SceneNode['textCase'] | symbol
+ declare hyperlink: HyperlinkTarget | null | symbol
+ declare textStyleId: string | symbol
+ declare fillStyleId: string | symbol
+ declare textDecoration: SceneNode['textDecoration'] | symbol
+ declare textDecorationStyle: TextDecorationStyle | null | symbol
+ declare textDecorationOffset: TextDecorationOffset | null | symbol
+ declare textDecorationThickness: TextDecorationThickness | null | symbol
+ declare textDecorationColor: FigmaDecorationColor | null | symbol
+ declare textDecorationSkipInk: boolean | null | symbol
+ declare leadingTrim: LeadingTrim
+ declare readonly openTypeFeatures: Readonly<Record<string, boolean>> | symbol
+ declare maxLines: number | null
+ declare listSpacing: number | symbol
+ declare paragraphSpacing: number | symbol
+ declare paragraphIndent: number | symbol
+ declare hangingList: boolean
+ declare textTruncation: string
+ declare autoRename: boolean
+
+ // Per-character and per-paragraph methods: accessors/text/ranges.ts.
+ declare getStyledTextSegments: TextRangeMethods['getStyledTextSegments']
+ declare getRangeAllFontNames: TextRangeMethods['getRangeAllFontNames']
+ declare getRangeFontSize: TextRangeMethods['getRangeFontSize']
+ declare setRangeFontSize: TextRangeMethods['setRangeFontSize']
+ declare getRangeFontName: TextRangeMethods['getRangeFontName']
+ declare setRangeFontName: TextRangeMethods['setRangeFontName']
+ declare getRangeFontWeight: TextRangeMethods['getRangeFontWeight']
+ declare getRangeFills: TextRangeMethods['getRangeFills']
+ declare setRangeFills: TextRangeMethods['setRangeFills']
+ declare getRangeLetterSpacing: TextRangeMethods['getRangeLetterSpacing']
+ declare setRangeLetterSpacing: TextRangeMethods['setRangeLetterSpacing']
+ declare getRangeLineHeight: TextRangeMethods['getRangeLineHeight']
+ declare setRangeLineHeight: TextRangeMethods['setRangeLineHeight']
+ declare getRangeTextDecoration: TextRangeMethods['getRangeTextDecoration']
+ declare setRangeTextDecoration: TextRangeMethods['setRangeTextDecoration']
+ declare getRangeTextDecorationStyle: TextRangeMethods['getRangeTextDecorationStyle']
+ declare setRangeTextDecorationStyle: TextRangeMethods['setRangeTextDecorationStyle']
+ declare getRangeTextDecorationOffset: TextRangeMethods['getRangeTextDecorationOffset']
+ declare setRangeTextDecorationOffset: TextRangeMethods['setRangeTextDecorationOffset']
+ declare getRangeTextDecorationThickness: TextRangeMethods['getRangeTextDecorationThickness']
+ declare setRangeTextDecorationThickness: TextRangeMethods['setRangeTextDecorationThickness']
+ declare getRangeTextDecorationColor: TextRangeMethods['getRangeTextDecorationColor']
+ declare setRangeTextDecorationColor: TextRangeMethods['setRangeTextDecorationColor']
+ declare getRangeTextDecorationSkipInk: TextRangeMethods['getRangeTextDecorationSkipInk']
+ declare setRangeTextDecorationSkipInk: TextRangeMethods['setRangeTextDecorationSkipInk']
+ declare getRangeOpenTypeFeatures: TextRangeMethods['getRangeOpenTypeFeatures']
+ declare getRangeListOptions: TextRangeMethods['getRangeListOptions']
+ declare setRangeListOptions: TextRangeMethods['setRangeListOptions']
+ declare getRangeIndentation: TextRangeMethods['getRangeIndentation']
+ declare setRangeIndentation: TextRangeMethods['setRangeIndentation']
+ declare getRangeListSpacing: TextRangeMethods['getRangeListSpacing']
+ declare setRangeListSpacing: TextRangeMethods['setRangeListSpacing']
+ declare getRangeParagraphSpacing: TextRangeMethods['getRangeParagraphSpacing']
+ declare setRangeParagraphSpacing: TextRangeMethods['setRangeParagraphSpacing']
+ declare getRangeParagraphIndent: TextRangeMethods['getRangeParagraphIndent']
+ declare setRangeParagraphIndent: TextRangeMethods['setRangeParagraphIndent']
+ declare getRangeTextCase: TextRangeMethods['getRangeTextCase']
+ declare setRangeTextCase: TextRangeMethods['setRangeTextCase']
+ declare getRangeHyperlink: TextRangeMethods['getRangeHyperlink']
+ declare setRangeHyperlink: TextRangeMethods['setRangeHyperlink']
+ declare getRangeTextStyleId: TextRangeMethods['getRangeTextStyleId']
+ declare setRangeTextStyleId: TextRangeMethods['setRangeTextStyleId']
+ declare setRangeTextStyleIdAsync: TextRangeMethods['setRangeTextStyleIdAsync']
+ declare getRangeFillStyleId: TextRangeMethods['getRangeFillStyleId']
+ declare setRangeFillStyleId: TextRangeMethods['setRangeFillStyleId']
+ declare setRangeFillStyleIdAsync: TextRangeMethods['setRangeFillStyleIdAsync']
+ declare getRangeBoundVariable: TextRangeMethods['getRangeBoundVariable']
+ declare setRangeBoundVariable: TextRangeMethods['setRangeBoundVariable']
+ declare strokeStyleId: string
+ declare effectStyleId: string
+ declare gridStyleId: string
+ /** @deprecated Figma's name for a frame's `fillStyleId`. */
+ declare backgroundStyleId: string
+ declare setFillStyleIdAsync: StyleIdSetter
+ declare setStrokeStyleIdAsync: StyleIdSetter
+ declare setEffectStyleIdAsync: StyleIdSetter
+ declare setGridStyleIdAsync: StyleIdSetter
+ declare setTextStyleIdAsync: StyleIdSetter
+}
diff --git a/packages/core/src/figma-api/node-types.ts b/packages/core/src/figma-api/node-types.ts
index 86517a694..cf6cf4f25 100644
--- a/packages/core/src/figma-api/node-types.ts
+++ b/packages/core/src/figma-api/node-types.ts
@@ -1,4 +1,23 @@
-/// <reference types="@figma/plugin-typings" />
+import type {
+ BooleanOperationNode,
+ ComponentNode,
+ ComponentSetNode,
+ ConnectorNode,
+ EllipseNode,
+ FrameNode,
+ GroupNode,
+ InstanceNode,
+ LineNode,
+ PolygonNode,
+ RectangleNode,
+ SectionNode,
+ ShapeWithTextNode,
+ SlotNode,
+ StarNode,
+ StickyNode,
+ TextNode,
+ VectorNode
+} from '@figma/plugin-typings/plugin-api-standalone'
import type { FigmaNodeProxy } from './proxy'
diff --git a/packages/core/src/figma-api/overrides.ts b/packages/core/src/figma-api/overrides.ts
index 5fa5a2102..b30d91128 100644
--- a/packages/core/src/figma-api/overrides.ts
+++ b/packages/core/src/figma-api/overrides.ts
@@ -239,11 +239,31 @@ function resetInstanceOverrides(graph: SceneGraph, root: SceneNode): void {
graph.syncInstance(outermost.id)
}
+/**
+ * Figma's `InstanceNode` members for overrides: the list, and `removeOverrides` with its
+ * deprecated name `resetOverrides`, which do the same. Installed on instance proxies alone, as
+ * Figma has them on no other node.
+ */
export function installInstanceOverrideAccessors(
- prototype: object,
- internals: NodeProxyInternals
+ target: object,
+ internals: NodeProxyInternals,
+ type: SceneNode['type']
): void {
- Object.defineProperties(prototype, {
+ if (type !== 'INSTANCE') return
+ // A proxy a script kept from before the instance was detached checks that it still is one.
+ const instance = (target: ProxyThis, method: string): SceneNode => {
+ const node = raw(target, internals)
+ if (node.type !== 'INSTANCE') throw new TypeError(`${method}() can only be called on instances`)
+ return node
+ }
+ const removal = (method: string) => ({
+ value(this: ProxyThis) {
+ const node = instance(this, method)
+ assertProxyEditable(this, internals)
+ resetInstanceOverrides(graph(this, internals), node)
+ }
+ })
+ Object.defineProperties(target, {
overrides: {
get(this: ProxyThis): FigmaInstanceOverride[] | undefined {
const node = raw(this, internals)
@@ -253,14 +273,7 @@ export function installInstanceOverrideAccessors(
return instanceOverrides(graph(this, internals), node)
}
},
- resetOverrides: {
- value(this: ProxyThis) {
- const node = raw(this, internals)
- if (node.type !== 'INSTANCE')
- throw new TypeError('resetOverrides() can only be called on instances')
- assertProxyEditable(this, internals)
- resetInstanceOverrides(graph(this, internals), node)
- }
- }
+ resetOverrides: removal('resetOverrides'),
+ removeOverrides: removal('removeOverrides')
})
}
diff --git a/packages/core/src/figma-api/paints.ts b/packages/core/src/figma-api/paints.ts
index 73dbcab28..6cc67a10c 100644
--- a/packages/core/src/figma-api/paints.ts
+++ b/packages/core/src/figma-api/paints.ts
@@ -8,7 +8,7 @@ import {
} from '@open-pencil/scene-graph/gradient'
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
-import { invalid, received } from './accessors/text/messages'
+import { invalid, invalidOption, received } from './accessors/text/messages'
import { BLEND_MODES, issuePath } from './effects'
import type { FigmaTransform } from './types'
import { variableAlias, type FigmaVariableAlias } from './variables/values'
@@ -57,10 +57,6 @@ const NO_FILTERS: ImageFilters = {
const SHA1_HASH = /^[0-9a-f]{40}$/i
/** Figma's message for a value that is none of `options`. */
-function invalidOption(options: readonly string[]): string {
- return `Invalid option: expected one of ${options.map((option) => `"${option}"`).join('|')}`
-}
-
const unitSchema = v.pipe(v.number(), v.minValue(0), v.maxValue(1))
const aliasSchema = v.object({ type: v.literal('VARIABLE_ALIAS'), id: v.string() })
const colorBindingSchema = v.optional(v.strictObject({ color: v.optional(aliasSchema) }))
@@ -245,8 +241,9 @@ function issueProblem(issue: v.BaseIssue<unknown>): string {
/** Figma's complaint about a paint type it does not take, or OpenPencil does not model. */
function typeProblem(value: readonly unknown[]): string | null {
for (const [index, paint] of value.entries()) {
- if (!v.is(v.object({ type: v.unknown() }), paint)) continue
- const { type } = paint
+ // A paint without a type is refused as one of an unknown type, as in Figma.
+ if (!paint || typeof paint !== 'object') continue
+ const { type } = paint as { type?: unknown }
if (typeof type === 'string' && UNSUPPORTED_PAINT_TYPES.has(type)) {
return `${type} paints are not supported at [${index}].type`
}
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index df3534e21..a14bf1d72 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -1,57 +1,40 @@
-import type {
- ArcData,
- HyperlinkTarget,
- SceneGraph,
- SceneNode,
- NodeType,
- LayoutGrid,
- LayoutMode
-} from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { attachedConnectors } from '@open-pencil/scene-graph/connectors'
import type { GroupFitOptions } from '@open-pencil/scene-graph/group-bounds'
import { createsComponentCycle, recordInstanceOverride } from '@open-pencil/scene-graph/instances'
-import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
-import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'
import { slotPropertyId } from '@open-pencil/scene-graph/slots'
import { assertNodeEditable } from '#core/editor/capabilities'
-import type { FigmaEffect } from '#core/figma-api/effects'
import { prepareFollowedFieldEdit, fitGroupsAround } from './accessor-utils'
import { installBasicNodeProxyAccessors } from './accessors/basic'
+import { installComponentNodeAccessors } from './accessors/component'
import { installConnectorNodeProxyAccessors } from './accessors/connector'
+import { installGuideAccessors } from './accessors/guides'
import { installLayoutNodeProxyAccessors } from './accessors/layout'
import { installShapeNodeProxyAccessors } from './accessors/shape'
import { installStickyNodeProxyAccessors, pluginChildren } from './accessors/sticky'
import { installStrokeNodeProxyAccessors } from './accessors/strokes'
+import { installStyleReferenceAccessors } from './accessors/styles'
import { installTextNodeProxyAccessors } from './accessors/text'
-import { installTextRangeMethods, type TextRangeMethods } from './accessors/text/ranges'
-import {
- installVariableModeNodeProxyAccessors,
- type VariableNodeMembers
-} from './accessors/variables'
-import {
- installVectorNodeProxyAccessors,
- type FigmaVectorNetwork,
- type FigmaVectorPath
-} from './accessors/vector'
+import { installTextRangeMethods } from './accessors/text/ranges'
+import { installVariableModeNodeProxyAccessors } from './accessors/variables'
+import { installVectorNodeProxyAccessors } from './accessors/vector'
import { installVisualNodeProxyAccessors } from './accessors/visual'
import { installComponentPropertyAccessors } from './components'
-import { installDevStatusAccessors, type FigmaDevStatusValue } from './dev-status'
-import type { FigmaFontName } from './fonts/names'
+import { installDevStatusAccessors } from './dev-status'
+import { FigmaNodeMembers } from './members'
import type { FigmaFrameNode, FigmaInstanceNode } from './node-types'
-import { installInstanceOverrideAccessors, type FigmaInstanceOverride } from './overrides'
+import { installInstanceOverrideAccessors } from './overrides'
import { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'
import { parseFigmaPaints, toFigmaPaint, type FigmaPaint } from './paints'
-import { installPluginDataMethods, type PluginDataMethods } from './plugin-data'
+import { installPluginDataMethods } from './plugin-data'
import { nodeProxyToJSON } from './serialization'
import { installShapeWithTextAccessors } from './shape-with-text'
import { installSlotAccessors, prepareSlotMove, prepareSlotRemoval } from './slots'
-import type { FigmaLetterSpacing, FigmaLineHeight } from './text'
import * as TextProxy from './text'
import { containerTransform, setContainerTransform } from './transform'
import * as Traversal from './traversal'
-import type { FigmaTransform } from './types'
const MIXED = Symbol('mixed')
@@ -81,190 +64,13 @@ function assertNoComponentCycle(
throw new Error(`in ${method}: Cannot move node. Reparenting would create a component cycle`)
}
-export class FigmaNodeProxy {
+export class FigmaNodeProxy extends FigmaNodeMembers {
[INTERNAL_ID]: string;
[INTERNAL_GRAPH]: SceneGraph;
[INTERNAL_API]: NodeProxyHost
- declare readonly id: string
- /** A slot frame reads as `'SLOT'`, as Figma's `SlotNode` does. */
- declare readonly type: NodeType | 'SLOT'
- declare name: string
- declare readonly removed: boolean
- declare x: number
- declare y: number
- declare readonly width: number
- declare readonly height: number
- declare rotation: number
- declare relativeTransform: FigmaTransform
- declare resize: (width: number, height: number) => void
- declare resizeWithoutConstraints: (width: number, height: number) => void
- declare rescale: (scale: number) => void
- declare readonly absoluteTransform: FigmaTransform
- declare readonly absoluteBoundingBox: Rect
- declare readonly absoluteRenderBounds: Rect | null
-
- declare fills: readonly FigmaPaint[] | symbol
- declare strokes: readonly FigmaPaint[]
- declare effects: readonly FigmaEffect[]
- declare opacity: number
- declare visible: boolean
- declare locked: boolean
- declare devStatus: FigmaDevStatusValue | undefined
- declare blendMode: string
- declare clipsContent: boolean
- declare cornerRadius: number | typeof MIXED
- declare topLeftRadius: number
- declare topRightRadius: number
- declare bottomLeftRadius: number
- declare bottomRightRadius: number
- declare cornerSmoothing: number
-
- declare layoutMode: LayoutMode
- declare layoutGrids: readonly LayoutGrid[]
- declare primaryAxisAlignItems: string
- declare counterAxisAlignItems: string
- declare itemSpacing: number
- declare counterAxisSpacing: number
- declare paddingTop: number
- declare paddingRight: number
- declare paddingBottom: number
- declare paddingLeft: number
- declare layoutWrap: string
- declare primaryAxisSizingMode: string
- declare counterAxisSizingMode: string
- declare counterAxisAlignContent: string
- declare itemReverseZIndex: boolean
- declare strokesIncludedInLayout: boolean
- declare layoutPositioning: string
- declare layoutGrow: number
- declare layoutAlign: string
- declare layoutSizingHorizontal: string
- declare layoutSizingVertical: string
- declare constraints: { horizontal: string; vertical: string }
- declare minWidth: number | null
- declare maxWidth: number | null
- declare minHeight: number | null
- declare maxHeight: number | null
- declare readonly targetAspectRatio: Vector | null
- /** @deprecated Figma's alias for whether `targetAspectRatio` is set. */
- declare constrainProportions: boolean
- declare lockAspectRatio: () => void
- declare unlockAspectRatio: () => void
- declare pointCount: number
- declare innerRadius: number
- declare arcData: Readonly<ArcData>
- declare vectorPaths: readonly FigmaVectorPath[]
- declare vectorNetwork: FigmaVectorNetwork
- declare setVectorNetworkAsync: (vectorNetwork: FigmaVectorNetwork) => Promise<void>
- declare handleMirroring: SceneNode['handleMirroring'] | typeof MIXED
- declare getPluginData: PluginDataMethods['getPluginData']
- declare setPluginData: PluginDataMethods['setPluginData']
- declare getPluginDataKeys: PluginDataMethods['getPluginDataKeys']
- declare getSharedPluginData: PluginDataMethods['getSharedPluginData']
- declare setSharedPluginData: PluginDataMethods['setSharedPluginData']
- declare getSharedPluginDataKeys: PluginDataMethods['getSharedPluginDataKeys']
- declare readonly explicitVariableModes: VariableNodeMembers['explicitVariableModes']
- declare readonly resolvedVariableModes: VariableNodeMembers['resolvedVariableModes']
- declare setExplicitVariableModeForCollection: VariableNodeMembers['setExplicitVariableModeForCollection']
- declare clearExplicitVariableModeForCollection: VariableNodeMembers['clearExplicitVariableModeForCollection']
- declare readonly boundVariables: VariableNodeMembers['boundVariables']
- declare setBoundVariable: VariableNodeMembers['setBoundVariable']
- declare readonly overrides: FigmaInstanceOverride[] | undefined
- /** A sticky note's body or a shape's label, a sticky's author line, and whether it is wide. */
- declare readonly text: FigmaNodeProxy | undefined
- declare readonly authorName: string | undefined
- declare authorVisible: boolean | undefined
- declare isWideWidth: boolean | undefined
- declare shapeType: ShapeWithTextType | undefined
- /** On pages alone, as in Figma. */
- declare loadAsync: () => Promise<void>
- declare resetOverrides: () => void
-
- declare strokeWeight: number
- declare strokeAlign: string
- declare dashPattern: readonly number[]
- declare strokeCap: string
- declare strokeJoin: string
- declare strokeMiterLimit: number
- declare strokeTopWeight: number
- declare strokeBottomWeight: number
- declare strokeLeftWeight: number
- declare strokeRightWeight: number
-
- declare characters: string
- declare fontSize: number | symbol
- declare fontName: FigmaFontName | symbol
- declare fontWeight: number | symbol
- declare textAlignHorizontal: string
- declare textAlignVertical: string
- declare textAutoResize: string
- declare letterSpacing: FigmaLetterSpacing | symbol
- declare lineHeight: FigmaLineHeight | symbol
- declare textCase: SceneNode['textCase'] | symbol
- declare hyperlink: HyperlinkTarget | null | symbol
- declare textStyleId: string | symbol
- declare fillStyleId: string | symbol
- declare textDecoration: SceneNode['textDecoration'] | symbol
- declare maxLines: number | null
- declare listSpacing: number | symbol
- declare paragraphSpacing: number | symbol
- declare paragraphIndent: number | symbol
- declare hangingList: boolean
- declare textTruncation: string
- declare autoRename: boolean
-
- // Per-character and per-paragraph methods: accessors/text/ranges.ts.
- declare getStyledTextSegments: TextRangeMethods['getStyledTextSegments']
- declare getRangeAllFontNames: TextRangeMethods['getRangeAllFontNames']
- declare getRangeFontSize: TextRangeMethods['getRangeFontSize']
- declare setRangeFontSize: TextRangeMethods['setRangeFontSize']
- declare getRangeFontName: TextRangeMethods['getRangeFontName']
- declare setRangeFontName: TextRangeMethods['setRangeFontName']
- declare getRangeFontWeight: TextRangeMethods['getRangeFontWeight']
- declare getRangeFills: TextRangeMethods['getRangeFills']
- declare setRangeFills: TextRangeMethods['setRangeFills']
- declare getRangeLetterSpacing: TextRangeMethods['getRangeLetterSpacing']
- declare setRangeLetterSpacing: TextRangeMethods['setRangeLetterSpacing']
- declare getRangeLineHeight: TextRangeMethods['getRangeLineHeight']
- declare setRangeLineHeight: TextRangeMethods['setRangeLineHeight']
- declare getRangeTextDecoration: TextRangeMethods['getRangeTextDecoration']
- declare setRangeTextDecoration: TextRangeMethods['setRangeTextDecoration']
- declare getRangeTextDecorationStyle: TextRangeMethods['getRangeTextDecorationStyle']
- declare setRangeTextDecorationStyle: TextRangeMethods['setRangeTextDecorationStyle']
- declare getRangeTextDecorationOffset: TextRangeMethods['getRangeTextDecorationOffset']
- declare setRangeTextDecorationOffset: TextRangeMethods['setRangeTextDecorationOffset']
- declare getRangeTextDecorationThickness: TextRangeMethods['getRangeTextDecorationThickness']
- declare setRangeTextDecorationThickness: TextRangeMethods['setRangeTextDecorationThickness']
- declare getRangeTextDecorationColor: TextRangeMethods['getRangeTextDecorationColor']
- declare setRangeTextDecorationColor: TextRangeMethods['setRangeTextDecorationColor']
- declare getRangeTextDecorationSkipInk: TextRangeMethods['getRangeTextDecorationSkipInk']
- declare setRangeTextDecorationSkipInk: TextRangeMethods['setRangeTextDecorationSkipInk']
- declare getRangeOpenTypeFeatures: TextRangeMethods['getRangeOpenTypeFeatures']
- declare getRangeListOptions: TextRangeMethods['getRangeListOptions']
- declare setRangeListOptions: TextRangeMethods['setRangeListOptions']
- declare getRangeIndentation: TextRangeMethods['getRangeIndentation']
- declare setRangeIndentation: TextRangeMethods['setRangeIndentation']
- declare getRangeListSpacing: TextRangeMethods['getRangeListSpacing']
- declare setRangeListSpacing: TextRangeMethods['setRangeListSpacing']
- declare getRangeParagraphSpacing: TextRangeMethods['getRangeParagraphSpacing']
- declare setRangeParagraphSpacing: TextRangeMethods['setRangeParagraphSpacing']
- declare getRangeParagraphIndent: TextRangeMethods['getRangeParagraphIndent']
- declare setRangeParagraphIndent: TextRangeMethods['setRangeParagraphIndent']
- declare getRangeTextCase: TextRangeMethods['getRangeTextCase']
- declare setRangeTextCase: TextRangeMethods['setRangeTextCase']
- declare getRangeHyperlink: TextRangeMethods['getRangeHyperlink']
- declare setRangeHyperlink: TextRangeMethods['setRangeHyperlink']
- declare getRangeTextStyleId: TextRangeMethods['getRangeTextStyleId']
- declare setRangeTextStyleId: TextRangeMethods['setRangeTextStyleId']
- declare setRangeTextStyleIdAsync: TextRangeMethods['setRangeTextStyleIdAsync']
- declare getRangeFillStyleId: TextRangeMethods['getRangeFillStyleId']
- declare setRangeFillStyleId: TextRangeMethods['setRangeFillStyleId']
- declare setRangeFillStyleIdAsync: TextRangeMethods['setRangeFillStyleIdAsync']
- declare getRangeBoundVariable: TextRangeMethods['getRangeBoundVariable']
- declare setRangeBoundVariable: TextRangeMethods['setRangeBoundVariable']
-
constructor(id: string, graph: SceneGraph, api: NodeProxyHost) {
+ super()
this[INTERNAL_ID] = id
this[INTERNAL_GRAPH] = graph
this[INTERNAL_API] = api
@@ -272,10 +78,18 @@ export class FigmaNodeProxy {
const internals = { id: INTERNAL_ID, graph: INTERNAL_GRAPH, api: INTERNAL_API }
if (type === 'VECTOR') installVectorNodeProxyAccessors(this, internals, MIXED)
if (type) installShapeNodeProxyAccessors(this, internals, type)
+ if (type) installComponentNodeAccessors(this, internals, type)
+ if (type) installGuideAccessors(this, internals, type)
+ if (type) installInstanceOverrideAccessors(this, internals, type)
+ if (type) installStyleReferenceAccessors(this, internals, type, id === graph.rootId, MIXED)
// Figma loads a page's layers on demand in dynamic-page mode and has `loadAsync` on pages
// alone; every page here is already loaded.
if (type === 'CANVAS')
Object.defineProperty(this, 'loadAsync', { value: () => Promise.resolve() })
+ if (id === graph.rootId)
+ Object.defineProperty(this, 'documentColorProfile', {
+ get: () => (graph.documentColorSpace === 'display-p3' ? 'DISPLAY_P3' : 'SRGB')
+ })
}
private _update(changes: Partial<SceneNode>): void {
@@ -563,7 +377,6 @@ installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
installVariableModeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
installPluginDataMethods(FigmaNodeProxy.prototype, proxyInternals)
installComponentPropertyAccessors(FigmaNodeProxy.prototype, proxyInternals)
-installInstanceOverrideAccessors(FigmaNodeProxy.prototype, proxyInternals)
installSlotAccessors(FigmaNodeProxy.prototype, proxyInternals)
installDevStatusAccessors(FigmaNodeProxy.prototype, proxyInternals)
installShapeWithTextAccessors(FigmaNodeProxy.prototype, proxyInternals)
diff --git a/packages/core/src/figma-api/styles/api.ts b/packages/core/src/figma-api/styles/api.ts
new file mode 100644
index 000000000..eede09b6c
--- /dev/null
+++ b/packages/core/src/figma-api/styles/api.ts
@@ -0,0 +1,168 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { GroupFitOptions } from '@open-pencil/scene-graph/group-bounds'
+import { internalCanvas, newSharedStyleId } from '@open-pencil/scene-graph/shared-styles'
+
+import { applyLayerChanges } from '#core/figma-api/accessor-utils'
+import type { FigmaNodeProxy } from '#core/figma-api/proxy'
+
+import {
+ FigmaEffectStyle,
+ FigmaGridStyle,
+ FigmaPaintStyle,
+ FigmaTextStyle,
+ STYLE_TYPES,
+ type FigmaBaseStyle,
+ type FigmaStyleType,
+ type StyleHost
+} from './handles'
+
+/** What the style methods need from `figma`. */
+interface StyleOwner {
+ readonly graph: SceneGraph
+ readonly groupFitOptions: GroupFitOptions
+ wrapNode(id: string): FigmaNodeProxy
+}
+
+interface StyleClasses {
+ PAINT: FigmaPaintStyle
+ TEXT: FigmaTextStyle
+ EFFECT: FigmaEffectStyle
+ GRID: FigmaGridStyle
+}
+
+const CLASSES = {
+ PAINT: FigmaPaintStyle,
+ TEXT: FigmaTextStyle,
+ EFFECT: FigmaEffectStyle,
+ GRID: FigmaGridStyle
+}
+
+/** Each API's style handles by ID, so a style reads back as the same object, as in Figma. */
+const handlesByOwner = new WeakMap<StyleOwner, Map<string, FigmaBaseStyle>>()
+
+function handles(owner: StyleOwner): Map<string, FigmaBaseStyle> {
+ let found = handlesByOwner.get(owner)
+ if (!found) {
+ found = new Map()
+ handlesByOwner.set(owner, found)
+ }
+ return found
+}
+
+function host(owner: StyleOwner): StyleHost {
+ return {
+ graph: owner.graph,
+ wrapNode: (id) => owner.wrapNode(id),
+ updateLayer: (node, changes, inInstance) =>
+ applyLayerChanges(owner.graph, node.id, changes, owner.groupFitOptions, !inInstance),
+ forgetStyle: (id) => handles(owner).delete(id)
+ }
+}
+
+function handle<T extends FigmaStyleType>(owner: StyleOwner, type: T, id: string): StyleClasses[T] {
+ const cache = handles(owner)
+ const found = cache.get(id)
+ if (found?.type === type) return found as StyleClasses[T]
+ const made = new CLASSES[type](host(owner), id) as StyleClasses[T]
+ cache.set(id, made)
+ return made
+}
+
+function typeOf(node: SceneNode): FigmaStyleType | null {
+ const entry = Object.entries(STYLE_TYPES).find(([, type]) => type === node.sharedStyleType)
+ return entry ? (entry[0] as FigmaStyleType) : null
+}
+
+/** A new style of `type`, empty and unnamed, kept on the document's internal page as Figma's. */
+function createStyle<T extends FigmaStyleType>(owner: StyleOwner, type: T): StyleClasses[T] {
+ const { graph } = owner
+ const node = graph.createNode(type === 'TEXT' ? 'TEXT' : 'RECTANGLE', internalCanvas(graph).id, {
+ name: '',
+ sharedStyleType: STYLE_TYPES[type],
+ internalOnly: true,
+ // A text style starts as Figma's does, at 12px; the others start empty.
+ ...(type === 'TEXT' ? { fontSize: 12 } : { fills: [] }),
+ effects: [],
+ layoutGrids: []
+ })
+ const id = newSharedStyleId()
+ node.source.id = id
+ return handle(owner, type, id)
+}
+
+/** The document's own styles of `type`, in the order they were made, as Figma lists them. */
+function localStyles<T extends FigmaStyleType>(owner: StyleOwner, type: T): StyleClasses[T][] {
+ const styles: StyleClasses[T][] = []
+ for (const node of owner.graph.getAllNodes()) {
+ if (node.sharedStyleType === STYLE_TYPES[type] && node.source.id)
+ styles.push(handle(owner, type, node.source.id))
+ }
+ return styles
+}
+
+function styleById(owner: StyleOwner, id: unknown): FigmaBaseStyle | null {
+ if (typeof id !== 'string' || !id) return null
+ for (const node of owner.graph.getAllNodes()) {
+ const type = typeOf(node)
+ if (type && node.source.id === id) return handle(owner, type, id)
+ }
+ return null
+}
+
+/**
+ * Figma's style members of `figma`, which `FigmaAPI` extends; installed at runtime below, this
+ * class only declares their types.
+ */
+export abstract class FigmaStyleMethods {
+ declare createPaintStyle: () => FigmaPaintStyle
+ declare createTextStyle: () => FigmaTextStyle
+ declare createEffectStyle: () => FigmaEffectStyle
+ declare createGridStyle: () => FigmaGridStyle
+ declare getLocalPaintStyles: () => FigmaPaintStyle[]
+ declare getLocalTextStyles: () => FigmaTextStyle[]
+ declare getLocalEffectStyles: () => FigmaEffectStyle[]
+ declare getLocalGridStyles: () => FigmaGridStyle[]
+ declare getLocalPaintStylesAsync: () => Promise<FigmaPaintStyle[]>
+ declare getLocalTextStylesAsync: () => Promise<FigmaTextStyle[]>
+ declare getLocalEffectStylesAsync: () => Promise<FigmaEffectStyle[]>
+ declare getLocalGridStylesAsync: () => Promise<FigmaGridStyle[]>
+ declare getStyleById: (id: string) => FigmaBaseStyle | null
+ declare getStyleByIdAsync: (id: string) => Promise<FigmaBaseStyle | null>
+}
+
+const NAMES = { PAINT: 'Paint', TEXT: 'Text', EFFECT: 'Effect', GRID: 'Grid' } as const
+
+function installStyleMethods(prototype: object): void {
+ const methods: PropertyDescriptorMap = {
+ getStyleById: {
+ value(this: StyleOwner, id: unknown) {
+ return styleById(this, id)
+ }
+ },
+ getStyleByIdAsync: {
+ value(this: StyleOwner, id: unknown) {
+ return Promise.resolve(styleById(this, id))
+ }
+ }
+ }
+ for (const [type, name] of Object.entries(NAMES) as Array<[FigmaStyleType, string]>) {
+ methods[`create${name}Style`] = {
+ value(this: StyleOwner) {
+ return createStyle(this, type)
+ }
+ }
+ methods[`getLocal${name}Styles`] = {
+ value(this: StyleOwner) {
+ return localStyles(this, type)
+ }
+ }
+ methods[`getLocal${name}StylesAsync`] = {
+ value(this: StyleOwner) {
+ return Promise.resolve(localStyles(this, type))
+ }
+ }
+ }
+ Object.defineProperties(prototype, methods)
+}
+
+installStyleMethods(FigmaStyleMethods.prototype)
diff --git a/packages/core/src/figma-api/styles/apply.ts b/packages/core/src/figma-api/styles/apply.ts
new file mode 100644
index 000000000..1887e85a1
--- /dev/null
+++ b/packages/core/src/figma-api/styles/apply.ts
@@ -0,0 +1,197 @@
+import type { InheritedStyleField } from '@figma/plugin-typings/plugin-api-standalone'
+
+import type {
+ CharacterStyleOverride,
+ SceneGraph,
+ SceneNode,
+ SharedStyleKind,
+ SharedStyleType
+} from '@open-pencil/scene-graph'
+import { findInstanceAncestor } from '@open-pencil/scene-graph/instances'
+import {
+ findSharedStyle,
+ sharedStyleDetachPatch,
+ sharedStylePatch,
+ sharedStyleRefKey,
+ sharedStyleTypeForKind
+} from '@open-pencil/scene-graph/shared-styles'
+
+import { figmaFills } from '#core/figma-api/accessors/visual'
+import { rangeSharedStylePatch } from '#core/figma-api/text/bindings'
+import { setPaintBindings } from '#core/figma-api/variables/bindings'
+import {
+ layerTextStyleChanges,
+ styleRunsWithPatchOver,
+ textStyleChanges
+} from '#core/text/character-style'
+
+/** Figma's message for a style ID the document does not hold, or one of another kind. */
+export const STYLE_NOT_FOUND = 'Cannot set style successfully: Cannot find style'
+
+/** The kinds of reference a style of each type is used through. */
+const KINDS_OF_TYPE: Record<SharedStyleType, readonly SharedStyleKind[]> = {
+ FILL: ['fill', 'stroke'],
+ TEXT: ['text'],
+ EFFECT: ['effect'],
+ GRID: ['grid']
+}
+
+/**
+ * Applies changes to a layer the way the plugin API's own setters do. A layer inside an instance
+ * takes a style's values without them counting as its own overrides.
+ */
+export type LayerUpdate = (
+ node: SceneNode,
+ changes: Partial<SceneNode>,
+ inInstance: boolean
+) => void
+
+/**
+ * The changes that give `node` the style with `styleId`, or take its style off when the ID is
+ * empty, keeping the values it had; null when the document holds no such style. A text takes a
+ * text or fill style in every character, as Figma's node setters give it.
+ */
+export function styleChanges(
+ graph: SceneGraph,
+ node: SceneNode,
+ kind: SharedStyleKind,
+ styleId: string
+): Partial<SceneNode> | null {
+ const wholeText = node.type === 'TEXT' && (kind === 'text' || kind === 'fill')
+ if (styleId === '') {
+ // Every character leaves the style, those that use it themselves too.
+ const patch = sharedStyleDetachPatch(kind)
+ return wholeText ? textStyleChanges(node, patch) : patch
+ }
+ const style = findSharedStyle(graph, styleId, sharedStyleTypeForKind(kind))
+ if (!style) return null
+ const patch = sharedStylePatch(kind, node, styleId, style)
+ return wholeText ? layerTextStyleChanges(node, patch) : patch
+}
+
+/**
+ * Binds `node`'s fills or strokes to the variables its paint style's paints are bound to, and
+ * drops bindings the style's paints do not carry, so the layer follows them as in Figma.
+ */
+export function bindStylePaints(
+ graph: SceneGraph,
+ node: SceneNode,
+ kind: SharedStyleKind,
+ styleId: string
+): void {
+ if ((kind !== 'fill' && kind !== 'stroke') || !styleId) return
+ const style = findSharedStyle(graph, styleId, 'FILL')
+ if (!style) return
+ setPaintBindings(graph, node, kind === 'fill' ? 'fills' : 'strokes', figmaFills(graph, style))
+}
+
+/** A layer that uses a style itself, and the fields it uses it through, as Figma lists them. */
+export interface StyleConsumer {
+ node: SceneNode
+ fields: InheritedStyleField[]
+}
+
+/** Whether `node` sits inside an instance; an instance itself does not. */
+function insideInstance(graph: SceneGraph, node: SceneNode): boolean {
+ return node.parentId !== null && findInstanceAncestor(graph, node.parentId) !== undefined
+}
+
+function listedConsumer(graph: SceneGraph, node: SceneNode): boolean {
+ // A style's own node is no consumer, and layers inside an instance follow their component.
+ return node.sharedStyleType === null && !insideInstance(graph, node)
+}
+
+/** The layers that use `style` themselves; characters of a text that use it are not listed. */
+export function styleConsumers(graph: SceneGraph, style: SceneNode): StyleConsumer[] {
+ const kinds = style.sharedStyleType ? KINDS_OF_TYPE[style.sharedStyleType] : []
+ const consumers: StyleConsumer[] = []
+ for (const node of graph.getAllNodes()) {
+ if (!listedConsumer(graph, node)) continue
+ const fields = kinds
+ .map((kind) => sharedStyleRefKey(kind))
+ .filter((field) => node[field] === style.source.id)
+ if (fields.length > 0) consumers.push({ node, fields })
+ }
+ return consumers
+}
+
+/** The runs of a text after `patch` restyles, in one pass, every run that uses the style `id`. */
+function restyledRuns(
+ node: SceneNode,
+ field: 'textStyleId' | 'fillStyleId',
+ id: string,
+ patch: () => CharacterStyleOverride
+): SceneNode['styleRuns'] | null {
+ const ranges = node.styleRuns
+ .filter((run) => run.style[field] === id)
+ .map((run) => [run.start, run.start + run.length] as const)
+ return ranges.length > 0 ? styleRunsWithPatchOver(node, ranges, patch()) : null
+}
+
+/**
+ * Gives every layer and text range that uses `style` its current values, as Figma does once a
+ * style changes; `patch` decides each layer's changes for each kind it uses, and `after` runs on
+ * each layer that uses it itself once its changes are in. Layers inside instances are updated
+ * too, so one that overrides a style follows it, without the update counting as an override.
+ */
+function updateUsers(
+ graph: SceneGraph,
+ style: SceneNode,
+ update: LayerUpdate,
+ patch: (node: SceneNode, kind: SharedStyleKind) => Partial<SceneNode>,
+ rangePatch: (kind: 'text' | 'fill') => CharacterStyleOverride,
+ after?: (node: SceneNode, kind: SharedStyleKind) => void
+): void {
+ const id = style.source.id
+ if (!id || !style.sharedStyleType) return
+ const kinds = KINDS_OF_TYPE[style.sharedStyleType]
+ // A style's range patch is the same for every text, so it is built once, when one needs it.
+ const rangePatches = new Map<'text' | 'fill', CharacterStyleOverride>()
+ const lazyRangePatch = (kind: 'text' | 'fill') => () => {
+ const found = rangePatches.get(kind) ?? rangePatch(kind)
+ rangePatches.set(kind, found)
+ return found
+ }
+ for (const node of graph.getAllNodes()) {
+ if (node.sharedStyleType !== null) continue
+ const own = kinds.filter((kind) => node[sharedStyleRefKey(kind)] === id)
+ const changes: Partial<SceneNode> = {}
+ for (const kind of own) Object.assign(changes, patch(node, kind))
+ if (node.type === 'TEXT') {
+ // A text or fill style reaches characters through one kind of run reference.
+ const runKind = kinds.find((kind) => kind === 'text' || kind === 'fill')
+ const field = runKind === 'text' ? 'textStyleId' : 'fillStyleId'
+ const runs = runKind && restyledRuns(node, field, id, lazyRangePatch(runKind))
+ if (runs) changes.styleRuns = runs
+ }
+ if (Object.keys(changes).length === 0) continue
+ update(node, changes, insideInstance(graph, node))
+ const updated = graph.getNode(node.id)
+ if (updated && after) for (const kind of own) after(updated, kind)
+ }
+}
+
+/** Gives the layers and text ranges that use `style` its values, after the style changed. */
+export function restyleUsers(graph: SceneGraph, style: SceneNode, update: LayerUpdate): void {
+ const id = style.source.id ?? ''
+ updateUsers(
+ graph,
+ style,
+ update,
+ // A layer's own fields only: its ranges keep the values they set themselves.
+ (node, kind) => sharedStylePatch(kind, node, id, style),
+ (kind) => rangeSharedStylePatch(graph, kind, id) ?? {},
+ (node, kind) => bindStylePaints(graph, node, kind, id)
+ )
+}
+
+/** Takes `style` off everything that uses it, which keeps the values it gave, as in Figma. */
+export function releaseUsers(graph: SceneGraph, style: SceneNode, update: LayerUpdate): void {
+ updateUsers(
+ graph,
+ style,
+ update,
+ (_node, kind) => sharedStyleDetachPatch(kind),
+ (kind) => ({ [kind === 'text' ? 'textStyleId' : 'fillStyleId']: null })
+ )
+}
diff --git a/packages/core/src/figma-api/styles/handles.ts b/packages/core/src/figma-api/styles/handles.ts
new file mode 100644
index 000000000..5a570eea7
--- /dev/null
+++ b/packages/core/src/figma-api/styles/handles.ts
@@ -0,0 +1,251 @@
+import type {
+ StyleConsumers,
+ StyleType,
+ TextStyle
+} from '@figma/plugin-typings/plugin-api-standalone'
+
+import type { SceneGraph, SceneNode, SharedStyleType } from '@open-pencil/scene-graph'
+
+import { invalid, received } from '#core/figma-api/accessors/text/messages'
+import { figmaFills } from '#core/figma-api/accessors/visual'
+import { parseFigmaPaints, type FigmaPaint } from '#core/figma-api/paints'
+import type { FigmaNodeProxy } from '#core/figma-api/proxy'
+import { setPaintBindings } from '#core/figma-api/variables/bindings'
+
+import { releaseUsers, restyleUsers, styleConsumers, type LayerUpdate } from './apply'
+
+/** The kinds of style OpenPencil keeps: Figma's, apart from custom animations. */
+export type FigmaStyleType = Exclude<StyleType, 'CUSTOM_ANIMATION'>
+
+export const STYLE_TYPES: Record<FigmaStyleType, SharedStyleType> = {
+ PAINT: 'FILL',
+ TEXT: 'TEXT',
+ EFFECT: 'EFFECT',
+ GRID: 'GRID'
+}
+
+/** What a style needs from the API that made it. */
+export interface StyleHost {
+ readonly graph: SceneGraph
+ wrapNode(id: string): FigmaNodeProxy
+ /** Applies changes to a layer as the plugin API's setters do. */
+ readonly updateLayer: LayerUpdate
+ /** Forgets a removed style's handle. */
+ forgetStyle(id: string): void
+}
+
+/** Figma's `StyleConsumers`, the layer read as a node proxy. */
+export type FigmaStyleConsumer = Omit<StyleConsumers, 'node'> & { node: FigmaNodeProxy }
+
+const KEY = /^S:([0-9a-f]{40}),/
+
+// Internals keyed by symbols, so scripts reach only the members of Figma's styles.
+const HOST = Symbol('host')
+const NODE = Symbol('node')
+const LAYER = Symbol('layer')
+const RESTYLE = Symbol('restyle')
+
+/**
+ * Figma's `BaseStyle`: a shared style the document holds, read and written through the node that
+ * keeps its values. A change to the style reaches every layer and text range that uses it.
+ */
+export abstract class FigmaBaseStyle {
+ readonly id: string
+ abstract readonly type: FigmaStyleType
+ readonly remote = false
+ readonly documentationLinks: readonly never[] = Object.freeze([])
+ readonly boundVariables: Readonly<Record<string, never>> = Object.freeze({})
+ readonly [HOST]: StyleHost
+
+ constructor(host: StyleHost, id: string) {
+ this[HOST] = host
+ this.id = id
+ }
+
+ /** The node holding the style's values, or Figma's refusal once the style is gone. */
+ [NODE](method: string): SceneNode {
+ const type = STYLE_TYPES[this.type]
+ for (const node of this[HOST].graph.getAllNodes())
+ if (node.sharedStyleType === type && node.source.id === this.id) return node
+ throw new Error(`in ${method}: The style with id "${this.id}" does not exist`)
+ }
+
+ /** The style's node as a layer, whose setters check and store its values. */
+ [LAYER](method: string): FigmaNodeProxy {
+ return this[HOST].wrapNode(this[NODE](method).id)
+ }
+
+ /** Brings what uses the style up to its values, after they changed. */
+ [RESTYLE](): void {
+ restyleUsers(this[HOST].graph, this[NODE]('restyle'), this[HOST].updateLayer)
+ }
+
+ get name(): string {
+ return this[NODE]('get_name').name
+ }
+
+ set name(value: string) {
+ const node = this[NODE]('set_name')
+ if (typeof value !== 'string') {
+ throw invalid('set_name', `Expected string, received ${received(value)}`, 'name')
+ }
+ this[HOST].graph.updateNode(node.id, { name: value })
+ }
+
+ get description(): string {
+ return this[NODE]('get_description').symbolDescription
+ }
+
+ /** Figma ignores a description that is not a string, without an error. */
+ set description(value: string) {
+ const node = this[NODE]('set_description')
+ if (typeof value === 'string')
+ this[HOST].graph.updateNode(node.id, { symbolDescription: value })
+ }
+
+ /** The key a library publishes the style by: the hex part of a local style's ID. */
+ get key(): string {
+ this[NODE]('get_key')
+ return KEY.exec(this.id)?.[1] ?? ''
+ }
+
+ /** @deprecated Figma's synchronous form of `getStyleConsumersAsync`. */
+ get consumers(): FigmaStyleConsumer[] {
+ return styleConsumers(this[HOST].graph, this[NODE]('get_consumers')).map(
+ ({ node, fields }) => ({
+ node: this[HOST].wrapNode(node.id),
+ fields
+ })
+ )
+ }
+
+ /** The layers that use the style themselves; text ranges that use it are not listed. */
+ getStyleConsumersAsync(): Promise<FigmaStyleConsumer[]> {
+ return Promise.resolve(this.consumers)
+ }
+
+ /** Deletes the style; what used it keeps the values it gave, as in Figma. */
+ remove(): void {
+ const style = this[NODE]('remove')
+ releaseUsers(this[HOST].graph, style, this[HOST].updateLayer)
+ this[HOST].graph.deleteNode(style.id)
+ this[HOST].forgetStyle(this.id)
+ }
+}
+
+export class FigmaPaintStyle extends FigmaBaseStyle {
+ readonly type = 'PAINT'
+
+ get paints(): readonly FigmaPaint[] {
+ const node = this[NODE]('get_paints')
+ return Object.freeze(figmaFills(this[HOST].graph, node).map((paint) => Object.freeze(paint)))
+ }
+
+ set paints(value: readonly FigmaPaint[]) {
+ const node = this[NODE]('set_paints')
+ const fills = parseFigmaPaints(value, 'set_paints', 'paints')
+ this[HOST].graph.updateNode(node.id, { fills })
+ // A paint bound to a variable keeps following it, as the style's consumers then do.
+ setPaintBindings(this[HOST].graph, node, 'fills', value)
+ this[RESTYLE]()
+ }
+}
+
+export class FigmaEffectStyle extends FigmaBaseStyle {
+ readonly type = 'EFFECT'
+
+ get effects(): FigmaNodeProxy['effects'] {
+ return this[LAYER]('get_effects').effects
+ }
+
+ set effects(value: FigmaNodeProxy['effects']) {
+ this[LAYER]('set_effects').effects = value
+ this[RESTYLE]()
+ }
+}
+
+export class FigmaGridStyle extends FigmaBaseStyle {
+ readonly type = 'GRID'
+
+ get layoutGrids(): FigmaNodeProxy['layoutGrids'] {
+ return this[LAYER]('get_layoutGrids').layoutGrids
+ }
+
+ set layoutGrids(value: FigmaNodeProxy['layoutGrids']) {
+ this[LAYER]('set_layoutGrids').layoutGrids = value
+ this[RESTYLE]()
+ }
+}
+
+/** The fields a text style keeps, read and written as a text's own (Figma desktop 126). */
+export const TEXT_STYLE_PROPERTIES = [
+ 'fontName',
+ 'fontSize',
+ 'lineHeight',
+ 'letterSpacing',
+ 'textCase',
+ 'textDecoration',
+ 'textDecorationStyle',
+ 'textDecorationOffset',
+ 'textDecorationThickness',
+ 'textDecorationColor',
+ 'textDecorationSkipInk',
+ 'leadingTrim',
+ 'paragraphSpacing',
+ 'paragraphIndent',
+ 'listSpacing',
+ 'hangingList'
+] as const satisfies readonly (keyof FigmaNodeProxy)[]
+
+type TextStyleProperty = (typeof TEXT_STYLE_PROPERTIES)[number]
+
+export class FigmaTextStyle extends FigmaBaseStyle {
+ readonly type = 'TEXT'
+ declare fontName: TextStyle['fontName']
+ declare fontSize: TextStyle['fontSize']
+ declare lineHeight: TextStyle['lineHeight']
+ declare letterSpacing: TextStyle['letterSpacing']
+ declare textCase: TextStyle['textCase']
+ declare textDecoration: TextStyle['textDecoration']
+ declare textDecorationStyle: FigmaNodeProxy['textDecorationStyle']
+ declare textDecorationOffset: FigmaNodeProxy['textDecorationOffset']
+ declare textDecorationThickness: FigmaNodeProxy['textDecorationThickness']
+ declare textDecorationColor: FigmaNodeProxy['textDecorationColor']
+ declare textDecorationSkipInk: FigmaNodeProxy['textDecorationSkipInk']
+ declare leadingTrim: TextStyle['leadingTrim']
+ declare paragraphSpacing: TextStyle['paragraphSpacing']
+ declare paragraphIndent: TextStyle['paragraphIndent']
+ declare listSpacing: TextStyle['listSpacing']
+ declare hangingList: TextStyle['hangingList']
+}
+
+// Each field is read from, and written to, the text that keeps the style, which checks it as a
+// text's own setter does; a change restyles what uses the style.
+for (const property of TEXT_STYLE_PROPERTIES satisfies readonly TextStyleProperty[]) {
+ Object.defineProperty(FigmaTextStyle.prototype, property, {
+ enumerable: true,
+ get(this: FigmaTextStyle) {
+ return this[LAYER](`get_${property}`)[property]
+ },
+ set(this: FigmaTextStyle, value: never) {
+ this[LAYER](`set_${property}`)[property] = value
+ this[RESTYLE]()
+ }
+ })
+}
+
+// Figma lists a style's members when a script enumerates it, so its accessors are enumerable.
+for (const style of [
+ FigmaBaseStyle,
+ FigmaPaintStyle,
+ FigmaEffectStyle,
+ FigmaGridStyle,
+ FigmaTextStyle
+]) {
+ for (const [name, descriptor] of Object.entries(
+ Object.getOwnPropertyDescriptors(style.prototype)
+ )) {
+ if (descriptor.get && !descriptor.enumerable)
+ Object.defineProperty(style.prototype, name, { ...descriptor, enumerable: true })
+ }
+}
diff --git a/packages/core/src/figma-api/surface.ts b/packages/core/src/figma-api/surface.ts
index dfa186539..86e638c21 100644
--- a/packages/core/src/figma-api/surface.ts
+++ b/packages/core/src/figma-api/surface.ts
@@ -24,10 +24,24 @@ export const FIGMA_API_HOST_MEMBERS = [
*/
export const FIGMA_API_INCOMPLETE_MEMBERS = [
'createComponentFromNode',
+ 'createEffectStyle',
+ 'createGridStyle',
'createPage',
+ 'createPaintStyle',
+ 'createTextStyle',
'currentPage',
+ 'getLocalEffectStyles',
+ 'getLocalEffectStylesAsync',
+ 'getLocalGridStyles',
+ 'getLocalGridStylesAsync',
+ 'getLocalPaintStyles',
+ 'getLocalPaintStylesAsync',
+ 'getLocalTextStyles',
+ 'getLocalTextStylesAsync',
'getNodeById',
'getNodeByIdAsync',
+ 'getStyleById',
+ 'getStyleByIdAsync',
'mixed',
'root',
'variables',
diff --git a/packages/core/src/figma-api/text/bindings.ts b/packages/core/src/figma-api/text/bindings.ts
index 5f6b6cffd..aa2de402d 100644
--- a/packages/core/src/figma-api/text/bindings.ts
+++ b/packages/core/src/figma-api/text/bindings.ts
@@ -10,8 +10,9 @@ import {
type Variable
} from '@open-pencil/scene-graph'
import { copyFills } from '@open-pencil/scene-graph/copy'
-import { getSharedStyles, SHARED_TEXT_STYLE_FIELDS } from '@open-pencil/scene-graph/shared-styles'
+import { findSharedStyle, SHARED_TEXT_STYLE_FIELDS } from '@open-pencil/scene-graph/shared-styles'
+import { invalidOption } from '#core/figma-api/accessors/text/messages'
import { variableAlias, type FigmaVariableAlias } from '#core/figma-api/variables/values'
import { styleRunsWithPatch } from '#core/text/character-style'
import { faceForStyle } from '#core/text/font/names'
@@ -30,19 +31,18 @@ function isParagraphField(
/**
* The style a text or fill style gives characters that use it, with the reference that keeps
- * them attached. An empty ID detaches them; a style the document does not hold attaches by ID
- * alone, as the text's own setters do.
+ * them attached; an empty ID detaches them, keeping their values. Null when the document holds
+ * no such style, which Figma refuses.
*/
export function rangeSharedStylePatch(
graph: SceneGraph,
kind: 'text' | 'fill',
styleId: string
-): CharacterStyleOverride {
+): CharacterStyleOverride | null {
const key = kind === 'text' ? 'textStyleId' : 'fillStyleId'
if (!styleId) return { [key]: null }
- const found = getSharedStyles(graph, kind).find((style) => style.id === styleId)
- const style = found ? graph.getNode(found.nodeId) : undefined
- if (!style) return { [key]: styleId }
+ const style = findSharedStyle(graph, styleId, kind === 'text' ? 'TEXT' : 'FILL')
+ if (!style) return null
if (kind === 'fill') return { fillStyleId: styleId, fills: copyFills(style.fills) }
return { textStyleId: styleId, ...structuredClone(pick(style, SHARED_TEXT_STYLE_FIELDS)) }
}
@@ -51,8 +51,7 @@ export function rangeSharedStylePatch(
export function assertTextBindableField(method: string, field: unknown): TextBindableField {
if (!(TEXT_BINDABLE_FIELDS as readonly unknown[]).includes(field)) {
throw new Error(
- `in ${method}: Property "field" failed validation: Invalid enum value. Expected ` +
- `${TEXT_BINDABLE_FIELDS.map((name) => `'${name}'`).join(' | ')}, received '${String(field)}'`
+ `in ${method}: Property "field" failed validation: ${invalidOption(TEXT_BINDABLE_FIELDS)}`
)
}
return field as TextBindableField
diff --git a/packages/core/src/figma-api/text/index.ts b/packages/core/src/figma-api/text/index.ts
index 4983b9594..f7940b834 100644
--- a/packages/core/src/figma-api/text/index.ts
+++ b/packages/core/src/figma-api/text/index.ts
@@ -1,3 +1,8 @@
+import type {
+ LetterSpacing,
+ LineHeight,
+ TextListOptions
+} from '@figma/plugin-typings/plugin-api-standalone'
import { compact } from 'es-toolkit/array'
import { upperFirst } from 'es-toolkit/string'
@@ -25,19 +30,23 @@ import {
withParagraphSpacing
} from '@open-pencil/scene-graph/text'
-import { invalid, received } from '#core/figma-api/accessors/text/messages'
+import {
+ invalid,
+ invalidOption,
+ numberProblem,
+ received,
+ tooBig,
+ tooSmall
+} from '#core/figma-api/accessors/text/messages'
import { assertTextFontsLoaded } from '#core/figma-api/fonts/loaded'
import { adjustRunsForDelete, getStyleAt, insertRunsWithStyle } from '#core/text/style-runs'
import { assertTextRange } from './style'
-/** Figma's plugin API line height: automatic, or a size in pixels or percent of the font size. */
-export type FigmaLineHeight = { unit: 'AUTO' } | { unit: 'PIXELS' | 'PERCENT'; value: number }
-/** Figma's plugin API letter spacing, in pixels or percent of the font size. */
-export interface FigmaLetterSpacing {
- unit: 'PIXELS' | 'PERCENT'
- value: number
-}
+/** Figma's `LineHeight`: automatic, or a size in pixels or percent of the font size. */
+export type FigmaLineHeight = LineHeight
+/** Figma's `LetterSpacing`, in pixels or percent of the font size. */
+export type FigmaLetterSpacing = LetterSpacing
/** Figma's complaint about a length's `.value`, or null when it is a number. */
function amountProblem(amount: unknown): string | null {
@@ -229,22 +238,33 @@ export function getRangeListOptions(
return types.size === 1 ? { type } : mixed
}
+function isListType(value: unknown): value is TextListOptions['type'] {
+ return (LIST_TYPES as ReadonlySet<unknown>).has(value)
+}
+
export function setRangeListOptions(
graph: SceneGraph,
node: SceneNode,
start: number,
end: number,
- options: TextListOptions
+ value: TextListOptions
): void {
- if (!LIST_TYPES.has(options.type)) {
- throw new Error(
- `in setRangeListOptions: Property "options" failed validation: Invalid enum value. ` +
- `Expected 'NONE' | 'ORDERED' | 'UNORDERED', received '${String(options.type)}' at .type`
+ // Scripts pass anything, whatever the types say.
+ const options: unknown = value
+ if (!options || typeof options !== 'object') {
+ throw invalid(
+ 'setRangeListOptions',
+ `Expected object, received ${received(options)}`,
+ 'options'
)
}
+ const type: unknown = Reflect.get(options, 'type')
+ if (!isListType(type)) {
+ throw invalid('setRangeListOptions', invalidOption(LIST_TYPES, ' at .type'), 'options')
+ }
assertTextRange('setRangeListOptions', node, start, end)
assertTextFontsLoaded('setRangeListOptions', node)
- updateParagraphs(graph, node, start, end, (style) => withListType(style, options.type))
+ updateParagraphs(graph, node, start, end, (style) => withListType(style, type))
}
export function getRangeIndentation(
@@ -260,11 +280,12 @@ export function getRangeIndentation(
}
/** What Figma reports about an indentation it rejects, or `null`. */
-function indentationProblem(level: number): string | null {
- if (!Number.isInteger(level)) return 'Expected integer, received float'
- if (level < 0) return 'Number must be greater than or equal to 0'
- if (level > MAX_LIST_INDENTATION)
- return `Number must be less than or equal to ${MAX_LIST_INDENTATION}`
+function indentationProblem(level: unknown): string | null {
+ const problem = numberProblem(level)
+ if (problem) return problem
+ if (!Number.isInteger(level)) return 'Expected int, received number'
+ if ((level as number) < 0) return tooSmall(0)
+ if ((level as number) > MAX_LIST_INDENTATION) return tooBig(MAX_LIST_INDENTATION)
return null
}
@@ -275,10 +296,8 @@ export function setRangeIndentation(
end: number,
level: number
): void {
- const invalid = indentationProblem(level)
- if (invalid) {
- throw new Error(`in setRangeIndentation: Property "indentation" failed validation: ${invalid}`)
- }
+ const problem = indentationProblem(level)
+ if (problem) throw invalid('setRangeIndentation', problem, 'indentation')
assertTextRange('setRangeIndentation', node, start, end)
assertTextFontsLoaded('setRangeIndentation', node)
updateParagraphs(graph, node, start, end, (style) => withIndentation(style, level))
@@ -292,9 +311,9 @@ function spacingParagraphs(node: SceneNode, start: number, end: number): [number
return [paragraphIndexAt(node.text, start), paragraphIndexAt(node.text, end)]
}
-/** What Figma reports about a spacing it rejects, or `null`. */
-export function spacingProblem(value: number): string | null {
- return value >= 0 ? null : 'Number must be greater than or equal to 0'
+/** What Figma reports about a spacing it rejects, a finite number of 0 or more, or `null`. */
+export function spacingProblem(value: unknown): string | null {
+ return numberProblem(value) ?? ((value as number) >= 0 ? null : tooSmall(0))
}
export function getRangeParagraphSpacing(
diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.ts
index cf450f1df..854cd1b84 100644
--- a/packages/core/src/figma-api/text/style.ts
+++ b/packages/core/src/figma-api/text/style.ts
@@ -1,3 +1,4 @@
+import type { TextDecorationOffset } from '@figma/plugin-typings/plugin-api-standalone'
import { mapValues, pickBy } from 'es-toolkit/object'
import { isEqual } from 'es-toolkit/predicate'
@@ -8,6 +9,7 @@ import {
paragraphStyleAt
} from '@open-pencil/scene-graph/text'
+import { invalidOption, tooSmall } from '#core/figma-api/accessors/text/messages'
import { readVariationSettings } from '#core/figma-api/fonts/variations'
import { toFigmaPaint, type FigmaPaint } from '#core/figma-api/paints'
import { variableAlias } from '#core/figma-api/variables/values'
@@ -47,7 +49,8 @@ export const TEXT_SEGMENT_FIELDS = [
export type TextSegmentField = (typeof TEXT_SEGMENT_FIELDS)[number]
/** A size Figma reads as automatic or in pixels; the node keeps pixels. */
-export type FigmaTextLength = { unit: 'AUTO' } | { unit: 'PIXELS' | 'PERCENT'; value: number }
+/** Figma's lengths that may be automatic, such as `TextDecorationOffset`. */
+export type FigmaTextLength = TextDecorationOffset
function pixels(value: number | null): FigmaTextLength {
return value === null ? { unit: 'AUTO' } : { unit: 'PIXELS', value }
@@ -124,7 +127,10 @@ const FIELD_READERS: Record<TextSegmentField, (context: FieldContext) => unknown
textDecorationColor: whenUnderlined(decorationColor),
textCase: ({ style }) => style.textCase,
lineHeight: ({ style }) => (style.lineHeight ? { ...style.lineHeight } : { unit: 'AUTO' }),
- letterSpacing: ({ style }) => ({ ...style.letterSpacing }),
+ letterSpacing: ({ style }) => ({
+ unit: style.letterSpacing.unit,
+ value: style.letterSpacing.value
+ }),
fills: ({ node, style }) => rangeFills(node, style),
textStyleId: ({ style }) => style.textStyleId ?? '',
fillStyleId: ({ style }) => style.fillStyleId ?? '',
@@ -156,9 +162,7 @@ function readField(
/** Figma's messages for a range a text method cannot use. */
export function assertTextRange(method: string, node: SceneNode, start: number, end: number) {
if (start < 0) {
- throw new Error(
- `in ${method}: Property "start" failed validation: Number must be greater than or equal to 0`
- )
+ throw new Error(`in ${method}: Property "start" failed validation: ${tooSmall(0)}`)
}
if (end <= start) {
throw new Error(`in ${method}: Empty range selected. 'end' must be greater than 'start'`)
@@ -188,6 +192,26 @@ function fieldValues(
})
}
+/** Fields that style an underline, which characters without one read as null. */
+const UNDERLINE_FIELDS: ReadonlySet<TextSegmentField> = new Set([
+ 'textDecorationStyle',
+ 'textDecorationSkipInk',
+ 'textDecorationOffset',
+ 'textDecorationThickness',
+ 'textDecorationColor'
+])
+
+/**
+ * The value characters share, or `mixed`. An underline's style is read from the underlined
+ * characters alone, and null when there are none (Figma desktop 126).
+ */
+function sharedValue(field: TextSegmentField, values: unknown[], mixed: symbol): unknown {
+ const read = UNDERLINE_FIELDS.has(field) ? values.filter((value) => value !== null) : values
+ if (read.length === 0) return null
+ const [first, ...rest] = read
+ return rest.every((value) => isEqual(value, first)) ? first : mixed
+}
+
/** The value every character of the range shares, or `mixed`. */
export function getRangeTextStyle(
method: string,
@@ -198,15 +222,13 @@ export function getRangeTextStyle(
mixed: symbol
): unknown {
assertTextRange(method, node, start, end)
- const [first, ...rest] = fieldValues(node, field, start, end)
- return rest.every((value) => isEqual(value, first)) ? first : mixed
+ return sharedValue(field, fieldValues(node, field, start, end), mixed)
}
/** The value every character of the text shares, or `mixed`; empty text reads its own style. */
export function getTextStyle(node: SceneNode, field: TextSegmentField, mixed: symbol): unknown {
if (node.text.length === 0) return readField(node, nodeStyle(node), 0, field)
- const [first, ...rest] = fieldValues(node, field, 0, node.text.length)
- return rest.every((value) => isEqual(value, first)) ? first : mixed
+ return sharedValue(field, fieldValues(node, field, 0, node.text.length), mixed)
}
export type StyledTextSegment = {
@@ -225,8 +247,8 @@ export function getStyledTextSegments(
for (const [index, field] of fields.entries()) {
if (!(TEXT_SEGMENT_FIELDS as readonly string[]).includes(field)) {
throw new Error(
- `in ${method}: Property "${method}" failed validation: Invalid enum value. Expected ` +
- `${TEXT_SEGMENT_FIELDS.map((name) => `'${name}'`).join(' | ')}, received '${String(field)}' at index ${index}`
+ `in ${method}: Property "${method}" failed validation: ` +
+ invalidOption(TEXT_SEGMENT_FIELDS, ` at index ${index}`)
)
}
}
diff --git a/packages/core/src/figma-api/types.ts b/packages/core/src/figma-api/types.ts
index 3e39f9c60..571bc9304 100644
--- a/packages/core/src/figma-api/types.ts
+++ b/packages/core/src/figma-api/types.ts
@@ -1,6 +1,9 @@
+import type { Transform } from '@figma/plugin-typings/plugin-api-standalone'
+
import type { RasterExportFormat } from '#core/io/formats/raster'
-export type FigmaTransform = [[number, number, number], [number, number, number]]
+/** Figma's `Transform`: a 2×3 affine matrix as two rows. */
+export type FigmaTransform = Transform
/** Raster export request; `pageId` names the page holding the nodes (default: the current page). */
export interface ExportImageOptions {
diff --git a/packages/core/src/figma-api/util.ts b/packages/core/src/figma-api/util.ts
index 1c0be8abb..2b2dd4ea7 100644
--- a/packages/core/src/figma-api/util.ts
+++ b/packages/core/src/figma-api/util.ts
@@ -1,5 +1,10 @@
-/// <reference types="@figma/plugin-typings" />
-
+import type {
+ BlendMode,
+ RGB,
+ RGBA,
+ SolidPaint,
+ UtilAPI
+} from '@figma/plugin-typings/plugin-api-standalone'
import { clampRgb as clampRGB, converter, parse, type Color as CuloriColor } from 'culori'
import { invalid, received } from './accessors/text/messages'
diff --git a/packages/core/src/text/character-style.ts b/packages/core/src/text/character-style.ts
index 9a1c85d92..32ce8a687 100644
--- a/packages/core/src/text/character-style.ts
+++ b/packages/core/src/text/character-style.ts
@@ -193,6 +193,15 @@ export function styleRunsWithPatch(
start: number,
end: number,
patch: TextStylePatch
+): StyleRun[] {
+ return styleRunsWithPatchOver(node, [[start, end]], patch)
+}
+
+/** Style runs with `patch` over each `[start, end)` range, rebuilding the text's runs once. */
+export function styleRunsWithPatchOver(
+ node: SceneNode,
+ ranges: ReadonlyArray<readonly [number, number]>,
+ patch: TextStylePatch
): StyleRun[] {
const length = node.text.length
const chars: CharacterStyleOverride[] = Array.from({ length }, () => ({}))
@@ -203,14 +212,16 @@ export function styleRunsWithPatch(
}
const sized = typeof patch === 'function' ? patch : null
const patches = new Map<number, CharacterStyleOverride>()
- for (let index = start; index < end; index++) {
- let style = sized ? undefined : (patch as CharacterStyleOverride)
- if (sized) {
- const fontSize = chars[index].fontSize ?? node.fontSize
- style = patches.get(fontSize) ?? sized(fontSize)
- patches.set(fontSize, style)
+ for (const [start, end] of ranges) {
+ for (let index = start; index < end; index++) {
+ let style = sized ? undefined : (patch as CharacterStyleOverride)
+ if (sized) {
+ const fontSize = chars[index].fontSize ?? node.fontSize
+ style = patches.get(fontSize) ?? sized(fontSize)
+ patches.set(fontSize, style)
+ }
+ chars[index] = { ...chars[index], ...style, ...detachedStyles(node, chars[index], style) }
}
- chars[index] = { ...chars[index], ...style, ...detachedStyles(node, chars[index], style) }
}
// A newline takes the style of the character before it, as in Figma: a range that ends a
// paragraph styles its newline too, and a newline cannot be styled on its own.
diff --git a/packages/core/tests/figma-api/accessors/basic/top-level-frame.test.ts b/packages/core/tests/figma-api/accessors/basic/top-level-frame.test.ts
new file mode 100644
index 000000000..262c2645e
--- /dev/null
+++ b/packages/core/tests/figma-api/accessors/basic/top-level-frame.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createAPI } from '#core-tests/helpers/figma-api'
+
+// Measured with the same scripts in Figma's plugin API (Figma desktop 126).
+
+describe('getTopLevelFrame', () => {
+ test('is the container a layer sits in at the top of its page or section', () => {
+ const figma = createAPI()
+ const named = <T extends { name: string }>(node: T, name: string) => {
+ node.name = name
+ return node
+ }
+ const top = named(figma.createFrame(), 'top')
+ const nested = figma.createFrame()
+ top.appendChild(nested)
+ const leaf = figma.createRectangle()
+ nested.appendChild(leaf)
+ expect(leaf.getTopLevelFrame()?.name).toBe('top')
+ expect(top.getTopLevelFrame()?.name).toBe('top')
+
+ const group = named(figma.group([figma.createRectangle()], figma.currentPage), 'group')
+ expect(group.children[0]?.getTopLevelFrame()?.name).toBe('group')
+
+ const section = named(figma.createSection(), 'section')
+ const inner = named(figma.createFrame(), 'inner')
+ section.appendChild(inner)
+ const loose = figma.createRectangle()
+ section.appendChild(loose)
+ expect(inner.getTopLevelFrame()?.name).toBe('inner')
+ expect(loose.getTopLevelFrame()?.name).toBe('section')
+ expect(section.getTopLevelFrame()?.name).toBe('section')
+ })
+
+ test('is undefined for a shape or boolean directly on a page, and for a page', () => {
+ const figma = createAPI()
+ expect(figma.createRectangle().getTopLevelFrame()).toBeUndefined()
+ const boolean = figma.union([figma.createRectangle(), figma.createEllipse()], figma.currentPage)
+ expect(boolean.getTopLevelFrame()).toBeUndefined()
+ expect(figma.currentPage.getTopLevelFrame()).toBeUndefined()
+ })
+})
+
+describe('documentColorProfile', () => {
+ test('is the document’s colour space, on the document alone', () => {
+ const figma = createAPI()
+ expect(figma.root.documentColorProfile).toBe('SRGB')
+ figma.graph.documentColorSpace = 'display-p3'
+ expect(figma.root.documentColorProfile).toBe('DISPLAY_P3')
+ expect('documentColorProfile' in figma.currentPage).toBe(false)
+ })
+})
diff --git a/packages/core/tests/figma-api/accessors/connector.test.ts b/packages/core/tests/figma-api/accessors/connector.test.ts
index 9509861a7..2c0c1d621 100644
--- a/packages/core/tests/figma-api/accessors/connector.test.ts
+++ b/packages/core/tests/figma-api/accessors/connector.test.ts
@@ -2,6 +2,7 @@ import { beforeAll, describe, expect, test } from 'bun:test'
import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { registerTestFont } from '#core-tests/helpers/figma-api'
+import type { ConnectorStrokeCap } from '@figma/plugin-typings/plugin-api-standalone'
import { pick } from 'es-toolkit'
import { FigmaAPI } from '@open-pencil/core/figma-api'
diff --git a/packages/core/tests/figma-api/accessors/layout/guides.test.ts b/packages/core/tests/figma-api/accessors/layout/guides.test.ts
new file mode 100644
index 000000000..f18151f51
--- /dev/null
+++ b/packages/core/tests/figma-api/accessors/layout/guides.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createAPI } from '#core-tests/helpers/figma-api'
+
+// Measured with the same scripts in Figma's plugin API (Figma desktop 126).
+
+describe('guides', () => {
+ test('read and set a frame’s and a page’s own guides', () => {
+ const figma = createAPI()
+ const frame = figma.createFrame()
+ expect(frame.guides).toEqual([])
+ frame.guides = [
+ { axis: 'X', offset: 10 },
+ { axis: 'Y', offset: 2.5 }
+ ]
+ expect(frame.guides).toEqual([
+ { axis: 'X', offset: 10 },
+ { axis: 'Y', offset: 2.5 }
+ ])
+ expect(Object.isFrozen(frame.guides)).toBe(true)
+ expect(
+ figma.graph.getNode(frame.id)?.guides.map(({ axis, position }) => [axis, position])
+ ).toEqual([
+ ['x', 10],
+ ['y', 2.5]
+ ])
+ const page = figma.currentPage
+ page.guides = page.guides.concat({ axis: 'Y', offset: 40 })
+ expect(page.guides).toEqual([{ axis: 'Y', offset: 40 }])
+ })
+
+ test('keep the identity of a guide set where one was, so a saved file updates it', () => {
+ const figma = createAPI()
+ const frame = figma.createFrame()
+ frame.guides = [{ axis: 'X', offset: 10 }]
+ const [before] = figma.graph.getNode(frame.id)?.guides ?? []
+ frame.guides = [
+ { axis: 'X', offset: 20 },
+ { axis: 'Y', offset: 5 }
+ ]
+ const [moved, added] = figma.graph.getNode(frame.id)?.guides ?? []
+ expect(moved?.id).toBe(before?.id)
+ expect(added?.id).not.toBe(before?.id)
+ })
+
+ test('are checked as Figma checks them', () => {
+ const frame = createAPI().createFrame()
+ const message = (problem: string) =>
+ `in set_guides: Property "guides" failed validation: ${problem}`
+ expect(() => (frame.guides = [{ axis: 'Z', offset: 10 }] as never)).toThrow(
+ message('Invalid option: expected one of "X"|"Y" at [0].axis')
+ )
+ expect(() => (frame.guides = [{ axis: 'X' }] as never)).toThrow(
+ message('Required value missing at [0].offset')
+ )
+ expect(() => (frame.guides = [{ axis: 'X', offset: Infinity }])).toThrow(
+ message('Expected number, received Infinity at [0].offset')
+ )
+ expect(() => (frame.guides = [5] as never)).toThrow(
+ message('Expected object, received number at index 0')
+ )
+ expect(frame.guides).toEqual([])
+ })
+
+ test('are a page’s and frame’s alone', () => {
+ const figma = createAPI()
+ expect('guides' in figma.createRectangle()).toBe(false)
+ expect('guides' in figma.createText()).toBe(false)
+ })
+})
+
+describe('horizontal and vertical padding', () => {
+ test('read the first side and set both, as Figma’s deprecated members do', () => {
+ const frame = createAPI().createFrame()
+ expect([frame.horizontalPadding, frame.verticalPadding]).toEqual([0, 0])
+ frame.paddingLeft = 4
+ frame.paddingRight = 9
+ expect(frame.horizontalPadding).toBe(4)
+ frame.horizontalPadding = 7
+ frame.verticalPadding = 3
+ expect([frame.paddingLeft, frame.paddingRight, frame.paddingTop, frame.paddingBottom]).toEqual([
+ 7, 7, 3, 3
+ ])
+ })
+
+ test('take numbers of zero or more', () => {
+ const frame = createAPI().createFrame()
+ const message = (problem: string) =>
+ `in set_horizontalPadding: Property "horizontalPadding" failed validation: ${problem}`
+ expect(() => (frame.horizontalPadding = -2)).toThrow(
+ message('Too small: expected number to be >=0')
+ )
+ expect(() => (frame.horizontalPadding = 'x' as never)).toThrow(
+ message('Expected number, received string')
+ )
+ expect(() => (frame.horizontalPadding = Infinity)).toThrow(
+ message('Expected number, received Infinity')
+ )
+ expect(() => (frame.paddingLeft = Infinity)).toThrow(
+ 'in set_paddingLeft: Property "paddingLeft" failed validation: Expected number, received Infinity'
+ )
+ expect([frame.paddingLeft, frame.paddingRight]).toEqual([0, 0])
+ })
+})
diff --git a/packages/core/tests/figma-api/accessors/shape.test.ts b/packages/core/tests/figma-api/accessors/shape.test.ts
index 5dbc0d3d7..a3c175e39 100644
--- a/packages/core/tests/figma-api/accessors/shape.test.ts
+++ b/packages/core/tests/figma-api/accessors/shape.test.ts
@@ -110,3 +110,21 @@ describe('shape members on other layers', () => {
expect('innerRadius' in figma.createPolygon()).toBe(false)
})
})
+
+describe('a boolean operation', () => {
+ test('reads and switches its operation', () => {
+ const { graph, figma } = api()
+ const boolean = figma.union([figma.createRectangle(), figma.createEllipse()], figma.currentPage)
+ expect(boolean.booleanOperation).toBe('UNION')
+ boolean.booleanOperation = 'SUBTRACT'
+ expect(boolean.booleanOperation).toBe('SUBTRACT')
+ expect(graph.getNode(boolean.id)?.booleanOperation).toBe('SUBTRACT')
+ expect(() => (boolean.booleanOperation = 'XOR' as never)).toThrow(
+ 'in set_booleanOperation: Property "booleanOperation" failed validation: Invalid option: expected one of "UNION"|"INTERSECT"|"SUBTRACT"|"EXCLUDE"'
+ )
+ })
+
+ test('is a boolean’s alone', () => {
+ expect('booleanOperation' in api().figma.createRectangle()).toBe(false)
+ })
+})
diff --git a/packages/core/tests/figma-api/accessors/text/decoration.test.ts b/packages/core/tests/figma-api/accessors/text/decoration.test.ts
new file mode 100644
index 000000000..c02814282
--- /dev/null
+++ b/packages/core/tests/figma-api/accessors/text/decoration.test.ts
@@ -0,0 +1,132 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { createAPI, registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(async () => {
+ await registerTestFont('Inter')
+})
+
+// Measured with the same scripts in Figma's plugin API (Figma desktop 126).
+
+async function text(characters = 'Hello world') {
+ const figma = createAPI()
+ await figma.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ const node = figma.createText()
+ node.characters = characters
+ return { figma, node }
+}
+
+const DECORATION_FIELDS = [
+ 'textDecorationStyle',
+ 'textDecorationOffset',
+ 'textDecorationThickness',
+ 'textDecorationColor',
+ 'textDecorationSkipInk'
+] as const
+
+describe('a text’s underline style', () => {
+ test('reads null while the text has no underline, and Figma’s defaults once it does', async () => {
+ const { node } = await text()
+ expect(DECORATION_FIELDS.map((field) => node[field])).toEqual([null, null, null, null, null])
+ node.textDecoration = 'STRIKETHROUGH'
+ expect(DECORATION_FIELDS.map((field) => node[field])).toEqual([null, null, null, null, null])
+ node.textDecoration = 'UNDERLINE'
+ expect(DECORATION_FIELDS.map((field) => node[field])).toEqual([
+ 'SOLID',
+ { unit: 'AUTO' },
+ { unit: 'AUTO' },
+ { value: 'AUTO' },
+ true
+ ])
+ })
+
+ test('sets every character’s', async () => {
+ const { node } = await text()
+ node.textDecoration = 'UNDERLINE'
+ node.textDecorationStyle = 'WAVY'
+ node.textDecorationOffset = { unit: 'PIXELS', value: 3 }
+ node.textDecorationThickness = { unit: 'PIXELS', value: 2 }
+ node.textDecorationColor = { value: { type: 'SOLID', color: { r: 1, g: 0, b: 0 } } }
+ node.textDecorationSkipInk = false
+ expect(node.textDecorationStyle).toBe('WAVY')
+ expect(node.getRangeTextDecorationStyle(6, 11)).toBe('WAVY')
+ expect(node.textDecorationOffset).toEqual({ unit: 'PIXELS', value: 3 })
+ expect(node.textDecorationThickness).toEqual({ unit: 'PIXELS', value: 2 })
+ expect(node.textDecorationColor).toMatchObject({
+ value: { type: 'SOLID', color: { r: 1, g: 0, b: 0 } }
+ })
+ expect(node.textDecorationSkipInk).toBe(false)
+ })
+
+ test('is read from the underlined characters alone', async () => {
+ const { node } = await text()
+ node.textDecoration = 'UNDERLINE'
+ node.setRangeTextDecorationStyle(0, 5, 'SOLID')
+ node.setRangeTextDecorationStyle(5, 11, 'WAVY')
+ expect(typeof node.textDecorationStyle).toBe('symbol')
+ node.setRangeTextDecoration(0, 5, 'NONE')
+ expect(node.textDecorationStyle).toBe('WAVY')
+ expect(node.getRangeTextDecorationStyle(0, 11)).toBe('WAVY')
+ expect(node.getRangeTextDecorationStyle(0, 5)).toBeNull()
+ })
+
+ test('is refused on text with no underline, apart from skip ink, which waits for one', async () => {
+ const { node } = await text()
+ const refusal = (field: string, name: string) =>
+ `in set_${field}: Cannot set text decoration ${name} on a non-underlined text range`
+ expect(() => (node.textDecorationStyle = 'WAVY')).toThrow(
+ refusal('textDecorationStyle', 'style')
+ )
+ expect(() => (node.textDecorationOffset = { unit: 'PIXELS', value: 2 })).toThrow(
+ refusal('textDecorationOffset', 'offset')
+ )
+ expect(() => (node.textDecorationThickness = { unit: 'PIXELS', value: 2 })).toThrow(
+ refusal('textDecorationThickness', 'thickness')
+ )
+ expect(() => (node.textDecorationColor = { value: 'AUTO' })).toThrow(
+ refusal('textDecorationColor', 'color')
+ )
+ node.textDecorationSkipInk = false
+ expect(node.textDecorationSkipInk).toBeNull()
+ node.textDecoration = 'UNDERLINE'
+ expect(node.textDecorationSkipInk).toBe(false)
+ })
+
+ test('checks the value, under the property’s name, before the underline', async () => {
+ const { node } = await text()
+ expect(() => (node.textDecorationSkipInk = 'no' as never)).toThrow(
+ 'in set_textDecorationSkipInk: Property "textDecorationSkipInk" failed validation: Expected boolean, received string'
+ )
+ expect(() => (node.textDecorationStyle = 'DASHED' as never)).toThrow(
+ 'in set_textDecorationStyle: Property "textDecorationStyle" failed validation:'
+ )
+ expect(() => (node.textDecorationOffset = 3 as never)).toThrow(
+ 'in set_textDecorationOffset: Property "textDecorationOffset" failed validation: Expected object, received number'
+ )
+ })
+})
+
+describe('a text’s leading trim', () => {
+ test('reads and sets the trim', async () => {
+ const { figma, node } = await text()
+ expect(node.leadingTrim).toBe('NONE')
+ node.leadingTrim = 'CAP_HEIGHT'
+ expect(node.leadingTrim).toBe('CAP_HEIGHT')
+ expect(figma.graph.getNode(node.id)?.leadingTrim).toBe('CAP_HEIGHT')
+ expect(() => (node.leadingTrim = 'X' as never)).toThrow(
+ 'in set_leadingTrim: Property "leadingTrim" failed validation: Invalid option: expected one of "CAP_HEIGHT"|"NONE"'
+ )
+ })
+})
+
+describe('a text’s OpenType features', () => {
+ test('read the features its characters set, and cannot be assigned', async () => {
+ const { figma, node } = await text()
+ expect<unknown>(node.openTypeFeatures).toEqual({})
+ expect(Object.isFrozen(node.openTypeFeatures)).toBe(true)
+ figma.graph.updateNode(node.id, { fontFeatures: [{ tag: 'CALT', enabled: false }] })
+ expect<unknown>(node.openTypeFeatures).toEqual({ CALT: false })
+ ;(node as { openTypeFeatures: unknown }).openTypeFeatures = { LIGA: false }
+ expect<unknown>(node.openTypeFeatures).toEqual({ CALT: false })
+ })
+})
diff --git a/packages/core/tests/figma-api/accessors/text/properties.test.ts b/packages/core/tests/figma-api/accessors/text/properties.test.ts
index 2d43aaa44..a24855706 100644
--- a/packages/core/tests/figma-api/accessors/text/properties.test.ts
+++ b/packages/core/tests/figma-api/accessors/text/properties.test.ts
@@ -89,3 +89,89 @@ describe('text extras', () => {
expect(text.characters).toBe('Hello World')
})
})
+
+// Measured with the same scripts in Figma's plugin API (Figma desktop 126).
+describe('text setters check their values as Figma does', () => {
+ test('font size, decoration, case, and font name', async () => {
+ const api = createAPI()
+ await api.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ const text = api.createText()
+ text.characters = 'Hello'
+ const message = (property: string, problem: string) =>
+ `in set_${property}: Property "${property}" failed validation: ${problem}`
+ expect(() => (text.fontSize = 'a' as never)).toThrow(
+ message('fontSize', 'Expected number, received string')
+ )
+ expect(() => (text.fontSize = 0)).toThrow(
+ message('fontSize', 'Too small: expected number to be >=1')
+ )
+ expect(() => (text.fontSize = Number.NaN)).toThrow(
+ message('fontSize', 'Expected number, received NaN')
+ )
+ expect(() => (text.textDecoration = 'OVER' as never)).toThrow(
+ message(
+ 'textDecoration',
+ 'Invalid option: expected one of "NONE"|"UNDERLINE"|"STRIKETHROUGH"'
+ )
+ )
+ expect(() => (text.textCase = 'SHOUT' as never)).toThrow(
+ message(
+ 'textCase',
+ 'Invalid option: expected one of "ORIGINAL"|"UPPER"|"LOWER"|"TITLE"|"SMALL_CAPS"|"SMALL_CAPS_FORCED"'
+ )
+ )
+ expect(() => (text.fontName = { family: 3 } as never)).toThrow(
+ message('fontName', 'Expected string, received number at .family')
+ )
+ expect(() => (text.hyperlink = { type: 'X', value: 'a' } as never)).toThrow(
+ 'in set_hyperlink: Property "value" failed validation: Expected one of the following, but none matched:\n' +
+ ' Invalid option: expected one of "URL"|"NODE" at .type\n Expected null, received object'
+ )
+ expect([text.fontSize, text.textDecoration, text.textCase]).toEqual([12, 'NONE', 'ORIGINAL'])
+ })
+
+ test('spacings take finite numbers of 0 or more', async () => {
+ const api = createAPI()
+ await api.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ const text = api.createText()
+ text.characters = 'ab'
+ const message = (property: string, problem: string) =>
+ `in set_${property}: Property "${property}" failed validation: ${problem}`
+ expect(() => (text.paragraphSpacing = 'a' as never)).toThrow(
+ message('paragraphSpacing', 'Expected number, received string')
+ )
+ expect(() => (text.paragraphSpacing = Number.NaN)).toThrow(
+ message('paragraphSpacing', 'Expected number, received NaN')
+ )
+ expect(() => (text.listSpacing = Infinity)).toThrow(
+ message('listSpacing', 'Expected number, received Infinity')
+ )
+ expect(() => text.setRangeParagraphSpacing(0, 1, 'a' as never)).toThrow(
+ 'in setRangeParagraphSpacing: Property "value" failed validation: Expected number, received string'
+ )
+ })
+
+ test('font names and lengths take no keys Figma does not know', async () => {
+ const api = createAPI()
+ await api.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ const text = api.createText()
+ text.characters = 'Hello'
+ expect(() =>
+ text.setRangeFontName(0, 3, { family: 'Inter', style: 'Regular', foo: 1 } as never)
+ ).toThrow('in setRangeFontName: Property "value" failed validation: Unrecognized key: "foo"')
+ expect(() =>
+ text.setRangeLetterSpacing(0, 3, { unit: 'PIXELS', value: 1, foo: 1 } as never)
+ ).toThrow(
+ 'in setRangeLetterSpacing: Property "value" failed validation: Unrecognized key: "foo"'
+ )
+ expect(() =>
+ text.setRangeFontName(0, 3, { family: 'Inter', variationSettings: 3 } as never)
+ ).toThrow('Expected record, received number at .variationSettings')
+ expect(() => text.setRangeLetterSpacing(0, 3, { unit: ['PIXELS'], value: 1 } as never)).toThrow(
+ 'Invalid option: expected one of "PIXELS"|"PERCENT" at .unit'
+ )
+ expect(() => text.setRangeLineHeight(0, 3, { unit: ['PIXELS'], value: 1 } as never)).toThrow(
+ 'Expected .unit to be one of the following: PIXELS, PERCENT, AUTO'
+ )
+ })
+})
diff --git a/packages/core/tests/figma-api/accessors/visual/async-paints.test.ts b/packages/core/tests/figma-api/accessors/visual/async-paints.test.ts
new file mode 100644
index 000000000..fad4fb9ee
--- /dev/null
+++ b/packages/core/tests/figma-api/accessors/visual/async-paints.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createAPI } from '#core-tests/helpers/figma-api'
+
+// Measured with the same scripts in Figma's plugin API (Figma desktop 126).
+
+describe('setFillsAsync and setStrokesAsync', () => {
+ test('set the paints and resolve', async () => {
+ const rectangle = createAPI().createRectangle()
+ const pending = rectangle.setFillsAsync([{ type: 'SOLID', color: { r: 1, g: 0, b: 0 } }])
+ expect(pending).toBeInstanceOf(Promise)
+ expect(await pending).toBeUndefined()
+ expect(rectangle.fills).toMatchObject([{ type: 'SOLID', color: { r: 1, g: 0, b: 0 } }])
+ await rectangle.setStrokesAsync([{ type: 'SOLID', color: { r: 0, g: 1, b: 0 } }])
+ expect(rectangle.strokes).toMatchObject([{ type: 'SOLID', color: { r: 0, g: 1, b: 0 } }])
+ })
+
+ test('refuse paints before they return, naming the method', () => {
+ const rectangle = createAPI().createRectangle()
+ expect(() => rectangle.setFillsAsync([{ type: 'NOPE' }] as never)).toThrow(
+ 'in setFillsAsync: Property "fills" failed validation:'
+ )
+ expect(() => rectangle.setStrokesAsync([{ type: 'NOPE' }] as never)).toThrow(
+ 'in setStrokesAsync: Property "strokes" failed validation:'
+ )
+ })
+})
diff --git a/packages/core/tests/figma-api/components/instances.test.ts b/packages/core/tests/figma-api/components/instances.test.ts
index ccb0de9a8..868435b2b 100644
--- a/packages/core/tests/figma-api/components/instances.test.ts
+++ b/packages/core/tests/figma-api/components/instances.test.ts
@@ -5,7 +5,6 @@ import { asTextNode, createAPI, registerTestFont } from '#core-tests/helpers/fig
import { hasInstanceOverride } from '@open-pencil/scene-graph/instances'
-
beforeAll(() => registerTestFont())
describe('components', () => {
@@ -189,17 +188,19 @@ describe('applied shared styles on instance children', () => {
sharedStyleType: 'TEXT',
text: 'Ag'
})
+ heading.source.id = 'S:heading,'
+ body.source.id = 'S:body,'
const component = graph.createNode('COMPONENT', page.id, { name: 'Card' })
const title = graph.createNode('TEXT', component.id, { name: 'title', text: 'Title' })
const first = expectDefined(graph.createInstance(component.id, page.id), 'first instance')
const second = expectDefined(graph.createInstance(component.id, page.id), 'second instance')
const firstTitle = expectDefined(graph.getChildren(first.id)[0], 'first title')
- asTextNode(api.wrapNode(firstTitle.id)).textStyleId = heading.id
+ asTextNode(api.wrapNode(firstTitle.id)).textStyleId = 'S:heading,'
expect(hasInstanceOverride(graph, firstTitle.id, 'textStyleId')).toBe(true)
- graph.updateNode(title.id, { textStyleId: body.id })
+ graph.updateNode(title.id, { textStyleId: 'S:body,' })
graph.syncInstances(component.id)
- expect(graph.getNode(firstTitle.id)?.textStyleId).toBe(heading.id)
- expect(graph.getChildren(second.id)[0]?.textStyleId).toBe(body.id)
+ expect(graph.getNode(firstTitle.id)?.textStyleId).toBe('S:heading,')
+ expect(graph.getChildren(second.id)[0]?.textStyleId).toBe('S:body,')
})
})
diff --git a/packages/core/tests/figma-api/components/members.test.ts b/packages/core/tests/figma-api/components/members.test.ts
new file mode 100644
index 000000000..582797984
--- /dev/null
+++ b/packages/core/tests/figma-api/components/members.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createAPI } from '#core-tests/helpers/figma-api'
+
+// Measured with the same scripts in Figma's plugin API (Figma desktop 126).
+
+describe('component and component set members', () => {
+ test('a description, on components and sets alone', () => {
+ const figma = createAPI()
+ const component = figma.createComponent()
+ expect(component.description).toBe('')
+ component.description = 'Primary action'
+ expect(component.description).toBe('Primary action')
+ expect(figma.graph.getNode(component.id)?.symbolDescription).toBe('Primary action')
+ expect(() => (component.description = 3 as never)).toThrow(
+ 'in set_description: Property "description" failed validation: Expected string, received number'
+ )
+ const set = figma.combineAsVariants([component], figma.currentPage)
+ set.description = 'Buttons'
+ expect(set.description).toBe('Buttons')
+ expect('description' in figma.createFrame()).toBe(false)
+ })
+
+ test('a component’s instances', async () => {
+ const figma = createAPI()
+ const component = figma.createComponent()
+ expect(component.instances).toEqual([])
+ const first = component.createInstance()
+ const second = component.createInstance()
+ const ids = [first.id, second.id].sort()
+ expect(component.instances.map((instance) => instance.id).sort()).toEqual(ids)
+ expect((await component.getInstancesAsync()).map((instance) => instance.id).sort()).toEqual(ids)
+ })
+
+ test('a removed component’s instances reject', async () => {
+ const component = createAPI().createComponent()
+ component.remove()
+ await expect(component.getInstancesAsync()).rejects.toThrow()
+ })
+
+ test('a set read from a file without its option lists gives its variants’ values', () => {
+ const figma = createAPI()
+ const small = figma.createComponent()
+ small.name = 'size=s'
+ const large = figma.createComponent()
+ large.name = 'size=l'
+ const set = figma.combineAsVariants([small, large], figma.currentPage)
+ const node = figma.graph.getNode(set.id)
+ if (!node) throw new Error('Expected the set')
+ figma.graph.updateNode(set.id, {
+ componentPropertyDefinitions: node.componentPropertyDefinitions.map(
+ ({ variantOptions: _options, ...definition }) => definition
+ )
+ })
+ expect(set.variantGroupProperties).toEqual({ size: { values: ['s', 'l'] } })
+ })
+
+ test('a set’s default variant, the first in reading order, and its variant values', () => {
+ const figma = createAPI()
+ const variant = (name: string, x: number, y: number) => {
+ const component = figma.createComponent()
+ component.name = name
+ component.resize(100, 100)
+ component.x = x
+ component.y = y
+ return component
+ }
+ // Large's row touches the top one, so the row reads left to right from it.
+ const set = figma.combineAsVariants(
+ [variant('size=s', 200, 0), variant('size=l', 0, 100), variant('size=m', 100, 0)],
+ figma.currentPage
+ )
+ expect(set.defaultVariant?.name).toBe('size=l')
+ expect(set.variantGroupProperties).toEqual({ size: { values: ['s', 'l', 'm'] } })
+ })
+})
diff --git a/packages/core/tests/figma-api/grouping/boolean-bounds.test.ts b/packages/core/tests/figma-api/grouping/boolean-bounds.test.ts
index e5102a65f..ff6ea24bd 100644
--- a/packages/core/tests/figma-api/grouping/boolean-bounds.test.ts
+++ b/packages/core/tests/figma-api/grouping/boolean-bounds.test.ts
@@ -71,6 +71,21 @@ describe('boolean operation bounds', () => {
expect(box(intersect)).toEqual([40, 20, 10, 30])
})
+ test('switching the operation refits the boolean and the group around it', () => {
+ const { figma, square } = api()
+ const boolean = figma.union([square(0, 0), square(20, 20)], figma.currentPage)
+ const group = figma.group([boolean, square(100, 0, 10, 10)], figma.currentPage)
+ expect([box(boolean), box(group)]).toEqual([
+ [0, 0, 70, 70],
+ [0, 0, 110, 70]
+ ])
+ boolean.booleanOperation = 'INTERSECT'
+ expect([box(boolean), box(group)]).toEqual([
+ [20, 20, 30, 30],
+ [20, 0, 90, 50]
+ ])
+ })
+
test('from the canvas, a boolean takes the box of its result too', () => {
const editor = createEditor()
// Attaching CanvasKit installs a global text measurer that later tests must not inherit.
diff --git a/packages/core/tests/figma-api/overrides/instance.test.ts b/packages/core/tests/figma-api/overrides/instance.test.ts
index 88cfc9915..42ec88d85 100644
--- a/packages/core/tests/figma-api/overrides/instance.test.ts
+++ b/packages/core/tests/figma-api/overrides/instance.test.ts
@@ -1,10 +1,10 @@
import { beforeAll, describe, expect, test } from 'bun:test'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { registerTestFont } from '#core-tests/helpers/figma-api'
-
beforeAll(() => registerTestFont())
// Each case repeats a script run in Figma desktop 126; the lists are what Figma returned.
@@ -148,6 +148,38 @@ describe('instance.resetOverrides', () => {
test('is an instance’s alone', () => {
const { card } = setup()
- expect(() => card.resetOverrides()).toThrow('resetOverrides() can only be called on instances')
+ expect('resetOverrides' in card).toBe(false)
+ })
+})
+
+describe('a detached instance', () => {
+ test('is a frame without the instance’s override members', () => {
+ const { instance } = setup()
+ const frame = instance.detachInstance()
+ expect(['overrides', 'removeOverrides', 'resetOverrides'].map((name) => name in frame)).toEqual(
+ [false, false, false]
+ )
+ // A reference kept from before refuses them.
+ expect(instance.overrides).toBeUndefined()
+ expect(() => instance.removeOverrides()).toThrow(
+ 'removeOverrides() can only be called on instances'
+ )
+ })
+})
+
+describe('instance.removeOverrides', () => {
+ test('does what resetOverrides does, under the name Figma gives it now', () => {
+ const { card, instance, find, overrides, show } = setup()
+ instance.setProperties({ [show]: false })
+ find('Label').fontSize = 30
+ find('Nested').opacity = 0.5
+ instance.removeOverrides()
+ expect([find('Box').visible, find('Label').fontSize, find('Nested').opacity]).toEqual([
+ false,
+ 12,
+ 1
+ ])
+ expect(overrides()).toEqual(['SELF: height,width'])
+ expect('removeOverrides' in card).toBe(false)
})
})
diff --git a/packages/core/tests/figma-api/styles/styles.test.ts b/packages/core/tests/figma-api/styles/styles.test.ts
new file mode 100644
index 000000000..6351fc286
--- /dev/null
+++ b/packages/core/tests/figma-api/styles/styles.test.ts
@@ -0,0 +1,379 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { createAPI, registerTestFont } from '#core-tests/helpers/figma-api'
+
+import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
+import { initCodec } from '@open-pencil/kiwi/fig/codec'
+import { getSharedStyles } from '@open-pencil/scene-graph/shared-styles'
+
+// Measured with the same scripts in Figma's plugin API (Figma desktop 126).
+
+beforeAll(async () => {
+ await registerTestFont('Inter')
+ await initCodec()
+})
+
+const RED = { r: 1, g: 0, b: 0 }
+const GREEN = { r: 0, g: 1, b: 0 }
+const BLUE = { r: 0, g: 0, b: 1 }
+const solid = (color: typeof RED) => [{ type: 'SOLID' as const, color }]
+
+/** A font name that is not mixed, as a style's and an unstyled text's are. */
+function fontName(node: { fontName: unknown }): { family: string; style: string } {
+ const name = node.fontName
+ if (!name || typeof name !== 'object') throw new Error('Expected one font name')
+ return name as { family: string; style: string }
+}
+
+describe('creating and finding styles', () => {
+ test('a new style is empty and unnamed, with an ID in Figma’s shape', () => {
+ const figma = createAPI()
+ const paint = figma.createPaintStyle()
+ expect(paint.id).toMatch(/^S:[0-9a-f]{40},$/)
+ expect(paint.key).toBe(paint.id.slice(2, 42))
+ expect([paint.type, paint.name, paint.description, paint.remote]).toEqual([
+ 'PAINT',
+ '',
+ '',
+ false
+ ])
+ expect(paint.paints).toEqual([])
+ expect(paint.boundVariables).toEqual({})
+ expect([figma.createEffectStyle().effects, figma.createGridStyle().layoutGrids]).toEqual([
+ [],
+ []
+ ])
+ const text = figma.createTextStyle()
+ expect([text.type, text.fontSize, fontName(text).family, text.lineHeight]).toEqual([
+ 'TEXT',
+ 12,
+ 'Inter',
+ { unit: 'AUTO' }
+ ])
+ })
+
+ test('local styles list in the order they were made, and an ID finds the same object', async () => {
+ const figma = createAPI()
+ for (const name of ['Zeta', 'alpha', 'Beta']) figma.createPaintStyle().name = name
+ figma.createTextStyle().name = 'Body'
+ expect((await figma.getLocalPaintStylesAsync()).map((style) => style.name)).toEqual([
+ 'Zeta',
+ 'alpha',
+ 'Beta'
+ ])
+ expect(figma.getLocalTextStyles().map((style) => style.name)).toEqual(['Body'])
+ const [first] = figma.getLocalPaintStyles()
+ expect(await figma.getStyleByIdAsync(first.id)).toBe(first)
+ expect(figma.getStyleById(first.id)).toBe(first)
+ expect(await figma.getStyleByIdAsync('S:missing,')).toBeNull()
+ expect(await figma.getStyleByIdAsync(3 as never)).toBeNull()
+ })
+
+ test('styles stay out of the pages and layers scripts walk', () => {
+ const figma = createAPI()
+ figma.createPaintStyle().name = 'Hidden'
+ expect(figma.root.children.map((page) => page.name)).toEqual(['Page 1'])
+ expect(figma.currentPage.children).toEqual([])
+ })
+
+ test('names and paints are checked as Figma checks them; a description that is not text is ignored', () => {
+ const style = createAPI().createPaintStyle()
+ expect(() => (style.name = 3 as never)).toThrow(
+ 'in set_name: Property "name" failed validation: Expected string, received number'
+ )
+ expect(() => (style.paints = [{ type: 'NOPE' }] as never)).toThrow(
+ 'in set_paints: Property "paints" failed validation: Expected [0].type to be one of the following:'
+ )
+ style.description = 'Main'
+ style.description = 3 as never
+ expect(style.description).toBe('Main')
+ })
+})
+
+describe('using styles', () => {
+ test('a layer takes the style’s paints, follows its changes, and lists as a consumer', async () => {
+ const figma = createAPI()
+ const style = figma.createPaintStyle()
+ style.paints = solid(RED)
+ const first = figma.createRectangle()
+ const second = figma.createRectangle()
+ expect(await first.setFillStyleIdAsync(style.id)).toBeUndefined()
+ second.fillStyleId = style.id
+ expect([first.fillStyleId, first.fills]).toMatchObject([style.id, solid(RED)])
+ style.paints = solid(GREEN)
+ expect([first.fills, second.fills]).toMatchObject([solid(GREEN), solid(GREEN)])
+ expect(
+ (await style.getStyleConsumersAsync()).map(({ node, fields }) => [node.id, fields])
+ ).toEqual([
+ [first.id, ['fillStyleId']],
+ [second.id, ['fillStyleId']]
+ ])
+ })
+
+ test('a paint style strokes a layer too', async () => {
+ const figma = createAPI()
+ const style = figma.createPaintStyle()
+ style.paints = solid(BLUE)
+ const rectangle = figma.createRectangle()
+ await rectangle.setStrokeStyleIdAsync(style.id)
+ expect([rectangle.strokeStyleId, rectangle.strokes]).toMatchObject([style.id, solid(BLUE)])
+ })
+
+ test('a layer leaves the style when its own paints change or the ID is empty, keeping them', async () => {
+ const figma = createAPI()
+ const style = figma.createPaintStyle()
+ style.paints = solid(RED)
+ const rectangle = figma.createRectangle()
+ await rectangle.setFillStyleIdAsync(style.id)
+ rectangle.fills = solid(BLUE)
+ expect(rectangle.fillStyleId).toBe('')
+ await rectangle.setFillStyleIdAsync(style.id)
+ await rectangle.setFillStyleIdAsync('')
+ expect([rectangle.fillStyleId, rectangle.fills]).toMatchObject(['', solid(RED)])
+ })
+
+ test('a style the document does not hold, or of another kind, is refused', async () => {
+ const figma = createAPI()
+ const rectangle = figma.createRectangle()
+ const effect = figma.createEffectStyle()
+ const refusal = 'Cannot set style successfully: Cannot find style'
+ await expect(rectangle.setFillStyleIdAsync('S:missing,')).rejects.toThrow(refusal)
+ await expect(rectangle.setFillStyleIdAsync(effect.id)).rejects.toThrow(refusal)
+ expect(() => (rectangle.fillStyleId = 'S:missing,')).toThrow(`in set_fillStyleId: ${refusal}`)
+ expect(() => (rectangle.fillStyleId = 3 as never)).toThrow(
+ 'in set_fillStyleId: Property "fillStyleId" failed validation: Expected string, received number'
+ )
+ expect(await rectangle.setFillStyleIdAsync(3 as never)).toBeUndefined()
+ })
+
+ test('a stroke style gives every paint, keeping the stroke’s weight, and an empty one clears it', async () => {
+ const figma = createAPI()
+ const gradient = figma.createPaintStyle()
+ gradient.paints = [
+ {
+ type: 'GRADIENT_LINEAR',
+ gradientTransform: [
+ [1, 0, 0],
+ [0, 1, 0]
+ ],
+ gradientStops: [
+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },
+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }
+ ]
+ }
+ ]
+ const rectangle = figma.createRectangle()
+ rectangle.strokes = solid(GREEN)
+ rectangle.strokeWeight = 3
+ await rectangle.setStrokeStyleIdAsync(gradient.id)
+ expect([rectangle.strokes.map((stroke) => stroke.type), rectangle.strokeWeight]).toEqual([
+ ['GRADIENT_LINEAR'],
+ 3
+ ])
+ await rectangle.setStrokeStyleIdAsync(figma.createPaintStyle().id)
+ expect([rectangle.strokes, rectangle.strokeWeight]).toEqual([[], 3])
+ // Without strokes, the layer's kept weight and alignment go to the new ones.
+ rectangle.strokeAlign = 'OUTSIDE'
+ await rectangle.setStrokeStyleIdAsync(gradient.id)
+ expect([rectangle.strokes.length, rectangle.strokeWeight, rectangle.strokeAlign]).toEqual([
+ 1,
+ 3,
+ 'OUTSIDE'
+ ])
+ })
+
+ test('a paint bound to a variable keeps it in the style and in the layers that use it', async () => {
+ const figma = createAPI()
+ const collection = figma.variables.createVariableCollection('Colors')
+ const brand = figma.variables.createVariable('Brand', collection, 'COLOR')
+ brand.setValueForMode(collection.defaultModeId, { r: 1, g: 0, b: 0, a: 1 })
+ const style = figma.createPaintStyle()
+ style.paints = [
+ figma.variables.setBoundVariableForPaint(
+ { type: 'SOLID', color: { r: 0, g: 0, b: 0 } },
+ 'color',
+ brand
+ )
+ ]
+ const [paint] = style.paints
+ expect(paint && 'boundVariables' in paint ? paint.boundVariables?.color?.id : null).toBe(
+ brand.id
+ )
+ const rectangle = figma.createRectangle()
+ await rectangle.setFillStyleIdAsync(style.id)
+ expect(rectangle.fills).toMatchObject([
+ { color: RED, boundVariables: { color: { id: brand.id } } }
+ ])
+ brand.setValueForMode(collection.defaultModeId, { r: 0, g: 1, b: 0, a: 1 })
+ expect(rectangle.fills).toMatchObject([{ color: GREEN }])
+ })
+
+ test('a connector’s stroke style strokes its line', async () => {
+ const figma = createAPI()
+ const style = figma.createPaintStyle()
+ style.paints = solid(BLUE)
+ const connector = figma.createConnector()
+ await connector.setStrokeStyleIdAsync(style.id)
+ expect([connector.strokeStyleId, connector.strokes]).toMatchObject([style.id, solid(BLUE)])
+ })
+
+ test('effect and grid styles give their effects and grids', async () => {
+ const figma = createAPI()
+ const effect = figma.createEffectStyle()
+ effect.effects = [{ type: 'LAYER_BLUR', radius: 4, visible: true, blurType: 'NORMAL' }]
+ const grid = figma.createGridStyle()
+ grid.layoutGrids = [
+ { pattern: 'GRID', sectionSize: 8, visible: true, color: { r: 1, g: 0, b: 0, a: 0.1 } }
+ ]
+ const frame = figma.createFrame()
+ await frame.setEffectStyleIdAsync(effect.id)
+ await frame.setGridStyleIdAsync(grid.id)
+ expect(frame.effects).toMatchObject([{ type: 'LAYER_BLUR', radius: 4 }])
+ expect(frame.layoutGrids).toMatchObject([{ pattern: 'GRID', sectionSize: 8 }])
+ expect(() => (effect.effects = 3 as never)).toThrow(
+ 'in set_effects: Property "effects" failed validation: Expected array, received number'
+ )
+ expect(() => (grid.layoutGrids = 3 as never)).toThrow(
+ 'in set_layoutGrids: Property "layoutGrids" failed validation: Expected array, received number'
+ )
+ })
+
+ test('each layer has the style references Figma gives its type', () => {
+ const figma = createAPI()
+ const has = (node: object, members: string[]) => members.map((member) => member in node)
+ expect(
+ has(figma.createRectangle(), ['fillStyleId', 'effectStyleId', 'gridStyleId', 'textStyleId'])
+ ).toEqual([true, true, false, false])
+ expect(has(figma.currentPage, ['fillStyleId', 'effectStyleId'])).toEqual([false, false])
+ expect(has(figma.createText(), ['textStyleId', 'gridStyleId'])).toEqual([true, false])
+ expect(has(figma.createFrame(), ['gridStyleId', 'backgroundStyleId', 'textStyleId'])).toEqual([
+ true,
+ true,
+ false
+ ])
+ const group = figma.group([figma.createRectangle()], figma.currentPage)
+ expect(has(group, ['fillStyleId', 'effectStyleId'])).toEqual([false, true])
+ })
+})
+
+describe('text styles', () => {
+ test('give a whole text their fields over its ranges, and follow their changes', async () => {
+ const figma = createAPI()
+ await figma.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ await figma.loadFontAsync({ family: 'Inter', style: 'Bold' })
+ const style = figma.createTextStyle()
+ style.fontName = { family: 'Inter', style: 'Bold' }
+ style.fontSize = 24
+ style.textCase = 'UPPER'
+ const text = figma.createText()
+ text.characters = 'abc def'
+ text.setRangeFontSize(0, 3, 40)
+ await text.setTextStyleIdAsync(style.id)
+ expect([text.textStyleId, text.fontSize, fontName(text).style, text.textCase]).toEqual([
+ style.id,
+ 24,
+ 'Bold',
+ 'UPPER'
+ ])
+ style.fontSize = 30
+ expect(text.fontSize).toBe(30)
+ text.fontSize = 10
+ expect(text.textStyleId).toBe('')
+ })
+
+ test('reach the ranges that use them, which are not listed as consumers', async () => {
+ const figma = createAPI()
+ await figma.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ const paint = figma.createPaintStyle()
+ paint.paints = solid(RED)
+ const style = figma.createTextStyle()
+ const text = figma.createText()
+ text.characters = 'Hello world'
+ await text.setRangeFillStyleIdAsync(0, 5, paint.id)
+ await text.setRangeTextStyleIdAsync(6, 11, style.id)
+ expect(await paint.getStyleConsumersAsync()).toEqual([])
+ paint.paints = solid(BLUE)
+ style.fontSize = 30
+ expect(text.getRangeFills(0, 5)).toMatchObject(solid(BLUE))
+ expect([text.getRangeFontSize(6, 11), text.getRangeFontSize(0, 5)]).toEqual([30, 12])
+ })
+
+ test('a range refuses a style the document does not hold', async () => {
+ const figma = createAPI()
+ const text = figma.createText()
+ text.characters = 'Hello'
+ expect(() => text.setRangeFillStyleId(0, 3, 'S:missing,')).toThrow(
+ 'in setRangeFillStyleId: Cannot set style successfully: Cannot find style'
+ )
+ await expect(text.setRangeTextStyleIdAsync(0, 3, 'S:missing,')).rejects.toThrow(
+ 'Cannot set style successfully: Cannot find style'
+ )
+ })
+})
+
+describe('styles inside instances', () => {
+ test('a text inside an instance that uses a style follows it and lets it go, as an override', async () => {
+ const figma = createAPI()
+ await figma.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ const style = figma.createTextStyle()
+ const component = figma.createComponent()
+ const label = figma.createText()
+ label.characters = 'Label'
+ component.appendChild(label)
+ const instance = component.createInstance()
+ const copy = instance.findOne((node) => node.type === 'TEXT')
+ if (!copy) throw new Error('Expected the instance’s text')
+ await copy.setTextStyleIdAsync(style.id)
+ const overridden = () => instance.overrides?.map((override) => override.overriddenFields)
+ const before = overridden()
+ style.fontSize = 30
+ expect(copy.fontSize).toBe(30)
+ expect(overridden()).toEqual(before)
+ style.remove()
+ expect(copy.textStyleId).toBe('')
+ expect(copy.fontSize).toBe(30)
+ })
+})
+
+describe('removing a style', () => {
+ test('leaves what used it its values, and the style refuses to be read', async () => {
+ const figma = createAPI()
+ await figma.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ const style = figma.createPaintStyle()
+ style.paints = solid(GREEN)
+ const rectangle = figma.createRectangle()
+ await rectangle.setFillStyleIdAsync(style.id)
+ const text = figma.createText()
+ text.characters = 'Hello'
+ await text.setRangeFillStyleIdAsync(0, 3, style.id)
+ const { id } = style
+ style.remove()
+ expect([rectangle.fillStyleId, rectangle.fills]).toMatchObject(['', solid(GREEN)])
+ expect([text.getRangeFillStyleId(0, 3), text.getRangeFills(0, 3)]).toMatchObject([
+ '',
+ solid(GREEN)
+ ])
+ expect(await figma.getStyleByIdAsync(id)).toBeNull()
+ expect(() => style.name).toThrow(`in get_name: The style with id "${id}" does not exist`)
+ expect(() => style.remove()).toThrow(`in remove: The style with id "${id}" does not exist`)
+ })
+})
+
+test('a style made by a script is saved with the file and the layers that use it', async () => {
+ const figma = createAPI()
+ const style = figma.createPaintStyle()
+ style.name = 'Brand/Primary'
+ style.paints = solid(RED)
+ const rectangle = figma.createRectangle()
+ rectangle.name = 'Card'
+ await rectangle.setFillStyleIdAsync(style.id)
+ const saved = await exportFigFile(figma.graph)
+ const reopened = await parseFigFile(saved.slice().buffer)
+ const [found] = getSharedStyles(reopened, 'fill')
+ expect(found?.name).toBe('Brand/Primary')
+ expect(reopened.getNode(found?.nodeId ?? '')?.fills).toMatchObject([
+ { type: 'SOLID', color: { r: 1, g: 0, b: 0 } }
+ ])
+ const card = [...reopened.getAllNodes()].find((node) => node.name === 'Card')
+ expect(card?.fillStyleId).toBe(found?.id)
+})
diff --git a/packages/core/tests/figma-api/surface.test.ts b/packages/core/tests/figma-api/surface.test.ts
index 869f5a84a..a5eb0bca4 100644
--- a/packages/core/tests/figma-api/surface.test.ts
+++ b/packages/core/tests/figma-api/surface.test.ts
@@ -59,10 +59,44 @@ describe('the scripting surface is Figma’s Plugin API', () => {
test('nodes have only the members of Figma’s node types', () => {
const nodeMembers = figmaMembers('SceneNode', 'PageNode', 'DocumentNode')
- for (const node of [figma.createFrame(), figma.createText(), figma.currentPage, figma.root])
+ const component = figma.createComponent()
+ const set = figma.combineAsVariants([component], figma.currentPage)
+ const nodes = [
+ figma.createFrame(),
+ figma.createText(),
+ figma.createRectangle(),
+ figma.createSection(),
+ figma.union([figma.createRectangle(), figma.createEllipse()], figma.currentPage),
+ figma.group([figma.createRectangle()], figma.currentPage),
+ component.createInstance(),
+ component,
+ set,
+ figma.currentPage,
+ figma.root
+ ]
+ for (const node of nodes)
expect(beyondFigma(node, nodeMembers, SERIALIZATION_MEMBERS)).toEqual([])
})
+ test('styles have only the members of Figma’s styles', () => {
+ // Members live Figma's text styles have (desktop 126) that its typings do not declare yet.
+ const untypedTextStyleMembers = [
+ 'textDecorationStyle',
+ 'textDecorationOffset',
+ 'textDecorationThickness',
+ 'textDecorationColor',
+ 'textDecorationSkipInk'
+ ]
+ const styles = [
+ [figma.createPaintStyle(), figmaMembers('PaintStyle'), []],
+ [figma.createTextStyle(), figmaMembers('TextStyle'), untypedTextStyleMembers],
+ [figma.createEffectStyle(), figmaMembers('EffectStyle'), []],
+ [figma.createGridStyle(), figmaMembers('GridStyle'), []]
+ ] as const
+ for (const [style, members, listed] of styles)
+ expect(beyondFigma(style, members, listed)).toEqual([])
+ })
+
test('variables, collections and figma.variables have only Figma’s members', () => {
const collection = figma.variables.createVariableCollection('Tokens')
const variable = figma.variables.createVariable('size', collection, 'FLOAT')
diff --git a/packages/core/tests/figma-api/text/autosize.test.ts b/packages/core/tests/figma-api/text/autosize.test.ts
index cdcc6fd8f..776bb7ad5 100644
--- a/packages/core/tests/figma-api/text/autosize.test.ts
+++ b/packages/core/tests/figma-api/text/autosize.test.ts
@@ -1,6 +1,7 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
+import type { TextNode } from '@figma/plugin-typings/plugin-api-standalone'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
diff --git a/packages/core/tests/figma-api/text/lists.test.ts b/packages/core/tests/figma-api/text/lists.test.ts
index 8e0205a35..438156210 100644
--- a/packages/core/tests/figma-api/text/lists.test.ts
+++ b/packages/core/tests/figma-api/text/lists.test.ts
@@ -1,10 +1,11 @@
import { beforeAll, describe, expect, test } from 'bun:test'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+import type { TextListOptions } from '@figma/plugin-typings/plugin-api-standalone'
+
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { registerTestFont } from '#core-tests/helpers/figma-api'
-
beforeAll(() => registerTestFont())
// Results recorded from the same scripts run in live Figma (2026-10-09).
@@ -90,21 +91,19 @@ describe('text lists', () => {
"in getRangeListOptions: Empty range selected. 'end' must be greater than 'start'"
)
expect(() => text.getRangeListOptions(-1, 2)).toThrow(
- 'in getRangeListOptions: Property "start" failed validation: Number must be greater than or equal to 0'
+ 'in getRangeListOptions: Property "start" failed validation: Too small: expected number to be >=0'
)
expect(() => text.getRangeListOptions(0, 99)).toThrow(
'in getRangeListOptions: Range outside of available characters.'
)
expect(() =>
text.setRangeListOptions(0, 1, { type: 'BULLET' as TextListOptions['type'] })
- ).toThrow("Expected 'NONE' | 'ORDERED' | 'UNORDERED', received 'BULLET' at .type")
- expect(() => text.setRangeIndentation(6, 8, -1)).toThrow(
- 'Number must be greater than or equal to 0'
- )
- expect(() => text.setRangeIndentation(3, 5, 2.5)).toThrow('Expected integer, received float')
- expect(() => text.setRangeIndentation(0, 2, 9)).toThrow(
- 'Number must be less than or equal to 5'
+ ).toThrow(
+ 'in setRangeListOptions: Property "options" failed validation: Invalid option: expected one of "NONE"|"ORDERED"|"UNORDERED" at .type'
)
+ expect(() => text.setRangeIndentation(6, 8, -1)).toThrow('Too small: expected number to be >=0')
+ expect(() => text.setRangeIndentation(3, 5, 2.5)).toThrow('Expected int, received number')
+ expect(() => text.setRangeIndentation(0, 2, 9)).toThrow('Too big: expected number to be <=5')
})
test('sets list and paragraph spacing, indent, and hanging markers', () => {
@@ -128,7 +127,7 @@ describe('text lists', () => {
expect(() => {
text.listSpacing = -3
}).toThrow(
- 'in set_listSpacing: Property "listSpacing" failed validation: Number must be greater than or equal to 0'
+ 'in set_listSpacing: Property "listSpacing" failed validation: Too small: expected number to be >=0'
)
})
})
diff --git a/packages/core/tests/figma-api/text/paragraph-spacing.test.ts b/packages/core/tests/figma-api/text/paragraph-spacing.test.ts
index 394c3cc62..7e421ce16 100644
--- a/packages/core/tests/figma-api/text/paragraph-spacing.test.ts
+++ b/packages/core/tests/figma-api/text/paragraph-spacing.test.ts
@@ -1,10 +1,10 @@
import { beforeAll, describe, expect, test } from 'bun:test'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { registerTestFont } from '#core-tests/helpers/figma-api'
-
beforeAll(() => registerTestFont())
// Results recorded from the same scripts run in live Figma (2026-10-10).
@@ -67,7 +67,7 @@ describe('paragraph spacing ranges', () => {
test('reject what Figma rejects, with its messages', () => {
const { text } = spacedText()
expect(() => text.setRangeParagraphSpacing(0, 1, -3)).toThrow(
- 'in setRangeParagraphSpacing: Property "value" failed validation: Number must be greater than or equal to 0'
+ 'in setRangeParagraphSpacing: Property "value" failed validation: Too small: expected number to be >=0'
)
expect(() => text.setRangeParagraphIndent(0, 1, -3)).toThrow(
'in setRangeParagraphIndent: Property "value" failed validation'
diff --git a/packages/core/tests/figma-api/text/references.test.ts b/packages/core/tests/figma-api/text/references.test.ts
index c17c8b7eb..ce129329d 100644
--- a/packages/core/tests/figma-api/text/references.test.ts
+++ b/packages/core/tests/figma-api/text/references.test.ts
@@ -1,11 +1,11 @@
import { beforeAll, describe, expect, test } from 'bun:test'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { registerTestFont } from '#core-tests/helpers/figma-api'
-
beforeAll(async () => {
await registerTestFont()
await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: 'Inter', style: 'Bold' })
@@ -68,7 +68,7 @@ describe('text case ranges', () => {
test('reject what Figma rejects, and small caps OpenPencil cannot draw', () => {
const { text } = styledText()
expect(() => text.setRangeTextCase(0, 5, 'SHOUT' as 'UPPER')).toThrow(
- `in setRangeTextCase: Property "value" failed validation: Invalid enum value. Expected 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE' | 'SMALL_CAPS' | 'SMALL_CAPS_FORCED', received 'SHOUT'`
+ `in setRangeTextCase: Property "textCase" failed validation: Invalid option: expected one of "ORIGINAL"|"UPPER"|"LOWER"|"TITLE"|"SMALL_CAPS"|"SMALL_CAPS_FORCED"`
)
expect(() => text.setRangeTextCase(0, 5, 'SMALL_CAPS' as 'UPPER')).toThrow(
'in setRangeTextCase: OpenPencil does not support the SMALL_CAPS text case'
@@ -106,13 +106,13 @@ describe('hyperlink ranges', () => {
test('reject links Figma rejects', () => {
const { text } = styledText()
expect(() => text.setRangeHyperlink(0, 5, 'https://x' as never)).toThrow(
- 'in setRangeHyperlink: Property "value" failed validation: Expected object, received string'
+ 'in setRangeHyperlink: Property "hyperlink" failed validation: Expected one of the following, but none matched:\n Expected object, received string\n Expected null, received string'
)
expect(() => text.setRangeHyperlink(0, 5, { type: 'PAGE', value: 'x' } as never)).toThrow(
- `in setRangeHyperlink: Property "value" failed validation: Invalid enum value. Expected 'URL' | 'NODE', received 'PAGE' at .type`
+ 'in setRangeHyperlink: Property "hyperlink" failed validation: Expected one of the following, but none matched:\n Invalid option: expected one of "URL"|"NODE" at .type\n Expected null, received object'
)
expect(() => text.setRangeHyperlink(0, 5, { type: 'URL', value: 3 } as never)).toThrow(
- 'in setRangeHyperlink: Property "value" failed validation: Expected string, received number at .value'
+ 'in setRangeHyperlink: Property "hyperlink" failed validation: Expected one of the following, but none matched:\n Expected string, received number at .value\n Expected null, received object'
)
})
@@ -267,7 +267,7 @@ describe('bound variable ranges', () => {
test('reject fields and variables Figma cannot bind', () => {
const { text, size, family } = sized()
expect(() => text.setRangeBoundVariable(0, 5, 'opacity' as 'fontSize', size)).toThrow(
- `in setRangeBoundVariable: Property "field" failed validation: Invalid enum value. Expected 'fontFamily' | 'fontSize'`
+ `in setRangeBoundVariable: Property "field" failed validation: Invalid option: expected one of "fontFamily"|"fontSize"|`
)
expect(() => text.setRangeBoundVariable(0, 5, 'fontSize', family)).toThrow(
'in setRangeBoundVariable: Cannot bind a STRING variable to "fontSize", which takes FLOAT'
diff --git a/packages/core/tests/figma-api/text/styles.test.ts b/packages/core/tests/figma-api/text/styles.test.ts
index ebe22e232..6ddb5891f 100644
--- a/packages/core/tests/figma-api/text/styles.test.ts
+++ b/packages/core/tests/figma-api/text/styles.test.ts
@@ -128,7 +128,7 @@ describe('styled text segments', () => {
"in getStyledTextSegments: Invalid range. Must provide both 'start' and 'end'"
)
expect(() => text.getStyledTextSegments(['nope' as 'fontSize'])).toThrow(
- `in getStyledTextSegments: Property "getStyledTextSegments" failed validation: Invalid enum value. Expected 'fontSize' | 'fontName'`
+ `in getStyledTextSegments: Property "getStyledTextSegments" failed validation: Invalid option: expected one of "fontSize"|"fontName"|`
)
expect(styledText('').text.getStyledTextSegments(['fontSize'])).toEqual([])
})
@@ -251,10 +251,10 @@ describe('character style ranges', () => {
const message = (method: string, problem: string) =>
`in ${method}: Property "value" failed validation: ${problem}`
expect(() => text.setRangeFontSize(0, 1, 0)).toThrow(
- message('setRangeFontSize', 'Number must be greater than or equal to 1')
+ message('setRangeFontSize', 'Too small: expected number to be >=1')
)
expect(() => text.setRangeFontSize(0, 1, Number.NaN)).toThrow(
- message('setRangeFontSize', 'Expected number, received nan')
+ message('setRangeFontSize', 'Expected number, received NaN')
)
// The range is checked before the value.
expect(() => text.setRangeFontSize(5, 9, 0)).toThrow(
@@ -263,22 +263,22 @@ describe('character style ranges', () => {
expect(() => text.setRangeLetterSpacing(0, 1, { value: 1, unit: 'EM' as 'PIXELS' })).toThrow(
message(
'setRangeLetterSpacing',
- "Invalid enum value. Expected 'PIXELS' | 'PERCENT', received 'EM' at .unit"
+ 'Invalid option: expected one of "PIXELS"|"PERCENT" at .unit'
)
)
expect(() => text.setRangeLineHeight(0, 1, { value: 1, unit: 'EM' as 'PIXELS' })).toThrow(
message(
'setRangeLineHeight',
- "Invalid discriminator value. Expected 'PIXELS' | 'PERCENT' | 'AUTO' at .unit"
+ 'Expected .unit to be one of the following: PIXELS, PERCENT, AUTO'
)
)
expect(() =>
text.setRangeFills(0, 1, [{ type: 'SOLID', color: { r: 2, g: 0, b: 0 } }])
- ).toThrow(message('setRangeFills', 'Number must be less than or equal to 1 at [0].color.r'))
+ ).toThrow(message('setRangeFills', 'Too big: expected number to be <=1 at [0].color.r'))
expect(() => text.setRangeTextDecoration(0, 1, 'OVERLINE' as 'NONE')).toThrow(
message(
'setRangeTextDecoration',
- "Invalid enum value. Expected 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH', received 'OVERLINE'"
+ 'Invalid option: expected one of "NONE"|"UNDERLINE"|"STRIKETHROUGH"'
)
)
expect(() => text.setRangeFontName(0, 1, null as never)).toThrow(
@@ -296,12 +296,11 @@ describe('character style ranges', () => {
test('reject paints Figma rejects, which would not survive saving', () => {
const { text } = styledText('Abc')
const paintTypes =
- "'SOLID' | 'SHADER' | 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'GRADIENT_ANGULAR' | " +
- "'GRADIENT_DIAMOND' | 'IMAGE' | 'VIDEO'"
+ 'SOLID, SHADER, GRADIENT_LINEAR, GRADIENT_RADIAL, GRADIENT_ANGULAR, GRADIENT_DIAMOND, IMAGE, VIDEO'
const fills = (problem: string) =>
`in setRangeFills: Property "value" failed validation: ${problem}`
expect(() => text.setRangeFills(0, 1, [{ color: BLUE } as never])).toThrow(
- fills(`Invalid discriminator value. Expected ${paintTypes} at [0].type`)
+ fills(`Expected [0].type to be one of the following: ${paintTypes}`)
)
expect(() => text.setRangeFills(0, 1, [{ type: 'SOLID' } as never])).toThrow(
fills('Required value missing at [0].color')
@@ -314,19 +313,19 @@ describe('character style ranges', () => {
expect(() => solid(null)).toThrow(fills('Expected object, received null at [0].color'))
expect(() => solid({ r: 0, g: 0 })).toThrow(fills('Required value missing at [0].color.b'))
expect(() => solid({ r: -0.1, g: 0, b: 0 })).toThrow(
- fills('Number must be greater than or equal to 0 at [0].color.r')
+ fills('Too small: expected number to be >=0 at [0].color.r')
)
expect(() => solid({ r: Number.NaN, g: 0, b: 0 })).toThrow(
- fills('Expected number, received nan at [0].color.r')
+ fills('Expected number, received NaN at [0].color.r')
)
expect(() => solid({ r: '1', g: 0, b: 0 })).toThrow(
fills('Expected number, received string at [0].color.r')
)
expect(() => solid({ r: 0, g: 0, b: 0, a: 2 })).toThrow(
- fills('Number must be less than or equal to 1 at [0].color.a')
+ fills('Too big: expected number to be <=1 at [0].color.a')
)
expect(() => solid({ r: 0, g: 0, b: 0 }, 2)).toThrow(
- fills('Number must be less than or equal to 1 at [0].opacity')
+ fills('Too big: expected number to be <=1 at [0].opacity')
)
expect(() => solid({ r: 0, g: 0, b: 0, a: 0.5 })).not.toThrow()
@@ -336,24 +335,24 @@ describe('character style ranges', () => {
const noneMatched = (issues: string) =>
color(
`Expected one of the following, but none matched:\n${issues}\n` +
- ' Invalid literal value, expected "AUTO" at .value'
+ ' Invalid input: expected "AUTO" at .value'
)
expect(() => text.setRangeTextDecorationColor(0, 1, { value: BLUE as never })).toThrow(
noneMatched(
' Multiple issues:\n' +
- ' Invalid literal value, expected "SOLID" at .value.type\n' +
+ ' Invalid input: expected "SOLID" at .value.type\n' +
' Required value missing at .value.color\n' +
- " Unrecognized key(s) in object: 'r', 'g', 'b', 'a' at .value"
+ ' Unrecognized keys: "r", "g", "b", "a" at .value'
)
)
expect(() =>
text.setRangeTextDecorationColor(0, 1, { value: { type: 'NOPE', color: RGB_BLUE } as never })
- ).toThrow(noneMatched(' Invalid literal value, expected "SOLID" at .value.type'))
+ ).toThrow(noneMatched(' Invalid input: expected "SOLID" at .value.type'))
expect(() =>
text.setRangeTextDecorationColor(0, 1, {
value: { type: 'SOLID', color: RGB_BLUE, foo: 1 } as never
})
- ).toThrow(color("Unrecognized key(s) in object: 'foo' at .value"))
+ ).toThrow(color('Unrecognized key: "foo" at .value'))
expect(() =>
text.setRangeTextDecorationColor(0, 1, { value: { type: 'SOLID', color: null } as never })
).toThrow(noneMatched(' Expected object, received null at .value.color'))
@@ -361,7 +360,7 @@ describe('character style ranges', () => {
text.setRangeTextDecorationColor(0, 1, {
value: { type: 'SOLID', color: { r: -1, g: 0, b: 0 } } as never
})
- ).toThrow(color('Number must be greater than or equal to 0 at .value.color.r'))
+ ).toThrow(color('Too small: expected number to be >=0 at .value.color.r'))
})
})
diff --git a/packages/core/tests/figma-api/text/units.test.ts b/packages/core/tests/figma-api/text/units.test.ts
index 81df6a278..e0a2e5477 100644
--- a/packages/core/tests/figma-api/text/units.test.ts
+++ b/packages/core/tests/figma-api/text/units.test.ts
@@ -1,13 +1,12 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
import { lineHeightPixels, percentLength, pixelLength } from '@open-pencil/scene-graph/text'
-import { registerTestFont } from '#core-tests/helpers/figma-api'
-
beforeAll(() => registerTestFont())
function text() {
@@ -68,7 +67,7 @@ describe('text units in the plugin API', () => {
'in set_letterSpacing: Property "letterSpacing" failed validation: Required value missing at .value\nInvalid option: expected one of "PIXELS"|"PERCENT" at .unit'
)
expect(set('lineHeight', { unit: 'PIXELS', value: Number.NaN })).toThrow(
- 'in set_lineHeight: Property "lineHeight" failed validation: Expected number, received nan at .value'
+ 'in set_lineHeight: Property "lineHeight" failed validation: Expected number, received NaN at .value'
)
expect(set('letterSpacing', { unit: 'RAW', value: 1 })).toThrow(
'in set_letterSpacing: Property "letterSpacing" failed validation: Invalid option: expected one of "PIXELS"|"PERCENT" at .unit'
diff --git a/packages/core/tests/helpers/figma-api.ts b/packages/core/tests/helpers/figma-api.ts
index 66cb7d275..424d7a056 100644
--- a/packages/core/tests/helpers/figma-api.ts
+++ b/packages/core/tests/helpers/figma-api.ts
@@ -1,3 +1,10 @@
+import type {
+ ComponentNode,
+ PageNode,
+ SolidPaint,
+ TextNode
+} from '@figma/plugin-typings/plugin-api-standalone'
+
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
import { fontManager } from '@open-pencil/core/text'
import { SceneGraph, type Fill } from '@open-pencil/scene-graph'
diff --git a/packages/core/tests/io/formats/fig/roundtrip/layout-guides.test.ts b/packages/core/tests/io/formats/fig/roundtrip/layout-guides.test.ts
index 1245cb2ee..b49543c77 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/layout-guides.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/layout-guides.test.ts
@@ -60,7 +60,7 @@ test('layout guides set from a script or the panel save and reopen in Figma’s
},
{ pattern: 'GRID', sectionSize: 10, visible: true, color: green }
]
- expect(guidesOf(await reopen(graph))).toEqual([
+ expect<unknown>(guidesOf(await reopen(graph))).toEqual([
{
pattern: 'COLUMNS',
alignment: 'STRETCH',
@@ -68,7 +68,8 @@ test('layout guides set from a script or the panel save and reopen in Figma’s
count: 5,
offset: 0,
visible: true,
- color: red
+ color: red,
+ boundVariables: {}
},
{
pattern: 'ROWS',
@@ -78,7 +79,8 @@ test('layout guides set from a script or the panel save and reopen in Figma’s
sectionSize: 40,
offset: 4,
visible: false,
- color: blue
+ color: blue,
+ boundVariables: {}
},
{
pattern: 'COLUMNS',
@@ -88,9 +90,10 @@ test('layout guides set from a script or the panel save and reopen in Figma’s
sectionSize: 40,
offset: 0,
visible: true,
- color: green
+ color: green,
+ boundVariables: {}
},
- { pattern: 'GRID', sectionSize: 10, visible: true, color: green }
+ { pattern: 'GRID', sectionSize: 10, visible: true, color: green, boundVariables: {} }
])
})
@@ -117,7 +120,7 @@ test('a grid saved without a size is Figma’s 10 px one', async () => {
name: 'Guides',
layoutGrids: [{ pattern: 'GRID', color: blue }]
})
- expect(guidesOf(await reopen(graph))).toEqual([
- { pattern: 'GRID', sectionSize: 10, visible: true, color: blue }
+ expect<unknown>(guidesOf(await reopen(graph))).toEqual([
+ { pattern: 'GRID', sectionSize: 10, visible: true, color: blue, boundVariables: {} }
])
})
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 5dc2861e7..8b68e21c0 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -216,6 +216,7 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'
- `node.findOne(callback)`
- `node.findChild(callback)`
- `node.findChildren(callback?)`
+- `node.getTopLevelFrame()` — the frame, group, section, component, or instance the node sits in directly under its page or section
- `figma.group(nodes, parent)`
- `figma.ungroup(node)`
@@ -224,8 +225,11 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'
- `figma.createComponentFromNode(node)`
- `figma.combineAsVariants(components, parent)` — properties come from names such as `State=On, Size=Large`
- On a component set, `addComponentProperty(name, 'VARIANT', value)` appends the value to every variant's name and `editComponentProperty(name, { name })` renames the property in them, which instances follow; renaming a variant updates the set's values, and `variantProperties` reads a variant's or an instance's values
-- `component.createInstance()`
+- `component.createInstance()`, `component.instances`, and `component.getInstancesAsync()`
+- `description` on components and component sets
+- `set.defaultVariant`, the first variant reading the set across each row and then down, and `set.variantGroupProperties`
- `instance.mainComponent`
+- `instance.removeOverrides()` (and its deprecated name `resetOverrides()`)
### Variables
@@ -236,17 +240,27 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'
- `collection.addMode(name)`, `renameMode(modeId, name)`, `removeMode(modeId)`, `modes`, `defaultModeId`, `variableIds`, and `remove()`
- `node.boundVariables`, `node.setBoundVariable(field, variable)`, `node.setExplicitVariableModeForCollection(collection, modeId)`, and `node.clearExplicitVariableModeForCollection(collection)`
+### Styles
+
+- `figma.createPaintStyle()`, `createTextStyle()`, `createEffectStyle()`, and `createGridStyle()`, kept on the document's internal page as Figma keeps them
+- `figma.getLocalPaintStyles()`, `getLocalTextStyles()`, `getLocalEffectStyles()`, `getLocalGridStyles()`, their `…Async` forms, and `figma.getStyleById(id)` / `getStyleByIdAsync(id)`
+- `style.name`, `description`, `key`, `paints`, `effects`, `layoutGrids`, a text style's font, size, spacing, case, and decoration, `getStyleConsumersAsync()`, and `remove()`; a change to a style reaches every layer and text range that uses it, and removing it leaves them its values
+- `fillStyleId`, `strokeStyleId`, `effectStyleId`, `gridStyleId`, and `textStyleId` with their `set…StyleIdAsync` setters, on the layers Figma has them on; setting one gives the layer the style's values, an empty ID takes the style off, and a style the document does not hold is refused
+
### Properties
Common node properties are readable/writable through the proxy, including:
- Geometry: `x`, `y`, `width`, `height`, `rotation`, `resize(width, height)`
-- Appearance: `fills`, `strokes`, `effects`, `opacity`, `visible`, `locked`, `blendMode`, `clipsContent`. Paints take Figma's shape here, on page `backgrounds`, text ranges, and vector regions: a solid `color` is RGB with its alpha in `opacity`, and an image names `scaleMode`, `rotation`, and `scalingFactor`; a paint Figma refuses throws Figma's message
+- Appearance: `fills`, `strokes` (also set with `setFillsAsync` and `setStrokesAsync`), `effects`, `opacity`, `visible`, `locked`, `blendMode`, `clipsContent`. Paints take Figma's shape here, on page `backgrounds`, text ranges, and vector regions: a solid `color` is RGB with its alpha in `opacity`, and an image names `scaleMode`, `rotation`, and `scalingFactor`; a paint Figma refuses throws Figma's message
- Radius: `cornerRadius`, `topLeftRadius`, `topRightRadius`, `bottomRightRadius`, `bottomLeftRadius`
-- Text: `characters`, `fontSize`, `fontName` (with `variationSettings`, every axis of a variable font), `fontWeight` (a variable font's `wght`), `fills`, `letterSpacing`, `lineHeight`, and `textDecoration`, which read `figma.mixed` while characters differ and restyle every character when set, and alignment
+- Text: `characters`, `fontSize`, `fontName` (with `variationSettings`, every axis of a variable font), `fontWeight` (a variable font's `wght`), `fills`, `letterSpacing`, `lineHeight`, and `textDecoration` with its `textDecorationStyle`, `textDecorationOffset`, `textDecorationThickness`, `textDecorationColor`, and `textDecorationSkipInk` (null without an underline), which read `figma.mixed` while characters differ and restyle every character when set, `openTypeFeatures`, `leadingTrim`, and alignment
- Text ranges: `getStyledTextSegments(fields, start?, end?)`, and `getRange…` / `setRange…` for `FontSize`, `FontName`, `Fills`, `LetterSpacing`, `LineHeight`, `TextDecoration` with its `Style`, `Offset`, `Thickness`, `Color`, and `SkipInk`, `TextCase`, `Hyperlink` (a `{ type: 'URL' | 'NODE', value }` link, or `null`), `TextStyleId` and `FillStyleId` (set with `setRangeTextStyleIdAsync` and `setRangeFillStyleIdAsync`, which give the range the style's fields), and `getRangeBoundVariable` / `setRangeBoundVariable` for the text fields Figma binds, plus `getRangeFontWeight`, `getRangeAllFontNames`, and `getRangeOpenTypeFeatures`. Line height and letter spacing keep the unit they are set in, pixels or a percent of the font size that follows the size, as in Figma; other lengths read in pixels, and a percent given to their setters is of the font size
- Text lists and paragraphs: `getRangeListOptions` / `setRangeListOptions` for bulleted (`UNORDERED`) and numbered (`ORDERED`) items, `getRangeIndentation` / `setRangeIndentation` for nesting (1–5 for list items), `listSpacing`, `paragraphSpacing`, and `paragraphIndent` for the whole text (`figma.mixed` when paragraphs differ) or per paragraph with `getRangeListSpacing` / `setRangeListSpacing`, `getRangeParagraphSpacing` / `setRangeParagraphSpacing`, and `getRangeParagraphIndent` / `setRangeParagraphIndent`, and `hangingList`
-- Auto-layout: `layoutMode`, `primaryAxisAlignItems`, `counterAxisAlignItems`, `itemSpacing`, padding, sizing, and layout positioning fields
+- Auto-layout: `layoutMode`, `primaryAxisAlignItems`, `counterAxisAlignItems`, `itemSpacing`, padding (including Figma's deprecated `horizontalPadding` and `verticalPadding`), sizing, and layout positioning fields
+- Guides: `guides` on pages and frames, as `{ axis: 'X' | 'Y', offset }`
+- Shapes: `pointCount`, a star's `innerRadius`, an ellipse's `arcData`, and a boolean's `booleanOperation`
+- Document: `figma.root.documentColorProfile`
- Stroke helpers: `strokeWeight`, `strokeAlign`, `dashPattern`
- Status: `devStatus` on sections, frames, components, component sets, and instances directly on a page or in a section, as `{ type: 'READY_FOR_DEV' | 'COMPLETED' }` or `null` (a description is not kept); it reads `null` while the layer sits where it cannot show one
diff --git a/packages/scene-graph/src/components/variants.ts b/packages/scene-graph/src/components/variants.ts
index 55a6447b3..dcbdefaa6 100644
--- a/packages/scene-graph/src/components/variants.ts
+++ b/packages/scene-graph/src/components/variants.ts
@@ -7,14 +7,25 @@ export function compareCanvasPosition(a: SceneNode, b: SceneNode): number {
}
/**
- * A component set's default variant, the one an instance starts as: the variant in its
- * top-left corner, as Figma defines it.
+ * Whether `a` comes before `b` reading the set as Figma does: variants whose rows overlap, edges
+ * touching included, read left to right, and others top to bottom.
+ */
+function readsBefore(a: SceneNode, b: SceneNode): boolean {
+ const sameRow = a.y <= b.y + b.height && b.y <= a.y + a.height
+ return sameRow ? a.x < b.x || (a.x === b.x && a.y < b.y) : a.y < b.y
+}
+
+/**
+ * A component set's default variant, the one an instance starts as: the first in reading order,
+ * and the first in layer order of those at the same place (measured in Figma desktop 126).
*/
export function defaultVariant(graph: SceneGraph, set: SceneNode): SceneNode | undefined {
- return graph
- .getChildren(set.id)
- .filter((child) => child.type === 'COMPONENT')
- .sort(compareCanvasPosition)[0]
+ let first: SceneNode | undefined
+ for (const child of graph.getChildren(set.id)) {
+ if (child.type !== 'COMPONENT') continue
+ if (!first || readsBefore(child, first)) first = child
+ }
+ return first
}
/**
diff --git a/packages/scene-graph/src/fields/text.ts b/packages/scene-graph/src/fields/text.ts
index bc77ffd5a..c7f971219 100644
--- a/packages/scene-graph/src/fields/text.ts
+++ b/packages/scene-graph/src/fields/text.ts
@@ -16,7 +16,9 @@ export const TEXT_METRIC_FIELDS = [
'listSpacing',
'paragraphSpacing',
'paragraphIndent',
- 'hangingList'
+ 'hangingList',
+ // A cap-height trim drops the space above and below the glyphs, so the text measures shorter.
+ 'leadingTrim'
] as const satisfies readonly (keyof SceneNode)[]
export const TEXT_SHAPING_FIELDS = [
diff --git a/packages/scene-graph/src/guides.ts b/packages/scene-graph/src/guides.ts
index 0f5cf58b0..64d93a411 100644
--- a/packages/scene-graph/src/guides.ts
+++ b/packages/scene-graph/src/guides.ts
@@ -9,6 +9,11 @@ export interface CanvasGuide {
figGuid?: GUID
}
+/** A new guide's id, unique across documents as a copied guide keeps its id. */
+export function newGuideId(): string {
+ return `guide:${crypto.randomUUID()}`
+}
+
const ownersByGraph = new WeakMap<SceneGraph, Set<string>>()
function ownerSet(graph: SceneGraph): Set<string> {
diff --git a/packages/scene-graph/src/shared-styles.ts b/packages/scene-graph/src/shared-styles.ts
index 868aa0302..f9857a3b7 100644
--- a/packages/scene-graph/src/shared-styles.ts
+++ b/packages/scene-graph/src/shared-styles.ts
@@ -1,6 +1,10 @@
-import { compact, isEqual, omit } from 'es-toolkit'
+import { compact, isEqual, omit, pick } from 'es-toolkit'
+import { BLACK } from './constants'
+import { copyEffects, copyFills, copyLayoutGrids } from './copy'
import type { SceneGraph } from './graph'
+import { newStrokeGeometry } from './node-defaults'
+import { randomHex } from './random'
import { styleRunReferences } from './text/references'
import type {
CharacterStyleOverride,
@@ -145,3 +149,80 @@ export function styleDetachmentChanges(
}
return next
}
+
+/** The node of the shared style with `id`, when the document holds one of `type`. */
+export function findSharedStyle(
+ graph: SceneGraph,
+ id: string,
+ type: SharedStyleType
+): SceneNode | undefined {
+ if (!id) return undefined
+ for (const node of graph.getAllNodes()) {
+ if (node.sharedStyleType === type && node.source.id === id) return node
+ }
+ return undefined
+}
+
+/** A new local style's ID, in the shape Figma gives one: `S:` and a 40-digit hex key. */
+export function newSharedStyleId(): string {
+ return `S:${randomHex(20)},`
+}
+
+const INTERNAL_CANVAS_NAME = 'Internal Only Canvas'
+
+/** The page that holds the document's styles out of view, as a `.fig` file keeps them; made once. */
+export function internalCanvas(graph: SceneGraph): SceneNode {
+ const existing = graph.getPages(true).find((page) => page.internalOnly)
+ if (existing) return existing
+ return graph.createNode('CANVAS', graph.rootId, {
+ name: INTERNAL_CANVAS_NAME,
+ width: 0,
+ height: 0,
+ internalOnly: true
+ })
+}
+
+/**
+ * A paint style's paints as a layer's strokes: every paint, each keeping the weight, alignment,
+ * and line style of the stroke it replaces, or of the layer's first; no paints clear the strokes
+ * (Figma desktop 126).
+ */
+function strokesFromStyle(target: SceneNode, style: SceneNode): SceneNode['strokes'] {
+ // Without strokes, the layer keeps the weight and alignment a new stroke takes.
+ const fallback: Stroke = target.strokes[0] ?? {
+ type: 'SOLID',
+ color: BLACK,
+ opacity: 1,
+ visible: true,
+ ...newStrokeGeometry(target)
+ }
+ return copyFills(style.fills).map((paint, index) => ({
+ ...paint,
+ ...pick(target.strokes[index] ?? fallback, STROKE_LINE_KEYS)
+ }))
+}
+
+/**
+ * What a layer takes from a shared style it starts using: the style's fields and the reference
+ * that keeps it attached. Without the style's node, the reference alone.
+ */
+export function sharedStylePatch(
+ kind: SharedStyleKind,
+ target: SceneNode,
+ styleId: string,
+ style: SceneNode | null
+): Partial<SceneNode> {
+ const patch: Partial<SceneNode> = { [STYLE_REF_KEYS[kind]]: styleId }
+ if (!style) return patch
+ if (kind === 'fill') patch.fills = copyFills(style.fills)
+ else if (kind === 'stroke') patch.strokes = strokesFromStyle(target, style)
+ else if (kind === 'effect') patch.effects = copyEffects(style.effects)
+ else if (kind === 'grid') patch.layoutGrids = copyLayoutGrids(style.layoutGrids)
+ else Object.assign(patch, structuredClone(pick(style, SHARED_STYLE_FIELDS.text)))
+ return patch
+}
+
+/** A layer leaving a shared style: it keeps the style's values, without the reference. */
+export function sharedStyleDetachPatch(kind: SharedStyleKind): Partial<SceneNode> {
+ return { [STYLE_REF_KEYS[kind]]: null }
+}
diff --git a/packages/scene-graph/tests/basic/update-node.test.ts b/packages/scene-graph/tests/basic/update-node.test.ts
index 6706f65e9..89139a652 100644
--- a/packages/scene-graph/tests/basic/update-node.test.ts
+++ b/packages/scene-graph/tests/basic/update-node.test.ts
@@ -185,6 +185,16 @@ describe('updateNode', () => {
expect(expectDefined(afterUpdate, 'updated node').textPicture).toBeNull()
})
+ test('a leading trim change drops the saved text drawing and layout', () => {
+ const graph = new SceneGraph()
+ const text = graph.createNode('TEXT', pageId(graph), { width: 100, height: 20 })
+ text.textPicture = new Uint8Array([1, 2, 3])
+ text.derivedLayout = { width: 100, height: 20 }
+ graph.updateNode(text.id, { leadingTrim: 'CAP_HEIGHT' })
+ const updated = expectDefined(graph.getNode(text.id), 'updated node')
+ expect([updated.textPicture, updated.derivedLayout]).toEqual([null, null])
+ })
+
test('derivedTextGlyphs are nulled when text rendering properties change on TEXT node', () => {
const graph = new SceneGraph()
const page = pageId(graph)
diff --git a/packages/scene-graph/tests/components/variants.test.ts b/packages/scene-graph/tests/components/variants.test.ts
index feda1d121..4dcb1eb2c 100644
--- a/packages/scene-graph/tests/components/variants.test.ts
+++ b/packages/scene-graph/tests/components/variants.test.ts
@@ -42,6 +42,26 @@ describe('default variants', () => {
expect(defaultVariant(graph, set)?.name).toBe('Size=Small')
})
+ test('read the set as Figma does: across a row first, then down', () => {
+ const at = (x: number, y: number, size = 50) => ({ x, y, width: size, height: size })
+ const pick = (...places: Array<ReturnType<typeof at>>) => {
+ const graph = new SceneGraph()
+ const set = graph.createNode('COMPONENT_SET', graph.getPages()[0].id, { name: 'Set' })
+ for (const [index, place] of places.entries())
+ graph.createNode('COMPONENT', set.id, { name: `v=${index}`, ...place })
+ return defaultVariant(graph, set)?.name
+ }
+ // Rows apart: the higher one, however far right it is.
+ expect(pick(at(100, 0), at(0, 100))).toBe('v=0')
+ expect(pick(at(0, 60), at(30, 0))).toBe('v=1')
+ // Rows overlapping, or touching, read left to right.
+ expect(pick(at(10, 0), at(0, 10))).toBe('v=1')
+ expect(pick(at(0, 40), at(30, 0))).toBe('v=0')
+ expect(pick(at(200, 0, 100), at(0, 100, 100), at(100, 0, 100))).toBe('v=1')
+ // At the same place, the first in layer order.
+ expect(pick(at(0, 0), at(0, 0))).toBe('v=0')
+ })
+
test('give a property its default value when the document leaves it out', () => {
const empty = sizes('')
expect(variantDefaultValue(empty.graph, empty.set, empty.definition)).toBe('Small')
diff --git a/packages/vue/src/controls/shared-style/index.ts b/packages/vue/src/controls/shared-style/index.ts
index 80d1604d9..ff86926ee 100644
--- a/packages/vue/src/controls/shared-style/index.ts
+++ b/packages/vue/src/controls/shared-style/index.ts
@@ -1,2 +1 @@
-export { sharedStyleDetachPatch, sharedStylePatch } from '#vue/controls/shared-style/model'
export { useSharedStyleBinding } from '#vue/controls/shared-style/use'
diff --git a/packages/vue/src/controls/shared-style/model.ts b/packages/vue/src/controls/shared-style/model.ts
deleted file mode 100644
index 19f011b8b..000000000
--- a/packages/vue/src/controls/shared-style/model.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { BLACK } from '@open-pencil/core/constants'
-import type { SceneNode, SharedStyleKind } from '@open-pencil/scene-graph'
-import { copyEffects, copyFills, copyLayoutGrids } from '@open-pencil/scene-graph/copy'
-import { sharedStyleRefKey } from '@open-pencil/scene-graph/shared-styles'
-
-function strokePaintsFromStyle(target: SceneNode, style: SceneNode): SceneNode['strokes'] {
- const fills = style.fills.filter((fill) => fill.type === 'SOLID')
- if (fills.length === 0) return target.strokes
- const fallback = target.strokes[0] ?? {
- type: 'SOLID' as const,
- color: BLACK,
- weight: 1,
- opacity: 1,
- visible: true,
- align: 'CENTER' as const
- }
- return fills.map((fill, index) => {
- const current = target.strokes[index] ?? fallback
- return {
- ...current,
- color: { ...fill.color },
- opacity: fill.opacity,
- visible: fill.visible
- }
- })
-}
-
-export function sharedStylePatch(
- kind: SharedStyleKind,
- target: SceneNode,
- styleId: string,
- style: SceneNode | null
-): Partial<SceneNode> {
- const refKey = sharedStyleRefKey(kind)
- const patch: Partial<SceneNode> = { [refKey]: styleId }
- if (!style) return patch
-
- if (kind === 'fill') patch.fills = copyFills(style.fills)
- else if (kind === 'stroke') patch.strokes = strokePaintsFromStyle(target, style)
- else if (kind === 'effect') patch.effects = copyEffects(style.effects)
- else if (kind === 'grid') patch.layoutGrids = copyLayoutGrids(style.layoutGrids)
- else {
- Object.assign(patch, {
- fontFamily: style.fontFamily,
- fontWeight: style.fontWeight,
- italic: style.italic,
- fontSize: style.fontSize,
- lineHeight: style.lineHeight,
- letterSpacing: style.letterSpacing,
- textDecoration: style.textDecoration,
- textCase: style.textCase
- })
- }
- return patch
-}
-
-export function sharedStyleDetachPatch(kind: SharedStyleKind): Partial<SceneNode> {
- return { [sharedStyleRefKey(kind)]: null }
-}
diff --git a/packages/vue/src/controls/shared-style/use.ts b/packages/vue/src/controls/shared-style/use.ts
index 83ff46ba5..7f2e5ceaa 100644
--- a/packages/vue/src/controls/shared-style/use.ts
+++ b/packages/vue/src/controls/shared-style/use.ts
@@ -3,12 +3,13 @@ import { computed } from 'vue'
import type { SceneNode, SharedStyleKind } from '@open-pencil/scene-graph'
import {
getSharedStyles,
+ sharedStyleDetachPatch,
+ sharedStylePatch,
sharedStyleRefKey,
sharedStyleTypeForKind
} from '@open-pencil/scene-graph/shared-styles'
import { useNodeProps } from '#vue/controls/node-props/use'
-import { sharedStyleDetachPatch, sharedStylePatch } from '#vue/controls/shared-style/model'
import { useSceneComputed } from '#vue/internal/scene-computed/use'
function supportsStyle(node: SceneNode, kind: SharedStyleKind): boolean {
diff --git a/tests/engine/vue/controls/shared-style.test.ts b/tests/engine/vue/controls/shared-style.test.ts
index 7d65bb9ba..17a842e11 100644
--- a/tests/engine/vue/controls/shared-style.test.ts
+++ b/tests/engine/vue/controls/shared-style.test.ts
@@ -3,11 +3,13 @@ import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
import { effectiveFigmaRawNodeFields } from '@open-pencil/fig'
import type { Effect, Fill, SceneNode } from '@open-pencil/scene-graph'
-import { getSharedStyles } from '@open-pencil/scene-graph/shared-styles'
+import {
+ getSharedStyles,
+ sharedStyleDetachPatch,
+ sharedStylePatch
+} from '@open-pencil/scene-graph/shared-styles'
import { pixelLength } from '@open-pencil/scene-graph/text'
-import { sharedStyleDetachPatch, sharedStylePatch } from '#vue/controls/shared-style/model'
-
import { firstPageId, makeSceneGraph } from '#tests/helpers/scene'
const red: Fill = {
diff --git a/tests/helpers/plugin-api.ts b/tests/helpers/plugin-api.ts
index df3b83157..671a8b564 100644
--- a/tests/helpers/plugin-api.ts
+++ b/tests/helpers/plugin-api.ts
@@ -1,3 +1,5 @@
+import type { PageNode, SolidPaint } from '@figma/plugin-typings/plugin-api-standalone'
+
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
import { SceneGraph, type Fill } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'