Skip to content

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

refactor(design-jsx): read sticky and connector props by Valibot schemas (#1296)

Danila Poyarkova0e3d8158499
diff --git a/packages/core/tests/design-jsx/connectors.test.ts b/packages/core/tests/design-jsx/connectors.test.ts
index a02352c38..5ce339c86 100644
--- a/packages/core/tests/design-jsx/connectors.test.ts
+++ b/packages/core/tests/design-jsx/connectors.test.ts
@@ -230,6 +230,24 @@ return <Frame name="Flow" w={800} h={400}>
expect(result.warnings).toContain('<Connector> to="Nowhere" names no layer.')
})
+ test('a prop of the wrong kind warns and is left out, and end warnings are kept', async () => {
+ const graph = new SceneGraph()
+ const [result] = await renderJSX(
+ graph,
+ '<Frame name="Flow" w={400} h={200}><Frame name="A" w={50} h={50} /><Connector from={5} to="A" stroke="nope" strokeWidth={0} /></Frame>'
+ )
+ expect(result.warnings).toEqual([
+ 'Invalid from 5 on <connector> is ignored; expected a layer name, a ref(), or { x, y }.',
+ 'Invalid stroke "nope" on <connector> is ignored; expected a colour.',
+ 'Invalid strokeWidth 0 on <connector> is ignored; expected >0.',
+ '<Connector> from="5" names no layer.'
+ ])
+ const connector = getNodeOrThrow(graph, graph.getChildren(result.id)[1].id)
+ const line = connectorSublayers(graph, connector)?.line
+ expect(line?.strokeWeight).toBe(4)
+ expect(connector.connectorEnd?.nodeId).toBe(graph.getChildren(result.id)[0].id)
+ })
+
test('name the rendered roots too, not only the layers inside them', async () => {
const graph = new SceneGraph()
const [flow] = await renderJSX(
diff --git a/packages/core/tests/design-jsx/stickies.test.ts b/packages/core/tests/design-jsx/stickies.test.ts
index 21820748c..e9869d023 100644
--- a/packages/core/tests/design-jsx/stickies.test.ts
+++ b/packages/core/tests/design-jsx/stickies.test.ts
@@ -4,7 +4,12 @@ import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { renderJSX } from '@open-pencil/core/design-jsx'
import { sceneNodeToJSX } from '@open-pencil/design-jsx'
-import { SceneGraph, STICKY_COLORS, stickySublayers } from '@open-pencil/scene-graph'
+import {
+ DEFAULT_STICKY_COLOR,
+ SceneGraph,
+ STICKY_COLORS,
+ stickySublayers
+} from '@open-pencil/scene-graph'
const BOARD = `
<Frame name="Board" w={900} h={400}>
@@ -59,6 +64,55 @@ describe('sticky notes in design JSX', () => {
expect(getNodeOrThrow(again, reread.id).autoRename).toBe(false)
})
+ test('a prop of the wrong kind warns and is left out', async () => {
+ const graph = new SceneGraph()
+ const [result] = await renderJSX(
+ graph,
+ '<Sticky color="sparkle" wide="yes" scale={0} textSize="giant">Hi</Sticky>'
+ )
+ expect(result.warnings).toEqual([
+ 'Unknown color "sparkle" on <sticky> is ignored; expected white, gray, red, orange, yellow, green, teal, blue, violet, pink, or a colour.',
+ 'Invalid wide "yes" on <sticky> is ignored; expected boolean.',
+ 'Unknown textSize "giant" on <sticky> is ignored; expected small, medium, large, extraLarge, huge.',
+ 'Invalid scale 0 on <sticky> is ignored; expected >0.'
+ ])
+ const sticky = getNodeOrThrow(graph, result.id)
+ expect(sticky).toMatchObject({ type: 'STICKY', width: 240 })
+ expect(sticky.fills[0]?.color).toEqual(DEFAULT_STICKY_COLOR)
+ })
+
+ test('take layer props as any layer does: a variable binds, and a placed note in auto layout is absolute', async () => {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'numbers',
+ name: 'Numbers',
+ modes: [{ modeId: 'base', name: 'Base' }],
+ defaultModeId: 'base',
+ variableIds: []
+ })
+ graph.addVariable({
+ id: 'var-faded',
+ name: 'Faded',
+ type: 'FLOAT',
+ collectionId: 'numbers',
+ valuesByMode: { base: 0.5 },
+ description: '',
+ hiddenFromPublishing: false
+ })
+ const [result] = await renderJSX(
+ graph,
+ `<Frame name="Board" flex="col" w={600} h={600}>
+ <Sticky opacity={designVar('var-faded', 0.5)}>Faded</Sticky>
+ <Sticky x={300} y={40}>Placed</Sticky>
+</Frame>`
+ )
+ expect(result.warnings ?? []).toEqual([])
+ const [faded, placed] = graph.getChildren(result.id)
+ expect(faded.opacity).toBe(0.5)
+ expect(faded.boundVariables.opacity).toBe('var-faded')
+ expect(placed).toMatchObject({ x: 300, y: 40, layoutPositioning: 'ABSOLUTE' })
+ })
+
test('join connectors to themselves, never to the layers they generate', async () => {
const graph = new SceneGraph()
const [result] = await renderJSX(
diff --git a/packages/design-jsx/AGENTS.md b/packages/design-jsx/AGENTS.md
index fabe50d3d..f210eb2c2 100644
--- a/packages/design-jsx/AGENTS.md
+++ b/packages/design-jsx/AGENTS.md
@@ -8,6 +8,8 @@ Rules:
- 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 element that draws its own layer, such as `<Sticky>` or `<Connector>`, declares its props as a Valibot `schema` and its renderer as `ownLayer` on its entry; a value that does not fit warns and is left out. Its layer props (`OwnLayerProps`) go through `propsToOverrides` like any layer's, so variables bind; the element reads only its own props (`packages/core/tests/design-jsx/stickies.test.ts`).
+- Export writes each generated frame through `OWN_ELEMENTS`, keyed by `GeneratedFrameType`, so a new generated frame does not compile until it has an exporter (`src/export/index.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.
diff --git a/packages/design-jsx/src/connectors.ts b/packages/design-jsx/src/connectors.ts
index 56e55638c..9e7a26a95 100644
--- a/packages/design-jsx/src/connectors.ts
+++ b/packages/design-jsx/src/connectors.ts
@@ -1,5 +1,6 @@
import { compact, countBy } from 'es-toolkit/array'
import { camelCase } from 'es-toolkit/string'
+import * as v from 'valibot'
import {
boundEndpoint,
@@ -19,11 +20,12 @@ import {
import { colorToHex, tryParseColor } from '@open-pencil/scene-graph/color'
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
-import { CONNECTOR_LINE, CONNECTOR_SIDE, STROKE_CAP } from './enums'
+import { CONNECTOR_LINE, CONNECTOR_SIDE, enumProp, STROKE_CAP } from './enums'
import { Reference } from './export/value'
import { isColor } from './overrides/fills'
-import { isLayerRef, type LayerRefs } from './refs'
-import type { TreeNode } from './tree'
+import { isLayerRef, type LayerRef, type LayerRefs } from './refs'
+import { plainTextOf, type TreeNode } from './tree'
+import { OwnLayerProps, readElementProps } from './validation'
/**
* `<Connector from="A" to="B">`: a FigJam connector whose ends name other layers of the same
@@ -32,21 +34,60 @@ import type { TreeNode } from './tree'
*/
export const CONNECTOR_ELEMENT = 'connector'
-function isPoint(value: unknown): value is Vector {
- if (typeof value !== 'object' || value === null || !('x' in value) || !('y' in value)) {
- return false
- }
- return typeof value.x === 'number' && typeof value.y === 'number'
-}
+/** A layer of the same JSX by name or `ref()`, or a point in the connector's parent. */
+const ConnectorEnd = v.union(
+ [v.string(), v.custom<LayerRef>(isLayerRef), v.object({ x: v.number(), y: v.number() })],
+ 'expected a layer name, a ref(), or { x, y }'
+)
-function labelOf(tree: TreeNode): string {
- return tree.children.filter((child): child is string => typeof child === 'string').join('')
-}
+/** A colour as a string, or as the colour a `designVar()` resolves to. */
+const LineColor = v.union(
+ [
+ v.pipe(
+ v.string(),
+ v.rawTransform(({ dataset, addIssue, NEVER }): Color => {
+ const color = tryParseColor(dataset.value)
+ if (color) return color
+ addIssue({ message: 'expected a colour' })
+ return NEVER
+ })
+ ),
+ v.custom<Color>(isColor)
+ ],
+ 'expected a colour'
+)
+
+/** The props `<Connector>` takes: its own, and the layer props that style its line. */
+export const ConnectorProps = v.object({
+ from: v.optional(ConnectorEnd),
+ to: v.optional(ConnectorEnd),
+ fromSide: v.optional(enumProp(CONNECTOR_SIDE)),
+ toSide: v.optional(enumProp(CONNECTOR_SIDE)),
+ line: v.optional(enumProp(CONNECTOR_LINE)),
+ startCap: v.optional(enumProp(STROKE_CAP)),
+ endCap: v.optional(enumProp(STROKE_CAP)),
+ ...OwnLayerProps.entries,
+ stroke: v.optional(LineColor),
+ strokeWidth: v.optional(v.pipe(v.number(), v.gtValue(0))),
+ dashPattern: v.optional(v.array(v.number()))
+})
+
+type ConnectorPropValues = v.InferOutput<typeof ConnectorProps>
-/** Makes the connector an element describes, its ends free until `resolveConnectorEnds`. */
-export function renderConnectorNode(graph: SceneGraph, tree: TreeNode, parentId: string) {
- const { props } = tree
- const line = CONNECTOR_LINE.parse(props.line)
+/** The layer props a connector has: no place or size, which its ends give it. */
+export const ConnectorLayerProps = OwnLayerProps
+
+/**
+ * Makes the connector an element describes, with `layer`'s fields, its ends free until
+ * `resolveConnectorEnds`.
+ */
+export function renderConnectorNode(
+ graph: SceneGraph,
+ tree: TreeNode,
+ parentId: string,
+ layer: Partial<SceneNode>
+) {
+ const props = readElementProps(ConnectorProps, tree.props)
const parent = graph.getNode(parentId)
const connector = createConnector(
graph,
@@ -54,15 +95,13 @@ export function renderConnectorNode(graph: SceneGraph, tree: TreeNode, parentId:
{
start: freeEndpoint(0, 0),
end: freeEndpoint(0, 0),
- lineType: line,
- startCap: STROKE_CAP.parse(props.startCap) ?? 'NONE',
- endCap: STROKE_CAP.parse(props.endCap) ?? 'ARROW_LINES',
- text: labelOf(tree)
+ lineType: props.line,
+ startCap: props.startCap ?? 'NONE',
+ endCap: props.endCap ?? 'ARROW_LINES',
+ text: plainTextOf(tree)
},
{
- ...(typeof props.name === 'string' && { name: props.name }),
- ...(props.visible === false && { visible: false }),
- ...(typeof props.opacity === 'number' && { opacity: props.opacity }),
+ ...layer,
// A connector is drawn between layers, not placed by its parent's auto layout.
...(parent && parent.layoutMode !== 'NONE' && { layoutPositioning: 'ABSOLUTE' as const })
}
@@ -72,26 +111,21 @@ export function renderConnectorNode(graph: SceneGraph, tree: TreeNode, parentId:
return connector
}
-function colorOf(value: unknown): Color | undefined {
- if (isColor(value)) return value
- return typeof value === 'string' ? (tryParseColor(value) ?? undefined) : undefined
+/** The layer a connector's variable binding goes on: its line for the stroke, else itself. */
+export function connectorBindingTarget(graph: SceneGraph, connector: SceneNode, field: string) {
+ const onLine = field.startsWith('strokes/') || field === 'strokeWeight'
+ return (onLine && connectorSublayers(graph, connector)?.line.id) || connector.id
}
/** Restyles the line by `stroke`, `strokeWidth`, and `dashPattern`; each left out keeps FigJam's. */
-function styleLine(graph: SceneGraph, line: SceneNode, props: TreeNode['props']) {
+function styleLine(graph: SceneGraph, line: SceneNode, props: ConnectorPropValues) {
const [stroke = connectorStroke()] = line.strokes
- const color = colorOf(props.stroke) ?? stroke.color
- const weight =
- typeof props.strokeWidth === 'number' && props.strokeWidth > 0
- ? props.strokeWidth
- : stroke.weight
- const dashPattern = Array.isArray(props.dashPattern)
- ? props.dashPattern.filter((length): length is number => typeof length === 'number')
- : line.dashPattern
+ const color = props.stroke ?? stroke.color
+ const weight = props.strokeWidth ?? stroke.weight
graph.updateNode(line.id, {
strokes: [{ ...stroke, color, weight }],
strokeWeight: weight,
- dashPattern
+ dashPattern: props.dashPattern ?? line.dashPattern
})
}
@@ -137,11 +171,16 @@ export function resolveConnectorEnds(
else named.set(layer.name, [layer.id])
}
const warnings: string[] = []
- const endpoint = (prop: 'from' | 'to', props: TreeNode['props'], straight: boolean) => {
+ const endpoint = (
+ prop: 'from' | 'to',
+ props: ConnectorPropValues,
+ written: TreeNode['props'],
+ straight: boolean
+ ) => {
const value = props[prop]
- if (isPoint(value)) return freeEndpoint(value.x, value.y)
let id: string | undefined
if (isLayerRef(value)) id = refs.layerOf(value)
+ else if (typeof value === 'object') return freeEndpoint(value.x, value.y)
else if (typeof value === 'string') {
const ids = named.get(value) ?? []
if (ids.length > 1) {
@@ -153,16 +192,17 @@ export function resolveConnectorEnds(
}
if (!id) {
const missing = isLayerRef(value) ? 'refers to no layer' : 'names no layer'
- warnings.push(`<Connector> ${endSource(prop, value)} ${missing}.`)
+ warnings.push(`<Connector> ${endSource(prop, written[prop])} ${missing}.`)
return null
}
const side = props[prop === 'from' ? 'fromSide' : 'toSide']
- return boundEndpoint(id, straight ? 'CENTER' : (CONNECTOR_SIDE.parse(side) ?? 'AUTO'))
+ return boundEndpoint(id, straight ? 'CENTER' : (side ?? 'AUTO'))
}
for (const { node, tree } of connectors) {
const straight = node.connectorLineType === 'STRAIGHT'
- const start = endpoint('from', tree.props, straight)
- const end = endpoint('to', tree.props, straight)
+ const props = readElementProps(ConnectorProps, tree.props)
+ const start = endpoint('from', props, tree.props, straight)
+ const end = endpoint('to', props, tree.props, straight)
graph.updateNode(node.id, {
...(start && { connectorStart: start }),
...(end && { connectorEnd: end })
diff --git a/packages/design-jsx/src/elements.ts b/packages/design-jsx/src/elements.ts
index b0f527a32..c0566af49 100644
--- a/packages/design-jsx/src/elements.ts
+++ b/packages/design-jsx/src/elements.ts
@@ -1,18 +1,32 @@
import { difference } from 'es-toolkit/array'
-import type { NodeType } from '@open-pencil/scene-graph'
+import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { REKA_ELEMENTS, rekaRole } from './behaviours'
import {
- DESIGN_JSX_CONNECTOR_LAYER_PROPERTY_NAMES,
- DESIGN_JSX_CONNECTOR_PROPERTY_NAMES,
+ connectorBindingTarget,
+ ConnectorLayerProps,
+ ConnectorProps,
+ renderConnectorNode
+} from './connectors'
+import {
DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,
DESIGN_JSX_SPAN_PROPERTY_NAMES,
- DESIGN_JSX_STICKY_LAYER_PROPERTY_NAMES,
- DESIGN_JSX_STICKY_PROPERTY_NAMES,
DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,
DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES
} from './schema'
+import { renderStickyNode, StickyLayerProps, StickyProps } from './stickies'
+import type { TreeNode } from './tree'
+import type { ElementPropsSchema } from './validation'
+
+/** How an element that draws a layer of its own, such as a sticky note, renders it. */
+export interface OwnLayerRenderer {
+ /** The layer props it takes, made into fields as any layer's are. */
+ layer: ElementPropsSchema
+ render(graph: SceneGraph, tree: TreeNode, parentId: string, layer: Partial<SceneNode>): SceneNode
+ /** The layer a variable binding of `field` goes on, when not the element's own. */
+ bindingTarget?(graph: SceneGraph, node: SceneNode, field: string): string
+}
/**
* One design JSX element: what JSX names it, what it makes, the props it takes, and which layers
@@ -28,6 +42,10 @@ export type DesignJSXElementDefinition = {
nodeType?: NodeType
/** The props it takes; every layer prop when left out. */
props?: readonly string[]
+ /** The props it takes and what each holds, for an element that reads them by this schema. */
+ schema?: ElementPropsSchema
+ /** How it draws its own layer, for an element that does. */
+ ownLayer?: OwnLayerRenderer
/** The layers export writes as this element. */
writes?: readonly NodeType[]
}
@@ -160,7 +178,8 @@ export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [
name: 'Sticky',
runtimeType: 'sticky',
description: 'A FigJam sticky note; its text is the body.',
- props: [...DESIGN_JSX_STICKY_PROPERTY_NAMES, ...DESIGN_JSX_STICKY_LAYER_PROPERTY_NAMES],
+ schema: StickyProps,
+ ownLayer: { layer: StickyLayerProps, render: renderStickyNode },
writes: ['STICKY']
},
{
@@ -168,7 +187,12 @@ export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [
runtimeType: 'connector',
description:
'A FigJam connector between two layers of the same JSX, named by `from` and `to`, or points.',
- props: [...DESIGN_JSX_CONNECTOR_PROPERTY_NAMES, ...DESIGN_JSX_CONNECTOR_LAYER_PROPERTY_NAMES],
+ schema: ConnectorProps,
+ ownLayer: {
+ layer: ConnectorLayerProps,
+ render: renderConnectorNode,
+ bindingTarget: connectorBindingTarget
+ },
writes: ['CONNECTOR']
},
...rekaElementDefinitions()
@@ -219,9 +243,10 @@ const BY_RUNTIME_TYPE = new Map(
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)]] : []
- )
+ ...DESIGN_JSX_ELEMENTS.flatMap((element): [string, ReadonlySet<string>][] => {
+ const props = element.schema ? Object.keys(element.schema.entries) : element.props
+ return props ? [[element.runtimeType, new Set(props)]] : []
+ })
])
const TAG_BY_NODE_TYPE = new Map(
@@ -240,6 +265,16 @@ export function elementProps(runtimeType: string): ReadonlySet<string> {
return PROPS_BY_RUNTIME_TYPE.get(runtimeType) ?? LAYER_PROPS
}
+/** The schema an element of `runtimeType` reads its props by, if it has one. */
+export function elementSchema(runtimeType: string): ElementPropsSchema | undefined {
+ return BY_RUNTIME_TYPE.get(runtimeType)?.schema
+}
+
+/** How an element of `runtimeType` draws its own layer, if it does. */
+export function elementOwnLayer(runtimeType: string): OwnLayerRenderer | undefined {
+ return BY_RUNTIME_TYPE.get(runtimeType)?.ownLayer
+}
+
/** 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)
diff --git a/packages/design-jsx/src/enums.ts b/packages/design-jsx/src/enums.ts
index fb92aeae8..9aa1ee567 100644
--- a/packages/design-jsx/src/enums.ts
+++ b/packages/design-jsx/src/enums.ts
@@ -1,3 +1,5 @@
+import * as v from 'valibot'
+
import type {
BlendMode,
ConnectorLineType,
@@ -51,6 +53,19 @@ export function jsxEnum<T extends string>(
}
}
+/** A prop that takes one of the enum's spellings, read as the value it names. */
+export function enumProp<T extends string>(values: JSXEnum<T>) {
+ return v.pipe(
+ v.string(),
+ v.rawTransform(({ dataset, addIssue, NEVER }) => {
+ const value = values.parse(dataset.value)
+ if (value !== undefined) return value
+ addIssue({ message: `expected ${values.names.join(', ')}` })
+ return NEVER
+ })
+ )
+}
+
/** 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[],
@@ -132,7 +147,10 @@ export const CONNECTOR_SIDE = lowercaseEnum<
Extract<ConnectorMagnet, 'AUTO' | 'TOP' | 'RIGHT' | 'BOTTOM' | 'LEFT' | 'CENTER'>
>(['AUTO', 'TOP', 'RIGHT', 'BOTTOM', 'LEFT', 'CENTER'])
-/** The props whose values are one of an enum's spellings, for checking what JSX passes. */
+/**
+ * The layer props whose values are one of an enum's spellings, for checking what JSX passes. An
+ * element with a props schema, such as `<Connector>`, checks its enums by `enumProp` instead.
+ */
export const ENUM_PROPS: Readonly<Partial<Record<string, JSXEnum<string>>>> = {
strokeCap: STROKE_CAP,
strokeJoin: STROKE_JOIN,
@@ -145,11 +163,5 @@ export const ENUM_PROPS: Readonly<Partial<Record<string, JSXEnum<string>>>> = {
dir: TEXT_DIRECTION,
textDecoration: TEXT_DECORATION,
textDecorationStyle: TEXT_DECORATION_STYLE,
- textCase: TEXT_CASE,
- textSize: STICKY_TEXT_SIZE,
- line: CONNECTOR_LINE,
- fromSide: CONNECTOR_SIDE,
- toSide: CONNECTOR_SIDE,
- startCap: STROKE_CAP,
- endCap: STROKE_CAP
+ textCase: TEXT_CASE
}
diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.ts
index b54ed5cf7..ee1a3cbb5 100644
--- a/packages/design-jsx/src/export/index.ts
+++ b/packages/design-jsx/src/export/index.ts
@@ -1,7 +1,12 @@
import { compact } from 'es-toolkit/array'
import { jsx, type SyntaxNode } from '@open-pencil/emit'
-import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ isGeneratedFrame,
+ type GeneratedFrameType,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import {
connectorExportScope,
@@ -60,9 +65,13 @@ interface OwnElement {
text: string
}
-/** The layers whose elements take props of their own rather than the layer props. */
-const OWN_ELEMENTS: Partial<
- Record<NodeType, (graph: SceneGraph, node: SceneNode, scope?: ConnectorExportScope) => OwnElement>
+/**
+ * The layers whose elements take props of their own rather than the layer props: every generated
+ * frame, whose sublayers its element writes as props and text.
+ */
+const OWN_ELEMENTS: Record<
+ GeneratedFrameType,
+ (graph: SceneGraph, node: SceneNode, scope?: ConnectorExportScope) => OwnElement
> = {
STICKY: (graph, node) => {
const name = stickyName(node)
@@ -84,6 +93,15 @@ const OWN_ELEMENTS: Partial<
})
}
+/** What a layer whose element takes props of its own writes, or undefined for another layer. */
+function ownElement(
+ graph: SceneGraph,
+ node: SceneNode,
+ scope?: ConnectorExportScope
+): OwnElement | undefined {
+ return isGeneratedFrame(node) ? OWN_ELEMENTS[node.type](graph, node, scope) : undefined
+}
+
/** The layers an export writes, by the roots it starts from. */
function nodeToJSX(
node: SceneNode,
@@ -113,7 +131,7 @@ function nodeToJSX(
const tag = reka.tags.get(node.id) ?? elementTag(node.type)
if (!tag) return []
layerIds?.push(node.id)
- const own = OWN_ELEMENTS[node.type]?.(graph, node, scope)
+ const own = ownElement(graph, node, scope)
if (own) {
const children = own.text ? [jsx.text(own.text)] : []
return [jsx.element(tag, own.props.map(propAttribute), children, depth, true)]
@@ -153,7 +171,7 @@ export function sceneNodeAttributes(
): JSXAttributeSource[] | null {
const node = graph.getNode(nodeId)
if (!node || !elementTag(node.type)) return null
- const own = OWN_ELEMENTS[node.type]?.(graph, node)
+ const own = ownElement(graph, node)
const props = own ? own.props : collectProps(node, graph)
if (node.type === 'TEXT') props.push(['text', node.text])
if (own?.text) props.push(['text', own.text])
@@ -194,7 +212,7 @@ export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXEl
if (!node || !tag || !printed) return null
// A text layer's content, a connector's label, or a sticky note's body is written as its
// children, not as the `text` attribute; the layers they generate are not written at all.
- const own = OWN_ELEMENTS[node.type]
+ const own = ownElement(graph, node)
const hasContent = node.type === 'TEXT' || own !== undefined
const attributes = Object.fromEntries(
printed
@@ -206,8 +224,7 @@ export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXEl
return { tag, attributes, text: contentBetween(tag, children, inline), childIds: [] }
}
if (own) {
- const { text } = own(graph, node)
- const children = text ? [jsx.text(text)] : []
+ const children = own.text ? [jsx.text(own.text)] : []
return { tag, attributes, text: contentBetween(tag, children, true), childIds: [] }
}
const childIds = graph
diff --git a/packages/design-jsx/src/render.ts b/packages/design-jsx/src/render.ts
index ee651ab5c..86a7434a9 100644
--- a/packages/design-jsx/src/render.ts
+++ b/packages/design-jsx/src/render.ts
@@ -3,7 +3,7 @@ import { uniq } from 'es-toolkit/array'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { REKA_ELEMENTS } from './behaviours'
-import { elementBindings, elementProps } from './elements'
+import { elementBindings, elementProps, elementSchema } from './elements'
import { ENUM_PROPS } from './enums'
import { designJSXHelpers } from './helpers'
import * as React from './mini-react'
@@ -13,6 +13,7 @@ import { TEXT_CONTENT_NAMES } from './text-content'
import { transformDesignJSXExpression } from './transform'
import { isTreeNode, resolveToTree, type TreeNode } from './tree'
import type { RenderOptions as RenderJSXOptions } from './types'
+import { elementPropWarnings } from './validation'
/** `const Switch = { Root: 'Switch.Root', … }`: each Reka namespace as element types. */
const REKA_ALIASES = Object.entries(REKA_ELEMENTS)
@@ -43,6 +44,8 @@ function collectUnsupportedPropWarnings(
// An instance sets its component's properties by name, such as `State="On"` or `Title="Hi"`.
const properties = componentPropNames(graph, tree.props)
const element = TEXT_CONTENT_NAMES[tree.type] ?? tree.type
+ const schema = elementSchema(tree.type)
+ if (schema) warnings.push(...elementPropWarnings(schema, tree.props, element))
for (const [key, value] of Object.entries(tree.props)) {
if (!supported.has(key) && !properties.includes(key)) {
warnings.push(`Unsupported prop "${key}" on <${element}> is ignored.`)
@@ -130,7 +133,12 @@ async function renderJSX<Artwork>(
const results = await renderRoots(services, graph, tree, options)
// After rendering, so an instance's component set drawn in the same JSX names its variants.
// A helper called in a loop reports each ignored option once.
- const warnings = uniq([...unsupportedPropWarnings(graph, tree), ...helperWarnings])
+ // Prop warnings come first, then the render's own, such as a connector end naming no layer.
+ const warnings = uniq([
+ ...unsupportedPropWarnings(graph, tree),
+ ...helperWarnings,
+ ...(results[0].warnings ?? [])
+ ])
if (warnings.length > 0) results[0].warnings = warnings
return results
}
diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.ts
index d58009623..5f19796f5 100644
--- a/packages/design-jsx/src/renderer.ts
+++ b/packages/design-jsx/src/renderer.ts
@@ -1,5 +1,6 @@
+import { omitBy } from 'es-toolkit/object'
+
import {
- connectorSublayers,
setInstanceOverride,
type Color,
type NodeType,
@@ -17,17 +18,17 @@ import {
componentPropertyScope,
inferComponentSetProperties
} from './component-properties'
-import { CONNECTOR_ELEMENT, renderConnectorNode, resolveConnectorEnds } from './connectors'
-import { elementNodeType } from './elements'
+import { CONNECTOR_ELEMENT, resolveConnectorEnds } from './connectors'
+import { elementNodeType, elementOwnLayer, type OwnLayerRenderer } from './elements'
import { applySizeOverrides, propsToOverrides } from './props-overrides'
import { LayerRefs } from './refs'
import { prepareScalarBindings } from './scalar-bindings'
import type { DesignJSXServices } from './services'
-import { renderStickyNode, STICKY_ELEMENT } from './stickies'
import { isTextContent, TEXT_CONTENT_NAMES, textContentFields } from './text-content'
import { FRAGMENT, isTreeNode } from './tree'
import type { TreeNode } from './tree'
import type { RenderOptions } from './types'
+import { readElementProps } from './validation'
import { isVariable, resolveVariableId, type DesignVariable } from './vars'
export interface RenderResult {
@@ -193,18 +194,27 @@ function preparePropsForRender(
}
/**
- * A connector, its props resolved as any layer's are: a `designVar()` stroke colour or width
- * styles and binds the line it draws, and the rest bind the connector itself.
+ * An element that draws its own layer. Its props are resolved as any layer's are, so a
+ * `designVar()` binds, and its layer props become fields as any layer's do; the element reads the
+ * rest itself.
*/
-function renderConnectorElement(graph: SceneGraph, tree: TreeNode, parentId: string): SceneNode {
+function renderOwnLayerElement(
+ graph: SceneGraph,
+ tree: TreeNode,
+ parentId: string,
+ element: OwnLayerRenderer
+): SceneNode {
const { props, bindings } = preparePropsForRender(graph, tree.props, false, parentId)
- const connector = renderConnectorNode(graph, { ...tree, props }, parentId)
- const line = connectorSublayers(graph, connector)?.line
+ const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'
+ const layer = omitBy(
+ propsToOverrides(readElementProps(element.layer, props), false, parentLayout),
+ (value) => value === undefined
+ )
+ const node = element.render(graph, { ...tree, props }, parentId, layer)
for (const [field, variableId] of Object.entries(bindings)) {
- const onLine = field.startsWith('strokes/') || field === 'strokeWeight'
- graph.bindVariable(onLine && line ? line.id : connector.id, field, variableId)
+ graph.bindVariable(element.bindingTarget?.(graph, node, field) ?? node.id, field, variableId)
}
- return connector
+ return node
}
function applyBindings(graph: SceneGraph, nodeId: string, bindings: Record<string, string>): void {
@@ -515,12 +525,10 @@ function renderOwnElement<Artwork>(
return renderArtworkNode(services, graph, tree, parentId)
case 'instance':
return renderInstanceNode(graph, tree, parentId)
- case STICKY_ELEMENT:
- return Promise.resolve(renderStickyNode(graph, tree, parentId))
- case CONNECTOR_ELEMENT:
- return Promise.resolve(renderConnectorElement(graph, tree, parentId))
- default:
- return null
+ default: {
+ const element = elementOwnLayer(tree.type)
+ return element ? Promise.resolve(renderOwnLayerElement(graph, tree, parentId, element)) : null
+ }
}
}
diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.ts
index 6f50f609e..f1025c278 100644
--- a/packages/design-jsx/src/schema.ts
+++ b/packages/design-jsx/src/schema.ts
@@ -15,49 +15,6 @@ export const DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES = [
'indent'
] as const
-/** Props only `<Sticky>` takes. */
-export const DESIGN_JSX_STICKY_PROPERTY_NAMES = [
- 'color',
- 'author',
- 'authorVisible',
- 'wide',
- 'textSize',
- 'scale'
-] as const
-
-/** Layer props a sticky note takes too. */
-export const DESIGN_JSX_STICKY_LAYER_PROPERTY_NAMES = [
- 'name',
- 'key',
- 'x',
- 'y',
- 'position',
- 'visible',
- 'opacity'
-] as const
-
-/** Props only `<Connector>` takes. */
-export const DESIGN_JSX_CONNECTOR_PROPERTY_NAMES = [
- 'from',
- 'to',
- 'fromSide',
- 'toSide',
- 'line',
- 'startCap',
- 'endCap'
-] as const
-
-/** Layer props a connector takes too: its name and the stroke of its line. */
-export const DESIGN_JSX_CONNECTOR_LAYER_PROPERTY_NAMES = [
- 'name',
- 'key',
- 'visible',
- 'opacity',
- 'stroke',
- 'strokeWidth',
- 'dashPattern'
-] as const
-
/** Props `<Span>` takes: `<Text>`'s character styles, under the same names, and a link. */
export const DESIGN_JSX_SPAN_PROPERTY_NAMES = [
'style',
diff --git a/packages/design-jsx/src/stickies.ts b/packages/design-jsx/src/stickies.ts
index 7f1507b8a..d459942e2 100644
--- a/packages/design-jsx/src/stickies.ts
+++ b/packages/design-jsx/src/stickies.ts
@@ -1,3 +1,5 @@
+import * as v from 'valibot'
+
import {
createSticky,
isWideSticky,
@@ -9,11 +11,12 @@ import {
type SceneGraph,
type SceneNode
} from '@open-pencil/scene-graph'
-import { colorToHex, parseColor } from '@open-pencil/scene-graph/color'
+import { colorToHex, tryParseColor } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { STICKY_TEXT_SIZE } from './enums'
-import type { TreeNode } from './tree'
+import { enumProp, STICKY_TEXT_SIZE } from './enums'
+import { plainTextOf, type TreeNode } from './tree'
+import { PlacedOwnLayerProps, readElementProps } from './validation'
/**
* `<Sticky color="yellow" author="Ada">Body</Sticky>`: a FigJam sticky note, made from the same
@@ -28,22 +31,45 @@ function isStickyColorName(value: string): value is StickyColorName {
}
/** A palette name such as `"yellow"`, or any colour. */
-function colorOf(value: unknown): Color | undefined {
- if (typeof value !== 'string') return undefined
- return isStickyColorName(value) ? { ...STICKY_COLORS[value] } : parseColor(value)
-}
+const StickyColor = v.pipe(
+ v.string(),
+ v.rawTransform(({ dataset, addIssue, NEVER }): Color => {
+ const name = dataset.value
+ if (isStickyColorName(name)) return { ...STICKY_COLORS[name] }
+ const color = tryParseColor(name)
+ if (color) return color
+ addIssue({ message: `expected ${Object.keys(STICKY_COLORS).join(', ')}, or a colour` })
+ return NEVER
+ })
+)
-function bodyOf(tree: TreeNode): string {
- return tree.children.filter((child): child is string => typeof child === 'string').join('')
-}
+/** The layer props a note has: those that place it, but no size, fills, or layout. */
+export const StickyLayerProps = PlacedOwnLayerProps
+
+/** The props `<Sticky>` takes: its own, and the few layer props a note has. */
+export const StickyProps = v.object({
+ color: v.optional(StickyColor),
+ author: v.optional(v.string()),
+ authorVisible: v.optional(v.boolean()),
+ wide: v.optional(v.boolean()),
+ textSize: v.optional(enumProp(STICKY_TEXT_SIZE)),
+ scale: v.optional(v.pipe(v.number(), v.gtValue(0))),
+ ...StickyLayerProps.entries
+})
-/** The note an element describes, named by its body as FigJam names a note until renamed. */
-export function renderStickyNode(graph: SceneGraph, tree: TreeNode, parentId: string) {
- const { props } = tree
- const text = bodyOf(tree)
- const author = typeof props.author === 'string' ? props.author : ''
- const parent = graph.getNode(parentId)
- const named = typeof props.name === 'string'
+/**
+ * The note an element describes, with `layer`'s fields; it is named by its body, as FigJam names
+ * a note, until given a name.
+ */
+export function renderStickyNode(
+ graph: SceneGraph,
+ tree: TreeNode,
+ parentId: string,
+ layer: Partial<SceneNode>
+) {
+ const props = readElementProps(StickyProps, tree.props)
+ const text = plainTextOf(tree)
+ const author = props.author ?? ''
const sticky = createSticky(
graph,
parentId,
@@ -51,24 +77,14 @@ export function renderStickyNode(graph: SceneGraph, tree: TreeNode, parentId: st
text,
author,
authorVisible: props.authorVisible !== false && author !== '',
- color: colorOf(props.color),
+ color: props.color,
wide: props.wide === true,
- scale: typeof props.scale === 'number' && props.scale > 0 ? props.scale : 1
+ scale: props.scale ?? 1
},
- {
- name: named ? String(props.name) : text.trim() || 'Sticky',
- autoRename: !named,
- ...(typeof props.x === 'number' && { x: props.x }),
- ...(typeof props.y === 'number' && { y: props.y }),
- ...(props.visible === false && { visible: false }),
- ...(typeof props.opacity === 'number' && { opacity: props.opacity }),
- ...(props.position === 'absolute' &&
- parent?.layoutMode !== 'NONE' && { layoutPositioning: 'ABSOLUTE' as const })
- }
+ { ...layer, name: layer.name ?? (text.trim() || 'Sticky'), autoRename: !layer.name }
)
const body = stickySublayers(graph, sticky)?.body
- const textSize = STICKY_TEXT_SIZE.parse(props.textSize)
- if (body && textSize) graph.updateNode(body.id, stickyBodySizeFields(textSize))
+ if (body && props.textSize) graph.updateNode(body.id, stickyBodySizeFields(props.textSize))
return sticky
}
diff --git a/packages/design-jsx/src/tree.ts b/packages/design-jsx/src/tree.ts
index ee5ad206e..81666be18 100644
--- a/packages/design-jsx/src/tree.ts
+++ b/packages/design-jsx/src/tree.ts
@@ -20,6 +20,14 @@ function inlineFragments(children: (TreeNode | string)[]): (TreeNode | string)[]
)
}
+/**
+ * The text an element holds as children, such as a sticky note's body or a connector's label.
+ * Elements among its children are not text and are skipped.
+ */
+export function plainTextOf(tree: TreeNode): string {
+ return tree.children.filter((child): child is string => typeof child === 'string').join('')
+}
+
export function isTreeNode(x: unknown): x is TreeNode {
if (x === null || typeof x !== 'object') return false
return (
diff --git a/packages/design-jsx/src/validation.ts b/packages/design-jsx/src/validation.ts
index 8a2f7f5bf..56a7feccf 100644
--- a/packages/design-jsx/src/validation.ts
+++ b/packages/design-jsx/src/validation.ts
@@ -1,5 +1,8 @@
+import { mapValues } from 'es-toolkit/object'
import * as v from 'valibot'
+import { isVariable } from './vars'
+
/**
* Parse a value a design JSX script passed, or throw `heading` followed by every problem and
* where it is, as `v.summarize` lists them. Core words tool arguments the same way.
@@ -13,3 +16,73 @@ export function parseScriptInput<S extends v.GenericSchema>(
if (result.success) return result.output
throw new Error(`${heading}:\n${v.summarize(result.issues)}`)
}
+
+/**
+ * The layer props an element that draws its own layer takes, such as a connector's: the
+ * renderer makes them into fields and variable bindings as it does for any layer.
+ */
+export const OwnLayerProps = v.object({
+ name: v.optional(v.string()),
+ key: v.optional(v.unknown()),
+ visible: v.optional(v.boolean()),
+ opacity: v.optional(v.number())
+})
+
+/** `OwnLayerProps` and the props that place a layer in its parent, such as a sticky note's. */
+export const PlacedOwnLayerProps = v.object({
+ ...OwnLayerProps.entries,
+ x: v.optional(v.number()),
+ y: v.optional(v.number()),
+ position: v.optional(v.picklist(['absolute']))
+})
+
+/** The props of an element read one at a time, each of them optional. */
+export type ElementPropsSchema = v.ObjectSchema<v.ObjectEntries, undefined>
+
+/**
+ * The props `schema` takes, read from `props`: one that does not fit is left out as if it were
+ * not set, since the renderer reports it (`elementPropWarnings`) and goes on.
+ */
+export function readElementProps<S extends ElementPropsSchema>(
+ schema: S,
+ props: Readonly<Record<string, unknown>>
+): v.InferOutput<S> {
+ const fitting = mapValues(schema.entries, (entry, key) =>
+ v.is(entry, props[key]) ? props[key] : undefined
+ )
+ return v.parse(schema, fitting)
+}
+
+/** A value as a warning quotes it; one JSON cannot write, such as a BigInt inside it, by its brackets. */
+function quoted(value: unknown): string {
+ if (typeof value === 'string') return `"${value}"`
+ if (typeof value !== 'object' || value === null) return String(value)
+ try {
+ return JSON.stringify(value)
+ } catch {
+ return Array.isArray(value) ? '[…]' : '{…}'
+ }
+}
+
+/** A warning for each prop `props` sets that does not fit `schema`, naming the element. */
+export function elementPropWarnings(
+ schema: ElementPropsSchema,
+ props: Readonly<Record<string, unknown>>,
+ element: string
+): string[] {
+ return Object.entries(schema.entries).flatMap(([key, entry]) => {
+ const value = props[key]
+ // A `designVar()` resolves to its value before the element reads it.
+ if (value === undefined || isVariable(value)) return []
+ const result = v.safeParse(entry, value)
+ if (result.success) return []
+ const [issue] = result.issues
+ const source = `${key} ${quoted(value)} on <${element}> is ignored`
+ // A reader of its own, such as an enum's, names what it takes.
+ if (issue.kind === 'transformation') return [`Unknown ${source}; ${issue.message}.`]
+ // A choice of kinds names them; a single type or bound is Valibot's to name.
+ if (issue.type === 'union' || issue.type === 'custom')
+ return [`Invalid ${source}; ${issue.message}.`]
+ return [`Invalid ${source}; expected ${issue.expected}.`]
+ })
+}
diff --git a/packages/design-jsx/tests/elements.test.ts b/packages/design-jsx/tests/elements.test.ts
index 225916762..e1ac6d876 100644
--- a/packages/design-jsx/tests/elements.test.ts
+++ b/packages/design-jsx/tests/elements.test.ts
@@ -1,9 +1,10 @@
import { describe, expect, test } from 'bun:test'
-import { DESIGN_JSX_ELEMENTS, elementTag } from '#design-jsx/elements'
+import { DESIGN_JSX_ELEMENTS, elementSchema, elementTag } from '#design-jsx/elements'
import { createDesignJSXRenderer } from '#design-jsx/index'
+import { elementPropWarnings } from '#design-jsx/validation'
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { GENERATED_FRAME_TYPES, SceneGraph } from '@open-pencil/scene-graph'
const renderer = createDesignJSXRenderer<never>({
icon: () => Promise.resolve(null),
@@ -29,6 +30,23 @@ describe('design JSX elements', () => {
}
)
+ test('every generated frame is written by an element that reads its props by a schema and draws its own layer', () => {
+ for (const type of GENERATED_FRAME_TYPES) {
+ const element = DESIGN_JSX_ELEMENTS.find((candidate) => candidate.writes?.includes(type))
+ expect(element?.schema).toBeDefined()
+ expect(element?.ownLayer).toBeDefined()
+ }
+ })
+
+ test('a prop value JSON cannot write is still reported', () => {
+ const schema = elementSchema('sticky')
+ expect(schema).toBeDefined()
+ if (!schema) return
+ expect(elementPropWarnings(schema, { wide: { flag: BigInt(1) } }, 'sticky')).toEqual([
+ 'Invalid wide {…} on <sticky> is ignored; expected boolean.'
+ ])
+ })
+
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/scene-graph/src/generated/index.ts b/packages/scene-graph/src/generated/index.ts
index d32215fda..d0d9c732f 100644
--- a/packages/scene-graph/src/generated/index.ts
+++ b/packages/scene-graph/src/generated/index.ts
@@ -13,21 +13,26 @@ import { STICKY_KIND } from './sticky'
* Each type is described once, here; the editor and file formats ask it instead of testing for
* the type.
*/
-const GENERATED_FRAME_KINDS: Partial<Record<NodeType, GeneratedFrameKind>> = {
+const GENERATED_FRAME_KINDS = {
STICKY: STICKY_KIND,
CONNECTOR: CONNECTOR_KIND
-}
+} satisfies Partial<Record<NodeType, GeneratedFrameKind>>
+
+/** The layer types that are generated frames, for tables that must cover each of them. */
+export type GeneratedFrameType = keyof typeof GENERATED_FRAME_KINDS
export const GENERATED_FRAME_TYPES: ReadonlySet<NodeType> = new Set(
- Object.keys(GENERATED_FRAME_KINDS) as NodeType[]
+ Object.keys(GENERATED_FRAME_KINDS) as GeneratedFrameType[]
)
/** 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]
+ return isGeneratedFrame(node) ? GENERATED_FRAME_KINDS[node.type] : undefined
}
-export function isGeneratedFrame(node: Pick<SceneNode, 'type'>): boolean {
+export function isGeneratedFrame<N extends Pick<SceneNode, 'type'>>(
+ node: N
+): node is N & { type: GeneratedFrameType } {
return GENERATED_FRAME_TYPES.has(node.type)
}