@pairdraw/core 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/canvas/noise/render.js +1 -1
- package/dist/canvas/noise/render.js.map +1 -1
- package/dist/canvas/noise/shader.d.ts +6 -3
- package/dist/canvas/noise/shader.d.ts.map +1 -1
- package/dist/canvas/noise/shader.js +12 -7
- package/dist/canvas/noise/shader.js.map +1 -1
- package/dist/canvas/noise/tile.d.ts.map +1 -1
- package/dist/canvas/noise/tile.js +2 -1
- package/dist/canvas/noise/tile.js.map +1 -1
- package/dist/canvas/renderer/colors.d.ts +20 -5
- package/dist/canvas/renderer/colors.d.ts.map +1 -1
- package/dist/canvas/renderer/colors.js +48 -42
- package/dist/canvas/renderer/colors.js.map +1 -1
- package/dist/canvas/renderer/document-surface.d.ts +25 -0
- package/dist/canvas/renderer/document-surface.d.ts.map +1 -0
- package/dist/canvas/renderer/document-surface.js +46 -0
- package/dist/canvas/renderer/document-surface.js.map +1 -0
- package/dist/canvas/renderer/fonts.d.ts.map +1 -1
- package/dist/canvas/renderer/fonts.js +6 -4
- package/dist/canvas/renderer/fonts.js.map +1 -1
- package/dist/canvas/renderer/lifecycle.js +4 -3
- package/dist/canvas/renderer/lifecycle.js.map +1 -1
- package/dist/canvas/renderer/methods.d.ts.map +1 -1
- package/dist/canvas/renderer/methods.js +1 -0
- package/dist/canvas/renderer/methods.js.map +1 -1
- package/dist/canvas/renderer/pipeline.d.ts.map +1 -1
- package/dist/canvas/renderer/pipeline.js +23 -2
- package/dist/canvas/renderer/pipeline.js.map +1 -1
- package/dist/canvas/renderer/retained-backing.d.ts.map +1 -1
- package/dist/canvas/renderer/retained-backing.js +2 -1
- package/dist/canvas/renderer/retained-backing.js.map +1 -1
- package/dist/canvas/renderer/tiles/surface-pool.d.ts.map +1 -1
- package/dist/canvas/renderer/tiles/surface-pool.js +2 -7
- package/dist/canvas/renderer/tiles/surface-pool.js.map +1 -1
- package/dist/canvas/renderer.d.ts +20 -2
- package/dist/canvas/renderer.d.ts.map +1 -1
- package/dist/canvas/renderer.js +28 -4
- package/dist/canvas/renderer.js.map +1 -1
- package/dist/canvas/scene.d.ts.map +1 -1
- package/dist/canvas/scene.js +4 -3
- package/dist/canvas/scene.js.map +1 -1
- package/dist/canvas/shaders/effect.d.ts.map +1 -1
- package/dist/canvas/shaders/effect.js +2 -1
- package/dist/canvas/shaders/effect.js.map +1 -1
- package/dist/canvas/shadows/shape.d.ts.map +1 -1
- package/dist/canvas/shadows/shape.js +4 -2
- package/dist/canvas/shadows/shape.js.map +1 -1
- package/dist/canvas/shadows.d.ts.map +1 -1
- package/dist/canvas/shadows.js +4 -2
- package/dist/canvas/shadows.js.map +1 -1
- package/dist/canvas/text/decorations.d.ts +2 -2
- package/dist/canvas/text/decorations.d.ts.map +1 -1
- package/dist/canvas/text/decorations.js +5 -5
- package/dist/canvas/text/decorations.js.map +1 -1
- package/dist/canvas/text/index.js +1 -1
- package/dist/canvas/text/index.js.map +1 -1
- package/dist/canvas/text/paragraph/index.d.ts +2 -2
- package/dist/canvas/text/paragraph/index.d.ts.map +1 -1
- package/dist/canvas/text/paragraph/index.js +16 -5
- package/dist/canvas/text/paragraph/index.js.map +1 -1
- package/dist/canvas/text/renderer.d.ts +2 -1
- package/dist/canvas/text/renderer.d.ts.map +1 -1
- package/dist/canvas/text/shape.js +4 -4
- package/dist/canvas/text/shape.js.map +1 -1
- package/dist/canvas/texture.d.ts.map +1 -1
- package/dist/canvas/texture.js +2 -1
- package/dist/canvas/texture.js.map +1 -1
- package/dist/design-memory/rules.js +1 -1
- package/dist/editor/bridges/undo.d.ts +1 -1
- package/dist/editor/clipboard/assets.d.ts.map +1 -1
- package/dist/editor/clipboard/assets.js +2 -2
- package/dist/editor/clipboard/assets.js.map +1 -1
- package/dist/editor/clipboard/component-matches.d.ts +13 -0
- package/dist/editor/clipboard/component-matches.d.ts.map +1 -0
- package/dist/editor/clipboard/component-matches.js +50 -0
- package/dist/editor/clipboard/component-matches.js.map +1 -0
- package/dist/editor/clipboard/dependencies.d.ts +7 -0
- package/dist/editor/clipboard/dependencies.d.ts.map +1 -1
- package/dist/editor/clipboard/dependencies.js +5 -0
- package/dist/editor/clipboard/dependencies.js.map +1 -1
- package/dist/editor/clipboard.d.ts.map +1 -1
- package/dist/editor/clipboard.js +48 -19
- package/dist/editor/clipboard.js.map +1 -1
- package/dist/editor/components/properties.d.ts.map +1 -1
- package/dist/editor/components/properties.js +3 -3
- package/dist/editor/components/properties.js.map +1 -1
- package/dist/editor/create.d.ts +1 -1
- package/dist/editor/eyedropper.d.ts +1 -1
- package/dist/editor/eyedropper.d.ts.map +1 -1
- package/dist/editor/eyedropper.js +6 -3
- package/dist/editor/eyedropper.js.map +1 -1
- package/dist/editor/history/atomic-tool.d.ts.map +1 -1
- package/dist/editor/history/atomic-tool.js +3 -2
- package/dist/editor/history/atomic-tool.js.map +1 -1
- package/dist/editor/shapes/pencil.js +1 -1
- package/dist/editor/structure/state.d.ts.map +1 -1
- package/dist/editor/structure/state.js +2 -2
- package/dist/editor/structure/state.js.map +1 -1
- package/dist/editor/text.d.ts.map +1 -1
- package/dist/editor/text.js +2 -2
- package/dist/editor/text.js.map +1 -1
- package/dist/editor/variables.js +3 -3
- package/dist/editor/variables.js.map +1 -1
- package/dist/figma-api/fresh-read.d.ts +15 -0
- package/dist/figma-api/fresh-read.d.ts.map +1 -0
- package/dist/figma-api/fresh-read.js +54 -0
- package/dist/figma-api/fresh-read.js.map +1 -0
- package/dist/figma-api/graph-ref.d.ts +9 -0
- package/dist/figma-api/graph-ref.d.ts.map +1 -0
- package/dist/figma-api/graph-ref.js +14 -0
- package/dist/figma-api/graph-ref.js.map +1 -0
- package/dist/figma-api/index.d.ts +6 -1
- package/dist/figma-api/index.d.ts.map +1 -1
- package/dist/figma-api/index.js +12 -5
- package/dist/figma-api/index.js.map +1 -1
- package/dist/figma-api/pending-layout.d.ts +3 -3
- package/dist/figma-api/pending-layout.d.ts.map +1 -1
- package/dist/figma-api/pending-layout.js +7 -3
- package/dist/figma-api/pending-layout.js.map +1 -1
- package/dist/figma-api/pending-sync.d.ts +1 -1
- package/dist/figma-api/pending-sync.d.ts.map +1 -1
- package/dist/figma-api/pending-sync.js +3 -1
- package/dist/figma-api/pending-sync.js.map +1 -1
- package/dist/figma-api/proxy.d.ts.map +1 -1
- package/dist/figma-api/proxy.js +3 -2
- package/dist/figma-api/proxy.js.map +1 -1
- package/dist/figma-api/reactions.d.ts +20 -4
- package/dist/figma-api/reactions.d.ts.map +1 -1
- package/dist/figma-api/reactions.js +49 -3
- package/dist/figma-api/reactions.js.map +1 -1
- package/dist/figma-api/variables/index.d.ts.map +1 -1
- package/dist/figma-api/variables/index.js +2 -2
- package/dist/figma-api/variables/index.js.map +1 -1
- package/dist/io/formats/design-tokens/css/known.js +1 -1
- package/dist/io/formats/design-tokens/css/known.js.map +1 -1
- package/dist/io/formats/design-tokens/css/read.d.ts +3 -1
- package/dist/io/formats/design-tokens/css/read.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/css/read.js +11 -5
- package/dist/io/formats/design-tokens/css/read.js.map +1 -1
- package/dist/io/formats/design-tokens/css/sync.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/css/sync.js +17 -4
- package/dist/io/formats/design-tokens/css/sync.js.map +1 -1
- package/dist/io/formats/design-tokens/css/values.d.ts +6 -5
- package/dist/io/formats/design-tokens/css/values.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/css/values.js +24 -8
- package/dist/io/formats/design-tokens/css/values.js.map +1 -1
- package/dist/io/formats/design-tokens/decode.d.ts +7 -6
- package/dist/io/formats/design-tokens/decode.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/decode.js +13 -12
- package/dist/io/formats/design-tokens/decode.js.map +1 -1
- package/dist/io/formats/design-tokens/export.js +3 -3
- package/dist/io/formats/design-tokens/export.js.map +1 -1
- package/dist/io/formats/design-tokens/plan/index.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/plan/index.js +4 -3
- package/dist/io/formats/design-tokens/plan/index.js.map +1 -1
- package/dist/io/formats/design-tokens/plan/styles.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/plan/styles.js +9 -9
- package/dist/io/formats/design-tokens/plan/styles.js.map +1 -1
- package/dist/io/formats/design-tokens/styles.d.ts +4 -4
- package/dist/io/formats/design-tokens/styles.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/styles.js +7 -7
- package/dist/io/formats/design-tokens/styles.js.map +1 -1
- package/dist/io/formats/design-tokens/sync/drift.js +2 -2
- package/dist/io/formats/design-tokens/sync/drift.js.map +1 -1
- package/dist/io/formats/design-tokens/values.d.ts +10 -5
- package/dist/io/formats/design-tokens/values.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/values.js +13 -7
- package/dist/io/formats/design-tokens/values.js.map +1 -1
- package/dist/io/formats/drawio/label.js +1 -1
- package/dist/io/formats/drawio/paint.js +1 -1
- package/dist/io/formats/drawio/warnings.js +2 -2
- package/dist/io/formats/drawio/warnings.js.map +1 -1
- package/dist/io/formats/fig/export/index.d.ts.map +1 -1
- package/dist/io/formats/fig/export/index.js +15 -3
- package/dist/io/formats/fig/export/index.js.map +1 -1
- package/dist/io/formats/fig/export/patch/index.d.ts.map +1 -1
- package/dist/io/formats/fig/export/patch/index.js +2 -1
- package/dist/io/formats/fig/export/patch/index.js.map +1 -1
- package/dist/io/formats/fig/export/setup.d.ts +7 -2
- package/dist/io/formats/fig/export/setup.d.ts.map +1 -1
- package/dist/io/formats/fig/export/setup.js +12 -13
- package/dist/io/formats/fig/export/setup.js.map +1 -1
- package/dist/io/formats/fig/export/variables.d.ts.map +1 -1
- package/dist/io/formats/fig/export/variables.js +9 -7
- package/dist/io/formats/fig/export/variables.js.map +1 -1
- package/dist/io/formats/html/vectors.js +1 -0
- package/dist/io/formats/html/vectors.js.map +1 -1
- package/dist/io/formats/mermaid/layers.js +2 -2
- package/dist/io/formats/mermaid/layers.js.map +1 -1
- package/dist/io/formats/mermaid/styles.js +1 -1
- package/dist/io/formats/pdf/export.d.ts.map +1 -1
- package/dist/io/formats/pdf/export.js +1 -0
- package/dist/io/formats/pdf/export.js.map +1 -1
- package/dist/io/formats/pdf/prepare.d.ts +4 -4
- package/dist/io/formats/pdf/prepare.d.ts.map +1 -1
- package/dist/io/formats/pdf/prepare.js +2 -2
- package/dist/io/formats/pdf/prepare.js.map +1 -1
- package/dist/io/formats/pen/index.js +4 -2
- package/dist/io/formats/pen/index.js.map +1 -1
- package/dist/io/formats/pptx/style.js +1 -1
- package/dist/io/formats/raster/render.d.ts +1 -1
- package/dist/io/formats/raster/render.d.ts.map +1 -1
- package/dist/io/formats/raster/render.js +9 -4
- package/dist/io/formats/raster/render.js.map +1 -1
- package/dist/io/formats/svg/defs.d.ts +6 -3
- package/dist/io/formats/svg/defs.d.ts.map +1 -1
- package/dist/io/formats/svg/defs.js +12 -11
- package/dist/io/formats/svg/defs.js.map +1 -1
- package/dist/io/formats/svg/effects.js +2 -2
- package/dist/io/formats/svg/effects.js.map +1 -1
- package/dist/io/formats/svg/export.d.ts +5 -2
- package/dist/io/formats/svg/export.d.ts.map +1 -1
- package/dist/io/formats/svg/export.js +4 -2
- package/dist/io/formats/svg/export.js.map +1 -1
- package/dist/io/formats/svg/filter.d.ts +4 -1
- package/dist/io/formats/svg/filter.d.ts.map +1 -1
- package/dist/io/formats/svg/filter.js +6 -2
- package/dist/io/formats/svg/filter.js.map +1 -1
- package/dist/io/formats/svg/grain.js +1 -1
- package/dist/io/formats/svg/grain.js.map +1 -1
- package/dist/io/formats/svg/import.d.ts +4 -2
- package/dist/io/formats/svg/import.d.ts.map +1 -1
- package/dist/io/formats/svg/import.js +2 -1
- package/dist/io/formats/svg/import.js.map +1 -1
- package/dist/io/formats/svg/text/export.d.ts.map +1 -1
- package/dist/io/formats/svg/text/export.js +8 -8
- package/dist/io/formats/svg/text/export.js.map +1 -1
- package/dist/io/formats/svg/text/layout.js +2 -2
- package/dist/io/formats/svg/text/layout.js.map +1 -1
- package/dist/io/formats.d.ts.map +1 -1
- package/dist/io/formats.js +1 -0
- package/dist/io/formats.js.map +1 -1
- package/dist/io/subgraph.d.ts.map +1 -1
- package/dist/io/subgraph.js +1 -1
- package/dist/io/subgraph.js.map +1 -1
- package/dist/io/types.d.ts +1 -1
- package/dist/kiwi/fig/session/options.d.ts +3 -0
- package/dist/kiwi/fig/session/options.d.ts.map +1 -1
- package/dist/kiwi/fig/session/options.js +4 -0
- package/dist/kiwi/fig/session/options.js.map +1 -1
- package/dist/layout/yoga-helpers.d.ts +2 -1
- package/dist/layout/yoga-helpers.d.ts.map +1 -1
- package/dist/layout/yoga-helpers.js +7 -1
- package/dist/layout/yoga-helpers.js.map +1 -1
- package/dist/layout.js +24 -1
- package/dist/layout.js.map +1 -1
- package/dist/lint/fixes.js +1 -1
- package/dist/lint/linter.js +2 -2
- package/dist/lint/linter.js.map +1 -1
- package/dist/pairdraw-api/comments.d.ts +4 -1
- package/dist/pairdraw-api/comments.d.ts.map +1 -1
- package/dist/pairdraw-api/comments.js +5 -0
- package/dist/pairdraw-api/comments.js.map +1 -1
- package/dist/pairdraw-api/index.d.ts +3 -3
- package/dist/pairdraw-api/index.d.ts.map +1 -1
- package/dist/pairdraw-api/index.js +5 -5
- package/dist/pairdraw-api/index.js.map +1 -1
- package/dist/pairdraw-api/nodes.d.ts +1 -1
- package/dist/prototype/scene.js +1 -1
- package/dist/rpc/analyze-commands.js +1 -1
- package/dist/rpc/read-commands.d.ts +2 -2
- package/dist/rpc/read-commands.js +3 -3
- package/dist/rpc/read-commands.js.map +1 -1
- package/dist/rpc/variables-command.js +2 -2
- package/dist/rpc/variables-command.js.map +1 -1
- package/dist/text/font/provider.d.ts +15 -0
- package/dist/text/font/provider.d.ts.map +1 -0
- package/dist/text/font/provider.js +18 -0
- package/dist/text/font/provider.js.map +1 -0
- package/dist/text/font/readiness.d.ts +32 -0
- package/dist/text/font/readiness.d.ts.map +1 -0
- package/dist/text/font/{status.js → readiness.js} +8 -4
- package/dist/text/font/readiness.js.map +1 -0
- package/dist/text/index.d.ts +4 -3
- package/dist/text/index.js +4 -3
- package/dist/text/prepare.d.ts +9 -4
- package/dist/text/prepare.d.ts.map +1 -1
- package/dist/text/prepare.js +9 -4
- package/dist/text/prepare.js.map +1 -1
- package/dist/tools/analyze/colors.js +1 -1
- package/dist/tools/analyze/responsive/index.js +7 -18
- package/dist/tools/analyze/responsive/index.js.map +1 -1
- package/dist/tools/analyze/responsive/widths.d.ts +27 -0
- package/dist/tools/analyze/responsive/widths.d.ts.map +1 -0
- package/dist/tools/analyze/responsive/widths.js +49 -0
- package/dist/tools/analyze/responsive/widths.js.map +1 -0
- package/dist/tools/analyze.d.ts +2 -1
- package/dist/tools/analyze.js +2 -1
- package/dist/tools/codegen/tokens.d.ts.map +1 -1
- package/dist/tools/codegen/tokens.js +2 -2
- package/dist/tools/codegen/tokens.js.map +1 -1
- package/dist/tools/comments.d.ts.map +1 -1
- package/dist/tools/comments.js +2 -2
- package/dist/tools/comments.js.map +1 -1
- package/dist/tools/component-catalog.d.ts.map +1 -1
- package/dist/tools/component-catalog.js +5 -3
- package/dist/tools/component-catalog.js.map +1 -1
- package/dist/tools/create/basic.js +1 -1
- package/dist/tools/create/behaviours.js +1 -1
- package/dist/tools/create/html.d.ts.map +1 -1
- package/dist/tools/create/html.js +1 -3
- package/dist/tools/create/html.js.map +1 -1
- package/dist/tools/create/icons.js +2 -2
- package/dist/tools/create/icons.js.map +1 -1
- package/dist/tools/create/mermaid.js +1 -1
- package/dist/tools/create/render.js +1 -1
- package/dist/tools/create/svg.js +5 -2
- package/dist/tools/create/svg.js.map +1 -1
- package/dist/tools/create/vector.js +3 -3
- package/dist/tools/create/vector.js.map +1 -1
- package/dist/tools/css/shorthand.d.ts +20 -0
- package/dist/tools/css/shorthand.d.ts.map +1 -0
- package/dist/tools/css/shorthand.js +54 -0
- package/dist/tools/css/shorthand.js.map +1 -0
- package/dist/tools/describe/index.js +2 -2
- package/dist/tools/describe/index.js.map +1 -1
- package/dist/tools/describe/issues.js +1 -1
- package/dist/tools/html-host.d.ts.map +1 -1
- package/dist/tools/html-host.js +5 -3
- package/dist/tools/html-host.js.map +1 -1
- package/dist/tools/image-ai/apply.d.ts.map +1 -1
- package/dist/tools/image-ai/apply.js +1 -3
- package/dist/tools/image-ai/apply.js.map +1 -1
- package/dist/tools/image-ai/generate.js +1 -1
- package/dist/tools/image-ai/service.d.ts.map +1 -1
- package/dist/tools/image-ai/service.js +5 -3
- package/dist/tools/image-ai/service.js.map +1 -1
- package/dist/tools/index.d.ts +2 -1
- package/dist/tools/index.js +2 -1
- package/dist/tools/modify/effects.js +1 -1
- package/dist/tools/modify/effects.js.map +1 -1
- package/dist/tools/modify/geometry.d.ts.map +1 -1
- package/dist/tools/modify/geometry.js +14 -3
- package/dist/tools/modify/geometry.js.map +1 -1
- package/dist/tools/modify/layout.d.ts.map +1 -1
- package/dist/tools/modify/layout.js +35 -8
- package/dist/tools/modify/layout.js.map +1 -1
- package/dist/tools/modify/matching.d.ts.map +1 -1
- package/dist/tools/modify/matching.js +10 -10
- package/dist/tools/modify/matching.js.map +1 -1
- package/dist/tools/modify/paint.d.ts.map +1 -1
- package/dist/tools/modify/paint.js +57 -5
- package/dist/tools/modify/paint.js.map +1 -1
- package/dist/tools/modify/reactions.d.ts.map +1 -1
- package/dist/tools/modify/reactions.js +2 -2
- package/dist/tools/modify/reactions.js.map +1 -1
- package/dist/tools/modify/text.d.ts.map +1 -1
- package/dist/tools/modify/text.js +3 -3
- package/dist/tools/modify/text.js.map +1 -1
- package/dist/tools/prompts/codegen.js +1 -1
- package/dist/tools/prompts/codegen.js.map +1 -1
- package/dist/tools/read/css.d.ts +14 -0
- package/dist/tools/read/css.d.ts.map +1 -0
- package/dist/tools/read/css.js +306 -0
- package/dist/tools/read/css.js.map +1 -0
- package/dist/tools/read/libraries.js +1 -1
- package/dist/tools/read/reactions.js +1 -1
- package/dist/tools/read/reactions.js.map +1 -1
- package/dist/tools/read/space.d.ts.map +1 -1
- package/dist/tools/read/space.js +0 -2
- package/dist/tools/read/space.js.map +1 -1
- package/dist/tools/read.d.ts +2 -1
- package/dist/tools/read.js +2 -1
- package/dist/tools/registry/core.d.ts +1 -1
- package/dist/tools/registry/core.js +3 -1
- package/dist/tools/registry/core.js.map +1 -1
- package/dist/tools/schema.d.ts +6 -4
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +9 -5
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/script/host.d.ts.map +1 -1
- package/dist/tools/script/host.js +5 -3
- package/dist/tools/script/host.js.map +1 -1
- package/dist/tools/variables/collections.js +1 -1
- package/dist/tools/variables/collections.js.map +1 -1
- package/dist/tools/variables/values.d.ts.map +1 -1
- package/dist/tools/variables/values.js +4 -4
- package/dist/tools/variables/values.js.map +1 -1
- package/dist/tools/vector/vectorize.d.ts.map +1 -1
- package/dist/tools/vector/vectorize.js +6 -4
- package/dist/tools/vector/vectorize.js.map +1 -1
- package/dist/tools/video-host.d.ts.map +1 -1
- package/dist/tools/video-host.js +5 -3
- package/dist/tools/video-host.js.map +1 -1
- package/dist/vector/vectorize/svg/gradients.d.ts +2 -2
- package/dist/vector/vectorize/svg/gradients.d.ts.map +1 -1
- package/dist/vector/vectorize/svg/gradients.js +5 -5
- package/dist/vector/vectorize/svg/gradients.js.map +1 -1
- package/dist/vector/vectorize/svg/to-vectors.d.ts +3 -1
- package/dist/vector/vectorize/svg/to-vectors.d.ts.map +1 -1
- package/dist/vector/vectorize/svg/to-vectors.js +13 -12
- package/dist/vector/vectorize/svg/to-vectors.js.map +1 -1
- package/package.json +9 -9
- package/src/canvas/noise/render.ts +1 -1
- package/src/canvas/noise/shader.ts +13 -5
- package/src/canvas/noise/tile.ts +2 -1
- package/src/canvas/renderer/colors.ts +76 -50
- package/src/canvas/renderer/document-surface.ts +53 -0
- package/src/canvas/renderer/fonts.ts +6 -4
- package/src/canvas/renderer/lifecycle.ts +4 -4
- package/src/canvas/renderer/methods.ts +1 -0
- package/src/canvas/renderer/pipeline.ts +21 -3
- package/src/canvas/renderer/retained-backing.ts +2 -1
- package/src/canvas/renderer/tiles/surface-pool.ts +9 -7
- package/src/canvas/renderer.ts +36 -11
- package/src/canvas/scene.ts +4 -3
- package/src/canvas/shaders/effect.ts +2 -1
- package/src/canvas/shadows/shape.ts +4 -2
- package/src/canvas/shadows.ts +5 -2
- package/src/canvas/text/decorations.ts +15 -5
- package/src/canvas/text/index.ts +9 -1
- package/src/canvas/text/paragraph/index.ts +16 -6
- package/src/canvas/text/renderer.ts +2 -1
- package/src/canvas/text/shape.ts +4 -4
- package/src/canvas/texture.ts +2 -1
- package/src/editor/clipboard/assets.ts +6 -2
- package/src/editor/clipboard/component-matches.ts +65 -0
- package/src/editor/clipboard/dependencies.ts +22 -1
- package/src/editor/clipboard.ts +74 -20
- package/src/editor/components/properties.ts +3 -2
- package/src/editor/eyedropper.ts +14 -4
- package/src/editor/history/atomic-tool.ts +3 -2
- package/src/editor/structure/state.ts +2 -1
- package/src/editor/text.ts +2 -1
- package/src/editor/variables.ts +3 -3
- package/src/figma-api/fresh-read.ts +57 -0
- package/src/figma-api/graph-ref.ts +13 -0
- package/src/figma-api/index.ts +12 -4
- package/src/figma-api/pending-layout.ts +7 -3
- package/src/figma-api/pending-sync.ts +4 -1
- package/src/figma-api/proxy.ts +2 -1
- package/src/figma-api/reactions.ts +91 -10
- package/src/figma-api/variables/index.ts +5 -4
- package/src/io/formats/design-tokens/css/known.ts +1 -1
- package/src/io/formats/design-tokens/css/read.ts +20 -7
- package/src/io/formats/design-tokens/css/sync.ts +9 -4
- package/src/io/formats/design-tokens/css/values.ts +37 -9
- package/src/io/formats/design-tokens/decode.ts +17 -12
- package/src/io/formats/design-tokens/export.ts +3 -3
- package/src/io/formats/design-tokens/plan/index.ts +6 -5
- package/src/io/formats/design-tokens/plan/styles.ts +37 -10
- package/src/io/formats/design-tokens/styles.ts +10 -7
- package/src/io/formats/design-tokens/sync/drift.ts +6 -4
- package/src/io/formats/design-tokens/values.ts +15 -8
- package/src/io/formats/drawio/warnings.ts +2 -2
- package/src/io/formats/fig/export/index.ts +36 -3
- package/src/io/formats/fig/export/patch/index.ts +4 -1
- package/src/io/formats/fig/export/setup.ts +25 -15
- package/src/io/formats/fig/export/variables.ts +17 -6
- package/src/io/formats/html/vectors.ts +1 -0
- package/src/io/formats/mermaid/layers.ts +2 -2
- package/src/io/formats/pdf/export.ts +1 -0
- package/src/io/formats/pdf/prepare.ts +6 -6
- package/src/io/formats/pen/index.ts +5 -2
- package/src/io/formats/raster/render.ts +12 -4
- package/src/io/formats/svg/defs.ts +26 -14
- package/src/io/formats/svg/effects.ts +2 -2
- package/src/io/formats/svg/export.ts +17 -3
- package/src/io/formats/svg/filter.ts +12 -2
- package/src/io/formats/svg/grain.ts +1 -1
- package/src/io/formats/svg/import.ts +6 -3
- package/src/io/formats/svg/text/export.ts +10 -8
- package/src/io/formats/svg/text/layout.ts +2 -2
- package/src/io/formats.ts +8 -1
- package/src/io/subgraph.ts +4 -1
- package/src/kiwi/fig/session/options.ts +4 -1
- package/src/layout/yoga-helpers.ts +8 -0
- package/src/layout.ts +47 -1
- package/src/lint/linter.ts +1 -1
- package/src/pairdraw-api/comments.ts +6 -0
- package/src/pairdraw-api/index.ts +7 -9
- package/src/rpc/read-commands.ts +4 -4
- package/src/rpc/variables-command.ts +2 -2
- package/src/text/font/provider.ts +26 -0
- package/src/text/font/{status.ts → readiness.ts} +13 -9
- package/src/text/index.ts +2 -1
- package/src/text/prepare.ts +9 -4
- package/src/tools/analyze/responsive/index.ts +8 -15
- package/src/tools/analyze/responsive/widths.ts +63 -0
- package/src/tools/analyze.ts +2 -0
- package/src/tools/codegen/tokens.ts +4 -2
- package/src/tools/comments.ts +6 -4
- package/src/tools/component-catalog.ts +5 -3
- package/src/tools/create/html.ts +0 -3
- package/src/tools/create/icons.ts +1 -1
- package/src/tools/create/svg.ts +4 -1
- package/src/tools/create/vector.ts +2 -2
- package/src/tools/css/shorthand.ts +64 -0
- package/src/tools/describe/index.ts +2 -8
- package/src/tools/html-host.ts +5 -3
- package/src/tools/image-ai/apply.ts +0 -2
- package/src/tools/image-ai/service.ts +5 -3
- package/src/tools/index.ts +2 -0
- package/src/tools/modify/effects.ts +1 -1
- package/src/tools/modify/geometry.ts +16 -3
- package/src/tools/modify/layout.ts +47 -13
- package/src/tools/modify/matching.ts +14 -11
- package/src/tools/modify/paint.ts +85 -5
- package/src/tools/modify/reactions.ts +3 -2
- package/src/tools/modify/text.ts +15 -11
- package/src/tools/prompts/codegen.md +2 -1
- package/src/tools/read/css.ts +365 -0
- package/src/tools/read/reactions.ts +3 -2
- package/src/tools/read/space.ts +0 -2
- package/src/tools/read.ts +1 -0
- package/src/tools/registry/core.ts +3 -2
- package/src/tools/schema.ts +14 -5
- package/src/tools/script/host.ts +6 -3
- package/src/tools/variables/collections.ts +1 -1
- package/src/tools/variables/values.ts +16 -5
- package/src/tools/vector/vectorize.ts +10 -4
- package/src/tools/video-host.ts +5 -3
- package/src/vector/vectorize/svg/gradients.ts +8 -5
- package/src/vector/vectorize/svg/to-vectors.ts +48 -14
- package/dist/text/font/status.d.ts +0 -28
- package/dist/text/font/status.d.ts.map +0 -1
- package/dist/text/font/status.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setup.js","names":[],"sources":["../../../../../src/io/formats/fig/export/setup.ts"],"sourcesContent":["import type { CanvasKit } from 'canvaskit-wasm'\nimport { deflateSync, inflateSync } from 'fflate'\nimport { toUint8Array } from 'js-base64'\n\nimport { figArchiveMetaJSON, figFontEntries, figFontsManifest } from '@pairdraw/fig'\nimport {\n buildComponentPropIndex,\n exportCanvasGuides,\n figImageEntries,\n importCanvasGuides,\n parseGuidOrNull,\n type FigNodeChangeExportRuntime,\n makeCanvasNodeChange,\n makeDocumentNodeChange\n} from '@pairdraw/fig/node-change'\nimport { getCompiledSchema, getSchemaBytes, type NodeChange } from '@pairdraw/kiwi/fig/codec'\nimport { stringToGuid } from '@pairdraw/kiwi/fig/guid'\nimport { decodeBinarySchema, compileSchema, ByteBuffer } from '@pairdraw/kiwi/schema-runtime'\nimport type { PluginDataEntry, SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n readBehaviour,\n renameBehaviourProperties,\n withBehaviour\n} from '@pairdraw/scene-graph/behaviours'\nimport { orderKeyBetween, siblingOrderKeys } from '@pairdraw/scene-graph/order-keys'\nimport type { GUID, Rect, Size } from '@pairdraw/scene-graph/primitives'\nimport { ownsSlotContent } from '@pairdraw/scene-graph/slots'\n\nimport type { SkiaRenderer } from '#core/canvas'\nimport { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '#core/constants'\nimport { getPageColor } from '#core/figma-api/page-backgrounds'\nimport { applyDocumentPluginData } from '#core/io/formats/fig/document-metadata'\nimport { figThumbnailPageId } from '#core/io/formats/fig/thumbnail-page'\nimport { renderThumbnail, thumbnailFrame } from '#core/io/formats/raster'\nimport { settleFontDigestMap } from '#core/kiwi/fig/node-change/serialize'\nimport { documentFontsOf } from '#core/text/font/document'\n\nimport { assignVariableGuid, assignVariableGuids } from './variables'\n\n/**\n * What a `.fig` write shares however many records it writes: the GUID maps, caches and\n * canvases, the schema, and the thumbnail and images beside the records.\n */\nconst THUMBNAIL_1X1 = toUint8Array(\n 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='\n)\n\nexport type KiwiNodeChange = NodeChange & Record<string, unknown>\nexport type FigExportPage = ReturnType<SceneGraph['getPages']>[number]\n\nexport interface CanvasExportEntry {\n page: FigExportPage\n canvasGuid: GUID\n canvasNc: KiwiNodeChange\n}\n\nconst THUMBNAIL_WIDTH = 512\nconst THUMBNAIL_HEIGHT = 512\n/** The name Figma gives a file it was not told the name of. */\nconst UNTITLED_FILE_NAME = 'Untitled'\n\ninterface FigThumbnail {\n png: Uint8Array\n size: Size\n /** The page-space rectangle the thumbnail shows; empty for the 1×1 placeholder. */\n region: Rect\n}\n\nfunction placeholderThumbnail(): FigThumbnail {\n return {\n png: THUMBNAIL_1X1,\n size: { width: 1, height: 1 },\n region: { x: 0, y: 0, width: 0, height: 0 }\n }\n}\n\nasync function renderFigThumbnailPNG(\n graph: SceneGraph,\n pageId: string,\n options: FigFileExtrasOptions\n): Promise<Uint8Array | null> {\n const { ck, renderer } = options\n if (ck && renderer) {\n return renderThumbnail(ck, renderer, graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)\n }\n if (!options.renderHeadlessThumbnail || IS_BROWSER || IS_TAURI) return null\n const { headlessRenderThumbnail } = await import('#core/io/formats/raster')\n return headlessRenderThumbnail(graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)\n}\n\nasync function renderFigThumbnail(\n graph: SceneGraph,\n pageId: string | undefined,\n options: FigFileExtrasOptions\n): Promise<FigThumbnail> {\n const frame = pageId ? thumbnailFrame(graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT) : null\n if (!pageId || !frame) return placeholderThumbnail()\n // The preview is optional: a renderer that throws while drawing it must not fail the save,\n // as a renderer that returns null already falls back to the placeholder.\n const png = await renderFigThumbnailPNG(graph, pageId, options).catch((error: unknown) => {\n console.warn('[.fig] Could not draw the file preview:', error)\n return null\n })\n if (!png) return placeholderThumbnail()\n const { minX, minY, maxX, maxY } = frame.bounds\n return {\n png,\n size: { width: frame.width, height: frame.height },\n region: { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n }\n}\n\n/**\n * The GUID a layer without a `source.id` is saved under: its graph ID, which has Figma's\n * `sessionID:localID` shape and never changes, so later saves keep it. A layer opened from a\n * file has its record's GUID as its ID, so it keeps that record even when something, such as a\n * room's copy of it, cleared its `source.id`. Another layer that keeps the GUID as its\n * `source.id`, and GUIDs already written, win over it.\n */\nfunction ownGuid(\n id: string,\n sourceOwners: ReadonlyMap<string, string>,\n assignedGuidValues: ReadonlySet<string>\n): GUID | null {\n const guid = parseGuidOrNull(id)\n if (!guid) return null\n const key = `${guid.sessionID}:${guid.localID}`\n const owner = sourceOwners.get(key)\n return (owner !== undefined && owner !== id) || assignedGuidValues.has(key) ? null : guid\n}\n\n/**\n * Whether a layer was opened from a file. A style keeps an ID of its own in `source.id`, which\n * only names a saved record when it spells a GUID; one made by token import or paste does not.\n */\nfunction savedFromFile(node: SceneNode): boolean {\n if (!node.source.id) return false\n return node.sharedStyleType === null || parseGuidOrNull(node.source.id) !== null\n}\n\nfunction assignOwnLayerGuids(\n graph: SceneGraph,\n sourceOwners: ReadonlyMap<string, string>,\n nodeIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>\n): void {\n for (const node of graph.nodes.values()) {\n if (savedFromFile(node) || node.id === graph.rootId || nodeIdToGuid.has(node.id)) continue\n const guid = ownGuid(node.id, sourceOwners, assignedGuidValues)\n if (!guid) continue\n nodeIdToGuid.set(node.id, guid)\n assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)\n }\n}\n\n/**\n * The first local ID the counter can mint in sessions 0 and 1: past every saved GUID and every\n * ID that layers, collections, modes, variables and component properties are saved under.\n */\n/** The first local ID above every GUID the graph's layers, variables, and properties claim. */\nexport function firstUnclaimedLocalId(graph: SceneGraph, propertyIds: readonly string[]): number {\n const ids = [...propertyIds]\n for (const node of graph.nodes.values()) ids.push(node.source.id || node.id)\n for (const [collectionId, collection] of graph.variableCollections) {\n ids.push(collectionId, ...collection.modes.map((mode) => mode.modeId))\n ids.push(...collection.variableIds)\n }\n let last = 0\n for (const id of ids) {\n const guid = parseGuidOrNull(id)\n if (guid && guid.sessionID <= 1) last = Math.max(last, guid.localID)\n }\n return last + 1\n}\n\n/** The layer that keeps each GUID as its `source.id`, by GUID. */\nfunction layerSourceOwners(graph: SceneGraph): Map<string, string> {\n const owners = new Map<string, string>()\n for (const node of graph.nodes.values()) if (node.source.id) owners.set(node.source.id, node.id)\n return owners\n}\n\n/** The GUIDs layers keep from the file they were read from, which variables must not take. */\nexport function layerSourceGuids(graph: SceneGraph): Set<string> {\n const guids = new Set<string>()\n for (const node of graph.nodes.values()) {\n if (node.source.id) guids.add(node.source.id)\n }\n return guids\n}\n\nexport function collectComponentPropertyIds(graph: SceneGraph): string[] {\n const ids = new Set<string>()\n for (const node of graph.getAllNodes()) {\n for (const definition of node.componentPropertyDefinitions) ids.add(definition.id)\n for (const reference of node.componentPropertyReferences) ids.add(reference.propertyId)\n for (const propertyId of Object.keys(node.componentPropertyAssignments)) ids.add(propertyId)\n for (const spec of node.variantPropSpecs) ids.add(spec.propDefId)\n }\n return [...ids]\n}\n\nfunction assignComponentPropertyGuids(\n propertyIds: readonly string[],\n localIdCounter: { value: number },\n propertyIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>,\n nodeSourceGuidValues: Set<string>\n): void {\n for (const propertyId of propertyIds) {\n const guid = assignVariableGuid(\n propertyId,\n localIdCounter,\n assignedGuidValues,\n nodeSourceGuidValues\n )\n propertyIdToGuid.set(propertyId, guid)\n }\n}\n\n/**\n * Behaviours bind component properties by id, so they follow the ids' new GUIDs. The renamed\n * plugin data is written in place of the node's own; the document keeps its ids.\n */\nfunction renamedBehaviourPluginData(\n graph: SceneGraph,\n propertyIdToGuid: Map<string, GUID>\n): Map<string, PluginDataEntry[]> {\n const rename = (propertyId: string) => {\n const guid = propertyIdToGuid.get(propertyId)\n return guid ? `${guid.sessionID}:${guid.localID}` : propertyId\n }\n const renamed = new Map<string, PluginDataEntry[]>()\n for (const node of graph.getAllNodes()) {\n const behaviour = readBehaviour(node)\n if (behaviour)\n renamed.set(node.id, withBehaviour(node, renameBehaviourProperties(behaviour, rename)))\n }\n return renamed\n}\n\nfunction applyImportedCanvasFields(page: FigExportPage, canvasNc: KiwiNodeChange): void {\n if ('backgroundColor' in page.source.fig.rawNodeFields) {\n canvasNc.backgroundColor = structuredClone(page.source.fig.rawNodeFields.backgroundColor)\n }\n if ('backgroundPaints' in page.source.fig.rawNodeFields) {\n canvasNc.backgroundPaints = structuredClone(\n page.source.fig.rawNodeFields.backgroundPaints\n ) as NodeChange['backgroundPaints']\n }\n if (!page.source.id) return\n if (!('pageType' in page.source.fig.rawNodeFields)) delete canvasNc.pageType\n if (page.guides.length > 0) {\n const normalized = exportCanvasGuides(page.guides)\n const raw = page.source.fig.rawNodeFields.guides\n canvasNc.guides =\n Array.isArray(raw) && JSON.stringify(importCanvasGuides(raw)) === JSON.stringify(page.guides)\n ? structuredClone(raw)\n : normalized\n }\n const strokeJoin = page.source.fig.rawNodeFields.strokeJoin\n if (typeof strokeJoin === 'string') canvasNc.strokeJoin = strokeJoin\n const strokeWeight = page.source.fig.rawNodeFields.strokeWeight\n if (typeof strokeWeight === 'number') canvasNc.strokeWeight = strokeWeight\n}\n\nfunction buildCanvasEntries(\n graph: SceneGraph,\n pages: FigExportPage[],\n docGuid: GUID,\n localIdCounter: { value: number },\n nodeIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>,\n sourceOwners: ReadonlyMap<string, string>,\n ownGuids = true\n): { canvasEntries: CanvasExportEntry[]; internalCanvasGuid: GUID | null } {\n const canvasEntries: CanvasExportEntry[] = []\n let internalCanvasGuid: GUID | null = null\n // Pages keep the keys they were read with while those stay in order; a page added or moved\n // gets one between its neighbours', as Figma sorts pages by these keys.\n const orderKeys = siblingOrderKeys(pages.map((page) => page.source.orderKey))\n for (let p = 0; p < pages.length; p++) {\n const page = pages[p]\n const canvasGuid = (() => {\n if (!page.source.id) {\n return (\n (ownGuids ? ownGuid(page.id, sourceOwners, assignedGuidValues) : null) ?? {\n sessionID: 0,\n localID: localIdCounter.value++\n }\n )\n }\n\n const importedGuid = stringToGuid(page.source.id)\n const key = `${importedGuid.sessionID}:${importedGuid.localID}`\n\n if (!assignedGuidValues.has(key)) return importedGuid\n\n return { sessionID: 0, localID: localIdCounter.value++ }\n })()\n // Advance counter past any source.id-derived GUID to prevent collisions\n // with subsequently generated variable/collection GUIDs.\n if (page.source.id && canvasGuid.sessionID === 0) {\n localIdCounter.value = Math.max(localIdCounter.value, canvasGuid.localID + 1)\n }\n nodeIdToGuid.set(page.id, canvasGuid)\n assignedGuidValues.add(`${canvasGuid.sessionID}:${canvasGuid.localID}`)\n if (page.internalOnly) internalCanvasGuid = canvasGuid\n\n const canvasNc = makeCanvasNodeChange(canvasGuid, docGuid, orderKeys[p], page.name, {\n backgroundOpacity: 1,\n backgroundColor: { ...CANVAS_BG_COLOR },\n backgroundEnabled: true\n })\n applyImportedCanvasFields(page, canvasNc)\n if (page.internalOnly) canvasNc.internalOnly = true\n canvasEntries.push({ page, canvasGuid, canvasNc })\n }\n\n const hasSharedStyles = [...graph.nodes.values()].some((node) => node.sharedStyleType !== null)\n const hasSlotContent = [...graph.nodes.values()].some((node) => ownsSlotContent(graph, node))\n if (\n (graph.variableCollections.size > 0 || hasSharedStyles || hasSlotContent) &&\n internalCanvasGuid === null\n ) {\n internalCanvasGuid = { sessionID: 0, localID: localIdCounter.value++ }\n assignedGuidValues.add(`${internalCanvasGuid.sessionID}:${internalCanvasGuid.localID}`)\n canvasEntries.push({\n page: { id: '', name: 'Internal Only Canvas', internalOnly: true } as FigExportPage,\n canvasGuid: internalCanvasGuid,\n canvasNc: makeCanvasNodeChange(\n internalCanvasGuid,\n docGuid,\n orderKeyBetween(orderKeys.at(-1) ?? null, null),\n 'Internal Only Canvas',\n { internalOnly: true }\n )\n })\n }\n\n return { canvasEntries, internalCanvasGuid }\n}\n\n/**\n * When the document was imported from a .fig file, preserve the original kiwi schema for both\n * encoding and embedding. Figma's schema has more types and fields than ours, and encoding with\n * ours would produce field IDs that don't align with the embedded schema.\n */\nexport function exportSchema(graph: SceneGraph): {\n compiled: ReturnType<typeof getCompiledSchema>\n schemaDeflated: Uint8Array\n} {\n if (graph.figSchemaDeflated) {\n const schemaBytes = inflateSync(graph.figSchemaDeflated)\n const figSchema = decodeBinarySchema(new ByteBuffer(schemaBytes))\n return {\n compiled: compileSchema(figSchema) as ReturnType<typeof getCompiledSchema>,\n schemaDeflated: graph.figSchemaDeflated\n }\n }\n return { compiled: getCompiledSchema(), schemaDeflated: deflateSync(getSchemaBytes()) }\n}\n\n/** GUID maps, caches and canvases one write shares across every record it serializes. */\nexport interface FigExportSetup {\n graph: SceneGraph\n runtime: FigNodeChangeExportRuntime\n docGuid: GUID\n documentNc: KiwiNodeChange\n localIdCounter: { value: number }\n blobs: Uint8Array[]\n pages: FigExportPage[]\n canvasEntries: CanvasExportEntry[]\n internalCanvasGuid: GUID | null\n nodeIdToGuid: Map<string, GUID>\n assignedGuidValues: Set<string>\n varIdToGuid: Map<string, GUID>\n modeIdToGuid: Map<string, GUID>\n propertyIdToGuid: Map<string, GUID>\n fontDigestMap: Map<string, Uint8Array>\n glyphBlobMap: Map<string, number>\n blobIndexByHex: Map<string, number>\n componentPropertyDefinitionsById: ReturnType<typeof buildComponentPropIndex>\n pluginDataOverrides: ReadonlyMap<string, PluginDataEntry[]>\n recordOwners?: ReadonlyMap<string, string>\n}\n\nexport interface FigExportSetupOptions {\n /** Saved identities on pages that may not be loaded; new variable IDs must not claim them. */\n archiveRecordIds?: readonly string[]\n /** The first local ID a new GUID may take, above every GUID the target archive holds. */\n nextLocalId?: number\n /** The target archive's blobs, so the indices of new blobs follow theirs. */\n blobs?: Uint8Array[]\n /**\n * The layer each archive GUID belongs to; only that layer writes the archive's record. Writing\n * into an archive preserves new layers' numeric graph IDs when unclaimed across all pages;\n * incompatible or colliding IDs fall back to counter GUIDs past the archive's reserved range.\n */\n recordOwners?: ReadonlyMap<string, string>\n /** Writing into an archive: the variables, collections and modes it holds keep their GUIDs. */\n archiveResourceIds?: ReadonlySet<string>\n}\n\n/**\n * The shared state of one write. The last await before the records: after it every record comes\n * from one synchronous pass over the document, and the font digests cover what that pass reads.\n */\nexport async function prepareFigExport(\n graph: SceneGraph,\n runtime: FigNodeChangeExportRuntime,\n options: FigExportSetupOptions = {}\n): Promise<FigExportSetup> {\n const fontDigestMap = await settleFontDigestMap(graph)\n const docGuid = { sessionID: 0, localID: 0 }\n const localIdCounter = { value: 2 }\n\n const documentNc = makeDocumentNodeChange(docGuid, graph.documentColorSpace)\n const rootNode = graph.getNode(graph.rootId)\n if (rootNode) Object.assign(documentNc, rootNode.source.fig.rawNodeFields)\n applyDocumentPluginData(documentNc, graph)\n\n const pages = graph.getPages(true)\n const nodeIdToGuid = new Map<string, GUID>()\n const assignedGuidValues = new Set<string>()\n // Reserve the document GUID to prevent imported nodes with source.id \"0:0\"\n // from reusing the document's own GUID slot.\n assignedGuidValues.add(`${docGuid.sessionID}:${docGuid.localID}`)\n const varIdToGuid = new Map<string, GUID>()\n const modeIdToGuid = new Map<string, GUID>()\n const propertyIdToGuid = new Map<string, GUID>()\n\n const nodeSourceGuidValues = layerSourceGuids(graph)\n const sourceOwners = layerSourceOwners(graph)\n const archiveRecordIds = new Set(options.archiveRecordIds)\n const propertyIds = collectComponentPropertyIds(graph)\n // Before any canvas, variable or layer takes a counter GUID, so none collides.\n localIdCounter.value = Math.max(\n localIdCounter.value,\n firstUnclaimedLocalId(graph, propertyIds),\n options.nextLocalId ?? 0\n )\n\n const { canvasEntries, internalCanvasGuid } = buildCanvasEntries(\n graph,\n pages,\n docGuid,\n localIdCounter,\n nodeIdToGuid,\n assignedGuidValues,\n sourceOwners,\n true\n )\n // Archive records keep their GUIDs: claim them before any copy that kept one can.\n for (const [guid, nodeId] of options.recordOwners ?? []) {\n if (nodeIdToGuid.has(nodeId) || !graph.nodes.has(nodeId)) continue\n nodeIdToGuid.set(nodeId, stringToGuid(guid))\n assignedGuidValues.add(guid)\n }\n\n // Assign variable GUIDs AFTER canvas entries so that source.id-derived\n // canvas GUIDs don't collide with generated variable GUIDs.\n const archived = options.archiveResourceIds\n assignVariableGuids(\n graph,\n localIdCounter,\n varIdToGuid,\n modeIdToGuid,\n assignedGuidValues,\n nodeSourceGuidValues,\n archived\n ? (id) =>\n archived.has(id) ||\n (!archiveRecordIds.has(id) && ownGuid(id, sourceOwners, assignedGuidValues) !== null)\n : undefined\n )\n\n assignComponentPropertyGuids(\n propertyIds,\n localIdCounter,\n propertyIdToGuid,\n assignedGuidValues,\n nodeSourceGuidValues\n )\n const pluginDataOverrides = renamedBehaviourPluginData(graph, propertyIdToGuid)\n assignOwnLayerGuids(graph, sourceOwners, nodeIdToGuid, assignedGuidValues)\n\n return {\n graph,\n runtime,\n docGuid,\n documentNc,\n localIdCounter,\n blobs: options.blobs ?? [],\n pages,\n canvasEntries,\n internalCanvasGuid,\n nodeIdToGuid,\n assignedGuidValues,\n varIdToGuid,\n modeIdToGuid,\n propertyIdToGuid,\n fontDigestMap,\n glyphBlobMap: new Map(),\n blobIndexByHex: new Map(),\n componentPropertyDefinitionsById: buildComponentPropIndex(graph),\n pluginDataOverrides,\n recordOwners: options.recordOwners\n }\n}\n\n/** The serializer options a setup's records share. */\nexport function figExportRecordOptions(setup: FigExportSetup) {\n return {\n nodeIdToGuid: setup.nodeIdToGuid,\n fontDigestMap: setup.fontDigestMap,\n varIdToGuid: setup.varIdToGuid,\n glyphBlobMap: setup.glyphBlobMap,\n blobIndexByHex: setup.blobIndexByHex,\n assignedGuidValues: setup.assignedGuidValues,\n componentPropertyDefinitionsById: setup.componentPropertyDefinitionsById,\n modeIdToGuid: setup.modeIdToGuid,\n propertyIdToGuid: setup.propertyIdToGuid,\n pluginDataOverrides: setup.pluginDataOverrides,\n recordOwners: setup.recordOwners,\n runtime: setup.runtime\n }\n}\n\nexport interface FigFileExtras {\n thumbnailPNG: Uint8Array\n metaJSON: string\n images: Array<{ name: string; data: Uint8Array }>\n /** Document fonts under their `fonts/<index>.<ext>` names. */\n fonts: Array<{ name: string; data: Uint8Array }>\n /** `fonts.json` recording each font's family and style. */\n fontsJSON: string\n}\n\nexport interface FigFileExtrasOptions {\n ck?: CanvasKit\n renderer?: SkiaRenderer\n /** The page the thumbnail shows; the cover page when absent. */\n pageId?: string\n renderHeadlessThumbnail?: boolean\n /** The name `meta.json` records for the file. */\n documentName?: string\n}\n\n/**\n * The thumbnail, metadata and images a written `.fig` carries besides its records, the images\n * under the names `nameImagesForFigma` gave them in those records.\n */\nexport async function figFileExtras(\n graph: SceneGraph,\n imageNames: ReadonlyMap<string, string>,\n options: FigFileExtrasOptions\n): Promise<FigFileExtras> {\n // Internal pages hold library data, not anything a person drew, so the thumbnail skips them.\n const thumbnailPageId = options.pageId ?? figThumbnailPageId(graph.getPages())\n const thumbnail = await renderFigThumbnail(graph, thumbnailPageId, options)\n const metaJSON = figArchiveMetaJSON({\n fileName: options.documentName || UNTITLED_FILE_NAME,\n backgroundColor: getPageColor(thumbnailPageId ? graph.getNode(thumbnailPageId) : undefined),\n thumbnailSize: thumbnail.size,\n renderCoordinates: thumbnail.region,\n exportedAt: new Date()\n })\n const fonts = figFontEntries(documentFontsOf(graph))\n return {\n thumbnailPNG: thumbnail.png,\n metaJSON,\n images: figImageEntries(graph.images, imageNames),\n fonts,\n fontsJSON: figFontsManifest(fonts)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,gBAAgB,aACpB,kGACF;AAWA,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;;AAEzB,MAAM,qBAAqB;AAS3B,SAAS,uBAAqC;CAC5C,OAAO;EACL,KAAK;EACL,MAAM;GAAE,OAAO;GAAG,QAAQ;EAAE;EAC5B,QAAQ;GAAE,GAAG;GAAG,GAAG;GAAG,OAAO;GAAG,QAAQ;EAAE;CAC5C;AACF;AAEA,eAAe,sBACb,OACA,QACA,SAC4B;CAC5B,MAAM,EAAE,IAAI,aAAa;CACzB,IAAI,MAAM,UACR,OAAO,gBAAgB,IAAI,UAAU,OAAO,QAAQ,iBAAiB,gBAAgB;CAEvF,IAAI,CAAC,QAAQ,2BAA2B,cAAc,UAAU,OAAO;CACvE,MAAM,EAAE,4BAA4B,MAAM,OAAO;CACjD,OAAO,wBAAwB,OAAO,QAAQ,iBAAiB,gBAAgB;AACjF;AAE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gB;CAC9E,oBAAoB,OAAO,cAAc,cAAc,kBAAkB;CAEzE,OAAO;EACL;EACA;EACA;EACA;EACA;EACA,OAAO,QAAQ,SAAS,CAAC;EACzB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,8BAAc,IAAI,IAAI;EACtB,gCAAgB,IAAI,IAAI;EACxB,kCAAkC,wBAAwB,KAAK;EAC/D;EACA,cAAc,QAAQ;CACxB;AACF;;AAGA,SAAgB,uBAAuB,OAAuB;CAC5D,OAAO;EACL,cAAc,MAAM;EACpB,eAAe,MAAM;EACrB,aAAa,MAAM;EACnB,cAAc,MAAM;EACpB,gBAAgB,MAAM;EACtB,oBAAoB,MAAM;EAC1B,kCAAkC,MAAM;EACxC,cAAc,MAAM;EACpB,kBAAkB,MAAM;EACxB,qBAAqB,MAAM;EAC3B,cAAc,MAAM;EACpB,SAAS,MAAM;CACjB;AACF;;;;;AA0BA,eAAsB,cACpB,OACA,YACA,SACwB;CAExB,MAAM,kBAAkB,QAAQ,UAAU,mBAAmB,MAAM,SAAS,CAAC;CAC7E,MAAM,YAAY,MAAM,mBAAmB,OAAO,iBAAiB,OAAO;CAC1E,MAAM,WAAW,mBAAmB;EAClC,UAAU,QAAQ,gBAAgB;EAClC,iBAAiB,aAAa,kBAAkB,MAAM,QAAQ,eAAe,IAAI,KAAA,CAAS;EAC1F,eAAe,UAAU;EACzB,mBAAmB,UAAU;EAC7B,4BAAY,IAAI,KAAK;CACvB,CAAC;CACD,MAAM,QAAQ,eAAe,gBAAgB,KAAK,CAAC;CACnD,OAAO;EACL,cAAc,UAAU;EACxB;EACA,QAAQ,gBAAgB,MAAM,QAAQ,UAAU;EAChD;EACA,WAAW,iBAAiB,KAAK;CACnC;AACF"}
|
|
1
|
+
{"version":3,"file":"setup.js","names":[],"sources":["../../../../../src/io/formats/fig/export/setup.ts"],"sourcesContent":["import type { CanvasKit } from 'canvaskit-wasm'\nimport { deflateSync, inflateSync } from 'fflate'\nimport { toUint8Array } from 'js-base64'\n\nimport {\n figArchiveMetaJSON,\n figFontEntries,\n figFontsManifest,\n type FigUnreadVariable\n} from '@pairdraw/fig'\nimport {\n buildComponentPropIndex,\n exportCanvasGuides,\n figImageEntries,\n importCanvasGuides,\n parseGuidOrNull,\n type FigNodeChangeExportRuntime,\n makeCanvasNodeChange,\n makeDocumentNodeChange\n} from '@pairdraw/fig/node-change'\nimport { getCompiledSchema, getSchemaBytes, type NodeChange } from '@pairdraw/kiwi/fig/codec'\nimport { stringToGuid } from '@pairdraw/kiwi/fig/guid'\nimport { decodeBinarySchema, compileSchema, ByteBuffer } from '@pairdraw/kiwi/schema-runtime'\nimport type { PluginDataEntry, SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n readBehaviour,\n renameBehaviourProperties,\n withBehaviour\n} from '@pairdraw/scene-graph/behaviours'\nimport { orderKeyBetween, siblingOrderKeys } from '@pairdraw/scene-graph/order-keys'\nimport type { GUID, Rect, Size } from '@pairdraw/scene-graph/primitives'\nimport { ownsSlotContent } from '@pairdraw/scene-graph/slots'\n\nimport type { SkiaRenderer } from '#core/canvas'\nimport { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '#core/constants'\nimport { getPageColor } from '#core/figma-api/page-backgrounds'\nimport { applyDocumentPluginData } from '#core/io/formats/fig/document-metadata'\nimport { figThumbnailPageId } from '#core/io/formats/fig/thumbnail-page'\nimport { renderThumbnail, thumbnailFrame } from '#core/io/formats/raster'\nimport { settleFontDigestMap } from '#core/kiwi/fig/node-change/serialize'\nimport { documentFontsOf } from '#core/text/font/document'\n\nimport { assignVariableGuid, assignVariableGuids } from './variables'\n\n/**\n * What a `.fig` write shares however many records it writes: the GUID maps, caches and\n * canvases, the schema, and the thumbnail and images beside the records.\n */\nconst THUMBNAIL_1X1 = toUint8Array(\n 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='\n)\n\nexport type KiwiNodeChange = NodeChange & Record<string, unknown>\nexport type FigExportPage = ReturnType<SceneGraph['getPages']>[number]\n\nexport interface CanvasExportEntry {\n page: FigExportPage\n canvasGuid: GUID\n canvasNc: KiwiNodeChange\n}\n\nconst THUMBNAIL_WIDTH = 512\nconst THUMBNAIL_HEIGHT = 512\n/** The name Figma gives a file it was not told the name of. */\nconst UNTITLED_FILE_NAME = 'Untitled'\n\ninterface FigThumbnail {\n png: Uint8Array\n size: Size\n /** The page-space rectangle the thumbnail shows; empty for the 1×1 placeholder. */\n region: Rect\n}\n\nfunction placeholderThumbnail(): FigThumbnail {\n return {\n png: THUMBNAIL_1X1,\n size: { width: 1, height: 1 },\n region: { x: 0, y: 0, width: 0, height: 0 }\n }\n}\n\nasync function renderFigThumbnailPNG(\n graph: SceneGraph,\n pageId: string,\n options: FigFileExtrasOptions\n): Promise<Uint8Array | null> {\n const { ck, renderer } = options\n if (ck && renderer) {\n return renderThumbnail(ck, renderer, graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)\n }\n if (!options.renderHeadlessThumbnail || IS_BROWSER || IS_TAURI) return null\n const { headlessRenderThumbnail } = await import('#core/io/formats/raster')\n return headlessRenderThumbnail(graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)\n}\n\nasync function renderFigThumbnail(\n graph: SceneGraph,\n pageId: string | undefined,\n options: FigFileExtrasOptions\n): Promise<FigThumbnail> {\n const frame = pageId ? thumbnailFrame(graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT) : null\n if (!pageId || !frame) return placeholderThumbnail()\n // The preview is optional: a renderer that throws while drawing it must not fail the save,\n // as a renderer that returns null already falls back to the placeholder.\n const png = await renderFigThumbnailPNG(graph, pageId, options).catch((error: unknown) => {\n console.warn('[.fig] Could not draw the file preview:', error)\n return null\n })\n if (!png) return placeholderThumbnail()\n const { minX, minY, maxX, maxY } = frame.bounds\n return {\n png,\n size: { width: frame.width, height: frame.height },\n region: { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n }\n}\n\n/**\n * The GUID a layer without a `source.id` is saved under: its graph ID, which has Figma's\n * `sessionID:localID` shape and never changes, so later saves keep it. A layer opened from a\n * file has its record's GUID as its ID, so it keeps that record even when something, such as a\n * room's copy of it, cleared its `source.id`. Another layer that keeps the GUID as its\n * `source.id`, and GUIDs already written, win over it.\n */\nfunction ownGuid(\n id: string,\n sourceOwners: ReadonlyMap<string, string>,\n assignedGuidValues: ReadonlySet<string>\n): GUID | null {\n const guid = parseGuidOrNull(id)\n if (!guid) return null\n const key = `${guid.sessionID}:${guid.localID}`\n const owner = sourceOwners.get(key)\n return (owner !== undefined && owner !== id) || assignedGuidValues.has(key) ? null : guid\n}\n\n/**\n * Whether a layer was opened from a file. A style keeps an ID of its own in `source.id`, which\n * only names a saved record when it spells a GUID; one made by token import or paste does not.\n */\nfunction savedFromFile(node: SceneNode): boolean {\n if (!node.source.id) return false\n return node.sharedStyleType === null || parseGuidOrNull(node.source.id) !== null\n}\n\nfunction assignOwnLayerGuids(\n graph: SceneGraph,\n sourceOwners: ReadonlyMap<string, string>,\n nodeIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>\n): void {\n for (const node of graph.nodes.values()) {\n if (savedFromFile(node) || node.id === graph.rootId || nodeIdToGuid.has(node.id)) continue\n const guid = ownGuid(node.id, sourceOwners, assignedGuidValues)\n if (!guid) continue\n nodeIdToGuid.set(node.id, guid)\n assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)\n }\n}\n\n/**\n * The first local ID the counter can mint in sessions 0 and 1: past every saved GUID and every\n * ID that layers, collections, modes, variables (deleted ones too) and component properties are\n * saved under.\n */\nexport function firstUnclaimedLocalId(graph: SceneGraph, propertyIds: readonly string[]): number {\n const ids = [...propertyIds, ...graph.variables.keys()]\n for (const node of graph.nodes.values()) ids.push(node.source.id || node.id)\n for (const [collectionId, collection] of graph.variableCollections) {\n ids.push(collectionId, ...collection.modes.map((mode) => mode.modeId))\n }\n let last = 0\n for (const id of ids) {\n const guid = parseGuidOrNull(id)\n if (guid && guid.sessionID <= 1) last = Math.max(last, guid.localID)\n }\n return last + 1\n}\n\n/** The layer that keeps each GUID as its `source.id`, by GUID. */\nfunction layerSourceOwners(graph: SceneGraph): Map<string, string> {\n const owners = new Map<string, string>()\n for (const node of graph.nodes.values()) if (node.source.id) owners.set(node.source.id, node.id)\n return owners\n}\n\n/** The GUIDs layers keep from the file they were read from, which variables must not take. */\nexport function layerSourceGuids(graph: SceneGraph): Set<string> {\n const guids = new Set<string>()\n for (const node of graph.nodes.values()) {\n if (node.source.id) guids.add(node.source.id)\n }\n return guids\n}\n\nexport function collectComponentPropertyIds(graph: SceneGraph): string[] {\n const ids = new Set<string>()\n for (const node of graph.getAllNodes()) {\n for (const definition of node.componentPropertyDefinitions) ids.add(definition.id)\n for (const reference of node.componentPropertyReferences) ids.add(reference.propertyId)\n for (const propertyId of Object.keys(node.componentPropertyAssignments)) ids.add(propertyId)\n for (const spec of node.variantPropSpecs) ids.add(spec.propDefId)\n }\n return [...ids]\n}\n\nfunction assignComponentPropertyGuids(\n propertyIds: readonly string[],\n localIdCounter: { value: number },\n propertyIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>,\n nodeSourceGuidValues: Set<string>\n): void {\n for (const propertyId of propertyIds) {\n const guid = assignVariableGuid(\n propertyId,\n localIdCounter,\n assignedGuidValues,\n nodeSourceGuidValues\n )\n propertyIdToGuid.set(propertyId, guid)\n }\n}\n\n/**\n * Behaviours bind component properties by id, so they follow the ids' new GUIDs. The renamed\n * plugin data is written in place of the node's own; the document keeps its ids.\n */\nfunction renamedBehaviourPluginData(\n graph: SceneGraph,\n propertyIdToGuid: Map<string, GUID>\n): Map<string, PluginDataEntry[]> {\n const rename = (propertyId: string) => {\n const guid = propertyIdToGuid.get(propertyId)\n return guid ? `${guid.sessionID}:${guid.localID}` : propertyId\n }\n const renamed = new Map<string, PluginDataEntry[]>()\n for (const node of graph.getAllNodes()) {\n const behaviour = readBehaviour(node)\n if (behaviour)\n renamed.set(node.id, withBehaviour(node, renameBehaviourProperties(behaviour, rename)))\n }\n return renamed\n}\n\nfunction applyImportedCanvasFields(page: FigExportPage, canvasNc: KiwiNodeChange): void {\n if ('backgroundColor' in page.source.fig.rawNodeFields) {\n canvasNc.backgroundColor = structuredClone(page.source.fig.rawNodeFields.backgroundColor)\n }\n if ('backgroundPaints' in page.source.fig.rawNodeFields) {\n canvasNc.backgroundPaints = structuredClone(\n page.source.fig.rawNodeFields.backgroundPaints\n ) as NodeChange['backgroundPaints']\n }\n if (!page.source.id) return\n if (!('pageType' in page.source.fig.rawNodeFields)) delete canvasNc.pageType\n if (page.guides.length > 0) {\n const normalized = exportCanvasGuides(page.guides)\n const raw = page.source.fig.rawNodeFields.guides\n canvasNc.guides =\n Array.isArray(raw) && JSON.stringify(importCanvasGuides(raw)) === JSON.stringify(page.guides)\n ? structuredClone(raw)\n : normalized\n }\n const strokeJoin = page.source.fig.rawNodeFields.strokeJoin\n if (typeof strokeJoin === 'string') canvasNc.strokeJoin = strokeJoin\n const strokeWeight = page.source.fig.rawNodeFields.strokeWeight\n if (typeof strokeWeight === 'number') canvasNc.strokeWeight = strokeWeight\n}\n\nfunction buildCanvasEntries(\n graph: SceneGraph,\n pages: FigExportPage[],\n docGuid: GUID,\n localIdCounter: { value: number },\n nodeIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>,\n sourceOwners: ReadonlyMap<string, string>,\n keepsUnreadRecords: boolean\n): { canvasEntries: CanvasExportEntry[]; internalCanvasGuid: GUID | null } {\n const canvasEntries: CanvasExportEntry[] = []\n let internalCanvasGuid: GUID | null = null\n // Pages keep the keys they were read with while those stay in order; a page added or moved\n // gets one between its neighbours', as Figma sorts pages by these keys.\n const orderKeys = siblingOrderKeys(pages.map((page) => page.source.orderKey))\n for (let p = 0; p < pages.length; p++) {\n const page = pages[p]\n const canvasGuid = (() => {\n if (!page.source.id) {\n return (\n ownGuid(page.id, sourceOwners, assignedGuidValues) ?? {\n sessionID: 0,\n localID: localIdCounter.value++\n }\n )\n }\n\n const importedGuid = stringToGuid(page.source.id)\n const key = `${importedGuid.sessionID}:${importedGuid.localID}`\n\n if (!assignedGuidValues.has(key)) return importedGuid\n\n return { sessionID: 0, localID: localIdCounter.value++ }\n })()\n // Advance counter past any source.id-derived GUID to prevent collisions\n // with subsequently generated variable/collection GUIDs.\n if (page.source.id && canvasGuid.sessionID === 0) {\n localIdCounter.value = Math.max(localIdCounter.value, canvasGuid.localID + 1)\n }\n nodeIdToGuid.set(page.id, canvasGuid)\n assignedGuidValues.add(`${canvasGuid.sessionID}:${canvasGuid.localID}`)\n if (page.internalOnly) internalCanvasGuid = canvasGuid\n\n const canvasNc = makeCanvasNodeChange(canvasGuid, docGuid, orderKeys[p], page.name, {\n backgroundOpacity: 1,\n backgroundColor: { ...CANVAS_BG_COLOR },\n backgroundEnabled: true\n })\n applyImportedCanvasFields(page, canvasNc)\n if (page.internalOnly) canvasNc.internalOnly = true\n canvasEntries.push({ page, canvasGuid, canvasNc })\n }\n\n const hasSharedStyles = [...graph.nodes.values()].some((node) => node.sharedStyleType !== null)\n const hasSlotContent = [...graph.nodes.values()].some((node) => ownsSlotContent(graph, node))\n const hasVariables = graph.variableCollections.size > 0 || keepsUnreadRecords\n if ((hasVariables || hasSharedStyles || hasSlotContent) && internalCanvasGuid === null) {\n internalCanvasGuid = { sessionID: 0, localID: localIdCounter.value++ }\n assignedGuidValues.add(`${internalCanvasGuid.sessionID}:${internalCanvasGuid.localID}`)\n canvasEntries.push({\n page: { id: '', name: 'Internal Only Canvas', internalOnly: true } as FigExportPage,\n canvasGuid: internalCanvasGuid,\n canvasNc: makeCanvasNodeChange(\n internalCanvasGuid,\n docGuid,\n orderKeyBetween(orderKeys.at(-1) ?? null, null),\n 'Internal Only Canvas',\n { internalOnly: true }\n )\n })\n }\n\n return { canvasEntries, internalCanvasGuid }\n}\n\n/**\n * When the document was imported from a .fig file, preserve the original kiwi schema for both\n * encoding and embedding. Figma's schema has more types and fields than ours, and encoding with\n * ours would produce field IDs that don't align with the embedded schema.\n */\nexport function exportSchema(graph: SceneGraph): {\n compiled: ReturnType<typeof getCompiledSchema>\n schemaDeflated: Uint8Array\n} {\n if (graph.figSchemaDeflated) {\n const schemaBytes = inflateSync(graph.figSchemaDeflated)\n const figSchema = decodeBinarySchema(new ByteBuffer(schemaBytes))\n return {\n compiled: compileSchema(figSchema) as ReturnType<typeof getCompiledSchema>,\n schemaDeflated: graph.figSchemaDeflated\n }\n }\n return { compiled: getCompiledSchema(), schemaDeflated: deflateSync(getSchemaBytes()) }\n}\n\n/** GUID maps, caches and canvases one write shares across every record it serializes. */\nexport interface FigExportSetup {\n graph: SceneGraph\n runtime: FigNodeChangeExportRuntime\n docGuid: GUID\n documentNc: KiwiNodeChange\n localIdCounter: { value: number }\n blobs: Uint8Array[]\n pages: FigExportPage[]\n canvasEntries: CanvasExportEntry[]\n internalCanvasGuid: GUID | null\n nodeIdToGuid: Map<string, GUID>\n assignedGuidValues: Set<string>\n varIdToGuid: Map<string, GUID>\n modeIdToGuid: Map<string, GUID>\n propertyIdToGuid: Map<string, GUID>\n fontDigestMap: Map<string, Uint8Array>\n glyphBlobMap: Map<string, number>\n blobIndexByHex: Map<string, number>\n componentPropertyDefinitionsById: ReturnType<typeof buildComponentPropIndex>\n pluginDataOverrides: ReadonlyMap<string, PluginDataEntry[]>\n recordOwners?: ReadonlyMap<string, string>\n /** Variable records the document never read, written back as the archive saved them. */\n unreadVariables: readonly FigUnreadVariable[]\n}\n\nexport interface FigExportSetupOptions {\n /** Saved identities on pages that may not be loaded; new variable IDs must not claim them. */\n archiveRecordIds?: readonly string[]\n /** The first local ID a new GUID may take, above every GUID the target archive holds. */\n nextLocalId?: number\n /** The target archive's blobs, so the indices of new blobs follow theirs. */\n blobs?: Uint8Array[]\n /**\n * The layer each archive GUID belongs to; only that layer writes the archive's record. Writing\n * into an archive preserves new layers' numeric graph IDs when unclaimed across all pages;\n * incompatible or colliding IDs fall back to counter GUIDs past the archive's reserved range.\n */\n recordOwners?: ReadonlyMap<string, string>\n /** Writing into an archive: the variables, collections and modes it holds keep their GUIDs. */\n archiveResourceIds?: ReadonlySet<string>\n /** Records the document never read, which the write keeps, so nothing new takes their GUIDs. */\n unreadVariables?: readonly FigUnreadVariable[]\n}\n\n/**\n * The shared state of one write. The last await before the records: after it every record comes\n * from one synchronous pass over the document, and the font digests cover what that pass reads.\n */\nexport async function prepareFigExport(\n graph: SceneGraph,\n runtime: FigNodeChangeExportRuntime,\n options: FigExportSetupOptions = {}\n): Promise<FigExportSetup> {\n const fontDigestMap = await settleFontDigestMap(graph)\n const docGuid = { sessionID: 0, localID: 0 }\n const localIdCounter = { value: 2 }\n\n const documentNc = makeDocumentNodeChange(docGuid, graph.documentColorSpace)\n const rootNode = graph.getNode(graph.rootId)\n if (rootNode) Object.assign(documentNc, rootNode.source.fig.rawNodeFields)\n applyDocumentPluginData(documentNc, graph)\n\n const pages = graph.getPages(true)\n const nodeIdToGuid = new Map<string, GUID>()\n const assignedGuidValues = new Set<string>()\n // Reserve the document GUID to prevent imported nodes with source.id \"0:0\"\n // from reusing the document's own GUID slot.\n assignedGuidValues.add(`${docGuid.sessionID}:${docGuid.localID}`)\n // No layer takes an unread record's GUID either: the save writes that record back.\n for (const { record } of options.unreadVariables ?? [])\n if (record.guid) assignedGuidValues.add(`${record.guid.sessionID}:${record.guid.localID}`)\n const varIdToGuid = new Map<string, GUID>()\n const modeIdToGuid = new Map<string, GUID>()\n const propertyIdToGuid = new Map<string, GUID>()\n\n const nodeSourceGuidValues = layerSourceGuids(graph)\n const sourceOwners = layerSourceOwners(graph)\n const archiveRecordIds = new Set(options.archiveRecordIds)\n const propertyIds = collectComponentPropertyIds(graph)\n // Before any canvas, variable or layer takes a counter GUID, so none collides with a reserved one.\n localIdCounter.value = Math.max(\n localIdCounter.value,\n firstUnclaimedLocalId(graph, [...propertyIds, ...assignedGuidValues]),\n options.nextLocalId ?? 0\n )\n\n const { canvasEntries, internalCanvasGuid } = buildCanvasEntries(\n graph,\n pages,\n docGuid,\n localIdCounter,\n nodeIdToGuid,\n assignedGuidValues,\n sourceOwners,\n (options.unreadVariables?.length ?? 0) > 0\n )\n // Archive records keep their GUIDs: claim them before any copy that kept one can.\n for (const [guid, nodeId] of options.recordOwners ?? []) {\n if (nodeIdToGuid.has(nodeId) || !graph.nodes.has(nodeId)) continue\n nodeIdToGuid.set(nodeId, stringToGuid(guid))\n assignedGuidValues.add(guid)\n }\n\n // Assign variable GUIDs AFTER canvas entries so that source.id-derived\n // canvas GUIDs don't collide with generated variable GUIDs.\n const archived = options.archiveResourceIds\n assignVariableGuids(\n graph,\n localIdCounter,\n varIdToGuid,\n modeIdToGuid,\n assignedGuidValues,\n nodeSourceGuidValues,\n archived\n ? (id) =>\n archived.has(id) ||\n (!archiveRecordIds.has(id) && ownGuid(id, sourceOwners, assignedGuidValues) !== null)\n : undefined\n )\n\n assignComponentPropertyGuids(\n propertyIds,\n localIdCounter,\n propertyIdToGuid,\n assignedGuidValues,\n nodeSourceGuidValues\n )\n const pluginDataOverrides = renamedBehaviourPluginData(graph, propertyIdToGuid)\n assignOwnLayerGuids(graph, sourceOwners, nodeIdToGuid, assignedGuidValues)\n\n return {\n graph,\n runtime,\n docGuid,\n documentNc,\n localIdCounter,\n blobs: options.blobs ?? [],\n pages,\n canvasEntries,\n internalCanvasGuid,\n nodeIdToGuid,\n assignedGuidValues,\n varIdToGuid,\n modeIdToGuid,\n propertyIdToGuid,\n fontDigestMap,\n glyphBlobMap: new Map(),\n blobIndexByHex: new Map(),\n componentPropertyDefinitionsById: buildComponentPropIndex(graph),\n pluginDataOverrides,\n recordOwners: options.recordOwners,\n unreadVariables: options.unreadVariables ?? []\n }\n}\n\n/** The serializer options a setup's records share. */\nexport function figExportRecordOptions(setup: FigExportSetup) {\n return {\n nodeIdToGuid: setup.nodeIdToGuid,\n fontDigestMap: setup.fontDigestMap,\n varIdToGuid: setup.varIdToGuid,\n glyphBlobMap: setup.glyphBlobMap,\n blobIndexByHex: setup.blobIndexByHex,\n assignedGuidValues: setup.assignedGuidValues,\n componentPropertyDefinitionsById: setup.componentPropertyDefinitionsById,\n modeIdToGuid: setup.modeIdToGuid,\n propertyIdToGuid: setup.propertyIdToGuid,\n pluginDataOverrides: setup.pluginDataOverrides,\n recordOwners: setup.recordOwners,\n runtime: setup.runtime\n }\n}\n\nexport interface FigFileExtras {\n thumbnailPNG: Uint8Array\n metaJSON: string\n images: Array<{ name: string; data: Uint8Array }>\n /** Document fonts under their `fonts/<index>.<ext>` names. */\n fonts: Array<{ name: string; data: Uint8Array }>\n /** `fonts.json` recording each font's family and style. */\n fontsJSON: string\n}\n\nexport interface FigFileExtrasOptions {\n ck?: CanvasKit\n renderer?: SkiaRenderer\n /** The page the thumbnail shows; the cover page when absent. */\n pageId?: string\n renderHeadlessThumbnail?: boolean\n /** The name `meta.json` records for the file. */\n documentName?: string\n}\n\n/**\n * The thumbnail, metadata and images a written `.fig` carries besides its records, the images\n * under the names `nameImagesForFigma` gave them in those records.\n */\nexport async function figFileExtras(\n graph: SceneGraph,\n imageNames: ReadonlyMap<string, string>,\n options: FigFileExtrasOptions\n): Promise<FigFileExtras> {\n // Internal pages hold library data, not anything a person drew, so the thumbnail skips them.\n const thumbnailPageId = options.pageId ?? figThumbnailPageId(graph.getPages())\n const thumbnail = await renderFigThumbnail(graph, thumbnailPageId, options)\n const metaJSON = figArchiveMetaJSON({\n fileName: options.documentName || UNTITLED_FILE_NAME,\n backgroundColor: getPageColor(thumbnailPageId ? graph.getNode(thumbnailPageId) : undefined),\n thumbnailSize: thumbnail.size,\n renderCoordinates: thumbnail.region,\n exportedAt: new Date()\n })\n const fonts = figFontEntries(documentFontsOf(graph))\n return {\n thumbnailPNG: thumbnail.png,\n metaJSON,\n images: figImageEntries(graph.images, imageNames),\n fonts,\n fontsJSON: figFontsManifest(fonts)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;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EACxC,cAAc,MAAM;EACpB,kBAAkB,MAAM;EACxB,qBAAqB,MAAM;EAC3B,cAAc,MAAM;EACpB,SAAS,MAAM;CACjB;AACF;;;;;AA0BA,eAAsB,cACpB,OACA,YACA,SACwB;CAExB,MAAM,kBAAkB,QAAQ,UAAU,mBAAmB,MAAM,SAAS,CAAC;CAC7E,MAAM,YAAY,MAAM,mBAAmB,OAAO,iBAAiB,OAAO;CAC1E,MAAM,WAAW,mBAAmB;EAClC,UAAU,QAAQ,gBAAgB;EAClC,iBAAiB,aAAa,kBAAkB,MAAM,QAAQ,eAAe,IAAI,KAAA,CAAS;EAC1F,eAAe,UAAU;EACzB,mBAAmB,UAAU;EAC7B,4BAAY,IAAI,KAAK;CACvB,CAAC;CACD,MAAM,QAAQ,eAAe,gBAAgB,KAAK,CAAC;CACnD,OAAO;EACL,cAAc,UAAU;EACxB;EACA,QAAQ,gBAAgB,MAAM,QAAQ,UAAU;EAChD;EACA,WAAW,iBAAiB,KAAK;CACnC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"variables.d.ts","names":[],"sources":["../../../../../src/io/formats/fig/export/variables.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"variables.d.ts","names":[],"sources":["../../../../../src/io/formats/fig/export/variables.ts"],"mappings":";;;;;;;;;iBAsCgB,mBACd,YACA;EAAkB;GAClB,oBAAoB,aACpB,sBAAsB,aACtB,aAAY,yBACX;iBAWa,oBACd,OAAO,YACP;EAAkB;GAClB,aAAa,YAAY,OACzB,cAAc,YAAY,OAC1B,oBAAoB,aACpB,sBAAsB,aACtB,aAAa;;;;;iBA6DC,uBACd,iBAAiB,aACjB;EAAkB;GAClB,cAAc,YAAY,OAC1B,oBAAoB;;;;;;iBAgHN,oBAAoB;iBAKpB,0BACd,OAAO,YACP,SAAS,cACT,QAAQ,MACR,KAAK,YAAY,OACjB,OAAO,YAAY,OACnB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { collectionPluginDataNodeChange, figmaFormulaFunction, mapUnsupportedExpressionReferences, parseGuidOrNull, safeColor, unsupportedExpressionData, variableAlias, variableMetadataNodeChange } from "@pairdraw/fig/node-change";
|
|
2
2
|
import { fractionalPosition, orderKeyBetween } from "@pairdraw/scene-graph/order-keys";
|
|
3
3
|
import { guidToString, stringToGuid } from "@pairdraw/kiwi/fig/guid";
|
|
4
|
-
import { foldFormula, formulaValueType, inferFormulaType, isUnsupportedVariableValue, variableColorExpressionSchema, variableFormulaSchema } from "@pairdraw/scene-graph/variables";
|
|
4
|
+
import { deletedVariablesOf, foldFormula, formulaValueType, inferFormulaType, isUnsupportedVariableValue, variableColorExpressionSchema, variableFormulaSchema } from "@pairdraw/scene-graph/variables";
|
|
5
5
|
import * as v from "valibot";
|
|
6
6
|
//#region src/io/formats/fig/export/variables.ts
|
|
7
7
|
/**
|
|
@@ -30,7 +30,7 @@ function assignVariableGuids(graph, localIdCounter, varIdToGuid, modeIdToGuid, a
|
|
|
30
30
|
const modeGuid = assignVariableGuid(mode.modeId, localIdCounter, assignedGuidValues, nodeSourceGuidValues, keepsGuid);
|
|
31
31
|
modeIdToGuid.set(mode.modeId, modeGuid);
|
|
32
32
|
}
|
|
33
|
-
for (const varId of col.variableIds) {
|
|
33
|
+
for (const varId of [...col.variableIds, ...deletedVariablesOf(graph, colId).map((item) => item.id)]) {
|
|
34
34
|
const varGuid = assignVariableGuid(varId, localIdCounter, assignedGuidValues, nodeSourceGuidValues, keepsGuid);
|
|
35
35
|
varIdToGuid.set(varId, varGuid);
|
|
36
36
|
}
|
|
@@ -185,11 +185,12 @@ function appendVariableNodeChanges(graph, changes, parent, ids, modes, nextPosit
|
|
|
185
185
|
})),
|
|
186
186
|
pluginData: collectionPluginDataNodeChange(collection, modeKey),
|
|
187
187
|
key: collection.key,
|
|
188
|
-
version: collection.version
|
|
188
|
+
version: collection.version,
|
|
189
|
+
...collection.deleted ? { isSoftDeleted: true } : {}
|
|
189
190
|
});
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
191
|
+
const variables = [...collection.variableIds.flatMap((id) => graph.variables.get(id) ?? []), ...deletedVariablesOf(graph, collection.id)];
|
|
192
|
+
for (const variable of variables) {
|
|
193
|
+
const id = variable.id;
|
|
193
194
|
changes.push({
|
|
194
195
|
guid: ids.get(id) ?? stringToGuid(id),
|
|
195
196
|
parentIndex: {
|
|
@@ -212,7 +213,8 @@ function appendVariableNodeChanges(graph, changes, parent, ids, modes, nextPosit
|
|
|
212
213
|
})) },
|
|
213
214
|
...variableMetadataNodeChange(variable, modeKey),
|
|
214
215
|
key: variable.key,
|
|
215
|
-
version: variable.version
|
|
216
|
+
version: variable.version,
|
|
217
|
+
...variable.deleted ? { isSoftDeleted: true } : {}
|
|
216
218
|
});
|
|
217
219
|
}
|
|
218
220
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"variables.js","names":[],"sources":["../../../../../src/io/formats/fig/export/variables.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport {\n collectionPluginDataNodeChange,\n figmaFormulaFunction,\n parseGuidOrNull,\n mapUnsupportedExpressionReferences,\n unsupportedExpressionData,\n variableAlias,\n variableMetadataNodeChange,\n safeColor\n} from '@pairdraw/fig/node-change'\nimport type { GUID } from '@pairdraw/kiwi/fig'\nimport type { NodeChange, VariableDataEntry } from '@pairdraw/kiwi/fig/codec'\nimport { guidToString, stringToGuid } from '@pairdraw/kiwi/fig/guid'\nimport type {\n SceneGraph,\n SceneNode,\n VariableFormulaNode,\n VariableCollectionMode,\n VariableValue\n} from '@pairdraw/scene-graph'\nimport { fractionalPosition, orderKeyBetween } from '@pairdraw/scene-graph/order-keys'\nimport {\n isUnsupportedVariableValue,\n foldFormula,\n formulaValueType,\n inferFormulaType,\n variableFormulaSchema,\n variableColorExpressionSchema\n} from '@pairdraw/scene-graph/variables'\n\n/**\n * Identity allocation shared by the two writers. The document exporter and the clipboard\n * both emit variables, modes and shared styles ahead of the nodes that reference them; when\n * each allocated its own way the two drifted.\n */\nexport function assignVariableGuid(\n id: string,\n localIdCounter: { value: number },\n assignedGuidValues: Set<string>,\n nodeSourceGuidValues: Set<string>,\n keepsGuid: (id: string) => boolean = () => true\n): GUID {\n const own = keepsGuid(id) ? parseGuidOrNull(id) : null\n if (own && !assignedGuidValues.has(id) && !nodeSourceGuidValues.has(id)) {\n assignedGuidValues.add(id)\n return own\n }\n const guid = { sessionID: 0, localID: localIdCounter.value++ }\n assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)\n return guid\n}\n\nexport function assignVariableGuids(\n graph: SceneGraph,\n localIdCounter: { value: number },\n varIdToGuid: Map<string, GUID>,\n modeIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>,\n nodeSourceGuidValues: Set<string>,\n keepsGuid?: (id: string) => boolean\n): void {\n for (const [colId, col] of graph.variableCollections) {\n const colGuid = assignVariableGuid(\n colId,\n localIdCounter,\n assignedGuidValues,\n nodeSourceGuidValues,\n keepsGuid\n )\n varIdToGuid.set(colId, colGuid)\n for (const mode of col.modes) {\n const modeGuid = assignVariableGuid(\n mode.modeId,\n localIdCounter,\n assignedGuidValues,\n nodeSourceGuidValues,\n keepsGuid\n )\n modeIdToGuid.set(mode.modeId, modeGuid)\n }\n for (const varId of col.variableIds) {\n const varGuid = assignVariableGuid(\n varId,\n localIdCounter,\n assignedGuidValues,\n nodeSourceGuidValues,\n keepsGuid\n )\n varIdToGuid.set(varId, varGuid)\n }\n }\n}\n\n/**\n * Where Figma lists each mode: where the file saved it, and a new mode after the rest. A\n * collection made in Pairdraw lists its modes in their order.\n */\nfunction modeSortPositions(modes: readonly VariableCollectionMode[]) {\n if (modes.every((mode) => !mode.sortPosition))\n return modes.map((mode, index) => ({ mode, sortPosition: fractionalPosition(index) }))\n let last = modes.reduce<string | null>(\n (highest, mode) =>\n mode.sortPosition && (!highest || mode.sortPosition > highest) ? mode.sortPosition : highest,\n null\n )\n return modes.map((mode) => {\n if (mode.sortPosition) return { mode, sortPosition: mode.sortPosition }\n last = orderKeyBetween(last, null)\n return { mode, sortPosition: last }\n })\n}\n\n/**\n * Shared styles live on the internal canvas and need a GUID before any node cites them. A style\n * read from Figma keeps the GUID it came with, which its ID spells; the others take new ones.\n */\nexport function assignSharedStyleGuids(\n styles: readonly SceneNode[],\n localIdCounter: { value: number },\n nodeIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>\n): void {\n for (const style of styles) {\n if (nodeIdToGuid.has(style.id)) continue\n // A style read from Figma keeps its GUID, compared in the form the ID parses to.\n const imported = style.source.id ? parseGuidOrNull(style.source.id) : null\n const value = imported ? guidToString(imported) : null\n if (imported && value && !assignedGuidValues.has(value)) {\n nodeIdToGuid.set(style.id, imported)\n assignedGuidValues.add(value)\n continue\n }\n let guid: GUID\n do {\n guid = { sessionID: 1, localID: localIdCounter.value++ }\n } while (assignedGuidValues.has(`${guid.sessionID}:${guid.localID}`))\n nodeIdToGuid.set(style.id, guid)\n assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)\n }\n}\n\nfunction variableValueToKiwi(\n graph: SceneGraph,\n value: VariableValue,\n type: string,\n ids: Map<string, GUID>,\n modes?: ReadonlyMap<string, GUID>\n): VariableDataEntry {\n if (isUnsupportedVariableValue(value)) {\n const data = unsupportedExpressionData(value.value)\n mapUnsupportedExpressionReferences(\n data,\n (_, index) => {\n const id = value.references[index]\n return id && graph.variables.has(id) ? variableAlias(graph, id, ids) : undefined\n },\n (guid, index) => modes?.get(value.modes[index] ?? '') ?? guid\n )\n return data\n }\n if (typeof value === 'object' && 'expression' in value && value.expression === 'FORMULA') {\n const formula = v.parse(variableFormulaSchema, value)\n if (formula.type !== type) throw new Error('Formula type does not match variable type')\n return formulaToKiwi(graph, formula.value, ids)\n }\n if (typeof value === 'object' && 'expression' in value) {\n const expression = v.parse(variableColorExpressionSchema, value)\n if (type !== 'COLOR') throw new Error('Color expression requires a color variable')\n return {\n dataType: 'EXPRESSION',\n resolvedDataType: 'COLOR',\n value: {\n expressionValue: {\n expressionFunction: expression.expression,\n expressionArguments: [\n variableValueToKiwi(graph, expression.color, 'COLOR', ids),\n variableValueToKiwi(graph, expression.opacity, 'FLOAT', ids)\n ]\n }\n }\n }\n }\n if (typeof value === 'object' && 'aliasId' in value)\n return {\n value: { alias: variableAlias(graph, value.aliasId, ids) },\n dataType: 'ALIAS',\n resolvedDataType: type\n }\n if (type === 'COLOR' && typeof value === 'object' && 'r' in value)\n return { value: { colorValue: safeColor(value) }, dataType: type, resolvedDataType: type }\n if (type === 'BOOLEAN')\n return { value: { boolValue: !!value }, dataType: type, resolvedDataType: type }\n if (type === 'STRING')\n return {\n value: { textValue: typeof value === 'string' ? value : JSON.stringify(value) },\n dataType: type,\n resolvedDataType: type\n }\n return { value: { floatValue: Number(value) }, dataType: 'FLOAT', resolvedDataType: 'FLOAT' }\n}\n\nfunction formulaToKiwi(\n graph: SceneGraph,\n node: VariableFormulaNode,\n ids: Map<string, GUID>\n): VariableDataEntry {\n const typeOf = (id: string) => graph.variables.get(id)?.type\n const known = <T>(type: T | undefined) => {\n if (!type) throw new Error('Formula references a missing variable')\n return type\n }\n return foldFormula<VariableDataEntry>(node, {\n literal: (value) => variableValueToKiwi(graph, value, formulaValueType(value), ids),\n reference: (id) => variableValueToKiwi(graph, { aliasId: id }, known(typeOf(id)), ids),\n operation: (operation, operands) => ({\n dataType: 'EXPRESSION',\n resolvedDataType: known(inferFormulaType(operation, typeOf)),\n value: {\n expressionValue: {\n expressionFunction: figmaFormulaFunction(operation.operator),\n expressionArguments: operands\n }\n }\n })\n })\n}\n\n/**\n * Order keys for one parent, in call order. Collections, variables, shared styles and the\n * canvas's own layers all append to the internal canvas, so they share one sequence rather\n * than each numbering from zero and handing siblings the same key.\n */\nexport function sequentialPositions(start = 0): () => string {\n let index = start\n return () => fractionalPosition(index++)\n}\n\nexport function appendVariableNodeChanges(\n graph: SceneGraph,\n changes: NodeChange[],\n parent: GUID,\n ids: Map<string, GUID>,\n modes: Map<string, GUID>,\n nextPosition: () => string = sequentialPositions()\n): void {\n const modeKey = (modeId: string) => guidToString(modes.get(modeId) ?? stringToGuid(modeId))\n for (const collection of graph.variableCollections.values()) {\n const guid = ids.get(collection.id) ?? stringToGuid(collection.id)\n changes.push({\n guid,\n parentIndex: { guid: parent, position: nextPosition() },\n type: 'VARIABLE_SET',\n name: collection.name,\n phase: 'CREATED',\n strokeAlign: 'CENTER',\n strokeJoin: 'BEVEL',\n // The saved array order is the file's own and round-trips as it was; the sort positions\n // carry the listed order, which the reader shows and the default follows.\n variableSetModes: modeSortPositions(collection.modes).map(({ mode, sortPosition }) => ({\n id: modes.get(mode.modeId) ?? stringToGuid(mode.modeId),\n name: mode.name,\n sortPosition\n })),\n pluginData: collectionPluginDataNodeChange(collection, modeKey),\n key: collection.key,\n version: collection.version\n })\n for (const id of collection.variableIds) {\n const variable = graph.variables.get(id)\n if (!variable) continue\n changes.push({\n guid: ids.get(id) ?? stringToGuid(id),\n parentIndex: { guid: parent, position: nextPosition() },\n type: 'VARIABLE',\n name: variable.name,\n phase: 'CREATED',\n strokeAlign: 'CENTER',\n strokeJoin: 'BEVEL',\n // A collection with a library key is named by it, as Figma names a library's.\n variableSetID: collection.key\n ? { assetRef: { key: collection.key, version: collection.version } }\n : { guid },\n variableResolvedType: variable.type,\n variableDataValues: {\n entries: Object.entries(variable.valuesByMode).map(([mode, value]) => ({\n modeID: modes.get(mode) ?? stringToGuid(mode),\n variableData: variableValueToKiwi(graph, value, variable.type, ids, modes)\n }))\n },\n ...variableMetadataNodeChange(variable, modeKey),\n key: variable.key,\n version: variable.version\n })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAqCA,SAAgB,mBACd,IACA,gBACA,oBACA,sBACA,kBAA2C,MACrC;CACN,MAAM,MAAM,UAAU,EAAE,IAAI,gBAAgB,EAAE,IAAI;CAClD,IAAI,OAAO,CAAC,mBAAmB,IAAI,EAAE,KAAK,CAAC,qBAAqB,IAAI,EAAE,GAAG;EACvE,mBA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C,CAAC,KAAK,CAAC,MAAM,YAAY;KACrE,QAAQ,MAAM,IAAI,IAAI,KAAK,aAAa,IAAI;KAC5C,cAAc,oBAAoB,OAAO,OAAO,SAAS,MAAM,KAAK,KAAK;IAC3E,EAAE,EACJ;IACA,GAAG,2BAA2B,UAAU,OAAO;IAC/C,KAAK,SAAS;IACd,SAAS,SAAS;GACpB,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"variables.js","names":[],"sources":["../../../../../src/io/formats/fig/export/variables.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport {\n collectionPluginDataNodeChange,\n figmaFormulaFunction,\n parseGuidOrNull,\n mapUnsupportedExpressionReferences,\n unsupportedExpressionData,\n variableAlias,\n variableMetadataNodeChange,\n safeColor\n} from '@pairdraw/fig/node-change'\nimport type { GUID } from '@pairdraw/kiwi/fig'\nimport type { NodeChange, VariableDataEntry } from '@pairdraw/kiwi/fig/codec'\nimport { guidToString, stringToGuid } from '@pairdraw/kiwi/fig/guid'\nimport type {\n SceneGraph,\n SceneNode,\n VariableFormulaNode,\n VariableCollectionMode,\n VariableValue\n} from '@pairdraw/scene-graph'\nimport { fractionalPosition, orderKeyBetween } from '@pairdraw/scene-graph/order-keys'\nimport {\n deletedVariablesOf,\n isUnsupportedVariableValue,\n foldFormula,\n formulaValueType,\n inferFormulaType,\n variableFormulaSchema,\n variableColorExpressionSchema\n} from '@pairdraw/scene-graph/variables'\n\n/**\n * Identity allocation shared by the two writers. The document exporter and the clipboard\n * both emit variables, modes and shared styles ahead of the nodes that reference them; when\n * each allocated its own way the two drifted.\n */\nexport function assignVariableGuid(\n id: string,\n localIdCounter: { value: number },\n assignedGuidValues: Set<string>,\n nodeSourceGuidValues: Set<string>,\n keepsGuid: (id: string) => boolean = () => true\n): GUID {\n const own = keepsGuid(id) ? parseGuidOrNull(id) : null\n if (own && !assignedGuidValues.has(id) && !nodeSourceGuidValues.has(id)) {\n assignedGuidValues.add(id)\n return own\n }\n const guid = { sessionID: 0, localID: localIdCounter.value++ }\n assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)\n return guid\n}\n\nexport function assignVariableGuids(\n graph: SceneGraph,\n localIdCounter: { value: number },\n varIdToGuid: Map<string, GUID>,\n modeIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>,\n nodeSourceGuidValues: Set<string>,\n keepsGuid?: (id: string) => boolean\n): void {\n for (const [colId, col] of graph.variableCollections) {\n const colGuid = assignVariableGuid(\n colId,\n localIdCounter,\n assignedGuidValues,\n nodeSourceGuidValues,\n keepsGuid\n )\n varIdToGuid.set(colId, colGuid)\n for (const mode of col.modes) {\n const modeGuid = assignVariableGuid(\n mode.modeId,\n localIdCounter,\n assignedGuidValues,\n nodeSourceGuidValues,\n keepsGuid\n )\n modeIdToGuid.set(mode.modeId, modeGuid)\n }\n // Deleted variables are written too, so they keep their GUIDs like the listed ones.\n for (const varId of [\n ...col.variableIds,\n ...deletedVariablesOf(graph, colId).map((item) => item.id)\n ]) {\n const varGuid = assignVariableGuid(\n varId,\n localIdCounter,\n assignedGuidValues,\n nodeSourceGuidValues,\n keepsGuid\n )\n varIdToGuid.set(varId, varGuid)\n }\n }\n}\n\n/**\n * Where Figma lists each mode: where the file saved it, and a new mode after the rest. A\n * collection made in Pairdraw lists its modes in their order.\n */\nfunction modeSortPositions(modes: readonly VariableCollectionMode[]) {\n if (modes.every((mode) => !mode.sortPosition))\n return modes.map((mode, index) => ({ mode, sortPosition: fractionalPosition(index) }))\n let last = modes.reduce<string | null>(\n (highest, mode) =>\n mode.sortPosition && (!highest || mode.sortPosition > highest) ? mode.sortPosition : highest,\n null\n )\n return modes.map((mode) => {\n if (mode.sortPosition) return { mode, sortPosition: mode.sortPosition }\n last = orderKeyBetween(last, null)\n return { mode, sortPosition: last }\n })\n}\n\n/**\n * Shared styles live on the internal canvas and need a GUID before any node cites them. A style\n * read from Figma keeps the GUID it came with, which its ID spells; the others take new ones.\n */\nexport function assignSharedStyleGuids(\n styles: readonly SceneNode[],\n localIdCounter: { value: number },\n nodeIdToGuid: Map<string, GUID>,\n assignedGuidValues: Set<string>\n): void {\n for (const style of styles) {\n if (nodeIdToGuid.has(style.id)) continue\n // A style read from Figma keeps its GUID, compared in the form the ID parses to.\n const imported = style.source.id ? parseGuidOrNull(style.source.id) : null\n const value = imported ? guidToString(imported) : null\n if (imported && value && !assignedGuidValues.has(value)) {\n nodeIdToGuid.set(style.id, imported)\n assignedGuidValues.add(value)\n continue\n }\n let guid: GUID\n do {\n guid = { sessionID: 1, localID: localIdCounter.value++ }\n } while (assignedGuidValues.has(`${guid.sessionID}:${guid.localID}`))\n nodeIdToGuid.set(style.id, guid)\n assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)\n }\n}\n\nfunction variableValueToKiwi(\n graph: SceneGraph,\n value: VariableValue,\n type: string,\n ids: Map<string, GUID>,\n modes?: ReadonlyMap<string, GUID>\n): VariableDataEntry {\n if (isUnsupportedVariableValue(value)) {\n const data = unsupportedExpressionData(value.value)\n mapUnsupportedExpressionReferences(\n data,\n (_, index) => {\n const id = value.references[index]\n return id && graph.variables.has(id) ? variableAlias(graph, id, ids) : undefined\n },\n (guid, index) => modes?.get(value.modes[index] ?? '') ?? guid\n )\n return data\n }\n if (typeof value === 'object' && 'expression' in value && value.expression === 'FORMULA') {\n const formula = v.parse(variableFormulaSchema, value)\n if (formula.type !== type) throw new Error('Formula type does not match variable type')\n return formulaToKiwi(graph, formula.value, ids)\n }\n if (typeof value === 'object' && 'expression' in value) {\n const expression = v.parse(variableColorExpressionSchema, value)\n if (type !== 'COLOR') throw new Error('Color expression requires a color variable')\n return {\n dataType: 'EXPRESSION',\n resolvedDataType: 'COLOR',\n value: {\n expressionValue: {\n expressionFunction: expression.expression,\n expressionArguments: [\n variableValueToKiwi(graph, expression.color, 'COLOR', ids),\n variableValueToKiwi(graph, expression.opacity, 'FLOAT', ids)\n ]\n }\n }\n }\n }\n if (typeof value === 'object' && 'aliasId' in value)\n return {\n value: { alias: variableAlias(graph, value.aliasId, ids) },\n dataType: 'ALIAS',\n resolvedDataType: type\n }\n if (type === 'COLOR' && typeof value === 'object' && 'r' in value)\n return { value: { colorValue: safeColor(value) }, dataType: type, resolvedDataType: type }\n if (type === 'BOOLEAN')\n return { value: { boolValue: !!value }, dataType: type, resolvedDataType: type }\n if (type === 'STRING')\n return {\n value: { textValue: typeof value === 'string' ? value : JSON.stringify(value) },\n dataType: type,\n resolvedDataType: type\n }\n return { value: { floatValue: Number(value) }, dataType: 'FLOAT', resolvedDataType: 'FLOAT' }\n}\n\nfunction formulaToKiwi(\n graph: SceneGraph,\n node: VariableFormulaNode,\n ids: Map<string, GUID>\n): VariableDataEntry {\n const typeOf = (id: string) => graph.variables.get(id)?.type\n const known = <T>(type: T | undefined) => {\n if (!type) throw new Error('Formula references a missing variable')\n return type\n }\n return foldFormula<VariableDataEntry>(node, {\n literal: (value) => variableValueToKiwi(graph, value, formulaValueType(value), ids),\n reference: (id) => variableValueToKiwi(graph, { aliasId: id }, known(typeOf(id)), ids),\n operation: (operation, operands) => ({\n dataType: 'EXPRESSION',\n resolvedDataType: known(inferFormulaType(operation, typeOf)),\n value: {\n expressionValue: {\n expressionFunction: figmaFormulaFunction(operation.operator),\n expressionArguments: operands\n }\n }\n })\n })\n}\n\n/**\n * Order keys for one parent, in call order. Collections, variables, shared styles and the\n * canvas's own layers all append to the internal canvas, so they share one sequence rather\n * than each numbering from zero and handing siblings the same key.\n */\nexport function sequentialPositions(start = 0): () => string {\n let index = start\n return () => fractionalPosition(index++)\n}\n\nexport function appendVariableNodeChanges(\n graph: SceneGraph,\n changes: NodeChange[],\n parent: GUID,\n ids: Map<string, GUID>,\n modes: Map<string, GUID>,\n nextPosition: () => string = sequentialPositions()\n): void {\n const modeKey = (modeId: string) => guidToString(modes.get(modeId) ?? stringToGuid(modeId))\n for (const collection of graph.variableCollections.values()) {\n const guid = ids.get(collection.id) ?? stringToGuid(collection.id)\n changes.push({\n guid,\n parentIndex: { guid: parent, position: nextPosition() },\n type: 'VARIABLE_SET',\n name: collection.name,\n phase: 'CREATED',\n strokeAlign: 'CENTER',\n strokeJoin: 'BEVEL',\n // The saved array order is the file's own and round-trips as it was; the sort positions\n // carry the listed order, which the reader shows and the default follows.\n variableSetModes: modeSortPositions(collection.modes).map(({ mode, sortPosition }) => ({\n id: modes.get(mode.modeId) ?? stringToGuid(mode.modeId),\n name: mode.name,\n sortPosition\n })),\n pluginData: collectionPluginDataNodeChange(collection, modeKey),\n key: collection.key,\n version: collection.version,\n ...(collection.deleted ? { isSoftDeleted: true } : {})\n })\n // Deleted variables follow the listed ones: the file keeps them for the layers bound to them.\n const variables = [\n ...collection.variableIds.flatMap((id) => graph.variables.get(id) ?? []),\n ...deletedVariablesOf(graph, collection.id)\n ]\n for (const variable of variables) {\n const id = variable.id\n changes.push({\n guid: ids.get(id) ?? stringToGuid(id),\n parentIndex: { guid: parent, position: nextPosition() },\n type: 'VARIABLE',\n name: variable.name,\n phase: 'CREATED',\n strokeAlign: 'CENTER',\n strokeJoin: 'BEVEL',\n // A collection with a library key is named by it, as Figma names a library's.\n variableSetID: collection.key\n ? { assetRef: { key: collection.key, version: collection.version } }\n : { guid },\n variableResolvedType: variable.type,\n variableDataValues: {\n entries: Object.entries(variable.valuesByMode).map(([mode, value]) => ({\n modeID: modes.get(mode) ?? stringToGuid(mode),\n variableData: variableValueToKiwi(graph, value, variable.type, ids, modes)\n }))\n },\n ...variableMetadataNodeChange(variable, modeKey),\n key: variable.key,\n version: variable.version,\n ...(variable.deleted ? { isSoftDeleted: true } : {})\n })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAsCA,SAAgB,mBACd,IACA,gBACA,oBACA,sBACA,kBAA2C,MACrC;CACN,MAAM,MAAM,UAAU,EAAE,IAAI,gBAAgB,EAAE,IAAI;CAClD,IAAI,OAAO,CAAC,mBAAmB,IAAI,EAAE,KAAK,CAAC,qBAAqB,IAAI,EAAE,GAAG;EACvE,mBAAmB,IAAI,EAAE;EACz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;IACf,OAAO;IACP,aAAa;IACb,YAAY;IAEZ,eAAe,WAAW,MACtB,EAAE,UAAU;KAAE,KAAK,WAAW;KAAK,SAAS,WAAW;IAAQ,EAAE,IACjE,EAAE,KAAK;IACX,sBAAsB,SAAS;IAC/B,oBAAoB,EAClB,SAAS,OAAO,QAAQ,SAAS,YAAY,CAAC,CAAC,KAAK,CAAC,MAAM,YAAY;KACrE,QAAQ,MAAM,IAAI,IAAI,KAAK,aAAa,IAAI;KAC5C,cAAc,oBAAoB,OAAO,OAAO,SAAS,MAAM,KAAK,KAAK;IAC3E,EAAE,EACJ;IACA,GAAG,2BAA2B,UAAU,OAAO;IAC/C,KAAK,SAAS;IACd,SAAS,SAAS;IAClB,GAAI,SAAS,UAAU,EAAE,eAAe,KAAK,IAAI,CAAC;GACpD,CAAC;EACH;CACF;AACF"}
|
|
@@ -33,6 +33,7 @@ const vectorElement = (graph, node, booleanPath) => {
|
|
|
33
33
|
const idPrefix = `${idPart(node.id)}-`;
|
|
34
34
|
const icon = readIcon(node);
|
|
35
35
|
const drawn = renderNodeSVGElement(graph, node, {
|
|
36
|
+
documentColorSpace: graph.documentColorSpace,
|
|
36
37
|
idPrefix,
|
|
37
38
|
colorSpace: graph.documentColorSpace,
|
|
38
39
|
tint: icon ? readIconTint : void 0,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vectors.js","names":[],"sources":["../../../../src/io/formats/html/vectors.ts"],"sourcesContent":["import type { DesignElement, DesignNode, VectorElementRenderer } from '@pairdraw/dom-css/export'\nimport { colorToHex } from '@pairdraw/scene-graph/color'\nimport { isIconModified, readIcon, readIconTint } from '@pairdraw/scene-graph/icons'\n\nimport { iconColor } from '#core/icons/render'\nimport type { BooleanPathResolver } from '#core/io/formats/boolean-path'\nimport { renderNodeSVGElement } from '#core/io/formats/svg/export'\nimport type { SVGNode } from '#core/io/formats/svg/node'\n\nfunction designNode(node: SVGNode | string): DesignNode {\n if (typeof node === 'string') return { type: 'text', text: node }\n return {\n type: 'element',\n tagName: node.tag,\n attrs: Object.fromEntries(\n Object.entries(node.attrs).map(([name, value]) => [name, String(value)])\n ),\n children: node.children.map(designNode)\n }\n}\n\n/**\n * A layer id as an id-safe string, one to one: letters, digits, and `-` stay, and anything\n * else, `_` included, becomes `_<code point>_`, so `a:b` and `a-b` never meet.\n */\nfunction idPart(id: string): string {\n return id.replace(/[^A-Za-z0-9-]/gu, (char) => `_${char.codePointAt(0)?.toString(16) ?? ''}_`)\n}\n\n/**\n * Vector layers and icons in HTML exports as inline SVG from the SVG export, so paths,\n * gradients, and shadows draw as they do there. An icon is one SVG whose tinted paths take\n * `currentColor`, so a page recolors it with CSS `color`, named by `data-icon` unless its paths\n * were edited. Def ids start with the layer's id, so several SVGs on one page never pick up each\n * other's gradients or filters.\n */\nexport const vectorElement = (\n graph: Parameters<VectorElementRenderer>[0],\n node: Parameters<VectorElementRenderer>[1],\n booleanPath?: BooleanPathResolver\n): ReturnType<VectorElementRenderer> => {\n const idPrefix = `${idPart(node.id)}-`\n const icon = readIcon(node)\n const drawn = renderNodeSVGElement(graph, node, {\n idPrefix,\n colorSpace: graph.documentColorSpace,\n tint: icon ? readIconTint : undefined,\n booleanPath\n })\n const element = drawn && designNode(drawn)\n if (element?.type !== 'element') return null\n const color = icon ? iconColor(graph, node) : null\n return {\n ...element,\n // An icon whose paths were edited no longer draws the named icon, so it goes unnamed.\n attrs:\n icon && !isIconModified(graph, node)\n ? { ...element.attrs, 'data-icon': icon.name }\n : element.attrs,\n // Strokes and shadows can reach past the layer's box, which an inline SVG would clip.\n inlineStyle: { overflow: 'visible', ...(color ? { color: colorToHex(color) } : {}) }\n } satisfies DesignElement\n}\n"],"mappings":";;;;;AASA,SAAS,WAAW,MAAoC;CACtD,IAAI,OAAO,SAAS,UAAU,OAAO;EAAE,MAAM;EAAQ,MAAM;CAAK;CAChE,OAAO;EACL,MAAM;EACN,SAAS,KAAK;EACd,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,MAAM,OAAO,KAAK,CAAC,CAAC,CACzE;EACA,UAAU,KAAK,SAAS,IAAI,UAAU;CACxC;AACF;;;;;AAMA,SAAS,OAAO,IAAoB;CAClC,OAAO,GAAG,QAAQ,oBAAoB,SAAS,IAAI,KAAK,YAAY,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,GAAG,EAAE;AAC/F;;;;;;;;AASA,MAAa,iBACX,OACA,MACA,gBACsC;CACtC,MAAM,WAAW,GAAG,OAAO,KAAK,EAAE,EAAE;CACpC,MAAM,OAAO,SAAS,IAAI;CAC1B,MAAM,QAAQ,qBAAqB,OAAO,MAAM;EAC9C;EACA,YAAY,MAAM;EAClB,MAAM,OAAO,eAAe,KAAA;EAC5B;CACF,CAAC;CACD,MAAM,UAAU,SAAS,WAAW,KAAK;CACzC,IAAI,SAAS,SAAS,WAAW,OAAO;CACxC,MAAM,QAAQ,OAAO,UAAU,OAAO,IAAI,IAAI;CAC9C,OAAO;EACL,GAAG;EAEH,OACE,QAAQ,CAAC,eAAe,OAAO,IAAI,IAC/B;GAAE,GAAG,QAAQ;GAAO,aAAa,KAAK;EAAK,IAC3C,QAAQ;EAEd,aAAa;GAAE,UAAU;GAAW,GAAI,QAAQ,EAAE,OAAO,WAAW,KAAK,EAAE,IAAI,CAAC;EAAG;CACrF;AACF"}
|
|
1
|
+
{"version":3,"file":"vectors.js","names":[],"sources":["../../../../src/io/formats/html/vectors.ts"],"sourcesContent":["import type { DesignElement, DesignNode, VectorElementRenderer } from '@pairdraw/dom-css/export'\nimport { colorToHex } from '@pairdraw/scene-graph/color'\nimport { isIconModified, readIcon, readIconTint } from '@pairdraw/scene-graph/icons'\n\nimport { iconColor } from '#core/icons/render'\nimport type { BooleanPathResolver } from '#core/io/formats/boolean-path'\nimport { renderNodeSVGElement } from '#core/io/formats/svg/export'\nimport type { SVGNode } from '#core/io/formats/svg/node'\n\nfunction designNode(node: SVGNode | string): DesignNode {\n if (typeof node === 'string') return { type: 'text', text: node }\n return {\n type: 'element',\n tagName: node.tag,\n attrs: Object.fromEntries(\n Object.entries(node.attrs).map(([name, value]) => [name, String(value)])\n ),\n children: node.children.map(designNode)\n }\n}\n\n/**\n * A layer id as an id-safe string, one to one: letters, digits, and `-` stay, and anything\n * else, `_` included, becomes `_<code point>_`, so `a:b` and `a-b` never meet.\n */\nfunction idPart(id: string): string {\n return id.replace(/[^A-Za-z0-9-]/gu, (char) => `_${char.codePointAt(0)?.toString(16) ?? ''}_`)\n}\n\n/**\n * Vector layers and icons in HTML exports as inline SVG from the SVG export, so paths,\n * gradients, and shadows draw as they do there. An icon is one SVG whose tinted paths take\n * `currentColor`, so a page recolors it with CSS `color`, named by `data-icon` unless its paths\n * were edited. Def ids start with the layer's id, so several SVGs on one page never pick up each\n * other's gradients or filters.\n */\nexport const vectorElement = (\n graph: Parameters<VectorElementRenderer>[0],\n node: Parameters<VectorElementRenderer>[1],\n booleanPath?: BooleanPathResolver\n): ReturnType<VectorElementRenderer> => {\n const idPrefix = `${idPart(node.id)}-`\n const icon = readIcon(node)\n const drawn = renderNodeSVGElement(graph, node, {\n documentColorSpace: graph.documentColorSpace,\n idPrefix,\n colorSpace: graph.documentColorSpace,\n tint: icon ? readIconTint : undefined,\n booleanPath\n })\n const element = drawn && designNode(drawn)\n if (element?.type !== 'element') return null\n const color = icon ? iconColor(graph, node) : null\n return {\n ...element,\n // An icon whose paths were edited no longer draws the named icon, so it goes unnamed.\n attrs:\n icon && !isIconModified(graph, node)\n ? { ...element.attrs, 'data-icon': icon.name }\n : element.attrs,\n // Strokes and shadows can reach past the layer's box, which an inline SVG would clip.\n inlineStyle: { overflow: 'visible', ...(color ? { color: colorToHex(color) } : {}) }\n } satisfies DesignElement\n}\n"],"mappings":";;;;;AASA,SAAS,WAAW,MAAoC;CACtD,IAAI,OAAO,SAAS,UAAU,OAAO;EAAE,MAAM;EAAQ,MAAM;CAAK;CAChE,OAAO;EACL,MAAM;EACN,SAAS,KAAK;EACd,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,MAAM,OAAO,KAAK,CAAC,CAAC,CACzE;EACA,UAAU,KAAK,SAAS,IAAI,UAAU;CACxC;AACF;;;;;AAMA,SAAS,OAAO,IAAoB;CAClC,OAAO,GAAG,QAAQ,oBAAoB,SAAS,IAAI,KAAK,YAAY,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,GAAG,EAAE;AAC/F;;;;;;;;AASA,MAAa,iBACX,OACA,MACA,gBACsC;CACtC,MAAM,WAAW,GAAG,OAAO,KAAK,EAAE,EAAE;CACpC,MAAM,OAAO,SAAS,IAAI;CAC1B,MAAM,QAAQ,qBAAqB,OAAO,MAAM;EAC9C,oBAAoB,MAAM;EAC1B;EACA,YAAY,MAAM;EAClB,MAAM,OAAO,eAAe,KAAA;EAC5B;CACF,CAAC;CACD,MAAM,UAAU,SAAS,WAAW,KAAK;CACzC,IAAI,SAAS,SAAS,WAAW,OAAO;CACxC,MAAM,QAAQ,OAAO,UAAU,OAAO,IAAI,IAAI;CAC9C,OAAO;EACL,GAAG;EAEH,OACE,QAAQ,CAAC,eAAe,OAAO,IAAI,IAC/B;GAAE,GAAG,QAAQ;GAAO,aAAa,KAAK;EAAK,IAC3C,QAAQ;EAEd,aAAa;GAAE,UAAU;GAAW,GAAI,QAAQ,EAAE,OAAO,WAAW,KAAK,EAAE,IAAI,CAAC;EAAG;CACrF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { resolveFontReadiness } from "../../../text/prepare.js";
|
|
2
2
|
import { shapeWithTextWidthFor } from "../../../layout/shape-with-text.js";
|
|
3
3
|
import { layoutAuthoredNodes } from "../../../layout.js";
|
|
4
4
|
import { connectorLabelSize } from "../../../layout/arrange/routes.js";
|
|
@@ -213,7 +213,7 @@ async function addFlowchart(graph, parentId, chart, placement = { topLeft: {
|
|
|
213
213
|
for (const edge of chart.edges) builder.connector(edge);
|
|
214
214
|
const added = addedSoFar();
|
|
215
215
|
created = added;
|
|
216
|
-
await
|
|
216
|
+
await resolveFontReadiness(graph, added);
|
|
217
217
|
for (const node of chart.nodes) builder.fitWidth(node);
|
|
218
218
|
layoutAuthoredNodes(graph, added);
|
|
219
219
|
const enclosing = enclosingSubgraphs(chart);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layers.js","names":[],"sources":["../../../../src/io/formats/mermaid/layers.ts"],"sourcesContent":["import type {\n FlowArrowhead,\n FlowEdge,\n FlowLabel,\n FlowNode,\n FlowSubgraph,\n Flowchart\n} from '@pairdraw/mermaid'\nimport type { Fill, SceneGraph, SceneNode, Stroke, StrokeCap } from '@pairdraw/scene-graph'\nimport { connectorSublayers, createConnector, freeEndpoint } from '@pairdraw/scene-graph/connectors'\nimport { BLACK } from '@pairdraw/scene-graph/constants'\nimport { createShapeWithText } from '@pairdraw/scene-graph/generated'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { newLayerDefaults } from '#core/editor/shapes/defaults'\nimport { layoutAuthoredNodes } from '#core/layout'\nimport { applyArrangement, type ArrangePlacement } from '#core/layout/arrange/apply'\nimport { arrangeBoxes, type ArrangeInput } from '#core/layout/arrange/boxes'\nimport { connectorLabelSize } from '#core/layout/arrange/routes'\nimport { shapeWithTextWidthFor } from '#core/layout/shape-with-text'\nimport { prepareGraphFonts } from '#core/text/prepare'\n\nimport { figJamShape } from './shapes'\nimport { declarationsFor, readStyle, type FlowStyle } from './styles'\n\n/** Shape widths Mermaid's labels fit between, and how wide a label runs before it wraps. */\nconst MIN_SHAPE_WIDTH = 96\nconst MAX_SHAPE_WIDTH = 320\nconst LABEL_LINE_WIDTH = 200\n/** The height a shape starts from; a label of more lines makes it taller. */\nconst SHAPE_HEIGHT = 56\n\n/** How much wider Mermaid draws a thick edge, `==>`, than a normal one. */\nconst THICK = 1.5\n\n/** Arrowheads as FigJam ends: Mermaid's filled triangle, dot, and cross. */\nconst CAPS: Record<FlowArrowhead, StrokeCap> = {\n none: 'NONE',\n arrow: 'ARROW_EQUILATERAL',\n circle: 'CIRCLE_FILLED',\n // FigJam has no cross end.\n cross: 'ARROW_LINES'\n}\n\nfunction solid(color: Color): Fill {\n return { type: 'SOLID', color: { ...color }, opacity: 1, visible: true }\n}\n\n/** Markdown's emphasis marks taken out, which a label shows as plain text for now. */\nfunction labelText(label: FlowLabel): string {\n if (label.format === 'text') return label.text\n return label.text.replace(/(\\*\\*|__)(.+?)\\1/g, '$2').replace(/([*_])(.+?)\\1/g, '$2')\n}\n\nfunction styledFills(layer: Partial<SceneNode>, style: FlowStyle): Fill[] | undefined {\n if (style.fill === undefined) return layer.fills\n return style.fill === null ? [] : [solid(style.fill)]\n}\n\n/** A stroke with a Mermaid style's colour, width, and dashes over it. */\nfunction styledStroke(base: Stroke, style: FlowStyle): Stroke {\n const stroke: Stroke = { ...base, color: { ...base.color }, align: 'CENTER' }\n if (style.stroke) stroke.color = { ...style.stroke }\n if (style.strokeWidth !== undefined) stroke.weight = style.strokeWidth\n if (style.dashPattern) stroke.dashPattern = style.dashPattern\n return stroke\n}\n\n/** A layer's paint with a Mermaid style over it: fill, outline colour, width, and dashes. */\nfunction painted(layer: Partial<SceneNode>, style: FlowStyle): Partial<SceneNode> {\n const result: Partial<SceneNode> = { ...layer, fills: styledFills(layer, style) }\n if (style.stroke === null) {\n result.strokes = []\n return result\n }\n if (!style.stroke && style.strokeWidth === undefined && !style.dashPattern) return result\n const base = layer.strokes?.at(0) ?? {\n ...solid(style.stroke ?? BLACK),\n weight: 1,\n align: 'CENTER'\n }\n const stroke = styledStroke(base, style)\n result.strokes = [stroke]\n result.strokeWeight = stroke.weight\n if (style.dashPattern) result.dashPattern = style.dashPattern\n return result\n}\n\n/** Where each node and subgraph sits: the subgraph holding it, if any. */\nfunction enclosingSubgraphs(chart: Flowchart): Map<string, string> {\n const enclosing = new Map<string, string>()\n for (const subgraph of chart.subgraphs) {\n for (const member of subgraph.members) enclosing.set(member, subgraph.id)\n }\n return enclosing\n}\n\nclass FlowchartBuilder {\n /** The layer each node and subgraph became. */\n readonly layers = new Map<string, string>()\n readonly connectors = new Map<string, string>()\n private readonly enclosing: Map<string, string>\n\n constructor(\n private readonly graph: SceneGraph,\n private readonly parentId: string,\n private readonly chart: Flowchart\n ) {\n this.enclosing = enclosingSubgraphs(chart)\n }\n\n /** The layer a node or subgraph goes in: its subgraph's section, or the diagram's parent. */\n private parentOf(id: string): string {\n const subgraph = this.enclosing.get(id)\n return (subgraph && this.layers.get(subgraph)) ?? this.parentId\n }\n\n sections() {\n const byId = new Map(this.chart.subgraphs.map((subgraph) => [subgraph.id, subgraph]))\n const create = (subgraph: FlowSubgraph) => {\n if (this.layers.has(subgraph.id)) return\n const outer = this.enclosing.get(subgraph.id)\n const outerSubgraph = outer ? byId.get(outer) : undefined\n if (outerSubgraph) create(outerSubgraph)\n const style = readStyle(\n declarationsFor(this.chart.classDefs, subgraph.classes, subgraph.styles)\n )\n const section = this.graph.createNode('SECTION', this.parentOf(subgraph.id), {\n ...painted(newLayerDefaults('SECTION'), style),\n name: labelText(subgraph.title) || subgraph.id\n })\n this.layers.set(subgraph.id, section.id)\n }\n for (const subgraph of this.chart.subgraphs) create(subgraph)\n }\n\n shape(node: FlowNode) {\n const { graph } = this\n const kind = figJamShape(node.shape)\n const style = readStyle(declarationsFor(this.chart.classDefs, node.classes, node.styles))\n const defaults = newLayerDefaults('SHAPE_WITH_TEXT')\n // Mermaid's text block draws its label alone.\n const own = node.shape === 'text' ? { ...defaults, fills: [], strokes: [] } : defaults\n const text = labelText(node.label)\n const shape = createShapeWithText(\n graph,\n this.parentOf(node.id),\n {\n ...painted(own, style),\n shapeWithTextType: kind.type,\n flipY: kind.flipY ?? false,\n width: MIN_SHAPE_WIDTH,\n height: kind.round ? MIN_SHAPE_WIDTH : SHAPE_HEIGHT,\n shapeTruncates: false,\n name: text.split('\\n')[0]?.trim() || node.id\n },\n style.color ? { text, fills: [solid(style.color)] } : { text }\n )\n this.layers.set(node.id, shape.id)\n }\n\n /** Widens a node's shape until its label runs no wider than a line, as Mermaid sizes it. */\n fitWidth(node: FlowNode) {\n const { graph } = this\n const layerId = this.layers.get(node.id)\n const shape = layerId ? graph.getNode(layerId) : undefined\n if (!shape) return\n const { round } = figJamShape(node.shape)\n const width = shapeWithTextWidthFor(\n graph,\n shape,\n { min: MIN_SHAPE_WIDTH, max: MAX_SHAPE_WIDTH, lineWidth: LABEL_LINE_WIDTH },\n (candidate) => (round ? candidate : SHAPE_HEIGHT)\n )\n const height = round ? width : SHAPE_HEIGHT\n graph.updateNode(shape.id, { width, height, shapeUserHeight: height })\n }\n\n /** A connector for each drawn edge, its ends free until the layout places them. */\n connector(edge: FlowEdge) {\n if (edge.stroke === 'invisible') return\n const { graph } = this\n const style = readStyle(edge.styles)\n const connector = createConnector(graph, this.parentId, {\n start: freeEndpoint(0, 0),\n end: freeEndpoint(0, 0),\n lineType: 'ELBOWED',\n startCap: CAPS[edge.startArrow],\n endCap: CAPS[edge.endArrow],\n text: edge.label ? labelText(edge.label) : ''\n })\n const parts = connectorSublayers(graph, connector)\n const stroke = parts?.line.strokes.at(0)\n if (parts && stroke) {\n const weight = edge.stroke === 'thick' ? stroke.weight * THICK : stroke.weight\n const line = styledStroke(\n {\n ...stroke,\n weight,\n dashPattern: edge.stroke === 'dotted' ? [weight * 2, weight * 2] : []\n },\n style\n )\n graph.updateNode(parts.line.id, {\n strokes: style.stroke === null ? [] : [line],\n strokeWeight: line.weight,\n dashPattern: line.dashPattern ?? []\n })\n if (style.color) graph.updateNode(parts.label.id, { fills: [solid(style.color)] })\n }\n this.connectors.set(edge.id, connector.id)\n }\n}\n\n/** What a flowchart became. */\nexport interface FlowchartLayers {\n /** The layers added to the parent, in order. */\n ids: string[]\n /** The layer each node and subgraph became, by its Mermaid id. */\n layers: Map<string, string>\n /** The connector each drawn edge became, by its Mermaid id. */\n connectors: Map<string, string>\n}\n\n/**\n * Adds a flowchart to `parentId` as FigJam layers, where `placement` puts it: each node a\n * shape with text sized to its label, each subgraph a section, and each edge an elbowed connector\n * joined to the layers it links, all laid out by ELK along the chart's direction, its text\n * measured in the fonts it is drawn in.\n */\nexport async function addFlowchart(\n graph: SceneGraph,\n parentId: string,\n chart: Flowchart,\n placement: ArrangePlacement = { topLeft: { x: 0, y: 0 } }\n): Promise<FlowchartLayers> {\n const before = new Set(graph.getNode(parentId)?.childIds)\n const builder = new FlowchartBuilder(graph, parentId, chart)\n const addedSoFar = () => (graph.getNode(parentId)?.childIds ?? []).filter((id) => !before.has(id))\n // Known before the first wait, so a layer someone else adds meanwhile is never taken for ours.\n let created: string[] | null = null\n try {\n builder.sections()\n for (const node of chart.nodes) builder.shape(node)\n for (const edge of chart.edges) builder.connector(edge)\n const added = addedSoFar()\n created = added\n // Shapes grow to their labels, and connector labels take their size, before the layout reads\n // them, measured in the fonts they are drawn in.\n await prepareGraphFonts(graph, added)\n for (const node of chart.nodes) builder.fitWidth(node)\n layoutAuthoredNodes(graph, added)\n const enclosing = enclosingSubgraphs(chart)\n const size = (id: string) => {\n const layer = builder.layers.get(id)\n const node = layer ? graph.getNode(layer) : undefined\n return { width: node?.width ?? MIN_SHAPE_WIDTH, height: node?.height ?? SHAPE_HEIGHT }\n }\n const labelSize = (edgeId: string) => {\n const connectorId = builder.connectors.get(edgeId)\n return (connectorId && connectorLabelSize(graph, connectorId)) || undefined\n }\n const input: ArrangeInput = {\n layout: 'flow',\n direction: chart.direction,\n boxes: chart.nodes.map((node) => ({\n id: node.id,\n ...size(node.id),\n group: enclosing.get(node.id)\n })),\n groups: chart.subgraphs.map((subgraph) => ({\n id: subgraph.id,\n group: enclosing.get(subgraph.id)\n })),\n edges: chart.edges.map((edge) => ({\n id: edge.id,\n from: edge.from,\n to: edge.to,\n label: labelSize(edge.id)\n }))\n }\n const arrangement = await arrangeBoxes(input)\n applyArrangement(\n graph,\n input,\n arrangement,\n { boxes: builder.layers, connectors: builder.connectors },\n placement\n )\n return { ids: added, layers: builder.layers, connectors: builder.connectors }\n } catch (error) {\n // A flowchart that fails to lay out leaves nothing half-built behind.\n for (const id of (created ?? addedSoFar()).toReversed()) graph.deleteNode(id)\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;;AAEzB,MAAM,eAAe;;AAGrB,MAAM,QAAQ;;AAGd,MAAM,OAAyC;CAC7C,MAAM;CACN,OAAO;CACP,QAAQ;CAER,OAAO;AACT;AAEA,SAAS,MAAM,OAAoB;CACjC,OAAO;EAAE,MAAM;EAAS,OAAO,EAAE,GAAG,MAAM;EAAG,SAAS;EAAG,SAAS;CAAK;AACzE;;AAGA,SAAS,UAAU,OAA0B;CAC3C,IAAI,MAAM,WAAW,QAAQ,OAAO,MAAM;CAC1C,OAAO,MAAM,KAAK,QAAQ,qBAAqB,IAAI,CAAC,CAAC,QAAQ,kBAAkB,IAAI;AACrF;AAEA,SAAS,YAAY,OAA2B,OAAsC;CACpF,IAAI,MAAM,SAAS,KAAA,GAAW,OAAO,MAAM;CAC3C,OAAO,MAAM,SAAS,OAAO,CAAC,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC;AACtD;;AAGA,SAAS,aAAa,MAAc,OAA0B;CAC5D,MAAM,SAAiB;EAAE,GAAG;EAAM,OAAO,EAAE,GAAG,KAAK,MAAM;EAAG,OAAO;CAAS;CAC5E,IAAI,MAAM,QAAQ,OAAO,QAAQ,EAAE,GAAG,MAAM,OAAO;CACnD,IAAI,MAAM,gBAAgB,KAAA,GAAW,OAAO,SAAS,MAAM;CAC3D,IAAI,MAAM,aAAa,OAAO,cAAc,MAAM;CAClD,OAAO;AACT;;AAGA,SAAS,QAAQ,OAA2B,OAAsC;CAChF,MAAM,SAA6B;EAAE,GAAG;EAAO,OAAO,YAAY,OAAO,KAAK;CAAE;CAChF,IAAI,MAAM,WAAW,MA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IAAI,KAAK,EAAE;GAC9B,EAAE;GACF,QAAQ,MAAM,UAAU,KAAK,cAAc;IACzC,IAAI,SAAS;IACb,OAAO,UAAU,IAAI,SAAS,EAAE;GAClC,EAAE;GACF,OAAO,MAAM,MAAM,KAAK,UAAU;IAChC,IAAI,KAAK;IACT,MAAM,KAAK;IACX,IAAI,KAAK;IACT,OAAO,UAAU,KAAK,EAAE;GAC1B,EAAE;EACJ;EACA,MAAM,cAAc,MAAM,aAAa,KAAK;EAC5C,iBACE,OACA,OACA,aACA;GAAE,OAAO,QAAQ;GAAQ,YAAY,QAAQ;EAAW,GACxD,SACF;EACA,OAAO;GAAE,KAAK;GAAO,QAAQ,QAAQ;GAAQ,YAAY,QAAQ;EAAW;CAC9E,SAAS,OAAO;EAEd,KAAK,MAAM,OAAO,WAAW,WAAW,EAAA,CAAG,WAAW,GAAG,MAAM,WAAW,EAAE;EAC5E,MAAM;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"layers.js","names":[],"sources":["../../../../src/io/formats/mermaid/layers.ts"],"sourcesContent":["import type {\n FlowArrowhead,\n FlowEdge,\n FlowLabel,\n FlowNode,\n FlowSubgraph,\n Flowchart\n} from '@pairdraw/mermaid'\nimport type { Fill, SceneGraph, SceneNode, Stroke, StrokeCap } from '@pairdraw/scene-graph'\nimport { connectorSublayers, createConnector, freeEndpoint } from '@pairdraw/scene-graph/connectors'\nimport { BLACK } from '@pairdraw/scene-graph/constants'\nimport { createShapeWithText } from '@pairdraw/scene-graph/generated'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { newLayerDefaults } from '#core/editor/shapes/defaults'\nimport { layoutAuthoredNodes } from '#core/layout'\nimport { applyArrangement, type ArrangePlacement } from '#core/layout/arrange/apply'\nimport { arrangeBoxes, type ArrangeInput } from '#core/layout/arrange/boxes'\nimport { connectorLabelSize } from '#core/layout/arrange/routes'\nimport { shapeWithTextWidthFor } from '#core/layout/shape-with-text'\nimport { resolveFontReadiness } from '#core/text/prepare'\n\nimport { figJamShape } from './shapes'\nimport { declarationsFor, readStyle, type FlowStyle } from './styles'\n\n/** Shape widths Mermaid's labels fit between, and how wide a label runs before it wraps. */\nconst MIN_SHAPE_WIDTH = 96\nconst MAX_SHAPE_WIDTH = 320\nconst LABEL_LINE_WIDTH = 200\n/** The height a shape starts from; a label of more lines makes it taller. */\nconst SHAPE_HEIGHT = 56\n\n/** How much wider Mermaid draws a thick edge, `==>`, than a normal one. */\nconst THICK = 1.5\n\n/** Arrowheads as FigJam ends: Mermaid's filled triangle, dot, and cross. */\nconst CAPS: Record<FlowArrowhead, StrokeCap> = {\n none: 'NONE',\n arrow: 'ARROW_EQUILATERAL',\n circle: 'CIRCLE_FILLED',\n // FigJam has no cross end.\n cross: 'ARROW_LINES'\n}\n\nfunction solid(color: Color): Fill {\n return { type: 'SOLID', color: { ...color }, opacity: 1, visible: true }\n}\n\n/** Markdown's emphasis marks taken out, which a label shows as plain text for now. */\nfunction labelText(label: FlowLabel): string {\n if (label.format === 'text') return label.text\n return label.text.replace(/(\\*\\*|__)(.+?)\\1/g, '$2').replace(/([*_])(.+?)\\1/g, '$2')\n}\n\nfunction styledFills(layer: Partial<SceneNode>, style: FlowStyle): Fill[] | undefined {\n if (style.fill === undefined) return layer.fills\n return style.fill === null ? [] : [solid(style.fill)]\n}\n\n/** A stroke with a Mermaid style's colour, width, and dashes over it. */\nfunction styledStroke(base: Stroke, style: FlowStyle): Stroke {\n const stroke: Stroke = { ...base, color: { ...base.color }, align: 'CENTER' }\n if (style.stroke) stroke.color = { ...style.stroke }\n if (style.strokeWidth !== undefined) stroke.weight = style.strokeWidth\n if (style.dashPattern) stroke.dashPattern = style.dashPattern\n return stroke\n}\n\n/** A layer's paint with a Mermaid style over it: fill, outline colour, width, and dashes. */\nfunction painted(layer: Partial<SceneNode>, style: FlowStyle): Partial<SceneNode> {\n const result: Partial<SceneNode> = { ...layer, fills: styledFills(layer, style) }\n if (style.stroke === null) {\n result.strokes = []\n return result\n }\n if (!style.stroke && style.strokeWidth === undefined && !style.dashPattern) return result\n const base = layer.strokes?.at(0) ?? {\n ...solid(style.stroke ?? BLACK),\n weight: 1,\n align: 'CENTER'\n }\n const stroke = styledStroke(base, style)\n result.strokes = [stroke]\n result.strokeWeight = stroke.weight\n if (style.dashPattern) result.dashPattern = style.dashPattern\n return result\n}\n\n/** Where each node and subgraph sits: the subgraph holding it, if any. */\nfunction enclosingSubgraphs(chart: Flowchart): Map<string, string> {\n const enclosing = new Map<string, string>()\n for (const subgraph of chart.subgraphs) {\n for (const member of subgraph.members) enclosing.set(member, subgraph.id)\n }\n return enclosing\n}\n\nclass FlowchartBuilder {\n /** The layer each node and subgraph became. */\n readonly layers = new Map<string, string>()\n readonly connectors = new Map<string, string>()\n private readonly enclosing: Map<string, string>\n\n constructor(\n private readonly graph: SceneGraph,\n private readonly parentId: string,\n private readonly chart: Flowchart\n ) {\n this.enclosing = enclosingSubgraphs(chart)\n }\n\n /** The layer a node or subgraph goes in: its subgraph's section, or the diagram's parent. */\n private parentOf(id: string): string {\n const subgraph = this.enclosing.get(id)\n return (subgraph && this.layers.get(subgraph)) ?? this.parentId\n }\n\n sections() {\n const byId = new Map(this.chart.subgraphs.map((subgraph) => [subgraph.id, subgraph]))\n const create = (subgraph: FlowSubgraph) => {\n if (this.layers.has(subgraph.id)) return\n const outer = this.enclosing.get(subgraph.id)\n const outerSubgraph = outer ? byId.get(outer) : undefined\n if (outerSubgraph) create(outerSubgraph)\n const style = readStyle(\n declarationsFor(this.chart.classDefs, subgraph.classes, subgraph.styles)\n )\n const section = this.graph.createNode('SECTION', this.parentOf(subgraph.id), {\n ...painted(newLayerDefaults('SECTION'), style),\n name: labelText(subgraph.title) || subgraph.id\n })\n this.layers.set(subgraph.id, section.id)\n }\n for (const subgraph of this.chart.subgraphs) create(subgraph)\n }\n\n shape(node: FlowNode) {\n const { graph } = this\n const kind = figJamShape(node.shape)\n const style = readStyle(declarationsFor(this.chart.classDefs, node.classes, node.styles))\n const defaults = newLayerDefaults('SHAPE_WITH_TEXT')\n // Mermaid's text block draws its label alone.\n const own = node.shape === 'text' ? { ...defaults, fills: [], strokes: [] } : defaults\n const text = labelText(node.label)\n const shape = createShapeWithText(\n graph,\n this.parentOf(node.id),\n {\n ...painted(own, style),\n shapeWithTextType: kind.type,\n flipY: kind.flipY ?? false,\n width: MIN_SHAPE_WIDTH,\n height: kind.round ? MIN_SHAPE_WIDTH : SHAPE_HEIGHT,\n shapeTruncates: false,\n name: text.split('\\n')[0]?.trim() || node.id\n },\n style.color ? { text, fills: [solid(style.color)] } : { text }\n )\n this.layers.set(node.id, shape.id)\n }\n\n /** Widens a node's shape until its label runs no wider than a line, as Mermaid sizes it. */\n fitWidth(node: FlowNode) {\n const { graph } = this\n const layerId = this.layers.get(node.id)\n const shape = layerId ? graph.getNode(layerId) : undefined\n if (!shape) return\n const { round } = figJamShape(node.shape)\n const width = shapeWithTextWidthFor(\n graph,\n shape,\n { min: MIN_SHAPE_WIDTH, max: MAX_SHAPE_WIDTH, lineWidth: LABEL_LINE_WIDTH },\n (candidate) => (round ? candidate : SHAPE_HEIGHT)\n )\n const height = round ? width : SHAPE_HEIGHT\n graph.updateNode(shape.id, { width, height, shapeUserHeight: height })\n }\n\n /** A connector for each drawn edge, its ends free until the layout places them. */\n connector(edge: FlowEdge) {\n if (edge.stroke === 'invisible') return\n const { graph } = this\n const style = readStyle(edge.styles)\n const connector = createConnector(graph, this.parentId, {\n start: freeEndpoint(0, 0),\n end: freeEndpoint(0, 0),\n lineType: 'ELBOWED',\n startCap: CAPS[edge.startArrow],\n endCap: CAPS[edge.endArrow],\n text: edge.label ? labelText(edge.label) : ''\n })\n const parts = connectorSublayers(graph, connector)\n const stroke = parts?.line.strokes.at(0)\n if (parts && stroke) {\n const weight = edge.stroke === 'thick' ? stroke.weight * THICK : stroke.weight\n const line = styledStroke(\n {\n ...stroke,\n weight,\n dashPattern: edge.stroke === 'dotted' ? [weight * 2, weight * 2] : []\n },\n style\n )\n graph.updateNode(parts.line.id, {\n strokes: style.stroke === null ? [] : [line],\n strokeWeight: line.weight,\n dashPattern: line.dashPattern ?? []\n })\n if (style.color) graph.updateNode(parts.label.id, { fills: [solid(style.color)] })\n }\n this.connectors.set(edge.id, connector.id)\n }\n}\n\n/** What a flowchart became. */\nexport interface FlowchartLayers {\n /** The layers added to the parent, in order. */\n ids: string[]\n /** The layer each node and subgraph became, by its Mermaid id. */\n layers: Map<string, string>\n /** The connector each drawn edge became, by its Mermaid id. */\n connectors: Map<string, string>\n}\n\n/**\n * Adds a flowchart to `parentId` as FigJam layers, where `placement` puts it: each node a\n * shape with text sized to its label, each subgraph a section, and each edge an elbowed connector\n * joined to the layers it links, all laid out by ELK along the chart's direction, its text\n * measured in the fonts it is drawn in.\n */\nexport async function addFlowchart(\n graph: SceneGraph,\n parentId: string,\n chart: Flowchart,\n placement: ArrangePlacement = { topLeft: { x: 0, y: 0 } }\n): Promise<FlowchartLayers> {\n const before = new Set(graph.getNode(parentId)?.childIds)\n const builder = new FlowchartBuilder(graph, parentId, chart)\n const addedSoFar = () => (graph.getNode(parentId)?.childIds ?? []).filter((id) => !before.has(id))\n // Known before the first wait, so a layer someone else adds meanwhile is never taken for ours.\n let created: string[] | null = null\n try {\n builder.sections()\n for (const node of chart.nodes) builder.shape(node)\n for (const edge of chart.edges) builder.connector(edge)\n const added = addedSoFar()\n created = added\n // Shapes grow to their labels, and connector labels take their size, before the layout reads\n // them, measured in the fonts they are drawn in.\n await resolveFontReadiness(graph, added)\n for (const node of chart.nodes) builder.fitWidth(node)\n layoutAuthoredNodes(graph, added)\n const enclosing = enclosingSubgraphs(chart)\n const size = (id: string) => {\n const layer = builder.layers.get(id)\n const node = layer ? graph.getNode(layer) : undefined\n return { width: node?.width ?? MIN_SHAPE_WIDTH, height: node?.height ?? SHAPE_HEIGHT }\n }\n const labelSize = (edgeId: string) => {\n const connectorId = builder.connectors.get(edgeId)\n return (connectorId && connectorLabelSize(graph, connectorId)) || undefined\n }\n const input: ArrangeInput = {\n layout: 'flow',\n direction: chart.direction,\n boxes: chart.nodes.map((node) => ({\n id: node.id,\n ...size(node.id),\n group: enclosing.get(node.id)\n })),\n groups: chart.subgraphs.map((subgraph) => ({\n id: subgraph.id,\n group: enclosing.get(subgraph.id)\n })),\n edges: chart.edges.map((edge) => ({\n id: edge.id,\n from: edge.from,\n to: edge.to,\n label: labelSize(edge.id)\n }))\n }\n const arrangement = await arrangeBoxes(input)\n applyArrangement(\n graph,\n input,\n arrangement,\n { boxes: builder.layers, connectors: builder.connectors },\n placement\n )\n return { ids: added, layers: builder.layers, connectors: builder.connectors }\n } catch (error) {\n // A flowchart that fails to lay out leaves nothing half-built behind.\n for (const id of (created ?? addedSoFar()).toReversed()) graph.deleteNode(id)\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;;AAEzB,MAAM,eAAe;;AAGrB,MAAM,QAAQ;;AAGd,MAAM,OAAyC;CAC7C,MAAM;CACN,OAAO;CACP,QAAQ;CAER,OAAO;AACT;AAEA,SAAS,MAAM,OAAoB;CACjC,OAAO;EAAE,MAAM;EAAS,OAAO,EAAE,GAAG,MAAM;EAAG,SAAS;EAAG,SAAS;CAAK;AACzE;;AAGA,SAAS,UAAU,OAA0B;CAC3C,IAAI,MAAM,WAAW,QAAQ,OAAO,MAAM;CAC1C,OAAO,MAAM,KAAK,QAAQ,qBAAqB,IAAI,CAAC,CAAC,QAAQ,kBAAkB,IAAI;AACrF;AAEA,SAAS,YAAY,OAA2B,OAAsC;CACpF,IAAI,MAAM,SAAS,KAAA,GAAW,OAAO,MAAM;CAC3C,OAAO,MAAM,SAAS,OAAO,CAAC,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC;AACtD;;AAGA,SAAS,aAAa,MAAc,OAA0B;CAC5D,MAAM,SAAiB;EAAE,GAAG;EAAM,OAAO,EAAE,GAAG,KAAK,MAAM;EAAG,OAAO;C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;IAAiB,QAAQ,MAAM,UAAU;GAAa;EACvF;EACA,MAAM,aAAa,WAAmB;GACpC,MAAM,cAAc,QAAQ,WAAW,IAAI,MAAM;GACjD,OAAQ,eAAe,mBAAmB,OAAO,WAAW,KAAM,KAAA;EACpE;EACA,MAAM,QAAsB;GAC1B,QAAQ;GACR,WAAW,MAAM;GACjB,OAAO,MAAM,MAAM,KAAK,UAAU;IAChC,IAAI,KAAK;IACT,GAAG,KAAK,KAAK,EAAE;IACf,OAAO,UAAU,IAAI,KAAK,EAAE;GAC9B,EAAE;GACF,QAAQ,MAAM,UAAU,KAAK,cAAc;IACzC,IAAI,SAAS;IACb,OAAO,UAAU,IAAI,SAAS,EAAE;GAClC,EAAE;GACF,OAAO,MAAM,MAAM,KAAK,UAAU;IAChC,IAAI,KAAK;IACT,MAAM,KAAK;IACX,IAAI,KAAK;IACT,OAAO,UAAU,KAAK,EAAE;GAC1B,EAAE;EACJ;EACA,MAAM,cAAc,MAAM,aAAa,KAAK;EAC5C,iBACE,OACA,OACA,aACA;GAAE,OAAO,QAAQ;GAAQ,YAAY,QAAQ;EAAW,GACxD,SACF;EACA,OAAO;GAAE,KAAK;GAAO,QAAQ,QAAQ;GAAQ,YAAY,QAAQ;EAAW;CAC9E,SAAS,OAAO;EAEd,KAAK,MAAM,OAAO,WAAW,WAAW,EAAA,CAAG,WAAW,GAAG,MAAM,WAAW,EAAE;EAC5E,MAAM;CACR;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { parseCSSNumber } from "@pairdraw/scene-graph/css";
|
|
2
1
|
import { tryParseColor } from "@pairdraw/scene-graph/color";
|
|
2
|
+
import { parseCSSNumber } from "@pairdraw/scene-graph/css";
|
|
3
3
|
//#region src/io/formats/mermaid/styles.ts
|
|
4
4
|
function color(value) {
|
|
5
5
|
if (value === "none" || value === "transparent") return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"export.d.ts","names":[],"sources":["../../../../src/io/formats/pdf/export.ts"],"mappings":";;;;;;UAiBiB;EACf;;EAEA,iBAAiB;;EAEjB,aAAa;;EAEb,eAAe;;UAGA;EACf,MAAM;;EAEN,OAAO;IAAQ;IAAgB;IAAe;;;EAE9C,QAAQ;;;;;
|
|
1
|
+
{"version":3,"file":"export.d.ts","names":[],"sources":["../../../../src/io/formats/pdf/export.ts"],"mappings":";;;;;;UAiBiB;EACf;;EAEA,iBAAiB;;EAEjB,aAAa;;EAEb,eAAe;;UAGA;EACf,MAAM;;EAEN,OAAO;IAAQ;IAAgB;IAAe;;;EAE9C,QAAQ;;;;;iBAyCM,yBACd,OAAO,YACP,gBAAgB,eAChB,UAAS,mBACR,QAAQ"}
|
|
@@ -6,6 +6,7 @@ import { cutFontInstances, embeddedFontAlias, planFontEmbedding, registerEmbedde
|
|
|
6
6
|
function preparePage(graph, spec, svgOptions, parse) {
|
|
7
7
|
const svg = renderNodesToSVG(graph, spec.pageId, spec.nodeIds, {
|
|
8
8
|
xmlDeclaration: false,
|
|
9
|
+
documentColorSpace: graph.documentColorSpace,
|
|
9
10
|
...svgOptions
|
|
10
11
|
});
|
|
11
12
|
if (!svg) return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"export.js","names":[],"sources":["../../../../src/io/formats/pdf/export.ts"],"sourcesContent":["import type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { computeContentBounds } from '#core/io/formats/raster'\nimport { renderNodesToSVG, type SVGExportOptions, type SVGTextLayout } from '#core/io/formats/svg'\n\nimport { loadSVG2PDF, withPDFDOM, type SVGPageParser } from './dom'\nimport {\n cutFontInstances,\n embeddedFontAlias,\n planFontEmbedding,\n registerEmbeddedFonts,\n type PDFFallbackFontFile,\n type PDFFontFace,\n type PDFFontReport\n} from './fonts'\nimport type { PDFPageSpec } from './plan'\n\nexport interface PDFExportOptions {\n title?: string\n /** The faces the text uses, to embed their files; without them text uses standard PDF fonts. */\n fonts?: readonly PDFFontFace[]\n /** Line breaks of text nodes as the editor laid them out, so paragraphs stay wrapped. */\n textLayout?: SVGTextLayout\n /** The files of fallback faces the text layout draws characters in, to embed them too. */\n fallbackFile?: PDFFallbackFontFile\n}\n\nexport interface PDFExportResult {\n data: Uint8Array\n /** The pages written, in order. Pages with nothing visible are skipped. */\n pages: Array<{ label?: string; width: number; height: number }>\n /** Embedded and fallback faces, when `fonts` was given. */\n fonts?: PDFFontReport\n}\n\ninterface PreparedPage {\n spec: PDFPageSpec\n svgElement: Element\n width: number\n height: number\n}\n\ntype PageSVGOptions = Pick<SVGExportOptions, 'textLayout' | 'fontAlias'>\n\nfunction preparePage(\n graph: SceneGraph,\n spec: PDFPageSpec,\n svgOptions: PageSVGOptions,\n parse: SVGPageParser\n): PreparedPage | null {\n const svg = renderNodesToSVG(graph, spec.pageId, spec.nodeIds, {\n xmlDeclaration: false,\n ...svgOptions\n })\n if (!svg) return null\n\n const bounds = computeContentBounds(graph, spec.nodeIds)\n if (!bounds) return null\n\n const width = bounds.maxX - bounds.minX\n const height = bounds.maxY - bounds.minY\n if (width <= 0 || height <= 0) return null\n\n const svgElement = parse(svg)\n return svgElement ? { spec, svgElement, width, height } : null\n}\n\nconst orientationOf = (page: PreparedPage) => (page.width > page.height ? 'landscape' : 'portrait')\n\n/**\n * A PDF with one page per spec, each sized to its content. Null when no page has anything visible.\n */\nexport function renderPagesToPDFDetailed(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[],\n options: PDFExportOptions = {}\n): Promise<PDFExportResult | null> {\n return withPDFDOM((parse) => renderPages(graph, specs, options, parse))\n}\n\nasync function renderPages(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[],\n options: PDFExportOptions,\n parse: SVGPageParser\n): Promise<PDFExportResult | null> {\n const embedding = options.fonts ? planFontEmbedding(options.fonts, options.fallbackFile) : null\n const svgOptions: PageSVGOptions = {\n textLayout: options.textLayout,\n fontAlias: embedding ? embeddedFontAlias(embedding) : undefined\n }\n const preparePages = () =>\n specs\n .map((spec) => preparePage(graph, spec, svgOptions, parse))\n .filter((page): page is PreparedPage => page !== null)\n let prepared = preparePages()\n if (prepared.length === 0) return null\n const first = prepared[0]\n\n const { jsPDF } = await import('jspdf')\n const svg2pdf = await loadSVG2PDF()\n\n const doc = new jsPDF({\n orientation: orientationOf(first),\n unit: 'pt',\n format: [first.width, first.height],\n compress: true\n })\n\n if (options.title) {\n doc.setProperties({ title: options.title })\n }\n\n // The pages name the variable instances they draw, which are cut now. jsPDF reads a font file\n // when it is registered, so a face it refuses is only known then. Either way, the pages are\n // written again without the names of faces that are not embedded.\n if (embedding) {\n const cut = await cutFontInstances(embedding)\n if (!registerEmbeddedFonts(doc, embedding) || !cut) prepared = preparePages()\n }\n\n for (const [index, page] of prepared.entries()) {\n if (index > 0) doc.addPage([page.width, page.height], orientationOf(page))\n await svg2pdf(page.svgElement, doc, { x: 0, y: 0, width: page.width, height: page.height })\n }\n\n return {\n data: new Uint8Array(doc.output('arraybuffer')),\n pages: prepared.map((page) => ({\n label: page.spec.label,\n width: page.width,\n height: page.height\n })),\n ...(embedding ? { fonts: embedding.report } : {})\n }\n}\n"],"mappings":";;;;;AA4CA,SAAS,YACP,OACA,MACA,YACA,OACqB;CACrB,MAAM,MAAM,iBAAiB,OAAO,KAAK,QAAQ,KAAK,SAAS;EAC7D,gBAAgB;EAChB,GAAG;CACL,CAAC;CACD,IAAI,CAAC,KAAK,OAAO;CAEjB,MAAM,SAAS,qBAAqB,OAAO,KAAK,OAAO;CACvD,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,QAAQ,OAAO,OAAO,OAAO;CACnC,MAAM,SAAS,OAAO,OAAO,OAAO;CACpC,IAAI,SAAS,KAAK,UAAU,GAAG,OAAO;CAEtC,MAAM,aAAa,MAAM,GAAG;CAC5B,OAAO,aAAa;EAAE;EAAM;EAAY;EAAO;CAAO,IAAI;AAC5D;AAEA,MAAM,iBAAiB,SAAwB,KAAK,QAAQ,KAAK,SAAS,cAAc;;;;AAKxF,SAAgB,yBACd,OACA,OACA,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K,UAAU;GAC7B,OAAO,KAAK,KAAK;GACjB,OAAO,KAAK;GACZ,QAAQ,KAAK;EACf,EAAE;EACF,GAAI,YAAY,EAAE,OAAO,UAAU,OAAO,IAAI,CAAC;CACjD;AACF"}
|
|
1
|
+
{"version":3,"file":"export.js","names":[],"sources":["../../../../src/io/formats/pdf/export.ts"],"sourcesContent":["import type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { computeContentBounds } from '#core/io/formats/raster'\nimport { renderNodesToSVG, type SVGExportOptions, type SVGTextLayout } from '#core/io/formats/svg'\n\nimport { loadSVG2PDF, withPDFDOM, type SVGPageParser } from './dom'\nimport {\n cutFontInstances,\n embeddedFontAlias,\n planFontEmbedding,\n registerEmbeddedFonts,\n type PDFFallbackFontFile,\n type PDFFontFace,\n type PDFFontReport\n} from './fonts'\nimport type { PDFPageSpec } from './plan'\n\nexport interface PDFExportOptions {\n title?: string\n /** The faces the text uses, to embed their files; without them text uses standard PDF fonts. */\n fonts?: readonly PDFFontFace[]\n /** Line breaks of text nodes as the editor laid them out, so paragraphs stay wrapped. */\n textLayout?: SVGTextLayout\n /** The files of fallback faces the text layout draws characters in, to embed them too. */\n fallbackFile?: PDFFallbackFontFile\n}\n\nexport interface PDFExportResult {\n data: Uint8Array\n /** The pages written, in order. Pages with nothing visible are skipped. */\n pages: Array<{ label?: string; width: number; height: number }>\n /** Embedded and fallback faces, when `fonts` was given. */\n fonts?: PDFFontReport\n}\n\ninterface PreparedPage {\n spec: PDFPageSpec\n svgElement: Element\n width: number\n height: number\n}\n\ntype PageSVGOptions = Pick<SVGExportOptions, 'textLayout' | 'fontAlias'>\n\nfunction preparePage(\n graph: SceneGraph,\n spec: PDFPageSpec,\n svgOptions: PageSVGOptions,\n parse: SVGPageParser\n): PreparedPage | null {\n const svg = renderNodesToSVG(graph, spec.pageId, spec.nodeIds, {\n xmlDeclaration: false,\n documentColorSpace: graph.documentColorSpace,\n ...svgOptions\n })\n if (!svg) return null\n\n const bounds = computeContentBounds(graph, spec.nodeIds)\n if (!bounds) return null\n\n const width = bounds.maxX - bounds.minX\n const height = bounds.maxY - bounds.minY\n if (width <= 0 || height <= 0) return null\n\n const svgElement = parse(svg)\n return svgElement ? { spec, svgElement, width, height } : null\n}\n\nconst orientationOf = (page: PreparedPage) => (page.width > page.height ? 'landscape' : 'portrait')\n\n/**\n * A PDF with one page per spec, each sized to its content. Null when no page has anything visible.\n */\nexport function renderPagesToPDFDetailed(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[],\n options: PDFExportOptions = {}\n): Promise<PDFExportResult | null> {\n return withPDFDOM((parse) => renderPages(graph, specs, options, parse))\n}\n\nasync function renderPages(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[],\n options: PDFExportOptions,\n parse: SVGPageParser\n): Promise<PDFExportResult | null> {\n const embedding = options.fonts ? planFontEmbedding(options.fonts, options.fallbackFile) : null\n const svgOptions: PageSVGOptions = {\n textLayout: options.textLayout,\n fontAlias: embedding ? embeddedFontAlias(embedding) : undefined\n }\n const preparePages = () =>\n specs\n .map((spec) => preparePage(graph, spec, svgOptions, parse))\n .filter((page): page is PreparedPage => page !== null)\n let prepared = preparePages()\n if (prepared.length === 0) return null\n const first = prepared[0]\n\n const { jsPDF } = await import('jspdf')\n const svg2pdf = await loadSVG2PDF()\n\n const doc = new jsPDF({\n orientation: orientationOf(first),\n unit: 'pt',\n format: [first.width, first.height],\n compress: true\n })\n\n if (options.title) {\n doc.setProperties({ title: options.title })\n }\n\n // The pages name the variable instances they draw, which are cut now. jsPDF reads a font file\n // when it is registered, so a face it refuses is only known then. Either way, the pages are\n // written again without the names of faces that are not embedded.\n if (embedding) {\n const cut = await cutFontInstances(embedding)\n if (!registerEmbeddedFonts(doc, embedding) || !cut) prepared = preparePages()\n }\n\n for (const [index, page] of prepared.entries()) {\n if (index > 0) doc.addPage([page.width, page.height], orientationOf(page))\n await svg2pdf(page.svgElement, doc, { x: 0, y: 0, width: page.width, height: page.height })\n }\n\n return {\n data: new Uint8Array(doc.output('arraybuffer')),\n pages: prepared.map((page) => ({\n label: page.spec.label,\n width: page.width,\n height: page.height\n })),\n ...(embedding ? { fonts: embedding.report } : {})\n }\n}\n"],"mappings":";;;;;AA4CA,SAAS,YACP,OACA,MACA,YACA,OACqB;CACrB,MAAM,MAAM,iBAAiB,OAAO,KAAK,QAAQ,KAAK,SAAS;EAC7D,gBAAgB;EAChB,oBAAoB,MAAM;EAC1B,GAAG;CACL,CAAC;CACD,IAAI,CAAC,KAAK,OAAO;CAEjB,MAAM,SAAS,qBAAqB,OAAO,KAAK,OAAO;CACvD,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,QAAQ,OAAO,OAAO,OAAO;CACnC,MAAM,SAAS,OAAO,OAAO,OAAO;CACpC,IAAI,SAAS,KAAK,UAAU,GAAG,OAAO;CAEtC,MAAM,aAAa,MAAM,GAAG;CAC5B,OAAO,aAAa;EAAE;EAAM;EAAY;EAAO;CAAO,IAAI;AAC5D;AAEA,MAAM,iBAAiB,SAAwB,KAAK,QAAQ,KAAK,SAAS,cAAc;;;;AAKxF,SAAgB,yBACd,OACA,OACA,UAA4B,CAAC,GACI;CACjC,OAAO,YAAY,UAAU,YAAY,OAAO,OAAO,SAAS,KAAK,CAAC;AACxE;AAEA,eAAe,YACb,OACA,OACA,SACA,OACiC;CACjC,MAAM,YAAY,QAAQ,QAAQ,kBAAkB,QAAQ,OAAO,QAAQ,YAAY,IAAI;CAC3F,MAAM,aAA6B;EACjC,YAAY,QAAQ;EACpB,WAAW,YAAY,kBAAkB,SAAS,IAAI,KAAA;CACxD;CACA,MAAM,qBACJ,MACG,KAAK,SAAS,YAAY,OAAO,MAAM,YAAY,KAAK,CAAC,CAAC,CAC1D,QAAQ,SAA+B,SAAS,IAAI;CACzD,IAAI,WAAW,aAAa;CAC5B,IAAI,SAAS,WAAW,GAAG,OAAO;CAClC,MAAM,QAAQ,SAAS;CAEvB,MAAM,EAAE,UAAU,MAAM,OAAO;CAC/B,MAAM,UAAU,MAAM,YAAY;CAElC,MAAM,MAAM,IAAI,MAAM;EACpB,aAAa,cAAc,KAAK;EAChC,MAAM;EACN,QAAQ,CAAC,MAAM,OAAO,MAAM,MAAM;EAClC,UAAU;CACZ,CAAC;CAED,IAAI,QAAQ,OACV,IAAI,cAAc,EAAE,OAAO,QAAQ,MAAM,CAAC;CAM5C,IAAI,WAAW;EACb,MAAM,MAAM,MAAM,iBAAiB,SAAS;EAC5C,IAAI,CAAC,sBAAsB,KAAK,SAAS,KAAK,CAAC,KAAK,WAAW,aAAa;CAC9E;CAEA,KAAK,MAAM,CAAC,OAAO,SAAS,SAAS,QAAQ,GAAG;EAC9C,IAAI,QAAQ,GAAG,IAAI,QAAQ,CAAC,KAAK,OAAO,KAAK,MAAM,GAAG,cAAc,IAAI,CAAC;EACzE,MAAM,QAAQ,KAAK,YAAY,KAAK;GAAE,GAAG;GAAG,GAAG;GAAG,OAAO,KAAK;GAAO,QAAQ,KAAK;EAAO,CAAC;CAC5F;CAEA,OAAO;EACL,MAAM,IAAI,WAAW,IAAI,OAAO,aAAa,CAAC;EAC9C,OAAO,SAAS,KAAK,UAAU;GAC7B,OAAO,KAAK,KAAK;GACjB,OAAO,KAAK;GACZ,QAAQ,KAAK;EACf,EAAE;EACF,GAAI,YAAY,EAAE,OAAO,UAAU,OAAO,IAAI,CAAC;CACjD;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { FontReadiness } from "../../../text/font/readiness.js";
|
|
2
2
|
import { SVGTextLayout } from "../svg/text/lines.js";
|
|
3
3
|
import "../svg/index.js";
|
|
4
4
|
import { PDFFontFace } from "./fonts.js";
|
|
@@ -10,7 +10,7 @@ import { SceneGraph } from "@pairdraw/scene-graph";
|
|
|
10
10
|
* characters remote fonts must cover, and the script and emoji fallbacks. Fonts loaded for some
|
|
11
11
|
* characters only cover the ones jsPDF writes too.
|
|
12
12
|
*/
|
|
13
|
-
declare function preparePDFFonts(graph: SceneGraph, specs: readonly PDFPageSpec[]): Promise<
|
|
13
|
+
declare function preparePDFFonts(graph: SceneGraph, specs: readonly PDFPageSpec[]): Promise<FontReadiness>;
|
|
14
14
|
/**
|
|
15
15
|
* Design pages other than the open one may still be unread, since `.fig` pages load on demand.
|
|
16
16
|
* Reads the pages a `pages` export asks for, or every page, so planning sees their layers.
|
|
@@ -20,9 +20,9 @@ declare function readPDFPages(graph: SceneGraph, pageIds?: readonly string[]): v
|
|
|
20
20
|
* Loads the fonts the text of pages read by {@link readPDFPages} needs and lays them out, since
|
|
21
21
|
* pages other than the open one have no layout yet, so every PDF page is complete.
|
|
22
22
|
*/
|
|
23
|
-
declare function preparePagesForPDF(graph: SceneGraph, specs: readonly PDFPageSpec[]): Promise<
|
|
23
|
+
declare function preparePagesForPDF(graph: SceneGraph, specs: readonly PDFPageSpec[]): Promise<FontReadiness>;
|
|
24
24
|
/** The faces the pages' text uses, with the files the canvas draws them from. */
|
|
25
|
-
declare function pdfFontFaces(status:
|
|
25
|
+
declare function pdfFontFaces(status: FontReadiness): PDFFontFace[];
|
|
26
26
|
/**
|
|
27
27
|
* Runs `render` with the line breaks the canvas gives each text node (same paragraph builder and
|
|
28
28
|
* fonts), so a wrapped paragraph stays wrapped in the PDF. Without CanvasKit, `render` gets no
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare.d.ts","names":[],"sources":["../../../../src/io/formats/pdf/prepare.ts"],"mappings":";;;;;;;;;;;;iBA2BsB,gBACpB,OAAO,YACP,gBAAgB,gBACf,QAAQ;;;;;iBA4BK,aAAa,OAAO,YAAY;;;;;iBAY1B,mBACpB,OAAO,YACP,gBAAgB,gBACf,QAAQ;;iBASK,aAAa,QAAQ,
|
|
1
|
+
{"version":3,"file":"prepare.d.ts","names":[],"sources":["../../../../src/io/formats/pdf/prepare.ts"],"mappings":";;;;;;;;;;;;iBA2BsB,gBACpB,OAAO,YACP,gBAAgB,gBACf,QAAQ;;;;;iBA4BK,aAAa,OAAO,YAAY;;;;;iBAY1B,mBACpB,OAAO,YACP,gBAAgB,gBACf,QAAQ;;iBASK,aAAa,QAAQ,gBAAgB;;;;;;iBAgB/B,kBAAkB,GACtC,SAAS,YAAY,8BAA8B,QAAQ,KAC1D,QAAQ"}
|
|
@@ -6,7 +6,7 @@ import { collectGraphFontRequirements } from "../../../text/requirements/collect
|
|
|
6
6
|
import { fontManager } from "../../../text/font/manager.js";
|
|
7
7
|
import { characterFace } from "../../../canvas/text/placed.js";
|
|
8
8
|
import { withTextShaper } from "../../../canvas/text/shape.js";
|
|
9
|
-
import {
|
|
9
|
+
import { resolveFontReadiness } from "../../../text/prepare.js";
|
|
10
10
|
import { populateFigPage } from "../../../kiwi/fig/session/document-state.js";
|
|
11
11
|
import { computeAllLayouts } from "../../../layout.js";
|
|
12
12
|
import { uniq } from "es-toolkit";
|
|
@@ -18,7 +18,7 @@ import { uniq } from "es-toolkit";
|
|
|
18
18
|
*/
|
|
19
19
|
async function preparePDFFonts(graph, specs) {
|
|
20
20
|
const nodeIds = specs.flatMap((spec) => spec.nodeIds);
|
|
21
|
-
return
|
|
21
|
+
return resolveFontReadiness(graph, nodeIds, await pdfWrittenCharacters(graph, nodeIds));
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
24
|
* Characters jsPDF writes for the text besides its own: it writes Arabic letters as their
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare.js","names":[],"sources":["../../../../src/io/formats/pdf/prepare.ts"],"sourcesContent":["import { uniq } from 'es-toolkit'\n\nimport type { ShapedTextGlyph } from '@pairdraw/fig/node-change'\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\nimport { characterFace } from '#core/canvas/text/placed'\nimport { withTextShaper } from '#core/canvas/text/shape'\nimport { getCanvasKit } from '#core/canvaskit'\nimport { populateFigPage } from '#core/io/formats/fig'\nimport type { SVGCharacterEdges, SVGFallbackFace, SVGTextLayout } from '#core/io/formats/svg'\nimport { computeAllLayouts } from '#core/layout'\nimport { shownText } from '#core/text/case'\nimport { EMOJI_METRICS_FAMILY } from '#core/text/emoji'\nimport { ARABIC_CHARACTER } from '#core/text/fallbacks'\nimport { fontManager } from '#core/text/font/manager'\nimport type {
|
|
1
|
+
{"version":3,"file":"prepare.js","names":[],"sources":["../../../../src/io/formats/pdf/prepare.ts"],"sourcesContent":["import { uniq } from 'es-toolkit'\n\nimport type { ShapedTextGlyph } from '@pairdraw/fig/node-change'\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\nimport { characterFace } from '#core/canvas/text/placed'\nimport { withTextShaper } from '#core/canvas/text/shape'\nimport { getCanvasKit } from '#core/canvaskit'\nimport { populateFigPage } from '#core/io/formats/fig'\nimport type { SVGCharacterEdges, SVGFallbackFace, SVGTextLayout } from '#core/io/formats/svg'\nimport { computeAllLayouts } from '#core/layout'\nimport { shownText } from '#core/text/case'\nimport { EMOJI_METRICS_FAMILY } from '#core/text/emoji'\nimport { ARABIC_CHARACTER } from '#core/text/fallbacks'\nimport { fontManager } from '#core/text/font/manager'\nimport type { FontReadiness } from '#core/text/font/readiness'\nimport { resolveFontReadiness } from '#core/text/prepare'\nimport { collectGraphFontRequirements } from '#core/text/requirements/collect'\n\nimport type { PDFFontFace } from './fonts'\nimport type { PDFPageSpec } from './plan'\n\n/**\n * Loads every font the text of these pages draws with, as the canvas does: the faces, the\n * characters remote fonts must cover, and the script and emoji fallbacks. Fonts loaded for some\n * characters only cover the ones jsPDF writes too.\n */\nexport async function preparePDFFonts(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[]\n): Promise<FontReadiness> {\n const nodeIds = specs.flatMap((spec) => spec.nodeIds)\n return resolveFontReadiness(graph, nodeIds, await pdfWrittenCharacters(graph, nodeIds))\n}\n\n/**\n * Characters jsPDF writes for the text besides its own: it writes Arabic letters as their\n * presentation forms, picked by the letters around them, so the embedded fonts must map those.\n */\nasync function pdfWrittenCharacters(\n graph: SceneGraph,\n nodeIds: readonly string[]\n): Promise<string> {\n const texts = collectGraphFontRequirements(graph, nodeIds)\n .nodes.filter((node) => node.type === 'TEXT')\n .map(shownText)\n .filter((text) => ARABIC_CHARACTER.test(text))\n if (texts.length === 0) return ''\n const { jsPDF } = await import('jspdf')\n // jsPDF adds its Arabic parser to each document it makes, as the one it writes the text with.\n const writer = new jsPDF()\n return uniq(texts.flatMap((text) => Array.from(writer.processArabic(text)))).join('')\n}\n\n/**\n * Design pages other than the open one may still be unread, since `.fig` pages load on demand.\n * Reads the pages a `pages` export asks for, or every page, so planning sees their layers.\n */\nexport function readPDFPages(graph: SceneGraph, pageIds?: readonly string[]): void {\n // No ids, or an empty list, exports every page, as planPDFPages reads them.\n const ids = pageIds?.length ? pageIds : graph.getPages().map((page) => page.id)\n for (const pageId of ids) {\n populateFigPage(graph, pageId)\n }\n}\n\n/**\n * Loads the fonts the text of pages read by {@link readPDFPages} needs and lays them out, since\n * pages other than the open one have no layout yet, so every PDF page is complete.\n */\nexport async function preparePagesForPDF(\n graph: SceneGraph,\n specs: readonly PDFPageSpec[]\n): Promise<FontReadiness> {\n const status = await preparePDFFonts(graph, specs)\n graph.applyDerivedLayoutDuring(() => {\n for (const spec of specs) computeAllLayouts(graph, spec.pageId)\n })\n return status\n}\n\n/** The faces the pages' text uses, with the files the canvas draws them from. */\nexport function pdfFontFaces(status: FontReadiness): PDFFontFace[] {\n return status.faces.map((face) => {\n const data =\n face.status === 'available' ? fontManager.loadedData(face.family, face.style) : null\n if (data) return { family: face.family, style: face.style, data }\n const missing =\n face.reason === 'unsupported-format' ? 'unsupported font format' : 'font file not available'\n return { family: face.family, style: face.style, data, missing }\n })\n}\n\n/**\n * Runs `render` with the line breaks the canvas gives each text node (same paragraph builder and\n * fonts), so a wrapped paragraph stays wrapped in the PDF. Without CanvasKit, `render` gets no\n * layout and only explicit newlines start a new line.\n */\nexport async function withPDFTextLayout<T>(\n render: (textLayout: SVGTextLayout | undefined) => Promise<T>\n): Promise<T> {\n const ck = await getCanvasKit().catch(() => null)\n if (!ck) return render(undefined)\n return withTextShaper(ck, (shape) =>\n render((node) => {\n // Shaped lines are cut by character index, which the text's case must keep.\n if (shownText(node).length !== node.text.length) return null\n const shaped = shape(node)\n if (!shaped?.baselines.length) return null\n const characters = characterEdges(shaped.glyphs)\n const fallbacks = fallbackFaces(node, characters)\n return shaped.baselines.map((line) => ({\n start: line.firstCharacter,\n end: line.endCharacter,\n x: line.position.x,\n y: line.position.y,\n width: line.width,\n characters,\n fallbacks\n }))\n })\n )\n}\n\n/**\n * The face of each drawn character the canvas draws from another file than its text's own: a\n * fallback font, such as for Chinese in Inter, or a shard of a font split by unicode-range. Emoji\n * keep their own family: the face the canvas lays them out with has no glyphs to embed.\n */\nfunction fallbackFaces(\n node: SceneNode,\n characters: ReadonlyMap<number, SVGCharacterEdges>\n): Map<number, SVGFallbackFace> {\n const text = shownText(node)\n const fallbacks = new Map<number, SVGFallbackFace>()\n for (const index of characters.keys()) {\n const face = characterFace(node, text, index)\n if (!face || (!face.fallback && face.file === 0) || face.family === EMOJI_METRICS_FAMILY)\n continue\n fallbacks.set(index, { family: face.family, style: face.style, file: face.file })\n }\n return fallbacks\n}\n\n/** The left and right edges of the glyphs each character is drawn with. */\nfunction characterEdges(glyphs: readonly ShapedTextGlyph[]): Map<number, SVGCharacterEdges> {\n const edges = new Map<number, SVGCharacterEdges>()\n for (const glyph of glyphs) {\n if (glyph.firstCharacter === undefined) continue\n const left = glyph.x\n const right = glyph.x + glyph.advance\n const known = edges.get(glyph.firstCharacter)\n edges.set(\n glyph.firstCharacter,\n known\n ? { left: Math.min(known.left, left), right: Math.max(known.right, right) }\n : { left, right }\n )\n }\n return edges\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,eAAsB,gBACpB,OACA,OACwB;CACxB,MAAM,UAAU,MAAM,SAAS,SAAS,KAAK,OAAO;CACpD,OAAO,qBAAqB,OAAO,SAAS,MAAM,qBAAqB,OAAO,OAAO,CAAC;AACxF;;;;;AAMA,eAAe,qBACb,OACA,SAC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OAAO;AACT"}
|
|
@@ -151,12 +151,14 @@ const penFormat = {
|
|
|
151
151
|
};
|
|
152
152
|
},
|
|
153
153
|
async writeDocument(graph) {
|
|
154
|
+
const warnings = [];
|
|
154
155
|
return {
|
|
155
156
|
format: "pen",
|
|
156
157
|
mimeType: "application/json",
|
|
157
158
|
extension: "pen",
|
|
158
|
-
data: writePenDocument(graph),
|
|
159
|
-
encoding: "utf8"
|
|
159
|
+
data: writePenDocument(graph, { warnings }),
|
|
160
|
+
encoding: "utf8",
|
|
161
|
+
...warnings.length > 0 ? { warnings } : {}
|
|
160
162
|
};
|
|
161
163
|
}
|
|
162
164
|
};
|