@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,189 @@
1
+ import type { SyntaxNode } from '@lezer/common'
2
+ import { decodeHTML } from 'entities'
3
+
4
+ import { DESIGN_JSX_ELEMENTS } from '../elements'
5
+ import { FRAGMENT, type TreeNode } from '../tree'
6
+ import { readLiteral } from './literals'
7
+
8
+ const ELEMENT_TYPES = new Map(
9
+ DESIGN_JSX_ELEMENTS.map(({ name, runtimeType }) => [name, runtimeType])
10
+ )
11
+ const MAX_PREVIEW_DEPTH = 100
12
+ const MAX_PREVIEW_NODES = 10_000
13
+
14
+ export interface JSXPreviewNode extends TreeNode {
15
+ /** Stable identity within an append-only source stream; not a permanent scene node ID. */
16
+ sourceStart: number
17
+ children: (JSXPreviewNode | string)[]
18
+ }
19
+
20
+ export interface JSXPreviewPending {
21
+ from: number
22
+ to: number
23
+ reason: 'incomplete' | 'unsupported'
24
+ }
25
+
26
+ export interface JSXPreviewSnapshot {
27
+ tree: JSXPreviewNode | null
28
+ pending: JSXPreviewPending[]
29
+ }
30
+
31
+ function children(node: SyntaxNode): SyntaxNode[] {
32
+ const result: SyntaxNode[] = []
33
+ for (let child = node.firstChild; child; child = child.nextSibling) result.push(child)
34
+ return result
35
+ }
36
+
37
+ function hasError(node: SyntaxNode): boolean {
38
+ let error = false
39
+ node.cursor().iterate((child) => {
40
+ if (child.type.isError) error = true
41
+ return !error
42
+ })
43
+ return error
44
+ }
45
+
46
+ /** Match JSX's line-oriented whitespace handling, rather than HTML whitespace collapsing. */
47
+ function textValue(raw: string): string {
48
+ const lines = raw.split(/\r\n|\n|\r/)
49
+ const lastNonEmpty = lines.findLastIndex((line) => /[^ \t]/.test(line))
50
+ return lines
51
+ .map((line, index) => {
52
+ let value = line.replaceAll('\t', ' ')
53
+ if (index > 0) value = value.replace(/^ +/, '')
54
+ if (index < lines.length - 1) value = value.replace(/ +$/, '')
55
+ return value && index < lastNonEmpty ? `${value} ` : value
56
+ })
57
+ .join('')
58
+ }
59
+
60
+ export function projectPreview(root: SyntaxNode, source: string): JSXPreviewSnapshot {
61
+ const pending: JSXPreviewPending[] = []
62
+ let nodeCount = 0
63
+ const raw = (node: SyntaxNode) => source.slice(node.from, node.to)
64
+ const defer = (node: SyntaxNode, reason: JSXPreviewPending['reason']) => {
65
+ pending.push({ from: node.from, to: node.to, reason })
66
+ }
67
+
68
+ function expression(node: SyntaxNode) {
69
+ if (hasError(node) || !raw(node).endsWith('}')) {
70
+ defer(node, 'incomplete')
71
+ return null
72
+ }
73
+ const value = readLiteral(raw(node).slice(1, -1))
74
+ if (!value) defer(node, 'unsupported')
75
+ return value
76
+ }
77
+
78
+ function attributes(opening: SyntaxNode): Record<string, unknown> | null {
79
+ const props: Record<string, unknown> = {}
80
+ for (const attribute of children(opening)) {
81
+ if (attribute.name === 'JSXSpreadAttribute') {
82
+ // A spread can change any prop, so don't guess the element's appearance.
83
+ defer(attribute, 'unsupported')
84
+ return null
85
+ }
86
+ if (attribute.name !== 'JSXAttribute') continue
87
+ const keyNode = attribute.firstChild
88
+ if (keyNode?.name !== 'JSXIdentifier') {
89
+ defer(attribute, 'unsupported')
90
+ continue
91
+ }
92
+ const key = raw(keyNode)
93
+ const valueNode = attribute.lastChild
94
+ let value: unknown = true
95
+ if (valueNode && valueNode !== keyNode && valueNode.from !== keyNode.from) {
96
+ if (valueNode.name === 'JSXAttributeValue') {
97
+ value = decodeHTML(
98
+ raw(valueNode)
99
+ .slice(1, -1)
100
+ .replace(/\r\n|[\r\n\t]/g, ' ')
101
+ )
102
+ } else if (valueNode.name === 'JSXEscape') {
103
+ const literal = expression(valueNode)
104
+ if (!literal) continue
105
+ value = literal.value
106
+ } else {
107
+ defer(attribute, 'unsupported')
108
+ continue
109
+ }
110
+ }
111
+ // defineProperty handles __proto__ as data, never as a prototype mutation.
112
+ Object.defineProperty(props, key, {
113
+ value,
114
+ enumerable: true,
115
+ configurable: true,
116
+ writable: true
117
+ })
118
+ }
119
+ return props
120
+ }
121
+
122
+ function element(node: SyntaxNode, depth: number): JSXPreviewNode | null {
123
+ if (depth > MAX_PREVIEW_DEPTH || ++nodeCount > MAX_PREVIEW_NODES) {
124
+ throw new RangeError('JSX preview tree limit exceeded')
125
+ }
126
+ const opening = node.firstChild
127
+ if (!opening || !['JSXOpenTag', 'JSXSelfClosingTag', 'JSXFragmentTag'].includes(opening.name)) {
128
+ defer(node, 'unsupported')
129
+ return null
130
+ }
131
+ // Recovery can synthesize a self-closing tag without an authored />.
132
+ const delimiter = opening.lastChild
133
+ if (hasError(opening) || !delimiter || !['>', '/>'].includes(raw(delimiter))) {
134
+ defer(opening, 'incomplete')
135
+ return null
136
+ }
137
+ const tagName = opening.getChild('JSXIdentifier') ?? opening.getChild('JSXBuiltin')
138
+ const fragment = raw(opening) === '<>'
139
+ const name = tagName ? raw(tagName) : ''
140
+ const type = fragment
141
+ ? FRAGMENT
142
+ : (ELEMENT_TYPES.get(name) ?? (/^[a-z][\w-]*$/.test(name) ? name : null))
143
+ if (type === null) {
144
+ defer(opening, 'unsupported')
145
+ return null
146
+ }
147
+ const props = attributes(opening)
148
+ if (!props) return null
149
+ const result: JSXPreviewNode = { type, props, children: [], sourceStart: node.from }
150
+ appendChildren(node, result, depth)
151
+ return result
152
+ }
153
+
154
+ function appendChildren(node: SyntaxNode, result: JSXPreviewNode, depth: number): void {
155
+ for (const child of children(node).slice(1)) {
156
+ if (child.name === 'JSXElement') {
157
+ const projected = element(child, depth + 1)
158
+ // A nested fragment adds its children, as it does in rendered trees.
159
+ if (projected?.type === FRAGMENT) result.children.push(...projected.children)
160
+ else if (projected) result.children.push(projected)
161
+ } else if (child.name === 'JSXText') {
162
+ let value = raw(child)
163
+ if (child.to === source.length) {
164
+ // Don't flash a partial entity or a split UTF-16 surrogate as literal text.
165
+ value = value.replace(/&(?:#x?[\da-f]*|[a-z]*)$/i, '').replace(/[\uD800-\uDBFF]$/, '')
166
+ }
167
+ value = decodeHTML(textValue(value))
168
+ if (value) result.children.push(value)
169
+ } else if (child.name === 'JSXEscape') {
170
+ const literal = expression(child)
171
+ if (literal && (typeof literal.value === 'string' || typeof literal.value === 'number')) {
172
+ result.children.push(String(literal.value))
173
+ } else if (literal && typeof literal.value === 'object' && literal.value !== null) {
174
+ defer(child, 'unsupported')
175
+ }
176
+ } else if (child.type.isError || hasError(child)) {
177
+ defer(child, 'incomplete')
178
+ }
179
+ }
180
+ }
181
+
182
+ const first = root.firstChild
183
+ if (!first) return { tree: null, pending }
184
+ if (first.name !== 'JSXElement') {
185
+ defer(first, hasError(root) ? 'incomplete' : 'unsupported')
186
+ return { tree: null, pending }
187
+ }
188
+ return { tree: element(first, 0), pending }
189
+ }
@@ -0,0 +1,233 @@
1
+ import { isEmptyObject, isEqual, omitBy, pick } from 'es-toolkit'
2
+ import * as v from 'valibot'
3
+
4
+ import type {
5
+ CharacterStyleOverride,
6
+ SceneNode,
7
+ StyleRun,
8
+ TextParagraphStyle
9
+ } from '@pairdraw/scene-graph'
10
+ import { createDefaultNode } from '@pairdraw/scene-graph/node-defaults'
11
+ import {
12
+ MAX_LIST_INDENTATION,
13
+ paragraphCount,
14
+ PLAIN_PARAGRAPH,
15
+ trimParagraphStyles
16
+ } from '@pairdraw/scene-graph/text'
17
+
18
+ import { parseScriptInput } from './schema'
19
+ import { isTreeNode, type TreeNode } from './tree'
20
+
21
+ /** `<Span>`: characters of a text styled apart from the rest of it. */
22
+ const SPAN = 'text-span'
23
+ /** `<Paragraph>`: one paragraph of a text, with its list and spacing. */
24
+ const PARAGRAPH = 'text-paragraph'
25
+
26
+ /** The names `<Span>` and `<Paragraph>` are written under, for messages about them. */
27
+ export const TEXT_CONTENT_NAMES: Readonly<Partial<Record<string, string>>> = {
28
+ [SPAN]: 'Span',
29
+ [PARAGRAPH]: 'Paragraph'
30
+ }
31
+
32
+ /** The character styles a `<Span>` sets, as the fields `<Text>`'s props set on a text. */
33
+ export const SPAN_STYLE_FIELDS = [
34
+ 'fontFamily',
35
+ 'fontSize',
36
+ 'fontWeight',
37
+ 'italic',
38
+ 'fills',
39
+ 'letterSpacing',
40
+ 'lineHeight',
41
+ 'textDecoration',
42
+ 'textDecorationStyle',
43
+ 'textDecorationFills',
44
+ 'textDecorationThickness',
45
+ 'textUnderlineOffset',
46
+ 'textDecorationSkipInk',
47
+ 'fontFeatures',
48
+ 'fontVariations',
49
+ 'textLanguage',
50
+ 'textCase'
51
+ ] as const satisfies readonly (keyof CharacterStyleOverride & keyof SceneNode)[]
52
+
53
+ /** A span's character styles and the URL it links to, which only characters have. */
54
+ export type SpanStyle = Pick<
55
+ CharacterStyleOverride,
56
+ (typeof SPAN_STYLE_FIELDS)[number] | 'hyperlink'
57
+ >
58
+
59
+ /** The fields an element's props set on a text node, as `propsToOverrides` reads them. */
60
+ export type SpanOverrides = (props: Record<string, unknown>) => Partial<SceneNode>
61
+
62
+ export type TextContentFields = Partial<Pick<SceneNode, 'text' | 'styleRuns' | 'textParagraphs'>>
63
+
64
+ const lengthSchema = v.pipe(v.number(), v.finite())
65
+
66
+ const paragraphPropsSchema = v.pipe(
67
+ v.object({
68
+ list: v.optional(v.picklist(['ordered', 'unordered'])),
69
+ level: v.optional(
70
+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(MAX_LIST_INDENTATION))
71
+ ),
72
+ spacing: v.optional(lengthSchema),
73
+ listSpacing: v.optional(lengthSchema),
74
+ indent: v.optional(lengthSchema)
75
+ }),
76
+ v.check(
77
+ (props) => props.level === undefined || props.list !== undefined,
78
+ '`level` nests list items; set `list` too'
79
+ )
80
+ )
81
+
82
+ /** Characters appended so far, each stretch with the style its spans give it. */
83
+ interface Segment {
84
+ length: number
85
+ style: SpanStyle
86
+ }
87
+
88
+ /** Whether a child is `<Span>` or `<Paragraph>`, which are part of their text, not layers. */
89
+ export function isTextContent(child: TreeNode | string): boolean {
90
+ return isTreeNode(child) && (child.type === SPAN || child.type === PARAGRAPH)
91
+ }
92
+
93
+ const spanLinkSchema = v.object({ href: v.optional(v.pipe(v.string(), v.trim(), v.nonEmpty())) })
94
+
95
+ function spanStyle(props: Record<string, unknown>, spanOverrides: SpanOverrides): SpanStyle {
96
+ const style: SpanStyle = omitBy(
97
+ pick(spanOverrides(props), SPAN_STYLE_FIELDS),
98
+ (value) => value === undefined
99
+ )
100
+ const { href } = parseScriptInput('Invalid <Span> props', spanLinkSchema, props)
101
+ if (href) style.hyperlink = { type: 'URL', value: href }
102
+ return style
103
+ }
104
+
105
+ function appendContent(
106
+ segments: Segment[],
107
+ children: TreeNode['children'],
108
+ inherited: SpanStyle,
109
+ owner: string,
110
+ spanOverrides: SpanOverrides
111
+ ): void {
112
+ for (const child of children) {
113
+ if (typeof child === 'string') {
114
+ segments.push({ length: child.length, style: inherited })
115
+ } else if (child.type === SPAN) {
116
+ // Nested spans style their characters over the span around them.
117
+ const style = { ...inherited, ...spanStyle(child.props, spanOverrides) }
118
+ appendContent(segments, child.children, style, '<Span>', spanOverrides)
119
+ } else if (child.type === PARAGRAPH) {
120
+ throw new Error(`<Paragraph> must be a direct child of <Text>, not of ${owner}`)
121
+ } else {
122
+ throw new Error(`${owner} can hold only text and <Span>, not <${child.type}>`)
123
+ }
124
+ }
125
+ }
126
+
127
+ function textOf(children: TreeNode['children']): string {
128
+ return children
129
+ .map((child) => (typeof child === 'string' ? child : textOf(child.children)))
130
+ .join('')
131
+ }
132
+
133
+ function paragraphStyle(props: Record<string, unknown>): TextParagraphStyle {
134
+ const { list, level, spacing, listSpacing, indent } = parseScriptInput(
135
+ 'Invalid <Paragraph> props',
136
+ paragraphPropsSchema,
137
+ props
138
+ )
139
+ const style: TextParagraphStyle = list
140
+ ? { listType: list === 'ordered' ? 'ORDERED' : 'UNORDERED', indentation: level ?? 1 }
141
+ : { ...PLAIN_PARAGRAPH }
142
+ if (spacing !== undefined) style.paragraphSpacing = spacing
143
+ if (listSpacing !== undefined) style.listSpacing = listSpacing
144
+ if (indent !== undefined) style.paragraphIndent = indent
145
+ return style
146
+ }
147
+
148
+ /** The `<Paragraph>` children of a text, or null without any; other content beside them is an error. */
149
+ function paragraphElements(tree: TreeNode): TreeNode[] | null {
150
+ const paragraphs = tree.children.filter(
151
+ (child): child is TreeNode => isTreeNode(child) && child.type === PARAGRAPH
152
+ )
153
+ if (paragraphs.length === 0) return null
154
+ const mixed = tree.children.some((child) =>
155
+ typeof child === 'string' ? child.trim() !== '' : child.type !== PARAGRAPH
156
+ )
157
+ if (mixed) {
158
+ throw new Error(
159
+ '<Text> mixes <Paragraph> with other content: put all of its text in <Paragraph> elements, or use none'
160
+ )
161
+ }
162
+ return paragraphs
163
+ }
164
+
165
+ /** Runs for the segments, holding only what differs from the text's own style. */
166
+ function styleRuns(segments: readonly Segment[], textStyle: SpanStyle): StyleRun[] {
167
+ const runs: StyleRun[] = []
168
+ let start = 0
169
+ for (const segment of segments) {
170
+ const style = omitBy(segment.style, (value, key) => isEqual(value, textStyle[key]))
171
+ if (segment.length > 0 && !isEmptyObject(style)) {
172
+ const previous = runs.at(-1)
173
+ const adjoins = previous && previous.start + previous.length === start
174
+ if (adjoins && isEqual(previous.style, style)) previous.length += segment.length
175
+ else runs.push({ start, length: segment.length, style })
176
+ }
177
+ start += segment.length
178
+ }
179
+ return runs
180
+ }
181
+
182
+ /** The style of the last character appended, which a newline after it takes, as in Figma. */
183
+ function lastStyle(segments: readonly Segment[]): SpanStyle {
184
+ return segments.findLast((segment) => segment.length > 0)?.style ?? {}
185
+ }
186
+
187
+ /**
188
+ * The text a `<Text>` element's children and text props give. Strings alone are its text, as
189
+ * before; `<Span>` children also give style runs and `<Paragraph>` children paragraph styles.
190
+ * `overrides` are the text's own fields, which runs leave out.
191
+ */
192
+ export function textContentFields(
193
+ tree: TreeNode,
194
+ props: Record<string, unknown>,
195
+ overrides: Partial<SceneNode>,
196
+ spanOverrides: SpanOverrides
197
+ ): TextContentFields {
198
+ if (!tree.children.some(isTextContent)) {
199
+ const childText = tree.children.filter((c): c is string => typeof c === 'string').join('')
200
+ const propText =
201
+ props.text ?? props.characters ?? props.content ?? props.label ?? props.value ?? props.title
202
+ if (childText) return { text: childText }
203
+ return typeof propText === 'string' ? { text: propText } : {}
204
+ }
205
+
206
+ const textStyle = pick(
207
+ createDefaultNode(() => '', 'TEXT', overrides),
208
+ SPAN_STYLE_FIELDS
209
+ )
210
+ const segments: Segment[] = []
211
+ const paragraphs = paragraphElements(tree)
212
+ if (!paragraphs) {
213
+ appendContent(segments, tree.children, {}, '<Text>', spanOverrides)
214
+ return { text: textOf(tree.children), styleRuns: styleRuns(segments, textStyle) }
215
+ }
216
+
217
+ const styles: TextParagraphStyle[] = []
218
+ const lines: string[] = []
219
+ for (const paragraph of paragraphs) {
220
+ if (lines.length > 0) segments.push({ length: 1, style: lastStyle(segments) })
221
+ appendContent(segments, paragraph.children, {}, '<Paragraph>', spanOverrides)
222
+ const content = textOf(paragraph.children)
223
+ // A line break inside a paragraph's text starts paragraphs of the same style.
224
+ const style = paragraphStyle(paragraph.props)
225
+ for (let index = 0; index < paragraphCount(content); index++) styles.push(style)
226
+ lines.push(content)
227
+ }
228
+ return {
229
+ text: lines.join('\n'),
230
+ styleRuns: styleRuns(segments, textStyle),
231
+ textParagraphs: trimParagraphStyles(styles, styles.length)
232
+ }
233
+ }
@@ -0,0 +1,78 @@
1
+ import { parse } from 'acorn'
2
+ import { transform } from 'sucrase'
3
+
4
+ const options = {
5
+ transforms: ['typescript', 'jsx'] as Array<'typescript' | 'jsx'>,
6
+ jsxPragma: '__h',
7
+ jsxFragmentPragma: '__fragment',
8
+ production: true
9
+ }
10
+
11
+ /**
12
+ * Transformed Design JSX: a function body that returns what the source renders. Its elements
13
+ * carry `__source: { lineNumber }` props; adding `lineOffset` to `lineNumber` gives the 1-based
14
+ * line in the source that was passed in.
15
+ */
16
+ export interface DesignJSXProgram {
17
+ code: string
18
+ lineOffset: number
19
+ }
20
+
21
+ const RULE = 'Design JSX is one JSX expression, or statements that end with `return` and the JSX'
22
+
23
+ function lineCount(text: string): number {
24
+ let lines = 0
25
+ for (const char of text) if (char === '\n') lines++
26
+ return lines
27
+ }
28
+
29
+ function transformBody(body: string, withLines: boolean): string {
30
+ return withLines
31
+ ? transform(body, { ...options, production: false, filePath: 'design.jsx' }).code
32
+ : transform(body, options).code
33
+ }
34
+
35
+ /** Whether a function body returns from its top level, as statements must end. */
36
+ function returns(code: string): boolean {
37
+ const program = parse(code, { ecmaVersion: 'latest', allowReturnOutsideFunction: true })
38
+ return program.body.some((statement) => statement.type === 'ReturnStatement')
39
+ }
40
+
41
+ /**
42
+ * The function body a Design JSX string stands for, tried in order: one JSX expression, sibling
43
+ * elements, or statements that end with `return` and the JSX, as a component's body does. Each
44
+ * keeps the source's lines where they are.
45
+ */
46
+ function transformProgram(source: string, withLines: boolean): DesignJSXProgram {
47
+ const trimmed = source.trim()
48
+ const lineOffset = lineCount(source.slice(0, source.length - source.trimStart().length))
49
+ const expressions = [`return (${trimmed})`]
50
+ if (trimmed.startsWith('<')) expressions.push(`return (<>${trimmed}</>)`)
51
+ for (const body of expressions) {
52
+ try {
53
+ return { code: transformBody(body, withLines), lineOffset }
54
+ } catch {
55
+ continue
56
+ }
57
+ }
58
+ let code: string
59
+ try {
60
+ code = transformBody(trimmed, withLines)
61
+ } catch (error) {
62
+ throw new Error(`${RULE}: ${error instanceof Error ? error.message : String(error)}`, {
63
+ cause: error
64
+ })
65
+ }
66
+ if (!returns(code)) throw new Error(`${RULE}; these statements return nothing.`)
67
+ return { code, lineOffset }
68
+ }
69
+
70
+ /** Transform Design JSX into the body of a function that returns what it renders. */
71
+ export function transformDesignJSXExpression(source: string): string {
72
+ return transformProgram(source, false).code
73
+ }
74
+
75
+ /** Like {@link transformDesignJSXExpression}, keeping the source line of every element. */
76
+ export function transformDesignJSXProgram(source: string): DesignJSXProgram {
77
+ return transformProgram(source, true)
78
+ }