@pairdraw/pen 0.17.0 → 0.19.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
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
2
  import { withImports } from "./imports.js";
3
- import { ellipseArc, lineNetwork, pathNetwork } from "./geometry.js";
3
+ import { ellipseArc, lineNetwork, networkToSVGPath, pathNetwork } from "./geometry.js";
4
4
  import { drawIcon, insideComponent, removeUnusedIconComponents, useIconComponent } from "./icons.js";
5
5
  import { applyStroke, convertEffects, convertPaints, createImageStore, penFileSchema, strokeFields } from "./effects.js";
6
6
  import { SceneGraph, generateId } from "@pairdraw/scene-graph";
@@ -10,6 +10,7 @@ import { isEqual } from "es-toolkit/predicate";
10
10
  import { createComponentPropertyId, libraryDefinitionsPage } from "@pairdraw/scene-graph/components";
11
11
  import * as v from "valibot";
12
12
  import { INSTANCE_OVERRIDE_FIELDS, detachInstance, populateInstanceChildren, recordInstanceOverride, swapInstanceComponent } from "@pairdraw/scene-graph/instances";
13
+ import { normalizeEffects } from "@pairdraw/scene-graph/effects";
13
14
  import { CORNER_FIELDS } from "@pairdraw/scene-graph/fields";
14
15
  import { fillSizingFields, layoutSizing } from "@pairdraw/scene-graph/layout";
15
16
  import { stickySublayers } from "@pairdraw/scene-graph/generated";
@@ -18,6 +19,7 @@ import { getNodeLocalMatrix, localTransformFromWorld } from "@pairdraw/scene-gra
18
19
  import { fitEnclosingGroups } from "@pairdraw/scene-graph/group-bounds";
19
20
  import Matrix from "@pairdraw/scene-graph/matrix";
20
21
  import { canCreateSlot, claimSlotContent, createSlotProperty, slotOwner, slotScope, updateSlotProperty } from "@pairdraw/scene-graph/slots";
22
+ import { parseFontStyle } from "@pairdraw/scene-graph/font-style";
21
23
  import { percentLength, pixelLength } from "@pairdraw/scene-graph/text";
22
24
  //#region src/library.ts
23
25
  /** The component IDs a layer and its overrides name: its `ref`s and the slots' suggestions. */
@@ -363,7 +365,7 @@ const TEXT_GROWTH = {
363
365
  * as pen.dev shows it. pen.dev 2.21 draws no underline, strikethrough, or text stroke, so those
364
366
  * are left out to match it. An `href` is kept as a link, drawn without an underline.
365
367
  */
366
- function applyTextProps(node, pen, ctx) {
368
+ function applyTextProps(node, pen, ctx, fonts) {
367
369
  const isIconFont = pen.type === "icon_font";
368
370
  node.text = isIconFont ? pen.iconFontName ?? "" : pen.content ?? "";
369
371
  node.fontFamily = isIconFont ? pen.iconFontFamily ?? "Material Symbols Sharp" : resolveString(pen.fontFamily, ctx) ?? "Inter";
@@ -374,6 +376,17 @@ function applyTextProps(node, pen, ctx) {
374
376
  node.fontWeight = fontWeight(weight, ctx);
375
377
  bindIfVar(node, "fontWeight", weight, ctx);
376
378
  node.italic = resolveString(pen.fontStyle, ctx)?.toLowerCase() === "italic";
379
+ const bundled = isIconFont ? void 0 : fonts.get(node.fontFamily);
380
+ if (bundled) {
381
+ const { weight, italic } = parseFontStyle(bundled.style);
382
+ Object.assign(node, {
383
+ fontFamily: bundled.family,
384
+ fontStyle: bundled.style,
385
+ fontWeight: weight,
386
+ italic
387
+ });
388
+ delete node.boundVariables.fontFamily;
389
+ }
377
390
  node.textAlignHorizontal = TEXT_ALIGN[pen.textAlign ?? "left"] ?? "LEFT";
378
391
  node.textAlignVertical = TEXT_ALIGN_VERTICAL[pen.textAlignVertical ?? "top"] ?? "TOP";
379
392
  if (pen.lineHeight !== void 0) node.lineHeight = percentLength(resolveNumber(pen.lineHeight, ctx) * 100);
@@ -458,6 +471,7 @@ function applyAutoLayout(node, layoutMode, pen, widthSizing, heightSizing, ctx)
458
471
  node.primaryAxisSizing = own(widthSizing);
459
472
  node.counterAxisSizing = own(heightSizing);
460
473
  }
474
+ if (node.primaryAxisAlign === "SPACE_BETWEEN" && node.primaryAxisSizing === "HUG") node.primaryAxisAlign = "MIN";
461
475
  }
462
476
  const PLACEMENT_FIELDS = [
463
477
  "x",
@@ -630,10 +644,10 @@ function applyPenProperties(node, pen, build) {
630
644
  ...paint,
631
645
  align: "CENTER"
632
646
  }));
633
- node.effects = convertEffects(pen.effect, ctx, build.shaders);
647
+ node.effects = normalizeEffects(convertEffects(pen.effect, ctx, build.shaders));
634
648
  applyCornerRadius(node, pen.cornerRadius, ctx);
635
649
  applyPadding(node, pen.padding, ctx);
636
- if (isTextLike) applyTextProps(node, pen, ctx);
650
+ if (isTextLike) applyTextProps(node, pen, ctx, build.fonts);
637
651
  if (pen.type === "icon") drawIconLayer(node, pen, build);
638
652
  if (pen.type === "ellipse") node.arcData = ellipseArc(pen, ctx);
639
653
  if (pen.type === "polygon") node.pointCount = Math.max(3, resolveNumber(pen.polygonCount, ctx, 3));
@@ -716,11 +730,16 @@ function sources(graph, node) {
716
730
  for (let id = node.componentId; id && !found.has(id); id = graph.getNode(id)?.componentId ?? null) found.add(id);
717
731
  return found;
718
732
  }
733
+ /** The pen.dev layer a layer was built from, which a component swap stops naming. */
734
+ function penLayerId(build, node) {
735
+ return build.effective.get(node.id)?.id;
736
+ }
719
737
  /** The copy in `root`'s layers made from the pen.dev layer `sourceId`, at any depth. */
720
- function findCopy(graph, root, sourceId) {
738
+ function findCopy(build, root, sourceId) {
739
+ const { graph } = build;
721
740
  const queue = graph.getChildren(root.id);
722
741
  for (const node of queue) {
723
- if (sources(graph, node).has(sourceId)) return node;
742
+ if (penLayerId(build, node) === sourceId || sources(graph, node).has(sourceId)) return node;
724
743
  queue.push(...graph.getChildren(node.id));
725
744
  }
726
745
  }
@@ -728,9 +747,9 @@ function findCopy(graph, root, sourceId) {
728
747
  * The layer an override's key names: pen.dev IDs separated by `/`, each one inside the copy of the
729
748
  * instance the one before it names.
730
749
  */
731
- function resolvePath(graph, instance, path) {
750
+ function resolvePath(build, instance, path) {
732
751
  let current = instance;
733
- for (const id of path.split("/")) current = current ? findCopy(graph, current, id) : void 0;
752
+ for (const id of path.split("/")) current = current ? findCopy(build, current, id) : void 0;
734
753
  return current;
735
754
  }
736
755
  /** Runs `apply` in the merged theme of a layer's ancestors, as the layer was read in. */
@@ -830,12 +849,14 @@ function overrideLayer(build, target, override, instance) {
830
849
  inAncestorThemes(build, target, () => {
831
850
  const leave = merged.theme ? ctx.enterTheme(merged.theme) : void 0;
832
851
  try {
833
- applyPenProperties(target, merged, build);
852
+ if (children) for (const childId of target.childIds) graph.deleteNode(childId);
853
+ applyPenProperties(target, children ? {
854
+ ...merged,
855
+ children
856
+ } : merged, build);
834
857
  recordChangedFields(graph, target, before, fields);
835
858
  if (children) {
836
859
  const fillsSlot = instance !== void 0 && claimSlot(build, instance, target);
837
- const replaced = target.childIds;
838
- for (const childId of replaced) graph.deleteNode(childId);
839
860
  for (const child of children) createSceneNode(child, target.id, build);
840
861
  if (!fillsSlot) build.replaced.add(target.id);
841
862
  }
@@ -860,7 +881,7 @@ function detachReplacingInstances(build) {
860
881
  /** Gives an instance's copies their overrides; a key with a `type` replaces the layer. */
861
882
  function applyDescendants(build, instance, descendants, populate) {
862
883
  for (const [path, override] of Object.entries(descendants ?? {})) {
863
- const target = resolvePath(build.graph, instance, path);
884
+ const target = resolvePath(build, instance, path);
864
885
  if (!target) continue;
865
886
  if (override.type) replaceLayer(build, target, override, populate);
866
887
  else overrideLayer(build, target, override, instance);
@@ -901,6 +922,7 @@ function populateInstances(build) {
901
922
  recordOwnFields(graph, instance, ref);
902
923
  inheritCopyFields(build, instance);
903
924
  applyDescendants(build, instance, ref.descendants, populate);
925
+ if (ref.children) overrideLayer(build, instance, { children: ref.children });
904
926
  detachReplacingInstances(build);
905
927
  }
906
928
  for (const id of instances.keys()) populate(id);
@@ -961,6 +983,7 @@ function buildPenGraph(doc, options = {}) {
961
983
  images: createImageStore(graph, options.images),
962
984
  shaders: options.shaders,
963
985
  icons: options.icons,
986
+ fonts: options.fonts ?? /* @__PURE__ */ new Map(),
964
987
  components: /* @__PURE__ */ new Map(),
965
988
  effective: /* @__PURE__ */ new Map(),
966
989
  instances: /* @__PURE__ */ new Map(),
@@ -972,7 +995,7 @@ function buildPenGraph(doc, options = {}) {
972
995
  };
973
996
  collectComponents(doc.children, build.components);
974
997
  for (const imported of imports.values()) collectComponents(imported.doc.children, build.components);
975
- const page = graph.addPage(doc.children[0]?.name ?? "Page 1");
998
+ const page = graph.addPage(doc.name ?? doc.children[0]?.name ?? "Page 1");
976
999
  for (const child of doc.children) createSceneNode(child, page.id, build);
977
1000
  const libraryRoots = createLibraryRoots(doc, imports, build, createSceneNode);
978
1001
  populateInstances(build);
@@ -1422,10 +1445,25 @@ function basicNodeFields(state, node, result) {
1422
1445
  if (node.rotation !== 0) result.rotation = rounded(node.flipX !== node.flipY ? node.rotation : -node.rotation);
1423
1446
  if (node.flipX) result.flipX = true;
1424
1447
  if (node.flipY) result.flipY = true;
1448
+ const theme = themeFields(state, node);
1449
+ if (theme) result.theme = theme;
1425
1450
  const fill = paintsOf(state, node, "fills", node.fills);
1426
1451
  if (fill !== void 0) result.fill = fill;
1427
1452
  Object.assign(result, strokesOf(state, node), layoutFields(state, node), cornerFields(node), textFields(state, node));
1428
1453
  }
1454
+ /**
1455
+ * A layer's variable mode assignments, by the names pen writes: the collection's name and the
1456
+ * mode's. A mode the document no longer holds is left out.
1457
+ */
1458
+ function themeFields(state, node) {
1459
+ const theme = {};
1460
+ for (const [collectionId, modeId] of Object.entries(node.variableModes)) {
1461
+ const collection = state.collections.get(collectionId);
1462
+ const mode = collection?.modes.find((candidate) => candidate.modeId === modeId);
1463
+ if (collection && mode) theme[collection.name] = mode.name;
1464
+ }
1465
+ return Object.keys(theme).length > 0 ? theme : void 0;
1466
+ }
1429
1467
  function semanticNodeFields(state, node, result) {
1430
1468
  if (node.type === "TEXT" && node.textAutoResize === "WIDTH_AND_HEIGHT" && layoutSizing(state.graph, node, "HORIZONTAL") === "HUG") result.width = "fit_content";
1431
1469
  if (node.type === "STICKY") result.content = stickySublayers(state.graph, node)?.body.text ?? "";
@@ -1447,6 +1485,19 @@ function writeNode(state, node) {
1447
1485
  };
1448
1486
  basicNodeFields(state, node, result);
1449
1487
  if (semanticNodeFields(state, node, result)) return result;
1488
+ if (node.type === "VECTOR" && node.vectorNetwork && node.vectorNetwork.segments.length > 0) {
1489
+ const geometry = networkToSVGPath(node.vectorNetwork);
1490
+ if (geometry) {
1491
+ result.geometry = geometry;
1492
+ result.viewBox = [
1493
+ 0,
1494
+ 0,
1495
+ rounded(node.width),
1496
+ rounded(node.height)
1497
+ ];
1498
+ if (node.vectorNetwork.regions[0]?.windingRule === "EVENODD") result.fillRule = "evenodd";
1499
+ }
1500
+ }
1450
1501
  const children = node.type === "STICKY" ? [] : state.graph.getChildren(node.id).filter((child) => !child.internalOnly).map((child) => writeNode(state, child));
1451
1502
  if (children.length > 0) result.children = children;
1452
1503
  return result;
@@ -1479,6 +1530,7 @@ function penDocumentFromGraph(graph) {
1479
1530
  const children = graph.getPages().flatMap((page) => graph.getChildren(page.id).filter((node) => !node.internalOnly).map((node) => writeNode(state, node)));
1480
1531
  const document = {
1481
1532
  version: PEN_VERSION,
1533
+ name: graph.getPages()[0]?.name,
1482
1534
  children
1483
1535
  };
1484
1536
  const variablesValue = variablesOf(state);