@pairdraw/design-jsx 0.0.0-stage → 0.16.0

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 +54 -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
package/src/schema.ts ADDED
@@ -0,0 +1,213 @@
1
+ import { mapValues } from 'es-toolkit/object'
2
+ import * as v from 'valibot'
3
+
4
+ import { tryParseColor } from '@pairdraw/scene-graph/color'
5
+ import { STICKY_COLORS } from '@pairdraw/scene-graph/generated'
6
+ import type { Color } from '@pairdraw/scene-graph/primitives'
7
+
8
+ import {
9
+ CONNECTOR_LINE,
10
+ CONNECTOR_SIDE,
11
+ enumProp,
12
+ FIGJAM_TEXT_SIZE,
13
+ FIGJAM_TYPEFACE,
14
+ SHAPE_KIND,
15
+ STROKE_ALIGN,
16
+ STROKE_CAP,
17
+ STROKE_JOIN
18
+ } from './enums'
19
+ import { isColor, isFillValue } from './overrides/fills'
20
+ import { isStrokeValue } from './overrides/strokes'
21
+ import { isLayerRef, type LayerRef } from './refs'
22
+ import { isVariable } from './variables'
23
+
24
+ /**
25
+ * Parse a value a design JSX script passed, or throw `heading` followed by every problem and
26
+ * where it is, as `v.summarize` lists them. Core words tool arguments the same way.
27
+ */
28
+ export function parseScriptInput<S extends v.GenericSchema>(
29
+ heading: string,
30
+ schema: S,
31
+ value: unknown
32
+ ): v.InferOutput<S> {
33
+ const result = v.safeParse(schema, value)
34
+ if (result.success) return result.output
35
+ throw new Error(`${heading}:\n${v.summarize(result.issues)}`)
36
+ }
37
+
38
+ /**
39
+ * The layer props an element that draws its own layer takes, such as a connector's: the
40
+ * renderer makes them into fields and variable bindings as it does for any layer.
41
+ */
42
+ export const ownLayerPropsSchema = v.object({
43
+ name: v.optional(v.string()),
44
+ key: v.optional(v.unknown()),
45
+ visible: v.optional(v.boolean()),
46
+ opacity: v.optional(v.number())
47
+ })
48
+
49
+ /** `OwnLayerProps` and the props that place a layer in its parent, such as a sticky note's. */
50
+ export const placedOwnLayerPropsSchema = v.object({
51
+ ...ownLayerPropsSchema.entries,
52
+ x: v.optional(v.number()),
53
+ y: v.optional(v.number()),
54
+ position: v.optional(v.picklist(['absolute']))
55
+ })
56
+
57
+ /** A colour as a string, or as the colour a `designVar()` resolves to. */
58
+ const colorPropSchema = v.union(
59
+ [
60
+ v.pipe(
61
+ v.string(),
62
+ v.rawTransform(({ dataset, addIssue, NEVER }): Color => {
63
+ const color = tryParseColor(dataset.value)
64
+ if (color) return color
65
+ addIssue({ message: 'expected a colour' })
66
+ return NEVER
67
+ })
68
+ ),
69
+ v.custom<Color>(isColor)
70
+ ],
71
+ 'expected a colour'
72
+ )
73
+
74
+ /** The props of an element read one at a time, each of them optional. */
75
+ export type ElementPropsSchema = v.ObjectSchema<v.ObjectEntries, undefined>
76
+
77
+ /**
78
+ * The props `schema` takes, read from `props`: one that does not fit is left out as if it were
79
+ * not set, since the renderer reports it (`elementPropWarnings`) and goes on.
80
+ */
81
+ export function readElementProps<S extends ElementPropsSchema>(
82
+ schema: S,
83
+ props: Readonly<Record<string, unknown>>
84
+ ): v.InferOutput<S> {
85
+ const fitting = mapValues(schema.entries, (entry, key) =>
86
+ v.is(entry, props[key]) ? props[key] : undefined
87
+ )
88
+ return v.parse(schema, fitting)
89
+ }
90
+
91
+ /** A value as a warning quotes it; one JSON cannot write, such as a BigInt inside it, by its brackets. */
92
+ function quoted(value: unknown): string {
93
+ if (typeof value === 'string') return `"${value}"`
94
+ if (typeof value !== 'object' || value === null) return String(value)
95
+ try {
96
+ return JSON.stringify(value)
97
+ } catch {
98
+ return Array.isArray(value) ? '[…]' : '{…}'
99
+ }
100
+ }
101
+
102
+ /** A warning for each prop `props` sets that does not fit `schema`, naming the element. */
103
+ export function elementPropWarnings(
104
+ schema: ElementPropsSchema,
105
+ props: Readonly<Record<string, unknown>>,
106
+ element: string
107
+ ): string[] {
108
+ return Object.entries(schema.entries).flatMap(([key, entry]) => {
109
+ const value = props[key]
110
+ // A `designVar()` resolves to its value before the element reads it.
111
+ if (value === undefined || isVariable(value)) return []
112
+ const result = v.safeParse(entry, value)
113
+ if (result.success) return []
114
+ const [issue] = result.issues
115
+ const source = `${key} ${quoted(value)} on <${element}> is ignored`
116
+ // A reader of its own, such as an enum's, names what it takes.
117
+ if (issue.kind === 'transformation') return [`Unknown ${source}; ${issue.message}.`]
118
+ // A choice of kinds names them; a single type or bound is Valibot's to name.
119
+ if (issue.type === 'union' || issue.type === 'custom')
120
+ return [`Invalid ${source}; ${issue.message}.`]
121
+ return [`Invalid ${source}; expected ${issue.expected}.`]
122
+ })
123
+ }
124
+
125
+ /** A layer of the same JSX by name or `ref()`, or a point in the connector's parent. */
126
+ const connectorEndSchema = v.union(
127
+ [v.string(), v.custom<LayerRef>(isLayerRef), v.object({ x: v.number(), y: v.number() })],
128
+ 'expected a layer name, a ref(), or { x, y }'
129
+ )
130
+
131
+ /** The props `<Connector>` takes: its own, and the layer props that style its line. */
132
+ export const connectorPropsSchema = v.object({
133
+ from: v.optional(connectorEndSchema),
134
+ to: v.optional(connectorEndSchema),
135
+ fromSide: v.optional(enumProp(CONNECTOR_SIDE)),
136
+ toSide: v.optional(enumProp(CONNECTOR_SIDE)),
137
+ line: v.optional(enumProp(CONNECTOR_LINE)),
138
+ startCap: v.optional(enumProp(STROKE_CAP)),
139
+ endCap: v.optional(enumProp(STROKE_CAP)),
140
+ ...ownLayerPropsSchema.entries,
141
+ stroke: v.optional(colorPropSchema),
142
+ strokeWidth: v.optional(v.pipe(v.number(), v.gtValue(0))),
143
+ dashPattern: v.optional(v.array(v.number()))
144
+ })
145
+
146
+ const sizeSchema = v.pipe(v.number(), v.gtValue(0))
147
+ const dashSchema = v.array(v.number())
148
+
149
+ /**
150
+ * The layer props a shape has: its place, the size it is given, which it grows past to fit its
151
+ * label, and its paint. The label is styled as FigJam styles it, and the shape lays it out.
152
+ */
153
+ export const shapeLayerPropsSchema = v.object({
154
+ ...placedOwnLayerPropsSchema.entries,
155
+ w: v.optional(sizeSchema),
156
+ h: v.optional(sizeSchema),
157
+ rotate: v.optional(v.number()),
158
+ rounded: v.optional(v.pipe(v.number(), v.minValue(0))),
159
+ bg: v.optional(v.custom(isFillValue, 'expected a colour or a paint')),
160
+ fills: v.optional(v.array(v.custom(isFillValue, 'expected a colour or a paint'))),
161
+ stroke: v.optional(colorPropSchema),
162
+ strokeWidth: v.optional(sizeSchema),
163
+ strokeAlign: v.optional(enumProp(STROKE_ALIGN)),
164
+ strokeDash: v.optional(dashSchema),
165
+ strokes: v.optional(v.array(v.custom(isStrokeValue, 'expected a stroke'))),
166
+ strokeCap: v.optional(enumProp(STROKE_CAP)),
167
+ strokeJoin: v.optional(enumProp(STROKE_JOIN)),
168
+ dashPattern: v.optional(dashSchema)
169
+ })
170
+
171
+ /**
172
+ * The props `<Shape>` takes: its kind, whether it keeps its height and truncates its label as a
173
+ * resized FigJam shape does, and the layer props a shape has.
174
+ */
175
+ export const shapePropsSchema = v.object({
176
+ kind: v.optional(enumProp(SHAPE_KIND)),
177
+ truncate: v.optional(v.boolean()),
178
+ textSize: v.optional(enumProp(FIGJAM_TEXT_SIZE)),
179
+ typeface: v.optional(enumProp(FIGJAM_TYPEFACE)),
180
+ ...shapeLayerPropsSchema.entries
181
+ })
182
+
183
+ type StickyColorName = keyof typeof STICKY_COLORS
184
+
185
+ function isStickyColorName(value: string): value is StickyColorName {
186
+ return value in STICKY_COLORS
187
+ }
188
+
189
+ /** A palette name such as `"yellow"`, or any colour. */
190
+ const stickyColorSchema = v.pipe(
191
+ v.string(),
192
+ v.rawTransform(({ dataset, addIssue, NEVER }): Color => {
193
+ const name = dataset.value
194
+ if (isStickyColorName(name)) return { ...STICKY_COLORS[name] }
195
+ const color = tryParseColor(name)
196
+ if (color) return color
197
+ addIssue({ message: `expected ${Object.keys(STICKY_COLORS).join(', ')}, or a colour` })
198
+ return NEVER
199
+ })
200
+ )
201
+
202
+ /** The props `<Sticky>` takes: its own, and the few layer props a note has. */
203
+ export const stickyPropsSchema = v.object({
204
+ color: v.optional(stickyColorSchema),
205
+ author: v.optional(v.string()),
206
+ authorVisible: v.optional(v.boolean()),
207
+ wide: v.optional(v.boolean()),
208
+ textSize: v.optional(enumProp(FIGJAM_TEXT_SIZE)),
209
+ typeface: v.optional(enumProp(FIGJAM_TYPEFACE)),
210
+ scale: v.optional(v.pipe(v.number(), v.gtValue(0))),
211
+ // A note takes the props that place it, but no size, fills, or layout.
212
+ ...placedOwnLayerPropsSchema.entries
213
+ })
@@ -0,0 +1,36 @@
1
+ import type { SceneGraph, SceneNode, VectorNetwork } from '@pairdraw/scene-graph'
2
+ import type { Color, Rect } from '@pairdraw/scene-graph/primitives'
3
+
4
+ import type { TreeNode } from './tree'
5
+
6
+ /** Inline `<svg>` content: markup, parsed shape elements, or both, with the element's props. */
7
+ export interface SVGSource {
8
+ body: string
9
+ elements: TreeNode[]
10
+ props: Record<string, unknown>
11
+ }
12
+
13
+ /** Where to put artwork and how to size and color it. */
14
+ export interface ArtworkPlacement {
15
+ parentId: string
16
+ size: number
17
+ color: Color
18
+ overrides: Partial<SceneNode>
19
+ }
20
+
21
+ /**
22
+ * Engine work the renderer delegates. `Artwork` is whatever the engine uses to describe
23
+ * vector paths; the renderer only passes it from `icon`/`svg` to `createArtwork`.
24
+ */
25
+ export interface DesignJSXServices<Artwork> {
26
+ /** A named icon such as `lucide:heart` at `size`, or null when it does not exist. */
27
+ icon(name: string, size: number): Promise<Artwork | null>
28
+ /** Inline SVG scaled to `size`, or null when it has no supported shapes. */
29
+ svg(source: SVGSource, size: number): Artwork | null
30
+ /** Vector nodes for the artwork, created under the placement's parent. */
31
+ createArtwork(graph: SceneGraph, artwork: Artwork, placement: ArtworkPlacement): SceneNode
32
+ /** Size and lay out the rendered roots once they are in place. */
33
+ layout(graph: SceneGraph, rootIds: readonly string[]): void
34
+ /** The tight bounds of a vector network, its curves included, which size a `<Vector>`. */
35
+ vectorBounds(network: VectorNetwork): Rect
36
+ }
@@ -0,0 +1,73 @@
1
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
2
+ import {
3
+ createShapeWithText,
4
+ SHAPE_WITH_TEXT_CORNER_RADIUS,
5
+ SHAPE_WITH_TEXT_SIZE,
6
+ shapeWithTextLabel
7
+ } from '@pairdraw/scene-graph/generated'
8
+
9
+ import { SHAPE_KIND } from './enums'
10
+ import { collectFillProps, collectStrokeProps } from './export/paint'
11
+ import type { JSXProp } from './export/value'
12
+ import { figJamTextFields, figJamTextProps } from './figjam-text'
13
+ import { readElementProps, shapePropsSchema } from './schema'
14
+ import { plainTextOf, type TreeNode } from './tree'
15
+
16
+ /**
17
+ * The shape an element describes, with `layer`'s fields; it is named by its label, as FigJam
18
+ * names a shape, until given a name.
19
+ */
20
+ export function renderShapeNode(
21
+ graph: SceneGraph,
22
+ tree: TreeNode,
23
+ parentId: string,
24
+ layer: Partial<SceneNode>
25
+ ) {
26
+ const props = readElementProps(shapePropsSchema, tree.props)
27
+ const text = plainTextOf(tree)
28
+ const shape = createShapeWithText(
29
+ graph,
30
+ parentId,
31
+ {
32
+ ...layer,
33
+ name: layer.name ?? (text.trim() || 'Shape with text'),
34
+ autoRename: !layer.name,
35
+ shapeWithTextType: props.kind ?? 'SQUARE',
36
+ shapeTruncates: props.truncate ?? false
37
+ },
38
+ { text }
39
+ )
40
+ const label = shapeWithTextLabel(graph, shape)
41
+ if (label) graph.updateNode(label.id, figJamTextFields(label, props.textSize, props.typeface))
42
+ return shape
43
+ }
44
+
45
+ /**
46
+ * A shape's own props as `<Shape>` writes them, after its name and position: the height it was
47
+ * given rather than the height its label grew it to, so it grows the same way when read back.
48
+ */
49
+ export function shapeWithTextProps(graph: SceneGraph, node: SceneNode): JSXProp[] {
50
+ const props: JSXProp[] = []
51
+ if (node.shapeWithTextType !== 'SQUARE') {
52
+ props.push(['kind', SHAPE_KIND.print(node.shapeWithTextType)])
53
+ }
54
+ const label = shapeWithTextLabel(graph, node)
55
+ if (label) props.push(...figJamTextProps(label))
56
+ // A truncating shape keeps the height it has; any other grows from the height it was given.
57
+ const height =
58
+ !node.shapeTruncates && node.shapeUserHeight > 0 ? node.shapeUserHeight : node.height
59
+ if (node.width !== SHAPE_WITH_TEXT_SIZE) props.push(['w', node.width])
60
+ if (height !== SHAPE_WITH_TEXT_SIZE) props.push(['h', height])
61
+ if (node.shapeTruncates) props.push(['truncate', true])
62
+ if (node.rotation !== 0) props.push(['rotate', Math.round(node.rotation * 100) / 100])
63
+ collectFillProps(node, props)
64
+ collectStrokeProps(node, props)
65
+ if (node.cornerRadius !== SHAPE_WITH_TEXT_CORNER_RADIUS)
66
+ props.push(['rounded', node.cornerRadius])
67
+ return props
68
+ }
69
+
70
+ /** The label a shape writes as its children. */
71
+ export function shapeWithTextLabelText(graph: SceneGraph, node: SceneNode): string {
72
+ return shapeWithTextLabel(graph, node)?.text ?? ''
73
+ }
@@ -0,0 +1,72 @@
1
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
2
+ import { colorToHex } from '@pairdraw/scene-graph/color'
3
+ import {
4
+ createSticky,
5
+ isWideSticky,
6
+ STICKY_COLORS,
7
+ stickyScale,
8
+ stickySublayers
9
+ } from '@pairdraw/scene-graph/generated'
10
+ import type { Color } from '@pairdraw/scene-graph/primitives'
11
+
12
+ import { figJamTextFields, figJamTextProps } from './figjam-text'
13
+ import { readElementProps, stickyPropsSchema } from './schema'
14
+ import { plainTextOf, type TreeNode } from './tree'
15
+
16
+ /**
17
+ * The note an element describes, with `layer`'s fields; it is named by its body, as FigJam names
18
+ * a note, until given a name.
19
+ */
20
+ export function renderStickyNode(
21
+ graph: SceneGraph,
22
+ tree: TreeNode,
23
+ parentId: string,
24
+ layer: Partial<SceneNode>
25
+ ) {
26
+ const props = readElementProps(stickyPropsSchema, tree.props)
27
+ const text = plainTextOf(tree)
28
+ const author = props.author ?? ''
29
+ const sticky = createSticky(
30
+ graph,
31
+ parentId,
32
+ {
33
+ text,
34
+ author,
35
+ authorVisible: props.authorVisible !== false && author !== '',
36
+ color: props.color,
37
+ wide: props.wide === true,
38
+ scale: props.scale ?? 1
39
+ },
40
+ { ...layer, name: layer.name ?? (text.trim() || 'Sticky'), autoRename: !layer.name }
41
+ )
42
+ const body = stickySublayers(graph, sticky)?.body
43
+ if (body) graph.updateNode(body.id, figJamTextFields(body, props.textSize, props.typeface))
44
+ return sticky
45
+ }
46
+
47
+ /** The colour as `<Sticky>` writes it: its palette name, or a hex colour off the palette. */
48
+ function colorName(color: Color): string {
49
+ const hex = colorToHex(color)
50
+ const named = Object.entries(STICKY_COLORS).find(([, value]) => colorToHex(value) === hex)
51
+ return named ? named[0] : hex
52
+ }
53
+
54
+ /** A note's own props as `<Sticky>` writes them, after its name and position. */
55
+ export function stickyProps(graph: SceneGraph, node: SceneNode): Array<[string, unknown]> {
56
+ const layers = stickySublayers(graph, node)
57
+ const color = node.fills.at(0)?.color
58
+ const props: Array<[string, unknown]> = []
59
+ if (color) props.push(['color', colorName(color)])
60
+ if (layers?.author.text) props.push(['author', layers.author.text])
61
+ if (layers?.author.text && !layers.author.visible) props.push(['authorVisible', false])
62
+ if (isWideSticky(graph, node)) props.push(['wide', true])
63
+ if (layers) props.push(...figJamTextProps(layers.body))
64
+ const scale = layers ? stickyScale(layers.author) : 1
65
+ if (scale !== 1) props.push(['scale', scale])
66
+ return props
67
+ }
68
+
69
+ /** The body a note writes as its children. */
70
+ export function stickyBody(graph: SceneGraph, node: SceneNode): string {
71
+ return stickySublayers(graph, node)?.body.text ?? ''
72
+ }
@@ -0,0 +1,47 @@
1
+ import { TreeFragment } from '@lezer/common'
2
+ import { parser } from '@lezer/javascript'
3
+
4
+ import { projectPreview, type JSXPreviewSnapshot } from './projection'
5
+
6
+ export type { JSXPreviewNode, JSXPreviewPending, JSXPreviewSnapshot } from './projection'
7
+
8
+ const jsxParser = parser.configure({ dialect: 'jsx', top: 'SingleExpression' })
9
+ const MAX_PREVIEW_SOURCE_LENGTH = 128_000
10
+
11
+ /**
12
+ * Append-only, non-executing Design JSX preview parser. Own one instance per tool call.
13
+ * Snapshots contain fresh data; later appends never mutate an earlier preview.
14
+ * This is not final JSX validation: unsupported expressions are deliberately deferred.
15
+ * Call append on coalesced chunks, not once per token, to bound projection work.
16
+ */
17
+ export function createStreamingJSXParser() {
18
+ let source = ''
19
+ let fragments: readonly TreeFragment[] = []
20
+
21
+ function append(chunk: string): JSXPreviewSnapshot {
22
+ if (source.length + chunk.length > MAX_PREVIEW_SOURCE_LENGTH) {
23
+ throw new RangeError('JSX preview source limit exceeded')
24
+ }
25
+ const next = source + chunk
26
+ const changed = TreeFragment.applyChanges(fragments, [
27
+ {
28
+ fromA: source.length,
29
+ toA: source.length,
30
+ fromB: source.length,
31
+ toB: next.length
32
+ }
33
+ ])
34
+ const tree = jsxParser.parse(next, changed)
35
+ const snapshot = projectPreview(tree.topNode, next)
36
+ source = next
37
+ fragments = TreeFragment.addTree(tree)
38
+ return snapshot
39
+ }
40
+
41
+ function reset(): void {
42
+ source = ''
43
+ fragments = []
44
+ }
45
+
46
+ return { append, reset }
47
+ }
@@ -0,0 +1,82 @@
1
+ import { parseExpressionAt, type Expression, type ObjectExpression } from 'acorn'
2
+
3
+ const MAX_LITERAL_DEPTH = 32
4
+ const UNSUPPORTED = Symbol('unsupported-literal')
5
+
6
+ type LiteralValue =
7
+ | string
8
+ | number
9
+ | boolean
10
+ | null
11
+ | LiteralValue[]
12
+ | { [key: string]: LiteralValue }
13
+ type Result = LiteralValue | typeof UNSUPPORTED
14
+
15
+ /** Decode data only. Calls, getters, spreads, identifiers and computed keys never execute. */
16
+ export function readLiteral(source: string): { value: LiteralValue } | null {
17
+ try {
18
+ const expression = parseExpressionAt(source, 0, { ecmaVersion: 'latest' })
19
+ if (source.slice(expression.end).trim()) return null
20
+ const value = evaluateLiteral(expression, 0)
21
+ return value === UNSUPPORTED ? null : { value }
22
+ } catch {
23
+ return null
24
+ }
25
+ }
26
+
27
+ function evaluateLiteral(expression: Expression, depth: number): Result {
28
+ if (depth > MAX_LITERAL_DEPTH) return UNSUPPORTED
29
+ switch (expression.type) {
30
+ case 'Literal': {
31
+ const value = expression.value
32
+ return value === null ||
33
+ typeof value === 'string' ||
34
+ typeof value === 'boolean' ||
35
+ (typeof value === 'number' && Number.isFinite(value))
36
+ ? value
37
+ : UNSUPPORTED
38
+ }
39
+ case 'UnaryExpression': {
40
+ if (expression.operator !== '-' && expression.operator !== '+') return UNSUPPORTED
41
+ const value = evaluateLiteral(expression.argument, depth + 1)
42
+ if (typeof value !== 'number') return UNSUPPORTED
43
+ return expression.operator === '-' ? -value : value
44
+ }
45
+ case 'ArrayExpression': {
46
+ const values: LiteralValue[] = []
47
+ for (const element of expression.elements) {
48
+ if (!element || element.type === 'SpreadElement') return UNSUPPORTED
49
+ const value = evaluateLiteral(element, depth + 1)
50
+ if (value === UNSUPPORTED) return UNSUPPORTED
51
+ values.push(value)
52
+ }
53
+ return values
54
+ }
55
+ case 'ObjectExpression':
56
+ return evaluateObject(expression, depth)
57
+ default:
58
+ return UNSUPPORTED
59
+ }
60
+ }
61
+
62
+ function evaluateObject(expression: ObjectExpression, depth: number): Result {
63
+ const entries: [string, LiteralValue][] = []
64
+ for (const property of expression.properties) {
65
+ if (
66
+ property.type !== 'Property' ||
67
+ property.computed ||
68
+ property.method ||
69
+ property.shorthand ||
70
+ property.kind !== 'init'
71
+ )
72
+ return UNSUPPORTED
73
+ let key: unknown
74
+ if (property.key.type === 'Identifier') key = property.key.name
75
+ else if (property.key.type === 'Literal') key = property.key.value
76
+ if (typeof key !== 'string' && typeof key !== 'number') return UNSUPPORTED
77
+ const value = evaluateLiteral(property.value, depth + 1)
78
+ if (value === UNSUPPORTED) return UNSUPPORTED
79
+ entries.push([String(key), value])
80
+ }
81
+ return Object.fromEntries(entries)
82
+ }