@pairdraw/core 0.19.0 → 0.19.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/canvas/overlays/index.d.ts +2 -2
- package/dist/canvas/overlays/index.js +2 -2
- package/dist/canvas/overlays/selection.d.ts +1 -2
- package/dist/canvas/overlays/selection.d.ts.map +1 -1
- package/dist/canvas/overlays/selection.js +2 -9
- package/dist/canvas/overlays/selection.js.map +1 -1
- package/dist/canvas/renderer/fonts.d.ts.map +1 -1
- package/dist/canvas/renderer/fonts.js +2 -0
- package/dist/canvas/renderer/fonts.js.map +1 -1
- package/dist/canvas/renderer/methods.d.ts +0 -1
- package/dist/canvas/renderer/methods.d.ts.map +1 -1
- package/dist/canvas/renderer/methods.js +1 -4
- package/dist/canvas/renderer/methods.js.map +1 -1
- package/dist/canvas/renderer/overlay-pass.d.ts.map +1 -1
- package/dist/canvas/renderer/overlay-pass.js +0 -1
- package/dist/canvas/renderer/overlay-pass.js.map +1 -1
- package/dist/canvas/renderer/pipeline.d.ts.map +1 -1
- package/dist/canvas/renderer/pipeline.js +0 -1
- package/dist/canvas/renderer/pipeline.js.map +1 -1
- package/dist/canvas/renderer/types.d.ts +0 -1
- package/dist/canvas/renderer/types.d.ts.map +1 -1
- package/dist/canvas/renderer.d.ts +0 -1
- package/dist/canvas/renderer.d.ts.map +1 -1
- package/dist/canvas/renderer.js.map +1 -1
- package/dist/design-jsx/index.d.ts +2 -2
- package/dist/design-jsx/index.js +2 -2
- package/dist/design-jsx/renderer.d.ts +3 -2
- package/dist/design-jsx/renderer.d.ts.map +1 -1
- package/dist/design-jsx/renderer.js +2 -2
- package/dist/design-jsx/renderer.js.map +1 -1
- package/dist/editor/clipboard/snapshot.d.ts.map +1 -1
- package/dist/editor/clipboard/snapshot.js +12 -4
- package/dist/editor/clipboard/snapshot.js.map +1 -1
- package/dist/editor/clipboard.d.ts.map +1 -1
- package/dist/editor/clipboard.js +2 -7
- package/dist/editor/clipboard.js.map +1 -1
- package/dist/editor/color-space.d.ts.map +1 -1
- package/dist/editor/color-space.js +33 -38
- package/dist/editor/color-space.js.map +1 -1
- package/dist/editor/create.d.ts +9 -5
- package/dist/editor/create.d.ts.map +1 -1
- package/dist/editor/create.js +10 -1
- package/dist/editor/create.js.map +1 -1
- package/dist/editor/history/edit.d.ts.map +1 -1
- package/dist/editor/history/edit.js +2 -1
- package/dist/editor/history/edit.js.map +1 -1
- package/dist/editor/nudge.js +1 -1
- package/dist/editor/nudge.js.map +1 -1
- package/dist/editor/read-only/actions.js +2 -0
- package/dist/editor/read-only/actions.js.map +1 -1
- package/dist/editor/selection/container.d.ts +2 -0
- package/dist/editor/selection/container.d.ts.map +1 -1
- package/dist/editor/selection/container.js +17 -1
- package/dist/editor/selection/container.js.map +1 -1
- package/dist/editor/selection/navigation.js +7 -4
- package/dist/editor/selection/navigation.js.map +1 -1
- package/dist/editor/selection/read.d.ts +2 -2
- package/dist/editor/selection.d.ts +4 -2
- package/dist/editor/selection.d.ts.map +1 -1
- package/dist/editor/shapes/with-text.d.ts.map +1 -1
- package/dist/editor/shapes/with-text.js +2 -5
- package/dist/editor/shapes/with-text.js.map +1 -1
- package/dist/editor/structure/auto-layout-wrap.js +1 -1
- package/dist/editor/structure/auto-layout-wrap.js.map +1 -1
- package/dist/editor/structure/boolean.d.ts +2 -3
- package/dist/editor/structure/boolean.d.ts.map +1 -1
- package/dist/editor/structure/boolean.js.map +1 -1
- package/dist/editor/structure/group/bounds.d.ts.map +1 -1
- package/dist/editor/structure/group/bounds.js +1 -3
- package/dist/editor/structure/group/bounds.js.map +1 -1
- package/dist/editor/structure/outline-stroke.js +3 -3
- package/dist/editor/structure/outline-stroke.js.map +1 -1
- package/dist/editor/structure/reorder.d.ts.map +1 -1
- package/dist/editor/structure/reorder.js +7 -14
- package/dist/editor/structure/reorder.js.map +1 -1
- package/dist/editor/structure/state.js +1 -1
- package/dist/editor/structure/state.js.map +1 -1
- package/dist/editor/structure.d.ts +1 -2
- package/dist/editor/structure.d.ts.map +1 -1
- package/dist/editor/structure.js +3 -3
- package/dist/editor/structure.js.map +1 -1
- package/dist/editor/types.d.ts +4 -1
- package/dist/editor/types.d.ts.map +1 -1
- package/dist/editor/variables.d.ts.map +1 -1
- package/dist/editor/variables.js +57 -1
- package/dist/editor/variables.js.map +1 -1
- package/dist/figma-api/accessors/text/index.d.ts.map +1 -1
- package/dist/figma-api/accessors/text/index.js +4 -1
- package/dist/figma-api/accessors/text/index.js.map +1 -1
- package/dist/figma-api/fonts/loaded.d.ts +3 -1
- package/dist/figma-api/fonts/loaded.d.ts.map +1 -1
- package/dist/figma-api/fonts/loaded.js +8 -1
- package/dist/figma-api/fonts/loaded.js.map +1 -1
- package/dist/figma-api/index.d.ts +13 -0
- package/dist/figma-api/index.d.ts.map +1 -1
- package/dist/figma-api/index.js +13 -0
- package/dist/figma-api/index.js.map +1 -1
- package/dist/figma-api/serialization.d.ts.map +1 -1
- package/dist/figma-api/serialization.js +2 -1
- package/dist/figma-api/serialization.js.map +1 -1
- package/dist/figma-api/shape-details.d.ts +26 -0
- package/dist/figma-api/shape-details.d.ts.map +1 -0
- package/dist/figma-api/shape-details.js +28 -0
- package/dist/figma-api/shape-details.js.map +1 -0
- package/dist/figma-api/shape-with-text.js +2 -5
- package/dist/figma-api/shape-with-text.js.map +1 -1
- package/dist/figma-api/surface.d.ts +1 -1
- package/dist/figma-api/surface.d.ts.map +1 -1
- package/dist/figma-api/surface.js +1 -0
- package/dist/figma-api/surface.js.map +1 -1
- package/dist/icons/svg.js +1 -1
- package/dist/icons/svg.js.map +1 -1
- package/dist/io/formats/design-tokens/apply.d.ts +1 -1
- package/dist/io/formats/drawio/index.d.ts.map +1 -1
- package/dist/io/formats/drawio/index.js +1 -1
- package/dist/io/formats/drawio/index.js.map +1 -1
- package/dist/io/formats/html/layers.d.ts +7 -4
- package/dist/io/formats/html/layers.d.ts.map +1 -1
- package/dist/io/formats/html/layers.js +4 -1
- package/dist/io/formats/html/layers.js.map +1 -1
- package/dist/io/formats/pdf/dom.d.ts +6 -1
- package/dist/io/formats/pdf/dom.d.ts.map +1 -1
- package/dist/io/formats/pdf/dom.js +9 -22
- package/dist/io/formats/pdf/dom.js.map +1 -1
- package/dist/io/formats/pdf/export.js +1 -1
- package/dist/io/formats/pdf/export.js.map +1 -1
- package/dist/io/formats/svg/defs.d.ts.map +1 -1
- package/dist/io/formats/svg/defs.js +3 -1
- package/dist/io/formats/svg/defs.js.map +1 -1
- package/dist/io/formats/svg/export.d.ts.map +1 -1
- package/dist/io/formats/svg/export.js +52 -16
- package/dist/io/formats/svg/export.js.map +1 -1
- package/dist/layout/apply.d.ts.map +1 -1
- package/dist/layout/apply.js +50 -12
- package/dist/layout/apply.js.map +1 -1
- package/dist/layout/derived.d.ts +7 -1
- package/dist/layout/derived.d.ts.map +1 -1
- package/dist/layout/derived.js +11 -1
- package/dist/layout/derived.js.map +1 -1
- package/dist/layout/grid.d.ts +7 -2
- package/dist/layout/grid.d.ts.map +1 -1
- package/dist/layout/grid.js +27 -9
- package/dist/layout/grid.js.map +1 -1
- package/dist/layout/mutations.d.ts +1 -0
- package/dist/layout/mutations.d.ts.map +1 -1
- package/dist/layout/mutations.js +10 -0
- package/dist/layout/mutations.js.map +1 -1
- package/dist/layout/strokes.d.ts +9 -1
- package/dist/layout/strokes.d.ts.map +1 -1
- package/dist/layout/strokes.js +12 -1
- package/dist/layout/strokes.js.map +1 -1
- package/dist/layout/yoga-helpers.d.ts +3 -1
- package/dist/layout/yoga-helpers.d.ts.map +1 -1
- package/dist/layout/yoga-helpers.js +16 -2
- package/dist/layout/yoga-helpers.js.map +1 -1
- package/dist/layout.d.ts.map +1 -1
- package/dist/layout.js +71 -38
- package/dist/layout.js.map +1 -1
- package/dist/lint/linter.d.ts +1 -0
- package/dist/lint/linter.d.ts.map +1 -1
- package/dist/lint/linter.js +13 -1
- package/dist/lint/linter.js.map +1 -1
- package/dist/lint/rules/effect-style-required.js +1 -0
- package/dist/lint/rules/effect-style-required.js.map +1 -1
- package/dist/lint/rules/text-style-required.js +1 -0
- package/dist/lint/rules/text-style-required.js.map +1 -1
- package/dist/lint/types.d.ts +7 -0
- package/dist/lint/types.d.ts.map +1 -1
- package/dist/rpc/commands.d.ts +2 -2
- package/dist/rpc/index.d.ts +2 -2
- package/dist/rpc/read-commands.d.ts +18 -8
- package/dist/rpc/read-commands.d.ts.map +1 -1
- package/dist/rpc/read-commands.js +18 -9
- package/dist/rpc/read-commands.js.map +1 -1
- package/dist/text/font/faces.d.ts +12 -1
- package/dist/text/font/faces.d.ts.map +1 -1
- package/dist/text/font/faces.js +15 -1
- package/dist/text/font/faces.js.map +1 -1
- package/dist/text/font/manager.d.ts.map +1 -1
- package/dist/text/font/manager.js +6 -11
- package/dist/text/font/manager.js.map +1 -1
- package/dist/text/index.d.ts +2 -2
- package/dist/text/index.js +2 -2
- package/dist/tools/modify/layout.d.ts.map +1 -1
- package/dist/tools/modify/layout.js +1 -0
- package/dist/tools/modify/layout.js.map +1 -1
- package/dist/tools/read/nodes.d.ts.map +1 -1
- package/dist/tools/read/nodes.js.map +1 -1
- package/dist/tools/structure/batch.d.ts.map +1 -1
- package/dist/tools/structure/batch.js +14 -0
- package/dist/tools/structure/batch.js.map +1 -1
- package/dist/tools/vector/path.d.ts.map +1 -1
- package/dist/tools/vector/path.js +39 -7
- package/dist/tools/vector/path.js.map +1 -1
- package/dist/xpath.d.ts +3 -0
- package/dist/xpath.d.ts.map +1 -1
- package/dist/xpath.js +3 -1
- package/dist/xpath.js.map +1 -1
- package/package.json +9 -9
- package/src/canvas/overlays/index.ts +0 -1
- package/src/canvas/overlays/selection.ts +1 -12
- package/src/canvas/renderer/fonts.ts +2 -0
- package/src/canvas/renderer/methods.ts +0 -9
- package/src/canvas/renderer/overlay-pass.ts +0 -1
- package/src/canvas/renderer/pipeline.ts +0 -1
- package/src/canvas/renderer/types.ts +0 -1
- package/src/canvas/renderer.ts +0 -1
- package/src/design-jsx/index.ts +1 -1
- package/src/design-jsx/renderer.ts +1 -1
- package/src/editor/clipboard/snapshot.ts +21 -4
- package/src/editor/clipboard.ts +4 -14
- package/src/editor/color-space.ts +47 -38
- package/src/editor/create.ts +14 -2
- package/src/editor/history/edit.ts +5 -1
- package/src/editor/nudge.ts +1 -1
- package/src/editor/read-only/actions.ts +2 -0
- package/src/editor/selection/container.ts +24 -1
- package/src/editor/selection/navigation.ts +8 -6
- package/src/editor/shapes/with-text.ts +2 -5
- package/src/editor/structure/auto-layout-wrap.ts +1 -1
- package/src/editor/structure/boolean.ts +1 -3
- package/src/editor/structure/group/bounds.ts +1 -5
- package/src/editor/structure/outline-stroke.ts +3 -3
- package/src/editor/structure/reorder.ts +8 -14
- package/src/editor/structure/state.ts +1 -1
- package/src/editor/structure.ts +5 -8
- package/src/editor/types.ts +4 -1
- package/src/editor/variables.ts +74 -2
- package/src/figma-api/accessors/text/index.ts +10 -1
- package/src/figma-api/fonts/loaded.ts +9 -0
- package/src/figma-api/index.ts +25 -0
- package/src/figma-api/serialization.ts +2 -1
- package/src/figma-api/shape-details.ts +50 -0
- package/src/figma-api/shape-with-text.ts +2 -5
- package/src/figma-api/surface.ts +1 -0
- package/src/global.d.ts +5 -0
- package/src/icons/svg.ts +3 -1
- package/src/io/formats/drawio/index.ts +3 -1
- package/src/io/formats/html/layers.ts +11 -2
- package/src/io/formats/pdf/dom.ts +10 -18
- package/src/io/formats/pdf/export.ts +1 -1
- package/src/io/formats/svg/defs.ts +10 -1
- package/src/io/formats/svg/export.ts +94 -19
- package/src/layout/apply.ts +87 -21
- package/src/layout/derived.ts +14 -0
- package/src/layout/grid.ts +33 -9
- package/src/layout/mutations.ts +13 -1
- package/src/layout/strokes.ts +12 -0
- package/src/layout/yoga-helpers.ts +18 -1
- package/src/layout.ts +94 -49
- package/src/lint/linter.ts +17 -2
- package/src/lint/rules/effect-style-required.ts +2 -0
- package/src/lint/rules/text-style-required.ts +2 -0
- package/src/lint/types.ts +8 -0
- package/src/rpc/index.ts +1 -0
- package/src/rpc/read-commands.ts +40 -23
- package/src/text/font/faces.ts +22 -0
- package/src/text/font/manager.ts +9 -11
- package/src/tools/modify/layout.ts +5 -0
- package/src/tools/read/nodes.ts +0 -1
- package/src/tools/structure/batch.ts +22 -0
- package/src/tools/vector/path.ts +30 -6
- package/src/xpath.ts +6 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serialization.js","names":[],"sources":["../../src/figma-api/serialization.ts"],"sourcesContent":["import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\nimport { pluginChildren } from './accessors/sticky'\nimport { figmaFills, figmaStrokes } from './accessors/visual'\nimport type { NodeProxyHost } from './proxy'\n\nfunction resolveBindings(graph: SceneGraph, node: SceneNode): Record<string, unknown> | undefined {\n const keys = Object.keys(node.boundVariables)\n if (keys.length === 0) return undefined\n const result: Record<string, unknown> = {}\n for (const [field, varId] of Object.entries(node.boundVariables)) {\n const variable = graph.variables.get(varId)\n result[field] = {\n variableId: varId,\n variableName: variable?.name ?? varId,\n resolvedValue: variable ? graph.resolveVariable(varId) : undefined\n }\n }\n return result\n}\n\nfunction appendTextProps(obj: Record<string, unknown>, n: SceneNode): void {\n obj.fontFamily = n.fontFamily\n obj.fontSize = n.fontSize\n obj.fontWeight = n.fontWeight\n obj.italic = n.italic\n obj.textAlignHorizontal = n.textAlignHorizontal\n obj.textAlignVertical = n.textAlignVertical\n obj.textAutoResize = n.textAutoResize\n obj.textDirection = n.textDirection\n if (n.lineHeight != null) obj.lineHeight = n.lineHeight\n if (n.letterSpacing.value !== 0) obj.letterSpacing = n.letterSpacing\n if (n.textCase !== 'ORIGINAL') obj.textCase = n.textCase\n if (n.textDecoration !== 'NONE') obj.textDecoration = n.textDecoration\n if (n.maxLines != null) obj.maxLines = n.maxLines\n}\n\nexport function nodeProxyToJSON(\n graph: SceneGraph,\n api: NodeProxyHost,\n nodeId: string,\n maxDepth?: number,\n currentDepth = 0\n): Record<string, unknown> {\n const n = graph.getNode(nodeId)\n if (!n) return { id: nodeId, removed: true }\n\n const obj: Record<string, unknown> = {\n id: n.id,\n type: n.type,\n name: n.name,\n x: n.x,\n y: n.y,\n width: n.width,\n height: n.height\n }\n if (n.fills.length > 0) obj.fills = figmaFills(n)\n if (n.strokes.length > 0) obj.strokes = figmaStrokes(n)\n if (n.effects.length > 0) obj.effects = n.effects\n if (n.opacity !== 1) obj.opacity = n.opacity\n // The angle `set_rotation` writes, as the Figma API reports it. The scene stores the turn in\n // the opposite direction and keeps floating-point noise, so read it through the proxy.\n if (n.rotation !== 0) obj.rotation = api.wrapNode(nodeId).rotation\n
|
|
1
|
+
{"version":3,"file":"serialization.js","names":[],"sources":["../../src/figma-api/serialization.ts"],"sourcesContent":["import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\nimport { pluginChildren } from './accessors/sticky'\nimport { figmaFills, figmaStrokes } from './accessors/visual'\nimport type { NodeProxyHost } from './proxy'\nimport { shapeDetailFields } from './shape-details'\n\nfunction resolveBindings(graph: SceneGraph, node: SceneNode): Record<string, unknown> | undefined {\n const keys = Object.keys(node.boundVariables)\n if (keys.length === 0) return undefined\n const result: Record<string, unknown> = {}\n for (const [field, varId] of Object.entries(node.boundVariables)) {\n const variable = graph.variables.get(varId)\n result[field] = {\n variableId: varId,\n variableName: variable?.name ?? varId,\n resolvedValue: variable ? graph.resolveVariable(varId) : undefined\n }\n }\n return result\n}\n\nfunction appendTextProps(obj: Record<string, unknown>, n: SceneNode): void {\n obj.fontFamily = n.fontFamily\n obj.fontSize = n.fontSize\n obj.fontWeight = n.fontWeight\n obj.italic = n.italic\n obj.textAlignHorizontal = n.textAlignHorizontal\n obj.textAlignVertical = n.textAlignVertical\n obj.textAutoResize = n.textAutoResize\n obj.textDirection = n.textDirection\n if (n.lineHeight != null) obj.lineHeight = n.lineHeight\n if (n.letterSpacing.value !== 0) obj.letterSpacing = n.letterSpacing\n if (n.textCase !== 'ORIGINAL') obj.textCase = n.textCase\n if (n.textDecoration !== 'NONE') obj.textDecoration = n.textDecoration\n if (n.maxLines != null) obj.maxLines = n.maxLines\n}\n\nexport function nodeProxyToJSON(\n graph: SceneGraph,\n api: NodeProxyHost,\n nodeId: string,\n maxDepth?: number,\n currentDepth = 0\n): Record<string, unknown> {\n const n = graph.getNode(nodeId)\n if (!n) return { id: nodeId, removed: true }\n\n const obj: Record<string, unknown> = {\n id: n.id,\n type: n.type,\n name: n.name,\n x: n.x,\n y: n.y,\n width: n.width,\n height: n.height\n }\n if (n.fills.length > 0) obj.fills = figmaFills(n)\n if (n.strokes.length > 0) obj.strokes = figmaStrokes(n)\n if (n.effects.length > 0) obj.effects = n.effects\n if (n.opacity !== 1) obj.opacity = n.opacity\n // The angle `set_rotation` writes, as the Figma API reports it. The scene stores the turn in\n // the opposite direction and keeps floating-point noise, so read it through the proxy.\n if (n.rotation !== 0) obj.rotation = api.wrapNode(nodeId).rotation\n Object.assign(obj, shapeDetailFields(n))\n if (!n.visible) obj.visible = false\n if (n.text) obj.characters = n.text\n if (n.type === 'TEXT') {\n appendTextProps(obj, n)\n }\n if (n.layoutMode !== 'NONE') {\n // An auto layout frame reports the insets and alignment a tool sets, so a caller can read back\n // what it wrote instead of measuring the result.\n const proxy = api.wrapNode(nodeId)\n obj.layoutMode = n.layoutMode\n obj.layoutDirection = n.layoutDirection\n obj.itemSpacing = n.itemSpacing\n obj.paddingTop = proxy.paddingTop\n obj.paddingRight = proxy.paddingRight\n obj.paddingBottom = proxy.paddingBottom\n obj.paddingLeft = proxy.paddingLeft\n obj.primaryAxisAlignItems = proxy.primaryAxisAlignItems\n obj.counterAxisAlignItems = proxy.counterAxisAlignItems\n obj.primaryAxisSizingMode = proxy.primaryAxisSizingMode\n obj.counterAxisSizingMode = proxy.counterAxisSizingMode\n }\n // Include variable bindings with resolved values\n const bindings = resolveBindings(graph, n)\n if (bindings) obj.boundVariables = bindings\n const children = pluginChildren(graph, nodeId)\n if (children.length > 0) {\n if (maxDepth !== undefined && currentDepth >= maxDepth) {\n obj.childCount = children.length\n } else {\n obj.children = children.map((child) =>\n api.wrapNode(child.id).toJSON(maxDepth, currentDepth + 1)\n )\n }\n }\n return obj\n}\n"],"mappings":";;;;AAOA,SAAS,gBAAgB,OAAmB,MAAsD;CAEhG,IADa,OAAO,KAAK,KAAK,cACvB,CAAC,CAAC,WAAW,GAAG,OAAO,KAAA;CAC9B,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,OAAO,UAAU,OAAO,QAAQ,KAAK,cAAc,GAAG;EAChE,MAAM,WAAW,MAAM,UAAU,IAAI,KAAK;EAC1C,OAAO,SAAS;GACd,YAAY;GACZ,cAAc,UAAU,QAAQ;GAChC,eAAe,WAAW,MAAM,gBAAgB,KAAK,IAAI,KAAA;EAC3D;CACF;CACA,OAAO;AACT;AAEA,SAAS,gBAAgB,KAA8B,GAAoB;CACzE,IAAI,aAAa,EAAE;CACnB,IAAI,WAAW,EAAE;CACjB,IAAI,aAAa,EAAE;CACnB,IAAI,SAAS,EAAE;CACf,IAAI,sBAAsB,EAAE;CAC5B,IAAI,oBAAoB,EAAE;CAC1B,IAAI,iBAAiB,EAAE;CACvB,IAAI,gBAAgB,EAAE;CACtB,IAAI,EAAE,cAAc,MAAM,IAAI,aAAa,EAAE;CAC7C,IAAI,EAAE,cAAc,UAAU,GAAG,IAAI,gBAAgB,EAAE;CACvD,IAAI,EAAE,aAAa,YAAY,IAAI,WAAW,EAAE;CAChD,IAAI,EAAE,mBAAmB,QAAQ,IAAI,iBAAiB,EAAE;CACxD,IAAI,EAAE,YAAY,MAAM,IAAI,WAAW,EAAE;AAC3C;AAEA,SAAgB,gBACd,OACA,KACA,QACA,UACA,eAAe,GACU;CACzB,MAAM,IAAI,MAAM,QAAQ,MAAM;CAC9B,IAAI,CAAC,GAAG,OAAO;EAAE,IAAI;EAAQ,SAAS;CAAK;CAE3C,MAAM,MAA+B;EACnC,IAAI,EAAE;EACN,MAAM,EAAE;EACR,MAAM,EAAE;EACR,GAAG,E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
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { BooleanOperation, MaskType, SceneNode } from "@pairdraw/scene-graph";
|
|
2
|
+
//#region src/figma-api/shape-details.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* The shape details a node summary reports, under Figma's plugin-API names: the per-corner radii
|
|
5
|
+
* once the corners are drawn one by one and disagree, the mask flag and type while the layer masks,
|
|
6
|
+
* and a boolean layer's operation. A plain layer carries none of them.
|
|
7
|
+
*
|
|
8
|
+
* The per-corner fields are live only while `independentCorners` is set; otherwise the shape renders
|
|
9
|
+
* the uniform `cornerRadius` and any stored per-corner values are stale (a .fig import or a uniform
|
|
10
|
+
* radius-handle write leaves them), so they stay out. While the corners disagree the proxy reads
|
|
11
|
+
* `cornerRadius` as `mixed`, which JSON cannot hold, so the uniform field stays out too.
|
|
12
|
+
*/
|
|
13
|
+
interface ShapeDetailFields {
|
|
14
|
+
cornerRadius?: number;
|
|
15
|
+
topLeftRadius?: number;
|
|
16
|
+
topRightRadius?: number;
|
|
17
|
+
bottomRightRadius?: number;
|
|
18
|
+
bottomLeftRadius?: number;
|
|
19
|
+
isMask?: boolean;
|
|
20
|
+
maskType?: MaskType;
|
|
21
|
+
booleanOperation?: BooleanOperation;
|
|
22
|
+
}
|
|
23
|
+
declare function shapeDetailFields(node: SceneNode): ShapeDetailFields;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { ShapeDetailFields, shapeDetailFields };
|
|
26
|
+
//# sourceMappingURL=shape-details.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shape-details.d.ts","names":[],"sources":["../../src/figma-api/shape-details.ts"],"mappings":";;;;;;;;;;;;UAYiB;EACf;EACA;EACA;EACA;EACA;EACA;EACA,WAAW;EACX,mBAAmB;;iBAGL,kBAAkB,MAAM,YAAY"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
//#region src/figma-api/shape-details.ts
|
|
2
|
+
function shapeDetailFields(node) {
|
|
3
|
+
const fields = {};
|
|
4
|
+
const corners = [
|
|
5
|
+
node.topLeftRadius,
|
|
6
|
+
node.topRightRadius,
|
|
7
|
+
node.bottomRightRadius,
|
|
8
|
+
node.bottomLeftRadius
|
|
9
|
+
];
|
|
10
|
+
const differ = node.independentCorners && corners.some((radius) => radius !== corners[0]);
|
|
11
|
+
const uniform = node.independentCorners ? corners[0] : node.cornerRadius;
|
|
12
|
+
if (differ) {
|
|
13
|
+
fields.topLeftRadius = node.topLeftRadius;
|
|
14
|
+
fields.topRightRadius = node.topRightRadius;
|
|
15
|
+
fields.bottomRightRadius = node.bottomRightRadius;
|
|
16
|
+
fields.bottomLeftRadius = node.bottomLeftRadius;
|
|
17
|
+
} else if (uniform > 0) fields.cornerRadius = uniform;
|
|
18
|
+
if (node.isMask) {
|
|
19
|
+
fields.isMask = true;
|
|
20
|
+
fields.maskType = node.maskType;
|
|
21
|
+
}
|
|
22
|
+
if (node.booleanOperation) fields.booleanOperation = node.booleanOperation;
|
|
23
|
+
return fields;
|
|
24
|
+
}
|
|
25
|
+
//#endregion
|
|
26
|
+
export { shapeDetailFields };
|
|
27
|
+
|
|
28
|
+
//# sourceMappingURL=shape-details.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shape-details.js","names":[],"sources":["../../src/figma-api/shape-details.ts"],"sourcesContent":["import type { BooleanOperation, MaskType, SceneNode } from '@pairdraw/scene-graph'\n\n/**\n * The shape details a node summary reports, under Figma's plugin-API names: the per-corner radii\n * once the corners are drawn one by one and disagree, the mask flag and type while the layer masks,\n * and a boolean layer's operation. A plain layer carries none of them.\n *\n * The per-corner fields are live only while `independentCorners` is set; otherwise the shape renders\n * the uniform `cornerRadius` and any stored per-corner values are stale (a .fig import or a uniform\n * radius-handle write leaves them), so they stay out. While the corners disagree the proxy reads\n * `cornerRadius` as `mixed`, which JSON cannot hold, so the uniform field stays out too.\n */\nexport interface ShapeDetailFields {\n cornerRadius?: number\n topLeftRadius?: number\n topRightRadius?: number\n bottomRightRadius?: number\n bottomLeftRadius?: number\n isMask?: boolean\n maskType?: MaskType\n booleanOperation?: BooleanOperation\n}\n\nexport function shapeDetailFields(node: SceneNode): ShapeDetailFields {\n const fields: ShapeDetailFields = {}\n const corners = [\n node.topLeftRadius,\n node.topRightRadius,\n node.bottomRightRadius,\n node.bottomLeftRadius\n ]\n const differ = node.independentCorners && corners.some((radius) => radius !== corners[0])\n // Figma reads independent corners that agree as one radius, so the reported radius must come from\n // that agreement rather than the stale uniform field the corner edits leave behind.\n const uniform = node.independentCorners ? corners[0] : node.cornerRadius\n if (differ) {\n fields.topLeftRadius = node.topLeftRadius\n fields.topRightRadius = node.topRightRadius\n fields.bottomRightRadius = node.bottomRightRadius\n fields.bottomLeftRadius = node.bottomLeftRadius\n } else if (uniform > 0) {\n fields.cornerRadius = uniform\n }\n if (node.isMask) {\n fields.isMask = true\n fields.maskType = node.maskType\n }\n if (node.booleanOperation) fields.booleanOperation = node.booleanOperation\n return fields\n}\n"],"mappings":";AAuBA,SAAgB,kBAAkB,MAAoC;CACpE,MAAM,SAA4B,CAAC;CACnC,MAAM,UAAU;EACd,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;CACP;CACA,MAAM,SAAS,KAAK,sBAAsB,QAAQ,MAAM,WAAW,WAAW,QAAQ,EAAE;CAGxF,MAAM,UAAU,KAAK,qBAAqB,QAAQ,KAAK,KAAK;CAC5D,IAAI,QAAQ;EACV,OAAO,gBAAgB,KAAK;EAC5B,OAAO,iBAAiB,KAAK;EAC7B,OAAO,oBAAoB,KAAK;EAChC,OAAO,mBAAmB,KAAK;CACjC,OAAO,IAAI,UAAU,GACnB,OAAO,eAAe;CAExB,IAAI,KAAK,QAAQ;EACf,OAAO,SAAS;EAChB,OAAO,WAAW,KAAK;CACzB;CACA,IAAI,KAAK,kBAAkB,OAAO,mBAAmB,KAAK;CAC1D,OAAO;AACT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { newLayerDefaults } from "../editor/shapes/defaults.js";
|
|
2
2
|
import { graph, prepareFollowedFieldEdit, raw, updateNode } from "./accessor-utils.js";
|
|
3
3
|
import { SHAPE_WITH_TEXT_TYPES, isShapeWithTextType } from "@pairdraw/scene-graph/shape-with-text";
|
|
4
|
-
import { createShapeWithText,
|
|
4
|
+
import { createShapeWithText, shapeWithTextKindFields } from "@pairdraw/scene-graph/generated";
|
|
5
5
|
//#region src/figma-api/shape-with-text.ts
|
|
6
6
|
/** `value` as a kind for `node`, refused in the words Figma's plugin API refuses it with. */
|
|
7
7
|
function checkedShapeType(node, value) {
|
|
@@ -33,10 +33,7 @@ function installShapeWithTextAccessors(prototype, internals) {
|
|
|
33
33
|
const node = raw(this, internals);
|
|
34
34
|
const kind = checkedShapeType(node, value);
|
|
35
35
|
prepareFollowedFieldEdit(graph(this, internals), node, "shapeType", "shape-type");
|
|
36
|
-
updateNode(this, internals,
|
|
37
|
-
shapeWithTextType: kind,
|
|
38
|
-
...shapeWithTextFrameFields(kind, node.width, node.height)
|
|
39
|
-
});
|
|
36
|
+
updateNode(this, internals, shapeWithTextKindFields(node, kind));
|
|
40
37
|
}
|
|
41
38
|
} });
|
|
42
39
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shape-with-text.js","names":[],"sources":["../../src/figma-api/shape-with-text.ts"],"sourcesContent":["import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { createShapeWithText,
|
|
1
|
+
{"version":3,"file":"shape-with-text.js","names":[],"sources":["../../src/figma-api/shape-with-text.ts"],"sourcesContent":["import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { createShapeWithText, shapeWithTextKindFields } from '@pairdraw/scene-graph/generated'\nimport {\n isShapeWithTextType,\n SHAPE_WITH_TEXT_TYPES,\n type ShapeWithTextType\n} from '@pairdraw/scene-graph/shape-with-text'\n\nimport type { InterfaceTheme } from '#core/constants'\nimport { newLayerDefaults } from '#core/editor/shapes/defaults'\n\nimport type { NodeProxyInternals, ProxyThis } from './accessor-utils'\nimport { graph, prepareFollowedFieldEdit, raw, updateNode } from './accessor-utils'\n\n/** `value` as a kind for `node`, refused in the words Figma's plugin API refuses it with. */\nfunction checkedShapeType(node: SceneNode, value: unknown): ShapeWithTextType {\n if (node.type !== 'SHAPE_WITH_TEXT') {\n throw new Error('in set_shapeType: Only a shape with text has a shape type')\n }\n if (!isShapeWithTextType(value)) {\n const expected = SHAPE_WITH_TEXT_TYPES.map((kind) => `'${kind}'`).join(' | ')\n throw new Error(\n `in set_shapeType: Property \"shapeType\" failed validation: Invalid enum value. Expected ${expected}, received '${String(value)}'`\n )\n }\n return value\n}\n\n/**\n * A new, empty shape with text on the API's current page, as FigJam's plugin API creates it: an\n * ellipse 176 px square, painted as the shape tool paints a new shape. Measured in FigJam.\n */\nexport function newShapeWithText(api: {\n graph: SceneGraph\n currentPageId: string\n theme: InterfaceTheme\n}): SceneNode {\n return createShapeWithText(api.graph, api.currentPageId, {\n ...newLayerDefaults('SHAPE_WITH_TEXT', api.theme),\n shapeWithTextType: 'ELLIPSE'\n })\n}\n\n/** `shapeType`, a shape with text's FigJam kind; other layers have none. */\nexport function installShapeWithTextAccessors(\n prototype: object,\n internals: NodeProxyInternals\n): void {\n Object.defineProperties(prototype, {\n shapeType: {\n get(this: ProxyThis): ShapeWithTextType | undefined {\n const node = raw(this, internals)\n return node.type === 'SHAPE_WITH_TEXT' ? node.shapeWithTextType : undefined\n },\n set(this: ProxyThis, value: unknown) {\n const node = raw(this, internals)\n const kind = checkedShapeType(node, value)\n prepareFollowedFieldEdit(graph(this, internals), node, 'shapeType', 'shape-type')\n // The new kind lays the label out in its own area, as FigJam's shape switcher does.\n updateNode(this, internals, shapeWithTextKindFields(node, kind))\n }\n }\n })\n}\n"],"mappings":";;;;;;AAeA,SAAS,iBAAiB,MAAiB,OAAmC;CAC5E,IAAI,KAAK,SAAS,mBAChB,MAAM,IAAI,MAAM,2DAA2D;CAE7E,IAAI,CAAC,oBAAoB,KAAK,GAAG;EAC/B,MAAM,WAAW,sBAAsB,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,KAAK;EAC5E,MAAM,IAAI,MACR,0FAA0F,SAAS,cAAc,OAAO,KAAK,EAAE,EACjI;CACF;CACA,OAAO;AACT;;;;;AAMA,SAAgB,iBAAiB,KAInB;CACZ,OAAO,oBAAoB,IAAI,OAAO,IAAI,eAAe;EACvD,GAAG,iBAAiB,mBAAmB,IAAI,KAAK;EAChD,mBAAmB;CACrB,CAAC;AACH;;AAGA,SAAgB,8BACd,WACA,WACM;CACN,OAAO,iBAAiB,WAAW,EACjC,WAAW;EACT,MAAoD;GAClD,MAAM,OAAO,IAAI,MAAM,SAAS;GAChC,OAAO,KAAK,SAAS,oBAAoB,KAAK,oBAAoB,KAAA;EACpE;EACA,IAAqB,OAAgB;GACnC,MAAM,OAAO,IAAI,MAAM,SAAS;GAChC,MAAM,OAAO,iBAAiB,MAAM,KAAK;GACzC,yBAAyB,MAAM,MAAM,SAAS,GAAG,MAAM,aAAa,YAAY;GAEhF,WAAW,MAAM,WAAW,wBAAwB,MAAM,IAAI,CAAC;EACjE;CACF,EACF,CAAC;AACH"}
|
|
@@ -10,7 +10,7 @@ declare const FIGMA_API_HOST_MEMBERS: readonly ["graph", "wrapNode", "currentPag
|
|
|
10
10
|
* Members named as in Figma whose types do not match Figma's yet, mostly because node proxies do
|
|
11
11
|
* not implement every Figma node type; remove one when it matches.
|
|
12
12
|
*/
|
|
13
|
-
declare const FIGMA_API_INCOMPLETE_MEMBERS: readonly ["createComponentFromNode", "createPage", "currentPage", "getNodeById", "getNodeByIdAsync", "mixed", "root", "variables", "viewport"];
|
|
13
|
+
declare const FIGMA_API_INCOMPLETE_MEMBERS: readonly ["createComponentFromNode", "createPage", "currentPage", "getNodeById", "getNodeByIdAsync", "mixed", "root", "ui", "variables", "viewport"];
|
|
14
14
|
/** The `JSON.stringify` hook hosts use to report what a script returns. */
|
|
15
15
|
declare const SERIALIZATION_MEMBERS: readonly ["toJSON"];
|
|
16
16
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"surface.d.ts","names":[],"sources":["../../src/figma-api/surface.ts"],"mappings":";;;;;;;cAOa;;;;;cAiBA;;
|
|
1
|
+
{"version":3,"file":"surface.d.ts","names":[],"sources":["../../src/figma-api/surface.ts"],"mappings":";;;;;;;cAOa;;;;;cAiBA;;cAcA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"surface.js","names":[],"sources":["../../src/figma-api/surface.ts"],"sourcesContent":["/**\n * What `figma` and its objects have beyond Figma's Plugin API. `compatibility.ts` checks the\n * types against these lists and `tests/figma-api/surface.test.ts` checks what scripts can reach.\n * A feature Figma has no API for goes on `pairdraw`, never on these lists; entries only leave.\n */\n\n/** Members a host or tool wires up on `figma`, which scripts do not write against. */\nexport const FIGMA_API_HOST_MEMBERS = [\n 'graph',\n 'wrapNode',\n 'currentPageId',\n 'groupFitOptions',\n 'setRenderer',\n 'theme',\n 'exportImage',\n 'icons',\n 'rasterCodec',\n 'changeBaseline'\n] as const\n\n/**\n * Members named as in Figma whose types do not match Figma's yet, mostly because node proxies do\n * not implement every Figma node type; remove one when it matches.\n */\nexport const FIGMA_API_INCOMPLETE_MEMBERS = [\n 'createComponentFromNode',\n 'createPage',\n 'currentPage',\n 'getNodeById',\n 'getNodeByIdAsync',\n 'mixed',\n 'root',\n 'variables',\n 'viewport'\n] as const\n\n/** The `JSON.stringify` hook hosts use to report what a script returns. */\nexport const SERIALIZATION_MEMBERS = ['toJSON'] as const\n"],"mappings":";;;;;;;AAOA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,wBAAwB,CAAC,QAAQ"}
|
|
1
|
+
{"version":3,"file":"surface.js","names":[],"sources":["../../src/figma-api/surface.ts"],"sourcesContent":["/**\n * What `figma` and its objects have beyond Figma's Plugin API. `compatibility.ts` checks the\n * types against these lists and `tests/figma-api/surface.test.ts` checks what scripts can reach.\n * A feature Figma has no API for goes on `pairdraw`, never on these lists; entries only leave.\n */\n\n/** Members a host or tool wires up on `figma`, which scripts do not write against. */\nexport const FIGMA_API_HOST_MEMBERS = [\n 'graph',\n 'wrapNode',\n 'currentPageId',\n 'groupFitOptions',\n 'setRenderer',\n 'theme',\n 'exportImage',\n 'icons',\n 'rasterCodec',\n 'changeBaseline'\n] as const\n\n/**\n * Members named as in Figma whose types do not match Figma's yet, mostly because node proxies do\n * not implement every Figma node type; remove one when it matches.\n */\nexport const FIGMA_API_INCOMPLETE_MEMBERS = [\n 'createComponentFromNode',\n 'createPage',\n 'currentPage',\n 'getNodeById',\n 'getNodeByIdAsync',\n 'mixed',\n 'root',\n 'ui',\n 'variables',\n 'viewport'\n] as const\n\n/** The `JSON.stringify` hook hosts use to report what a script returns. */\nexport const SERIALIZATION_MEMBERS = ['toJSON'] as const\n"],"mappings":";;;;;;;AAOA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,wBAAwB,CAAC,QAAQ"}
|
package/dist/icons/svg.js
CHANGED
|
@@ -283,7 +283,7 @@ function scalePathInfos(pathInfos, scaleX, scaleY, offsetX = 0, offsetY = 0) {
|
|
|
283
283
|
if (path.transform && path.transform !== "none") transformedPath = transformedPath.transform(path.transform);
|
|
284
284
|
if (scaleX !== 1 || scaleY !== 1) transformedPath = transformedPath.scale(scaleX, scaleY);
|
|
285
285
|
if (offsetX !== 0 || offsetY !== 0) transformedPath = transformedPath.translate(offsetX, offsetY);
|
|
286
|
-
const scaledD = transformedPath.round(2).toString();
|
|
286
|
+
const scaledD = transformedPath.abs().unshort().unarc().round(2).toString();
|
|
287
287
|
const fill = normalizeSVGPaint(path.fill);
|
|
288
288
|
const stroke = normalizeSVGPaint(path.stroke);
|
|
289
289
|
return {
|
package/dist/icons/svg.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"svg.js","names":[],"sources":["../../src/icons/svg.ts"],"sourcesContent":["import { iconToSVG, type IconifyIcon } from '@iconify/utils'\nimport { DOMImplementation, type Document as XMLDocument, type Element } from '@xmldom/xmldom'\nimport svgpath from 'svgpath'\n\nimport { parseSVGPath } from '@pairdraw/scene-graph/parse-path'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { parseSVGFragment } from '#core/io/formats/svg/document'\n\nimport {\n combinedTransform,\n DEFAULT_PRESENTATION,\n isElement,\n normalizeSVGPaint,\n num,\n opacityValue,\n presentationFor,\n presentationVisible\n} from './svg/presentation'\nimport { elementLayer, type Scope, type Traversal } from './svg/scope'\nimport { textInfo } from './svg/text'\nimport type {\n IconData,\n IconPathInfo,\n SVGClipPathRegion,\n SVGElementLayer,\n SVGTextInfo\n} from './types'\n\ninterface SVGElementInput {\n type: string\n props: Readonly<Record<string, unknown>>\n children: readonly (SVGElementInput | string)[]\n}\n\nconst SVG_NAMESPACE = 'http://www.w3.org/2000/svg'\nconst JSX_ATTRIBUTE_NAMES: Readonly<Record<string, string>> = {\n className: 'class',\n fillRule: 'fill-rule',\n strokeLinecap: 'stroke-linecap',\n strokeLinejoin: 'stroke-linejoin',\n strokeWidth: 'stroke-width',\n xlinkHref: 'xlink:href'\n}\n\nconst SHAPE_NAMES = new Set(['path', 'circle', 'ellipse', 'rect', 'line', 'polygon', 'polyline'])\nconst NON_RENDERED_CONTAINERS = new Set(['defs', 'clipPath', 'mask', 'symbol'])\n\nfunction circleToD(element: Element): string | null {\n const cx = num(element, 'cx')\n const cy = num(element, 'cy')\n const r = num(element, 'r')\n return r > 0\n ? `M${cx - r},${cy}A${r},${r},0,1,0,${cx + r},${cy}A${r},${r},0,1,0,${cx - r},${cy}Z`\n : null\n}\n\nfunction ellipseToD(element: Element): string | null {\n const cx = num(element, 'cx')\n const cy = num(element, 'cy')\n const rx = num(element, 'rx')\n const ry = num(element, 'ry')\n return rx > 0 && ry > 0\n ? `M${cx - rx},${cy}A${rx},${ry},0,1,0,${cx + rx},${cy}A${rx},${ry},0,1,0,${cx - rx},${cy}Z`\n : null\n}\n\nfunction rectToD(element: Element): string | null {\n const x = num(element, 'x')\n const y = num(element, 'y')\n const width = num(element, 'width')\n const height = num(element, 'height')\n if (width <= 0 || height <= 0) return null\n const rx = Math.min(num(element, 'rx'), width / 2)\n const ry = Math.min(num(element, 'ry', rx), height / 2)\n if (rx > 0 || ry > 0) {\n const arcX = rx || ry\n const arcY = ry || rx\n return `M${x + arcX},${y}H${x + width - arcX}A${arcX},${arcY},0,0,1,${x + width},${y + arcY}V${y + height - arcY}A${arcX},${arcY},0,0,1,${x + width - arcX},${y + height}H${x + arcX}A${arcX},${arcY},0,0,1,${x},${y + height - arcY}V${y + arcY}A${arcX},${arcY},0,0,1,${x + arcX},${y}Z`\n }\n return `M${x},${y}H${x + width}V${y + height}H${x}Z`\n}\n\nfunction pointsToD(element: Element, close: boolean): string | null {\n const points = element.getAttribute('points')\n if (!points) return null\n const values = points\n .trim()\n .split(/[\\s,]+/)\n .map(Number)\n if (values.length < 4 || values.length % 2 !== 0) return null\n let path = `M${values[0]},${values[1]}`\n for (let index = 2; index < values.length; index += 2) {\n path += `L${values[index]},${values[index + 1]}`\n }\n return close ? `${path}Z` : path\n}\n\nfunction shapeToD(tagName: string, element: Element): string | null {\n switch (tagName) {\n case 'circle':\n return circleToD(element)\n case 'ellipse':\n return ellipseToD(element)\n case 'rect':\n return rectToD(element)\n case 'line':\n return `M${num(element, 'x1')},${num(element, 'y1')}L${num(element, 'x2')},${num(element, 'y2')}`\n case 'polygon':\n return pointsToD(element, true)\n case 'polyline':\n return pointsToD(element, false)\n default:\n return null\n }\n}\n\nfunction appendShapePath(\n tagName: string,\n element: Element,\n scope: Scope,\n layer: SVGElementLayer,\n result: IconPathInfo[]\n): void {\n const pathData = tagName === 'path' ? element.getAttribute('d') : shapeToD(tagName, element)\n if (!pathData) return\n const { presentation } = scope\n const strokeWidth = Number.parseFloat(presentation.strokeWidth)\n result.push({\n d: pathData,\n fill: normalizeSVGPaint(presentation.fill, presentation.color),\n stroke: normalizeSVGPaint(presentation.stroke, presentation.color),\n strokeWidth: Number.isFinite(strokeWidth) ? strokeWidth : 1,\n strokeCap: presentation.strokeCap,\n strokeJoin: presentation.strokeJoin,\n fillRule: presentation.fillRule === 'evenodd' ? 'EVENODD' : 'NONZERO',\n fillOpacity: opacityValue(presentation.fillOpacity),\n strokeOpacity: opacityValue(presentation.strokeOpacity),\n transform: scope.transform,\n clipPaths: scope.clipPaths.length > 0 ? scope.clipPaths : undefined,\n elements: [...scope.elements, layer]\n })\n}\n\nfunction collectUsePaths(\n element: Element,\n scope: Scope,\n traversal: Traversal,\n result: IconPathInfo[]\n): void {\n const x = num(element, 'x')\n const y = num(element, 'y')\n const transform =\n x !== 0 || y !== 0 ? `${scope.transform ?? ''} translate(${x} ${y})`.trim() : scope.transform\n const href = element.getAttribute('href') ?? element.getAttribute('xlink:href')\n const target = href?.startsWith('#') ? traversal.elementsById.get(href.slice(1)) : null\n if (target && !scope.useStack.has(target)) {\n collectPaths(\n target,\n { ...scope, transform, useStack: new Set([...scope.useStack, target]), referenced: true },\n traversal,\n result\n )\n }\n}\n\nfunction collectClipPath(\n value: string | null,\n parentTransform: string | null,\n traversal: Traversal\n): SVGClipPathRegion | null {\n const match = value?.trim().match(/^url\\(\\s*['\"]?#([^'\")\\s]+)['\"]?\\s*\\)$/)\n const target = match ? traversal.elementsById.get(match[1]) : null\n if (!match || !target || (target.localName || target.tagName) !== 'clipPath') return null\n\n const units =\n target.getAttribute('clipPathUnits') === 'objectBoundingBox'\n ? 'objectBoundingBox'\n : 'userSpaceOnUse'\n const paths: IconPathInfo[] = []\n collectPaths(\n target,\n {\n presentation: { ...DEFAULT_PRESENTATION, fill: '#000000' },\n transform: units === 'objectBoundingBox' ? null : parentTransform,\n clipPaths: [],\n elements: [],\n useStack: new Set([target]),\n referenced: true\n },\n traversal,\n paths\n )\n return {\n id: match[1],\n paths: paths.map((path) => ({\n d: path.d,\n fillRule: path.fillRule,\n transform: path.transform,\n visible: isSVGPathShown(path)\n })),\n units,\n visible: presentationVisible(presentationFor(target, DEFAULT_PRESENTATION))\n }\n}\n\nfunction collectPaths(\n element: Element,\n inherited: Scope,\n traversal: Traversal,\n result: IconPathInfo[]\n): void {\n const tagName = element.localName || element.tagName\n if (NON_RENDERED_CONTAINERS.has(tagName) && !inherited.referenced) return\n\n const transform = combinedTransform(inherited.transform, element)\n const ownClipPath = collectClipPath(element.getAttribute('clip-path'), transform, traversal)\n const clipPaths = ownClipPath ? [...inherited.clipPaths, ownClipPath] : inherited.clipPaths\n const clip = ownClipPath ? clipPaths.length - 1 : null\n const scope: Scope = {\n ...inherited,\n presentation: presentationFor(element, inherited.presentation),\n transform,\n clipPaths\n }\n\n if (tagName === 'text') {\n const text = textInfo(element, scope, result.length)\n if (text) {\n const layer = elementLayer(traversal, element, 'shape', scope, clip)\n traversal.texts.push({ ...text, elements: [...scope.elements, layer] })\n }\n return\n }\n if (SHAPE_NAMES.has(tagName)) {\n appendShapePath(\n tagName,\n element,\n scope,\n elementLayer(traversal, element, 'shape', scope, clip),\n result\n )\n return\n }\n // A group is a layer; another container only becomes one to keep its clip or opacity.\n const layer = elementLayer(traversal, element, 'group', scope, clip)\n const isLayer =\n tagName === 'g' || clip !== null || (layer.opacity !== 1 && element !== traversal.root)\n const childScope = isLayer ? { ...scope, elements: [...scope.elements, layer] } : scope\n if (tagName === 'use') {\n collectUsePaths(element, childScope, traversal, result)\n return\n }\n for (const child of Array.from(element.childNodes)) {\n if (isElement(child)) collectPaths(child, childScope, traversal, result)\n }\n}\n\nfunction appendSVGElement(svgDocument: XMLDocument, parent: Element, input: SVGElementInput): void {\n if (!/^[A-Za-z][\\w:.-]*$/.test(input.type)) return\n const element = svgDocument.createElementNS(SVG_NAMESPACE, input.type)\n for (const [propName, value] of Object.entries(input.props)) {\n if (typeof value !== 'string' && typeof value !== 'number') continue\n const attributeName = JSX_ATTRIBUTE_NAMES[propName] ?? propName\n element.setAttribute(attributeName, String(value))\n }\n if (input.type === 'path' && !element.hasAttribute('d') && typeof input.props.body === 'string') {\n element.setAttribute('d', input.props.body)\n }\n for (const child of input.children) {\n if (typeof child !== 'string') appendSVGElement(svgDocument, element, child)\n }\n parent.appendChild(element)\n}\n\n/** The shapes and text an SVG draws, in drawing order. */\nexport interface SVGContent {\n paths: IconPathInfo[]\n texts: SVGTextInfo[]\n}\n\nfunction collectDocument(root: Element): SVGContent {\n const elementsById = new Map<string, Element>()\n for (const element of Array.from(root.getElementsByTagName('*'))) {\n const id = element.getAttribute('id')\n if (id) elementsById.set(id, element)\n }\n const paths: IconPathInfo[] = []\n const traversal: Traversal = { root, elementsById, nextKey: 0, texts: [] }\n collectPaths(\n root,\n {\n presentation: DEFAULT_PRESENTATION,\n transform: null,\n clipPaths: [],\n elements: [],\n useStack: new Set(),\n referenced: false\n },\n traversal,\n paths\n )\n return { paths, texts: traversal.texts }\n}\n\nexport function extractPathsFromElements(\n elements: readonly SVGElementInput[],\n rootProps: Readonly<Record<string, unknown>> = {}\n): IconPathInfo[] {\n const svgDocument = new DOMImplementation().createDocument(SVG_NAMESPACE, 'svg')\n const root = svgDocument.documentElement\n if (!root) return []\n appendSVGElement(svgDocument, root, { type: 'svg', props: rootProps, children: elements })\n return collectDocument(root).paths.filter(isSVGPathShown)\n}\n\nexport function extractSVGContent(svgBody: string): SVGContent {\n const root = parseSVGFragment(svgBody)?.documentElement\n return root ? collectDocument(root) : { paths: [], texts: [] }\n}\n\n/** Whether a shape shows: a hidden element hides everything in it, as a hidden layer does. */\nexport function isSVGPathShown(path: Pick<IconPathInfo, 'elements'>): boolean {\n return path.elements.every((element) => element.visible)\n}\n\n/** The shapes an SVG shows, for drawing it as one icon rather than importing its layers. */\nexport function extractPaths(svgBody: string): IconPathInfo[] {\n return extractSVGContent(svgBody).paths.filter(isSVGPathShown)\n}\n\n/**\n * An Iconify icon at `size`. Iconify's own rendering applies its box, defaulting to 16, and any\n * turn or flip, before the shapes are placed in the icon box as SVG import places them.\n */\nexport function buildIconData(\n icon: IconifyIcon,\n prefix: string,\n iconName: string,\n size: number\n): IconData {\n const rendered = iconToSVG(icon)\n const [x, y, width, height] = rendered.viewBox\n // As a browser draws the SVG: one scale for both axes, centered in the icon box, and the box's\n // own origin moved to the box's top-left.\n const scale = Math.min(size / width, size / height)\n const offsetX = -x * scale + (size - width * scale) / 2\n const offsetY = -y * scale + (size - height * scale) / 2\n\n return {\n prefix,\n name: iconName,\n width: size,\n height: size,\n paths: scalePathInfos(extractPaths(rendered.body), scale, scale, offsetX, offsetY)\n }\n}\n\nfunction transformStrokeScale(transform: string | null | undefined): number {\n if (!transform || transform === 'none') return 1\n\n const points: Vector[] = []\n svgpath('M0 0 L1 0 M0 0 L0 1')\n .transform(transform)\n .abs()\n .iterate((segment) => {\n if (segment[0] === 'M' || segment[0] === 'L') {\n points.push({ x: segment[1], y: segment[2] })\n }\n })\n if (points.length < 4) return 1\n\n const xScale = Math.hypot(points[1].x - points[0].x, points[1].y - points[0].y)\n const yScale = Math.hypot(points[3].x - points[2].x, points[3].y - points[2].y)\n return Math.min(xScale, yScale)\n}\n\n/** Scale extracted SVG path info into IconData paths (shared by buildIconData and design-jsx <svg>). */\nexport function scalePathInfos(\n pathInfos: IconPathInfo[],\n scaleX: number,\n scaleY: number,\n offsetX = 0,\n offsetY = 0\n): IconData['paths'] {\n return pathInfos.map((path) => {\n let transformedPath = svgpath(path.d)\n if (path.transform && path.transform !== 'none') {\n transformedPath = transformedPath.transform(path.transform)\n }\n if (scaleX !== 1 || scaleY !== 1) transformedPath = transformedPath.scale(scaleX, scaleY)\n if (offsetX !== 0 || offsetY !== 0)\n transformedPath = transformedPath.translate(offsetX, offsetY)\n const scaledD = transformedPath.round(2).toString()\n const fill = normalizeSVGPaint(path.fill)\n const stroke = normalizeSVGPaint(path.stroke)\n return {\n // A stroke would also trace the closing edge of an open subpath in the fill region.\n vectorNetwork: parseSVGPath(scaledD, path.fillRule, {\n includeOpenRegions: fill !== null && stroke === null\n }),\n fill,\n stroke,\n strokeWidth:\n path.strokeWidth * transformStrokeScale(path.transform) * Math.min(scaleX, scaleY),\n strokeCap: path.strokeCap,\n strokeJoin: path.strokeJoin\n }\n })\n}\n"],"mappings":";;;;;;;;;AAmCA,MAAM,gBAAgB;AACtB,MAAM,sBAAwD;CAC5D,WAAW;CACX,UAAU;CACV,eAAe;CACf,gBAAgB;CAChB,aAAa;CACb,WAAW;AACb;AAEA,MAAM,8BAAc,IAAI,IAAI;CAAC;CAAQ;CAAU;CAAW;CAAQ;CAAQ;CAAW;AAAU,CAAC;AAChG,MAAM,0CAA0B,IAAI,IAAI;CAAC;CAAQ;CAAY;CAAQ;AAAQ,CAAC;AAE9E,SAAS,UAAU,SAAiC;CAClD,MAAM,KAAK,IAAI,SAAS,IAAI;CAC5B,MAAM,KAAK,IAAI,SAAS,IAAI;CAC5B,MAAM,IAAI,IAAI,SAAS,GAAG;CAC1B,OAAO,IAAI,IACP,IAAI,KAAK,EAAE,GAAG,GAAG,GAAG,EAAE,GAAG,EAAE,SAAS,KAAK,EAAE,GAAG,GAAG,GAAG,EAAE,GAAG,EAAE,SAAS,KAAK,EAAE,GAAG,GAAG,KACjF;AACN;AAEA,SAAS,WAAW,SAAiC;CACnD,MAAM,KAAK,IAAI,SAAS,IAAI;CAC5B,MAAM,KAAK,IAAI,SAAS,IAAI;CAC5B,MAAM,KAAK,IAAI,SAAS,IAAI;CAC5B,MAAM,KAAK,IAAI,SAAS,IAAI;CAC5B,OAAO,KAAK,KAAK,KAAK,IAClB,IAAI,KAAK,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,SAAS,KAAK,GAAG,G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,CAAC;CACH,IAAI,OAAO,SAAS,GAAG,OAAO;CAE9B,MAAM,SAAS,KAAK,MAAM,OAAO,EAAE,CAAC,IAAI,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,IAAI,OAAO,EAAE,CAAC,CAAC;CAC9E,MAAM,SAAS,KAAK,MAAM,OAAO,EAAE,CAAC,IAAI,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,IAAI,OAAO,EAAE,CAAC,CAAC;CAC9E,OAAO,KAAK,IAAI,QAAQ,MAAM;AAChC;;AAGA,SAAgB,eACd,WACA,QACA,QACA,UAAU,GACV,UAAU,GACS;CACnB,OAAO,UAAU,KAAK,SAAS;EAC7B,IAAI,kBAAkB,QAAQ,KAAK,CAAC;EACpC,IAAI,KAAK,aAAa,KAAK,cAAc,QACvC,kBAAkB,gBAAgB,UAAU,KAAK,SAAS;EAE5D,IAAI,WAAW,KAAK,WAAW,GAAG,kBAAkB,gBAAgB,MAAM,QAAQ,MAAM;EACxF,IAAI,YAAY,KAAK,YAAY,GAC/B,kBAAkB,gBAAgB,UAAU,SAAS,OAAO;EAC9D,MAAM,UAAU,gBAAgB,MAAM,CAAC,CAAC,CAAC,SAAS;EAClD,MAAM,OAAO,kBAAkB,KAAK,IAAI;EACxC,MAAM,SAAS,kBAAkB,KAAK,MAAM;EAC5C,OAAO;GAEL,eAAe,aAAa,SAAS,KAAK,UAAU,EAClD,oBAAoB,SAAS,QAAQ,WAAW,KAClD,CAAC;GACD;GACA;GACA,aACE,KAAK,cAAc,qBAAqB,KAAK,SAAS,IAAI,KAAK,IAAI,QAAQ,MAAM;GACnF,WAAW,KAAK;GAChB,YAAY,KAAK;EACnB;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"svg.js","names":[],"sources":["../../src/icons/svg.ts"],"sourcesContent":["import { iconToSVG, type IconifyIcon } from '@iconify/utils'\nimport { DOMImplementation, type Document as XMLDocument, type Element } from '@xmldom/xmldom'\nimport svgpath from 'svgpath'\n\nimport { parseSVGPath } from '@pairdraw/scene-graph/parse-path'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { parseSVGFragment } from '#core/io/formats/svg/document'\n\nimport {\n combinedTransform,\n DEFAULT_PRESENTATION,\n isElement,\n normalizeSVGPaint,\n num,\n opacityValue,\n presentationFor,\n presentationVisible\n} from './svg/presentation'\nimport { elementLayer, type Scope, type Traversal } from './svg/scope'\nimport { textInfo } from './svg/text'\nimport type {\n IconData,\n IconPathInfo,\n SVGClipPathRegion,\n SVGElementLayer,\n SVGTextInfo\n} from './types'\n\ninterface SVGElementInput {\n type: string\n props: Readonly<Record<string, unknown>>\n children: readonly (SVGElementInput | string)[]\n}\n\nconst SVG_NAMESPACE = 'http://www.w3.org/2000/svg'\nconst JSX_ATTRIBUTE_NAMES: Readonly<Record<string, string>> = {\n className: 'class',\n fillRule: 'fill-rule',\n strokeLinecap: 'stroke-linecap',\n strokeLinejoin: 'stroke-linejoin',\n strokeWidth: 'stroke-width',\n xlinkHref: 'xlink:href'\n}\n\nconst SHAPE_NAMES = new Set(['path', 'circle', 'ellipse', 'rect', 'line', 'polygon', 'polyline'])\nconst NON_RENDERED_CONTAINERS = new Set(['defs', 'clipPath', 'mask', 'symbol'])\n\nfunction circleToD(element: Element): string | null {\n const cx = num(element, 'cx')\n const cy = num(element, 'cy')\n const r = num(element, 'r')\n return r > 0\n ? `M${cx - r},${cy}A${r},${r},0,1,0,${cx + r},${cy}A${r},${r},0,1,0,${cx - r},${cy}Z`\n : null\n}\n\nfunction ellipseToD(element: Element): string | null {\n const cx = num(element, 'cx')\n const cy = num(element, 'cy')\n const rx = num(element, 'rx')\n const ry = num(element, 'ry')\n return rx > 0 && ry > 0\n ? `M${cx - rx},${cy}A${rx},${ry},0,1,0,${cx + rx},${cy}A${rx},${ry},0,1,0,${cx - rx},${cy}Z`\n : null\n}\n\nfunction rectToD(element: Element): string | null {\n const x = num(element, 'x')\n const y = num(element, 'y')\n const width = num(element, 'width')\n const height = num(element, 'height')\n if (width <= 0 || height <= 0) return null\n const rx = Math.min(num(element, 'rx'), width / 2)\n const ry = Math.min(num(element, 'ry', rx), height / 2)\n if (rx > 0 || ry > 0) {\n const arcX = rx || ry\n const arcY = ry || rx\n return `M${x + arcX},${y}H${x + width - arcX}A${arcX},${arcY},0,0,1,${x + width},${y + arcY}V${y + height - arcY}A${arcX},${arcY},0,0,1,${x + width - arcX},${y + height}H${x + arcX}A${arcX},${arcY},0,0,1,${x},${y + height - arcY}V${y + arcY}A${arcX},${arcY},0,0,1,${x + arcX},${y}Z`\n }\n return `M${x},${y}H${x + width}V${y + height}H${x}Z`\n}\n\nfunction pointsToD(element: Element, close: boolean): string | null {\n const points = element.getAttribute('points')\n if (!points) return null\n const values = points\n .trim()\n .split(/[\\s,]+/)\n .map(Number)\n if (values.length < 4 || values.length % 2 !== 0) return null\n let path = `M${values[0]},${values[1]}`\n for (let index = 2; index < values.length; index += 2) {\n path += `L${values[index]},${values[index + 1]}`\n }\n return close ? `${path}Z` : path\n}\n\nfunction shapeToD(tagName: string, element: Element): string | null {\n switch (tagName) {\n case 'circle':\n return circleToD(element)\n case 'ellipse':\n return ellipseToD(element)\n case 'rect':\n return rectToD(element)\n case 'line':\n return `M${num(element, 'x1')},${num(element, 'y1')}L${num(element, 'x2')},${num(element, 'y2')}`\n case 'polygon':\n return pointsToD(element, true)\n case 'polyline':\n return pointsToD(element, false)\n default:\n return null\n }\n}\n\nfunction appendShapePath(\n tagName: string,\n element: Element,\n scope: Scope,\n layer: SVGElementLayer,\n result: IconPathInfo[]\n): void {\n const pathData = tagName === 'path' ? element.getAttribute('d') : shapeToD(tagName, element)\n if (!pathData) return\n const { presentation } = scope\n const strokeWidth = Number.parseFloat(presentation.strokeWidth)\n result.push({\n d: pathData,\n fill: normalizeSVGPaint(presentation.fill, presentation.color),\n stroke: normalizeSVGPaint(presentation.stroke, presentation.color),\n strokeWidth: Number.isFinite(strokeWidth) ? strokeWidth : 1,\n strokeCap: presentation.strokeCap,\n strokeJoin: presentation.strokeJoin,\n fillRule: presentation.fillRule === 'evenodd' ? 'EVENODD' : 'NONZERO',\n fillOpacity: opacityValue(presentation.fillOpacity),\n strokeOpacity: opacityValue(presentation.strokeOpacity),\n transform: scope.transform,\n clipPaths: scope.clipPaths.length > 0 ? scope.clipPaths : undefined,\n elements: [...scope.elements, layer]\n })\n}\n\nfunction collectUsePaths(\n element: Element,\n scope: Scope,\n traversal: Traversal,\n result: IconPathInfo[]\n): void {\n const x = num(element, 'x')\n const y = num(element, 'y')\n const transform =\n x !== 0 || y !== 0 ? `${scope.transform ?? ''} translate(${x} ${y})`.trim() : scope.transform\n const href = element.getAttribute('href') ?? element.getAttribute('xlink:href')\n const target = href?.startsWith('#') ? traversal.elementsById.get(href.slice(1)) : null\n if (target && !scope.useStack.has(target)) {\n collectPaths(\n target,\n { ...scope, transform, useStack: new Set([...scope.useStack, target]), referenced: true },\n traversal,\n result\n )\n }\n}\n\nfunction collectClipPath(\n value: string | null,\n parentTransform: string | null,\n traversal: Traversal\n): SVGClipPathRegion | null {\n const match = value?.trim().match(/^url\\(\\s*['\"]?#([^'\")\\s]+)['\"]?\\s*\\)$/)\n const target = match ? traversal.elementsById.get(match[1]) : null\n if (!match || !target || (target.localName || target.tagName) !== 'clipPath') return null\n\n const units =\n target.getAttribute('clipPathUnits') === 'objectBoundingBox'\n ? 'objectBoundingBox'\n : 'userSpaceOnUse'\n const paths: IconPathInfo[] = []\n collectPaths(\n target,\n {\n presentation: { ...DEFAULT_PRESENTATION, fill: '#000000' },\n transform: units === 'objectBoundingBox' ? null : parentTransform,\n clipPaths: [],\n elements: [],\n useStack: new Set([target]),\n referenced: true\n },\n traversal,\n paths\n )\n return {\n id: match[1],\n paths: paths.map((path) => ({\n d: path.d,\n fillRule: path.fillRule,\n transform: path.transform,\n visible: isSVGPathShown(path)\n })),\n units,\n visible: presentationVisible(presentationFor(target, DEFAULT_PRESENTATION))\n }\n}\n\nfunction collectPaths(\n element: Element,\n inherited: Scope,\n traversal: Traversal,\n result: IconPathInfo[]\n): void {\n const tagName = element.localName || element.tagName\n if (NON_RENDERED_CONTAINERS.has(tagName) && !inherited.referenced) return\n\n const transform = combinedTransform(inherited.transform, element)\n const ownClipPath = collectClipPath(element.getAttribute('clip-path'), transform, traversal)\n const clipPaths = ownClipPath ? [...inherited.clipPaths, ownClipPath] : inherited.clipPaths\n const clip = ownClipPath ? clipPaths.length - 1 : null\n const scope: Scope = {\n ...inherited,\n presentation: presentationFor(element, inherited.presentation),\n transform,\n clipPaths\n }\n\n if (tagName === 'text') {\n const text = textInfo(element, scope, result.length)\n if (text) {\n const layer = elementLayer(traversal, element, 'shape', scope, clip)\n traversal.texts.push({ ...text, elements: [...scope.elements, layer] })\n }\n return\n }\n if (SHAPE_NAMES.has(tagName)) {\n appendShapePath(\n tagName,\n element,\n scope,\n elementLayer(traversal, element, 'shape', scope, clip),\n result\n )\n return\n }\n // A group is a layer; another container only becomes one to keep its clip or opacity.\n const layer = elementLayer(traversal, element, 'group', scope, clip)\n const isLayer =\n tagName === 'g' || clip !== null || (layer.opacity !== 1 && element !== traversal.root)\n const childScope = isLayer ? { ...scope, elements: [...scope.elements, layer] } : scope\n if (tagName === 'use') {\n collectUsePaths(element, childScope, traversal, result)\n return\n }\n for (const child of Array.from(element.childNodes)) {\n if (isElement(child)) collectPaths(child, childScope, traversal, result)\n }\n}\n\nfunction appendSVGElement(svgDocument: XMLDocument, parent: Element, input: SVGElementInput): void {\n if (!/^[A-Za-z][\\w:.-]*$/.test(input.type)) return\n const element = svgDocument.createElementNS(SVG_NAMESPACE, input.type)\n for (const [propName, value] of Object.entries(input.props)) {\n if (typeof value !== 'string' && typeof value !== 'number') continue\n const attributeName = JSX_ATTRIBUTE_NAMES[propName] ?? propName\n element.setAttribute(attributeName, String(value))\n }\n if (input.type === 'path' && !element.hasAttribute('d') && typeof input.props.body === 'string') {\n element.setAttribute('d', input.props.body)\n }\n for (const child of input.children) {\n if (typeof child !== 'string') appendSVGElement(svgDocument, element, child)\n }\n parent.appendChild(element)\n}\n\n/** The shapes and text an SVG draws, in drawing order. */\nexport interface SVGContent {\n paths: IconPathInfo[]\n texts: SVGTextInfo[]\n}\n\nfunction collectDocument(root: Element): SVGContent {\n const elementsById = new Map<string, Element>()\n for (const element of Array.from(root.getElementsByTagName('*'))) {\n const id = element.getAttribute('id')\n if (id) elementsById.set(id, element)\n }\n const paths: IconPathInfo[] = []\n const traversal: Traversal = { root, elementsById, nextKey: 0, texts: [] }\n collectPaths(\n root,\n {\n presentation: DEFAULT_PRESENTATION,\n transform: null,\n clipPaths: [],\n elements: [],\n useStack: new Set(),\n referenced: false\n },\n traversal,\n paths\n )\n return { paths, texts: traversal.texts }\n}\n\nexport function extractPathsFromElements(\n elements: readonly SVGElementInput[],\n rootProps: Readonly<Record<string, unknown>> = {}\n): IconPathInfo[] {\n const svgDocument = new DOMImplementation().createDocument(SVG_NAMESPACE, 'svg')\n const root = svgDocument.documentElement\n if (!root) return []\n appendSVGElement(svgDocument, root, { type: 'svg', props: rootProps, children: elements })\n return collectDocument(root).paths.filter(isSVGPathShown)\n}\n\nexport function extractSVGContent(svgBody: string): SVGContent {\n const root = parseSVGFragment(svgBody)?.documentElement\n return root ? collectDocument(root) : { paths: [], texts: [] }\n}\n\n/** Whether a shape shows: a hidden element hides everything in it, as a hidden layer does. */\nexport function isSVGPathShown(path: Pick<IconPathInfo, 'elements'>): boolean {\n return path.elements.every((element) => element.visible)\n}\n\n/** The shapes an SVG shows, for drawing it as one icon rather than importing its layers. */\nexport function extractPaths(svgBody: string): IconPathInfo[] {\n return extractSVGContent(svgBody).paths.filter(isSVGPathShown)\n}\n\n/**\n * An Iconify icon at `size`. Iconify's own rendering applies its box, defaulting to 16, and any\n * turn or flip, before the shapes are placed in the icon box as SVG import places them.\n */\nexport function buildIconData(\n icon: IconifyIcon,\n prefix: string,\n iconName: string,\n size: number\n): IconData {\n const rendered = iconToSVG(icon)\n const [x, y, width, height] = rendered.viewBox\n // As a browser draws the SVG: one scale for both axes, centered in the icon box, and the box's\n // own origin moved to the box's top-left.\n const scale = Math.min(size / width, size / height)\n const offsetX = -x * scale + (size - width * scale) / 2\n const offsetY = -y * scale + (size - height * scale) / 2\n\n return {\n prefix,\n name: iconName,\n width: size,\n height: size,\n paths: scalePathInfos(extractPaths(rendered.body), scale, scale, offsetX, offsetY)\n }\n}\n\nfunction transformStrokeScale(transform: string | null | undefined): number {\n if (!transform || transform === 'none') return 1\n\n const points: Vector[] = []\n svgpath('M0 0 L1 0 M0 0 L0 1')\n .transform(transform)\n .abs()\n .iterate((segment) => {\n if (segment[0] === 'M' || segment[0] === 'L') {\n points.push({ x: segment[1], y: segment[2] })\n }\n })\n if (points.length < 4) return 1\n\n const xScale = Math.hypot(points[1].x - points[0].x, points[1].y - points[0].y)\n const yScale = Math.hypot(points[3].x - points[2].x, points[3].y - points[2].y)\n return Math.min(xScale, yScale)\n}\n\n/** Scale extracted SVG path info into IconData paths (shared by buildIconData and design-jsx <svg>). */\nexport function scalePathInfos(\n pathInfos: IconPathInfo[],\n scaleX: number,\n scaleY: number,\n offsetX = 0,\n offsetY = 0\n): IconData['paths'] {\n return pathInfos.map((path) => {\n let transformedPath = svgpath(path.d)\n if (path.transform && path.transform !== 'none') {\n transformedPath = transformedPath.transform(path.transform)\n }\n if (scaleX !== 1 || scaleY !== 1) transformedPath = transformedPath.scale(scaleX, scaleY)\n if (offsetX !== 0 || offsetY !== 0)\n transformedPath = transformedPath.translate(offsetX, offsetY)\n // Arcs become curves before rounding, as the path parser would turn them anyway: rounding an\n // arc's own end can put it on its start, and a degenerate arc draws nothing.\n const scaledD = transformedPath.abs().unshort().unarc().round(2).toString()\n const fill = normalizeSVGPaint(path.fill)\n const stroke = normalizeSVGPaint(path.stroke)\n return {\n // A stroke would also trace the closing edge of an open subpath in the fill region.\n vectorNetwork: parseSVGPath(scaledD, path.fillRule, {\n includeOpenRegions: fill !== null && stroke === null\n }),\n fill,\n stroke,\n strokeWidth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,CAAC,GAAG,OAAO,EAAE,CAAC,IAAI,OAAO,EAAE,CAAC,CAAC;CAC9E,OAAO,KAAK,IAAI,QAAQ,MAAM;AAChC;;AAGA,SAAgB,eACd,WACA,QACA,QACA,UAAU,GACV,UAAU,GACS;CACnB,OAAO,UAAU,KAAK,SAAS;EAC7B,IAAI,kBAAkB,QAAQ,KAAK,CAAC;EACpC,IAAI,KAAK,aAAa,KAAK,cAAc,QACvC,kBAAkB,gBAAgB,UAAU,KAAK,SAAS;EAE5D,IAAI,WAAW,KAAK,WAAW,GAAG,kBAAkB,gBAAgB,MAAM,QAAQ,MAAM;EACxF,IAAI,YAAY,KAAK,YAAY,GAC/B,kBAAkB,gBAAgB,UAAU,SAAS,OAAO;EAG9D,MAAM,UAAU,gBAAgB,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;EAC1E,MAAM,OAAO,kBAAkB,KAAK,IAAI;EACxC,MAAM,SAAS,kBAAkB,KAAK,MAAM;EAC5C,OAAO;GAEL,eAAe,aAAa,SAAS,KAAK,UAAU,EAClD,oBAAoB,SAAS,QAAQ,WAAW,KAClD,CAAC;GACD;GACA;GACA,aACE,KAAK,cAAc,qBAAqB,KAAK,SAAS,IAAI,KAAK,IAAI,QAAQ,MAAM;GACnF,WAAW,KAAK;GAChB,YAAY,KAAK;EACnB;CACF,CAAC;AACH"}
|
|
@@ -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): "
|
|
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":"index.d.ts","names":[],"sources":["../../../../src/io/formats/drawio/index.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/io/formats/drawio/index.ts"],"mappings":";;;;;;;;;iBAoOgB,mBAAmB,MAAM,aAAa"}
|
|
@@ -110,7 +110,7 @@ var PageBuilder = class {
|
|
|
110
110
|
for (const cell of page.cells) place(cell);
|
|
111
111
|
const layerOf = (cellId) => this.layers.get(cellId);
|
|
112
112
|
for (const pending of this.edges) for (const extra of bindEdge(graph, pending, layerOf)) this.edgeText(pending, extra);
|
|
113
|
-
|
|
113
|
+
fitEnclosingGroups(graph, this.groups);
|
|
114
114
|
}
|
|
115
115
|
vertex(cell, parentId, hasChildren) {
|
|
116
116
|
const { graph } = this;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/io/formats/drawio/index.ts"],"sourcesContent":["import type { DrawIOCell, DrawIOFile, DrawIOPage, DrawIOStyle } from '@pairdraw/drawio'\nimport { SceneGraph, type SceneNode } from '@pairdraw/scene-graph'\nimport { connectorRoute, placeConnectorLabel } from '@pairdraw/scene-graph/connectors'\nimport { createShapeWithText } from '@pairdraw/scene-graph/generated'\nimport { fitEnclosingGroups } from '@pairdraw/scene-graph/group-bounds'\n\nimport { bindEdge, createEdge, labelPositionOf, type PendingEdge } from './edges'\nimport { readLabel } from './label'\nimport { labelFields, labelFormat, shapePaint } from './paint'\nimport { shapeName, vertexKind } from './shapes'\n\n/** A cell's label as text and runs, in the cell's own style. */\nfunction labelOf(cell: DrawIOCell) {\n const format = labelFormat(cell.style)\n return { format, ...readLabel(cell.value, cell.style.values.html === '1', format) }\n}\n\n/**\n * A cell's turn and mirrors as a layer's. draw.io mirrors a cell about its centre and then turns\n * it, negating the turn when it mirrors one way only; a layer turns and then mirrors, so that\n * turn is the layer's own. `ownFlipH` is a mirror the shape itself stands for, as a left\n * parallelogram is draw.io's mirrored one.\n */\nfunction placementOf(style: DrawIOStyle, ownFlipH = false) {\n const flipX = style.values.flipH === '1' && !ownFlipH\n const flipY = style.values.flipV === '1'\n const turn = Number(style.values.rotation ?? 0) || 0\n return { flipX, flipY, rotation: flipX === flipY ? turn : -turn }\n}\n\n/** The first line of a label, as a layer's name. */\nfunction nameOf(text: string, fallback: string): string {\n return text.split('\\n')[0]?.trim() || fallback\n}\n\n/**\n * The name Pairdraw wrote into a cell's style. draw.io has no field of its own for a layer whose\n * cell draws no text, and a text cell's label is its content, so the name travels beside them.\n */\nfunction writtenName(style: DrawIOStyle): string | undefined {\n const value = style.values.pairdrawName\n if (value === undefined) return undefined\n try {\n return decodeURIComponent(value)\n } catch {\n return undefined\n }\n}\n\n/** A layer's name: the one Pairdraw wrote, else the first line of its label. */\nfunction layerName(style: DrawIOStyle, text: string, fallback: string): string {\n return writtenName(style) ?? nameOf(text, fallback)\n}\n\n/** Builds one draw.io page's cells into `pageId`, in draw.io's drawing order. */\nclass PageBuilder {\n /** The layer each draw.io cell or layer became. */\n private readonly layers = new Map<string, string>()\n private readonly edges: PendingEdge[] = []\n private readonly groups: string[] = []\n\n constructor(\n private readonly graph: SceneGraph,\n private readonly page: DrawIOPage,\n private readonly pageId: string\n ) {}\n\n build() {\n const { graph, page, pageId } = this\n // One layer draws straight onto the page; several each become a group named after it, as\n // does a single layer that is hidden or locked, so it stays so.\n for (const [index, layer] of page.layers.entries()) {\n if (page.layers.length === 1 && layer.visible && !layer.locked) {\n this.layers.set(layer.id, pageId)\n continue\n }\n const group = graph.createNode('GROUP', pageId, {\n name: layer.name || `Layer ${index + 1}`,\n visible: layer.visible,\n locked: layer.locked\n })\n this.layers.set(layer.id, group.id)\n this.groups.push(group.id)\n }\n const parents = new Set(page.cells.map((cell) => cell.parent))\n const labelsOf = new Map<string, DrawIOCell[]>()\n const edgeIds = new Set(\n page.cells.filter((cell) => cell.kind === 'edge').map((cell) => cell.id)\n )\n for (const cell of page.cells) {\n // A vertex inside an edge is one of its labels.\n if (edgeIds.has(cell.parent)) {\n const labels = labelsOf.get(cell.parent) ?? []\n labels.push(cell)\n labelsOf.set(cell.parent, labels)\n }\n }\n const cells = new Map(page.cells.map((cell) => [cell.id, cell]))\n const placing = new Set<string>()\n const place = (cell: DrawIOCell) => {\n if (edgeIds.has(cell.parent) || this.layers.has(cell.id) || placing.has(cell.id)) return\n placing.add(cell.id)\n // A cell listed before its parent, as draw.io's format allows, waits for the parent.\n const parent = cells.get(cell.parent)\n if (parent) place(parent)\n const parentId = this.layers.get(cell.parent) ?? pageId\n if (cell.kind === 'edge') {\n const pending = createEdge(graph, parentId, cell, labelsOf.get(cell.id) ?? [])\n this.layers.set(cell.id, pending.connector.id)\n this.edges.push(pending)\n return\n }\n const node = this.vertex(cell, parentId, parents.has(cell.id))\n this.layers.set(cell.id, node.id)\n }\n for (const cell of page.cells) place(cell)\n const layerOf = (cellId: string) => this.layers.get(cellId)\n for (const pending of this.edges) {\n for (const extra of bindEdge(graph, pending, layerOf)) this.edgeText(pending, extra)\n }\n // Groups fit around what they hold, the innermost first.\n for (const id of this.groups.toReversed()) fitEnclosingGroups(graph, [id])\n }\n\n private vertex(cell: DrawIOCell, parentId: string, hasChildren: boolean): SceneNode {\n const { graph } = this\n const { x, y, width, height } = cell.geometry\n const kind = vertexKind(cell.style, hasChildren)\n const label = labelOf(cell)\n const box = { x, y, width, height, visible: cell.visible }\n if (kind.type === 'TEXT') {\n return graph.createNode('TEXT', parentId, {\n ...box,\n ...placementOf(cell.style),\n name: layerName(cell.style, label.text, 'Text'),\n ...labelFields(cell.style, label.format),\n text: label.text,\n styleRuns: label.runs,\n textAutoResize: 'NONE'\n })\n }\n if (kind.type === 'FRAME') {\n return graph.createNode('FRAME', parentId, {\n ...box,\n ...shapePaint(cell.style),\n name: layerName(cell.style, label.text, 'Frame')\n })\n }\n if (kind.type === 'RECTANGLE') {\n const radius = Number.parseFloat(cell.style.values.pairdrawCornerRadius ?? '')\n return graph.createNode('RECTANGLE', parentId, {\n ...box,\n ...shapePaint(cell.style),\n ...(radius > 0 ? { cornerRadius: radius } : {}),\n name: layerName(cell.style, label.text, 'Rectangle')\n })\n }\n if (kind.type === 'SECTION') {\n return graph.createNode('SECTION', parentId, {\n ...box,\n ...shapePaint(cell.style),\n name: nameOf(label.text, 'Section')\n })\n }\n if (kind.type === 'GROUP') {\n const group = graph.createNode('GROUP', parentId, {\n ...box,\n name: nameOf(label.text, 'Group')\n })\n this.groups.push(group.id)\n return group\n }\n // A shape turned a quarter swaps its sides, about the centre of the box it fills.\n const quarter = Math.abs(kind.rotation) === 90\n const placed = quarter\n ? { x: x + (width - height) / 2, y: y + (height - width) / 2, width: height, height: width }\n : { x, y, width, height }\n const known = shapeName(cell.style)\n const own = placementOf(cell.style, kind.shape === 'PARALLELOGRAM_LEFT')\n return createShapeWithText(\n graph,\n parentId,\n {\n ...placed,\n visible: cell.visible,\n ...own,\n rotation: own.rotation + kind.rotation,\n shapeWithTextType: kind.shape,\n // draw.io sized it, so it keeps its size, as a FigJam shape whose height was set does.\n shapeTruncates: true,\n ...shapePaint(cell.style),\n // A stencil FigJam has no shape for keeps its name, so it can be found and replaced.\n name: kind.stencil ? known : nameOf(label.text, 'Shape with text')\n },\n { ...labelFields(cell.style, label.format), text: label.text, styleRuns: label.runs }\n )\n }\n\n /** A label beyond an edge's first, as text where draw.io placed it along the edge. */\n private edgeText({ connector }: PendingEdge, cell: DrawIOCell) {\n const { graph } = this\n const node = graph.getNode(connector.id)\n const route = node ? connectorRoute(graph, node) : null\n if (!node?.parentId || !route) return\n const label = labelOf(cell)\n const size = { width: cell.geometry.width, height: cell.geometry.height }\n const plate = placeConnectorLabel(route.pieces, size, labelPositionOf(cell.geometry.x))?.plate\n const offset = cell.geometry.offset ?? { x: 0, y: 0 }\n graph.createNode('TEXT', node.parentId, {\n x: (plate?.x ?? 0) + offset.x,\n y: (plate?.y ?? 0) + offset.y,\n visible: cell.visible,\n name: nameOf(label.text, 'Text'),\n ...labelFields(cell.style, label.format),\n text: label.text,\n styleRuns: label.runs,\n textAutoResize: 'WIDTH_AND_HEIGHT'\n })\n }\n}\n\n/**\n * A draw.io file as layers: each page a page, its shapes FigJam shapes with text, its edges\n * connectors joined to them, its layers groups when there are several, in draw.io's drawing order.\n * Text sizes are left for layout, which measures them once fonts load.\n */\nexport function drawioToSceneGraph(file: DrawIOFile): SceneGraph {\n const graph = new SceneGraph()\n const first = graph.getPages().at(0)\n for (const [index, page] of file.pages.entries()) {\n const pageNode = index === 0 && first ? first : graph.addPage(page.name)\n if (index === 0) graph.updateNode(pageNode.id, { name: page.name })\n new PageBuilder(graph, page, pageNode.id).build()\n }\n return graph\n}\n\nexport { sceneGraphToDrawIO } from './export'\n"],"mappings":";;;;;;;;;;;AAYA,SAAS,QAAQ,MAAkB;CACjC,MAAM,SAAS,YAAY,KAAK,KAAK;CACrC,OAAO;EAAE;EAAQ,GAAG,UAAU,KAAK,OAAO,KAAK,MAAM,OAAO,SAAS,KAAK,MAAM;CAAE;AACpF;;;;;;;AAQA,SAAS,YAAY,OAAoB,WAAW,OAAO;CACzD,MAAM,QAAQ,MAAM,OAAO,UAAU,OAAO,CAAC;CAC7C,MAAM,QAAQ,MAAM,OAAO,UAAU;CACrC,MAAM,OAAO,OAAO,MAAM,OAAO,YAAY,CAAC,KAAK;CACnD,OAAO;EAAE;EAAO;EAAO,UAAU,UAAU,QAAQ,OAAO,CAAC;CAAK;AAClE;;AAGA,SAAS,OAAO,MAAc,UAA0B;CACtD,OAAO,KAAK,MAAM,IAAI,CAAC,CAAC,EAAE,EAAE,KAAK,KAAK;AACxC;;;;;AAMA,SAAS,YAAY,OAAwC;CAC3D,MAAM,QAAQ,MAAM,OAAO;CAC3B,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,IAAI;EACF,OAAO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AAmB,MAA8B;CAC/D,MAAM,QAAQ,IAAI,WAAW;CAC7B,MAAM,QAAQ,MAAM,SAAS,CAAC,CAAC,GAAG,CAAC;CACnC,KAAK,MAAM,CAAC,OAAO,SAAS,KAAK,MAAM,QAAQ,GAAG;EAChD,MAAM,WAAW,UAAU,KAAK,QAAQ,QAAQ,MAAM,QAAQ,KAAK,IAAI;EACvE,IAAI,UAAU,GAAG,MAAM,WAAW,SAAS,IAAI,EAAE,MAAM,KAAK,KAAK,CAAC;EAClE,IAAI,YAAY,OAAO,MAAM,SAAS,EAAE,CAAC,CAAC,MAAM;CAClD;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/io/formats/drawio/index.ts"],"sourcesContent":["import type { DrawIOCell, DrawIOFile, DrawIOPage, DrawIOStyle } from '@pairdraw/drawio'\nimport { SceneGraph, type SceneNode } from '@pairdraw/scene-graph'\nimport { connectorRoute, placeConnectorLabel } from '@pairdraw/scene-graph/connectors'\nimport { createShapeWithText } from '@pairdraw/scene-graph/generated'\nimport { fitEnclosingGroups } from '@pairdraw/scene-graph/group-bounds'\n\nimport { bindEdge, createEdge, labelPositionOf, type PendingEdge } from './edges'\nimport { readLabel } from './label'\nimport { labelFields, labelFormat, shapePaint } from './paint'\nimport { shapeName, vertexKind } from './shapes'\n\n/** A cell's label as text and runs, in the cell's own style. */\nfunction labelOf(cell: DrawIOCell) {\n const format = labelFormat(cell.style)\n return { format, ...readLabel(cell.value, cell.style.values.html === '1', format) }\n}\n\n/**\n * A cell's turn and mirrors as a layer's. draw.io mirrors a cell about its centre and then turns\n * it, negating the turn when it mirrors one way only; a layer turns and then mirrors, so that\n * turn is the layer's own. `ownFlipH` is a mirror the shape itself stands for, as a left\n * parallelogram is draw.io's mirrored one.\n */\nfunction placementOf(style: DrawIOStyle, ownFlipH = false) {\n const flipX = style.values.flipH === '1' && !ownFlipH\n const flipY = style.values.flipV === '1'\n const turn = Number(style.values.rotation ?? 0) || 0\n return { flipX, flipY, rotation: flipX === flipY ? turn : -turn }\n}\n\n/** The first line of a label, as a layer's name. */\nfunction nameOf(text: string, fallback: string): string {\n return text.split('\\n')[0]?.trim() || fallback\n}\n\n/**\n * The name Pairdraw wrote into a cell's style. draw.io has no field of its own for a layer whose\n * cell draws no text, and a text cell's label is its content, so the name travels beside them.\n */\nfunction writtenName(style: DrawIOStyle): string | undefined {\n const value = style.values.pairdrawName\n if (value === undefined) return undefined\n try {\n return decodeURIComponent(value)\n } catch {\n return undefined\n }\n}\n\n/** A layer's name: the one Pairdraw wrote, else the first line of its label. */\nfunction layerName(style: DrawIOStyle, text: string, fallback: string): string {\n return writtenName(style) ?? nameOf(text, fallback)\n}\n\n/** Builds one draw.io page's cells into `pageId`, in draw.io's drawing order. */\nclass PageBuilder {\n /** The layer each draw.io cell or layer became. */\n private readonly layers = new Map<string, string>()\n private readonly edges: PendingEdge[] = []\n private readonly groups: string[] = []\n\n constructor(\n private readonly graph: SceneGraph,\n private readonly page: DrawIOPage,\n private readonly pageId: string\n ) {}\n\n build() {\n const { graph, page, pageId } = this\n // One layer draws straight onto the page; several each become a group named after it, as\n // does a single layer that is hidden or locked, so it stays so.\n for (const [index, layer] of page.layers.entries()) {\n if (page.layers.length === 1 && layer.visible && !layer.locked) {\n this.layers.set(layer.id, pageId)\n continue\n }\n const group = graph.createNode('GROUP', pageId, {\n name: layer.name || `Layer ${index + 1}`,\n visible: layer.visible,\n locked: layer.locked\n })\n this.layers.set(layer.id, group.id)\n this.groups.push(group.id)\n }\n const parents = new Set(page.cells.map((cell) => cell.parent))\n const labelsOf = new Map<string, DrawIOCell[]>()\n const edgeIds = new Set(\n page.cells.filter((cell) => cell.kind === 'edge').map((cell) => cell.id)\n )\n for (const cell of page.cells) {\n // A vertex inside an edge is one of its labels.\n if (edgeIds.has(cell.parent)) {\n const labels = labelsOf.get(cell.parent) ?? []\n labels.push(cell)\n labelsOf.set(cell.parent, labels)\n }\n }\n const cells = new Map(page.cells.map((cell) => [cell.id, cell]))\n const placing = new Set<string>()\n const place = (cell: DrawIOCell) => {\n if (edgeIds.has(cell.parent) || this.layers.has(cell.id) || placing.has(cell.id)) return\n placing.add(cell.id)\n // A cell listed before its parent, as draw.io's format allows, waits for the parent.\n const parent = cells.get(cell.parent)\n if (parent) place(parent)\n const parentId = this.layers.get(cell.parent) ?? pageId\n if (cell.kind === 'edge') {\n const pending = createEdge(graph, parentId, cell, labelsOf.get(cell.id) ?? [])\n this.layers.set(cell.id, pending.connector.id)\n this.edges.push(pending)\n return\n }\n const node = this.vertex(cell, parentId, parents.has(cell.id))\n this.layers.set(cell.id, node.id)\n }\n for (const cell of page.cells) place(cell)\n const layerOf = (cellId: string) => this.layers.get(cellId)\n for (const pending of this.edges) {\n for (const extra of bindEdge(graph, pending, layerOf)) this.edgeText(pending, extra)\n }\n // Groups fit around what they hold, the innermost first.\n // One pass fits every group and its ancestors once; fitting per group walks the chain above\n // that group again for each of them, which on a deep draw.io drawing is most of the import.\n fitEnclosingGroups(graph, this.groups)\n }\n\n private vertex(cell: DrawIOCell, parentId: string, hasChildren: boolean): SceneNode {\n const { graph } = this\n const { x, y, width, height } = cell.geometry\n const kind = vertexKind(cell.style, hasChildren)\n const label = labelOf(cell)\n const box = { x, y, width, height, visible: cell.visible }\n if (kind.type === 'TEXT') {\n return graph.createNode('TEXT', parentId, {\n ...box,\n ...placementOf(cell.style),\n name: layerName(cell.style, label.text, 'Text'),\n ...labelFields(cell.style, label.format),\n text: label.text,\n styleRuns: label.runs,\n textAutoResize: 'NONE'\n })\n }\n if (kind.type === 'FRAME') {\n return graph.createNode('FRAME', parentId, {\n ...box,\n ...shapePaint(cell.style),\n name: layerName(cell.style, label.text, 'Frame')\n })\n }\n if (kind.type === 'RECTANGLE') {\n const radius = Number.parseFloat(cell.style.values.pairdrawCornerRadius ?? '')\n return graph.createNode('RECTANGLE', parentId, {\n ...box,\n ...shapePaint(cell.style),\n ...(radius > 0 ? { cornerRadius: radius } : {}),\n name: layerName(cell.style, label.text, 'Rectangle')\n })\n }\n if (kind.type === 'SECTION') {\n return graph.createNode('SECTION', parentId, {\n ...box,\n ...shapePaint(cell.style),\n name: nameOf(label.text, 'Section')\n })\n }\n if (kind.type === 'GROUP') {\n const group = graph.createNode('GROUP', parentId, {\n ...box,\n name: nameOf(label.text, 'Group')\n })\n this.groups.push(group.id)\n return group\n }\n // A shape turned a quarter swaps its sides, about the centre of the box it fills.\n const quarter = Math.abs(kind.rotation) === 90\n const placed = quarter\n ? { x: x + (width - height) / 2, y: y + (height - width) / 2, width: height, height: width }\n : { x, y, width, height }\n const known = shapeName(cell.style)\n const own = placementOf(cell.style, kind.shape === 'PARALLELOGRAM_LEFT')\n return createShapeWithText(\n graph,\n parentId,\n {\n ...placed,\n visible: cell.visible,\n ...own,\n rotation: own.rotation + kind.rotation,\n shapeWithTextType: kind.shape,\n // draw.io sized it, so it keeps its size, as a FigJam shape whose height was set does.\n shapeTruncates: true,\n ...shapePaint(cell.style),\n // A stencil FigJam has no shape for keeps its name, so it can be found and replaced.\n name: kind.stencil ? known : nameOf(label.text, 'Shape with text')\n },\n { ...labelFields(cell.style, label.format), text: label.text, styleRuns: label.runs }\n )\n }\n\n /** A label beyond an edge's first, as text where draw.io placed it along the edge. */\n private edgeText({ connector }: PendingEdge, cell: DrawIOCell) {\n const { graph } = this\n const node = graph.getNode(connector.id)\n const route = node ? connectorRoute(graph, node) : null\n if (!node?.parentId || !route) return\n const label = labelOf(cell)\n const size = { width: cell.geometry.width, height: cell.geometry.height }\n const plate = placeConnectorLabel(route.pieces, size, labelPositionOf(cell.geometry.x))?.plate\n const offset = cell.geometry.offset ?? { x: 0, y: 0 }\n graph.createNode('TEXT', node.parentId, {\n x: (plate?.x ?? 0) + offset.x,\n y: (plate?.y ?? 0) + offset.y,\n visible: cell.visible,\n name: nameOf(label.text, 'Text'),\n ...labelFields(cell.style, label.format),\n text: label.text,\n styleRuns: label.runs,\n textAutoResize: 'WIDTH_AND_HEIGHT'\n })\n }\n}\n\n/**\n * A draw.io file as layers: each page a page, its shapes FigJam shapes with text, its edges\n * connectors joined to them, its layers groups when there are several, in draw.io's drawing order.\n * Text sizes are left for layout, which measures them once fonts load.\n */\nexport function drawioToSceneGraph(file: DrawIOFile): SceneGraph {\n const graph = new SceneGraph()\n const first = graph.getPages().at(0)\n for (const [index, page] of file.pages.entries()) {\n const pageNode = index === 0 && first ? first : graph.addPage(page.name)\n if (index === 0) graph.updateNode(pageNode.id, { name: page.name })\n new PageBuilder(graph, page, pageNode.id).build()\n }\n return graph\n}\n\nexport { sceneGraphToDrawIO } from './export'\n"],"mappings":";;;;;;;;;;;AAYA,SAAS,QAAQ,MAAkB;CACjC,MAAM,SAAS,YAAY,KAAK,KAAK;CACrC,OAAO;EAAE;EAAQ,GAAG,UAAU,KAAK,OAAO,KAAK,MAAM,OAAO,SAAS,KAAK,MAAM;CAAE;AACpF;;;;;;;AAQA,SAAS,YAAY,OAAoB,WAAW,OAAO;CACzD,MAAM,QAAQ,MAAM,OAAO,UAAU,OAAO,CAAC;CAC7C,MAAM,QAAQ,MAAM,OAAO,UAAU;CACrC,MAAM,OAAO,OAAO,MAAM,OAAO,YAAY,CAAC,KAAK;CACnD,OAAO;EAAE;EAAO;EAAO,UAAU,UAAU,QAAQ,OAAO,CAAC;CAAK;AAClE;;AAGA,SAAS,OAAO,MAAc,UAA0B;CACtD,OAAO,KAAK,MAAM,IAAI,CAAC,CAAC,EAAE,EAAE,KAAK,KAAK;AACxC;;;;;AAMA,SAAS,YAAY,OAAwC;CAC3D,MAAM,QAAQ,MAAM,OAAO;CAC3B,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,IAAI;EACF,OAAO,mBAAmB,KAAK;CACjC,QAAQ;EACN;CACF;AACF;;AAGA,SAAS,UAAU,OAAoB,MAAc,UAA0B;CAC7E,OAAO,YAAY,KAAK,KAAK,OAAO,MAAM,QAAQ;AACpD;;AAGA,IAAM,cAAN,MAAkB;CAOG;CACA;CACA;;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;EACvE,IAAI,UAAU,GAAG,MAAM,WAAW,SAAS,IAAI,EAAE,MAAM,KAAK,KAAK,CAAC;EAClE,IAAI,YAAY,OAAO,MAAM,SAAS,EAAE,CAAC,CAAC,MAAM;CAClD;CACA,OAAO;AACT"}
|
|
@@ -7,6 +7,11 @@ interface StyleHTMLOptions {
|
|
|
7
7
|
/** Compile the Tailwind utilities the markup's classes name into the stylesheet. */
|
|
8
8
|
tailwind?: boolean;
|
|
9
9
|
}
|
|
10
|
+
interface SceneGraphFromStyledHTMLOptions {
|
|
11
|
+
pageName?: string;
|
|
12
|
+
/** The family a CSS stack should draw; null keeps its first family. See the dom-css option. */
|
|
13
|
+
resolveFontFamily?: (value: string) => string | null;
|
|
14
|
+
}
|
|
10
15
|
/**
|
|
11
16
|
* Styles HTML with the CSS runtime a host has: the browser's in the app, the headless runtime
|
|
12
17
|
* in the CLI. Hosts hand it to tools, which build the layers with `sceneGraphFromStyledHTML`.
|
|
@@ -22,9 +27,7 @@ declare function htmlClassNames(html: string): string[];
|
|
|
22
27
|
* belongs to whoever has a CSS runtime, such as a browser or the headless runtime; building and
|
|
23
28
|
* laying out the layers happens here for every caller. Safe to bundle for the browser.
|
|
24
29
|
*/
|
|
25
|
-
declare function sceneGraphFromStyledHTML(styled: DesignDocument, options?:
|
|
26
|
-
pageName?: string;
|
|
27
|
-
}): SceneGraph;
|
|
30
|
+
declare function sceneGraphFromStyledHTML(styled: DesignDocument, options?: SceneGraphFromStyledHTMLOptions): SceneGraph;
|
|
28
31
|
//#endregion
|
|
29
|
-
export { HTMLStyler, StyleHTMLOptions, htmlClassNames, sceneGraphFromStyledHTML };
|
|
32
|
+
export { HTMLStyler, SceneGraphFromStyledHTMLOptions, StyleHTMLOptions, htmlClassNames, sceneGraphFromStyledHTML };
|
|
30
33
|
//# sourceMappingURL=layers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layers.d.ts","names":[],"sources":["../../../../src/io/formats/html/layers.ts"],"mappings":";;;UAMiB;;EAEf;;EAEA;;;;;;
|
|
1
|
+
{"version":3,"file":"layers.d.ts","names":[],"sources":["../../../../src/io/formats/html/layers.ts"],"mappings":";;;UAMiB;;EAEf;;EAEA;;UAGe;EACf;;EAEA,qBAAqB;;;;;;KAOX,cAAc,cAAc,SAAS,qBAAqB,QAAQ;;;;;iBAY9D,eAAe;;;;;;iBAef,yBACd,QAAQ,gBACR,UAAS,kCACR"}
|
|
@@ -24,7 +24,10 @@ function htmlClassNames(html) {
|
|
|
24
24
|
* laying out the layers happens here for every caller. Safe to bundle for the browser.
|
|
25
25
|
*/
|
|
26
26
|
function sceneGraphFromStyledHTML(styled, options = {}) {
|
|
27
|
-
const graph = designDocumentToSceneGraph(styled, {
|
|
27
|
+
const graph = designDocumentToSceneGraph(styled, {
|
|
28
|
+
pageName: options.pageName,
|
|
29
|
+
resolveFontFamily: options.resolveFontFamily
|
|
30
|
+
});
|
|
28
31
|
layoutAuthoredNodes(graph, graph.getPages().map((page) => page.id));
|
|
29
32
|
return graph;
|
|
30
33
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layers.js","names":[],"sources":["../../../../src/io/formats/html/layers.ts"],"sourcesContent":["import type { DesignDocument } from '@pairdraw/dom-css'\nimport { designDocumentToSceneGraph } from '@pairdraw/dom-css/scene-graph'\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { layoutAuthoredNodes } from '#core/layout'\n\nexport interface StyleHTMLOptions {\n /** A stylesheet applied after the document's own `<style>` blocks. */\n cssText?: string\n /** Compile the Tailwind utilities the markup's classes name into the stylesheet. */\n tailwind?: boolean\n}\n\n/**\n * Styles HTML with the CSS runtime a host has: the browser's in the app, the headless runtime\n * in the CLI. Hosts hand it to tools, which build the layers with `sceneGraphFromStyledHTML`.\n */\nexport type HTMLStyler = (html: string, options: StyleHTMLOptions) => Promise<DesignDocument>\n\n/**\n * A `class` or JSX `className` attribute with a double-quoted, single-quoted, or unquoted value.\n * The name must follow whitespace, so `data-class` and similar attributes do not count.\n */\nconst CLASS_ATTRIBUTE = /(?:^|\\s)class(?:Name)?\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+))/g\n\n/**\n * The class names `class` attributes in `html` use, as Tailwind candidates, for hosts without a\n * DOM parser; a browser reads them from each element's `classList` instead.\n */\nexport function htmlClassNames(html: string): string[] {\n const names = new Set<string>()\n for (const match of html.matchAll(CLASS_ATTRIBUTE)) {\n // Only one alternative matches; `join` reads the others, which are undefined, as empty.\n const value = match.slice(1).join('')\n for (const name of value.split(/\\s+/)) if (name) names.add(name)\n }\n return [...names]\n}\n\n/**\n * The layers a styled DOM describes, with the sizes and positions its layout implies. Styling\n * belongs to whoever has a CSS runtime, such as a browser or the headless runtime; building and\n * laying out the layers happens here for every caller. Safe to bundle for the browser.\n */\nexport function sceneGraphFromStyledHTML(\n styled: DesignDocument,\n options:
|
|
1
|
+
{"version":3,"file":"layers.js","names":[],"sources":["../../../../src/io/formats/html/layers.ts"],"sourcesContent":["import type { DesignDocument } from '@pairdraw/dom-css'\nimport { designDocumentToSceneGraph } from '@pairdraw/dom-css/scene-graph'\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { layoutAuthoredNodes } from '#core/layout'\n\nexport interface StyleHTMLOptions {\n /** A stylesheet applied after the document's own `<style>` blocks. */\n cssText?: string\n /** Compile the Tailwind utilities the markup's classes name into the stylesheet. */\n tailwind?: boolean\n}\n\nexport interface SceneGraphFromStyledHTMLOptions {\n pageName?: string\n /** The family a CSS stack should draw; null keeps its first family. See the dom-css option. */\n resolveFontFamily?: (value: string) => string | null\n}\n\n/**\n * Styles HTML with the CSS runtime a host has: the browser's in the app, the headless runtime\n * in the CLI. Hosts hand it to tools, which build the layers with `sceneGraphFromStyledHTML`.\n */\nexport type HTMLStyler = (html: string, options: StyleHTMLOptions) => Promise<DesignDocument>\n\n/**\n * A `class` or JSX `className` attribute with a double-quoted, single-quoted, or unquoted value.\n * The name must follow whitespace, so `data-class` and similar attributes do not count.\n */\nconst CLASS_ATTRIBUTE = /(?:^|\\s)class(?:Name)?\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+))/g\n\n/**\n * The class names `class` attributes in `html` use, as Tailwind candidates, for hosts without a\n * DOM parser; a browser reads them from each element's `classList` instead.\n */\nexport function htmlClassNames(html: string): string[] {\n const names = new Set<string>()\n for (const match of html.matchAll(CLASS_ATTRIBUTE)) {\n // Only one alternative matches; `join` reads the others, which are undefined, as empty.\n const value = match.slice(1).join('')\n for (const name of value.split(/\\s+/)) if (name) names.add(name)\n }\n return [...names]\n}\n\n/**\n * The layers a styled DOM describes, with the sizes and positions its layout implies. Styling\n * belongs to whoever has a CSS runtime, such as a browser or the headless runtime; building and\n * laying out the layers happens here for every caller. Safe to bundle for the browser.\n */\nexport function sceneGraphFromStyledHTML(\n styled: DesignDocument,\n options: SceneGraphFromStyledHTMLOptions = {}\n): SceneGraph {\n const graph = designDocumentToSceneGraph(styled, {\n pageName: options.pageName,\n resolveFontFamily: options.resolveFontFamily\n })\n layoutAuthoredNodes(\n graph,\n graph.getPages().map((page) => page.id)\n )\n return graph\n}\n"],"mappings":";;;;;;;AA6BA,MAAM,kBAAkB;;;;;AAMxB,SAAgB,eAAe,MAAwB;CACrD,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,SAAS,KAAK,SAAS,eAAe,GAAG;EAElD,MAAM,QAAQ,MAAM,MAAM,CAAC,CAAC,CAAC,KAAK,EAAE;EACpC,KAAK,MAAM,QAAQ,MAAM,MAAM,KAAK,GAAG,IAAI,MAAM,MAAM,IAAI,IAAI;CACjE;CACA,OAAO,CAAC,GAAG,KAAK;AAClB;;;;;;AAOA,SAAgB,yBACd,QACA,UAA2C,CAAC,GAChC;CACZ,MAAM,QAAQ,2BAA2B,QAAQ;EAC/C,UAAU,QAAQ;EAClB,mBAAmB,QAAQ;CAC7B,CAAC;CACD,oBACE,OACA,MAAM,SAAS,CAAC,CAAC,KAAK,SAAS,KAAK,EAAE,CACxC;CACA,OAAO;AACT"}
|
|
@@ -15,7 +15,12 @@ declare function withPDFDOM<T>(draw: (parse: SVGPageParser) => Promise<T>): Prom
|
|
|
15
15
|
* The two globals exist only while the import evaluates, and the function the module made keeps
|
|
16
16
|
* the jsPDF it read, so the rest of the export needs nothing from them.
|
|
17
17
|
*/
|
|
18
|
-
|
|
18
|
+
/**
|
|
19
|
+
* svg2pdf.js's `main` is a UMD build in a `"type": "module"` package with no `exports`, so Node
|
|
20
|
+
* loads it as ESM and it throws for want of a global jsPDF. Its ES build, the `module` file
|
|
21
|
+
* bundlers and Bun already pick, loads everywhere.
|
|
22
|
+
*/
|
|
23
|
+
declare function loadSVG2PDF(): Promise<typeof svg2pdf>;
|
|
19
24
|
//#endregion
|
|
20
25
|
export { SVGPageParser, loadSVG2PDF, withPDFDOM };
|
|
21
26
|
//# sourceMappingURL=dom.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom.d.ts","names":[],"sources":["../../../../src/io/formats/pdf/dom.ts"],"mappings":";;;KAOY,iBAAiB,gBAAgB;;;;;;iBAkI7B,WAAW,GAAG,OAAO,OAAO,kBAAkB,QAAQ,KAAK,QAAQ
|
|
1
|
+
{"version":3,"file":"dom.d.ts","names":[],"sources":["../../../../src/io/formats/pdf/dom.ts"],"mappings":";;;KAOY,iBAAiB,gBAAgB;;;;;;iBAkI7B,WAAW,GAAG,OAAO,OAAO,kBAAkB,QAAQ,KAAK,QAAQ;;;;;;;;;;;;;iBAuE7D,eAAe,eAAe"}
|
|
@@ -138,28 +138,15 @@ async function withHappyDOM(draw) {
|
|
|
138
138
|
* The two globals exist only while the import evaluates, and the function the module made keeps
|
|
139
139
|
* the jsPDF it read, so the rest of the export needs nothing from them.
|
|
140
140
|
*/
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
});
|
|
151
|
-
};
|
|
152
|
-
set("jspdf", { jsPDF });
|
|
153
|
-
try {
|
|
154
|
-
const draw = (await import("svg2pdf.js")).svg2pdf ?? scope.svg2pdf?.svg2pdf;
|
|
155
|
-
if (!draw) throw new Error("svg2pdf.js exported no svg2pdf function");
|
|
156
|
-
return draw;
|
|
157
|
-
} finally {
|
|
158
|
-
if (previousJSPDF) Object.defineProperty(globalThis, "jspdf", previousJSPDF);
|
|
159
|
-
else delete scope.jspdf;
|
|
160
|
-
if (previousSVG2PDF) Object.defineProperty(globalThis, "svg2pdf", previousSVG2PDF);
|
|
161
|
-
else delete scope.svg2pdf;
|
|
162
|
-
}
|
|
141
|
+
/**
|
|
142
|
+
* svg2pdf.js's `main` is a UMD build in a `"type": "module"` package with no `exports`, so Node
|
|
143
|
+
* loads it as ESM and it throws for want of a global jsPDF. Its ES build, the `module` file
|
|
144
|
+
* bundlers and Bun already pick, loads everywhere.
|
|
145
|
+
*/
|
|
146
|
+
async function loadSVG2PDF() {
|
|
147
|
+
const module = await import("svg2pdf.js/dist/svg2pdf.es.min.js");
|
|
148
|
+
if (!module.svg2pdf) throw new Error("svg2pdf.js exported no svg2pdf function");
|
|
149
|
+
return module.svg2pdf;
|
|
163
150
|
}
|
|
164
151
|
//#endregion
|
|
165
152
|
export { loadSVG2PDF, withPDFDOM };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom.js","names":[],"sources":["../../../../src/io/formats/pdf/dom.ts"],"sourcesContent":["import type * as HappyDOM from 'happy-dom'\nimport { toUint8Array } from 'js-base64'\nimport type { svg2pdf } from 'svg2pdf.js'\n\nimport { IS_BROWSER } from '#core/constants'\n\n/** A page's SVG markup as the element svg2pdf draws, or null when it does not parse. */\nexport type SVGPageParser = (svg: string) => Element | null\n\ninterface SVGParser {\n parseFromString(\n svg: string,\n type: 'image/svg+xml'\n ): {\n querySelector(selectors: string): unknown\n documentElement: unknown\n }\n}\n\n/** The pixel size a data URI's image holds, as svg2pdf asks an `Image` for it. */\nfunction imageSize(source: string): [number, number] {\n const comma = source.indexOf(',')\n if (comma === -1 || !source.slice(0, comma).includes(';base64')) {\n throw new Error('Not a base64 data URI')\n }\n const bytes = toUint8Array(source.slice(comma + 1))\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n const starts = (text: string, at = 0) =>\n Array.from(text, (character, index) => bytes[at + index] === character.charCodeAt(0)).every(\n Boolean\n )\n if (starts('\\x89PNG')) return [view.getUint32(16), view.getUint32(20)]\n if (starts('GIF8')) return [view.getUint16(6, true), view.getUint16(8, true)]\n if (starts('RIFF') && starts('WEBP', 8)) {\n const kind = String.fromCharCode(...bytes.subarray(12, 16))\n if (kind === 'VP8X') {\n return [\n 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16)),\n 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16))\n ]\n }\n if (kind === 'VP8 ')\n return [view.getUint16(26, true) & 0x3fff, view.getUint16(28, true) & 0x3fff]\n }\n if (bytes[0] === 0xff && bytes[1] === 0xd8) {\n for (let at = 2; at + 9 < bytes.length;) {\n if (bytes[at] !== 0xff) {\n at++\n continue\n }\n const marker = bytes[at + 1]\n const length = view.getUint16(at + 2)\n // Start-of-frame markers carry the image's size; C4, C8, and CC are other segments.\n if (\n marker >= 0xc0 &&\n marker <= 0xcf &&\n marker !== 0xc4 &&\n marker !== 0xc8 &&\n marker !== 0xcc\n ) {\n return [view.getUint16(at + 7), view.getUint16(at + 5)]\n }\n at += 2 + length\n }\n }\n throw new Error('Unsupported image data')\n}\n\n/**\n * The `Image` svg2pdf asks for an image's size by name, for a host without one: it decodes only a\n * base64 data URI's header, which is all the size needs.\n */\nclass HeadlessImage {\n width = 0\n height = 0\n onload: (() => void) | null = null\n onerror: ((error: unknown) => void) | null = null\n\n set src(value: string) {\n try {\n const [width, height] = imageSize(value)\n this.width = width\n this.height = height\n queueMicrotask(() => this.onload?.())\n } catch (error) {\n queueMicrotask(() => this.onerror?.(error))\n }\n }\n}\n\n/**\n * The globals svg2pdf reads: it parses a page's stylesheets in a document it makes, and keeps the\n * rules that are instances of the CSSOM classes.\n */\ninterface SVG2PDFGlobals {\n document?: unknown\n CSSStyleSheet?: unknown\n CSSStyleRule?: unknown\n Image?: unknown\n}\n\nconst SVG2PDF_GLOBALS = ['document', 'CSSStyleSheet', 'CSSStyleRule'] as const\n\ntype SVG2PDFGlobal = (typeof SVG2PDF_GLOBALS)[number] | 'Image'\n\nfunction removeGlobal(scope: SVG2PDFGlobals, name: SVG2PDFGlobal): void {\n if (name === 'document') delete scope.document\n else if (name === 'CSSStyleSheet') delete scope.CSSStyleSheet\n else if (name === 'Image') delete scope.Image\n else delete scope.CSSStyleRule\n}\n\n/**\n * Kept out of the browser bundle: a browser has a DOM of its own, and happy-dom is only loaded\n * where there is none.\n */\nconst HAPPY_DOM = 'happy-dom'\n\nlet exporting: Promise<unknown> = Promise.resolve()\n\nfunction isElement(value: unknown): value is Element {\n return typeof value === 'object' && value !== null && 'tagName' in value\n}\n\nfunction parseSVGPage(parser: SVGParser): SVGPageParser {\n return (svg) => {\n const parsed = parser.parseFromString(svg, 'image/svg+xml')\n if (parsed.querySelector('parsererror')) return null\n return isElement(parsed.documentElement) ? parsed.documentElement : null\n }\n}\n\n/**\n * Runs `draw` with a parser for page SVG and the DOM svg2pdf draws it through. A browser has both.\n * Elsewhere, as in the CLI, happy-dom stands in: svg2pdf reads its DOM as globals, so they are set\n * only while `draw` runs, one export at a time, and restored after.\n */\nexport function withPDFDOM<T>(draw: (parse: SVGPageParser) => Promise<T>): Promise<T> {\n if (IS_BROWSER) return draw(parseSVGPage(new DOMParser()))\n const run = exporting.then(() => withHappyDOM(draw))\n exporting = run.catch(() => undefined)\n return run\n}\n\nasync function withHappyDOM<T>(draw: (parse: SVGPageParser) => Promise<T>): Promise<T> {\n const { Window } = (await import(/* @vite-ignore */ HAPPY_DOM)) as typeof HappyDOM\n const dom = new Window()\n const scope: SVG2PDFGlobals = globalThis\n const values: Record<SVG2PDFGlobal, unknown> = {\n document: dom.document,\n CSSStyleSheet: dom.CSSStyleSheet,\n CSSStyleRule: dom.CSSStyleRule,\n Image: HeadlessImage\n }\n // Each global replaced, with its descriptor before, so an accessor a host defines comes back as\n // one and a global that could not be replaced is left as it was.\n const replaced: Array<[SVG2PDFGlobal, PropertyDescriptor | undefined]> = []\n let replacedImage: PropertyDescriptor | undefined\n let hadImage = false\n try {\n // svg2pdf reads an image's size through a browser `Image`, which a CLI host lacks.\n if (!('Image' in globalThis)) {\n replacedImage = Object.getOwnPropertyDescriptor(globalThis, 'Image')\n hadImage = false\n Object.defineProperty(globalThis, 'Image', {\n value: HeadlessImage,\n configurable: true,\n writable: true\n })\n } else {\n hadImage = true\n }\n for (const name of SVG2PDF_GLOBALS) {\n const previous = Object.getOwnPropertyDescriptor(globalThis, name)\n Object.defineProperty(globalThis, name, {\n value: values[name],\n configurable: true,\n writable: true\n })\n replaced.push([name, previous])\n }\n return await draw(parseSVGPage(new dom.DOMParser()))\n } finally {\n // What is replaced is configurable, so putting it back does not throw.\n for (const [name, previous] of replaced) {\n if (previous) Object.defineProperty(globalThis, name, previous)\n else removeGlobal(scope, name)\n }\n if (!hadImage) {\n if (replacedImage) Object.defineProperty(globalThis, 'Image', replacedImage)\n else removeGlobal(scope, 'Image')\n }\n await dom.happyDOM.close()\n }\n}\n\n/**\n * Loads `svg2pdf.js`. Its package publishes a UMD build only, whose factory reads jsPDF from the\n * global `jspdf` and, with no CommonJS `exports`, writes the function to the global `svg2pdf`; a\n * bundler supplies both, a bare Node install supplies neither, and the module then fails on load.\n * The two globals exist only while the import evaluates, and the function the module made keeps\n * the jsPDF it read, so the rest of the export needs nothing from them.\n */\nexport async function loadSVG2PDF(jsPDF: unknown): Promise<typeof svg2pdf> {\n const scope = globalThis as { jspdf?: unknown; svg2pdf?: { svg2pdf?: typeof svg2pdf } }\n const previousJSPDF = Object.getOwnPropertyDescriptor(globalThis, 'jspdf')\n const previousSVG2PDF = Object.getOwnPropertyDescriptor(globalThis, 'svg2pdf')\n const set = (name: string, value: unknown): void => {\n Object.defineProperty(globalThis, name, { value, configurable: true, writable: true })\n }\n set('jspdf', { jsPDF })\n try {\n const module = (await import('svg2pdf.js')) as { svg2pdf?: typeof svg2pdf }\n const draw = module.svg2pdf ?? scope.svg2pdf?.svg2pdf\n if (!draw) throw new Error('svg2pdf.js exported no svg2pdf function')\n return draw\n } finally {\n if (previousJSPDF) Object.defineProperty(globalThis, 'jspdf', previousJSPDF)\n else delete scope.jspdf\n if (previousSVG2PDF) Object.defineProperty(globalThis, 'svg2pdf', previousSVG2PDF)\n else delete scope.svg2pdf\n }\n}\n"],"mappings":";;;;AAoBA,SAAS,UAAU,QAAkC;CACnD,MAAM,QAAQ,OAAO,QAAQ,GAAG;CAChC,IAAI,UAAU,MAAM,CAAC,OAAO,MAAM,GAAG,KAAK,CAAC,CAAC,SAAS,SAAS,GAC5D,MAAM,IAAI,MAAM,uBAAuB;CAEzC,MAAM,QAAQ,aAAa,OAAO,MAAM,QAAQ,CAAC,CAAC;CAClD,MAAM,OAAO,IAAI,SAAS,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU;CAC1E,MAAM,UAAU,MAAc,KAAK,MACjC,MAAM,KAAK,OAAO,WAAW,UAAU,MAAM,KAAK,WAAW,UAAU,WAAW,CAAC,CAAC,CAAC,CAAC,MACpF,OACF;CACF,IAAI,OAAO,MAAS,GAAG,OAAO,CAAC,KAAK,UAAU,EAAE,GAAG,KAAK,UAAU,EAAE,CAAC;CACrE,IAAI,OAAO,MAAM,GAAG,OAAO,CAAC,KAAK,UAAU,GAAG,IAAI,GAAG,KAAK,UAAU,GAAG,IAAI,CAAC;CAC5E,IAAI,OAAO,MAAM,KAAK,OAAO,QAAQ,CAAC,GAAG;EACvC,MAAM,OAAO,OAAO,aAAa,GAAG,MAAM,SAAS,IAAI,EAAE,CAAC;EAC1D,IAAI,SAAS,Q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,IAAI,UAAU,OAAO,eAAe,YAAY,MAAM,QAAQ;OACzD,aAAa,OAAO,IAAI;EAE/B,IAAI,CAAC,UAAU;GACb,IAAI,eAAe,OAAO,eAAe,YAAY,SAAS,aAAa;QACtE,aAAa,OAAO,OAAO;EAClC;EACA,MAAM,IAAI,SAAS,MAAM;CAC3B;AACF;;;;;;;;AASA,eAAsB,YAAY,OAAyC;CACzE,MAAM,QAAQ;CACd,MAAM,gBAAgB,OAAO,yBAAyB,YAAY,OAAO;CACzE,MAAM,kBAAkB,OAAO,yBAAyB,YAAY,SAAS;CAC7E,MAAM,OAAO,MAAc,UAAyB;EAClD,OAAO,eAAe,YAAY,MAAM;GAAE;GAAO,cAAc;GAAM,UAAU;EAAK,CAAC;CACvF;CACA,IAAI,SAAS,EAAE,MAAM,CAAC;CACtB,IAAI;EAEF,MAAM,QAAO,MADS,OAAO,cAAA,CACT,WAAW,MAAM,SAAS;EAC9C,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,yCAAyC;EACpE,OAAO;CACT,UAAU;EACR,IAAI,eAAe,OAAO,eAAe,YAAY,SAAS,aAAa;OACtE,OAAO,MAAM;EAClB,IAAI,iBAAiB,OAAO,eAAe,YAAY,WAAW,eAAe;OAC5E,OAAO,MAAM;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"dom.js","names":[],"sources":["../../../../src/io/formats/pdf/dom.ts"],"sourcesContent":["import type * as HappyDOM from 'happy-dom'\nimport { toUint8Array } from 'js-base64'\nimport type { svg2pdf } from 'svg2pdf.js'\n\nimport { IS_BROWSER } from '#core/constants'\n\n/** A page's SVG markup as the element svg2pdf draws, or null when it does not parse. */\nexport type SVGPageParser = (svg: string) => Element | null\n\ninterface SVGParser {\n parseFromString(\n svg: string,\n type: 'image/svg+xml'\n ): {\n querySelector(selectors: string): unknown\n documentElement: unknown\n }\n}\n\n/** The pixel size a data URI's image holds, as svg2pdf asks an `Image` for it. */\nfunction imageSize(source: string): [number, number] {\n const comma = source.indexOf(',')\n if (comma === -1 || !source.slice(0, comma).includes(';base64')) {\n throw new Error('Not a base64 data URI')\n }\n const bytes = toUint8Array(source.slice(comma + 1))\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n const starts = (text: string, at = 0) =>\n Array.from(text, (character, index) => bytes[at + index] === character.charCodeAt(0)).every(\n Boolean\n )\n if (starts('\\x89PNG')) return [view.getUint32(16), view.getUint32(20)]\n if (starts('GIF8')) return [view.getUint16(6, true), view.getUint16(8, true)]\n if (starts('RIFF') && starts('WEBP', 8)) {\n const kind = String.fromCharCode(...bytes.subarray(12, 16))\n if (kind === 'VP8X') {\n return [\n 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16)),\n 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16))\n ]\n }\n if (kind === 'VP8 ')\n return [view.getUint16(26, true) & 0x3fff, view.getUint16(28, true) & 0x3fff]\n }\n if (bytes[0] === 0xff && bytes[1] === 0xd8) {\n for (let at = 2; at + 9 < bytes.length;) {\n if (bytes[at] !== 0xff) {\n at++\n continue\n }\n const marker = bytes[at + 1]\n const length = view.getUint16(at + 2)\n // Start-of-frame markers carry the image's size; C4, C8, and CC are other segments.\n if (\n marker >= 0xc0 &&\n marker <= 0xcf &&\n marker !== 0xc4 &&\n marker !== 0xc8 &&\n marker !== 0xcc\n ) {\n return [view.getUint16(at + 7), view.getUint16(at + 5)]\n }\n at += 2 + length\n }\n }\n throw new Error('Unsupported image data')\n}\n\n/**\n * The `Image` svg2pdf asks for an image's size by name, for a host without one: it decodes only a\n * base64 data URI's header, which is all the size needs.\n */\nclass HeadlessImage {\n width = 0\n height = 0\n onload: (() => void) | null = null\n onerror: ((error: unknown) => void) | null = null\n\n set src(value: string) {\n try {\n const [width, height] = imageSize(value)\n this.width = width\n this.height = height\n queueMicrotask(() => this.onload?.())\n } catch (error) {\n queueMicrotask(() => this.onerror?.(error))\n }\n }\n}\n\n/**\n * The globals svg2pdf reads: it parses a page's stylesheets in a document it makes, and keeps the\n * rules that are instances of the CSSOM classes.\n */\ninterface SVG2PDFGlobals {\n document?: unknown\n CSSStyleSheet?: unknown\n CSSStyleRule?: unknown\n Image?: unknown\n}\n\nconst SVG2PDF_GLOBALS = ['document', 'CSSStyleSheet', 'CSSStyleRule'] as const\n\ntype SVG2PDFGlobal = (typeof SVG2PDF_GLOBALS)[number] | 'Image'\n\nfunction removeGlobal(scope: SVG2PDFGlobals, name: SVG2PDFGlobal): void {\n if (name === 'document') delete scope.document\n else if (name === 'CSSStyleSheet') delete scope.CSSStyleSheet\n else if (name === 'Image') delete scope.Image\n else delete scope.CSSStyleRule\n}\n\n/**\n * Kept out of the browser bundle: a browser has a DOM of its own, and happy-dom is only loaded\n * where there is none.\n */\nconst HAPPY_DOM = 'happy-dom'\n\nlet exporting: Promise<unknown> = Promise.resolve()\n\nfunction isElement(value: unknown): value is Element {\n return typeof value === 'object' && value !== null && 'tagName' in value\n}\n\nfunction parseSVGPage(parser: SVGParser): SVGPageParser {\n return (svg) => {\n const parsed = parser.parseFromString(svg, 'image/svg+xml')\n if (parsed.querySelector('parsererror')) return null\n return isElement(parsed.documentElement) ? parsed.documentElement : null\n }\n}\n\n/**\n * Runs `draw` with a parser for page SVG and the DOM svg2pdf draws it through. A browser has both.\n * Elsewhere, as in the CLI, happy-dom stands in: svg2pdf reads its DOM as globals, so they are set\n * only while `draw` runs, one export at a time, and restored after.\n */\nexport function withPDFDOM<T>(draw: (parse: SVGPageParser) => Promise<T>): Promise<T> {\n if (IS_BROWSER) return draw(parseSVGPage(new DOMParser()))\n const run = exporting.then(() => withHappyDOM(draw))\n exporting = run.catch(() => undefined)\n return run\n}\n\nasync function withHappyDOM<T>(draw: (parse: SVGPageParser) => Promise<T>): Promise<T> {\n const { Window } = (await import(/* @vite-ignore */ HAPPY_DOM)) as typeof HappyDOM\n const dom = new Window()\n const scope: SVG2PDFGlobals = globalThis\n const values: Record<SVG2PDFGlobal, unknown> = {\n document: dom.document,\n CSSStyleSheet: dom.CSSStyleSheet,\n CSSStyleRule: dom.CSSStyleRule,\n Image: HeadlessImage\n }\n // Each global replaced, with its descriptor before, so an accessor a host defines comes back as\n // one and a global that could not be replaced is left as it was.\n const replaced: Array<[SVG2PDFGlobal, PropertyDescriptor | undefined]> = []\n let replacedImage: PropertyDescriptor | undefined\n let hadImage = false\n try {\n // svg2pdf reads an image's size through a browser `Image`, which a CLI host lacks.\n if (!('Image' in globalThis)) {\n replacedImage = Object.getOwnPropertyDescriptor(globalThis, 'Image')\n hadImage = false\n Object.defineProperty(globalThis, 'Image', {\n value: HeadlessImage,\n configurable: true,\n writable: true\n })\n } else {\n hadImage = true\n }\n for (const name of SVG2PDF_GLOBALS) {\n const previous = Object.getOwnPropertyDescriptor(globalThis, name)\n Object.defineProperty(globalThis, name, {\n value: values[name],\n configurable: true,\n writable: true\n })\n replaced.push([name, previous])\n }\n return await draw(parseSVGPage(new dom.DOMParser()))\n } finally {\n // What is replaced is configurable, so putting it back does not throw.\n for (const [name, previous] of replaced) {\n if (previous) Object.defineProperty(globalThis, name, previous)\n else removeGlobal(scope, name)\n }\n if (!hadImage) {\n if (replacedImage) Object.defineProperty(globalThis, 'Image', replacedImage)\n else removeGlobal(scope, 'Image')\n }\n await dom.happyDOM.close()\n }\n}\n\n/**\n * Loads `svg2pdf.js`. Its package publishes a UMD build only, whose factory reads jsPDF from the\n * global `jspdf` and, with no CommonJS `exports`, writes the function to the global `svg2pdf`; a\n * bundler supplies both, a bare Node install supplies neither, and the module then fails on load.\n * The two globals exist only while the import evaluates, and the function the module made keeps\n * the jsPDF it read, so the rest of the export needs nothing from them.\n */\n/**\n * svg2pdf.js's `main` is a UMD build in a `\"type\": \"module\"` package with no `exports`, so Node\n * loads it as ESM and it throws for want of a global jsPDF. Its ES build, the `module` file\n * bundlers and Bun already pick, loads everywhere.\n */\nexport async function loadSVG2PDF(): Promise<typeof svg2pdf> {\n const module = (await import('svg2pdf.js/dist/svg2pdf.es.min.js')) as {\n svg2pdf?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@@ -40,7 +40,7 @@ async function renderPages(graph, specs, options, parse) {
|
|
|
40
40
|
if (prepared.length === 0) return null;
|
|
41
41
|
const first = prepared[0];
|
|
42
42
|
const { jsPDF } = await import("jspdf");
|
|
43
|
-
const svg2pdf = await loadSVG2PDF(
|
|
43
|
+
const svg2pdf = await loadSVG2PDF();
|
|
44
44
|
const doc = new jsPDF({
|
|
45
45
|
orientation: orientationOf(first),
|
|
46
46
|
unit: "pt",
|