@pairdraw/pen 0.21.0 → 0.21.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.
@@ -1102,6 +1102,25 @@ const PEN_PLUGIN_FIELDS = {
1102
1102
  "pen/scrollX": "scrollX",
1103
1103
  "pen/scrollY": "scrollY"
1104
1104
  };
1105
+ /** The English sentence a write warning has always been reported as. */
1106
+ function penWriteWarningText(warning) {
1107
+ switch (warning.kind) {
1108
+ case "merged-pages": return `Pencil.dev files hold one page; ${warning.pages} pages were merged into “${warning.name}”.`;
1109
+ case "display-p3-colors": return "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.";
1110
+ case "library-definitions": return `Library components came from ${warning.count} enabled ${warning.count === 1 ? "library" : "libraries"}, whose definitions Pencil.dev files do not hold; re-enable those libraries after reopening to restore them.`;
1111
+ case "missing-image-fills": return `Image fills with missing image data were left out (${warning.count}); Pencil.dev files cannot hold a paint without its image.`;
1112
+ case "dropped-effects": return `Noise and texture effects were left out (${warning.count}); Pencil.dev files have no form for them.`;
1113
+ case "dropped-filters": return `Image adjustment filters were left out (${warning.count}); Pencil.dev files have no form for them.`;
1114
+ case "dropped-scroll": return `Scroll overflow was left out (${warning.count}); Pencil.dev files have no form for it.`;
1115
+ case "dropped-font-features": return `OpenType font features were left out (${warning.count}); Pencil.dev files have no form for them.`;
1116
+ default: throw new Error(`Unhandled pen write warning: ${String(warning)}`);
1117
+ }
1118
+ }
1119
+ /** Records a warning as its sentence and its kind, in the order it was found. */
1120
+ function emit(state, warning) {
1121
+ state.details.push(warning);
1122
+ state.warnings.push(penWriteWarningText(warning));
1123
+ }
1105
1124
  /** Snaps matrix values that are within floating-point noise of an integer. */
1106
1125
  function snapCoordinate(value) {
1107
1126
  return Math.abs(value - Math.round(value)) < 1e-9 ? Math.round(value) : value;
@@ -1724,6 +1743,7 @@ function penDocumentFromGraph(graph, options = {}) {
1724
1743
  writtenIds: writtenNodeIds(graph),
1725
1744
  importedIds: importedComponentIds(graph, imports ?? {}),
1726
1745
  warnings: options.warnings ?? [],
1746
+ details: [],
1727
1747
  drops: {
1728
1748
  images: 0,
1729
1749
  effects: 0,
@@ -1772,10 +1792,15 @@ function penDocumentFromGraph(graph, options = {}) {
1772
1792
  if (publication) document.sourceLibraryPublication = publication;
1773
1793
  if (pages.length > 1) {
1774
1794
  const name = document.name ?? "Page 1";
1775
- state.warnings.push(`Pencil.dev files hold one page; ${pages.length} pages were merged into “${name}”.`);
1795
+ emit(state, {
1796
+ kind: "merged-pages",
1797
+ pages: pages.length,
1798
+ name
1799
+ });
1776
1800
  }
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.");
1801
+ if (graph.documentColorSpace === "display-p3") emit(state, { kind: "display-p3-colors" });
1778
1802
  reportDrops(state);
1803
+ options.warningDetails?.push(...state.details);
1779
1804
  return document;
1780
1805
  }
1781
1806
  /**
@@ -1787,17 +1812,35 @@ function enabledLibrariesOf(graph, state) {
1787
1812
  const bindings = [...graph.enabledLibraries.values()];
1788
1813
  if (bindings.length === 0) return null;
1789
1814
  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.`);
1815
+ if (enabled > 0) emit(state, {
1816
+ kind: "library-definitions",
1817
+ count: enabled
1818
+ });
1791
1819
  return bindings;
1792
1820
  }
1793
1821
  /** Adds one sentence for each kind of content the written file had to leave out. */
1794
1822
  function reportDrops(state) {
1795
1823
  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.`);
1824
+ if (images > 0) emit(state, {
1825
+ kind: "missing-image-fills",
1826
+ count: images
1827
+ });
1828
+ if (effects > 0) emit(state, {
1829
+ kind: "dropped-effects",
1830
+ count: effects
1831
+ });
1832
+ if (filters > 0) emit(state, {
1833
+ kind: "dropped-filters",
1834
+ count: filters
1835
+ });
1836
+ if (scroll > 0) emit(state, {
1837
+ kind: "dropped-scroll",
1838
+ count: scroll
1839
+ });
1840
+ if (fontFeatures > 0) emit(state, {
1841
+ kind: "dropped-font-features",
1842
+ count: fontFeatures
1843
+ });
1801
1844
  }
1802
1845
  function stringifyPenDocument(document) {
1803
1846
  return `${JSON.stringify(sortKeys(document), null, 2)}\n`;
@@ -1806,6 +1849,6 @@ function writePenDocument(source, options = {}) {
1806
1849
  return stringifyPenDocument(source instanceof SceneGraph ? penDocumentFromGraph(source, options) : source);
1807
1850
  }
1808
1851
  //#endregion
1809
- export { buildPenGraph, parsePenDocument, parsePenFile, penDocumentFromGraph, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };
1852
+ export { buildPenGraph, parsePenDocument, parsePenFile, penDocumentFromGraph, penWriteWarningText, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };
1810
1853
 
1811
1854
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["isEqual","SceneGraphValue"],"sources":["../../src/library.ts","../../src/placeholders.ts","../../src/placement.ts","../../src/slots.ts","../../src/text.ts","../../src/nodes.ts","../../src/instances.ts","../../src/read.ts","../../src/written-nodes.ts","../../src/write.ts"],"sourcesContent":["import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { libraryDefinitionsPage } from '@pairdraw/scene-graph/components'\n\nimport { withImports, type PenImports } from './imports'\nimport type { Build } from './nodes'\nimport type { PenDocument, PenNode, PenOverride } from './schema'\n\n/** A component an imported document defines, with the outermost component holding it. */\ninterface Owner {\n alias: string\n path: string\n root: PenNode\n /** The themes of the layers around the root in its document, which it was drawn in. */\n theme: Record<string, string> | undefined\n}\n\n/** An imported component the document draws, as it went on the library page. */\nexport interface LibraryRoot {\n id: string\n alias: string\n path: string\n}\n\n/** The component IDs a layer and its overrides name: its `ref`s and the slots' suggestions. */\nfunction namedComponents(node: PenOverride, found: string[]): void {\n if (typeof node.ref === 'string') found.push(node.ref)\n if (Array.isArray(node.slot)) found.push(...node.slot)\n for (const child of node.children ?? []) namedComponents(child, found)\n for (const override of Object.values(node.descendants ?? {})) namedComponents(override, found)\n}\n\nfunction mergeTheme(\n outer: Record<string, string> | undefined,\n inner: Record<string, string> | undefined\n): Record<string, string> | undefined {\n return outer || inner ? { ...outer, ...inner } : undefined\n}\n\n/** Each reusable layer of the imported documents by ID, with the outermost component holding it. */\nfunction componentOwners(imports: PenImports): Map<string, Owner> {\n const owners = new Map<string, Owner>()\n for (const [alias, { path, doc }] of imports) {\n const visit = (nodes: readonly PenNode[], root: PenNode | undefined, theme: Owner['theme']) => {\n for (const node of nodes) {\n const own = root ?? (node.reusable ? node : undefined)\n if (node.reusable && own) owners.set(node.id, { alias, path, root: own, theme })\n visit(node.children ?? [], own, own ? theme : mergeTheme(theme, node.theme))\n }\n }\n visit(doc.children, undefined, undefined)\n }\n return owners\n}\n\n/**\n * The imported components a document draws, through the components they draw in turn, each as the\n * outermost component holding it, in the order the document first names them. A library's other\n * components stay out of the document, which only ever shows instances of the ones it uses.\n */\nfunction usedRoots(doc: PenDocument, imports: PenImports): Owner[] {\n const owners = componentOwners(imports)\n const pending: string[] = []\n for (const node of doc.children) namedComponents(node, pending)\n const roots = new Map<string, Owner>()\n // Each root's own names join the list as it is read.\n for (const id of pending) {\n const owner = owners.get(id)\n if (!owner || roots.has(owner.root.id)) continue\n roots.set(owner.root.id, owner)\n namedComponents(owner.root, pending)\n }\n return [...roots.values()]\n}\n\n/**\n * The document with the imported components it uses after its own layers, and the imported\n * variables and themes, so `penAssets` lists every icon and image it draws and no other of a\n * library's.\n */\nexport function withUsedImports(doc: PenDocument, imports: PenImports): PenDocument {\n if (imports.size === 0) return doc\n return {\n ...withImports(doc, imports),\n children: [...doc.children, ...usedRoots(doc, imports).map((owner) => owner.root)]\n }\n}\n\n/**\n * Draws the imported components the document uses on the hidden library page, in the themes they\n * sit in in their own documents, so its instances of them resolve. Nothing is drawn when the\n * document uses none.\n */\nexport function createLibraryRoots(\n doc: PenDocument,\n imports: PenImports,\n build: Build,\n create: (pen: PenNode, parentId: string, build: Build) => string\n): LibraryRoot[] {\n const roots = usedRoots(doc, imports)\n if (roots.length === 0) return []\n const page = libraryDefinitionsPage(build.graph)\n return roots.map(({ alias, path, root, theme }) => {\n const leave = theme ? build.ctx.enterTheme(theme) : undefined\n try {\n return { id: create(root, page.id, build), alias, path }\n } finally {\n leave?.()\n }\n })\n}\n\n/** `value` with what `allowed` rejects replaced, starting with a letter or digit, at most `max` long. */\nfunction libraryName(value: string, allowed: RegExp, max: number): string {\n const name = value.replace(allowed, '_')\n return (/^[a-zA-Z0-9]/.test(name) ? name : `x${name}`).slice(0, max)\n}\n\n/** The ID a library's assets name it by: `pen:<alias>`, in the characters library IDs take. */\nfunction penLibraryId(alias: string): string {\n return libraryName(`pen:${alias}`, /[^a-zA-Z0-9._:-]/g, 128)\n}\n\n/** A component's key in its library: its ID in the imported document, without the alias. */\nfunction penLibraryAssetKey(alias: string, id: string): string {\n const prefix = `${alias}:`\n const own = id.startsWith(prefix) ? id.slice(prefix.length) : id\n return libraryName(own, /[^a-zA-Z0-9._:/-]/g, 256)\n}\n\n/**\n * Marks the imported components as a library's definitions: read-only, locked, and each with its\n * library and key, so the editor treats them as it treats a component library's, and their\n * instances as library instances. The file they came from is their revision.\n */\nexport function markLibraryRoots(graph: SceneGraph, roots: readonly LibraryRoot[]): void {\n for (const { id, alias, path } of roots) {\n const root = graph.getNode(id)\n if (!root) continue\n const libraryId = penLibraryId(alias)\n const queue = [root]\n for (const node of queue) {\n if (node === root || node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') {\n node.librarySource = {\n identity: { libraryId, assetKey: penLibraryAssetKey(alias, node.id), revisionId: path },\n sourceNodeId: null,\n readOnly: true\n }\n }\n queue.push(...graph.getChildren(node.id))\n }\n root.locked = true\n }\n}\n\n/**\n * The components whose `ref`s a file can resolve: the library definitions its own imports give it,\n * matched to the alias and path each import names. Writing their ids as refs keeps the instances\n * linked on a reopen; the definitions themselves stay out of the file.\n */\nexport function importedComponentIds(\n graph: SceneGraph,\n imports: Readonly<Record<string, string>>\n): Set<string> {\n const ids = new Set<string>()\n const aliases = Object.entries(imports)\n if (aliases.length === 0) return ids\n const paths = new Map(aliases.map(([alias, path]) => [penLibraryId(alias), path]))\n const visit = (node: SceneNode): void => {\n const identity = node.librarySource?.identity\n if (identity && paths.get(identity.libraryId) === identity.revisionId) ids.add(node.id)\n for (const child of graph.getChildren(node.id)) visit(child)\n }\n for (const page of graph.getPages(true))\n for (const node of graph.getChildren(page.id)) visit(node)\n return ids\n}\n","import type { SceneNode } from '@pairdraw/scene-graph'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { unresolvedRef } from './plugin-data'\nimport type { PenNode } from './schema'\n\n/**\n * Layers pen.dev draws that this reader cannot: a `script` node's generated layers, a `browser`\n * node's live page, and a `ref` to a component that could not be found, such as one from a library\n * the host could not read. Each reads as a frame in its box, filled and outlined with a dashed line\n * where pen.dev gives it neither, and labelled with what it stands for when it has no layers.\n */\nconst EMBED_TYPES: ReadonlySet<string> = new Set(['script', 'browser'])\n\nconst PLACEHOLDER_FILL: Color = { r: 0.96, g: 0.96, b: 0.96, a: 1 }\nconst PLACEHOLDER_OUTLINE: Color = { r: 0.62, g: 0.62, b: 0.62, a: 1 }\nconst PLACEHOLDER_DASH = [4, 4]\n/** Room around the label, inside the outline. */\nconst PLACEHOLDER_INSET = 8\nconst LABEL_SIZE = 12\nconst LABEL_COLOR = '#737373'\n\n/** Whether a layer reads as a placeholder. */\nexport function isPlaceholder(pen: PenNode): boolean {\n return EMBED_TYPES.has(pen.type) || unresolvedRef(pen) !== undefined\n}\n\n/**\n * Fills and outlines a placeholder where pen.dev gives it no paint of its own, insets an auto\n * layout's content, and clips a script or browser frame to its box, as pen.dev shows them.\n */\nexport function applyPlaceholderLook(node: SceneNode, pen: PenNode): void {\n if (pen.fill === undefined) {\n node.fills = [{ type: 'SOLID', color: { ...PLACEHOLDER_FILL }, opacity: 1, visible: true }]\n }\n if (node.strokes.length === 0) {\n node.strokes = [\n {\n type: 'SOLID',\n color: { ...PLACEHOLDER_OUTLINE },\n opacity: 1,\n visible: true,\n weight: 1,\n align: 'INSIDE',\n dashPattern: [...PLACEHOLDER_DASH]\n }\n ]\n }\n if (pen.padding === undefined && node.layoutMode !== 'NONE') {\n node.paddingTop = PLACEHOLDER_INSET\n node.paddingRight = PLACEHOLDER_INSET\n node.paddingBottom = PLACEHOLDER_INSET\n node.paddingLeft = PLACEHOLDER_INSET\n }\n if (EMBED_TYPES.has(pen.type) && pen.clip === undefined) node.clipsContent = true\n}\n\n/** What a placeholder stands for: its file, its page, or the component it names. */\nfunction labelText(pen: PenNode): string {\n const missing = unresolvedRef(pen)\n if (missing !== undefined) return missing || (pen.name ?? 'ref')\n if (pen.type === 'script' && pen.scriptUri) return pen.scriptUri\n if (pen.type === 'browser' && pen.url) return pen.url\n return pen.name ?? pen.type\n}\n\n/**\n * The label a placeholder without layers of its own shows, as a text layer; none for one with\n * layers, such as a script node pen.dev saved with what it generated. The label says it was\n * generated, so a writer can leave it out.\n */\nexport function placeholderLabel(pen: PenNode, nodeId: string): PenNode | undefined {\n if (!isPlaceholder(pen) || (pen.children?.length ?? 0) > 0) return undefined\n const text = labelText(pen)\n return {\n id: `${nodeId}#label`,\n type: 'text',\n name: text,\n content: text,\n fontSize: LABEL_SIZE,\n fill: LABEL_COLOR,\n x: PLACEHOLDER_INSET,\n y: PLACEHOLDER_INSET,\n generated: 'placeholder'\n }\n}\n","import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { localTransformFromWorld } from '@pairdraw/scene-graph/coordinate'\nimport { fitEnclosingGroups } from '@pairdraw/scene-graph/group-bounds'\nimport Matrix from '@pairdraw/scene-graph/matrix'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\n/**\n * Where pen.dev puts a layer: at `x`, `y` in its parent, turned `rotation` degrees\n * counter-clockwise and then mirrored, both about that corner. The scene graph turns clockwise and\n * mirrors about a layer's centre, so a layer's position depends on its final size and is set after\n * layout. Measured against pen.dev 2.21 renders of turned, mirrored, and grouped layers.\n */\nexport interface PenPlacement {\n x: number\n y: number\n rotation: number\n flipX: boolean\n flipY: boolean\n}\n\nexport function isPlain(placement: PenPlacement): boolean {\n return placement.rotation === 0 && !placement.flipX && !placement.flipY\n}\n\nfunction inFlow(graph: SceneGraph, node: SceneNode): boolean {\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n return !!parent && parent.layoutMode !== 'NONE' && node.layoutPositioning !== 'ABSOLUTE'\n}\n\n/** 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. */\nfunction place(\n graph: SceneGraph,\n node: SceneNode,\n placement: PenPlacement,\n offset: Vector = { x: 0, y: 0 }\n) {\n const world = Matrix.multiply(\n Matrix.translated(placement.x, placement.y),\n Matrix.rotated((-placement.rotation * Math.PI) / 180),\n Matrix.scaled(placement.flipX ? -1 : 1, placement.flipY ? -1 : 1),\n Matrix.translated(offset.x, offset.y)\n )\n const local = localTransformFromWorld(\n { ...node, flipX: placement.flipX },\n world,\n Matrix.identity()\n )\n if (!local) return\n // Auto layout places the layers in its flow; only their turn and mirroring carry over.\n if (inFlow(graph, node)) graph.updateNode(node.id, { ...local, x: node.x, y: node.y })\n else graph.updateNode(node.id, local)\n}\n\n/**\n * Places every turned or mirrored layer, which the reader builds upright. Then each group, inner\n * ones first, is fitted to its placed layers and placed itself; its box starts at its layers'\n * bounds, wherever pen.dev's starts. `groupIds` is in reading order.\n */\nexport function placeLayers(\n graph: SceneGraph,\n placements: ReadonlyMap<string, PenPlacement>,\n groupIds: readonly string[]\n): void {\n const groups = new Set(groupIds)\n for (const [id, placement] of placements) {\n const node = graph.getNode(id)\n if (node && !groups.has(id) && !isPlain(placement)) place(graph, node, placement)\n }\n\n const origins = new Map<string, Vector>()\n for (const id of groupIds) {\n const group = graph.getNode(id)\n if (group) origins.set(id, { x: group.x, y: group.y })\n }\n // Reading order lists a group before the groups inside it, so reversed it is innermost first.\n for (const id of groupIds.toReversed()) {\n fitEnclosingGroups(graph, [id])\n const node = graph.getNode(id)\n const origin = origins.get(id)\n const placement = placements.get(id)\n if (!node || !origin || !placement || isPlain(placement)) continue\n place(graph, node, placement, { x: node.x - origin.x, y: node.y - origin.y })\n }\n}\n","import type { SceneNode } from '@pairdraw/scene-graph'\nimport { createComponentPropertyId } from '@pairdraw/scene-graph/components'\nimport {\n canCreateSlot,\n claimSlotContent,\n createSlotProperty,\n slotOwner,\n slotScope,\n updateSlotProperty\n} from '@pairdraw/scene-graph/slots'\n\nimport type { Build } from './nodes'\nimport type { PenNode } from './schema'\n\n/**\n * Makes a frame pen.dev marks with `slot` a slot of the component it is in, suggesting the\n * components it lists that the document defines. A frame outside a component has no slot to be.\n */\nexport function createPenSlot(node: SceneNode, pen: PenNode, build: Build): void {\n const { graph, components } = build\n if (!Array.isArray(pen.slot) || !canCreateSlot(graph, node)) return\n const definition = createSlotProperty(graph, node.id, createComponentPropertyId())\n const owner = slotOwner(graph, node)\n if (!definition || !owner) return\n const preferredValues = pen.slot.filter((id) => components.get(id)?.type === 'frame')\n if (preferredValues.length > 0)\n updateSlotProperty(graph, owner.id, definition.id, { preferredValues })\n}\n\n/**\n * Lets `instance` own the content of the slot frame `target`, which an override of its is about\n * to fill, as filling a slot in pen.dev keeps the instance. Returns false when `target` is not a\n * slot of that very instance, whose layers the override must then replace.\n */\nexport function claimSlot(build: Build, instance: SceneNode, target: SceneNode): boolean {\n const scope = slotScope(build.graph, target.id)\n if (scope.kind !== 'slot' || scope.frame.id !== target.id || scope.instance.id !== instance.id)\n return false\n claimSlotContent(build.graph, scope)\n return true\n}\n","import { omit } from 'es-toolkit'\n\nimport type { SceneNode, StyleRun, TextAlignVertical, TextAutoResize } from '@pairdraw/scene-graph'\nimport { parseFontStyle, type FontFamilyStyle } from '@pairdraw/scene-graph/font-style'\nimport { percentLength, pixelLength } from '@pairdraw/scene-graph/text'\n\nimport type { PenNode } from './schema'\nimport { bindIfVar, isVarRef, resolveNumber, resolveString, type VarContext } from './variables'\n\nconst FONT_WEIGHTS: Partial<Record<string, number>> = {\n thin: 100,\n extralight: 200,\n light: 300,\n normal: 400,\n regular: 400,\n medium: 500,\n semibold: 600,\n bold: 700,\n extrabold: 800,\n black: 900\n}\n\n/** pen.dev writes weights as numbers in strings, such as \"700\"; older files use names. */\nfunction fontWeight(value: PenNode['fontWeight'], ctx: VarContext): number {\n if (value === undefined) return 400\n if (typeof value === 'number') return value\n const named = isVarRef(value) ? ctx.resolveString(value) || ctx.resolveNumber(value) : value\n const numeric = Number(named)\n if (Number.isFinite(numeric) && numeric > 0) return numeric\n return FONT_WEIGHTS[String(named).toLowerCase()] ?? 400\n}\n\nconst TEXT_ALIGN: Partial<Record<string, SceneNode['textAlignHorizontal']>> = {\n left: 'LEFT',\n center: 'CENTER',\n right: 'RIGHT',\n justify: 'JUSTIFIED'\n}\n\nconst TEXT_ALIGN_VERTICAL: Partial<Record<string, TextAlignVertical>> = {\n top: 'TOP',\n middle: 'CENTER',\n bottom: 'BOTTOM'\n}\n\n/**\n * `auto` grows on one line, `fixed-width` wraps and grows down, and `fixed-width-height` wraps in\n * a fixed box its text may overflow.\n */\nconst TEXT_GROWTH: Partial<Record<string, TextAutoResize>> = {\n auto: 'WIDTH_AND_HEIGHT',\n 'fixed-width': 'HEIGHT',\n 'fixed-width-height': 'NONE'\n}\n\n/**\n * A text layer's content and style. Content that reads like a variable reference stays as written,\n * as pen.dev shows it. pen.dev 2.21 draws no underline, strikethrough, or text stroke, so those\n * are left out to match it. An `href` is kept as a link, drawn without an underline.\n */\nexport function applyTextProps(\n node: SceneNode,\n pen: PenNode,\n ctx: VarContext,\n fonts: ReadonlyMap<string, FontFamilyStyle>\n): void {\n const isIconFont = pen.type === 'icon_font'\n node.text = isIconFont ? (pen.iconFontName ?? '') : (pen.content ?? '')\n node.fontFamily = isIconFont\n ? (pen.iconFontFamily ?? 'Material Symbols Sharp')\n : (resolveString(pen.fontFamily, ctx) ?? 'Inter')\n bindIfVar(node, 'fontFamily', pen.fontFamily, ctx)\n node.fontSize = resolveNumber(pen.fontSize, ctx, 14)\n bindIfVar(node, 'fontSize', pen.fontSize, ctx)\n const weight = pen.fontWeight ?? (isIconFont ? pen.weight : undefined)\n node.fontWeight = fontWeight(weight, ctx)\n bindIfVar(node, 'fontWeight', weight, ctx)\n node.italic = resolveString(pen.fontStyle, ctx)?.toLowerCase() === 'italic'\n // A bundled font's name stands for one face of the family its file names.\n const bundled = isIconFont ? undefined : fonts.get(node.fontFamily)\n if (bundled) {\n const { weight, italic } = parseFontStyle(bundled.style)\n Object.assign(node, {\n fontFamily: bundled.family,\n fontStyle: bundled.style,\n fontWeight: weight,\n italic\n })\n // The bound name is the pen-only one no font is registered under, so a later reconcile\n // would restore a family nothing draws with. The bundled face owns the family now.\n node.boundVariables = omit(node.boundVariables, ['fontFamily'])\n }\n node.textAlignHorizontal = TEXT_ALIGN[pen.textAlign ?? 'left'] ?? 'LEFT'\n node.textAlignVertical = TEXT_ALIGN_VERTICAL[pen.textAlignVertical ?? 'top'] ?? 'TOP'\n // pen.dev's line height multiplies the font size, so it follows the size as a percent.\n if (pen.lineHeight !== undefined) {\n node.lineHeight = percentLength(resolveNumber(pen.lineHeight, ctx) * 100)\n }\n if (pen.letterSpacing !== undefined) {\n node.letterSpacing = pixelLength(resolveNumber(pen.letterSpacing, ctx))\n }\n node.textAutoResize = TEXT_GROWTH[pen.textGrowth ?? 'auto'] ?? 'WIDTH_AND_HEIGHT'\n // pen.dev draws every font at its default optical size, whatever the text's size.\n node.opticalSizeFromFontSize = false\n node.strokes = []\n node.styleRuns = textLink(pen, node.text, ctx)\n}\n\n/** A text's `href` links all of its characters, as one run. */\nfunction textLink(pen: PenNode, text: string, ctx: VarContext): StyleRun[] {\n const href = pen.type === 'text' ? resolveString(pen.href ?? undefined, ctx)?.trim() : undefined\n if (!href || text.length === 0) return []\n return [{ start: 0, length: text.length, style: { hyperlink: { type: 'URL', value: href } } }]\n}\n","import type {\n AxisSizingMode,\n LayoutMode,\n LayoutSizing,\n NodeType,\n SceneGraph,\n SceneNode\n} from '@pairdraw/scene-graph'\nimport { normalizeEffects } from '@pairdraw/scene-graph/effects'\nimport { CORNER_FIELDS } from '@pairdraw/scene-graph/fields'\nimport type { FontFamilyStyle } from '@pairdraw/scene-graph/font-style'\nimport { fillSizingFields } from '@pairdraw/scene-graph/layout'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { ANNOTATION_TYPES, applyAnnotation, createAnnotation, isAnnotation } from './annotations'\nimport { convertEffects } from './effects'\nimport { ellipseArc } from './geometry'\nimport { drawIcon, insideComponent, useIconComponent } from './icons'\nimport type { PenImages } from './images'\nimport {\n applyCornerRadius,\n applyPadding,\n mapAlignItems,\n mapJustifyContent,\n mapLayoutMode,\n parseSize\n} from './layout'\nimport { applyStroke, convertPaints, strokeFields, type PenShaderSources } from './paints'\nimport { applyPlaceholderLook, isPlaceholder, placeholderLabel } from './placeholders'\nimport { isPlain, type PenPlacement } from './placement'\nimport { applyPenPluginData, UNRESOLVED_REF } from './plugin-data'\nimport type { NodeFields, PenNode, PenOverride } from './schema'\nimport { createPenSlot } from './slots'\nimport { applyTextProps } from './text'\nimport { bindIfVar, resolveBoolean, resolveNumber, type VarContext } from './variables'\n\n/** Where icon glyphs come from, as the host loaded them. */\nexport interface PenIconSource {\n /**\n * Draws the icon `name` into the frame, `size` square at its origin, painted `color` where the\n * icon takes its colour and drawn with `options` where its set has them. False when the source\n * does not have it.\n */\n draw(\n graph: SceneGraph,\n frameId: string,\n name: string,\n size: number,\n color: Color,\n options?: Record<string, number>\n ): boolean\n}\n\n/** What reading one document builds up. */\nexport interface Build {\n graph: SceneGraph\n ctx: VarContext\n images: PenImages\n /** Shader files the document's paints and effects name, by URL, as their source. */\n shaders: PenShaderSources | undefined\n icons: PenIconSource | undefined\n /** The family and style of each font the document bundles, by the name its text gives it. */\n fonts: ReadonlyMap<string, FontFamilyStyle>\n /** Reusable nodes by their pen.dev ID. */\n components: Map<string, PenNode>\n /** The pen.dev fields each layer was built from, its instance's and overrides' merged in. */\n effective: Map<string, PenNode>\n /** Instances in reading order, with the `ref` node that made each. */\n instances: Map<string, PenNode>\n /** pen.dev's placement of each turned or mirrored layer, and of every group. */\n placements: Map<string, PenPlacement>\n /** Groups in reading order. */\n groupIds: Set<string>\n /** Called with a node type the reader does not know. */\n onUnknownNodeType?: (type: string) => void\n /** The components icons in components are instances of, by glyph and size. */\n iconComponents: Map<string, string>\n /** The page those components are on, added with the first one. */\n iconPageId: string | null\n /** Layers whose children an override replaced, whose instances are detached. */\n replaced: Set<string>\n}\n\nfunction penPlacement(pen: PenOverride, ctx: VarContext): PenPlacement {\n return {\n x: pen.x ?? 0,\n y: pen.y ?? 0,\n rotation: resolveNumber(pen.rotation, ctx),\n flipX: resolveBoolean(pen.flipX, ctx, false),\n flipY: resolveBoolean(pen.flipY, ctx, false)\n }\n}\n\n/**\n * A `line` runs from its box's top-left corner to its bottom-right, so a line with no height is\n * a line layer and any other one a vector drawn across its box.\n */\nfunction isFlatLine(pen: PenNode, ctx: VarContext): boolean {\n const height = parseSize(pen.height, 100, ctx)\n return height.sizing === 'FIXED' && height.value === 0\n}\n\nconst KNOWN_PEN_TYPES = new Set([\n 'frame',\n 'line',\n 'rectangle',\n 'ellipse',\n 'polygon',\n 'group',\n 'text',\n 'icon_font',\n 'path',\n 'icon',\n 'sticky',\n 'ref',\n // The annotation cards read as stickies; they are known types, not placeholders.\n ...ANNOTATION_TYPES\n])\n\nfunction sceneType(pen: PenNode, ctx: VarContext, warn?: (type: string) => void): NodeType {\n if (!KNOWN_PEN_TYPES.has(pen.type)) warn?.(pen.type)\n if (pen.type === 'frame') return pen.reusable ? 'COMPONENT' : 'FRAME'\n if (pen.type === 'line') return isFlatLine(pen, ctx) ? 'LINE' : 'VECTOR'\n if (isAnnotation(pen)) return 'STICKY'\n if (pen.type === 'rectangle') return 'RECTANGLE'\n if (pen.type === 'ellipse') return 'ELLIPSE'\n if (pen.type === 'polygon') return 'POLYGON'\n if (pen.type === 'group') return 'GROUP'\n if (pen.type === 'text' || pen.type === 'icon_font') return 'TEXT'\n if (pen.type === 'path') return 'VECTOR'\n return 'FRAME'\n}\n\nfunction resolveSizing(pen: PenNode, ctx: VarContext) {\n const isTextLike = pen.type === 'text' || pen.type === 'icon_font'\n const defaultSize = isTextLike ? 20 : 100\n const defaultW = isTextLike && pen.width === undefined ? 0 : defaultSize\n const w = parseSize(pen.width, defaultW, ctx)\n const h = parseSize(pen.height, defaultSize, ctx)\n const layout = mapLayoutMode(pen)\n\n if (pen.width === undefined && layout !== 'NONE') w.sizing = 'HUG'\n if (pen.height === undefined && layout !== 'NONE') h.sizing = 'HUG'\n\n return { w, h, layout, isTextLike }\n}\n\nfunction applyAutoLayout(\n node: SceneNode,\n layoutMode: LayoutMode,\n pen: PenNode,\n widthSizing: LayoutSizing,\n heightSizing: LayoutSizing,\n ctx: VarContext\n): void {\n node.layoutMode = layoutMode\n node.primaryAxisAlign = mapJustifyContent(pen.justifyContent)\n node.counterAxisAlign = mapAlignItems(pen.alignItems)\n node.itemSpacing = resolveNumber(pen.gap, ctx)\n bindIfVar(node, 'itemSpacing', pen.gap, ctx)\n node.strokesIncludedInLayout = pen.layoutIncludeStroke ?? false\n\n // Fill is the child's grow or stretch, set with its parent; the frame itself stays fixed.\n const own = (sizing: LayoutSizing): AxisSizingMode => (sizing === 'HUG' ? 'HUG' : 'FIXED')\n if (layoutMode === 'VERTICAL') {\n node.primaryAxisSizing = own(heightSizing)\n node.counterAxisSizing = own(widthSizing)\n } else {\n node.primaryAxisSizing = own(widthSizing)\n node.counterAxisSizing = own(heightSizing)\n }\n // pen.dev keeps `gap` between children under `space_between`, as CSS does; auto layout drops it.\n // A hugging frame has no free space to spread, so packing it from the start lays it out the same.\n if (node.primaryAxisAlign === 'SPACE_BETWEEN' && node.primaryAxisSizing === 'HUG') {\n node.primaryAxisAlign = 'MIN'\n }\n}\n\nconst PLACEMENT_FIELDS = ['x', 'y', 'rotation', 'flipX', 'flipY'] as const\n\n/** What `applyStroke` writes: a stroke's weight and alignment are its paints'. */\nconst STROKE_WRITES = [\n 'strokes',\n 'independentStrokeWeights',\n 'borderTopWeight',\n 'borderRightWeight',\n 'borderBottomWeight',\n 'borderLeftWeight',\n 'strokeCap',\n 'strokeJoin'\n] as const\n\n/**\n * The layer fields each property `applyPenProperties` reads writes. A property that writes none of\n * the layer's own fields maps to none: bookkeeping, the decorations pen.dev does not draw, and an\n * icon's glyph, which is the layer's children or the component it shows.\n */\nconst PROPERTY_FIELDS = {\n name: ['name'],\n context: ['pluginData'],\n metadata: ['pluginData'],\n x: PLACEMENT_FIELDS,\n y: PLACEMENT_FIELDS,\n width: ['width'],\n height: ['height'],\n reusable: [],\n theme: ['variableModes'],\n enabled: ['visible'],\n opacity: ['opacity'],\n flipX: PLACEMENT_FIELDS,\n flipY: PLACEMENT_FIELDS,\n layoutPosition: ['layoutPositioning'],\n rotation: PLACEMENT_FIELDS,\n fill: ['fills'],\n stroke: STROKE_WRITES,\n strokeWidth: STROKE_WRITES,\n strokeLinecap: ['strokes', 'strokeCap'],\n strokeLinejoin: ['strokes', 'strokeJoin'],\n strokeAlignment: ['strokes'],\n effect: ['effects'],\n cornerRadius: CORNER_FIELDS,\n layout: ['layoutMode'],\n gap: ['itemSpacing'],\n layoutIncludeStroke: ['strokesIncludedInLayout'],\n padding: ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'],\n justifyContent: ['primaryAxisAlign'],\n alignItems: ['counterAxisAlign'],\n clip: ['clipsContent'],\n status: ['status'],\n placeholder: ['pluginData'],\n slot: ['pluginData'],\n innerRadius: ['arcData'],\n startAngle: ['arcData'],\n sweepAngle: ['arcData'],\n polygonCount: ['pointCount'],\n geometry: ['vectorNetwork'],\n fillRule: ['vectorNetwork'],\n viewBox: ['vectorNetwork'],\n content: ['text'],\n textGrowth: ['textAutoResize'],\n fontFamily: ['fontFamily'],\n fontSize: ['fontSize'],\n fontWeight: ['fontWeight'],\n fontStyle: ['italic'],\n letterSpacing: ['letterSpacing'],\n lineHeight: ['lineHeight'],\n textAlign: ['textAlignHorizontal'],\n textAlignVertical: ['textAlignVertical'],\n underline: [],\n strikethrough: [],\n href: ['styleRuns'],\n library: [],\n icon: [],\n weight: [],\n iconFontName: [],\n iconFontFamily: [],\n ref: [],\n model: ['pluginData'],\n scriptUri: ['pluginData'],\n inputs: ['pluginData'],\n url: ['pluginData'],\n deviceId: ['pluginData'],\n zoom: ['pluginData'],\n scrollX: ['pluginData'],\n scrollY: ['pluginData']\n} satisfies Record<keyof NodeFields, readonly (keyof SceneNode)[]>\n\nconst isProperty = (key: string): key is keyof typeof PROPERTY_FIELDS => key in PROPERTY_FIELDS\n\n/**\n * The fields the properties `pen` carries write, whatever their values: pen.dev keeps a property\n * an instance sets even when it equals its component's, so a later change to the component does\n * not reach it.\n */\nexport function fieldsSetBy(pen: PenOverride): (keyof SceneNode)[] {\n return Object.keys(pen).flatMap((key) => (isProperty(key) ? PROPERTY_FIELDS[key] : []))\n}\n\nfunction drawIconLayer(node: SceneNode, pen: PenNode, build: Build): void {\n if (node.type === 'INSTANCE') useIconComponent(node, pen, build)\n else drawIcon(node, pen, build)\n}\n\n/**\n * Draws a filling or fitting icon again at its laid-out size, which reading it could only guess.\n * Drawing takes the icon's colour from its fill and moves it to the glyph, so the fill is read again.\n */\nexport function redrawIconAtLaidOutSize(node: SceneNode, pen: PenNode, build: Build): void {\n const { w, h } = resolveSizing(pen, build.ctx)\n if (w.sizing === 'FIXED' && h.sizing === 'FIXED') return\n node.fills = convertPaints(pen.fill, 'fills', build.ctx, node, build.images, build.shaders)\n drawIconLayer(node, pen, build)\n}\n\n/**\n * Sets every field a layer takes from its pen.dev fields, so a layer copied from a component can be\n * given its overrides by applying its merged fields again. Turned and mirrored layers are built\n * upright and placed once laid out.\n */\n// eslint-disable-next-line complexity -- .pen node mapping touches many format-specific fields\nexport function applyPenProperties(node: SceneNode, pen: PenNode, build: Build): void {\n if (node.type === 'STICKY') {\n applyAnnotation(node, pen, build)\n return\n }\n const { graph, ctx } = build\n const { w, h, layout, isTextLike } = resolveSizing(pen, ctx)\n const hasChildren = (pen.children?.length ?? 0) > 0 || node.childIds.length > 0\n const parentLayout = (node.parentId && graph.getNode(node.parentId)?.layoutMode) || 'NONE'\n // An absolute layer leaves its parent's flow; fill sizing then falls back to its value.\n const absolute = pen.layoutPosition === 'absolute' && parentLayout !== 'NONE'\n const flowLayout = absolute ? 'NONE' : parentLayout\n\n Object.assign(node, {\n name: pen.name ?? (pen.type === 'icon_font' ? (pen.iconFontName ?? 'Icon') : pen.type),\n x: pen.x ?? 0,\n y: pen.y ?? 0,\n rotation: 0,\n flipX: false,\n flipY: false,\n width: w.value,\n height: h.value,\n minWidth: !hasChildren && w.fitContentFallback !== undefined ? w.fitContentFallback : null,\n minHeight: !hasChildren && h.fitContentFallback !== undefined ? h.fitContentFallback : null,\n visible: resolveBoolean(pen.enabled, ctx),\n opacity: resolveNumber(pen.opacity, ctx, 1),\n clipsContent: resolveBoolean(pen.clip, ctx, false),\n status: pen.status ?? null,\n layoutPositioning: absolute ? 'ABSOLUTE' : 'AUTO',\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO',\n boundVariables: {},\n variableModes: pen.theme ? ctx.variableModes(pen.theme) : {}\n } satisfies Partial<SceneNode>)\n bindIfVar(node, 'visible', pen.enabled, ctx)\n bindIfVar(node, 'opacity', pen.opacity, ctx)\n bindIfVar(node, 'width', pen.width, ctx)\n bindIfVar(node, 'height', pen.height, ctx)\n\n node.layoutMode = 'NONE'\n if (layout !== 'NONE') {\n const widthSizing = flowLayout === 'NONE' && w.sizing === 'FILL' ? 'FIXED' : w.sizing\n const heightSizing = flowLayout === 'NONE' && h.sizing === 'FILL' ? 'FIXED' : h.sizing\n applyAutoLayout(node, layout, pen, widthSizing, heightSizing, ctx)\n }\n\n const placement = penPlacement(pen, ctx)\n if (pen.type === 'group') build.groupIds.add(node.id)\n if (pen.type === 'group' || !isPlain(placement)) build.placements.set(node.id, placement)\n else build.placements.delete(node.id)\n\n node.fills = convertPaints(pen.fill, 'fills', ctx, node, build.images, build.shaders)\n applyStroke(node, strokeFields(pen), ctx, build.images, build.shaders)\n // A line layer has no inside or outside; its stroke is centred on it.\n if (node.type === 'LINE')\n node.strokes = node.strokes.map((paint) => ({ ...paint, align: 'CENTER' }))\n node.effects = normalizeEffects(convertEffects(pen.effect, ctx, build.shaders))\n applyCornerRadius(node, pen.cornerRadius, ctx)\n applyPadding(node, pen.padding, ctx)\n\n // Text without a width resizes to its content, which laying out the document measures.\n if (isTextLike) applyTextProps(node, pen, ctx, build.fonts)\n\n if (pen.type === 'icon') drawIconLayer(node, pen, build)\n if (pen.type === 'ellipse') node.arcData = ellipseArc(pen, ctx)\n if (pen.type === 'polygon') node.pointCount = Math.max(3, resolveNumber(pen.polygonCount, ctx, 3))\n\n if (flowLayout !== 'NONE') {\n if (w.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'HORIZONTAL'))\n if (h.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'VERTICAL'))\n }\n if (isPlaceholder(pen)) applyPlaceholderLook(node, pen)\n applyPenPluginData(node, pen)\n build.effective.set(node.id, pen)\n}\n\n/**\n * The fields an instance draws with: its component's, with the `ref` node's own replacing them one\n * by one, as pen.dev reads them. A theme on both merges axis by axis. A `ref` whose component is\n * missing, such as one from a library the host could not read, is a placeholder naming it.\n */\nfunction instanceFields(ref: PenNode, component: PenNode | undefined): PenNode {\n const { ref: _ref, type: _type, descendants: _descendants, children: _children, ...own } = ref\n if (!component) return { ...own, type: 'frame', [UNRESOLVED_REF]: ref.ref ?? '' }\n const {\n id: _id,\n reusable: _reusable,\n ref: _componentRef,\n children: _componentChildren,\n descendants: _componentDescendants,\n ...inherited\n } = component\n const theme = component.theme || ref.theme ? { ...component.theme, ...ref.theme } : undefined\n return { ...inherited, ...own, theme, name: ref.name ?? component.name }\n}\n\n/**\n * Builds the layers inside a layer that is no instance: a `ref`'s copies of its component's, named\n * by the path to them, or the layer's own, then a placeholder's label and a slot.\n */\nfunction createChildren(node: SceneNode, pen: PenNode, fields: PenNode, build: Build): void {\n const component = pen.type === 'ref' && pen.ref ? build.components.get(pen.ref) : undefined\n const children = pen.type === 'ref' ? (component?.children ?? []) : (pen.children ?? [])\n for (const child of children) {\n createSceneNode(\n pen.type === 'ref' ? { ...child, id: `${pen.id}/${child.id}` } : child,\n node.id,\n build\n )\n }\n const label = placeholderLabel(fields, node.id)\n if (label) createSceneNode(label, node.id, build)\n createPenSlot(node, fields, build)\n}\n\n/** Builds a layer and its children in the layer's theme, merged over its parent's. */\nexport function createSceneNode(pen: PenNode, parentId: string, build: Build): string {\n const component = pen.type === 'ref' && pen.ref ? build.components.get(pen.ref) : undefined\n // A component that is not a frame has no instances; its uses are plain copies.\n const instanceOf = pen.type === 'ref' && component?.type === 'frame' ? component : undefined\n const fields = pen.type === 'ref' ? instanceFields(pen, component) : pen\n const iconInstance = fields.type === 'icon' && insideComponent(build.graph, parentId)\n const leaveTheme = fields.theme ? build.ctx.enterTheme(fields.theme) : undefined\n try {\n const type =\n instanceOf || iconInstance\n ? 'INSTANCE'\n : sceneType(fields, build.ctx, build.onUnknownNodeType)\n // An ID a hand-edited file repeats gets a fresh one, so the layer does not replace the first\n // layer with it or become its own parent.\n const id = build.graph.getNode(pen.id) ? build.graph.entityIdMinter()() : pen.id\n const node =\n type === 'STICKY'\n ? createAnnotation({ ...fields, id }, parentId, build)\n : build.graph.createNode(type, parentId, { id })\n applyPenProperties(node, fields, build)\n if (instanceOf) {\n node.componentId = instanceOf.id\n build.instances.set(node.id, pen)\n } else {\n createChildren(node, pen, fields, build)\n }\n return node.id\n } finally {\n leaveTheme?.()\n }\n}\n","import { pick } from 'es-toolkit/object'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport { generateId, type SceneGraph, type SceneNode } from '@pairdraw/scene-graph'\nimport {\n detachInstance,\n INSTANCE_OVERRIDE_FIELDS,\n populateInstanceChildren,\n recordInstanceOverride,\n swapInstanceComponent\n} from '@pairdraw/scene-graph/instances'\n\nimport { applyPenProperties, createSceneNode, fieldsSetBy, type Build } from './nodes'\nimport type { PenNode, PenOverride } from './schema'\nimport { claimSlot } from './slots'\n\n/** Fills an instance read from `.pen`, after the instances inside its component. */\ntype Populate = (id: string) => void\n\n/** The layers a copy was made from, nearest first, through copies of copies. */\nfunction sources(graph: SceneGraph, node: SceneNode): Set<string> {\n const found = new Set<string>()\n for (\n let id = node.componentId;\n id && !found.has(id);\n id = graph.getNode(id)?.componentId ?? null\n ) {\n found.add(id)\n }\n return found\n}\n\n/** The pen.dev layer a layer was built from, which a component swap stops naming. */\nfunction penLayerId(build: Build, node: SceneNode): string | undefined {\n return build.effective.get(node.id)?.id\n}\n\n/** The copy in `root`'s layers made from the pen.dev layer `sourceId`, at any depth. */\nfunction findCopy(build: Build, root: SceneNode, sourceId: string): SceneNode | undefined {\n const { graph } = build\n const queue = graph.getChildren(root.id)\n for (const node of queue) {\n if (penLayerId(build, node) === sourceId || sources(graph, node).has(sourceId)) return node\n queue.push(...graph.getChildren(node.id))\n }\n return undefined\n}\n\n/**\n * The layer an override's key names: pen.dev IDs separated by `/`, each one inside the copy of the\n * instance the one before it names.\n */\nfunction resolvePath(build: Build, instance: SceneNode, path: string): SceneNode | undefined {\n let current: SceneNode | undefined = instance\n for (const id of path.split('/')) {\n current = current ? findCopy(build, current, id) : undefined\n }\n return current\n}\n\n/** Runs `apply` in the merged theme of a layer's ancestors, as the layer was read in. */\nexport function inAncestorThemes<T>(build: Build, node: SceneNode, apply: () => T): T {\n const chain: Record<string, string>[] = []\n for (let id = node.parentId; id; id = build.graph.getNode(id)?.parentId ?? null) {\n const theme = build.effective.get(id)?.theme\n if (theme) chain.unshift(theme)\n }\n const leave = chain.map((theme) => build.ctx.enterTheme(theme))\n try {\n return apply()\n } finally {\n for (const exit of leave.toReversed()) exit()\n }\n}\n\nfunction replaceLayer(\n build: Build,\n target: SceneNode,\n replacement: PenOverride,\n populate: Populate\n): void {\n const { graph } = build\n const parentId = target.parentId\n if (!parentId) return\n if (swapLayer(build, target, replacement, populate)) return\n const index = graph.getNode(parentId)?.childIds.indexOf(target.id) ?? -1\n const pen: PenNode = {\n ...replacement,\n type: replacement.type ?? 'frame',\n id: replacement.id ?? generateId()\n }\n inAncestorThemes(build, target, () => {\n graph.deleteNode(target.id)\n const id = createSceneNode(pen, parentId, build)\n if (id && index >= 0) graph.insertChildAt(id, parentId, index)\n // The parent's layers changed; a replacement that is itself an instance stays one.\n if (id) build.replaced.add(parentId)\n })\n}\n\n/**\n * Swaps a nested instance an override replaces with an instance of another component for that\n * component, as Figma's instance swap does, so the instances holding it stay instances. The\n * replacement's own fields and overrides then apply to the swapped layer. Returns whether it\n * swapped; any other replacement changes the layers of the instance holding it.\n */\nfunction swapLayer(\n build: Build,\n target: SceneNode,\n replacement: PenOverride,\n populate: Populate\n): boolean {\n const { graph, effective, instances } = build\n const component =\n typeof replacement.ref === 'string' ? build.components.get(replacement.ref) : undefined\n if (target.type !== 'INSTANCE' || replacement.type !== 'ref' || component?.type !== 'frame')\n return false\n for (const nested of instances.keys()) {\n if (graph.isDescendant(nested, component.id)) populate(nested)\n }\n swapInstanceComponent(graph, target.id, component.id)\n if (graph.getNode(target.id)?.componentId !== component.id) return false\n const {\n children: _children,\n reusable: _reusable,\n descendants: _descendants,\n ...fields\n } = component\n effective.set(target.id, { ...fields, id: target.id })\n inheritCopyFields(build, target)\n const { ref: _ref, type: _type, id: _id, descendants, ...own } = replacement\n overrideLayer(build, target, own)\n applyDescendants(build, target, descendants, populate)\n return true\n}\n\n/**\n * Records as the instance's overrides the fields an override set or changed on a copy, so they\n * survive the instance's next sync and a save, as an edit made in the editor would.\n */\nfunction recordChangedFields(\n graph: SceneGraph,\n target: SceneNode,\n before: Partial<SceneNode>,\n override: PenOverride\n): void {\n const changed = INSTANCE_OVERRIDE_FIELDS.filter((field) => !isEqual(before[field], target[field]))\n recordInstanceOverride(graph, target.id, [...changed, ...fieldsSetBy(override)])\n}\n\n/**\n * Records as the instance's own overrides the fields its `ref` sets or makes differ from its\n * component's. A size counts only when the `ref` sets it: otherwise it is the layout's, which\n * follows the component's.\n */\nfunction recordOwnFields(graph: SceneGraph, instance: SceneNode, ref: PenNode): void {\n const component = instance.componentId ? graph.getNode(instance.componentId) : undefined\n if (!component) return\n const changed = INSTANCE_OVERRIDE_FIELDS.filter(\n (field) =>\n (field !== 'width' || 'width' in ref) &&\n (field !== 'height' || 'height' in ref) &&\n !isEqual(instance[field], component[field])\n )\n recordInstanceOverride(graph, instance.id, [...changed, ...fieldsSetBy(ref)])\n}\n\n/**\n * Gives a copy an override's fields. Children the override gives a slot of `instance` become the\n * instance's content for that slot; any other layer's children are replaced, which detaches the\n * instances holding it.\n */\nfunction overrideLayer(\n build: Build,\n target: SceneNode,\n override: PenOverride,\n instance?: SceneNode\n): void {\n const { graph, ctx, effective } = build\n const base = effective.get(target.id) ?? { type: 'frame', id: target.id }\n const { descendants: _descendants, children, ...fields } = override\n const merged: PenNode = { ...base, ...fields, type: base.type, id: base.id }\n const before = structuredClone(pick(target, INSTANCE_OVERRIDE_FIELDS))\n inAncestorThemes(build, target, () => {\n const leave = merged.theme ? ctx.enterTheme(merged.theme) : undefined\n try {\n // Children that replace the layer's own decide its size, as a fit_content(N) fallback holds\n // only while the layer is empty, so the old ones go first.\n if (children) for (const childId of target.childIds) graph.deleteNode(childId)\n applyPenProperties(target, children ? { ...merged, children } : merged, build)\n recordChangedFields(graph, target, before, fields)\n if (children) {\n const fillsSlot = instance !== undefined && claimSlot(build, instance, target)\n for (const child of children) createSceneNode(child, target.id, build)\n if (!fillsSlot) build.replaced.add(target.id)\n }\n } finally {\n leave?.()\n }\n })\n}\n\n/**\n * Detaches the instances holding a layer whose children an override replaced. An instance keeps\n * its component's layers, overriding their fields but never replacing them, so such an instance\n * becomes a frame that keeps what it shows, as detaching it in Figma does.\n */\nfunction detachReplacingInstances(build: Build): void {\n const { graph } = build\n for (const id of build.replaced) {\n for (let node = graph.getNode(id); node;) {\n if (node.type === 'INSTANCE') detachInstance(graph, node.id)\n node = node.parentId ? graph.getNode(node.parentId) : undefined\n }\n }\n build.replaced.clear()\n}\n\n/** Gives an instance's copies their overrides; a key with a `type` replaces the layer. */\nfunction applyDescendants(\n build: Build,\n instance: SceneNode,\n descendants: PenNode['descendants'],\n populate: Populate\n): void {\n for (const [path, override] of Object.entries(descendants ?? {})) {\n const target = resolvePath(build, instance, path)\n if (!target) continue\n if (override.type) replaceLayer(build, target, override, populate)\n else overrideLayer(build, target, override, instance)\n }\n}\n\n/** Gives each copy inside `root` the pen.dev fields and placement of the layer it copies. */\nfunction inheritCopyFields(build: Build, root: SceneNode): void {\n const { graph, effective, placements } = build\n const copies = graph.getChildren(root.id)\n for (const copy of copies) {\n const source = copy.componentId\n const fields = source ? effective.get(source) : undefined\n if (fields) effective.set(copy.id, fields)\n const placement = source ? placements.get(source) : undefined\n if (placement) placements.set(copy.id, placement)\n if (source && build.groupIds.has(source)) build.groupIds.add(copy.id)\n copies.push(...graph.getChildren(copy.id))\n }\n}\n\n/**\n * Fills each instance with copies of its component's layers, then applies its overrides. An\n * instance inside a component is filled first, so the copies made of it carry its layers and\n * overrides; a copy keeps its source's pen.dev fields and placement.\n */\nexport function populateInstances(build: Build): void {\n const { graph, instances } = build\n const done = new Set<string>()\n\n function populate(id: string): void {\n if (done.has(id)) return\n done.add(id)\n const instance = graph.getNode(id)\n const ref = instances.get(id)\n if (!instance?.componentId || !ref) return\n const component = graph.getNode(instance.componentId)\n if (!component) return\n for (const nested of instances.keys()) {\n if (graph.isDescendant(nested, component.id)) populate(nested)\n }\n populateInstanceChildren(graph, instance.id, component.id)\n recordOwnFields(graph, instance, ref)\n inheritCopyFields(build, instance)\n applyDescendants(build, instance, ref.descendants, populate)\n // pen.dev draws a ref's own children in place of its component's, whether or not the\n // component declares a `slot`; like an override's children, they detach the instance.\n if (ref.children) overrideLayer(build, instance, { children: ref.children })\n // Before anything copies this instance, so the copies are of what it became.\n detachReplacingInstances(build)\n }\n\n // A replacement may hold instances of its own, which join the map as they are read.\n for (const id of instances.keys()) populate(id)\n}\n","import * as v from 'valibot'\n\nimport { SceneGraph } from '@pairdraw/scene-graph'\nimport { writeDesignMemory } from '@pairdraw/scene-graph/design-memory'\nimport type { FontFamilyStyle } from '@pairdraw/scene-graph/font-style'\nimport { writeStatusWorkflow } from '@pairdraw/scene-graph/statuses'\nimport { rekeyTokenSources, tokenSourcesPluginData } from '@pairdraw/scene-graph/token-sources'\n\nimport { writeLibraryLinks } from './document-libraries'\nimport { lineNetwork, pathNetwork } from './geometry'\nimport { removeUnusedIconComponents } from './icons'\nimport { createImageStore } from './images'\nimport { withImports, type PenImports } from './imports'\nimport { inAncestorThemes, populateInstances } from './instances'\nimport { createLibraryRoots, markLibraryRoots } from './library'\nimport { createSceneNode, redrawIconAtLaidOutSize, type Build, type PenIconSource } from './nodes'\nimport { placeLayers } from './placement'\nimport { penFileSchema, type PenDocument, type PenNode } from './schema'\nimport { buildVarContext } from './variables'\n\n/** Options for reading a document. */\nexport interface PenReadOptions {\n /**\n * Lays out the graph's auto layout and text, as `layoutAuthoredNodes` in Core does. Turned and\n * mirrored layers are placed after it, since where they land depends on their final size.\n */\n layout?(graph: SceneGraph): void\n /** The image files the document's paints name, by their URL in it; see `penAssets`. */\n images?: ReadonlyMap<string, Uint8Array>\n /**\n * The shader files the document's paints and effects name, by their URL in it, as their source\n * text; see `penAssets`. A shader whose file is missing draws nothing.\n */\n shaders?: ReadonlyMap<string, string>\n /** Where icon glyphs come from; icons are empty frames without it. */\n icons?: PenIconSource\n /**\n * The family and style each bundled font file names itself with, by its `name` in the\n * document's `fonts`. pen.dev registers a bundled file under that name, such as\n * `Geist-SemiBold`, and its text uses it as the family; the text takes the file's own names.\n */\n fonts?: ReadonlyMap<string, FontFamilyStyle>\n /**\n * The documents the document imports, by alias, as `importedDocument` gives them. Their\n * variables join the document's as `<alias>:<name>`, and the components it uses, as\n * `<alias>:<id>`, go on the hidden library page as read-only library definitions. A `ref` to a\n * component no import has reads as a placeholder.\n */\n imports?: PenImports\n /** Called with a variable a layer references that the document does not define. */\n onUnknownVariable?(name: string): void\n /** Called with a node type the reader does not know, which reads as a placeholder frame. */\n onUnknownNodeType?(type: string): void\n}\n\nfunction collectComponents(nodes: PenNode[], components: Map<string, PenNode>): void {\n for (const node of nodes) {\n if (node.reusable) components.set(node.id, node)\n if (node.children) collectComponents(node.children, components)\n }\n}\n\n/** Whether a group sits in an auto layout's flow, where fitting it changes the layout. */\nfunction groupsInFlow(graph: SceneGraph, groupIds: Iterable<string>): boolean {\n for (const id of groupIds) {\n const group = graph.getNode(id)\n const parent = group?.parentId ? graph.getNode(group.parentId) : undefined\n if (parent && parent.layoutMode !== 'NONE') return true\n }\n return false\n}\n\n/**\n * Draws each path and slanted line in its box once boxes have their final size, which fill and\n * fit sizing only give once laid out, and redraws each icon laying out sized.\n */\nfunction drawAtFinalSize(build: Build, laidOut: boolean): void {\n for (const [id, pen] of build.effective) {\n const node = build.graph.getNode(id)\n if (!node) continue\n if (pen.type === 'path') {\n const network = pathNetwork(pen, node.width, node.height)\n if (network) node.vectorNetwork = network\n } else if (pen.type === 'line' && node.type === 'VECTOR') {\n node.vectorNetwork = lineNetwork(node.width, node.height)\n } else if (pen.type === 'icon' && laidOut) {\n // In the themes the icon was read in, which its colour and glyph may take variables from.\n inAncestorThemes(build, node, () => {\n const leave = pen.theme ? build.ctx.enterTheme(pen.theme) : undefined\n try {\n redrawIconAtLaidOutSize(node, pen, build)\n } finally {\n leave?.()\n }\n })\n }\n }\n}\n\n/** A `.pen` document's JSON, validated; throws for text that is not one. */\nexport function parsePenDocument(json: string): PenDocument {\n const parsed = v.safeParse(penFileSchema, json)\n if (!parsed.success) {\n throw new Error(`Not a .pen document: ${v.summarize(parsed.issues)}`)\n }\n return parsed.output\n}\n\n/** Builds the scene graph of a document `parsePenDocument` read. */\nexport function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): SceneGraph {\n const graph = new SceneGraph()\n\n for (const page of graph.getPages(true)) {\n graph.deleteNode(page.id)\n }\n\n const imports: PenImports = options.imports ?? new Map()\n const build: Build = {\n graph,\n ctx: buildVarContext(graph, withImports(doc, imports), (name) =>\n options.onUnknownVariable?.(name)\n ),\n images: createImageStore(graph, options.images),\n shaders: options.shaders,\n icons: options.icons,\n fonts: options.fonts ?? new Map(),\n components: new Map(),\n effective: new Map(),\n instances: new Map(),\n placements: new Map(),\n groupIds: new Set(),\n iconComponents: new Map(),\n iconPageId: null,\n replaced: new Set(),\n onUnknownNodeType: (type) => options.onUnknownNodeType?.(type)\n }\n collectComponents(doc.children, build.components)\n for (const imported of imports.values())\n collectComponents(imported.doc.children, build.components)\n\n const page = graph.addPage(doc.name ?? doc.children[0]?.name ?? 'Page 1')\n for (const child of doc.children) createSceneNode(child, page.id, build)\n const libraryRoots = createLibraryRoots(doc, imports, build, createSceneNode)\n populateInstances(build)\n\n options.layout?.(graph)\n drawAtFinalSize(build, options.layout !== undefined)\n placeLayers(graph, build.placements, [...build.groupIds])\n if (options.layout && groupsInFlow(graph, build.groupIds)) {\n options.layout(graph)\n drawAtFinalSize(build, true)\n }\n removeUnusedIconComponents(build)\n markLibraryRoots(graph, libraryRoots)\n\n if (graph.getPages(true).length === 0) {\n graph.addPage('Page 1')\n }\n if (doc.tokenSources && doc.tokenSources.length > 0) {\n graph.updateNode(graph.rootId, {\n pluginData: tokenSourcesPluginData(graph, rekeyTokenSources(graph, doc.tokenSources))\n })\n }\n // After the links, which replace the document node's plugin data: the memory is stored beside them.\n if (doc.designMemory) writeDesignMemory(graph, doc.designMemory)\n if (doc.statuses) writeStatusWorkflow(graph, doc.statuses)\n writeLibraryLinks(graph, doc)\n\n return graph\n}\n\nexport function parsePenFile(json: string, options: PenReadOptions = {}): SceneGraph {\n return buildPenGraph(parsePenDocument(json), options)\n}\n\nexport async function readPenFile(file: File, options?: PenReadOptions): Promise<SceneGraph> {\n return parsePenFile(await file.text(), options)\n}\n","import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\n/**\n * Collects the nodes `writeNode` emits. Instance subtrees are skipped because a ref writes\n * no children; an instance whose component is missing here is written as a frame instead.\n */\nexport function writtenNodeIds(graph: SceneGraph): Set<string> {\n const ids = new Set<string>()\n const visit = (node: SceneNode): void => {\n if (node.internalOnly) return\n ids.add(node.id)\n if (node.type === 'STICKY' || node.type === 'INSTANCE') return\n for (const child of graph.getChildren(node.id)) visit(child)\n }\n for (const page of graph.getPages()) for (const node of graph.getChildren(page.id)) visit(node)\n return ids\n}\n","import { isEqual } from 'es-toolkit'\nimport { fromUint8Array } from 'js-base64'\n\nimport type {\n BlendMode,\n EnabledLibraryBinding,\n Fill,\n GradientTransform,\n LayoutAlign,\n LayoutCounterAlign,\n SceneGraph,\n SceneNode,\n ShadowEffect,\n Stroke,\n Variable,\n VariableCollection,\n VariableValue\n} from '@pairdraw/scene-graph'\nimport { SceneGraph as SceneGraphValue } from '@pairdraw/scene-graph'\nimport { colorToHex, colorToHex8 } from '@pairdraw/scene-graph/color'\nimport { getNodeLocalMatrix } from '@pairdraw/scene-graph/coordinate'\nimport { readDesignMemory } from '@pairdraw/scene-graph/design-memory'\nimport { stickySublayers } from '@pairdraw/scene-graph/generated'\nimport { applyGradientTransform, invertGradientTransform } from '@pairdraw/scene-graph/gradient'\nimport { imageMimeType } from '@pairdraw/scene-graph/images'\nimport { layoutSizing } from '@pairdraw/scene-graph/layout'\nimport type { Color, Vector } from '@pairdraw/scene-graph/primitives'\nimport { readStoredStatusWorkflow } from '@pairdraw/scene-graph/statuses'\nimport { readTokenSources, type TokenSource } from '@pairdraw/scene-graph/token-sources'\n\nimport { readPenImports, readSourceLibraryPublication } from './document-libraries'\nimport { networkToSVGPath } from './geometry'\nimport { penCropTransform } from './images'\nimport { importedComponentIds } from './library'\nimport { PEN_PLUGIN_DATA_NAMESPACE, readIconOrigin } from './plugin-data'\nimport type {\n PenDocument,\n PenEffect,\n PenOverride,\n PenImagePaint,\n PenNode,\n PenNumber,\n PenPaint,\n PenPaints,\n PenSides,\n PenVariable,\n PenVariableScalar\n} from './schema'\nimport { writtenNodeIds } from './written-nodes'\nconst PEN_VERSION = '2.21'\nconst PEN_PLUGIN_FIELDS: Readonly<Partial<Record<string, string>>> = {\n 'pen/type': 'type',\n 'pen/ref': 'ref',\n 'pen/generated': 'generated',\n 'pen/context': 'context',\n 'pen/metadata': 'metadata',\n 'pen/placeholder': 'placeholder',\n 'pen/slot': 'slot',\n 'pen/model': 'model',\n 'pen/scriptUri': 'scriptUri',\n 'pen/inputs': 'inputs',\n 'pen/url': 'url',\n 'pen/deviceId': 'deviceId',\n 'pen/zoom': 'zoom',\n 'pen/scrollX': 'scrollX',\n 'pen/scrollY': 'scrollY'\n}\n\ntype PenWriteState = {\n graph: SceneGraph\n variables: ReadonlyMap<string, Variable>\n collections: ReadonlyMap<string, VariableCollection>\n /** Nodes the document will contain, so an instance refs only a component that is written. */\n writtenIds: ReadonlySet<string>\n /** Components the file resolves through its `imports`, which a ref may name without writing them. */\n importedIds: ReadonlySet<string>\n /** What the file cannot hold, reported once writing leaves it out. */\n warnings: string[]\n drops: {\n images: number\n effects: number\n filters: number\n scroll: number\n fontFeatures: number\n }\n}\n\n/** What a caller learns about content a written `.pen` file cannot hold. */\nexport interface PenWriteOptions {\n /** Collects one sentence per kind of content left out, in place of silently losing it. */\n warnings?: string[]\n}\n\n/** Snaps matrix values that are within floating-point noise of an integer. */\nfunction snapCoordinate(value: number): number {\n return Math.abs(value - Math.round(value)) < 1e-9 ? Math.round(value) : value\n}\n/** A non-finite number has no JSON form, so it is written as 0 to keep the file loadable. */\nfunction rounded(value: number): number {\n return Number.isFinite(value) ? Number(value.toFixed(3)) : 0\n}\nfunction colorValue(value: Color): string {\n return value.a === 1 ? colorToHex(value) : colorToHex8(value)\n}\nfunction variableReference(state: PenWriteState, id: string | undefined): string | undefined {\n const variable = id === undefined ? undefined : state.variables.get(id)\n return variable === undefined ? undefined : `$${variable.name}`\n}\nfunction variableOr<T>(state: PenWriteState, node: SceneNode, field: string, value: T): T | string {\n return variableReference(state, node.boundVariables[field]) ?? value\n}\n\n/** Matches the pen corner convention of placing x/y after undoing the node's rotation or flip. */\nfunction penCoordinates(node: SceneNode): Vector {\n if (node.rotation === 0 && !node.flipX && !node.flipY) return { x: node.x, y: node.y }\n const matrix = getNodeLocalMatrix({ ...node, x: 0, y: 0 })\n return { x: snapCoordinate(node.x + matrix[2]), y: snapCoordinate(node.y + matrix[5]) }\n}\n\n/** pen.dev's names for the scene graph's blend modes, inverse of the reader's `BLEND_MODES`. */\nconst BLEND_MODE_NAMES: Partial<Record<BlendMode, string>> = {\n NORMAL: 'normal',\n DARKEN: 'darken',\n MULTIPLY: 'multiply',\n COLOR_BURN: 'colorBurn',\n LIGHTEN: 'light',\n SCREEN: 'screen',\n COLOR_DODGE: 'colorDodge',\n OVERLAY: 'overlay',\n SOFT_LIGHT: 'softLight',\n HARD_LIGHT: 'hardLight',\n DIFFERENCE: 'difference',\n EXCLUSION: 'exclusion',\n HUE: 'hue',\n SATURATION: 'saturation',\n COLOR: 'color',\n LUMINOSITY: 'luminosity'\n}\nfunction paintBase(fill: Fill): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n if (!fill.visible) result.enabled = false\n if (fill.opacity !== 1) result.opacity = rounded(fill.opacity)\n const blendMode = (fill.blendMode && BLEND_MODE_NAMES[fill.blendMode]) ?? undefined\n if (blendMode && blendMode !== 'normal') result.blendMode = blendMode\n return result\n}\n\nfunction gradientName(type: Fill['type']): 'linear' | 'radial' | 'angular' | 'diamond' {\n if (type === 'GRADIENT_RADIAL') return 'radial'\n if (type === 'GRADIENT_ANGULAR') return 'angular'\n if (type === 'GRADIENT_DIAMOND') return 'diamond'\n return 'linear'\n}\n\nfunction gradientPoint(inverse: GradientTransform | undefined, point: Vector): Vector {\n return inverse === undefined ? point : applyGradientTransform(inverse, point)\n}\nfunction gradientAxis(\n fill: Fill,\n inverse: GradientTransform | undefined,\n center: Vector,\n first: Vector,\n second: Vector\n): { rotation: number; width: number; height: number } {\n const firstLength = 2 * Math.hypot(first.x - center.x, first.y - center.y)\n const secondLength = 2 * Math.hypot(second.x - center.x, second.y - center.y)\n const rotationOf = (axis: Vector, offset: number): number =>\n offset - (Math.atan2(axis.x, -axis.y) * 180) / Math.PI\n if (fill.type === 'GRADIENT_LINEAR') {\n const axis =\n inverse === undefined\n ? { x: 0, y: -1 }\n : {\n x: applyGradientTransform(inverse, { x: 1, y: 0.5 }).x - center.x,\n y: applyGradientTransform(inverse, { x: 1, y: 0.5 }).y - center.y\n }\n return { rotation: rotationOf(axis, 0), width: secondLength, height: firstLength }\n }\n if (fill.type === 'GRADIENT_RADIAL' || fill.type === 'GRADIENT_DIAMOND') {\n const axis = { x: second.x - center.x, y: second.y - center.y }\n return { rotation: rotationOf(axis, 180), width: firstLength, height: secondLength }\n }\n const axis = { x: first.x - center.x, y: first.y - center.y }\n return { rotation: rotationOf(axis, 0), width: secondLength, height: firstLength }\n}\nfunction gradientPaint(fill: Fill): PenPaint {\n const transform = fill.gradientTransform\n const inverse = transform === undefined ? undefined : invertGradientTransform(transform)\n const center = gradientPoint(inverse, { x: 0.5, y: 0.5 })\n const first = gradientPoint(inverse, { x: 1, y: 0.5 })\n const second = gradientPoint(inverse, { x: 0.5, y: 1 })\n const axis = gradientAxis(fill, inverse, center, first, second)\n return {\n type: 'gradient',\n gradientType: gradientName(fill.type),\n ...paintBase(fill),\n center: { x: rounded(center.x), y: rounded(center.y) },\n size: { width: rounded(axis.width), height: rounded(axis.height) },\n rotation: rounded(axis.rotation),\n colors: (fill.gradientStops ?? []).map((stop) => ({\n color: colorValue(stop.color),\n position: rounded(stop.position)\n }))\n }\n}\n\n/**\n * An image fill as a pen.dev paint whose image travels with the file: Pencil.dev opens a data URL\n * and the scene graph keeps the bytes, so the fill is written whole instead of pointing at a hash\n * no reader can resolve. A paint whose bytes are gone is left out and reported, never written as a\n * dead URL.\n */\nfunction imagePaint(state: PenWriteState, fill: Fill): PenPaint | null {\n const bytes = fill.imageHash ? state.graph.images.get(fill.imageHash) : undefined\n if (!bytes) {\n state.drops.images++\n return null\n }\n if (fill.filters) state.drops.filters++\n const paint: PenImagePaint = {\n type: 'image',\n ...paintBase(fill),\n url: `data:${imageMimeType(bytes)};base64,${fromUint8Array(bytes)}`\n }\n if (fill.imageScaleMode === 'FIT') paint.mode = 'contain'\n if (fill.imageScaleMode === 'CROP') {\n paint.mode = 'stretch'\n const transform = fill.imageTransform && penCropTransform(fill.imageTransform)\n if (transform) paint.transform = transform\n }\n return paint\n}\n\nfunction penPaint(\n state: PenWriteState,\n node: SceneNode,\n field: 'fills' | 'strokes',\n fill: Fill,\n index: number\n): PenPaint | null {\n if (fill.type === 'SOLID') {\n const binding = variableReference(state, node.boundVariables[`${field}/${index}/color`])\n return { type: 'color', color: binding ?? colorValue(fill.color), ...paintBase(fill) }\n }\n if (fill.type.startsWith('GRADIENT_')) return gradientPaint(fill)\n if (fill.type === 'IMAGE') return imagePaint(state, fill)\n return { type: fill.type.toLowerCase(), ...paintBase(fill) }\n}\n\nfunction paintsOf(\n state: PenWriteState,\n node: SceneNode,\n field: 'fills' | 'strokes',\n paints: readonly Fill[]\n): PenPaints | undefined {\n if (paints.length === 0) return undefined\n const result = paints\n .map((paint, index) => penPaint(state, node, field, paint, index))\n .filter((paint): paint is PenPaint => paint !== null)\n if (result.length === 0) return undefined\n return result.length === 1 ? result[0] : result\n}\n\nfunction strokesOf(\n state: PenWriteState,\n node: SceneNode\n): Pick<\n PenNode,\n 'stroke' | 'strokeWidth' | 'strokeAlignment' | 'strokeLinecap' | 'strokeLinejoin'\n> {\n if (node.strokes.length === 0) return {}\n const paints = paintsOf(state, node, 'strokes', node.strokes)\n if (paints === undefined) return {}\n const first = node.strokes[0]\n const strokeWidth: PenNumber | PenSides = node.independentStrokeWeights\n ? {\n top: variableOr(state, node, 'borderTopWeight', rounded(node.borderTopWeight)),\n right: variableOr(state, node, 'borderRightWeight', rounded(node.borderRightWeight)),\n bottom: variableOr(state, node, 'borderBottomWeight', rounded(node.borderBottomWeight)),\n left: variableOr(state, node, 'borderLeftWeight', rounded(node.borderLeftWeight))\n }\n : variableOr(state, node, 'strokeWeight', rounded(first.weight))\n const caps: Record<NonNullable<Stroke['cap']>, string> = {\n NONE: 'butt',\n ROUND: 'round',\n SQUARE: 'square',\n ARROW_LINES: 'butt',\n ARROW_EQUILATERAL: 'butt',\n TRIANGLE_FILLED: 'butt',\n DIAMOND_FILLED: 'butt',\n CIRCLE_FILLED: 'butt'\n }\n const joins: Record<NonNullable<Stroke['join']>, string> = {\n MITER: 'miter',\n BEVEL: 'bevel',\n ROUND: 'round'\n }\n const linecap = first.cap === undefined ? undefined : caps[first.cap]\n const linejoin = first.join === undefined ? undefined : joins[first.join]\n return {\n stroke: paints,\n strokeWidth,\n strokeAlignment: first.align.toLowerCase(),\n strokeLinecap: linecap === 'butt' ? undefined : linecap,\n strokeLinejoin: linejoin === 'miter' ? undefined : linejoin\n }\n}\n\nfunction effectOf(effect: ShadowEffect): PenEffect {\n if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') {\n return {\n type: effect.type === 'LAYER_BLUR' ? 'blur' : 'background_blur',\n radius: rounded(effect.radius),\n enabled: effect.visible\n }\n }\n return {\n type: 'shadow',\n shadowType: effect.type === 'INNER_SHADOW' ? 'inner' : undefined,\n color: colorValue(effect.color),\n offset: { x: rounded(effect.offset.x), y: rounded(effect.offset.y) },\n blur: rounded(effect.radius),\n spread: rounded(effect.spread),\n enabled: effect.visible\n }\n}\n\nfunction variableType(type: Variable['type']): PenVariable['type'] {\n if (type === 'COLOR') return 'color'\n if (type === 'FLOAT') return 'number'\n if (type === 'BOOLEAN') return 'boolean'\n return 'string'\n}\n\nfunction layoutFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {\n if (node.layoutMode === 'NONE')\n return node.type === 'FRAME' || node.type === 'COMPONENT' ? { layout: 'none' } : {}\n const justify: Partial<Record<LayoutAlign, string>> = {\n CENTER: 'center',\n MAX: 'end',\n SPACE_BETWEEN: 'space_between',\n SPACE_AROUND: 'space_around'\n }\n const align: Partial<Record<LayoutCounterAlign, string>> = {\n CENTER: 'center',\n MAX: 'end',\n STRETCH: 'stretch',\n BASELINE: 'baseline'\n }\n const fields: Partial<PenNode> = {\n layout: node.layoutMode === 'HORIZONTAL' ? 'horizontal' : 'vertical'\n }\n const gapBinding = variableReference(state, node.boundVariables['itemSpacing'])\n if (gapBinding !== undefined) fields.gap = gapBinding\n else if (node.itemSpacing !== 0) fields.gap = rounded(node.itemSpacing)\n if (node.primaryAxisAlign !== 'MIN') fields.justifyContent = justify[node.primaryAxisAlign]\n if (node.counterAxisAlign !== 'MIN') fields.alignItems = align[node.counterAxisAlign]\n // A padding bound to a variable is written as its reference, as the reader binds it again.\n const padding: [PenNumber, PenNumber, PenNumber, PenNumber] = [\n variableOr(state, node, 'paddingTop', node.paddingTop),\n variableOr(state, node, 'paddingRight', node.paddingRight),\n variableOr(state, node, 'paddingBottom', node.paddingBottom),\n variableOr(state, node, 'paddingLeft', node.paddingLeft)\n ]\n if (padding.some((value) => value !== 0)) fields.padding = padding\n if (node.clipsContent) fields.clip = true\n if (node.strokesIncludedInLayout) fields.layoutIncludeStroke = true\n return fields\n}\n\nfunction sizing(\n state: PenWriteState,\n node: SceneNode,\n axis: 'HORIZONTAL' | 'VERTICAL'\n): PenNumber | undefined {\n const mode = layoutSizing(state.graph, node, axis)\n if (mode === 'FILL') return 'fill_container'\n if (mode === 'HUG') return 'fit_content'\n return undefined\n}\n\nfunction penPluginFields(node: SceneNode, result: PenNode): void {\n for (const entry of node.pluginData) {\n if (entry.pluginId !== PEN_PLUGIN_DATA_NAMESPACE) continue\n const field = PEN_PLUGIN_FIELDS[entry.key]\n if (field === undefined) continue\n let value: unknown\n try {\n value = JSON.parse(entry.value)\n } catch {\n console.warn(`Skipping corrupt pen plugin field ${field}`)\n continue\n }\n result[field] = value\n }\n}\n\nfunction nodeType(node: SceneNode): string {\n switch (node.type) {\n case 'COMPONENT':\n case 'COMPONENT_SET':\n case 'FRAME':\n case 'SECTION':\n return 'frame'\n case 'RECTANGLE':\n case 'ROUNDED_RECTANGLE':\n return 'rectangle'\n case 'ELLIPSE':\n return 'ellipse'\n case 'POLYGON':\n case 'STAR':\n return 'polygon'\n case 'GROUP':\n case 'BOOLEAN_OPERATION':\n return 'group'\n case 'TEXT':\n return 'text'\n case 'VECTOR':\n return 'path'\n case 'LINE':\n return 'line'\n case 'STICKY':\n return 'note'\n default:\n return 'frame'\n }\n}\n\n/** A line height as the multiple of the font size pen.dev stores; undefined when it has none. */\nfunction lineHeightMultiple(node: SceneNode): number | undefined {\n const lineHeight = node.lineHeight\n if (!lineHeight) return undefined\n if (lineHeight.unit !== 'PIXELS') return rounded(lineHeight.value / 100)\n return node.fontSize > 0 ? rounded(lineHeight.value / node.fontSize) : undefined\n}\n\n/** Letter spacing in the pixels pen.dev stores, a percent following the font size. */\nfunction letterSpacingPixels(node: SceneNode): number {\n const spacing = node.letterSpacing\n return spacing.unit === 'PIXELS' ? spacing.value : (spacing.value / 100) * node.fontSize\n}\n\nfunction textFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {\n if (node.type !== 'TEXT') return {}\n const fields: Partial<PenNode> = { content: node.text }\n if (node.fontFamily !== 'Inter')\n fields.fontFamily = variableOr(state, node, 'fontFamily', node.fontFamily)\n if (node.fontSize !== 14)\n fields.fontSize = variableOr(state, node, 'fontSize', rounded(node.fontSize))\n const fontWeight = variableOr(state, node, 'fontWeight', node.fontWeight)\n if (typeof fontWeight === 'string' || node.fontWeight !== 400) fields.fontWeight = fontWeight\n if (node.italic) fields.fontStyle = 'italic'\n const textAlign: Partial<Record<SceneNode['textAlignHorizontal'], string>> = {\n CENTER: 'center',\n RIGHT: 'right',\n JUSTIFIED: 'justify'\n }\n const textAlignVertical: Partial<Record<SceneNode['textAlignVertical'], string>> = {\n CENTER: 'middle',\n BOTTOM: 'bottom'\n }\n if (node.textAlignHorizontal !== 'LEFT') fields.textAlign = textAlign[node.textAlignHorizontal]\n if (node.textAlignVertical !== 'TOP')\n fields.textAlignVertical = textAlignVertical[node.textAlignVertical]\n const lineHeight = lineHeightMultiple(node)\n if (lineHeight !== undefined) fields.lineHeight = lineHeight\n if (node.letterSpacing.value !== 0) fields.letterSpacing = rounded(letterSpacingPixels(node))\n if (node.textAutoResize === 'HEIGHT') fields.textGrowth = 'fixed-width'\n if (node.textAutoResize === 'NONE' || node.textAutoResize === 'TRUNCATE')\n fields.textGrowth = 'fixed-width-height'\n const link = node.styleRuns.find((run) => run.style.hyperlink?.type === 'URL')\n if (link?.style.hyperlink?.type === 'URL') fields.href = link.style.hyperlink.value\n return fields\n}\n\nfunction cornerFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {\n if (node.independentCorners) {\n return {\n cornerRadius: [\n variableOr(state, node, 'topLeftRadius', rounded(node.topLeftRadius)),\n variableOr(state, node, 'topRightRadius', rounded(node.topRightRadius)),\n variableOr(state, node, 'bottomRightRadius', rounded(node.bottomRightRadius)),\n variableOr(state, node, 'bottomLeftRadius', rounded(node.bottomLeftRadius))\n ]\n }\n }\n const radius = variableOr(state, node, 'cornerRadius', rounded(node.cornerRadius))\n return radius === 0 ? {} : { cornerRadius: radius }\n}\n\nfunction variableScalar(value: VariableValue | undefined, state: PenWriteState): PenVariableScalar {\n if (value === undefined) return ''\n if (typeof value === 'object' && 'aliasId' in value) {\n const variable = state.variables.get(value.aliasId)\n return variable === undefined ? '' : `$${variable.name}`\n }\n if (typeof value === 'object') return 'r' in value ? colorValue(value) : ''\n return value\n}\nfunction penVariable(\n variable: Variable,\n collection: VariableCollection | undefined,\n state: PenWriteState\n): PenVariable {\n const modes = collection?.modes ?? []\n const syntax = variable.codeSyntax ? { codeSyntax: variable.codeSyntax } : {}\n if (modes.length <= 1)\n return {\n type: variableType(variable.type),\n value: variableScalar(variable.valuesByMode[modes[0]?.modeId ?? ''], state),\n ...syntax\n }\n return {\n type: variableType(variable.type),\n value: modes.map((mode, index) => ({\n value: variableScalar(variable.valuesByMode[mode.modeId], state),\n ...(index === 0 ? {} : { theme: { [collection?.name ?? 'Mode']: mode.name } })\n })),\n ...syntax\n }\n}\n\nfunction variablesOf(state: PenWriteState): Record<string, PenVariable> | undefined {\n if (state.variables.size === 0) return undefined\n return Object.fromEntries(\n [...state.variables.values()]\n .sort((left, right) => left.name.localeCompare(right.name))\n .map((variable) => [\n variable.name,\n penVariable(variable, state.collections.get(variable.collectionId), state)\n ])\n )\n}\n\nfunction themesOf(state: PenWriteState): PenDocument['themes'] {\n if (state.collections.size === 0) return undefined\n return Object.fromEntries(\n [...state.collections.values()]\n .sort((left, right) => left.name.localeCompare(right.name))\n .map((collection) => [collection.name, collection.modes.map((mode) => mode.name)])\n )\n}\n\n/** The selector each mode applies in, by collection and mode name; none when no mode names one. */\nfunction modeConditionsOf(state: PenWriteState): PenDocument['modeConditions'] {\n const entries = [...state.collections.values()].flatMap((collection) => {\n const modes = collection.modes.flatMap((mode) =>\n mode.condition ? [[mode.name, mode.condition] as const] : []\n )\n return modes.length > 0 ? [[collection.name, Object.fromEntries(modes)] as const] : []\n })\n return entries.length > 0 ? Object.fromEntries(entries) : undefined\n}\n\nfunction basicNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): void {\n if (node.name) result.name = node.name\n const placement = penCoordinates(node)\n if (placement.x !== 0) result.x = rounded(placement.x)\n if (placement.y !== 0) result.y = rounded(placement.y)\n result.width = variableOr(\n state,\n node,\n 'width',\n sizing(state, node, 'HORIZONTAL') ?? rounded(node.width)\n )\n result.height = variableOr(\n state,\n node,\n 'height',\n sizing(state, node, 'VERTICAL') ?? rounded(node.height)\n )\n if (!node.visible) result.enabled = false\n if (node.opacity !== 1) result.opacity = rounded(node.opacity)\n if (node.rotation !== 0)\n result.rotation = rounded(node.flipX !== node.flipY ? node.rotation : -node.rotation)\n if (node.flipX) result.flipX = true\n if (node.flipY) result.flipY = true\n const theme = themeFields(state, node)\n if (theme) result.theme = theme\n const fill = paintsOf(state, node, 'fills', node.fills)\n if (fill !== undefined) result.fill = fill\n Object.assign(\n result,\n strokesOf(state, node),\n layoutFields(state, node),\n cornerFields(state, node),\n textFields(state, node)\n )\n}\n/**\n * A layer's variable mode assignments, by the names pen writes: the collection's name and the\n * mode's. A mode the document no longer holds is left out.\n */\nfunction themeFields(state: PenWriteState, node: SceneNode): Record<string, string> | undefined {\n const theme: Record<string, string> = {}\n for (const [collectionId, modeId] of Object.entries(node.variableModes)) {\n const collection = state.collections.get(collectionId)\n const mode = collection?.modes.find((candidate) => candidate.modeId === modeId)\n if (collection && mode) theme[collection.name] = mode.name\n }\n return Object.keys(theme).length > 0 ? theme : undefined\n}\n\n/**\n * The pen fields an instance override writes: what it changes on a layer, not the placement and\n * layout a reopen recalculates from the component and the boxes around it.\n */\nconst OVERRIDABLE_FIELDS: ReadonlySet<string> = new Set([\n 'content',\n 'fill',\n 'stroke',\n 'strokeWidth',\n 'cornerRadius',\n 'effect',\n 'opacity',\n 'enabled',\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'fontStyle',\n 'textAlign',\n 'textAlignVertical',\n 'lineHeight',\n 'letterSpacing',\n 'href'\n])\n\n/**\n * The path a copy sits at in its component, from the instance down: the ids of the layers it\n * copies, as pen names a `descendants` override. A copy that swapped its component copies `swapOf`\n * instead of the component it draws.\n */\nfunction overridePath(\n graph: SceneGraph,\n instanceId: string,\n copyId: string,\n swapOf?: string\n): string | null {\n const parts: string[] = []\n let current = graph.getNode(copyId)\n while (current && current.id !== instanceId) {\n const id = current.id === copyId && swapOf ? swapOf : current.componentId\n if (!id) return null\n parts.unshift(id)\n current = current.parentId ? graph.getNode(current.parentId) : undefined\n }\n return current ? parts.join('/') : null\n}\n\n/**\n * The fields a swap override names an icon by: pen carries the glyph, not the component drawn.\n */\nfunction iconOverride(graph: SceneGraph, componentId: string | null): PenOverride | undefined {\n const origin = readIconOrigin(componentId ? graph.getNode(componentId) : undefined)\n if (!origin) return undefined\n const override: PenOverride = { icon: origin.icon }\n if (origin.library) override.library = origin.library\n if (origin.weight !== undefined) override.weight = origin.weight\n return override\n}\n\n/**\n * The overrides an instance writes, and whether one of them is a swap the file cannot name. A\n * layer that swapped its component draws another component than the one it copies, which pen holds\n * as a glyph for an icon; any other swap is what the instance shows, not what it links to.\n */\nfunction instanceDescendants(\n state: PenWriteState,\n node: SceneNode\n): { descendants?: Record<string, PenOverride>; unrepresentable: boolean } {\n const overridden = [...node.instanceOverrides.descendants.keys()]\n if (overridden.length === 0) return { unrepresentable: false }\n // Comparing writes fields the moment a document writes them, but their drops are counted once.\n const probe: PenWriteState = {\n ...state,\n drops: { images: 0, effects: 0, filters: 0, scroll: 0, fontFeatures: 0 }\n }\n const descendants: Record<string, PenOverride> = {}\n let unrepresentable = false\n for (const copyId of overridden) {\n const overrides = node.instanceOverrides.descendants.get(copyId)\n const swapped = overrides?.has('componentId') === true\n const swapOf = swapped ? overrides.get('sourceComponentId') : undefined\n const path = overridePath(\n state.graph,\n node.id,\n copyId,\n typeof swapOf === 'string' ? swapOf : undefined\n )\n const copy = state.graph.getNode(copyId)\n if (!path || !copy) {\n unrepresentable = true\n continue\n }\n if (swapped) {\n const icon = iconOverride(state.graph, copy.componentId)\n if (!icon) {\n unrepresentable = true\n continue\n }\n descendants[path] = icon\n continue\n }\n const master = copy.componentId ? state.graph.getNode(copy.componentId) : undefined\n if (!master) {\n unrepresentable = true\n continue\n }\n const own = writeNode(probe, copy)\n const base = writeNode(probe, master)\n const override: PenOverride = {}\n for (const field of OVERRIDABLE_FIELDS) {\n if (!isEqual(own[field], base[field])) override[field] = own[field]\n }\n if (Object.keys(override).length > 0) descendants[path] = override\n }\n return {\n descendants: Object.keys(descendants).length > 0 ? descendants : undefined,\n unrepresentable\n }\n}\n\nfunction semanticNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): boolean {\n if (\n node.type === 'TEXT' &&\n node.textAutoResize === 'WIDTH_AND_HEIGHT' &&\n layoutSizing(state.graph, node, 'HORIZONTAL') === 'HUG'\n )\n result.width = 'fit_content'\n if (node.type === 'STICKY') result.content = stickySublayers(state.graph, node)?.body.text ?? ''\n penPluginFields(node, result)\n // Shader, noise, and texture effects have no pen.dev form; dropping them keeps the file loadable.\n const effects = node.effects.filter((effect): effect is ShadowEffect => {\n if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') return true\n if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') return true\n if (effect.type === 'NOISE' || effect.type === 'TEXTURE') state.drops.effects++\n return false\n })\n if (effects.length > 0)\n result.effect = effects.length === 1 ? effectOf(effects[0]) : effects.map(effectOf)\n if (node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') result.reusable = true\n if (\n node.type === 'INSTANCE' &&\n node.componentId &&\n (state.writtenIds.has(node.componentId) || state.importedIds.has(node.componentId))\n ) {\n const overrides = instanceDescendants(state, node)\n // The file names a swap through the library it imports; one it cannot name is written as the\n // layers the instance draws, which keeps what it shows, as before the library work.\n if (overrides.unrepresentable && !state.writtenIds.has(node.componentId)) return false\n result.type = 'ref'\n result.ref = node.componentId\n if (overrides.descendants) result.descendants = overrides.descendants\n return true\n }\n return false\n}\nfunction writeNode(state: PenWriteState, node: SceneNode): PenNode {\n if (node.overflowDirection !== 'NONE') state.drops.scroll++\n if (node.fontFeatures.length > 0) state.drops.fontFeatures++\n const result: PenNode = { id: node.id, type: nodeType(node) }\n if (node.status !== null) result.status = node.status\n basicNodeFields(state, node, result)\n if (semanticNodeFields(state, node, result)) return result\n // Written after the preserved pen fields, so a regenerated path wins over the source text.\n if (node.type === 'VECTOR' && node.vectorNetwork && node.vectorNetwork.segments.length > 0) {\n const geometry = networkToSVGPath(node.vectorNetwork)\n if (geometry) {\n result.geometry = geometry\n // The written box is rounded; the view box names the same box, so the path maps onto it\n // one to one rather than being scaled into a rounded height on the next read.\n result.viewBox = [0, 0, rounded(node.width), rounded(node.height)]\n if (node.vectorNetwork.regions[0]?.windingRule === 'EVENODD') result.fillRule = 'evenodd'\n }\n }\n const children =\n node.type === 'STICKY'\n ? []\n : state.graph\n .getChildren(node.id)\n .filter((child) => !child.internalOnly)\n .map((child) => writeNode(state, child))\n if (children.length > 0) result.children = children\n return result\n}\n\n/** Code-point order, so the canonical text does not depend on the runtime locale. */\nfunction compareCodePoints(left: string, right: string): number {\n if (left < right) return -1\n if (left > right) return 1\n return 0\n}\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeys)\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as { [key: string]: unknown })\n return Object.fromEntries(\n entries\n .sort(([left], [right]) => compareCodePoints(left, right))\n .map(([key, entry]) => [key, sortKeys(entry)])\n )\n }\n return value\n}\n\nexport function penDocumentFromGraph(\n graph: SceneGraph,\n options: PenWriteOptions = {}\n): PenDocument {\n // A deleted variable has no state `.pen` can hold, so layers bound to it write its value.\n const variables = new Map<string, Variable>()\n for (const variable of graph.getLiveVariables()) variables.set(variable.id, variable)\n const collections = new Map<string, VariableCollection>()\n for (const collection of graph.getLiveCollections()) collections.set(collection.id, collection)\n // The file declares its imports, so a ref to a component one of them defines resolves on reopen.\n const imports = readPenImports(graph)\n const state: PenWriteState = {\n graph,\n variables,\n collections,\n writtenIds: writtenNodeIds(graph),\n importedIds: importedComponentIds(graph, imports ?? {}),\n warnings: options.warnings ?? [],\n drops: { images: 0, effects: 0, filters: 0, scroll: 0, fontFeatures: 0 }\n }\n const pages = graph.getPages()\n const children = pages.flatMap((page) =>\n graph\n .getChildren(page.id)\n .filter((node) => !node.internalOnly)\n .map((node) => writeNode(state, node))\n )\n const document: PenDocument = { version: PEN_VERSION, name: pages[0]?.name, children }\n const variablesValue = variablesOf(state)\n if (variablesValue) document.variables = variablesValue\n const themes = themesOf(state)\n if (themes) document.themes = themes\n const conditions = modeConditionsOf(state)\n if (conditions) document.modeConditions = conditions\n const tokenSources = readTokenSources(graph).map((source) => {\n // The reopen gives variables new ids; these are the names the file holds for them. `names`\n // stays as the last sync recorded it, where the token each variable stands for lives.\n const currentNames = Object.fromEntries(\n Object.keys(source.names ?? {}).flatMap((id) => {\n const variable = variables.get(id)\n const collection = variable ? collections.get(variable.collectionId) : undefined\n return variable && collection ? [[id, `${collection.name}/${variable.name}`]] : []\n })\n )\n const modes = {\n ...source.modes,\n ...Object.fromEntries(\n [...collections.values()].map((collection) => [\n collection.name,\n Object.fromEntries(collection.modes.map((mode) => [mode.modeId, mode.name]))\n ])\n )\n }\n const refreshed: TokenSource = { ...source }\n if (Object.keys(currentNames).length > 0) refreshed.currentNames = currentNames\n if (Object.keys(modes).length > 0) refreshed.modes = modes\n return refreshed\n })\n if (tokenSources.length > 0) document.tokenSources = tokenSources\n const designMemory = readDesignMemory(graph)\n if (designMemory) document.designMemory = designMemory\n // Only a document that chose its statuses writes them: the default falls back on read.\n const statuses = readStoredStatusWorkflow(graph)\n if (statuses) document.statuses = statuses\n if (imports) document.imports = imports\n const enabledLibraries = enabledLibrariesOf(graph, state)\n if (enabledLibraries) document.enabledLibraries = enabledLibraries\n const publication = readSourceLibraryPublication(graph)\n if (publication) document.sourceLibraryPublication = publication\n if (pages.length > 1) {\n const name = document.name ?? 'Page 1'\n state.warnings.push(\n `Pencil.dev files hold one page; ${pages.length} pages were merged into “${name}”.`\n )\n }\n if (graph.documentColorSpace === 'display-p3') {\n state.warnings.push(\n '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.'\n )\n }\n reportDrops(state)\n return document\n}\n\n/**\n * The library bindings a `.pen` file records, or null when the document has none. The definitions\n * live on the hidden page, which a Pencil.dev file cannot hold, so the file records the bindings\n * and says that the components it was built from come back as placeholders.\n */\nfunction enabledLibrariesOf(\n graph: SceneGraph,\n state: PenWriteState\n): EnabledLibraryBinding[] | null {\n const bindings = [...graph.enabledLibraries.values()]\n if (bindings.length === 0) return null\n const enabled = bindings.filter((binding) => binding.enabled).length\n if (enabled > 0)\n state.warnings.push(\n `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.`\n )\n return bindings\n}\n\n/** Adds one sentence for each kind of content the written file had to leave out. */\nfunction reportDrops(state: PenWriteState): void {\n const { images, effects, filters, scroll, fontFeatures } = state.drops\n if (images > 0)\n state.warnings.push(\n `Image fills with missing image data were left out (${images}); Pencil.dev files cannot hold a paint without its image.`\n )\n if (effects > 0)\n state.warnings.push(\n `Noise and texture effects were left out (${effects}); Pencil.dev files have no form for them.`\n )\n if (filters > 0)\n state.warnings.push(\n `Image adjustment filters were left out (${filters}); Pencil.dev files have no form for them.`\n )\n if (scroll > 0)\n state.warnings.push(\n `Scroll overflow was left out (${scroll}); Pencil.dev files have no form for it.`\n )\n if (fontFeatures > 0)\n state.warnings.push(\n `OpenType font features were left out (${fontFeatures}); Pencil.dev files have no form for them.`\n )\n}\n\nexport function stringifyPenDocument(document: PenDocument): string {\n return `${JSON.stringify(sortKeys(document), null, 2)}\\n`\n}\n\nexport function writePenDocument(\n source: PenDocument | SceneGraph,\n options: PenWriteOptions = {}\n): string {\n const document =\n source instanceof SceneGraphValue ? penDocumentFromGraph(source, options) : source\n return stringifyPenDocument(document)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,gBAAgB,MAAmB,OAAuB;CACjE,IAAI,OAAO,KAAK,QAAQ,UAAU,MAAM,KAAK,KAAK,GAAG;CACrD,IAAI,MAAM,QAAQ,KAAK,IAAI,GAAG,MAAM,KAAK,GAAG,KAAK,IAAI;CACrD,KAAK,MAAM,SAAS,KAAK,YAAY,CAAC,GAAG,gBAAgB,OAAO,KAAK;CACrE,KAAK,MAAM,YAAY,OAAO,OAAO,KAAK,eAAe,CAAC,CAAC,GAAG,gBAAgB,UAAU,KAAK;AAC/F;AAEA,SAAS,WACP,OACA,OACoC;CACpC,OAAO,SAAS,QAAQ;EAAE,GAAG;EAAO,GAAG;CAAM,IAAI,KAAA;AACnD;;AAGA,SAAS,gBAAgB,SAAyC;CAChE,MAAM,yBAAS,IAAI,IAAmB;CACtC,KAAK,MAAM,CAAC,OAAO,EAAE,MAAM,UAAU,SAAS;EAC5C,MAAM,SAAS,OAA2B,MAA2B,UAA0B;GAC7F,KAAK,MAAM,QAAQ,OAAO;IACxB,MAAM,MAAM,SAAS,KAAK,WAAW,OAAO,KAAA;IAC5C,IAAI,KAAK,YAAY,KAAK,OAAO,IAAI,KAAK,IAAI;KAAE;KAAO;KAAM,MAAM;KAAK;IAAM,CAAC;IAC/E,MAAM,KAAK,YAAY,CAAC,GAAG,KAAK,MAAM,QAAQ,WAAW,OAAO,KAAK,KAAK,CAAC;GAC7E;EACF;EACA,MAAM,IAAI,UAAU,KAAA,GAAW,KAAA,CAAS;CAC1C;CACA,OAAO;AACT;;;;;;AAOA,SAAS,UAAU,KAAkB,SAA8B;CACjE,MAAM,SAAS,gBAAgB,OAAO;CACtC,MAAM,UAAoB,CAAC;CAC3B,KAAK,MAAM,QAAQ,IAAI,UAAU,gBAAgB,MAAM,OAAO;CAC9D,MAAM,wBAAQ,IAA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MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,SAAS,KACb,mCAAmC,MAAM,OAAO,2BAA2B,KAAK,GAClF;CACF;CACA,IAAI,MAAM,uBAAuB,cAC/B,MAAM,SAAS,KACb,6IACF;CAEF,YAAY,KAAK;CACjB,OAAO;AACT;;;;;;AAOA,SAAS,mBACP,OACA,OACgC;CAChC,MAAM,WAAW,CAAC,GAAG,MAAM,iBAAiB,OAAO,CAAC;CACpD,IAAI,SAAS,WAAW,GAAG,OAAO;CAClC,MAAM,UAAU,SAAS,QAAQ,YAAY,QAAQ,OAAO,CAAC,CAAC;CAC9D,IAAI,UAAU,GACZ,MAAM,SAAS,KACb,gCAAgC,QAAQ,WAAW,YAAY,IAAI,YAAY,YAAY,6GAC7F;CACF,OAAO;AACT;;AAGA,SAAS,YAAY,OAA4B;CAC/C,MAAM,EAAE,QAAQ,SAAS,SAAS,QAAQ,iBAAiB,MAAM;CACjE,IAAI,SAAS,GACX,MAAM,SAAS,KACb,sDAAsD,OAAO,2DAC/D;CACF,IAAI,UAAU,GACZ,MAAM,SAAS,KACb,4CAA4C,QAAQ,2CACtD;CACF,IAAI,UAAU,GACZ,MAAM,SAAS,KACb,2CAA2C,QAAQ,2CACrD;CACF,IAAI,SAAS,GACX,MAAM,SAAS,KACb,iCAAiC,OAAO,yCAC1C;CACF,IAAI,eAAe,GACjB,MAAM,SAAS,KACb,yCAAyC,aAAa,2CACxD;AACJ;AAEA,SAAgB,qBAAqB,UAA+B;CAClE,OAAO,GAAG,KAAK,UAAU,SAAS,QAAQ,GAAG,MAAM,CAAC,EAAE;AACxD;AAEA,SAAgB,iBACd,QACA,UAA2B,CAAC,GACpB;CAGR,OAAO,qBADL,kBAAkBC,aAAkB,qBAAqB,QAAQ,OAAO,IAAI,MAC1C;AACtC"}
1
+ {"version":3,"file":"index.js","names":["unhandled","isEqual","SceneGraphValue"],"sources":["../../src/library.ts","../../src/placeholders.ts","../../src/placement.ts","../../src/slots.ts","../../src/text.ts","../../src/nodes.ts","../../src/instances.ts","../../src/read.ts","../../src/written-nodes.ts","../../src/write.ts"],"sourcesContent":["import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { libraryDefinitionsPage } from '@pairdraw/scene-graph/components'\n\nimport { withImports, type PenImports } from './imports'\nimport type { Build } from './nodes'\nimport type { PenDocument, PenNode, PenOverride } from './schema'\n\n/** A component an imported document defines, with the outermost component holding it. */\ninterface Owner {\n alias: string\n path: string\n root: PenNode\n /** The themes of the layers around the root in its document, which it was drawn in. */\n theme: Record<string, string> | undefined\n}\n\n/** An imported component the document draws, as it went on the library page. */\nexport interface LibraryRoot {\n id: string\n alias: string\n path: string\n}\n\n/** The component IDs a layer and its overrides name: its `ref`s and the slots' suggestions. */\nfunction namedComponents(node: PenOverride, found: string[]): void {\n if (typeof node.ref === 'string') found.push(node.ref)\n if (Array.isArray(node.slot)) found.push(...node.slot)\n for (const child of node.children ?? []) namedComponents(child, found)\n for (const override of Object.values(node.descendants ?? {})) namedComponents(override, found)\n}\n\nfunction mergeTheme(\n outer: Record<string, string> | undefined,\n inner: Record<string, string> | undefined\n): Record<string, string> | undefined {\n return outer || inner ? { ...outer, ...inner } : undefined\n}\n\n/** Each reusable layer of the imported documents by ID, with the outermost component holding it. */\nfunction componentOwners(imports: PenImports): Map<string, Owner> {\n const owners = new Map<string, Owner>()\n for (const [alias, { path, doc }] of imports) {\n const visit = (nodes: readonly PenNode[], root: PenNode | undefined, theme: Owner['theme']) => {\n for (const node of nodes) {\n const own = root ?? (node.reusable ? node : undefined)\n if (node.reusable && own) owners.set(node.id, { alias, path, root: own, theme })\n visit(node.children ?? [], own, own ? theme : mergeTheme(theme, node.theme))\n }\n }\n visit(doc.children, undefined, undefined)\n }\n return owners\n}\n\n/**\n * The imported components a document draws, through the components they draw in turn, each as the\n * outermost component holding it, in the order the document first names them. A library's other\n * components stay out of the document, which only ever shows instances of the ones it uses.\n */\nfunction usedRoots(doc: PenDocument, imports: PenImports): Owner[] {\n const owners = componentOwners(imports)\n const pending: string[] = []\n for (const node of doc.children) namedComponents(node, pending)\n const roots = new Map<string, Owner>()\n // Each root's own names join the list as it is read.\n for (const id of pending) {\n const owner = owners.get(id)\n if (!owner || roots.has(owner.root.id)) continue\n roots.set(owner.root.id, owner)\n namedComponents(owner.root, pending)\n }\n return [...roots.values()]\n}\n\n/**\n * The document with the imported components it uses after its own layers, and the imported\n * variables and themes, so `penAssets` lists every icon and image it draws and no other of a\n * library's.\n */\nexport function withUsedImports(doc: PenDocument, imports: PenImports): PenDocument {\n if (imports.size === 0) return doc\n return {\n ...withImports(doc, imports),\n children: [...doc.children, ...usedRoots(doc, imports).map((owner) => owner.root)]\n }\n}\n\n/**\n * Draws the imported components the document uses on the hidden library page, in the themes they\n * sit in in their own documents, so its instances of them resolve. Nothing is drawn when the\n * document uses none.\n */\nexport function createLibraryRoots(\n doc: PenDocument,\n imports: PenImports,\n build: Build,\n create: (pen: PenNode, parentId: string, build: Build) => string\n): LibraryRoot[] {\n const roots = usedRoots(doc, imports)\n if (roots.length === 0) return []\n const page = libraryDefinitionsPage(build.graph)\n return roots.map(({ alias, path, root, theme }) => {\n const leave = theme ? build.ctx.enterTheme(theme) : undefined\n try {\n return { id: create(root, page.id, build), alias, path }\n } finally {\n leave?.()\n }\n })\n}\n\n/** `value` with what `allowed` rejects replaced, starting with a letter or digit, at most `max` long. */\nfunction libraryName(value: string, allowed: RegExp, max: number): string {\n const name = value.replace(allowed, '_')\n return (/^[a-zA-Z0-9]/.test(name) ? name : `x${name}`).slice(0, max)\n}\n\n/** The ID a library's assets name it by: `pen:<alias>`, in the characters library IDs take. */\nfunction penLibraryId(alias: string): string {\n return libraryName(`pen:${alias}`, /[^a-zA-Z0-9._:-]/g, 128)\n}\n\n/** A component's key in its library: its ID in the imported document, without the alias. */\nfunction penLibraryAssetKey(alias: string, id: string): string {\n const prefix = `${alias}:`\n const own = id.startsWith(prefix) ? id.slice(prefix.length) : id\n return libraryName(own, /[^a-zA-Z0-9._:/-]/g, 256)\n}\n\n/**\n * Marks the imported components as a library's definitions: read-only, locked, and each with its\n * library and key, so the editor treats them as it treats a component library's, and their\n * instances as library instances. The file they came from is their revision.\n */\nexport function markLibraryRoots(graph: SceneGraph, roots: readonly LibraryRoot[]): void {\n for (const { id, alias, path } of roots) {\n const root = graph.getNode(id)\n if (!root) continue\n const libraryId = penLibraryId(alias)\n const queue = [root]\n for (const node of queue) {\n if (node === root || node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') {\n node.librarySource = {\n identity: { libraryId, assetKey: penLibraryAssetKey(alias, node.id), revisionId: path },\n sourceNodeId: null,\n readOnly: true\n }\n }\n queue.push(...graph.getChildren(node.id))\n }\n root.locked = true\n }\n}\n\n/**\n * The components whose `ref`s a file can resolve: the library definitions its own imports give it,\n * matched to the alias and path each import names. Writing their ids as refs keeps the instances\n * linked on a reopen; the definitions themselves stay out of the file.\n */\nexport function importedComponentIds(\n graph: SceneGraph,\n imports: Readonly<Record<string, string>>\n): Set<string> {\n const ids = new Set<string>()\n const aliases = Object.entries(imports)\n if (aliases.length === 0) return ids\n const paths = new Map(aliases.map(([alias, path]) => [penLibraryId(alias), path]))\n const visit = (node: SceneNode): void => {\n const identity = node.librarySource?.identity\n if (identity && paths.get(identity.libraryId) === identity.revisionId) ids.add(node.id)\n for (const child of graph.getChildren(node.id)) visit(child)\n }\n for (const page of graph.getPages(true))\n for (const node of graph.getChildren(page.id)) visit(node)\n return ids\n}\n","import type { SceneNode } from '@pairdraw/scene-graph'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { unresolvedRef } from './plugin-data'\nimport type { PenNode } from './schema'\n\n/**\n * Layers pen.dev draws that this reader cannot: a `script` node's generated layers, a `browser`\n * node's live page, and a `ref` to a component that could not be found, such as one from a library\n * the host could not read. Each reads as a frame in its box, filled and outlined with a dashed line\n * where pen.dev gives it neither, and labelled with what it stands for when it has no layers.\n */\nconst EMBED_TYPES: ReadonlySet<string> = new Set(['script', 'browser'])\n\nconst PLACEHOLDER_FILL: Color = { r: 0.96, g: 0.96, b: 0.96, a: 1 }\nconst PLACEHOLDER_OUTLINE: Color = { r: 0.62, g: 0.62, b: 0.62, a: 1 }\nconst PLACEHOLDER_DASH = [4, 4]\n/** Room around the label, inside the outline. */\nconst PLACEHOLDER_INSET = 8\nconst LABEL_SIZE = 12\nconst LABEL_COLOR = '#737373'\n\n/** Whether a layer reads as a placeholder. */\nexport function isPlaceholder(pen: PenNode): boolean {\n return EMBED_TYPES.has(pen.type) || unresolvedRef(pen) !== undefined\n}\n\n/**\n * Fills and outlines a placeholder where pen.dev gives it no paint of its own, insets an auto\n * layout's content, and clips a script or browser frame to its box, as pen.dev shows them.\n */\nexport function applyPlaceholderLook(node: SceneNode, pen: PenNode): void {\n if (pen.fill === undefined) {\n node.fills = [{ type: 'SOLID', color: { ...PLACEHOLDER_FILL }, opacity: 1, visible: true }]\n }\n if (node.strokes.length === 0) {\n node.strokes = [\n {\n type: 'SOLID',\n color: { ...PLACEHOLDER_OUTLINE },\n opacity: 1,\n visible: true,\n weight: 1,\n align: 'INSIDE',\n dashPattern: [...PLACEHOLDER_DASH]\n }\n ]\n }\n if (pen.padding === undefined && node.layoutMode !== 'NONE') {\n node.paddingTop = PLACEHOLDER_INSET\n node.paddingRight = PLACEHOLDER_INSET\n node.paddingBottom = PLACEHOLDER_INSET\n node.paddingLeft = PLACEHOLDER_INSET\n }\n if (EMBED_TYPES.has(pen.type) && pen.clip === undefined) node.clipsContent = true\n}\n\n/** What a placeholder stands for: its file, its page, or the component it names. */\nfunction labelText(pen: PenNode): string {\n const missing = unresolvedRef(pen)\n if (missing !== undefined) return missing || (pen.name ?? 'ref')\n if (pen.type === 'script' && pen.scriptUri) return pen.scriptUri\n if (pen.type === 'browser' && pen.url) return pen.url\n return pen.name ?? pen.type\n}\n\n/**\n * The label a placeholder without layers of its own shows, as a text layer; none for one with\n * layers, such as a script node pen.dev saved with what it generated. The label says it was\n * generated, so a writer can leave it out.\n */\nexport function placeholderLabel(pen: PenNode, nodeId: string): PenNode | undefined {\n if (!isPlaceholder(pen) || (pen.children?.length ?? 0) > 0) return undefined\n const text = labelText(pen)\n return {\n id: `${nodeId}#label`,\n type: 'text',\n name: text,\n content: text,\n fontSize: LABEL_SIZE,\n fill: LABEL_COLOR,\n x: PLACEHOLDER_INSET,\n y: PLACEHOLDER_INSET,\n generated: 'placeholder'\n }\n}\n","import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { localTransformFromWorld } from '@pairdraw/scene-graph/coordinate'\nimport { fitEnclosingGroups } from '@pairdraw/scene-graph/group-bounds'\nimport Matrix from '@pairdraw/scene-graph/matrix'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\n/**\n * Where pen.dev puts a layer: at `x`, `y` in its parent, turned `rotation` degrees\n * counter-clockwise and then mirrored, both about that corner. The scene graph turns clockwise and\n * mirrors about a layer's centre, so a layer's position depends on its final size and is set after\n * layout. Measured against pen.dev 2.21 renders of turned, mirrored, and grouped layers.\n */\nexport interface PenPlacement {\n x: number\n y: number\n rotation: number\n flipX: boolean\n flipY: boolean\n}\n\nexport function isPlain(placement: PenPlacement): boolean {\n return placement.rotation === 0 && !placement.flipX && !placement.flipY\n}\n\nfunction inFlow(graph: SceneGraph, node: SceneNode): boolean {\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n return !!parent && parent.layoutMode !== 'NONE' && node.layoutPositioning !== 'ABSOLUTE'\n}\n\n/** 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. */\nfunction place(\n graph: SceneGraph,\n node: SceneNode,\n placement: PenPlacement,\n offset: Vector = { x: 0, y: 0 }\n) {\n const world = Matrix.multiply(\n Matrix.translated(placement.x, placement.y),\n Matrix.rotated((-placement.rotation * Math.PI) / 180),\n Matrix.scaled(placement.flipX ? -1 : 1, placement.flipY ? -1 : 1),\n Matrix.translated(offset.x, offset.y)\n )\n const local = localTransformFromWorld(\n { ...node, flipX: placement.flipX },\n world,\n Matrix.identity()\n )\n if (!local) return\n // Auto layout places the layers in its flow; only their turn and mirroring carry over.\n if (inFlow(graph, node)) graph.updateNode(node.id, { ...local, x: node.x, y: node.y })\n else graph.updateNode(node.id, local)\n}\n\n/**\n * Places every turned or mirrored layer, which the reader builds upright. Then each group, inner\n * ones first, is fitted to its placed layers and placed itself; its box starts at its layers'\n * bounds, wherever pen.dev's starts. `groupIds` is in reading order.\n */\nexport function placeLayers(\n graph: SceneGraph,\n placements: ReadonlyMap<string, PenPlacement>,\n groupIds: readonly string[]\n): void {\n const groups = new Set(groupIds)\n for (const [id, placement] of placements) {\n const node = graph.getNode(id)\n if (node && !groups.has(id) && !isPlain(placement)) place(graph, node, placement)\n }\n\n const origins = new Map<string, Vector>()\n for (const id of groupIds) {\n const group = graph.getNode(id)\n if (group) origins.set(id, { x: group.x, y: group.y })\n }\n // Reading order lists a group before the groups inside it, so reversed it is innermost first.\n for (const id of groupIds.toReversed()) {\n fitEnclosingGroups(graph, [id])\n const node = graph.getNode(id)\n const origin = origins.get(id)\n const placement = placements.get(id)\n if (!node || !origin || !placement || isPlain(placement)) continue\n place(graph, node, placement, { x: node.x - origin.x, y: node.y - origin.y })\n }\n}\n","import type { SceneNode } from '@pairdraw/scene-graph'\nimport { createComponentPropertyId } from '@pairdraw/scene-graph/components'\nimport {\n canCreateSlot,\n claimSlotContent,\n createSlotProperty,\n slotOwner,\n slotScope,\n updateSlotProperty\n} from '@pairdraw/scene-graph/slots'\n\nimport type { Build } from './nodes'\nimport type { PenNode } from './schema'\n\n/**\n * Makes a frame pen.dev marks with `slot` a slot of the component it is in, suggesting the\n * components it lists that the document defines. A frame outside a component has no slot to be.\n */\nexport function createPenSlot(node: SceneNode, pen: PenNode, build: Build): void {\n const { graph, components } = build\n if (!Array.isArray(pen.slot) || !canCreateSlot(graph, node)) return\n const definition = createSlotProperty(graph, node.id, createComponentPropertyId())\n const owner = slotOwner(graph, node)\n if (!definition || !owner) return\n const preferredValues = pen.slot.filter((id) => components.get(id)?.type === 'frame')\n if (preferredValues.length > 0)\n updateSlotProperty(graph, owner.id, definition.id, { preferredValues })\n}\n\n/**\n * Lets `instance` own the content of the slot frame `target`, which an override of its is about\n * to fill, as filling a slot in pen.dev keeps the instance. Returns false when `target` is not a\n * slot of that very instance, whose layers the override must then replace.\n */\nexport function claimSlot(build: Build, instance: SceneNode, target: SceneNode): boolean {\n const scope = slotScope(build.graph, target.id)\n if (scope.kind !== 'slot' || scope.frame.id !== target.id || scope.instance.id !== instance.id)\n return false\n claimSlotContent(build.graph, scope)\n return true\n}\n","import { omit } from 'es-toolkit'\n\nimport type { SceneNode, StyleRun, TextAlignVertical, TextAutoResize } from '@pairdraw/scene-graph'\nimport { parseFontStyle, type FontFamilyStyle } from '@pairdraw/scene-graph/font-style'\nimport { percentLength, pixelLength } from '@pairdraw/scene-graph/text'\n\nimport type { PenNode } from './schema'\nimport { bindIfVar, isVarRef, resolveNumber, resolveString, type VarContext } from './variables'\n\nconst FONT_WEIGHTS: Partial<Record<string, number>> = {\n thin: 100,\n extralight: 200,\n light: 300,\n normal: 400,\n regular: 400,\n medium: 500,\n semibold: 600,\n bold: 700,\n extrabold: 800,\n black: 900\n}\n\n/** pen.dev writes weights as numbers in strings, such as \"700\"; older files use names. */\nfunction fontWeight(value: PenNode['fontWeight'], ctx: VarContext): number {\n if (value === undefined) return 400\n if (typeof value === 'number') return value\n const named = isVarRef(value) ? ctx.resolveString(value) || ctx.resolveNumber(value) : value\n const numeric = Number(named)\n if (Number.isFinite(numeric) && numeric > 0) return numeric\n return FONT_WEIGHTS[String(named).toLowerCase()] ?? 400\n}\n\nconst TEXT_ALIGN: Partial<Record<string, SceneNode['textAlignHorizontal']>> = {\n left: 'LEFT',\n center: 'CENTER',\n right: 'RIGHT',\n justify: 'JUSTIFIED'\n}\n\nconst TEXT_ALIGN_VERTICAL: Partial<Record<string, TextAlignVertical>> = {\n top: 'TOP',\n middle: 'CENTER',\n bottom: 'BOTTOM'\n}\n\n/**\n * `auto` grows on one line, `fixed-width` wraps and grows down, and `fixed-width-height` wraps in\n * a fixed box its text may overflow.\n */\nconst TEXT_GROWTH: Partial<Record<string, TextAutoResize>> = {\n auto: 'WIDTH_AND_HEIGHT',\n 'fixed-width': 'HEIGHT',\n 'fixed-width-height': 'NONE'\n}\n\n/**\n * A text layer's content and style. Content that reads like a variable reference stays as written,\n * as pen.dev shows it. pen.dev 2.21 draws no underline, strikethrough, or text stroke, so those\n * are left out to match it. An `href` is kept as a link, drawn without an underline.\n */\nexport function applyTextProps(\n node: SceneNode,\n pen: PenNode,\n ctx: VarContext,\n fonts: ReadonlyMap<string, FontFamilyStyle>\n): void {\n const isIconFont = pen.type === 'icon_font'\n node.text = isIconFont ? (pen.iconFontName ?? '') : (pen.content ?? '')\n node.fontFamily = isIconFont\n ? (pen.iconFontFamily ?? 'Material Symbols Sharp')\n : (resolveString(pen.fontFamily, ctx) ?? 'Inter')\n bindIfVar(node, 'fontFamily', pen.fontFamily, ctx)\n node.fontSize = resolveNumber(pen.fontSize, ctx, 14)\n bindIfVar(node, 'fontSize', pen.fontSize, ctx)\n const weight = pen.fontWeight ?? (isIconFont ? pen.weight : undefined)\n node.fontWeight = fontWeight(weight, ctx)\n bindIfVar(node, 'fontWeight', weight, ctx)\n node.italic = resolveString(pen.fontStyle, ctx)?.toLowerCase() === 'italic'\n // A bundled font's name stands for one face of the family its file names.\n const bundled = isIconFont ? undefined : fonts.get(node.fontFamily)\n if (bundled) {\n const { weight, italic } = parseFontStyle(bundled.style)\n Object.assign(node, {\n fontFamily: bundled.family,\n fontStyle: bundled.style,\n fontWeight: weight,\n italic\n })\n // The bound name is the pen-only one no font is registered under, so a later reconcile\n // would restore a family nothing draws with. The bundled face owns the family now.\n node.boundVariables = omit(node.boundVariables, ['fontFamily'])\n }\n node.textAlignHorizontal = TEXT_ALIGN[pen.textAlign ?? 'left'] ?? 'LEFT'\n node.textAlignVertical = TEXT_ALIGN_VERTICAL[pen.textAlignVertical ?? 'top'] ?? 'TOP'\n // pen.dev's line height multiplies the font size, so it follows the size as a percent.\n if (pen.lineHeight !== undefined) {\n node.lineHeight = percentLength(resolveNumber(pen.lineHeight, ctx) * 100)\n }\n if (pen.letterSpacing !== undefined) {\n node.letterSpacing = pixelLength(resolveNumber(pen.letterSpacing, ctx))\n }\n node.textAutoResize = TEXT_GROWTH[pen.textGrowth ?? 'auto'] ?? 'WIDTH_AND_HEIGHT'\n // pen.dev draws every font at its default optical size, whatever the text's size.\n node.opticalSizeFromFontSize = false\n node.strokes = []\n node.styleRuns = textLink(pen, node.text, ctx)\n}\n\n/** A text's `href` links all of its characters, as one run. */\nfunction textLink(pen: PenNode, text: string, ctx: VarContext): StyleRun[] {\n const href = pen.type === 'text' ? resolveString(pen.href ?? undefined, ctx)?.trim() : undefined\n if (!href || text.length === 0) return []\n return [{ start: 0, length: text.length, style: { hyperlink: { type: 'URL', value: href } } }]\n}\n","import type {\n AxisSizingMode,\n LayoutMode,\n LayoutSizing,\n NodeType,\n SceneGraph,\n SceneNode\n} from '@pairdraw/scene-graph'\nimport { normalizeEffects } from '@pairdraw/scene-graph/effects'\nimport { CORNER_FIELDS } from '@pairdraw/scene-graph/fields'\nimport type { FontFamilyStyle } from '@pairdraw/scene-graph/font-style'\nimport { fillSizingFields } from '@pairdraw/scene-graph/layout'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { ANNOTATION_TYPES, applyAnnotation, createAnnotation, isAnnotation } from './annotations'\nimport { convertEffects } from './effects'\nimport { ellipseArc } from './geometry'\nimport { drawIcon, insideComponent, useIconComponent } from './icons'\nimport type { PenImages } from './images'\nimport {\n applyCornerRadius,\n applyPadding,\n mapAlignItems,\n mapJustifyContent,\n mapLayoutMode,\n parseSize\n} from './layout'\nimport { applyStroke, convertPaints, strokeFields, type PenShaderSources } from './paints'\nimport { applyPlaceholderLook, isPlaceholder, placeholderLabel } from './placeholders'\nimport { isPlain, type PenPlacement } from './placement'\nimport { applyPenPluginData, UNRESOLVED_REF } from './plugin-data'\nimport type { NodeFields, PenNode, PenOverride } from './schema'\nimport { createPenSlot } from './slots'\nimport { applyTextProps } from './text'\nimport { bindIfVar, resolveBoolean, resolveNumber, type VarContext } from './variables'\n\n/** Where icon glyphs come from, as the host loaded them. */\nexport interface PenIconSource {\n /**\n * Draws the icon `name` into the frame, `size` square at its origin, painted `color` where the\n * icon takes its colour and drawn with `options` where its set has them. False when the source\n * does not have it.\n */\n draw(\n graph: SceneGraph,\n frameId: string,\n name: string,\n size: number,\n color: Color,\n options?: Record<string, number>\n ): boolean\n}\n\n/** What reading one document builds up. */\nexport interface Build {\n graph: SceneGraph\n ctx: VarContext\n images: PenImages\n /** Shader files the document's paints and effects name, by URL, as their source. */\n shaders: PenShaderSources | undefined\n icons: PenIconSource | undefined\n /** The family and style of each font the document bundles, by the name its text gives it. */\n fonts: ReadonlyMap<string, FontFamilyStyle>\n /** Reusable nodes by their pen.dev ID. */\n components: Map<string, PenNode>\n /** The pen.dev fields each layer was built from, its instance's and overrides' merged in. */\n effective: Map<string, PenNode>\n /** Instances in reading order, with the `ref` node that made each. */\n instances: Map<string, PenNode>\n /** pen.dev's placement of each turned or mirrored layer, and of every group. */\n placements: Map<string, PenPlacement>\n /** Groups in reading order. */\n groupIds: Set<string>\n /** Called with a node type the reader does not know. */\n onUnknownNodeType?: (type: string) => void\n /** The components icons in components are instances of, by glyph and size. */\n iconComponents: Map<string, string>\n /** The page those components are on, added with the first one. */\n iconPageId: string | null\n /** Layers whose children an override replaced, whose instances are detached. */\n replaced: Set<string>\n}\n\nfunction penPlacement(pen: PenOverride, ctx: VarContext): PenPlacement {\n return {\n x: pen.x ?? 0,\n y: pen.y ?? 0,\n rotation: resolveNumber(pen.rotation, ctx),\n flipX: resolveBoolean(pen.flipX, ctx, false),\n flipY: resolveBoolean(pen.flipY, ctx, false)\n }\n}\n\n/**\n * A `line` runs from its box's top-left corner to its bottom-right, so a line with no height is\n * a line layer and any other one a vector drawn across its box.\n */\nfunction isFlatLine(pen: PenNode, ctx: VarContext): boolean {\n const height = parseSize(pen.height, 100, ctx)\n return height.sizing === 'FIXED' && height.value === 0\n}\n\nconst KNOWN_PEN_TYPES = new Set([\n 'frame',\n 'line',\n 'rectangle',\n 'ellipse',\n 'polygon',\n 'group',\n 'text',\n 'icon_font',\n 'path',\n 'icon',\n 'sticky',\n 'ref',\n // The annotation cards read as stickies; they are known types, not placeholders.\n ...ANNOTATION_TYPES\n])\n\nfunction sceneType(pen: PenNode, ctx: VarContext, warn?: (type: string) => void): NodeType {\n if (!KNOWN_PEN_TYPES.has(pen.type)) warn?.(pen.type)\n if (pen.type === 'frame') return pen.reusable ? 'COMPONENT' : 'FRAME'\n if (pen.type === 'line') return isFlatLine(pen, ctx) ? 'LINE' : 'VECTOR'\n if (isAnnotation(pen)) return 'STICKY'\n if (pen.type === 'rectangle') return 'RECTANGLE'\n if (pen.type === 'ellipse') return 'ELLIPSE'\n if (pen.type === 'polygon') return 'POLYGON'\n if (pen.type === 'group') return 'GROUP'\n if (pen.type === 'text' || pen.type === 'icon_font') return 'TEXT'\n if (pen.type === 'path') return 'VECTOR'\n return 'FRAME'\n}\n\nfunction resolveSizing(pen: PenNode, ctx: VarContext) {\n const isTextLike = pen.type === 'text' || pen.type === 'icon_font'\n const defaultSize = isTextLike ? 20 : 100\n const defaultW = isTextLike && pen.width === undefined ? 0 : defaultSize\n const w = parseSize(pen.width, defaultW, ctx)\n const h = parseSize(pen.height, defaultSize, ctx)\n const layout = mapLayoutMode(pen)\n\n if (pen.width === undefined && layout !== 'NONE') w.sizing = 'HUG'\n if (pen.height === undefined && layout !== 'NONE') h.sizing = 'HUG'\n\n return { w, h, layout, isTextLike }\n}\n\nfunction applyAutoLayout(\n node: SceneNode,\n layoutMode: LayoutMode,\n pen: PenNode,\n widthSizing: LayoutSizing,\n heightSizing: LayoutSizing,\n ctx: VarContext\n): void {\n node.layoutMode = layoutMode\n node.primaryAxisAlign = mapJustifyContent(pen.justifyContent)\n node.counterAxisAlign = mapAlignItems(pen.alignItems)\n node.itemSpacing = resolveNumber(pen.gap, ctx)\n bindIfVar(node, 'itemSpacing', pen.gap, ctx)\n node.strokesIncludedInLayout = pen.layoutIncludeStroke ?? false\n\n // Fill is the child's grow or stretch, set with its parent; the frame itself stays fixed.\n const own = (sizing: LayoutSizing): AxisSizingMode => (sizing === 'HUG' ? 'HUG' : 'FIXED')\n if (layoutMode === 'VERTICAL') {\n node.primaryAxisSizing = own(heightSizing)\n node.counterAxisSizing = own(widthSizing)\n } else {\n node.primaryAxisSizing = own(widthSizing)\n node.counterAxisSizing = own(heightSizing)\n }\n // pen.dev keeps `gap` between children under `space_between`, as CSS does; auto layout drops it.\n // A hugging frame has no free space to spread, so packing it from the start lays it out the same.\n if (node.primaryAxisAlign === 'SPACE_BETWEEN' && node.primaryAxisSizing === 'HUG') {\n node.primaryAxisAlign = 'MIN'\n }\n}\n\nconst PLACEMENT_FIELDS = ['x', 'y', 'rotation', 'flipX', 'flipY'] as const\n\n/** What `applyStroke` writes: a stroke's weight and alignment are its paints'. */\nconst STROKE_WRITES = [\n 'strokes',\n 'independentStrokeWeights',\n 'borderTopWeight',\n 'borderRightWeight',\n 'borderBottomWeight',\n 'borderLeftWeight',\n 'strokeCap',\n 'strokeJoin'\n] as const\n\n/**\n * The layer fields each property `applyPenProperties` reads writes. A property that writes none of\n * the layer's own fields maps to none: bookkeeping, the decorations pen.dev does not draw, and an\n * icon's glyph, which is the layer's children or the component it shows.\n */\nconst PROPERTY_FIELDS = {\n name: ['name'],\n context: ['pluginData'],\n metadata: ['pluginData'],\n x: PLACEMENT_FIELDS,\n y: PLACEMENT_FIELDS,\n width: ['width'],\n height: ['height'],\n reusable: [],\n theme: ['variableModes'],\n enabled: ['visible'],\n opacity: ['opacity'],\n flipX: PLACEMENT_FIELDS,\n flipY: PLACEMENT_FIELDS,\n layoutPosition: ['layoutPositioning'],\n rotation: PLACEMENT_FIELDS,\n fill: ['fills'],\n stroke: STROKE_WRITES,\n strokeWidth: STROKE_WRITES,\n strokeLinecap: ['strokes', 'strokeCap'],\n strokeLinejoin: ['strokes', 'strokeJoin'],\n strokeAlignment: ['strokes'],\n effect: ['effects'],\n cornerRadius: CORNER_FIELDS,\n layout: ['layoutMode'],\n gap: ['itemSpacing'],\n layoutIncludeStroke: ['strokesIncludedInLayout'],\n padding: ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'],\n justifyContent: ['primaryAxisAlign'],\n alignItems: ['counterAxisAlign'],\n clip: ['clipsContent'],\n status: ['status'],\n placeholder: ['pluginData'],\n slot: ['pluginData'],\n innerRadius: ['arcData'],\n startAngle: ['arcData'],\n sweepAngle: ['arcData'],\n polygonCount: ['pointCount'],\n geometry: ['vectorNetwork'],\n fillRule: ['vectorNetwork'],\n viewBox: ['vectorNetwork'],\n content: ['text'],\n textGrowth: ['textAutoResize'],\n fontFamily: ['fontFamily'],\n fontSize: ['fontSize'],\n fontWeight: ['fontWeight'],\n fontStyle: ['italic'],\n letterSpacing: ['letterSpacing'],\n lineHeight: ['lineHeight'],\n textAlign: ['textAlignHorizontal'],\n textAlignVertical: ['textAlignVertical'],\n underline: [],\n strikethrough: [],\n href: ['styleRuns'],\n library: [],\n icon: [],\n weight: [],\n iconFontName: [],\n iconFontFamily: [],\n ref: [],\n model: ['pluginData'],\n scriptUri: ['pluginData'],\n inputs: ['pluginData'],\n url: ['pluginData'],\n deviceId: ['pluginData'],\n zoom: ['pluginData'],\n scrollX: ['pluginData'],\n scrollY: ['pluginData']\n} satisfies Record<keyof NodeFields, readonly (keyof SceneNode)[]>\n\nconst isProperty = (key: string): key is keyof typeof PROPERTY_FIELDS => key in PROPERTY_FIELDS\n\n/**\n * The fields the properties `pen` carries write, whatever their values: pen.dev keeps a property\n * an instance sets even when it equals its component's, so a later change to the component does\n * not reach it.\n */\nexport function fieldsSetBy(pen: PenOverride): (keyof SceneNode)[] {\n return Object.keys(pen).flatMap((key) => (isProperty(key) ? PROPERTY_FIELDS[key] : []))\n}\n\nfunction drawIconLayer(node: SceneNode, pen: PenNode, build: Build): void {\n if (node.type === 'INSTANCE') useIconComponent(node, pen, build)\n else drawIcon(node, pen, build)\n}\n\n/**\n * Draws a filling or fitting icon again at its laid-out size, which reading it could only guess.\n * Drawing takes the icon's colour from its fill and moves it to the glyph, so the fill is read again.\n */\nexport function redrawIconAtLaidOutSize(node: SceneNode, pen: PenNode, build: Build): void {\n const { w, h } = resolveSizing(pen, build.ctx)\n if (w.sizing === 'FIXED' && h.sizing === 'FIXED') return\n node.fills = convertPaints(pen.fill, 'fills', build.ctx, node, build.images, build.shaders)\n drawIconLayer(node, pen, build)\n}\n\n/**\n * Sets every field a layer takes from its pen.dev fields, so a layer copied from a component can be\n * given its overrides by applying its merged fields again. Turned and mirrored layers are built\n * upright and placed once laid out.\n */\n// eslint-disable-next-line complexity -- .pen node mapping touches many format-specific fields\nexport function applyPenProperties(node: SceneNode, pen: PenNode, build: Build): void {\n if (node.type === 'STICKY') {\n applyAnnotation(node, pen, build)\n return\n }\n const { graph, ctx } = build\n const { w, h, layout, isTextLike } = resolveSizing(pen, ctx)\n const hasChildren = (pen.children?.length ?? 0) > 0 || node.childIds.length > 0\n const parentLayout = (node.parentId && graph.getNode(node.parentId)?.layoutMode) || 'NONE'\n // An absolute layer leaves its parent's flow; fill sizing then falls back to its value.\n const absolute = pen.layoutPosition === 'absolute' && parentLayout !== 'NONE'\n const flowLayout = absolute ? 'NONE' : parentLayout\n\n Object.assign(node, {\n name: pen.name ?? (pen.type === 'icon_font' ? (pen.iconFontName ?? 'Icon') : pen.type),\n x: pen.x ?? 0,\n y: pen.y ?? 0,\n rotation: 0,\n flipX: false,\n flipY: false,\n width: w.value,\n height: h.value,\n minWidth: !hasChildren && w.fitContentFallback !== undefined ? w.fitContentFallback : null,\n minHeight: !hasChildren && h.fitContentFallback !== undefined ? h.fitContentFallback : null,\n visible: resolveBoolean(pen.enabled, ctx),\n opacity: resolveNumber(pen.opacity, ctx, 1),\n clipsContent: resolveBoolean(pen.clip, ctx, false),\n status: pen.status ?? null,\n layoutPositioning: absolute ? 'ABSOLUTE' : 'AUTO',\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO',\n boundVariables: {},\n variableModes: pen.theme ? ctx.variableModes(pen.theme) : {}\n } satisfies Partial<SceneNode>)\n bindIfVar(node, 'visible', pen.enabled, ctx)\n bindIfVar(node, 'opacity', pen.opacity, ctx)\n bindIfVar(node, 'width', pen.width, ctx)\n bindIfVar(node, 'height', pen.height, ctx)\n\n node.layoutMode = 'NONE'\n if (layout !== 'NONE') {\n const widthSizing = flowLayout === 'NONE' && w.sizing === 'FILL' ? 'FIXED' : w.sizing\n const heightSizing = flowLayout === 'NONE' && h.sizing === 'FILL' ? 'FIXED' : h.sizing\n applyAutoLayout(node, layout, pen, widthSizing, heightSizing, ctx)\n }\n\n const placement = penPlacement(pen, ctx)\n if (pen.type === 'group') build.groupIds.add(node.id)\n if (pen.type === 'group' || !isPlain(placement)) build.placements.set(node.id, placement)\n else build.placements.delete(node.id)\n\n node.fills = convertPaints(pen.fill, 'fills', ctx, node, build.images, build.shaders)\n applyStroke(node, strokeFields(pen), ctx, build.images, build.shaders)\n // A line layer has no inside or outside; its stroke is centred on it.\n if (node.type === 'LINE')\n node.strokes = node.strokes.map((paint) => ({ ...paint, align: 'CENTER' }))\n node.effects = normalizeEffects(convertEffects(pen.effect, ctx, build.shaders))\n applyCornerRadius(node, pen.cornerRadius, ctx)\n applyPadding(node, pen.padding, ctx)\n\n // Text without a width resizes to its content, which laying out the document measures.\n if (isTextLike) applyTextProps(node, pen, ctx, build.fonts)\n\n if (pen.type === 'icon') drawIconLayer(node, pen, build)\n if (pen.type === 'ellipse') node.arcData = ellipseArc(pen, ctx)\n if (pen.type === 'polygon') node.pointCount = Math.max(3, resolveNumber(pen.polygonCount, ctx, 3))\n\n if (flowLayout !== 'NONE') {\n if (w.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'HORIZONTAL'))\n if (h.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'VERTICAL'))\n }\n if (isPlaceholder(pen)) applyPlaceholderLook(node, pen)\n applyPenPluginData(node, pen)\n build.effective.set(node.id, pen)\n}\n\n/**\n * The fields an instance draws with: its component's, with the `ref` node's own replacing them one\n * by one, as pen.dev reads them. A theme on both merges axis by axis. A `ref` whose component is\n * missing, such as one from a library the host could not read, is a placeholder naming it.\n */\nfunction instanceFields(ref: PenNode, component: PenNode | undefined): PenNode {\n const { ref: _ref, type: _type, descendants: _descendants, children: _children, ...own } = ref\n if (!component) return { ...own, type: 'frame', [UNRESOLVED_REF]: ref.ref ?? '' }\n const {\n id: _id,\n reusable: _reusable,\n ref: _componentRef,\n children: _componentChildren,\n descendants: _componentDescendants,\n ...inherited\n } = component\n const theme = component.theme || ref.theme ? { ...component.theme, ...ref.theme } : undefined\n return { ...inherited, ...own, theme, name: ref.name ?? component.name }\n}\n\n/**\n * Builds the layers inside a layer that is no instance: a `ref`'s copies of its component's, named\n * by the path to them, or the layer's own, then a placeholder's label and a slot.\n */\nfunction createChildren(node: SceneNode, pen: PenNode, fields: PenNode, build: Build): void {\n const component = pen.type === 'ref' && pen.ref ? build.components.get(pen.ref) : undefined\n const children = pen.type === 'ref' ? (component?.children ?? []) : (pen.children ?? [])\n for (const child of children) {\n createSceneNode(\n pen.type === 'ref' ? { ...child, id: `${pen.id}/${child.id}` } : child,\n node.id,\n build\n )\n }\n const label = placeholderLabel(fields, node.id)\n if (label) createSceneNode(label, node.id, build)\n createPenSlot(node, fields, build)\n}\n\n/** Builds a layer and its children in the layer's theme, merged over its parent's. */\nexport function createSceneNode(pen: PenNode, parentId: string, build: Build): string {\n const component = pen.type === 'ref' && pen.ref ? build.components.get(pen.ref) : undefined\n // A component that is not a frame has no instances; its uses are plain copies.\n const instanceOf = pen.type === 'ref' && component?.type === 'frame' ? component : undefined\n const fields = pen.type === 'ref' ? instanceFields(pen, component) : pen\n const iconInstance = fields.type === 'icon' && insideComponent(build.graph, parentId)\n const leaveTheme = fields.theme ? build.ctx.enterTheme(fields.theme) : undefined\n try {\n const type =\n instanceOf || iconInstance\n ? 'INSTANCE'\n : sceneType(fields, build.ctx, build.onUnknownNodeType)\n // An ID a hand-edited file repeats gets a fresh one, so the layer does not replace the first\n // layer with it or become its own parent.\n const id = build.graph.getNode(pen.id) ? build.graph.entityIdMinter()() : pen.id\n const node =\n type === 'STICKY'\n ? createAnnotation({ ...fields, id }, parentId, build)\n : build.graph.createNode(type, parentId, { id })\n applyPenProperties(node, fields, build)\n if (instanceOf) {\n node.componentId = instanceOf.id\n build.instances.set(node.id, pen)\n } else {\n createChildren(node, pen, fields, build)\n }\n return node.id\n } finally {\n leaveTheme?.()\n }\n}\n","import { pick } from 'es-toolkit/object'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport { generateId, type SceneGraph, type SceneNode } from '@pairdraw/scene-graph'\nimport {\n detachInstance,\n INSTANCE_OVERRIDE_FIELDS,\n populateInstanceChildren,\n recordInstanceOverride,\n swapInstanceComponent\n} from '@pairdraw/scene-graph/instances'\n\nimport { applyPenProperties, createSceneNode, fieldsSetBy, type Build } from './nodes'\nimport type { PenNode, PenOverride } from './schema'\nimport { claimSlot } from './slots'\n\n/** Fills an instance read from `.pen`, after the instances inside its component. */\ntype Populate = (id: string) => void\n\n/** The layers a copy was made from, nearest first, through copies of copies. */\nfunction sources(graph: SceneGraph, node: SceneNode): Set<string> {\n const found = new Set<string>()\n for (\n let id = node.componentId;\n id && !found.has(id);\n id = graph.getNode(id)?.componentId ?? null\n ) {\n found.add(id)\n }\n return found\n}\n\n/** The pen.dev layer a layer was built from, which a component swap stops naming. */\nfunction penLayerId(build: Build, node: SceneNode): string | undefined {\n return build.effective.get(node.id)?.id\n}\n\n/** The copy in `root`'s layers made from the pen.dev layer `sourceId`, at any depth. */\nfunction findCopy(build: Build, root: SceneNode, sourceId: string): SceneNode | undefined {\n const { graph } = build\n const queue = graph.getChildren(root.id)\n for (const node of queue) {\n if (penLayerId(build, node) === sourceId || sources(graph, node).has(sourceId)) return node\n queue.push(...graph.getChildren(node.id))\n }\n return undefined\n}\n\n/**\n * The layer an override's key names: pen.dev IDs separated by `/`, each one inside the copy of the\n * instance the one before it names.\n */\nfunction resolvePath(build: Build, instance: SceneNode, path: string): SceneNode | undefined {\n let current: SceneNode | undefined = instance\n for (const id of path.split('/')) {\n current = current ? findCopy(build, current, id) : undefined\n }\n return current\n}\n\n/** Runs `apply` in the merged theme of a layer's ancestors, as the layer was read in. */\nexport function inAncestorThemes<T>(build: Build, node: SceneNode, apply: () => T): T {\n const chain: Record<string, string>[] = []\n for (let id = node.parentId; id; id = build.graph.getNode(id)?.parentId ?? null) {\n const theme = build.effective.get(id)?.theme\n if (theme) chain.unshift(theme)\n }\n const leave = chain.map((theme) => build.ctx.enterTheme(theme))\n try {\n return apply()\n } finally {\n for (const exit of leave.toReversed()) exit()\n }\n}\n\nfunction replaceLayer(\n build: Build,\n target: SceneNode,\n replacement: PenOverride,\n populate: Populate\n): void {\n const { graph } = build\n const parentId = target.parentId\n if (!parentId) return\n if (swapLayer(build, target, replacement, populate)) return\n const index = graph.getNode(parentId)?.childIds.indexOf(target.id) ?? -1\n const pen: PenNode = {\n ...replacement,\n type: replacement.type ?? 'frame',\n id: replacement.id ?? generateId()\n }\n inAncestorThemes(build, target, () => {\n graph.deleteNode(target.id)\n const id = createSceneNode(pen, parentId, build)\n if (id && index >= 0) graph.insertChildAt(id, parentId, index)\n // The parent's layers changed; a replacement that is itself an instance stays one.\n if (id) build.replaced.add(parentId)\n })\n}\n\n/**\n * Swaps a nested instance an override replaces with an instance of another component for that\n * component, as Figma's instance swap does, so the instances holding it stay instances. The\n * replacement's own fields and overrides then apply to the swapped layer. Returns whether it\n * swapped; any other replacement changes the layers of the instance holding it.\n */\nfunction swapLayer(\n build: Build,\n target: SceneNode,\n replacement: PenOverride,\n populate: Populate\n): boolean {\n const { graph, effective, instances } = build\n const component =\n typeof replacement.ref === 'string' ? build.components.get(replacement.ref) : undefined\n if (target.type !== 'INSTANCE' || replacement.type !== 'ref' || component?.type !== 'frame')\n return false\n for (const nested of instances.keys()) {\n if (graph.isDescendant(nested, component.id)) populate(nested)\n }\n swapInstanceComponent(graph, target.id, component.id)\n if (graph.getNode(target.id)?.componentId !== component.id) return false\n const {\n children: _children,\n reusable: _reusable,\n descendants: _descendants,\n ...fields\n } = component\n effective.set(target.id, { ...fields, id: target.id })\n inheritCopyFields(build, target)\n const { ref: _ref, type: _type, id: _id, descendants, ...own } = replacement\n overrideLayer(build, target, own)\n applyDescendants(build, target, descendants, populate)\n return true\n}\n\n/**\n * Records as the instance's overrides the fields an override set or changed on a copy, so they\n * survive the instance's next sync and a save, as an edit made in the editor would.\n */\nfunction recordChangedFields(\n graph: SceneGraph,\n target: SceneNode,\n before: Partial<SceneNode>,\n override: PenOverride\n): void {\n const changed = INSTANCE_OVERRIDE_FIELDS.filter((field) => !isEqual(before[field], target[field]))\n recordInstanceOverride(graph, target.id, [...changed, ...fieldsSetBy(override)])\n}\n\n/**\n * Records as the instance's own overrides the fields its `ref` sets or makes differ from its\n * component's. A size counts only when the `ref` sets it: otherwise it is the layout's, which\n * follows the component's.\n */\nfunction recordOwnFields(graph: SceneGraph, instance: SceneNode, ref: PenNode): void {\n const component = instance.componentId ? graph.getNode(instance.componentId) : undefined\n if (!component) return\n const changed = INSTANCE_OVERRIDE_FIELDS.filter(\n (field) =>\n (field !== 'width' || 'width' in ref) &&\n (field !== 'height' || 'height' in ref) &&\n !isEqual(instance[field], component[field])\n )\n recordInstanceOverride(graph, instance.id, [...changed, ...fieldsSetBy(ref)])\n}\n\n/**\n * Gives a copy an override's fields. Children the override gives a slot of `instance` become the\n * instance's content for that slot; any other layer's children are replaced, which detaches the\n * instances holding it.\n */\nfunction overrideLayer(\n build: Build,\n target: SceneNode,\n override: PenOverride,\n instance?: SceneNode\n): void {\n const { graph, ctx, effective } = build\n const base = effective.get(target.id) ?? { type: 'frame', id: target.id }\n const { descendants: _descendants, children, ...fields } = override\n const merged: PenNode = { ...base, ...fields, type: base.type, id: base.id }\n const before = structuredClone(pick(target, INSTANCE_OVERRIDE_FIELDS))\n inAncestorThemes(build, target, () => {\n const leave = merged.theme ? ctx.enterTheme(merged.theme) : undefined\n try {\n // Children that replace the layer's own decide its size, as a fit_content(N) fallback holds\n // only while the layer is empty, so the old ones go first.\n if (children) for (const childId of target.childIds) graph.deleteNode(childId)\n applyPenProperties(target, children ? { ...merged, children } : merged, build)\n recordChangedFields(graph, target, before, fields)\n if (children) {\n const fillsSlot = instance !== undefined && claimSlot(build, instance, target)\n for (const child of children) createSceneNode(child, target.id, build)\n if (!fillsSlot) build.replaced.add(target.id)\n }\n } finally {\n leave?.()\n }\n })\n}\n\n/**\n * Detaches the instances holding a layer whose children an override replaced. An instance keeps\n * its component's layers, overriding their fields but never replacing them, so such an instance\n * becomes a frame that keeps what it shows, as detaching it in Figma does.\n */\nfunction detachReplacingInstances(build: Build): void {\n const { graph } = build\n for (const id of build.replaced) {\n for (let node = graph.getNode(id); node;) {\n if (node.type === 'INSTANCE') detachInstance(graph, node.id)\n node = node.parentId ? graph.getNode(node.parentId) : undefined\n }\n }\n build.replaced.clear()\n}\n\n/** Gives an instance's copies their overrides; a key with a `type` replaces the layer. */\nfunction applyDescendants(\n build: Build,\n instance: SceneNode,\n descendants: PenNode['descendants'],\n populate: Populate\n): void {\n for (const [path, override] of Object.entries(descendants ?? {})) {\n const target = resolvePath(build, instance, path)\n if (!target) continue\n if (override.type) replaceLayer(build, target, override, populate)\n else overrideLayer(build, target, override, instance)\n }\n}\n\n/** Gives each copy inside `root` the pen.dev fields and placement of the layer it copies. */\nfunction inheritCopyFields(build: Build, root: SceneNode): void {\n const { graph, effective, placements } = build\n const copies = graph.getChildren(root.id)\n for (const copy of copies) {\n const source = copy.componentId\n const fields = source ? effective.get(source) : undefined\n if (fields) effective.set(copy.id, fields)\n const placement = source ? placements.get(source) : undefined\n if (placement) placements.set(copy.id, placement)\n if (source && build.groupIds.has(source)) build.groupIds.add(copy.id)\n copies.push(...graph.getChildren(copy.id))\n }\n}\n\n/**\n * Fills each instance with copies of its component's layers, then applies its overrides. An\n * instance inside a component is filled first, so the copies made of it carry its layers and\n * overrides; a copy keeps its source's pen.dev fields and placement.\n */\nexport function populateInstances(build: Build): void {\n const { graph, instances } = build\n const done = new Set<string>()\n\n function populate(id: string): void {\n if (done.has(id)) return\n done.add(id)\n const instance = graph.getNode(id)\n const ref = instances.get(id)\n if (!instance?.componentId || !ref) return\n const component = graph.getNode(instance.componentId)\n if (!component) return\n for (const nested of instances.keys()) {\n if (graph.isDescendant(nested, component.id)) populate(nested)\n }\n populateInstanceChildren(graph, instance.id, component.id)\n recordOwnFields(graph, instance, ref)\n inheritCopyFields(build, instance)\n applyDescendants(build, instance, ref.descendants, populate)\n // pen.dev draws a ref's own children in place of its component's, whether or not the\n // component declares a `slot`; like an override's children, they detach the instance.\n if (ref.children) overrideLayer(build, instance, { children: ref.children })\n // Before anything copies this instance, so the copies are of what it became.\n detachReplacingInstances(build)\n }\n\n // A replacement may hold instances of its own, which join the map as they are read.\n for (const id of instances.keys()) populate(id)\n}\n","import * as v from 'valibot'\n\nimport { SceneGraph } from '@pairdraw/scene-graph'\nimport { writeDesignMemory } from '@pairdraw/scene-graph/design-memory'\nimport type { FontFamilyStyle } from '@pairdraw/scene-graph/font-style'\nimport { writeStatusWorkflow } from '@pairdraw/scene-graph/statuses'\nimport { rekeyTokenSources, tokenSourcesPluginData } from '@pairdraw/scene-graph/token-sources'\n\nimport { writeLibraryLinks } from './document-libraries'\nimport { lineNetwork, pathNetwork } from './geometry'\nimport { removeUnusedIconComponents } from './icons'\nimport { createImageStore } from './images'\nimport { withImports, type PenImports } from './imports'\nimport { inAncestorThemes, populateInstances } from './instances'\nimport { createLibraryRoots, markLibraryRoots } from './library'\nimport { createSceneNode, redrawIconAtLaidOutSize, type Build, type PenIconSource } from './nodes'\nimport { placeLayers } from './placement'\nimport { penFileSchema, type PenDocument, type PenNode } from './schema'\nimport { buildVarContext } from './variables'\n\n/** Options for reading a document. */\nexport interface PenReadOptions {\n /**\n * Lays out the graph's auto layout and text, as `layoutAuthoredNodes` in Core does. Turned and\n * mirrored layers are placed after it, since where they land depends on their final size.\n */\n layout?(graph: SceneGraph): void\n /** The image files the document's paints name, by their URL in it; see `penAssets`. */\n images?: ReadonlyMap<string, Uint8Array>\n /**\n * The shader files the document's paints and effects name, by their URL in it, as their source\n * text; see `penAssets`. A shader whose file is missing draws nothing.\n */\n shaders?: ReadonlyMap<string, string>\n /** Where icon glyphs come from; icons are empty frames without it. */\n icons?: PenIconSource\n /**\n * The family and style each bundled font file names itself with, by its `name` in the\n * document's `fonts`. pen.dev registers a bundled file under that name, such as\n * `Geist-SemiBold`, and its text uses it as the family; the text takes the file's own names.\n */\n fonts?: ReadonlyMap<string, FontFamilyStyle>\n /**\n * The documents the document imports, by alias, as `importedDocument` gives them. Their\n * variables join the document's as `<alias>:<name>`, and the components it uses, as\n * `<alias>:<id>`, go on the hidden library page as read-only library definitions. A `ref` to a\n * component no import has reads as a placeholder.\n */\n imports?: PenImports\n /** Called with a variable a layer references that the document does not define. */\n onUnknownVariable?(name: string): void\n /** Called with a node type the reader does not know, which reads as a placeholder frame. */\n onUnknownNodeType?(type: string): void\n}\n\nfunction collectComponents(nodes: PenNode[], components: Map<string, PenNode>): void {\n for (const node of nodes) {\n if (node.reusable) components.set(node.id, node)\n if (node.children) collectComponents(node.children, components)\n }\n}\n\n/** Whether a group sits in an auto layout's flow, where fitting it changes the layout. */\nfunction groupsInFlow(graph: SceneGraph, groupIds: Iterable<string>): boolean {\n for (const id of groupIds) {\n const group = graph.getNode(id)\n const parent = group?.parentId ? graph.getNode(group.parentId) : undefined\n if (parent && parent.layoutMode !== 'NONE') return true\n }\n return false\n}\n\n/**\n * Draws each path and slanted line in its box once boxes have their final size, which fill and\n * fit sizing only give once laid out, and redraws each icon laying out sized.\n */\nfunction drawAtFinalSize(build: Build, laidOut: boolean): void {\n for (const [id, pen] of build.effective) {\n const node = build.graph.getNode(id)\n if (!node) continue\n if (pen.type === 'path') {\n const network = pathNetwork(pen, node.width, node.height)\n if (network) node.vectorNetwork = network\n } else if (pen.type === 'line' && node.type === 'VECTOR') {\n node.vectorNetwork = lineNetwork(node.width, node.height)\n } else if (pen.type === 'icon' && laidOut) {\n // In the themes the icon was read in, which its colour and glyph may take variables from.\n inAncestorThemes(build, node, () => {\n const leave = pen.theme ? build.ctx.enterTheme(pen.theme) : undefined\n try {\n redrawIconAtLaidOutSize(node, pen, build)\n } finally {\n leave?.()\n }\n })\n }\n }\n}\n\n/** A `.pen` document's JSON, validated; throws for text that is not one. */\nexport function parsePenDocument(json: string): PenDocument {\n const parsed = v.safeParse(penFileSchema, json)\n if (!parsed.success) {\n throw new Error(`Not a .pen document: ${v.summarize(parsed.issues)}`)\n }\n return parsed.output\n}\n\n/** Builds the scene graph of a document `parsePenDocument` read. */\nexport function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): SceneGraph {\n const graph = new SceneGraph()\n\n for (const page of graph.getPages(true)) {\n graph.deleteNode(page.id)\n }\n\n const imports: PenImports = options.imports ?? new Map()\n const build: Build = {\n graph,\n ctx: buildVarContext(graph, withImports(doc, imports), (name) =>\n options.onUnknownVariable?.(name)\n ),\n images: createImageStore(graph, options.images),\n shaders: options.shaders,\n icons: options.icons,\n fonts: options.fonts ?? new Map(),\n components: new Map(),\n effective: new Map(),\n instances: new Map(),\n placements: new Map(),\n groupIds: new Set(),\n iconComponents: new Map(),\n iconPageId: null,\n replaced: new Set(),\n onUnknownNodeType: (type) => options.onUnknownNodeType?.(type)\n }\n collectComponents(doc.children, build.components)\n for (const imported of imports.values())\n collectComponents(imported.doc.children, build.components)\n\n const page = graph.addPage(doc.name ?? doc.children[0]?.name ?? 'Page 1')\n for (const child of doc.children) createSceneNode(child, page.id, build)\n const libraryRoots = createLibraryRoots(doc, imports, build, createSceneNode)\n populateInstances(build)\n\n options.layout?.(graph)\n drawAtFinalSize(build, options.layout !== undefined)\n placeLayers(graph, build.placements, [...build.groupIds])\n if (options.layout && groupsInFlow(graph, build.groupIds)) {\n options.layout(graph)\n drawAtFinalSize(build, true)\n }\n removeUnusedIconComponents(build)\n markLibraryRoots(graph, libraryRoots)\n\n if (graph.getPages(true).length === 0) {\n graph.addPage('Page 1')\n }\n if (doc.tokenSources && doc.tokenSources.length > 0) {\n graph.updateNode(graph.rootId, {\n pluginData: tokenSourcesPluginData(graph, rekeyTokenSources(graph, doc.tokenSources))\n })\n }\n // After the links, which replace the document node's plugin data: the memory is stored beside them.\n if (doc.designMemory) writeDesignMemory(graph, doc.designMemory)\n if (doc.statuses) writeStatusWorkflow(graph, doc.statuses)\n writeLibraryLinks(graph, doc)\n\n return graph\n}\n\nexport function parsePenFile(json: string, options: PenReadOptions = {}): SceneGraph {\n return buildPenGraph(parsePenDocument(json), options)\n}\n\nexport async function readPenFile(file: File, options?: PenReadOptions): Promise<SceneGraph> {\n return parsePenFile(await file.text(), options)\n}\n","import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\n/**\n * Collects the nodes `writeNode` emits. Instance subtrees are skipped because a ref writes\n * no children; an instance whose component is missing here is written as a frame instead.\n */\nexport function writtenNodeIds(graph: SceneGraph): Set<string> {\n const ids = new Set<string>()\n const visit = (node: SceneNode): void => {\n if (node.internalOnly) return\n ids.add(node.id)\n if (node.type === 'STICKY' || node.type === 'INSTANCE') return\n for (const child of graph.getChildren(node.id)) visit(child)\n }\n for (const page of graph.getPages()) for (const node of graph.getChildren(page.id)) visit(node)\n return ids\n}\n","import { isEqual } from 'es-toolkit'\nimport { fromUint8Array } from 'js-base64'\n\nimport type {\n BlendMode,\n EnabledLibraryBinding,\n Fill,\n GradientTransform,\n LayoutAlign,\n LayoutCounterAlign,\n SceneGraph,\n SceneNode,\n ShadowEffect,\n Stroke,\n Variable,\n VariableCollection,\n VariableValue\n} from '@pairdraw/scene-graph'\nimport { SceneGraph as SceneGraphValue } from '@pairdraw/scene-graph'\nimport { colorToHex, colorToHex8 } from '@pairdraw/scene-graph/color'\nimport { getNodeLocalMatrix } from '@pairdraw/scene-graph/coordinate'\nimport { readDesignMemory } from '@pairdraw/scene-graph/design-memory'\nimport { stickySublayers } from '@pairdraw/scene-graph/generated'\nimport { applyGradientTransform, invertGradientTransform } from '@pairdraw/scene-graph/gradient'\nimport { imageMimeType } from '@pairdraw/scene-graph/images'\nimport { layoutSizing } from '@pairdraw/scene-graph/layout'\nimport type { Color, Vector } from '@pairdraw/scene-graph/primitives'\nimport { readStoredStatusWorkflow } from '@pairdraw/scene-graph/statuses'\nimport { readTokenSources, type TokenSource } from '@pairdraw/scene-graph/token-sources'\n\nimport { readPenImports, readSourceLibraryPublication } from './document-libraries'\nimport { networkToSVGPath } from './geometry'\nimport { penCropTransform } from './images'\nimport { importedComponentIds } from './library'\nimport { PEN_PLUGIN_DATA_NAMESPACE, readIconOrigin } from './plugin-data'\nimport type {\n PenDocument,\n PenEffect,\n PenOverride,\n PenImagePaint,\n PenNode,\n PenNumber,\n PenPaint,\n PenPaints,\n PenSides,\n PenVariable,\n PenVariableScalar\n} from './schema'\nimport { writtenNodeIds } from './written-nodes'\nconst PEN_VERSION = '2.21'\nconst PEN_PLUGIN_FIELDS: Readonly<Partial<Record<string, string>>> = {\n 'pen/type': 'type',\n 'pen/ref': 'ref',\n 'pen/generated': 'generated',\n 'pen/context': 'context',\n 'pen/metadata': 'metadata',\n 'pen/placeholder': 'placeholder',\n 'pen/slot': 'slot',\n 'pen/model': 'model',\n 'pen/scriptUri': 'scriptUri',\n 'pen/inputs': 'inputs',\n 'pen/url': 'url',\n 'pen/deviceId': 'deviceId',\n 'pen/zoom': 'zoom',\n 'pen/scrollX': 'scrollX',\n 'pen/scrollY': 'scrollY'\n}\n\ntype PenWriteState = {\n graph: SceneGraph\n variables: ReadonlyMap<string, Variable>\n collections: ReadonlyMap<string, VariableCollection>\n /** Nodes the document will contain, so an instance refs only a component that is written. */\n writtenIds: ReadonlySet<string>\n /** Components the file resolves through its `imports`, which a ref may name without writing them. */\n importedIds: ReadonlySet<string>\n /** What the file cannot hold, reported once writing leaves it out. */\n warnings: string[]\n /** The same facts as kinds, for a host that shows them in its own language. */\n details: PenWriteWarning[]\n drops: {\n images: number\n effects: number\n filters: number\n scroll: number\n fontFeatures: number\n }\n}\n\n/**\n * What a written `.pen` file could not hold, as facts rather than a sentence: the app shows these\n * in the reader's language, while the CLI and MCP print `penWriteWarningText` of each.\n */\nexport type PenWriteWarning =\n | { kind: 'merged-pages'; pages: number; name: string }\n | { kind: 'display-p3-colors' }\n | { kind: 'library-definitions'; count: number }\n | { kind: 'missing-image-fills'; count: number }\n | { kind: 'dropped-effects'; count: number }\n | { kind: 'dropped-filters'; count: number }\n | { kind: 'dropped-scroll'; count: number }\n | { kind: 'dropped-font-features'; count: number }\n\n/** The English sentence a write warning has always been reported as. */\nexport function penWriteWarningText(warning: PenWriteWarning): string {\n switch (warning.kind) {\n case 'merged-pages':\n return `Pencil.dev files hold one page; ${warning.pages} pages were merged into “${warning.name}”.`\n case 'display-p3-colors':\n return '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.'\n case 'library-definitions':\n return `Library components came from ${warning.count} enabled ${warning.count === 1 ? 'library' : 'libraries'}, whose definitions Pencil.dev files do not hold; re-enable those libraries after reopening to restore them.`\n case 'missing-image-fills':\n return `Image fills with missing image data were left out (${warning.count}); Pencil.dev files cannot hold a paint without its image.`\n case 'dropped-effects':\n return `Noise and texture effects were left out (${warning.count}); Pencil.dev files have no form for them.`\n case 'dropped-filters':\n return `Image adjustment filters were left out (${warning.count}); Pencil.dev files have no form for them.`\n case 'dropped-scroll':\n return `Scroll overflow was left out (${warning.count}); Pencil.dev files have no form for it.`\n case 'dropped-font-features':\n return `OpenType font features were left out (${warning.count}); Pencil.dev files have no form for them.`\n default: {\n const unhandled: never = warning\n throw new Error(`Unhandled pen write warning: ${String(unhandled)}`)\n }\n }\n}\n\n/** Records a warning as its sentence and its kind, in the order it was found. */\nfunction emit(state: PenWriteState, warning: PenWriteWarning): void {\n state.details.push(warning)\n state.warnings.push(penWriteWarningText(warning))\n}\n\n/** What a caller learns about content a written `.pen` file cannot hold. */\nexport interface PenWriteOptions {\n /** Collects one sentence per kind of content left out, in place of silently losing it. */\n warnings?: string[]\n /** Collects the same facts as kinds, for a host that shows them in its own language. */\n warningDetails?: PenWriteWarning[]\n}\n\n/** Snaps matrix values that are within floating-point noise of an integer. */\nfunction snapCoordinate(value: number): number {\n return Math.abs(value - Math.round(value)) < 1e-9 ? Math.round(value) : value\n}\n/** A non-finite number has no JSON form, so it is written as 0 to keep the file loadable. */\nfunction rounded(value: number): number {\n return Number.isFinite(value) ? Number(value.toFixed(3)) : 0\n}\nfunction colorValue(value: Color): string {\n return value.a === 1 ? colorToHex(value) : colorToHex8(value)\n}\nfunction variableReference(state: PenWriteState, id: string | undefined): string | undefined {\n const variable = id === undefined ? undefined : state.variables.get(id)\n return variable === undefined ? undefined : `$${variable.name}`\n}\nfunction variableOr<T>(state: PenWriteState, node: SceneNode, field: string, value: T): T | string {\n return variableReference(state, node.boundVariables[field]) ?? value\n}\n\n/** Matches the pen corner convention of placing x/y after undoing the node's rotation or flip. */\nfunction penCoordinates(node: SceneNode): Vector {\n if (node.rotation === 0 && !node.flipX && !node.flipY) return { x: node.x, y: node.y }\n const matrix = getNodeLocalMatrix({ ...node, x: 0, y: 0 })\n return { x: snapCoordinate(node.x + matrix[2]), y: snapCoordinate(node.y + matrix[5]) }\n}\n\n/** pen.dev's names for the scene graph's blend modes, inverse of the reader's `BLEND_MODES`. */\nconst BLEND_MODE_NAMES: Partial<Record<BlendMode, string>> = {\n NORMAL: 'normal',\n DARKEN: 'darken',\n MULTIPLY: 'multiply',\n COLOR_BURN: 'colorBurn',\n LIGHTEN: 'light',\n SCREEN: 'screen',\n COLOR_DODGE: 'colorDodge',\n OVERLAY: 'overlay',\n SOFT_LIGHT: 'softLight',\n HARD_LIGHT: 'hardLight',\n DIFFERENCE: 'difference',\n EXCLUSION: 'exclusion',\n HUE: 'hue',\n SATURATION: 'saturation',\n COLOR: 'color',\n LUMINOSITY: 'luminosity'\n}\nfunction paintBase(fill: Fill): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n if (!fill.visible) result.enabled = false\n if (fill.opacity !== 1) result.opacity = rounded(fill.opacity)\n const blendMode = (fill.blendMode && BLEND_MODE_NAMES[fill.blendMode]) ?? undefined\n if (blendMode && blendMode !== 'normal') result.blendMode = blendMode\n return result\n}\n\nfunction gradientName(type: Fill['type']): 'linear' | 'radial' | 'angular' | 'diamond' {\n if (type === 'GRADIENT_RADIAL') return 'radial'\n if (type === 'GRADIENT_ANGULAR') return 'angular'\n if (type === 'GRADIENT_DIAMOND') return 'diamond'\n return 'linear'\n}\n\nfunction gradientPoint(inverse: GradientTransform | undefined, point: Vector): Vector {\n return inverse === undefined ? point : applyGradientTransform(inverse, point)\n}\nfunction gradientAxis(\n fill: Fill,\n inverse: GradientTransform | undefined,\n center: Vector,\n first: Vector,\n second: Vector\n): { rotation: number; width: number; height: number } {\n const firstLength = 2 * Math.hypot(first.x - center.x, first.y - center.y)\n const secondLength = 2 * Math.hypot(second.x - center.x, second.y - center.y)\n const rotationOf = (axis: Vector, offset: number): number =>\n offset - (Math.atan2(axis.x, -axis.y) * 180) / Math.PI\n if (fill.type === 'GRADIENT_LINEAR') {\n const axis =\n inverse === undefined\n ? { x: 0, y: -1 }\n : {\n x: applyGradientTransform(inverse, { x: 1, y: 0.5 }).x - center.x,\n y: applyGradientTransform(inverse, { x: 1, y: 0.5 }).y - center.y\n }\n return { rotation: rotationOf(axis, 0), width: secondLength, height: firstLength }\n }\n if (fill.type === 'GRADIENT_RADIAL' || fill.type === 'GRADIENT_DIAMOND') {\n const axis = { x: second.x - center.x, y: second.y - center.y }\n return { rotation: rotationOf(axis, 180), width: firstLength, height: secondLength }\n }\n const axis = { x: first.x - center.x, y: first.y - center.y }\n return { rotation: rotationOf(axis, 0), width: secondLength, height: firstLength }\n}\nfunction gradientPaint(fill: Fill): PenPaint {\n const transform = fill.gradientTransform\n const inverse = transform === undefined ? undefined : invertGradientTransform(transform)\n const center = gradientPoint(inverse, { x: 0.5, y: 0.5 })\n const first = gradientPoint(inverse, { x: 1, y: 0.5 })\n const second = gradientPoint(inverse, { x: 0.5, y: 1 })\n const axis = gradientAxis(fill, inverse, center, first, second)\n return {\n type: 'gradient',\n gradientType: gradientName(fill.type),\n ...paintBase(fill),\n center: { x: rounded(center.x), y: rounded(center.y) },\n size: { width: rounded(axis.width), height: rounded(axis.height) },\n rotation: rounded(axis.rotation),\n colors: (fill.gradientStops ?? []).map((stop) => ({\n color: colorValue(stop.color),\n position: rounded(stop.position)\n }))\n }\n}\n\n/**\n * An image fill as a pen.dev paint whose image travels with the file: Pencil.dev opens a data URL\n * and the scene graph keeps the bytes, so the fill is written whole instead of pointing at a hash\n * no reader can resolve. A paint whose bytes are gone is left out and reported, never written as a\n * dead URL.\n */\nfunction imagePaint(state: PenWriteState, fill: Fill): PenPaint | null {\n const bytes = fill.imageHash ? state.graph.images.get(fill.imageHash) : undefined\n if (!bytes) {\n state.drops.images++\n return null\n }\n if (fill.filters) state.drops.filters++\n const paint: PenImagePaint = {\n type: 'image',\n ...paintBase(fill),\n url: `data:${imageMimeType(bytes)};base64,${fromUint8Array(bytes)}`\n }\n if (fill.imageScaleMode === 'FIT') paint.mode = 'contain'\n if (fill.imageScaleMode === 'CROP') {\n paint.mode = 'stretch'\n const transform = fill.imageTransform && penCropTransform(fill.imageTransform)\n if (transform) paint.transform = transform\n }\n return paint\n}\n\nfunction penPaint(\n state: PenWriteState,\n node: SceneNode,\n field: 'fills' | 'strokes',\n fill: Fill,\n index: number\n): PenPaint | null {\n if (fill.type === 'SOLID') {\n const binding = variableReference(state, node.boundVariables[`${field}/${index}/color`])\n return { type: 'color', color: binding ?? colorValue(fill.color), ...paintBase(fill) }\n }\n if (fill.type.startsWith('GRADIENT_')) return gradientPaint(fill)\n if (fill.type === 'IMAGE') return imagePaint(state, fill)\n return { type: fill.type.toLowerCase(), ...paintBase(fill) }\n}\n\nfunction paintsOf(\n state: PenWriteState,\n node: SceneNode,\n field: 'fills' | 'strokes',\n paints: readonly Fill[]\n): PenPaints | undefined {\n if (paints.length === 0) return undefined\n const result = paints\n .map((paint, index) => penPaint(state, node, field, paint, index))\n .filter((paint): paint is PenPaint => paint !== null)\n if (result.length === 0) return undefined\n return result.length === 1 ? result[0] : result\n}\n\nfunction strokesOf(\n state: PenWriteState,\n node: SceneNode\n): Pick<\n PenNode,\n 'stroke' | 'strokeWidth' | 'strokeAlignment' | 'strokeLinecap' | 'strokeLinejoin'\n> {\n if (node.strokes.length === 0) return {}\n const paints = paintsOf(state, node, 'strokes', node.strokes)\n if (paints === undefined) return {}\n const first = node.strokes[0]\n const strokeWidth: PenNumber | PenSides = node.independentStrokeWeights\n ? {\n top: variableOr(state, node, 'borderTopWeight', rounded(node.borderTopWeight)),\n right: variableOr(state, node, 'borderRightWeight', rounded(node.borderRightWeight)),\n bottom: variableOr(state, node, 'borderBottomWeight', rounded(node.borderBottomWeight)),\n left: variableOr(state, node, 'borderLeftWeight', rounded(node.borderLeftWeight))\n }\n : variableOr(state, node, 'strokeWeight', rounded(first.weight))\n const caps: Record<NonNullable<Stroke['cap']>, string> = {\n NONE: 'butt',\n ROUND: 'round',\n SQUARE: 'square',\n ARROW_LINES: 'butt',\n ARROW_EQUILATERAL: 'butt',\n TRIANGLE_FILLED: 'butt',\n DIAMOND_FILLED: 'butt',\n CIRCLE_FILLED: 'butt'\n }\n const joins: Record<NonNullable<Stroke['join']>, string> = {\n MITER: 'miter',\n BEVEL: 'bevel',\n ROUND: 'round'\n }\n const linecap = first.cap === undefined ? undefined : caps[first.cap]\n const linejoin = first.join === undefined ? undefined : joins[first.join]\n return {\n stroke: paints,\n strokeWidth,\n strokeAlignment: first.align.toLowerCase(),\n strokeLinecap: linecap === 'butt' ? undefined : linecap,\n strokeLinejoin: linejoin === 'miter' ? undefined : linejoin\n }\n}\n\nfunction effectOf(effect: ShadowEffect): PenEffect {\n if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') {\n return {\n type: effect.type === 'LAYER_BLUR' ? 'blur' : 'background_blur',\n radius: rounded(effect.radius),\n enabled: effect.visible\n }\n }\n return {\n type: 'shadow',\n shadowType: effect.type === 'INNER_SHADOW' ? 'inner' : undefined,\n color: colorValue(effect.color),\n offset: { x: rounded(effect.offset.x), y: rounded(effect.offset.y) },\n blur: rounded(effect.radius),\n spread: rounded(effect.spread),\n enabled: effect.visible\n }\n}\n\nfunction variableType(type: Variable['type']): PenVariable['type'] {\n if (type === 'COLOR') return 'color'\n if (type === 'FLOAT') return 'number'\n if (type === 'BOOLEAN') return 'boolean'\n return 'string'\n}\n\nfunction layoutFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {\n if (node.layoutMode === 'NONE')\n return node.type === 'FRAME' || node.type === 'COMPONENT' ? { layout: 'none' } : {}\n const justify: Partial<Record<LayoutAlign, string>> = {\n CENTER: 'center',\n MAX: 'end',\n SPACE_BETWEEN: 'space_between',\n SPACE_AROUND: 'space_around'\n }\n const align: Partial<Record<LayoutCounterAlign, string>> = {\n CENTER: 'center',\n MAX: 'end',\n STRETCH: 'stretch',\n BASELINE: 'baseline'\n }\n const fields: Partial<PenNode> = {\n layout: node.layoutMode === 'HORIZONTAL' ? 'horizontal' : 'vertical'\n }\n const gapBinding = variableReference(state, node.boundVariables['itemSpacing'])\n if (gapBinding !== undefined) fields.gap = gapBinding\n else if (node.itemSpacing !== 0) fields.gap = rounded(node.itemSpacing)\n if (node.primaryAxisAlign !== 'MIN') fields.justifyContent = justify[node.primaryAxisAlign]\n if (node.counterAxisAlign !== 'MIN') fields.alignItems = align[node.counterAxisAlign]\n // A padding bound to a variable is written as its reference, as the reader binds it again.\n const padding: [PenNumber, PenNumber, PenNumber, PenNumber] = [\n variableOr(state, node, 'paddingTop', node.paddingTop),\n variableOr(state, node, 'paddingRight', node.paddingRight),\n variableOr(state, node, 'paddingBottom', node.paddingBottom),\n variableOr(state, node, 'paddingLeft', node.paddingLeft)\n ]\n if (padding.some((value) => value !== 0)) fields.padding = padding\n if (node.clipsContent) fields.clip = true\n if (node.strokesIncludedInLayout) fields.layoutIncludeStroke = true\n return fields\n}\n\nfunction sizing(\n state: PenWriteState,\n node: SceneNode,\n axis: 'HORIZONTAL' | 'VERTICAL'\n): PenNumber | undefined {\n const mode = layoutSizing(state.graph, node, axis)\n if (mode === 'FILL') return 'fill_container'\n if (mode === 'HUG') return 'fit_content'\n return undefined\n}\n\nfunction penPluginFields(node: SceneNode, result: PenNode): void {\n for (const entry of node.pluginData) {\n if (entry.pluginId !== PEN_PLUGIN_DATA_NAMESPACE) continue\n const field = PEN_PLUGIN_FIELDS[entry.key]\n if (field === undefined) continue\n let value: unknown\n try {\n value = JSON.parse(entry.value)\n } catch {\n console.warn(`Skipping corrupt pen plugin field ${field}`)\n continue\n }\n result[field] = value\n }\n}\n\nfunction nodeType(node: SceneNode): string {\n switch (node.type) {\n case 'COMPONENT':\n case 'COMPONENT_SET':\n case 'FRAME':\n case 'SECTION':\n return 'frame'\n case 'RECTANGLE':\n case 'ROUNDED_RECTANGLE':\n return 'rectangle'\n case 'ELLIPSE':\n return 'ellipse'\n case 'POLYGON':\n case 'STAR':\n return 'polygon'\n case 'GROUP':\n case 'BOOLEAN_OPERATION':\n return 'group'\n case 'TEXT':\n return 'text'\n case 'VECTOR':\n return 'path'\n case 'LINE':\n return 'line'\n case 'STICKY':\n return 'note'\n default:\n return 'frame'\n }\n}\n\n/** A line height as the multiple of the font size pen.dev stores; undefined when it has none. */\nfunction lineHeightMultiple(node: SceneNode): number | undefined {\n const lineHeight = node.lineHeight\n if (!lineHeight) return undefined\n if (lineHeight.unit !== 'PIXELS') return rounded(lineHeight.value / 100)\n return node.fontSize > 0 ? rounded(lineHeight.value / node.fontSize) : undefined\n}\n\n/** Letter spacing in the pixels pen.dev stores, a percent following the font size. */\nfunction letterSpacingPixels(node: SceneNode): number {\n const spacing = node.letterSpacing\n return spacing.unit === 'PIXELS' ? spacing.value : (spacing.value / 100) * node.fontSize\n}\n\nfunction textFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {\n if (node.type !== 'TEXT') return {}\n const fields: Partial<PenNode> = { content: node.text }\n if (node.fontFamily !== 'Inter')\n fields.fontFamily = variableOr(state, node, 'fontFamily', node.fontFamily)\n if (node.fontSize !== 14)\n fields.fontSize = variableOr(state, node, 'fontSize', rounded(node.fontSize))\n const fontWeight = variableOr(state, node, 'fontWeight', node.fontWeight)\n if (typeof fontWeight === 'string' || node.fontWeight !== 400) fields.fontWeight = fontWeight\n if (node.italic) fields.fontStyle = 'italic'\n const textAlign: Partial<Record<SceneNode['textAlignHorizontal'], string>> = {\n CENTER: 'center',\n RIGHT: 'right',\n JUSTIFIED: 'justify'\n }\n const textAlignVertical: Partial<Record<SceneNode['textAlignVertical'], string>> = {\n CENTER: 'middle',\n BOTTOM: 'bottom'\n }\n if (node.textAlignHorizontal !== 'LEFT') fields.textAlign = textAlign[node.textAlignHorizontal]\n if (node.textAlignVertical !== 'TOP')\n fields.textAlignVertical = textAlignVertical[node.textAlignVertical]\n const lineHeight = lineHeightMultiple(node)\n if (lineHeight !== undefined) fields.lineHeight = lineHeight\n if (node.letterSpacing.value !== 0) fields.letterSpacing = rounded(letterSpacingPixels(node))\n if (node.textAutoResize === 'HEIGHT') fields.textGrowth = 'fixed-width'\n if (node.textAutoResize === 'NONE' || node.textAutoResize === 'TRUNCATE')\n fields.textGrowth = 'fixed-width-height'\n const link = node.styleRuns.find((run) => run.style.hyperlink?.type === 'URL')\n if (link?.style.hyperlink?.type === 'URL') fields.href = link.style.hyperlink.value\n return fields\n}\n\nfunction cornerFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {\n if (node.independentCorners) {\n return {\n cornerRadius: [\n variableOr(state, node, 'topLeftRadius', rounded(node.topLeftRadius)),\n variableOr(state, node, 'topRightRadius', rounded(node.topRightRadius)),\n variableOr(state, node, 'bottomRightRadius', rounded(node.bottomRightRadius)),\n variableOr(state, node, 'bottomLeftRadius', rounded(node.bottomLeftRadius))\n ]\n }\n }\n const radius = variableOr(state, node, 'cornerRadius', rounded(node.cornerRadius))\n return radius === 0 ? {} : { cornerRadius: radius }\n}\n\nfunction variableScalar(value: VariableValue | undefined, state: PenWriteState): PenVariableScalar {\n if (value === undefined) return ''\n if (typeof value === 'object' && 'aliasId' in value) {\n const variable = state.variables.get(value.aliasId)\n return variable === undefined ? '' : `$${variable.name}`\n }\n if (typeof value === 'object') return 'r' in value ? colorValue(value) : ''\n return value\n}\nfunction penVariable(\n variable: Variable,\n collection: VariableCollection | undefined,\n state: PenWriteState\n): PenVariable {\n const modes = collection?.modes ?? []\n const syntax = variable.codeSyntax ? { codeSyntax: variable.codeSyntax } : {}\n if (modes.length <= 1)\n return {\n type: variableType(variable.type),\n value: variableScalar(variable.valuesByMode[modes[0]?.modeId ?? ''], state),\n ...syntax\n }\n return {\n type: variableType(variable.type),\n value: modes.map((mode, index) => ({\n value: variableScalar(variable.valuesByMode[mode.modeId], state),\n ...(index === 0 ? {} : { theme: { [collection?.name ?? 'Mode']: mode.name } })\n })),\n ...syntax\n }\n}\n\nfunction variablesOf(state: PenWriteState): Record<string, PenVariable> | undefined {\n if (state.variables.size === 0) return undefined\n return Object.fromEntries(\n [...state.variables.values()]\n .sort((left, right) => left.name.localeCompare(right.name))\n .map((variable) => [\n variable.name,\n penVariable(variable, state.collections.get(variable.collectionId), state)\n ])\n )\n}\n\nfunction themesOf(state: PenWriteState): PenDocument['themes'] {\n if (state.collections.size === 0) return undefined\n return Object.fromEntries(\n [...state.collections.values()]\n .sort((left, right) => left.name.localeCompare(right.name))\n .map((collection) => [collection.name, collection.modes.map((mode) => mode.name)])\n )\n}\n\n/** The selector each mode applies in, by collection and mode name; none when no mode names one. */\nfunction modeConditionsOf(state: PenWriteState): PenDocument['modeConditions'] {\n const entries = [...state.collections.values()].flatMap((collection) => {\n const modes = collection.modes.flatMap((mode) =>\n mode.condition ? [[mode.name, mode.condition] as const] : []\n )\n return modes.length > 0 ? [[collection.name, Object.fromEntries(modes)] as const] : []\n })\n return entries.length > 0 ? Object.fromEntries(entries) : undefined\n}\n\nfunction basicNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): void {\n if (node.name) result.name = node.name\n const placement = penCoordinates(node)\n if (placement.x !== 0) result.x = rounded(placement.x)\n if (placement.y !== 0) result.y = rounded(placement.y)\n result.width = variableOr(\n state,\n node,\n 'width',\n sizing(state, node, 'HORIZONTAL') ?? rounded(node.width)\n )\n result.height = variableOr(\n state,\n node,\n 'height',\n sizing(state, node, 'VERTICAL') ?? rounded(node.height)\n )\n if (!node.visible) result.enabled = false\n if (node.opacity !== 1) result.opacity = rounded(node.opacity)\n if (node.rotation !== 0)\n result.rotation = rounded(node.flipX !== node.flipY ? node.rotation : -node.rotation)\n if (node.flipX) result.flipX = true\n if (node.flipY) result.flipY = true\n const theme = themeFields(state, node)\n if (theme) result.theme = theme\n const fill = paintsOf(state, node, 'fills', node.fills)\n if (fill !== undefined) result.fill = fill\n Object.assign(\n result,\n strokesOf(state, node),\n layoutFields(state, node),\n cornerFields(state, node),\n textFields(state, node)\n )\n}\n/**\n * A layer's variable mode assignments, by the names pen writes: the collection's name and the\n * mode's. A mode the document no longer holds is left out.\n */\nfunction themeFields(state: PenWriteState, node: SceneNode): Record<string, string> | undefined {\n const theme: Record<string, string> = {}\n for (const [collectionId, modeId] of Object.entries(node.variableModes)) {\n const collection = state.collections.get(collectionId)\n const mode = collection?.modes.find((candidate) => candidate.modeId === modeId)\n if (collection && mode) theme[collection.name] = mode.name\n }\n return Object.keys(theme).length > 0 ? theme : undefined\n}\n\n/**\n * The pen fields an instance override writes: what it changes on a layer, not the placement and\n * layout a reopen recalculates from the component and the boxes around it.\n */\nconst OVERRIDABLE_FIELDS: ReadonlySet<string> = new Set([\n 'content',\n 'fill',\n 'stroke',\n 'strokeWidth',\n 'cornerRadius',\n 'effect',\n 'opacity',\n 'enabled',\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'fontStyle',\n 'textAlign',\n 'textAlignVertical',\n 'lineHeight',\n 'letterSpacing',\n 'href'\n])\n\n/**\n * The path a copy sits at in its component, from the instance down: the ids of the layers it\n * copies, as pen names a `descendants` override. A copy that swapped its component copies `swapOf`\n * instead of the component it draws.\n */\nfunction overridePath(\n graph: SceneGraph,\n instanceId: string,\n copyId: string,\n swapOf?: string\n): string | null {\n const parts: string[] = []\n let current = graph.getNode(copyId)\n while (current && current.id !== instanceId) {\n const id = current.id === copyId && swapOf ? swapOf : current.componentId\n if (!id) return null\n parts.unshift(id)\n current = current.parentId ? graph.getNode(current.parentId) : undefined\n }\n return current ? parts.join('/') : null\n}\n\n/**\n * The fields a swap override names an icon by: pen carries the glyph, not the component drawn.\n */\nfunction iconOverride(graph: SceneGraph, componentId: string | null): PenOverride | undefined {\n const origin = readIconOrigin(componentId ? graph.getNode(componentId) : undefined)\n if (!origin) return undefined\n const override: PenOverride = { icon: origin.icon }\n if (origin.library) override.library = origin.library\n if (origin.weight !== undefined) override.weight = origin.weight\n return override\n}\n\n/**\n * The overrides an instance writes, and whether one of them is a swap the file cannot name. A\n * layer that swapped its component draws another component than the one it copies, which pen holds\n * as a glyph for an icon; any other swap is what the instance shows, not what it links to.\n */\nfunction instanceDescendants(\n state: PenWriteState,\n node: SceneNode\n): { descendants?: Record<string, PenOverride>; unrepresentable: boolean } {\n const overridden = [...node.instanceOverrides.descendants.keys()]\n if (overridden.length === 0) return { unrepresentable: false }\n // Comparing writes fields the moment a document writes them, but their drops are counted once.\n const probe: PenWriteState = {\n ...state,\n drops: { images: 0, effects: 0, filters: 0, scroll: 0, fontFeatures: 0 }\n }\n const descendants: Record<string, PenOverride> = {}\n let unrepresentable = false\n for (const copyId of overridden) {\n const overrides = node.instanceOverrides.descendants.get(copyId)\n const swapped = overrides?.has('componentId') === true\n const swapOf = swapped ? overrides.get('sourceComponentId') : undefined\n const path = overridePath(\n state.graph,\n node.id,\n copyId,\n typeof swapOf === 'string' ? swapOf : undefined\n )\n const copy = state.graph.getNode(copyId)\n if (!path || !copy) {\n unrepresentable = true\n continue\n }\n if (swapped) {\n const icon = iconOverride(state.graph, copy.componentId)\n if (!icon) {\n unrepresentable = true\n continue\n }\n descendants[path] = icon\n continue\n }\n const master = copy.componentId ? state.graph.getNode(copy.componentId) : undefined\n if (!master) {\n unrepresentable = true\n continue\n }\n const own = writeNode(probe, copy)\n const base = writeNode(probe, master)\n const override: PenOverride = {}\n for (const field of OVERRIDABLE_FIELDS) {\n if (!isEqual(own[field], base[field])) override[field] = own[field]\n }\n if (Object.keys(override).length > 0) descendants[path] = override\n }\n return {\n descendants: Object.keys(descendants).length > 0 ? descendants : undefined,\n unrepresentable\n }\n}\n\nfunction semanticNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): boolean {\n if (\n node.type === 'TEXT' &&\n node.textAutoResize === 'WIDTH_AND_HEIGHT' &&\n layoutSizing(state.graph, node, 'HORIZONTAL') === 'HUG'\n )\n result.width = 'fit_content'\n if (node.type === 'STICKY') result.content = stickySublayers(state.graph, node)?.body.text ?? ''\n penPluginFields(node, result)\n // Shader, noise, and texture effects have no pen.dev form; dropping them keeps the file loadable.\n const effects = node.effects.filter((effect): effect is ShadowEffect => {\n if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') return true\n if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') return true\n if (effect.type === 'NOISE' || effect.type === 'TEXTURE') state.drops.effects++\n return false\n })\n if (effects.length > 0)\n result.effect = effects.length === 1 ? effectOf(effects[0]) : effects.map(effectOf)\n if (node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') result.reusable = true\n if (\n node.type === 'INSTANCE' &&\n node.componentId &&\n (state.writtenIds.has(node.componentId) || state.importedIds.has(node.componentId))\n ) {\n const overrides = instanceDescendants(state, node)\n // The file names a swap through the library it imports; one it cannot name is written as the\n // layers the instance draws, which keeps what it shows, as before the library work.\n if (overrides.unrepresentable && !state.writtenIds.has(node.componentId)) return false\n result.type = 'ref'\n result.ref = node.componentId\n if (overrides.descendants) result.descendants = overrides.descendants\n return true\n }\n return false\n}\nfunction writeNode(state: PenWriteState, node: SceneNode): PenNode {\n if (node.overflowDirection !== 'NONE') state.drops.scroll++\n if (node.fontFeatures.length > 0) state.drops.fontFeatures++\n const result: PenNode = { id: node.id, type: nodeType(node) }\n if (node.status !== null) result.status = node.status\n basicNodeFields(state, node, result)\n if (semanticNodeFields(state, node, result)) return result\n // Written after the preserved pen fields, so a regenerated path wins over the source text.\n if (node.type === 'VECTOR' && node.vectorNetwork && node.vectorNetwork.segments.length > 0) {\n const geometry = networkToSVGPath(node.vectorNetwork)\n if (geometry) {\n result.geometry = geometry\n // The written box is rounded; the view box names the same box, so the path maps onto it\n // one to one rather than being scaled into a rounded height on the next read.\n result.viewBox = [0, 0, rounded(node.width), rounded(node.height)]\n if (node.vectorNetwork.regions[0]?.windingRule === 'EVENODD') result.fillRule = 'evenodd'\n }\n }\n const children =\n node.type === 'STICKY'\n ? []\n : state.graph\n .getChildren(node.id)\n .filter((child) => !child.internalOnly)\n .map((child) => writeNode(state, child))\n if (children.length > 0) result.children = children\n return result\n}\n\n/** Code-point order, so the canonical text does not depend on the runtime locale. */\nfunction compareCodePoints(left: string, right: string): number {\n if (left < right) return -1\n if (left > right) return 1\n return 0\n}\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeys)\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as { [key: string]: unknown })\n return Object.fromEntries(\n entries\n .sort(([left], [right]) => compareCodePoints(left, right))\n .map(([key, entry]) => [key, sortKeys(entry)])\n )\n }\n return value\n}\n\nexport function penDocumentFromGraph(\n graph: SceneGraph,\n options: PenWriteOptions = {}\n): PenDocument {\n // A deleted variable has no state `.pen` can hold, so layers bound to it write its value.\n const variables = new Map<string, Variable>()\n for (const variable of graph.getLiveVariables()) variables.set(variable.id, variable)\n const collections = new Map<string, VariableCollection>()\n for (const collection of graph.getLiveCollections()) collections.set(collection.id, collection)\n // The file declares its imports, so a ref to a component one of them defines resolves on reopen.\n const imports = readPenImports(graph)\n const state: PenWriteState = {\n graph,\n variables,\n collections,\n writtenIds: writtenNodeIds(graph),\n importedIds: importedComponentIds(graph, imports ?? {}),\n warnings: options.warnings ?? [],\n details: [],\n drops: { images: 0, effects: 0, filters: 0, scroll: 0, fontFeatures: 0 }\n }\n const pages = graph.getPages()\n const children = pages.flatMap((page) =>\n graph\n .getChildren(page.id)\n .filter((node) => !node.internalOnly)\n .map((node) => writeNode(state, node))\n )\n const document: PenDocument = { version: PEN_VERSION, name: pages[0]?.name, children }\n const variablesValue = variablesOf(state)\n if (variablesValue) document.variables = variablesValue\n const themes = themesOf(state)\n if (themes) document.themes = themes\n const conditions = modeConditionsOf(state)\n if (conditions) document.modeConditions = conditions\n const tokenSources = readTokenSources(graph).map((source) => {\n // The reopen gives variables new ids; these are the names the file holds for them. `names`\n // stays as the last sync recorded it, where the token each variable stands for lives.\n const currentNames = Object.fromEntries(\n Object.keys(source.names ?? {}).flatMap((id) => {\n const variable = variables.get(id)\n const collection = variable ? collections.get(variable.collectionId) : undefined\n return variable && collection ? [[id, `${collection.name}/${variable.name}`]] : []\n })\n )\n const modes = {\n ...source.modes,\n ...Object.fromEntries(\n [...collections.values()].map((collection) => [\n collection.name,\n Object.fromEntries(collection.modes.map((mode) => [mode.modeId, mode.name]))\n ])\n )\n }\n const refreshed: TokenSource = { ...source }\n if (Object.keys(currentNames).length > 0) refreshed.currentNames = currentNames\n if (Object.keys(modes).length > 0) refreshed.modes = modes\n return refreshed\n })\n if (tokenSources.length > 0) document.tokenSources = tokenSources\n const designMemory = readDesignMemory(graph)\n if (designMemory) document.designMemory = designMemory\n // Only a document that chose its statuses writes them: the default falls back on read.\n const statuses = readStoredStatusWorkflow(graph)\n if (statuses) document.statuses = statuses\n if (imports) document.imports = imports\n const enabledLibraries = enabledLibrariesOf(graph, state)\n if (enabledLibraries) document.enabledLibraries = enabledLibraries\n const publication = readSourceLibraryPublication(graph)\n if (publication) document.sourceLibraryPublication = publication\n if (pages.length > 1) {\n const name = document.name ?? 'Page 1'\n emit(state, { kind: 'merged-pages', pages: pages.length, name })\n }\n if (graph.documentColorSpace === 'display-p3') {\n emit(state, { kind: 'display-p3-colors' })\n }\n reportDrops(state)\n options.warningDetails?.push(...state.details)\n return document\n}\n\n/**\n * The library bindings a `.pen` file records, or null when the document has none. The definitions\n * live on the hidden page, which a Pencil.dev file cannot hold, so the file records the bindings\n * and says that the components it was built from come back as placeholders.\n */\nfunction enabledLibrariesOf(\n graph: SceneGraph,\n state: PenWriteState\n): EnabledLibraryBinding[] | null {\n const bindings = [...graph.enabledLibraries.values()]\n if (bindings.length === 0) return null\n const enabled = bindings.filter((binding) => binding.enabled).length\n if (enabled > 0) emit(state, { kind: 'library-definitions', count: enabled })\n return bindings\n}\n\n/** Adds one sentence for each kind of content the written file had to leave out. */\nfunction reportDrops(state: PenWriteState): void {\n const { images, effects, filters, scroll, fontFeatures } = state.drops\n if (images > 0) emit(state, { kind: 'missing-image-fills', count: images })\n if (effects > 0) emit(state, { kind: 'dropped-effects', count: effects })\n if (filters > 0) emit(state, { kind: 'dropped-filters', count: filters })\n if (scroll > 0) emit(state, { kind: 'dropped-scroll', count: scroll })\n if (fontFeatures > 0) emit(state, { kind: 'dropped-font-features', count: fontFeatures })\n}\n\nexport function stringifyPenDocument(document: PenDocument): string {\n return `${JSON.stringify(sortKeys(document), null, 2)}\\n`\n}\n\nexport function writePenDocument(\n source: PenDocument | SceneGraph,\n options: PenWriteOptions = {}\n): string {\n const document =\n source instanceof SceneGraphValue ? penDocumentFromGraph(source, options) : source\n return stringifyPenDocument(document)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,gBAAgB,MAAmB,OAAuB;CACjE,IA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K,OAAO;EAAE,MAAM;EAAmB,OAAO;CAAQ,CAAC;CACxE,IAAI,UAAU,GAAG,KAAK,OAAO;EAAE,MAAM;EAAmB,OAAO;CAAQ,CAAC;CACxE,IAAI,SAAS,GAAG,KAAK,OAAO;EAAE,MAAM;EAAkB,OAAO;CAAO,CAAC;CACrE,IAAI,eAAe,GAAG,KAAK,OAAO;EAAE,MAAM;EAAyB,OAAO;CAAa,CAAC;AAC1F;AAEA,SAAgB,qBAAqB,UAA+B;CAClE,OAAO,GAAG,KAAK,UAAU,SAAS,QAAQ,GAAG,MAAM,CAAC,EAAE;AACxD;AAEA,SAAgB,iBACd,QACA,UAA2B,CAAC,GACpB;CAGR,OAAO,qBADL,kBAAkBC,aAAkB,qBAAqB,QAAQ,OAAO,IAAI,MAC1C;AACtC"}
package/dist/index.d.ts CHANGED
@@ -618,14 +618,47 @@ declare function parsePenFile(json: string, options?: PenReadOptions): SceneGrap
618
618
  declare function readPenFile(file: File, options?: PenReadOptions): Promise<SceneGraph>;
619
619
  //#endregion
620
620
  //#region src/write.d.ts
621
+ /**
622
+ * What a written `.pen` file could not hold, as facts rather than a sentence: the app shows these
623
+ * in the reader's language, while the CLI and MCP print `penWriteWarningText` of each.
624
+ */
625
+ type PenWriteWarning = {
626
+ kind: 'merged-pages';
627
+ pages: number;
628
+ name: string;
629
+ } | {
630
+ kind: 'display-p3-colors';
631
+ } | {
632
+ kind: 'library-definitions';
633
+ count: number;
634
+ } | {
635
+ kind: 'missing-image-fills';
636
+ count: number;
637
+ } | {
638
+ kind: 'dropped-effects';
639
+ count: number;
640
+ } | {
641
+ kind: 'dropped-filters';
642
+ count: number;
643
+ } | {
644
+ kind: 'dropped-scroll';
645
+ count: number;
646
+ } | {
647
+ kind: 'dropped-font-features';
648
+ count: number;
649
+ };
650
+ /** The English sentence a write warning has always been reported as. */
651
+ declare function penWriteWarningText(warning: PenWriteWarning): string;
621
652
  /** What a caller learns about content a written `.pen` file cannot hold. */
622
653
  interface PenWriteOptions {
623
654
  /** Collects one sentence per kind of content left out, in place of silently losing it. */
624
655
  warnings?: string[];
656
+ /** Collects the same facts as kinds, for a host that shows them in its own language. */
657
+ warningDetails?: PenWriteWarning[];
625
658
  }
626
659
  declare function penDocumentFromGraph(graph: SceneGraph, options?: PenWriteOptions): PenDocument;
627
660
  declare function stringifyPenDocument(document: PenDocument): string;
628
661
  declare function writePenDocument(source: PenDocument | SceneGraph, options?: PenWriteOptions): string;
629
662
  //#endregion
630
- export { PEN_PLUGIN_DATA_NAMESPACE, type PenAssets, type PenDocument, type PenFont, type PenIconRequest, type PenIconSource, type PenImport, type PenImports, type PenNode, type PenOverride, type PenReadOptions, type PenWriteOptions, buildPenGraph, iconName, iconOptions, importedDocument, isDataURL, isDocumentAssetPath, parseImportedImageURL, parsePenDocument, parsePenFile, penAssets, penDocumentFromGraph, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };
663
+ export { PEN_PLUGIN_DATA_NAMESPACE, type PenAssets, type PenDocument, type PenFont, type PenIconRequest, type PenIconSource, type PenImport, type PenImports, type PenNode, type PenOverride, type PenReadOptions, type PenWriteOptions, type PenWriteWarning, buildPenGraph, iconName, iconOptions, importedDocument, isDataURL, isDocumentAssetPath, parseImportedImageURL, parsePenDocument, parsePenFile, penAssets, penDocumentFromGraph, penWriteWarningText, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };
631
664
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/schema.ts","../src/assets.ts","../src/imports.ts","../src/nodes.ts","../src/library.ts","../src/plugin-data.ts","../src/read.ts","../src/write.ts"],"mappings":";;;;;;cA6KM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;iBAgDL,iBAAiB,eAAe;;iBAShC,cAAc,KAAK,aAAa,UAAS,iBAAsB;iBA8D/D,aAAa,cAAc,UAAS,iBAAsB;iBAIpD,YAAY,MAAM,MAAM,UAAU,iBAAiB,QAAQ;;;;UCvFhE;;EAEf;;iBA4sBc,qBACd,OAAO,YACP,UAAS,kBACR;iBA6Ha,qBAAqB,UAAU;iBAI/B,iBACd,QAAQ,cAAc,YACtB,UAAS"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/schema.ts","../src/assets.ts","../src/imports.ts","../src/nodes.ts","../src/library.ts","../src/plugin-data.ts","../src/read.ts","../src/write.ts"],"mappings":";;;;;;cA6KM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA4FM,aAAa,EAAE,YAAY,EAAE,oBAAoB;;UAG5C,oBAAoB;EACnC;EACA;EACA,WAAW;EACX,cAAc,eAAe;GAC5B;;UAGc,gBAAgB;EAC/B;EACA;;;cA8CI,YAAU,EAAA;;;;cAwDV,mBAAiB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA2CX,cAAc,EAAE,mBAAmB;KACnC,UAAU,EAAE,mBAAmB;;;;iBC7Y3B,SAAS,iBAAiB;;iBAM1B,YACd,iBACA,6BACC;;UAKc;EACf;EACA,UAAU;;;;;;iBAOI,oBAAoB;;iBAMpB,UAAU;;;;;iBAWV,sBAAsB;EAAgB;EAAe;;;UASpD;;EAEf,OAAO;;;;;EAKP;;;;;EAKA;;;;;;iBAsHc,UAAU,KAAK,cAAc;;;;UCrM5B;;EAEf;;EAEA,KAAK;;;KAIK,aAAa,oBAAoB;;;;;;;iBAqH7B,iBACd,eACA,cACA,KAAK,aACL,SAAS,aACR;;;;UCtGc;;;;;;EAMf,KACE,OAAO,YACP,iBACA,cACA,cACA,OAAO,OACP,UAAU;;;;;;;;;iBC8BE,gBAAgB,KAAK,aAAa,SAAS,aAAa;;;;;;;;cCpE3D;;;;UCUI;;;;;EAKf,QAAQ,OAAO;;EAEf,SAAS,oBAAoB;;;;;EAK7B,UAAU;;EAEV,QAAQ;;;;;;EAMR,QAAQ,oBAAoB;;;;;;;EAO5B,UAAU;;EAEV,mBAAmB;;EAEnB,mBAAmB;;;iBAgDL,iBAAiB,eAAe;;iBAShC,cAAc,KAAK,aAAa,UAAS,iBAAsB;iBA8D/D,aAAa,cAAc,UAAS,iBAAsB;iBAIpD,YAAY,MAAM,MAAM,UAAU,iBAAiB,QAAQ;;;;;;;KClFrE;EACN;EAAsB;EAAe;;EACrC;;EACA;EAA6B;;EAC7B;EAA6B;;EAC7B;EAAyB;;EACzB;EAAyB;;EACzB;EAAwB;;EACxB;EAA+B;;;iBAGrB,oBAAoB,SAAS;;UAgC5B;;EAEf;;EAEA,iBAAiB;;iBA4sBH,qBACd,OAAO,YACP,UAAS,kBACR;iBAyGa,qBAAqB,UAAU;iBAI/B,iBACd,QAAQ,cAAc,YACtB,UAAS"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PEN_PLUGIN_DATA_NAMESPACE } from "./chunks/annotations.js";
2
2
  import { iconName, iconOptions, isDataURL, isDocumentAssetPath, parseImportedImageURL, penAssets } from "./chunks/assets.js";
3
3
  import { importedDocument } from "./chunks/imports.js";
4
- import { buildPenGraph, parsePenDocument, parsePenFile, penDocumentFromGraph, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument } from "./chunks/index.js";
5
- export { PEN_PLUGIN_DATA_NAMESPACE, buildPenGraph, iconName, iconOptions, importedDocument, isDataURL, isDocumentAssetPath, parseImportedImageURL, parsePenDocument, parsePenFile, penAssets, penDocumentFromGraph, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };
4
+ import { buildPenGraph, parsePenDocument, parsePenFile, penDocumentFromGraph, penWriteWarningText, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument } from "./chunks/index.js";
5
+ export { PEN_PLUGIN_DATA_NAMESPACE, buildPenGraph, iconName, iconOptions, importedDocument, isDataURL, isDocumentAssetPath, parseImportedImageURL, parsePenDocument, parsePenFile, penAssets, penDocumentFromGraph, penWriteWarningText, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/pen",
3
- "version": "0.21.0",
3
+ "version": "0.21.1",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -15,7 +15,7 @@
15
15
  "valibot": "^1.5.0"
16
16
  },
17
17
  "peerDependencies": {
18
- "@pairdraw/scene-graph": "^0.21.0"
18
+ "@pairdraw/scene-graph": "^0.21.1"
19
19
  },
20
20
  "exports": {
21
21
  ".": {
package/src/index.ts CHANGED
@@ -22,7 +22,9 @@ export {
22
22
  export type { PenDocument, PenFont, PenNode, PenOverride } from './schema'
23
23
  export {
24
24
  penDocumentFromGraph,
25
+ penWriteWarningText,
25
26
  stringifyPenDocument,
26
27
  writePenDocument,
27
- type PenWriteOptions
28
+ type PenWriteOptions,
29
+ type PenWriteWarning
28
30
  } from './write'
package/src/write.ts CHANGED
@@ -76,6 +76,8 @@ type PenWriteState = {
76
76
  importedIds: ReadonlySet<string>
77
77
  /** What the file cannot hold, reported once writing leaves it out. */
78
78
  warnings: string[]
79
+ /** The same facts as kinds, for a host that shows them in its own language. */
80
+ details: PenWriteWarning[]
79
81
  drops: {
80
82
  images: number
81
83
  effects: number
@@ -85,10 +87,58 @@ type PenWriteState = {
85
87
  }
86
88
  }
87
89
 
90
+ /**
91
+ * What a written `.pen` file could not hold, as facts rather than a sentence: the app shows these
92
+ * in the reader's language, while the CLI and MCP print `penWriteWarningText` of each.
93
+ */
94
+ export type PenWriteWarning =
95
+ | { kind: 'merged-pages'; pages: number; name: string }
96
+ | { kind: 'display-p3-colors' }
97
+ | { kind: 'library-definitions'; count: number }
98
+ | { kind: 'missing-image-fills'; count: number }
99
+ | { kind: 'dropped-effects'; count: number }
100
+ | { kind: 'dropped-filters'; count: number }
101
+ | { kind: 'dropped-scroll'; count: number }
102
+ | { kind: 'dropped-font-features'; count: number }
103
+
104
+ /** The English sentence a write warning has always been reported as. */
105
+ export function penWriteWarningText(warning: PenWriteWarning): string {
106
+ switch (warning.kind) {
107
+ case 'merged-pages':
108
+ return `Pencil.dev files hold one page; ${warning.pages} pages were merged into “${warning.name}”.`
109
+ case 'display-p3-colors':
110
+ return '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.'
111
+ case 'library-definitions':
112
+ return `Library components came from ${warning.count} enabled ${warning.count === 1 ? 'library' : 'libraries'}, whose definitions Pencil.dev files do not hold; re-enable those libraries after reopening to restore them.`
113
+ case 'missing-image-fills':
114
+ return `Image fills with missing image data were left out (${warning.count}); Pencil.dev files cannot hold a paint without its image.`
115
+ case 'dropped-effects':
116
+ return `Noise and texture effects were left out (${warning.count}); Pencil.dev files have no form for them.`
117
+ case 'dropped-filters':
118
+ return `Image adjustment filters were left out (${warning.count}); Pencil.dev files have no form for them.`
119
+ case 'dropped-scroll':
120
+ return `Scroll overflow was left out (${warning.count}); Pencil.dev files have no form for it.`
121
+ case 'dropped-font-features':
122
+ return `OpenType font features were left out (${warning.count}); Pencil.dev files have no form for them.`
123
+ default: {
124
+ const unhandled: never = warning
125
+ throw new Error(`Unhandled pen write warning: ${String(unhandled)}`)
126
+ }
127
+ }
128
+ }
129
+
130
+ /** Records a warning as its sentence and its kind, in the order it was found. */
131
+ function emit(state: PenWriteState, warning: PenWriteWarning): void {
132
+ state.details.push(warning)
133
+ state.warnings.push(penWriteWarningText(warning))
134
+ }
135
+
88
136
  /** What a caller learns about content a written `.pen` file cannot hold. */
89
137
  export interface PenWriteOptions {
90
138
  /** Collects one sentence per kind of content left out, in place of silently losing it. */
91
139
  warnings?: string[]
140
+ /** Collects the same facts as kinds, for a host that shows them in its own language. */
141
+ warningDetails?: PenWriteWarning[]
92
142
  }
93
143
 
94
144
  /** Snaps matrix values that are within floating-point noise of an integer. */
@@ -822,6 +872,7 @@ export function penDocumentFromGraph(
822
872
  writtenIds: writtenNodeIds(graph),
823
873
  importedIds: importedComponentIds(graph, imports ?? {}),
824
874
  warnings: options.warnings ?? [],
875
+ details: [],
825
876
  drops: { images: 0, effects: 0, filters: 0, scroll: 0, fontFeatures: 0 }
826
877
  }
827
878
  const pages = graph.getPages()
@@ -875,16 +926,13 @@ export function penDocumentFromGraph(
875
926
  if (publication) document.sourceLibraryPublication = publication
876
927
  if (pages.length > 1) {
877
928
  const name = document.name ?? 'Page 1'
878
- state.warnings.push(
879
- `Pencil.dev files hold one page; ${pages.length} pages were merged into “${name}”.`
880
- )
929
+ emit(state, { kind: 'merged-pages', pages: pages.length, name })
881
930
  }
882
931
  if (graph.documentColorSpace === 'display-p3') {
883
- state.warnings.push(
884
- '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.'
885
- )
932
+ emit(state, { kind: 'display-p3-colors' })
886
933
  }
887
934
  reportDrops(state)
935
+ options.warningDetails?.push(...state.details)
888
936
  return document
889
937
  }
890
938
 
@@ -900,36 +948,18 @@ function enabledLibrariesOf(
900
948
  const bindings = [...graph.enabledLibraries.values()]
901
949
  if (bindings.length === 0) return null
902
950
  const enabled = bindings.filter((binding) => binding.enabled).length
903
- if (enabled > 0)
904
- state.warnings.push(
905
- `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.`
906
- )
951
+ if (enabled > 0) emit(state, { kind: 'library-definitions', count: enabled })
907
952
  return bindings
908
953
  }
909
954
 
910
955
  /** Adds one sentence for each kind of content the written file had to leave out. */
911
956
  function reportDrops(state: PenWriteState): void {
912
957
  const { images, effects, filters, scroll, fontFeatures } = state.drops
913
- if (images > 0)
914
- state.warnings.push(
915
- `Image fills with missing image data were left out (${images}); Pencil.dev files cannot hold a paint without its image.`
916
- )
917
- if (effects > 0)
918
- state.warnings.push(
919
- `Noise and texture effects were left out (${effects}); Pencil.dev files have no form for them.`
920
- )
921
- if (filters > 0)
922
- state.warnings.push(
923
- `Image adjustment filters were left out (${filters}); Pencil.dev files have no form for them.`
924
- )
925
- if (scroll > 0)
926
- state.warnings.push(
927
- `Scroll overflow was left out (${scroll}); Pencil.dev files have no form for it.`
928
- )
929
- if (fontFeatures > 0)
930
- state.warnings.push(
931
- `OpenType font features were left out (${fontFeatures}); Pencil.dev files have no form for them.`
932
- )
958
+ if (images > 0) emit(state, { kind: 'missing-image-fills', count: images })
959
+ if (effects > 0) emit(state, { kind: 'dropped-effects', count: effects })
960
+ if (filters > 0) emit(state, { kind: 'dropped-filters', count: filters })
961
+ if (scroll > 0) emit(state, { kind: 'dropped-scroll', count: scroll })
962
+ if (fontFeatures > 0) emit(state, { kind: 'dropped-font-features', count: fontFeatures })
933
963
  }
934
964
 
935
965
  export function stringifyPenDocument(document: PenDocument): string {