@open-pencil/scene-graph 0.15.0 → 0.16.0-beta.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 (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +596 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +573 -521
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2021 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/fields/text.js +36 -0
  34. package/dist/chunks/fields/text.js.map +1 -0
  35. package/dist/chunks/group-bounds.js +104 -0
  36. package/dist/chunks/group-bounds.js.map +1 -0
  37. package/dist/chunks/icons/glyph.js +147 -0
  38. package/dist/chunks/icons/glyph.js.map +1 -0
  39. package/dist/chunks/index.js +1712 -662
  40. package/dist/chunks/index.js.map +1 -1
  41. package/dist/color.d.ts +72 -0
  42. package/dist/color.d.ts.map +1 -0
  43. package/dist/color.js +3 -0
  44. package/dist/constants.d.ts +2 -2
  45. package/dist/constants.js +2 -2
  46. package/dist/constants2.d.ts +3 -1
  47. package/dist/constants2.d.ts.map +1 -1
  48. package/dist/coordinate.d.ts +2 -448
  49. package/dist/coordinate.js +2 -2
  50. package/dist/copy.d.ts +1 -1
  51. package/dist/copy.js +1 -1
  52. package/dist/css.d.ts +39 -0
  53. package/dist/css.d.ts.map +1 -0
  54. package/dist/css.js +3 -0
  55. package/dist/geometry.d.ts +1 -1
  56. package/dist/geometry.js +1 -1
  57. package/dist/gradient.d.ts +51 -0
  58. package/dist/gradient.d.ts.map +1 -0
  59. package/dist/gradient.js +132 -0
  60. package/dist/gradient.js.map +1 -0
  61. package/dist/guides.d.ts +2 -2
  62. package/dist/guides.js +39 -0
  63. package/dist/guides.js.map +1 -0
  64. package/dist/hit-test.d.ts +2 -9
  65. package/dist/hit-test.js +154 -18
  66. package/dist/hit-test.js.map +1 -1
  67. package/dist/index.d.ts +4 -8
  68. package/dist/index.js +20 -5
  69. package/dist/instances.d.ts +2 -2
  70. package/dist/instances.js +2 -2
  71. package/dist/layout.d.ts +2 -0
  72. package/dist/layout.js +4 -0
  73. package/dist/node-defaults.d.ts +2 -8
  74. package/dist/node-defaults.js +2 -2
  75. package/dist/order-keys.d.ts +39 -0
  76. package/dist/order-keys.d.ts.map +1 -0
  77. package/dist/order-keys.js +136 -0
  78. package/dist/order-keys.js.map +1 -0
  79. package/dist/parse-path.d.ts +7 -1
  80. package/dist/parse-path.d.ts.map +1 -1
  81. package/dist/parse-path.js +6 -2
  82. package/dist/parse-path.js.map +1 -1
  83. package/dist/polygon.d.ts +53 -0
  84. package/dist/polygon.d.ts.map +1 -0
  85. package/dist/polygon.js +205 -0
  86. package/dist/polygon.js.map +1 -0
  87. package/dist/preview.d.ts +1 -1
  88. package/dist/random.d.ts +7 -0
  89. package/dist/random.d.ts.map +1 -0
  90. package/dist/random.js +2 -0
  91. package/dist/resize.d.ts +11 -2
  92. package/dist/resize.d.ts.map +1 -1
  93. package/dist/resize.js +2 -184
  94. package/dist/snap.d.ts +1 -1
  95. package/dist/text-direction.d.ts +13 -0
  96. package/dist/text-direction.d.ts.map +1 -0
  97. package/dist/text-direction.js +31 -0
  98. package/dist/text-direction.js.map +1 -0
  99. package/dist/text-picture.d.ts +1 -1
  100. package/dist/text-picture.d.ts.map +1 -1
  101. package/dist/text.d.ts +2 -0
  102. package/dist/text.js +3 -0
  103. package/dist/types.d.ts +2063 -13
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js +2 -1
  106. package/dist/types2.d.ts +2 -2
  107. package/dist/undo.d.ts +2 -2
  108. package/dist/undo.js +2 -2
  109. package/dist/undo2.d.ts +29 -1
  110. package/dist/undo2.d.ts.map +1 -1
  111. package/dist/variables.d.ts +2 -29
  112. package/dist/variables.js +2 -2
  113. package/dist/variant-properties.d.ts +9 -1
  114. package/dist/variant-properties.d.ts.map +1 -1
  115. package/dist/variant-properties.js +36 -1
  116. package/dist/variant-properties.js.map +1 -1
  117. package/dist/vector-network.d.ts +1 -1
  118. package/dist/vector-network.js +1 -1
  119. package/package.json +60 -9
  120. package/src/behaviours/kinds.ts +185 -0
  121. package/src/behaviours/layers.ts +51 -0
  122. package/src/behaviours/model.ts +192 -0
  123. package/src/behaviours/schema.ts +58 -0
  124. package/src/behaviours/spec.ts +223 -0
  125. package/src/buffered-events.ts +64 -0
  126. package/src/color/contrast.ts +31 -0
  127. package/src/color/index.ts +88 -0
  128. package/src/color/management.ts +210 -0
  129. package/src/color/normalize.ts +7 -0
  130. package/src/color/okhcl.ts +201 -0
  131. package/src/comments/document.ts +51 -0
  132. package/src/comments/list.ts +52 -0
  133. package/src/comments/merge.ts +63 -0
  134. package/src/comments/threads.ts +156 -0
  135. package/src/components/exposure.ts +61 -0
  136. package/src/components/properties.ts +18 -15
  137. package/src/components/variants.ts +53 -0
  138. package/src/constants.ts +2 -0
  139. package/src/coordinate.ts +100 -43
  140. package/src/copy.ts +13 -5
  141. package/src/css/grid.ts +70 -0
  142. package/src/css/index.ts +9 -0
  143. package/src/css/layout.ts +53 -0
  144. package/src/css/shadows.ts +68 -0
  145. package/src/css/values.ts +42 -0
  146. package/src/export-format.ts +12 -0
  147. package/src/fields/geometry.ts +11 -0
  148. package/src/fields/text.ts +35 -0
  149. package/src/gradient.ts +166 -0
  150. package/src/group-bounds.ts +131 -0
  151. package/src/guides.ts +39 -0
  152. package/src/hit-test.ts +219 -25
  153. package/src/icons/glyph.ts +128 -0
  154. package/src/icons/model.ts +54 -0
  155. package/src/icons/schema.ts +18 -0
  156. package/src/index.ts +344 -56
  157. package/src/instance-overrides.ts +27 -0
  158. package/src/instances/copies.ts +239 -0
  159. package/src/instances/cycles.ts +73 -0
  160. package/src/instances/fields.ts +143 -0
  161. package/src/instances/main-component.ts +19 -0
  162. package/src/instances/placement.ts +29 -0
  163. package/src/instances/source-walk.ts +41 -0
  164. package/src/instances/sync.ts +599 -0
  165. package/src/instances.ts +122 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +1 -1
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/slots/authoring.ts +101 -0
  187. package/src/slots/content.ts +124 -0
  188. package/src/slots/frames.ts +160 -0
  189. package/src/slots/limits.ts +49 -0
  190. package/src/text/direction.ts +55 -0
  191. package/src/text/index.ts +2 -0
  192. package/src/text/lists.ts +138 -0
  193. package/src/text/paragraphs.ts +241 -0
  194. package/src/{text-picture.ts → text/picture.ts} +21 -29
  195. package/src/transfer/apply.ts +84 -0
  196. package/src/transfer/history.ts +49 -0
  197. package/src/transfer/identity.ts +16 -0
  198. package/src/transfer/index.ts +6 -0
  199. package/src/transfer/nodes.ts +108 -0
  200. package/src/transfer/plan.ts +107 -0
  201. package/src/transfer/references.ts +9 -0
  202. package/src/transfer/remove.ts +39 -0
  203. package/src/transfer/validation.ts +54 -0
  204. package/src/transfer/variables.ts +82 -0
  205. package/src/types.ts +221 -11
  206. package/src/undo.ts +54 -2
  207. package/src/variables/bindings.ts +186 -0
  208. package/src/variables/fields.ts +43 -0
  209. package/src/variables/token.ts +14 -0
  210. package/src/variables/units.ts +15 -0
  211. package/src/variables.ts +118 -69
  212. package/src/variant-properties.ts +50 -0
  213. package/dist/chunks/components/properties.js.map +0 -1
  214. package/dist/chunks/export-scale.js +0 -19
  215. package/dist/chunks/export-scale.js.map +0 -1
  216. package/dist/coordinate.d.ts.map +0 -1
  217. package/dist/coordinate2.d.ts +0 -2
  218. package/dist/guides2.d.ts +0 -11
  219. package/dist/guides2.d.ts.map +0 -1
  220. package/dist/hit-test.d.ts.map +0 -1
  221. package/dist/layout-guides.d.ts +0 -2
  222. package/dist/layout-guides.js +0 -2
  223. package/dist/layout-guides2.d.ts +0 -16
  224. package/dist/layout-guides2.d.ts.map +0 -1
  225. package/dist/node-defaults.d.ts.map +0 -1
  226. package/dist/preview2.d.ts +0 -12
  227. package/dist/preview2.d.ts.map +0 -1
  228. package/dist/resize.js.map +0 -1
  229. package/dist/variables.d.ts.map +0 -1
  230. package/dist/vector-network2.d.ts +0 -32
  231. package/dist/vector-network2.d.ts.map +0 -1
  232. package/src/instance-overrides.test.ts +0 -67
@@ -0,0 +1,246 @@
1
+ import * as v from 'valibot'
2
+
3
+ import { behaviourSchema } from '../behaviours/schema'
4
+ import type { OkHCLPayload } from '../color/okhcl'
5
+ import { isExportFormatId, type ExportFormatId } from '../export-format'
6
+ import { clampExportScale } from '../export-scale'
7
+ import { iconSchema, iconTintSchema } from '../icons/schema'
8
+ import type { Rect } from '../primitives'
9
+ import { shaderPaintSchema } from '../shaders/schema'
10
+ import {
11
+ MODE_ATTRIBUTE_PATTERN,
12
+ TOKEN_UNITS,
13
+ type CommentThread,
14
+ type EnabledLibraryBinding,
15
+ type ExportSetting,
16
+ type LayoutDirection,
17
+ type LibraryAssetSource,
18
+ type PluginDataEntry,
19
+ type SourceLibraryPublication,
20
+ type TextDirection,
21
+ type TokenUnit
22
+ } from '../types'
23
+ import {
24
+ jsonPluginDataField,
25
+ textPluginDataField,
26
+ withoutPluginData,
27
+ type PluginDataKey
28
+ } from './field'
29
+
30
+ const DIRECTIONS = ['AUTO', 'LTR', 'RTL'] as const satisfies readonly (
31
+ | TextDirection
32
+ | LayoutDirection
33
+ )[]
34
+
35
+ const textPathBox: v.GenericSchema<unknown, Rect> = v.pipe(
36
+ v.object({ x: v.number(), y: v.number(), width: v.number(), height: v.number() }),
37
+ v.check(
38
+ ({ x, y, width, height }) => Number.isFinite(x + y + width + height) && width > 0 && height > 0
39
+ )
40
+ )
41
+
42
+ /** String-valued entries of a JSON object; other entries are dropped, not rejected. */
43
+ const boundVariables = v.pipe(
44
+ v.custom<Record<string, unknown>>(
45
+ (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
46
+ ),
47
+ v.transform((value) =>
48
+ Object.fromEntries(
49
+ Object.entries(value).filter(
50
+ (entry): entry is [string, string] => typeof entry[1] === 'string'
51
+ )
52
+ )
53
+ )
54
+ )
55
+
56
+ /** Every entry must be valid, or the whole value is ignored in favour of native settings. */
57
+ const exportSettings: v.GenericSchema<unknown, ExportSetting[]> = v.array(
58
+ v.pipe(
59
+ v.object({
60
+ scale: v.pipe(v.number(), v.finite()),
61
+ format: v.custom<ExportFormatId>(isExportFormatId)
62
+ }),
63
+ // Clamp at the file boundary: imported plugin data may carry a scale the UI never produces.
64
+ v.transform(({ scale, format }) => ({ scale: clampExportScale(scale), format }))
65
+ )
66
+ )
67
+
68
+ const librarySource: v.GenericSchema<unknown, LibraryAssetSource> = v.pipe(
69
+ v.object({
70
+ identity: v.object({ libraryId: v.string(), assetKey: v.string(), revisionId: v.string() }),
71
+ sourceNodeId: v.optional(v.unknown()),
72
+ readOnly: v.optional(v.unknown())
73
+ }),
74
+ v.transform(({ identity, sourceNodeId, readOnly }) => ({
75
+ identity,
76
+ sourceNodeId: typeof sourceNodeId === 'string' ? sourceNodeId : null,
77
+ readOnly: readOnly === true
78
+ }))
79
+ )
80
+
81
+ const enabledLibrary = v.object({
82
+ libraryId: v.string(),
83
+ revisionId: v.string(),
84
+ enabled: v.optional(v.unknown())
85
+ })
86
+
87
+ /** Invalid entries are skipped one by one, so one bad binding keeps the others. */
88
+ const enabledLibraries: v.GenericSchema<unknown, EnabledLibraryBinding[]> = v.pipe(
89
+ v.array(v.unknown()),
90
+ v.transform((items) =>
91
+ items.flatMap((item) => {
92
+ const parsed = v.safeParse(enabledLibrary, item)
93
+ if (!parsed.success) return []
94
+ const { libraryId, revisionId, enabled } = parsed.output
95
+ return [{ libraryId, revisionId, enabled: enabled === true }]
96
+ })
97
+ )
98
+ )
99
+
100
+ // Shape only. Whether a string is valid CSS is checked where it is written into a stylesheet.
101
+ const cssText = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(1000))
102
+
103
+ /** Token fields Figma has no slot for, with mode ids as the file spells them. */
104
+ export interface StoredToken {
105
+ unit?: TokenUnit
106
+ expressions?: Record<string, { css: string; resolved: number }>
107
+ }
108
+
109
+ const token: v.GenericSchema<unknown, StoredToken> = v.object({
110
+ unit: v.optional(v.picklist(TOKEN_UNITS)),
111
+ expressions: v.optional(
112
+ v.record(v.string(), v.object({ css: cssText, resolved: v.pipe(v.number(), v.finite()) }))
113
+ )
114
+ })
115
+
116
+ const okhcl: v.GenericSchema<unknown, OkHCLPayload> = v.object({
117
+ version: v.literal(1),
118
+ kind: v.picklist(['fill', 'stroke']),
119
+ index: v.number(),
120
+ color: v.object({
121
+ h: v.number(),
122
+ c: v.number(),
123
+ l: v.number(),
124
+ a: v.fallback(v.optional(v.number()), undefined)
125
+ })
126
+ })
127
+
128
+ const sourceLibraryPublication: v.GenericSchema<unknown, SourceLibraryPublication> = v.object({
129
+ libraryId: v.string(),
130
+ revisionId: v.string(),
131
+ name: v.string(),
132
+ catalogSource: v.optional(v.string())
133
+ })
134
+
135
+ // Lenient on purpose: other tools may write comments, so missing fields get defaults and one
136
+ // malformed thread is skipped instead of hiding every comment.
137
+ const commentAuthorColor = v.fallback(
138
+ v.optional(v.object({ r: v.number(), g: v.number(), b: v.number(), a: v.number() })),
139
+ undefined
140
+ )
141
+
142
+ /** What a comment and each reply say, who wrote them and when, and whether they were deleted. */
143
+ const commentEntry = {
144
+ author: v.fallback(v.string(), ''),
145
+ authorColor: commentAuthorColor,
146
+ text: v.fallback(v.string(), ''),
147
+ createdAt: v.fallback(v.string(), ''),
148
+ deleted: v.optional(v.boolean())
149
+ }
150
+
151
+ const commentReply = v.object({ id: v.string(), ...commentEntry })
152
+
153
+ const commentThread = v.object({
154
+ id: v.string(),
155
+ pageId: v.string(),
156
+ pageName: v.optional(v.string()),
157
+ nodeId: v.optional(v.nullable(v.string())),
158
+ nodeName: v.optional(v.nullable(v.string())),
159
+ offsetX: v.optional(v.number()),
160
+ offsetY: v.optional(v.number()),
161
+ x: v.fallback(v.number(), 0),
162
+ y: v.fallback(v.number(), 0),
163
+ ...commentEntry,
164
+ updatedAt: v.fallback(v.string(), ''),
165
+ resolved: v.fallback(v.boolean(), false),
166
+ resolvedAt: v.optional(v.nullable(v.string())),
167
+ replies: v.fallback(v.array(commentReply), [])
168
+ })
169
+
170
+ const comments: v.GenericSchema<unknown, CommentThread[]> = v.pipe(
171
+ v.array(v.unknown()),
172
+ v.transform((items) =>
173
+ items.flatMap((item) => {
174
+ const parsed = v.safeParse(commentThread, item)
175
+ if (!parsed.success) return []
176
+ const thread = parsed.output
177
+ return [{ ...thread, updatedAt: thread.updatedAt || thread.createdAt }]
178
+ })
179
+ )
180
+ )
181
+
182
+ /**
183
+ * Every plugin-data entry OpenPencil writes under {@link OPEN_PENCIL_PLUGIN_ID}: state Figma's
184
+ * format has no field for. Add a key here, never as a string elsewhere, so reading and writing
185
+ * it share one schema.
186
+ */
187
+ export const OPEN_PENCIL_PLUGIN_DATA = {
188
+ /** A text node's direction, on TEXT nodes. */
189
+ textDirection: textPluginDataField('textDirection', 'format', DIRECTIONS),
190
+ /** An auto-layout frame's direction. */
191
+ layoutDirection: textPluginDataField('layoutDirection', 'format', DIRECTIONS),
192
+ /** Marks a component set Figma would read as a plain frame. */
193
+ nodeType: textPluginDataField('nodeType', 'format', ['COMPONENT_SET']),
194
+ /** Variable bindings by field path, including those Figma cannot store natively. */
195
+ boundVariables: jsonPluginDataField('boundVariables', 'format', boundVariables),
196
+ exportSettings: jsonPluginDataField('exportSettings', 'format', exportSettings),
197
+ /** The node-local rect a TEXT_PATH layout maps onto, which Kiwi has no field for. */
198
+ textPathBox: jsonPluginDataField('textPathBox', 'format', textPathBox),
199
+ /** The library asset a node was inserted from. */
200
+ librarySource: jsonPluginDataField('librarySource', 'bookkeeping', librarySource),
201
+ /** Libraries enabled for the document, on the DOCUMENT node. */
202
+ enabledLibraries: jsonPluginDataField('enabledLibraries', 'bookkeeping', enabledLibraries),
203
+ /** The library this document publishes as, on the DOCUMENT node. */
204
+ sourceLibraryPublication: jsonPluginDataField(
205
+ 'sourceLibraryPublication',
206
+ 'bookkeeping',
207
+ sourceLibraryPublication
208
+ ),
209
+ /** Canvas comment threads, deleted ones included, on the DOCUMENT node. */
210
+ comments: jsonPluginDataField('comments', 'bookkeeping', comments),
211
+ /** Unit and CSS expressions, on each VARIABLE. */
212
+ token: jsonPluginDataField('token', 'format', token),
213
+ /** Mode conditions by mode id, on each VARIABLE_SET. */
214
+ modeConditions: jsonPluginDataField('modeConditions', 'format', v.record(v.string(), cssText)),
215
+ /** The attribute that switches manual modes, on each VARIABLE_SET. */
216
+ modeAttribute: jsonPluginDataField(
217
+ 'modeAttribute',
218
+ 'format',
219
+ v.pipe(v.string(), v.trim(), v.maxLength(100), v.regex(MODE_ATTRIBUTE_PATTERN))
220
+ ),
221
+ /** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */
222
+ okhcl: jsonPluginDataField('okhcl', 'content', okhcl),
223
+ /** How a main component or component set behaves as a control in preview. */
224
+ behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema),
225
+ /** The icon a frame draws, such as `lucide:home`, on the frame its paths are in. */
226
+ icon: jsonPluginDataField('icon', 'content', iconSchema),
227
+ /** Which of an icon path's paints its icon's color sets, on each path the source drew in it. */
228
+ iconTint: jsonPluginDataField('iconTint', 'content', iconTintSchema),
229
+ /** One entry per paint that draws a shader, matched to its image paint by the frame's hash. */
230
+ shader: jsonPluginDataField('shader', 'content', shaderPaintSchema)
231
+ } satisfies Record<string, PluginDataKey>
232
+
233
+ const NOT_CONTENT = Object.values(OPEN_PENCIL_PLUGIN_DATA).filter(
234
+ (field) => field.role !== 'content'
235
+ )
236
+
237
+ /**
238
+ * A node's plugin data that is part of its content, in a stable order: OpenPencil's content
239
+ * fields and every other plugin's entries, which the node carries wherever it goes. Format
240
+ * copies of node fields and bookkeeping are left out.
241
+ */
242
+ export function contentPluginData(entries: readonly PluginDataEntry[]): PluginDataEntry[] {
243
+ return withoutPluginData(entries, NOT_CONTENT).sort(
244
+ (a, b) => a.pluginId.localeCompare(b.pluginId) || a.key.localeCompare(b.key)
245
+ )
246
+ }
package/src/polygon.ts ADDED
@@ -0,0 +1,211 @@
1
+ import { polygonVertices } from './geometry'
2
+ import type { Vector } from './primitives'
3
+ import type { SceneNode } from './types'
4
+
5
+ /**
6
+ * Rounded polygon and star outlines, as Figma draws them. Each corner, convex or not, is rounded by
7
+ * a circular arc tangent to both edges, capped so that it and its neighbours fit along every edge;
8
+ * corner smoothing replaces the arc's ends with curves that ease into the edges, as on rectangles.
9
+ */
10
+
11
+ /** Figma keeps a polygon's sides or a star's points within this range, and its plugin API clamps to it. */
12
+ export const POINT_COUNT_RANGE = { min: 3, max: 60 } as const
13
+
14
+ export type PolygonOutlineCommand =
15
+ | { type: 'M' | 'L'; x: number; y: number }
16
+ | { type: 'C'; x1: number; y1: number; x2: number; y2: number; x: number; y: number }
17
+ | { type: 'Z' }
18
+
19
+ type PolygonNode = Pick<
20
+ SceneNode,
21
+ | 'type'
22
+ | 'width'
23
+ | 'height'
24
+ | 'pointCount'
25
+ | 'starInnerRadius'
26
+ | 'cornerRadius'
27
+ | 'cornerSmoothing'
28
+ >
29
+
30
+ export interface PolygonCorner {
31
+ vertex: Vector
32
+ /** The unit direction of the edge arriving at the vertex. */
33
+ incoming: Vector
34
+ /** The unit direction of the edge leaving the vertex. */
35
+ outgoing: Vector
36
+ /** How far the outline turns at the vertex, in radians: 0 for a straight line. */
37
+ turn: number
38
+ /** The radius the corner is drawn with, after fitting it along its edges. */
39
+ radius: number
40
+ /** How far along each edge from the vertex the rounding starts. */
41
+ extent: number
42
+ }
43
+
44
+ const sub = (a: Vector, b: Vector): Vector => ({ x: a.x - b.x, y: a.y - b.y })
45
+ const along = (point: Vector, direction: Vector, distance: number): Vector => ({
46
+ x: point.x + direction.x * distance,
47
+ y: point.y + direction.y * distance
48
+ })
49
+
50
+ function unit(vector: Vector): Vector {
51
+ const length = Math.hypot(vector.x, vector.y)
52
+ return length > 0 ? { x: vector.x / length, y: vector.y / length } : { x: 0, y: 0 }
53
+ }
54
+
55
+ /** The perpendicular of `direction` on the side the outline turns towards. */
56
+ function inward(direction: Vector, towards: Vector): Vector {
57
+ const normal = { x: -direction.y, y: direction.x }
58
+ return normal.x * towards.x + normal.y * towards.y < 0
59
+ ? { x: direction.y, y: -direction.x }
60
+ : normal
61
+ }
62
+
63
+ /**
64
+ * The polygon's or star's corners with the radius each is drawn with. A corner turning by α keeps
65
+ * r·tan(α/2) of each edge, so on an edge of length L between corners turning by α and β the radius
66
+ * is at most L / (tan(α/2) + tan(β/2)); each corner takes the least of its two edges' limits.
67
+ */
68
+ export function polygonCorners(node: PolygonNode): PolygonCorner[] {
69
+ const vertices = polygonVertices(node)
70
+ const count = vertices.length
71
+ const at = (index: number) => vertices[(index + count) % count]
72
+ const shape = vertices.map((vertex, index) => {
73
+ const incoming = unit(sub(vertex, at(index - 1)))
74
+ const outgoing = unit(sub(at(index + 1), vertex))
75
+ const cos = Math.min(1, Math.max(-1, incoming.x * outgoing.x + incoming.y * outgoing.y))
76
+ const turn = Math.acos(cos)
77
+ return { vertex, incoming, outgoing, turn, factor: Math.tan(turn / 2) }
78
+ })
79
+ const edgeLimit = (index: number) => {
80
+ const from = shape[(index + count) % count]
81
+ const to = shape[(index + 1 + count) % count]
82
+ const length = Math.hypot(to.vertex.x - from.vertex.x, to.vertex.y - from.vertex.y)
83
+ const factors = from.factor + to.factor
84
+ return factors > 0 ? length / factors : Number.POSITIVE_INFINITY
85
+ }
86
+ const requested = Math.max(0, node.cornerRadius)
87
+ return shape.map(({ factor, ...corner }, index) => {
88
+ const radius = Math.min(requested, edgeLimit(index - 1), edgeLimit(index))
89
+ return { ...corner, radius, extent: radius * factor }
90
+ })
91
+ }
92
+
93
+ interface SmoothCorner {
94
+ /** Where the rounding starts, along each edge from the vertex. */
95
+ p: number
96
+ a: number
97
+ b: number
98
+ c: number
99
+ d: number
100
+ /** The angle each eased end takes from the arc, in radians. */
101
+ ease: number
102
+ }
103
+
104
+ /**
105
+ * Figma's smoothing for a corner turning by any angle: the rectangle construction with the
106
+ * tangent length r·tan(α/2) in place of r and α/2 in place of 45°. Smoothing grows the rounded
107
+ * part of each edge by up to its tangent length again.
108
+ */
109
+ function smoothCorner(corner: PolygonCorner, smoothing: number): SmoothCorner {
110
+ const { radius, extent } = corner
111
+ const p = (1 + smoothing) * extent
112
+ const ease = (corner.turn * smoothing) / 2
113
+ const toEase = radius * Math.tan(ease / 2)
114
+ const c = toEase * Math.cos(ease)
115
+ const d = toEase * Math.sin(ease)
116
+ const arcStart = extent - radius * Math.sin(ease) - d
117
+ const b = (p - arcStart - c - d) / 3
118
+ return { p, a: 2 * b, b, c, d, ease }
119
+ }
120
+
121
+ function rotate(direction: Vector, towards: Vector, angle: number): Vector {
122
+ const normal = inward(direction, towards)
123
+ return {
124
+ x: direction.x * Math.cos(angle) + normal.x * Math.sin(angle),
125
+ y: direction.y * Math.cos(angle) + normal.y * Math.sin(angle)
126
+ }
127
+ }
128
+
129
+ function cubic(c1: Vector, c2: Vector, to: Vector): PolygonOutlineCommand {
130
+ return { type: 'C', x1: c1.x, y1: c1.y, x2: c2.x, y2: c2.y, x: to.x, y: to.y }
131
+ }
132
+
133
+ /** The rounded corner from where it leaves the incoming edge to where it joins the outgoing one. */
134
+ function cornerCommands(corner: PolygonCorner, smooth: SmoothCorner): PolygonOutlineCommand[] {
135
+ const { vertex, incoming, outgoing, radius, turn } = corner
136
+ const { p, a, b, c, d, ease } = smooth
137
+ const back = { x: -incoming.x, y: -incoming.y }
138
+ const start = along(vertex, back, p)
139
+ const end = along(vertex, outgoing, p)
140
+ const normalIn = inward(incoming, outgoing)
141
+ const normalOut = inward(outgoing, back)
142
+ const arcFrom = along(along(start, incoming, a + b + c), normalIn, d)
143
+ const arcTo = along(along(end, outgoing, -(a + b + c)), normalOut, d)
144
+ const commands: PolygonOutlineCommand[] = []
145
+ if (ease > 0)
146
+ commands.push(cubic(along(start, incoming, a), along(start, incoming, a + b), arcFrom))
147
+ const sweep = turn - 2 * ease
148
+ if (sweep > 0) {
149
+ const handle = (4 / 3) * Math.tan(sweep / 4) * radius
150
+ const leaving = rotate(incoming, outgoing, ease)
151
+ const arriving = rotate(outgoing, incoming, ease)
152
+ commands.push(cubic(along(arcFrom, leaving, handle), along(arcTo, arriving, -handle), arcTo))
153
+ }
154
+ if (ease > 0) commands.push(cubic(along(end, outgoing, -(a + b)), along(end, outgoing, -a), end))
155
+ return commands
156
+ }
157
+
158
+ /**
159
+ * The smoothing every corner can take: on each edge a corner may use the part its tangent length
160
+ * takes of both corners' tangent lengths, and Figma lowers smoothing for the whole shape to what
161
+ * its tightest corner allows rather than corner by corner.
162
+ */
163
+ function fittedSmoothing(corners: readonly PolygonCorner[], smoothing: number): number {
164
+ const count = corners.length
165
+ const share = (corner: PolygonCorner, neighbour: PolygonCorner) => {
166
+ const length = Math.hypot(
167
+ neighbour.vertex.x - corner.vertex.x,
168
+ neighbour.vertex.y - corner.vertex.y
169
+ )
170
+ return (length * corner.extent) / (corner.extent + neighbour.extent)
171
+ }
172
+ return corners.reduce(
173
+ (fitted, corner, index) => {
174
+ if (!(corner.extent > 0)) return fitted
175
+ const budget = Math.min(
176
+ share(corner, corners[(index - 1 + count) % count]),
177
+ share(corner, corners[(index + 1) % count])
178
+ )
179
+ return Math.min(fitted, budget / corner.extent - 1)
180
+ },
181
+ Math.min(Math.max(smoothing, 0), 1)
182
+ )
183
+ }
184
+
185
+ /** The outline of a polygon or star with its corner radius and smoothing, in its own pixels. */
186
+ export function polygonOutline(node: PolygonNode): PolygonOutlineCommand[] {
187
+ const corners = polygonCorners(node)
188
+ const smoothing = Math.max(0, fittedSmoothing(corners, node.cornerSmoothing))
189
+ const commands: PolygonOutlineCommand[] = []
190
+ let current: Vector | null = null
191
+ // Corners whose rounding meets along an edge leave no line between them.
192
+ const lineTo = ({ x, y }: Vector) => {
193
+ if (current && Math.hypot(x - current.x, y - current.y) < 1e-6) return
194
+ commands.push({ type: current ? 'L' : 'M', x, y })
195
+ current = { x, y }
196
+ }
197
+ for (const corner of corners) {
198
+ if (!(corner.radius > 0) || !(corner.turn > 0)) {
199
+ lineTo(corner.vertex)
200
+ continue
201
+ }
202
+ const smooth = smoothCorner(corner, smoothing)
203
+ lineTo(along(corner.vertex, { x: -corner.incoming.x, y: -corner.incoming.y }, smooth.p))
204
+ for (const command of cornerCommands(corner, smooth)) {
205
+ commands.push(command)
206
+ if (command.type === 'C') current = { x: command.x, y: command.y }
207
+ }
208
+ }
209
+ commands.push({ type: 'Z' })
210
+ return commands
211
+ }
package/src/preview.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { textCacheInvalidationChanges } from './text-picture'
1
+ import { textCacheInvalidationChanges } from './text/picture'
2
2
  import type { SceneNode } from './types'
3
3
  import { normalizeVectorNetwork } from './vector-network'
4
4
 
package/src/random.ts ADDED
@@ -0,0 +1,28 @@
1
+ export function randomHex(bytes = 16): string {
2
+ if (!Number.isInteger(bytes) || bytes < 0) {
3
+ throw new RangeError('bytes must be a non-negative integer')
4
+ }
5
+ const buf = crypto.getRandomValues(new Uint8Array(bytes))
6
+ let hex = ''
7
+ for (const b of buf) hex += b.toString(16).padStart(2, '0')
8
+ return hex
9
+ }
10
+
11
+ export function randomInt(): number {
12
+ return crypto.getRandomValues(new Int32Array(1))[0]
13
+ }
14
+
15
+ export function randomIndex(length: number): number {
16
+ if (!Number.isInteger(length) || length <= 0) {
17
+ throw new RangeError('length must be a positive integer')
18
+ }
19
+ const max = 0x1_0000_0000
20
+ const limit = max - (max % length)
21
+ const buffer = new Uint32Array(1)
22
+
23
+ do {
24
+ crypto.getRandomValues(buffer)
25
+ } while (buffer[0] >= limit)
26
+
27
+ return buffer[0] % length
28
+ }
package/src/resize.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  copyStrokes,
6
6
  scaleGeometryPaths
7
7
  } from './copy'
8
+ import { enforcedAspectRatio } from './layout/aspect-ratio'
8
9
  import type { Rect } from './primitives'
9
10
  import type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'
10
11
  import { cloneVectorNetwork } from './vector-network'
@@ -61,21 +62,51 @@ function constrainedAxis(
61
62
  return { position, size }
62
63
  }
63
64
 
65
+ type AxisPlacement = { position: number; size: number }
66
+
67
+ const FLEXIBLE_CONSTRAINTS: ReadonlySet<ConstraintType> = new Set(['STRETCH', 'SCALE'])
68
+
69
+ /** The axis at `size`, keeping the edge or centre its constraint pins where it was placed. */
70
+ function resizedInPlace(
71
+ placed: AxisPlacement,
72
+ size: number,
73
+ constraint: ConstraintType
74
+ ): AxisPlacement {
75
+ if (constraint === 'MAX') return { position: placed.position + placed.size - size, size }
76
+ if (constraint === 'CENTER') return { position: placed.position + (placed.size - size) / 2, size }
77
+ return { position: placed.position, size }
78
+ }
79
+
80
+ /**
81
+ * A locked aspect ratio holds when exactly one axis follows the parent, as in Figma: that axis
82
+ * sizes the other. With both axes following the parent, or neither, the ratio gives way.
83
+ */
84
+ function keepLockedRatio(
85
+ x: AxisPlacement,
86
+ y: AxisPlacement,
87
+ horizontal: ConstraintType,
88
+ vertical: ConstraintType,
89
+ aspectRatio: number | null
90
+ ): { x: AxisPlacement; y: AxisPlacement } {
91
+ const flexibleX = FLEXIBLE_CONSTRAINTS.has(horizontal)
92
+ if (aspectRatio === null || flexibleX === FLEXIBLE_CONSTRAINTS.has(vertical)) return { x, y }
93
+ return flexibleX
94
+ ? { x, y: resizedInPlace(y, x.size / aspectRatio, vertical) }
95
+ : { x: resizedInPlace(x, y.size * aspectRatio, horizontal), y }
96
+ }
97
+
98
+ /** A child's box after its parent resizes, keeping a locked aspect ratio as Figma does. */
64
99
  export function constrainedChildRect(
65
100
  child: Rect,
66
101
  parentBefore: Pick<Rect, 'width' | 'height'>,
67
102
  parentAfter: Pick<Rect, 'width' | 'height'>,
68
103
  horizontal: ConstraintType,
69
- vertical: ConstraintType
104
+ vertical: ConstraintType,
105
+ aspectRatio: number | null = null
70
106
  ): Rect {
71
- const x = constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal)
72
- const y = constrainedAxis(
73
- child.y,
74
- child.height,
75
- parentBefore.height,
76
- parentAfter.height,
77
- vertical
78
- )
107
+ let x = constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal)
108
+ let y = constrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical)
109
+ ;({ x, y } = keepLockedRatio(x, y, horizontal, vertical, aspectRatio))
79
110
  return {
80
111
  x: Math.round(x.position),
81
112
  y: Math.round(y.position),
@@ -84,6 +115,56 @@ export function constrainedChildRect(
84
115
  }
85
116
  }
86
117
 
118
+ function layoutConstrainedAxis(
119
+ position: number,
120
+ size: number,
121
+ parentBefore: number,
122
+ parentAfter: number,
123
+ constraint: ConstraintType
124
+ ): { position: number; size: number } {
125
+ const delta = Math.round(parentAfter) - Math.round(parentBefore)
126
+ if (constraint === 'MAX') return { position: position + delta, size }
127
+ if (constraint === 'CENTER') {
128
+ return { position: position + Math.round(parentAfter / 2) - Math.round(parentBefore / 2), size }
129
+ }
130
+ if (constraint === 'STRETCH') return { position, size: Math.abs(size + delta) }
131
+ if (constraint === 'SCALE' && parentBefore > 0) {
132
+ const scale = parentAfter / parentBefore
133
+ return { position: Math.round(position * scale * 128) / 128, size: size * scale }
134
+ }
135
+ return { position, size }
136
+ }
137
+
138
+ /**
139
+ * Where a child goes when layout resizes its parent, as Figma places a layer that ignores auto
140
+ * layout when its Hug frame grows (measured on desktop 126): Right and Left & right move or grow
141
+ * it by the change in the parent's size rounded to whole pixels, Center by the change in its
142
+ * rounded half, and Scale by the exact ratio, its position to 1/128 of a pixel. Sizes are not
143
+ * rounded, so applying a run of changes one at a time lands where applying them at once does.
144
+ */
145
+ export function layoutConstrainedChildRect(
146
+ child: Rect,
147
+ parentBefore: Pick<Rect, 'width' | 'height'>,
148
+ parentAfter: Pick<Rect, 'width' | 'height'>,
149
+ horizontal: ConstraintType,
150
+ vertical: ConstraintType,
151
+ aspectRatio: number | null = null
152
+ ): Rect {
153
+ const placed = keepLockedRatio(
154
+ layoutConstrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal),
155
+ layoutConstrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical),
156
+ horizontal,
157
+ vertical,
158
+ aspectRatio
159
+ )
160
+ return {
161
+ x: placed.x.position,
162
+ y: placed.y.position,
163
+ width: placed.x.size,
164
+ height: placed.y.size
165
+ }
166
+ }
167
+
87
168
  export function scaledChildRect(
88
169
  child: Rect,
89
170
  parentBefore: Pick<Rect, 'width' | 'height'>,
@@ -209,8 +290,13 @@ export function scaledGeometryChanges(
209
290
  if (orig.strokeGeometry.length > 0) {
210
291
  changes.strokeGeometry = scaleGeometryPaths(orig.strokeGeometry, sx, sy)
211
292
  }
212
- if (orig.derivedTextGlyphs?.length) {
213
- changes.derivedTextGlyphs = scaleDerivedGlyphs(orig.derivedTextGlyphs, sx, sy)
293
+ // Path text scales with its path, including baked path text that kept only rotated glyphs;
294
+ // other text reflows in the new box, so its glyphs are dropped.
295
+ const glyphs = orig.derivedTextGlyphs ?? []
296
+ const pathText =
297
+ !!orig.textPathData || !!orig.textPathBox || glyphs.some((glyph) => (glyph.rotation ?? 0) !== 0)
298
+ if (glyphs.length > 0 && pathText) {
299
+ changes.derivedTextGlyphs = scaleDerivedGlyphs(glyphs, sx, sy)
214
300
  // Keep the layout/selection box in sync with the scaled glyphs. reflow
215
301
  // overrides this when it applies; this covers the fallback where reflow
216
302
  // returns null (no path data) so the box doesn't carry a stale size.
@@ -285,7 +371,8 @@ export function computeConstrainedResizeChanges(
285
371
  parentBefore,
286
372
  parentAfter,
287
373
  child.horizontalConstraint,
288
- child.verticalConstraint
374
+ child.verticalConstraint,
375
+ enforcedAspectRatio(child)
289
376
  )
290
377
  const childChanges: Partial<SceneNode> = {
291
378
  ...rect,
@@ -0,0 +1,2 @@
1
+ export { scaleNodeChanges } from './node'
2
+ export { rescaleNodeTree } from './tree'