Skip to content

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

refactor: register generated frames, design JSX elements, and enum props (#1243)

Danila Poyarkov14a2738dcb30
diff --git a/changes/1243/changed.md b/changes/1243/changed.md
new file mode 100644
index 000000000..b664648e2
--- /dev/null
+++ b/changes/1243/changed.md
@@ -0,0 +1 @@
+- Design JSX warns about an unknown enum value, such as `blendMode="sparkle"` or `mask="sparkle"`, and renders the rest instead of ignoring the value silently or failing.
diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.ts
index 6a45bca1b..3af35c064 100644
--- a/packages/core/src/canvas/overlays/selection.ts
+++ b/packages/core/src/canvas/overlays/selection.ts
@@ -1,6 +1,6 @@
import type { Canvas } from 'canvaskit-wasm'
-import { slotPropertyId } from '@open-pencil/scene-graph'
+import { layerRotates, slotPropertyId } from '@open-pencil/scene-graph'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { computeBounds, rotatedCorners } from '@open-pencil/scene-graph/geometry'
import Matrix from '@open-pencil/scene-graph/matrix'
@@ -355,8 +355,8 @@ export function drawNodeSelection(
y1,
x2,
y2,
- // FigJam keeps sticky notes upright.
- node.type === 'STICKY'
+ // A generated frame such as a sticky note may stay upright.
+ !layerRotates(node)
? null
: rotationHandleLayout(node, createSceneGeometry(graph, preview), r.zoom, {
x: x1,
diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.ts
index f12885886..15940ea14 100644
--- a/packages/core/src/editor/structure.ts
+++ b/packages/core/src/editor/structure.ts
@@ -1,6 +1,11 @@
import { pick } from 'es-toolkit'
-import { createsComponentCycle, TRANSFORM_FIELDS, type SceneNode } from '@open-pencil/scene-graph'
+import {
+ createsComponentCycle,
+ generatedFrameKind,
+ TRANSFORM_FIELDS,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'
import { fitEnclosingGroupsWithUndo } from '#core/editor/structure/group/bounds'
@@ -173,8 +178,9 @@ export function createStructureActions(ctx: EditorContext) {
const previous = { name: node.name, autoRename: node.autoRename }
const next = name.trim() || defaultNodeName(node.type)
if (next === previous.name) return
- // A sticky note named by hand no longer takes its name from its text, as in FigJam.
- const renamed = { name: next, autoRename: node.type === 'STICKY' ? false : node.autoRename }
+ // A layer named by its text, as a sticky note is, keeps the name it is given, as in FigJam.
+ const namedByText = generatedFrameKind(node)?.namedByText ?? false
+ const renamed = { name: next, autoRename: namedByText ? false : node.autoRename }
ctx.graph.updateNode(id, renamed)
ctx.undo.push({
label: 'Rename',
diff --git a/packages/core/src/figma-api/accessors/sticky.ts b/packages/core/src/figma-api/accessors/sticky.ts
index 81e56039c..81fee50a3 100644
--- a/packages/core/src/figma-api/accessors/sticky.ts
+++ b/packages/core/src/figma-api/accessors/sticky.ts
@@ -1,4 +1,5 @@
import {
+ generatedFrameText,
isGeneratedFrame,
isWideSticky,
stickyScale,
@@ -34,16 +35,20 @@ function wrap(target: ProxyThis, internals: NodeProxyInternals, id: string): Fig
return (target[internals.api] as NodeProxyHost).wrapNode(id)
}
-/** `StickyNode`'s members: its body as `text`, its author line, and its wide shape. */
+/**
+ * `StickyNode`'s members: its author line and wide shape, and `text`, which every generated frame
+ * answers with the text it edits in place.
+ */
export function installStickyNodeProxyAccessors(
prototype: object,
internals: NodeProxyInternals
): void {
Object.defineProperties(prototype, {
+ // A generated frame's text, such as a sticky note's body, as Figma's `text`.
text: {
get(this: ProxyThis): FigmaNodeProxy | undefined {
- const layers = sublayers(this, internals)
- return layers ? wrap(this, internals, layers.body.id) : undefined
+ const text = generatedFrameText(graph(this, internals), raw(this, internals))
+ return text ? wrap(this, internals, text.id) : undefined
}
},
authorName: {
diff --git a/packages/design-jsx/AGENTS.md b/packages/design-jsx/AGENTS.md
index c6d833d58..fabe50d3d 100644
--- a/packages/design-jsx/AGENTS.md
+++ b/packages/design-jsx/AGENTS.md
@@ -7,6 +7,8 @@ Rules:
- Depend only on `@open-pencil/scene-graph` and `@open-pencil/emit`. Engine work the renderer needs — icon lookup, SVG path conversion, vector node creation, and layout — comes in through `DesignJSXServices` (`src/services.ts`). Core binds them in `packages/core/src/design-jsx/renderer.ts` and exports the bound `renderJSX` and `renderTree` from `@open-pencil/core/design-jsx`.
- The `layout` service receives the rendered roots. A caller that moves them into place afterwards passes `deferLayout` and lays them out once (`packages/core/src/design-jsx/placement.ts`).
- `src/streaming/` parses JSX as it streams in and projects the static subset into trees without evaluating expressions; Core's `packages/core/src/design-jsx/preview/` stages and records those trees on the canvas.
+- Each element is one entry in `DESIGN_JSX_ELEMENTS` (`src/elements.ts`): its name, the layer type it builds and the types it writes, and its props. The runtime bindings, renderer, export tag, unsupported-prop warnings, schema, and reference read it; do not add a parallel tag or type map (`tests/elements.test.ts`).
+- An enum prop is one `jsxEnum` table in `src/enums.ts` that both reads and writes it, and an unknown value warns instead of falling back silently (`tests/enums.test.ts`).
- JSX export (`src/export/`) collects typed props in `props.ts` and prints them with `@open-pencil/emit`'s JSX builders; never build JSX from string fragments.
- `src/reference/authoring.md` is the source of the shared authoring reference. Run `bun run generate:authoring-reference` after changing it or the schema; never edit the generated copies.
- Tests that need icons, layout, or the bound renderer live in `packages/core/tests/design-jsx` (existing ones still in `tests/engine/render/jsx`); tests of trees, parsing, schema, and export live in `packages/design-jsx/tests`.
diff --git a/packages/design-jsx/src/elements.ts b/packages/design-jsx/src/elements.ts
new file mode 100644
index 000000000..ace8762d3
--- /dev/null
+++ b/packages/design-jsx/src/elements.ts
@@ -0,0 +1,237 @@
+import { difference } from 'es-toolkit/array'
+
+import type { NodeType } from '@open-pencil/scene-graph'
+
+import { REKA_ELEMENTS, rekaRole } from './behaviours'
+import {
+ DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,
+ DESIGN_JSX_SPAN_PROPERTY_NAMES,
+ DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,
+ DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES
+} from './schema'
+
+/**
+ * One design JSX element: what JSX names it, what it makes, the props it takes, and which layers
+ * export writes as it. The renderer, the export, the prop checks, the streaming preview, and the
+ * authoring reference all read this list rather than keeping their own.
+ */
+export type DesignJSXElementDefinition = {
+ name: string
+ /** The type its tree nodes carry, such as `frame`. */
+ runtimeType: string
+ description: string
+ /** The layer a plain element makes; an element rendered its own way, such as `Icon`, has none. */
+ nodeType?: NodeType
+ /** The props it takes; every layer prop when left out. */
+ props?: readonly string[]
+ /** The layers export writes as this element. */
+ writes?: readonly NodeType[]
+}
+
+function rekaDescription(namespace: string, part: string): string {
+ const role = rekaRole(`${namespace}.${part}`)
+ if (role?.role === 'root')
+ return `A main component that behaves as Reka UI's ${namespace} ${part}.`
+ if (role?.role === 'input') return `The text layer of a ${namespace}'s text property.`
+ return `The ${namespace} ${part}, drawn by a slot of its component.`
+}
+
+/** A Reka UI element as the element list describes it. */
+function rekaElementDefinitions(): DesignJSXElementDefinition[] {
+ return Object.entries(REKA_ELEMENTS).flatMap(([namespace, parts]) =>
+ Object.keys(parts).map((part) => {
+ const type = `${namespace}.${part}`
+ return { name: type, runtimeType: type, description: rekaDescription(namespace, part) }
+ })
+ )
+}
+
+export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [
+ {
+ name: 'Frame',
+ runtimeType: 'frame',
+ description: 'A frame or auto-layout container.',
+ nodeType: 'FRAME',
+ // A set and an instance read back as frames: JSX cannot name what they come from.
+ writes: ['FRAME', 'COMPONENT_SET', 'INSTANCE']
+ },
+ {
+ name: 'Text',
+ runtimeType: 'text',
+ description: 'A text layer.',
+ nodeType: 'TEXT',
+ writes: ['TEXT']
+ },
+ {
+ name: 'Span',
+ runtimeType: 'text-span',
+ description: 'Characters inside a Text, styled apart from the rest.',
+ props: ['key', ...DESIGN_JSX_SPAN_PROPERTY_NAMES]
+ },
+ {
+ name: 'Paragraph',
+ runtimeType: 'text-paragraph',
+ description: 'One paragraph of a Text, plain or a list item.',
+ props: ['key', ...DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES]
+ },
+ {
+ name: 'Rectangle',
+ runtimeType: 'rectangle',
+ description: 'A rectangle layer.',
+ nodeType: 'RECTANGLE',
+ writes: ['RECTANGLE', 'ROUNDED_RECTANGLE']
+ },
+ {
+ name: 'Ellipse',
+ runtimeType: 'ellipse',
+ description: 'An ellipse layer.',
+ nodeType: 'ELLIPSE',
+ writes: ['ELLIPSE']
+ },
+ {
+ name: 'Line',
+ runtimeType: 'line',
+ description: 'A line layer.',
+ nodeType: 'LINE',
+ writes: ['LINE']
+ },
+ {
+ name: 'Star',
+ runtimeType: 'star',
+ description: 'A star layer.',
+ nodeType: 'STAR',
+ writes: ['STAR']
+ },
+ {
+ name: 'Polygon',
+ runtimeType: 'polygon',
+ description: 'A polygon layer.',
+ nodeType: 'POLYGON',
+ writes: ['POLYGON']
+ },
+ {
+ name: 'Vector',
+ runtimeType: 'vector',
+ description: 'A vector layer.',
+ nodeType: 'VECTOR',
+ writes: ['VECTOR']
+ },
+ {
+ name: 'Group',
+ runtimeType: 'group',
+ description: 'A group of layers.',
+ nodeType: 'GROUP',
+ writes: ['GROUP']
+ },
+ {
+ name: 'Section',
+ runtimeType: 'section',
+ description: 'A canvas section.',
+ nodeType: 'SECTION',
+ writes: ['SECTION']
+ },
+ {
+ name: 'Component',
+ runtimeType: 'component',
+ description: 'A reusable component.',
+ nodeType: 'COMPONENT',
+ writes: ['COMPONENT']
+ },
+ {
+ name: 'ComponentSet',
+ runtimeType: 'component-set',
+ description: 'A component variant set.',
+ nodeType: 'COMPONENT_SET'
+ },
+ { name: 'Instance', runtimeType: 'instance', description: 'An instance of a component.' },
+ { name: 'View', runtimeType: 'frame', description: 'An alias for Frame.', nodeType: 'FRAME' },
+ {
+ name: 'Rect',
+ runtimeType: 'rectangle',
+ description: 'An alias for Rectangle.',
+ nodeType: 'RECTANGLE'
+ },
+ { name: 'Icon', runtimeType: 'icon', description: 'An Iconify icon.' },
+ ...rekaElementDefinitions()
+]
+
+/** Props an inline `<svg>` takes besides a layer's: its markup's view box and body. */
+const SVG_PROPERTY_NAMES = ['viewBox', 'body'] as const
+
+/**
+ * Lowercase tags JSX also accepts, as HTML names them, with the layer each makes; they are
+ * not written back.
+ */
+const INTRINSIC_ELEMENTS: Readonly<Record<string, NodeType | null>> = {
+ componentset: 'COMPONENT_SET',
+ div: 'FRAME',
+ main: 'FRAME',
+ header: 'FRAME',
+ footer: 'FRAME',
+ nav: 'FRAME',
+ article: 'FRAME',
+ aside: 'FRAME',
+ span: 'TEXT',
+ p: 'TEXT',
+ h1: 'TEXT',
+ h2: 'TEXT',
+ h3: 'TEXT',
+ h4: 'TEXT',
+ h5: 'TEXT',
+ h6: 'TEXT',
+ // Inline SVG markup, which the artwork service draws.
+ svg: null
+}
+
+/** Paragraph props describe a paragraph of a text, never a layer, unless a text sets them too. */
+const LAYER_PROPS: ReadonlySet<string> = new Set<string>(
+ difference(
+ DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,
+ difference(DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES, DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES)
+ )
+)
+
+const BY_RUNTIME_TYPE = new Map(
+ DESIGN_JSX_ELEMENTS.map((element): [string, DesignJSXElementDefinition] => [
+ element.runtimeType,
+ element
+ ]).reverse()
+)
+
+const PROPS_BY_RUNTIME_TYPE = new Map<string, ReadonlySet<string>>([
+ ['svg', new Set([...LAYER_PROPS, ...SVG_PROPERTY_NAMES])],
+ ...DESIGN_JSX_ELEMENTS.flatMap((element): [string, ReadonlySet<string>][] =>
+ element.props ? [[element.runtimeType, new Set(element.props)]] : []
+ )
+])
+
+const TAG_BY_NODE_TYPE = new Map(
+ DESIGN_JSX_ELEMENTS.flatMap((element) =>
+ (element.writes ?? []).map((type): [NodeType, string] => [type, element.name])
+ )
+)
+
+/** The layer an element of `runtimeType` makes, for an element without its own renderer. */
+export function elementNodeType(runtimeType: string): NodeType | undefined {
+ return BY_RUNTIME_TYPE.get(runtimeType)?.nodeType ?? INTRINSIC_ELEMENTS[runtimeType] ?? undefined
+}
+
+/** The props an element of `runtimeType` takes. */
+export function elementProps(runtimeType: string): ReadonlySet<string> {
+ return PROPS_BY_RUNTIME_TYPE.get(runtimeType) ?? LAYER_PROPS
+}
+
+/** The element export writes a layer of `type` as, if any. */
+export function elementTag(type: NodeType): string | undefined {
+ return TAG_BY_NODE_TYPE.get(type)
+}
+
+/**
+ * `const Frame = 'frame', …`: the element names a JSX string's code can use, bound to their
+ * runtime types. Reka UI elements, named `Switch.Root`, are bound by their namespaces.
+ */
+export function elementBindings(): string {
+ return DESIGN_JSX_ELEMENTS.filter((element) => !element.name.includes('.'))
+ .map((element) => `const ${element.name} = '${element.runtimeType}'`)
+ .join('\n')
+}
diff --git a/packages/design-jsx/src/enums.ts b/packages/design-jsx/src/enums.ts
new file mode 100644
index 000000000..7273bb9c3
--- /dev/null
+++ b/packages/design-jsx/src/enums.ts
@@ -0,0 +1,129 @@
+import type {
+ BlendMode,
+ ConstraintType,
+ MaskType,
+ SceneNode,
+ Stroke,
+ StrokeCap,
+ StrokeJoin,
+ TextAutoResize,
+ TextCase,
+ TextDecoration,
+ TextDecorationStyle,
+ TextDirection
+} from '@open-pencil/scene-graph'
+
+/**
+ * A Figma enum as design JSX spells it. Reading and writing come from one table, so whatever the
+ * export writes reads back, and a value the table does not know is reported instead of reaching
+ * the document.
+ */
+export interface JSXEnum<T extends string> {
+ /** The value a spelling names, read case-insensitively, or undefined for none. */
+ parse(value: unknown): T | undefined
+ /** How the export spells a value. */
+ print(value: T): string
+ /** Every spelling it reads, aliases included. */
+ readonly names: readonly string[]
+}
+
+/**
+ * `spellings` names every value of the enum, which the type checks, and is what the export writes;
+ * `aliases` are further spellings it only reads.
+ */
+export function jsxEnum<T extends string>(
+ spellings: Readonly<Record<T, string>>,
+ aliases: Readonly<Record<string, T>> = {}
+): JSXEnum<T> {
+ const entries = Object.entries(spellings) as [T, string][]
+ const byName = new Map<string, T>([
+ ...entries.map(([value, name]): [string, T] => [name, value]),
+ ...Object.entries(aliases)
+ ])
+ return {
+ parse: (value) => (typeof value === 'string' ? byName.get(value.toLowerCase()) : undefined),
+ print: (value) => spellings[value],
+ names: [...byName.keys()]
+ }
+}
+
+/** An enum spelled by each value's lowercase name, as most of design JSX's enums are. */
+function lowercaseEnum<T extends string>(
+ values: readonly T[],
+ aliases: Readonly<Record<string, T>> = {}
+): JSXEnum<T> {
+ const spellings = Object.fromEntries(values.map((value) => [value, value.toLowerCase()]))
+ return jsxEnum(spellings as Record<T, string>, aliases)
+}
+
+export const STROKE_CAP = lowercaseEnum<StrokeCap>([
+ 'NONE',
+ 'ROUND',
+ 'SQUARE',
+ 'ARROW_LINES',
+ 'ARROW_EQUILATERAL'
+])
+export const STROKE_JOIN = lowercaseEnum<StrokeJoin>(['MITER', 'BEVEL', 'ROUND'])
+export const STROKE_ALIGN = lowercaseEnum<Stroke['align']>(['INSIDE', 'CENTER', 'OUTSIDE'])
+export const CONSTRAINT = lowercaseEnum<ConstraintType>([
+ 'MIN',
+ 'CENTER',
+ 'MAX',
+ 'STRETCH',
+ 'SCALE'
+])
+export const MASK_TYPE = lowercaseEnum<MaskType>(['ALPHA', 'LUMINANCE', 'VECTOR'])
+export const BLEND_MODE = lowercaseEnum<BlendMode>([
+ 'NORMAL',
+ 'DARKEN',
+ 'MULTIPLY',
+ 'COLOR_BURN',
+ 'LIGHTEN',
+ 'SCREEN',
+ 'COLOR_DODGE',
+ 'OVERLAY',
+ 'SOFT_LIGHT',
+ 'HARD_LIGHT',
+ 'DIFFERENCE',
+ 'EXCLUSION',
+ 'HUE',
+ 'SATURATION',
+ 'COLOR',
+ 'LUMINOSITY',
+ 'PASS_THROUGH'
+])
+export const TEXT_ALIGN = lowercaseEnum<SceneNode['textAlignHorizontal']>(
+ ['LEFT', 'CENTER', 'RIGHT', 'JUSTIFIED'],
+ { left_align: 'LEFT', center_align: 'CENTER', right_align: 'RIGHT' }
+)
+export const TEXT_ALIGN_VERTICAL = lowercaseEnum<SceneNode['textAlignVertical']>([
+ 'TOP',
+ 'CENTER',
+ 'BOTTOM'
+])
+export const TEXT_AUTO_RESIZE = jsxEnum<TextAutoResize>({
+ NONE: 'none',
+ WIDTH_AND_HEIGHT: 'width',
+ HEIGHT: 'height',
+ TRUNCATE: 'truncate'
+})
+export const TEXT_DIRECTION = lowercaseEnum<TextDirection>(['AUTO', 'LTR', 'RTL'])
+export const TEXT_DECORATION = lowercaseEnum<TextDecoration>(['NONE', 'UNDERLINE', 'STRIKETHROUGH'])
+export const TEXT_DECORATION_STYLE = lowercaseEnum<TextDecorationStyle>(['SOLID', 'DOTTED', 'WAVY'])
+export const TEXT_CASE = lowercaseEnum<TextCase>(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'])
+
+/** The props whose values are one of an enum's spellings, for checking what JSX passes. */
+export const ENUM_PROPS: Readonly<Partial<Record<string, JSXEnum<string>>>> = {
+ strokeCap: STROKE_CAP,
+ strokeJoin: STROKE_JOIN,
+ strokeAlign: STROKE_ALIGN,
+ mask: MASK_TYPE,
+ blendMode: BLEND_MODE,
+ textAlign: TEXT_ALIGN,
+ textAlignVertical: TEXT_ALIGN_VERTICAL,
+ textAutoResize: TEXT_AUTO_RESIZE,
+ dir: TEXT_DIRECTION,
+ textDecoration: TEXT_DECORATION,
+ textDecorationStyle: TEXT_DECORATION_STYLE,
+ textCase: TEXT_CASE
+}
diff --git a/packages/design-jsx/src/export/decoration.ts b/packages/design-jsx/src/export/decoration.ts
index 93e01bd49..28de3a021 100644
--- a/packages/design-jsx/src/export/decoration.ts
+++ b/packages/design-jsx/src/export/decoration.ts
@@ -1,5 +1,6 @@
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+import { TEXT_DECORATION_STYLE } from '../enums'
import { AUTO, CURRENT_COLOR } from '../overrides/text'
import { paintPropValue } from './paint'
import type { JSXProp } from './value'
@@ -24,7 +25,7 @@ export function collectDecorationProps(
): void {
const { textDecorationFills: fills } = style
if (style.textDecorationStyle !== undefined)
- props.push(['textDecorationStyle', style.textDecorationStyle.toLowerCase()])
+ props.push(['textDecorationStyle', TEXT_DECORATION_STYLE.print(style.textDecorationStyle)])
if (fills) {
const fill = fills.at(0)
props.push(['textDecorationColor', fill ? paintPropValue(fill, node) : CURRENT_COLOR])
diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.ts
index 8927bf650..9326bd106 100644
--- a/packages/design-jsx/src/export/index.ts
+++ b/packages/design-jsx/src/export/index.ts
@@ -3,9 +3,10 @@ import { compact } from 'es-toolkit/array'
import { jsx, type SyntaxNode } from '@open-pencil/emit'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { elementTag } from '../elements'
import { rekaExport, type RekaExport } from './behaviours'
import { iconProps } from './icons'
-import { collectProps, NODE_TYPE_TO_TAG } from './props'
+import { collectProps } from './props'
import { textChildren } from './text'
import { propAttribute } from './value'
@@ -65,7 +66,7 @@ function nodeToJSX(
layerIds?.push(node.id)
return [jsx.element('Icon', icon.map(propAttribute), [], depth)]
}
- const tag = reka.tags.get(node.id) ?? NODE_TYPE_TO_TAG[node.type]
+ const tag = reka.tags.get(node.id) ?? elementTag(node.type)
if (!tag) return []
layerIds?.push(node.id)
const ownProps = reka.props.get(node.id)
@@ -101,7 +102,7 @@ export function sceneNodeAttributes(
graph: SceneGraph
): JSXAttributeSource[] | null {
const node = graph.getNode(nodeId)
- if (!node || !NODE_TYPE_TO_TAG[node.type]) return null
+ if (!node || !elementTag(node.type)) return null
const props = collectProps(node, graph)
if (node.type === 'TEXT') props.push(['text', node.text])
return props.map((prop) => ({
@@ -137,7 +138,7 @@ function textContent(node: SceneNode, tag: string): string | null {
export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXElement | null {
const node = graph.getNode(nodeId)
- const tag = node && NODE_TYPE_TO_TAG[node.type]
+ const tag = node && elementTag(node.type)
const printed = sceneNodeAttributes(nodeId, graph)
if (!node || !tag || !printed) return null
// A text layer's content is written as its children, not as the `text` attribute.
@@ -150,7 +151,7 @@ export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXEl
if (isText) return { tag, attributes, text: textContent(node, tag), childIds: [] }
const childIds = graph
.getChildren(node.id)
- .filter((child) => NODE_TYPE_TO_TAG[child.type])
+ .filter((child) => elementTag(child.type))
.map((child) => child.id)
return { tag, attributes, text: null, childIds }
}
diff --git a/packages/design-jsx/src/export/paint.ts b/packages/design-jsx/src/export/paint.ts
index 9550e5f4e..27f822d4a 100644
--- a/packages/design-jsx/src/export/paint.ts
+++ b/packages/design-jsx/src/export/paint.ts
@@ -8,6 +8,7 @@ import {
} from '@open-pencil/scene-graph'
import { isIdentityGradientTransform } from '@open-pencil/scene-graph/gradient'
+import { STROKE_ALIGN, STROKE_CAP, STROKE_JOIN } from '../enums'
import { formatColor, formatShadow } from './helpers'
import { helperCall, plainValue, type HelperCall, type JSXProp, type JSXValue } from './value'
@@ -126,10 +127,10 @@ function strokeValue(stroke: Stroke): StrokeValue {
color: formatColor(stroke.color, stroke.color.a),
opacity: stroke.opacity === stroke.color.a ? undefined : stroke.opacity,
weight: stroke.weight === 1 ? undefined : stroke.weight,
- align: stroke.align === 'INSIDE' ? undefined : stroke.align.toLowerCase(),
+ align: stroke.align === 'INSIDE' ? undefined : STROKE_ALIGN.print(stroke.align),
dash: stroke.dashPattern && stroke.dashPattern.length > 0 ? [...stroke.dashPattern] : undefined,
- cap: stroke.cap?.toLowerCase(),
- join: stroke.join?.toLowerCase(),
+ cap: stroke.cap && STROKE_CAP.print(stroke.cap),
+ join: stroke.join && STROKE_JOIN.print(stroke.join),
visible: stroke.visible ? undefined : false
}
}
@@ -151,8 +152,8 @@ const DEFAULT_STROKE_JOIN = 'MITER'
*/
function fitsStrokeShorthand(node: SceneNode, stroke: StrokeValue): boolean {
if (stroke.visible !== undefined || stroke.opacity !== undefined) return false
- const nodeCap = node.strokeCap.toLowerCase()
- const nodeJoin = node.strokeJoin.toLowerCase()
+ const nodeCap = STROKE_CAP.print(node.strokeCap)
+ const nodeJoin = STROKE_JOIN.print(node.strokeJoin)
return (stroke.cap ?? nodeCap) === nodeCap && (stroke.join ?? nodeJoin) === nodeJoin
}
@@ -169,9 +170,10 @@ export function collectStrokeProps(node: SceneNode, props: JSXProp[]): void {
} else if (strokes.length > 0) {
props.push(['strokes', strokes])
}
- if (node.strokeCap !== DEFAULT_STROKE_CAP) props.push(['strokeCap', node.strokeCap.toLowerCase()])
+ if (node.strokeCap !== DEFAULT_STROKE_CAP)
+ props.push(['strokeCap', STROKE_CAP.print(node.strokeCap)])
if (node.strokeJoin !== DEFAULT_STROKE_JOIN) {
- props.push(['strokeJoin', node.strokeJoin.toLowerCase()])
+ props.push(['strokeJoin', STROKE_JOIN.print(node.strokeJoin)])
}
if (node.dashPattern.length > 0) props.push(['dashPattern', [...node.dashPattern]])
if (node.independentStrokeWeights) {
diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.ts
index 6082570b6..1cb433b9a 100644
--- a/packages/design-jsx/src/export/props.ts
+++ b/packages/design-jsx/src/export/props.ts
@@ -4,12 +4,12 @@ import {
createDefaultNode,
layoutSizing,
type SceneGraph,
- type SceneNode,
- type NodeType
+ type SceneNode
} from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY } from '@open-pencil/scene-graph/constants'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
+import { BLEND_MODE, TEXT_ALIGN, TEXT_ALIGN_VERTICAL, TEXT_CASE, TEXT_DECORATION } from '../enums'
import { collectDecorationProps } from './decoration'
import {
collectCornerRadii,
@@ -25,22 +25,6 @@ import type { JSXProp } from './value'
export type { JSXProp } from './value'
/** The element that represents each node type; other types are not exported. */
-export const NODE_TYPE_TO_TAG: Partial<Record<NodeType, string>> = {
- FRAME: 'Frame',
- RECTANGLE: 'Rectangle',
- ROUNDED_RECTANGLE: 'Rectangle',
- ELLIPSE: 'Ellipse',
- TEXT: 'Text',
- LINE: 'Line',
- STAR: 'Star',
- POLYGON: 'Polygon',
- VECTOR: 'Vector',
- GROUP: 'Group',
- SECTION: 'Section',
- COMPONENT: 'Component',
- COMPONENT_SET: 'Frame',
- INSTANCE: 'Frame'
-}
function collectGridSizingProps(node: SceneNode, props: JSXProp[]): void {
props.push(['grid', true])
@@ -141,7 +125,7 @@ function collectAppearanceProps(node: SceneNode, props: JSXProp[]): void {
if (node.opacity < 1) props.push(['opacity', Math.round(node.opacity * 100) / 100])
if (node.rotation !== 0) props.push(['rotate', Math.round(node.rotation * 100) / 100])
if (node.blendMode !== 'PASS_THROUGH' && node.blendMode !== 'NORMAL') {
- props.push(['blendMode', node.blendMode.toLowerCase()])
+ props.push(['blendMode', BLEND_MODE.print(node.blendMode)])
}
if (node.clipsContent) props.push(['overflow', 'hidden'])
collectEffectProps(node, props)
@@ -249,21 +233,21 @@ function collectTextNodeProps(node: SceneNode, props: JSXProp[]): void {
if (direction === 'RTL') props.push(['dir', 'rtl'])
if (node.italic) props.push(['italic', true])
if (node.textAlignHorizontal !== 'LEFT') {
- props.push(['textAlign', node.textAlignHorizontal.toLowerCase()])
+ props.push(['textAlign', TEXT_ALIGN.print(node.textAlignHorizontal)])
}
if (node.textAlignVertical !== 'TOP') {
- props.push(['textAlignVertical', node.textAlignVertical.toLowerCase()])
+ props.push(['textAlignVertical', TEXT_ALIGN_VERTICAL.print(node.textAlignVertical)])
}
if (node.lineHeight != null) props.push(['lineHeight', node.lineHeight])
if (node.letterSpacing !== 0) props.push(['letterSpacing', node.letterSpacing])
if (node.textDecoration !== 'NONE')
- props.push(['textDecoration', node.textDecoration.toLowerCase()])
+ props.push(['textDecoration', TEXT_DECORATION.print(node.textDecoration)])
collectDecorationProps(
omitBy(pick(node, DECORATION_FIELDS), (value, key) => isEqual(value, TEXT_DEFAULTS[key])),
node,
props
)
- if (node.textCase !== 'ORIGINAL') props.push(['textCase', node.textCase.toLowerCase()])
+ if (node.textCase !== 'ORIGINAL') props.push(['textCase', TEXT_CASE.print(node.textCase)])
if (node.maxLines != null) props.push(['maxLines', node.maxLines])
if (node.textTruncation === 'ENDING' && node.maxLines == null) props.push(['truncate', true])
if (node.paragraphSpacing !== 0) props.push(['paragraphSpacing', node.paragraphSpacing])
diff --git a/packages/design-jsx/src/export/state.ts b/packages/design-jsx/src/export/state.ts
index b2028bbed..f346085fa 100644
--- a/packages/design-jsx/src/export/state.ts
+++ b/packages/design-jsx/src/export/state.ts
@@ -1,5 +1,6 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { CONSTRAINT, MASK_TYPE } from '../enums'
import type { getNodeContext } from './helpers'
import { helperCall, type JSXProp, type JSXValue } from './value'
@@ -19,7 +20,10 @@ function collectConstraintProps(
if (!horizontal && !vertical) return
props.push([
'constraints',
- { horizontal: horizontal?.toLowerCase(), vertical: vertical?.toLowerCase() }
+ {
+ horizontal: horizontal && CONSTRAINT.print(horizontal),
+ vertical: vertical && CONSTRAINT.print(vertical)
+ }
])
}
@@ -58,7 +62,7 @@ export function collectStateProps(
): void {
collectConstraintProps(node, ctx, props)
collectSizeLimitProps(node, props)
- if (node.isMask) props.push(['mask', node.maskType.toLowerCase()])
+ if (node.isMask) props.push(['mask', MASK_TYPE.print(node.maskType)])
if (!node.visible) props.push(['visible', false])
if (node.locked) props.push(['locked', true])
collectBindingProps(node, graph, props)
diff --git a/packages/design-jsx/src/export/text.ts b/packages/design-jsx/src/export/text.ts
index 3a720f388..6691bfe7a 100644
--- a/packages/design-jsx/src/export/text.ts
+++ b/packages/design-jsx/src/export/text.ts
@@ -12,6 +12,7 @@ import {
type TextParagraphStyle
} from '@open-pencil/scene-graph'
+import { TEXT_CASE, TEXT_DECORATION } from '../enums'
import { AUTO } from '../overrides/text'
import { SPAN_STYLE_FIELDS, type SpanStyle } from '../text-content'
import { collectDecorationProps } from './decoration'
@@ -55,9 +56,9 @@ function spanProps(style: SpanStyle, node: SceneNode): JSXProp[] {
if (style.lineHeight !== undefined) props.push(['lineHeight', style.lineHeight ?? AUTO])
if (style.letterSpacing !== undefined) props.push(['letterSpacing', style.letterSpacing])
if (style.textDecoration !== undefined)
- props.push(['textDecoration', style.textDecoration.toLowerCase()])
+ props.push(['textDecoration', TEXT_DECORATION.print(style.textDecoration)])
collectDecorationProps(style, node, props)
- if (style.textCase !== undefined) props.push(['textCase', style.textCase.toLowerCase()])
+ if (style.textCase !== undefined) props.push(['textCase', TEXT_CASE.print(style.textCase)])
if (style.hyperlink) props.push(['href', style.hyperlink.value])
return props
}
diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.ts
index 8016bd2ec..8d4200e65 100644
--- a/packages/design-jsx/src/index.ts
+++ b/packages/design-jsx/src/index.ts
@@ -88,8 +88,8 @@ export { createElement } from './mini-react'
export { buildComponent, createDesignJSXRenderer, type DesignJSXRenderer } from './render'
export type { ArtworkPlacement, DesignJSXServices, SVGSource } from './services'
export type { RenderOptions } from './types'
+export { DESIGN_JSX_ELEMENTS, type DesignJSXElementDefinition } from './elements'
export {
- DESIGN_JSX_ELEMENTS,
DESIGN_JSX_HELPERS,
DESIGN_JSX_PROPERTIES,
DESIGN_JSX_SUPPORTED_PROPERTIES,
@@ -102,7 +102,6 @@ export {
type DesignJSXStyleKey,
designJSXProp,
designJSXPropertyNames,
- type DesignJSXElementDefinition,
type DesignJSXHelperDefinition,
type DesignJSXPropertyDefinition
} from './schema'
diff --git a/packages/design-jsx/src/overrides/state.ts b/packages/design-jsx/src/overrides/state.ts
index 1317f552d..22521dd04 100644
--- a/packages/design-jsx/src/overrides/state.ts
+++ b/packages/design-jsx/src/overrides/state.ts
@@ -1,21 +1,9 @@
-import type { ConstraintType, SceneNode } from '@open-pencil/scene-graph'
-
-const CONSTRAINT_VALUES: Record<string, ConstraintType> = {
- min: 'MIN',
- center: 'CENTER',
- max: 'MAX',
- stretch: 'STRETCH',
- scale: 'SCALE'
-}
+import { CONSTRAINT, MASK_TYPE } from '#design-jsx/enums'
-const MASK_TYPES: Record<string, SceneNode['maskType']> = {
- alpha: 'ALPHA',
- luminance: 'LUMINANCE',
- vector: 'VECTOR'
-}
+import type { ConstraintType, SceneNode } from '@open-pencil/scene-graph'
function constraintValue(value: unknown): ConstraintType | undefined {
- return typeof value === 'string' ? CONSTRAINT_VALUES[value.toLowerCase()] : undefined
+ return CONSTRAINT.parse(value)
}
/** The `constraints` prop, shaped like Figma's `constraints` object. */
@@ -58,8 +46,10 @@ export function applyStateOverrides(props: Record<string, unknown>, o: Partial<S
if (minHeight !== undefined) o.minHeight = minHeight
if (maxHeight !== undefined) o.maxHeight = maxHeight
- if (props.mask) {
+ // `mask` alone masks by alpha; an unknown mask type leaves the layer as it was.
+ const maskType = props.mask === true ? 'ALPHA' : MASK_TYPE.parse(props.mask)
+ if (maskType) {
o.isMask = true
- o.maskType = (typeof props.mask === 'string' && MASK_TYPES[props.mask]) || 'ALPHA'
+ o.maskType = maskType
}
}
diff --git a/packages/design-jsx/src/overrides/strokes.ts b/packages/design-jsx/src/overrides/strokes.ts
index dd081b789..bff0085c0 100644
--- a/packages/design-jsx/src/overrides/strokes.ts
+++ b/packages/design-jsx/src/overrides/strokes.ts
@@ -1,29 +1,10 @@
+import { STROKE_ALIGN, STROKE_CAP, STROKE_JOIN } from '#design-jsx/enums'
import { designJSXProp } from '#design-jsx/schema'
-import type { SceneNode, Stroke, StrokeCap, StrokeJoin } from '@open-pencil/scene-graph'
+import type { SceneNode, Stroke } from '@open-pencil/scene-graph'
import { parseColor } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-const ALIGN_VALUES: Record<string, Stroke['align']> = {
- inside: 'INSIDE',
- center: 'CENTER',
- outside: 'OUTSIDE'
-}
-
-const CAP_VALUES: Record<string, StrokeCap> = {
- none: 'NONE',
- round: 'ROUND',
- square: 'SQUARE',
- arrow_lines: 'ARROW_LINES',
- arrow_equilateral: 'ARROW_EQUILATERAL'
-}
-
-const JOIN_VALUES: Record<string, StrokeJoin> = {
- miter: 'MITER',
- bevel: 'BEVEL',
- round: 'ROUND'
-}
-
/** One entry of the `strokes` prop; enums are lowercase, as `blendMode` is. */
export interface StrokeValue {
color: string | Color
@@ -46,10 +27,6 @@ function isStrokeValue(value: unknown): value is StrokeValue {
return typeof value.color === 'string' || isColor(value.color)
}
-function enumValue<T>(values: Record<string, T>, value: unknown): T | undefined {
- return typeof value === 'string' ? values[value.toLowerCase()] : undefined
-}
-
function dashValue(value: unknown): number[] | undefined {
if (!Array.isArray(value)) return undefined
const dash = value.filter((item): item is number => typeof item === 'number')
@@ -64,13 +41,13 @@ function toStroke(value: StrokeValue): Stroke {
opacity: typeof value.opacity === 'number' ? value.opacity : color.a,
visible: value.visible ?? true,
weight: value.weight ?? 1,
- align: enumValue(ALIGN_VALUES, value.align) ?? 'INSIDE'
+ align: STROKE_ALIGN.parse(value.align) ?? 'INSIDE'
}
const dash = dashValue(value.dash)
if (dash) stroke.dashPattern = dash
- const cap = enumValue(CAP_VALUES, value.cap)
+ const cap = STROKE_CAP.parse(value.cap)
if (cap) stroke.cap = cap
- const join = enumValue(JOIN_VALUES, value.join)
+ const join = STROKE_JOIN.parse(value.join)
if (join) stroke.join = join
return stroke
}
@@ -104,9 +81,9 @@ function applyStrokeWeights(value: unknown, o: Partial<SceneNode>): void {
export function applyStrokeOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
applyStrokeWeights(props.strokeWeights, o)
// Node-level cap and join, which strokes without their own use.
- const nodeCap = enumValue(CAP_VALUES, props.strokeCap)
+ const nodeCap = STROKE_CAP.parse(props.strokeCap)
if (nodeCap) o.strokeCap = nodeCap
- const nodeJoin = enumValue(JOIN_VALUES, props.strokeJoin)
+ const nodeJoin = STROKE_JOIN.parse(props.strokeJoin)
if (nodeJoin) o.strokeJoin = nodeJoin
// The node's own dash pattern, separate from the stroke-local dash `strokeDash` sets.
const nodeDash = dashValue(props.dashPattern)
diff --git a/packages/design-jsx/src/overrides/text.ts b/packages/design-jsx/src/overrides/text.ts
index 78ae519ee..918fd0c1e 100644
--- a/packages/design-jsx/src/overrides/text.ts
+++ b/packages/design-jsx/src/overrides/text.ts
@@ -1,8 +1,9 @@
import * as v from 'valibot'
-import type { Fill, SceneNode, TextDecorationStyle } from '@open-pencil/scene-graph'
+import type { Fill, SceneNode } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { TEXT_DECORATION_STYLE } from '../enums'
import { parseScriptInput } from '../validation'
import { fillFromValue, isFillValue } from './fills'
@@ -14,14 +15,9 @@ export const CURRENT_COLOR = 'currentColor'
const Length = v.pipe(v.number(), v.finite())
const AutoLength = v.union([Length, v.literal(AUTO)])
-const DECORATION_STYLES = {
- solid: 'SOLID',
- dotted: 'DOTTED',
- wavy: 'WAVY'
-} as const satisfies Record<string, TextDecorationStyle>
-
const TextProps = v.object({
- textDecorationStyle: v.optional(v.picklist(['solid', 'dotted', 'wavy'])),
+ // Read by TEXT_DECORATION_STYLE, so an unknown style warns rather than failing the render.
+ textDecorationStyle: v.optional(v.string()),
textDecorationColor: v.optional(
v.custom<string | Color | Fill>(isFillValue, 'Expected a colour or a paint')
),
@@ -45,8 +41,8 @@ export function applyTextDetailOverrides(
): void {
const parsed = parseScriptInput('Invalid <Text> props', TextProps, props)
const color = parsed.textDecorationColor
- if (parsed.textDecorationStyle !== undefined)
- o.textDecorationStyle = DECORATION_STYLES[parsed.textDecorationStyle]
+ const style = TEXT_DECORATION_STYLE.parse(parsed.textDecorationStyle)
+ if (style) o.textDecorationStyle = style
if (color !== undefined) {
o.textDecorationFills =
typeof color === 'string' && color.toLowerCase() === CURRENT_COLOR.toLowerCase()
diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/props-overrides.ts
index 89fc70e70..b8e7d1ffb 100644
--- a/packages/design-jsx/src/props-overrides.ts
+++ b/packages/design-jsx/src/props-overrides.ts
@@ -13,6 +13,15 @@ import { colorToFill } from '@open-pencil/scene-graph/color'
import { parseCSSGridTracks, parseCSSNumber } from '@open-pencil/scene-graph/css'
import type { Color, JSONObject } from '@open-pencil/scene-graph/primitives'
+import {
+ BLEND_MODE,
+ TEXT_ALIGN,
+ TEXT_ALIGN_VERTICAL,
+ TEXT_AUTO_RESIZE,
+ TEXT_CASE,
+ TEXT_DECORATION,
+ TEXT_DIRECTION
+} from './enums'
import { applyEffectOverrides } from './overrides/effects'
import { fillFromValue, isColor, isFillValue } from './overrides/fills'
import { applyStateOverrides } from './overrides/state'
@@ -27,42 +36,9 @@ const WEIGHT_MAP: Record<string, number> = {
bold: 700
}
-const TEXT_ALIGN_MAP: Record<string, SceneNode['textAlignHorizontal']> = {
- left: 'LEFT',
- center: 'CENTER',
- right: 'RIGHT',
- justified: 'JUSTIFIED'
-}
-
-const TEXT_VERTICAL_ALIGN_MAP: Record<string, SceneNode['textAlignVertical']> = {
- top: 'TOP',
- center: 'CENTER',
- bottom: 'BOTTOM'
-}
-
-const TEXT_ALIGN_ALIAS_MAP: Record<string, SceneNode['textAlignHorizontal']> = {
- ...TEXT_ALIGN_MAP,
- left_align: 'LEFT',
- center_align: 'CENTER',
- right_align: 'RIGHT'
-}
-
-const TEXT_AUTO_RESIZE_MAP: Record<string, SceneNode['textAutoResize']> = {
- none: 'NONE',
- width: 'WIDTH_AND_HEIGHT',
- height: 'HEIGHT',
- truncate: 'TRUNCATE'
-}
-
-const DIRECTION_MAP: Record<string, SceneNode['textDirection']> = {
- auto: 'AUTO',
- ltr: 'LTR',
- rtl: 'RTL'
-}
-
function parseDirection(value: unknown): SceneNode['textDirection'] | undefined {
if (typeof value !== 'string') return undefined
- return DIRECTION_MAP[value.toLowerCase()] ?? 'AUTO'
+ return TEXT_DIRECTION.parse(value) ?? 'AUTO'
}
function numberFromPx(value: unknown): number | undefined {
@@ -176,9 +152,8 @@ function applyVisualOverrides(props: Record<string, unknown>, o: Partial<SceneNo
if (props.opacity !== undefined) o.opacity = props.opacity as number
applyTransformOverrides(props, o)
- if (props.blendMode !== undefined) {
- o.blendMode = (props.blendMode as string).toUpperCase() as SceneNode['blendMode']
- }
+ const blendMode = BLEND_MODE.parse(props.blendMode)
+ if (blendMode) o.blendMode = blendMode
if (props.overflow === 'hidden') o.clipsContent = true
}
@@ -377,11 +352,11 @@ function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<Scen
if (props.lineHeight === AUTO) o.lineHeight = null
else if (props.lineHeight !== undefined) o.lineHeight = props.lineHeight as number
if (props.letterSpacing !== undefined) o.letterSpacing = props.letterSpacing as number
- if (props.textDecoration !== undefined)
- o.textDecoration = (props.textDecoration as string).toUpperCase() as SceneNode['textDecoration']
+ const textDecoration = TEXT_DECORATION.parse(props.textDecoration)
+ if (textDecoration) o.textDecoration = textDecoration
applyTextDetailOverrides(props, o)
- if (props.textCase !== undefined)
- o.textCase = (props.textCase as string).toUpperCase() as SceneNode['textCase']
+ const textCase = TEXT_CASE.parse(props.textCase)
+ if (textCase) o.textCase = textCase
if (props.maxLines !== undefined) {
o.maxLines = props.maxLines as number
o.textTruncation = 'ENDING'
@@ -396,12 +371,12 @@ function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<Scen
function applyTextAlignmentOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
const textAlign = designJSXProp(props, 'textAlign')
if (typeof textAlign === 'string') {
- o.textAlignHorizontal = TEXT_ALIGN_ALIAS_MAP[textAlign.toLowerCase()] ?? 'LEFT'
+ o.textAlignHorizontal = TEXT_ALIGN.parse(textAlign) ?? 'LEFT'
}
const textAlignVertical = designJSXProp(props, 'textAlignVertical')
if (typeof textAlignVertical === 'string') {
- o.textAlignVertical = TEXT_VERTICAL_ALIGN_MAP[textAlignVertical.toLowerCase()] ?? 'TOP'
+ o.textAlignVertical = TEXT_ALIGN_VERTICAL.parse(textAlignVertical) ?? 'TOP'
}
}
@@ -420,7 +395,7 @@ function applyTextAutoResize(
// default SceneNode size and blows up every HUG container. layout.ts has a
// fallback estimator, but changing this logic can silently break all JSX rendering.
if (props.textAutoResize) {
- o.textAutoResize = TEXT_AUTO_RESIZE_MAP[props.textAutoResize as string] ?? 'NONE'
+ o.textAutoResize = TEXT_AUTO_RESIZE.parse(props.textAutoResize) ?? 'NONE'
} else if (hasExplicitWidth || (isInsideAutoLayout && fillsParent)) {
o.textAutoResize = 'HEIGHT'
} else {
diff --git a/packages/design-jsx/src/reference.ts b/packages/design-jsx/src/reference.ts
index 1e203541d..deeb9fd03 100644
--- a/packages/design-jsx/src/reference.ts
+++ b/packages/design-jsx/src/reference.ts
@@ -1,10 +1,7 @@
+import { DESIGN_JSX_ELEMENTS } from './elements'
import authoring from './reference/authoring.md?raw'
import { AUTHORING_EXAMPLES } from './reference/examples'
-import {
- DESIGN_JSX_ELEMENTS,
- DESIGN_JSX_HELPERS,
- DESIGN_JSX_SUPPORTED_PROPERTY_NAMES
-} from './schema'
+import { DESIGN_JSX_HELPERS, DESIGN_JSX_SUPPORTED_PROPERTY_NAMES } from './schema'
export { AUTHORING_EXAMPLES, type AuthoringExample } from './reference/examples'
diff --git a/packages/design-jsx/src/render.ts b/packages/design-jsx/src/render.ts
index 2f7f4b6fe..120d7d542 100644
--- a/packages/design-jsx/src/render.ts
+++ b/packages/design-jsx/src/render.ts
@@ -1,20 +1,16 @@
-import { difference, uniq } from 'es-toolkit/array'
+import { uniq } from 'es-toolkit/array'
import { transform } from 'sucrase'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { REKA_ELEMENTS } from './behaviours'
+import { elementBindings, elementProps } from './elements'
+import { ENUM_PROPS } from './enums'
import { designJSXHelpers } from './helpers'
import * as React from './mini-react'
import { renderRoots, renderTree, componentPropNames, type RenderResult } from './renderer'
-import {
- DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,
- DESIGN_JSX_SPAN_PROPERTY_NAMES,
- DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,
- DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES
-} from './schema'
import type { DesignJSXServices } from './services'
-import { PARAGRAPH, SPAN, TEXT_CONTENT_NAMES } from './text-content'
+import { TEXT_CONTENT_NAMES } from './text-content'
import { isTreeNode, resolveToTree, type TreeNode } from './tree'
import type { RenderOptions as RenderJSXOptions } from './types'
@@ -38,36 +34,25 @@ function unsupportedPropWarnings(graph: SceneGraph, tree: TreeNode): string[] {
return warnings
}
-// Paragraph props describe a paragraph of a text, never a layer, unless a text sets them too.
-const LAYER_PROPS = new Set<string>(
- difference(
- DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,
- difference(DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES, DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES)
- )
-)
-const SVG_ROOT_PROPS = new Set([...LAYER_PROPS, 'viewBox', 'body'])
-const PARAGRAPH_PROPS = new Set<string>(['key', ...DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES])
-const SPAN_PROPS = new Set<string>(['key', ...DESIGN_JSX_SPAN_PROPERTY_NAMES])
-
-function supportedProps(type: string): ReadonlySet<string> {
- if (type === 'svg') return SVG_ROOT_PROPS
- if (type === SPAN) return SPAN_PROPS
- if (type === PARAGRAPH) return PARAGRAPH_PROPS
- return LAYER_PROPS
-}
-
function collectUnsupportedPropWarnings(
graph: SceneGraph,
tree: TreeNode,
warnings: string[]
): void {
- const supported = supportedProps(tree.type)
+ const supported = elementProps(tree.type)
// An instance sets its component's properties by name, such as `State="On"` or `Title="Hi"`.
const properties = componentPropNames(graph, tree.props)
- for (const key of Object.keys(tree.props)) {
+ const element = TEXT_CONTENT_NAMES[tree.type] ?? tree.type
+ for (const [key, value] of Object.entries(tree.props)) {
if (!supported.has(key) && !properties.includes(key)) {
- const element = TEXT_CONTENT_NAMES[tree.type] ?? tree.type
warnings.push(`Unsupported prop "${key}" on <${element}> is ignored.`)
+ continue
+ }
+ const values = ENUM_PROPS[key]
+ if (values && typeof value === 'string' && values.parse(value) === undefined) {
+ warnings.push(
+ `Unknown ${key} "${value}" on <${element}> is ignored; expected ${values.names.join(', ')}.`
+ )
}
}
@@ -89,12 +74,7 @@ export function buildComponent(jsxString: string, warnings: string[] = []): Reac
const aliases = `
const __h = React.createElement
const __frag = ''
- const Frame = 'frame', Text = 'text', Rectangle = 'rectangle', Ellipse = 'ellipse'
- const Line = 'line', Star = 'star', Polygon = 'polygon', Vector = 'vector'
- const Group = 'group', Section = 'section', View = 'frame', Rect = 'rectangle'
- const Component = 'component', ComponentSet = 'component-set', Instance = 'instance'
- const Span = 'text-span', Paragraph = 'text-paragraph'
- const Icon = 'icon'
+ ${elementBindings()}
const svg = 'svg'
${REKA_ALIASES}
const dropShadow = __helpers.dropShadow
diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.ts
index 19249d91c..6495a37f4 100644
--- a/packages/design-jsx/src/renderer.ts
+++ b/packages/design-jsx/src/renderer.ts
@@ -16,6 +16,7 @@ import {
componentPropertyScope,
inferComponentSetProperties
} from './component-properties'
+import { elementNodeType } from './elements'
import { applySizeOverrides, propsToOverrides } from './props-overrides'
import { prepareScalarBindings } from './scalar-bindings'
import type { DesignJSXServices } from './services'
@@ -25,39 +26,6 @@ import type { TreeNode } from './tree'
import type { RenderOptions } from './types'
import { isVariable, resolveVariableId, type DesignVariable } from './vars'
-const TYPE_MAP: Partial<Record<string, NodeType>> = {
- frame: 'FRAME',
- view: 'FRAME',
- rectangle: 'RECTANGLE',
- rect: 'RECTANGLE',
- ellipse: 'ELLIPSE',
- text: 'TEXT',
- line: 'LINE',
- star: 'STAR',
- polygon: 'POLYGON',
- vector: 'VECTOR',
- group: 'GROUP',
- section: 'SECTION',
- component: 'COMPONENT',
- 'component-set': 'COMPONENT_SET',
- componentset: 'COMPONENT_SET',
- div: 'FRAME',
- main: 'FRAME',
- header: 'FRAME',
- footer: 'FRAME',
- nav: 'FRAME',
- article: 'FRAME',
- aside: 'FRAME',
- span: 'TEXT',
- p: 'TEXT',
- h1: 'TEXT',
- h2: 'TEXT',
- h3: 'TEXT',
- h4: 'TEXT',
- h5: 'TEXT',
- h6: 'TEXT'
-}
-
export interface RenderResult {
id: string
name: string
@@ -503,6 +471,27 @@ async function renderNode<Artwork>(
return node
}
+/**
+ * The elements rendered their own way rather than as the layer their definition names, or null
+ * for any other element.
+ */
+function renderOwnElement<Artwork>(
+ services: DesignJSXServices<Artwork>,
+ graph: SceneGraph,
+ tree: TreeNode,
+ parentId: string
+): Promise<SceneNode> | null {
+ switch (tree.type) {
+ case 'icon':
+ case 'svg':
+ return renderArtworkNode(services, graph, tree, parentId)
+ case 'instance':
+ return renderInstanceNode(graph, tree, parentId)
+ default:
+ return null
+ }
+}
+
async function renderNodeContent<Artwork>(
services: DesignJSXServices<Artwork>,
graph: SceneGraph,
@@ -511,9 +500,8 @@ async function renderNodeContent<Artwork>(
onNode?: RenderOptions['onNode'],
scope?: RekaScope
): Promise<SceneNode> {
- if (tree.type === 'icon' || tree.type === 'svg')
- return renderArtworkNode(services, graph, tree, parentId)
- if (tree.type === 'instance') return renderInstanceNode(graph, tree, parentId)
+ const own = renderOwnElement(services, graph, tree, parentId)
+ if (own) return own
const reka = await renderRekaNode(graph, tree, parentId, scope, {
render: (child, childParentId, childScope) =>
renderNode(services, graph, child, childParentId, onNode, childScope),
@@ -530,7 +518,7 @@ async function renderNodeContent<Artwork>(
if (isTextContent(tree))
throw new Error(`<${TEXT_CONTENT_NAMES[tree.type]}> must be inside <Text>`)
- const nodeType = TYPE_MAP[tree.type]
+ const nodeType = elementNodeType(tree.type)
if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)
const { overrides, bindings } = elementOverrides(graph, nodeType, tree, parentId)
diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.ts
index e68e8a359..2af1270cf 100644
--- a/packages/design-jsx/src/schema.ts
+++ b/packages/design-jsx/src/schema.ts
@@ -1,29 +1,3 @@
-import { REKA_ELEMENTS, rekaRole } from './behaviours'
-
-function rekaDescription(namespace: string, part: string): string {
- const role = rekaRole(`${namespace}.${part}`)
- if (role?.role === 'root')
- return `A main component that behaves as Reka UI's ${namespace} ${part}.`
- if (role?.role === 'input') return `The text layer of a ${namespace}'s text property.`
- return `The ${namespace} ${part}, drawn by a slot of its component.`
-}
-
-/** A Reka UI element as the element list describes it. */
-function rekaElementDefinitions(): DesignJSXElementDefinition[] {
- return Object.entries(REKA_ELEMENTS).flatMap(([namespace, parts]) =>
- Object.keys(parts).map((part) => {
- const type = `${namespace}.${part}`
- return { name: type, runtimeType: type, description: rekaDescription(namespace, part) }
- })
- )
-}
-
-export type DesignJSXElementDefinition = {
- name: string
- runtimeType: string
- description: string
-}
-
export type DesignJSXNamedDefinition = {
name: string
description: string
@@ -32,36 +6,6 @@ export type DesignJSXNamedDefinition = {
export type DesignJSXPropertyDefinition = DesignJSXNamedDefinition
export type DesignJSXHelperDefinition = DesignJSXNamedDefinition
-export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [
- { name: 'Frame', runtimeType: 'frame', description: 'A frame or auto-layout container.' },
- { name: 'Text', runtimeType: 'text', description: 'A text layer.' },
- {
- name: 'Span',
- runtimeType: 'text-span',
- description: 'Characters inside a Text, styled apart from the rest.'
- },
- {
- name: 'Paragraph',
- runtimeType: 'text-paragraph',
- description: 'One paragraph of a Text, plain or a list item.'
- },
- { name: 'Rectangle', runtimeType: 'rectangle', description: 'A rectangle layer.' },
- { name: 'Ellipse', runtimeType: 'ellipse', description: 'An ellipse layer.' },
- { name: 'Line', runtimeType: 'line', description: 'A line layer.' },
- { name: 'Star', runtimeType: 'star', description: 'A star layer.' },
- { name: 'Polygon', runtimeType: 'polygon', description: 'A polygon layer.' },
- { name: 'Vector', runtimeType: 'vector', description: 'A vector layer.' },
- { name: 'Group', runtimeType: 'group', description: 'A group of layers.' },
- { name: 'Section', runtimeType: 'section', description: 'A canvas section.' },
- { name: 'Component', runtimeType: 'component', description: 'A reusable component.' },
- { name: 'ComponentSet', runtimeType: 'component-set', description: 'A component variant set.' },
- { name: 'Instance', runtimeType: 'instance', description: 'An instance of a component.' },
- { name: 'View', runtimeType: 'frame', description: 'An alias for Frame.' },
- { name: 'Rect', runtimeType: 'rectangle', description: 'An alias for Rectangle.' },
- { name: 'Icon', runtimeType: 'icon', description: 'An Iconify icon.' },
- ...rekaElementDefinitions()
-]
-
/** Props only `<Paragraph>` takes; like every element, it also takes `key`. */
export const DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES = [
'list',
diff --git a/packages/design-jsx/src/streaming/projection.ts b/packages/design-jsx/src/streaming/projection.ts
index e8be7916b..905956fe8 100644
--- a/packages/design-jsx/src/streaming/projection.ts
+++ b/packages/design-jsx/src/streaming/projection.ts
@@ -1,7 +1,7 @@
import type { SyntaxNode } from '@lezer/common'
import { decodeHTML } from 'entities'
-import { DESIGN_JSX_ELEMENTS } from '../schema'
+import { DESIGN_JSX_ELEMENTS } from '../elements'
import { FRAGMENT, type TreeNode } from '../tree'
import { readLiteral } from './literals'
diff --git a/packages/design-jsx/tests/elements.test.ts b/packages/design-jsx/tests/elements.test.ts
new file mode 100644
index 000000000..225916762
--- /dev/null
+++ b/packages/design-jsx/tests/elements.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, test } from 'bun:test'
+
+import { DESIGN_JSX_ELEMENTS, elementTag } from '#design-jsx/elements'
+import { createDesignJSXRenderer } from '#design-jsx/index'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+const renderer = createDesignJSXRenderer<never>({
+ icon: () => Promise.resolve(null),
+ svg: () => null,
+ createArtwork: () => {
+ throw new Error('No artwork in these tests')
+ },
+ layout: () => {
+ // Element types do not depend on layout.
+ }
+})
+
+const LAYER_ELEMENTS = DESIGN_JSX_ELEMENTS.filter((element) => element.nodeType !== undefined)
+
+describe('design JSX elements', () => {
+ test.each(LAYER_ELEMENTS.map((element) => [element.name, element.nodeType]))(
+ '<%s /> builds a %s',
+ async (name, nodeType) => {
+ const graph = new SceneGraph()
+ const [result] = await renderer.renderJSX(graph, `<${name} />`)
+ expect(graph.getNode(result.id)?.type).toBe(nodeType)
+ expect(result.warnings ?? []).toEqual([])
+ }
+ )
+
+ test('every layer type an element writes is written by that element', () => {
+ for (const element of DESIGN_JSX_ELEMENTS) {
+ for (const type of element.writes ?? []) expect(elementTag(type)).toBe(element.name)
+ }
+ })
+})
diff --git a/packages/design-jsx/tests/enums.test.ts b/packages/design-jsx/tests/enums.test.ts
new file mode 100644
index 000000000..04268e4b6
--- /dev/null
+++ b/packages/design-jsx/tests/enums.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ BLEND_MODE,
+ CONSTRAINT,
+ MASK_TYPE,
+ STROKE_ALIGN,
+ STROKE_CAP,
+ STROKE_JOIN,
+ TEXT_ALIGN,
+ TEXT_ALIGN_VERTICAL,
+ TEXT_AUTO_RESIZE,
+ TEXT_CASE,
+ TEXT_DECORATION,
+ TEXT_DECORATION_STYLE,
+ TEXT_DIRECTION,
+ type JSXEnum
+} from '#design-jsx/enums'
+import { createDesignJSXRenderer, sceneNodeToJSX } from '#design-jsx/index'
+
+import { SceneGraph, type StrokeCap } from '@open-pencil/scene-graph'
+
+const renderer = createDesignJSXRenderer<never>({
+ icon: () => Promise.resolve(null),
+ svg: () => null,
+ createArtwork: () => {
+ throw new Error('No artwork in these tests')
+ },
+ layout: () => {
+ // These props do not depend on layout.
+ }
+})
+
+async function render(source: string) {
+ const graph = new SceneGraph()
+ const [result] = await renderer.renderJSX(graph, source)
+ const node = graph.getNode(result.id)
+ if (!node) throw new Error('Rendered layer is missing')
+ return { graph, node, warnings: result.warnings ?? [] }
+}
+
+const ENUMS: Record<string, JSXEnum<string>> = {
+ BLEND_MODE,
+ CONSTRAINT,
+ MASK_TYPE,
+ STROKE_ALIGN,
+ STROKE_CAP,
+ STROKE_JOIN,
+ TEXT_ALIGN,
+ TEXT_ALIGN_VERTICAL,
+ TEXT_AUTO_RESIZE,
+ TEXT_CASE,
+ TEXT_DECORATION,
+ TEXT_DECORATION_STYLE,
+ TEXT_DIRECTION
+}
+
+describe('design JSX enums', () => {
+ test.each(Object.entries(ENUMS))('%s reads back every spelling it writes', (_, values) => {
+ for (const name of values.names) {
+ const value = values.parse(name)
+ expect(value).toBeDefined()
+ if (value) expect(values.parse(values.print(value))).toBe(value)
+ }
+ })
+
+ test('spellings read case-insensitively and unknown ones read as nothing', () => {
+ expect(TEXT_ALIGN.parse('Center')).toBe('CENTER')
+ expect(TEXT_ALIGN.parse('left_align')).toBe('LEFT')
+ expect(TEXT_AUTO_RESIZE.parse('width')).toBe('WIDTH_AND_HEIGHT')
+ expect(BLEND_MODE.parse('sparkle')).toBeUndefined()
+ expect(BLEND_MODE.parse(3)).toBeUndefined()
+ })
+
+ const caps: StrokeCap[] = ['ROUND', 'SQUARE', 'ARROW_LINES', 'ARROW_EQUILATERAL']
+
+ test.each(caps)('a %s stroke cap survives export and render', async (cap) => {
+ const graph = new SceneGraph()
+ const page = graph.createNode('CANVAS', graph.rootId, { name: 'Page 1' })
+ const line = graph.createNode('LINE', page.id, { width: 100, strokeCap: cap })
+ const { node, warnings } = await render(sceneNodeToJSX(line.id, graph))
+ expect(warnings).toEqual([])
+ expect(node.strokeCap).toBe(cap)
+ })
+
+ test('an unknown value warns and is not applied', async () => {
+ const { node, warnings } = await render('<Frame blendMode="sparkle" />')
+ expect(node.blendMode).toBe('PASS_THROUGH')
+ expect(warnings).toHaveLength(1)
+ expect(warnings[0]).toStartWith('Unknown blendMode "sparkle" on <frame> is ignored; expected ')
+ })
+ test('an unknown mask type warns and leaves the layer unmasked', async () => {
+ const { node, warnings } = await render('<Rectangle mask="sparkle" />')
+ expect(node.isMask).toBe(false)
+ expect(warnings[0]).toStartWith('Unknown mask "sparkle" on <rectangle> is ignored')
+ expect((await render('<Rectangle mask />')).node.maskType).toBe('ALPHA')
+ })
+
+ test('a text decoration style reads in any case', async () => {
+ const { node, warnings } = await render(
+ '<Text textDecoration="underline" textDecorationStyle="WAVY">a</Text>'
+ )
+ expect(node.textDecorationStyle).toBe('WAVY')
+ expect(warnings).toEqual([])
+ })
+})
diff --git a/packages/design-jsx/tests/text-content.test.ts b/packages/design-jsx/tests/text-content.test.ts
index 126ce0d3b..40ea59fc9 100644
--- a/packages/design-jsx/tests/text-content.test.ts
+++ b/packages/design-jsx/tests/text-content.test.ts
@@ -97,10 +97,10 @@ describe('Span', () => {
expect(warnings).toEqual([])
})
- test('rejects decoration details it cannot draw', async () => {
- await expect(renderText('<Text textDecorationStyle="dashed">a</Text>')).rejects.toThrow(
- 'Invalid <Text> props'
- )
+ test('warns about a decoration style it cannot draw', async () => {
+ const { node, warnings } = await renderText('<Text textDecorationStyle="dashed">a</Text>')
+ expect(node.textDecorationStyle).toBe('SOLID')
+ expect(warnings[0]).toStartWith('Unknown textDecorationStyle "dashed" on <text> is ignored')
})
test('nests, the inner span winning', async () => {
diff --git a/packages/fig/AGENTS.md b/packages/fig/AGENTS.md
index c3c9d4f1c..1068bf3bc 100644
--- a/packages/fig/AGENTS.md
+++ b/packages/fig/AGENTS.md
@@ -5,6 +5,7 @@
- Keep Kiwi runtime changes minimal; put project policy in wrappers, not in the runtime.
- Figma clipboard envelope encoding, decoding, and bounds belong to `@open-pencil/fig/clipboard`; converting those records to a SceneGraph is `materializeFigFragment` in `packages/fig/src/document/fragment.ts`, which Core drives from `packages/core/src/clipboard/fig-import.ts`. Core prepares runtime fonts and text and owns editor placement and history; browser and Tauri adapters own system clipboard I/O. Do not add platform clipboard APIs here.
- One reader serves every `.fig` path — parse, worker, page population, session recovery, export, and paste — through the document sessions in `packages/fig/src/document/`. Read what it could not resolve with `readerDiagnostics(graph)` from `packages/core/src/kiwi/fig/session/document-state.ts`; do not add a second import path.
+- A generated frame's `.fig` record carries its sublayers as `nodeGenerationData` and their derived geometry. Each generated type registers a `GeneratedFrameCodec` that reads and writes them in `packages/fig/src/node-change/generated/codecs.ts`; the import and export dispatch through it and never test node types (`packages/fig/tests/node-change/generated/codecs.test.ts`).
- Browser `.fig` export uses fflate and `@open-pencil/fig`; Tauri uses `build_fig_file` in `desktop/`.
- Saving a document opened from a `.fig` writes only the fields its edits changed, merged into the archive's records, and copies the rest as bytes (`packages/core/src/io/formats/fig/export/patch/`, `patchFigMessage` in `packages/fig/src/record-patch/`); the full export remains for documents with no archive. A change is what the archive tracker sees outside page loads and outside `applyDerivedLayoutDuring`, which wraps layout derived from the file or its fonts; layout an edit causes counts, and the tracker keeps each edited layer as it was so the fields are found by comparing records (`packages/core/tests/io/formats/fig/export/patch/`).
- Changes to `.fig` behavior require round-trip validation in Figma. `packages/docs/development/roadmap.md` tracks raw metadata coverage and the code map for import/export mapping and schema files.
diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.ts
index 2408f59c3..5576bb78b 100644
--- a/packages/fig/src/document/materialize.ts
+++ b/packages/fig/src/document/materialize.ts
@@ -22,7 +22,7 @@ import {
type MaterializedComponentOccurrence
} from '../instance-overrides/source-children'
import { nodeChangeToProps } from '../node-change'
-import { materializeStickyContent } from '../node-change/generated/import'
+import { generatedFrameCodec } from '../node-change/generated/codecs'
import { figArchiveRecordInfo, type FigArchiveRecordInfo } from '../record-patch'
import { applyDocumentLayoutBindings } from './bindings/layout'
import { applyDocumentPaintBindings } from './bindings/paint'
@@ -330,7 +330,7 @@ function materializeReaderInto(
const node = graph.createNode(nodeType, parentId, props)
sources.set(occurrence.sourceId, node.id)
if (node.type === 'COMPONENT') componentIds.set(occurrence.sourceId, node.id)
- if (node.type === 'STICKY') materializeStickyContent(graph, node, occurrence.properties, blobs)
+ generatedFrameCodec(node.type)?.read(graph, node, occurrence.properties, blobs)
for (const child of occurrence.children) createShells(child, node.id)
}
for (const page of pages) createShells(page, graph.rootId)
diff --git a/packages/fig/src/node-change/export/generated.ts b/packages/fig/src/node-change/export/generated.ts
index 58d122e88..db84d2b01 100644
--- a/packages/fig/src/node-change/export/generated.ts
+++ b/packages/fig/src/node-change/export/generated.ts
@@ -1,113 +1,28 @@
-import { pick } from 'es-toolkit'
-
-import { stickySublayers } from '@open-pencil/scene-graph'
+import { generatedFrameKind } from '@open-pencil/scene-graph'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { generatedSlotPath, STICKY_SLOTS } from '../generated/records'
-import type { GeneratedEntry } from '../generated/records'
-import { createFillPaints } from './context'
+import { generatedFrameCodec } from '../generated/codecs'
import type { KiwiNodeChange, SceneNodeToKiwiContext } from './context'
-import { serializeText } from './text'
-
-/**
- * The fields a STICKY's own record keeps, as Figma writes it. Its colour, text and layout live in
- * its sublayers' entries, so the fields the note carries here as an auto layout frame stay out.
- */
-const STICKY_RECORD_FIELDS = [
- 'guid',
- 'parentIndex',
- 'phase',
- 'type',
- 'name',
- 'visible',
- 'opacity',
- 'blendMode',
- 'locked',
- 'size',
- 'transform',
- 'effects',
- 'autoRename',
- 'frameMaskDisabled',
- 'exportSettings',
- 'pluginData',
- 'pluginRelaunchData'
-] as const
-
-function placement(node: SceneNode): Pick<GeneratedEntry, 'size' | 'transform'> {
- return {
- size: { x: node.width, y: node.height },
- transform: { m00: 1, m01: 0, m02: node.x, m10: 0, m11: 1, m12: node.y }
- }
-}
-
-/** A text sublayer's entry, and its placement and glyphs as Figma would derive them. */
-function textSublayer(
- context: SceneNodeToKiwiContext,
- slot: number,
- node: SceneNode
-): { entry: GeneratedEntry; derived: GeneratedEntry } {
- const fields: KiwiNodeChange = {}
- serializeText(context, node, fields)
- const { derivedTextData, ...text } = fields
- const entry: GeneratedEntry = {
- ...text,
- guidPath: generatedSlotPath(slot),
- visible: node.visible,
- fillPaints: createFillPaints(context, node)
- }
- const derived: GeneratedEntry = { guidPath: generatedSlotPath(slot), ...placement(node) }
- if (derivedTextData) derived.derivedTextData = derivedTextData
- return { entry, derived }
-}
-
-/** Whether a sublayer's derived text can stand in for Figma's: shaped, unless it has no text. */
-function shaped(node: SceneNode, derived: GeneratedEntry): boolean {
- return node.text === '' || (derived.derivedTextData?.glyphs?.length ?? 0) > 0
-}
/**
- * Whether a layer is written as a generated frame: a note whose sublayers are the template's.
- * One that lost them is written as a plain frame with its children, so nothing it shows is lost.
+ * Whether a layer is written as a generated frame: one whose type has a codec and which still has
+ * its template's layers. One that lost them is written as a plain frame with its children, so
+ * nothing it shows is lost.
*/
export function writesGeneratedFrame(context: SceneNodeToKiwiContext, node: SceneNode): boolean {
- return node.type === 'STICKY' && stickySublayers(context.graph, node) !== null
+ const complete = generatedFrameKind(node)?.complete(context.graph, node) ?? false
+ return complete && generatedFrameCodec(node.type) !== undefined
}
/**
- * A generated frame's record, with its sublayers written on it as Figma stores a sticky note: what
- * each sublayer shows under `nodeGenerationData`, and the layout derived from it under
- * `derivedImmutableFrameData`. Figma draws a note from its derived data as saved and lays it out
- * afresh only without it, so the export writes that data only when it has shaped every text.
+ * A generated frame's record, with its sublayers written on it as its type's codec writes them;
+ * null for any other layer.
*/
export function generatedFrameRecord(
context: SceneNodeToKiwiContext,
node: SceneNode,
nc: KiwiNodeChange
): KiwiNodeChange | null {
- const sublayers = node.type === 'STICKY' ? stickySublayers(context.graph, node) : null
- if (!sublayers) return null
- const record: KiwiNodeChange = pick(nc, STICKY_RECORD_FIELDS)
- const fillPaints = createFillPaints(context, node)
- const background: GeneratedEntry = {
- guidPath: generatedSlotPath(STICKY_SLOTS.background),
- fillPaints,
- cornerRadius: 0
- }
- const overrides: GeneratedEntry[] = [background]
- const derived: GeneratedEntry[] = [
- { guidPath: generatedSlotPath(STICKY_SLOTS.background), ...placement({ ...node, x: 0, y: 0 }) }
- ]
- let complete = true
- for (const [slot, layer] of [
- [STICKY_SLOTS.body, sublayers.body],
- [STICKY_SLOTS.author, sublayers.author]
- ] as const) {
- const text = textSublayer(context, slot, layer)
- overrides.push(text.entry)
- derived.push(text.derived)
- complete &&= shaped(layer, text.derived)
- }
- record.nodeGenerationData = { overrides, useFineGrainedSyncing: false, diffOnlyRemovals: [] }
- if (complete) record.derivedImmutableFrameData = { overrides: derived, version: 1 }
- return record
+ if (!writesGeneratedFrame(context, node)) return null
+ return generatedFrameCodec(node.type)?.write(context, node, nc) ?? null
}
diff --git a/packages/fig/src/node-change/generated/codec.ts b/packages/fig/src/node-change/generated/codec.ts
new file mode 100644
index 000000000..c4d94a6f4
--- /dev/null
+++ b/packages/fig/src/node-change/generated/codec.ts
@@ -0,0 +1,17 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import type { KiwiNodeChange, SceneNodeToKiwiContext } from '../export/context'
+
+/**
+ * How one type of generated frame is read from and written to its `.fig` record. Its sublayers
+ * live on the frame's record as `nodeGenerationData` and `derivedImmutableFrameData` entries, so
+ * the reader builds them from it and the writer puts them back; the document reader and the
+ * exporter ask the type's codec instead of testing for the type.
+ */
+export interface GeneratedFrameCodec {
+ /** Gives a frame read from its record the sublayers the record describes. */
+ read(graph: SceneGraph, frame: SceneNode, record: NodeChange, blobs: Uint8Array[]): void
+ /** The frame's own record, with its sublayers written on it as Figma stores them. */
+ write(context: SceneNodeToKiwiContext, frame: SceneNode, nc: KiwiNodeChange): KiwiNodeChange
+}
diff --git a/packages/fig/src/node-change/generated/codecs.ts b/packages/fig/src/node-change/generated/codecs.ts
new file mode 100644
index 000000000..48bc7c1f0
--- /dev/null
+++ b/packages/fig/src/node-change/generated/codecs.ts
@@ -0,0 +1,15 @@
+import type { NodeType } from '@open-pencil/scene-graph'
+
+import type { GeneratedFrameCodec } from './codec'
+import { STICKY_CODEC } from './sticky'
+
+/** Each generated frame type's codec; a type without one is written as a plain frame. */
+const GENERATED_FRAME_CODECS: Partial<Record<NodeType, GeneratedFrameCodec>> = {
+ STICKY: STICKY_CODEC
+}
+
+export function generatedFrameCodec(type: NodeType): GeneratedFrameCodec | undefined {
+ return GENERATED_FRAME_CODECS[type]
+}
+
+export type { GeneratedFrameCodec } from './codec'
diff --git a/packages/fig/src/node-change/generated/entries.ts b/packages/fig/src/node-change/generated/entries.ts
new file mode 100644
index 000000000..efe64f170
--- /dev/null
+++ b/packages/fig/src/node-change/generated/entries.ts
@@ -0,0 +1,61 @@
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import { cloneRecord } from '../clone'
+import { createFillPaints } from '../export/context'
+import type { KiwiNodeChange, SceneNodeToKiwiContext } from '../export/context'
+import { serializeText } from '../export/text'
+import { generatedSlotPath, type GeneratedEntry } from './records'
+
+/**
+ * A sublayer as a whole record of `type`: what the user set on it, placed and shaped as Figma
+ * derived it, for the reader to turn into a layer.
+ */
+export function sublayerRecord(
+ type: string,
+ entry: GeneratedEntry | undefined,
+ derived: GeneratedEntry | undefined
+): NodeChange {
+ const { guidPath: _set, ...fields } = cloneRecord(entry ?? {})
+ const record: NodeChange = { ...fields, type }
+ if (derived?.size) record.size = cloneRecord(derived.size)
+ if (derived?.transform) record.transform = cloneRecord(derived.transform)
+ if (derived?.vectorData) record.vectorData = cloneRecord(derived.vectorData)
+ if (derived?.derivedTextData) record.derivedTextData = cloneRecord(derived.derivedTextData)
+ return record
+}
+
+/** A sublayer's size and place in its frame, as a derived entry gives them. */
+export function placement(
+ node: Pick<SceneNode, 'width' | 'height' | 'x' | 'y'>
+): Pick<GeneratedEntry, 'size' | 'transform'> {
+ return {
+ size: { x: node.width, y: node.height },
+ transform: { m00: 1, m01: 0, m02: node.x, m10: 0, m11: 1, m12: node.y }
+ }
+}
+
+/** A text sublayer's entry, and its placement and glyphs as Figma would derive them. */
+export function textSublayer(
+ context: SceneNodeToKiwiContext,
+ slot: number,
+ node: SceneNode
+): { entry: GeneratedEntry; derived: GeneratedEntry } {
+ const fields: KiwiNodeChange = {}
+ serializeText(context, node, fields)
+ const { derivedTextData, ...text } = fields
+ const entry: GeneratedEntry = {
+ ...text,
+ guidPath: generatedSlotPath(slot),
+ visible: node.visible,
+ fillPaints: createFillPaints(context, node)
+ }
+ const derived: GeneratedEntry = { guidPath: generatedSlotPath(slot), ...placement(node) }
+ if (derivedTextData) derived.derivedTextData = derivedTextData
+ return { entry, derived }
+}
+
+/** Whether a sublayer's derived text can stand in for Figma's: shaped, unless it has no text. */
+export function shaped(node: SceneNode, derived: GeneratedEntry): boolean {
+ return node.text === '' || (derived.derivedTextData?.glyphs?.length ?? 0) > 0
+}
diff --git a/packages/fig/src/node-change/generated/import.ts b/packages/fig/src/node-change/generated/import.ts
deleted file mode 100644
index 6a0701884..000000000
--- a/packages/fig/src/node-change/generated/import.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import {
- buildStickySublayers,
- STICKY_SUBLAYER_LAYOUT,
- stickyFrameFields,
- stickyScale
-} from '@open-pencil/scene-graph'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-
-import { cloneRecord } from '../clone'
-import { nodeChangeToProps } from '../convert'
-import { convertFills } from '../paint'
-import { derivedFrameEntriesOf, generationOverridesOf, STICKY_SLOTS } from './records'
-import type { GeneratedEntry } from './records'
-
-/** A sublayer as a whole TEXT record: what the user set, placed and shaped as Figma derived it. */
-function sublayerRecord(entry: GeneratedEntry | undefined, derived: GeneratedEntry | undefined) {
- const { guidPath: _set, ...fields } = cloneRecord(entry ?? {})
- const record: NodeChange = { ...fields, type: 'TEXT' }
- if (derived?.size) record.size = cloneRecord(derived.size)
- if (derived?.transform) record.transform = cloneRecord(derived.transform)
- if (derived?.derivedTextData) record.derivedTextData = cloneRecord(derived.derivedTextData)
- return record
-}
-
-function sublayerProps(
- entry: GeneratedEntry | undefined,
- derived: GeneratedEntry | undefined,
- blobs: Uint8Array[]
-): Partial<SceneNode> {
- const {
- nodeType: _type,
- name: _name,
- ...props
- } = nodeChangeToProps(sublayerRecord(entry, derived), blobs, 'occurrence')
- return { ...props, ...STICKY_SUBLAYER_LAYOUT }
-}
-
-/**
- * Gives an imported STICKY the sublayers its record describes. The note's colour is its
- * background's fill, which the note itself carries here; its layout comes from the template at
- * the scale its author line was set in.
- */
-export function materializeStickyContent(
- graph: SceneGraph,
- sticky: SceneNode,
- record: NodeChange,
- blobs: Uint8Array[]
-): void {
- const overrides = generationOverridesOf(record)
- const derived = derivedFrameEntriesOf(record)
- const { background, body, author } = STICKY_SLOTS
- const bodyProps = sublayerProps(overrides.get(body), derived.get(body), blobs)
- const authorProps = sublayerProps(overrides.get(author), derived.get(author), blobs)
- const scale = overrides.has(author) ? stickyScale({ fontSize: authorProps.fontSize ?? 0 }) : 1
- graph.updateNode(sticky.id, {
- fills: convertFills(overrides.get(background)?.fillPaints),
- ...stickyFrameFields(scale)
- })
- buildStickySublayers(graph, sticky, { scale }, { body: bodyProps, author: authorProps })
-}
diff --git a/packages/fig/src/node-change/generated/records.ts b/packages/fig/src/node-change/generated/records.ts
index 9f85f2387..97b809c6d 100644
--- a/packages/fig/src/node-change/generated/records.ts
+++ b/packages/fig/src/node-change/generated/records.ts
@@ -7,8 +7,6 @@ import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
*/
export const GENERATED_SESSION_ID = 40_000_000
-export const STICKY_SLOTS = { background: 0, body: 1, author: 2 } as const
-
export interface GeneratedEntry extends NodeChange {
guidPath?: { guids?: GUID[] }
}
diff --git a/packages/fig/src/node-change/generated/sticky.ts b/packages/fig/src/node-change/generated/sticky.ts
new file mode 100644
index 000000000..505b41542
--- /dev/null
+++ b/packages/fig/src/node-change/generated/sticky.ts
@@ -0,0 +1,129 @@
+import { pick } from 'es-toolkit'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import {
+ buildStickySublayers,
+ STICKY_SUBLAYER_LAYOUT,
+ stickyFrameFields,
+ stickyScale,
+ stickySublayers
+} from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import { nodeChangeToProps } from '../convert'
+import { createFillPaints } from '../export/context'
+import type { KiwiNodeChange, SceneNodeToKiwiContext } from '../export/context'
+import { convertFills } from '../paint'
+import type { GeneratedFrameCodec } from './codec'
+import { placement, shaped, sublayerRecord, textSublayer } from './entries'
+import {
+ derivedFrameEntriesOf,
+ generatedSlotPath,
+ generationOverridesOf,
+ type GeneratedEntry
+} from './records'
+
+export const STICKY_SLOTS = { background: 0, body: 1, author: 2 } as const
+
+/**
+ * The fields a STICKY's own record keeps, as Figma writes it. Its colour, text and layout live in
+ * its sublayers' entries, so the fields the note carries here as an auto layout frame stay out.
+ */
+const STICKY_RECORD_FIELDS = [
+ 'guid',
+ 'parentIndex',
+ 'phase',
+ 'type',
+ 'name',
+ 'visible',
+ 'opacity',
+ 'blendMode',
+ 'locked',
+ 'size',
+ 'transform',
+ 'effects',
+ 'autoRename',
+ 'frameMaskDisabled',
+ 'exportSettings',
+ 'pluginData',
+ 'pluginRelaunchData'
+] as const
+
+function sublayerProps(
+ entry: GeneratedEntry | undefined,
+ derived: GeneratedEntry | undefined,
+ blobs: Uint8Array[]
+): Partial<SceneNode> {
+ const {
+ nodeType: _type,
+ name: _name,
+ ...props
+ } = nodeChangeToProps(sublayerRecord('TEXT', entry, derived), blobs, 'occurrence')
+ return { ...props, ...STICKY_SUBLAYER_LAYOUT }
+}
+
+/**
+ * Gives an imported STICKY the sublayers its record describes. The note's colour is its
+ * background's fill, which the note itself carries here; its layout comes from the template at
+ * the scale its author line was set in.
+ */
+function readSticky(
+ graph: SceneGraph,
+ sticky: SceneNode,
+ record: NodeChange,
+ blobs: Uint8Array[]
+): void {
+ const overrides = generationOverridesOf(record)
+ const derived = derivedFrameEntriesOf(record)
+ const { background, body, author } = STICKY_SLOTS
+ const bodyProps = sublayerProps(overrides.get(body), derived.get(body), blobs)
+ const authorProps = sublayerProps(overrides.get(author), derived.get(author), blobs)
+ const scale = overrides.has(author) ? stickyScale({ fontSize: authorProps.fontSize ?? 0 }) : 1
+ graph.updateNode(sticky.id, {
+ fills: convertFills(overrides.get(background)?.fillPaints),
+ ...stickyFrameFields(scale)
+ })
+ buildStickySublayers(graph, sticky, { scale }, { body: bodyProps, author: authorProps })
+}
+
+/**
+ * A generated frame's record, with its sublayers written on it as Figma stores a sticky note: what
+ * each sublayer shows under `nodeGenerationData`, and the layout derived from it under
+ * `derivedImmutableFrameData`. Figma draws a note from its derived data as saved and lays it out
+ * afresh only without it, so the export writes that data only when it has shaped every text.
+ */
+function writeSticky(
+ context: SceneNodeToKiwiContext,
+ node: SceneNode,
+ nc: KiwiNodeChange
+): KiwiNodeChange {
+ const sublayers = stickySublayers(context.graph, node)
+ if (!sublayers) return nc
+ const record: KiwiNodeChange = pick(nc, STICKY_RECORD_FIELDS)
+ const fillPaints = createFillPaints(context, node)
+ const background: GeneratedEntry = {
+ guidPath: generatedSlotPath(STICKY_SLOTS.background),
+ fillPaints,
+ cornerRadius: 0
+ }
+ const overrides: GeneratedEntry[] = [background]
+ const derived: GeneratedEntry[] = [
+ { guidPath: generatedSlotPath(STICKY_SLOTS.background), ...placement({ ...node, x: 0, y: 0 }) }
+ ]
+ let complete = true
+ for (const [slot, layer] of [
+ [STICKY_SLOTS.body, sublayers.body],
+ [STICKY_SLOTS.author, sublayers.author]
+ ] as const) {
+ const text = textSublayer(context, slot, layer)
+ overrides.push(text.entry)
+ derived.push(text.derived)
+ complete &&= shaped(layer, text.derived)
+ }
+ record.nodeGenerationData = { overrides, useFineGrainedSyncing: false, diffOnlyRemovals: [] }
+ if (complete) record.derivedImmutableFrameData = { overrides: derived, version: 1 }
+ return record
+}
+
+/** A sticky note: its colour on a background slot, and its body and author as text slots. */
+export const STICKY_CODEC: GeneratedFrameCodec = { read: readSticky, write: writeSticky }
diff --git a/packages/fig/src/node-classification.ts b/packages/fig/src/node-classification.ts
index ddc4942aa..8bba7a54d 100644
--- a/packages/fig/src/node-classification.ts
+++ b/packages/fig/src/node-classification.ts
@@ -1,3 +1,5 @@
+import { GENERATED_FRAME_TYPES } from '@open-pencil/scene-graph'
+
const UNSUPPORTED_FRAGMENT_TYPES: ReadonlySet<string> = new Set([
'STYLE',
'STYLE_SET',
@@ -21,8 +23,13 @@ const CONTAINER_AND_RESOURCE_TYPES: ReadonlySet<string> = new Set([
'VARIABLE'
])
+/**
+ * Whether a record is dropped on paste. FigJam's generated frames are kept once their type is
+ * defined as one, as a sticky note is.
+ */
export function isUnsupportedFigFragmentType(type: string | undefined): boolean {
- return UNSUPPORTED_FRAGMENT_TYPES.has(type ?? '')
+ const generated: ReadonlySet<string> = GENERATED_FRAME_TYPES
+ return UNSUPPORTED_FRAGMENT_TYPES.has(type ?? '') && !generated.has(type ?? '')
}
/** Clipboard bounds exclude containers, resources, and unsupported scene records. */
diff --git a/packages/fig/tests/node-change/generated/codecs.test.ts b/packages/fig/tests/node-change/generated/codecs.test.ts
new file mode 100644
index 000000000..56004180f
--- /dev/null
+++ b/packages/fig/tests/node-change/generated/codecs.test.ts
@@ -0,0 +1,10 @@
+import { expect, test } from 'bun:test'
+
+import { generatedFrameCodec } from '#fig/node-change/generated/codecs'
+
+import { GENERATED_FRAME_TYPES } from '@open-pencil/scene-graph'
+
+test('every generated frame type is read and written through a codec', () => {
+ for (const type of GENERATED_FRAME_TYPES)
+ expect({ type, codec: !!generatedFrameCodec(type) }).toEqual({ type, codec: true })
+})
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index ab78b166a..a45f07a09 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -9,7 +9,7 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice
- Bounds accumulation goes through the helpers in `packages/scene-graph/src/geometry.ts` (`computeBounds`, `computeAbsoluteBounds`, `computeVisualBounds`); do not add another min/max loop.
- Reparenting preserves child world positions; groups preserve them too. Sort children geometrically before creating auto-layout. Consumers such as layer trees must react to reparenting rather than retaining stale child references.
- Use the copy helpers in `packages/scene-graph/src/copy.ts` for nested values (fills, strokes, effects); never hand-copy node properties.
-- A generated frame (`GENERATED_FRAME_TYPES`, Figma's immutable frames such as `STICKY`) owns real child layers built from its template in `packages/scene-graph/src/generated/`; nothing adds, moves, or removes them (`slotScope` reports `locked`), the layers panel lists the frame alone, and `.fig` writes them as `nodeGenerationData` on the frame's record (`packages/fig/tests/node-change/generated/sticky.test.ts`).
+- A generated frame (Figma's immutable frames such as `STICKY`) owns real child layers built from its template in `packages/scene-graph/src/generated/`; nothing adds, moves, or removes them (`slotScope` reports `locked`), and the layers panel lists the frame alone. Each type registers a `GeneratedFrameKind` in `GENERATED_FRAME_KINDS`, and the editor asks it (`layerRotates`, `layerResizes`, `generatedFrameText`) instead of testing node types (`packages/scene-graph/tests/generated/kind.test.ts`).
- Instance children map to component children through `componentId`; runtime overrides use the structured `InstanceOverrideState` (`self` and `descendants` maps) in `packages/scene-graph/src/instance-overrides.ts`.
- A bound numeric field records its unit conversion in `variableBindingScales`; preserve it through clone, copy, and transfer so a binding keeps meaning in its new scope. Core reconciles bindings and layout together in `packages/core/src/layout/variables.ts`, which the editor and the Figma API both call rather than reimplementing.
- `componentScale` records an occurrence's coordinates relative to its component definition. Shared rescaling lives in `packages/scene-graph/src/scaling/`; Core's Figma API delegates there instead of scaling nodes itself.
diff --git a/packages/scene-graph/src/generated/index.ts b/packages/scene-graph/src/generated/index.ts
index 7a0e1b617..88c94ce56 100644
--- a/packages/scene-graph/src/generated/index.ts
+++ b/packages/scene-graph/src/generated/index.ts
@@ -1,13 +1,29 @@
import type { SceneGraph } from '../index'
import type { NodeType, SceneNode } from '../types'
+import type { GeneratedFrameKind } from './kind'
+import { STICKY_KIND } from './sticky'
/**
* Layers Figma generates from a template, which it calls immutable frames: their sublayers come
* from the type and its settings, and a user edits them only through the frame. A sticky note's
* body and author are such sublayers. They are real children here, so layout, drawing and text
* editing treat them as any other layer, but nothing may add, move or remove them.
+ *
+ * Each type is described once, here; the editor and file formats ask it instead of testing for
+ * the type.
*/
-export const GENERATED_FRAME_TYPES: ReadonlySet<NodeType> = new Set(['STICKY'])
+const GENERATED_FRAME_KINDS: Partial<Record<NodeType, GeneratedFrameKind>> = {
+ STICKY: STICKY_KIND
+}
+
+export const GENERATED_FRAME_TYPES: ReadonlySet<NodeType> = new Set(
+ Object.keys(GENERATED_FRAME_KINDS) as NodeType[]
+)
+
+/** What a generated frame's type says about it, or undefined for any other layer. */
+export function generatedFrameKind(node: Pick<SceneNode, 'type'>): GeneratedFrameKind | undefined {
+ return GENERATED_FRAME_KINDS[node.type]
+}
export function isGeneratedFrame(node: Pick<SceneNode, 'type'>): boolean {
return GENERATED_FRAME_TYPES.has(node.type)
@@ -15,12 +31,23 @@ export function isGeneratedFrame(node: Pick<SceneNode, 'type'>): boolean {
/** The generated frame a layer belongs to, if it is one of its sublayers. */
export function generatedFrameOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {
- let current = node.parentId ? graph.nodes.get(node.parentId) : undefined
- while (current) {
- if (isGeneratedFrame(current)) return current
- current = current.parentId ? graph.nodes.get(current.parentId) : undefined
- }
- return undefined
+ return node.parentId ? graph.closest(node.parentId, isGeneratedFrame) : undefined
+}
+
+/** The text a generated frame edits in place, such as a sticky note's body. */
+export function generatedFrameText(graph: SceneGraph, node: SceneNode): SceneNode | undefined {
+ return generatedFrameKind(node)?.text(graph, node)
+}
+
+/** Whether a layer turns: any layer but a generated frame that stays upright. */
+export function layerRotates(node: Pick<SceneNode, 'type'>): boolean {
+ return generatedFrameKind(node)?.rotates ?? true
+}
+
+/** Whether a layer's resize handles and W and H fields resize it freely. */
+export function layerResizes(node: Pick<SceneNode, 'type'>): boolean {
+ return generatedFrameKind(node)?.resizes ?? true
}
+export type { GeneratedFrameKind } from './kind'
export * from './sticky'
diff --git a/packages/scene-graph/src/generated/kind.ts b/packages/scene-graph/src/generated/kind.ts
new file mode 100644
index 000000000..a10a1c95e
--- /dev/null
+++ b/packages/scene-graph/src/generated/kind.ts
@@ -0,0 +1,19 @@
+import type { SceneGraph } from '../index'
+import type { SceneNode } from '../types'
+
+/**
+ * What the editor and file formats need to know about one type of generated frame, so they ask
+ * the type rather than test for it. Each type defines one in its own module.
+ */
+export interface GeneratedFrameKind {
+ /** Whether the frame still has its template's layers; one that lost them is a plain frame. */
+ complete(graph: SceneGraph, frame: SceneNode): boolean
+ /** The text a user types into in place: on double-click or Enter, and as a script's `text`. */
+ text(graph: SceneGraph, frame: SceneNode): SceneNode | undefined
+ /** Whether the frame turns; FigJam keeps sticky notes upright. */
+ rotates: boolean
+ /** Whether the frame's resize handles and W and H fields resize it freely. */
+ resizes: boolean
+ /** Whether it takes its name from its text until the user names it, as a sticky note does. */
+ namedByText: boolean
+}
diff --git a/packages/scene-graph/src/generated/sticky.ts b/packages/scene-graph/src/generated/sticky.ts
index 533d85b0f..3227b6aee 100644
--- a/packages/scene-graph/src/generated/sticky.ts
+++ b/packages/scene-graph/src/generated/sticky.ts
@@ -2,6 +2,7 @@ import { BLACK } from '../constants'
import type { SceneGraph } from '../index'
import type { Color } from '../primitives'
import type { Effect, Fill, SceneNode } from '../types'
+import type { GeneratedFrameKind } from './kind'
/**
* A FigJam sticky note as Figma lays it out: a fixed-width card that grows to fit its body, with
@@ -165,6 +166,15 @@ export function stickySublayers(graph: SceneGraph, sticky: SceneNode): StickySub
return { body, author }
}
+/** A sticky note scales as a whole from its own handles and stays upright, as in FigJam. */
+export const STICKY_KIND: GeneratedFrameKind = {
+ complete: (graph, frame) => stickySublayers(graph, frame) !== null,
+ text: (graph, frame) => stickySublayers(graph, frame)?.body,
+ rotates: false,
+ resizes: false,
+ namedByText: true
+}
+
export interface StickyContent {
text?: string
author?: string
diff --git a/packages/scene-graph/tests/generated/kind.test.ts b/packages/scene-graph/tests/generated/kind.test.ts
new file mode 100644
index 000000000..c414d1bfb
--- /dev/null
+++ b/packages/scene-graph/tests/generated/kind.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ createSticky,
+ generatedFrameKind,
+ generatedFrameText,
+ layerResizes,
+ layerRotates,
+ SceneGraph,
+ stickySublayers
+} from '@open-pencil/scene-graph'
+
+describe('generated frame kinds', () => {
+ test('a sticky note edits its body in place, stays upright, and scales by its own handles', () => {
+ const graph = new SceneGraph()
+ const sticky = createSticky(graph, graph.getPages()[0].id, { text: 'Hi' })
+ expect(generatedFrameText(graph, sticky)?.id).toBe(stickySublayers(graph, sticky)?.body.id)
+ expect([layerRotates(sticky), layerResizes(sticky)]).toEqual([false, false])
+ expect(generatedFrameKind(sticky)?.namedByText).toBe(true)
+ expect(generatedFrameKind(sticky)?.complete(graph, sticky)).toBe(true)
+ })
+
+ test('any other layer has no kind and turns and resizes freely', () => {
+ const rectangle = { type: 'RECTANGLE' as const }
+ expect(generatedFrameKind(rectangle)).toBeUndefined()
+ expect([layerRotates(rectangle), layerResizes(rectangle)]).toEqual([true, true])
+ })
+})
diff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.ts
index 6d957129b..f437c1f57 100644
--- a/packages/vue/src/canvas/text-edit/input.ts
+++ b/packages/vue/src/canvas/text-edit/input.ts
@@ -1,5 +1,5 @@
import { getNodeEditCapability, type Editor } from '@open-pencil/core/editor'
-import { generatedFrameOwner, stickySublayers, type SceneNode } from '@open-pencil/scene-graph'
+import { generatedFrameOwner, generatedFrameText, type SceneNode } from '@open-pencil/scene-graph'
import type { CanvasLabelKind } from '#vue/canvas/labels/edit'
import type { DragState } from '#vue/shared/input/types'
@@ -82,11 +82,14 @@ export function createTextEditInput(options: TextEditInputOptions) {
}
}
- /** A sticky note keeps its selection while its body is edited, all of it selected, as in Figma. */
- function startStickyEditing(sticky: SceneNode) {
- const body = stickySublayers(editor.graph, sticky)?.body
+ /**
+ * A generated frame, such as a sticky note, keeps its selection while its text is edited, all of
+ * it selected, as in Figma.
+ */
+ function startGeneratedTextEditing(frame: SceneNode) {
+ const body = generatedFrameText(editor.graph, frame)
if (!body) return
- editor.select([sticky.id])
+ editor.select([frame.id])
editor.startTextEditing(body.id)
if (editor.state.editingTextId !== body.id) return
editor.textEditor?.selectAll()
@@ -179,8 +182,8 @@ export function createTextEditInput(options: TextEditInputOptions) {
return
}
- if (hit.type === 'STICKY') {
- startStickyEditing(hit)
+ if (generatedFrameText(editor.graph, hit)) {
+ startGeneratedTextEditing(hit)
return
}
diff --git a/packages/vue/src/canvas/transform/rotation.ts b/packages/vue/src/canvas/transform/rotation.ts
index 0a1397f70..cb405d89b 100644
--- a/packages/vue/src/canvas/transform/rotation.ts
+++ b/packages/vue/src/canvas/transform/rotation.ts
@@ -1,6 +1,7 @@
import { ROTATION_SNAP_DEGREES } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
import { createSceneGeometry } from '@open-pencil/core/geometry'
+import { layerRotates } from '@open-pencil/scene-graph'
import {
hitTestCornerRotationByMatrix,
@@ -23,8 +24,8 @@ export function tryStartRotation(
if (editor.state.selectedIds.size !== 1) return false
const id = [...editor.state.selectedIds][0]
const node = editor.graph.getNode(id)
- // FigJam keeps sticky notes upright.
- if (!node || node.locked || node.type === 'STICKY') return false
+ // A generated frame such as a sticky note may stay upright.
+ if (!node || node.locked || !layerRotates(node)) return false
const geometry = createSceneGeometry(editor.graph, editor.state.rotationPreview)
const center = geometry.rotationOrigin(node)
diff --git a/packages/vue/src/shared/input/resize/start.ts b/packages/vue/src/shared/input/resize/start.ts
index f1ca4e00f..2be1d9a12 100644
--- a/packages/vue/src/shared/input/resize/start.ts
+++ b/packages/vue/src/shared/input/resize/start.ts
@@ -1,5 +1,5 @@
import type { Editor } from '@open-pencil/core/editor'
-import { enforcedAspectRatio } from '@open-pencil/scene-graph'
+import { enforcedAspectRatio, layerResizes } from '@open-pencil/scene-graph'
import { collectResizeDescendants, createResizeSnapshot } from '@open-pencil/scene-graph/resize'
import { getHitHandleByMatrix } from '#vue/shared/input/geometry'
@@ -8,8 +8,9 @@ import type { DragResize } from '#vue/shared/input/types'
export function tryStartResize(cx: number, cy: number, editor: Editor): DragResize | null {
for (const id of editor.state.selectedIds) {
const node = editor.graph.getNode(id)
- // A sticky note only scales, from its corners; see `tryStartStickyScale`.
- if (!node || node.locked || node.type === 'STICKY') continue
+ // A generated frame such as a sticky note is shaped by its own handles; see
+ // `tryStartStickyScale`.
+ if (!node || node.locked || !layerResizes(node)) continue
const handleResult = getHitHandleByMatrix(
cx,
cy,
diff --git a/packages/vue/src/shared/input/select/hover.ts b/packages/vue/src/shared/input/select/hover.ts
index 36215c949..207bf8e33 100644
--- a/packages/vue/src/shared/input/select/hover.ts
+++ b/packages/vue/src/shared/input/select/hover.ts
@@ -1,4 +1,5 @@
import type { Editor } from '@open-pencil/core/editor'
+import { layerRotates } from '@open-pencil/scene-graph'
import {
buildResizeCursor,
@@ -33,7 +34,7 @@ function getRotationCursorForSelection(cx: number, cy: number, editor: Editor):
const id = [...editor.state.selectedIds][0]
const node = editor.graph.getNode(id)
- if (!node || node.type === 'STICKY') return null
+ if (!node || !layerRotates(node)) return null
const corner = hitTestCornerRotationByMatrix(
cx,
diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts
index 5a6fd2700..eb40165ee 100644
--- a/src/app/shell/keyboard/actions.ts
+++ b/src/app/shell/keyboard/actions.ts
@@ -1,7 +1,7 @@
import type { Ref } from 'vue'
import { opacityFromBuffer } from '@open-pencil/core/editor'
-import { stickySublayers } from '@open-pencil/scene-graph'
+import { generatedFrameText } from '@open-pencil/scene-graph'
import type { useEditorCommands, useViewportKind } from '@open-pencil/vue'
import type { PropertiesTab } from '@/app/ai/chat/use'
@@ -55,8 +55,9 @@ export function createKeyboardActions({
store.enterNodeEditMode(node.id)
return
}
- // A sticky note opens its body, all of it selected, keeping the note selected.
- const text = node?.type === 'STICKY' ? stickySublayers(store.graph, node)?.body : node
+ // A generated frame opens its text, such as a sticky note's body, all of it selected,
+ // keeping the frame selected.
+ const text = (node && generatedFrameText(store.graph, node)) ?? node
if (text?.type === 'TEXT') {
requestAnimationFrame(() => {
store.startTextEditing(text.id)
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index 7557ef5db..88ad76b8a 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -2,7 +2,7 @@
import { computed } from 'vue'
import { getNodeEditCapability } from '@open-pencil/core/editor'
-import { readIcon } from '@open-pencil/scene-graph'
+import { layerResizes, readIcon } from '@open-pencil/scene-graph'
import { useI18n, useSceneComputed, useSelectionState, useEditorCommands } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
@@ -215,7 +215,7 @@ const { panels } = useI18n()
<PositionSection />
<ConstraintsSection />
<!-- A sticky note's size follows its text and its scale; Figma leaves W and H read-only. -->
- <LayoutSection v-if="node.type !== 'STICKY'" />
+ <LayoutSection v-if="layerResizes(node)" />
<AppearanceSection />
<MaskSection />
<TypographySection v-if="node.type === 'TEXT'" />