@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,809 @@
1
+ import { DESIGN_JSX_SUPPORTED_PROPERTIES, designJSXProp } from "./behaviours/render.js";
2
+ import { applyComponentPropertyValue, componentPropertyDefinitions, createComponentPropertyId, exposableInstances, exposedInstances, instanceExposureIssue } from "@pairdraw/scene-graph/components";
3
+ import { colorToFill, parseColor, tryParseColor } from "@pairdraw/scene-graph/color";
4
+ import * as v from "valibot";
5
+ import { paintTransformSchema } from "@pairdraw/scene-graph/paints";
6
+ import { mapValues } from "es-toolkit/object";
7
+ import { STICKY_COLORS } from "@pairdraw/scene-graph/generated";
8
+ import { SHAPE_WITH_TEXT_TYPES } from "@pairdraw/scene-graph/shape-with-text";
9
+ import { isPlainObject } from "es-toolkit/predicate";
10
+ import { compact } from "es-toolkit/array";
11
+ import { instanceMainComponent } from "@pairdraw/scene-graph/instances";
12
+ //#region src/enums.ts
13
+ /**
14
+ * `spellings` names every value of the enum, which the type checks, and is what the export writes;
15
+ * `aliases` are further spellings it only reads.
16
+ */
17
+ function jsxEnum(spellings, aliases = {}) {
18
+ const entries = Object.entries(spellings);
19
+ const byName = new Map([...entries.map(([value, name]) => [name, value]), ...Object.entries(aliases)].map(([name, value]) => [name.toLowerCase(), value]));
20
+ return {
21
+ parse: (value) => typeof value === "string" ? byName.get(value.toLowerCase()) : void 0,
22
+ print: (value) => spellings[value],
23
+ names: [...entries.map(([, name]) => name), ...Object.keys(aliases)]
24
+ };
25
+ }
26
+ /** A prop that takes one of the enum's spellings, read as the value it names. */
27
+ function enumProp(values) {
28
+ return v.pipe(v.string(), v.rawTransform(({ dataset, addIssue, NEVER }) => {
29
+ const value = values.parse(dataset.value);
30
+ if (value !== void 0) return value;
31
+ addIssue({ message: `expected ${values.names.join(", ")}` });
32
+ return NEVER;
33
+ }));
34
+ }
35
+ /** An enum spelled by each value's lowercase name, as most of design JSX's enums are. */
36
+ function lowercaseEnum(values, aliases = {}) {
37
+ return jsxEnum(Object.fromEntries(values.map((value) => [value, value.toLowerCase()])), aliases);
38
+ }
39
+ const STROKE_CAP = lowercaseEnum([
40
+ "NONE",
41
+ "ROUND",
42
+ "SQUARE",
43
+ "ARROW_LINES",
44
+ "ARROW_EQUILATERAL",
45
+ "TRIANGLE_FILLED",
46
+ "DIAMOND_FILLED",
47
+ "CIRCLE_FILLED"
48
+ ]);
49
+ const STROKE_JOIN = lowercaseEnum([
50
+ "MITER",
51
+ "BEVEL",
52
+ "ROUND"
53
+ ]);
54
+ const STROKE_ALIGN = lowercaseEnum([
55
+ "INSIDE",
56
+ "CENTER",
57
+ "OUTSIDE"
58
+ ]);
59
+ const CONSTRAINT = lowercaseEnum([
60
+ "MIN",
61
+ "CENTER",
62
+ "MAX",
63
+ "STRETCH",
64
+ "SCALE"
65
+ ]);
66
+ const MASK_TYPE = lowercaseEnum([
67
+ "ALPHA",
68
+ "LUMINANCE",
69
+ "VECTOR"
70
+ ]);
71
+ const BLEND_MODE = lowercaseEnum([
72
+ "NORMAL",
73
+ "DARKEN",
74
+ "MULTIPLY",
75
+ "LINEAR_BURN",
76
+ "COLOR_BURN",
77
+ "LIGHTEN",
78
+ "SCREEN",
79
+ "LINEAR_DODGE",
80
+ "COLOR_DODGE",
81
+ "OVERLAY",
82
+ "SOFT_LIGHT",
83
+ "HARD_LIGHT",
84
+ "DIFFERENCE",
85
+ "EXCLUSION",
86
+ "HUE",
87
+ "SATURATION",
88
+ "COLOR",
89
+ "LUMINOSITY",
90
+ "PASS_THROUGH"
91
+ ]);
92
+ const TEXT_ALIGN = lowercaseEnum([
93
+ "LEFT",
94
+ "CENTER",
95
+ "RIGHT",
96
+ "JUSTIFIED"
97
+ ], {
98
+ left_align: "LEFT",
99
+ center_align: "CENTER",
100
+ right_align: "RIGHT"
101
+ });
102
+ const TEXT_ALIGN_VERTICAL = lowercaseEnum([
103
+ "TOP",
104
+ "CENTER",
105
+ "BOTTOM"
106
+ ]);
107
+ const TEXT_AUTO_RESIZE = jsxEnum({
108
+ NONE: "none",
109
+ WIDTH_AND_HEIGHT: "width",
110
+ HEIGHT: "height",
111
+ TRUNCATE: "truncate"
112
+ });
113
+ const TEXT_DIRECTION = lowercaseEnum([
114
+ "AUTO",
115
+ "LTR",
116
+ "RTL"
117
+ ]);
118
+ const TEXT_DECORATION = lowercaseEnum([
119
+ "NONE",
120
+ "UNDERLINE",
121
+ "STRIKETHROUGH"
122
+ ]);
123
+ const TEXT_DECORATION_STYLE = lowercaseEnum([
124
+ "SOLID",
125
+ "DOTTED",
126
+ "WAVY"
127
+ ]);
128
+ const TEXT_CASE = lowercaseEnum([
129
+ "ORIGINAL",
130
+ "UPPER",
131
+ "LOWER",
132
+ "TITLE"
133
+ ]);
134
+ const FIGJAM_TEXT_SIZE = jsxEnum({
135
+ small: "small",
136
+ medium: "medium",
137
+ large: "large",
138
+ extraLarge: "extraLarge",
139
+ huge: "huge"
140
+ });
141
+ /** FigJam's typefaces, as its text menus name them. */
142
+ const FIGJAM_TYPEFACE = jsxEnum({
143
+ simple: "simple",
144
+ bookish: "bookish",
145
+ technical: "technical",
146
+ scribbled: "scribbled"
147
+ });
148
+ /** The kinds a `<Shape>` draws, as FigJam names them: `rounded_rectangle`, `eng_database`. */
149
+ const SHAPE_KIND = lowercaseEnum(SHAPE_WITH_TEXT_TYPES);
150
+ const CONNECTOR_LINE = lowercaseEnum([
151
+ "ELBOWED",
152
+ "STRAIGHT",
153
+ "CURVED"
154
+ ]);
155
+ /** The sides a `<Connector>` end attaches by; the other magnets come only from files. */
156
+ const CONNECTOR_SIDE = lowercaseEnum([
157
+ "AUTO",
158
+ "TOP",
159
+ "RIGHT",
160
+ "BOTTOM",
161
+ "LEFT",
162
+ "CENTER"
163
+ ]);
164
+ /**
165
+ * The layer props whose values are one of an enum's spellings, for checking what JSX passes. An
166
+ * element with a props schema, such as `<Connector>`, checks its enums by `enumProp` instead.
167
+ */
168
+ const ENUM_PROPS = {
169
+ strokeCap: STROKE_CAP,
170
+ strokeJoin: STROKE_JOIN,
171
+ strokeAlign: STROKE_ALIGN,
172
+ mask: MASK_TYPE,
173
+ blendMode: BLEND_MODE,
174
+ textAlign: TEXT_ALIGN,
175
+ textAlignVertical: TEXT_ALIGN_VERTICAL,
176
+ textAutoResize: TEXT_AUTO_RESIZE,
177
+ dir: TEXT_DIRECTION,
178
+ textDecoration: TEXT_DECORATION,
179
+ textDecorationStyle: TEXT_DECORATION_STYLE,
180
+ textCase: TEXT_CASE
181
+ };
182
+ //#endregion
183
+ //#region src/overrides/fills.ts
184
+ function isColor$1(value) {
185
+ return value !== null && typeof value === "object" && "r" in value && "g" in value && "b" in value && "a" in value;
186
+ }
187
+ function isFill(value) {
188
+ return value !== null && typeof value === "object" && "type" in value && "color" in value && "visible" in value;
189
+ }
190
+ /** A paint as props write it: a colour string, a colour, or a paint from a helper. */
191
+ function isFillValue(value) {
192
+ return typeof value === "string" || isColor$1(value) || isFill(value);
193
+ }
194
+ const TRANSFORM_FIELDS = ["gradientTransform", "imageTransform"];
195
+ /** Worded as `parseScriptInput` words it; that lives in `schema.ts`, which imports this module. */
196
+ function parseTransform(field, value) {
197
+ const result = v.safeParse(paintTransformSchema, value);
198
+ if (result.success) return result.output;
199
+ throw new Error(`A paint's ${field} expects Figma's [[a, b, c], [d, e, f]] or { m00, m01, m02, m10, m11, m12 }:\n${v.summarize(result.issues)}`);
200
+ }
201
+ function fillFromValue(value) {
202
+ if (!isFill(value)) return colorToFill(value);
203
+ const fill = structuredClone(value);
204
+ for (const field of TRANSFORM_FIELDS) if (fill[field] !== void 0) fill[field] = parseTransform(field, fill[field]);
205
+ return fill;
206
+ }
207
+ //#endregion
208
+ //#region src/overrides/strokes.ts
209
+ function isColor(value) {
210
+ return value !== null && typeof value === "object" && "r" in value && "a" in value;
211
+ }
212
+ function isStrokeValue(value) {
213
+ if (value === null || typeof value !== "object" || !("color" in value)) return false;
214
+ return typeof value.color === "string" || isColor(value.color);
215
+ }
216
+ function dashValue(value) {
217
+ if (!Array.isArray(value)) return void 0;
218
+ const dash = value.filter((item) => typeof item === "number");
219
+ return dash.length > 0 ? dash : void 0;
220
+ }
221
+ function toStroke(value) {
222
+ const color = typeof value.color === "string" ? parseColor(value.color) : value.color;
223
+ const stroke = {
224
+ type: "SOLID",
225
+ color,
226
+ opacity: typeof value.opacity === "number" ? value.opacity : color.a,
227
+ visible: value.visible ?? true,
228
+ weight: value.weight ?? 1,
229
+ align: STROKE_ALIGN.parse(value.align) ?? "INSIDE"
230
+ };
231
+ const dash = dashValue(value.dash);
232
+ if (dash) stroke.dashPattern = dash;
233
+ const cap = STROKE_CAP.parse(value.cap);
234
+ if (cap) stroke.cap = cap;
235
+ const join = STROKE_JOIN.parse(value.join);
236
+ if (join) stroke.join = join;
237
+ return stroke;
238
+ }
239
+ function isStrokeWeights(value) {
240
+ return value !== null && typeof value === "object" && !Array.isArray(value);
241
+ }
242
+ function sideWeight(value) {
243
+ return typeof value === "number" ? value : 0;
244
+ }
245
+ function applyStrokeWeights(value, o) {
246
+ if (!isStrokeWeights(value)) return;
247
+ o.independentStrokeWeights = true;
248
+ o.borderTopWeight = sideWeight(value.top);
249
+ o.borderRightWeight = sideWeight(value.right);
250
+ o.borderBottomWeight = sideWeight(value.bottom);
251
+ o.borderLeftWeight = sideWeight(value.left);
252
+ }
253
+ /** `strokes` takes structured strokes; `stroke` and its sibling props describe a single one. */
254
+ function applyStrokeOverrides(props, o) {
255
+ applyStrokeWeights(props.strokeWeights, o);
256
+ const nodeCap = STROKE_CAP.parse(props.strokeCap);
257
+ if (nodeCap) o.strokeCap = nodeCap;
258
+ const nodeJoin = STROKE_JOIN.parse(props.strokeJoin);
259
+ if (nodeJoin) o.strokeJoin = nodeJoin;
260
+ const nodeDash = dashValue(props.dashPattern);
261
+ if (nodeDash) o.dashPattern = nodeDash;
262
+ if (Array.isArray(props.strokes)) {
263
+ const strokes = props.strokes.filter(isStrokeValue).map(toStroke);
264
+ if (strokes.length > 0) o.strokes = strokes;
265
+ return;
266
+ }
267
+ const color = designJSXProp(props, "stroke");
268
+ if (typeof color !== "string" && !isColor(color)) return;
269
+ o.strokes = [toStroke({
270
+ color,
271
+ weight: props.strokeWidth ?? props.borderWidth,
272
+ align: props.strokeAlign,
273
+ dash: props.strokeDash
274
+ })];
275
+ }
276
+ //#endregion
277
+ //#region src/refs.ts
278
+ const REF_SYMBOL = Symbol.for("pairdraw.layer-ref");
279
+ /** A new handle for `ref={…}` to mark a layer with. */
280
+ function ref() {
281
+ return Object.freeze({ [REF_SYMBOL]: true });
282
+ }
283
+ function isLayerRef(value) {
284
+ return typeof value === "object" && value !== null && REF_SYMBOL in value;
285
+ }
286
+ /** The layers a render marked with `ref={…}`, for the elements that refer to them. */
287
+ var LayerRefs = class {
288
+ warnings = [];
289
+ layers = /* @__PURE__ */ new Map();
290
+ /** Marks `node` with the `ref` prop its element passed, if any. */
291
+ mark(value, node) {
292
+ if (value === void 0) return;
293
+ if (!isLayerRef(value)) {
294
+ this.warnings.push(`ref on "${node.name}" is not a ref() and is ignored.`);
295
+ return;
296
+ }
297
+ const first = this.layers.get(value);
298
+ if (first) {
299
+ this.warnings.push(`One ref() marks both "${first.name}" and "${node.name}"; it refers to "${first.name}".`);
300
+ return;
301
+ }
302
+ this.layers.set(value, node);
303
+ }
304
+ /** The id of the layer `ref` marks, if one does. */
305
+ layerOf(ref) {
306
+ return this.layers.get(ref)?.id;
307
+ }
308
+ };
309
+ //#endregion
310
+ //#region src/variables/index.ts
311
+ const VAR_SYMBOL = Symbol.for("pairdraw.variable");
312
+ const MODE_SYMBOL = Symbol.for("pairdraw.variable-mode");
313
+ /** The name a collection's first mode has when `defineVars` names none, as Figma names it. */
314
+ const DEFAULT_MODE_NAME = "Mode 1";
315
+ function isVariable(value) {
316
+ return typeof value === "object" && value !== null && VAR_SYMBOL in value;
317
+ }
318
+ function isMode(value) {
319
+ return typeof value === "object" && value !== null && MODE_SYMBOL in value;
320
+ }
321
+ /** Whether a value can be a variable's value: a color, a number, a boolean, or a variable. */
322
+ function isVariableInput(value) {
323
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return true;
324
+ if (isVariable(value)) return true;
325
+ return isPlainObject(value) && [
326
+ "r",
327
+ "g",
328
+ "b",
329
+ "a"
330
+ ].every((key) => typeof value[key] === "number");
331
+ }
332
+ function designVar(first, second) {
333
+ return Object.freeze(second === void 0 ? {
334
+ [VAR_SYMBOL]: true,
335
+ name: first
336
+ } : {
337
+ [VAR_SYMBOL]: true,
338
+ name: second,
339
+ collection: first
340
+ });
341
+ }
342
+ /**
343
+ * Define a variable collection: its variables, by name, with their values in its first mode,
344
+ * named `mode` (Figma's `Mode 1` by default). A render that binds any of them creates the
345
+ * collection, or updates the one with that name, so running the JSX again changes nothing twice.
346
+ */
347
+ function defineVars(collection, values, options = {}) {
348
+ const definition = {
349
+ name: collection,
350
+ modes: [{
351
+ name: options.mode ?? "Mode 1",
352
+ values
353
+ }]
354
+ };
355
+ const handles = {};
356
+ for (const name of Object.keys(values)) handles[name] = Object.freeze({
357
+ [VAR_SYMBOL]: true,
358
+ name,
359
+ collection: definition
360
+ });
361
+ return handles;
362
+ }
363
+ /**
364
+ * Add a mode to a collection `defineVars` defined, with the values that differ from its first
365
+ * mode; the rest keep the first mode's values, as a mode Figma adds copies them.
366
+ */
367
+ function defineMode(vars, name, values) {
368
+ const definition = Object.values(vars)[0]?.collection;
369
+ if (!definition || typeof definition === "string") throw new Error("defineMode() takes the variables defineVars() returned");
370
+ if (definition.modes.some((mode) => mode.name === name)) throw new Error(`Collection ${definition.name} already has a mode named ${name}`);
371
+ const known = definition.modes[0].values;
372
+ for (const key of Object.keys(values)) if (!Object.hasOwn(known, key)) throw new Error(`Collection ${definition.name} has no variable named ${key}`);
373
+ definition.modes.push({
374
+ name,
375
+ values
376
+ });
377
+ return Object.freeze({
378
+ [MODE_SYMBOL]: true,
379
+ name,
380
+ collection: definition
381
+ });
382
+ }
383
+ /**
384
+ * A mode of a collection the document already has, by their names, or by the collection's ID
385
+ * when several collections share its name.
386
+ */
387
+ function designMode(collection, mode) {
388
+ return Object.freeze({
389
+ [MODE_SYMBOL]: true,
390
+ name: mode,
391
+ collection
392
+ });
393
+ }
394
+ //#endregion
395
+ //#region src/schema.ts
396
+ /**
397
+ * Parse a value a design JSX script passed, or throw `heading` followed by every problem and
398
+ * where it is, as `v.summarize` lists them. Core words tool arguments the same way.
399
+ */
400
+ function parseScriptInput(heading, schema, value) {
401
+ const result = v.safeParse(schema, value);
402
+ if (result.success) return result.output;
403
+ throw new Error(`${heading}:\n${v.summarize(result.issues)}`);
404
+ }
405
+ /**
406
+ * The layer props an element that draws its own layer takes, such as a connector's: the
407
+ * renderer makes them into fields and variable bindings as it does for any layer.
408
+ */
409
+ const ownLayerPropsSchema = v.object({
410
+ name: v.optional(v.string()),
411
+ key: v.optional(v.unknown()),
412
+ visible: v.optional(v.boolean()),
413
+ opacity: v.optional(v.number())
414
+ });
415
+ /** `OwnLayerProps` and the props that place a layer in its parent, such as a sticky note's. */
416
+ const placedOwnLayerPropsSchema = v.object({
417
+ ...ownLayerPropsSchema.entries,
418
+ x: v.optional(v.number()),
419
+ y: v.optional(v.number()),
420
+ position: v.optional(v.picklist(["absolute"]))
421
+ });
422
+ /** A colour as a string, or as the colour a `designVar()` resolves to. */
423
+ const colorPropSchema = v.union([v.pipe(v.string(), v.rawTransform(({ dataset, addIssue, NEVER }) => {
424
+ const color = tryParseColor(dataset.value);
425
+ if (color) return color;
426
+ addIssue({ message: "expected a colour" });
427
+ return NEVER;
428
+ })), v.custom(isColor$1)], "expected a colour");
429
+ /**
430
+ * The props `schema` takes, read from `props`: one that does not fit is left out as if it were
431
+ * not set, since the renderer reports it (`elementPropWarnings`) and goes on.
432
+ */
433
+ function readElementProps(schema, props) {
434
+ const fitting = mapValues(schema.entries, (entry, key) => v.is(entry, props[key]) ? props[key] : void 0);
435
+ return v.parse(schema, fitting);
436
+ }
437
+ /** A value as a warning quotes it; one JSON cannot write, such as a BigInt inside it, by its brackets. */
438
+ function quoted(value) {
439
+ if (typeof value === "string") return `"${value}"`;
440
+ if (typeof value !== "object" || value === null) return String(value);
441
+ try {
442
+ return JSON.stringify(value);
443
+ } catch {
444
+ return Array.isArray(value) ? "[…]" : "{…}";
445
+ }
446
+ }
447
+ /** A warning for each prop `props` sets that does not fit `schema`, naming the element. */
448
+ function elementPropWarnings(schema, props, element) {
449
+ return Object.entries(schema.entries).flatMap(([key, entry]) => {
450
+ const value = props[key];
451
+ if (value === void 0 || isVariable(value)) return [];
452
+ const result = v.safeParse(entry, value);
453
+ if (result.success) return [];
454
+ const [issue] = result.issues;
455
+ const source = `${key} ${quoted(value)} on <${element}> is ignored`;
456
+ if (issue.kind === "transformation") return [`Unknown ${source}; ${issue.message}.`];
457
+ if (issue.type === "union" || issue.type === "custom") return [`Invalid ${source}; ${issue.message}.`];
458
+ return [`Invalid ${source}; expected ${issue.expected}.`];
459
+ });
460
+ }
461
+ /** A layer of the same JSX by name or `ref()`, or a point in the connector's parent. */
462
+ const connectorEndSchema = v.union([
463
+ v.string(),
464
+ v.custom(isLayerRef),
465
+ v.object({
466
+ x: v.number(),
467
+ y: v.number()
468
+ })
469
+ ], "expected a layer name, a ref(), or { x, y }");
470
+ /** The props `<Connector>` takes: its own, and the layer props that style its line. */
471
+ const connectorPropsSchema = v.object({
472
+ from: v.optional(connectorEndSchema),
473
+ to: v.optional(connectorEndSchema),
474
+ fromSide: v.optional(enumProp(CONNECTOR_SIDE)),
475
+ toSide: v.optional(enumProp(CONNECTOR_SIDE)),
476
+ line: v.optional(enumProp(CONNECTOR_LINE)),
477
+ startCap: v.optional(enumProp(STROKE_CAP)),
478
+ endCap: v.optional(enumProp(STROKE_CAP)),
479
+ ...ownLayerPropsSchema.entries,
480
+ stroke: v.optional(colorPropSchema),
481
+ strokeWidth: v.optional(v.pipe(v.number(), v.gtValue(0))),
482
+ dashPattern: v.optional(v.array(v.number()))
483
+ });
484
+ const sizeSchema = v.pipe(v.number(), v.gtValue(0));
485
+ const dashSchema = v.array(v.number());
486
+ /**
487
+ * The layer props a shape has: its place, the size it is given, which it grows past to fit its
488
+ * label, and its paint. The label is styled as FigJam styles it, and the shape lays it out.
489
+ */
490
+ const shapeLayerPropsSchema = v.object({
491
+ ...placedOwnLayerPropsSchema.entries,
492
+ w: v.optional(sizeSchema),
493
+ h: v.optional(sizeSchema),
494
+ rotate: v.optional(v.number()),
495
+ rounded: v.optional(v.pipe(v.number(), v.minValue(0))),
496
+ bg: v.optional(v.custom(isFillValue, "expected a colour or a paint")),
497
+ fills: v.optional(v.array(v.custom(isFillValue, "expected a colour or a paint"))),
498
+ stroke: v.optional(colorPropSchema),
499
+ strokeWidth: v.optional(sizeSchema),
500
+ strokeAlign: v.optional(enumProp(STROKE_ALIGN)),
501
+ strokeDash: v.optional(dashSchema),
502
+ strokes: v.optional(v.array(v.custom(isStrokeValue, "expected a stroke"))),
503
+ strokeCap: v.optional(enumProp(STROKE_CAP)),
504
+ strokeJoin: v.optional(enumProp(STROKE_JOIN)),
505
+ dashPattern: v.optional(dashSchema)
506
+ });
507
+ /**
508
+ * The props `<Shape>` takes: its kind, whether it keeps its height and truncates its label as a
509
+ * resized FigJam shape does, and the layer props a shape has.
510
+ */
511
+ const shapePropsSchema = v.object({
512
+ kind: v.optional(enumProp(SHAPE_KIND)),
513
+ truncate: v.optional(v.boolean()),
514
+ textSize: v.optional(enumProp(FIGJAM_TEXT_SIZE)),
515
+ typeface: v.optional(enumProp(FIGJAM_TYPEFACE)),
516
+ ...shapeLayerPropsSchema.entries
517
+ });
518
+ function isStickyColorName(value) {
519
+ return value in STICKY_COLORS;
520
+ }
521
+ /** A palette name such as `"yellow"`, or any colour. */
522
+ const stickyColorSchema = v.pipe(v.string(), v.rawTransform(({ dataset, addIssue, NEVER }) => {
523
+ const name = dataset.value;
524
+ if (isStickyColorName(name)) return { ...STICKY_COLORS[name] };
525
+ const color = tryParseColor(name);
526
+ if (color) return color;
527
+ addIssue({ message: `expected ${Object.keys(STICKY_COLORS).join(", ")}, or a colour` });
528
+ return NEVER;
529
+ }));
530
+ /** The props `<Sticky>` takes: its own, and the few layer props a note has. */
531
+ const stickyPropsSchema = v.object({
532
+ color: v.optional(stickyColorSchema),
533
+ author: v.optional(v.string()),
534
+ authorVisible: v.optional(v.boolean()),
535
+ wide: v.optional(v.boolean()),
536
+ textSize: v.optional(enumProp(FIGJAM_TEXT_SIZE)),
537
+ typeface: v.optional(enumProp(FIGJAM_TYPEFACE)),
538
+ scale: v.optional(v.pipe(v.number(), v.gtValue(0))),
539
+ ...placedOwnLayerPropsSchema.entries
540
+ });
541
+ //#endregion
542
+ //#region src/component-properties.ts
543
+ const PROPERTY_SYMBOL = Symbol.for("pairdraw.component-property");
544
+ function isComponentProperty(value) {
545
+ return typeof value === "object" && value !== null && PROPERTY_SYMBOL in value;
546
+ }
547
+ /**
548
+ * Bind a field to a property of the component it is drawn in, created on first use: on the
549
+ * component set, for a variant, as Figma keeps them, or else on the component.
550
+ */
551
+ function property(name, defaultValue) {
552
+ return Object.freeze({
553
+ [PROPERTY_SYMBOL]: true,
554
+ name,
555
+ defaultValue
556
+ });
557
+ }
558
+ /** The prop each property type binds, and the field it binds there. */
559
+ const BOUND_PROPS = {
560
+ text: {
561
+ type: "TEXT",
562
+ field: "TEXT",
563
+ node: "TEXT"
564
+ },
565
+ visible: {
566
+ type: "BOOLEAN",
567
+ field: "VISIBLE",
568
+ node: void 0
569
+ },
570
+ of: {
571
+ type: "INSTANCE_SWAP",
572
+ field: "INSTANCE_SWAP",
573
+ node: "INSTANCE"
574
+ }
575
+ };
576
+ /** The component, or the set it is a variant of, that holds properties for layers under `parentId`. */
577
+ function propertyOwner(graph, parentId) {
578
+ let node = graph.getNode(parentId);
579
+ while (node) {
580
+ if (node.type === "INSTANCE") throw new Error("property() cannot be used inside an instance");
581
+ if (node.type === "COMPONENT_SET") return node;
582
+ if (node.type === "COMPONENT") {
583
+ const set = node.parentId ? graph.getNode(node.parentId) : void 0;
584
+ return set?.type === "COMPONENT_SET" ? set : node;
585
+ }
586
+ node = node.parentId ? graph.getNode(node.parentId) : void 0;
587
+ }
588
+ throw new Error("property() must be inside a <Component> or <ComponentSet>");
589
+ }
590
+ /** The ID of the property with this name on `owner`, added if it has none. */
591
+ function ensureDefinition(graph, owner, name, type, defaultValue) {
592
+ const existing = owner.componentPropertyDefinitions.find((item) => item.name === name);
593
+ if (existing) {
594
+ if (existing.type !== type) throw new Error(`Component property ${name} is ${existing.type}, not ${type}`);
595
+ if (existing.defaultValue !== defaultValue) throw new Error(`Component property ${name} has two defaults: ${existing.defaultValue} and ${defaultValue}`);
596
+ return existing.id;
597
+ }
598
+ const id = createComponentPropertyId();
599
+ graph.updateNode(owner.id, { componentPropertyDefinitions: [...owner.componentPropertyDefinitions, {
600
+ id,
601
+ name,
602
+ type,
603
+ defaultValue
604
+ }] });
605
+ return id;
606
+ }
607
+ /**
608
+ * Bind the fields a layer's props place a `property()` in, creating the properties on its
609
+ * component; `componentId` gives the ID a swap's default component has.
610
+ */
611
+ function bindProperties(graph, source, type, parentId, componentId) {
612
+ if (source.properties !== void 0 && type !== "INSTANCE") throw new Error("Only instances accept properties; bind a field to property() instead");
613
+ const props = { ...source };
614
+ const references = [];
615
+ for (const [key, value] of Object.entries(source)) {
616
+ if (!isComponentProperty(value)) continue;
617
+ if (!Object.hasOwn(BOUND_PROPS, key)) throw new Error(`property() binds text, visible, or of, not ${key}`);
618
+ const bound = BOUND_PROPS[key];
619
+ if (bound.node && bound.node !== type) throw new Error(`property() in ${key} needs ${bound.node === "TEXT" ? "<Text>" : "<Instance>"}`);
620
+ const expected = bound.type === "BOOLEAN" ? "boolean" : "string";
621
+ if (typeof value.defaultValue !== expected) throw new Error(`Component property ${value.name} in ${key} takes a ${expected} default`);
622
+ let defaultValue = String(value.defaultValue);
623
+ if (bound.type === "INSTANCE_SWAP") {
624
+ const id = componentId(defaultValue);
625
+ if (!id) throw new Error(`<Instance> component not found: ${defaultValue}`);
626
+ defaultValue = id;
627
+ }
628
+ const propertyId = ensureDefinition(graph, propertyOwner(graph, parentId), value.name, bound.type, defaultValue);
629
+ references.push({
630
+ propertyId,
631
+ field: bound.field
632
+ });
633
+ props[key] = value.defaultValue;
634
+ }
635
+ return {
636
+ props,
637
+ references
638
+ };
639
+ }
640
+ /** Match the nearest component scope, including definitions inherited from its set. */
641
+ function componentPropertyScope(graph, parentId) {
642
+ let parent = graph.getNode(parentId);
643
+ while (parent) {
644
+ if (parent.type === "INSTANCE") return componentPropertyDefinitions(graph, parent);
645
+ if (parent.type === "COMPONENT_SET") return parent.componentPropertyDefinitions;
646
+ if (parent.type === "COMPONENT") {
647
+ const set = parent.parentId ? graph.getNode(parent.parentId) : void 0;
648
+ return set?.type === "COMPONENT_SET" ? [...set.componentPropertyDefinitions, ...parent.componentPropertyDefinitions] : parent.componentPropertyDefinitions;
649
+ }
650
+ parent = parent.parentId ? graph.getNode(parent.parentId) : void 0;
651
+ }
652
+ }
653
+ /** The one property with this name; a name several properties share is an error. */
654
+ function namedDefinition(definitions, name) {
655
+ const matches = definitions.filter((item) => item.name === name);
656
+ if (matches.length > 1) throw new Error(`Component property name ${name} is ambiguous; use one of the IDs: ${matches.map((item) => item.id).join(", ")}`);
657
+ return matches[0];
658
+ }
659
+ function assignValue(graph, instance, definition, key, value, componentId) {
660
+ if (definition.type === "VARIANT") throw new Error("Select a component-set variant when creating the instance");
661
+ if (definition.type === "BOOLEAN" && value !== "true" && value !== "false") throw new Error(`Expected true or false for component property: ${key}`);
662
+ const assigned = definition.type === "INSTANCE_SWAP" ? componentId(value) ?? value : value;
663
+ if (!applyComponentPropertyValue(graph, instance.id, definition, assigned)) throw new Error(`Cannot assign component property: ${key}`);
664
+ }
665
+ /** A value an instance gives a property, or an exposed nested instance's values by name. */
666
+ const assignedValueSchema = v.union([
667
+ v.string(),
668
+ v.boolean(),
669
+ v.number()
670
+ ]);
671
+ const exposedValuesSchema = v.record(v.string(), assignedValueSchema);
672
+ /** The one exposed nested instance with this name; a name several share is an error. */
673
+ function exposedInstanceNamed(graph, instance, name) {
674
+ const matches = exposedInstances(graph, instance).filter((node) => node.name === name);
675
+ if (matches.length > 1) throw new Error(`Exposed instance name ${name} is shared by ${matches.length} layers`);
676
+ return matches[0];
677
+ }
678
+ /**
679
+ * Pick the variant of an exposed instance's set that has the values it names, keeping its own
680
+ * for the rest, as its panel group does.
681
+ */
682
+ function selectNestedVariant(graph, nested, name, values) {
683
+ if (Object.keys(values).length === 0) return;
684
+ const component = instanceMainComponent(graph, nested);
685
+ const set = component?.parentId ? graph.getNode(component.parentId) : void 0;
686
+ if (!component || set?.type !== "COMPONENT_SET") return;
687
+ const wanted = {
688
+ ...component.componentPropertyValues,
689
+ ...values
690
+ };
691
+ const variant = graph.getChildren(set.id).find((node) => node.type === "COMPONENT" && Object.entries(wanted).every(([key, value]) => node.componentPropertyValues[key] === value));
692
+ if (!variant) throw new Error(`${name} has no variant ${Object.entries(values).map(([key, value]) => `${key}=${value}`).join(", ")}`);
693
+ if (variant.id !== component.id) graph.swapInstanceComponent(nested.id, variant.id);
694
+ }
695
+ /**
696
+ * Give the exposed nested instance named `name` its values: variants and properties by name,
697
+ * the way the instance itself takes them.
698
+ */
699
+ function assignExposedInstance(graph, instance, name, input, componentId) {
700
+ const nested = exposedInstanceNamed(graph, instance, name);
701
+ if (!nested) throw new Error(`Unknown component property or exposed instance: ${name}`);
702
+ const values = parseScriptInput(`Invalid values for ${name}`, exposedValuesSchema, input);
703
+ const variantNames = new Set(componentPropertyDefinitions(graph, nested).filter((definition) => definition.type === "VARIANT").map((definition) => definition.name));
704
+ selectNestedVariant(graph, nested, name, Object.fromEntries(Object.entries(values).filter(([key]) => variantNames.has(key)).map(([key, value]) => [key, String(value)])));
705
+ const definitions = componentPropertyDefinitions(graph, nested);
706
+ for (const [key, value] of Object.entries(values)) {
707
+ if (variantNames.has(key)) continue;
708
+ const definition = namedDefinition(definitions, key);
709
+ if (!definition) throw new Error(`Unknown component property on ${name}: ${key}`);
710
+ assignValue(graph, nested, definition, key, String(value), componentId);
711
+ }
712
+ }
713
+ /**
714
+ * Set text, boolean, and swap properties an instance names as props, as in `Title="Hello"`, the
715
+ * way it picks a variant, and an exposed nested instance's values, as in `Action={{ Label: 'Save' }}`;
716
+ * design JSX props keep their meaning.
717
+ */
718
+ function assignNamedProperties(graph, instance, props, componentId) {
719
+ const definitions = componentPropertyDefinitions(graph, instance).filter((definition) => definition.type !== "VARIANT");
720
+ for (const [key, value] of Object.entries(props)) {
721
+ if (DESIGN_JSX_SUPPORTED_PROPERTIES.has(key)) continue;
722
+ if (isPlainObject(value) && exposedInstanceNamed(graph, instance, key)) {
723
+ assignExposedInstance(graph, instance, key, value, componentId);
724
+ continue;
725
+ }
726
+ const definition = namedDefinition(definitions, key);
727
+ if (!definition) continue;
728
+ if (typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") throw new Error(`Expected a string or boolean for component property: ${key}`);
729
+ assignValue(graph, instance, definition, key, String(value), componentId);
730
+ }
731
+ }
732
+ /**
733
+ * Keys are property IDs or, because saving to `.fig` replaces authored IDs
734
+ * with GUIDs, names, which survive a reload; an object gives an exposed nested instance its values.
735
+ */
736
+ function assignComponentProperties(graph, instance, input, componentId) {
737
+ if (input === void 0) return;
738
+ const assignments = parseScriptInput("Invalid properties on <Instance>", v.record(v.string(), v.union([assignedValueSchema, exposedValuesSchema])), input);
739
+ const definitions = componentPropertyDefinitions(graph, instance);
740
+ for (const [key, value] of Object.entries(assignments)) {
741
+ if (isPlainObject(value)) {
742
+ assignExposedInstance(graph, instance, key, value, componentId);
743
+ continue;
744
+ }
745
+ const definition = definitions.find((item) => item.id === key) ?? namedDefinition(definitions, key);
746
+ if (!definition) throw new Error(`Unknown component property: ${key}`);
747
+ assignValue(graph, instance, definition, key, String(value), componentId);
748
+ }
749
+ }
750
+ /** Mark an instance in a component's layers as exposed, under Figma's rules for exposing one. */
751
+ function exposeInstance(graph, instance) {
752
+ const issue = instanceExposureIssue(graph, instance);
753
+ if (issue === "not-in-component") throw new Error("exposed needs an <Instance> in a component");
754
+ if (issue === "not-primary") throw new Error("exposed needs an <Instance> in a component, not inside another instance");
755
+ if (issue === "nothing-to-expose") throw new Error(`${instance.name} has no properties or exposed instances to expose`);
756
+ graph.updateNode(instance.id, { isExposedInstance: true });
757
+ }
758
+ /** The names an instance of `component` takes: its properties' and its exposed instances'. */
759
+ function componentPropNames(graph, component) {
760
+ return [...(componentPropertyScope(graph, component.id) ?? []).map((definition) => definition.name), ...exposableInstances(graph, component.id).filter((node) => node.isExposedInstance).map((node) => node.name)];
761
+ }
762
+ function parseVariantValues(name) {
763
+ const entries = compact(name.split(",").map((part) => part.trim()));
764
+ const values = {};
765
+ for (const entry of entries) {
766
+ const [key = "", ...rest] = entry.split("=");
767
+ const property = key.trim();
768
+ const value = rest.join("=").trim();
769
+ if (property && value) values[property] = value;
770
+ }
771
+ return values;
772
+ }
773
+ /** Variant properties a component set takes from its variants' names, such as `State=On`. */
774
+ function inferComponentSetProperties(graph, componentSetId) {
775
+ const componentSet = graph.getNode(componentSetId);
776
+ if (componentSet?.type !== "COMPONENT_SET") return;
777
+ const existingDefinitions = componentSet.componentPropertyDefinitions;
778
+ const variants = graph.getChildren(componentSetId).filter((node) => node.type === "COMPONENT");
779
+ const options = /* @__PURE__ */ new Map();
780
+ const valuesById = /* @__PURE__ */ new Map();
781
+ for (const variant of variants) {
782
+ const values = parseVariantValues(variant.name);
783
+ valuesById.set(variant.id, values);
784
+ for (const [property, value] of Object.entries(values)) {
785
+ let set = options.get(property);
786
+ if (!set) {
787
+ set = /* @__PURE__ */ new Set();
788
+ options.set(property, set);
789
+ }
790
+ set.add(value);
791
+ }
792
+ }
793
+ const definitions = [...options.entries()].filter(([name]) => !existingDefinitions.some((definition) => definition.type === "VARIANT" && definition.name === name)).map(([name, values]) => {
794
+ const variantOptions = [...values];
795
+ return {
796
+ id: createComponentPropertyId(),
797
+ name,
798
+ type: "VARIANT",
799
+ defaultValue: variantOptions[0] ?? "",
800
+ variantOptions
801
+ };
802
+ });
803
+ for (const [id, values] of valuesById) graph.updateNode(id, { componentPropertyValues: values });
804
+ graph.updateNode(componentSetId, { componentPropertyDefinitions: [...existingDefinitions, ...definitions] });
805
+ }
806
+ //#endregion
807
+ export { BLEND_MODE, CONNECTOR_LINE, CONNECTOR_SIDE, CONSTRAINT, DEFAULT_MODE_NAME, ENUM_PROPS, FIGJAM_TEXT_SIZE, FIGJAM_TYPEFACE, LayerRefs, MASK_TYPE, SHAPE_KIND, STROKE_ALIGN, STROKE_CAP, STROKE_JOIN, TEXT_ALIGN, TEXT_ALIGN_VERTICAL, TEXT_AUTO_RESIZE, TEXT_CASE, TEXT_DECORATION, TEXT_DECORATION_STYLE, TEXT_DIRECTION, applyStrokeOverrides, assignComponentProperties, assignNamedProperties, bindProperties, componentPropNames, connectorPropsSchema, defineMode, defineVars, designMode, designVar, elementPropWarnings, exposeInstance, fillFromValue, inferComponentSetProperties, isColor$1 as isColor, isComponentProperty, isFillValue, isLayerRef, isMode, isVariable, isVariableInput, ownLayerPropsSchema, parseScriptInput, placedOwnLayerPropsSchema, property, readElementProps, ref, shapeLayerPropsSchema, shapePropsSchema, stickyPropsSchema };
808
+
809
+ //# sourceMappingURL=component-properties.js.map