@pairdraw/pen 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.
- package/LICENSE +21 -0
- package/README.md +10 -2
- package/dist/chunks/annotations.js +510 -0
- package/dist/chunks/annotations.js.map +1 -0
- package/dist/chunks/assets.js +158 -0
- package/dist/chunks/assets.js.map +1 -0
- package/dist/chunks/effects.js +775 -0
- package/dist/chunks/effects.js.map +1 -0
- package/dist/chunks/geometry.js +95 -0
- package/dist/chunks/geometry.js.map +1 -0
- package/dist/chunks/icons.js +156 -0
- package/dist/chunks/icons.js.map +1 -0
- package/dist/chunks/imports.js +120 -0
- package/dist/chunks/imports.js.map +1 -0
- package/dist/chunks/index.js +1478 -0
- package/dist/chunks/index.js.map +1 -0
- package/dist/index.d.ts +492 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/package.json +31 -4
- package/src/annotations.ts +128 -0
- package/src/assets.ts +224 -0
- package/src/effects.ts +62 -0
- package/src/geometry.ts +71 -0
- package/src/icons.ts +173 -0
- package/src/images.ts +109 -0
- package/src/imports.ts +169 -0
- package/src/index.ts +23 -0
- package/src/instances.ts +272 -0
- package/src/jsonc.ts +77 -0
- package/src/layout.ts +135 -0
- package/src/library.ts +153 -0
- package/src/nodes.ts +410 -0
- package/src/paints.ts +417 -0
- package/src/placeholders.ts +86 -0
- package/src/placement.ts +84 -0
- package/src/plugin-data.ts +86 -0
- package/src/read.ts +150 -0
- package/src/schema.ts +299 -0
- package/src/slots.ts +41 -0
- package/src/text.ts +92 -0
- package/src/variables.ts +284 -0
- package/src/write.ts +594 -0
|
@@ -0,0 +1,1478 @@
|
|
|
1
|
+
import { UNRESOLVED_REF, applyAnnotation, applyCornerRadius, applyPadding, applyPenPluginData, bindIfVar, buildVarContext, createAnnotation, isAnnotation, isVarRef, mapAlignItems, mapJustifyContent, mapLayoutMode, parseSize, resolveBoolean, resolveNumber, resolveString, unresolvedRef } from "./annotations.js";
|
|
2
|
+
import { withImports } from "./imports.js";
|
|
3
|
+
import { ellipseArc, lineNetwork, pathNetwork } from "./geometry.js";
|
|
4
|
+
import { drawIcon, insideComponent, removeUnusedIconComponents, useIconComponent } from "./icons.js";
|
|
5
|
+
import { applyStroke, convertEffects, convertPaints, createImageStore, penFileSchema, strokeFields } from "./effects.js";
|
|
6
|
+
import { SceneGraph, generateId } from "@pairdraw/scene-graph";
|
|
7
|
+
import { colorToHex, colorToHex8 } from "@pairdraw/scene-graph/color";
|
|
8
|
+
import { pick } from "es-toolkit/object";
|
|
9
|
+
import { isEqual } from "es-toolkit/predicate";
|
|
10
|
+
import { createComponentPropertyId, libraryDefinitionsPage } from "@pairdraw/scene-graph/components";
|
|
11
|
+
import * as v from "valibot";
|
|
12
|
+
import { INSTANCE_OVERRIDE_FIELDS, detachInstance, populateInstanceChildren, recordInstanceOverride, swapInstanceComponent } from "@pairdraw/scene-graph/instances";
|
|
13
|
+
import { CORNER_FIELDS } from "@pairdraw/scene-graph/fields";
|
|
14
|
+
import { fillSizingFields, layoutSizing } from "@pairdraw/scene-graph/layout";
|
|
15
|
+
import { stickySublayers } from "@pairdraw/scene-graph/generated";
|
|
16
|
+
import { applyGradientTransform, invertGradientTransform } from "@pairdraw/scene-graph/gradient";
|
|
17
|
+
import { getNodeLocalMatrix, localTransformFromWorld } from "@pairdraw/scene-graph/coordinate";
|
|
18
|
+
import { fitEnclosingGroups } from "@pairdraw/scene-graph/group-bounds";
|
|
19
|
+
import Matrix from "@pairdraw/scene-graph/matrix";
|
|
20
|
+
import { canCreateSlot, claimSlotContent, createSlotProperty, slotOwner, slotScope, updateSlotProperty } from "@pairdraw/scene-graph/slots";
|
|
21
|
+
import { percentLength, pixelLength } from "@pairdraw/scene-graph/text";
|
|
22
|
+
//#region src/library.ts
|
|
23
|
+
/** The component IDs a layer and its overrides name: its `ref`s and the slots' suggestions. */
|
|
24
|
+
function namedComponents(node, found) {
|
|
25
|
+
if (typeof node.ref === "string") found.push(node.ref);
|
|
26
|
+
if (Array.isArray(node.slot)) found.push(...node.slot);
|
|
27
|
+
for (const child of node.children ?? []) namedComponents(child, found);
|
|
28
|
+
for (const override of Object.values(node.descendants ?? {})) namedComponents(override, found);
|
|
29
|
+
}
|
|
30
|
+
function mergeTheme(outer, inner) {
|
|
31
|
+
return outer || inner ? {
|
|
32
|
+
...outer,
|
|
33
|
+
...inner
|
|
34
|
+
} : void 0;
|
|
35
|
+
}
|
|
36
|
+
/** Each reusable layer of the imported documents by ID, with the outermost component holding it. */
|
|
37
|
+
function componentOwners(imports) {
|
|
38
|
+
const owners = /* @__PURE__ */ new Map();
|
|
39
|
+
for (const [alias, { path, doc }] of imports) {
|
|
40
|
+
const visit = (nodes, root, theme) => {
|
|
41
|
+
for (const node of nodes) {
|
|
42
|
+
const own = root ?? (node.reusable ? node : void 0);
|
|
43
|
+
if (node.reusable && own) owners.set(node.id, {
|
|
44
|
+
alias,
|
|
45
|
+
path,
|
|
46
|
+
root: own,
|
|
47
|
+
theme
|
|
48
|
+
});
|
|
49
|
+
visit(node.children ?? [], own, own ? theme : mergeTheme(theme, node.theme));
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
visit(doc.children, void 0, void 0);
|
|
53
|
+
}
|
|
54
|
+
return owners;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The imported components a document draws, through the components they draw in turn, each as the
|
|
58
|
+
* outermost component holding it, in the order the document first names them. A library's other
|
|
59
|
+
* components stay out of the document, which only ever shows instances of the ones it uses.
|
|
60
|
+
*/
|
|
61
|
+
function usedRoots(doc, imports) {
|
|
62
|
+
const owners = componentOwners(imports);
|
|
63
|
+
const pending = [];
|
|
64
|
+
for (const node of doc.children) namedComponents(node, pending);
|
|
65
|
+
const roots = /* @__PURE__ */ new Map();
|
|
66
|
+
for (const id of pending) {
|
|
67
|
+
const owner = owners.get(id);
|
|
68
|
+
if (!owner || roots.has(owner.root.id)) continue;
|
|
69
|
+
roots.set(owner.root.id, owner);
|
|
70
|
+
namedComponents(owner.root, pending);
|
|
71
|
+
}
|
|
72
|
+
return [...roots.values()];
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The document with the imported components it uses after its own layers, and the imported
|
|
76
|
+
* variables and themes, so `penAssets` lists every icon and image it draws and no other of a
|
|
77
|
+
* library's.
|
|
78
|
+
*/
|
|
79
|
+
function withUsedImports(doc, imports) {
|
|
80
|
+
if (imports.size === 0) return doc;
|
|
81
|
+
return {
|
|
82
|
+
...withImports(doc, imports),
|
|
83
|
+
children: [...doc.children, ...usedRoots(doc, imports).map((owner) => owner.root)]
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Draws the imported components the document uses on the hidden library page, in the themes they
|
|
88
|
+
* sit in in their own documents, so its instances of them resolve. Nothing is drawn when the
|
|
89
|
+
* document uses none.
|
|
90
|
+
*/
|
|
91
|
+
function createLibraryRoots(doc, imports, build, create) {
|
|
92
|
+
const roots = usedRoots(doc, imports);
|
|
93
|
+
if (roots.length === 0) return [];
|
|
94
|
+
const page = libraryDefinitionsPage(build.graph);
|
|
95
|
+
return roots.map(({ alias, path, root, theme }) => {
|
|
96
|
+
const leave = theme ? build.ctx.enterTheme(theme) : void 0;
|
|
97
|
+
try {
|
|
98
|
+
return {
|
|
99
|
+
id: create(root, page.id, build),
|
|
100
|
+
alias,
|
|
101
|
+
path
|
|
102
|
+
};
|
|
103
|
+
} finally {
|
|
104
|
+
leave?.();
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/** `value` with what `allowed` rejects replaced, starting with a letter or digit, at most `max` long. */
|
|
109
|
+
function libraryName(value, allowed, max) {
|
|
110
|
+
const name = value.replace(allowed, "_");
|
|
111
|
+
return (/^[a-zA-Z0-9]/.test(name) ? name : `x${name}`).slice(0, max);
|
|
112
|
+
}
|
|
113
|
+
/** The ID a library's assets name it by: `pen:<alias>`, in the characters library IDs take. */
|
|
114
|
+
function penLibraryId(alias) {
|
|
115
|
+
return libraryName(`pen:${alias}`, /[^a-zA-Z0-9._:-]/g, 128);
|
|
116
|
+
}
|
|
117
|
+
/** A component's key in its library: its ID in the imported document, without the alias. */
|
|
118
|
+
function penLibraryAssetKey(alias, id) {
|
|
119
|
+
const prefix = `${alias}:`;
|
|
120
|
+
return libraryName(id.startsWith(prefix) ? id.slice(prefix.length) : id, /[^a-zA-Z0-9._:/-]/g, 256);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Marks the imported components as a library's definitions: read-only, locked, and each with its
|
|
124
|
+
* library and key, so the editor treats them as it treats a component library's, and their
|
|
125
|
+
* instances as library instances. The file they came from is their revision.
|
|
126
|
+
*/
|
|
127
|
+
function markLibraryRoots(graph, roots) {
|
|
128
|
+
for (const { id, alias, path } of roots) {
|
|
129
|
+
const root = graph.getNode(id);
|
|
130
|
+
if (!root) continue;
|
|
131
|
+
const libraryId = penLibraryId(alias);
|
|
132
|
+
const queue = [root];
|
|
133
|
+
for (const node of queue) {
|
|
134
|
+
if (node === root || node.type === "COMPONENT" || node.type === "COMPONENT_SET") node.librarySource = {
|
|
135
|
+
identity: {
|
|
136
|
+
libraryId,
|
|
137
|
+
assetKey: penLibraryAssetKey(alias, node.id),
|
|
138
|
+
revisionId: path
|
|
139
|
+
},
|
|
140
|
+
sourceNodeId: null,
|
|
141
|
+
readOnly: true
|
|
142
|
+
};
|
|
143
|
+
queue.push(...graph.getChildren(node.id));
|
|
144
|
+
}
|
|
145
|
+
root.locked = true;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
//#endregion
|
|
149
|
+
//#region src/placeholders.ts
|
|
150
|
+
/**
|
|
151
|
+
* Layers pen.dev draws that this reader cannot: a `script` node's generated layers, a `browser`
|
|
152
|
+
* node's live page, and a `ref` to a component that could not be found, such as one from a library
|
|
153
|
+
* the host could not read. Each reads as a frame in its box, filled and outlined with a dashed line
|
|
154
|
+
* where pen.dev gives it neither, and labelled with what it stands for when it has no layers.
|
|
155
|
+
*/
|
|
156
|
+
const EMBED_TYPES = /* @__PURE__ */ new Set(["script", "browser"]);
|
|
157
|
+
const PLACEHOLDER_FILL = {
|
|
158
|
+
r: .96,
|
|
159
|
+
g: .96,
|
|
160
|
+
b: .96,
|
|
161
|
+
a: 1
|
|
162
|
+
};
|
|
163
|
+
const PLACEHOLDER_OUTLINE = {
|
|
164
|
+
r: .62,
|
|
165
|
+
g: .62,
|
|
166
|
+
b: .62,
|
|
167
|
+
a: 1
|
|
168
|
+
};
|
|
169
|
+
const PLACEHOLDER_DASH = [4, 4];
|
|
170
|
+
/** Room around the label, inside the outline. */
|
|
171
|
+
const PLACEHOLDER_INSET = 8;
|
|
172
|
+
const LABEL_SIZE = 12;
|
|
173
|
+
const LABEL_COLOR = "#737373";
|
|
174
|
+
/** Whether a layer reads as a placeholder. */
|
|
175
|
+
function isPlaceholder(pen) {
|
|
176
|
+
return EMBED_TYPES.has(pen.type) || unresolvedRef(pen) !== void 0;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Fills and outlines a placeholder where pen.dev gives it no paint of its own, insets an auto
|
|
180
|
+
* layout's content, and clips a script or browser frame to its box, as pen.dev shows them.
|
|
181
|
+
*/
|
|
182
|
+
function applyPlaceholderLook(node, pen) {
|
|
183
|
+
if (pen.fill === void 0) node.fills = [{
|
|
184
|
+
type: "SOLID",
|
|
185
|
+
color: { ...PLACEHOLDER_FILL },
|
|
186
|
+
opacity: 1,
|
|
187
|
+
visible: true
|
|
188
|
+
}];
|
|
189
|
+
if (node.strokes.length === 0) node.strokes = [{
|
|
190
|
+
type: "SOLID",
|
|
191
|
+
color: { ...PLACEHOLDER_OUTLINE },
|
|
192
|
+
opacity: 1,
|
|
193
|
+
visible: true,
|
|
194
|
+
weight: 1,
|
|
195
|
+
align: "INSIDE",
|
|
196
|
+
dashPattern: [...PLACEHOLDER_DASH]
|
|
197
|
+
}];
|
|
198
|
+
if (pen.padding === void 0 && node.layoutMode !== "NONE") {
|
|
199
|
+
node.paddingTop = PLACEHOLDER_INSET;
|
|
200
|
+
node.paddingRight = PLACEHOLDER_INSET;
|
|
201
|
+
node.paddingBottom = PLACEHOLDER_INSET;
|
|
202
|
+
node.paddingLeft = PLACEHOLDER_INSET;
|
|
203
|
+
}
|
|
204
|
+
if (EMBED_TYPES.has(pen.type) && pen.clip === void 0) node.clipsContent = true;
|
|
205
|
+
}
|
|
206
|
+
/** What a placeholder stands for: its file, its page, or the component it names. */
|
|
207
|
+
function labelText(pen) {
|
|
208
|
+
const missing = unresolvedRef(pen);
|
|
209
|
+
if (missing !== void 0) return missing || (pen.name ?? "ref");
|
|
210
|
+
if (pen.type === "script" && pen.scriptUri) return pen.scriptUri;
|
|
211
|
+
if (pen.type === "browser" && pen.url) return pen.url;
|
|
212
|
+
return pen.name ?? pen.type;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* The label a placeholder without layers of its own shows, as a text layer; none for one with
|
|
216
|
+
* layers, such as a script node pen.dev saved with what it generated. The label says it was
|
|
217
|
+
* generated, so a writer can leave it out.
|
|
218
|
+
*/
|
|
219
|
+
function placeholderLabel(pen, nodeId) {
|
|
220
|
+
if (!isPlaceholder(pen) || (pen.children?.length ?? 0) > 0) return void 0;
|
|
221
|
+
const text = labelText(pen);
|
|
222
|
+
return {
|
|
223
|
+
id: `${nodeId}#label`,
|
|
224
|
+
type: "text",
|
|
225
|
+
name: text,
|
|
226
|
+
content: text,
|
|
227
|
+
fontSize: LABEL_SIZE,
|
|
228
|
+
fill: LABEL_COLOR,
|
|
229
|
+
x: PLACEHOLDER_INSET,
|
|
230
|
+
y: PLACEHOLDER_INSET,
|
|
231
|
+
generated: "placeholder"
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
//#endregion
|
|
235
|
+
//#region src/placement.ts
|
|
236
|
+
function isPlain(placement) {
|
|
237
|
+
return placement.rotation === 0 && !placement.flipX && !placement.flipY;
|
|
238
|
+
}
|
|
239
|
+
function inFlow(graph, node) {
|
|
240
|
+
const parent = node.parentId ? graph.getNode(node.parentId) : void 0;
|
|
241
|
+
return !!parent && parent.layoutMode !== "NONE" && node.layoutPositioning !== "ABSOLUTE";
|
|
242
|
+
}
|
|
243
|
+
/** Sets a layer's position and turn so it lands where pen.dev draws it; `offset` is where its box starts in pen.dev's. */
|
|
244
|
+
function place(graph, node, placement, offset = {
|
|
245
|
+
x: 0,
|
|
246
|
+
y: 0
|
|
247
|
+
}) {
|
|
248
|
+
const world = Matrix.multiply(Matrix.translated(placement.x, placement.y), Matrix.rotated(-placement.rotation * Math.PI / 180), Matrix.scaled(placement.flipX ? -1 : 1, placement.flipY ? -1 : 1), Matrix.translated(offset.x, offset.y));
|
|
249
|
+
const local = localTransformFromWorld({
|
|
250
|
+
...node,
|
|
251
|
+
flipX: placement.flipX
|
|
252
|
+
}, world, Matrix.identity());
|
|
253
|
+
if (!local) return;
|
|
254
|
+
if (inFlow(graph, node)) graph.updateNode(node.id, {
|
|
255
|
+
...local,
|
|
256
|
+
x: node.x,
|
|
257
|
+
y: node.y
|
|
258
|
+
});
|
|
259
|
+
else graph.updateNode(node.id, local);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Places every turned or mirrored layer, which the reader builds upright. Then each group, inner
|
|
263
|
+
* ones first, is fitted to its placed layers and placed itself; its box starts at its layers'
|
|
264
|
+
* bounds, wherever pen.dev's starts. `groupIds` is in reading order.
|
|
265
|
+
*/
|
|
266
|
+
function placeLayers(graph, placements, groupIds) {
|
|
267
|
+
const groups = new Set(groupIds);
|
|
268
|
+
for (const [id, placement] of placements) {
|
|
269
|
+
const node = graph.getNode(id);
|
|
270
|
+
if (node && !groups.has(id) && !isPlain(placement)) place(graph, node, placement);
|
|
271
|
+
}
|
|
272
|
+
const origins = /* @__PURE__ */ new Map();
|
|
273
|
+
for (const id of groupIds) {
|
|
274
|
+
const group = graph.getNode(id);
|
|
275
|
+
if (group) origins.set(id, {
|
|
276
|
+
x: group.x,
|
|
277
|
+
y: group.y
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
for (const id of groupIds.toReversed()) {
|
|
281
|
+
fitEnclosingGroups(graph, [id]);
|
|
282
|
+
const node = graph.getNode(id);
|
|
283
|
+
const origin = origins.get(id);
|
|
284
|
+
const placement = placements.get(id);
|
|
285
|
+
if (!node || !origin || !placement || isPlain(placement)) continue;
|
|
286
|
+
place(graph, node, placement, {
|
|
287
|
+
x: node.x - origin.x,
|
|
288
|
+
y: node.y - origin.y
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
//#endregion
|
|
293
|
+
//#region src/slots.ts
|
|
294
|
+
/**
|
|
295
|
+
* Makes a frame pen.dev marks with `slot` a slot of the component it is in, suggesting the
|
|
296
|
+
* components it lists that the document defines. A frame outside a component has no slot to be.
|
|
297
|
+
*/
|
|
298
|
+
function createPenSlot(node, pen, build) {
|
|
299
|
+
const { graph, components } = build;
|
|
300
|
+
if (!Array.isArray(pen.slot) || !canCreateSlot(graph, node)) return;
|
|
301
|
+
const definition = createSlotProperty(graph, node.id, createComponentPropertyId());
|
|
302
|
+
const owner = slotOwner(graph, node);
|
|
303
|
+
if (!definition || !owner) return;
|
|
304
|
+
const preferredValues = pen.slot.filter((id) => components.get(id)?.type === "frame");
|
|
305
|
+
if (preferredValues.length > 0) updateSlotProperty(graph, owner.id, definition.id, { preferredValues });
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Lets `instance` own the content of the slot frame `target`, which an override of its is about
|
|
309
|
+
* to fill, as filling a slot in pen.dev keeps the instance. Returns false when `target` is not a
|
|
310
|
+
* slot of that very instance, whose layers the override must then replace.
|
|
311
|
+
*/
|
|
312
|
+
function claimSlot(build, instance, target) {
|
|
313
|
+
const scope = slotScope(build.graph, target.id);
|
|
314
|
+
if (scope.kind !== "slot" || scope.frame.id !== target.id || scope.instance.id !== instance.id) return false;
|
|
315
|
+
claimSlotContent(build.graph, scope);
|
|
316
|
+
return true;
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
//#region src/text.ts
|
|
320
|
+
const FONT_WEIGHTS = {
|
|
321
|
+
thin: 100,
|
|
322
|
+
extralight: 200,
|
|
323
|
+
light: 300,
|
|
324
|
+
normal: 400,
|
|
325
|
+
regular: 400,
|
|
326
|
+
medium: 500,
|
|
327
|
+
semibold: 600,
|
|
328
|
+
bold: 700,
|
|
329
|
+
extrabold: 800,
|
|
330
|
+
black: 900
|
|
331
|
+
};
|
|
332
|
+
/** pen.dev writes weights as numbers in strings, such as "700"; older files use names. */
|
|
333
|
+
function fontWeight(value, ctx) {
|
|
334
|
+
if (value === void 0) return 400;
|
|
335
|
+
if (typeof value === "number") return value;
|
|
336
|
+
const named = isVarRef(value) ? ctx.resolveString(value) || ctx.resolveNumber(value) : value;
|
|
337
|
+
const numeric = Number(named);
|
|
338
|
+
if (Number.isFinite(numeric) && numeric > 0) return numeric;
|
|
339
|
+
return FONT_WEIGHTS[String(named).toLowerCase()] ?? 400;
|
|
340
|
+
}
|
|
341
|
+
const TEXT_ALIGN = {
|
|
342
|
+
left: "LEFT",
|
|
343
|
+
center: "CENTER",
|
|
344
|
+
right: "RIGHT",
|
|
345
|
+
justify: "JUSTIFIED"
|
|
346
|
+
};
|
|
347
|
+
const TEXT_ALIGN_VERTICAL = {
|
|
348
|
+
top: "TOP",
|
|
349
|
+
middle: "CENTER",
|
|
350
|
+
bottom: "BOTTOM"
|
|
351
|
+
};
|
|
352
|
+
/**
|
|
353
|
+
* `auto` grows on one line, `fixed-width` wraps and grows down, and `fixed-width-height` wraps in
|
|
354
|
+
* a fixed box its text may overflow.
|
|
355
|
+
*/
|
|
356
|
+
const TEXT_GROWTH = {
|
|
357
|
+
auto: "WIDTH_AND_HEIGHT",
|
|
358
|
+
"fixed-width": "HEIGHT",
|
|
359
|
+
"fixed-width-height": "NONE"
|
|
360
|
+
};
|
|
361
|
+
/**
|
|
362
|
+
* A text layer's content and style. Content that reads like a variable reference stays as written,
|
|
363
|
+
* as pen.dev shows it. pen.dev 2.21 draws no underline, strikethrough, or text stroke, so those
|
|
364
|
+
* are left out to match it. An `href` is kept as a link, drawn without an underline.
|
|
365
|
+
*/
|
|
366
|
+
function applyTextProps(node, pen, ctx) {
|
|
367
|
+
const isIconFont = pen.type === "icon_font";
|
|
368
|
+
node.text = isIconFont ? pen.iconFontName ?? "" : pen.content ?? "";
|
|
369
|
+
node.fontFamily = isIconFont ? pen.iconFontFamily ?? "Material Symbols Sharp" : resolveString(pen.fontFamily, ctx) ?? "Inter";
|
|
370
|
+
bindIfVar(node, "fontFamily", pen.fontFamily, ctx);
|
|
371
|
+
node.fontSize = resolveNumber(pen.fontSize, ctx, 14);
|
|
372
|
+
bindIfVar(node, "fontSize", pen.fontSize, ctx);
|
|
373
|
+
const weight = pen.fontWeight ?? (isIconFont ? pen.weight : void 0);
|
|
374
|
+
node.fontWeight = fontWeight(weight, ctx);
|
|
375
|
+
bindIfVar(node, "fontWeight", weight, ctx);
|
|
376
|
+
node.italic = resolveString(pen.fontStyle, ctx)?.toLowerCase() === "italic";
|
|
377
|
+
node.textAlignHorizontal = TEXT_ALIGN[pen.textAlign ?? "left"] ?? "LEFT";
|
|
378
|
+
node.textAlignVertical = TEXT_ALIGN_VERTICAL[pen.textAlignVertical ?? "top"] ?? "TOP";
|
|
379
|
+
if (pen.lineHeight !== void 0) node.lineHeight = percentLength(resolveNumber(pen.lineHeight, ctx) * 100);
|
|
380
|
+
if (pen.letterSpacing !== void 0) node.letterSpacing = pixelLength(resolveNumber(pen.letterSpacing, ctx));
|
|
381
|
+
node.textAutoResize = TEXT_GROWTH[pen.textGrowth ?? "auto"] ?? "WIDTH_AND_HEIGHT";
|
|
382
|
+
node.opticalSizeFromFontSize = false;
|
|
383
|
+
node.strokes = [];
|
|
384
|
+
node.styleRuns = textLink(pen, node.text, ctx);
|
|
385
|
+
}
|
|
386
|
+
/** A text's `href` links all of its characters, as one run. */
|
|
387
|
+
function textLink(pen, text, ctx) {
|
|
388
|
+
const href = pen.type === "text" ? resolveString(pen.href ?? void 0, ctx)?.trim() : void 0;
|
|
389
|
+
if (!href || text.length === 0) return [];
|
|
390
|
+
return [{
|
|
391
|
+
start: 0,
|
|
392
|
+
length: text.length,
|
|
393
|
+
style: { hyperlink: {
|
|
394
|
+
type: "URL",
|
|
395
|
+
value: href
|
|
396
|
+
} }
|
|
397
|
+
}];
|
|
398
|
+
}
|
|
399
|
+
//#endregion
|
|
400
|
+
//#region src/nodes.ts
|
|
401
|
+
function penPlacement(pen, ctx) {
|
|
402
|
+
return {
|
|
403
|
+
x: pen.x ?? 0,
|
|
404
|
+
y: pen.y ?? 0,
|
|
405
|
+
rotation: resolveNumber(pen.rotation, ctx),
|
|
406
|
+
flipX: resolveBoolean(pen.flipX, ctx, false),
|
|
407
|
+
flipY: resolveBoolean(pen.flipY, ctx, false)
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* A `line` runs from its box's top-left corner to its bottom-right, so a line with no height is
|
|
412
|
+
* a line layer and any other one a vector drawn across its box.
|
|
413
|
+
*/
|
|
414
|
+
function isFlatLine(pen, ctx) {
|
|
415
|
+
const height = parseSize(pen.height, 100, ctx);
|
|
416
|
+
return height.sizing === "FIXED" && height.value === 0;
|
|
417
|
+
}
|
|
418
|
+
function sceneType(pen, ctx) {
|
|
419
|
+
if (pen.type === "frame") return pen.reusable ? "COMPONENT" : "FRAME";
|
|
420
|
+
if (pen.type === "line") return isFlatLine(pen, ctx) ? "LINE" : "VECTOR";
|
|
421
|
+
if (isAnnotation(pen)) return "STICKY";
|
|
422
|
+
if (pen.type === "rectangle") return "RECTANGLE";
|
|
423
|
+
if (pen.type === "ellipse") return "ELLIPSE";
|
|
424
|
+
if (pen.type === "polygon") return "POLYGON";
|
|
425
|
+
if (pen.type === "group") return "GROUP";
|
|
426
|
+
if (pen.type === "text" || pen.type === "icon_font") return "TEXT";
|
|
427
|
+
if (pen.type === "path") return "VECTOR";
|
|
428
|
+
return "FRAME";
|
|
429
|
+
}
|
|
430
|
+
function resolveSizing(pen, ctx) {
|
|
431
|
+
const isTextLike = pen.type === "text" || pen.type === "icon_font";
|
|
432
|
+
const defaultSize = isTextLike ? 20 : 100;
|
|
433
|
+
const defaultW = isTextLike && pen.width === void 0 ? 0 : defaultSize;
|
|
434
|
+
const w = parseSize(pen.width, defaultW, ctx);
|
|
435
|
+
const h = parseSize(pen.height, defaultSize, ctx);
|
|
436
|
+
const layout = mapLayoutMode(pen);
|
|
437
|
+
if (pen.width === void 0 && layout !== "NONE") w.sizing = "HUG";
|
|
438
|
+
if (pen.height === void 0 && layout !== "NONE") h.sizing = "HUG";
|
|
439
|
+
return {
|
|
440
|
+
w,
|
|
441
|
+
h,
|
|
442
|
+
layout,
|
|
443
|
+
isTextLike
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
function applyAutoLayout(node, layoutMode, pen, widthSizing, heightSizing, ctx) {
|
|
447
|
+
node.layoutMode = layoutMode;
|
|
448
|
+
node.primaryAxisAlign = mapJustifyContent(pen.justifyContent);
|
|
449
|
+
node.counterAxisAlign = mapAlignItems(pen.alignItems);
|
|
450
|
+
node.itemSpacing = resolveNumber(pen.gap, ctx);
|
|
451
|
+
bindIfVar(node, "itemSpacing", pen.gap, ctx);
|
|
452
|
+
node.strokesIncludedInLayout = pen.layoutIncludeStroke ?? false;
|
|
453
|
+
const own = (sizing) => sizing === "HUG" ? "HUG" : "FIXED";
|
|
454
|
+
if (layoutMode === "VERTICAL") {
|
|
455
|
+
node.primaryAxisSizing = own(heightSizing);
|
|
456
|
+
node.counterAxisSizing = own(widthSizing);
|
|
457
|
+
} else {
|
|
458
|
+
node.primaryAxisSizing = own(widthSizing);
|
|
459
|
+
node.counterAxisSizing = own(heightSizing);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
const PLACEMENT_FIELDS = [
|
|
463
|
+
"x",
|
|
464
|
+
"y",
|
|
465
|
+
"rotation",
|
|
466
|
+
"flipX",
|
|
467
|
+
"flipY"
|
|
468
|
+
];
|
|
469
|
+
/** What `applyStroke` writes: a stroke's weight and alignment are its paints'. */
|
|
470
|
+
const STROKE_WRITES = [
|
|
471
|
+
"strokes",
|
|
472
|
+
"independentStrokeWeights",
|
|
473
|
+
"borderTopWeight",
|
|
474
|
+
"borderRightWeight",
|
|
475
|
+
"borderBottomWeight",
|
|
476
|
+
"borderLeftWeight",
|
|
477
|
+
"strokeCap",
|
|
478
|
+
"strokeJoin"
|
|
479
|
+
];
|
|
480
|
+
/**
|
|
481
|
+
* The layer fields each property `applyPenProperties` reads writes. A property that writes none of
|
|
482
|
+
* the layer's own fields maps to none: bookkeeping, the decorations pen.dev does not draw, and an
|
|
483
|
+
* icon's glyph, which is the layer's children or the component it shows.
|
|
484
|
+
*/
|
|
485
|
+
const PROPERTY_FIELDS = {
|
|
486
|
+
name: ["name"],
|
|
487
|
+
context: ["pluginData"],
|
|
488
|
+
metadata: ["pluginData"],
|
|
489
|
+
x: PLACEMENT_FIELDS,
|
|
490
|
+
y: PLACEMENT_FIELDS,
|
|
491
|
+
width: ["width"],
|
|
492
|
+
height: ["height"],
|
|
493
|
+
reusable: [],
|
|
494
|
+
theme: ["variableModes"],
|
|
495
|
+
enabled: ["visible"],
|
|
496
|
+
opacity: ["opacity"],
|
|
497
|
+
flipX: PLACEMENT_FIELDS,
|
|
498
|
+
flipY: PLACEMENT_FIELDS,
|
|
499
|
+
layoutPosition: ["layoutPositioning"],
|
|
500
|
+
rotation: PLACEMENT_FIELDS,
|
|
501
|
+
fill: ["fills"],
|
|
502
|
+
stroke: STROKE_WRITES,
|
|
503
|
+
strokeWidth: STROKE_WRITES,
|
|
504
|
+
strokeLinecap: ["strokes", "strokeCap"],
|
|
505
|
+
strokeLinejoin: ["strokes", "strokeJoin"],
|
|
506
|
+
strokeAlignment: ["strokes"],
|
|
507
|
+
effect: ["effects"],
|
|
508
|
+
cornerRadius: CORNER_FIELDS,
|
|
509
|
+
layout: ["layoutMode"],
|
|
510
|
+
gap: ["itemSpacing"],
|
|
511
|
+
layoutIncludeStroke: ["strokesIncludedInLayout"],
|
|
512
|
+
padding: [
|
|
513
|
+
"paddingTop",
|
|
514
|
+
"paddingRight",
|
|
515
|
+
"paddingBottom",
|
|
516
|
+
"paddingLeft"
|
|
517
|
+
],
|
|
518
|
+
justifyContent: ["primaryAxisAlign"],
|
|
519
|
+
alignItems: ["counterAxisAlign"],
|
|
520
|
+
clip: ["clipsContent"],
|
|
521
|
+
placeholder: ["pluginData"],
|
|
522
|
+
slot: ["pluginData"],
|
|
523
|
+
innerRadius: ["arcData"],
|
|
524
|
+
startAngle: ["arcData"],
|
|
525
|
+
sweepAngle: ["arcData"],
|
|
526
|
+
polygonCount: ["pointCount"],
|
|
527
|
+
geometry: ["vectorNetwork"],
|
|
528
|
+
fillRule: ["vectorNetwork"],
|
|
529
|
+
viewBox: ["vectorNetwork"],
|
|
530
|
+
content: ["text"],
|
|
531
|
+
textGrowth: ["textAutoResize"],
|
|
532
|
+
fontFamily: ["fontFamily"],
|
|
533
|
+
fontSize: ["fontSize"],
|
|
534
|
+
fontWeight: ["fontWeight"],
|
|
535
|
+
fontStyle: ["italic"],
|
|
536
|
+
letterSpacing: ["letterSpacing"],
|
|
537
|
+
lineHeight: ["lineHeight"],
|
|
538
|
+
textAlign: ["textAlignHorizontal"],
|
|
539
|
+
textAlignVertical: ["textAlignVertical"],
|
|
540
|
+
underline: [],
|
|
541
|
+
strikethrough: [],
|
|
542
|
+
href: ["styleRuns"],
|
|
543
|
+
library: [],
|
|
544
|
+
icon: [],
|
|
545
|
+
weight: [],
|
|
546
|
+
iconFontName: [],
|
|
547
|
+
iconFontFamily: [],
|
|
548
|
+
ref: [],
|
|
549
|
+
model: ["pluginData"],
|
|
550
|
+
scriptUri: ["pluginData"],
|
|
551
|
+
inputs: ["pluginData"],
|
|
552
|
+
url: ["pluginData"],
|
|
553
|
+
deviceId: ["pluginData"],
|
|
554
|
+
zoom: ["pluginData"],
|
|
555
|
+
scrollX: ["pluginData"],
|
|
556
|
+
scrollY: ["pluginData"]
|
|
557
|
+
};
|
|
558
|
+
const isProperty = (key) => key in PROPERTY_FIELDS;
|
|
559
|
+
/**
|
|
560
|
+
* The fields the properties `pen` carries write, whatever their values: pen.dev keeps a property
|
|
561
|
+
* an instance sets even when it equals its component's, so a later change to the component does
|
|
562
|
+
* not reach it.
|
|
563
|
+
*/
|
|
564
|
+
function fieldsSetBy(pen) {
|
|
565
|
+
return Object.keys(pen).flatMap((key) => isProperty(key) ? PROPERTY_FIELDS[key] : []);
|
|
566
|
+
}
|
|
567
|
+
function drawIconLayer(node, pen, build) {
|
|
568
|
+
if (node.type === "INSTANCE") useIconComponent(node, pen, build);
|
|
569
|
+
else drawIcon(node, pen, build);
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Draws a filling or fitting icon again at its laid-out size, which reading it could only guess.
|
|
573
|
+
* Drawing takes the icon's colour from its fill and moves it to the glyph, so the fill is read again.
|
|
574
|
+
*/
|
|
575
|
+
function redrawIconAtLaidOutSize(node, pen, build) {
|
|
576
|
+
const { w, h } = resolveSizing(pen, build.ctx);
|
|
577
|
+
if (w.sizing === "FIXED" && h.sizing === "FIXED") return;
|
|
578
|
+
node.fills = convertPaints(pen.fill, "fills", build.ctx, node, build.images, build.shaders);
|
|
579
|
+
drawIconLayer(node, pen, build);
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Sets every field a layer takes from its pen.dev fields, so a layer copied from a component can be
|
|
583
|
+
* given its overrides by applying its merged fields again. Turned and mirrored layers are built
|
|
584
|
+
* upright and placed once laid out.
|
|
585
|
+
*/
|
|
586
|
+
function applyPenProperties(node, pen, build) {
|
|
587
|
+
if (node.type === "STICKY") {
|
|
588
|
+
applyAnnotation(node, pen, build);
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
const { graph, ctx } = build;
|
|
592
|
+
const { w, h, layout, isTextLike } = resolveSizing(pen, ctx);
|
|
593
|
+
const hasChildren = (pen.children?.length ?? 0) > 0 || node.childIds.length > 0;
|
|
594
|
+
const parentLayout = node.parentId && graph.getNode(node.parentId)?.layoutMode || "NONE";
|
|
595
|
+
const absolute = pen.layoutPosition === "absolute" && parentLayout !== "NONE";
|
|
596
|
+
const flowLayout = absolute ? "NONE" : parentLayout;
|
|
597
|
+
Object.assign(node, {
|
|
598
|
+
name: pen.name ?? (pen.type === "icon_font" ? pen.iconFontName ?? "Icon" : pen.type),
|
|
599
|
+
x: pen.x ?? 0,
|
|
600
|
+
y: pen.y ?? 0,
|
|
601
|
+
rotation: 0,
|
|
602
|
+
flipX: false,
|
|
603
|
+
flipY: false,
|
|
604
|
+
width: w.value,
|
|
605
|
+
height: h.value,
|
|
606
|
+
minWidth: !hasChildren && w.fitContentFallback !== void 0 ? w.fitContentFallback : null,
|
|
607
|
+
minHeight: !hasChildren && h.fitContentFallback !== void 0 ? h.fitContentFallback : null,
|
|
608
|
+
visible: resolveBoolean(pen.enabled, ctx),
|
|
609
|
+
opacity: resolveNumber(pen.opacity, ctx, 1),
|
|
610
|
+
clipsContent: resolveBoolean(pen.clip, ctx, false),
|
|
611
|
+
layoutPositioning: absolute ? "ABSOLUTE" : "AUTO",
|
|
612
|
+
layoutGrow: 0,
|
|
613
|
+
layoutAlignSelf: "AUTO",
|
|
614
|
+
boundVariables: {},
|
|
615
|
+
variableModes: pen.theme && ctx.collectionId ? { [ctx.collectionId]: ctx.modeId() } : {}
|
|
616
|
+
});
|
|
617
|
+
bindIfVar(node, "visible", pen.enabled, ctx);
|
|
618
|
+
bindIfVar(node, "opacity", pen.opacity, ctx);
|
|
619
|
+
bindIfVar(node, "width", pen.width, ctx);
|
|
620
|
+
bindIfVar(node, "height", pen.height, ctx);
|
|
621
|
+
node.layoutMode = "NONE";
|
|
622
|
+
if (layout !== "NONE") applyAutoLayout(node, layout, pen, flowLayout === "NONE" && w.sizing === "FILL" ? "FIXED" : w.sizing, flowLayout === "NONE" && h.sizing === "FILL" ? "FIXED" : h.sizing, ctx);
|
|
623
|
+
const placement = penPlacement(pen, ctx);
|
|
624
|
+
if (pen.type === "group") build.groupIds.add(node.id);
|
|
625
|
+
if (pen.type === "group" || !isPlain(placement)) build.placements.set(node.id, placement);
|
|
626
|
+
else build.placements.delete(node.id);
|
|
627
|
+
node.fills = convertPaints(pen.fill, "fills", ctx, node, build.images, build.shaders);
|
|
628
|
+
applyStroke(node, strokeFields(pen), ctx, build.images, build.shaders);
|
|
629
|
+
if (node.type === "LINE") node.strokes = node.strokes.map((paint) => ({
|
|
630
|
+
...paint,
|
|
631
|
+
align: "CENTER"
|
|
632
|
+
}));
|
|
633
|
+
node.effects = convertEffects(pen.effect, ctx, build.shaders);
|
|
634
|
+
applyCornerRadius(node, pen.cornerRadius, ctx);
|
|
635
|
+
applyPadding(node, pen.padding, ctx);
|
|
636
|
+
if (isTextLike) applyTextProps(node, pen, ctx);
|
|
637
|
+
if (pen.type === "icon") drawIconLayer(node, pen, build);
|
|
638
|
+
if (pen.type === "ellipse") node.arcData = ellipseArc(pen, ctx);
|
|
639
|
+
if (pen.type === "polygon") node.pointCount = Math.max(3, resolveNumber(pen.polygonCount, ctx, 3));
|
|
640
|
+
if (flowLayout !== "NONE") {
|
|
641
|
+
if (w.sizing === "FILL") Object.assign(node, fillSizingFields(flowLayout, "HORIZONTAL"));
|
|
642
|
+
if (h.sizing === "FILL") Object.assign(node, fillSizingFields(flowLayout, "VERTICAL"));
|
|
643
|
+
}
|
|
644
|
+
if (isPlaceholder(pen)) applyPlaceholderLook(node, pen);
|
|
645
|
+
applyPenPluginData(node, pen);
|
|
646
|
+
build.effective.set(node.id, pen);
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* The fields an instance draws with: its component's, with the `ref` node's own replacing them one
|
|
650
|
+
* by one, as pen.dev reads them. A theme on both merges axis by axis. A `ref` whose component is
|
|
651
|
+
* missing, such as one from a library the host could not read, is a placeholder naming it.
|
|
652
|
+
*/
|
|
653
|
+
function instanceFields(ref, component) {
|
|
654
|
+
const { ref: _ref, type: _type, descendants: _descendants, children: _children, ...own } = ref;
|
|
655
|
+
if (!component) return {
|
|
656
|
+
...own,
|
|
657
|
+
type: "frame",
|
|
658
|
+
[UNRESOLVED_REF]: ref.ref ?? ""
|
|
659
|
+
};
|
|
660
|
+
const { id: _id, reusable: _reusable, ref: _componentRef, children: _componentChildren, descendants: _componentDescendants, ...inherited } = component;
|
|
661
|
+
const theme = component.theme || ref.theme ? {
|
|
662
|
+
...component.theme,
|
|
663
|
+
...ref.theme
|
|
664
|
+
} : void 0;
|
|
665
|
+
return {
|
|
666
|
+
...inherited,
|
|
667
|
+
...own,
|
|
668
|
+
theme,
|
|
669
|
+
name: ref.name ?? component.name
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Builds the layers inside a layer that is no instance: a `ref`'s copies of its component's, named
|
|
674
|
+
* by the path to them, or the layer's own, then a placeholder's label and a slot.
|
|
675
|
+
*/
|
|
676
|
+
function createChildren(node, pen, fields, build) {
|
|
677
|
+
const component = pen.type === "ref" && pen.ref ? build.components.get(pen.ref) : void 0;
|
|
678
|
+
const children = pen.type === "ref" ? component?.children ?? [] : pen.children ?? [];
|
|
679
|
+
for (const child of children) createSceneNode(pen.type === "ref" ? {
|
|
680
|
+
...child,
|
|
681
|
+
id: `${pen.id}/${child.id}`
|
|
682
|
+
} : child, node.id, build);
|
|
683
|
+
const label = placeholderLabel(fields, node.id);
|
|
684
|
+
if (label) createSceneNode(label, node.id, build);
|
|
685
|
+
createPenSlot(node, fields, build);
|
|
686
|
+
}
|
|
687
|
+
/** Builds a layer and its children in the layer's theme, merged over its parent's. */
|
|
688
|
+
function createSceneNode(pen, parentId, build) {
|
|
689
|
+
const component = pen.type === "ref" && pen.ref ? build.components.get(pen.ref) : void 0;
|
|
690
|
+
const instanceOf = pen.type === "ref" && component?.type === "frame" ? component : void 0;
|
|
691
|
+
const fields = pen.type === "ref" ? instanceFields(pen, component) : pen;
|
|
692
|
+
const iconInstance = fields.type === "icon" && insideComponent(build.graph, parentId);
|
|
693
|
+
const leaveTheme = fields.theme ? build.ctx.enterTheme(fields.theme) : void 0;
|
|
694
|
+
try {
|
|
695
|
+
const type = instanceOf || iconInstance ? "INSTANCE" : sceneType(fields, build.ctx);
|
|
696
|
+
const node = type === "STICKY" ? createAnnotation({
|
|
697
|
+
...fields,
|
|
698
|
+
id: pen.id
|
|
699
|
+
}, parentId, build) : build.graph.createNode(type, parentId, { id: pen.id });
|
|
700
|
+
applyPenProperties(node, fields, build);
|
|
701
|
+
if (instanceOf) {
|
|
702
|
+
node.componentId = instanceOf.id;
|
|
703
|
+
build.instances.set(node.id, pen);
|
|
704
|
+
} else createChildren(node, pen, fields, build);
|
|
705
|
+
return node.id;
|
|
706
|
+
} finally {
|
|
707
|
+
leaveTheme?.();
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
//#endregion
|
|
711
|
+
//#region src/instances.ts
|
|
712
|
+
/** The layers a copy was made from, nearest first, through copies of copies. */
|
|
713
|
+
function sources(graph, node) {
|
|
714
|
+
const found = /* @__PURE__ */ new Set();
|
|
715
|
+
for (let id = node.componentId; id && !found.has(id); id = graph.getNode(id)?.componentId ?? null) found.add(id);
|
|
716
|
+
return found;
|
|
717
|
+
}
|
|
718
|
+
/** The copy in `root`'s layers made from the pen.dev layer `sourceId`, at any depth. */
|
|
719
|
+
function findCopy(graph, root, sourceId) {
|
|
720
|
+
const queue = graph.getChildren(root.id);
|
|
721
|
+
for (const node of queue) {
|
|
722
|
+
if (sources(graph, node).has(sourceId)) return node;
|
|
723
|
+
queue.push(...graph.getChildren(node.id));
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* The layer an override's key names: pen.dev IDs separated by `/`, each one inside the copy of the
|
|
728
|
+
* instance the one before it names.
|
|
729
|
+
*/
|
|
730
|
+
function resolvePath(graph, instance, path) {
|
|
731
|
+
let current = instance;
|
|
732
|
+
for (const id of path.split("/")) current = current ? findCopy(graph, current, id) : void 0;
|
|
733
|
+
return current;
|
|
734
|
+
}
|
|
735
|
+
/** Runs `apply` in the merged theme of a layer's ancestors, as the layer was read in. */
|
|
736
|
+
function inAncestorThemes(build, node, apply) {
|
|
737
|
+
const chain = [];
|
|
738
|
+
for (let id = node.parentId; id; id = build.graph.getNode(id)?.parentId ?? null) {
|
|
739
|
+
const theme = build.effective.get(id)?.theme;
|
|
740
|
+
if (theme) chain.unshift(theme);
|
|
741
|
+
}
|
|
742
|
+
const leave = chain.map((theme) => build.ctx.enterTheme(theme));
|
|
743
|
+
try {
|
|
744
|
+
return apply();
|
|
745
|
+
} finally {
|
|
746
|
+
for (const exit of leave.toReversed()) exit();
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
function replaceLayer(build, target, replacement, populate) {
|
|
750
|
+
const { graph } = build;
|
|
751
|
+
const parentId = target.parentId;
|
|
752
|
+
if (!parentId) return;
|
|
753
|
+
if (swapLayer(build, target, replacement, populate)) return;
|
|
754
|
+
const index = graph.getNode(parentId)?.childIds.indexOf(target.id) ?? -1;
|
|
755
|
+
const pen = {
|
|
756
|
+
...replacement,
|
|
757
|
+
type: replacement.type ?? "frame",
|
|
758
|
+
id: replacement.id ?? generateId()
|
|
759
|
+
};
|
|
760
|
+
inAncestorThemes(build, target, () => {
|
|
761
|
+
graph.deleteNode(target.id);
|
|
762
|
+
const id = createSceneNode(pen, parentId, build);
|
|
763
|
+
if (id && index >= 0) graph.insertChildAt(id, parentId, index);
|
|
764
|
+
if (id) build.replaced.add(parentId);
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Swaps a nested instance an override replaces with an instance of another component for that
|
|
769
|
+
* component, as Figma's instance swap does, so the instances holding it stay instances. The
|
|
770
|
+
* replacement's own fields and overrides then apply to the swapped layer. Returns whether it
|
|
771
|
+
* swapped; any other replacement changes the layers of the instance holding it.
|
|
772
|
+
*/
|
|
773
|
+
function swapLayer(build, target, replacement, populate) {
|
|
774
|
+
const { graph, effective, instances } = build;
|
|
775
|
+
const component = typeof replacement.ref === "string" ? build.components.get(replacement.ref) : void 0;
|
|
776
|
+
if (target.type !== "INSTANCE" || replacement.type !== "ref" || component?.type !== "frame") return false;
|
|
777
|
+
for (const nested of instances.keys()) if (graph.isDescendant(nested, component.id)) populate(nested);
|
|
778
|
+
swapInstanceComponent(graph, target.id, component.id);
|
|
779
|
+
if (graph.getNode(target.id)?.componentId !== component.id) return false;
|
|
780
|
+
const { children: _children, reusable: _reusable, descendants: _descendants, ...fields } = component;
|
|
781
|
+
effective.set(target.id, {
|
|
782
|
+
...fields,
|
|
783
|
+
id: target.id
|
|
784
|
+
});
|
|
785
|
+
inheritCopyFields(build, target);
|
|
786
|
+
const { ref: _ref, type: _type, id: _id, descendants, ...own } = replacement;
|
|
787
|
+
overrideLayer(build, target, own);
|
|
788
|
+
applyDescendants(build, target, descendants, populate);
|
|
789
|
+
return true;
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Records as the instance's overrides the fields an override set or changed on a copy, so they
|
|
793
|
+
* survive the instance's next sync and a save, as an edit made in the editor would.
|
|
794
|
+
*/
|
|
795
|
+
function recordChangedFields(graph, target, before, override) {
|
|
796
|
+
const changed = INSTANCE_OVERRIDE_FIELDS.filter((field) => !isEqual(before[field], target[field]));
|
|
797
|
+
recordInstanceOverride(graph, target.id, [...changed, ...fieldsSetBy(override)]);
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Records as the instance's own overrides the fields its `ref` sets or makes differ from its
|
|
801
|
+
* component's. A size counts only when the `ref` sets it: otherwise it is the layout's, which
|
|
802
|
+
* follows the component's.
|
|
803
|
+
*/
|
|
804
|
+
function recordOwnFields(graph, instance, ref) {
|
|
805
|
+
const component = instance.componentId ? graph.getNode(instance.componentId) : void 0;
|
|
806
|
+
if (!component) return;
|
|
807
|
+
const changed = INSTANCE_OVERRIDE_FIELDS.filter((field) => (field !== "width" || "width" in ref) && (field !== "height" || "height" in ref) && !isEqual(instance[field], component[field]));
|
|
808
|
+
recordInstanceOverride(graph, instance.id, [...changed, ...fieldsSetBy(ref)]);
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Gives a copy an override's fields. Children the override gives a slot of `instance` become the
|
|
812
|
+
* instance's content for that slot; any other layer's children are replaced, which detaches the
|
|
813
|
+
* instances holding it.
|
|
814
|
+
*/
|
|
815
|
+
function overrideLayer(build, target, override, instance) {
|
|
816
|
+
const { graph, ctx, effective } = build;
|
|
817
|
+
const base = effective.get(target.id) ?? {
|
|
818
|
+
type: "frame",
|
|
819
|
+
id: target.id
|
|
820
|
+
};
|
|
821
|
+
const { descendants: _descendants, children, ...fields } = override;
|
|
822
|
+
const merged = {
|
|
823
|
+
...base,
|
|
824
|
+
...fields,
|
|
825
|
+
type: base.type,
|
|
826
|
+
id: base.id
|
|
827
|
+
};
|
|
828
|
+
const before = structuredClone(pick(target, INSTANCE_OVERRIDE_FIELDS));
|
|
829
|
+
inAncestorThemes(build, target, () => {
|
|
830
|
+
const leave = merged.theme ? ctx.enterTheme(merged.theme) : void 0;
|
|
831
|
+
try {
|
|
832
|
+
applyPenProperties(target, merged, build);
|
|
833
|
+
recordChangedFields(graph, target, before, fields);
|
|
834
|
+
if (children) {
|
|
835
|
+
const fillsSlot = instance !== void 0 && claimSlot(build, instance, target);
|
|
836
|
+
const replaced = target.childIds;
|
|
837
|
+
for (const childId of replaced) graph.deleteNode(childId);
|
|
838
|
+
for (const child of children) createSceneNode(child, target.id, build);
|
|
839
|
+
if (!fillsSlot) build.replaced.add(target.id);
|
|
840
|
+
}
|
|
841
|
+
} finally {
|
|
842
|
+
leave?.();
|
|
843
|
+
}
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Detaches the instances holding a layer whose children an override replaced. An instance keeps
|
|
848
|
+
* its component's layers, overriding their fields but never replacing them, so such an instance
|
|
849
|
+
* becomes a frame that keeps what it shows, as detaching it in Figma does.
|
|
850
|
+
*/
|
|
851
|
+
function detachReplacingInstances(build) {
|
|
852
|
+
const { graph } = build;
|
|
853
|
+
for (const id of build.replaced) for (let node = graph.getNode(id); node;) {
|
|
854
|
+
if (node.type === "INSTANCE") detachInstance(graph, node.id);
|
|
855
|
+
node = node.parentId ? graph.getNode(node.parentId) : void 0;
|
|
856
|
+
}
|
|
857
|
+
build.replaced.clear();
|
|
858
|
+
}
|
|
859
|
+
/** Gives an instance's copies their overrides; a key with a `type` replaces the layer. */
|
|
860
|
+
function applyDescendants(build, instance, descendants, populate) {
|
|
861
|
+
for (const [path, override] of Object.entries(descendants ?? {})) {
|
|
862
|
+
const target = resolvePath(build.graph, instance, path);
|
|
863
|
+
if (!target) continue;
|
|
864
|
+
if (override.type) replaceLayer(build, target, override, populate);
|
|
865
|
+
else overrideLayer(build, target, override, instance);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
/** Gives each copy inside `root` the pen.dev fields and placement of the layer it copies. */
|
|
869
|
+
function inheritCopyFields(build, root) {
|
|
870
|
+
const { graph, effective, placements } = build;
|
|
871
|
+
const copies = graph.getChildren(root.id);
|
|
872
|
+
for (const copy of copies) {
|
|
873
|
+
const source = copy.componentId;
|
|
874
|
+
const fields = source ? effective.get(source) : void 0;
|
|
875
|
+
if (fields) effective.set(copy.id, fields);
|
|
876
|
+
const placement = source ? placements.get(source) : void 0;
|
|
877
|
+
if (placement) placements.set(copy.id, placement);
|
|
878
|
+
if (source && build.groupIds.has(source)) build.groupIds.add(copy.id);
|
|
879
|
+
copies.push(...graph.getChildren(copy.id));
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Fills each instance with copies of its component's layers, then applies its overrides. An
|
|
884
|
+
* instance inside a component is filled first, so the copies made of it carry its layers and
|
|
885
|
+
* overrides; a copy keeps its source's pen.dev fields and placement.
|
|
886
|
+
*/
|
|
887
|
+
function populateInstances(build) {
|
|
888
|
+
const { graph, instances } = build;
|
|
889
|
+
const done = /* @__PURE__ */ new Set();
|
|
890
|
+
function populate(id) {
|
|
891
|
+
if (done.has(id)) return;
|
|
892
|
+
done.add(id);
|
|
893
|
+
const instance = graph.getNode(id);
|
|
894
|
+
const ref = instances.get(id);
|
|
895
|
+
if (!instance?.componentId || !ref) return;
|
|
896
|
+
const component = graph.getNode(instance.componentId);
|
|
897
|
+
if (!component) return;
|
|
898
|
+
for (const nested of instances.keys()) if (graph.isDescendant(nested, component.id)) populate(nested);
|
|
899
|
+
populateInstanceChildren(graph, instance.id, component.id);
|
|
900
|
+
recordOwnFields(graph, instance, ref);
|
|
901
|
+
inheritCopyFields(build, instance);
|
|
902
|
+
applyDescendants(build, instance, ref.descendants, populate);
|
|
903
|
+
detachReplacingInstances(build);
|
|
904
|
+
}
|
|
905
|
+
for (const id of instances.keys()) populate(id);
|
|
906
|
+
}
|
|
907
|
+
//#endregion
|
|
908
|
+
//#region src/read.ts
|
|
909
|
+
function collectComponents(nodes, components) {
|
|
910
|
+
for (const node of nodes) {
|
|
911
|
+
if (node.reusable) components.set(node.id, node);
|
|
912
|
+
if (node.children) collectComponents(node.children, components);
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
/** Whether a group sits in an auto layout's flow, where fitting it changes the layout. */
|
|
916
|
+
function groupsInFlow(graph, groupIds) {
|
|
917
|
+
for (const id of groupIds) {
|
|
918
|
+
const group = graph.getNode(id);
|
|
919
|
+
const parent = group?.parentId ? graph.getNode(group.parentId) : void 0;
|
|
920
|
+
if (parent && parent.layoutMode !== "NONE") return true;
|
|
921
|
+
}
|
|
922
|
+
return false;
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Draws each path and slanted line in its box once boxes have their final size, which fill and
|
|
926
|
+
* fit sizing only give once laid out, and redraws each icon laying out sized.
|
|
927
|
+
*/
|
|
928
|
+
function drawAtFinalSize(build, laidOut) {
|
|
929
|
+
for (const [id, pen] of build.effective) {
|
|
930
|
+
const node = build.graph.getNode(id);
|
|
931
|
+
if (!node) continue;
|
|
932
|
+
if (pen.type === "path") {
|
|
933
|
+
const network = pathNetwork(pen, node.width, node.height);
|
|
934
|
+
if (network) node.vectorNetwork = network;
|
|
935
|
+
} else if (pen.type === "line" && node.type === "VECTOR") node.vectorNetwork = lineNetwork(node.width, node.height);
|
|
936
|
+
else if (pen.type === "icon" && laidOut) inAncestorThemes(build, node, () => {
|
|
937
|
+
const leave = pen.theme ? build.ctx.enterTheme(pen.theme) : void 0;
|
|
938
|
+
try {
|
|
939
|
+
redrawIconAtLaidOutSize(node, pen, build);
|
|
940
|
+
} finally {
|
|
941
|
+
leave?.();
|
|
942
|
+
}
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
/** A `.pen` document's JSON, validated; throws for text that is not one. */
|
|
947
|
+
function parsePenDocument(json) {
|
|
948
|
+
const parsed = v.safeParse(penFileSchema, json);
|
|
949
|
+
if (!parsed.success) throw new Error(`Not a .pen document: ${v.summarize(parsed.issues)}`);
|
|
950
|
+
return parsed.output;
|
|
951
|
+
}
|
|
952
|
+
/** Builds the scene graph of a document `parsePenDocument` read. */
|
|
953
|
+
function buildPenGraph(doc, options = {}) {
|
|
954
|
+
const graph = new SceneGraph();
|
|
955
|
+
for (const page of graph.getPages(true)) graph.deleteNode(page.id);
|
|
956
|
+
const imports = options.imports ?? /* @__PURE__ */ new Map();
|
|
957
|
+
const build = {
|
|
958
|
+
graph,
|
|
959
|
+
ctx: buildVarContext(graph, withImports(doc, imports)),
|
|
960
|
+
images: createImageStore(graph, options.images),
|
|
961
|
+
shaders: options.shaders,
|
|
962
|
+
icons: options.icons,
|
|
963
|
+
components: /* @__PURE__ */ new Map(),
|
|
964
|
+
effective: /* @__PURE__ */ new Map(),
|
|
965
|
+
instances: /* @__PURE__ */ new Map(),
|
|
966
|
+
placements: /* @__PURE__ */ new Map(),
|
|
967
|
+
groupIds: /* @__PURE__ */ new Set(),
|
|
968
|
+
iconComponents: /* @__PURE__ */ new Map(),
|
|
969
|
+
iconPageId: null,
|
|
970
|
+
replaced: /* @__PURE__ */ new Set()
|
|
971
|
+
};
|
|
972
|
+
collectComponents(doc.children, build.components);
|
|
973
|
+
for (const imported of imports.values()) collectComponents(imported.doc.children, build.components);
|
|
974
|
+
const page = graph.addPage(doc.children[0]?.name ?? "Page 1");
|
|
975
|
+
for (const child of doc.children) createSceneNode(child, page.id, build);
|
|
976
|
+
const libraryRoots = createLibraryRoots(doc, imports, build, createSceneNode);
|
|
977
|
+
populateInstances(build);
|
|
978
|
+
options.layout?.(graph);
|
|
979
|
+
drawAtFinalSize(build, options.layout !== void 0);
|
|
980
|
+
placeLayers(graph, build.placements, [...build.groupIds]);
|
|
981
|
+
if (options.layout && groupsInFlow(graph, build.groupIds)) {
|
|
982
|
+
options.layout(graph);
|
|
983
|
+
drawAtFinalSize(build, true);
|
|
984
|
+
}
|
|
985
|
+
removeUnusedIconComponents(build);
|
|
986
|
+
markLibraryRoots(graph, libraryRoots);
|
|
987
|
+
if (graph.getPages(true).length === 0) graph.addPage("Page 1");
|
|
988
|
+
return graph;
|
|
989
|
+
}
|
|
990
|
+
function parsePenFile(json, options = {}) {
|
|
991
|
+
return buildPenGraph(parsePenDocument(json), options);
|
|
992
|
+
}
|
|
993
|
+
async function readPenFile(file, options) {
|
|
994
|
+
return parsePenFile(await file.text(), options);
|
|
995
|
+
}
|
|
996
|
+
//#endregion
|
|
997
|
+
//#region src/write.ts
|
|
998
|
+
const PEN_VERSION = "2.21";
|
|
999
|
+
const PEN_PLUGIN_FIELDS = {
|
|
1000
|
+
"pen/type": "type",
|
|
1001
|
+
"pen/ref": "ref",
|
|
1002
|
+
"pen/generated": "generated",
|
|
1003
|
+
"pen/context": "context",
|
|
1004
|
+
"pen/placeholder": "placeholder",
|
|
1005
|
+
"pen/slot": "slot",
|
|
1006
|
+
"pen/model": "model",
|
|
1007
|
+
"pen/scriptUri": "scriptUri",
|
|
1008
|
+
"pen/inputs": "inputs",
|
|
1009
|
+
"pen/url": "url",
|
|
1010
|
+
"pen/deviceId": "deviceId",
|
|
1011
|
+
"pen/zoom": "zoom",
|
|
1012
|
+
"pen/scrollX": "scrollX",
|
|
1013
|
+
"pen/scrollY": "scrollY"
|
|
1014
|
+
};
|
|
1015
|
+
/** Snaps matrix values that are within floating-point noise of an integer. */
|
|
1016
|
+
function snapCoordinate(value) {
|
|
1017
|
+
return Math.abs(value - Math.round(value)) < 1e-9 ? Math.round(value) : value;
|
|
1018
|
+
}
|
|
1019
|
+
function rounded(value) {
|
|
1020
|
+
return Number(value.toFixed(3));
|
|
1021
|
+
}
|
|
1022
|
+
function colorValue(value) {
|
|
1023
|
+
return value.a === 1 ? colorToHex(value) : colorToHex8(value);
|
|
1024
|
+
}
|
|
1025
|
+
function variableReference(state, id) {
|
|
1026
|
+
const variable = id === void 0 ? void 0 : state.variables.get(id);
|
|
1027
|
+
return variable === void 0 ? void 0 : `$${variable.name}`;
|
|
1028
|
+
}
|
|
1029
|
+
function variableOr(state, node, field, value) {
|
|
1030
|
+
return variableReference(state, node.boundVariables[field]) ?? value;
|
|
1031
|
+
}
|
|
1032
|
+
/** Matches the pen corner convention of placing x/y after undoing the node's rotation or flip. */
|
|
1033
|
+
function penCoordinates(node) {
|
|
1034
|
+
if (node.rotation === 0 && !node.flipX && !node.flipY) return {
|
|
1035
|
+
x: node.x,
|
|
1036
|
+
y: node.y
|
|
1037
|
+
};
|
|
1038
|
+
const matrix = getNodeLocalMatrix({
|
|
1039
|
+
...node,
|
|
1040
|
+
x: 0,
|
|
1041
|
+
y: 0
|
|
1042
|
+
});
|
|
1043
|
+
return {
|
|
1044
|
+
x: snapCoordinate(node.x + matrix[2]),
|
|
1045
|
+
y: snapCoordinate(node.y + matrix[5])
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
/** pen.dev's names for the scene graph's blend modes, inverse of the reader's `BLEND_MODES`. */
|
|
1049
|
+
const BLEND_MODE_NAMES = {
|
|
1050
|
+
NORMAL: "normal",
|
|
1051
|
+
DARKEN: "darken",
|
|
1052
|
+
MULTIPLY: "multiply",
|
|
1053
|
+
COLOR_BURN: "colorBurn",
|
|
1054
|
+
LIGHTEN: "light",
|
|
1055
|
+
SCREEN: "screen",
|
|
1056
|
+
COLOR_DODGE: "colorDodge",
|
|
1057
|
+
OVERLAY: "overlay",
|
|
1058
|
+
SOFT_LIGHT: "softLight",
|
|
1059
|
+
HARD_LIGHT: "hardLight",
|
|
1060
|
+
DIFFERENCE: "difference",
|
|
1061
|
+
EXCLUSION: "exclusion",
|
|
1062
|
+
HUE: "hue",
|
|
1063
|
+
SATURATION: "saturation",
|
|
1064
|
+
COLOR: "color",
|
|
1065
|
+
LUMINOSITY: "luminosity"
|
|
1066
|
+
};
|
|
1067
|
+
function paintBase(fill) {
|
|
1068
|
+
const result = {};
|
|
1069
|
+
if (!fill.visible) result.enabled = false;
|
|
1070
|
+
if (fill.opacity !== 1) result.opacity = rounded(fill.opacity);
|
|
1071
|
+
const blendMode = (fill.blendMode && BLEND_MODE_NAMES[fill.blendMode]) ?? void 0;
|
|
1072
|
+
if (blendMode && blendMode !== "normal") result.blendMode = blendMode;
|
|
1073
|
+
return result;
|
|
1074
|
+
}
|
|
1075
|
+
function gradientName(type) {
|
|
1076
|
+
if (type === "GRADIENT_RADIAL") return "radial";
|
|
1077
|
+
if (type === "GRADIENT_ANGULAR") return "angular";
|
|
1078
|
+
if (type === "GRADIENT_DIAMOND") return "diamond";
|
|
1079
|
+
return "linear";
|
|
1080
|
+
}
|
|
1081
|
+
function gradientPoint(inverse, point) {
|
|
1082
|
+
return inverse === void 0 ? point : applyGradientTransform(inverse, point);
|
|
1083
|
+
}
|
|
1084
|
+
function gradientAxis(fill, inverse, center, first, second) {
|
|
1085
|
+
const firstLength = 2 * Math.hypot(first.x - center.x, first.y - center.y);
|
|
1086
|
+
const secondLength = 2 * Math.hypot(second.x - center.x, second.y - center.y);
|
|
1087
|
+
const rotationOf = (axis, offset) => offset - Math.atan2(axis.x, -axis.y) * 180 / Math.PI;
|
|
1088
|
+
if (fill.type === "GRADIENT_LINEAR") return {
|
|
1089
|
+
rotation: rotationOf(inverse === void 0 ? {
|
|
1090
|
+
x: 0,
|
|
1091
|
+
y: -1
|
|
1092
|
+
} : {
|
|
1093
|
+
x: applyGradientTransform(inverse, {
|
|
1094
|
+
x: 1,
|
|
1095
|
+
y: .5
|
|
1096
|
+
}).x - center.x,
|
|
1097
|
+
y: applyGradientTransform(inverse, {
|
|
1098
|
+
x: 1,
|
|
1099
|
+
y: .5
|
|
1100
|
+
}).y - center.y
|
|
1101
|
+
}, 0),
|
|
1102
|
+
width: secondLength,
|
|
1103
|
+
height: firstLength
|
|
1104
|
+
};
|
|
1105
|
+
if (fill.type === "GRADIENT_RADIAL" || fill.type === "GRADIENT_DIAMOND") return {
|
|
1106
|
+
rotation: rotationOf({
|
|
1107
|
+
x: second.x - center.x,
|
|
1108
|
+
y: second.y - center.y
|
|
1109
|
+
}, 180),
|
|
1110
|
+
width: firstLength,
|
|
1111
|
+
height: secondLength
|
|
1112
|
+
};
|
|
1113
|
+
return {
|
|
1114
|
+
rotation: rotationOf({
|
|
1115
|
+
x: first.x - center.x,
|
|
1116
|
+
y: first.y - center.y
|
|
1117
|
+
}, 0),
|
|
1118
|
+
width: secondLength,
|
|
1119
|
+
height: firstLength
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
function gradientPaint(fill) {
|
|
1123
|
+
const transform = fill.gradientTransform;
|
|
1124
|
+
const inverse = transform === void 0 ? void 0 : invertGradientTransform(transform);
|
|
1125
|
+
const center = gradientPoint(inverse, {
|
|
1126
|
+
x: .5,
|
|
1127
|
+
y: .5
|
|
1128
|
+
});
|
|
1129
|
+
const axis = gradientAxis(fill, inverse, center, gradientPoint(inverse, {
|
|
1130
|
+
x: 1,
|
|
1131
|
+
y: .5
|
|
1132
|
+
}), gradientPoint(inverse, {
|
|
1133
|
+
x: .5,
|
|
1134
|
+
y: 1
|
|
1135
|
+
}));
|
|
1136
|
+
return {
|
|
1137
|
+
type: "gradient",
|
|
1138
|
+
gradientType: gradientName(fill.type),
|
|
1139
|
+
...paintBase(fill),
|
|
1140
|
+
center: {
|
|
1141
|
+
x: rounded(center.x),
|
|
1142
|
+
y: rounded(center.y)
|
|
1143
|
+
},
|
|
1144
|
+
size: {
|
|
1145
|
+
width: rounded(axis.width),
|
|
1146
|
+
height: rounded(axis.height)
|
|
1147
|
+
},
|
|
1148
|
+
rotation: rounded(axis.rotation),
|
|
1149
|
+
colors: (fill.gradientStops ?? []).map((stop) => ({
|
|
1150
|
+
color: colorValue(stop.color),
|
|
1151
|
+
position: rounded(stop.position)
|
|
1152
|
+
}))
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
function imagePaint(fill) {
|
|
1156
|
+
return {
|
|
1157
|
+
type: "image",
|
|
1158
|
+
...paintBase(fill),
|
|
1159
|
+
url: fill.imageHash
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
function penPaint(state, node, field, fill, index) {
|
|
1163
|
+
if (fill.type === "SOLID") return {
|
|
1164
|
+
type: "color",
|
|
1165
|
+
color: variableReference(state, node.boundVariables[`${field}/${index}/color`]) ?? colorValue(fill.color),
|
|
1166
|
+
...paintBase(fill)
|
|
1167
|
+
};
|
|
1168
|
+
if (fill.type.startsWith("GRADIENT_")) return gradientPaint(fill);
|
|
1169
|
+
if (fill.type === "IMAGE") return imagePaint(fill);
|
|
1170
|
+
return {
|
|
1171
|
+
type: fill.type.toLowerCase(),
|
|
1172
|
+
...paintBase(fill)
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
function paintsOf(state, node, field, paints) {
|
|
1176
|
+
if (paints.length === 0) return void 0;
|
|
1177
|
+
const result = paints.map((paint, index) => penPaint(state, node, field, paint, index));
|
|
1178
|
+
return result.length === 1 ? result[0] : result;
|
|
1179
|
+
}
|
|
1180
|
+
function strokesOf(state, node) {
|
|
1181
|
+
if (node.strokes.length === 0) return {};
|
|
1182
|
+
const paints = paintsOf(state, node, "strokes", node.strokes);
|
|
1183
|
+
if (paints === void 0) return {};
|
|
1184
|
+
const first = node.strokes[0];
|
|
1185
|
+
const strokeWidth = node.independentStrokeWeights ? {
|
|
1186
|
+
top: variableOr(state, node, "borderTopWeight", rounded(node.borderTopWeight)),
|
|
1187
|
+
right: variableOr(state, node, "borderRightWeight", rounded(node.borderRightWeight)),
|
|
1188
|
+
bottom: variableOr(state, node, "borderBottomWeight", rounded(node.borderBottomWeight)),
|
|
1189
|
+
left: variableOr(state, node, "borderLeftWeight", rounded(node.borderLeftWeight))
|
|
1190
|
+
} : variableOr(state, node, "strokeWeight", rounded(first.weight));
|
|
1191
|
+
const caps = {
|
|
1192
|
+
NONE: "butt",
|
|
1193
|
+
ROUND: "round",
|
|
1194
|
+
SQUARE: "square",
|
|
1195
|
+
ARROW_LINES: "butt",
|
|
1196
|
+
ARROW_EQUILATERAL: "butt",
|
|
1197
|
+
TRIANGLE_FILLED: "butt",
|
|
1198
|
+
DIAMOND_FILLED: "butt",
|
|
1199
|
+
CIRCLE_FILLED: "butt"
|
|
1200
|
+
};
|
|
1201
|
+
const joins = {
|
|
1202
|
+
MITER: "miter",
|
|
1203
|
+
BEVEL: "bevel",
|
|
1204
|
+
ROUND: "round"
|
|
1205
|
+
};
|
|
1206
|
+
const linecap = first.cap === void 0 ? void 0 : caps[first.cap];
|
|
1207
|
+
const linejoin = first.join === void 0 ? void 0 : joins[first.join];
|
|
1208
|
+
return {
|
|
1209
|
+
stroke: paints,
|
|
1210
|
+
strokeWidth,
|
|
1211
|
+
strokeAlignment: first.align.toLowerCase(),
|
|
1212
|
+
strokeLinecap: linecap === "butt" ? void 0 : linecap,
|
|
1213
|
+
strokeLinejoin: linejoin === "miter" ? void 0 : linejoin
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
function effectOf(effect) {
|
|
1217
|
+
if (effect.type === "LAYER_BLUR" || effect.type === "BACKGROUND_BLUR") return {
|
|
1218
|
+
type: effect.type === "LAYER_BLUR" ? "blur" : "background_blur",
|
|
1219
|
+
radius: rounded(effect.radius),
|
|
1220
|
+
enabled: effect.visible
|
|
1221
|
+
};
|
|
1222
|
+
return {
|
|
1223
|
+
type: "shadow",
|
|
1224
|
+
shadowType: effect.type === "INNER_SHADOW" ? "inner" : void 0,
|
|
1225
|
+
color: colorValue(effect.color),
|
|
1226
|
+
offset: {
|
|
1227
|
+
x: rounded(effect.offset.x),
|
|
1228
|
+
y: rounded(effect.offset.y)
|
|
1229
|
+
},
|
|
1230
|
+
blur: rounded(effect.radius),
|
|
1231
|
+
spread: rounded(effect.spread),
|
|
1232
|
+
enabled: effect.visible
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
function variableType(type) {
|
|
1236
|
+
if (type === "COLOR") return "color";
|
|
1237
|
+
if (type === "FLOAT") return "number";
|
|
1238
|
+
if (type === "BOOLEAN") return "boolean";
|
|
1239
|
+
return "string";
|
|
1240
|
+
}
|
|
1241
|
+
function layoutFields(state, node) {
|
|
1242
|
+
if (node.layoutMode === "NONE") return node.type === "FRAME" || node.type === "COMPONENT" ? { layout: "none" } : {};
|
|
1243
|
+
const justify = {
|
|
1244
|
+
CENTER: "center",
|
|
1245
|
+
MAX: "end",
|
|
1246
|
+
SPACE_BETWEEN: "space_between",
|
|
1247
|
+
SPACE_AROUND: "space_around"
|
|
1248
|
+
};
|
|
1249
|
+
const align = {
|
|
1250
|
+
CENTER: "center",
|
|
1251
|
+
MAX: "end",
|
|
1252
|
+
STRETCH: "stretch",
|
|
1253
|
+
BASELINE: "baseline"
|
|
1254
|
+
};
|
|
1255
|
+
const fields = { layout: node.layoutMode === "HORIZONTAL" ? "horizontal" : "vertical" };
|
|
1256
|
+
const gapBinding = variableReference(state, node.boundVariables["itemSpacing"]);
|
|
1257
|
+
if (gapBinding !== void 0) fields.gap = gapBinding;
|
|
1258
|
+
else if (node.itemSpacing !== 0) fields.gap = rounded(node.itemSpacing);
|
|
1259
|
+
if (node.primaryAxisAlign !== "MIN") fields.justifyContent = justify[node.primaryAxisAlign];
|
|
1260
|
+
if (node.counterAxisAlign !== "MIN") fields.alignItems = align[node.counterAxisAlign];
|
|
1261
|
+
const padding = [
|
|
1262
|
+
node.paddingTop,
|
|
1263
|
+
node.paddingRight,
|
|
1264
|
+
node.paddingBottom,
|
|
1265
|
+
node.paddingLeft
|
|
1266
|
+
];
|
|
1267
|
+
if (padding.some((value) => value !== 0)) fields.padding = padding;
|
|
1268
|
+
if (node.clipsContent) fields.clip = true;
|
|
1269
|
+
if (node.strokesIncludedInLayout) fields.layoutIncludeStroke = true;
|
|
1270
|
+
return fields;
|
|
1271
|
+
}
|
|
1272
|
+
function sizing(state, node, axis) {
|
|
1273
|
+
const mode = layoutSizing(state.graph, node, axis);
|
|
1274
|
+
if (mode === "FILL") return "fill_container";
|
|
1275
|
+
if (mode === "HUG") return "fit_content";
|
|
1276
|
+
}
|
|
1277
|
+
function penPluginFields(node, result) {
|
|
1278
|
+
for (const entry of node.pluginData) {
|
|
1279
|
+
if (entry.pluginId !== "pen") continue;
|
|
1280
|
+
const field = PEN_PLUGIN_FIELDS[entry.key];
|
|
1281
|
+
if (field === void 0) continue;
|
|
1282
|
+
let value;
|
|
1283
|
+
try {
|
|
1284
|
+
value = JSON.parse(entry.value);
|
|
1285
|
+
} catch {
|
|
1286
|
+
console.warn(`Skipping corrupt pen plugin field ${field}`);
|
|
1287
|
+
continue;
|
|
1288
|
+
}
|
|
1289
|
+
result[field] = value;
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
function nodeType(node) {
|
|
1293
|
+
switch (node.type) {
|
|
1294
|
+
case "COMPONENT":
|
|
1295
|
+
case "COMPONENT_SET":
|
|
1296
|
+
case "FRAME":
|
|
1297
|
+
case "SECTION": return "frame";
|
|
1298
|
+
case "RECTANGLE":
|
|
1299
|
+
case "ROUNDED_RECTANGLE": return "rectangle";
|
|
1300
|
+
case "ELLIPSE": return "ellipse";
|
|
1301
|
+
case "POLYGON":
|
|
1302
|
+
case "STAR": return "polygon";
|
|
1303
|
+
case "GROUP":
|
|
1304
|
+
case "BOOLEAN_OPERATION": return "group";
|
|
1305
|
+
case "TEXT": return "text";
|
|
1306
|
+
case "VECTOR": return "path";
|
|
1307
|
+
case "LINE": return "line";
|
|
1308
|
+
case "STICKY": return "note";
|
|
1309
|
+
default: return "frame";
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
/** A line height as the multiple of the font size pen.dev stores; undefined when it has none. */
|
|
1313
|
+
function lineHeightMultiple(node) {
|
|
1314
|
+
const lineHeight = node.lineHeight;
|
|
1315
|
+
if (!lineHeight) return void 0;
|
|
1316
|
+
if (lineHeight.unit !== "PIXELS") return rounded(lineHeight.value / 100);
|
|
1317
|
+
return node.fontSize > 0 ? rounded(lineHeight.value / node.fontSize) : void 0;
|
|
1318
|
+
}
|
|
1319
|
+
/** Letter spacing in the pixels pen.dev stores, a percent following the font size. */
|
|
1320
|
+
function letterSpacingPixels(node) {
|
|
1321
|
+
const spacing = node.letterSpacing;
|
|
1322
|
+
return spacing.unit === "PIXELS" ? spacing.value : spacing.value / 100 * node.fontSize;
|
|
1323
|
+
}
|
|
1324
|
+
function textFields(state, node) {
|
|
1325
|
+
if (node.type !== "TEXT") return {};
|
|
1326
|
+
const fields = { content: node.text };
|
|
1327
|
+
if (node.fontFamily !== "Inter") fields.fontFamily = variableOr(state, node, "fontFamily", node.fontFamily);
|
|
1328
|
+
if (node.fontSize !== 14) fields.fontSize = variableOr(state, node, "fontSize", rounded(node.fontSize));
|
|
1329
|
+
const fontWeight = variableOr(state, node, "fontWeight", node.fontWeight);
|
|
1330
|
+
if (typeof fontWeight === "string" || node.fontWeight !== 400) fields.fontWeight = fontWeight;
|
|
1331
|
+
if (node.italic) fields.fontStyle = "italic";
|
|
1332
|
+
const textAlign = {
|
|
1333
|
+
CENTER: "center",
|
|
1334
|
+
RIGHT: "right",
|
|
1335
|
+
JUSTIFIED: "justify"
|
|
1336
|
+
};
|
|
1337
|
+
const textAlignVertical = {
|
|
1338
|
+
CENTER: "middle",
|
|
1339
|
+
BOTTOM: "bottom"
|
|
1340
|
+
};
|
|
1341
|
+
if (node.textAlignHorizontal !== "LEFT") fields.textAlign = textAlign[node.textAlignHorizontal];
|
|
1342
|
+
if (node.textAlignVertical !== "TOP") fields.textAlignVertical = textAlignVertical[node.textAlignVertical];
|
|
1343
|
+
const lineHeight = lineHeightMultiple(node);
|
|
1344
|
+
if (lineHeight !== void 0) fields.lineHeight = lineHeight;
|
|
1345
|
+
if (node.letterSpacing.value !== 0) fields.letterSpacing = rounded(letterSpacingPixels(node));
|
|
1346
|
+
if (node.textAutoResize === "HEIGHT") fields.textGrowth = "fixed-width";
|
|
1347
|
+
if (node.textAutoResize === "NONE" || node.textAutoResize === "TRUNCATE") fields.textGrowth = "fixed-width-height";
|
|
1348
|
+
const link = node.styleRuns.find((run) => run.style.hyperlink?.type === "URL");
|
|
1349
|
+
if (link?.style.hyperlink?.type === "URL") fields.href = link.style.hyperlink.value;
|
|
1350
|
+
return fields;
|
|
1351
|
+
}
|
|
1352
|
+
function cornerFields(node) {
|
|
1353
|
+
if (node.independentCorners) return { cornerRadius: [
|
|
1354
|
+
node.topLeftRadius,
|
|
1355
|
+
node.topRightRadius,
|
|
1356
|
+
node.bottomRightRadius,
|
|
1357
|
+
node.bottomLeftRadius
|
|
1358
|
+
] };
|
|
1359
|
+
if (node.cornerRadius !== 0) return { cornerRadius: rounded(node.cornerRadius) };
|
|
1360
|
+
return {};
|
|
1361
|
+
}
|
|
1362
|
+
function variableScalar(value, state) {
|
|
1363
|
+
if (value === void 0) return "";
|
|
1364
|
+
if (typeof value === "object" && "aliasId" in value) {
|
|
1365
|
+
const variable = state.variables.get(value.aliasId);
|
|
1366
|
+
return variable === void 0 ? "" : `$${variable.name}`;
|
|
1367
|
+
}
|
|
1368
|
+
if (typeof value === "object") return "r" in value ? colorValue(value) : "";
|
|
1369
|
+
return value;
|
|
1370
|
+
}
|
|
1371
|
+
function penVariable(variable, collection, state) {
|
|
1372
|
+
const modes = collection?.modes ?? [];
|
|
1373
|
+
if (modes.length <= 1) return {
|
|
1374
|
+
type: variableType(variable.type),
|
|
1375
|
+
value: variableScalar(variable.valuesByMode[modes[0]?.modeId ?? ""], state)
|
|
1376
|
+
};
|
|
1377
|
+
return {
|
|
1378
|
+
type: variableType(variable.type),
|
|
1379
|
+
value: modes.map((mode, index) => ({
|
|
1380
|
+
value: variableScalar(variable.valuesByMode[mode.modeId], state),
|
|
1381
|
+
...index === 0 ? {} : { theme: { [collection?.name ?? "Mode"]: mode.name } }
|
|
1382
|
+
}))
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
function variablesOf(state) {
|
|
1386
|
+
if (state.graph.variables.size === 0) return void 0;
|
|
1387
|
+
return Object.fromEntries([...state.graph.variables.values()].sort((left, right) => left.name.localeCompare(right.name)).map((variable) => [variable.name, penVariable(variable, state.collections.get(variable.collectionId), state)]));
|
|
1388
|
+
}
|
|
1389
|
+
function themesOf(state) {
|
|
1390
|
+
if (state.graph.variableCollections.size === 0) return void 0;
|
|
1391
|
+
return Object.fromEntries([...state.graph.variableCollections.values()].sort((left, right) => left.name.localeCompare(right.name)).map((collection) => [collection.name, collection.modes.map((mode) => mode.name)]));
|
|
1392
|
+
}
|
|
1393
|
+
function basicNodeFields(state, node, result) {
|
|
1394
|
+
if (node.name) result.name = node.name;
|
|
1395
|
+
const placement = penCoordinates(node);
|
|
1396
|
+
if (placement.x !== 0) result.x = rounded(placement.x);
|
|
1397
|
+
if (placement.y !== 0) result.y = rounded(placement.y);
|
|
1398
|
+
result.width = variableOr(state, node, "width", sizing(state, node, "HORIZONTAL") ?? rounded(node.width));
|
|
1399
|
+
result.height = variableOr(state, node, "height", sizing(state, node, "VERTICAL") ?? rounded(node.height));
|
|
1400
|
+
if (!node.visible) result.enabled = false;
|
|
1401
|
+
if (node.opacity !== 1) result.opacity = rounded(node.opacity);
|
|
1402
|
+
if (node.rotation !== 0) result.rotation = rounded(node.flipX !== node.flipY ? node.rotation : -node.rotation);
|
|
1403
|
+
if (node.flipX) result.flipX = true;
|
|
1404
|
+
if (node.flipY) result.flipY = true;
|
|
1405
|
+
const fill = paintsOf(state, node, "fills", node.fills);
|
|
1406
|
+
if (fill !== void 0) result.fill = fill;
|
|
1407
|
+
Object.assign(result, strokesOf(state, node), layoutFields(state, node), cornerFields(node), textFields(state, node));
|
|
1408
|
+
}
|
|
1409
|
+
function semanticNodeFields(state, node, result) {
|
|
1410
|
+
if (node.type === "TEXT" && node.textAutoResize === "WIDTH_AND_HEIGHT" && layoutSizing(state.graph, node, "HORIZONTAL") === "HUG") result.width = "fit_content";
|
|
1411
|
+
if (node.type === "STICKY") result.content = stickySublayers(state.graph, node)?.body.text ?? "";
|
|
1412
|
+
penPluginFields(node, result);
|
|
1413
|
+
const effects = node.effects.filter((effect) => effect.type !== "SHADER");
|
|
1414
|
+
if (effects.length > 0) result.effect = effects.length === 1 ? effectOf(effects[0]) : effects.map(effectOf);
|
|
1415
|
+
if (node.type === "COMPONENT" || node.type === "COMPONENT_SET") result.reusable = true;
|
|
1416
|
+
if (node.type === "INSTANCE" && node.componentId) {
|
|
1417
|
+
result.type = "ref";
|
|
1418
|
+
result.ref = node.componentId;
|
|
1419
|
+
return true;
|
|
1420
|
+
}
|
|
1421
|
+
return false;
|
|
1422
|
+
}
|
|
1423
|
+
function writeNode(state, node) {
|
|
1424
|
+
const result = {
|
|
1425
|
+
id: node.id,
|
|
1426
|
+
type: nodeType(node)
|
|
1427
|
+
};
|
|
1428
|
+
basicNodeFields(state, node, result);
|
|
1429
|
+
if (semanticNodeFields(state, node, result)) return result;
|
|
1430
|
+
const children = node.type === "STICKY" ? [] : state.graph.getChildren(node.id).filter((child) => !child.internalOnly).map((child) => writeNode(state, child));
|
|
1431
|
+
if (children.length > 0) result.children = children;
|
|
1432
|
+
return result;
|
|
1433
|
+
}
|
|
1434
|
+
/** Code-point order, so the canonical text does not depend on the runtime locale. */
|
|
1435
|
+
function compareCodePoints(left, right) {
|
|
1436
|
+
if (left < right) return -1;
|
|
1437
|
+
if (left > right) return 1;
|
|
1438
|
+
return 0;
|
|
1439
|
+
}
|
|
1440
|
+
function sortKeys(value) {
|
|
1441
|
+
if (Array.isArray(value)) return value.map(sortKeys);
|
|
1442
|
+
if (value !== null && typeof value === "object") {
|
|
1443
|
+
const entries = Object.entries(value);
|
|
1444
|
+
return Object.fromEntries(entries.sort(([left], [right]) => compareCodePoints(left, right)).map(([key, entry]) => [key, sortKeys(entry)]));
|
|
1445
|
+
}
|
|
1446
|
+
return value;
|
|
1447
|
+
}
|
|
1448
|
+
function penDocumentFromGraph(graph) {
|
|
1449
|
+
const variables = /* @__PURE__ */ new Map();
|
|
1450
|
+
for (const variable of graph.variables.values()) variables.set(variable.id, variable);
|
|
1451
|
+
const collections = /* @__PURE__ */ new Map();
|
|
1452
|
+
for (const collection of graph.variableCollections.values()) collections.set(collection.id, collection);
|
|
1453
|
+
const state = {
|
|
1454
|
+
graph,
|
|
1455
|
+
variables,
|
|
1456
|
+
collections
|
|
1457
|
+
};
|
|
1458
|
+
const children = graph.getPages().flatMap((page) => graph.getChildren(page.id).filter((node) => !node.internalOnly).map((node) => writeNode(state, node)));
|
|
1459
|
+
const document = {
|
|
1460
|
+
version: PEN_VERSION,
|
|
1461
|
+
children
|
|
1462
|
+
};
|
|
1463
|
+
const variablesValue = variablesOf(state);
|
|
1464
|
+
if (variablesValue) document.variables = variablesValue;
|
|
1465
|
+
const themes = themesOf(state);
|
|
1466
|
+
if (themes) document.themes = themes;
|
|
1467
|
+
return document;
|
|
1468
|
+
}
|
|
1469
|
+
function stringifyPenDocument(document) {
|
|
1470
|
+
return `${JSON.stringify(sortKeys(document), null, 2)}\n`;
|
|
1471
|
+
}
|
|
1472
|
+
function writePenDocument(source) {
|
|
1473
|
+
return stringifyPenDocument(source instanceof SceneGraph ? penDocumentFromGraph(source) : source);
|
|
1474
|
+
}
|
|
1475
|
+
//#endregion
|
|
1476
|
+
export { buildPenGraph, parsePenDocument, parsePenFile, penDocumentFromGraph, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };
|
|
1477
|
+
|
|
1478
|
+
//# sourceMappingURL=index.js.map
|