@pairdraw/pen 0.20.0 → 0.21.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.
@@ -1,16 +1,20 @@
1
- import { ANNOTATION_TYPES, UNRESOLVED_REF, applyAnnotation, applyCornerRadius, applyPadding, applyPenPluginData, bindIfVar, buildVarContext, createAnnotation, isAnnotation, isVarRef, mapAlignItems, mapJustifyContent, mapLayoutMode, parseSize, resolveBoolean, resolveNumber, resolveString, unresolvedRef } from "./annotations.js";
1
+ import { ANNOTATION_TYPES, UNRESOLVED_REF, applyAnnotation, applyCornerRadius, applyPadding, applyPenPluginData, bindIfVar, buildVarContext, createAnnotation, isAnnotation, isVarRef, mapAlignItems, mapJustifyContent, mapLayoutMode, parseSize, readIconOrigin, resolveBoolean, resolveNumber, resolveString, unresolvedRef } from "./annotations.js";
2
2
  import { withImports } from "./imports.js";
3
+ import { readPenImports, readSourceLibraryPublication, writeLibraryLinks } from "./document-libraries.js";
3
4
  import { ellipseArc, lineNetwork, networkToSVGPath, pathNetwork } from "./geometry.js";
4
5
  import { drawIcon, insideComponent, removeUnusedIconComponents, useIconComponent } from "./icons.js";
5
- import { applyStroke, convertEffects, convertPaints, createImageStore, penFileSchema, strokeFields } from "./effects.js";
6
+ import { applyStroke, convertEffects, convertPaints, createImageStore, penCropTransform, penFileSchema, strokeFields } from "./effects.js";
6
7
  import { SceneGraph, generateId } from "@pairdraw/scene-graph";
7
8
  import { colorToHex, colorToHex8 } from "@pairdraw/scene-graph/color";
8
9
  import { pick } from "es-toolkit/object";
9
10
  import { isEqual } from "es-toolkit/predicate";
10
11
  import { createComponentPropertyId, libraryDefinitionsPage } from "@pairdraw/scene-graph/components";
11
12
  import * as v from "valibot";
13
+ import { readDesignMemory, writeDesignMemory } from "@pairdraw/scene-graph/design-memory";
14
+ import { readStoredStatusWorkflow, writeStatusWorkflow } from "@pairdraw/scene-graph/statuses";
12
15
  import { readTokenSources, rekeyTokenSources, tokenSourcesPluginData } from "@pairdraw/scene-graph/token-sources";
13
16
  import { INSTANCE_OVERRIDE_FIELDS, detachInstance, populateInstanceChildren, recordInstanceOverride, swapInstanceComponent } from "@pairdraw/scene-graph/instances";
17
+ import { imageMimeType } from "@pairdraw/scene-graph/images";
14
18
  import { normalizeEffects } from "@pairdraw/scene-graph/effects";
15
19
  import { CORNER_FIELDS } from "@pairdraw/scene-graph/fields";
16
20
  import { fillSizingFields, layoutSizing } from "@pairdraw/scene-graph/layout";
@@ -20,9 +24,10 @@ import { getNodeLocalMatrix, localTransformFromWorld } from "@pairdraw/scene-gra
20
24
  import { fitEnclosingGroups } from "@pairdraw/scene-graph/group-bounds";
21
25
  import Matrix from "@pairdraw/scene-graph/matrix";
22
26
  import { canCreateSlot, claimSlotContent, createSlotProperty, slotOwner, slotScope, updateSlotProperty } from "@pairdraw/scene-graph/slots";
23
- import { omit } from "es-toolkit";
27
+ import { isEqual as isEqual$1, omit } from "es-toolkit";
24
28
  import { parseFontStyle } from "@pairdraw/scene-graph/font-style";
25
29
  import { percentLength, pixelLength } from "@pairdraw/scene-graph/text";
30
+ import { fromUint8Array } from "js-base64";
26
31
  //#region src/library.ts
27
32
  /** The component IDs a layer and its overrides name: its `ref`s and the slots' suggestions. */
28
33
  function namedComponents(node, found) {
@@ -149,6 +154,24 @@ function markLibraryRoots(graph, roots) {
149
154
  root.locked = true;
150
155
  }
151
156
  }
157
+ /**
158
+ * The components whose `ref`s a file can resolve: the library definitions its own imports give it,
159
+ * matched to the alias and path each import names. Writing their ids as refs keeps the instances
160
+ * linked on a reopen; the definitions themselves stay out of the file.
161
+ */
162
+ function importedComponentIds(graph, imports) {
163
+ const ids = /* @__PURE__ */ new Set();
164
+ const aliases = Object.entries(imports);
165
+ if (aliases.length === 0) return ids;
166
+ const paths = new Map(aliases.map(([alias, path]) => [penLibraryId(alias), path]));
167
+ const visit = (node) => {
168
+ const identity = node.librarySource?.identity;
169
+ if (identity && paths.get(identity.libraryId) === identity.revisionId) ids.add(node.id);
170
+ for (const child of graph.getChildren(node.id)) visit(child);
171
+ };
172
+ for (const page of graph.getPages(true)) for (const node of graph.getChildren(page.id)) visit(node);
173
+ return ids;
174
+ }
152
175
  //#endregion
153
176
  //#region src/placeholders.ts
154
177
  /**
@@ -550,6 +573,7 @@ const PROPERTY_FIELDS = {
550
573
  justifyContent: ["primaryAxisAlign"],
551
574
  alignItems: ["counterAxisAlign"],
552
575
  clip: ["clipsContent"],
576
+ status: ["status"],
553
577
  placeholder: ["pluginData"],
554
578
  slot: ["pluginData"],
555
579
  innerRadius: ["arcData"],
@@ -640,6 +664,7 @@ function applyPenProperties(node, pen, build) {
640
664
  visible: resolveBoolean(pen.enabled, ctx),
641
665
  opacity: resolveNumber(pen.opacity, ctx, 1),
642
666
  clipsContent: resolveBoolean(pen.clip, ctx, false),
667
+ status: pen.status ?? null,
643
668
  layoutPositioning: absolute ? "ABSOLUTE" : "AUTO",
644
669
  layoutGrow: 0,
645
670
  layoutAlignSelf: "AUTO",
@@ -1029,6 +1054,9 @@ function buildPenGraph(doc, options = {}) {
1029
1054
  markLibraryRoots(graph, libraryRoots);
1030
1055
  if (graph.getPages(true).length === 0) graph.addPage("Page 1");
1031
1056
  if (doc.tokenSources && doc.tokenSources.length > 0) graph.updateNode(graph.rootId, { pluginData: tokenSourcesPluginData(graph, rekeyTokenSources(graph, doc.tokenSources)) });
1057
+ if (doc.designMemory) writeDesignMemory(graph, doc.designMemory);
1058
+ if (doc.statuses) writeStatusWorkflow(graph, doc.statuses);
1059
+ writeLibraryLinks(graph, doc);
1032
1060
  return graph;
1033
1061
  }
1034
1062
  function parsePenFile(json, options = {}) {
@@ -1215,12 +1243,31 @@ function gradientPaint(fill) {
1215
1243
  }))
1216
1244
  };
1217
1245
  }
1218
- function imagePaint(fill) {
1219
- return {
1246
+ /**
1247
+ * An image fill as a pen.dev paint whose image travels with the file: Pencil.dev opens a data URL
1248
+ * and the scene graph keeps the bytes, so the fill is written whole instead of pointing at a hash
1249
+ * no reader can resolve. A paint whose bytes are gone is left out and reported, never written as a
1250
+ * dead URL.
1251
+ */
1252
+ function imagePaint(state, fill) {
1253
+ const bytes = fill.imageHash ? state.graph.images.get(fill.imageHash) : void 0;
1254
+ if (!bytes) {
1255
+ state.drops.images++;
1256
+ return null;
1257
+ }
1258
+ if (fill.filters) state.drops.filters++;
1259
+ const paint = {
1220
1260
  type: "image",
1221
1261
  ...paintBase(fill),
1222
- url: fill.imageHash
1262
+ url: `data:${imageMimeType(bytes)};base64,${fromUint8Array(bytes)}`
1223
1263
  };
1264
+ if (fill.imageScaleMode === "FIT") paint.mode = "contain";
1265
+ if (fill.imageScaleMode === "CROP") {
1266
+ paint.mode = "stretch";
1267
+ const transform = fill.imageTransform && penCropTransform(fill.imageTransform);
1268
+ if (transform) paint.transform = transform;
1269
+ }
1270
+ return paint;
1224
1271
  }
1225
1272
  function penPaint(state, node, field, fill, index) {
1226
1273
  if (fill.type === "SOLID") return {
@@ -1229,7 +1276,7 @@ function penPaint(state, node, field, fill, index) {
1229
1276
  ...paintBase(fill)
1230
1277
  };
1231
1278
  if (fill.type.startsWith("GRADIENT_")) return gradientPaint(fill);
1232
- if (fill.type === "IMAGE") return imagePaint(fill);
1279
+ if (fill.type === "IMAGE") return imagePaint(state, fill);
1233
1280
  return {
1234
1281
  type: fill.type.toLowerCase(),
1235
1282
  ...paintBase(fill)
@@ -1237,7 +1284,8 @@ function penPaint(state, node, field, fill, index) {
1237
1284
  }
1238
1285
  function paintsOf(state, node, field, paints) {
1239
1286
  if (paints.length === 0) return void 0;
1240
- const result = paints.map((paint, index) => penPaint(state, node, field, paint, index));
1287
+ const result = paints.map((paint, index) => penPaint(state, node, field, paint, index)).filter((paint) => paint !== null);
1288
+ if (result.length === 0) return void 0;
1241
1289
  return result.length === 1 ? result[0] : result;
1242
1290
  }
1243
1291
  function strokesOf(state, node) {
@@ -1449,16 +1497,16 @@ function penVariable(variable, collection, state) {
1449
1497
  };
1450
1498
  }
1451
1499
  function variablesOf(state) {
1452
- if (state.graph.variables.size === 0) return void 0;
1453
- 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)]));
1500
+ if (state.variables.size === 0) return void 0;
1501
+ return Object.fromEntries([...state.variables.values()].sort((left, right) => left.name.localeCompare(right.name)).map((variable) => [variable.name, penVariable(variable, state.collections.get(variable.collectionId), state)]));
1454
1502
  }
1455
1503
  function themesOf(state) {
1456
- if (state.graph.variableCollections.size === 0) return void 0;
1457
- 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)]));
1504
+ if (state.collections.size === 0) return void 0;
1505
+ return Object.fromEntries([...state.collections.values()].sort((left, right) => left.name.localeCompare(right.name)).map((collection) => [collection.name, collection.modes.map((mode) => mode.name)]));
1458
1506
  }
1459
1507
  /** The selector each mode applies in, by collection and mode name; none when no mode names one. */
1460
1508
  function modeConditionsOf(state) {
1461
- const entries = [...state.graph.variableCollections.values()].flatMap((collection) => {
1509
+ const entries = [...state.collections.values()].flatMap((collection) => {
1462
1510
  const modes = collection.modes.flatMap((mode) => mode.condition ? [[mode.name, mode.condition]] : []);
1463
1511
  return modes.length > 0 ? [[collection.name, Object.fromEntries(modes)]] : [];
1464
1512
  });
@@ -1495,25 +1543,141 @@ function themeFields(state, node) {
1495
1543
  }
1496
1544
  return Object.keys(theme).length > 0 ? theme : void 0;
1497
1545
  }
1546
+ /**
1547
+ * The pen fields an instance override writes: what it changes on a layer, not the placement and
1548
+ * layout a reopen recalculates from the component and the boxes around it.
1549
+ */
1550
+ const OVERRIDABLE_FIELDS = /* @__PURE__ */ new Set([
1551
+ "content",
1552
+ "fill",
1553
+ "stroke",
1554
+ "strokeWidth",
1555
+ "cornerRadius",
1556
+ "effect",
1557
+ "opacity",
1558
+ "enabled",
1559
+ "fontFamily",
1560
+ "fontSize",
1561
+ "fontWeight",
1562
+ "fontStyle",
1563
+ "textAlign",
1564
+ "textAlignVertical",
1565
+ "lineHeight",
1566
+ "letterSpacing",
1567
+ "href"
1568
+ ]);
1569
+ /**
1570
+ * The path a copy sits at in its component, from the instance down: the ids of the layers it
1571
+ * copies, as pen names a `descendants` override. A copy that swapped its component copies `swapOf`
1572
+ * instead of the component it draws.
1573
+ */
1574
+ function overridePath(graph, instanceId, copyId, swapOf) {
1575
+ const parts = [];
1576
+ let current = graph.getNode(copyId);
1577
+ while (current && current.id !== instanceId) {
1578
+ const id = current.id === copyId && swapOf ? swapOf : current.componentId;
1579
+ if (!id) return null;
1580
+ parts.unshift(id);
1581
+ current = current.parentId ? graph.getNode(current.parentId) : void 0;
1582
+ }
1583
+ return current ? parts.join("/") : null;
1584
+ }
1585
+ /**
1586
+ * The fields a swap override names an icon by: pen carries the glyph, not the component drawn.
1587
+ */
1588
+ function iconOverride(graph, componentId) {
1589
+ const origin = readIconOrigin(componentId ? graph.getNode(componentId) : void 0);
1590
+ if (!origin) return void 0;
1591
+ const override = { icon: origin.icon };
1592
+ if (origin.library) override.library = origin.library;
1593
+ if (origin.weight !== void 0) override.weight = origin.weight;
1594
+ return override;
1595
+ }
1596
+ /**
1597
+ * The overrides an instance writes, and whether one of them is a swap the file cannot name. A
1598
+ * layer that swapped its component draws another component than the one it copies, which pen holds
1599
+ * as a glyph for an icon; any other swap is what the instance shows, not what it links to.
1600
+ */
1601
+ function instanceDescendants(state, node) {
1602
+ const overridden = [...node.instanceOverrides.descendants.keys()];
1603
+ if (overridden.length === 0) return { unrepresentable: false };
1604
+ const probe = {
1605
+ ...state,
1606
+ drops: {
1607
+ images: 0,
1608
+ effects: 0,
1609
+ filters: 0,
1610
+ scroll: 0,
1611
+ fontFeatures: 0
1612
+ }
1613
+ };
1614
+ const descendants = {};
1615
+ let unrepresentable = false;
1616
+ for (const copyId of overridden) {
1617
+ const overrides = node.instanceOverrides.descendants.get(copyId);
1618
+ const swapped = overrides?.has("componentId") === true;
1619
+ const swapOf = swapped ? overrides.get("sourceComponentId") : void 0;
1620
+ const path = overridePath(state.graph, node.id, copyId, typeof swapOf === "string" ? swapOf : void 0);
1621
+ const copy = state.graph.getNode(copyId);
1622
+ if (!path || !copy) {
1623
+ unrepresentable = true;
1624
+ continue;
1625
+ }
1626
+ if (swapped) {
1627
+ const icon = iconOverride(state.graph, copy.componentId);
1628
+ if (!icon) {
1629
+ unrepresentable = true;
1630
+ continue;
1631
+ }
1632
+ descendants[path] = icon;
1633
+ continue;
1634
+ }
1635
+ const master = copy.componentId ? state.graph.getNode(copy.componentId) : void 0;
1636
+ if (!master) {
1637
+ unrepresentable = true;
1638
+ continue;
1639
+ }
1640
+ const own = writeNode(probe, copy);
1641
+ const base = writeNode(probe, master);
1642
+ const override = {};
1643
+ for (const field of OVERRIDABLE_FIELDS) if (!isEqual$1(own[field], base[field])) override[field] = own[field];
1644
+ if (Object.keys(override).length > 0) descendants[path] = override;
1645
+ }
1646
+ return {
1647
+ descendants: Object.keys(descendants).length > 0 ? descendants : void 0,
1648
+ unrepresentable
1649
+ };
1650
+ }
1498
1651
  function semanticNodeFields(state, node, result) {
1499
1652
  if (node.type === "TEXT" && node.textAutoResize === "WIDTH_AND_HEIGHT" && layoutSizing(state.graph, node, "HORIZONTAL") === "HUG") result.width = "fit_content";
1500
1653
  if (node.type === "STICKY") result.content = stickySublayers(state.graph, node)?.body.text ?? "";
1501
1654
  penPluginFields(node, result);
1502
- const effects = node.effects.filter((effect) => effect.type !== "SHADER");
1655
+ const effects = node.effects.filter((effect) => {
1656
+ if (effect.type === "DROP_SHADOW" || effect.type === "INNER_SHADOW") return true;
1657
+ if (effect.type === "LAYER_BLUR" || effect.type === "BACKGROUND_BLUR") return true;
1658
+ if (effect.type === "NOISE" || effect.type === "TEXTURE") state.drops.effects++;
1659
+ return false;
1660
+ });
1503
1661
  if (effects.length > 0) result.effect = effects.length === 1 ? effectOf(effects[0]) : effects.map(effectOf);
1504
1662
  if (node.type === "COMPONENT" || node.type === "COMPONENT_SET") result.reusable = true;
1505
- if (node.type === "INSTANCE" && node.componentId && state.writtenIds.has(node.componentId)) {
1663
+ if (node.type === "INSTANCE" && node.componentId && (state.writtenIds.has(node.componentId) || state.importedIds.has(node.componentId))) {
1664
+ const overrides = instanceDescendants(state, node);
1665
+ if (overrides.unrepresentable && !state.writtenIds.has(node.componentId)) return false;
1506
1666
  result.type = "ref";
1507
1667
  result.ref = node.componentId;
1668
+ if (overrides.descendants) result.descendants = overrides.descendants;
1508
1669
  return true;
1509
1670
  }
1510
1671
  return false;
1511
1672
  }
1512
1673
  function writeNode(state, node) {
1674
+ if (node.overflowDirection !== "NONE") state.drops.scroll++;
1675
+ if (node.fontFeatures.length > 0) state.drops.fontFeatures++;
1513
1676
  const result = {
1514
1677
  id: node.id,
1515
1678
  type: nodeType(node)
1516
1679
  };
1680
+ if (node.status !== null) result.status = node.status;
1517
1681
  basicNodeFields(state, node, result);
1518
1682
  if (semanticNodeFields(state, node, result)) return result;
1519
1683
  if (node.type === "VECTOR" && node.vectorNetwork && node.vectorNetwork.segments.length > 0) {
@@ -1547,21 +1711,32 @@ function sortKeys(value) {
1547
1711
  }
1548
1712
  return value;
1549
1713
  }
1550
- function penDocumentFromGraph(graph) {
1714
+ function penDocumentFromGraph(graph, options = {}) {
1551
1715
  const variables = /* @__PURE__ */ new Map();
1552
- for (const variable of graph.variables.values()) variables.set(variable.id, variable);
1716
+ for (const variable of graph.getLiveVariables()) variables.set(variable.id, variable);
1553
1717
  const collections = /* @__PURE__ */ new Map();
1554
- for (const collection of graph.variableCollections.values()) collections.set(collection.id, collection);
1718
+ for (const collection of graph.getLiveCollections()) collections.set(collection.id, collection);
1719
+ const imports = readPenImports(graph);
1555
1720
  const state = {
1556
1721
  graph,
1557
1722
  variables,
1558
1723
  collections,
1559
- writtenIds: writtenNodeIds(graph)
1724
+ writtenIds: writtenNodeIds(graph),
1725
+ importedIds: importedComponentIds(graph, imports ?? {}),
1726
+ warnings: options.warnings ?? [],
1727
+ drops: {
1728
+ images: 0,
1729
+ effects: 0,
1730
+ filters: 0,
1731
+ scroll: 0,
1732
+ fontFeatures: 0
1733
+ }
1560
1734
  };
1561
- const children = graph.getPages().flatMap((page) => graph.getChildren(page.id).filter((node) => !node.internalOnly).map((node) => writeNode(state, node)));
1735
+ const pages = graph.getPages();
1736
+ const children = pages.flatMap((page) => graph.getChildren(page.id).filter((node) => !node.internalOnly).map((node) => writeNode(state, node)));
1562
1737
  const document = {
1563
1738
  version: PEN_VERSION,
1564
- name: graph.getPages()[0]?.name,
1739
+ name: pages[0]?.name,
1565
1740
  children
1566
1741
  };
1567
1742
  const variablesValue = variablesOf(state);
@@ -1586,13 +1761,49 @@ function penDocumentFromGraph(graph) {
1586
1761
  return refreshed;
1587
1762
  });
1588
1763
  if (tokenSources.length > 0) document.tokenSources = tokenSources;
1764
+ const designMemory = readDesignMemory(graph);
1765
+ if (designMemory) document.designMemory = designMemory;
1766
+ const statuses = readStoredStatusWorkflow(graph);
1767
+ if (statuses) document.statuses = statuses;
1768
+ if (imports) document.imports = imports;
1769
+ const enabledLibraries = enabledLibrariesOf(graph, state);
1770
+ if (enabledLibraries) document.enabledLibraries = enabledLibraries;
1771
+ const publication = readSourceLibraryPublication(graph);
1772
+ if (publication) document.sourceLibraryPublication = publication;
1773
+ if (pages.length > 1) {
1774
+ const name = document.name ?? "Page 1";
1775
+ state.warnings.push(`Pencil.dev files hold one page; ${pages.length} pages were merged into “${name}”.`);
1776
+ }
1777
+ if (graph.documentColorSpace === "display-p3") state.warnings.push("Colors are written as sRGB hex, the only form a Pencil.dev file holds; a Display P3 color outside sRGB comes out as the nearest sRGB color.");
1778
+ reportDrops(state);
1589
1779
  return document;
1590
1780
  }
1781
+ /**
1782
+ * The library bindings a `.pen` file records, or null when the document has none. The definitions
1783
+ * live on the hidden page, which a Pencil.dev file cannot hold, so the file records the bindings
1784
+ * and says that the components it was built from come back as placeholders.
1785
+ */
1786
+ function enabledLibrariesOf(graph, state) {
1787
+ const bindings = [...graph.enabledLibraries.values()];
1788
+ if (bindings.length === 0) return null;
1789
+ const enabled = bindings.filter((binding) => binding.enabled).length;
1790
+ if (enabled > 0) state.warnings.push(`Library components came from ${enabled} enabled ${enabled === 1 ? "library" : "libraries"}, whose definitions Pencil.dev files do not hold; re-enable those libraries after reopening to restore them.`);
1791
+ return bindings;
1792
+ }
1793
+ /** Adds one sentence for each kind of content the written file had to leave out. */
1794
+ function reportDrops(state) {
1795
+ const { images, effects, filters, scroll, fontFeatures } = state.drops;
1796
+ if (images > 0) state.warnings.push(`Image fills with missing image data were left out (${images}); Pencil.dev files cannot hold a paint without its image.`);
1797
+ if (effects > 0) state.warnings.push(`Noise and texture effects were left out (${effects}); Pencil.dev files have no form for them.`);
1798
+ if (filters > 0) state.warnings.push(`Image adjustment filters were left out (${filters}); Pencil.dev files have no form for them.`);
1799
+ if (scroll > 0) state.warnings.push(`Scroll overflow was left out (${scroll}); Pencil.dev files have no form for it.`);
1800
+ if (fontFeatures > 0) state.warnings.push(`OpenType font features were left out (${fontFeatures}); Pencil.dev files have no form for them.`);
1801
+ }
1591
1802
  function stringifyPenDocument(document) {
1592
1803
  return `${JSON.stringify(sortKeys(document), null, 2)}\n`;
1593
1804
  }
1594
- function writePenDocument(source) {
1595
- return stringifyPenDocument(source instanceof SceneGraph ? penDocumentFromGraph(source) : source);
1805
+ function writePenDocument(source, options = {}) {
1806
+ return stringifyPenDocument(source instanceof SceneGraph ? penDocumentFromGraph(source, options) : source);
1596
1807
  }
1597
1808
  //#endregion
1598
1809
  export { buildPenGraph, parsePenDocument, parsePenFile, penDocumentFromGraph, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };