@open-pencil/scene-graph 0.15.1 → 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 +1711 -661
  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 +343 -55
  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,596 @@
1
+ import { BEHAVIOUR_KINDS, INTERACTION_STATES, behaviourContract } from "./kinds.js";
2
+ import * as v from "valibot";
3
+ //#region src/plugin-data/field.ts
4
+ /** The plugin id OpenPencil keeps its own state under, on nodes and in `.fig` files. */
5
+ const OPEN_PENCIL_PLUGIN_ID = "open-pencil";
6
+ /**
7
+ * A value stored as JSON. Invalid JSON and a wrong shape both read as missing: plugin data
8
+ * comes from files anyone can edit, so a bad entry is ignored rather than thrown on.
9
+ */
10
+ function jsonPluginDataField(key, role, schema) {
11
+ const stored = v.pipe(v.string(), v.parseJson(), schema);
12
+ return {
13
+ key,
14
+ role,
15
+ decode(value) {
16
+ const parsed = v.safeParse(stored, value);
17
+ return parsed.success ? parsed.output : void 0;
18
+ },
19
+ encode: (value) => JSON.stringify(value)
20
+ };
21
+ }
22
+ /** A value stored as one of a fixed set of plain strings. */
23
+ function textPluginDataField(key, role, values) {
24
+ const schema = v.picklist(values);
25
+ return {
26
+ key,
27
+ role,
28
+ decode(value) {
29
+ const parsed = v.safeParse(schema, value);
30
+ return parsed.success ? parsed.output : void 0;
31
+ },
32
+ encode: (value) => value
33
+ };
34
+ }
35
+ function isPluginDataEntry(entry, field) {
36
+ return entry.pluginId === "open-pencil" && entry.key === field.key;
37
+ }
38
+ function hasPluginData(entries, field) {
39
+ return entries?.some((entry) => isPluginDataEntry(entry, field)) ?? false;
40
+ }
41
+ function readPluginData(entries, field) {
42
+ return field.decode(entries?.find((entry) => isPluginDataEntry(entry, field))?.value);
43
+ }
44
+ /** Every valid value of a field kept as several entries under one key. */
45
+ function readAllPluginData(entries, field) {
46
+ return (entries ?? []).flatMap((entry) => {
47
+ if (!isPluginDataEntry(entry, field)) return [];
48
+ const value = field.decode(entry.value);
49
+ return value === void 0 ? [] : [value];
50
+ });
51
+ }
52
+ function pluginDataEntry(field, value) {
53
+ return {
54
+ pluginId: OPEN_PENCIL_PLUGIN_ID,
55
+ key: field.key,
56
+ value: field.encode(value)
57
+ };
58
+ }
59
+ /** Entries other than those of `fields`; other plugins' entries are always kept. */
60
+ function withoutPluginData(entries, fields) {
61
+ return entries.filter((entry) => !fields.some((field) => isPluginDataEntry(entry, field)));
62
+ }
63
+ /** Entries with `field` set to `value`, appended last; `undefined` removes the field. */
64
+ function withPluginData(entries, field, value) {
65
+ return withAllPluginData(entries, field, value === void 0 ? [] : [value]);
66
+ }
67
+ /** Entries with every entry of `field` replaced by one per value. */
68
+ function withAllPluginData(entries, field, values) {
69
+ return [...withoutPluginData(entries, [field]), ...values.map((value) => pluginDataEntry(field, value))];
70
+ }
71
+ //#endregion
72
+ //#region src/behaviours/schema.ts
73
+ const BooleanBinding = v.object({
74
+ propertyId: v.string(),
75
+ /** For a variant property: the values that mean on and off. */
76
+ on: v.optional(v.string()),
77
+ off: v.optional(v.string())
78
+ });
79
+ /** Whether a number value's range can be stepped through: `max` above `min`, a positive step. */
80
+ function isNumberRange(settings) {
81
+ return settings.max > settings.min && settings.step > 0;
82
+ }
83
+ const NumberSettings = v.pipe(v.object({
84
+ min: v.pipe(v.number(), v.finite()),
85
+ max: v.pipe(v.number(), v.finite()),
86
+ step: v.pipe(v.number(), v.finite()),
87
+ default: v.pipe(v.number(), v.finite())
88
+ }), v.check((settings) => isNumberRange(settings), "A number value needs max above min and a positive step"));
89
+ /** Each interaction state's variant value, by state; a state left out shows the rest value. */
90
+ const interactionStateValues = {
91
+ rest: v.optional(v.string()),
92
+ hover: v.optional(v.string()),
93
+ pressed: v.optional(v.string()),
94
+ focus: v.optional(v.string()),
95
+ disabled: v.optional(v.string())
96
+ };
97
+ const InteractionStates = v.object({
98
+ propertyId: v.string(),
99
+ ...interactionStateValues
100
+ });
101
+ const behaviourSchema = v.object({
102
+ kind: v.picklist(BEHAVIOUR_KINDS),
103
+ /** Boolean values, by value id, bound to component properties. */
104
+ booleans: v.record(v.string(), BooleanBinding),
105
+ /** Text values, by value id, bound to text properties. */
106
+ texts: v.optional(v.record(v.string(), v.object({ propertyId: v.string() })), {}),
107
+ /** Number values, by value id: the range the behaviour keeps itself. */
108
+ numbers: v.record(v.string(), NumberSettings),
109
+ /** Parts, by part id, bound to slot properties. */
110
+ parts: v.record(v.string(), v.string()),
111
+ states: v.optional(InteractionStates)
112
+ });
113
+ //#endregion
114
+ //#region src/export-format.ts
115
+ /**
116
+ * Formats a node's export settings may persist. Each id must name a Core IO
117
+ * export adapter that supports node export; labels and options come from that
118
+ * adapter, so this list only decides what the Export panel offers.
119
+ */
120
+ const EXPORT_FORMAT_IDS = [
121
+ "png",
122
+ "jpg",
123
+ "webp",
124
+ "svg",
125
+ "pdf",
126
+ "pptx"
127
+ ];
128
+ function isExportFormatId(value) {
129
+ return EXPORT_FORMAT_IDS.some((id) => id === value);
130
+ }
131
+ //#endregion
132
+ //#region src/export-scale.ts
133
+ /**
134
+ * Bounds for export scale multipliers. A huge multiplier would allocate an
135
+ * enormous canvas and crash the renderer, so clamp at every boundary the value
136
+ * can enter from: the UI (edits) and the file format (imported/plugin .fig data).
137
+ */
138
+ const MIN_EXPORT_SCALE = .01;
139
+ const MAX_EXPORT_SCALE = 1024;
140
+ function clampExportScale(scale) {
141
+ return Math.min(MAX_EXPORT_SCALE, Math.max(MIN_EXPORT_SCALE, scale));
142
+ }
143
+ /** Accept a scale only if it is finite and within bounds (no silent clamping). */
144
+ function isValidExportScale(scale) {
145
+ return Number.isFinite(scale) && scale >= .01 && scale <= 1024;
146
+ }
147
+ //#endregion
148
+ //#region src/icons/schema.ts
149
+ /** An icon's name in its set, `prefix:name`, as Iconify names icons. */
150
+ const ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:[-_][a-z0-9]+)*$/;
151
+ const iconSchema = v.object({
152
+ name: v.pipe(v.string(), v.regex(ICON_NAME)),
153
+ /** A fingerprint of the glyph as placed, to tell when its paths were edited; see `iconGlyph`. */
154
+ glyph: v.optional(v.string())
155
+ });
156
+ const ICON_PAINTS = ["fill", "stroke"];
157
+ const iconTintSchema = v.pipe(v.array(v.picklist(ICON_PAINTS)), v.minLength(1));
158
+ //#endregion
159
+ //#region src/shaders/schema.ts
160
+ const shaderComponent = v.object({
161
+ type: v.pipe(v.string(), v.nonEmpty(), v.maxLength(100)),
162
+ id: v.optional(v.string()),
163
+ props: v.optional(v.record(v.string(), v.unknown())),
164
+ children: v.optional(v.array(v.lazy(() => shaderComponent)))
165
+ });
166
+ /**
167
+ * A shader as the `shaders` library describes it and shaders.com exports it: a tree of effects,
168
+ * drawn first to last.
169
+ */
170
+ const shaderPresetSchema = v.object({
171
+ components: v.pipe(v.array(shaderComponent), v.minLength(1)),
172
+ structureVersion: v.optional(v.number())
173
+ });
174
+ /**
175
+ * A paint that draws a shader. The paint itself is an image fill of the shader's still frame, so
176
+ * every format and renderer that reads images shows it; this entry says which image it is, the
177
+ * preset that draws it, and the layer size and preset the frame was rendered for, which is
178
+ * missing until it is first rendered.
179
+ */
180
+ const shaderPaintSchema = v.object({
181
+ image: v.pipe(v.string(), v.nonEmpty()),
182
+ preset: shaderPresetSchema,
183
+ frame: v.optional(v.object({
184
+ width: v.pipe(v.number(), v.finite(), v.minValue(0)),
185
+ height: v.pipe(v.number(), v.finite(), v.minValue(0)),
186
+ /** The preset's key (`shaderPresetKey`) when the frame was rendered. */
187
+ preset: v.pipe(v.string(), v.nonEmpty())
188
+ }))
189
+ });
190
+ //#endregion
191
+ //#region src/types.ts
192
+ /** Property pickers a variable is offered in, as Figma names them. */
193
+ const VARIABLE_SCOPES = [
194
+ "ALL_SCOPES",
195
+ "TEXT_CONTENT",
196
+ "CORNER_RADIUS",
197
+ "WIDTH_HEIGHT",
198
+ "GAP",
199
+ "ALL_FILLS",
200
+ "FRAME_FILL",
201
+ "SHAPE_FILL",
202
+ "TEXT_FILL",
203
+ "STROKE",
204
+ "STROKE_FLOAT",
205
+ "EFFECT_FLOAT",
206
+ "EFFECT_COLOR",
207
+ "OPACITY",
208
+ "FONT_STYLE",
209
+ "FONT_FAMILY",
210
+ "FONT_SIZE",
211
+ "LINE_HEIGHT",
212
+ "LETTER_SPACING",
213
+ "PARAGRAPH_SPACING",
214
+ "PARAGRAPH_INDENT",
215
+ "FONT_VARIATIONS",
216
+ "TRANSFORM"
217
+ ];
218
+ const CODE_SYNTAX_PLATFORMS = [
219
+ "WEB",
220
+ "ANDROID",
221
+ "iOS"
222
+ ];
223
+ /**
224
+ * The CSS unit a numeric token is written in. Lengths (`px`, `rem`) stay in canvas pixels in
225
+ * the document and convert only when written as CSS; the other units store the number as written.
226
+ */
227
+ const TOKEN_UNITS = [
228
+ "none",
229
+ "px",
230
+ "rem",
231
+ "%",
232
+ "ms",
233
+ "s",
234
+ "deg"
235
+ ];
236
+ /** An HTML attribute name a stylesheet can select on unescaped: `data-theme`, `theme`. */
237
+ const MODE_ATTRIBUTE_PATTERN = /^[A-Za-z_][\w-]*$/;
238
+ function isModeAttributeName(name) {
239
+ return name.length <= 100 && MODE_ATTRIBUTE_PATTERN.test(name);
240
+ }
241
+ //#endregion
242
+ //#region src/plugin-data/fields.ts
243
+ const DIRECTIONS = [
244
+ "AUTO",
245
+ "LTR",
246
+ "RTL"
247
+ ];
248
+ const textPathBox = v.pipe(v.object({
249
+ x: v.number(),
250
+ y: v.number(),
251
+ width: v.number(),
252
+ height: v.number()
253
+ }), v.check(({ x, y, width, height }) => Number.isFinite(x + y + width + height) && width > 0 && height > 0));
254
+ /** String-valued entries of a JSON object; other entries are dropped, not rejected. */
255
+ const boundVariables = v.pipe(v.custom((value) => typeof value === "object" && value !== null && !Array.isArray(value)), v.transform((value) => Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"))));
256
+ /** Every entry must be valid, or the whole value is ignored in favour of native settings. */
257
+ const exportSettings = v.array(v.pipe(v.object({
258
+ scale: v.pipe(v.number(), v.finite()),
259
+ format: v.custom(isExportFormatId)
260
+ }), v.transform(({ scale, format }) => ({
261
+ scale: clampExportScale(scale),
262
+ format
263
+ }))));
264
+ const librarySource = v.pipe(v.object({
265
+ identity: v.object({
266
+ libraryId: v.string(),
267
+ assetKey: v.string(),
268
+ revisionId: v.string()
269
+ }),
270
+ sourceNodeId: v.optional(v.unknown()),
271
+ readOnly: v.optional(v.unknown())
272
+ }), v.transform(({ identity, sourceNodeId, readOnly }) => ({
273
+ identity,
274
+ sourceNodeId: typeof sourceNodeId === "string" ? sourceNodeId : null,
275
+ readOnly: readOnly === true
276
+ })));
277
+ const enabledLibrary = v.object({
278
+ libraryId: v.string(),
279
+ revisionId: v.string(),
280
+ enabled: v.optional(v.unknown())
281
+ });
282
+ /** Invalid entries are skipped one by one, so one bad binding keeps the others. */
283
+ const enabledLibraries = v.pipe(v.array(v.unknown()), v.transform((items) => items.flatMap((item) => {
284
+ const parsed = v.safeParse(enabledLibrary, item);
285
+ if (!parsed.success) return [];
286
+ const { libraryId, revisionId, enabled } = parsed.output;
287
+ return [{
288
+ libraryId,
289
+ revisionId,
290
+ enabled: enabled === true
291
+ }];
292
+ })));
293
+ const cssText = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(1e3));
294
+ const token = v.object({
295
+ unit: v.optional(v.picklist(TOKEN_UNITS)),
296
+ expressions: v.optional(v.record(v.string(), v.object({
297
+ css: cssText,
298
+ resolved: v.pipe(v.number(), v.finite())
299
+ })))
300
+ });
301
+ const okhcl = v.object({
302
+ version: v.literal(1),
303
+ kind: v.picklist(["fill", "stroke"]),
304
+ index: v.number(),
305
+ color: v.object({
306
+ h: v.number(),
307
+ c: v.number(),
308
+ l: v.number(),
309
+ a: v.fallback(v.optional(v.number()), void 0)
310
+ })
311
+ });
312
+ const sourceLibraryPublication = v.object({
313
+ libraryId: v.string(),
314
+ revisionId: v.string(),
315
+ name: v.string(),
316
+ catalogSource: v.optional(v.string())
317
+ });
318
+ const commentAuthorColor = v.fallback(v.optional(v.object({
319
+ r: v.number(),
320
+ g: v.number(),
321
+ b: v.number(),
322
+ a: v.number()
323
+ })), void 0);
324
+ /** What a comment and each reply say, who wrote them and when, and whether they were deleted. */
325
+ const commentEntry = {
326
+ author: v.fallback(v.string(), ""),
327
+ authorColor: commentAuthorColor,
328
+ text: v.fallback(v.string(), ""),
329
+ createdAt: v.fallback(v.string(), ""),
330
+ deleted: v.optional(v.boolean())
331
+ };
332
+ const commentReply = v.object({
333
+ id: v.string(),
334
+ ...commentEntry
335
+ });
336
+ const commentThread = v.object({
337
+ id: v.string(),
338
+ pageId: v.string(),
339
+ pageName: v.optional(v.string()),
340
+ nodeId: v.optional(v.nullable(v.string())),
341
+ nodeName: v.optional(v.nullable(v.string())),
342
+ offsetX: v.optional(v.number()),
343
+ offsetY: v.optional(v.number()),
344
+ x: v.fallback(v.number(), 0),
345
+ y: v.fallback(v.number(), 0),
346
+ ...commentEntry,
347
+ updatedAt: v.fallback(v.string(), ""),
348
+ resolved: v.fallback(v.boolean(), false),
349
+ resolvedAt: v.optional(v.nullable(v.string())),
350
+ replies: v.fallback(v.array(commentReply), [])
351
+ });
352
+ const comments = v.pipe(v.array(v.unknown()), v.transform((items) => items.flatMap((item) => {
353
+ const parsed = v.safeParse(commentThread, item);
354
+ if (!parsed.success) return [];
355
+ const thread = parsed.output;
356
+ return [{
357
+ ...thread,
358
+ updatedAt: thread.updatedAt || thread.createdAt
359
+ }];
360
+ })));
361
+ /**
362
+ * Every plugin-data entry OpenPencil writes under {@link OPEN_PENCIL_PLUGIN_ID}: state Figma's
363
+ * format has no field for. Add a key here, never as a string elsewhere, so reading and writing
364
+ * it share one schema.
365
+ */
366
+ const OPEN_PENCIL_PLUGIN_DATA = {
367
+ /** A text node's direction, on TEXT nodes. */
368
+ textDirection: textPluginDataField("textDirection", "format", DIRECTIONS),
369
+ /** An auto-layout frame's direction. */
370
+ layoutDirection: textPluginDataField("layoutDirection", "format", DIRECTIONS),
371
+ /** Marks a component set Figma would read as a plain frame. */
372
+ nodeType: textPluginDataField("nodeType", "format", ["COMPONENT_SET"]),
373
+ /** Variable bindings by field path, including those Figma cannot store natively. */
374
+ boundVariables: jsonPluginDataField("boundVariables", "format", boundVariables),
375
+ exportSettings: jsonPluginDataField("exportSettings", "format", exportSettings),
376
+ /** The node-local rect a TEXT_PATH layout maps onto, which Kiwi has no field for. */
377
+ textPathBox: jsonPluginDataField("textPathBox", "format", textPathBox),
378
+ /** The library asset a node was inserted from. */
379
+ librarySource: jsonPluginDataField("librarySource", "bookkeeping", librarySource),
380
+ /** Libraries enabled for the document, on the DOCUMENT node. */
381
+ enabledLibraries: jsonPluginDataField("enabledLibraries", "bookkeeping", enabledLibraries),
382
+ /** The library this document publishes as, on the DOCUMENT node. */
383
+ sourceLibraryPublication: jsonPluginDataField("sourceLibraryPublication", "bookkeeping", sourceLibraryPublication),
384
+ /** Canvas comment threads, deleted ones included, on the DOCUMENT node. */
385
+ comments: jsonPluginDataField("comments", "bookkeeping", comments),
386
+ /** Unit and CSS expressions, on each VARIABLE. */
387
+ token: jsonPluginDataField("token", "format", token),
388
+ /** Mode conditions by mode id, on each VARIABLE_SET. */
389
+ modeConditions: jsonPluginDataField("modeConditions", "format", v.record(v.string(), cssText)),
390
+ /** The attribute that switches manual modes, on each VARIABLE_SET. */
391
+ modeAttribute: jsonPluginDataField("modeAttribute", "format", v.pipe(v.string(), v.trim(), v.maxLength(100), v.regex(MODE_ATTRIBUTE_PATTERN))),
392
+ /** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */
393
+ okhcl: jsonPluginDataField("okhcl", "content", okhcl),
394
+ /** How a main component or component set behaves as a control in preview. */
395
+ behaviour: jsonPluginDataField("behaviour", "content", behaviourSchema),
396
+ /** The icon a frame draws, such as `lucide:home`, on the frame its paths are in. */
397
+ icon: jsonPluginDataField("icon", "content", iconSchema),
398
+ /** Which of an icon path's paints its icon's color sets, on each path the source drew in it. */
399
+ iconTint: jsonPluginDataField("iconTint", "content", iconTintSchema),
400
+ /** One entry per paint that draws a shader, matched to its image paint by the frame's hash. */
401
+ shader: jsonPluginDataField("shader", "content", shaderPaintSchema)
402
+ };
403
+ const NOT_CONTENT = Object.values(OPEN_PENCIL_PLUGIN_DATA).filter((field) => field.role !== "content");
404
+ /**
405
+ * A node's plugin data that is part of its content, in a stable order: OpenPencil's content
406
+ * fields and every other plugin's entries, which the node carries wherever it goes. Format
407
+ * copies of node fields and bookkeeping are left out.
408
+ */
409
+ function contentPluginData(entries) {
410
+ return withoutPluginData(entries, NOT_CONTENT).sort((a, b) => a.pluginId.localeCompare(b.pluginId) || a.key.localeCompare(b.key));
411
+ }
412
+ //#endregion
413
+ //#region src/behaviours/model.ts
414
+ const DEFAULT_NUMBER_SETTINGS = {
415
+ min: 0,
416
+ max: 100,
417
+ step: 1,
418
+ default: 50
419
+ };
420
+ /** A boolean value's binding, if the behaviour has one. */
421
+ function booleanBinding(behaviour, valueId) {
422
+ return Object.hasOwn(behaviour.booleans, valueId) ? behaviour.booleans[valueId] : void 0;
423
+ }
424
+ /** The slot property a part is bound to, if any. */
425
+ function partBinding(behaviour, partId) {
426
+ return Object.hasOwn(behaviour.parts, partId) ? behaviour.parts[partId] : void 0;
427
+ }
428
+ /** The text property a text value is bound to, if any. */
429
+ function textBinding(behaviour, valueId) {
430
+ return Object.hasOwn(behaviour.texts, valueId) ? behaviour.texts[valueId].propertyId : void 0;
431
+ }
432
+ /** A number value's range, if the behaviour has one. */
433
+ function numberSettings(behaviour, valueId) {
434
+ return Object.hasOwn(behaviour.numbers, valueId) ? behaviour.numbers[valueId] : void 0;
435
+ }
436
+ /** A new behaviour of a kind, its number values at their defaults and nothing bound. */
437
+ function emptyBehaviour(kind) {
438
+ const contract = behaviourContract(kind);
439
+ return {
440
+ kind,
441
+ booleans: {},
442
+ texts: {},
443
+ numbers: Object.fromEntries(contract.values.filter((value) => value.type === "number").map((value) => [value.id, { ...DEFAULT_NUMBER_SETTINGS }])),
444
+ parts: {}
445
+ };
446
+ }
447
+ /**
448
+ * The node that keeps the behaviour: a component set for its variants, otherwise the main
449
+ * component itself.
450
+ */
451
+ function behaviourOwner(graph, node) {
452
+ if (node.type === "COMPONENT_SET") return node;
453
+ if (node.type !== "COMPONENT") return void 0;
454
+ const parent = node.parentId ? graph.getNode(node.parentId) : void 0;
455
+ return parent?.type === "COMPONENT_SET" ? parent : node;
456
+ }
457
+ /** The behaviour a component or component set keeps, or null when it has none or it is unreadable. */
458
+ function readBehaviour(owner) {
459
+ return readPluginData(owner.pluginData, OPEN_PENCIL_PLUGIN_DATA.behaviour) ?? null;
460
+ }
461
+ /** The owner's plugin data with the behaviour set, or removed when null. */
462
+ function withBehaviour(owner, behaviour) {
463
+ return withPluginData(owner.pluginData, OPEN_PENCIL_PLUGIN_DATA.behaviour, behaviour ?? void 0);
464
+ }
465
+ /** Component properties the behaviour can bind to: the owner's, and a set's variants' own. */
466
+ function behaviourProperties(graph, owner) {
467
+ const variants = owner.type === "COMPONENT_SET" ? owner.childIds.flatMap((id) => graph.getNode(id)?.componentPropertyDefinitions ?? []) : [];
468
+ const seen = /* @__PURE__ */ new Set();
469
+ return [...owner.componentPropertyDefinitions, ...variants].filter((definition) => {
470
+ if (seen.has(definition.id)) return false;
471
+ seen.add(definition.id);
472
+ return true;
473
+ });
474
+ }
475
+ /**
476
+ * Required values and parts that are unbound, or bound to a property the component no longer
477
+ * has, by value or part id; `states` when the interaction states lost their variant property.
478
+ */
479
+ function missingBindings(graph, owner, behaviour) {
480
+ const contract = behaviourContract(behaviour.kind);
481
+ const properties = new Map(behaviourProperties(graph, owner).map((definition) => [definition.id, definition]));
482
+ const bound = (propertyId, type) => {
483
+ const definition = propertyId ? properties.get(propertyId) : void 0;
484
+ return !!definition && type.includes(definition.type);
485
+ };
486
+ const values = contract.values.filter((value) => value.required).filter((value) => value.type === "text" ? !bound(textBinding(behaviour, value.id), ["TEXT"]) : value.type === "boolean" && !bound(booleanBinding(behaviour, value.id)?.propertyId, ["VARIANT", "BOOLEAN"])).map((value) => value.id);
487
+ const parts = contract.parts.filter((part) => part.required && !bound(partBinding(behaviour, part.id), ["SLOT"])).map((part) => part.id);
488
+ const states = behaviour.states && !bound(behaviour.states.propertyId, ["VARIANT"]) ? ["states"] : [];
489
+ return [
490
+ ...values,
491
+ ...parts,
492
+ ...states
493
+ ];
494
+ }
495
+ /** Variant value names that usually mean each interaction state, compared case-insensitively. */
496
+ const STATE_NAMES = {
497
+ rest: [
498
+ "default",
499
+ "rest",
500
+ "idle",
501
+ "normal",
502
+ "enabled"
503
+ ],
504
+ hover: [
505
+ "hover",
506
+ "hovered",
507
+ "hovering"
508
+ ],
509
+ pressed: [
510
+ "pressed",
511
+ "active",
512
+ "down",
513
+ "pressing"
514
+ ],
515
+ focus: [
516
+ "focus",
517
+ "focused",
518
+ "focus visible",
519
+ "focus-visible"
520
+ ],
521
+ disabled: ["disabled", "inactive"]
522
+ };
523
+ /**
524
+ * Interaction states for a variant property, each mapped to the value whose name means it, such
525
+ * as `Hover` or `Pressed`; states without such a value are left unset.
526
+ */
527
+ function guessInteractionStates(propertyId, values) {
528
+ const states = { propertyId };
529
+ for (const state of INTERACTION_STATES) {
530
+ const match = values.find((value) => STATE_NAMES[state].includes(value.trim().toLowerCase()));
531
+ if (match) states[state] = match;
532
+ }
533
+ return states;
534
+ }
535
+ /**
536
+ * The behaviour with every component property id it binds renamed by `rename`, for formats that
537
+ * give properties new ids on write, such as `.fig` with its GUIDs.
538
+ */
539
+ function renameBehaviourProperties(behaviour, rename) {
540
+ const mapValues = (record, change) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, change(value)]));
541
+ return {
542
+ ...behaviour,
543
+ booleans: mapValues(behaviour.booleans, (binding) => ({
544
+ ...binding,
545
+ propertyId: rename(binding.propertyId)
546
+ })),
547
+ texts: mapValues(behaviour.texts, (binding) => ({ propertyId: rename(binding.propertyId) })),
548
+ parts: mapValues(behaviour.parts, rename),
549
+ ...behaviour.states ? { states: {
550
+ ...behaviour.states,
551
+ propertyId: rename(behaviour.states.propertyId)
552
+ } } : {}
553
+ };
554
+ }
555
+ //#endregion
556
+ //#region src/behaviours/layers.ts
557
+ /** Whether an instance's main component, or its set, has a behaviour. */
558
+ function hasBehaviour(graph, node) {
559
+ if (node.type !== "INSTANCE" || !node.componentId) return false;
560
+ const component = graph.getNode(node.componentId);
561
+ const owner = component && behaviourOwner(graph, component);
562
+ return !!owner && !!readBehaviour(owner);
563
+ }
564
+ /** A name as a path segment: `/` separates segments and `#` the twin index, so both are escaped. */
565
+ const pathName = (name) => name.replace(/[%/#]/g, (char) => encodeURIComponent(char));
566
+ /**
567
+ * A layer's path below a root: the names of the layers down to it, with the position among
568
+ * same-named siblings when names repeat. It stays the same when a variant switch rebuilds an
569
+ * instance's layers, so it identifies controls and keeps their DOM in place.
570
+ */
571
+ function layerPath(graph, rootId, nodeId) {
572
+ const segments = [];
573
+ graph.closest(nodeId, (node) => {
574
+ if (node.id === rootId) return true;
575
+ const twins = node.parentId ? graph.getChildren(node.parentId).filter((child) => child.name === node.name) : [];
576
+ const index = twins.findIndex((child) => child.id === node.id);
577
+ segments.unshift(twins.length > 1 ? `${pathName(node.name)}#${index}` : pathName(node.name));
578
+ return false;
579
+ });
580
+ return segments.join("/");
581
+ }
582
+ /** The layer at `path` below a root, the inverse of `layerPath`. */
583
+ function findLayerByPath(graph, rootId, path) {
584
+ let current = graph.getNode(rootId);
585
+ for (const segment of path ? path.split("/") : []) {
586
+ if (!current) return void 0;
587
+ const hash = segment.lastIndexOf("#");
588
+ const name = hash === -1 ? segment : segment.slice(0, hash);
589
+ current = graph.getChildren(current.id).filter((child) => pathName(child.name) === name).at(hash === -1 ? 0 : Number(segment.slice(hash + 1)));
590
+ }
591
+ return current;
592
+ }
593
+ //#endregion
594
+ export { CODE_SYNTAX_PLATFORMS, DEFAULT_NUMBER_SETTINGS, EXPORT_FORMAT_IDS, ICON_NAME, ICON_PAINTS, MAX_EXPORT_SCALE, MIN_EXPORT_SCALE, MODE_ATTRIBUTE_PATTERN, OPEN_PENCIL_PLUGIN_DATA, OPEN_PENCIL_PLUGIN_ID, TOKEN_UNITS, VARIABLE_SCOPES, behaviourOwner, behaviourProperties, booleanBinding, clampExportScale, contentPluginData, emptyBehaviour, findLayerByPath, guessInteractionStates, hasBehaviour, hasPluginData, iconSchema, iconTintSchema, interactionStateValues, isExportFormatId, isModeAttributeName, isNumberRange, isPluginDataEntry, isValidExportScale, jsonPluginDataField, layerPath, missingBindings, numberSettings, partBinding, pluginDataEntry, readAllPluginData, readBehaviour, readPluginData, renameBehaviourProperties, shaderPaintSchema, shaderPresetSchema, textBinding, textPluginDataField, withAllPluginData, withBehaviour, withPluginData, withoutPluginData };
595
+
596
+ //# sourceMappingURL=layers.js.map