Skip to content

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

Add .fig plugin data support

Danila Poyarkov049a13a081b9
diff --git a/packages/core/src/figma-api-proxy.ts b/packages/core/src/figma-api-proxy.ts
index b2c5dbd27..da76197b1 100644
--- a/packages/core/src/figma-api-proxy.ts
+++ b/packages/core/src/figma-api-proxy.ts
@@ -1,6 +1,7 @@
import { normalizeColor } from './color'
import { copyFills, copyStrokes, copyEffects } from './copy'
import { FONT_WEIGHT_NAMES } from './fonts'
+import { getFillOkHCL, getStrokeOkHCL, setNodeFillOkHCL, setNodeStrokeOkHCL } from './okhcl'
/* eslint-disable max-lines -- Figma Plugin API proxy; FigmaAPI already in separate file */
import type {
@@ -13,6 +14,7 @@ import type {
LayoutMode
} from './scene-graph'
import type { Rect } from './types'
+import type { OkHCLColor, OkHCLPayload } from './okhcl'
const MIXED = Symbol('mixed')
@@ -43,6 +45,8 @@ export const INTERNAL_ID = Symbol('id')
export const INTERNAL_GRAPH = Symbol('graph')
export const INTERNAL_API = Symbol('api')
+const OPEN_PENCIL_PLUGIN_DATA_NAMESPACE = 'open-pencil'
+
export interface NodeProxyHost {
wrapNode(id: string): FigmaNodeProxy
readonly currentPageId: string
@@ -933,6 +937,70 @@ export class FigmaNodeProxy {
return this.findAll((node) => !types || types.has(node.type))
}
+ // --- Plugin data ---
+
+ getPluginData(key: string): string {
+ return this._raw().pluginData.find(
+ (entry) => entry.pluginId === OPEN_PENCIL_PLUGIN_DATA_NAMESPACE && entry.key === key
+ )?.value ?? ''
+ }
+
+ setPluginData(key: string, value: string): void {
+ const node = this._raw()
+ const pluginData = node.pluginData.filter(
+ (entry) => !(entry.pluginId === OPEN_PENCIL_PLUGIN_DATA_NAMESPACE && entry.key === key)
+ )
+ if (value !== '') {
+ pluginData.push({ pluginId: OPEN_PENCIL_PLUGIN_DATA_NAMESPACE, key, value })
+ }
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { pluginData })
+ }
+
+ getPluginDataKeys(): string[] {
+ return this._raw().pluginData
+ .filter((entry) => entry.pluginId === OPEN_PENCIL_PLUGIN_DATA_NAMESPACE)
+ .map((entry) => entry.key)
+ }
+
+ getSharedPluginData(namespace: string, key: string): string {
+ return this._raw().sharedPluginData.find(
+ (entry) => entry.namespace === namespace && entry.key === key
+ )?.value ?? ''
+ }
+
+ setSharedPluginData(namespace: string, key: string, value: string): void {
+ const node = this._raw()
+ const sharedPluginData = node.sharedPluginData.filter(
+ (entry) => !(entry.namespace === namespace && entry.key === key)
+ )
+ if (value !== '') {
+ sharedPluginData.push({ namespace, key, value })
+ }
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { sharedPluginData })
+ }
+
+ getSharedPluginDataKeys(namespace: string): string[] {
+ return this._raw().sharedPluginData
+ .filter((entry) => entry.namespace === namespace)
+ .map((entry) => entry.key)
+ }
+
+ getFillOkHCL(index = 0): OkHCLPayload | null {
+ return getFillOkHCL(this._raw(), index)
+ }
+
+ setFillOkHCL(color: OkHCLColor, index = 0): void {
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], setNodeFillOkHCL(this._raw(), index, color))
+ }
+
+ getStrokeOkHCL(index = 0): OkHCLPayload | null {
+ return getStrokeOkHCL(this._raw(), index)
+ }
+
+ setStrokeOkHCL(color: OkHCLColor, index = 0): void {
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], setNodeStrokeOkHCL(this._raw(), index, color))
+ }
+
// --- Serialization ---
toJSON(maxDepth?: number, currentDepth = 0): Record<string, unknown> {
diff --git a/packages/core/src/figma-api.ts b/packages/core/src/figma-api.ts
index 9ccf3f9e3..cebc2c43d 100644
--- a/packages/core/src/figma-api.ts
+++ b/packages/core/src/figma-api.ts
@@ -219,7 +219,10 @@ export class FigmaAPI implements NodeProxyHost {
paddingTop: raw.paddingTop,
paddingRight: raw.paddingRight,
paddingBottom: raw.paddingBottom,
- paddingLeft: raw.paddingLeft
+ paddingLeft: raw.paddingLeft,
+ pluginData: structuredClone(raw.pluginData),
+ sharedPluginData: structuredClone(raw.sharedPluginData),
+ pluginRelaunchData: structuredClone(raw.pluginRelaunchData)
})
for (const childId of raw.childIds) {
this.graph.cloneTree(childId, comp.id)
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 2b85e5c78..63631049e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -95,6 +95,18 @@ export type {
export { executeRpcCommand, ALL_RPC_COMMANDS } from './rpc'
export { queryByXPath, matchByXPath } from './xpath'
export type { XPathQueryOptions } from './xpath'
+export {
+ okhclToRGBA,
+ serializeOkHCLPayload,
+ parseOkHCLPayload,
+ setNodeFillOkHCL,
+ setNodeStrokeOkHCL,
+ getNodeOkHCLPayloads,
+ getFillOkHCL,
+ getStrokeOkHCL,
+ type OkHCLColor,
+ type OkHCLPayload
+} from './okhcl'
export type {
InfoResult,
PageItem,
diff --git a/packages/core/src/kiwi/codec.ts b/packages/core/src/kiwi/codec.ts
index e9eea9e91..8a83fd97e 100644
--- a/packages/core/src/kiwi/codec.ts
+++ b/packages/core/src/kiwi/codec.ts
@@ -243,6 +243,19 @@ export interface VariableDataValuesEntry {
variableData: VariableDataEntry
}
+export interface PluginData {
+ pluginID: string
+ value: string
+ key: string
+}
+
+export interface PluginRelaunchData {
+ pluginID: string
+ message: string
+ command: string
+ isDeleted: boolean
+}
+
export interface NodeChange {
[key: string]: unknown
guid?: GUID
@@ -346,6 +359,8 @@ export interface NodeChange {
variableResolvedType?: string
variableDataValues?: { entries?: VariableDataValuesEntry[] }
variableScopes?: string[]
+ pluginData?: PluginData[]
+ pluginRelaunchData?: PluginRelaunchData[]
}
export interface FigmaMessage {
diff --git a/packages/core/src/kiwi/convert.ts b/packages/core/src/kiwi/convert.ts
index fececc26c..2852768f1 100644
--- a/packages/core/src/kiwi/convert.ts
+++ b/packages/core/src/kiwi/convert.ts
@@ -31,7 +31,10 @@ import type {
GeometryPath,
StyleRun,
CharacterStyleOverride,
- WindingRule
+ WindingRule,
+ PluginDataEntry,
+ SharedPluginDataEntry,
+ PluginRelaunchDataEntry
} from '../scene-graph'
import type { Color, Matrix, Vector } from '../types'
import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from './codec'
@@ -486,6 +489,41 @@ function extractBoundVariables(nc: NodeChange): Record<string, string> {
return bindings
}
+function extractPluginData(nc: NodeChange): PluginDataEntry[] {
+ return (nc.pluginData ?? []).map((entry) => ({
+ pluginId: entry.pluginID,
+ key: entry.key,
+ value: entry.value
+ }))
+}
+
+function extractSharedPluginData(nc: NodeChange): SharedPluginDataEntry[] {
+ return extractPluginData(nc).map((entry) => {
+ const slashIndex = entry.key.indexOf('/')
+ if (slashIndex === -1) {
+ return {
+ namespace: entry.pluginId,
+ key: entry.key,
+ value: entry.value
+ }
+ }
+ return {
+ namespace: entry.key.slice(0, slashIndex),
+ key: entry.key.slice(slashIndex + 1),
+ value: entry.value
+ }
+ })
+}
+
+function extractPluginRelaunchData(nc: NodeChange): PluginRelaunchDataEntry[] {
+ return (nc.pluginRelaunchData ?? []).map((entry) => ({
+ pluginId: entry.pluginID,
+ command: entry.command,
+ message: entry.message,
+ isDeleted: entry.isDeleted
+ }))
+}
+
function convertTransformProps(
nc: NodeChange
): Pick<SceneNode, 'x' | 'y' | 'width' | 'height' | 'rotation' | 'flipX' | 'flipY'> {
@@ -702,6 +740,9 @@ export function nodeChangeToProps(
expanded: true,
autoRename: (nc.autoRename ?? true) as boolean,
boundVariables: extractBoundVariables(nc),
+ pluginData: extractPluginData(nc),
+ sharedPluginData: extractSharedPluginData(nc),
+ pluginRelaunchData: extractPluginRelaunchData(nc),
clipsContent: nc.frameMaskDisabled === false && nc.resizeToFit !== true,
componentId: extractSymbolId(nc)
}
diff --git a/packages/core/src/kiwi/node-export.ts b/packages/core/src/kiwi/node-export.ts
new file mode 100644
index 000000000..91ad2976a
--- /dev/null
+++ b/packages/core/src/kiwi/node-export.ts
@@ -0,0 +1,147 @@
+import { mergePluginData, serializePluginRelaunchData } from './plugin-data'
+
+import type { SceneGraph, SceneNode } from '../scene-graph'
+import type { Color, GUID, Matrix } from '../types'
+import type { NodeChange, Paint } from './codec'
+
+export type KiwiNodeChange = NodeChange & Record<string, unknown>
+
+interface SceneNodeToKiwiContext {
+ graph: SceneGraph
+ blobs: Uint8Array[]
+ nodeIdToGuid?: Map<string, GUID>
+ fontDigestMap?: Map<string, Uint8Array>
+ varIdToGuid?: Map<string, GUID>
+ fractionalPosition: (index: number) => string
+ mapToFigmaType: (type: SceneNode['type']) => string
+ fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paint
+ safeColor: (color: { r: number; g: number; b: number; a?: number }) => Color
+ computeExportTransform: (node: SceneNode, graph: SceneGraph) => Matrix
+ serializeCornerRadii: (node: SceneNode, nc: KiwiNodeChange) => void
+ serializeTextProps: (
+ node: SceneNode,
+ nc: KiwiNodeChange,
+ graph: SceneGraph,
+ fontDigestMap?: Map<string, Uint8Array>
+ ) => void
+ serializeLayoutProps: (node: SceneNode, nc: KiwiNodeChange) => void
+ serializeGeometry: (node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Array[]) => void
+ serializeVariableBindings: (
+ node: SceneNode,
+ nc: KiwiNodeChange,
+ graph: SceneGraph,
+ varIdToGuid?: Map<string, GUID>
+ ) => void
+ sceneNodeToKiwi: (
+ node: SceneNode,
+ parentGuid: GUID,
+ childIndex: number,
+ localIdCounter: { value: number },
+ context: SceneNodeToKiwiContext
+ ) => KiwiNodeChange[]
+}
+
+const DEFAULT_STROKE_WEIGHT = 1
+
+function createStrokePaints(context: SceneNodeToKiwiContext, node: SceneNode): Paint[] {
+ return node.strokes.map((stroke) => ({
+ type: 'SOLID',
+ color: context.safeColor(stroke.color),
+ opacity: stroke.opacity,
+ visible: stroke.visible,
+ blendMode: 'NORMAL'
+ }))
+}
+
+function applyNodeVisualProps(context: SceneNodeToKiwiContext, node: SceneNode, nc: KiwiNodeChange): void {
+ if (node.independentStrokeWeights) {
+ nc.borderStrokeWeightsIndependent = true
+ nc.borderTopWeight = node.borderTopWeight
+ nc.borderRightWeight = node.borderRightWeight
+ nc.borderBottomWeight = node.borderBottomWeight
+ nc.borderLeftWeight = node.borderLeftWeight
+ }
+
+ if (node.fills.length > 0) nc.fillPaints = node.fills.map(context.fillToKiwiPaint)
+
+ context.serializeCornerRadii(node, nc)
+
+ if (node.effects.length > 0) {
+ nc.effects = node.effects.map((effect) => ({
+ type: effect.type === 'LAYER_BLUR' ? 'FOREGROUND_BLUR' : effect.type,
+ color: context.safeColor(effect.color),
+ offset: effect.offset,
+ radius: effect.radius,
+ spread: effect.spread,
+ visible: effect.visible
+ }))
+ }
+
+ if (node.type === 'TEXT') {
+ context.serializeTextProps(node, nc, context.graph, context.fontDigestMap)
+ }
+
+ nc.frameMaskDisabled = !node.clipsContent
+ if (node.horizontalConstraint !== 'MIN') nc.horizontalConstraint = node.horizontalConstraint
+ if (node.verticalConstraint !== 'MIN') nc.verticalConstraint = node.verticalConstraint
+ if (node.strokeCap !== 'NONE') nc.strokeCap = node.strokeCap
+ if (node.strokeJoin !== 'MITER') nc.strokeJoin = node.strokeJoin
+ if (node.strokeMiterLimit !== 28.96) nc.miterLimit = node.strokeMiterLimit
+ if (node.dashPattern.length > 0) nc.dashPattern = node.dashPattern
+ if (node.arcData) {
+ nc.arcData = {
+ startingAngle: node.arcData.startingAngle,
+ endingAngle: node.arcData.endingAngle,
+ innerRadius: node.arcData.innerRadius
+ }
+ }
+ if (!node.autoRename) nc.autoRename = false
+}
+
+export function sceneNodeToKiwiWithContext(
+ node: SceneNode,
+ parentGuid: GUID,
+ childIndex: number,
+ localIdCounter: { value: number },
+ context: SceneNodeToKiwiContext
+): KiwiNodeChange[] {
+ const localID = localIdCounter.value++
+ const guid = { sessionID: 1, localID }
+ context.nodeIdToGuid?.set(node.id, guid)
+
+ const strokePaints = createStrokePaints(context, node)
+
+ const nc: KiwiNodeChange = {
+ guid,
+ parentIndex: { guid: parentGuid, position: context.fractionalPosition(childIndex) },
+ type: context.mapToFigmaType(node.type),
+ name: node.name,
+ visible: node.visible,
+ opacity: node.opacity,
+ phase: 'CREATED',
+ size: { x: node.width, y: node.height },
+ transform: context.computeExportTransform(node, context.graph),
+ strokeWeight: node.strokes[0]?.weight ?? DEFAULT_STROKE_WEIGHT,
+ strokeAlign: node.strokes[0]?.align ?? 'INSIDE'
+ }
+
+ applyNodeVisualProps(context, node, nc)
+ if (strokePaints.length > 0) nc.strokePaints = strokePaints
+
+ context.serializeLayoutProps(node, nc)
+ context.serializeGeometry(node, nc, context.blobs)
+ context.serializeVariableBindings(node, nc, context.graph, context.varIdToGuid)
+
+ const pluginData = mergePluginData(node.pluginData, node.sharedPluginData)
+ if (pluginData.length > 0) nc.pluginData = pluginData
+ if (node.pluginRelaunchData.length > 0) {
+ nc.pluginRelaunchData = serializePluginRelaunchData(node.pluginRelaunchData)
+ }
+
+ const result: KiwiNodeChange[] = [nc]
+ const children = context.graph.getChildren(node.id)
+ for (let i = 0; i < children.length; i++) {
+ result.push(...context.sceneNodeToKiwi(children[i], guid, i, localIdCounter, context))
+ }
+ return result
+}
diff --git a/packages/core/src/kiwi/plugin-data.ts b/packages/core/src/kiwi/plugin-data.ts
new file mode 100644
index 000000000..34464a3bd
--- /dev/null
+++ b/packages/core/src/kiwi/plugin-data.ts
@@ -0,0 +1,35 @@
+import type {
+ PluginDataEntry,
+ PluginRelaunchDataEntry,
+ SharedPluginDataEntry
+} from '../scene-graph'
+import type { PluginData, PluginRelaunchData } from './codec'
+
+export function mergePluginData(
+ pluginData: PluginDataEntry[],
+ sharedPluginData: SharedPluginDataEntry[]
+): PluginData[] {
+ return [
+ ...pluginData.map((entry) => ({
+ pluginID: entry.pluginId,
+ key: entry.key,
+ value: entry.value
+ })),
+ ...sharedPluginData.map((entry) => ({
+ pluginID: entry.namespace,
+ key: `${entry.namespace}/${entry.key}`,
+ value: entry.value
+ }))
+ ]
+}
+
+export function serializePluginRelaunchData(
+ entries: PluginRelaunchDataEntry[]
+): PluginRelaunchData[] {
+ return entries.map((entry) => ({
+ pluginID: entry.pluginId,
+ command: entry.command,
+ message: entry.message,
+ isDeleted: entry.isDeleted
+ }))
+}
diff --git a/packages/core/src/kiwi/serialize.ts b/packages/core/src/kiwi/serialize.ts
index 0ddb04d60..01549fef0 100644
--- a/packages/core/src/kiwi/serialize.ts
+++ b/packages/core/src/kiwi/serialize.ts
@@ -5,6 +5,7 @@ import { deflateSync, inflateSync } from 'fflate'
import { getLoadedFontData, normalizeFontFamily, weightToStyle } from '../fonts'
import { encodeVectorNetworkBlob, buildStyleOverrideTable } from '../vector'
import { stringToGuid, VARIABLE_BINDING_FIELDS } from './convert'
+import { sceneNodeToKiwiWithContext, type KiwiNodeChange } from './node-export'
import type { SceneGraph, SceneNode, CharacterStyleOverride } from '../scene-graph'
import type { Color, GUID, Matrix } from '../types'
@@ -54,8 +55,6 @@ export async function buildFontDigestMap(graph: SceneGraph): Promise<Map<string,
return result
}
-type KiwiNodeChange = NodeChange & Record<string, unknown>
-
export function parseFigKiwiChunks(binary: Uint8Array): Uint8Array[] | null {
const header = new TextDecoder().decode(binary.slice(0, 8))
if (header !== 'fig-kiwi') return null
@@ -77,7 +76,7 @@ export function decompressFigKiwiData(compressed: Uint8Array): Uint8Array {
try {
return inflateSync(compressed)
} catch {
- throw new Error('Failed to decompress fig-kiwi data (try async variant for Zstd)')
+ throw new Error('Failed to decompress fig-kiwi data')
}
}
@@ -458,105 +457,28 @@ export function sceneNodeToKiwi(
fontDigestMap?: Map<string, Uint8Array>,
varIdToGuid?: Map<string, GUID>
): KiwiNodeChange[] {
- const localID = localIdCounter.value++
- const guid = { sessionID: 1, localID }
- nodeIdToGuid?.set(node.id, guid)
-
- const fillPaints = node.fills.map(fillToKiwiPaint)
- const strokePaints = node.strokes.map((s) => ({
- type: 'SOLID' as const,
- color: safeColor(s.color),
- opacity: s.opacity,
- visible: s.visible,
- blendMode: 'NORMAL' as const
- }))
-
- const nc: KiwiNodeChange = {
- guid,
- parentIndex: { guid: parentGuid, position: fractionalPosition(childIndex) },
- type: mapToFigmaType(node.type),
- name: node.name,
- visible: node.visible,
- opacity: node.opacity,
- phase: 'CREATED',
- size: { x: node.width, y: node.height },
- transform: computeExportTransform(node, graph),
- strokeWeight: node.strokes.length > 0 ? node.strokes[0].weight : 1,
- strokeAlign: node.strokes.length > 0 ? node.strokes[0].align : 'INSIDE'
- }
-
- if (node.independentStrokeWeights) {
- nc.borderStrokeWeightsIndependent = true
- nc.borderTopWeight = node.borderTopWeight
- nc.borderRightWeight = node.borderRightWeight
- nc.borderBottomWeight = node.borderBottomWeight
- nc.borderLeftWeight = node.borderLeftWeight
- }
-
- if (fillPaints.length > 0) nc.fillPaints = fillPaints
- if (strokePaints.length > 0) nc.strokePaints = strokePaints
-
- serializeCornerRadii(node, nc)
-
- if (node.effects.length > 0) {
- nc.effects = node.effects.map((e) => ({
- type: e.type === 'LAYER_BLUR' ? 'FOREGROUND_BLUR' : e.type,
- color: safeColor(e.color),
- offset: e.offset,
- radius: e.radius,
- spread: e.spread,
- visible: e.visible
- }))
- }
-
- if (node.type === 'TEXT') serializeTextProps(node, nc, graph, fontDigestMap)
-
- nc.frameMaskDisabled = !node.clipsContent
-
- if (node.horizontalConstraint !== 'MIN') nc.horizontalConstraint = node.horizontalConstraint
- if (node.verticalConstraint !== 'MIN') nc.verticalConstraint = node.verticalConstraint
-
- if (node.strokeCap !== 'NONE') nc.strokeCap = node.strokeCap
- if (node.strokeJoin !== 'MITER') nc.strokeJoin = node.strokeJoin
- if (node.strokeMiterLimit !== 28.96) nc.miterLimit = node.strokeMiterLimit
- if (node.dashPattern.length > 0) nc.dashPattern = node.dashPattern
-
- if (node.arcData) {
- nc.arcData = {
- startingAngle: node.arcData.startingAngle,
- endingAngle: node.arcData.endingAngle,
- innerRadius: node.arcData.innerRadius
- }
- }
-
- if (!node.autoRename) nc.autoRename = false
-
- serializeLayoutProps(node, nc)
- serializeGeometry(node, nc, blobs)
- serializeVariableBindings(node, nc, graph, varIdToGuid)
-
- const result: KiwiNodeChange[] = [nc]
- const children = graph.getChildren(node.id)
- for (let i = 0; i < children.length; i++) {
- result.push(
- ...sceneNodeToKiwi(
- children[i],
- guid,
- i,
- localIdCounter,
- graph,
- blobs,
- nodeIdToGuid,
- fontDigestMap,
- varIdToGuid
- )
- )
- }
-
- return result
+ return sceneNodeToKiwiWithContext(node, parentGuid, childIndex, localIdCounter, {
+ graph,
+ blobs,
+ nodeIdToGuid,
+ fontDigestMap,
+ varIdToGuid,
+ fractionalPosition,
+ mapToFigmaType,
+ fillToKiwiPaint,
+ safeColor,
+ computeExportTransform,
+ serializeCornerRadii,
+ serializeTextProps,
+ serializeLayoutProps,
+ serializeGeometry,
+ serializeVariableBindings,
+ sceneNodeToKiwi: sceneNodeToKiwiWithContext
+ })
}
const IDENTITY_TRANSFORM = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+const DEFAULT_STROKE_WEIGHT = 1
export function makeDocumentNodeChange(guid: GUID): NodeChange & Record<string, unknown> {
return {
@@ -567,7 +489,7 @@ export function makeDocumentNodeChange(guid: GUID): NodeChange & Record<string,
opacity: 1,
phase: 'CREATED',
transform: { ...IDENTITY_TRANSFORM },
- strokeWeight: 1,
+ strokeWeight: DEFAULT_STROKE_WEIGHT,
strokeAlign: 'CENTER',
strokeJoin: 'MITER',
documentColorProfile: 'SRGB'
@@ -590,7 +512,7 @@ export function makeCanvasNodeChange(
opacity: 1,
phase: 'CREATED',
transform: { ...IDENTITY_TRANSFORM },
- strokeWeight: 1,
+ strokeWeight: DEFAULT_STROKE_WEIGHT,
strokeAlign: 'CENTER',
strokeJoin: 'MITER',
...extra
diff --git a/packages/core/src/okhcl.ts b/packages/core/src/okhcl.ts
new file mode 100644
index 000000000..6b6b271ca
--- /dev/null
+++ b/packages/core/src/okhcl.ts
@@ -0,0 +1,158 @@
+import { converter } from 'culori'
+
+import { normalizeColor } from './color'
+import { copyFill, copyStroke } from './copy'
+
+import type { SceneNode } from './scene-graph'
+import type { Color } from './types'
+
+export interface OkHCLColor {
+ h: number
+ c: number
+ l: number
+ a?: number
+}
+
+export interface OkHCLPayload {
+ version: 1
+ kind: 'fill' | 'stroke'
+ index: number
+ color: OkHCLColor
+}
+
+const toRgb = converter('rgb')
+const OKHCL_PLUGIN_KEY = 'okhcl'
+
+function clampUnit(value: number): number {
+ if (value < 0) return 0
+ if (value > 1) return 1
+ return value
+}
+
+function normalizeHue(value: number): number {
+ const hue = value % 360
+ return hue < 0 ? hue + 360 : hue
+}
+
+export function okhclToRGBA(color: OkHCLColor): Color {
+ const rgb = toRgb({
+ mode: 'oklch',
+ l: clampUnit(color.l),
+ c: Math.max(0, color.c),
+ h: normalizeHue(color.h),
+ alpha: color.a ?? 1
+ })
+ return normalizeColor({
+ r: rgb.r,
+ g: rgb.g,
+ b: rgb.b,
+ a: rgb.alpha ?? color.a ?? 1
+ })
+}
+
+export function serializeOkHCLPayload(payload: OkHCLPayload): string {
+ return JSON.stringify(payload)
+}
+
+export function parseOkHCLPayload(value: string): OkHCLPayload | null {
+ try {
+ const parsed = JSON.parse(value) as Partial<OkHCLPayload>
+ if (parsed.version !== 1) return null
+ if (parsed.kind !== 'fill' && parsed.kind !== 'stroke') return null
+ if (typeof parsed.index !== 'number') return null
+ if (!parsed.color) return null
+ const color = parsed.color as Partial<OkHCLColor>
+ if (typeof color.h !== 'number' || typeof color.c !== 'number' || typeof color.l !== 'number') {
+ return null
+ }
+ return {
+ version: 1,
+ kind: parsed.kind,
+ index: parsed.index,
+ color: {
+ h: color.h,
+ c: color.c,
+ l: color.l,
+ a: typeof color.a === 'number' ? color.a : undefined
+ }
+ }
+ } catch {
+ return null
+ }
+}
+
+function createOkHCLPayload(kind: 'fill' | 'stroke', index: number, color: OkHCLColor): OkHCLPayload {
+ return {
+ version: 1,
+ kind,
+ index,
+ color: {
+ h: normalizeHue(color.h),
+ c: Math.max(0, color.c),
+ l: clampUnit(color.l),
+ a: color.a ?? 1
+ }
+ }
+}
+
+function filterOkHCLPayloads(entries: string[], kind: 'fill' | 'stroke', index: number): string[] {
+ return entries.filter((entry) => {
+ const payload = parseOkHCLPayload(entry)
+ return !payload || payload.kind !== kind || payload.index !== index
+ })
+}
+
+export function setNodeFillOkHCL(node: SceneNode, index: number, color: OkHCLColor): Partial<SceneNode> {
+ const fills = node.fills.map(copyFill)
+ if (index < 0 || index >= fills.length) throw new Error(`Fill ${index} not found`)
+ const fill = fills[index]
+ const rgba = okhclToRGBA(color)
+ fills[index] = {
+ ...fill,
+ color: rgba,
+ opacity: rgba.a
+ }
+
+ const payloads = filterOkHCLPayloads(node.pluginData.map((entry) => entry.value), 'fill', index)
+ payloads.push(serializeOkHCLPayload(createOkHCLPayload('fill', index, color)))
+
+ return {
+ fills,
+ pluginData: payloads.map((value) => ({ pluginId: 'open-pencil', key: OKHCL_PLUGIN_KEY, value }))
+ }
+}
+
+export function setNodeStrokeOkHCL(node: SceneNode, index: number, color: OkHCLColor): Partial<SceneNode> {
+ const strokes = node.strokes.map(copyStroke)
+ if (index < 0 || index >= strokes.length) throw new Error(`Stroke ${index} not found`)
+ const stroke = strokes[index]
+ const rgba = okhclToRGBA(color)
+ strokes[index] = {
+ ...stroke,
+ color: rgba,
+ opacity: rgba.a
+ }
+
+ const payloads = filterOkHCLPayloads(node.pluginData.map((entry) => entry.value), 'stroke', index)
+ payloads.push(serializeOkHCLPayload(createOkHCLPayload('stroke', index, color)))
+
+ return {
+ strokes,
+ pluginData: payloads.map((value) => ({ pluginId: 'open-pencil', key: OKHCL_PLUGIN_KEY, value }))
+ }
+}
+
+export function getNodeOkHCLPayloads(node: SceneNode): OkHCLPayload[] {
+ return node.pluginData
+ .filter((entry) => entry.pluginId === 'open-pencil' && entry.key === OKHCL_PLUGIN_KEY)
+ .map((entry) => parseOkHCLPayload(entry.value))
+ .filter((payload): payload is OkHCLPayload => payload !== null)
+}
+
+export function getFillOkHCL(node: SceneNode, index: number): OkHCLPayload | null {
+ return getNodeOkHCLPayloads(node).find((payload) => payload.kind === 'fill' && payload.index === index) ?? null
+}
+
+export function getStrokeOkHCL(node: SceneNode, index: number): OkHCLPayload | null {
+ return getNodeOkHCLPayloads(node).find((payload) => payload.kind === 'stroke' && payload.index === index) ?? null
+}
diff --git a/packages/core/src/scene-graph.ts b/packages/core/src/scene-graph.ts
index f9a9d1cfd..7d858f8a3 100644
--- a/packages/core/src/scene-graph.ts
+++ b/packages/core/src/scene-graph.ts
@@ -220,6 +220,25 @@ export type LayoutCounterAlign = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELIN
export type LayoutAlignSelf = 'AUTO' | 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'
export type LayoutWrap = 'NO_WRAP' | 'WRAP'
+export interface PluginDataEntry {
+ pluginId: string
+ key: string
+ value: string
+}
+
+export interface SharedPluginDataEntry {
+ namespace: string
+ key: string
+ value: string
+}
+
+export interface PluginRelaunchDataEntry {
+ pluginId: string
+ command: string
+ message: string
+ isDeleted: boolean
+}
+
export interface SceneNode {
id: string
type: NodeType
@@ -335,6 +354,10 @@ export interface SceneNode {
boundVariables: Record<string, string>
+ pluginData: PluginDataEntry[]
+ sharedPluginData: SharedPluginDataEntry[]
+ pluginRelaunchData: PluginRelaunchDataEntry[]
+
internalOnly: boolean
flipX: boolean
@@ -471,6 +494,9 @@ function createDefaultNode(type: NodeType, overrides: Partial<SceneNode> = {}):
componentId: null,
overrides: {},
boundVariables: {},
+ pluginData: [],
+ sharedPluginData: [],
+ pluginRelaunchData: [],
internalOnly: false,
flipX: false,
flipY: false,
diff --git a/tests/engine/okhcl.test.ts b/tests/engine/okhcl.test.ts
new file mode 100644
index 000000000..9d3e277ed
--- /dev/null
+++ b/tests/engine/okhcl.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ exportFigFile,
+ FigmaAPI,
+ getFillOkHCL,
+ getStrokeOkHCL,
+ initCodec,
+ okhclToRGBA,
+ parseFigFile,
+ SceneGraph
+} from '@open-pencil/core'
+
+describe('OkHCL metadata', () => {
+ test('applies rgba rendering color while preserving fill metadata', () => {
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const frame = api.createFrame()
+ frame.fills = [{ type: 'SOLID', visible: true, opacity: 1, color: { r: 0, g: 0, b: 0, a: 1 } }]
+
+ frame.setFillOkHCL({ h: 240, c: 0.12, l: 0.7, a: 0.8 })
+
+ expect(frame.fills[0]?.color).toEqual(okhclToRGBA({ h: 240, c: 0.12, l: 0.7, a: 0.8 }))
+ expect(frame.getFillOkHCL()).toMatchObject({
+ version: 1,
+ kind: 'fill',
+ index: 0,
+ color: { h: 240, c: 0.12, l: 0.7, a: 0.8 }
+ })
+ })
+
+ test('applies rgba rendering color while preserving stroke metadata', () => {
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const frame = api.createFrame()
+ frame.strokes = [{ color: { r: 0, g: 0, b: 0, a: 1 }, weight: 1, opacity: 1, visible: true, align: 'INSIDE' }]
+
+ frame.setStrokeOkHCL({ h: 20, c: 0.08, l: 0.6 })
+
+ expect(frame.strokes[0]?.color).toEqual(okhclToRGBA({ h: 20, c: 0.08, l: 0.6 }))
+ expect(frame.getStrokeOkHCL()).toMatchObject({
+ version: 1,
+ kind: 'stroke',
+ index: 0,
+ color: { h: 20, c: 0.08, l: 0.6, a: 1 }
+ })
+ })
+
+ test('roundtrips okhcl metadata through fig export/import', async () => {
+ await initCodec()
+
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const frame = api.createFrame()
+ frame.name = 'OKHCL frame'
+ frame.fills = [{ type: 'SOLID', visible: true, opacity: 1, color: { r: 0, g: 0, b: 0, a: 1 } }]
+ frame.strokes = [{ color: { r: 0, g: 0, b: 0, a: 1 }, weight: 1, opacity: 1, visible: true, align: 'INSIDE' }]
+ frame.setFillOkHCL({ h: 210, c: 0.1, l: 0.65 })
+ frame.setStrokeOkHCL({ h: 320, c: 0.09, l: 0.55, a: 0.9 })
+
+ const bytes = await exportFigFile(graph)
+ const parsed = await parseFigFile(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength))
+ const parsedFrame = [...parsed.getAllNodes()].find((node) => node.name === 'OKHCL frame')
+
+ expect(parsedFrame).toBeDefined()
+ expect(getFillOkHCL(parsedFrame!, 0)).toMatchObject({
+ kind: 'fill',
+ color: { h: 210, c: 0.1, l: 0.65, a: 1 }
+ })
+ expect(getStrokeOkHCL(parsedFrame!, 0)).toMatchObject({
+ kind: 'stroke',
+ color: { h: 320, c: 0.09, l: 0.55, a: 0.9 }
+ })
+ })
+})
diff --git a/tests/engine/plugin-data.test.ts b/tests/engine/plugin-data.test.ts
new file mode 100644
index 000000000..2e303370d
--- /dev/null
+++ b/tests/engine/plugin-data.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, test } from 'bun:test'
+
+import { exportFigFile, FigmaAPI, SceneGraph, initCodec, parseFigFile } from '@open-pencil/core'
+
+describe('plugin data', () => {
+ test('figma proxy supports private and shared plugin data methods', () => {
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const frame = api.createFrame()
+
+ frame.setPluginData('okhcl', '{"l":0.7}')
+ frame.setPluginData('empty', 'temp')
+ frame.setPluginData('empty', '')
+
+ frame.setSharedPluginData('tokens', 'accent', '{"h":240}')
+ frame.setSharedPluginData('tokens', 'remove-me', 'x')
+ frame.setSharedPluginData('tokens', 'remove-me', '')
+
+ expect(frame.getPluginData('okhcl')).toBe('{"l":0.7}')
+ expect(frame.getPluginData('missing')).toBe('')
+ expect(frame.getPluginDataKeys()).toEqual(['okhcl'])
+
+ expect(frame.getSharedPluginData('tokens', 'accent')).toBe('{"h":240}')
+ expect(frame.getSharedPluginData('tokens', 'missing')).toBe('')
+ expect(frame.getSharedPluginDataKeys('tokens')).toEqual(['accent'])
+ })
+
+ test('roundtrips private and shared plugin data through fig export/import', async () => {
+ await initCodec()
+
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const frame = api.createFrame()
+ frame.name = 'Plugin data frame'
+ frame.setPluginData('okhcl', '{"l":0.7,"c":0.12,"h":240}')
+ frame.setSharedPluginData('tokens', 'accent', '{"ref":"brand/500"}')
+
+ const bytes = await exportFigFile(graph)
+ const parsed = await parseFigFile(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength))
+ const parsedFrame = [...parsed.getAllNodes()].find((node) => node.name === 'Plugin data frame')
+
+ expect(parsedFrame).toBeDefined()
+ expect(parsedFrame?.pluginData).toContainEqual({
+ pluginId: 'open-pencil',
+ key: 'okhcl',
+ value: '{"l":0.7,"c":0.12,"h":240}'
+ })
+ expect(parsedFrame?.sharedPluginData).toContainEqual({
+ namespace: 'tokens',
+ key: 'accent',
+ value: '{"ref":"brand/500"}'
+ })
+ })
+
+ test('preserves plugin relaunch data from imported fig files', async () => {
+ await initCodec()
+ const bytes = new Uint8Array(await Bun.file('./tests/fixtures/material3.fig').arrayBuffer())
+ const graph = await parseFigFile(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength))
+ const nodeWithRelaunch = [...graph.getAllNodes()].find((node) => node.pluginRelaunchData.length > 0)
+
+ expect(nodeWithRelaunch).toBeDefined()
+ expect(nodeWithRelaunch?.pluginRelaunchData[0]).toMatchObject({
+ pluginId: expect.any(String),
+ command: expect.any(String),
+ message: expect.any(String),
+ isDeleted: expect.any(Boolean)
+ })
+ })
+})