@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
@@ -0,0 +1,155 @@
1
+ import { isEmptyObject, isEqual, omitBy, pick } from 'es-toolkit'
2
+
3
+ import { jsx, type SyntaxNode } from '@pairdraw/emit'
4
+ import type {
5
+ SceneNode,
6
+ TextParagraphSpacingField,
7
+ TextParagraphStyle
8
+ } from '@pairdraw/scene-graph'
9
+ import {
10
+ hasParagraphSpacing,
11
+ MAX_LIST_INDENTATION,
12
+ paragraphStyleAt,
13
+ textParagraphRanges,
14
+ withParagraphSpacing
15
+ } from '@pairdraw/scene-graph/text'
16
+
17
+ import { TEXT_CASE, TEXT_DECORATION } from '../enums'
18
+ import { AUTO, textLengthJSX } from '../overrides/text'
19
+ import { SPAN_STYLE_FIELDS, type SpanStyle } from '../text-content'
20
+ import { collectDecorationProps } from './decoration'
21
+ import { collectFontSettingProps } from './font'
22
+ import { collectFillProps } from './paint'
23
+ import { fontWeightValue } from './props'
24
+ import { propAttribute, type JSXProp } from './value'
25
+
26
+ /** A text's content as JSX children, and whether they print on the element's own line. */
27
+ export interface TextChildren {
28
+ children: SyntaxNode[]
29
+ inline: boolean
30
+ }
31
+
32
+ /**
33
+ * Each character's style where it differs from the text's own, as a span writes it, with the
34
+ * URL it links to; a span cannot write a link to a node.
35
+ */
36
+ function characterStyles(node: SceneNode): SpanStyle[] {
37
+ const styles = Array.from({ length: node.text.length }, (): SpanStyle => ({}))
38
+ for (const run of node.styleRuns) {
39
+ const style: SpanStyle = pick(run.style, SPAN_STYLE_FIELDS)
40
+ if (run.style.hyperlink?.type === 'URL') style.hyperlink = run.style.hyperlink
41
+ const end = Math.min(run.start + run.length, styles.length)
42
+ for (let index = run.start; index < end; index++) styles[index] = { ...styles[index], ...style }
43
+ }
44
+ return styles.map((style) =>
45
+ omitBy(
46
+ style,
47
+ (value, key) => value === undefined || (key !== 'hyperlink' && isEqual(value, node[key]))
48
+ )
49
+ )
50
+ }
51
+
52
+ function spanProps(style: SpanStyle, node: SceneNode): JSXProp[] {
53
+ const props: JSXProp[] = []
54
+ if (style.fontSize !== undefined) props.push(['size', style.fontSize])
55
+ if (style.fontFamily !== undefined) props.push(['font', style.fontFamily])
56
+ if (style.fontWeight !== undefined) props.push(['weight', fontWeightValue(style.fontWeight)])
57
+ if (style.italic !== undefined) props.push(['italic', style.italic])
58
+ if (style.fills) collectFillProps({ ...node, fills: style.fills }, props)
59
+ if (style.lineHeight !== undefined) {
60
+ props.push(['lineHeight', style.lineHeight ? textLengthJSX(style.lineHeight) : AUTO])
61
+ }
62
+ if (style.letterSpacing !== undefined) {
63
+ props.push(['letterSpacing', textLengthJSX(style.letterSpacing)])
64
+ }
65
+ if (style.textDecoration !== undefined)
66
+ props.push(['textDecoration', TEXT_DECORATION.print(style.textDecoration)])
67
+ collectDecorationProps(style, node, props)
68
+ collectFontSettingProps(style, props)
69
+ if (style.textCase !== undefined) props.push(['textCase', TEXT_CASE.print(style.textCase)])
70
+ if (style.hyperlink) props.push(['href', style.hyperlink.value])
71
+ return props
72
+ }
73
+
74
+ /** `text[start, end)` as text and a `<Span>` for every stretch styled apart from the text. */
75
+ function inlineContent(
76
+ node: SceneNode,
77
+ styles: readonly SpanStyle[],
78
+ start: number,
79
+ end: number
80
+ ): SyntaxNode[] {
81
+ const content: SyntaxNode[] = []
82
+ let from = start
83
+ for (let index = start + 1; index <= end; index++) {
84
+ if (index < end && isEqual(styles[index], styles[from])) continue
85
+ const text = jsx.inlineText(node.text.slice(from, index))
86
+ const style = styles[from]
87
+ content.push(
88
+ isEmptyObject(style)
89
+ ? text
90
+ : jsx.element('Span', spanProps(style, node).map(propAttribute), [text], 0, true)
91
+ )
92
+ from = index
93
+ }
94
+ return content
95
+ }
96
+
97
+ /** `<Paragraph>`'s prop for each spacing a paragraph can set, in the order they are written. */
98
+ const PARAGRAPH_SPACING_PROPS: readonly (readonly [TextParagraphSpacingField, string])[] = [
99
+ ['paragraphSpacing', 'spacing'],
100
+ ['listSpacing', 'listSpacing'],
101
+ ['paragraphIndent', 'indent']
102
+ ]
103
+
104
+ /** A paragraph's style with only the spacing that differs from the text's own. */
105
+ function ownParagraphStyle(node: SceneNode, paragraph: number): TextParagraphStyle {
106
+ let style = paragraphStyleAt(node.textParagraphs, paragraph)
107
+ for (const [field] of PARAGRAPH_SPACING_PROPS) {
108
+ if (style[field] === node[field]) style = withParagraphSpacing(style, field, undefined)
109
+ }
110
+ return style
111
+ }
112
+
113
+ function paragraphProps(style: TextParagraphStyle): JSXProp[] {
114
+ const props: JSXProp[] = []
115
+ if (style.listType !== 'NONE') {
116
+ props.push(['list', style.listType === 'ORDERED' ? 'ordered' : 'unordered'])
117
+ const level = Math.min(style.indentation, MAX_LIST_INDENTATION)
118
+ if (level > 1) props.push(['level', level])
119
+ }
120
+ for (const [field, name] of PARAGRAPH_SPACING_PROPS) {
121
+ const value = style[field]
122
+ if (value !== undefined) props.push([name, value])
123
+ }
124
+ return props
125
+ }
126
+
127
+ /**
128
+ * A text's content as JSX children: its text alone when it is styled as a whole, with
129
+ * `<Span>`s for characters styled apart, and as `<Paragraph>`s when a paragraph is a list item
130
+ * or has spacing other than the text's.
131
+ */
132
+ export function textChildren(node: SceneNode, depth: number): TextChildren {
133
+ const styles = characterStyles(node)
134
+ const ranges = textParagraphRanges(node.text)
135
+ const paragraphs = ranges.map((_, index) => ownParagraphStyle(node, index))
136
+ const styledParagraphs = paragraphs.some(
137
+ (style) => style.listType !== 'NONE' || hasParagraphSpacing(style)
138
+ )
139
+ if (!styledParagraphs) {
140
+ if (styles.every(isEmptyObject)) {
141
+ return { children: node.text ? [jsx.text(node.text)] : [], inline: true }
142
+ }
143
+ return { children: inlineContent(node, styles, 0, node.text.length), inline: true }
144
+ }
145
+ const children = ranges.map(({ start, end }, index) =>
146
+ jsx.element(
147
+ 'Paragraph',
148
+ paragraphProps(paragraphs[index]).map(propAttribute),
149
+ inlineContent(node, styles, start, end),
150
+ depth + 1,
151
+ true
152
+ )
153
+ )
154
+ return { children, inline: false }
155
+ }
@@ -0,0 +1,99 @@
1
+ import { es, jsx, type SyntaxNode } from '@pairdraw/emit'
2
+
3
+ /** A paint, effect, or variable helper call inside a prop value, such as `solid("#FF0000")`. */
4
+ export class HelperCall {
5
+ constructor(
6
+ readonly helper: string,
7
+ readonly args: JSXValue[]
8
+ ) {}
9
+ }
10
+
11
+ /**
12
+ * A name the export declares before the JSX, such as the `card1` of `ref={card1}`, or one of its
13
+ * members, such as the `theme.Page` of a variable `defineVars` declared.
14
+ */
15
+ export class Reference {
16
+ constructor(
17
+ readonly name: string,
18
+ readonly member?: string
19
+ ) {}
20
+ }
21
+
22
+ /** A prop value: plain data, possibly holding helper calls. Undefined object fields are left out. */
23
+ export type JSXValue =
24
+ | string
25
+ | number
26
+ | boolean
27
+ | null
28
+ | HelperCall
29
+ | Reference
30
+ | JSXValue[]
31
+ | { [key: string]: JSXValue | undefined }
32
+
33
+ /** A prop name and its value. */
34
+ export type JSXProp = [name: string, value: JSXValue]
35
+
36
+ /** A call with trailing undefined arguments dropped, so defaults stay implicit. */
37
+ export function helperCall(helper: string, ...args: (JSXValue | undefined)[]): HelperCall {
38
+ const last = args.findLastIndex((arg) => arg !== undefined)
39
+ return new HelperCall(
40
+ helper,
41
+ args.slice(0, last + 1).map((arg) => arg ?? null)
42
+ )
43
+ }
44
+
45
+ function isRecord(value: unknown): value is Record<string, unknown> {
46
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
47
+ }
48
+
49
+ /**
50
+ * Plain scene data, such as a paint with no helper, as a prop value. Throws on values JSX
51
+ * cannot write back, such as binary data.
52
+ */
53
+ export function plainValue(value: unknown): JSXValue {
54
+ if (value instanceof Reference) return value
55
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value
56
+ if (typeof value === 'number' && Number.isFinite(value)) return value
57
+ if (Array.isArray(value)) return value.map(plainValue)
58
+ if (isRecord(value)) {
59
+ return Object.fromEntries(
60
+ Object.entries(value).flatMap(([key, item]) =>
61
+ item === undefined ? [] : [[key, plainValue(item)]]
62
+ )
63
+ )
64
+ }
65
+ throw new TypeError(`Cannot write a ${typeof value} value as JSX`)
66
+ }
67
+
68
+ /** The expression for a value, printed through the emit builders. */
69
+ export function valueSyntax(value: JSXValue): SyntaxNode {
70
+ if (value === null) return { type: 'Literal', value: null }
71
+ if (value instanceof HelperCall) return es.call(value.helper, value.args.map(valueSyntax))
72
+ if (value instanceof Reference)
73
+ return value.member === undefined
74
+ ? es.identifier(value.name)
75
+ : es.member(es.identifier(value.name), value.member)
76
+ if (Array.isArray(value)) return es.array(value.map(valueSyntax))
77
+ if (typeof value === 'object') {
78
+ return es.object(
79
+ Object.entries(value).flatMap(([key, item]) =>
80
+ item === undefined ? [] : [[key, valueSyntax(item)] as const]
81
+ )
82
+ )
83
+ }
84
+ return jsx.literal(value)
85
+ }
86
+
87
+ function propValue(value: JSXValue): SyntaxNode | null {
88
+ if (value === true) return null
89
+ if (typeof value === 'string') return jsx.stringValue(value)
90
+ return jsx.container(valueSyntax(value))
91
+ }
92
+
93
+ /**
94
+ * A prop as a JSX attribute: `true` prints the bare name, strings as attribute strings, and
95
+ * other values as expressions, with paint and effect helpers as calls.
96
+ */
97
+ export function propAttribute([name, value]: JSXProp): SyntaxNode {
98
+ return jsx.attribute(name, propValue(value))
99
+ }
@@ -0,0 +1,393 @@
1
+ import { isEqual } from 'es-toolkit'
2
+ import { camelCase } from 'es-toolkit/string'
3
+
4
+ import { jsx } from '@pairdraw/emit'
5
+ import type { SceneGraph, Variable, VariableCollection, VariableValue } from '@pairdraw/scene-graph'
6
+ import { modesDefaultFirst } from '@pairdraw/scene-graph/variables'
7
+
8
+ import { layersUnder } from '../connectors'
9
+ import { DESIGN_JSX_ELEMENTS } from '../elements'
10
+ import { DESIGN_JSX_HELPERS } from '../helpers'
11
+ import { DEFAULT_MODE_NAME, designMode, designVar, type DesignVariable } from '../variables'
12
+ import { collectionNamed, resolveVariableId, variableModes } from '../variables/graph'
13
+ import { formatColor } from './helpers'
14
+ import { helperCall, Reference, valueSyntax, type JSXValue } from './value'
15
+
16
+ /** How an export writes the variables its layers bind and the modes they pin. */
17
+ export interface VariableExport {
18
+ variable(variableId: string): JSXValue
19
+ mode(collectionId: string, modeId: string): JSXValue
20
+ /** The `defineVars` and `defineMode` statements the JSX refers to, if it declares any. */
21
+ declarations(): string
22
+ }
23
+
24
+ /**
25
+ * Variables and modes by reference to the document's own, as `designVar` and `designMode` find
26
+ * them: by name when it is unique, then by collection and name, and by ID otherwise.
27
+ */
28
+ export function variableReferences(graph: SceneGraph): VariableExport {
29
+ // A reference is written only when rendering would resolve it back to the same variable.
30
+ const finds = (handle: DesignVariable, variableId: string) => {
31
+ try {
32
+ return resolveVariableId(graph, handle) === variableId
33
+ } catch {
34
+ return false
35
+ }
36
+ }
37
+ // A collection name several collections share names none of them; its ID still does.
38
+ const findsMode = (collection: string, mode: string, collectionId: string, modeId: string) => {
39
+ try {
40
+ return variableModes(graph, designMode(collection, mode))?.[collectionId] === modeId
41
+ } catch {
42
+ return false
43
+ }
44
+ }
45
+ return {
46
+ variable(variableId) {
47
+ const variable = graph.variables.get(variableId)
48
+ if (!variable) return variableId
49
+ if (finds(designVar(variable.name), variableId)) return helperCall('designVar', variable.name)
50
+ const collection = graph.variableCollections.get(variable.collectionId)
51
+ return collection && finds(designVar(collection.name, variable.name), variableId)
52
+ ? helperCall('designVar', collection.name, variable.name)
53
+ : variableId
54
+ },
55
+ mode(collectionId, modeId) {
56
+ const collection = graph.variableCollections.get(collectionId)
57
+ const mode = collection?.modes.find((item) => item.modeId === modeId)
58
+ if (!collection || !mode) return modeId
59
+ const named = [collection.name, collectionId].find((name) =>
60
+ findsMode(name, mode.name, collectionId, modeId)
61
+ )
62
+ return named ? helperCall('designMode', named, mode.name) : modeId
63
+ },
64
+ declarations: () => ''
65
+ }
66
+ }
67
+
68
+ /** The variables the layers under `rootIds` bind. */
69
+ function boundVariableIds(graph: SceneGraph, rootIds: readonly string[]): Set<string> {
70
+ return new Set(
71
+ layersUnder(graph, rootIds).flatMap((layer) => Object.values(layer.boundVariables))
72
+ )
73
+ }
74
+
75
+ /** A value `defineVars` can write: a color, a number, a boolean, or an alias. */
76
+ function definable(variable: Variable): boolean {
77
+ if (variable.type === 'STRING') return false
78
+ return Object.values(variable.valuesByMode).every(
79
+ (value) =>
80
+ typeof value === 'number' ||
81
+ typeof value === 'boolean' ||
82
+ (typeof value === 'object' && ('aliasId' in value || 'r' in value))
83
+ )
84
+ }
85
+
86
+ /** Words JavaScript reserves, which no `const` may be named, as a mode named Default would be. */
87
+ const RESERVED_WORDS = [
88
+ 'await',
89
+ 'break',
90
+ 'case',
91
+ 'catch',
92
+ 'class',
93
+ 'const',
94
+ 'continue',
95
+ 'debugger',
96
+ 'default',
97
+ 'delete',
98
+ 'do',
99
+ 'else',
100
+ 'enum',
101
+ 'export',
102
+ 'extends',
103
+ 'false',
104
+ 'finally',
105
+ 'for',
106
+ 'function',
107
+ 'if',
108
+ 'implements',
109
+ 'import',
110
+ 'in',
111
+ 'instanceof',
112
+ 'interface',
113
+ 'let',
114
+ 'new',
115
+ 'null',
116
+ 'package',
117
+ 'private',
118
+ 'protected',
119
+ 'public',
120
+ 'return',
121
+ 'static',
122
+ 'super',
123
+ 'switch',
124
+ 'this',
125
+ 'throw',
126
+ 'true',
127
+ 'try',
128
+ 'typeof',
129
+ 'var',
130
+ 'void',
131
+ 'while',
132
+ 'with',
133
+ 'yield',
134
+ 'arguments',
135
+ 'eval',
136
+ 'undefined',
137
+ 'NaN',
138
+ 'Infinity'
139
+ ]
140
+
141
+ const TAKEN = new Set([
142
+ ...RESERVED_WORDS,
143
+ ...DESIGN_JSX_ELEMENTS.map((element) => element.name),
144
+ ...DESIGN_JSX_HELPERS.map((helper) => helper.name),
145
+ 'svg',
146
+ 'React'
147
+ ])
148
+
149
+ function handleName(name: string, taken: Set<string>, fallback: string): string {
150
+ const camel = camelCase(name)
151
+ const base = /^[A-Za-z_$][\w$]*$/.test(camel) ? camel : fallback
152
+ let candidate = base
153
+ for (let count = 2; taken.has(candidate); count++) candidate = `${base}${count}`
154
+ taken.add(candidate)
155
+ return candidate
156
+ }
157
+
158
+ interface DefinedCollection {
159
+ collection: VariableCollection
160
+ name: string
161
+ variables: Variable[]
162
+ /** Handles for the modes after the first, by mode ID. */
163
+ modes: Map<string, string>
164
+ }
165
+
166
+ /** The variable a value aliases, if it is an alias. */
167
+ function aliasOf(value: VariableValue | undefined): string | undefined {
168
+ return typeof value === 'object' && 'aliasId' in value ? value.aliasId : undefined
169
+ }
170
+
171
+ /**
172
+ * Whether rendering finds `variable` again by its collection's name and its own, as definitions
173
+ * are found: a name another collection or variable shares stays a reference rather than redefine
174
+ * whichever comes first.
175
+ */
176
+ function findsByName(graph: SceneGraph, variable: Variable): boolean {
177
+ const collection = graph.variableCollections.get(variable.collectionId)
178
+ if (!collection) return false
179
+ try {
180
+ return (
181
+ collectionNamed(graph, collection.name) === collection &&
182
+ resolveVariableId(graph, designVar(collection.name, variable.name)) === variable.id
183
+ )
184
+ } catch {
185
+ return false
186
+ }
187
+ }
188
+
189
+ /** The variables the layers bind that JSX can define, with every variable they alias. */
190
+ function definableVariables(graph: SceneGraph, rootIds: readonly string[]): Set<string> {
191
+ const included = new Set<string>()
192
+ const include = (variableId: string) => {
193
+ const variable = graph.variables.get(variableId)
194
+ if (!variable || included.has(variableId) || !definable(variable)) return
195
+ if (!findsByName(graph, variable)) return
196
+ included.add(variableId)
197
+ for (const value of Object.values(variable.valuesByMode)) {
198
+ const target = aliasOf(value)
199
+ if (target) include(target)
200
+ }
201
+ }
202
+ for (const id of boundVariableIds(graph, rootIds)) include(id)
203
+ return included
204
+ }
205
+
206
+ /** The variables by collection, each in its collection's order, as the variables panel lists them. */
207
+ function byCollectionOf(graph: SceneGraph, included: Set<string>): Map<string, Variable[]> {
208
+ const byCollection = new Map<string, Variable[]>()
209
+ for (const id of included) {
210
+ const variable = graph.variables.get(id)
211
+ if (variable)
212
+ byCollection.set(variable.collectionId, [
213
+ ...(byCollection.get(variable.collectionId) ?? []),
214
+ variable
215
+ ])
216
+ }
217
+ for (const [collectionId, variables] of byCollection) {
218
+ const listed = graph.variableCollections.get(collectionId)?.variableIds ?? []
219
+ variables.sort((a, b) => listed.indexOf(a.id) - listed.indexOf(b.id))
220
+ }
221
+ return byCollection
222
+ }
223
+
224
+ /** The collections in the order they are declared: after the ones their first mode aliases. */
225
+ function declarationOrder(graph: SceneGraph, byCollection: Map<string, Variable[]>): string[] {
226
+ const order: string[] = []
227
+ const visiting = new Set<string>()
228
+ const visit = (collectionId: string) => {
229
+ if (order.includes(collectionId) || visiting.has(collectionId)) return
230
+ visiting.add(collectionId)
231
+ const collection = graph.variableCollections.get(collectionId)
232
+ for (const variable of byCollection.get(collectionId) ?? []) {
233
+ const target = collection && aliasOf(variable.valuesByMode[collection.defaultModeId])
234
+ const aliased = target ? graph.variables.get(target) : undefined
235
+ if (aliased) visit(aliased.collectionId)
236
+ }
237
+ order.push(collectionId)
238
+ }
239
+ for (const id of byCollection.keys()) visit(id)
240
+ return order
241
+ }
242
+
243
+ /**
244
+ * What an export declares: the variables it can define and still have its code run. A first-mode
245
+ * value can only name a collection declared before its own, so one that aliases its own
246
+ * collection, or a later one in a cycle, is written by reference, which keeps the alias; and a
247
+ * declared value may alias only a declared variable, so one that aliases a reference, in any mode,
248
+ * is written by reference too.
249
+ */
250
+ function declaredVariables(graph: SceneGraph, rootIds: readonly string[]) {
251
+ const included = definableVariables(graph, rootIds)
252
+ let byCollection = byCollectionOf(graph, included)
253
+ const order = declarationOrder(graph, byCollection)
254
+ const declaredEarlier = (variable: Variable) => {
255
+ const collection = graph.variableCollections.get(variable.collectionId)
256
+ const target = collection && aliasOf(variable.valuesByMode[collection.defaultModeId])
257
+ const aliased = target && included.has(target) ? graph.variables.get(target) : undefined
258
+ return !aliased || order.indexOf(aliased.collectionId) < order.indexOf(variable.collectionId)
259
+ }
260
+ const aliasesDeclared = (variable: Variable) =>
261
+ Object.values(variable.valuesByMode).every((value) => {
262
+ const target = aliasOf(value)
263
+ return !target || included.has(target)
264
+ })
265
+ for (const variable of [...byCollection.values()].flat()) {
266
+ if (!declaredEarlier(variable)) included.delete(variable.id)
267
+ }
268
+ for (let dropped = 1; dropped > 0;) {
269
+ const unresolved = [...included].flatMap((id) => {
270
+ const variable = graph.variables.get(id)
271
+ return variable && !aliasesDeclared(variable) ? [id] : []
272
+ })
273
+ for (const id of unresolved) included.delete(id)
274
+ dropped = unresolved.length
275
+ }
276
+ // What is left is declared only if a layer still uses it, itself or through an alias.
277
+ const used = new Set<string>()
278
+ const use = (variableId: string) => {
279
+ const variable = graph.variables.get(variableId)
280
+ if (!variable || used.has(variableId) || !included.has(variableId)) return
281
+ used.add(variableId)
282
+ for (const value of Object.values(variable.valuesByMode)) {
283
+ const target = aliasOf(value)
284
+ if (target) use(target)
285
+ }
286
+ }
287
+ for (const id of boundVariableIds(graph, rootIds)) use(id)
288
+ for (const id of included) if (!used.has(id)) included.delete(id)
289
+ byCollection = byCollectionOf(graph, included)
290
+ return { included, byCollection, order }
291
+ }
292
+
293
+ /**
294
+ * Writes the collections the layers use as `defineVars`, with a `defineMode` for each mode after
295
+ * the first, so the JSX carries its tokens: only the variables it binds and those they alias.
296
+ * Variables JSX cannot define, such as formulas, and collections whose name is not unique are
297
+ * written by reference.
298
+ */
299
+ function definitionExport(graph: SceneGraph, rootIds: readonly string[]): VariableExport {
300
+ const references = variableReferences(graph)
301
+ const { included, byCollection, order } = declaredVariables(graph, rootIds)
302
+
303
+ const taken = new Set(TAKEN)
304
+ const defined = new Map<string, DefinedCollection>()
305
+ for (const collectionId of order) {
306
+ const collection = graph.variableCollections.get(collectionId)
307
+ if (!collection || !byCollection.get(collectionId)?.length) continue
308
+ defined.set(collectionId, {
309
+ collection,
310
+ name: handleName(collection.name, taken, 'vars'),
311
+ variables: byCollection.get(collectionId) ?? [],
312
+ modes: new Map()
313
+ })
314
+ }
315
+ for (const entry of defined.values()) {
316
+ for (const mode of modesDefaultFirst(entry.collection).slice(1)) {
317
+ entry.modes.set(mode.modeId, handleName(mode.name, taken, `${entry.name}Mode`))
318
+ }
319
+ }
320
+
321
+ const variable = (variableId: string): JSXValue => {
322
+ const found = graph.variables.get(variableId)
323
+ const entry = found && included.has(variableId) ? defined.get(found.collectionId) : undefined
324
+ return entry && found ? new Reference(entry.name, found.name) : references.variable(variableId)
325
+ }
326
+ const value = (raw: VariableValue | undefined): JSXValue | undefined => {
327
+ if (typeof raw === 'number' || typeof raw === 'boolean') return raw
328
+ if (typeof raw !== 'object') return undefined
329
+ if ('aliasId' in raw) return variable(raw.aliasId)
330
+ return 'r' in raw ? formatColor(raw, raw.a) : undefined
331
+ }
332
+ const values = (variables: Variable[], modeId: string, base?: string) =>
333
+ Object.fromEntries(
334
+ variables.flatMap((item) => {
335
+ const written = value(item.valuesByMode[modeId])
336
+ const first = base === undefined ? undefined : value(item.valuesByMode[base])
337
+ if (written === undefined) return []
338
+ if (base !== undefined && isEqual(written, first)) return []
339
+ return [[item.name, written]]
340
+ })
341
+ )
342
+
343
+ return {
344
+ variable,
345
+ mode(collectionId, modeId) {
346
+ const name = defined.get(collectionId)?.modes.get(modeId)
347
+ return name ? new Reference(name) : references.mode(collectionId, modeId)
348
+ },
349
+ declarations() {
350
+ // Written as `ref()` declarations are, so the statements read like the JSX after them.
351
+ const statements: string[] = []
352
+ const declare = (name: string, value: JSXValue) =>
353
+ statements.push(`const ${name} = ${jsx.printJSX(valueSyntax(value))}`)
354
+ for (const entry of defined.values()) {
355
+ const [first] = modesDefaultFirst(entry.collection)
356
+ const options = first.name === DEFAULT_MODE_NAME ? undefined : { mode: first.name }
357
+ const call = helperCall(
358
+ 'defineVars',
359
+ entry.collection.name,
360
+ values(entry.variables, first.modeId),
361
+ options
362
+ )
363
+ declare(entry.name, call)
364
+ }
365
+ for (const entry of defined.values()) {
366
+ const [first] = modesDefaultFirst(entry.collection)
367
+ for (const [modeId, name] of entry.modes) {
368
+ const mode = entry.collection.modes.find((item) => item.modeId === modeId)
369
+ const call = helperCall(
370
+ 'defineMode',
371
+ new Reference(entry.name),
372
+ mode?.name ?? '',
373
+ values(entry.variables, modeId, first.modeId)
374
+ )
375
+ declare(name, call)
376
+ }
377
+ }
378
+ return statements.join('\n')
379
+ }
380
+ }
381
+ }
382
+
383
+ /**
384
+ * How an export writes variables: with `declare`, as the definitions its JSX carries, otherwise
385
+ * by reference to the document's own.
386
+ */
387
+ export function variableExport(
388
+ graph: SceneGraph,
389
+ rootIds: readonly string[],
390
+ declare: boolean
391
+ ): VariableExport {
392
+ return declare ? definitionExport(graph, rootIds) : variableReferences(graph)
393
+ }
package/src/fields.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { omit } from 'es-toolkit'
2
+
3
+ import type { NodeType, SceneGraph, SceneNode } from '@pairdraw/scene-graph'
4
+ import { createDefaultNode } from '@pairdraw/scene-graph/node-defaults'
5
+
6
+ import type { JSXAttributeSource } from './export'
7
+ import * as React from './mini-react'
8
+ import { buildComponent } from './render'
9
+ import { elementOverrides } from './renderer'
10
+ import { resolveToTree } from './tree'
11
+
12
+ export interface JSXNodeFields {
13
+ /** Every field the attributes describe, with defaults for the ones they leave out. */
14
+ fields: Partial<SceneNode>
15
+ /** Variable IDs by bound field, such as `fills/0/color`. */
16
+ bindings: Record<string, string>
17
+ }
18
+
19
+ /**
20
+ * The node state a `nodeType` node under `parentId` gets from `attributes`, as rendering
21
+ * would set it, without creating a node. Diffing two results gives the fields an attribute
22
+ * change moves, so an update leaves state that JSX does not describe untouched.
23
+ */
24
+ export function jsxNodeFields(
25
+ graph: SceneGraph,
26
+ nodeType: NodeType,
27
+ attributes: JSXAttributeSource[],
28
+ parentId: string
29
+ ): JSXNodeFields {
30
+ const source = `<Frame ${attributes.map((attribute) => attribute.source).join(' ')} />`
31
+ const tree = resolveToTree(React.createElement(buildComponent(source), null))
32
+ if (!tree) throw new Error(`Invalid JSX attributes: ${source}`)
33
+ const { overrides, bindings } = elementOverrides(graph, nodeType, tree, parentId)
34
+ const defaults = omit(
35
+ createDefaultNode(() => '', nodeType),
36
+ ['id', 'parentId', 'childIds']
37
+ )
38
+ return { fields: { ...defaults, ...overrides }, bindings }
39
+ }