@pairdraw/design-jsx 0.0.0-stage → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -2
  3. package/dist/chunks/attributes.js +32 -0
  4. package/dist/chunks/attributes.js.map +1 -0
  5. package/dist/chunks/behaviours/elements.js +321 -0
  6. package/dist/chunks/behaviours/elements.js.map +1 -0
  7. package/dist/chunks/behaviours/render.js +368 -0
  8. package/dist/chunks/behaviours/render.js.map +1 -0
  9. package/dist/chunks/component-properties.js +809 -0
  10. package/dist/chunks/component-properties.js.map +1 -0
  11. package/dist/chunks/components.js +78 -0
  12. package/dist/chunks/components.js.map +1 -0
  13. package/dist/chunks/connectors.js +290 -0
  14. package/dist/chunks/connectors.js.map +1 -0
  15. package/dist/chunks/effects.js +57 -0
  16. package/dist/chunks/effects.js.map +1 -0
  17. package/dist/chunks/elements.js +618 -0
  18. package/dist/chunks/elements.js.map +1 -0
  19. package/dist/chunks/export/behaviours.js +113 -0
  20. package/dist/chunks/export/behaviours.js.map +1 -0
  21. package/dist/chunks/export/bindings.js +273 -0
  22. package/dist/chunks/export/bindings.js.map +1 -0
  23. package/dist/chunks/export/decoration.js +96 -0
  24. package/dist/chunks/export/decoration.js.map +1 -0
  25. package/dist/chunks/export/font.js +17 -0
  26. package/dist/chunks/export/font.js.map +1 -0
  27. package/dist/chunks/export/icons.js +34 -0
  28. package/dist/chunks/export/icons.js.map +1 -0
  29. package/dist/chunks/export/index.js +1390 -0
  30. package/dist/chunks/export/index.js.map +1 -0
  31. package/dist/chunks/fields.js +1065 -0
  32. package/dist/chunks/fields.js.map +1 -0
  33. package/dist/chunks/index.js +438 -0
  34. package/dist/chunks/index.js.map +1 -0
  35. package/dist/chunks/jsx-dev-runtime.js +16 -0
  36. package/dist/chunks/jsx-dev-runtime.js.map +1 -0
  37. package/dist/index.d.ts +543 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +11 -0
  40. package/dist/jsx-dev-runtime.d.ts +2 -0
  41. package/dist/jsx-dev-runtime.js +2 -0
  42. package/dist/jsx-runtime.d.ts +44 -0
  43. package/dist/jsx-runtime.d.ts.map +1 -0
  44. package/dist/jsx-runtime.js +2 -0
  45. package/dist/tree.d.ts +261 -0
  46. package/dist/tree.d.ts.map +1 -0
  47. package/package.json +66 -4
  48. package/src/attributes.ts +30 -0
  49. package/src/behaviours/elements.ts +47 -0
  50. package/src/behaviours/index.ts +253 -0
  51. package/src/behaviours/render.ts +144 -0
  52. package/src/component-properties.ts +428 -0
  53. package/src/components.ts +109 -0
  54. package/src/connectors.ts +316 -0
  55. package/src/definitions.ts +277 -0
  56. package/src/effects.ts +80 -0
  57. package/src/elements.ts +321 -0
  58. package/src/enums.ts +182 -0
  59. package/src/export/behaviours.ts +143 -0
  60. package/src/export/bindings.ts +155 -0
  61. package/src/export/decoration.ts +39 -0
  62. package/src/export/font.ts +25 -0
  63. package/src/export/helpers.ts +75 -0
  64. package/src/export/icons.ts +42 -0
  65. package/src/export/index.ts +297 -0
  66. package/src/export/paint.ts +276 -0
  67. package/src/export/props.ts +369 -0
  68. package/src/export/state.ts +52 -0
  69. package/src/export/text.ts +155 -0
  70. package/src/export/value.ts +99 -0
  71. package/src/export/variables.ts +393 -0
  72. package/src/fields.ts +39 -0
  73. package/src/figjam-text.ts +37 -0
  74. package/src/global.d.ts +4 -0
  75. package/src/helpers.ts +135 -0
  76. package/src/index.ts +155 -0
  77. package/src/jsx-dev-runtime.ts +1 -0
  78. package/src/jsx-runtime.ts +51 -0
  79. package/src/mini-react.ts +23 -0
  80. package/src/overrides/effects.ts +39 -0
  81. package/src/overrides/fills.ts +56 -0
  82. package/src/overrides/state.ts +55 -0
  83. package/src/overrides/strokes.ts +109 -0
  84. package/src/overrides/text.ts +116 -0
  85. package/src/overrides/vector.ts +122 -0
  86. package/src/paints.ts +230 -0
  87. package/src/props-overrides.ts +481 -0
  88. package/src/reconcile.ts +134 -0
  89. package/src/reference/authoring.md +76 -0
  90. package/src/reference/examples.ts +49 -0
  91. package/src/reference.ts +19 -0
  92. package/src/refs.ts +48 -0
  93. package/src/render.ts +147 -0
  94. package/src/renderer.ts +598 -0
  95. package/src/scalar-bindings.ts +36 -0
  96. package/src/schema.ts +213 -0
  97. package/src/services.ts +36 -0
  98. package/src/shapes-with-text.ts +73 -0
  99. package/src/stickies.ts +72 -0
  100. package/src/streaming/index.ts +47 -0
  101. package/src/streaming/literals.ts +82 -0
  102. package/src/streaming/projection.ts +189 -0
  103. package/src/text-content.ts +233 -0
  104. package/src/transform.ts +78 -0
  105. package/src/tree.ts +285 -0
  106. package/src/types.ts +13 -0
  107. package/src/variables/graph.ts +265 -0
  108. package/src/variables/index.ts +124 -0
  109. package/src/variables/props.ts +77 -0
@@ -0,0 +1,76 @@
1
+ # Pairdraw design authoring
2
+
3
+ This reference describes scene creation, not React DOM output. Use the `render` tool for JSX strings, or import `Frame`, `Text`, and other authoring exports from `@pairdraw/design-jsx` and render them with `renderTree` from `@pairdraw/core/design-jsx` in library code. Library exports are not automatically globals in agent `eval`; use only the bindings exposed by that execution environment.
4
+
5
+ ## Composition and layout
6
+
7
+ - `flex="row"` / `flex="col"` enables auto-layout. Use it for content; reserve explicit `x`/`y` or `position="absolute"` for intentional overlays and artwork. Without layout, children share the origin unless positioned.
8
+ - `w` / `h` accept pixels, `"hug"` (content-sized), or `"fill"` (available space in a supported layout parent). Use Hug for notes, cards, and long pages instead of guessing heights. Fixed viewport sizes and artwork geometry are intentional exceptions.
9
+ - `gap` controls spacing. `p`, `px`, `py`, and `pt`/`pr`/`pb`/`pl` control padding; longhands override shorthands. There is no margin shorthand.
10
+ - `justify="start"|"end"|"center"|"between"|"around"` controls the primary axis; `items="start"|"end"|"center"|"stretch"|"baseline"` controls the cross axis. `around` gives each child an equal share of the free space, half on each side, on top of `gap`. Distribution needs available space: `between` and `around` cannot create extra room in a Hug container.
11
+ - `grow` distributes available space. Avoid circular Hug/Fill dependencies and redundant fixed widths on growing children. Keep Fill sizing through intermediate containers that should stretch.
12
+ - For wrapping text in a column, prefer `w="fill"`; fixed-width text can use `textAutoResize="height"`. `maxLines` / `truncate` are intentional truncation, not fixes for accidental overflow.
13
+ - `wrap` and `rowGap` enable wrapped flex rows. `grid`, `columns`, and `rows` enable grid (for example `columns="1fr 200px 1fr"` or `columns="repeat(7, 1fr)"`); tracks are `fr`, pixel lengths, `auto`, `repeat()`, and `minmax()`, which grows like its maximum. Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.
14
+ - `flow="auto"|"ltr"|"rtl"` controls container flow; text `dir` controls writing direction. Preserve these separately.
15
+ - Outside auto-layout, and for `position="absolute"` children, `constraints={{ horizontal, vertical }}` sets how a layer follows its parent's resizing, with Figma's values in lowercase: `"min"`, `"center"`, `"max"`, `"stretch"`, or `"scale"`. `minW`, `maxW`, `minH`, and `maxH` bound a layer's size. `visible={false}` hides a layer and `locked` locks it.
16
+ - Use measured node bounds and the existing `arrange` tool for independent artboards: `pack` for a page of screens, `spread` when generated layers overlap. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.
17
+
18
+ ## Paint, text, and artwork
19
+
20
+ - `bg` / `fill`, `stroke`, and text `color` accept colors and supported variable references. Set colors explicitly for predictable contrast. `fills` accepts structured paints; gradient helpers include `linearGradient`, `radialGradient`, `angularGradient`, and `diamondGradient`, each taking an array of stops and optional `{ opacity, transform }`: `fills={[linearGradient([['#3b82f6', 0], ['#8b5cf6', 1]])]}`. Without a `transform` a linear gradient runs left to right and the others are centred; `transform` is Figma's `gradientTransform`, mapping the layer's unit square onto gradient space. Write it as the plugin API's rows, as export does: `linearGradient(stops, { transform: [[0, 1, 0], [-1, 0, 1]] })` runs top to bottom. A paint written as an object takes its `gradientTransform` and `imageTransform` as rows too; the matrix fields `{ m00, m01, m02, m10, m11, m12 }` are accepted as well.
21
+ - `shader(effects, { opacity, visible, blendMode })` fills a layer with a shader from the [`shaders`](https://shaders.com) library: an array of effects such as `bg={shader([{ type: 'Aurora', props: { speed: 2 } }])}`, or a preset as shaders.com exports it, `{ components: [...] }`. The canvas shows the shader's first frame, preview plays it, and files and other formats keep that frame as an image.
22
+ - `shaderSource(code, { uniforms, opacity, visible, blendMode })` fills a layer with shader code written here rather than a preset; `uniforms` gives the values its `@directive` inputs start with, such as `bg={shaderSource(code, { uniforms: { u_color: '#ff0000' } })}`.
23
+ - `stroke` describes one stroke, refined by `strokeWidth`, `strokeAlign` (`"inside"`, `"center"`, `"outside"`), `strokeDash`, `strokeCap`, and `strokeJoin`. `strokes` takes several, as objects with `color`, `weight`, `align`, `dash`, `cap`, `join`, and `visible`; `strokeWeights={{ top, right, bottom, left }}` sets per-side widths. `dashPattern` sets the node's own dash pattern, separate from the per-stroke `strokeDash`.
24
+ - `rounded` and `roundedTL`/`roundedTR`/`roundedBL`/`roundedBR` control corners. `strokeWidth`, `opacity`, `rotate`, and `blendMode` control appearance. `overflow="hidden"` clips content; do not hide accidental text overflow to make a broken layout appear correct.
25
+ - `rotate` turns a layer by degrees, and `flipX` and `flipY` reflect it across its centre before it turns, as the canvas places it. `Star` takes `points` and `innerRadius` (0–1, how deep its points go); `Polygon` takes `points`. `Ellipse` draws an arc or a donut with `startAngle` and `endAngle` in degrees, clockwise from three o'clock (0 to 360 by default), and `innerRadius` (0–1, the hole): `<Ellipse w={80} h={80} startAngle={0} endAngle={270} innerRadius={0.6} />`.
26
+ - `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow` takes a CSS `box-shadow` list, such as `shadow="0 4 8 #0002, inset 0 1 0 #fff"`, and `blur` a layer blur radius; both are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.
27
+ - Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `fontFeatures` turns OpenType features on or off by tag (`fontFeatures={{ tnum: true, liga: false }}`), `fontVariations` sets variable-font axes by tag (`fontVariations={{ wght: 650 }}`), and `lang` names the text's language (`lang="de"`) for shaping and font fallback. A variable font's optical size follows the font size unless `fontOpticalSizing="none"`, as in CSS; only then does an `opsz` in `fontVariations` apply. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.
28
+ - `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, `fontFeatures`, `fontVariations`, `lang`, and `textCase`; a span's `fontFeatures` and `fontVariations` replace the text's rather than adding to them, and `fontOpticalSizing` is set on the `Text` for all of it. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.
29
+ - `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.
30
+ - Pick artwork by where it comes from. A known icon is an `Icon` by its Iconify name. A shape you draw yourself is a `Vector` with its path in SVG syntax, `<Vector d="M11 2L4 11h5l-1 7 7-9h-5z" bg={designVar(…)} />`: one layer, styled with the same props as any other, so its fills can use variables, stack, and take `strokeAlign` and `effects`. `fillRule="evenodd"` cuts holes. An open path with a `stroke` stays open, a line; with only a `bg` it fills as if closed. Given `w` and `h`, the path is drawn in that box as written, as an icon is in its view box; without them the layer fits the path. `paths` takes several paths as export writes them, each `{ windingRule, data }` with `NONZERO`, `EVENODD`, or `NONE` for an open path: `paths={[{ windingRule: "EVENODD", data: "M0 0L10 0L10 10Z" }]}`. Inline `<svg>` is for artwork copied from elsewhere: it draws the SVG's shapes, a frame with a layer per shape in the SVG's own colours, and leaves out its text, so do not use it for a shape you will style or bind, nor for text.
31
+ - `Sticky` makes a FigJam sticky note whose text is its body: `<Sticky color="yellow" author="Ada">Ship it</Sticky>`. `color` takes a FigJam palette name (`white`, `gray`, `red`, `orange`, `yellow`, `green`, `teal`, `blue`, `violet`, `pink`) or any colour, `author` signs it (`authorVisible={false}` hides the line), `wide` makes it 416 wide instead of 240, `textSize` is `small`, `medium`, `large`, `extraLarge`, or `huge`, `typeface` is `simple`, `bookish`, `technical`, or `scribbled`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.
32
+ - `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind="diamond" bg="#FFC943">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows taller to fit its label, never wider, so a word too long for it breaks. `truncate` keeps its height and cuts the label off with "…" instead, as FigJam does once a shape's height is set. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.
33
+ - `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.
34
+ - Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.
35
+
36
+ ## Variables and components
37
+
38
+ - `defineVars('Theme', { Page: '#FFFFFF', Radius: 12 }, { mode: 'Light' })` defines a collection in the file's variables table and returns its variables by name, such as `theme.Page`. Each value is the variable's value in the first mode, named by `mode` (`Mode 1` without one): strings are colors, numbers FLOAT, booleans BOOLEAN, and another collection's variable makes an alias, such as `palette['Gray/900']`. `defineMode(theme, 'Dark', { Page: '#111111' })` adds a mode with the values that differ; the rest keep the first mode's. A render that binds any of the variables creates the collection with all its modes, or updates the one with that name, so running the JSX again changes values instead of adding collections.
39
+ - `designVar('name-or-id')` refers to a variable the document already has; a missing one is an error. When more than one collection has a variable of that name, name the collection too, as `designMode` does: `designVar('Theme', 'Line')`.
40
+ - COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings; the one exception is `lineHeight` and `letterSpacing`, which also take a percent of the font size such as `"150%"` that follows the size when it changes.
41
+ - `mode={dark}` shows a layer and its children in a mode, as the Appearance panel's variable mode control does; a list pins several collections, and `designMode('Theme', 'Dark')` names a mode of a collection the document already has, by the collection's ID when several share its name. Without `mode`, a layer inherits its parent's.
42
+ - Variables bind real graph fields, not copied values. Layout resolves scalar variables in the mode the layer is created in, its own or inherited; it does not lay content out again after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
43
+ - `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.
44
+ - Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.
45
+ - A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.
46
+ - `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.
47
+ - `property(name, defaultValue)` binds a field of a component's layer to a component property, created on first use: `text={property('Message', 'Hi')}` on a `Text` makes a TEXT property, `visible={property('Pinned', true)}` a BOOLEAN one, and `of={property('Icon', 'Star')}` on an `Instance` an INSTANCE_SWAP one whose default is the component `of` names. The property belongs to the nearest `Component`, or to its `ComponentSet` for a variant, so the same name in each variant binds one property; one name with two types or two defaults is an error.
48
+ - An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Only instances accept `properties`.
49
+ - `exposed` on an `Instance` in a component shows that instance's own properties on the component's instances, as Figma's "Expose properties from nested instances" does; the instance's component needs properties to expose. An outer instance gives an exposed instance its variant and properties as an object under the exposed layer's name: `<Instance of="Card" Title="Welcome" Action={{ Variant: 'Secondary', Label: 'Save' }} />`, or `properties={{ Action: { … } }}`.
50
+ - Instance assignments take `true` / `false` or the native `'true'` / `'false'` for BOOLEAN properties, and a component's name or ID for swaps, as `of` does, whether set as a prop or in `properties`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.
51
+ - Reuse existing local or library components before recreating them. Keep meaningful text, visibility, and swap properties exposed rather than hand-editing cloned child nodes.
52
+ - Explicit instance `w` / `h` replace the inherited sizing mode on that axis; omitted dimensions retain the main component's sizing. Authored overrides survive component synchronization. Distinguish those placement constraints from the main component's default size, and verify actual bounds in narrower parents. Do not compensate for a sizing mismatch with guessed heights, clipping, or manually positioned siblings.
53
+
54
+ ## Controls
55
+
56
+ - A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Track`, `Progress.Indicator`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.
57
+ - The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.
58
+ - `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.
59
+ - A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.
60
+
61
+ ```tsx
62
+ <Switch.Root name="Switch" modelValue="State" states="Interaction">
63
+ <Component name="State=Off, Interaction=Default" w={44} h={24} rounded={12} bg="#D0D4DA">
64
+ <Switch.Thumb x={2} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />
65
+ </Component>
66
+ <Component name="State=On, Interaction=Default" w={44} h={24} rounded={12} bg="#3B6CF6">
67
+ <Switch.Thumb x={22} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />
68
+ </Component>
69
+ </Switch.Root>
70
+ ```
71
+
72
+ ## Verification
73
+
74
+ Inspect structure and actual rendered output. Node counts and `describe` diagnostics do not establish visual fidelity. Check wrapping with longer content, narrower containers, component edits, and relevant modes. Resolve overflow and contrast problems at their source. Reuse IDs returned by creation tools rather than repeatedly searching for the same nodes.
75
+
76
+ The examples below are executed by the authoring-reference tests. Create the named variables before running a variable-bound example.
@@ -0,0 +1,49 @@
1
+ import dedent from 'dedent'
2
+
3
+ export interface AuthoringExample {
4
+ title: string
5
+ jsx: string
6
+ }
7
+
8
+ /** Shared verbatim by runtime prompts and the installable skill; exercised in engine tests. */
9
+ export const AUTHORING_EXAMPLES: readonly AuthoringExample[] = [
10
+ {
11
+ title: 'Content-sized review note',
12
+ jsx: dedent`<Frame name="Review note" w={280} h="hug" flex="col" gap={8} p={16} bg="#FFFFFF">
13
+ <Text name="Author" size={12} weight="medium" color="#252A31">June Lee</Text>
14
+ <Text name="Message" w="fill" size={12} color="#6B7079">Give the date a little more room at the bottom.</Text>
15
+ </Frame>`
16
+ },
17
+ {
18
+ title: 'Variable-bound spacing and typography',
19
+ jsx: dedent`<Frame name="Bound note" w={280} h="hug" flex="col" gap={designVar('Space/small')} p={designVar('Space/medium')} bg="#FFFFFF">
20
+ <Text name="Message" w="fill" size={designVar('Type/body')} lineHeight={designVar('Type/body-leading')} letterSpacing={designVar('Type/body-tracking')} color="#252A31">A note that grows with its content.</Text>
21
+ </Frame>`
22
+ },
23
+ {
24
+ title: 'A theme with two modes',
25
+ jsx: dedent`const theme = defineVars('Theme', { Surface: '#FFFFFF', Ink: '#252A31', Radius: 12 }, { mode: 'Light' })
26
+ const dark = defineMode(theme, 'Dark', { Surface: '#1A1A20', Ink: '#F5F5F7' })
27
+ return <Frame name="Dark note" mode={dark} w={280} h="hug" flex="col" gap={8} p={16} bg={theme.Surface} rounded={theme.Radius}>
28
+ <Text name="Message" w="fill" size={12} color={theme.Ink}>Shown in the Dark mode of the Theme collection.</Text>
29
+ </Frame>`
30
+ },
31
+ {
32
+ title: 'Component with text and visibility properties',
33
+ jsx: dedent`<Component name="Comment" w={280} h="hug" flex="col" gap={8} p={16} bg="#FFFFFF">
34
+ <Text name="Author" size={12} weight="medium" color="#252A31" text={property('Author', 'June Lee')} />
35
+ <Text name="Message" w="fill" size={12} color="#6B7079" text={property('Message', 'Give the date more room.')} visible={property('Show message', true)} />
36
+ </Component>`
37
+ },
38
+ {
39
+ title: 'Rich text with spans and lists',
40
+ jsx: dedent`<Frame name="Release notes" w={280} h="hug" flex="col" gap={8} p={16} bg="#FFFFFF">
41
+ <Text name="Notes" w="fill" size={12} color="#252A31" paragraphSpacing={4}>
42
+ <Paragraph spacing={8}>Version 2 is <Span weight="bold" color="#3B6CF6" textDecoration="underline" textDecorationStyle="wavy" textUnderlineOffset={2}>out now</Span>.</Paragraph>
43
+ <Paragraph list="unordered">Faster export</Paragraph>
44
+ <Paragraph list="unordered" level={2}>PDF and SVG</Paragraph>
45
+ <Paragraph list="ordered">Fewer clicks</Paragraph>
46
+ </Text>
47
+ </Frame>`
48
+ }
49
+ ]
@@ -0,0 +1,19 @@
1
+ import { DESIGN_JSX_SUPPORTED_PROPERTY_NAMES } from './definitions'
2
+ import { DESIGN_JSX_ELEMENTS } from './elements'
3
+ import { DESIGN_JSX_HELPERS } from './helpers'
4
+ import authoring from './reference/authoring.md?raw'
5
+ import { AUTHORING_EXAMPLES } from './reference/examples'
6
+
7
+ export { AUTHORING_EXAMPLES, type AuthoringExample } from './reference/examples'
8
+
9
+ /** Canonical scene-authoring guidance shared by runtime prompts and generated skill references. */
10
+ export const JSX_REFERENCE = [
11
+ authoring.trim(),
12
+ // Examples are written verbatim; dedenting them again would flatten their nesting.
13
+ ...AUTHORING_EXAMPLES.map(({ title, jsx }) => `## ${title}\n\n\`\`\`jsx\n${jsx}\n\`\`\``),
14
+ '## Supported syntax inventory',
15
+ 'Generated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.',
16
+ `**Elements:** ${DESIGN_JSX_ELEMENTS.map(({ name }) => `\`${name}\``).join(', ')}.`,
17
+ `**Helpers:** ${DESIGN_JSX_HELPERS.map(({ name }) => `\`${name}\``).join(', ')}.`,
18
+ `**Properties:** ${DESIGN_JSX_SUPPORTED_PROPERTY_NAMES.map((name) => `\`${name}\``).join(', ')}.`
19
+ ].join('\n\n')
package/src/refs.ts ADDED
@@ -0,0 +1,48 @@
1
+ import type { SceneNode } from '@pairdraw/scene-graph'
2
+
3
+ const REF_SYMBOL = Symbol.for('pairdraw.layer-ref')
4
+
5
+ /**
6
+ * A handle on one layer of the JSX: `ref={card}` marks the layer, and an element that refers to
7
+ * a layer, such as `<Connector from={card}>`, takes the handle where a name could be ambiguous.
8
+ */
9
+ export interface LayerRef {
10
+ readonly [REF_SYMBOL]: true
11
+ }
12
+
13
+ /** A new handle for `ref={…}` to mark a layer with. */
14
+ export function ref(): LayerRef {
15
+ return Object.freeze({ [REF_SYMBOL]: true as const })
16
+ }
17
+
18
+ export function isLayerRef(value: unknown): value is LayerRef {
19
+ return typeof value === 'object' && value !== null && REF_SYMBOL in value
20
+ }
21
+
22
+ /** The layers a render marked with `ref={…}`, for the elements that refer to them. */
23
+ export class LayerRefs {
24
+ readonly warnings: string[] = []
25
+ private readonly layers = new Map<LayerRef, SceneNode>()
26
+
27
+ /** Marks `node` with the `ref` prop its element passed, if any. */
28
+ mark(value: unknown, node: SceneNode) {
29
+ if (value === undefined) return
30
+ if (!isLayerRef(value)) {
31
+ this.warnings.push(`ref on "${node.name}" is not a ref() and is ignored.`)
32
+ return
33
+ }
34
+ const first = this.layers.get(value)
35
+ if (first) {
36
+ this.warnings.push(
37
+ `One ref() marks both "${first.name}" and "${node.name}"; it refers to "${first.name}".`
38
+ )
39
+ return
40
+ }
41
+ this.layers.set(value, node)
42
+ }
43
+
44
+ /** The id of the layer `ref` marks, if one does. */
45
+ layerOf(ref: LayerRef): string | undefined {
46
+ return this.layers.get(ref)?.id
47
+ }
48
+ }
package/src/render.ts ADDED
@@ -0,0 +1,147 @@
1
+ import { uniq } from 'es-toolkit/array'
2
+
3
+ import type { SceneGraph } from '@pairdraw/scene-graph'
4
+
5
+ import { REKA_ELEMENTS } from './behaviours'
6
+ import { elementBindings, elementProps, elementSchema } from './elements'
7
+ import { ENUM_PROPS } from './enums'
8
+ import { DESIGN_JSX_HELPERS, designJSXHelpers } from './helpers'
9
+ import * as React from './mini-react'
10
+ import { renderRoots, renderTree, componentPropNames, type RenderResult } from './renderer'
11
+ import { elementPropWarnings } from './schema'
12
+ import type { DesignJSXServices } from './services'
13
+ import { TEXT_CONTENT_NAMES } from './text-content'
14
+ import { transformDesignJSXExpression } from './transform'
15
+ import { isTreeNode, resolveToTree, type TreeNode } from './tree'
16
+ import type { RenderOptions as RenderJSXOptions } from './types'
17
+
18
+ /** `const Switch = { Root: 'Switch.Root', … }`: each Reka namespace as element types. */
19
+ const REKA_ALIASES = Object.entries(REKA_ELEMENTS)
20
+ .map(
21
+ ([namespace, parts]) =>
22
+ `const ${namespace} = ${JSON.stringify(
23
+ Object.fromEntries(Object.keys(parts).map((part) => [part, `${namespace}.${part}`]))
24
+ )}`
25
+ )
26
+ .join('\n')
27
+
28
+ /** `const solid = __helpers.solid`, …: every helper in the scope of the code. */
29
+ const HELPER_BINDINGS = DESIGN_JSX_HELPERS.map(
30
+ ({ name }) => `const ${name} = __helpers.${name}`
31
+ ).join('\n')
32
+
33
+ function stripHTMLComments(jsxString: string): string {
34
+ return jsxString.replace(/<!--[\s\S]*?-->/g, '')
35
+ }
36
+
37
+ function unsupportedPropWarnings(graph: SceneGraph, tree: TreeNode): string[] {
38
+ const warnings: string[] = []
39
+ collectUnsupportedPropWarnings(graph, tree, warnings)
40
+ return warnings
41
+ }
42
+
43
+ function collectUnsupportedPropWarnings(
44
+ graph: SceneGraph,
45
+ tree: TreeNode,
46
+ warnings: string[]
47
+ ): void {
48
+ const supported = elementProps(tree.type)
49
+ // An instance sets its component's properties by name, such as `State="On"` or `Title="Hi"`.
50
+ const properties = componentPropNames(graph, tree.props)
51
+ const element = TEXT_CONTENT_NAMES[tree.type] ?? tree.type
52
+ const schema = elementSchema(tree.type)
53
+ if (schema) warnings.push(...elementPropWarnings(schema, tree.props, element))
54
+ for (const [key, value] of Object.entries(tree.props)) {
55
+ if (!supported.has(key) && !properties.includes(key)) {
56
+ warnings.push(`Unsupported prop "${key}" on <${element}> is ignored.`)
57
+ continue
58
+ }
59
+ const values = ENUM_PROPS[key]
60
+ if (values && typeof value === 'string' && values.parse(value) === undefined) {
61
+ warnings.push(
62
+ `Unknown ${key} "${value}" on <${element}> is ignored; expected ${values.names.join(', ')}.`
63
+ )
64
+ }
65
+ }
66
+
67
+ // SVG descendants are parsed as markup by renderSvgNode, not as Design JSX nodes.
68
+ if (tree.type === 'svg') return
69
+
70
+ for (const child of tree.children) {
71
+ if (isTreeNode(child)) collectUnsupportedPropWarnings(graph, child, warnings)
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Build a component function from a JSX string: one JSX expression, sibling elements, or
77
+ * statements that end with `return` and the JSX. The statements run inside the component, so
78
+ * they may shadow an element or helper name. Works in both Node/Bun and the browser.
79
+ */
80
+ export function buildComponent(jsxString: string, warnings: string[] = []): React.ComponentType {
81
+ const trimmed = stripHTMLComments(jsxString).trim()
82
+
83
+ const aliases = `
84
+ const __h = React.createElement
85
+ const __fragment = ''
86
+ ${elementBindings()}
87
+ const svg = 'svg'
88
+ ${REKA_ALIASES}
89
+ ${HELPER_BINDINGS}
90
+ `
91
+
92
+ const body = transformDesignJSXExpression(trimmed)
93
+ // eslint-disable-next-line typescript-eslint/no-implied-eval -- sucrase output must be evaluated at runtime
94
+ return new Function('React', '__helpers', `${aliases}\nreturn function __render() {\n${body}\n}`)(
95
+ React,
96
+ designJSXHelpers(warnings)
97
+ ) as React.ComponentType
98
+ }
99
+
100
+ /**
101
+ * Render a JSX string into the scene graph.
102
+ * Works in both Node/Bun and the browser.
103
+ */
104
+ async function renderJSX<Artwork>(
105
+ services: DesignJSXServices<Artwork>,
106
+ graph: SceneGraph,
107
+ jsxString: string,
108
+ options?: RenderJSXOptions
109
+ ): Promise<RenderResult[]> {
110
+ const helperWarnings: string[] = []
111
+ const Component = buildComponent(jsxString, helperWarnings)
112
+ const element = React.createElement(Component, null)
113
+ const tree = resolveToTree(element)
114
+
115
+ if (!tree) {
116
+ throw new Error('JSX must return a Figma element (Frame, Text, etc)')
117
+ }
118
+
119
+ const results = await renderRoots(services, graph, tree, options)
120
+ // After rendering, so an instance's component set drawn in the same JSX names its variants.
121
+ // A helper called in a loop reports each ignored option once.
122
+ // Prop warnings come first, then the render's own, such as a connector end naming no layer.
123
+ const warnings = uniq([
124
+ ...unsupportedPropWarnings(graph, tree),
125
+ ...helperWarnings,
126
+ ...(results[0].warnings ?? [])
127
+ ])
128
+ if (warnings.length > 0) results[0].warnings = warnings
129
+ return results
130
+ }
131
+
132
+ /**
133
+ * A Design JSX renderer bound to an engine. Rendering needs `services` for icons, inline
134
+ * SVG, and layout; Pairdraw's engine provides them through `@pairdraw/core/design-jsx`.
135
+ */
136
+ export function createDesignJSXRenderer<Artwork>(services: DesignJSXServices<Artwork>) {
137
+ return {
138
+ /** Render a Design JSX string into the graph, one result per top-level element. */
139
+ renderJSX: (graph: SceneGraph, jsxString: string, options?: RenderJSXOptions) =>
140
+ renderJSX(services, graph, jsxString, options),
141
+ /** Render a tree built with the element functions into the graph. */
142
+ renderTree: (graph: SceneGraph, tree: TreeNode, options?: RenderJSXOptions) =>
143
+ renderTree(services, graph, tree, options)
144
+ }
145
+ }
146
+
147
+ export type DesignJSXRenderer = ReturnType<typeof createDesignJSXRenderer>