@pairdraw/core 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/canvas/rulers.js +1 -1
  2. package/dist/canvas/rulers.js.map +1 -1
  3. package/dist/clipboard/pairdraw.d.ts.map +1 -1
  4. package/dist/clipboard/pairdraw.js +53 -7
  5. package/dist/clipboard/pairdraw.js.map +1 -1
  6. package/dist/design-jsx/preview/picture.js +6 -1
  7. package/dist/design-jsx/preview/picture.js.map +1 -1
  8. package/dist/editor/alignment.d.ts.map +1 -1
  9. package/dist/editor/alignment.js +35 -27
  10. package/dist/editor/alignment.js.map +1 -1
  11. package/dist/editor/clipboard/detach.d.ts.map +1 -1
  12. package/dist/editor/clipboard/detach.js +3 -3
  13. package/dist/editor/clipboard/detach.js.map +1 -1
  14. package/dist/editor/clipboard/paste/properties.d.ts.map +1 -1
  15. package/dist/editor/clipboard/paste/properties.js +3 -1
  16. package/dist/editor/clipboard/paste/properties.js.map +1 -1
  17. package/dist/editor/structure.d.ts.map +1 -1
  18. package/dist/editor/structure.js +3 -1
  19. package/dist/editor/structure.js.map +1 -1
  20. package/dist/editor/viewport.js +2 -2
  21. package/dist/editor/viewport.js.map +1 -1
  22. package/dist/figma-api/text/bindings.d.ts.map +1 -1
  23. package/dist/figma-api/text/bindings.js +20 -8
  24. package/dist/figma-api/text/bindings.js.map +1 -1
  25. package/dist/figma-api/text/index.js +1 -1
  26. package/dist/io/formats/design-tokens/apply.d.ts +1 -1
  27. package/dist/io/formats.d.ts.map +1 -1
  28. package/dist/io/formats.js +3 -5
  29. package/dist/io/formats.js.map +1 -1
  30. package/dist/text/character-style.d.ts.map +1 -1
  31. package/dist/text/character-style.js +2 -1
  32. package/dist/text/character-style.js.map +1 -1
  33. package/dist/text/index.js +1 -1
  34. package/dist/tools/read/libraries.d.ts.map +1 -1
  35. package/dist/tools/read/libraries.js +5 -5
  36. package/dist/tools/read/libraries.js.map +1 -1
  37. package/package.json +9 -9
  38. package/src/canvas/rulers.ts +1 -1
  39. package/src/clipboard/pairdraw.ts +51 -7
  40. package/src/design-jsx/preview/picture.ts +8 -2
  41. package/src/editor/alignment.ts +33 -29
  42. package/src/editor/clipboard/detach.ts +9 -3
  43. package/src/editor/clipboard/paste/properties.ts +3 -1
  44. package/src/editor/structure.ts +3 -1
  45. package/src/editor/viewport.ts +2 -2
  46. package/src/figma-api/text/bindings.ts +26 -8
  47. package/src/io/formats.ts +5 -9
  48. package/src/text/character-style.ts +8 -4
  49. package/src/tools/read/libraries.ts +15 -8
@@ -1 +1 @@
1
- {"version":3,"file":"properties.js","names":[],"sources":["../../../../src/editor/clipboard/paste/properties.ts"],"sourcesContent":["import { noop } from 'es-toolkit/function'\nimport { omitBy, pick } from 'es-toolkit/object'\n\nimport { materializeFigFragment } from '@pairdraw/fig'\nimport { parseFigmaClipboard } from '@pairdraw/fig/clipboard'\nimport type { SceneGraph, SceneNode, StyleRun } from '@pairdraw/scene-graph'\nimport {\n AUTO_LAYOUT_FIELDS,\n CORNER_FIELDS,\n PAINT_FIELDS,\n STROKE_FIELDS,\n TEXT_STYLE_FIELDS\n} from '@pairdraw/scene-graph/fields'\nimport { STYLE_LINK_FIELDS, sharedStyleRefKey } from '@pairdraw/scene-graph/shared-styles'\n\nimport { parsePairdrawClipboard } from '#core/clipboard'\nimport { importClipboardDependenciesWithUndo } from '#core/editor/clipboard/dependencies'\nimport type { ClipboardSnapshot } from '#core/editor/clipboard/snapshot'\nimport { loadBoundFonts } from '#core/editor/text/bound-fonts'\nimport type { EditorContext } from '#core/editor/types'\nimport { reconcileVariableLayouts } from '#core/layout/variables'\n\n/**\n * Figma's Paste properties: the look of the one copied layer, applied to others. Position, size,\n * rotation, name, constraints, export settings, content, and structure never move.\n */\n\nconst APPEARANCE_FIELDS = [\n ...PAINT_FIELDS,\n ...STROKE_FIELDS,\n sharedStyleRefKey('fill'),\n sharedStyleRefKey('stroke'),\n sharedStyleRefKey('effect')\n] as const\n\n/** Auto layout and layout grids, which move only from one frame to another. */\nconst FRAME_FIELDS = [\n ...AUTO_LAYOUT_FIELDS,\n 'itemReverseZIndex',\n 'layoutGrids',\n sharedStyleRefKey('grid')\n] as const satisfies ReadonlyArray<keyof SceneNode>\n\n/** Text style fields, which move only from one text layer to another. */\nconst TEXT_FIELDS = [...TEXT_STYLE_FIELDS, sharedStyleRefKey('text')] as const\n\nconst NO_APPEARANCE: ReadonlySet<SceneNode['type']> = new Set(['CANVAS', 'SECTION', 'CONNECTOR'])\nconst FRAME_TYPES: ReadonlySet<SceneNode['type']> = new Set(['FRAME', 'COMPONENT', 'INSTANCE'])\n\ntype PastedField =\n | (typeof APPEARANCE_FIELDS)[number]\n | (typeof CORNER_FIELDS)[number]\n | (typeof FRAME_FIELDS)[number]\n | (typeof TEXT_FIELDS)[number]\n\n/** The run overrides that replace a text layer's own value of each pasted field. */\nconst RUN_OVERRIDES: Readonly<Record<string, readonly string[]>> = {\n fills: ['fills', 'fillStyleId'],\n fillStyleId: ['fills', 'fillStyleId'],\n textStyleId: ['textStyleId']\n}\n\nfunction fieldOf(key: string): string {\n return key.split('/')[0] ?? key\n}\n\n/** Fields a text layer's character runs override, which Figma treats as mixed and leaves alone. */\nfunction mixedFields(source: SceneNode): Set<string> {\n const mixed = new Set<string>()\n for (const run of source.styleRuns) {\n for (const key of Object.keys(run.style)) mixed.add(key)\n for (const key of Object.keys(run.style.boundVariables ?? {})) mixed.add(key)\n }\n if (mixed.has('fills') || mixed.has('fillStyleId')) mixed.add('fills').add('fillStyleId')\n return mixed\n}\n\nfunction pastedFields(source: SceneNode, target: SceneNode): PastedField[] {\n const fields: PastedField[] = [...APPEARANCE_FIELDS]\n // A text layer has no corners in Figma.\n if (source.type !== 'TEXT' && target.type !== 'TEXT') fields.push(...CORNER_FIELDS)\n if (FRAME_TYPES.has(source.type) && FRAME_TYPES.has(target.type)) fields.push(...FRAME_FIELDS)\n if (source.type === 'TEXT' && target.type === 'TEXT') fields.push(...TEXT_FIELDS)\n const mixed = source.type === 'TEXT' ? mixedFields(source) : new Set<string>()\n return fields.filter((field) => !mixed.has(field))\n}\n\n/** The target's runs without the overrides the pasted fields replace, so they cover all of it. */\nfunction runsWithout(runs: StyleRun[], fields: ReadonlySet<string>): StyleRun[] {\n const overrides = new Set([...fields].flatMap((field) => RUN_OVERRIDES[field] ?? [field]))\n return runs.flatMap((run) => {\n const style = omitBy(run.style, (_, key) => overrides.has(key))\n if (style.boundVariables) {\n const bound = omitBy(style.boundVariables, (_, key) => fields.has(key))\n if (Object.keys(bound).length > 0) style.boundVariables = bound\n else delete style.boundVariables\n }\n return Object.keys(style).length > 0 ? [{ ...run, style }] : []\n })\n}\n\n/** Whether `source` is a layer whose look can be pasted. */\nexport function hasPastableProperties(source: SceneNode): boolean {\n return !NO_APPEARANCE.has(source.type)\n}\n\n/**\n * What pasting the look of `source` onto `target` changes, or null when the target takes none (a\n * page, a section, a connector). Locked layers take it, as in Figma.\n */\nexport function pastedPropertyChanges(\n source: SceneNode,\n target: SceneNode\n): Partial<SceneNode> | null {\n if (!hasPastableProperties(source) || NO_APPEARANCE.has(target.type)) return null\n const fields = pastedFields(source, target)\n const changes: Partial<SceneNode> = structuredClone(pick(source, fields))\n const replaced = new Set<string>(fields)\n if (target.type === 'TEXT' && target.styleRuns.length > 0)\n changes.styleRuns = runsWithout(target.styleRuns, replaced)\n // Bindings of the fields being replaced go; the copied ones come in.\n const kept = Object.entries(target.boundVariables).filter(([key]) => !replaced.has(fieldOf(key)))\n const brought = Object.entries(source.boundVariables).filter(([key]) =>\n replaced.has(fieldOf(key))\n )\n changes.boundVariables = Object.fromEntries([...kept, ...brought])\n return changes\n}\n\n/**\n * A copied layer from another document, keeping only the style and variable links `graph` can\n * resolve; the copied values stay either way.\n */\nexport function withResolvableLinks(source: SceneNode, graph: SceneGraph): SceneNode {\n const resolved = structuredClone(source)\n for (const field of STYLE_LINK_FIELDS) {\n const id = resolved[field]\n if (id && !graph.getNode(id)) resolved[field] = null\n }\n resolved.boundVariables = Object.fromEntries(\n Object.entries(resolved.boundVariables).filter(([, id]) => graph.variables.has(id))\n )\n return resolved\n}\n\ninterface PastedSource {\n node: SceneNode\n images: ReadonlyMap<string, Uint8Array>\n}\n\n/** The one layer a clipboard payload from another app or tab holds, or null. */\nasync function sourceFromHTML(html: string): Promise<PastedSource | null> {\n const pairdraw = parsePairdrawClipboard(html)\n if (pairdraw) {\n const { nodes, images } = pairdraw\n return nodes.length === 1 ? { node: nodes[0], images } : null\n }\n const figma = await parseFigmaClipboard(html)\n if (!figma) return null\n const fragment = materializeFigFragment(figma.nodes, figma.blobs, {\n missingComponent: 'detach-empty'\n })\n const { rootIds } = fragment\n const node = rootIds.length === 1 ? fragment.graph.getNode(rootIds[0]) : undefined\n return node ? { node, images: fragment.graph.images } : null\n}\n\nexport function createClipboardPropertiesActions(\n ctx: EditorContext,\n updateNodeWithUndo: (id: string, changes: Partial<SceneNode>, label?: string) => void,\n loadFontsForNodes: (nodeIds: string[]) => Promise<unknown>\n) {\n const LABEL = 'Paste properties'\n\n function targets(): SceneNode[] {\n return [...ctx.state.selectedIds].flatMap((id) => {\n const node = ctx.graph.getNode(id)\n return node && !NO_APPEARANCE.has(node.type) ? [node] : []\n })\n }\n\n /** Applies the look of `source` to `targets` in the running batch; returns the changed ids. */\n function apply(\n source: SceneNode,\n images: ReadonlyMap<string, Uint8Array>,\n nodes: SceneNode[]\n ): string[] {\n for (const paint of [...source.fills, ...source.strokes]) {\n const bytes = paint.imageHash ? images.get(paint.imageHash) : undefined\n if (paint.imageHash && bytes && !ctx.graph.images.has(paint.imageHash))\n ctx.graph.images.set(paint.imageHash, bytes)\n }\n return nodes.flatMap((target) => {\n const changes = pastedPropertyChanges(source, target)\n if (!changes) return []\n updateNodeWithUndo(target.id, changes, LABEL)\n return [target.id]\n })\n }\n\n /**\n * Resolves the bindings brought onto `changed` against this document's variables, whose values\n * can differ from the copied ones, now and again on redo after the pasted values return.\n */\n function resolveBindings(changed: string[]) {\n const resolve = () =>\n loadBoundFonts(ctx, reconcileVariableLayouts(ctx.graph, { subtrees: changed }))\n resolve()\n // Undoing the paste puts back every field it set, so this step has nothing of its own to undo.\n ctx.undo.push({ label: LABEL, forward: resolve, inverse: noop })\n }\n\n async function finish(changed: string[]): Promise<number> {\n if (changed.length > 0) {\n await loadFontsForNodes(changed)\n ctx.requestRender()\n }\n return changed.length\n }\n\n /**\n * Paste properties from a copy made in this app: the look of its one layer, with the styles and\n * variables it uses, onto every selected layer in one undo step. Returns how many changed.\n * From another document, a collection or style this one has by name is used, not added again.\n */\n async function pastePropertiesFromSnapshot(snapshot: ClipboardSnapshot): Promise<number> {\n const nodes = targets()\n if (snapshot.nodes.length !== 1 || !hasPastableProperties(snapshot.nodes[0])) return 0\n if (nodes.length === 0) return 0\n const changed = ctx.undo.runBatch(LABEL, () => {\n const dependencies = importClipboardDependenciesWithUndo(ctx, snapshot, { mode: 'import' })\n const [source] = dependencies.nodes\n const pasted = apply(source, snapshot.images, nodes)\n if (dependencies.resolveBindings && pasted.length > 0) resolveBindings(pasted)\n return pasted\n })\n return finish(changed)\n }\n\n /** Paste properties from clipboard HTML, such as a Figma copy; links it cannot resolve drop. */\n async function pastePropertiesFromHTML(html: string): Promise<number> {\n const nodes = targets()\n if (nodes.length === 0) return 0\n const source = await sourceFromHTML(html)\n if (!source || !hasPastableProperties(source.node)) return 0\n const resolved = withResolvableLinks(source.node, ctx.graph)\n const changed = ctx.undo.runBatch(LABEL, () => apply(resolved, source.images, nodes))\n return finish(changed)\n }\n\n return { pastePropertiesFromSnapshot, pastePropertiesFromHTML }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,MAAM,oBAAoB;CACxB,GAAG;CACH,GAAG;CACH,kBAAkB,MAAM;CACxB,kBAAkB,QAAQ;CAC1B,kBAAkB,QAAQ;AAC5B;;AAGA,MAAM,eAAe;CACnB,GAAG;CACH;CACA;CACA,kBAAkB,MAAM;AAC1B;;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AAC;CACvB;;CAGA,eAAe,wBAAwB,MAA+B;EACpE,MAAM,QAAQ,QAAQ;EACtB,IAAI,MAAM,WAAW,GAAG,OAAO;EAC/B,MAAM,SAAS,MAAM,eAAe,IAAI;EACxC,IAAI,CAAC,UAAU,CAAC,sBAAsB,OAAO,IAAI,GAAG,OAAO;EAC3D,MAAM,WAAW,oBAAoB,OAAO,MAAM,IAAI,KAAK;EAE3D,OAAO,OADS,IAAI,KAAK,SAAS,aAAa,MAAM,UAAU,OAAO,QAAQ,KAAK,CAC/D,CAAC;CACvB;CAEA,OAAO;EAAE;EAA6B;CAAwB;AAChE"}
1
+ {"version":3,"file":"properties.js","names":[],"sources":["../../../../src/editor/clipboard/paste/properties.ts"],"sourcesContent":["import { noop } from 'es-toolkit/function'\nimport { omitBy, pick } from 'es-toolkit/object'\n\nimport { materializeFigFragment } from '@pairdraw/fig'\nimport { parseFigmaClipboard } from '@pairdraw/fig/clipboard'\nimport type { SceneGraph, SceneNode, StyleRun } from '@pairdraw/scene-graph'\nimport {\n AUTO_LAYOUT_FIELDS,\n CORNER_FIELDS,\n PAINT_FIELDS,\n STROKE_FIELDS,\n TEXT_STYLE_FIELDS\n} from '@pairdraw/scene-graph/fields'\nimport { STYLE_LINK_FIELDS, sharedStyleRefKey } from '@pairdraw/scene-graph/shared-styles'\nimport { withBoundBindingScales } from '@pairdraw/scene-graph/variables'\n\nimport { parsePairdrawClipboard } from '#core/clipboard'\nimport { importClipboardDependenciesWithUndo } from '#core/editor/clipboard/dependencies'\nimport type { ClipboardSnapshot } from '#core/editor/clipboard/snapshot'\nimport { loadBoundFonts } from '#core/editor/text/bound-fonts'\nimport type { EditorContext } from '#core/editor/types'\nimport { reconcileVariableLayouts } from '#core/layout/variables'\n\n/**\n * Figma's Paste properties: the look of the one copied layer, applied to others. Position, size,\n * rotation, name, constraints, export settings, content, and structure never move.\n */\n\nconst APPEARANCE_FIELDS = [\n ...PAINT_FIELDS,\n ...STROKE_FIELDS,\n sharedStyleRefKey('fill'),\n sharedStyleRefKey('stroke'),\n sharedStyleRefKey('effect')\n] as const\n\n/** Auto layout and layout grids, which move only from one frame to another. */\nconst FRAME_FIELDS = [\n ...AUTO_LAYOUT_FIELDS,\n 'itemReverseZIndex',\n 'layoutGrids',\n sharedStyleRefKey('grid')\n] as const satisfies ReadonlyArray<keyof SceneNode>\n\n/** Text style fields, which move only from one text layer to another. */\nconst TEXT_FIELDS = [...TEXT_STYLE_FIELDS, sharedStyleRefKey('text')] as const\n\nconst NO_APPEARANCE: ReadonlySet<SceneNode['type']> = new Set(['CANVAS', 'SECTION', 'CONNECTOR'])\nconst FRAME_TYPES: ReadonlySet<SceneNode['type']> = new Set(['FRAME', 'COMPONENT', 'INSTANCE'])\n\ntype PastedField =\n | (typeof APPEARANCE_FIELDS)[number]\n | (typeof CORNER_FIELDS)[number]\n | (typeof FRAME_FIELDS)[number]\n | (typeof TEXT_FIELDS)[number]\n\n/** The run overrides that replace a text layer's own value of each pasted field. */\nconst RUN_OVERRIDES: Readonly<Record<string, readonly string[]>> = {\n fills: ['fills', 'fillStyleId'],\n fillStyleId: ['fills', 'fillStyleId'],\n textStyleId: ['textStyleId']\n}\n\nfunction fieldOf(key: string): string {\n return key.split('/')[0] ?? key\n}\n\n/** Fields a text layer's character runs override, which Figma treats as mixed and leaves alone. */\nfunction mixedFields(source: SceneNode): Set<string> {\n const mixed = new Set<string>()\n for (const run of source.styleRuns) {\n for (const key of Object.keys(run.style)) mixed.add(key)\n for (const key of Object.keys(run.style.boundVariables ?? {})) mixed.add(key)\n }\n if (mixed.has('fills') || mixed.has('fillStyleId')) mixed.add('fills').add('fillStyleId')\n return mixed\n}\n\nfunction pastedFields(source: SceneNode, target: SceneNode): PastedField[] {\n const fields: PastedField[] = [...APPEARANCE_FIELDS]\n // A text layer has no corners in Figma.\n if (source.type !== 'TEXT' && target.type !== 'TEXT') fields.push(...CORNER_FIELDS)\n if (FRAME_TYPES.has(source.type) && FRAME_TYPES.has(target.type)) fields.push(...FRAME_FIELDS)\n if (source.type === 'TEXT' && target.type === 'TEXT') fields.push(...TEXT_FIELDS)\n const mixed = source.type === 'TEXT' ? mixedFields(source) : new Set<string>()\n return fields.filter((field) => !mixed.has(field))\n}\n\n/** The target's runs without the overrides the pasted fields replace, so they cover all of it. */\nfunction runsWithout(runs: StyleRun[], fields: ReadonlySet<string>): StyleRun[] {\n const overrides = new Set([...fields].flatMap((field) => RUN_OVERRIDES[field] ?? [field]))\n return runs.flatMap((run) => {\n let style = omitBy(run.style, (_, key) => overrides.has(key))\n if (style.boundVariables) {\n const bound = omitBy(style.boundVariables, (_, key) => fields.has(key))\n if (Object.keys(bound).length > 0) style.boundVariables = bound\n else delete style.boundVariables\n }\n style = withBoundBindingScales(style)\n return Object.keys(style).length > 0 ? [{ ...run, style }] : []\n })\n}\n\n/** Whether `source` is a layer whose look can be pasted. */\nexport function hasPastableProperties(source: SceneNode): boolean {\n return !NO_APPEARANCE.has(source.type)\n}\n\n/**\n * What pasting the look of `source` onto `target` changes, or null when the target takes none (a\n * page, a section, a connector). Locked layers take it, as in Figma.\n */\nexport function pastedPropertyChanges(\n source: SceneNode,\n target: SceneNode\n): Partial<SceneNode> | null {\n if (!hasPastableProperties(source) || NO_APPEARANCE.has(target.type)) return null\n const fields = pastedFields(source, target)\n const changes: Partial<SceneNode> = structuredClone(pick(source, fields))\n const replaced = new Set<string>(fields)\n if (target.type === 'TEXT' && target.styleRuns.length > 0)\n changes.styleRuns = runsWithout(target.styleRuns, replaced)\n // Bindings of the fields being replaced go; the copied ones come in.\n const kept = Object.entries(target.boundVariables).filter(([key]) => !replaced.has(fieldOf(key)))\n const brought = Object.entries(source.boundVariables).filter(([key]) =>\n replaced.has(fieldOf(key))\n )\n changes.boundVariables = Object.fromEntries([...kept, ...brought])\n return changes\n}\n\n/**\n * A copied layer from another document, keeping only the style and variable links `graph` can\n * resolve; the copied values stay either way.\n */\nexport function withResolvableLinks(source: SceneNode, graph: SceneGraph): SceneNode {\n const resolved = structuredClone(source)\n for (const field of STYLE_LINK_FIELDS) {\n const id = resolved[field]\n if (id && !graph.getNode(id)) resolved[field] = null\n }\n resolved.boundVariables = Object.fromEntries(\n Object.entries(resolved.boundVariables).filter(([, id]) => graph.variables.has(id))\n )\n return resolved\n}\n\ninterface PastedSource {\n node: SceneNode\n images: ReadonlyMap<string, Uint8Array>\n}\n\n/** The one layer a clipboard payload from another app or tab holds, or null. */\nasync function sourceFromHTML(html: string): Promise<PastedSource | null> {\n const pairdraw = parsePairdrawClipboard(html)\n if (pairdraw) {\n const { nodes, images } = pairdraw\n return nodes.length === 1 ? { node: nodes[0], images } : null\n }\n const figma = await parseFigmaClipboard(html)\n if (!figma) return null\n const fragment = materializeFigFragment(figma.nodes, figma.blobs, {\n missingComponent: 'detach-empty'\n })\n const { rootIds } = fragment\n const node = rootIds.length === 1 ? fragment.graph.getNode(rootIds[0]) : undefined\n return node ? { node, images: fragment.graph.images } : null\n}\n\nexport function createClipboardPropertiesActions(\n ctx: EditorContext,\n updateNodeWithUndo: (id: string, changes: Partial<SceneNode>, label?: string) => void,\n loadFontsForNodes: (nodeIds: string[]) => Promise<unknown>\n) {\n const LABEL = 'Paste properties'\n\n function targets(): SceneNode[] {\n return [...ctx.state.selectedIds].flatMap((id) => {\n const node = ctx.graph.getNode(id)\n return node && !NO_APPEARANCE.has(node.type) ? [node] : []\n })\n }\n\n /** Applies the look of `source` to `targets` in the running batch; returns the changed ids. */\n function apply(\n source: SceneNode,\n images: ReadonlyMap<string, Uint8Array>,\n nodes: SceneNode[]\n ): string[] {\n for (const paint of [...source.fills, ...source.strokes]) {\n const bytes = paint.imageHash ? images.get(paint.imageHash) : undefined\n if (paint.imageHash && bytes && !ctx.graph.images.has(paint.imageHash))\n ctx.graph.images.set(paint.imageHash, bytes)\n }\n return nodes.flatMap((target) => {\n const changes = pastedPropertyChanges(source, target)\n if (!changes) return []\n updateNodeWithUndo(target.id, changes, LABEL)\n return [target.id]\n })\n }\n\n /**\n * Resolves the bindings brought onto `changed` against this document's variables, whose values\n * can differ from the copied ones, now and again on redo after the pasted values return.\n */\n function resolveBindings(changed: string[]) {\n const resolve = () =>\n loadBoundFonts(ctx, reconcileVariableLayouts(ctx.graph, { subtrees: changed }))\n resolve()\n // Undoing the paste puts back every field it set, so this step has nothing of its own to undo.\n ctx.undo.push({ label: LABEL, forward: resolve, inverse: noop })\n }\n\n async function finish(changed: string[]): Promise<number> {\n if (changed.length > 0) {\n await loadFontsForNodes(changed)\n ctx.requestRender()\n }\n return changed.length\n }\n\n /**\n * Paste properties from a copy made in this app: the look of its one layer, with the styles and\n * variables it uses, onto every selected layer in one undo step. Returns how many changed.\n * From another document, a collection or style this one has by name is used, not added again.\n */\n async function pastePropertiesFromSnapshot(snapshot: ClipboardSnapshot): Promise<number> {\n const nodes = targets()\n if (snapshot.nodes.length !== 1 || !hasPastableProperties(snapshot.nodes[0])) return 0\n if (nodes.length === 0) return 0\n const changed = ctx.undo.runBatch(LABEL, () => {\n const dependencies = importClipboardDependenciesWithUndo(ctx, snapshot, { mode: 'import' })\n const [source] = dependencies.nodes\n const pasted = apply(source, snapshot.images, nodes)\n if (dependencies.resolveBindings && pasted.length > 0) resolveBindings(pasted)\n return pasted\n })\n return finish(changed)\n }\n\n /** Paste properties from clipboard HTML, such as a Figma copy; links it cannot resolve drop. */\n async function pastePropertiesFromHTML(html: string): Promise<number> {\n const nodes = targets()\n if (nodes.length === 0) return 0\n const source = await sourceFromHTML(html)\n if (!source || !hasPastableProperties(source.node)) return 0\n const resolved = withResolvableLinks(source.node, ctx.graph)\n const changed = ctx.undo.runBatch(LABEL, () => apply(resolved, source.images, nodes))\n return finish(changed)\n }\n\n return { pastePropertiesFromSnapshot, pastePropertiesFromHTML }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,oBAAoB;CACxB,GAAG;CACH,GAAG;CACH,kBAAkB,MAAM;CACxB,kBAAkB,QAAQ;CAC1B,kBAAkB,QAAQ;AAC5B;;AAGA,MAA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;GACnD,IAAI,aAAa,mBAAmB,OAAO,SAAS,GAAG,gBAAgB,MAAM;GAC7E,OAAO;EACT,CACoB,CAAC;CACvB;;CAGA,eAAe,wBAAwB,MAA+B;EACpE,MAAM,QAAQ,QAAQ;EACtB,IAAI,MAAM,WAAW,GAAG,OAAO;EAC/B,MAAM,SAAS,MAAM,eAAe,IAAI;EACxC,IAAI,CAAC,UAAU,CAAC,sBAAsB,OAAO,IAAI,GAAG,OAAO;EAC3D,MAAM,WAAW,oBAAoB,OAAO,MAAM,IAAI,KAAK;EAE3D,OAAO,OADS,IAAI,KAAK,SAAS,aAAa,MAAM,UAAU,OAAO,QAAQ,KAAK,CAC/D,CAAC;CACvB;CAEA,OAAO;EAAE;EAA6B;CAAwB;AAChE"}
@@ -1 +1 @@
1
- {"version":3,"file":"structure.d.ts","names":[],"sources":["../../src/editor/structure.ts"],"mappings":";;;;;;;iBA6BgB,uBAAuB,KAAK;EA8Ed,aAAA;EAyCY,wBAAA,SAAA,2BAAA;EAIP,iBAAA,SAAA;EAkBT,aAAA,YAAM;;;;;;EArFmB,2BAAA,eAAA,aAAW,WAAa;EAIlC,kBAAA,cAAA;EAIC,kBAAA,eAAA;EAII,sBAAA,eAAA;EAME,wBAAA,eAAA;2CAAA;EA7Dd,gBAAA,mBAAQ;EAuBvB,2BAAA,kEAAiD,eACjD,aAAW,aACb,QAAQ;EAKkB,mBAAA,eAAA;EAIH,gBAAA,eAAA;EAKC,iBAAA,eAAA;;;;;;;;EA/CT,aAAA;EA2JA,kBAAA;EACA,kBAAA;EACI,qBAAA,WAAA"}
1
+ {"version":3,"file":"structure.d.ts","names":[],"sources":["../../src/editor/structure.ts"],"mappings":";;;;;;;iBA6BgB,uBAAuB,KAAK;EA8Ed,aAAA;EA2CY,wBAAA,SAAA,2BAAA;EAIP,iBAAA,SAAA;EAkBT,aAAA,YAAM;;;;;;EAvFmB,2BAAA,eAAA,aAAW,WAAa;EAIlC,kBAAA,cAAA;EAIC,kBAAA,eAAA;EAII,sBAAA,eAAA;EAME,wBAAA,eAAA;2CAAA;EA7Dd,gBAAA,mBAAQ;EAuBvB,2BAAA,kEAAiD,eACjD,aAAW,aACb,QAAQ;EAKkB,mBAAA,eAAA;EAIH,gBAAA,eAAA;EAKC,iBAAA,eAAA;;;;;;;;EA/CT,aAAA;EA6JA,kBAAA;EACA,kBAAA;EACI,qBAAA,WAAA"}
@@ -84,12 +84,13 @@ function createStructureActions(ctx) {
84
84
  }).sort((a, b) => a.index - b.index);
85
85
  if (origins.length === 0) return;
86
86
  const parentIds = new Set(origins.map((origin) => origin.parentId));
87
+ const prevSelection = new Set(ctx.state.selectedIds);
87
88
  const move = () => {
88
89
  for (const { id } of origins) ctx.graph.reparentNode(id, pageId);
89
90
  for (const parentId of parentIds) ctx.runLayoutForNode(parentId);
91
+ ctx.setSelectedIds(/* @__PURE__ */ new Set());
90
92
  };
91
93
  move();
92
- ctx.setSelectedIds(/* @__PURE__ */ new Set());
93
94
  ctx.undo.push({
94
95
  label: "Move to page",
95
96
  forward: move,
@@ -99,6 +100,7 @@ function createStructureActions(ctx) {
99
100
  ctx.graph.updateNode(id, place);
100
101
  }
101
102
  for (const parentId of parentIds) ctx.runLayoutForNode(parentId);
103
+ ctx.setSelectedIds(new Set(prevSelection));
102
104
  }
103
105
  });
104
106
  }
@@ -1 +1 @@
1
- {"version":3,"file":"structure.js","names":["wrapSelectionInContainer","wrapSelectionInContainerImpl","wrapInAutoLayout","wrapInAutoLayoutImpl","booleanOperationSelected","booleanOperationSelectedImpl","ungroupSelected","flattenSelected","flattenSelectedImpl","outlineStrokeSelected","outlineStrokeSelectedImpl"],"sources":["../../src/editor/structure.ts"],"sourcesContent":["import { pick } from 'es-toolkit'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { TRANSFORM_FIELDS } from '@pairdraw/scene-graph/fields'\nimport { generatedFrameKind } from '@pairdraw/scene-graph/generated'\nimport { createsComponentCycle } from '@pairdraw/scene-graph/instances'\n\nimport { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'\nimport { fitEnclosingGroupsWithUndo } from '#core/editor/structure/group/bounds'\n\nimport { wrapInAutoLayout as wrapInAutoLayoutImpl } from './structure/auto-layout-wrap'\nimport {\n booleanOperationSelected as booleanOperationSelectedImpl,\n type BooleanOperation\n} from './structure/boolean'\nimport { wrapSelectionInContainer as wrapSelectionInContainerImpl } from './structure/container-wrap'\nimport { flattenSelected as flattenSelectedImpl } from './structure/flatten'\nimport { ungroupSelected as ungroupImpl } from './structure/group/ungroup'\nimport { createLayerTypeActions } from './structure/layer-type'\nimport { outlineStrokeSelected as outlineStrokeSelectedImpl } from './structure/outline-stroke'\nimport {\n defaultNodeName,\n previewRenamedNodes,\n type RenameSelectionOptions\n} from './structure/rename'\nimport { createStructureReorderActions } from './structure/reorder'\nimport { createStructureStateActions } from './structure/state'\nimport type { EditorContext } from './types'\n\nexport function createStructureActions(ctx: EditorContext) {\n const reorderActions = createStructureReorderActions(ctx)\n const stateActions = createStructureStateActions(ctx)\n const layerTypeActions = createLayerTypeActions(ctx)\n\n function isTopLevel(parentId: string | null): boolean {\n return !parentId || parentId === ctx.graph.rootId || parentId === ctx.state.currentPageId\n }\n\n /**\n * Moves layers under a new parent; refuses the locked part of an instance, and a layer that\n * would make a component contain itself, as Figma does.\n */\n function reparentNodes(nodeIds: string[], newParentId: string): boolean {\n const parent = ctx.graph.getNode(newParentId)\n // Sections only go into pages and other sections.\n const movable = nodeIds.filter(\n (id) =>\n (ctx.graph.getNode(id)?.type !== 'SECTION' ||\n !parent ||\n parent.type === 'CANVAS' ||\n parent.type === 'SECTION') &&\n !createsComponentCycle(ctx.graph, id, newParentId)\n )\n if (movable.length === 0) return true\n const parents = new Set([newParentId])\n for (const id of movable) {\n const current = ctx.graph.getNode(id)?.parentId\n if (current && current !== newParentId) parents.add(current)\n }\n if (!prepareSlotEdits(ctx, parents)) return false\n for (const id of movable) ctx.graph.reparentNode(id, newParentId)\n return true\n }\n\n function wrapSelectionInContainer(\n containerType: 'GROUP' | 'FRAME' | 'COMPONENT' | 'COMPONENT_SET',\n selectedNodes: SceneNode[],\n extraProps?: Partial<SceneNode>\n ) {\n return wrapSelectionInContainerImpl(ctx, containerType, selectedNodes, extraProps)\n }\n\n function wrapInAutoLayout(selectedNodes: SceneNode[]) {\n return wrapInAutoLayoutImpl(ctx, selectedNodes)\n }\n\n function groupSelected(selectedNodes: SceneNode[]) {\n return wrapSelectionInContainer('GROUP', selectedNodes)\n }\n\n /** Figma frames a selection without a fill or clipping, unlike a drawn frame. */\n function frameSelection(selectedNodes: SceneNode[]) {\n return wrapSelectionInContainer('FRAME', selectedNodes)\n }\n\n function booleanOperationSelected(selectedNodes: SceneNode[], operation: BooleanOperation) {\n return booleanOperationSelectedImpl(ctx, selectedNodes, operation)\n }\n\n function ungroupSelected(selectedNode: SceneNode | undefined) {\n ungroupImpl(ctx, selectedNode)\n }\n\n function flattenSelected(selectedNodes: SceneNode[]) {\n return flattenSelectedImpl(ctx, selectedNodes)\n }\n\n function outlineTextSelected(selectedNodes: SceneNode[]) {\n if (selectedNodes.length === 0 || selectedNodes.some((node) => node.type !== 'TEXT'))\n return null\n return flattenSelectedImpl(ctx, selectedNodes, { label: 'Outline text' })\n }\n\n function outlineStrokeSelected(selectedNodes: SceneNode[]) {\n return outlineStrokeSelectedImpl(ctx, selectedNodes)\n }\n\n function moveToPage(pageId: string) {\n const targetPage = ctx.graph.getNode(pageId)\n if (targetPage?.type !== 'CANVAS') return\n // Where each layer was, read before any of them moves: put back in this order, each lands at\n // its own index again.\n const origins = [...ctx.state.selectedIds]\n .flatMap((id) => {\n const node = ctx.graph.getNode(id)\n const parent = node?.parentId ? ctx.graph.getNode(node.parentId) : undefined\n if (!node || !parent || parent.id === pageId) return []\n const index = parent.childIds.indexOf(id)\n return [{ id, parentId: parent.id, index, place: pick(node, TRANSFORM_FIELDS) }]\n })\n .sort((a, b) => a.index - b.index)\n if (origins.length === 0) return\n const parentIds = new Set(origins.map((origin) => origin.parentId))\n const move = () => {\n for (const { id } of origins) ctx.graph.reparentNode(id, pageId)\n for (const parentId of parentIds) ctx.runLayoutForNode(parentId)\n }\n move()\n ctx.setSelectedIds(new Set())\n ctx.undo.push({\n label: 'Move to page',\n forward: move,\n inverse: () => {\n for (const { id, parentId, index, place } of origins) {\n ctx.graph.insertChildAt(id, parentId, index)\n ctx.graph.updateNode(id, place)\n }\n for (const parentId of parentIds) ctx.runLayoutForNode(parentId)\n }\n })\n }\n\n function selectedNodes(): SceneNode[] {\n return [...ctx.state.selectedIds]\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n }\n\n function previewRenameSelected(options: RenameSelectionOptions) {\n return previewRenamedNodes(selectedNodes(), options)\n }\n\n function renameSelected(options: RenameSelectionOptions) {\n const nodes = selectedNodes()\n if (nodes.length === 0) return\n const before = new Map(nodes.map((node) => [node.id, node.name]))\n const preview = previewRenamedNodes(nodes, options)\n if (preview.error) return\n const applyNames = (names: ReadonlyMap<string, string>) => {\n for (const [id, nextName] of names) ctx.graph.updateNode(id, { name: nextName })\n }\n\n applyNames(preview.names)\n ctx.undo.push({\n label: 'Rename selection',\n forward: () => applyNames(preview.names),\n inverse: () => applyNames(before)\n })\n }\n\n function renameNode(id: string, name: string) {\n const node = ctx.graph.getNode(id)\n if (!node) return\n const previous = { name: node.name, autoRename: node.autoRename }\n const next = name.trim() || defaultNodeName(node.type)\n if (next === previous.name) return\n // A layer named by its text, as a sticky note is, keeps the name it is given, as in FigJam.\n const namedByText = generatedFrameKind(node)?.namedByText ?? false\n const renamed = { name: next, autoRename: namedByText ? false : node.autoRename }\n ctx.graph.updateNode(id, renamed)\n ctx.undo.push({\n label: 'Rename',\n forward: () => ctx.graph.updateNode(id, renamed),\n inverse: () => ctx.graph.updateNode(id, previous)\n })\n }\n\n return {\n isTopLevel,\n acceptsChildren: (parentId: string) => acceptsChildren(ctx, parentId),\n acceptingParent: (parentId: string) => acceptingParent(ctx, parentId),\n fitEnclosingGroups: (parentIds: Iterable<string>) => fitEnclosingGroupsWithUndo(ctx, parentIds),\n ...reorderActions,\n reparentNodes,\n wrapSelectionInContainer,\n wrapInAutoLayout,\n groupSelected,\n frameSelection,\n ...layerTypeActions,\n booleanOperationSelected,\n ungroupSelected,\n flattenSelected,\n outlineTextSelected,\n outlineStrokeSelected,\n ...stateActions,\n moveToPage,\n previewRenameSelected,\n renameSelected,\n renameNode\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,SAAgB,uBAAuB,KAAoB;CACzD,MAAM,iBAAiB,8BAA8B,GAAG;CACxD,MAAM,eAAe,4BAA4B,GAAG;CACpD,MAAM,mBAAmB,uBAAuB,GAAG;CAEnD,SAAS,WAAW,UAAkC;EACpD,OAAO,CAAC,YAAY,aAAa,IAAI,MAAM,UAAU,aAAa,IAAI,MAAM;CAC9E;;;;;CAMA,SAAS,cAAc,SAAmB,aAA8B;EACtE,MAAM,SAAS,IAAI,MAAM,QAAQ,WAAW;EAE5C,MAAM,UAAU,QAAQ,QACrB,QACE,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE,SAAS,aAC/B,CAAC,UACD,OAAO,SAAS,YAChB,OAAO,SAAS,cAClB,CAAC,sBAAsB,IAAI,OAAO,IAAI,WAAW,CACrD;EACA,IAAI,QAAQ,WAAW,GAAG,OAAO;EACjC,MAAM,0BAAU,IAAI,IAAI,CAAC,WAAW,CAAC;EACrC,KAAK,MAAM,MAAM,SAAS;GACxB,MAAM,UAAU,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE;GACvC,IAAI,WAAW,YAAY,aAAa,QAAQ,IAAI,OAAO;EAC7D;EACA,IAAI,CAAC,iBAAiB,KAAK,OAAO,GAAG,OAAO;EAC5C,KAAK,MAAM,MAAM,SAAS,IAAI,MAAM,aAAa,IAAI,WAAW;EAChE,OAAO;CACT;CAEA,SAASA,2BACP,eACA,eACA,YACA;EACA,OAAOC,yBAA6B,KAAK,eAAe,eAAe,UAAU;CAC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,MAAM;EAClC,CAAC;CACH;CAEA,SAAS,WAAW,IAAY,MAAc;EAC5C,MAAM,OAAO,IAAI,MAAM,QAAQ,EAAE;EACjC,IAAI,CAAC,MAAM;EACX,MAAM,WAAW;GAAE,MAAM,KAAK;GAAM,YAAY,KAAK;EAAW;EAChE,MAAM,OAAO,KAAK,KAAK,KAAK,gBAAgB,KAAK,IAAI;EACrD,IAAI,SAAS,SAAS,MAAM;EAG5B,MAAM,UAAU;GAAE,MAAM;GAAM,YADV,mBAAmB,IAAI,CAAC,EAAE,eAAe,QACL,QAAQ,KAAK;EAAW;EAChF,IAAI,MAAM,WAAW,IAAI,OAAO;EAChC,IAAI,KAAK,KAAK;GACZ,OAAO;GACP,eAAe,IAAI,MAAM,WAAW,IAAI,OAAO;GAC/C,eAAe,IAAI,MAAM,WAAW,IAAI,QAAQ;EAClD,CAAC;CACH;CAEA,OAAO;EACL;EACA,kBAAkB,aAAqB,gBAAgB,KAAK,QAAQ;EACpE,kBAAkB,aAAqB,gBAAgB,KAAK,QAAQ;EACpE,qBAAqB,cAAgC,2BAA2B,KAAK,SAAS;EAC9F,GAAG;EACH;EACA,0BAAA;EACA,kBAAA;EACA;EACA;EACA,GAAG;EACH,0BAAA;EACA,iBAAA;EACA,iBAAA;EACA;EACA,uBAAA;EACA,GAAG;EACH;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"structure.js","names":["wrapSelectionInContainer","wrapSelectionInContainerImpl","wrapInAutoLayout","wrapInAutoLayoutImpl","booleanOperationSelected","booleanOperationSelectedImpl","ungroupSelected","flattenSelected","flattenSelectedImpl","outlineStrokeSelected","outlineStrokeSelectedImpl"],"sources":["../../src/editor/structure.ts"],"sourcesContent":["import { pick } from 'es-toolkit'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { TRANSFORM_FIELDS } from '@pairdraw/scene-graph/fields'\nimport { generatedFrameKind } from '@pairdraw/scene-graph/generated'\nimport { createsComponentCycle } from '@pairdraw/scene-graph/instances'\n\nimport { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'\nimport { fitEnclosingGroupsWithUndo } from '#core/editor/structure/group/bounds'\n\nimport { wrapInAutoLayout as wrapInAutoLayoutImpl } from './structure/auto-layout-wrap'\nimport {\n booleanOperationSelected as booleanOperationSelectedImpl,\n type BooleanOperation\n} from './structure/boolean'\nimport { wrapSelectionInContainer as wrapSelectionInContainerImpl } from './structure/container-wrap'\nimport { flattenSelected as flattenSelectedImpl } from './structure/flatten'\nimport { ungroupSelected as ungroupImpl } from './structure/group/ungroup'\nimport { createLayerTypeActions } from './structure/layer-type'\nimport { outlineStrokeSelected as outlineStrokeSelectedImpl } from './structure/outline-stroke'\nimport {\n defaultNodeName,\n previewRenamedNodes,\n type RenameSelectionOptions\n} from './structure/rename'\nimport { createStructureReorderActions } from './structure/reorder'\nimport { createStructureStateActions } from './structure/state'\nimport type { EditorContext } from './types'\n\nexport function createStructureActions(ctx: EditorContext) {\n const reorderActions = createStructureReorderActions(ctx)\n const stateActions = createStructureStateActions(ctx)\n const layerTypeActions = createLayerTypeActions(ctx)\n\n function isTopLevel(parentId: string | null): boolean {\n return !parentId || parentId === ctx.graph.rootId || parentId === ctx.state.currentPageId\n }\n\n /**\n * Moves layers under a new parent; refuses the locked part of an instance, and a layer that\n * would make a component contain itself, as Figma does.\n */\n function reparentNodes(nodeIds: string[], newParentId: string): boolean {\n const parent = ctx.graph.getNode(newParentId)\n // Sections only go into pages and other sections.\n const movable = nodeIds.filter(\n (id) =>\n (ctx.graph.getNode(id)?.type !== 'SECTION' ||\n !parent ||\n parent.type === 'CANVAS' ||\n parent.type === 'SECTION') &&\n !createsComponentCycle(ctx.graph, id, newParentId)\n )\n if (movable.length === 0) return true\n const parents = new Set([newParentId])\n for (const id of movable) {\n const current = ctx.graph.getNode(id)?.parentId\n if (current && current !== newParentId) parents.add(current)\n }\n if (!prepareSlotEdits(ctx, parents)) return false\n for (const id of movable) ctx.graph.reparentNode(id, newParentId)\n return true\n }\n\n function wrapSelectionInContainer(\n containerType: 'GROUP' | 'FRAME' | 'COMPONENT' | 'COMPONENT_SET',\n selectedNodes: SceneNode[],\n extraProps?: Partial<SceneNode>\n ) {\n return wrapSelectionInContainerImpl(ctx, containerType, selectedNodes, extraProps)\n }\n\n function wrapInAutoLayout(selectedNodes: SceneNode[]) {\n return wrapInAutoLayoutImpl(ctx, selectedNodes)\n }\n\n function groupSelected(selectedNodes: SceneNode[]) {\n return wrapSelectionInContainer('GROUP', selectedNodes)\n }\n\n /** Figma frames a selection without a fill or clipping, unlike a drawn frame. */\n function frameSelection(selectedNodes: SceneNode[]) {\n return wrapSelectionInContainer('FRAME', selectedNodes)\n }\n\n function booleanOperationSelected(selectedNodes: SceneNode[], operation: BooleanOperation) {\n return booleanOperationSelectedImpl(ctx, selectedNodes, operation)\n }\n\n function ungroupSelected(selectedNode: SceneNode | undefined) {\n ungroupImpl(ctx, selectedNode)\n }\n\n function flattenSelected(selectedNodes: SceneNode[]) {\n return flattenSelectedImpl(ctx, selectedNodes)\n }\n\n function outlineTextSelected(selectedNodes: SceneNode[]) {\n if (selectedNodes.length === 0 || selectedNodes.some((node) => node.type !== 'TEXT'))\n return null\n return flattenSelectedImpl(ctx, selectedNodes, { label: 'Outline text' })\n }\n\n function outlineStrokeSelected(selectedNodes: SceneNode[]) {\n return outlineStrokeSelectedImpl(ctx, selectedNodes)\n }\n\n function moveToPage(pageId: string) {\n const targetPage = ctx.graph.getNode(pageId)\n if (targetPage?.type !== 'CANVAS') return\n // Where each layer was, read before any of them moves: put back in this order, each lands at\n // its own index again.\n const origins = [...ctx.state.selectedIds]\n .flatMap((id) => {\n const node = ctx.graph.getNode(id)\n const parent = node?.parentId ? ctx.graph.getNode(node.parentId) : undefined\n if (!node || !parent || parent.id === pageId) return []\n const index = parent.childIds.indexOf(id)\n return [{ id, parentId: parent.id, index, place: pick(node, TRANSFORM_FIELDS) }]\n })\n .sort((a, b) => a.index - b.index)\n if (origins.length === 0) return\n const parentIds = new Set(origins.map((origin) => origin.parentId))\n const prevSelection = new Set(ctx.state.selectedIds)\n const move = () => {\n for (const { id } of origins) ctx.graph.reparentNode(id, pageId)\n for (const parentId of parentIds) ctx.runLayoutForNode(parentId)\n ctx.setSelectedIds(new Set())\n }\n move()\n ctx.undo.push({\n label: 'Move to page',\n forward: move,\n inverse: () => {\n for (const { id, parentId, index, place } of origins) {\n ctx.graph.insertChildAt(id, parentId, index)\n ctx.graph.updateNode(id, place)\n }\n for (const parentId of parentIds) ctx.runLayoutForNode(parentId)\n ctx.setSelectedIds(new Set(prevSelection))\n }\n })\n }\n\n function selectedNodes(): SceneNode[] {\n return [...ctx.state.selectedIds]\n .map((id) => ctx.graph.getNode(id))\n .filter((node): node is SceneNode => node != null)\n }\n\n function previewRenameSelected(options: RenameSelectionOptions) {\n return previewRenamedNodes(selectedNodes(), options)\n }\n\n function renameSelected(options: RenameSelectionOptions) {\n const nodes = selectedNodes()\n if (nodes.length === 0) return\n const before = new Map(nodes.map((node) => [node.id, node.name]))\n const preview = previewRenamedNodes(nodes, options)\n if (preview.error) return\n const applyNames = (names: ReadonlyMap<string, string>) => {\n for (const [id, nextName] of names) ctx.graph.updateNode(id, { name: nextName })\n }\n\n applyNames(preview.names)\n ctx.undo.push({\n label: 'Rename selection',\n forward: () => applyNames(preview.names),\n inverse: () => applyNames(before)\n })\n }\n\n function renameNode(id: string, name: string) {\n const node = ctx.graph.getNode(id)\n if (!node) return\n const previous = { name: node.name, autoRename: node.autoRename }\n const next = name.trim() || defaultNodeName(node.type)\n if (next === previous.name) return\n // A layer named by its text, as a sticky note is, keeps the name it is given, as in FigJam.\n const namedByText = generatedFrameKind(node)?.namedByText ?? false\n const renamed = { name: next, autoRename: namedByText ? false : node.autoRename }\n ctx.graph.updateNode(id, renamed)\n ctx.undo.push({\n label: 'Rename',\n forward: () => ctx.graph.updateNode(id, renamed),\n inverse: () => ctx.graph.updateNode(id, previous)\n })\n }\n\n return {\n isTopLevel,\n acceptsChildren: (parentId: string) => acceptsChildren(ctx, parentId),\n acceptingParent: (parentId: string) => acceptingParent(ctx, parentId),\n fitEnclosingGroups: (parentIds: Iterable<string>) => fitEnclosingGroupsWithUndo(ctx, parentIds),\n ...reorderActions,\n reparentNodes,\n wrapSelectionInContainer,\n wrapInAutoLayout,\n groupSelected,\n frameSelection,\n ...layerTypeActions,\n booleanOperationSelected,\n ungroupSelected,\n flattenSelected,\n outlineTextSelected,\n outlineStrokeSelected,\n ...stateActions,\n moveToPage,\n previewRenameSelected,\n renameSelected,\n renameNode\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,SAAgB,uBAAuB,KAAoB;CACzD,MAAM,iBAAiB,8BAA8B,GAAG;CACxD,MAAM,eAAe,4BAA4B,GAAG;CACpD,MAAM,mBAAmB,uBAAuB,GAAG;CAEnD,SAAS,WAAW,UAAkC;EACpD,OAAO,CAAC,YAAY,aAAa,IAAI,MAAM,UAAU,aAAa,IAAI,MAAM;CAC9E;;;;;CAMA,SAAS,cAAc,SAAmB,aAA8B;EACtE,MAAM,SAAS,IAAI,MAAM,QAAQ,WAAW;EAE5C,MAAM,UAAU,QAAQ,QACrB,QACE,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE,SAAS,aAC/B,CAAC,UACD,OAAO,SAAS,YAChB,OAAO,SAAS,cAClB,CAAC,sBAAsB,IAAI,OAAO,IAAI,WAAW,CACrD;EACA,IAAI,QAAQ,WAAW,GAAG,OAAO;EACjC,MAAM,0BAAU,IAAI,IAAI,CAAC,WAAW,CAAC;EACrC,KAAK,MAAM,MAAM,SAAS;GACxB,MAAM,UAAU,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE;GACvC,IAAI,WAAW,YAAY,aAAa,QAAQ,IAAI,OAAO;EAC7D;EACA,IAAI,CAAC,iBAAiB,KAAK,OAAO,GAAG,OAAO;EAC5C,KAAK,MAAM,MAAM,SAAS,IAAI,MAAM,aAAa,IAAI,WAAW;EAChE,OAAO;CACT;CAEA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a,OAAO,IAAI,MAAM,WAAW,IAAI,EAAE,MAAM,SAAS,CAAC;EACjF;EAEA,WAAW,QAAQ,KAAK;EACxB,IAAI,KAAK,KAAK;GACZ,OAAO;GACP,eAAe,WAAW,QAAQ,KAAK;GACvC,eAAe,WAAW,MAAM;EAClC,CAAC;CACH;CAEA,SAAS,WAAW,IAAY,MAAc;EAC5C,MAAM,OAAO,IAAI,MAAM,QAAQ,EAAE;EACjC,IAAI,CAAC,MAAM;EACX,MAAM,WAAW;GAAE,MAAM,KAAK;GAAM,YAAY,KAAK;EAAW;EAChE,MAAM,OAAO,KAAK,KAAK,KAAK,gBAAgB,KAAK,IAAI;EACrD,IAAI,SAAS,SAAS,MAAM;EAG5B,MAAM,UAAU;GAAE,MAAM;GAAM,YADV,mBAAmB,IAAI,CAAC,EAAE,eAAe,QACL,QAAQ,KAAK;EAAW;EAChF,IAAI,MAAM,WAAW,IAAI,OAAO;EAChC,IAAI,KAAK,KAAK;GACZ,OAAO;GACP,eAAe,IAAI,MAAM,WAAW,IAAI,OAAO;GAC/C,eAAe,IAAI,MAAM,WAAW,IAAI,QAAQ;EAClD,CAAC;CACH;CAEA,OAAO;EACL;EACA,kBAAkB,aAAqB,gBAAgB,KAAK,QAAQ;EACpE,kBAAkB,aAAqB,gBAAgB,KAAK,QAAQ;EACpE,qBAAqB,cAAgC,2BAA2B,KAAK,SAAS;EAC9F,GAAG;EACH;EACA,0BAAA;EACA,kBAAA;EACA;EACA;EACA,GAAG;EACH,0BAAA;EACA,iBAAA;EACA,iBAAA;EACA;EACA,uBAAA;EACA,GAAG;EACH;EACA;EACA;EACA;CACF;AACF"}
@@ -59,7 +59,7 @@ function createViewportActions(ctx) {
59
59
  const w = maxX - minX + 160;
60
60
  const h = maxY - minY + 160;
61
61
  const { width: viewW, height: viewH } = ctx.getViewportSize();
62
- const zoom = Math.min(viewW / w, viewH / h, 1);
62
+ const zoom = Math.max(.02, Math.min(viewW / w, viewH / h, 1));
63
63
  ctx.state.zoom = zoom;
64
64
  ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom;
65
65
  ctx.state.panY = (viewH - h * zoom) / 2 - minY * zoom + padding * zoom;
@@ -122,7 +122,7 @@ function createViewportActions(ctx) {
122
122
  if (ctx.state.selectedIds.size === 0) return;
123
123
  const nodes = [...ctx.state.selectedIds].map((id) => ctx.graph.getNode(id)).filter((n) => n != null);
124
124
  if (nodes.length === 0) return;
125
- const b = computeAbsoluteBounds(nodes, (id) => ctx.graph.getAbsolutePosition(id));
125
+ const b = computeAbsoluteBounds(nodes, ctx.graph);
126
126
  zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height);
127
127
  }
128
128
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"viewport.js","names":[],"sources":["../../src/editor/viewport.ts"],"sourcesContent":["import { getAxisAlignedWorldBounds } from '@pairdraw/scene-graph/coordinate'\nimport { computeBounds, computeAbsoluteBounds } from '@pairdraw/scene-graph/geometry'\n\nimport { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '#core/constants'\nimport { emitNavigationTrace } from '#core/profiler'\n\nimport type { EditorContext } from './types'\n\n/** Space kept between revealed layers and the viewport edge. */\nconst REVEAL_MARGIN = 48\n\nexport function createViewportActions(ctx: EditorContext) {\n function currentViewport() {\n return { panX: ctx.state.panX, panY: ctx.state.panY, zoom: ctx.state.zoom }\n }\n\n function emitViewportChanged(previous: ReturnType<typeof currentViewport>) {\n const next = currentViewport()\n if (next.panX !== previous.panX || next.panY !== previous.panY || next.zoom !== previous.zoom) {\n emitNavigationTrace('viewport:changed', {\n panX: next.panX,\n panY: next.panY,\n zoom: next.zoom,\n previousPanX: previous.panX,\n previousPanY: previous.panY,\n previousZoom: previous.zoom\n })\n ctx.emitEditorEvent('viewport:changed', next, previous)\n }\n }\n\n function screenToCanvas(sx: number, sy: number) {\n return {\n x: (sx - ctx.state.panX) / ctx.state.zoom,\n y: (sy - ctx.state.panY) / ctx.state.zoom\n }\n }\n\n function setZoomAroundPoint(level: number, centerX: number, centerY: number) {\n const previous = currentViewport()\n const newZoom = Math.max(0.02, Math.min(256, level))\n ctx.state.panX = centerX - (centerX - ctx.state.panX) * (newZoom / ctx.state.zoom)\n ctx.state.panY = centerY - (centerY - ctx.state.panY) * (newZoom / ctx.state.zoom)\n ctx.state.zoom = newZoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function applyZoom(delta: number, centerX: number, centerY: number) {\n const factor = Math.min(\n ZOOM_SCALE_MAX,\n Math.max(ZOOM_SCALE_MIN, Math.exp(-delta / ZOOM_DIVISOR))\n )\n setZoomAroundPoint(ctx.state.zoom * factor, centerX, centerY)\n }\n\n function pan(dx: number, dy: number) {\n const previous = currentViewport()\n ctx.state.panX += dx\n ctx.state.panY += dy\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomToBounds(minX: number, minY: number, maxX: number, maxY: number) {\n const previous = currentViewport()\n const padding = 80\n const w = maxX - minX + padding * 2\n const h = maxY - minY + padding * 2\n\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const zoom = Math.min(viewW / w, viewH / h, 1)\n\n ctx.state.zoom = zoom\n ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom\n ctx.state.panY = (viewH - h * zoom) / 2 - minY * zoom + padding * zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n /**\n * Fits the world area to the viewport, edge to edge and at any zoom, as a drag of Figma's zoom\n * tool does; `zoomToBounds` instead leaves a margin and never zooms past 100%. An area with no\n * width or height leaves the view alone.\n */\n function zoomToArea(minX: number, minY: number, maxX: number, maxY: number) {\n const width = maxX - minX\n const height = maxY - minY\n if (!(width > 0) || !(height > 0)) return\n const previous = currentViewport()\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const zoom = Math.max(0.02, Math.min(256, Math.min(viewW / width, viewH / height)))\n ctx.state.zoom = zoom\n ctx.state.panX = viewW / 2 - (minX + width / 2) * zoom\n ctx.state.panY = viewH / 2 - (minY + height / 2) * zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n /** Put the world point (x, y) at the center of the viewport, at `zoom` (the current one by default). */\n function centerOn(x: number, y: number, zoom = ctx.state.zoom) {\n const previous = currentViewport()\n const { width, height } = ctx.getViewportSize()\n const nextZoom = Math.max(0.02, Math.min(256, zoom))\n const panX = width / 2 - x * nextZoom\n const panY = height / 2 - y * nextZoom\n // Remote cursors are finite but unbounded; a point that overflows leaves the view alone.\n if (!Number.isFinite(panX) || !Number.isFinite(panY)) return\n ctx.state.zoom = nextZoom\n ctx.state.panX = panX\n ctx.state.panY = panY\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomToFit() {\n const nodes = ctx.graph.getChildren(ctx.state.currentPageId)\n if (nodes.length === 0) return\n\n const b = computeBounds(nodes)\n zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)\n }\n\n function zoomToLevel(level: number) {\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const centerX = (-ctx.state.panX + viewW / 2) / ctx.state.zoom\n const centerY = (-ctx.state.panY + viewH / 2) / ctx.state.zoom\n\n const previous = currentViewport()\n ctx.state.zoom = Math.max(0.02, Math.min(256, level))\n // Keep the world point at the center of the viewport where it was.\n ctx.state.panX = viewW / 2 - centerX * ctx.state.zoom\n ctx.state.panY = viewH / 2 - centerY * ctx.state.zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomTo100() {\n zoomToLevel(1)\n }\n\n function zoomToSelection() {\n if (ctx.state.selectedIds.size === 0) return\n\n const nodes = [...ctx.state.selectedIds]\n .map((id) => ctx.graph.getNode(id))\n .filter((n): n is NonNullable<typeof n> => n != null)\n if (nodes.length === 0) return\n\n const b = computeAbsoluteBounds(nodes, (id) => ctx.graph.getAbsolutePosition(id))\n zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)\n }\n\n /**\n * Brings layers into view: pans to center them when they fit at the current zoom and are not\n * already visible, and zooms out to fit them only when they do not fit.\n */\n function revealNodes(nodeIds: readonly string[], margin = REVEAL_MARGIN) {\n const nodes = nodeIds.map((id) => ctx.graph.getNode(id)).filter((node) => node !== undefined)\n if (nodes.length === 0) return\n const bounds = computeBounds(nodes.map((node) => getAxisAlignedWorldBounds(node, ctx.graph)))\n const { width, height } = ctx.getViewportSize()\n const { zoom, panX, panY } = ctx.state\n const fits =\n bounds.width * zoom <= width - margin * 2 && bounds.height * zoom <= height - margin * 2\n if (!fits) {\n zoomToBounds(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height)\n return\n }\n const left = bounds.x * zoom + panX\n const top = bounds.y * zoom + panY\n const right = left + bounds.width * zoom\n const bottom = top + bounds.height * zoom\n const visible =\n left >= margin && top >= margin && right <= width - margin && bottom <= height - margin\n if (visible) return\n pan(width / 2 - (left + right) / 2, height / 2 - (top + bottom) / 2)\n }\n\n return {\n revealNodes,\n screenToCanvas,\n setZoomAroundPoint,\n applyZoom,\n pan,\n zoomToBounds,\n zoomToArea,\n centerOn,\n zoomToFit,\n zoomTo100,\n zoomToLevel,\n zoomToSelection\n }\n}\n"],"mappings":";;;;;;AASA,MAAM,gBAAgB;AAEtB,SAAgB,sBAAsB,KAAoB;CACxD,SAAS,kBAAkB;EACzB,OAAO;GAAE,MAAM,IAAI,MAAM;GAAM,MAAM,IAAI,MAAM;GAAM,MAAM,IAAI,MAAM;EAAK;CAC5E;CAEA,SAAS,oBAAoB,UAA8C;EACzE,MAAM,OAAO,gBAAgB;EAC7B,IAAI,KAAK,SAAS,SAAS,QAAQ,KAAK,SAAS,SAAS,QAAQ,KAAK,SAAS,SAAS,MAAM;GAC7F,oBAAoB,oBAAoB;IACtC,MAAM,KAAK;IACX,MAAM,KAAK;IACX,MAAM,KAAK;IACX,cAAc,SAAS;IACvB,cAAc,SAAS;IACvB,cAAc,SAAS;GACzB,CAAC;GACD,IAAI,gBAAgB,oBAAoB,MAAM,QAAQ;EACxD;CACF;CAEA,SAAS,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AAI,KAAK,CAAC,CAAC;EAC5F,MAAM,EAAE,OAAO,WAAW,IAAI,gBAAgB;EAC9C,MAAM,EAAE,MAAM,MAAM,SAAS,IAAI;EAGjC,IAAI,EADF,OAAO,QAAQ,QAAQ,QAAQ,SAAS,KAAK,OAAO,SAAS,QAAQ,SAAS,SAAS,IAC9E;GACT,aAAa,OAAO,GAAG,OAAO,GAAG,OAAO,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,MAAM;GAClF;EACF;EACA,MAAM,OAAO,OAAO,IAAI,OAAO;EAC/B,MAAM,MAAM,OAAO,IAAI,OAAO;EAC9B,MAAM,QAAQ,OAAO,OAAO,QAAQ;EACpC,MAAM,SAAS,MAAM,OAAO,SAAS;EAGrC,IADE,QAAQ,UAAU,OAAO,UAAU,SAAS,QAAQ,UAAU,UAAU,SAAS,QACtE;EACb,IAAI,QAAQ,KAAK,OAAO,SAAS,GAAG,SAAS,KAAK,MAAM,UAAU,CAAC;CACrE;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"viewport.js","names":[],"sources":["../../src/editor/viewport.ts"],"sourcesContent":["import { getAxisAlignedWorldBounds } from '@pairdraw/scene-graph/coordinate'\nimport { computeBounds, computeAbsoluteBounds } from '@pairdraw/scene-graph/geometry'\n\nimport { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '#core/constants'\nimport { emitNavigationTrace } from '#core/profiler'\n\nimport type { EditorContext } from './types'\n\n/** Space kept between revealed layers and the viewport edge. */\nconst REVEAL_MARGIN = 48\n\nexport function createViewportActions(ctx: EditorContext) {\n function currentViewport() {\n return { panX: ctx.state.panX, panY: ctx.state.panY, zoom: ctx.state.zoom }\n }\n\n function emitViewportChanged(previous: ReturnType<typeof currentViewport>) {\n const next = currentViewport()\n if (next.panX !== previous.panX || next.panY !== previous.panY || next.zoom !== previous.zoom) {\n emitNavigationTrace('viewport:changed', {\n panX: next.panX,\n panY: next.panY,\n zoom: next.zoom,\n previousPanX: previous.panX,\n previousPanY: previous.panY,\n previousZoom: previous.zoom\n })\n ctx.emitEditorEvent('viewport:changed', next, previous)\n }\n }\n\n function screenToCanvas(sx: number, sy: number) {\n return {\n x: (sx - ctx.state.panX) / ctx.state.zoom,\n y: (sy - ctx.state.panY) / ctx.state.zoom\n }\n }\n\n function setZoomAroundPoint(level: number, centerX: number, centerY: number) {\n const previous = currentViewport()\n const newZoom = Math.max(0.02, Math.min(256, level))\n ctx.state.panX = centerX - (centerX - ctx.state.panX) * (newZoom / ctx.state.zoom)\n ctx.state.panY = centerY - (centerY - ctx.state.panY) * (newZoom / ctx.state.zoom)\n ctx.state.zoom = newZoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function applyZoom(delta: number, centerX: number, centerY: number) {\n const factor = Math.min(\n ZOOM_SCALE_MAX,\n Math.max(ZOOM_SCALE_MIN, Math.exp(-delta / ZOOM_DIVISOR))\n )\n setZoomAroundPoint(ctx.state.zoom * factor, centerX, centerY)\n }\n\n function pan(dx: number, dy: number) {\n const previous = currentViewport()\n ctx.state.panX += dx\n ctx.state.panY += dy\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomToBounds(minX: number, minY: number, maxX: number, maxY: number) {\n const previous = currentViewport()\n const padding = 80\n const w = maxX - minX + padding * 2\n const h = maxY - minY + padding * 2\n\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const zoom = Math.max(0.02, Math.min(viewW / w, viewH / h, 1))\n\n ctx.state.zoom = zoom\n ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom\n ctx.state.panY = (viewH - h * zoom) / 2 - minY * zoom + padding * zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n /**\n * Fits the world area to the viewport, edge to edge and at any zoom, as a drag of Figma's zoom\n * tool does; `zoomToBounds` instead leaves a margin and never zooms past 100%. An area with no\n * width or height leaves the view alone.\n */\n function zoomToArea(minX: number, minY: number, maxX: number, maxY: number) {\n const width = maxX - minX\n const height = maxY - minY\n if (!(width > 0) || !(height > 0)) return\n const previous = currentViewport()\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const zoom = Math.max(0.02, Math.min(256, Math.min(viewW / width, viewH / height)))\n ctx.state.zoom = zoom\n ctx.state.panX = viewW / 2 - (minX + width / 2) * zoom\n ctx.state.panY = viewH / 2 - (minY + height / 2) * zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n /** Put the world point (x, y) at the center of the viewport, at `zoom` (the current one by default). */\n function centerOn(x: number, y: number, zoom = ctx.state.zoom) {\n const previous = currentViewport()\n const { width, height } = ctx.getViewportSize()\n const nextZoom = Math.max(0.02, Math.min(256, zoom))\n const panX = width / 2 - x * nextZoom\n const panY = height / 2 - y * nextZoom\n // Remote cursors are finite but unbounded; a point that overflows leaves the view alone.\n if (!Number.isFinite(panX) || !Number.isFinite(panY)) return\n ctx.state.zoom = nextZoom\n ctx.state.panX = panX\n ctx.state.panY = panY\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomToFit() {\n const nodes = ctx.graph.getChildren(ctx.state.currentPageId)\n if (nodes.length === 0) return\n\n const b = computeBounds(nodes)\n zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)\n }\n\n function zoomToLevel(level: number) {\n const { width: viewW, height: viewH } = ctx.getViewportSize()\n const centerX = (-ctx.state.panX + viewW / 2) / ctx.state.zoom\n const centerY = (-ctx.state.panY + viewH / 2) / ctx.state.zoom\n\n const previous = currentViewport()\n ctx.state.zoom = Math.max(0.02, Math.min(256, level))\n // Keep the world point at the center of the viewport where it was.\n ctx.state.panX = viewW / 2 - centerX * ctx.state.zoom\n ctx.state.panY = viewH / 2 - centerY * ctx.state.zoom\n ctx.requestRepaint()\n emitViewportChanged(previous)\n }\n\n function zoomTo100() {\n zoomToLevel(1)\n }\n\n function zoomToSelection() {\n if (ctx.state.selectedIds.size === 0) return\n\n const nodes = [...ctx.state.selectedIds]\n .map((id) => ctx.graph.getNode(id))\n .filter((n): n is NonNullable<typeof n> => n != null)\n if (nodes.length === 0) return\n\n const b = computeAbsoluteBounds(nodes, ctx.graph)\n zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)\n }\n\n /**\n * Brings layers into view: pans to center them when they fit at the current zoom and are not\n * already visible, and zooms out to fit them only when they do not fit.\n */\n function revealNodes(nodeIds: readonly string[], margin = REVEAL_MARGIN) {\n const nodes = nodeIds.map((id) => ctx.graph.getNode(id)).filter((node) => node !== undefined)\n if (nodes.length === 0) return\n const bounds = computeBounds(nodes.map((node) => getAxisAlignedWorldBounds(node, ctx.graph)))\n const { width, height } = ctx.getViewportSize()\n const { zoom, panX, panY } = ctx.state\n const fits =\n bounds.width * zoom <= width - margin * 2 && bounds.height * zoom <= height - margin * 2\n if (!fits) {\n zoomToBounds(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height)\n return\n }\n const left = bounds.x * zoom + panX\n const top = bounds.y * zoom + panY\n const right = left + bounds.width * zoom\n const bottom = top + bounds.height * zoom\n const visible =\n left >= margin && top >= margin && right <= width - margin && bottom <= height - margin\n if (visible) return\n pan(width / 2 - (left + right) / 2, height / 2 - (top + bottom) / 2)\n }\n\n return {\n revealNodes,\n screenToCanvas,\n setZoomAroundPoint,\n applyZoom,\n pan,\n zoomToBounds,\n zoomToArea,\n centerOn,\n zoomToFit,\n zoomTo100,\n zoomToLevel,\n zoomToSelection\n }\n}\n"],"mappings":";;;;;;AASA,MAAM,gBAAgB;AAEtB,SAAgB,sBAAsB,KAAoB;CACxD,SAAS,kBAAkB;EACzB,OAAO;GAAE,MAAM,IAAI,MAAM;GAAM,MAAM,IAAI,MAAM;GAAM,MAAM,IAAI,MAAM;EAAK;CAC5E;CAEA,SAAS,oBAAoB,UAA8C;EACzE,MAAM,OAAO,gBAAgB;EAC7B,IAAI,KAAK,SAAS,SAAS,QAAQ,KAAK,SAAS,SAAS,Q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"file":"bindings.d.ts","names":[],"sources":["../../../src/figma-api/text/bindings.ts"],"mappings":";;;;;;;;iBAyCgB,sBACd,OAAO,YACP,uBACA,kBACC;;iBAWa,wBAAwB,gBAAgB,iBAAiB;;;;;;iBA0DzD,oBACd,OAAO,YACP,MAAM,WACN,eACA,aACA,OAAO,mBACP;EACG,WAAW;EAAY;;;iBAgCZ,sBACd,MAAM,WACN,eACA,aACA,OAAO,mBACP,gBACC"}
@@ -1,9 +1,11 @@
1
1
  import { styleRunsWithPatch } from "../../text/character-style.js";
2
2
  import { faceForStyle } from "../../text/font/names.js";
3
3
  import { variableAlias } from "../variables/values.js";
4
+ import { getStyleAt } from "../../text/style-runs.js";
4
5
  import { getStyledTextSegments } from "./style.js";
5
6
  import { copyFills } from "@pairdraw/scene-graph/copy";
6
7
  import { TEXT_BINDABLE_FIELDS } from "@pairdraw/scene-graph";
8
+ import { SCALED_RUN_BINDING_FIELDS, boundNumberValue, variableBindingOwner } from "@pairdraw/scene-graph/variables";
7
9
  import { SHARED_TEXT_STYLE_FIELDS, getSharedStyles } from "@pairdraw/scene-graph/shared-styles";
8
10
  import { mapValues, omit, pick } from "es-toolkit/object";
9
11
  //#region src/figma-api/text/bindings.ts
@@ -47,8 +49,11 @@ function boundVariable(graph, method, field, variable) {
47
49
  if (found.type !== expected) throw new Error(`in ${method}: Cannot bind a ${found.type} variable to "${field}", which takes ${expected}`);
48
50
  return found;
49
51
  }
50
- /** What the characters show for a bound field: the variable's value in their mode. */
51
- function boundValue(graph, node, field, variable) {
52
+ /**
53
+ * What the characters show for a bound field: the variable's value in their mode, a number in
54
+ * the scale the characters' binding keeps.
55
+ */
56
+ function boundValue(graph, node, field, variable, scale) {
52
57
  if (STRING_FIELDS.has(field)) {
53
58
  const value = graph.resolveVariableForNode(node.id, variable.id);
54
59
  if (typeof value !== "string") return {};
@@ -62,7 +67,7 @@ function boundValue(graph, node, field, variable) {
62
67
  }
63
68
  const value = graph.resolveNumberVariableForNode(node.id, variable.id);
64
69
  if (value === void 0 || !Number.isFinite(value) || isParagraphField(field)) return {};
65
- return { [field]: value };
70
+ return { [field]: boundNumberValue(field, value * scale) };
66
71
  }
67
72
  /**
68
73
  * The runs that bind `field` of `text[start, end)` to a variable, or unbind it, showing the
@@ -71,7 +76,8 @@ function boundValue(graph, node, field, variable) {
71
76
  */
72
77
  function rangeBindingChanges(graph, node, start, end, field, variable) {
73
78
  const bound = variable === null ? null : boundVariable(graph, "setRangeBoundVariable", field, variable);
74
- const value = bound ? boundValue(graph, node, field, bound) : {};
79
+ const scaled = SCALED_RUN_BINDING_FIELDS.has(field);
80
+ const scale = scaled ? variableBindingOwner(graph, node).variableAssignmentScales[field] ?? 1 : 1;
75
81
  let styleRuns = node.styleRuns;
76
82
  for (const segment of getStyledTextSegments(node, ["boundVariables"], start, end)) {
77
83
  const aliases = segment.boundVariables ?? {};
@@ -80,13 +86,19 @@ function rangeBindingChanges(graph, node, start, end, field, variable) {
80
86
  ...ids,
81
87
  [field]: bound.id
82
88
  } : omit(ids, [field]);
89
+ const scales = getStyleAt(node.styleRuns, segment.start).variableBindingScales ?? {};
90
+ const patch = bound ? {
91
+ ...boundValue(graph, node, field, bound, scale),
92
+ boundVariables
93
+ } : { boundVariables };
94
+ if (bound && scaled) patch.variableBindingScales = {
95
+ ...scales,
96
+ [field]: scale
97
+ };
83
98
  styleRuns = styleRunsWithPatch({
84
99
  ...node,
85
100
  styleRuns
86
- }, segment.start, segment.end, {
87
- ...value,
88
- boundVariables
89
- });
101
+ }, segment.start, segment.end, patch);
90
102
  }
91
103
  const resolved = bound ? graph.resolveNumberVariableForNode(node.id, bound.id) : void 0;
92
104
  const paragraphValue = isParagraphField(field) && resolved !== void 0 && Number.isFinite(resolved) ? Math.max(0, resolved) : null;
@@ -1 +1 @@
1
- {"version":3,"file":"bindings.js","names":[],"sources":["../../../src/figma-api/text/bindings.ts"],"sourcesContent":["import { mapValues, omit, pick } from 'es-toolkit/object'\n\nimport {\n TEXT_BINDABLE_FIELDS,\n type CharacterStyleOverride,\n type SceneGraph,\n type SceneNode,\n type StyleRun,\n type TextBindableField,\n type Variable\n} from '@pairdraw/scene-graph'\nimport { copyFills } from '@pairdraw/scene-graph/copy'\nimport { getSharedStyles, SHARED_TEXT_STYLE_FIELDS } from '@pairdraw/scene-graph/shared-styles'\n\nimport { variableAlias, type FigmaVariableAlias } from '#core/figma-api/variables/values'\nimport { styleRunsWithPatch } from '#core/text/character-style'\nimport { faceForStyle } from '#core/text/font/names'\n\nimport { getStyledTextSegments } from './style'\n\n/** Fields a string variable binds; the rest take numbers. */\nconst STRING_FIELDS: ReadonlySet<TextBindableField> = new Set(['fontFamily', 'fontStyle'])\nconst PARAGRAPH_FIELDS = new Set(['paragraphSpacing', 'paragraphIndent'] as const)\n\nfunction isParagraphField(\n field: TextBindableField\n): field is 'paragraphSpacing' | 'paragraphIndent' {\n return (PARAGRAPH_FIELDS as ReadonlySet<string>).has(field)\n}\n\n/**\n * The style a text or fill style gives characters that use it, with the reference that keeps\n * them attached. An empty ID detaches them; a style the document does not hold attaches by ID\n * alone, as the text's own setters do.\n */\nexport function rangeSharedStylePatch(\n graph: SceneGraph,\n kind: 'text' | 'fill',\n styleId: string\n): CharacterStyleOverride {\n const key = kind === 'text' ? 'textStyleId' : 'fillStyleId'\n if (!styleId) return { [key]: null }\n const found = getSharedStyles(graph, kind).find((style) => style.id === styleId)\n const style = found ? graph.getNode(found.nodeId) : undefined\n if (!style) return { [key]: styleId }\n if (kind === 'fill') return { fillStyleId: styleId, fills: copyFills(style.fills) }\n return { textStyleId: styleId, ...structuredClone(pick(style, SHARED_TEXT_STYLE_FIELDS)) }\n}\n\n/** Figma's message for a text field it cannot bind. */\nexport function assertTextBindableField(method: string, field: unknown): TextBindableField {\n if (!(TEXT_BINDABLE_FIELDS as readonly unknown[]).includes(field)) {\n throw new Error(\n `in ${method}: Property \"field\" failed validation: Invalid enum value. Expected ` +\n `${TEXT_BINDABLE_FIELDS.map((name) => `'${name}'`).join(' | ')}, received '${String(field)}'`\n )\n }\n return field as TextBindableField\n}\n\n/** The variable a binding takes: one the document holds, of the type the field takes. */\nfunction boundVariable(\n graph: SceneGraph,\n method: string,\n field: TextBindableField,\n variable: unknown\n): Variable {\n const id = (variable as { id?: unknown } | null)?.id\n const found = typeof id === 'string' ? graph.variables.get(id) : undefined\n if (!found) throw new Error(`in ${method}: Variable not found`)\n const expected = STRING_FIELDS.has(field) ? 'STRING' : 'FLOAT'\n if (found.type !== expected) {\n throw new Error(\n `in ${method}: Cannot bind a ${found.type} variable to \"${field}\", which takes ${expected}`\n )\n }\n return found\n}\n\n/** What the characters show for a bound field: the variable's value in their mode. */\nfunction boundValue(\n graph: SceneGraph,\n node: SceneNode,\n field: TextBindableField,\n variable: Variable\n): CharacterStyleOverride {\n if (STRING_FIELDS.has(field)) {\n const value = graph.resolveVariableForNode(node.id, variable.id)\n if (typeof value !== 'string') return {}\n if (field === 'fontFamily') return { fontFamily: value }\n // A style variable names a face of the text's family, as its font names it.\n const face = faceForStyle(node.fontFamily, value)\n return { fontWeight: face.weight, italic: face.italic, fontStyle: face.style }\n }\n const value = graph.resolveNumberVariableForNode(node.id, variable.id)\n if (value === undefined || !Number.isFinite(value) || isParagraphField(field)) return {}\n return { [field]: value }\n}\n\n/**\n * The runs that bind `field` of `text[start, end)` to a variable, or unbind it, showing the\n * variable's value there as Figma does, and the value a bound paragraph spacing or indent gives\n * the range's paragraphs.\n */\nexport function rangeBindingChanges(\n graph: SceneGraph,\n node: SceneNode,\n start: number,\n end: number,\n field: TextBindableField,\n variable: unknown\n): { styleRuns: StyleRun[]; paragraphValue: number | null } {\n const bound =\n variable === null ? null : boundVariable(graph, 'setRangeBoundVariable', field, variable)\n const value = bound ? boundValue(graph, node, field, bound) : {}\n let styleRuns = node.styleRuns\n // Characters bound apart keep their other bindings.\n for (const segment of getStyledTextSegments(node, ['boundVariables'], start, end)) {\n const aliases = (segment.boundVariables ?? {}) as Record<string, FigmaVariableAlias>\n const ids = mapValues(aliases, (alias) => alias.id)\n const boundVariables = bound ? { ...ids, [field]: bound.id } : omit(ids, [field])\n styleRuns = styleRunsWithPatch({ ...node, styleRuns }, segment.start, segment.end, {\n ...value,\n boundVariables\n })\n }\n const resolved = bound ? graph.resolveNumberVariableForNode(node.id, bound.id) : undefined\n const paragraphValue =\n isParagraphField(field) && resolved !== undefined && Number.isFinite(resolved)\n ? Math.max(0, resolved)\n : null\n return { styleRuns, paragraphValue }\n}\n\n/** The variable `field` of every character of the range is bound to, `null`, or `mixed`. */\nexport function getRangeBoundVariable(\n node: SceneNode,\n start: number,\n end: number,\n field: TextBindableField,\n mixed: symbol\n): FigmaVariableAlias | null | symbol {\n const segments = getStyledTextSegments(node, ['boundVariables'], start, end)\n const ids = new Set(\n segments.map(\n (segment) =>\n (segment.boundVariables as Partial<Record<string, FigmaVariableAlias>> | undefined)?.[field]\n ?.id ?? null\n )\n )\n if (ids.size > 1) return mixed\n const [id] = ids\n return id ? variableAlias(id) : null\n}\n"],"mappings":";;;;;;;;;;AAqBA,MAAM,gCAAgD,IAAI,IAAI,CAAC,cAAc,WAAW,CAAC;AACzF,MAAM,mCAAmB,IAAI,IAAI,CAAC,oBAAoB,iBAAiB,CAAU;AAEjF,SAAS,iBACP,OACiD;CACjD,OAAQ,iBAAyC,IAAI,KAAK;AAC5D;;;;;;AAOA,SAAgB,sBACd,OACA,MACA,SACwB;CACxB,MAAM,MAAM,SAAS,SAAS,gBAAgB;CAC9C,IAAI,CAAC,SAAS,OAAO,GAAG,MAAM,KAAK;CACnC,MAAM,QAAQ,gBAAgB,OAAO,IAAI,CAAC,CAAC,MAAM,UAAU,MAAM,OAAO,OAAO;CAC/E,MAAM,QAAQ,QAAQ,MAAM,QAAQ,MAAM,MAAM,IAAI,KAAA;CACpD,IAAI,CAAC,OAAO,OAAO,GAAG,MAAM,QAAQ;CACpC,IAAI,SAAS,QAAQ,OAAO;EAAE,aAAa;EAAS,OAAO,UAAU,MAAM,KAAK;CAAE;CAClF,O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A,SAAgB,oBACd,OACA,MACA,OACA,KACA,OACA,UAC0D;CAC1D,MAAM,QACJ,aAAa,OAAO,OAAO,cAAc,OAAO,yBAAyB,OAAO,QAAQ;CAC1F,MAAM,QAAQ,QAAQ,WAAW,OAAO,MAAM,OAAO,KAAK,IAAI,CAAC;CAC/D,IAAI,YAAY,KAAK;CAErB,KAAK,MAAM,WAAW,sBAAsB,MAAM,CAAC,gBAAgB,GAAG,OAAO,GAAG,GAAG;EACjF,MAAM,UAAW,QAAQ,kBAAkB,CAAC;EAC5C,MAAM,MAAM,UAAU,UAAU,UAAU,MAAM,EAAE;EAClD,MAAM,iBAAiB,QAAQ;GAAE,GAAG;IAAM,QAAQ,MAAM;EAAG,IAAI,KAAK,KAAK,CAAC,KAAK,CAAC;EAChF,YAAY,mBAAmB;GAAE,GAAG;GAAM;EAAU,GAAG,QAAQ,OAAO,QAAQ,KAAK;GACjF,GAAG;GACH;EACF,CAAC;CACH;CACA,MAAM,WAAW,QAAQ,MAAM,6BAA6B,KAAK,IAAI,MAAM,EAAE,IAAI,KAAA;CACjF,MAAM,iBACJ,iBAAiB,KAAK,KAAK,aAAa,KAAA,KAAa,OAAO,SAAS,QAAQ,IACzE,KAAK,IAAI,GAAG,QAAQ,IACpB;CACN,OAAO;EAAE;EAAW;CAAe;AACrC;;AAGA,SAAgB,sBACd,MACA,OACA,KACA,OACA,OACoC;CACpC,MAAM,WAAW,sBAAsB,MAAM,CAAC,gBAAgB,GAAG,OAAO,GAAG;CAC3E,MAAM,MAAM,IAAI,IACd,SAAS,KACN,YACE,QAAQ,iBAA6E,MAAM,EACxF,MAAM,IACd,CACF;CACA,IAAI,IAAI,OAAO,GAAG,OAAO;CACzB,MAAM,CAAC,MAAM;CACb,OAAO,KAAK,cAAc,EAAE,IAAI;AAClC"}
1
+ {"version":3,"file":"bindings.js","names":[],"sources":["../../../src/figma-api/text/bindings.ts"],"sourcesContent":["import { mapValues, omit, pick } from 'es-toolkit/object'\n\nimport {\n TEXT_BINDABLE_FIELDS,\n type CharacterStyleOverride,\n type SceneGraph,\n type SceneNode,\n type StyleRun,\n type TextBindableField,\n type Variable\n} from '@pairdraw/scene-graph'\nimport { copyFills } from '@pairdraw/scene-graph/copy'\nimport { getSharedStyles, SHARED_TEXT_STYLE_FIELDS } from '@pairdraw/scene-graph/shared-styles'\nimport {\n boundNumberValue,\n SCALED_RUN_BINDING_FIELDS,\n variableBindingOwner\n} from '@pairdraw/scene-graph/variables'\n\nimport { variableAlias, type FigmaVariableAlias } from '#core/figma-api/variables/values'\nimport { styleRunsWithPatch } from '#core/text/character-style'\nimport { faceForStyle } from '#core/text/font/names'\nimport { getStyleAt } from '#core/text/style-runs'\n\nimport { getStyledTextSegments } from './style'\n\n/** Fields a string variable binds; the rest take numbers. */\nconst STRING_FIELDS: ReadonlySet<TextBindableField> = new Set(['fontFamily', 'fontStyle'])\nconst PARAGRAPH_FIELDS = new Set(['paragraphSpacing', 'paragraphIndent'] as const)\n\nfunction isParagraphField(\n field: TextBindableField\n): field is 'paragraphSpacing' | 'paragraphIndent' {\n return (PARAGRAPH_FIELDS as ReadonlySet<string>).has(field)\n}\n\n/**\n * The style a text or fill style gives characters that use it, with the reference that keeps\n * them attached. An empty ID detaches them; a style the document does not hold attaches by ID\n * alone, as the text's own setters do.\n */\nexport function rangeSharedStylePatch(\n graph: SceneGraph,\n kind: 'text' | 'fill',\n styleId: string\n): CharacterStyleOverride {\n const key = kind === 'text' ? 'textStyleId' : 'fillStyleId'\n if (!styleId) return { [key]: null }\n const found = getSharedStyles(graph, kind).find((style) => style.id === styleId)\n const style = found ? graph.getNode(found.nodeId) : undefined\n if (!style) return { [key]: styleId }\n if (kind === 'fill') return { fillStyleId: styleId, fills: copyFills(style.fills) }\n return { textStyleId: styleId, ...structuredClone(pick(style, SHARED_TEXT_STYLE_FIELDS)) }\n}\n\n/** Figma's message for a text field it cannot bind. */\nexport function assertTextBindableField(method: string, field: unknown): TextBindableField {\n if (!(TEXT_BINDABLE_FIELDS as readonly unknown[]).includes(field)) {\n throw new Error(\n `in ${method}: Property \"field\" failed validation: Invalid enum value. Expected ` +\n `${TEXT_BINDABLE_FIELDS.map((name) => `'${name}'`).join(' | ')}, received '${String(field)}'`\n )\n }\n return field as TextBindableField\n}\n\n/** The variable a binding takes: one the document holds, of the type the field takes. */\nfunction boundVariable(\n graph: SceneGraph,\n method: string,\n field: TextBindableField,\n variable: unknown\n): Variable {\n const id = (variable as { id?: unknown } | null)?.id\n const found = typeof id === 'string' ? graph.variables.get(id) : undefined\n if (!found) throw new Error(`in ${method}: Variable not found`)\n const expected = STRING_FIELDS.has(field) ? 'STRING' : 'FLOAT'\n if (found.type !== expected) {\n throw new Error(\n `in ${method}: Cannot bind a ${found.type} variable to \"${field}\", which takes ${expected}`\n )\n }\n return found\n}\n\n/**\n * What the characters show for a bound field: the variable's value in their mode, a number in\n * the scale the characters' binding keeps.\n */\nfunction boundValue(\n graph: SceneGraph,\n node: SceneNode,\n field: TextBindableField,\n variable: Variable,\n scale: number\n): CharacterStyleOverride {\n if (STRING_FIELDS.has(field)) {\n const value = graph.resolveVariableForNode(node.id, variable.id)\n if (typeof value !== 'string') return {}\n if (field === 'fontFamily') return { fontFamily: value }\n // A style variable names a face of the text's family, as its font names it.\n const face = faceForStyle(node.fontFamily, value)\n return { fontWeight: face.weight, italic: face.italic, fontStyle: face.style }\n }\n const value = graph.resolveNumberVariableForNode(node.id, variable.id)\n if (value === undefined || !Number.isFinite(value) || isParagraphField(field)) return {}\n return { [field]: boundNumberValue(field, value * scale) }\n}\n\n/**\n * The runs that bind `field` of `text[start, end)` to a variable, or unbind it, showing the\n * variable's value there as Figma does, and the value a bound paragraph spacing or indent gives\n * the range's paragraphs.\n */\nexport function rangeBindingChanges(\n graph: SceneGraph,\n node: SceneNode,\n start: number,\n end: number,\n field: TextBindableField,\n variable: unknown\n): { styleRuns: StyleRun[]; paragraphValue: number | null } {\n const bound =\n variable === null ? null : boundVariable(graph, 'setRangeBoundVariable', field, variable)\n // A new binding starts at the variable's number in the scope that declares it, as a layer's does\n // (`assignVariableBindingUnits`), not at a scale a rescale left on the characters' old binding.\n const scaled = SCALED_RUN_BINDING_FIELDS.has(field)\n const scale = scaled\n ? (variableBindingOwner(graph, node).variableAssignmentScales[field] ?? 1)\n : 1\n let styleRuns = node.styleRuns\n // Characters bound apart keep their other bindings.\n for (const segment of getStyledTextSegments(node, ['boundVariables'], start, end)) {\n const aliases = (segment.boundVariables ?? {}) as Record<string, FigmaVariableAlias>\n const ids = mapValues(aliases, (alias) => alias.id)\n const boundVariables = bound ? { ...ids, [field]: bound.id } : omit(ids, [field])\n const scales = getStyleAt(node.styleRuns, segment.start).variableBindingScales ?? {}\n const patch: CharacterStyleOverride = bound\n ? { ...boundValue(graph, node, field, bound, scale), boundVariables }\n : { boundVariables }\n // An unbound range's scale goes with its binding (`withBoundBindingScales`).\n if (bound && scaled) patch.variableBindingScales = { ...scales, [field]: scale }\n styleRuns = styleRunsWithPatch({ ...node, styleRuns }, segment.start, segment.end, patch)\n }\n const resolved = bound ? graph.resolveNumberVariableForNode(node.id, bound.id) : undefined\n const paragraphValue =\n isParagraphField(field) && resolved !== undefined && Number.isFinite(resolved)\n ? Math.max(0, resolved)\n : null\n return { styleRuns, paragraphValue }\n}\n\n/** The variable `field` of every character of the range is bound to, `null`, or `mixed`. */\nexport function getRangeBoundVariable(\n node: SceneNode,\n start: number,\n end: number,\n field: TextBindableField,\n mixed: symbol\n): FigmaVariableAlias | null | symbol {\n const segments = getStyledTextSegments(node, ['boundVariables'], start, end)\n const ids = new Set(\n segments.map(\n (segment) =>\n (segment.boundVariables as Partial<Record<string, FigmaVariableAlias>> | undefined)?.[field]\n ?.id ?? null\n )\n )\n if (ids.size > 1) return mixed\n const [id] = ids\n return id ? variableAlias(id) : null\n}\n"],"mappings":";;;;;;;;;;;;AA2BA,MAAM,gCAAgD,IAAI,IAAI,CAAC,cAAc,WAAW,CAAC;AACzF,MAAM,mCAAmB,IAAI,IAAI,CAA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EAAE,eAAe;EAErB,IAAI,SAAS,QAAQ,MAAM,wBAAwB;GAAE,GAAG;IAAS,QAAQ;EAAM;EAC/E,YAAY,mBAAmB;GAAE,GAAG;GAAM;EAAU,GAAG,QAAQ,OAAO,QAAQ,KAAK,KAAK;CAC1F;CACA,MAAM,WAAW,QAAQ,MAAM,6BAA6B,KAAK,IAAI,MAAM,EAAE,IAAI,KAAA;CACjF,MAAM,iBACJ,iBAAiB,KAAK,KAAK,aAAa,KAAA,KAAa,OAAO,SAAS,QAAQ,IACzE,KAAK,IAAI,GAAG,QAAQ,IACpB;CACN,OAAO;EAAE;EAAW;CAAe;AACrC;;AAGA,SAAgB,sBACd,MACA,OACA,KACA,OACA,OACoC;CACpC,MAAM,WAAW,sBAAsB,MAAM,CAAC,gBAAgB,GAAG,OAAO,GAAG;CAC3E,MAAM,MAAM,IAAI,IACd,SAAS,KACN,YACE,QAAQ,iBAA6E,MAAM,EACxF,MAAM,IACd,CACF;CACA,IAAI,IAAI,OAAO,GAAG,OAAO;CACzB,MAAM,CAAC,MAAM;CACb,OAAO,KAAK,cAAc,EAAE,IAAI;AAClC"}
@@ -1,7 +1,7 @@
1
+ import { adjustRunsForDelete, getStyleAt, insertRunsWithStyle } from "../../text/style-runs.js";
1
2
  import { invalid, received } from "../accessors/text/messages.js";
2
3
  import { assertTextRange } from "./style.js";
3
4
  import { assertTextFontsLoaded } from "../fonts/loaded.js";
4
- import { adjustRunsForDelete, getStyleAt, insertRunsWithStyle } from "../../text/style-runs.js";
5
5
  import { MAX_LIST_INDENTATION, paragraphIndexAt, paragraphStyleAt, paragraphStylesAfterEdit, paragraphStylesInRange, pixelLength, sharedParagraphSpacing, textParagraphRanges, trimParagraphStyles, withIndentation, withListType, withParagraphSpacing } from "@pairdraw/scene-graph/text";
6
6
  import { compact } from "es-toolkit/array";
7
7
  import { recordInstanceOverride } from "@pairdraw/scene-graph/instances";
@@ -43,7 +43,7 @@ interface TokenImportResult {
43
43
  declare function applyTokenImport(target: TokenImportTarget, plan: TokenImportPlan): TokenImportResult;
44
44
  /** A style node: hidden from the layer list, found by its style id, as `.fig` styles are. */
45
45
  declare function styleNodeProps(style: PlannedStyle, fields: Partial<SceneNode>): Partial<SceneNode>;
46
- declare function styleNodeType(style: PlannedStyle): "TEXT" | "RECTANGLE";
46
+ declare function styleNodeType(style: PlannedStyle): "RECTANGLE" | "TEXT";
47
47
  /**
48
48
  * Imports straight into a graph, for scripts, tools, and the CLI working on a document without
49
49
  * an editor; the layers bound to variables whose values changed are resolved and laid out
@@ -1 +1 @@
1
- {"version":3,"file":"formats.d.ts","names":[],"sources":["../../src/io/formats.ts"],"mappings":";;;;;cAiKa,qBAAqB,SAAS,OAAO;cAKrC,WAAW;cA8DX,cAAc;cA2Dd,eAAe;cAsCf,WAAS;cACT,WAAS;cACT,YAAU;cAEV,WAAW;cA4DX,WAAW;cAqCX,YAAY;cA2BZ,WAAW;cA+BX,YAAY;cA8BZ,mBAAmB;cA4BnB,8BAAkB,wBAAA,wBAAA,2BAAA,4BAAA,wBAAA,wBAAA,yBAAA,wBAAA,wBAAA,yBAAA,wBAAA,iCAAA;KAgBnB,4BAA4B"}
1
+ {"version":3,"file":"formats.d.ts","names":[],"sources":["../../src/io/formats.ts"],"mappings":";;;;;cAiKa,qBAAqB,SAAS,OAAO;cAKrC,WAAW;cA8DX,cAAc;cA2Dd,eAAe;cAsCf,WAAS;cACT,WAAS;cACT,YAAU;cAEV,WAAW;cA4DX,WAAW;cAqCX,YAAY;cA2BZ,WAAW;cA2BX,YAAY;cA8BZ,mBAAmB;cA4BnB,8BAAkB,wBAAA,wBAAA,2BAAA,4BAAA,wBAAA,wBAAA,yBAAA,wBAAA,wBAAA,yBAAA,wBAAA,iCAAA;KAgBnB,4BAA4B"}
@@ -389,16 +389,14 @@ const jsxFormat = {
389
389
  category: "code",
390
390
  extensions: ["jsx"],
391
391
  mimeTypes: ["text/plain", "text/jsx"],
392
- support: {
393
- exportSelection: true,
394
- exportNode: true
395
- },
392
+ support: EXPORT_EVERY_TARGET,
396
393
  exportOptions: FIXED_SIZE_EXPORT,
397
394
  async exportContent(request) {
398
395
  const nodeId = ensureSingleNode(request.target);
396
+ const target = nodeId ? null : resolveExportNodes(request);
399
397
  let data = "";
400
398
  if (nodeId) data = sceneNodeToJSX(nodeId, request.graph);
401
- else if (request.target.scope === "selection") data = selectionToJSX(request.target.nodeIds, request.graph);
399
+ else if (target) data = selectionToJSX(target.nodeIds, request.graph);
402
400
  if (!data) throw new Error("Nothing to export");
403
401
  return {
404
402
  format: "jsx",
@@ -1 +1 @@
1
- {"version":3,"file":"formats.js","names":[],"sources":["../../src/io/formats.ts"],"sourcesContent":["import { filename } from 'pathe/utils'\n\nimport { sceneNodeToJSX, selectionToJSX } from '@pairdraw/design-jsx'\nimport { isDrawIOExportFileName } from '@pairdraw/drawio'\nimport type { DocumentKind, SceneGraph } from '@pairdraw/scene-graph'\n\nimport { layoutAuthoredNodes } from '#core/layout'\n\nimport type { DrawIOExportTarget } from './formats/drawio/export'\nimport { exportFigFile, parseFigFile } from './formats/fig'\nimport type { PDFPageSpec } from './formats/pdf/plan'\nimport { penFormat } from './formats/pen'\nimport type { PPTXExportOptions } from './formats/pptx'\nimport { headlessRenderNodes, renderNodesToImage, type RasterExportFormat } from './formats/raster'\nimport { extractExportGraph, findPageId } from './subgraph'\nimport type {\n ExportRequest,\n ExportResult,\n FigWriteOptions,\n HTMLExportOptions,\n IOContext,\n IOFormatAdapter,\n IOFormatExportOptions,\n IOFormatSupport,\n PDFFormatExportOptions,\n RasterExportOptions,\n SVGExportOptions\n} from './types'\n\n/** Formats that export a document, page, selection, or single node alike. */\nconst EXPORT_EVERY_TARGET: IOFormatSupport = {\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n}\n\n/** Formats with a size of their own, so no export scale or quality. */\nconst FIXED_SIZE_EXPORT: IOFormatExportOptions = { scale: false, quality: false }\n\nfunction lowerExt(name: string): string {\n const match = /\\.([^.]+)$/.exec(name.toLowerCase())\n return match?.[1] ?? ''\n}\n\nfunction ensureSingleNode(target: ExportRequest['target']): string | null {\n if (target.scope === 'node') return target.nodeId\n if (target.scope === 'selection' && target.nodeIds.length === 1) return target.nodeIds[0]\n return null\n}\n\nfunction resolveExportNodes(request: ExportRequest): { pageId: string; nodeIds: string[] } | null {\n switch (request.target.scope) {\n case 'document': {\n const page = request.graph.getPages()[0]\n return { pageId: page.id, nodeIds: page.childIds }\n }\n case 'page': {\n const page = request.graph.getNode(request.target.pageId)\n if (!page) return null\n return { pageId: page.id, nodeIds: page.childIds }\n }\n case 'selection': {\n const first = request.target.nodeIds[0]\n if (!first) return null\n const pageId = findPageId(request.graph, first)\n if (!pageId) return null\n if (!request.target.nodeIds.every((nodeId) => findPageId(request.graph, nodeId) === pageId)) {\n throw new Error('Export selection must stay on a single page')\n }\n return { pageId, nodeIds: request.target.nodeIds }\n }\n case 'node':\n return resolveExportNodes({\n ...request,\n target: { scope: 'selection', nodeIds: [request.target.nodeId] }\n })\n default:\n return null\n }\n}\n\nasync function renderRaster(\n request: ExportRequest,\n options: RasterExportOptions,\n context?: IOContext\n): Promise<Uint8Array | null> {\n const target = resolveExportNodes(request)\n if (!target) return null\n const scale = options.scale ?? 1\n\n if (context?.canvasKit && context.renderer) {\n return renderNodesToImage(\n context.canvasKit,\n context.renderer,\n request.graph,\n target.pageId,\n target.nodeIds,\n {\n scale,\n format: options.format,\n quality: options.quality,\n trimTransparent: request.target.scope === 'page' || request.target.scope === 'document'\n }\n )\n }\n\n return headlessRenderNodes(request.graph, target.pageId, target.nodeIds, {\n scale,\n format: options.format,\n quality: options.quality,\n trimTransparent: request.target.scope === 'page' || request.target.scope === 'document'\n })\n}\n\nfunction rasterFormat<F extends RasterExportFormat>(format: F): IOFormatAdapter<Lowercase<F>> {\n const extension = format.toLowerCase() as Lowercase<F>\n let mimeType = 'image/png'\n if (format === 'JPG') mimeType = 'image/jpeg'\n else if (format === 'WEBP') mimeType = 'image/webp'\n\n return {\n id: extension,\n label: format,\n role: 'derived-export',\n category: 'raster',\n extensions: [extension],\n mimeTypes: [mimeType],\n support: {\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: {\n scale: true,\n quality: format !== 'PNG',\n colorSpace: false\n },\n async exportContent(request, options?: RasterExportOptions, context?: IOContext) {\n const data = await renderRaster(\n request,\n {\n format,\n scale: options?.scale,\n quality: options?.quality\n },\n context\n )\n if (!data) throw new Error('Nothing to export')\n return {\n format: extension,\n mimeType,\n extension,\n data\n }\n }\n }\n}\n\n/** The file a document saves as: Figma's `.fig` for a design, FigJam's `.jam` for a board. */\nexport const DOCUMENT_EXTENSIONS: Readonly<Record<DocumentKind, 'fig' | 'jam'>> = {\n design: 'fig',\n board: 'jam'\n}\n\nexport const figFormat: IOFormatAdapter<'fig'> = {\n id: 'fig',\n label: 'Pairdraw Document',\n role: 'native-document',\n category: 'document',\n extensions: ['fig', 'jam'],\n mimeTypes: ['application/octet-stream'],\n support: {\n readDocument: true,\n writeDocument: true,\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: FIXED_SIZE_EXPORT,\n matchesFile(fileName) {\n const ext = lowerExt(fileName)\n return ext === 'fig' || ext === 'jam'\n },\n async readDocument(input) {\n const data = input.data.slice().buffer\n const graph = await parseFigFile(data, { populate: 'first-page' })\n return { graph, sourceFormat: 'fig' }\n },\n async writeDocument(graph, options?: FigWriteOptions, context?: IOContext) {\n return writeFig(graph, options, context, options?.thumbnailPageId)\n },\n async exportContent(request, options?: FigWriteOptions, context?: IOContext) {\n // A whole document is written as it is, so one opened from an archive keeps that archive.\n if (request.target.scope === 'document')\n return writeFig(request.graph, options, context, options?.thumbnailPageId, request.fileName)\n const extracted = extractExportGraph(request.graph, request.target)\n return writeFig(\n extracted.graph,\n options,\n context,\n options?.thumbnailPageId ?? extracted.pageId ?? undefined,\n request.fileName\n )\n }\n}\n\n/** A `.fig` named as asked, or else after the file it is written to, or else Untitled. */\nasync function writeFig(\n graph: SceneGraph,\n options: FigWriteOptions | undefined,\n context: IOContext | undefined,\n pageId: string | undefined,\n fileName?: string\n): Promise<ExportResult> {\n const data = await exportFigFile(graph, {\n ck: context?.canvasKit,\n renderer: context?.renderer,\n pageId,\n renderHeadlessThumbnail: options?.renderThumbnail ?? false,\n documentName: options?.documentName ?? (fileName && filename(fileName))\n })\n const extension = DOCUMENT_EXTENSIONS[graph.documentKind]\n return { format: 'fig', mimeType: 'application/octet-stream', extension, data }\n}\n\nexport const drawioFormat: IOFormatAdapter<'drawio'> = {\n id: 'drawio',\n label: 'draw.io Diagram',\n role: 'interchange-document',\n category: 'document',\n extensions: ['drawio', 'dio'],\n mimeTypes: ['application/vnd.jgraph.mxfile'],\n support: {\n readDocument: true,\n writeDocument: true,\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: FIXED_SIZE_EXPORT,\n laysOutOnRead: true,\n // A draw.io PNG or SVG export opens as its diagram when its name says it is one.\n matchesFile(fileName, mimeType) {\n const ext = lowerExt(fileName)\n return (\n ext === 'drawio' ||\n ext === 'dio' ||\n isDrawIOExportFileName(fileName) ||\n mimeType === 'application/vnd.jgraph.mxfile'\n )\n },\n async readDocument(input) {\n const { readDrawIOBytes } = await import('@pairdraw/drawio')\n const { drawioToSceneGraph } = await import('./formats/drawio')\n const file = readDrawIOBytes(input.data)\n if (!file) throw new Error('This file holds no draw.io diagram')\n if (file.unreadable.length > 0) {\n throw new Error(`Could not read the draw.io pages ${file.unreadable.join(', ')}`)\n }\n const graph = drawioToSceneGraph(file)\n // draw.io stores label text, not the sizes it lays out to.\n layoutAuthoredNodes(\n graph,\n graph.getPages().map((page) => page.id)\n )\n return { graph, sourceFormat: 'drawio' }\n },\n async writeDocument(graph) {\n const pageIds = graph.getPages().map((page) => page.id)\n return writeDrawIO(graph, { pageIds })\n },\n // A page or a selection goes as a one-page diagram; the document, every page.\n async exportContent(request) {\n if (request.target.scope === 'document') {\n const pageIds = request.graph.getPages().map((page) => page.id)\n return writeDrawIO(request.graph, { pageIds })\n }\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n return writeDrawIO(request.graph, target)\n }\n}\n\nexport const mermaidFormat: IOFormatAdapter<'mermaid'> = {\n id: 'mermaid',\n label: 'Mermaid Diagram',\n role: 'interchange-document',\n category: 'document',\n extensions: ['mmd', 'mermaid'],\n mimeTypes: ['text/vnd.mermaid'],\n support: {\n readDocument: true\n },\n laysOutOnRead: true,\n matchesFile(fileName, mimeType) {\n const ext = lowerExt(fileName)\n return ext === 'mmd' || ext === 'mermaid' || mimeType === 'text/vnd.mermaid'\n },\n async readDocument(input) {\n const { detectMermaidDiagram } = await import('@pairdraw/mermaid')\n const text = new TextDecoder().decode(input.data)\n if (!detectMermaidDiagram(text)) throw new Error('This file holds no Mermaid flowchart')\n // Mermaid stores a diagram's structure, which reading lays out with its text measured.\n const { mermaidToSceneGraph } = await import('./formats/mermaid')\n return { graph: await mermaidToSceneGraph(text), sourceFormat: 'mermaid' }\n }\n}\n\n/** Pages or layers as a draw.io file, loading the writer only when one is saved. */\nasync function writeDrawIO(graph: SceneGraph, target: DrawIOExportTarget): Promise<ExportResult> {\n const { writeDrawIOFile } = await import('@pairdraw/drawio')\n const { sceneGraphToDrawIO } = await import('./formats/drawio')\n return {\n format: 'drawio',\n mimeType: 'application/vnd.jgraph.mxfile',\n extension: 'drawio',\n data: writeDrawIOFile(sceneGraphToDrawIO(graph, target)),\n encoding: 'utf8'\n }\n}\n\nexport const pngFormat = rasterFormat('PNG')\nexport const jpgFormat = rasterFormat('JPG')\nexport const webpFormat = rasterFormat('WEBP')\n\nexport const svgFormat: IOFormatAdapter<'svg'> = {\n id: 'svg',\n label: 'SVG',\n role: 'derived-export',\n category: 'vector',\n extensions: ['svg'],\n mimeTypes: ['image/svg+xml'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: { ...FIXED_SIZE_EXPORT, colorSpace: true },\n async exportContent(request, options?: SVGExportOptions) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToLaidOutSVG } = await import('./formats/svg/text/layout')\n const data = await renderNodesToLaidOutSVG(\n request.graph,\n target.pageId,\n target.nodeIds,\n options\n )\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'svg',\n mimeType: 'image/svg+xml',\n extension: 'svg',\n data,\n encoding: 'utf8'\n }\n }\n}\n\n/**\n * The PDF pages an export makes. A selection gets a page per layer in the order it lists them,\n * each sized to its layer, as slides and Figma's frame export do, unless `single` asks for one\n * page; a page or a document is one page of its layers unless `frames` asks for a page each.\n */\nasync function pdfPageSpecs(\n request: ExportRequest,\n options: PDFFormatExportOptions | undefined\n): Promise<PDFPageSpec[]> {\n const frames = options?.pages ? options.pages === 'frames' : request.target.scope === 'selection'\n if (frames) {\n const { target } = request\n let ids: string[] | undefined\n if (target.scope === 'selection') ids = target.nodeIds\n else if (target.scope === 'node') ids = [target.nodeId]\n const first = ids?.[0]\n let currentPageId: string | null | undefined\n if (first) currentPageId = findPageId(request.graph, first)\n else if (target.scope === 'page') currentPageId = target.pageId\n else if (target.scope === 'document') currentPageId = request.graph.getPages()[0]?.id\n if (!currentPageId) throw new Error('Nothing to export')\n // Without IDs, the plan takes the page's visible layers, in layer order.\n const { planPDFPages } = await import('./formats/pdf/plan')\n return planPDFPages(request.graph, { mode: 'frames', ids, currentPageId })\n }\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n return [target]\n}\n\nexport const pdfFormat: IOFormatAdapter<'pdf'> = {\n id: 'pdf',\n label: 'PDF',\n role: 'derived-export',\n category: 'vector',\n extensions: ['pdf'],\n mimeTypes: ['application/pdf'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: PDFFormatExportOptions) {\n const specs = await pdfPageSpecs(request, options)\n // Embedded, as Figma embeds every face its PDFs draw.\n const { exportPDFDocument } = await import('./formats/pdf/document')\n const data = (await exportPDFDocument(request.graph, specs, { embedFonts: true }))?.data\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'pdf',\n mimeType: 'application/pdf',\n extension: 'pdf',\n data\n }\n }\n}\n\n/**\n * Every top-level frame becomes a slide, so a PPTX document export spans all\n * pages — the shared resolver only reaches the first one.\n */\nfunction resolvePPTXExportNodes(\n request: ExportRequest\n): { pageId: string; nodeIds: string[] } | null {\n if (request.target.scope !== 'document') return resolveExportNodes(request)\n const pages = request.graph.getPages()\n if (!pages.length) return null\n return { pageId: pages[0].id, nodeIds: pages.flatMap((page) => page.childIds) }\n}\n\nexport const pptxFormat: IOFormatAdapter<'pptx'> = {\n id: 'pptx',\n label: 'PowerPoint',\n role: 'derived-export',\n category: 'print',\n extensions: ['pptx'],\n mimeTypes: ['application/vnd.openxmlformats-officedocument.presentationml.presentation'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: PPTXExportOptions, context?: IOContext) {\n const target = resolvePPTXExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToPPTX } = await import('./formats/pptx')\n const data = await renderNodesToPPTX(request.graph, target.pageId, target.nodeIds, {\n ...options,\n context: options?.context ?? context\n })\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'pptx',\n mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n extension: 'pptx',\n data\n }\n }\n}\n\nexport const jsxFormat: IOFormatAdapter<'jsx'> = {\n id: 'jsx',\n label: 'JSX',\n role: 'derived-export',\n category: 'code',\n extensions: ['jsx'],\n mimeTypes: ['text/plain', 'text/jsx'],\n support: {\n exportSelection: true,\n exportNode: true\n },\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request): Promise<ExportResult> {\n const nodeId = ensureSingleNode(request.target)\n let data = ''\n if (nodeId) {\n data = sceneNodeToJSX(nodeId, request.graph)\n } else if (request.target.scope === 'selection') {\n data = selectionToJSX(request.target.nodeIds, request.graph)\n }\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'jsx',\n mimeType: 'text/plain',\n extension: 'jsx',\n data,\n encoding: 'utf8'\n }\n }\n}\n\nexport const htmlFormat: IOFormatAdapter<'html'> = {\n id: 'html',\n label: 'HTML',\n role: 'derived-export',\n category: 'code',\n extensions: ['html'],\n mimeTypes: ['text/html'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: HTMLExportOptions) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToHTML } = await import('./formats/html')\n const { html, assets } = await renderNodesToHTML(\n request.graph,\n target.nodeIds,\n options,\n request.fileName\n )\n return {\n format: 'html',\n mimeType: 'text/html',\n extension: 'html',\n data: html,\n encoding: 'utf8',\n assets\n }\n }\n}\n\nexport const tailwindJSXFormat: IOFormatAdapter<'tailwind-jsx'> = {\n id: 'tailwind-jsx',\n label: 'Tailwind JSX',\n role: 'derived-export',\n category: 'code',\n extensions: ['jsx'],\n mimeTypes: ['text/plain', 'text/jsx'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { sceneNodesToTailwindJSX } = await import('@pairdraw/dom-css/export')\n const { vectorElement } = await import('#core/io/formats/html/vectors')\n const data = sceneNodesToTailwindJSX(request.graph, target.nodeIds, { vectorElement })\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'tailwind-jsx',\n mimeType: 'text/plain',\n extension: 'jsx',\n data,\n encoding: 'utf8'\n }\n }\n}\n\nexport { penFormat }\n\nexport const BUILTIN_IO_FORMATS = [\n figFormat,\n penFormat,\n drawioFormat,\n mermaidFormat,\n pngFormat,\n jpgFormat,\n webpFormat,\n svgFormat,\n pdfFormat,\n pptxFormat,\n jsxFormat,\n tailwindJSXFormat,\n htmlFormat\n] as const satisfies readonly IOFormatAdapter[]\n\nexport type BuiltinIOFormatId = (typeof B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A;AACF"}
1
+ {"version":3,"file":"formats.js","names":[],"sources":["../../src/io/formats.ts"],"sourcesContent":["import { filename } from 'pathe/utils'\n\nimport { sceneNodeToJSX, selectionToJSX } from '@pairdraw/design-jsx'\nimport { isDrawIOExportFileName } from '@pairdraw/drawio'\nimport type { DocumentKind, SceneGraph } from '@pairdraw/scene-graph'\n\nimport { layoutAuthoredNodes } from '#core/layout'\n\nimport type { DrawIOExportTarget } from './formats/drawio/export'\nimport { exportFigFile, parseFigFile } from './formats/fig'\nimport type { PDFPageSpec } from './formats/pdf/plan'\nimport { penFormat } from './formats/pen'\nimport type { PPTXExportOptions } from './formats/pptx'\nimport { headlessRenderNodes, renderNodesToImage, type RasterExportFormat } from './formats/raster'\nimport { extractExportGraph, findPageId } from './subgraph'\nimport type {\n ExportRequest,\n ExportResult,\n FigWriteOptions,\n HTMLExportOptions,\n IOContext,\n IOFormatAdapter,\n IOFormatExportOptions,\n IOFormatSupport,\n PDFFormatExportOptions,\n RasterExportOptions,\n SVGExportOptions\n} from './types'\n\n/** Formats that export a document, page, selection, or single node alike. */\nconst EXPORT_EVERY_TARGET: IOFormatSupport = {\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n}\n\n/** Formats with a size of their own, so no export scale or quality. */\nconst FIXED_SIZE_EXPORT: IOFormatExportOptions = { scale: false, quality: false }\n\nfunction lowerExt(name: string): string {\n const match = /\\.([^.]+)$/.exec(name.toLowerCase())\n return match?.[1] ?? ''\n}\n\nfunction ensureSingleNode(target: ExportRequest['target']): string | null {\n if (target.scope === 'node') return target.nodeId\n if (target.scope === 'selection' && target.nodeIds.length === 1) return target.nodeIds[0]\n return null\n}\n\nfunction resolveExportNodes(request: ExportRequest): { pageId: string; nodeIds: string[] } | null {\n switch (request.target.scope) {\n case 'document': {\n const page = request.graph.getPages()[0]\n return { pageId: page.id, nodeIds: page.childIds }\n }\n case 'page': {\n const page = request.graph.getNode(request.target.pageId)\n if (!page) return null\n return { pageId: page.id, nodeIds: page.childIds }\n }\n case 'selection': {\n const first = request.target.nodeIds[0]\n if (!first) return null\n const pageId = findPageId(request.graph, first)\n if (!pageId) return null\n if (!request.target.nodeIds.every((nodeId) => findPageId(request.graph, nodeId) === pageId)) {\n throw new Error('Export selection must stay on a single page')\n }\n return { pageId, nodeIds: request.target.nodeIds }\n }\n case 'node':\n return resolveExportNodes({\n ...request,\n target: { scope: 'selection', nodeIds: [request.target.nodeId] }\n })\n default:\n return null\n }\n}\n\nasync function renderRaster(\n request: ExportRequest,\n options: RasterExportOptions,\n context?: IOContext\n): Promise<Uint8Array | null> {\n const target = resolveExportNodes(request)\n if (!target) return null\n const scale = options.scale ?? 1\n\n if (context?.canvasKit && context.renderer) {\n return renderNodesToImage(\n context.canvasKit,\n context.renderer,\n request.graph,\n target.pageId,\n target.nodeIds,\n {\n scale,\n format: options.format,\n quality: options.quality,\n trimTransparent: request.target.scope === 'page' || request.target.scope === 'document'\n }\n )\n }\n\n return headlessRenderNodes(request.graph, target.pageId, target.nodeIds, {\n scale,\n format: options.format,\n quality: options.quality,\n trimTransparent: request.target.scope === 'page' || request.target.scope === 'document'\n })\n}\n\nfunction rasterFormat<F extends RasterExportFormat>(format: F): IOFormatAdapter<Lowercase<F>> {\n const extension = format.toLowerCase() as Lowercase<F>\n let mimeType = 'image/png'\n if (format === 'JPG') mimeType = 'image/jpeg'\n else if (format === 'WEBP') mimeType = 'image/webp'\n\n return {\n id: extension,\n label: format,\n role: 'derived-export',\n category: 'raster',\n extensions: [extension],\n mimeTypes: [mimeType],\n support: {\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: {\n scale: true,\n quality: format !== 'PNG',\n colorSpace: false\n },\n async exportContent(request, options?: RasterExportOptions, context?: IOContext) {\n const data = await renderRaster(\n request,\n {\n format,\n scale: options?.scale,\n quality: options?.quality\n },\n context\n )\n if (!data) throw new Error('Nothing to export')\n return {\n format: extension,\n mimeType,\n extension,\n data\n }\n }\n }\n}\n\n/** The file a document saves as: Figma's `.fig` for a design, FigJam's `.jam` for a board. */\nexport const DOCUMENT_EXTENSIONS: Readonly<Record<DocumentKind, 'fig' | 'jam'>> = {\n design: 'fig',\n board: 'jam'\n}\n\nexport const figFormat: IOFormatAdapter<'fig'> = {\n id: 'fig',\n label: 'Pairdraw Document',\n role: 'native-document',\n category: 'document',\n extensions: ['fig', 'jam'],\n mimeTypes: ['application/octet-stream'],\n support: {\n readDocument: true,\n writeDocument: true,\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: FIXED_SIZE_EXPORT,\n matchesFile(fileName) {\n const ext = lowerExt(fileName)\n return ext === 'fig' || ext === 'jam'\n },\n async readDocument(input) {\n const data = input.data.slice().buffer\n const graph = await parseFigFile(data, { populate: 'first-page' })\n return { graph, sourceFormat: 'fig' }\n },\n async writeDocument(graph, options?: FigWriteOptions, context?: IOContext) {\n return writeFig(graph, options, context, options?.thumbnailPageId)\n },\n async exportContent(request, options?: FigWriteOptions, context?: IOContext) {\n // A whole document is written as it is, so one opened from an archive keeps that archive.\n if (request.target.scope === 'document')\n return writeFig(request.graph, options, context, options?.thumbnailPageId, request.fileName)\n const extracted = extractExportGraph(request.graph, request.target)\n return writeFig(\n extracted.graph,\n options,\n context,\n options?.thumbnailPageId ?? extracted.pageId ?? undefined,\n request.fileName\n )\n }\n}\n\n/** A `.fig` named as asked, or else after the file it is written to, or else Untitled. */\nasync function writeFig(\n graph: SceneGraph,\n options: FigWriteOptions | undefined,\n context: IOContext | undefined,\n pageId: string | undefined,\n fileName?: string\n): Promise<ExportResult> {\n const data = await exportFigFile(graph, {\n ck: context?.canvasKit,\n renderer: context?.renderer,\n pageId,\n renderHeadlessThumbnail: options?.renderThumbnail ?? false,\n documentName: options?.documentName ?? (fileName && filename(fileName))\n })\n const extension = DOCUMENT_EXTENSIONS[graph.documentKind]\n return { format: 'fig', mimeType: 'application/octet-stream', extension, data }\n}\n\nexport const drawioFormat: IOFormatAdapter<'drawio'> = {\n id: 'drawio',\n label: 'draw.io Diagram',\n role: 'interchange-document',\n category: 'document',\n extensions: ['drawio', 'dio'],\n mimeTypes: ['application/vnd.jgraph.mxfile'],\n support: {\n readDocument: true,\n writeDocument: true,\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: FIXED_SIZE_EXPORT,\n laysOutOnRead: true,\n // A draw.io PNG or SVG export opens as its diagram when its name says it is one.\n matchesFile(fileName, mimeType) {\n const ext = lowerExt(fileName)\n return (\n ext === 'drawio' ||\n ext === 'dio' ||\n isDrawIOExportFileName(fileName) ||\n mimeType === 'application/vnd.jgraph.mxfile'\n )\n },\n async readDocument(input) {\n const { readDrawIOBytes } = await import('@pairdraw/drawio')\n const { drawioToSceneGraph } = await import('./formats/drawio')\n const file = readDrawIOBytes(input.data)\n if (!file) throw new Error('This file holds no draw.io diagram')\n if (file.unreadable.length > 0) {\n throw new Error(`Could not read the draw.io pages ${file.unreadable.join(', ')}`)\n }\n const graph = drawioToSceneGraph(file)\n // draw.io stores label text, not the sizes it lays out to.\n layoutAuthoredNodes(\n graph,\n graph.getPages().map((page) => page.id)\n )\n return { graph, sourceFormat: 'drawio' }\n },\n async writeDocument(graph) {\n const pageIds = graph.getPages().map((page) => page.id)\n return writeDrawIO(graph, { pageIds })\n },\n // A page or a selection goes as a one-page diagram; the document, every page.\n async exportContent(request) {\n if (request.target.scope === 'document') {\n const pageIds = request.graph.getPages().map((page) => page.id)\n return writeDrawIO(request.graph, { pageIds })\n }\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n return writeDrawIO(request.graph, target)\n }\n}\n\nexport const mermaidFormat: IOFormatAdapter<'mermaid'> = {\n id: 'mermaid',\n label: 'Mermaid Diagram',\n role: 'interchange-document',\n category: 'document',\n extensions: ['mmd', 'mermaid'],\n mimeTypes: ['text/vnd.mermaid'],\n support: {\n readDocument: true\n },\n laysOutOnRead: true,\n matchesFile(fileName, mimeType) {\n const ext = lowerExt(fileName)\n return ext === 'mmd' || ext === 'mermaid' || mimeType === 'text/vnd.mermaid'\n },\n async readDocument(input) {\n const { detectMermaidDiagram } = await import('@pairdraw/mermaid')\n const text = new TextDecoder().decode(input.data)\n if (!detectMermaidDiagram(text)) throw new Error('This file holds no Mermaid flowchart')\n // Mermaid stores a diagram's structure, which reading lays out with its text measured.\n const { mermaidToSceneGraph } = await import('./formats/mermaid')\n return { graph: await mermaidToSceneGraph(text), sourceFormat: 'mermaid' }\n }\n}\n\n/** Pages or layers as a draw.io file, loading the writer only when one is saved. */\nasync function writeDrawIO(graph: SceneGraph, target: DrawIOExportTarget): Promise<ExportResult> {\n const { writeDrawIOFile } = await import('@pairdraw/drawio')\n const { sceneGraphToDrawIO } = await import('./formats/drawio')\n return {\n format: 'drawio',\n mimeType: 'application/vnd.jgraph.mxfile',\n extension: 'drawio',\n data: writeDrawIOFile(sceneGraphToDrawIO(graph, target)),\n encoding: 'utf8'\n }\n}\n\nexport const pngFormat = rasterFormat('PNG')\nexport const jpgFormat = rasterFormat('JPG')\nexport const webpFormat = rasterFormat('WEBP')\n\nexport const svgFormat: IOFormatAdapter<'svg'> = {\n id: 'svg',\n label: 'SVG',\n role: 'derived-export',\n category: 'vector',\n extensions: ['svg'],\n mimeTypes: ['image/svg+xml'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: { ...FIXED_SIZE_EXPORT, colorSpace: true },\n async exportContent(request, options?: SVGExportOptions) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToLaidOutSVG } = await import('./formats/svg/text/layout')\n const data = await renderNodesToLaidOutSVG(\n request.graph,\n target.pageId,\n target.nodeIds,\n options\n )\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'svg',\n mimeType: 'image/svg+xml',\n extension: 'svg',\n data,\n encoding: 'utf8'\n }\n }\n}\n\n/**\n * The PDF pages an export makes. A selection gets a page per layer in the order it lists them,\n * each sized to its layer, as slides and Figma's frame export do, unless `single` asks for one\n * page; a page or a document is one page of its layers unless `frames` asks for a page each.\n */\nasync function pdfPageSpecs(\n request: ExportRequest,\n options: PDFFormatExportOptions | undefined\n): Promise<PDFPageSpec[]> {\n const frames = options?.pages ? options.pages === 'frames' : request.target.scope === 'selection'\n if (frames) {\n const { target } = request\n let ids: string[] | undefined\n if (target.scope === 'selection') ids = target.nodeIds\n else if (target.scope === 'node') ids = [target.nodeId]\n const first = ids?.[0]\n let currentPageId: string | null | undefined\n if (first) currentPageId = findPageId(request.graph, first)\n else if (target.scope === 'page') currentPageId = target.pageId\n else if (target.scope === 'document') currentPageId = request.graph.getPages()[0]?.id\n if (!currentPageId) throw new Error('Nothing to export')\n // Without IDs, the plan takes the page's visible layers, in layer order.\n const { planPDFPages } = await import('./formats/pdf/plan')\n return planPDFPages(request.graph, { mode: 'frames', ids, currentPageId })\n }\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n return [target]\n}\n\nexport const pdfFormat: IOFormatAdapter<'pdf'> = {\n id: 'pdf',\n label: 'PDF',\n role: 'derived-export',\n category: 'vector',\n extensions: ['pdf'],\n mimeTypes: ['application/pdf'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: PDFFormatExportOptions) {\n const specs = await pdfPageSpecs(request, options)\n // Embedded, as Figma embeds every face its PDFs draw.\n const { exportPDFDocument } = await import('./formats/pdf/document')\n const data = (await exportPDFDocument(request.graph, specs, { embedFonts: true }))?.data\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'pdf',\n mimeType: 'application/pdf',\n extension: 'pdf',\n data\n }\n }\n}\n\n/**\n * Every top-level frame becomes a slide, so a PPTX document export spans all\n * pages — the shared resolver only reaches the first one.\n */\nfunction resolvePPTXExportNodes(\n request: ExportRequest\n): { pageId: string; nodeIds: string[] } | null {\n if (request.target.scope !== 'document') return resolveExportNodes(request)\n const pages = request.graph.getPages()\n if (!pages.length) return null\n return { pageId: pages[0].id, nodeIds: pages.flatMap((page) => page.childIds) }\n}\n\nexport const pptxFormat: IOFormatAdapter<'pptx'> = {\n id: 'pptx',\n label: 'PowerPoint',\n role: 'derived-export',\n category: 'print',\n extensions: ['pptx'],\n mimeTypes: ['application/vnd.openxmlformats-officedocument.presentationml.presentation'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: PPTXExportOptions, context?: IOContext) {\n const target = resolvePPTXExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToPPTX } = await import('./formats/pptx')\n const data = await renderNodesToPPTX(request.graph, target.pageId, target.nodeIds, {\n ...options,\n context: options?.context ?? context\n })\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'pptx',\n mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n extension: 'pptx',\n data\n }\n }\n}\n\nexport const jsxFormat: IOFormatAdapter<'jsx'> = {\n id: 'jsx',\n label: 'JSX',\n role: 'derived-export',\n category: 'code',\n extensions: ['jsx'],\n mimeTypes: ['text/plain', 'text/jsx'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request): Promise<ExportResult> {\n const nodeId = ensureSingleNode(request.target)\n // A page or a document exports its top-level layers, as Tailwind JSX does.\n const target = nodeId ? null : resolveExportNodes(request)\n let data = ''\n if (nodeId) data = sceneNodeToJSX(nodeId, request.graph)\n else if (target) data = selectionToJSX(target.nodeIds, request.graph)\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'jsx',\n mimeType: 'text/plain',\n extension: 'jsx',\n data,\n encoding: 'utf8'\n }\n }\n}\n\nexport const htmlFormat: IOFormatAdapter<'html'> = {\n id: 'html',\n label: 'HTML',\n role: 'derived-export',\n category: 'code',\n extensions: ['html'],\n mimeTypes: ['text/html'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: HTMLExportOptions) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToHTML } = await import('./formats/html')\n const { html, assets } = await renderNodesToHTML(\n request.graph,\n target.nodeIds,\n options,\n request.fileName\n )\n return {\n format: 'html',\n mimeType: 'text/html',\n extension: 'html',\n data: html,\n encoding: 'utf8',\n assets\n }\n }\n}\n\nexport const tailwindJSXFormat: IOFormatAdapter<'tailwind-jsx'> = {\n id: 'tailwind-jsx',\n label: 'Tailwind JSX',\n role: 'derived-export',\n category: 'code',\n extensions: ['jsx'],\n mimeTypes: ['text/plain', 'text/jsx'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { sceneNodesToTailwindJSX } = await import('@pairdraw/dom-css/export')\n const { vectorElement } = await import('#core/io/formats/html/vectors')\n const data = sceneNodesToTailwindJSX(request.graph, target.nodeIds, { vectorElement })\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'tailwind-jsx',\n mimeType: 'text/plain',\n extension: 'jsx',\n data,\n encoding: 'utf8'\n }\n }\n}\n\nexport { penFormat }\n\nexport const BUILTIN_IO_FORMATS = [\n figFormat,\n penFormat,\n drawioFormat,\n mermaidFormat,\n pngFormat,\n jpgFormat,\n webpFormat,\n svgFormat,\n pdfFormat,\n pptxFormat,\n jsxFormat,\n tailwindJSXFormat,\n htmlFormat\n] as const satisfies readonly IOFormatAdapter[]\n\nexport type BuiltinIOFormatId = (typeof BUILTIN_IO_FORMATS)[number]['id']\n"],"mappings":";;;;;;;;;;;;AA8BA,MAAM,sBAAuC;CAC3C,gBAAgB;CAChB,YAAY;CACZ,iBAAiB;CACjB,YAAY;AACd;;AAGA,MAAM,oBAA2C;CAAE,OAAO;CAAO,SAAS;AAAM;AAEhF,SAAS,SAAS,MAAsB;CAEtC,OADc,aAAa,KAAK,KAAK,YAAY,CACtC,CAAC,GAAG,MAAM;AACvB;AAEA,SAAS,iBAAiB,QAAgD;CACxE,IAAI,OAA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B;EACxD,MAAM,SAAS,mBAAmB,OAAO;EACzC,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,mBAAmB;EAChD,MAAM,EAAE,sBAAsB,MAAM,OAAO;EAC3C,MAAM,EAAE,MAAM,WAAW,MAAM,kBAC7B,QAAQ,OACR,OAAO,SACP,SACA,QAAQ,QACV;EACA,OAAO;GACL,QAAQ;GACR,UAAU;GACV,WAAW;GACX,MAAM;GACN,UAAU;GACV;EACF;CACF;AACF;AAEA,MAAa,oBAAqD;CAChE,IAAI;CACJ,OAAO;CACP,MAAM;CACN,UAAU;CACV,YAAY,CAAC,KAAK;CAClB,WAAW,CAAC,cAAc,UAAU;CACpC,SAAS;CACT,eAAe;CACf,MAAM,cAAc,SAAS;EAC3B,MAAM,SAAS,mBAAmB,OAAO;EACzC,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,mBAAmB;EAChD,MAAM,EAAE,4BAA4B,MAAM,OAAO;EACjD,MAAM,EAAE,kBAAkB,MAAM,OAAO;EACvC,MAAM,OAAO,wBAAwB,QAAQ,OAAO,OAAO,SAAS,EAAE,cAAc,CAAC;EACrF,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,mBAAmB;EAC9C,OAAO;GACL,QAAQ;GACR,UAAU;GACV,WAAW;GACX;GACA,UAAU;EACZ;CACF;AACF;AAIA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"character-style.d.ts","names":[],"sources":["../../src/text/character-style.ts"],"mappings":";;;KAoBY,iBAAiB,SAC3B,KACE;EAiBF;EACA,YAAY;EACZ;EACA;EACA,WAAW;EACX;EACA;EACA,gBAAgB;;KAGN,uBAAuB;cAEtB;;cA4BA;iBAKG,UAAU,MAAM,YAAY;;iBA4B5B,gBAAgB,MAAM,WAAW,eAAe,cAAc;;;;;KAuDlE,iBAAiB,2BAA2B,qBAAqB;;iBAwB7D,mBACd,MAAM,WACN,eACA,aACA,OAAO,iBACN;;;;;iBAwCa,iBACd,MAAM,WACN,SAAS,QAAQ,KAAK,WAAW,gDACjC,SAAS,qBAAqB,yBAC7B,QAAQ"}
1
+ {"version":3,"file":"character-style.d.ts","names":[],"sources":["../../src/text/character-style.ts"],"mappings":";;;KAqBY,iBAAiB,SAC3B,KACE;EAiBF;EACA,YAAY;EACZ;EACA;EACA,WAAW;EACX;EACA;EACA,gBAAgB;;KAGN,uBAAuB;cAEtB;;cA4BA;iBAKG,UAAU,MAAM,YAAY;;iBA4B5B,gBAAgB,MAAM,WAAW,eAAe,cAAc;;;;;KA0DlE,iBAAiB,2BAA2B,qBAAqB;;iBAwB7D,mBACd,MAAM,WACN,eACA,aACA,OAAO,iBACN;;;;;iBAwCa,iBACd,MAAM,WACN,SAAS,QAAQ,KAAK,WAAW,gDACjC,SAAS,qBAAqB,yBAC7B,QAAQ"}
@@ -1,4 +1,5 @@
1
1
  import { TEXT_BINDABLE_FIELDS } from "@pairdraw/scene-graph";
2
+ import { withBoundBindingScales } from "@pairdraw/scene-graph/variables";
2
3
  import { FACE_KEYS, SHARED_TEXT_STYLE_FIELDS, rangeFontStyle, styleDetachmentChanges } from "@pairdraw/scene-graph/shared-styles";
3
4
  import { isEqual } from "es-toolkit/predicate";
4
5
  import { omit, pick } from "es-toolkit/object";
@@ -86,7 +87,7 @@ function withoutRedundantOverrides(node, runs) {
86
87
  const base = nodeStyle(node);
87
88
  const result = [];
88
89
  for (const run of runs) {
89
- const style = omit(run.style, CHARACTER_STYLE_KEYS.filter((key) => run.style[key] !== void 0 && isEqual(run.style[key], base[key])));
90
+ const style = withBoundBindingScales(omit(run.style, CHARACTER_STYLE_KEYS.filter((key) => run.style[key] !== void 0 && isEqual(run.style[key], base[key]))));
90
91
  if (Object.keys(style).length === 0) continue;
91
92
  const previous = result.at(-1);
92
93
  if (previous && previous.start + previous.length === run.start && isEqual(previous.style, style)) previous.length += run.length;