@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,155 @@
1
+ import { isEqual } from 'es-toolkit'
2
+
3
+ import type { SceneNode } from '@pairdraw/scene-graph'
4
+
5
+ import {
6
+ PADDING_FIELDS,
7
+ paintProps,
8
+ scalarProps,
9
+ type BindingContext,
10
+ type BoundProp
11
+ } from '../variables/props'
12
+ import type { JSXProp, JSXValue } from './value'
13
+ import type { VariableExport } from './variables'
14
+
15
+ /** Sizes are not added when the export left them out, as a fixed size would replace Hug or Fill. */
16
+ const NOT_ADDED = new Set(['width', 'height'])
17
+ /** The corner props, which make the corners independent wherever one of them is written. */
18
+ const CORNER_PROPS = ['roundedTL', 'roundedTR', 'roundedBR', 'roundedBL']
19
+
20
+ function bindingContext(node: SceneNode): BindingContext {
21
+ return {
22
+ text: node.type === 'TEXT',
23
+ grid: node.layoutMode === 'GRID',
24
+ wrap: node.layoutWrap === 'WRAP'
25
+ }
26
+ }
27
+
28
+ /**
29
+ * The prop `field` is written through on `node`: one the export printed that sets that field
30
+ * alone, or else the last number prop that does, as rendering reads it, or none, when only
31
+ * `bind` can set it. A paint prop is printed only for a single solid paint, which a colour
32
+ * variable can stand for; a number prop printed as a word, such as `w="fill"`, keeps it.
33
+ */
34
+ function fieldProp(node: SceneNode, field: string, props: JSXProp[]) {
35
+ const context = bindingContext(node)
36
+ const sets = ({ fields }: BoundProp) => fields.length === 1 && fields[0] === field
37
+ const scalar = scalarProps(context).filter(sets)
38
+ const printedAs = (prop: string, numeric: boolean) =>
39
+ props.some(([name, value]) => name === prop && (!numeric || typeof value === 'number'))
40
+ const printed =
41
+ scalar.find(({ prop }) => printedAs(prop, true)) ??
42
+ paintProps(context)
43
+ .filter(sets)
44
+ .find(({ prop }) => printedAs(prop, false))
45
+ if (printed) return { prop: printed.prop, add: false }
46
+ const last = scalar.at(-1)
47
+ return last && !NOT_ADDED.has(field) ? { prop: last.prop, add: true } : undefined
48
+ }
49
+
50
+ function setProp(props: JSXProp[], name: string, value: JSXValue, add: boolean): boolean {
51
+ const index = props.findIndex(([prop]) => prop === name)
52
+ if (index !== -1) props[index] = [name, value]
53
+ else if (add) props.push([name, value])
54
+ return index !== -1 || add
55
+ }
56
+
57
+ /**
58
+ * Write the padding again when a side is bound, each bound side as its variable, grouped as
59
+ * `p`, `py` and `px`, or one prop per side, as the export groups literal padding.
60
+ */
61
+ function writePadding(
62
+ node: SceneNode,
63
+ props: JSXProp[],
64
+ remaining: Map<string, string>,
65
+ variables: VariableExport,
66
+ named: (variableId: string) => boolean
67
+ ): void {
68
+ const sides = PADDING_FIELDS.map((field): JSXValue => {
69
+ const variableId = remaining.get(field)
70
+ return variableId && named(variableId)
71
+ ? variables.variable(variableId)
72
+ : node[field as 'paddingTop']
73
+ })
74
+ if (sides.every((side) => typeof side === 'number')) return
75
+ const paddingProps = new Set(
76
+ scalarProps(bindingContext(node))
77
+ .filter(({ fields }) => fields.every((field) => PADDING_FIELDS.includes(field)))
78
+ .map(({ prop }) => prop)
79
+ )
80
+ for (let index = props.length - 1; index >= 0; index--) {
81
+ if (paddingProps.has(props[index][0])) props.splice(index, 1)
82
+ }
83
+ const [top, right, bottom, left] = sides
84
+ if ([right, bottom, left].every((side) => isEqual(side, top))) props.push(['p', top])
85
+ else if (isEqual(top, bottom) && isEqual(left, right)) props.push(['py', top], ['px', left])
86
+ else {
87
+ ;(['pt', 'pr', 'pb', 'pl'] as const).forEach((prop, index) => {
88
+ if (sides[index] !== 0) props.push([prop, sides[index]])
89
+ })
90
+ }
91
+ for (const field of PADDING_FIELDS) {
92
+ const variableId = remaining.get(field)
93
+ if (variableId && named(variableId)) remaining.delete(field)
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Write corners printed together as `rounded` one by one when a corner is bound, since the
99
+ * bound corner's own prop makes the corners independent and the others would then be 0.
100
+ */
101
+ function expandCorners(
102
+ node: SceneNode,
103
+ props: JSXProp[],
104
+ remaining: Map<string, string>,
105
+ named: (variableId: string) => boolean
106
+ ): void {
107
+ const corners = new Set(
108
+ scalarProps(bindingContext(node))
109
+ .filter(({ prop }) => CORNER_PROPS.includes(prop))
110
+ .flatMap(({ fields }) => fields)
111
+ )
112
+ const bound = [...remaining].some(([field, id]) => corners.has(field) && named(id))
113
+ const index = props.findIndex(([prop]) => prop === 'rounded')
114
+ if (!bound || index === -1) return
115
+ const [, radius] = props[index]
116
+ props.splice(index, 1, ...CORNER_PROPS.map((prop): JSXProp => [prop, radius]))
117
+ }
118
+
119
+ /**
120
+ * Write the variables `node` binds through the props that set those fields, such as
121
+ * `bg={theme.Surface}` and `p={density.Pad}`, and the rest in `bind`. Padding stays in `bind`
122
+ * on a layer without auto layout, where a padding prop would turn it on.
123
+ */
124
+ export function collectBindingProps(
125
+ node: SceneNode,
126
+ props: JSXProp[],
127
+ variables: VariableExport
128
+ ): void {
129
+ const remaining = new Map(Object.entries(node.boundVariables))
130
+ // A variable only `bind` can name, by its ID, is not written in a prop, which reads a string.
131
+ const named = (variableId: string) => typeof variables.variable(variableId) !== 'string'
132
+ const laidOut = node.layoutMode !== 'NONE'
133
+ if (laidOut) writePadding(node, props, remaining, variables, named)
134
+ expandCorners(node, props, remaining, named)
135
+ for (const [field, variableId] of remaining) {
136
+ if (!named(variableId) || (!laidOut && PADDING_FIELDS.includes(field))) continue
137
+ const target = fieldProp(node, field, props)
138
+ if (target && setProp(props, target.prop, variables.variable(variableId), target.add))
139
+ remaining.delete(field)
140
+ }
141
+ if (remaining.size === 0) return
142
+ const bindings = [...remaining].toSorted(([a], [b]) => a.localeCompare(b))
143
+ props.push([
144
+ 'bind',
145
+ Object.fromEntries(bindings.map(([field, id]) => [field, variables.variable(id)]))
146
+ ])
147
+ }
148
+
149
+ /** The modes a layer pins; one is written without a list. */
150
+ export function collectModeProps(node: SceneNode, props: JSXProp[], variables: VariableExport) {
151
+ const modes = Object.entries(node.variableModes).map(([collectionId, modeId]) =>
152
+ variables.mode(collectionId, modeId)
153
+ )
154
+ if (modes.length > 0) props.push(['mode', modes.length === 1 ? modes[0] : modes])
155
+ }
@@ -0,0 +1,39 @@
1
+ import type { CharacterStyleOverride, SceneNode } from '@pairdraw/scene-graph'
2
+
3
+ import { TEXT_DECORATION_STYLE } from '../enums'
4
+ import { AUTO, CURRENT_COLOR } from '../overrides/text'
5
+ import { paintPropValue } from './paint'
6
+ import type { JSXProp } from './value'
7
+
8
+ type DecorationStyle = Pick<
9
+ CharacterStyleOverride,
10
+ | 'textDecorationStyle'
11
+ | 'textDecorationFills'
12
+ | 'textDecorationThickness'
13
+ | 'textUnderlineOffset'
14
+ | 'textDecorationSkipInk'
15
+ >
16
+
17
+ /**
18
+ * The decoration details set in `style`, as `<Text>` and `<Span>` write them. A decoration
19
+ * painted with more than one paint keeps only its first, the one `textDecorationColor` holds.
20
+ */
21
+ export function collectDecorationProps(
22
+ style: DecorationStyle,
23
+ node: SceneNode,
24
+ props: JSXProp[]
25
+ ): void {
26
+ const { textDecorationFills: fills } = style
27
+ if (style.textDecorationStyle !== undefined)
28
+ props.push(['textDecorationStyle', TEXT_DECORATION_STYLE.print(style.textDecorationStyle)])
29
+ if (fills) {
30
+ const fill = fills.at(0)
31
+ props.push(['textDecorationColor', fill ? paintPropValue(fill, node) : CURRENT_COLOR])
32
+ }
33
+ if (style.textDecorationThickness !== undefined)
34
+ props.push(['textDecorationThickness', style.textDecorationThickness ?? AUTO])
35
+ if (style.textUnderlineOffset !== undefined)
36
+ props.push(['textUnderlineOffset', style.textUnderlineOffset ?? AUTO])
37
+ if (style.textDecorationSkipInk !== undefined)
38
+ props.push(['textDecorationSkipInk', style.textDecorationSkipInk])
39
+ }
@@ -0,0 +1,25 @@
1
+ import type { CharacterStyleOverride } from '@pairdraw/scene-graph'
2
+
3
+ import type { JSXProp } from './value'
4
+
5
+ /** The font settings a `<Text>` or `<Span>` writes, by their scene fields. */
6
+ export const FONT_SETTING_FIELDS = ['fontFeatures', 'fontVariations', 'textLanguage'] as const
7
+
8
+ type FontSettings = Pick<CharacterStyleOverride, (typeof FONT_SETTING_FIELDS)[number]>
9
+
10
+ /** The font settings set in `style`, as `<Text>` and `<Span>` write them. */
11
+ export function collectFontSettingProps(style: FontSettings, props: JSXProp[]): void {
12
+ if (style.fontFeatures) {
13
+ props.push([
14
+ 'fontFeatures',
15
+ Object.fromEntries(style.fontFeatures.map(({ tag, enabled }) => [tag.toLowerCase(), enabled]))
16
+ ])
17
+ }
18
+ if (style.fontVariations) {
19
+ props.push([
20
+ 'fontVariations',
21
+ Object.fromEntries(style.fontVariations.map(({ axis, value }) => [axis, value]))
22
+ ])
23
+ }
24
+ if (style.textLanguage !== undefined) props.push(['lang', style.textLanguage])
25
+ }
@@ -0,0 +1,75 @@
1
+ import type { SceneGraph, SceneNode, Effect, GridTrack } from '@pairdraw/scene-graph'
2
+ import { colorToHex8 } from '@pairdraw/scene-graph/color'
3
+ import type { Color } from '@pairdraw/scene-graph/primitives'
4
+
5
+ export function formatColor(color: Color, opacity = 1): string {
6
+ return colorToHex8(color, opacity)
7
+ }
8
+
9
+ export function formatShadow(e: Effect): string | null {
10
+ if (e.type !== 'DROP_SHADOW' && e.type !== 'INNER_SHADOW') return null
11
+ return `${e.offset.x} ${e.offset.y} ${e.radius} ${formatColor(e.color, e.color.a)}`
12
+ }
13
+
14
+ export function getNodeContext(node: SceneNode, graph: SceneGraph) {
15
+ const parent = node.parentId ? graph.getNode(node.parentId) : null
16
+ return {
17
+ isAutoLayout: node.layoutMode !== 'NONE',
18
+ isGrid: node.layoutMode === 'GRID',
19
+ isFlex: node.layoutMode === 'HORIZONTAL' || node.layoutMode === 'VERTICAL',
20
+ parentIsAutoLayout: parent ? parent.layoutMode !== 'NONE' : false,
21
+ parentIsGrid: parent ? parent.layoutMode === 'GRID' : false
22
+ }
23
+ }
24
+
25
+ export type PaddingEdges = { pt: number; pr: number; pb: number; pl: number }
26
+
27
+ export function collectPadding(node: SceneNode): PaddingEdges | null {
28
+ const { paddingTop: pt, paddingRight: pr, paddingBottom: pb, paddingLeft: pl } = node
29
+ if (pt === 0 && pr === 0 && pb === 0 && pl === 0) return null
30
+ return { pt, pr, pb, pl }
31
+ }
32
+
33
+ export function emitPadding<T>(
34
+ edges: PaddingEdges,
35
+ uniform: (v: number) => T,
36
+ symmetric: (y: number, x: number) => T[],
37
+ individual: (edges: PaddingEdges) => T[]
38
+ ): T[] {
39
+ const { pt, pr, pb, pl } = edges
40
+ if (pt === pr && pr === pb && pb === pl) return [uniform(pt)]
41
+ if (pt === pb && pl === pr) return symmetric(pt, pl)
42
+ return individual(edges)
43
+ }
44
+
45
+ export interface CornerRadii {
46
+ tl: number
47
+ tr: number
48
+ br: number
49
+ bl: number
50
+ }
51
+
52
+ export function collectCornerRadii(node: SceneNode): CornerRadii | null {
53
+ if (node.independentCorners) {
54
+ const corners = {
55
+ tl: node.topLeftRadius,
56
+ tr: node.topRightRadius,
57
+ br: node.bottomRightRadius,
58
+ bl: node.bottomLeftRadius
59
+ }
60
+ return Object.values(corners).some((radius) => radius > 0) ? corners : null
61
+ }
62
+ if (node.cornerRadius <= 0) return null
63
+ const r = node.cornerRadius
64
+ return { tl: r, tr: r, br: r, bl: r }
65
+ }
66
+
67
+ function formatTrack(t: GridTrack): string {
68
+ if (t.sizing === 'FR') return `${t.value}fr`
69
+ if (t.sizing === 'FIXED') return `${t.value}px`
70
+ return 'auto'
71
+ }
72
+
73
+ export function formatTracks(tracks: GridTrack[]): string {
74
+ return tracks.map(formatTrack).join(' ')
75
+ }
@@ -0,0 +1,42 @@
1
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
2
+ import { colorToHex } from '@pairdraw/scene-graph/color'
3
+ import {
4
+ isIconModified,
5
+ isPlacedIconName,
6
+ isNamedIcon,
7
+ readIcon,
8
+ readIconTint
9
+ } from '@pairdraw/scene-graph/icons'
10
+
11
+ import type { JSXProp } from './props'
12
+
13
+ /** The color an icon's tinted paths have, as `<Icon color>` takes it. */
14
+ function tintColor(graph: SceneGraph, frame: SceneNode): string | null {
15
+ for (const path of graph.getChildren(frame.id)) {
16
+ const tint = readIconTint(path)
17
+ const paint = tint.includes('fill') ? path.fills[0] : undefined
18
+ const stroke = tint.includes('stroke') ? path.strokes[0] : undefined
19
+ const color = paint?.color ?? stroke?.color
20
+ if (color) return colorToHex(color)
21
+ }
22
+ return null
23
+ }
24
+
25
+ /**
26
+ * An icon frame as `<Icon>` props: its name and size, its color when it is not black, and its
27
+ * layer name when someone renamed it. `null` for a layer that is not an icon, or no longer draws
28
+ * one because its paths were edited.
29
+ */
30
+ export function iconProps(node: SceneNode, graph: SceneGraph): JSXProp[] | null {
31
+ const icon = readIcon(node)
32
+ // An icon whose paths were edited exports as the paths it draws, which <Icon> would lose, as
33
+ // does one drawn from a set of our own, which its name alone does not draw.
34
+ if (!icon || !isNamedIcon(icon) || isIconModified(graph, node)) return null
35
+ const color = tintColor(graph, node)
36
+ return [
37
+ ['name', icon.name],
38
+ ['size', Math.round(Math.min(node.width, node.height))],
39
+ ...(color && color.toLowerCase() !== '#000000' ? [['color', color] as JSXProp] : []),
40
+ ...(isPlacedIconName(node.name, icon.name) ? [] : [['label', node.name] as JSXProp])
41
+ ]
42
+ }
@@ -0,0 +1,297 @@
1
+ import { compact } from 'es-toolkit/array'
2
+
3
+ import { jsx, type SyntaxNode } from '@pairdraw/emit'
4
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
5
+ import { isGeneratedFrame, type GeneratedFrameType } from '@pairdraw/scene-graph/generated'
6
+
7
+ import {
8
+ connectorExportScope,
9
+ connectorLabel,
10
+ connectorProps,
11
+ connectorRefDeclarations,
12
+ type ConnectorExportScope
13
+ } from '../connectors'
14
+ import { elementTag } from '../elements'
15
+ import { shapeWithTextLabelText, shapeWithTextProps } from '../shapes-with-text'
16
+ import { stickyBody, stickyProps } from '../stickies'
17
+ import { rekaExport, type RekaExport } from './behaviours'
18
+ import { iconProps } from './icons'
19
+ import { collectProps, positionProps, presenceProps } from './props'
20
+ import { textChildren } from './text'
21
+ import { plainValue, propAttribute, Reference, type JSXProp } from './value'
22
+ import { variableExport, type VariableExport } from './variables'
23
+
24
+ /** Design JSX with the layer behind each element, in the order elements open. */
25
+ export interface DesignJSXWithLayers {
26
+ code: string
27
+ /**
28
+ * One entry per JSX element, in pre-order, so editors can link elements to layers: the
29
+ * layer's id, or `null` for an element no layer is, such as a `<Span>` or `<Paragraph>`.
30
+ */
31
+ layerIds: Array<string | null>
32
+ }
33
+
34
+ const NO_REKA: RekaExport = { tags: new Map(), props: new Map(), flatten: new Set() }
35
+
36
+ function mergeReka(outer: RekaExport, inner: RekaExport | null): RekaExport {
37
+ if (!inner) return outer
38
+ return {
39
+ tags: new Map([...outer.tags, ...inner.tags]),
40
+ props: new Map([...outer.props, ...inner.props]),
41
+ flatten: new Set([...outer.flatten, ...inner.flatten])
42
+ }
43
+ }
44
+
45
+ /** How many JSX elements the syntax holds, as an editor finds them in pre-order. */
46
+ function elementCount(nodes: readonly SyntaxNode[]): number {
47
+ let count = 0
48
+ for (const node of nodes) {
49
+ if (node.type !== 'JSXElement') continue
50
+ const children = (node as { children?: SyntaxNode[] }).children ?? []
51
+ count += 1 + elementCount(children)
52
+ }
53
+ return count
54
+ }
55
+
56
+ /**
57
+ * A layer and the layers below it as JSX elements. A component with a behaviour is written as
58
+ * Reka UI elements; a container JSX leaves implicit is written as its children alone.
59
+ */
60
+ /** What an element written its own way holds: its props, and the text it writes as children. */
61
+ interface OwnElement {
62
+ props: JSXProp[]
63
+ text: string
64
+ }
65
+
66
+ /**
67
+ * The name an element named by its text writes: none while the layer still follows its text, and
68
+ * its name once renamed, even to its text, so reading it back keeps the name from following it.
69
+ */
70
+ function textNamedName(node: SceneNode): JSXProp[] {
71
+ return node.autoRename ? [] : [['name', node.name]]
72
+ }
73
+
74
+ /**
75
+ * The layers whose elements take props of their own rather than the layer props: every generated
76
+ * frame, whose sublayers its element writes as props and text.
77
+ */
78
+ const OWN_ELEMENTS: Record<
79
+ GeneratedFrameType,
80
+ (graph: SceneGraph, node: SceneNode, scope?: ConnectorExportScope) => OwnElement
81
+ > = {
82
+ STICKY: (graph, node) => ({
83
+ props: [
84
+ ...textNamedName(node),
85
+ ...positionProps(node, graph),
86
+ ...stickyProps(graph, node).map(([key, value]): JSXProp => [key, plainValue(value)]),
87
+ ...presenceProps(node)
88
+ ],
89
+ text: stickyBody(graph, node)
90
+ }),
91
+ SHAPE_WITH_TEXT: (graph, node) => ({
92
+ props: [
93
+ ...textNamedName(node),
94
+ ...positionProps(node, graph),
95
+ ...shapeWithTextProps(graph, node),
96
+ ...presenceProps(node)
97
+ ],
98
+ text: shapeWithTextLabelText(graph, node)
99
+ }),
100
+ CONNECTOR: (graph, node, scope) => ({
101
+ props: connectorProps(graph, node, scope).map(([key, value]): JSXProp => [
102
+ key,
103
+ plainValue(value)
104
+ ]),
105
+ text: connectorLabel(graph, node)
106
+ })
107
+ }
108
+
109
+ /** What a layer whose element takes props of its own writes, or undefined for another layer. */
110
+ function ownElement(
111
+ graph: SceneGraph,
112
+ node: SceneNode,
113
+ scope?: ConnectorExportScope
114
+ ): OwnElement | undefined {
115
+ return isGeneratedFrame(node) ? OWN_ELEMENTS[node.type](graph, node, scope) : undefined
116
+ }
117
+
118
+ /** The layers an export writes, by the roots it starts from. */
119
+ function nodeToJSX(
120
+ node: SceneNode,
121
+ graph: SceneGraph,
122
+ depth: number,
123
+ scope: ConnectorExportScope,
124
+ variables: VariableExport,
125
+ layerIds?: Array<string | null>,
126
+ outer: RekaExport = NO_REKA
127
+ ): SyntaxNode[] {
128
+ const reka = mergeReka(outer, rekaExport(graph, node))
129
+ const ref = scope.refs.get(node.id)
130
+ // A layer a connector joins by a ref is marked with it, after its own props.
131
+ const withRef = (props: JSXProp[]): JSXProp[] =>
132
+ ref ? [...props, ['ref', new Reference(ref)]] : props
133
+ // Hidden children export with `visible={false}` rather than disappearing.
134
+ const children = (childDepth: number) =>
135
+ graph
136
+ .getChildren(node.id)
137
+ .flatMap((child) => nodeToJSX(child, graph, childDepth, scope, variables, layerIds, reka))
138
+ if (reka.flatten.has(node.id)) return children(depth)
139
+ // An icon is written by name; its paths are the icon set's to draw again.
140
+ const icon = iconProps(node, graph)
141
+ if (icon) {
142
+ layerIds?.push(node.id)
143
+ return [jsx.element('Icon', withRef(icon).map(propAttribute), [], depth)]
144
+ }
145
+ const tag = reka.tags.get(node.id) ?? elementTag(node.type)
146
+ if (!tag) return []
147
+ layerIds?.push(node.id)
148
+ const own = ownElement(graph, node, scope)
149
+ if (own) {
150
+ const children = own.text ? [jsx.text(own.text)] : []
151
+ return [jsx.element(tag, own.props.map(propAttribute), children, depth, true)]
152
+ }
153
+ const ownProps = reka.props.get(node.id)
154
+ // An item names its component; the instance's own layers are the component's to write.
155
+ if (ownProps?.some(([name]) => name === 'of'))
156
+ return [jsx.element(tag, withRef(ownProps).map(propAttribute), [], depth)]
157
+ const attributes = withRef([...collectProps(node, graph, variables), ...(ownProps ?? [])]).map(
158
+ propAttribute
159
+ )
160
+ if (node.type === 'TEXT') {
161
+ const { children: content, inline } = textChildren(node, depth)
162
+ for (let count = elementCount(content); count > 0; count--) layerIds?.push(null)
163
+ return [jsx.element(tag, attributes, content, depth, inline)]
164
+ }
165
+ return [jsx.element(tag, attributes, children(depth + 1), depth)]
166
+ }
167
+
168
+ /** A JSX attribute as the export prints it: its name and its source, such as `w={320}`. */
169
+ export interface JSXAttributeSource {
170
+ name: string
171
+ source: string
172
+ }
173
+
174
+ /** Printed values break lines only between tokens, never inside a string, so joining is lossless. */
175
+ function oneLine(source: string): string {
176
+ return source.replace(/\s*\n\s*/g, ' ')
177
+ }
178
+
179
+ /**
180
+ * The attributes `sceneNodeToJSX` prints for a node, each on one line, with a text node's
181
+ * content, or a connector's label, as a `text` attribute. `null` for a node the export does not
182
+ * write. A connector's ends are written by their layers' names.
183
+ */
184
+ export function sceneNodeAttributes(
185
+ nodeId: string,
186
+ graph: SceneGraph
187
+ ): JSXAttributeSource[] | null {
188
+ const node = graph.getNode(nodeId)
189
+ if (!node || !elementTag(node.type)) return null
190
+ const own = ownElement(graph, node)
191
+ const props = own ? own.props : collectProps(node, graph)
192
+ if (node.type === 'TEXT') props.push(['text', node.text])
193
+ if (own?.text) props.push(['text', own.text])
194
+ return props.map((prop) => ({
195
+ name: prop[0],
196
+ source: oneLine(jsx.printJSX(propAttribute(prop)))
197
+ }))
198
+ }
199
+
200
+ /**
201
+ * One layer as Design JSX writes it, so an editor can patch the code a person has edited
202
+ * instead of writing it again.
203
+ */
204
+ export interface DesignJSXElement {
205
+ tag: string
206
+ /** Each attribute as `sceneNodeAttributes` prints it, keyed by name: `w={320}`. */
207
+ attributes: Record<string, string>
208
+ /**
209
+ * A text layer's content as JSX writes it between its tags, `<Span>`s and `<Paragraph>`s
210
+ * included, for an element at the start of its line; `null` for no content or another layer.
211
+ */
212
+ text: string | null
213
+ /** The layers written as child elements, in order. */
214
+ childIds: string[]
215
+ }
216
+
217
+ /** What an element holds between its tags, printed as `sceneNodeToJSX` prints it. */
218
+ function contentBetween(tag: string, children: SyntaxNode[], inline: boolean): string | null {
219
+ if (children.length === 0) return null
220
+ const printed = jsx.printJSX(jsx.element(tag, [], children, 0, inline))
221
+ return printed.slice(tag.length + 2, printed.lastIndexOf(`</${tag}>`))
222
+ }
223
+
224
+ export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXElement | null {
225
+ const node = graph.getNode(nodeId)
226
+ const tag = node && elementTag(node.type)
227
+ const printed = sceneNodeAttributes(nodeId, graph)
228
+ if (!node || !tag || !printed) return null
229
+ // A text layer's content, a connector's label, or a sticky note's body is written as its
230
+ // children, not as the `text` attribute; the layers they generate are not written at all.
231
+ const own = ownElement(graph, node)
232
+ const hasContent = node.type === 'TEXT' || own !== undefined
233
+ const attributes = Object.fromEntries(
234
+ printed
235
+ .filter(({ name }) => !hasContent || name !== 'text')
236
+ .map(({ name, source }) => [name, source])
237
+ )
238
+ if (node.type === 'TEXT') {
239
+ const { children, inline } = textChildren(node, 0)
240
+ return { tag, attributes, text: contentBetween(tag, children, inline), childIds: [] }
241
+ }
242
+ if (own) {
243
+ const children = own.text ? [jsx.text(own.text)] : []
244
+ return { tag, attributes, text: contentBetween(tag, children, true), childIds: [] }
245
+ }
246
+ const childIds = graph
247
+ .getChildren(node.id)
248
+ .filter((child) => elementTag(child.type))
249
+ .map((child) => child.id)
250
+ return { tag, attributes, text: null, childIds }
251
+ }
252
+
253
+ /** How an export is written: by default, with the declarations its JSX uses before it. */
254
+ export interface JSXExportOptions {
255
+ /**
256
+ * `false` writes only JSX, for code that places it inside other JSX: a connector end whose
257
+ * layer would need a declared `ref()` is then written as the point it is drawn at, and the
258
+ * variables layers bind are written by reference (`designVar`) instead of with the
259
+ * `defineVars` and `defineMode` that define them.
260
+ */
261
+ declarations?: boolean
262
+ }
263
+
264
+ export function sceneNodeToJSX(nodeId: string, graph: SceneGraph): string {
265
+ return selectionToJSX([nodeId], graph)
266
+ }
267
+
268
+ export function selectionToJSX(nodeIds: string[], graph: SceneGraph): string {
269
+ return selectionToJSXWithLayers(nodeIds, graph).code
270
+ }
271
+
272
+ export function selectionToJSXWithLayers(
273
+ nodeIds: string[],
274
+ graph: SceneGraph,
275
+ options: JSXExportOptions = {}
276
+ ): DesignJSXWithLayers {
277
+ const layerIds: Array<string | null> = []
278
+ const declare = options.declarations ?? true
279
+ const scope = connectorExportScope(graph, nodeIds, declare)
280
+ const variables = variableExport(graph, nodeIds, declare)
281
+ const roots = compact(
282
+ nodeIds.map((id) => {
283
+ const node = graph.getNode(id)
284
+ const syntax = node ? nodeToJSX(node, graph, 0, scope, variables, layerIds).at(0) : undefined
285
+ return syntax ? jsx.printJSX(syntax) : ''
286
+ })
287
+ )
288
+ const elements = roots.join('\n\n')
289
+ // Variables first: a ref names a layer, and nothing in a variable's definition refers to one.
290
+ const declarations = compact([variables.declarations(), connectorRefDeclarations(scope)]).join(
291
+ '\n\n'
292
+ )
293
+ if (!declarations || !elements) return { code: elements, layerIds }
294
+ // Statements end with `return` and the JSX; several roots return as siblings in a fragment.
295
+ const returned = roots.length > 1 ? `<>\n${elements}\n</>` : elements
296
+ return { code: `${declarations}\n\nreturn ${returned}`, layerIds }
297
+ }