@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":"export.js","names":[],"sources":["../../../../../src/io/formats/svg/text/export.ts"],"sourcesContent":["import type { CharacterStyleOverride, SceneNode } from '@pairdraw/scene-graph'\nimport { parseFontStyle } from '@pairdraw/scene-graph/font-style'\nimport { textLengthPixels } from '@pairdraw/scene-graph/text'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport { drawnFontVariations } from '#core/canvas/text/font-families'\nimport {\n formatColor,\n formatSolidColor,\n type SVGExportContext,\n type SVGFontAlias,\n type SVGFontRequest\n} from '#core/io/formats/svg/defs'\nimport { svg, type SVGNode } from '#core/io/formats/svg/node'\nimport { round } from '#core/io/formats/svg/paths'\nimport {\n explicitNewlineLines,\n laidOutTextSpans,\n textStyleSpans,\n type SpanAttrs,\n type SVGFallbackFace\n} from '#core/io/formats/svg/text/lines'\nimport { shownText } from '#core/text/case'\nimport { textFontFace } from '#core/text/requirements/collect'\n\nfunction styleOverrideToTspanAttrs(\n style: CharacterStyleOverride,\n colorSpace: 'srgb' | 'display-p3',\n parentFillOpacity: number | undefined,\n node: Pick<SceneNode, 'fontSize' | 'letterSpacing'>\n): Record<string, string | number | undefined> {\n const attrs: Record<string, string | number | undefined> = {}\n if (style.fontFamily) attrs['font-family'] = style.fontFamily\n if (style.fontSize) attrs['font-size'] = style.fontSize\n if (style.fontWeight) attrs['font-weight'] = style.fontWeight\n if (style.italic) attrs['font-style'] = 'italic'\n // A run's own spacing is written even at zero, or it would inherit the layer's. A percent the\n // run inherits follows its own font size, so a larger or smaller run writes it again.\n const inherited =\n style.fontSize !== undefined &&\n node.letterSpacing.unit === 'PERCENT' &&\n node.letterSpacing.value !== 0\n ? node.letterSpacing\n : undefined\n const spacing = style.letterSpacing ?? inherited\n if (spacing) {\n attrs['letter-spacing'] = round(textLengthPixels(spacing, style.fontSize ?? node.fontSize))\n }\n if (style.textDecoration === 'UNDERLINE') attrs['text-decoration'] = 'underline'\n if (style.textDecoration === 'STRIKETHROUGH') attrs['text-decoration'] = 'line-through'\n if (style.fills) {\n const visibleFill = style.fills.find((f) => f.visible && f.type === 'SOLID')\n if (visibleFill) {\n // Paragraphs and saved glyphs draw a run at color.a * opacity. Shapes paint opacity alone.\n const alpha = round(visibleFill.color.a * visibleFill.opacity)\n if (colorSpace === 'display-p3') {\n attrs.fill = formatColor({ ...visibleFill.color, a: 1 }, alpha, colorSpace)\n } else {\n attrs.fill = formatColor(visibleFill.color, 1, colorSpace)\n if (alpha < 1) attrs['fill-opacity'] = alpha\n }\n // `fill-opacity` inherits, so an opaque run has to cover a translucent parent.\n if (alpha >= 1 && parentFillOpacity !== undefined) attrs['fill-opacity'] = 1\n }\n }\n return attrs\n}\n\n/**\n * Font attributes naming a face's alias, such as the family a PDF embeds its file under, or else\n * the face itself, so text inside an aliased parent does not inherit the alias.\n */\nfunction aliasedFontAttrs(\n face: SVGFontRequest,\n fontAlias: SVGFontAlias\n): Record<string, string | number> {\n const alias = fontAlias(face)\n if (alias) return { 'font-family': alias, 'font-weight': 'normal', 'font-style': 'normal' }\n return {\n 'font-family': face.family,\n 'font-weight': face.weight,\n 'font-style': face.italic ? 'italic' : 'normal'\n }\n}\n\n/**\n * The font attributes of a span: its face's alias where there is one, otherwise the family of the\n * fallback face that draws it, if any.\n */\nfunction spanFontAttrs(\n node: SceneNode,\n style: CharacterStyleOverride,\n fallback: SVGFallbackFace | undefined,\n fontAlias: SVGFontAlias | undefined\n): Record<string, string | number> {\n if (fontAlias) return aliasedFontAttrs(fontRequest(node, style, fallback), fontAlias)\n return fallback ? { 'font-family': fallback.family } : {}\n}\n\n/**\n * A text layer's stroke, painted on the glyphs themselves. The canvas strokes an outside stroke at\n * twice its weight and clips it to the outside of the glyphs; live text cannot be clipped in SVG,\n * so the same band is painted behind the fill at twice the weight, which hides the inner half. An\n * inside or centred stroke keeps its own weight over the fill.\n */\nfunction textStrokeAttrs(\n node: SceneNode,\n colorSpace: 'srgb' | 'display-p3'\n): Record<string, string | number | undefined> {\n const stroke = node.strokes.find((candidate) => candidate.visible)\n if (!stroke) return {}\n const attrs: Record<string, string | number | undefined> = {\n stroke: formatSolidColor(stroke.color, 1, colorSpace),\n 'stroke-width': round(stroke.weight * (stroke.align === 'OUTSIDE' ? 2 : 1))\n }\n if (stroke.opacity < 1) attrs['stroke-opacity'] = round(stroke.opacity)\n if (stroke.align === 'OUTSIDE') attrs['paint-order'] = 'stroke'\n return attrs\n}\n\n/**\n * The face a run of `node` is drawn in, or the fallback face that draws its characters instead,\n * with the size and axes its instance follows. A fallback is drawn at the axes the run's own font\n * is drawn at, as the paragraph draws every font it falls back to.\n */\nfunction fontRequest(\n node: SceneNode,\n style: CharacterStyleOverride = {},\n fallback?: SVGFallbackFace\n): SVGFontRequest {\n const own: SVGFontRequest = {\n ...textFontFace(node, style),\n fontSize: style.fontSize ?? node.fontSize,\n variations: style.fontVariations ?? node.fontVariations,\n opticalSizeFromFontSize: style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize\n }\n if (!fallback) return own\n return {\n ...own,\n ...fallback,\n ...parseFontStyle(fallback.style),\n variations: drawnFontVariations(own),\n opticalSizeFromFontSize: false\n }\n}\n\nfunction isLogicalTextEnd(node: SceneNode, direction: 'LTR' | 'RTL'): boolean {\n return (\n (direction === 'LTR' && node.textAlignHorizontal === 'RIGHT') ||\n (direction === 'RTL' && node.textAlignHorizontal === 'LEFT')\n )\n}\n\nfunction textAnchorForNode(\n node: SceneNode,\n direction: 'LTR' | 'RTL'\n): 'middle' | 'end' | undefined {\n if (node.textAlignHorizontal === 'CENTER') return 'middle'\n if (isLogicalTextEnd(node, direction)) return 'end'\n return undefined\n}\n\nfunction textXForNode(node: SceneNode, direction: 'LTR' | 'RTL'): number {\n if (node.textAlignHorizontal === 'CENTER') return round(node.width / 2)\n if (isLogicalTextEnd(node, direction)) return round(node.width)\n return 0\n}\n\n/** Text with no measured layout: explicit newlines on their own baselines, otherwise one line. */\nfunction renderUnmeasuredText(\n node: SceneNode,\n attrs: Record<string, string | number | undefined>,\n spanAttrs: SpanAttrs,\n direction: 'LTR' | 'RTL'\n): SVGNode {\n const x = textXForNode(node, direction)\n const y = node.fontSize || 14\n // No measured wraps: an explicit newline still starts a line, on the same anchor as one line.\n const newlineLines = explicitNewlineLines(node, x, y)\n if (newlineLines) {\n return svg(\n 'text',\n { ...attrs, 'xml:space': 'preserve' },\n ...laidOutTextSpans(node, newlineLines, spanAttrs)\n )\n }\n\n if (node.styleRuns.length > 0) {\n return svg(\n 'text',\n { x, y, ...attrs, 'xml:space': 'preserve' },\n ...textStyleSpans(node, spanAttrs)\n )\n }\n\n return svg('text', { x, y, ...attrs }, shownText(node))\n}\n\nexport function renderTextNode(\n node: SceneNode,\n fillAttr: string | null,\n ctx: SVGExportContext,\n fillOpacity?: number\n): SVGNode {\n const { colorSpace, textLayout, fontAlias } = ctx\n const direction = resolveNodeTextDirection(node)\n const lines = textLayout ? textLayout(node) : null\n const laidOut = lines && lines.length > 0 ? lines : null\n\n let textDecoration: 'underline' | 'line-through' | undefined\n if (node.textDecoration === 'UNDERLINE') textDecoration = 'underline'\n else if (node.textDecoration === 'STRIKETHROUGH') textDecoration = 'line-through'\n const letterSpacing = textLengthPixels(node.letterSpacing, node.fontSize)\n\n const attrs: Record<string, string | number | undefined> = {\n 'font-family': node.fontFamily || undefined,\n 'font-size': node.fontSize || undefined,\n 'font-weight': node.fontWeight !== 400 ? node.fontWeight : undefined,\n 'font-style': node.italic ? 'italic' : undefined,\n fill: fillAttr ?? undefined,\n 'fill-opacity': fillOpacity,\n // Laid-out spans each start at their own left edge, so they take no direction or anchor.\n direction: direction === 'RTL' && !laidOut ? 'rtl' : undefined,\n 'text-anchor': laidOut ? undefined : textAnchorForNode(node, direction),\n 'text-decoration': textDecoration,\n 'letter-spacing': letterSpacing ? round(letterSpacing) : undefined,\n ...textStrokeAttrs(node, colorSpace),\n ...(fontAlias ? aliasedFontAttrs(fontRequest(node), fontAlias) : {})\n }\n const spanAttrs = (style: CharacterStyleOverride, fallback?: SVGFallbackFace) => ({\n ...styleOverrideToTspanAttrs(style, colorSpace, fillOpacity, node),\n ...spanFontAttrs(node, style, fallback, fontAlias)\n })\n\n if (laidOut) {\n // Laid-out spans sit where the editor draws them, which keeps every space it draws.\n return svg(\n 'text',\n { ...attrs, 'xml:space': 'preserve' },\n ...laidOutTextSpans(node, laidOut, spanAttrs)\n )\n }\n\n return renderUnmeasuredText(node, attrs, spanAttrs, direction)\n}\n"],"mappings":";;;;;;;;;;;AAyBA,SAAS,0BACP,OACA,YACA,mBACA,MAC6C;CAC7C,MAAM,QAAqD,CAAC;CAC5D,IAAI,MAAM,YAAY,MAAM,i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AAI,YAAY,iBAAiB,YAAY,IAAI,GAAG,SAAS,IAAI,CAAC;CACpE;CACA,MAAM,aAAa,OAA+B,cAAgC;EAChF,GAAG,0BAA0B,OAAO,YAAY,aAAa,IAAI;EACjE,GAAG,cAAc,MAAM,OAAO,UAAU,SAAS;CACnD;CAEA,IAAI,SAEF,OAAO,IACL,QACA;EAAE,GAAG;EAAO,aAAa;CAAW,GACpC,GAAG,iBAAiB,MAAM,SAAS,SAAS,CAC9C;CAGF,OAAO,qBAAqB,MAAM,OAAO,WAAW,SAAS;AAC/D"}
|
|
1
|
+
{"version":3,"file":"export.js","names":[],"sources":["../../../../../src/io/formats/svg/text/export.ts"],"sourcesContent":["import type { CharacterStyleOverride, ColorProfile, SceneNode } from '@pairdraw/scene-graph'\nimport { parseFontStyle } from '@pairdraw/scene-graph/font-style'\nimport { textLengthPixels } from '@pairdraw/scene-graph/text'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport { drawnFontVariations } from '#core/canvas/text/font-families'\nimport {\n formatColor,\n formatSolidColor,\n type SVGExportContext,\n type SVGFontAlias,\n type SVGFontRequest\n} from '#core/io/formats/svg/defs'\nimport { svg, type SVGNode } from '#core/io/formats/svg/node'\nimport { round } from '#core/io/formats/svg/paths'\nimport {\n explicitNewlineLines,\n laidOutTextSpans,\n textStyleSpans,\n type SpanAttrs,\n type SVGFallbackFace\n} from '#core/io/formats/svg/text/lines'\nimport { shownText } from '#core/text/case'\nimport { textFontFace } from '#core/text/requirements/collect'\n\nfunction styleOverrideToTspanAttrs(\n style: CharacterStyleOverride,\n colorSpace: 'srgb' | 'display-p3',\n documentSpace: ColorProfile,\n parentFillOpacity: number | undefined,\n node: Pick<SceneNode, 'fontSize' | 'letterSpacing'>\n): Record<string, string | number | undefined> {\n const attrs: Record<string, string | number | undefined> = {}\n if (style.fontFamily) attrs['font-family'] = style.fontFamily\n if (style.fontSize) attrs['font-size'] = style.fontSize\n if (style.fontWeight) attrs['font-weight'] = style.fontWeight\n if (style.italic) attrs['font-style'] = 'italic'\n // A run's own spacing is written even at zero, or it would inherit the layer's. A percent the\n // run inherits follows its own font size, so a larger or smaller run writes it again.\n const inherited =\n style.fontSize !== undefined &&\n node.letterSpacing.unit === 'PERCENT' &&\n node.letterSpacing.value !== 0\n ? node.letterSpacing\n : undefined\n const spacing = style.letterSpacing ?? inherited\n if (spacing) {\n attrs['letter-spacing'] = round(textLengthPixels(spacing, style.fontSize ?? node.fontSize))\n }\n if (style.textDecoration === 'UNDERLINE') attrs['text-decoration'] = 'underline'\n if (style.textDecoration === 'STRIKETHROUGH') attrs['text-decoration'] = 'line-through'\n if (style.fills) {\n const visibleFill = style.fills.find((f) => f.visible && f.type === 'SOLID')\n if (visibleFill) {\n // Paragraphs and saved glyphs draw a run at color.a * opacity. Shapes paint opacity alone.\n const alpha = round(visibleFill.color.a * visibleFill.opacity)\n if (colorSpace === 'display-p3') {\n attrs.fill = formatColor({ ...visibleFill.color, a: 1 }, alpha, colorSpace, documentSpace)\n } else {\n attrs.fill = formatColor(visibleFill.color, 1, colorSpace, documentSpace)\n if (alpha < 1) attrs['fill-opacity'] = alpha\n }\n // `fill-opacity` inherits, so an opaque run has to cover a translucent parent.\n if (alpha >= 1 && parentFillOpacity !== undefined) attrs['fill-opacity'] = 1\n }\n }\n return attrs\n}\n\n/**\n * Font attributes naming a face's alias, such as the family a PDF embeds its file under, or else\n * the face itself, so text inside an aliased parent does not inherit the alias.\n */\nfunction aliasedFontAttrs(\n face: SVGFontRequest,\n fontAlias: SVGFontAlias\n): Record<string, string | number> {\n const alias = fontAlias(face)\n if (alias) return { 'font-family': alias, 'font-weight': 'normal', 'font-style': 'normal' }\n return {\n 'font-family': face.family,\n 'font-weight': face.weight,\n 'font-style': face.italic ? 'italic' : 'normal'\n }\n}\n\n/**\n * The font attributes of a span: its face's alias where there is one, otherwise the family of the\n * fallback face that draws it, if any.\n */\nfunction spanFontAttrs(\n node: SceneNode,\n style: CharacterStyleOverride,\n fallback: SVGFallbackFace | undefined,\n fontAlias: SVGFontAlias | undefined\n): Record<string, string | number> {\n if (fontAlias) return aliasedFontAttrs(fontRequest(node, style, fallback), fontAlias)\n return fallback ? { 'font-family': fallback.family } : {}\n}\n\n/**\n * A text layer's stroke, painted on the glyphs themselves. The canvas strokes an outside stroke at\n * twice its weight and clips it to the outside of the glyphs; live text cannot be clipped in SVG,\n * so the same band is painted behind the fill at twice the weight, which hides the inner half. An\n * inside or centred stroke keeps its own weight over the fill.\n */\nfunction textStrokeAttrs(\n node: SceneNode,\n colorSpace: 'srgb' | 'display-p3',\n documentSpace: ColorProfile = 'srgb'\n): Record<string, string | number | undefined> {\n const stroke = node.strokes.find((candidate) => candidate.visible)\n if (!stroke) return {}\n const attrs: Record<string, string | number | undefined> = {\n stroke: formatSolidColor(stroke.color, 1, colorSpace, documentSpace),\n 'stroke-width': round(stroke.weight * (stroke.align === 'OUTSIDE' ? 2 : 1))\n }\n if (stroke.opacity < 1) attrs['stroke-opacity'] = round(stroke.opacity)\n if (stroke.align === 'OUTSIDE') attrs['paint-order'] = 'stroke'\n return attrs\n}\n\n/**\n * The face a run of `node` is drawn in, or the fallback face that draws its characters instead,\n * with the size and axes its instance follows. A fallback is drawn at the axes the run's own font\n * is drawn at, as the paragraph draws every font it falls back to.\n */\nfunction fontRequest(\n node: SceneNode,\n style: CharacterStyleOverride = {},\n fallback?: SVGFallbackFace\n): SVGFontRequest {\n const own: SVGFontRequest = {\n ...textFontFace(node, style),\n fontSize: style.fontSize ?? node.fontSize,\n variations: style.fontVariations ?? node.fontVariations,\n opticalSizeFromFontSize: style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize\n }\n if (!fallback) return own\n return {\n ...own,\n ...fallback,\n ...parseFontStyle(fallback.style),\n variations: drawnFontVariations(own),\n opticalSizeFromFontSize: false\n }\n}\n\nfunction isLogicalTextEnd(node: SceneNode, direction: 'LTR' | 'RTL'): boolean {\n return (\n (direction === 'LTR' && node.textAlignHorizontal === 'RIGHT') ||\n (direction === 'RTL' && node.textAlignHorizontal === 'LEFT')\n )\n}\n\nfunction textAnchorForNode(\n node: SceneNode,\n direction: 'LTR' | 'RTL'\n): 'middle' | 'end' | undefined {\n if (node.textAlignHorizontal === 'CENTER') return 'middle'\n if (isLogicalTextEnd(node, direction)) return 'end'\n return undefined\n}\n\nfunction textXForNode(node: SceneNode, direction: 'LTR' | 'RTL'): number {\n if (node.textAlignHorizontal === 'CENTER') return round(node.width / 2)\n if (isLogicalTextEnd(node, direction)) return round(node.width)\n return 0\n}\n\n/** Text with no measured layout: explicit newlines on their own baselines, otherwise one line. */\nfunction renderUnmeasuredText(\n node: SceneNode,\n attrs: Record<string, string | number | undefined>,\n spanAttrs: SpanAttrs,\n direction: 'LTR' | 'RTL'\n): SVGNode {\n const x = textXForNode(node, direction)\n const y = node.fontSize || 14\n // No measured wraps: an explicit newline still starts a line, on the same anchor as one line.\n const newlineLines = explicitNewlineLines(node, x, y)\n if (newlineLines) {\n return svg(\n 'text',\n { ...attrs, 'xml:space': 'preserve' },\n ...laidOutTextSpans(node, newlineLines, spanAttrs)\n )\n }\n\n if (node.styleRuns.length > 0) {\n return svg(\n 'text',\n { x, y, ...attrs, 'xml:space': 'preserve' },\n ...textStyleSpans(node, spanAttrs)\n )\n }\n\n return svg('text', { x, y, ...attrs }, shownText(node))\n}\n\nexport function renderTextNode(\n node: SceneNode,\n fillAttr: string | null,\n ctx: SVGExportContext,\n fillOpacity?: number\n): SVGNode {\n const { colorSpace, documentColorSpace: documentSpace, textLayout, fontAlias } = ctx\n const direction = resolveNodeTextDirection(node)\n const lines = textLayout ? textLayout(node) : null\n const laidOut = lines && lines.length > 0 ? lines : null\n\n let textDecoration: 'underline' | 'line-through' | undefined\n if (node.textDecoration === 'UNDERLINE') textDecoration = 'underline'\n else if (node.textDecoration === 'STRIKETHROUGH') textDecoration = 'line-through'\n const letterSpacing = textLengthPixels(node.letterSpacing, node.fontSize)\n\n const attrs: Record<string, string | number | undefined> = {\n 'font-family': node.fontFamily || undefined,\n 'font-size': node.fontSize || undefined,\n 'font-weight': node.fontWeight !== 400 ? node.fontWeight : undefined,\n 'font-style': node.italic ? 'italic' : undefined,\n fill: fillAttr ?? undefined,\n 'fill-opacity': fillOpacity,\n // Laid-out spans each start at their own left edge, so they take no direction or anchor.\n direction: direction === 'RTL' && !laidOut ? 'rtl' : undefined,\n 'text-anchor': laidOut ? undefined : textAnchorForNode(node, direction),\n 'text-decoration': textDecoration,\n 'letter-spacing': letterSpacing ? round(letterSpacing) : undefined,\n ...textStrokeAttrs(node, colorSpace, documentSpace),\n ...(fontAlias ? aliasedFontAttrs(fontRequest(node), fontAlias) : {})\n }\n const spanAttrs = (style: CharacterStyleOverride, fallback?: SVGFallbackFace) => ({\n ...styleOverrideToTspanAttrs(style, colorSpace, documentSpace, fillOpacity, node),\n ...spanFontAttrs(node, style, fallback, fontAlias)\n })\n\n if (laidOut) {\n // Laid-out spans sit where the editor draws them, which keeps every space it draws.\n return svg(\n 'text',\n { ...attrs, 'xml:space': 'preserve' },\n ...laidOutTextSpans(node, laidOut, spanAttrs)\n )\n }\n\n return renderUnmeasuredText(node, attrs, spanAttrs, direction)\n}\n"],"mappings":";;;;;;;;;;;AAyBA,SAAS,0BACP,OACA,YACA,eACA,mBACA,MAC6C;CAC7C,MAAM,QAAqD,CAAC;CAC5D,IAAI,MAAM,YAAY,MAAM,iBAAiB,MAAM;CACnD,IAAI,MAAM,UAAU,MAAM,eAAe,MAAM;CAC/C,IAAI,MAAM,YAAY,MAAM,iBAAiB,MAAM;CACnD,IAAI,MAAM,QAAQ,MAAM,gBAAgB;CAGxC,MAAM,YACJ,MAAM,aAAa,KAAA,KACnB,KAAK,cAAc,SAAS,aAC5B,KAAK,cAAc,UAAU,IACzB,KAAK,gBACL,KAAA;CACN,MAAM,UAAU,MAAM,iBAAiB;CACvC,IAAI,SACF,MAAM,oBAAoB,MAAM,iBAAiB,SAAS,MAAM,YAAY,KAAK,QAAQ,CAAC;CAE5F,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M,OAAO,WAAW,SAAS;AAC/D"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { resolveFontReadiness } from "../../../../text/prepare.js";
|
|
2
2
|
import { renderNodesToSVG } from "../export.js";
|
|
3
3
|
import { withPDFTextLayout } from "../../pdf/prepare.js";
|
|
4
4
|
import { bakeAdjustedImages, hasAdjustedImagePaints } from "../../raster/adjusted-images.js";
|
|
@@ -10,7 +10,7 @@ import { bakeAdjustedImages, hasAdjustedImagePaints } from "../../raster/adjuste
|
|
|
10
10
|
* the pattern embeds the adjusted pixels.
|
|
11
11
|
*/
|
|
12
12
|
async function renderNodesToLaidOutSVG(graph, pageId, nodeIds, options = {}, canvasKit, renderer) {
|
|
13
|
-
await
|
|
13
|
+
await resolveFontReadiness(graph, nodeIds);
|
|
14
14
|
const baked = hasAdjustedImagePaints(graph, nodeIds) ? await bakeAdjustedImages(graph, nodeIds, canvasKit, renderer) : graph;
|
|
15
15
|
return withPDFTextLayout(async (textLayout) => renderNodesToSVG(baked, pageId, nodeIds, {
|
|
16
16
|
textLayout,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layout.js","names":[],"sources":["../../../../../src/io/formats/svg/text/layout.ts"],"sourcesContent":["import type { CanvasKit } from 'canvaskit-wasm'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport type { SkiaRenderer } from '#core/canvas/renderer'\nimport { withPDFTextLayout } from '#core/io/formats/pdf/prepare'\nimport { bakeAdjustedImages, hasAdjustedImagePaints } from '#core/io/formats/raster/adjusted-images'\nimport { renderNodesToSVG, type SVGExportOptions } from '#core/io/formats/svg/export'\nimport {
|
|
1
|
+
{"version":3,"file":"layout.js","names":[],"sources":["../../../../../src/io/formats/svg/text/layout.ts"],"sourcesContent":["import type { CanvasKit } from 'canvaskit-wasm'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport type { SkiaRenderer } from '#core/canvas/renderer'\nimport { withPDFTextLayout } from '#core/io/formats/pdf/prepare'\nimport { bakeAdjustedImages, hasAdjustedImagePaints } from '#core/io/formats/raster/adjusted-images'\nimport { renderNodesToSVG, type SVGExportOptions } from '#core/io/formats/svg/export'\nimport { resolveFontReadiness } from '#core/text/prepare'\n\n/**\n * Layers as SVG with their text set as the canvas sets it: the fonts it draws with loaded, each\n * line on the baseline the canvas gives it, and wrapped paragraphs kept wrapped, as PDF export\n * sets them. An image paint with adjustments is baked to the PNG the raster pipeline draws, so\n * the pattern embeds the adjusted pixels.\n */\nexport async function renderNodesToLaidOutSVG(\n graph: SceneGraph,\n pageId: string,\n nodeIds: string[],\n options: SVGExportOptions = {},\n canvasKit?: CanvasKit,\n renderer?: SkiaRenderer\n): Promise<string | null> {\n await resolveFontReadiness(graph, nodeIds)\n const baked = hasAdjustedImagePaints(graph, nodeIds)\n ? await bakeAdjustedImages(graph, nodeIds, canvasKit, renderer)\n : graph\n return withPDFTextLayout(async (textLayout) =>\n renderNodesToSVG(baked, pageId, nodeIds, { textLayout, ...options })\n )\n}\n"],"mappings":";;;;;;;;;;;AAgBA,eAAsB,wBACpB,OACA,QACA,SACA,UAA4B,CAAC,GAC7B,WACA,UACwB;CACxB,MAAM,qBAAqB,OAAO,OAAO;CACzC,MAAM,QAAQ,uBAAuB,OAAO,OAAO,IAC/C,MAAM,mBAAmB,OAAO,SAAS,WAAW,QAAQ,IAC5D;CACJ,OAAO,kBAAkB,OAAO,eAC9B,iBAAiB,OAAO,QAAQ,SAAS;EAAE;EAAY,GAAG;CAAQ,CAAC,CACrE;AACF"}
|
package/dist/io/formats.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formats.d.ts","names":[],"sources":["../../src/io/formats.ts"],"mappings":";;;;;cAiKa,qBAAqB,SAAS,OAAO;cAKrC,WAAW;cA8DX,cAAc;cA2Dd,eAAe;cAwCf,WAAS;cACT,WAAS;cACT,YAAU;cAEV,WAAW;
|
|
1
|
+
{"version":3,"file":"formats.d.ts","names":[],"sources":["../../src/io/formats.ts"],"mappings":";;;;;cAiKa,qBAAqB,SAAS,OAAO;cAKrC,WAAW;cA8DX,cAAc;cA2Dd,eAAe;cAwCf,WAAS;cACT,WAAS;cACT,YAAU;cAEV,WAAW;cA0EX,WAAW;cA6CX,YAAY;cA2BZ,WAAW;cAqDX,YAAY;cA+BZ,mBAAmB;cAkCnB,8BAAkB,wBAAA,wBAAA,2BAAA,4BAAA,wBAAA,wBAAA,yBAAA,wBAAA,wBAAA,yBAAA,wBAAA,iCAAA;KAgBnB,4BAA4B"}
|
package/dist/io/formats.js
CHANGED
|
@@ -288,6 +288,7 @@ const svgFormat = {
|
|
|
288
288
|
const booleanPath = needsBooleanPaths(request.graph) ? await booleanPathResolver(context?.canvasKit, context?.renderer) : void 0;
|
|
289
289
|
const data = await renderNodesToLaidOutSVG(request.graph, target.pageId, target.nodeIds, {
|
|
290
290
|
...options,
|
|
291
|
+
colorSpace: options?.colorSpace ?? request.graph.documentColorSpace,
|
|
291
292
|
booleanPath
|
|
292
293
|
}, context?.canvasKit, context?.renderer);
|
|
293
294
|
if (!data) throw new Error("Nothing to export");
|
package/dist/io/formats.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formats.js","names":[],"sources":["../../src/io/formats.ts"],"sourcesContent":["import { filename } from 'pathe/utils'\n\nimport { sceneNodeToJSX, selectionToJSX } from '@pairdraw/design-jsx'\nimport { isDrawIOExportFileName } from '@pairdraw/drawio'\nimport type { DocumentKind, SceneGraph } from '@pairdraw/scene-graph'\n\nimport { layoutAuthoredNodes } from '#core/layout'\n\nimport type { DrawIOExportTarget } from './formats/drawio/export'\nimport { exportFigFile, parseFigFile } from './formats/fig'\nimport type { PDFPageSpec } from './formats/pdf/plan'\nimport { penFormat } from './formats/pen'\nimport type { PPTXExportOptions } from './formats/pptx'\nimport { headlessRenderNodes, renderNodesToImage, type RasterExportFormat } from './formats/raster'\nimport { extractExportGraph, findPageId } from './subgraph'\nimport type {\n ExportRequest,\n ExportResult,\n FigWriteOptions,\n HTMLExportOptions,\n IOContext,\n IOFormatAdapter,\n IOFormatExportOptions,\n IOFormatSupport,\n PDFFormatExportOptions,\n RasterExportOptions,\n SVGExportOptions\n} from './types'\n\n/** Formats that export a document, page, selection, or single node alike. */\nconst EXPORT_EVERY_TARGET: IOFormatSupport = {\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n}\n\n/** Formats with a size of their own, so no export scale or quality. */\nconst FIXED_SIZE_EXPORT: IOFormatExportOptions = { scale: false, quality: false }\n\nfunction lowerExt(name: string): string {\n const match = /\\.([^.]+)$/.exec(name.toLowerCase())\n return match?.[1] ?? ''\n}\n\nfunction ensureSingleNode(target: ExportRequest['target']): string | null {\n if (target.scope === 'node') return target.nodeId\n if (target.scope === 'selection' && target.nodeIds.length === 1) return target.nodeIds[0]\n return null\n}\n\nfunction resolveExportNodes(request: ExportRequest): { pageId: string; nodeIds: string[] } | null {\n switch (request.target.scope) {\n case 'document': {\n const page = request.graph.getPages()[0]\n return { pageId: page.id, nodeIds: page.childIds }\n }\n case 'page': {\n const page = request.graph.getNode(request.target.pageId)\n if (!page) return null\n return { pageId: page.id, nodeIds: page.childIds }\n }\n case 'selection': {\n const first = request.target.nodeIds[0]\n if (!first) return null\n const pageId = findPageId(request.graph, first)\n if (!pageId) return null\n if (!request.target.nodeIds.every((nodeId) => findPageId(request.graph, nodeId) === pageId)) {\n throw new Error('Export selection must stay on a single page')\n }\n return { pageId, nodeIds: request.target.nodeIds }\n }\n case 'node':\n return resolveExportNodes({\n ...request,\n target: { scope: 'selection', nodeIds: [request.target.nodeId] }\n })\n default:\n return null\n }\n}\n\nasync function renderRaster(\n request: ExportRequest,\n options: RasterExportOptions,\n context?: IOContext\n): Promise<Uint8Array | null> {\n const target = resolveExportNodes(request)\n if (!target) return null\n const scale = options.scale ?? 1\n\n if (context?.canvasKit && context.renderer) {\n return renderNodesToImage(\n context.canvasKit,\n context.renderer,\n request.graph,\n target.pageId,\n target.nodeIds,\n {\n scale,\n format: options.format,\n quality: options.quality,\n trimTransparent: request.target.scope === 'page' || request.target.scope === 'document'\n }\n )\n }\n\n return headlessRenderNodes(request.graph, target.pageId, target.nodeIds, {\n scale,\n format: options.format,\n quality: options.quality,\n trimTransparent: request.target.scope === 'page' || request.target.scope === 'document'\n })\n}\n\nfunction rasterFormat<F extends RasterExportFormat>(format: F): IOFormatAdapter<Lowercase<F>> {\n const extension = format.toLowerCase() as Lowercase<F>\n let mimeType = 'image/png'\n if (format === 'JPG') mimeType = 'image/jpeg'\n else if (format === 'WEBP') mimeType = 'image/webp'\n\n return {\n id: extension,\n label: format,\n role: 'derived-export',\n category: 'raster',\n extensions: [extension],\n mimeTypes: [mimeType],\n support: {\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: {\n scale: true,\n quality: format !== 'PNG',\n colorSpace: false\n },\n async exportContent(request, options?: RasterExportOptions, context?: IOContext) {\n const data = await renderRaster(\n request,\n {\n format,\n scale: options?.scale,\n quality: options?.quality\n },\n context\n )\n if (!data) throw new Error('Nothing to export')\n return {\n format: extension,\n mimeType,\n extension,\n data\n }\n }\n }\n}\n\n/** The file a document saves as: Figma's `.fig` for a design, FigJam's `.jam` for a board. */\nexport const DOCUMENT_EXTENSIONS: Readonly<Record<DocumentKind, 'fig' | 'jam'>> = {\n design: 'fig',\n board: 'jam'\n}\n\nexport const figFormat: IOFormatAdapter<'fig'> = {\n id: 'fig',\n label: 'Pairdraw Document',\n role: 'native-document',\n category: 'document',\n extensions: ['fig', 'jam'],\n mimeTypes: ['application/octet-stream'],\n support: {\n readDocument: true,\n writeDocument: true,\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: FIXED_SIZE_EXPORT,\n matchesFile(fileName) {\n const ext = lowerExt(fileName)\n return ext === 'fig' || ext === 'jam'\n },\n async readDocument(input) {\n const data = input.data.slice().buffer\n const graph = await parseFigFile(data, { populate: 'first-page' })\n return { graph, sourceFormat: 'fig' }\n },\n async writeDocument(graph, options?: FigWriteOptions, context?: IOContext) {\n return writeFig(graph, options, context, options?.thumbnailPageId)\n },\n async exportContent(request, options?: FigWriteOptions, context?: IOContext) {\n // A whole document is written as it is, so one opened from an archive keeps that archive.\n if (request.target.scope === 'document')\n return writeFig(request.graph, options, context, options?.thumbnailPageId, request.fileName)\n const extracted = extractExportGraph(request.graph, request.target)\n return writeFig(\n extracted.graph,\n options,\n context,\n options?.thumbnailPageId ?? extracted.pageId ?? undefined,\n request.fileName\n )\n }\n}\n\n/** A `.fig` named as asked, or else after the file it is written to, or else Untitled. */\nasync function writeFig(\n graph: SceneGraph,\n options: FigWriteOptions | undefined,\n context: IOContext | undefined,\n pageId: string | undefined,\n fileName?: string\n): Promise<ExportResult> {\n const data = await exportFigFile(graph, {\n ck: context?.canvasKit,\n renderer: context?.renderer,\n pageId,\n renderHeadlessThumbnail: options?.renderThumbnail ?? false,\n documentName: options?.documentName ?? (fileName && filename(fileName))\n })\n const extension = DOCUMENT_EXTENSIONS[graph.documentKind]\n return { format: 'fig', mimeType: 'application/octet-stream', extension, data }\n}\n\nexport const drawioFormat: IOFormatAdapter<'drawio'> = {\n id: 'drawio',\n label: 'draw.io Diagram',\n role: 'interchange-document',\n category: 'document',\n extensions: ['drawio', 'dio'],\n mimeTypes: ['application/vnd.jgraph.mxfile'],\n support: {\n readDocument: true,\n writeDocument: true,\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: FIXED_SIZE_EXPORT,\n laysOutOnRead: true,\n // A draw.io PNG or SVG export opens as its diagram when its name says it is one.\n matchesFile(fileName, mimeType) {\n const ext = lowerExt(fileName)\n return (\n ext === 'drawio' ||\n ext === 'dio' ||\n isDrawIOExportFileName(fileName) ||\n mimeType === 'application/vnd.jgraph.mxfile'\n )\n },\n async readDocument(input) {\n const { readDrawIOBytes } = await import('@pairdraw/drawio')\n const { drawioToSceneGraph } = await import('./formats/drawio')\n const file = readDrawIOBytes(input.data)\n if (!file) throw new Error('This file holds no draw.io diagram')\n if (file.unreadable.length > 0) {\n throw new Error(`Could not read the draw.io pages ${file.unreadable.join(', ')}`)\n }\n const graph = drawioToSceneGraph(file)\n // draw.io stores label text, not the sizes it lays out to.\n layoutAuthoredNodes(\n graph,\n graph.getPages().map((page) => page.id)\n )\n return { graph, sourceFormat: 'drawio' }\n },\n async writeDocument(graph) {\n const pageIds = graph.getPages().map((page) => page.id)\n return writeDrawIO(graph, { pageIds })\n },\n // A page or a selection goes as a one-page diagram; the document, every page.\n async exportContent(request) {\n if (request.target.scope === 'document') {\n const pageIds = request.graph.getPages().map((page) => page.id)\n return writeDrawIO(request.graph, { pageIds })\n }\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n return writeDrawIO(request.graph, target)\n }\n}\n\nexport const mermaidFormat: IOFormatAdapter<'mermaid'> = {\n id: 'mermaid',\n label: 'Mermaid Diagram',\n role: 'interchange-document',\n category: 'document',\n extensions: ['mmd', 'mermaid'],\n mimeTypes: ['text/vnd.mermaid'],\n support: {\n readDocument: true\n },\n laysOutOnRead: true,\n matchesFile(fileName, mimeType) {\n const ext = lowerExt(fileName)\n return ext === 'mmd' || ext === 'mermaid' || mimeType === 'text/vnd.mermaid'\n },\n async readDocument(input) {\n const { detectMermaidDiagram } = await import('@pairdraw/mermaid')\n const text = new TextDecoder().decode(input.data)\n if (!detectMermaidDiagram(text)) throw new Error('This file holds no Mermaid flowchart')\n // Mermaid stores a diagram's structure, which reading lays out with its text measured.\n const { mermaidToSceneGraph } = await import('./formats/mermaid')\n return { graph: await mermaidToSceneGraph(text), sourceFormat: 'mermaid' }\n }\n}\n\n/** Pages or layers as a draw.io file, loading the writer only when one is saved. */\nasync function writeDrawIO(graph: SceneGraph, target: DrawIOExportTarget): Promise<ExportResult> {\n const { writeDrawIOFile } = await import('@pairdraw/drawio')\n const { sceneGraphToDrawIO } = await import('./formats/drawio')\n const { drawioDroppedWarnings } = await import('./formats/drawio/warnings')\n return {\n format: 'drawio',\n mimeType: 'application/vnd.jgraph.mxfile',\n extension: 'drawio',\n data: writeDrawIOFile(sceneGraphToDrawIO(graph, target)),\n encoding: 'utf8',\n warnings: drawioDroppedWarnings(graph)\n }\n}\n\nexport const pngFormat = rasterFormat('PNG')\nexport const jpgFormat = rasterFormat('JPG')\nexport const webpFormat = rasterFormat('WEBP')\n\nexport const svgFormat: IOFormatAdapter<'svg'> = {\n id: 'svg',\n label: 'SVG',\n role: 'derived-export',\n category: 'vector',\n extensions: ['svg'],\n mimeTypes: ['image/svg+xml'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: { ...FIXED_SIZE_EXPORT, colorSpace: true },\n async exportContent(request, options?: SVGExportOptions, context?: IOContext) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToLaidOutSVG } = await import('./formats/svg/text/layout')\n const { booleanPathResolver, needsBooleanPaths } = await import('./formats/boolean-path')\n // A boolean made in Pairdraw stores no result path; the export computes it from the operands.\n const booleanPath = needsBooleanPaths(request.graph)\n ? await booleanPathResolver(context?.canvasKit, context?.renderer)\n : undefined\n const data = await renderNodesToLaidOutSVG(\n request.graph,\n target.pageId,\n target.nodeIds,\n { ...options, booleanPath },\n context?.canvasKit,\n context?.renderer\n )\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'svg',\n mimeType: 'image/svg+xml',\n extension: 'svg',\n data,\n encoding: 'utf8'\n }\n }\n}\n\n/**\n * The PDF pages an export makes. A selection gets a page per layer in the order it lists them,\n * each sized to its layer, as slides and Figma's frame export do, unless `single` asks for one\n * page; a page or a document is one page of its layers unless `frames` asks for a page each.\n */\nasync function pdfPageSpecs(\n request: ExportRequest,\n options: PDFFormatExportOptions | undefined\n): Promise<PDFPageSpec[]> {\n const frames = options?.pages ? options.pages === 'frames' : request.target.scope === 'selection'\n if (frames) {\n const { target } = request\n let ids: string[] | undefined\n if (target.scope === 'selection') ids = target.nodeIds\n else if (target.scope === 'node') ids = [target.nodeId]\n const first = ids?.[0]\n let currentPageId: string | null | undefined\n if (first) currentPageId = findPageId(request.graph, first)\n else if (target.scope === 'page') currentPageId = target.pageId\n else if (target.scope === 'document') currentPageId = request.graph.getPages()[0]?.id\n if (!currentPageId) throw new Error('Nothing to export')\n // Without IDs, the plan takes the page's visible layers, in layer order.\n const { planPDFPages } = await import('./formats/pdf/plan')\n return planPDFPages(request.graph, { mode: 'frames', ids, currentPageId })\n }\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n return [target]\n}\n\nexport const pdfFormat: IOFormatAdapter<'pdf'> = {\n id: 'pdf',\n label: 'PDF',\n role: 'derived-export',\n category: 'vector',\n extensions: ['pdf'],\n mimeTypes: ['application/pdf'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: PDFFormatExportOptions, context?: IOContext) {\n const specs = await pdfPageSpecs(request, options)\n // Embedded, as Figma embeds every face its PDFs draw.\n const { exportPDFDocument } = await import('./formats/pdf/document')\n const data = (\n await exportPDFDocument(\n request.graph,\n specs,\n { embedFonts: true },\n context?.canvasKit,\n context?.renderer\n )\n )?.data\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'pdf',\n mimeType: 'application/pdf',\n extension: 'pdf',\n data\n }\n }\n}\n\n/**\n * Every top-level frame becomes a slide, so a PPTX document export spans all\n * pages — the shared resolver only reaches the first one.\n */\nfunction resolvePPTXExportNodes(\n request: ExportRequest\n): { pageId: string; nodeIds: string[] } | null {\n if (request.target.scope !== 'document') return resolveExportNodes(request)\n const pages = request.graph.getPages()\n if (!pages.length) return null\n return { pageId: pages[0].id, nodeIds: pages.flatMap((page) => page.childIds) }\n}\n\nexport const pptxFormat: IOFormatAdapter<'pptx'> = {\n id: 'pptx',\n label: 'PowerPoint',\n role: 'derived-export',\n category: 'print',\n extensions: ['pptx'],\n mimeTypes: ['application/vnd.openxmlformats-officedocument.presentationml.presentation'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: PPTXExportOptions, context?: IOContext) {\n const target = resolvePPTXExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToPPTX } = await import('./formats/pptx')\n const data = await renderNodesToPPTX(request.graph, target.pageId, target.nodeIds, {\n ...options,\n context: options?.context ?? context\n })\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'pptx',\n mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n extension: 'pptx',\n data\n }\n }\n}\n\nexport const jsxFormat: IOFormatAdapter<'jsx'> = {\n id: 'jsx',\n label: 'JSX',\n role: 'derived-export',\n category: 'code',\n extensions: ['jsx'],\n mimeTypes: ['text/plain', 'text/jsx'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, _options?: unknown, context?: IOContext): Promise<ExportResult> {\n const nodeId = ensureSingleNode(request.target)\n // A page or a document exports its top-level layers, as Tailwind JSX does.\n const target = nodeId ? null : resolveExportNodes(request)\n const { booleanPathResolver, needsBooleanPaths } = await import('./formats/boolean-path')\n const authored = needsBooleanPaths(request.graph)\n ? [...request.graph.getAllNodes()].filter(\n (node) => node.type === 'BOOLEAN_OPERATION' && node.fillGeometry.length === 0\n )\n : []\n const restore: (() => void)[] = []\n if (authored.length > 0) {\n const { parseSVGPath } = await import('@pairdraw/scene-graph/parse-path')\n const booleanPath = await booleanPathResolver(context?.canvasKit, context?.renderer)\n for (const node of authored) {\n const d = booleanPath(request.graph, node)\n if (!d) continue\n const network = parseSVGPath(d, 'EVENODD', { includeOpenRegions: true })\n const carrier = node as typeof node & { vectorNetwork?: typeof network }\n const previous = carrier.vectorNetwork\n carrier.vectorNetwork = network\n restore.push(() => {\n carrier.vectorNetwork = previous\n })\n }\n }\n let data = ''\n try {\n if (nodeId) data = sceneNodeToJSX(nodeId, request.graph)\n else if (target) data = selectionToJSX(target.nodeIds, request.graph)\n } finally {\n for (const undo of restore) undo()\n }\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'jsx',\n mimeType: 'text/plain',\n extension: 'jsx',\n data,\n encoding: 'utf8'\n }\n }\n}\n\nexport const htmlFormat: IOFormatAdapter<'html'> = {\n id: 'html',\n label: 'HTML',\n role: 'derived-export',\n category: 'code',\n extensions: ['html'],\n mimeTypes: ['text/html'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: HTMLExportOptions, context?: IOContext) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToHTML } = await import('./formats/html')\n const { html, assets } = await renderNodesToHTML(\n request.graph,\n target.nodeIds,\n options,\n request.fileName,\n context\n )\n return {\n format: 'html',\n mimeType: 'text/html',\n extension: 'html',\n data: html,\n encoding: 'utf8',\n assets\n }\n }\n}\n\nexport const tailwindJSXFormat: IOFormatAdapter<'tailwind-jsx'> = {\n id: 'tailwind-jsx',\n label: 'Tailwind JSX',\n role: 'derived-export',\n category: 'code',\n extensions: ['jsx'],\n mimeTypes: ['text/plain', 'text/jsx'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, _options?: unknown, context?: IOContext) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { sceneNodesToTailwindJSX } = await import('@pairdraw/dom-css/export')\n const { vectorElement } = await import('#core/io/formats/html/vectors')\n const { booleanPathResolver, needsBooleanPaths } = await import('./formats/boolean-path')\n const booleanPath = needsBooleanPaths(request.graph)\n ? await booleanPathResolver(context?.canvasKit, context?.renderer)\n : undefined\n const data = sceneNodesToTailwindJSX(request.graph, target.nodeIds, {\n vectorElement: (graph, node) => vectorElement(graph, node, booleanPath)\n })\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'tailwind-jsx',\n mimeType: 'text/plain',\n extension: 'jsx',\n data,\n encoding: 'utf8'\n }\n }\n}\n\nexport { penFormat }\n\nexport const BUILTIN_IO_FORMATS = [\n figFormat,\n penFormat,\n drawioFormat,\n mermaidFormat,\n pngFormat,\n jpgFormat,\n webpFormat,\n svgFormat,\n pdfFormat,\n pptxFormat,\n jsxFormat,\n tailwindJSXFormat,\n htmlFormat\n] as const satisfies readonly IOFormatAdapter[]\n\nexport type BuiltinIOFormatId = (typeof BUILTIN_IO_FORMATS)[number]['id']\n"],"mappings":";;;;;;;;;;;;AA8BA,MAAM,sBAAuC;CAC3C,gBAAgB;CAChB,YAAY;CACZ,iBAAiB;CACjB,YAAY;AACd;;AAGA,MAAM,oBAA2C;CAAE,OAAO;CAAO,SAAS;AAAM;AAEhF,SAAS,SAAS,MAAsB;CAEtC,OADc,aAAa,KAAK,KAAK,YAAY,CACtC,CAAC,GAAG,MAAM;AACvB;AAEA,SAAS,iBAAiB,QAAgD;CACxE,IAAI,OAAO,UAAU,QAAQ,OAAO,OAAO;CAC3C,IAAI,OAAO,UAAU,eAAe,OAAO,QAAQ,WAAW,GAAG,OAAO,OAAO,QAAQ;CACvF,OAAO;AACT;AAEA,SAAS,mBAAmB,SAAsE;CAChG,QAAQ,QAAQ,OAAO,OAAvB;EACE,KAAK,YAAY;GACf,MAAM,OAAO,QAAQ,MAAM,SAAS,CAAC,CAAC;GACtC,OAAO;IAAE,QAAQ,KAAK;IAAI,SAAS,KAAK;GAAS;EACnD;EACA,KAAK,QAAQ;GACX,MAAM,OAAO,QAAQ,MAAM,QAAQ,QAAQ,OAAO,MAAM;GACxD,IAAI,CAAC,MAAM,OAAO;GAClB,OAAO;IAAE,QAAQ,KAAK;IAAI,SAAS,KAAK;GAAS;EACnD;EACA,KAAK,aAAa;GAChB,MAAM,QAAQ,QAAQ,OAAO,QAAQ;GACrC,IAAI,CAAC,OAAO,OAAO;GACnB,MAAM,SAAS,WAAW,QAAQ,OAAO,KAAK;GAC9C,IAAI,CAAC,QAAQ,OAAO;GACpB,IAAI,CAAC,QAAQ,OAAO,QAAQ,OAAO,WAAW,WAAW,Q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AAC;EACD,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,mBAAmB;EAC9C,OAAO;GACL,QAAQ;GACR,UAAU;GACV,WAAW;GACX;GACA,UAAU;EACZ;CACF;AACF;AAIA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
1
|
+
{"version":3,"file":"formats.js","names":[],"sources":["../../src/io/formats.ts"],"sourcesContent":["import { filename } from 'pathe/utils'\n\nimport { sceneNodeToJSX, selectionToJSX } from '@pairdraw/design-jsx'\nimport { isDrawIOExportFileName } from '@pairdraw/drawio'\nimport type { DocumentKind, SceneGraph } from '@pairdraw/scene-graph'\n\nimport { layoutAuthoredNodes } from '#core/layout'\n\nimport type { DrawIOExportTarget } from './formats/drawio/export'\nimport { exportFigFile, parseFigFile } from './formats/fig'\nimport type { PDFPageSpec } from './formats/pdf/plan'\nimport { penFormat } from './formats/pen'\nimport type { PPTXExportOptions } from './formats/pptx'\nimport { headlessRenderNodes, renderNodesToImage, type RasterExportFormat } from './formats/raster'\nimport { extractExportGraph, findPageId } from './subgraph'\nimport type {\n ExportRequest,\n ExportResult,\n FigWriteOptions,\n HTMLExportOptions,\n IOContext,\n IOFormatAdapter,\n IOFormatExportOptions,\n IOFormatSupport,\n PDFFormatExportOptions,\n RasterExportOptions,\n SVGExportOptions\n} from './types'\n\n/** Formats that export a document, page, selection, or single node alike. */\nconst EXPORT_EVERY_TARGET: IOFormatSupport = {\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n}\n\n/** Formats with a size of their own, so no export scale or quality. */\nconst FIXED_SIZE_EXPORT: IOFormatExportOptions = { scale: false, quality: false }\n\nfunction lowerExt(name: string): string {\n const match = /\\.([^.]+)$/.exec(name.toLowerCase())\n return match?.[1] ?? ''\n}\n\nfunction ensureSingleNode(target: ExportRequest['target']): string | null {\n if (target.scope === 'node') return target.nodeId\n if (target.scope === 'selection' && target.nodeIds.length === 1) return target.nodeIds[0]\n return null\n}\n\nfunction resolveExportNodes(request: ExportRequest): { pageId: string; nodeIds: string[] } | null {\n switch (request.target.scope) {\n case 'document': {\n const page = request.graph.getPages()[0]\n return { pageId: page.id, nodeIds: page.childIds }\n }\n case 'page': {\n const page = request.graph.getNode(request.target.pageId)\n if (!page) return null\n return { pageId: page.id, nodeIds: page.childIds }\n }\n case 'selection': {\n const first = request.target.nodeIds[0]\n if (!first) return null\n const pageId = findPageId(request.graph, first)\n if (!pageId) return null\n if (!request.target.nodeIds.every((nodeId) => findPageId(request.graph, nodeId) === pageId)) {\n throw new Error('Export selection must stay on a single page')\n }\n return { pageId, nodeIds: request.target.nodeIds }\n }\n case 'node':\n return resolveExportNodes({\n ...request,\n target: { scope: 'selection', nodeIds: [request.target.nodeId] }\n })\n default:\n return null\n }\n}\n\nasync function renderRaster(\n request: ExportRequest,\n options: RasterExportOptions,\n context?: IOContext\n): Promise<Uint8Array | null> {\n const target = resolveExportNodes(request)\n if (!target) return null\n const scale = options.scale ?? 1\n\n if (context?.canvasKit && context.renderer) {\n return renderNodesToImage(\n context.canvasKit,\n context.renderer,\n request.graph,\n target.pageId,\n target.nodeIds,\n {\n scale,\n format: options.format,\n quality: options.quality,\n trimTransparent: request.target.scope === 'page' || request.target.scope === 'document'\n }\n )\n }\n\n return headlessRenderNodes(request.graph, target.pageId, target.nodeIds, {\n scale,\n format: options.format,\n quality: options.quality,\n trimTransparent: request.target.scope === 'page' || request.target.scope === 'document'\n })\n}\n\nfunction rasterFormat<F extends RasterExportFormat>(format: F): IOFormatAdapter<Lowercase<F>> {\n const extension = format.toLowerCase() as Lowercase<F>\n let mimeType = 'image/png'\n if (format === 'JPG') mimeType = 'image/jpeg'\n else if (format === 'WEBP') mimeType = 'image/webp'\n\n return {\n id: extension,\n label: format,\n role: 'derived-export',\n category: 'raster',\n extensions: [extension],\n mimeTypes: [mimeType],\n support: {\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: {\n scale: true,\n quality: format !== 'PNG',\n colorSpace: false\n },\n async exportContent(request, options?: RasterExportOptions, context?: IOContext) {\n const data = await renderRaster(\n request,\n {\n format,\n scale: options?.scale,\n quality: options?.quality\n },\n context\n )\n if (!data) throw new Error('Nothing to export')\n return {\n format: extension,\n mimeType,\n extension,\n data\n }\n }\n }\n}\n\n/** The file a document saves as: Figma's `.fig` for a design, FigJam's `.jam` for a board. */\nexport const DOCUMENT_EXTENSIONS: Readonly<Record<DocumentKind, 'fig' | 'jam'>> = {\n design: 'fig',\n board: 'jam'\n}\n\nexport const figFormat: IOFormatAdapter<'fig'> = {\n id: 'fig',\n label: 'Pairdraw Document',\n role: 'native-document',\n category: 'document',\n extensions: ['fig', 'jam'],\n mimeTypes: ['application/octet-stream'],\n support: {\n readDocument: true,\n writeDocument: true,\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: FIXED_SIZE_EXPORT,\n matchesFile(fileName) {\n const ext = lowerExt(fileName)\n return ext === 'fig' || ext === 'jam'\n },\n async readDocument(input) {\n const data = input.data.slice().buffer\n const graph = await parseFigFile(data, { populate: 'first-page' })\n return { graph, sourceFormat: 'fig' }\n },\n async writeDocument(graph, options?: FigWriteOptions, context?: IOContext) {\n return writeFig(graph, options, context, options?.thumbnailPageId)\n },\n async exportContent(request, options?: FigWriteOptions, context?: IOContext) {\n // A whole document is written as it is, so one opened from an archive keeps that archive.\n if (request.target.scope === 'document')\n return writeFig(request.graph, options, context, options?.thumbnailPageId, request.fileName)\n const extracted = extractExportGraph(request.graph, request.target)\n return writeFig(\n extracted.graph,\n options,\n context,\n options?.thumbnailPageId ?? extracted.pageId ?? undefined,\n request.fileName\n )\n }\n}\n\n/** A `.fig` named as asked, or else after the file it is written to, or else Untitled. */\nasync function writeFig(\n graph: SceneGraph,\n options: FigWriteOptions | undefined,\n context: IOContext | undefined,\n pageId: string | undefined,\n fileName?: string\n): Promise<ExportResult> {\n const data = await exportFigFile(graph, {\n ck: context?.canvasKit,\n renderer: context?.renderer,\n pageId,\n renderHeadlessThumbnail: options?.renderThumbnail ?? false,\n documentName: options?.documentName ?? (fileName && filename(fileName))\n })\n const extension = DOCUMENT_EXTENSIONS[graph.documentKind]\n return { format: 'fig', mimeType: 'application/octet-stream', extension, data }\n}\n\nexport const drawioFormat: IOFormatAdapter<'drawio'> = {\n id: 'drawio',\n label: 'draw.io Diagram',\n role: 'interchange-document',\n category: 'document',\n extensions: ['drawio', 'dio'],\n mimeTypes: ['application/vnd.jgraph.mxfile'],\n support: {\n readDocument: true,\n writeDocument: true,\n exportDocument: true,\n exportPage: true,\n exportSelection: true,\n exportNode: true\n },\n exportOptions: FIXED_SIZE_EXPORT,\n laysOutOnRead: true,\n // A draw.io PNG or SVG export opens as its diagram when its name says it is one.\n matchesFile(fileName, mimeType) {\n const ext = lowerExt(fileName)\n return (\n ext === 'drawio' ||\n ext === 'dio' ||\n isDrawIOExportFileName(fileName) ||\n mimeType === 'application/vnd.jgraph.mxfile'\n )\n },\n async readDocument(input) {\n const { readDrawIOBytes } = await import('@pairdraw/drawio')\n const { drawioToSceneGraph } = await import('./formats/drawio')\n const file = readDrawIOBytes(input.data)\n if (!file) throw new Error('This file holds no draw.io diagram')\n if (file.unreadable.length > 0) {\n throw new Error(`Could not read the draw.io pages ${file.unreadable.join(', ')}`)\n }\n const graph = drawioToSceneGraph(file)\n // draw.io stores label text, not the sizes it lays out to.\n layoutAuthoredNodes(\n graph,\n graph.getPages().map((page) => page.id)\n )\n return { graph, sourceFormat: 'drawio' }\n },\n async writeDocument(graph) {\n const pageIds = graph.getPages().map((page) => page.id)\n return writeDrawIO(graph, { pageIds })\n },\n // A page or a selection goes as a one-page diagram; the document, every page.\n async exportContent(request) {\n if (request.target.scope === 'document') {\n const pageIds = request.graph.getPages().map((page) => page.id)\n return writeDrawIO(request.graph, { pageIds })\n }\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n return writeDrawIO(request.graph, target)\n }\n}\n\nexport const mermaidFormat: IOFormatAdapter<'mermaid'> = {\n id: 'mermaid',\n label: 'Mermaid Diagram',\n role: 'interchange-document',\n category: 'document',\n extensions: ['mmd', 'mermaid'],\n mimeTypes: ['text/vnd.mermaid'],\n support: {\n readDocument: true\n },\n laysOutOnRead: true,\n matchesFile(fileName, mimeType) {\n const ext = lowerExt(fileName)\n return ext === 'mmd' || ext === 'mermaid' || mimeType === 'text/vnd.mermaid'\n },\n async readDocument(input) {\n const { detectMermaidDiagram } = await import('@pairdraw/mermaid')\n const text = new TextDecoder().decode(input.data)\n if (!detectMermaidDiagram(text)) throw new Error('This file holds no Mermaid flowchart')\n // Mermaid stores a diagram's structure, which reading lays out with its text measured.\n const { mermaidToSceneGraph } = await import('./formats/mermaid')\n return { graph: await mermaidToSceneGraph(text), sourceFormat: 'mermaid' }\n }\n}\n\n/** Pages or layers as a draw.io file, loading the writer only when one is saved. */\nasync function writeDrawIO(graph: SceneGraph, target: DrawIOExportTarget): Promise<ExportResult> {\n const { writeDrawIOFile } = await import('@pairdraw/drawio')\n const { sceneGraphToDrawIO } = await import('./formats/drawio')\n const { drawioDroppedWarnings } = await import('./formats/drawio/warnings')\n return {\n format: 'drawio',\n mimeType: 'application/vnd.jgraph.mxfile',\n extension: 'drawio',\n data: writeDrawIOFile(sceneGraphToDrawIO(graph, target)),\n encoding: 'utf8',\n warnings: drawioDroppedWarnings(graph)\n }\n}\n\nexport const pngFormat = rasterFormat('PNG')\nexport const jpgFormat = rasterFormat('JPG')\nexport const webpFormat = rasterFormat('WEBP')\n\nexport const svgFormat: IOFormatAdapter<'svg'> = {\n id: 'svg',\n label: 'SVG',\n role: 'derived-export',\n category: 'vector',\n extensions: ['svg'],\n mimeTypes: ['image/svg+xml'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: { ...FIXED_SIZE_EXPORT, colorSpace: true },\n async exportContent(request, options?: SVGExportOptions, context?: IOContext) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToLaidOutSVG } = await import('./formats/svg/text/layout')\n const { booleanPathResolver, needsBooleanPaths } = await import('./formats/boolean-path')\n // A boolean made in Pairdraw stores no result path; the export computes it from the operands.\n const booleanPath = needsBooleanPaths(request.graph)\n ? await booleanPathResolver(context?.canvasKit, context?.renderer)\n : undefined\n const data = await renderNodesToLaidOutSVG(\n request.graph,\n target.pageId,\n target.nodeIds,\n {\n ...options,\n // An export writes the profile the document is stored in, so a Display P3 color keeps its\n // gamut; a caller may still ask for sRGB. PDF and thumbnails render SVG themselves and\n // stay sRGB, as their formats expect.\n colorSpace: options?.colorSpace ?? request.graph.documentColorSpace,\n booleanPath\n },\n context?.canvasKit,\n context?.renderer\n )\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'svg',\n mimeType: 'image/svg+xml',\n extension: 'svg',\n data,\n encoding: 'utf8'\n }\n }\n}\n\n/**\n * The PDF pages an export makes. A selection gets a page per layer in the order it lists them,\n * each sized to its layer, as slides and Figma's frame export do, unless `single` asks for one\n * page; a page or a document is one page of its layers unless `frames` asks for a page each.\n */\nasync function pdfPageSpecs(\n request: ExportRequest,\n options: PDFFormatExportOptions | undefined\n): Promise<PDFPageSpec[]> {\n const frames = options?.pages ? options.pages === 'frames' : request.target.scope === 'selection'\n if (frames) {\n const { target } = request\n let ids: string[] | undefined\n if (target.scope === 'selection') ids = target.nodeIds\n else if (target.scope === 'node') ids = [target.nodeId]\n const first = ids?.[0]\n let currentPageId: string | null | undefined\n if (first) currentPageId = findPageId(request.graph, first)\n else if (target.scope === 'page') currentPageId = target.pageId\n else if (target.scope === 'document') currentPageId = request.graph.getPages()[0]?.id\n if (!currentPageId) throw new Error('Nothing to export')\n // Without IDs, the plan takes the page's visible layers, in layer order.\n const { planPDFPages } = await import('./formats/pdf/plan')\n return planPDFPages(request.graph, { mode: 'frames', ids, currentPageId })\n }\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n return [target]\n}\n\nexport const pdfFormat: IOFormatAdapter<'pdf'> = {\n id: 'pdf',\n label: 'PDF',\n role: 'derived-export',\n category: 'vector',\n extensions: ['pdf'],\n mimeTypes: ['application/pdf'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: PDFFormatExportOptions, context?: IOContext) {\n const specs = await pdfPageSpecs(request, options)\n // Embedded, as Figma embeds every face its PDFs draw.\n const { exportPDFDocument } = await import('./formats/pdf/document')\n const data = (\n await exportPDFDocument(\n request.graph,\n specs,\n { embedFonts: true },\n context?.canvasKit,\n context?.renderer\n )\n )?.data\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'pdf',\n mimeType: 'application/pdf',\n extension: 'pdf',\n data\n }\n }\n}\n\n/**\n * Every top-level frame becomes a slide, so a PPTX document export spans all\n * pages — the shared resolver only reaches the first one.\n */\nfunction resolvePPTXExportNodes(\n request: ExportRequest\n): { pageId: string; nodeIds: string[] } | null {\n if (request.target.scope !== 'document') return resolveExportNodes(request)\n const pages = request.graph.getPages()\n if (!pages.length) return null\n return { pageId: pages[0].id, nodeIds: pages.flatMap((page) => page.childIds) }\n}\n\nexport const pptxFormat: IOFormatAdapter<'pptx'> = {\n id: 'pptx',\n label: 'PowerPoint',\n role: 'derived-export',\n category: 'print',\n extensions: ['pptx'],\n mimeTypes: ['application/vnd.openxmlformats-officedocument.presentationml.presentation'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: PPTXExportOptions, context?: IOContext) {\n const target = resolvePPTXExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToPPTX } = await import('./formats/pptx')\n const data = await renderNodesToPPTX(request.graph, target.pageId, target.nodeIds, {\n ...options,\n context: options?.context ?? context\n })\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'pptx',\n mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n extension: 'pptx',\n data\n }\n }\n}\n\nexport const jsxFormat: IOFormatAdapter<'jsx'> = {\n id: 'jsx',\n label: 'JSX',\n role: 'derived-export',\n category: 'code',\n extensions: ['jsx'],\n mimeTypes: ['text/plain', 'text/jsx'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, _options?: unknown, context?: IOContext): Promise<ExportResult> {\n const nodeId = ensureSingleNode(request.target)\n // A page or a document exports its top-level layers, as Tailwind JSX does.\n const target = nodeId ? null : resolveExportNodes(request)\n const { booleanPathResolver, needsBooleanPaths } = await import('./formats/boolean-path')\n const authored = needsBooleanPaths(request.graph)\n ? [...request.graph.getAllNodes()].filter(\n (node) => node.type === 'BOOLEAN_OPERATION' && node.fillGeometry.length === 0\n )\n : []\n const restore: (() => void)[] = []\n if (authored.length > 0) {\n const { parseSVGPath } = await import('@pairdraw/scene-graph/parse-path')\n const booleanPath = await booleanPathResolver(context?.canvasKit, context?.renderer)\n for (const node of authored) {\n const d = booleanPath(request.graph, node)\n if (!d) continue\n const network = parseSVGPath(d, 'EVENODD', { includeOpenRegions: true })\n const carrier = node as typeof node & { vectorNetwork?: typeof network }\n const previous = carrier.vectorNetwork\n carrier.vectorNetwork = network\n restore.push(() => {\n carrier.vectorNetwork = previous\n })\n }\n }\n let data = ''\n try {\n if (nodeId) data = sceneNodeToJSX(nodeId, request.graph)\n else if (target) data = selectionToJSX(target.nodeIds, request.graph)\n } finally {\n for (const undo of restore) undo()\n }\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'jsx',\n mimeType: 'text/plain',\n extension: 'jsx',\n data,\n encoding: 'utf8'\n }\n }\n}\n\nexport const htmlFormat: IOFormatAdapter<'html'> = {\n id: 'html',\n label: 'HTML',\n role: 'derived-export',\n category: 'code',\n extensions: ['html'],\n mimeTypes: ['text/html'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, options?: HTMLExportOptions, context?: IOContext) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { renderNodesToHTML } = await import('./formats/html')\n const { html, assets } = await renderNodesToHTML(\n request.graph,\n target.nodeIds,\n options,\n request.fileName,\n context\n )\n return {\n format: 'html',\n mimeType: 'text/html',\n extension: 'html',\n data: html,\n encoding: 'utf8',\n assets\n }\n }\n}\n\nexport const tailwindJSXFormat: IOFormatAdapter<'tailwind-jsx'> = {\n id: 'tailwind-jsx',\n label: 'Tailwind JSX',\n role: 'derived-export',\n category: 'code',\n extensions: ['jsx'],\n mimeTypes: ['text/plain', 'text/jsx'],\n support: EXPORT_EVERY_TARGET,\n exportOptions: FIXED_SIZE_EXPORT,\n async exportContent(request, _options?: unknown, context?: IOContext) {\n const target = resolveExportNodes(request)\n if (!target) throw new Error('Nothing to export')\n const { sceneNodesToTailwindJSX } = await import('@pairdraw/dom-css/export')\n const { vectorElement } = await import('#core/io/formats/html/vectors')\n const { booleanPathResolver, needsBooleanPaths } = await import('./formats/boolean-path')\n const booleanPath = needsBooleanPaths(request.graph)\n ? await booleanPathResolver(context?.canvasKit, context?.renderer)\n : undefined\n const data = sceneNodesToTailwindJSX(request.graph, target.nodeIds, {\n vectorElement: (graph, node) => vectorElement(graph, node, booleanPath)\n })\n if (!data) throw new Error('Nothing to export')\n return {\n format: 'tailwind-jsx',\n mimeType: 'text/plain',\n extension: 'jsx',\n data,\n encoding: 'utf8'\n }\n }\n}\n\nexport { penFormat }\n\nexport const BUILTIN_IO_FORMATS = [\n figFormat,\n penFormat,\n drawioFormat,\n mermaidFormat,\n pngFormat,\n jpgFormat,\n webpFormat,\n svgFormat,\n pdfFormat,\n pptxFormat,\n jsxFormat,\n tailwindJSXFormat,\n htmlFormat\n] as const satisfies readonly IOFormatAdapter[]\n\nexport type BuiltinIOFormatId = (typeof BUILTIN_IO_FORMATS)[number]['id']\n"],"mappings":";;;;;;;;;;;;AA8BA,MAAM,sBAAuC;CAC3C,gBAAgB;CAChB,YAAY;CACZ,iBAAiB;CACjB,YAAY;AACd;;AAGA,MAAM,oBAA2C;CAAE,OAAO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e;EACf,OAAO;EACP;EACA;;
|
|
1
|
+
{"version":3,"file":"subgraph.d.ts","names":[],"sources":["../../src/io/subgraph.ts"],"mappings":";;;UAMiB;;EAEf;;;;;EAKA;;UAGe;EACf,OAAO;EACP;EACA;;iBA0Nc,WAAW,QAAQ,YAAY;;iBAY/B,gBAAgB,QAAQ,YAAY;;;;;iBAkEpC,mBACd,QAAQ,YACR,oCACA,4BACA,UAAS,iBACR;iBAMa,mBAAmB,QAAQ,YAAY,QAAQ,eAAe"}
|
package/dist/io/subgraph.js
CHANGED
|
@@ -91,7 +91,7 @@ function copyReferencedTables(source, graph) {
|
|
|
91
91
|
...structuredClone(collection),
|
|
92
92
|
variableIds: []
|
|
93
93
|
});
|
|
94
|
-
graph.variableCollections.get(collection.id)?.variableIds.push(variableId);
|
|
94
|
+
if (!variable.deleted) graph.variableCollections.get(collection.id)?.variableIds.push(variableId);
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
97
|
function collectReferencedResources(source, graph) {
|
package/dist/io/subgraph.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subgraph.js","names":[],"sources":["../../src/io/subgraph.ts"],"sourcesContent":["import { SceneGraph } from '@pairdraw/scene-graph'\nimport { styleRunReferences } from '@pairdraw/scene-graph/text'\nimport { resolvedVariableModes, variableValueReferences } from '@pairdraw/scene-graph/variables'\n\nimport type { ExportTarget } from './types'\n\nexport interface ExtractOptions {\n /** Every variant of an instance's set, not only its main component, so it can switch variant. */\n componentSets?: boolean\n /**\n * Use the source's variables, collections, and images instead of copies, for a read-only view\n * rebuilt often, such as preview's. A copy may change its tables without touching the source.\n */\n shareTables?: boolean\n}\n\nexport interface ExtractedGraph {\n graph: SceneGraph\n pageId: string | null\n nodeIds: string[]\n}\n\nfunction includeReferencedStyles(source: SceneGraph, ids: Set<string>): void {\n const referencedStyleIds = new Set<string>()\n for (const id of ids) {\n const node = source.getNode(id)\n if (!node) continue\n for (const styleId of [\n node.fillStyleId,\n node.strokeStyleId,\n node.textStyleId,\n node.effectStyleId,\n node.gridStyleId,\n ...styleRunReferences(node.styleRuns).styles\n ]) {\n if (styleId) referencedStyleIds.add(styleId)\n }\n }\n // Style definitions can sit anywhere in the document; only layers that use one need the search.\n if (referencedStyleIds.size === 0) return\n for (const node of source.getAllNodes()) {\n if (node.sharedStyleType && node.source.id && referencedStyleIds.has(node.source.id)) {\n ids.add(node.id)\n }\n }\n}\n\nfunction cloneIntoGraph(\n source: SceneGraph,\n ids: Set<string>,\n { shareTables = false }: ExtractOptions = {}\n): SceneGraph {\n const graph = new SceneGraph()\n graph.rootId = source.rootId\n graph.nodes = new Map()\n graph.images = new Map()\n graph.variables = new Map()\n graph.variableCollections = new Map()\n graph.activeMode = new Map(source.activeMode)\n graph.figKiwiVersion = source.figKiwiVersion\n graph.figSchemaDeflated = source.figSchemaDeflated\n graph.documentColorSpace = source.documentColorSpace\n graph.documentKind = source.documentKind\n\n includeReferencedStyles(source, ids)\n\n const sortedIds = [...ids].sort((a, b) => {\n if (a === source.rootId) return -1\n if (b === source.rootId) return 1\n const aNode = source.getNode(a)\n const bNode = source.getNode(b)\n const aDepth = depthOf(source, aNode)\n const bDepth = depthOf(source, bNode)\n return aDepth - bDepth\n })\n\n for (const id of sortedIds) {\n const node = source.getNode(id)\n if (!node) continue\n const copy = structuredClone(node)\n graph.nodes.set(id, copy)\n // Syncing and swapping find an instance through its component's index.\n if (copy.type === 'INSTANCE' && copy.componentId) {\n const instances = graph.instanceIndex.get(copy.componentId) ?? new Set<string>()\n instances.add(id)\n graph.instanceIndex.set(copy.componentId, instances)\n }\n if (copy.type === 'CONNECTOR') graph.connectorIds.add(id)\n }\n\n const rootClone = graph.getNode(source.rootId)\n if (rootClone) {\n rootClone.parentId = null\n rootClone.childIds = rootClone.childIds.filter((id) => ids.has(id))\n }\n\n for (const id of sortedIds) {\n if (id === source.rootId) continue\n const node = graph.getNode(id)\n if (!node) continue\n if (!node.parentId || !ids.has(node.parentId)) {\n node.parentId = source.rootId\n // The ancestor that set a mode is not in the copy, so the node keeps what it inherited.\n node.variableModes = resolvedVariableModes(source, id)\n }\n node.childIds = node.childIds.filter((childId) => ids.has(childId))\n }\n\n if (shareTables) {\n graph.images = source.images\n graph.variables = source.variables\n graph.variableCollections = source.variableCollections\n } else copyReferencedTables(source, graph)\n\n graph.clearAbsPosCache()\n return graph\n}\n\n/** The images and variables the copied layers use, with their collections, copied in. */\nfunction copyReferencedTables(source: SceneGraph, graph: SceneGraph): void {\n const { imageHashes, variableIds } = collectReferencedResources(source, graph)\n\n for (const imageHash of imageHashes) {\n const image = source.images.get(imageHash)\n if (image) graph.images.set(imageHash, image)\n }\n\n for (const variableId of variableIds) {\n const variable = source.variables.get(variableId)\n if (!variable) continue\n graph.variables.set(variableId, structuredClone(variable))\n const collection = source.variableCollections.get(variable.collectionId)\n if (!collection) continue\n const existing = graph.variableCollections.get(collection.id)\n if (!existing) {\n graph.variableCollections.set(collection.id, {\n ...structuredClone(collection),\n variableIds: []\n })\n }\n graph.variableCollections.get(collection.id)?.variableIds.push(variableId)\n }\n}\n\nfunction collectReferencedResources(source: SceneGraph, graph: SceneGraph) {\n const imageHashes = new Set<string>()\n const variableIds = new Set<string>()\n for (const node of graph.nodes.values()) {\n for (const fill of node.fills) {\n if (fill.type === 'IMAGE' && fill.imageHash) imageHashes.add(fill.imageHash)\n }\n const bound = [\n ...Object.values(node.boundVariables),\n ...styleRunReferences(node.styleRuns).variables\n ]\n for (const variableId of bound) collectVariableClosure(source, variableId, variableIds)\n }\n return { imageHashes, variableIds }\n}\n\nfunction collectVariableClosure(source: SceneGraph, variableId: string, out: Set<string>) {\n if (out.has(variableId)) return\n const variable = source.variables.get(variableId)\n if (!variable) return\n out.add(variableId)\n for (const value of Object.values(variable.valuesByMode)) {\n for (const id of variableValueReferences(value)) collectVariableClosure(source, id, out)\n }\n}\n\nfunction depthOf(source: SceneGraph, node: ReturnType<SceneGraph['getNode']>): number {\n let depth = 0\n let current = node\n while (current?.parentId) {\n depth += 1\n current = source.getNode(current.parentId)\n }\n return depth\n}\n\nfunction collectDescendants(source: SceneGraph, id: string, out: Set<string>) {\n if (out.has(id)) return\n out.add(id)\n const node = source.getNode(id)\n if (!node) return\n for (const childId of node.childIds) {\n collectDescendants(source, childId, out)\n }\n}\n\nfunction collectAncestors(source: SceneGraph, id: string, out: Set<string>) {\n let current = source.getNode(id)\n while (current?.parentId) {\n out.add(current.parentId)\n current = source.getNode(current.parentId)\n }\n}\n\nfunction resolveInstanceComponentId(source: SceneGraph, componentId: string): string {\n const seen = new Set<string>()\n let currentId = componentId\n while (!seen.has(currentId)) {\n seen.add(currentId)\n const node = source.getNode(currentId)\n if (node?.type !== 'INSTANCE' || !node.componentId) return currentId\n currentId = node.componentId\n }\n return componentId\n}\n\nfunction collectComponentDependencies(\n source: SceneGraph,\n ids: Set<string>,\n { componentSets = false }: ExtractOptions = {}\n) {\n let changed = true\n while (changed) {\n changed = false\n for (const id of Array.from(ids)) {\n const node = source.getNode(id)\n if (node?.type !== 'INSTANCE' || !node.componentId) continue\n const componentId = resolveInstanceComponentId(source, node.componentId)\n const component = source.getNode(componentId)\n const set = component?.parentId ? source.getNode(component.parentId) : undefined\n const dependency = componentSets && set?.type === 'COMPONENT_SET' ? set.id : componentId\n if (ids.has(dependency)) continue\n const before = ids.size\n collectAncestors(source, dependency, ids)\n collectDescendants(source, dependency, ids)\n changed ||= ids.size !== before\n }\n }\n}\n\nexport function findPageId(source: SceneGraph, nodeId: string): string | null {\n let current = source.getNode(nodeId)\n while (current?.parentId) {\n const parent = source.getNode(current.parentId)\n if (!parent) return null\n if (parent.type === 'CANVAS') return parent.id\n current = parent\n }\n return current?.type === 'CANVAS' ? current.id : null\n}\n\n/** The page child containing `nodeId`, or the node itself when it is a page child. */\nexport function findPageChildId(source: SceneGraph, nodeId: string): string | null {\n let current = source.getNode(nodeId)\n while (current?.parentId) {\n const parent = source.getNode(current.parentId)\n if (parent?.type === 'CANVAS') return current.id\n current = parent\n }\n return null\n}\n\nfunction ancestorChain(source: SceneGraph, id: string): string[] {\n const chain: string[] = []\n let current = source.getNode(id)\n while (current?.parentId) {\n chain.push(current.parentId)\n current = source.getNode(current.parentId)\n }\n return chain.reverse()\n}\n\nfunction collectSelectionIds(\n source: SceneGraph,\n nodeIds: readonly string[],\n options: ExtractOptions = {}\n): Set<string> {\n const ids = new Set<string>([source.rootId])\n const pageIds = new Set<string>()\n\n for (const nodeId of nodeIds) {\n const node = source.getNode(nodeId)\n if (!node) continue\n for (const ancestorId of ancestorChain(source, nodeId)) {\n ids.add(ancestorId)\n const ancestor = source.getNode(ancestorId)\n if (ancestor?.type === 'CANVAS') pageIds.add(ancestorId)\n }\n collectDescendants(source, nodeId, ids)\n }\n\n for (const pageId of pageIds) {\n ids.add(pageId)\n }\n\n collectComponentDependencies(source, ids, options)\n return ids\n}\n\nfunction pageNodeIds(source: SceneGraph, pageId: string): Set<string> {\n const ids = new Set<string>([source.rootId])\n collectDescendants(source, pageId, ids)\n collectComponentDependencies(source, ids)\n return ids\n}\n\nfunction rootNodeIds(source: SceneGraph): Set<string> {\n const ids = new Set<string>()\n for (const node of source.nodes.values()) {\n ids.add(node.id)\n }\n return ids\n}\n\n/**\n * Clone `pageId`, or each of several pages, with only the subtrees of `nodeIds` (none keeps an\n * empty page) and their dependencies.\n */\nexport function extractPageContext(\n source: SceneGraph,\n pageId: string | readonly string[],\n nodeIds: readonly string[],\n options: ExtractOptions = {}\n): SceneGraph {\n const ids = collectSelectionIds(source, nodeIds, options)\n for (const id of typeof pageId === 'string' ? [pageId] : pageId) ids.add(id)\n return cloneIntoGraph(source, ids, options)\n}\n\nexport function extractExportGraph(source: SceneGraph, target: ExportTarget): ExtractedGraph {\n switch (target.scope) {\n case 'document': {\n const graph = cloneIntoGraph(source, rootNodeIds(source))\n return {\n graph,\n pageId: graph.getPages()[0]?.id ?? null,\n nodeIds: graph.getPages()[0]?.childIds ?? []\n }\n }\n case 'page': {\n const graph = cloneIntoGraph(source, pageNodeIds(source, target.pageId))\n const page = graph.getNode(target.pageId)\n return {\n graph,\n pageId: page?.id ?? null,\n nodeIds: page?.childIds ?? []\n }\n }\n case 'selection': {\n const graph = cloneIntoGraph(source, collectSelectionIds(source, target.nodeIds))\n const firstId = target.nodeIds[0]\n const first = firstId ? source.getNode(firstId) : undefined\n const pageId = first\n ? (ancestorChain(source, first.id).find((id) => source.getNode(id)?.type === 'CANVAS') ??\n null)\n : null\n return {\n graph,\n pageId,\n nodeIds: target.nodeIds.filter((id) => graph.getNode(id) !== undefined)\n }\n }\n case 'node':\n return extractExportGraph(source, { scope: 'selection', nodeIds: [target.nodeId] })\n default:\n return extractExportGraph(source, { scope: 'document' })\n }\n}\n"],"mappings":";;;;AAsBA,SAAS,wBAAwB,QAAoB,KAAwB;CAC3E,MAAM,qCAAqB,IAAI,IAAY;CAC3C,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,OAAO,OAAO,QAAQ,EAAE;EAC9B,IAAI,CAAC,MAAM;EACX,KAAK,MAAM,WAAW;GACpB,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK;GACL,GAAG,mBAAmB,KAAK,SAAS,CAAC,CAAC;EACxC,GACE,IAAI,SAAS,mBAAmB,IAAI,OAAO;CAE/C;CAEA,IAAI,mBAAmB,SAAS,GAAG;CACnC,KAAK,MAAM,QAAQ,OAAO,YAAY,GACpC,IAAI,KAAK,mBAAmB,KAAK,OAAO,MAAM,mBAAmB,IAAI,KAAK,OAAO,EAAE,GACjF,IAAI,IAAI,KAAK,EAAE;AAGrB;AAEA,SAAS,eACP,QACA,KACA,EAAE,cAAc,UAA0B,CAAC,GAC/B;CACZ,MAAM,QAAQ,IAAI,WAAW;CAC7B,MAAM,SAAS,OAAO;CACtB,MAAM,wBAAQ,IAAI,IAAI;CACtB,MAAM,yBAAS,IAAI,IAAI;CACvB,MAAM,4BAAY,IAAI,IAAI;CAC1B,MAAM,sCAAsB,IAAI,IAAI;CACpC,MAAM,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IAAI,EAAE;CAC3E,OAAO,eAAe,QAAQ,KAAK,OAAO;AAC5C;AAEA,SAAgB,mBAAmB,QAAoB,QAAsC;CAC3F,QAAQ,OAAO,OAAf;EACE,KAAK,YAAY;GACf,MAAM,QAAQ,eAAe,QAAQ,YAAY,MAAM,CAAC;GACxD,OAAO;IACL;IACA,QAAQ,MAAM,SAAS,CAAC,CAAC,EAAE,EAAE,MAAM;IACnC,SAAS,MAAM,SAAS,CAAC,CAAC,EAAE,EAAE,YAAY,CAAC;GAC7C;EACF;EACA,KAAK,QAAQ;GACX,MAAM,QAAQ,eAAe,QAAQ,YAAY,QAAQ,OAAO,MAAM,CAAC;GACvE,MAAM,OAAO,MAAM,QAAQ,OAAO,MAAM;GACxC,OAAO;IACL;IACA,QAAQ,MAAM,MAAM;IACpB,SAAS,MAAM,YAAY,CAAC;GAC9B;EACF;EACA,KAAK,aAAa;GAChB,MAAM,QAAQ,eAAe,QAAQ,oBAAoB,QAAQ,OAAO,OAAO,CAAC;GAChF,MAAM,UAAU,OAAO,QAAQ;GAC/B,MAAM,QAAQ,UAAU,OAAO,QAAQ,OAAO,IAAI,KAAA;GAKlD,OAAO;IACL;IACA,QANa,QACV,cAAc,QAAQ,MAAM,EAAE,CAAC,CAAC,MAAM,OAAO,OAAO,QAAQ,EAAE,CAAC,EAAE,SAAS,QAAQ,KACnF,OACA;IAIF,SAAS,OAAO,QAAQ,QAAQ,OAAO,MAAM,QAAQ,EAAE,MAAM,KAAA,CAAS;GACxE;EACF;EACA,KAAK,QACH,OAAO,mBAAmB,QAAQ;GAAE,OAAO;GAAa,SAAS,CAAC,OAAO,MAAM;EAAE,CAAC;EACpF,SACE,OAAO,mBAAmB,QAAQ,EAAE,OAAO,WAAW,CAAC;CAC3D;AACF"}
|
|
1
|
+
{"version":3,"file":"subgraph.js","names":[],"sources":["../../src/io/subgraph.ts"],"sourcesContent":["import { SceneGraph } from '@pairdraw/scene-graph'\nimport { styleRunReferences } from '@pairdraw/scene-graph/text'\nimport { resolvedVariableModes, variableValueReferences } from '@pairdraw/scene-graph/variables'\n\nimport type { ExportTarget } from './types'\n\nexport interface ExtractOptions {\n /** Every variant of an instance's set, not only its main component, so it can switch variant. */\n componentSets?: boolean\n /**\n * Use the source's variables, collections, and images instead of copies, for a read-only view\n * rebuilt often, such as preview's. A copy may change its tables without touching the source.\n */\n shareTables?: boolean\n}\n\nexport interface ExtractedGraph {\n graph: SceneGraph\n pageId: string | null\n nodeIds: string[]\n}\n\nfunction includeReferencedStyles(source: SceneGraph, ids: Set<string>): void {\n const referencedStyleIds = new Set<string>()\n for (const id of ids) {\n const node = source.getNode(id)\n if (!node) continue\n for (const styleId of [\n node.fillStyleId,\n node.strokeStyleId,\n node.textStyleId,\n node.effectStyleId,\n node.gridStyleId,\n ...styleRunReferences(node.styleRuns).styles\n ]) {\n if (styleId) referencedStyleIds.add(styleId)\n }\n }\n // Style definitions can sit anywhere in the document; only layers that use one need the search.\n if (referencedStyleIds.size === 0) return\n for (const node of source.getAllNodes()) {\n if (node.sharedStyleType && node.source.id && referencedStyleIds.has(node.source.id)) {\n ids.add(node.id)\n }\n }\n}\n\nfunction cloneIntoGraph(\n source: SceneGraph,\n ids: Set<string>,\n { shareTables = false }: ExtractOptions = {}\n): SceneGraph {\n const graph = new SceneGraph()\n graph.rootId = source.rootId\n graph.nodes = new Map()\n graph.images = new Map()\n graph.variables = new Map()\n graph.variableCollections = new Map()\n graph.activeMode = new Map(source.activeMode)\n graph.figKiwiVersion = source.figKiwiVersion\n graph.figSchemaDeflated = source.figSchemaDeflated\n graph.documentColorSpace = source.documentColorSpace\n graph.documentKind = source.documentKind\n\n includeReferencedStyles(source, ids)\n\n const sortedIds = [...ids].sort((a, b) => {\n if (a === source.rootId) return -1\n if (b === source.rootId) return 1\n const aNode = source.getNode(a)\n const bNode = source.getNode(b)\n const aDepth = depthOf(source, aNode)\n const bDepth = depthOf(source, bNode)\n return aDepth - bDepth\n })\n\n for (const id of sortedIds) {\n const node = source.getNode(id)\n if (!node) continue\n const copy = structuredClone(node)\n graph.nodes.set(id, copy)\n // Syncing and swapping find an instance through its component's index.\n if (copy.type === 'INSTANCE' && copy.componentId) {\n const instances = graph.instanceIndex.get(copy.componentId) ?? new Set<string>()\n instances.add(id)\n graph.instanceIndex.set(copy.componentId, instances)\n }\n if (copy.type === 'CONNECTOR') graph.connectorIds.add(id)\n }\n\n const rootClone = graph.getNode(source.rootId)\n if (rootClone) {\n rootClone.parentId = null\n rootClone.childIds = rootClone.childIds.filter((id) => ids.has(id))\n }\n\n for (const id of sortedIds) {\n if (id === source.rootId) continue\n const node = graph.getNode(id)\n if (!node) continue\n if (!node.parentId || !ids.has(node.parentId)) {\n node.parentId = source.rootId\n // The ancestor that set a mode is not in the copy, so the node keeps what it inherited.\n node.variableModes = resolvedVariableModes(source, id)\n }\n node.childIds = node.childIds.filter((childId) => ids.has(childId))\n }\n\n if (shareTables) {\n graph.images = source.images\n graph.variables = source.variables\n graph.variableCollections = source.variableCollections\n } else copyReferencedTables(source, graph)\n\n graph.clearAbsPosCache()\n return graph\n}\n\n/** The images and variables the copied layers use, with their collections, copied in. */\nfunction copyReferencedTables(source: SceneGraph, graph: SceneGraph): void {\n const { imageHashes, variableIds } = collectReferencedResources(source, graph)\n\n for (const imageHash of imageHashes) {\n const image = source.images.get(imageHash)\n if (image) graph.images.set(imageHash, image)\n }\n\n for (const variableId of variableIds) {\n const variable = source.variables.get(variableId)\n if (!variable) continue\n graph.variables.set(variableId, structuredClone(variable))\n const collection = source.variableCollections.get(variable.collectionId)\n if (!collection) continue\n const existing = graph.variableCollections.get(collection.id)\n if (!existing) {\n graph.variableCollections.set(collection.id, {\n ...structuredClone(collection),\n variableIds: []\n })\n }\n // A collection lists its live variables; a deleted one is copied out of the list (addVariable).\n if (!variable.deleted) {\n graph.variableCollections.get(collection.id)?.variableIds.push(variableId)\n }\n }\n}\n\nfunction collectReferencedResources(source: SceneGraph, graph: SceneGraph) {\n const imageHashes = new Set<string>()\n const variableIds = new Set<string>()\n for (const node of graph.nodes.values()) {\n for (const fill of node.fills) {\n if (fill.type === 'IMAGE' && fill.imageHash) imageHashes.add(fill.imageHash)\n }\n const bound = [\n ...Object.values(node.boundVariables),\n ...styleRunReferences(node.styleRuns).variables\n ]\n for (const variableId of bound) collectVariableClosure(source, variableId, variableIds)\n }\n return { imageHashes, variableIds }\n}\n\nfunction collectVariableClosure(source: SceneGraph, variableId: string, out: Set<string>) {\n if (out.has(variableId)) return\n const variable = source.variables.get(variableId)\n if (!variable) return\n out.add(variableId)\n for (const value of Object.values(variable.valuesByMode)) {\n for (const id of variableValueReferences(value)) collectVariableClosure(source, id, out)\n }\n}\n\nfunction depthOf(source: SceneGraph, node: ReturnType<SceneGraph['getNode']>): number {\n let depth = 0\n let current = node\n while (current?.parentId) {\n depth += 1\n current = source.getNode(current.parentId)\n }\n return depth\n}\n\nfunction collectDescendants(source: SceneGraph, id: string, out: Set<string>) {\n if (out.has(id)) return\n out.add(id)\n const node = source.getNode(id)\n if (!node) return\n for (const childId of node.childIds) {\n collectDescendants(source, childId, out)\n }\n}\n\nfunction collectAncestors(source: SceneGraph, id: string, out: Set<string>) {\n let current = source.getNode(id)\n while (current?.parentId) {\n out.add(current.parentId)\n current = source.getNode(current.parentId)\n }\n}\n\nfunction resolveInstanceComponentId(source: SceneGraph, componentId: string): string {\n const seen = new Set<string>()\n let currentId = componentId\n while (!seen.has(currentId)) {\n seen.add(currentId)\n const node = source.getNode(currentId)\n if (node?.type !== 'INSTANCE' || !node.componentId) return currentId\n currentId = node.componentId\n }\n return componentId\n}\n\nfunction collectComponentDependencies(\n source: SceneGraph,\n ids: Set<string>,\n { componentSets = false }: ExtractOptions = {}\n) {\n let changed = true\n while (changed) {\n changed = false\n for (const id of Array.from(ids)) {\n const node = source.getNode(id)\n if (node?.type !== 'INSTANCE' || !node.componentId) continue\n const componentId = resolveInstanceComponentId(source, node.componentId)\n const component = source.getNode(componentId)\n const set = component?.parentId ? source.getNode(component.parentId) : undefined\n const dependency = componentSets && set?.type === 'COMPONENT_SET' ? set.id : componentId\n if (ids.has(dependency)) continue\n const before = ids.size\n collectAncestors(source, dependency, ids)\n collectDescendants(source, dependency, ids)\n changed ||= ids.size !== before\n }\n }\n}\n\nexport function findPageId(source: SceneGraph, nodeId: string): string | null {\n let current = source.getNode(nodeId)\n while (current?.parentId) {\n const parent = source.getNode(current.parentId)\n if (!parent) return null\n if (parent.type === 'CANVAS') return parent.id\n current = parent\n }\n return current?.type === 'CANVAS' ? current.id : null\n}\n\n/** The page child containing `nodeId`, or the node itself when it is a page child. */\nexport function findPageChildId(source: SceneGraph, nodeId: string): string | null {\n let current = source.getNode(nodeId)\n while (current?.parentId) {\n const parent = source.getNode(current.parentId)\n if (parent?.type === 'CANVAS') return current.id\n current = parent\n }\n return null\n}\n\nfunction ancestorChain(source: SceneGraph, id: string): string[] {\n const chain: string[] = []\n let current = source.getNode(id)\n while (current?.parentId) {\n chain.push(current.parentId)\n current = source.getNode(current.parentId)\n }\n return chain.reverse()\n}\n\nfunction collectSelectionIds(\n source: SceneGraph,\n nodeIds: readonly string[],\n options: ExtractOptions = {}\n): Set<string> {\n const ids = new Set<string>([source.rootId])\n const pageIds = new Set<string>()\n\n for (const nodeId of nodeIds) {\n const node = source.getNode(nodeId)\n if (!node) continue\n for (const ancestorId of ancestorChain(source, nodeId)) {\n ids.add(ancestorId)\n const ancestor = source.getNode(ancestorId)\n if (ancestor?.type === 'CANVAS') pageIds.add(ancestorId)\n }\n collectDescendants(source, nodeId, ids)\n }\n\n for (const pageId of pageIds) {\n ids.add(pageId)\n }\n\n collectComponentDependencies(source, ids, options)\n return ids\n}\n\nfunction pageNodeIds(source: SceneGraph, pageId: string): Set<string> {\n const ids = new Set<string>([source.rootId])\n collectDescendants(source, pageId, ids)\n collectComponentDependencies(source, ids)\n return ids\n}\n\nfunction rootNodeIds(source: SceneGraph): Set<string> {\n const ids = new Set<string>()\n for (const node of source.nodes.values()) {\n ids.add(node.id)\n }\n return ids\n}\n\n/**\n * Clone `pageId`, or each of several pages, with only the subtrees of `nodeIds` (none keeps an\n * empty page) and their dependencies.\n */\nexport function extractPageContext(\n source: SceneGraph,\n pageId: string | readonly string[],\n nodeIds: readonly string[],\n options: ExtractOptions = {}\n): SceneGraph {\n const ids = collectSelectionIds(source, nodeIds, options)\n for (const id of typeof pageId === 'string' ? [pageId] : pageId) ids.add(id)\n return cloneIntoGraph(source, ids, options)\n}\n\nexport function extractExportGraph(source: SceneGraph, target: ExportTarget): ExtractedGraph {\n switch (target.scope) {\n case 'document': {\n const graph = cloneIntoGraph(source, rootNodeIds(source))\n return {\n graph,\n pageId: graph.getPages()[0]?.id ?? null,\n nodeIds: graph.getPages()[0]?.childIds ?? []\n }\n }\n case 'page': {\n const graph = cloneIntoGraph(source, pageNodeIds(source, target.pageId))\n const page = graph.getNode(target.pageId)\n return {\n graph,\n pageId: page?.id ?? null,\n nodeIds: page?.childIds ?? []\n }\n }\n case 'selection': {\n const graph = cloneIntoGraph(source, collectSelectionIds(source, target.nodeIds))\n const firstId = target.nodeIds[0]\n const first = firstId ? source.getNode(firstId) : undefined\n const pageId = first\n ? (ancestorChain(source, first.id).find((id) => source.getNode(id)?.type === 'CANVAS') ??\n null)\n : null\n return {\n graph,\n pageId,\n nodeIds: target.nodeIds.filter((id) => graph.getNode(id) !== undefined)\n }\n }\n case 'node':\n return extractExportGraph(source, { scope: 'selection', nodeIds: [target.nodeId] })\n default:\n return extractExportGraph(source, { scope: 'document' })\n }\n}\n"],"mappings":";;;;AAsBA,SAAS,wBAAwB,QAAoB,KAAwB;CAC3E,MAAM,qCAAqB,IAAI,IAAY;CAC3C,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,OAAO,OAAO,QAAQ,EAAE;EAC9B,IAAI,CAAC,MAAM;EACX,KAAK,MAAM,WAAW;GACpB,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK;GACL,GAAG,mBAAmB,KAAK,SAAS,CAAC,CAAC;EACx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;IACL;IACA,QANa,QACV,cAAc,QAAQ,MAAM,EAAE,CAAC,CAAC,MAAM,OAAO,OAAO,QAAQ,EAAE,CAAC,EAAE,SAAS,QAAQ,KACnF,OACA;IAIF,SAAS,OAAO,QAAQ,QAAQ,OAAO,MAAM,QAAQ,EAAE,MAAM,KAAA,CAAS;GACxE;EACF;EACA,KAAK,QACH,OAAO,mBAAmB,QAAQ;GAAE,OAAO;GAAa,SAAS,CAAC,OAAO,MAAM;EAAE,CAAC;EACpF,SACE,OAAO,mBAAmB,QAAQ,EAAE,OAAO,WAAW,CAAC;CAC3D;AACF"}
|
package/dist/io/types.d.ts
CHANGED
|
@@ -5,8 +5,8 @@ import "../icons/index.js";
|
|
|
5
5
|
import { RasterExportFormat } from "./formats/raster/render.js";
|
|
6
6
|
import "./formats/raster/index.js";
|
|
7
7
|
import { CanvasKit } from "canvaskit-wasm";
|
|
8
|
-
import { SceneGraph } from "@pairdraw/scene-graph";
|
|
9
8
|
import { RenderColorSpace } from "@pairdraw/scene-graph/color";
|
|
9
|
+
import { SceneGraph } from "@pairdraw/scene-graph";
|
|
10
10
|
import { TailwindStylesheetLoader } from "@pairdraw/dom-css/export";
|
|
11
11
|
//#region src/io/types.d.ts
|
|
12
12
|
type IOFormatRole = 'native-document' | 'interchange-document' | 'derived-export';
|
|
@@ -20,6 +20,9 @@ type FigReaderDiagnostic = {
|
|
|
20
20
|
} | {
|
|
21
21
|
kind: 'slot-content';
|
|
22
22
|
diagnostic: Parameters<Handler<'onMissingSlotContent'>>[0];
|
|
23
|
+
} | {
|
|
24
|
+
kind: 'variable-type';
|
|
25
|
+
diagnostic: Parameters<Handler<'onUnsupportedVariableType'>>[0];
|
|
23
26
|
};
|
|
24
27
|
/**
|
|
25
28
|
* Figma retains override and binding records that address nodes it later deleted, and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.d.ts","names":[],"sources":["../../../../src/kiwi/fig/session/options.ts"],"mappings":";;KAEK,QAAQ,gBAAgB,2BAA2B,YAAY,wBAAwB;;KAGhF;EACN;EAAkB,YAAY,WAAW;;EACzC;EAAoB,YAAY,WAAW;;EAC3C;EAAiB,YAAY,WAAW;;EAExC;EACA,YAAY,WAAW;;EAEvB;EAAmB,YAAY,WAAW;;EAC1C;EAAsB,YAAY,WAAW;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"options.d.ts","names":[],"sources":["../../../../src/kiwi/fig/session/options.ts"],"mappings":";;KAEK,QAAQ,gBAAgB,2BAA2B,YAAY,wBAAwB;;KAGhF;EACN;EAAkB,YAAY,WAAW;;EACzC;EAAoB,YAAY,WAAW;;EAC3C;EAAiB,YAAY,WAAW;;EAExC;EACA,YAAY,WAAW;;EAEvB;EAAmB,YAAY,WAAW;;EAC1C;EAAsB,YAAY,WAAW;;EAC7C;EAAuB,YAAY,WAAW;;;;;;;;;;iBA6BpC,qBAAqB,MAAM,wBAAwB"}
|
|
@@ -50,6 +50,10 @@ function readerSessionOptions(sink) {
|
|
|
50
50
|
onMissingSlotContent: (diagnostic) => report(sink, {
|
|
51
51
|
kind: "slot-content",
|
|
52
52
|
diagnostic
|
|
53
|
+
}),
|
|
54
|
+
onUnsupportedVariableType: (resource) => report(sink, {
|
|
55
|
+
kind: "variable-type",
|
|
56
|
+
diagnostic: resource
|
|
53
57
|
})
|
|
54
58
|
};
|
|
55
59
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../../../../src/kiwi/fig/session/options.ts"],"sourcesContent":["import type { DocumentAssemblyOptions } from '@pairdraw/fig'\n\ntype Handler<K extends keyof DocumentAssemblyOptions> = NonNullable<DocumentAssemblyOptions[K]>\n\n/** A saved record the reader could not apply and skipped instead of refusing the file. */\nexport type FigReaderDiagnostic =\n | { kind: 'property'; diagnostic: Parameters<Handler<'onUnresolvedProperty'>>[0] }\n | { kind: 'assignment'; diagnostic: Parameters<Handler<'onUnresolvedAssignment'>>[0] }\n | { kind: 'binding'; diagnostic: Parameters<Handler<'onUnresolvedBinding'>>[0] }\n | {\n kind: 'variable-expression'\n diagnostic: Parameters<Handler<'onUnsupportedVariableExpression'>>[0]\n }\n | { kind: 'component'; diagnostic: Parameters<Handler<'onMissingComponent'>>[0] }\n | { kind: 'slot-content'; diagnostic: Parameters<Handler<'onMissingSlotContent'>>[0] }\n\n/** Each sink's entries, so a record reported again is not listed twice. */\nconst reported = new WeakMap<FigReaderDiagnostic[], Set<string>>()\n\n/**\n * Opening a file, recovering a page, and every save read records through sessions that share\n * one sink, so the same skipped record can reach it more than once.\n */\nfunction report(sink: FigReaderDiagnostic[], entry: FigReaderDiagnostic): void {\n let keys = reported.get(sink)\n if (!keys) {\n keys = new Set(sink.map((existing) => JSON.stringify(existing)))\n reported.set(sink, keys)\n }\n const key = JSON.stringify(entry)\n if (keys.has(key)) return\n keys.add(key)\n sink.push(entry)\n}\n\n/**\n * Figma retains override and binding records that address nodes it later deleted, and\n * instances of deleted components, and the reader has no replacement to guess at. Opening\n * a file skips those records, keeps such instances childless, and reports both, including a\n * swap whose target layer is gone. A slot whose assigned content frame is gone keeps its\n * component's content. An ambiguous address means the path is wrong, not stale,\n * and still fails.\n */\nexport function readerSessionOptions(sink: FigReaderDiagnostic[]): DocumentAssemblyOptions {\n return {\n derivedBounds: true,\n onUnresolvedProperty: (diagnostic) => report(sink, { kind: 'property', diagnostic }),\n onUnresolvedAssignment: (diagnostic) => report(sink, { kind: 'assignment', diagnostic }),\n onUnresolvedBinding: (diagnostic) => report(sink, { kind: 'binding', diagnostic }),\n onUnsupportedVariableExpression: (diagnostic) =>\n report(sink, { kind: 'variable-expression', diagnostic }),\n onMissingComponent: (diagnostic) => report(sink, { kind: 'component', diagnostic }),\n onMissingSlotContent: (diagnostic) => report(sink, { kind: 'slot-content', diagnostic })\n }\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../../../../src/kiwi/fig/session/options.ts"],"sourcesContent":["import type { DocumentAssemblyOptions } from '@pairdraw/fig'\n\ntype Handler<K extends keyof DocumentAssemblyOptions> = NonNullable<DocumentAssemblyOptions[K]>\n\n/** A saved record the reader could not apply and skipped instead of refusing the file. */\nexport type FigReaderDiagnostic =\n | { kind: 'property'; diagnostic: Parameters<Handler<'onUnresolvedProperty'>>[0] }\n | { kind: 'assignment'; diagnostic: Parameters<Handler<'onUnresolvedAssignment'>>[0] }\n | { kind: 'binding'; diagnostic: Parameters<Handler<'onUnresolvedBinding'>>[0] }\n | {\n kind: 'variable-expression'\n diagnostic: Parameters<Handler<'onUnsupportedVariableExpression'>>[0]\n }\n | { kind: 'component'; diagnostic: Parameters<Handler<'onMissingComponent'>>[0] }\n | { kind: 'slot-content'; diagnostic: Parameters<Handler<'onMissingSlotContent'>>[0] }\n | { kind: 'variable-type'; diagnostic: Parameters<Handler<'onUnsupportedVariableType'>>[0] }\n\n/** Each sink's entries, so a record reported again is not listed twice. */\nconst reported = new WeakMap<FigReaderDiagnostic[], Set<string>>()\n\n/**\n * Opening a file, recovering a page, and every save read records through sessions that share\n * one sink, so the same skipped record can reach it more than once.\n */\nfunction report(sink: FigReaderDiagnostic[], entry: FigReaderDiagnostic): void {\n let keys = reported.get(sink)\n if (!keys) {\n keys = new Set(sink.map((existing) => JSON.stringify(existing)))\n reported.set(sink, keys)\n }\n const key = JSON.stringify(entry)\n if (keys.has(key)) return\n keys.add(key)\n sink.push(entry)\n}\n\n/**\n * Figma retains override and binding records that address nodes it later deleted, and\n * instances of deleted components, and the reader has no replacement to guess at. Opening\n * a file skips those records, keeps such instances childless, and reports both, including a\n * swap whose target layer is gone. A slot whose assigned content frame is gone keeps its\n * component's content. An ambiguous address means the path is wrong, not stale,\n * and still fails.\n */\nexport function readerSessionOptions(sink: FigReaderDiagnostic[]): DocumentAssemblyOptions {\n return {\n derivedBounds: true,\n onUnresolvedProperty: (diagnostic) => report(sink, { kind: 'property', diagnostic }),\n onUnresolvedAssignment: (diagnostic) => report(sink, { kind: 'assignment', diagnostic }),\n onUnresolvedBinding: (diagnostic) => report(sink, { kind: 'binding', diagnostic }),\n onUnsupportedVariableExpression: (diagnostic) =>\n report(sink, { kind: 'variable-expression', diagnostic }),\n onMissingComponent: (diagnostic) => report(sink, { kind: 'component', diagnostic }),\n onMissingSlotContent: (diagnostic) => report(sink, { kind: 'slot-content', diagnostic }),\n onUnsupportedVariableType: (resource) =>\n report(sink, { kind: 'variable-type', diagnostic: resource })\n }\n}\n"],"mappings":";;AAkBA,MAAM,2BAAW,IAAI,QAA4C;;;;;AAMjE,SAAS,OAAO,MAA6B,OAAkC;CAC7E,IAAI,OAAO,SAAS,IAAI,IAAI;CAC5B,IAAI,CAAC,MAAM;EACT,OAAO,IAAI,IAAI,KAAK,KAAK,aAAa,KAAK,UAAU,QAAQ,CAAC,CAAC;EAC/D,SAAS,IAAI,MAAM,IAAI;CACzB;CACA,MAAM,MAAM,KAAK,UAAU,KAAK;CAChC,IAAI,KAAK,IAAI,GAAG,GAAG;CACnB,KAAK,IAAI,GAAG;CACZ,KAAK,KAAK,KAAK;AACjB;;;;;;;;;AAUA,SAAgB,qBAAqB,MAAsD;CACzF,OAAO;EACL,eAAe;EACf,uBAAuB,eAAe,OAAO,MAAM;GAAE,MAAM;GAAY;EAAW,CAAC;EACnF,yBAAyB,eAAe,OAAO,MAAM;GAAE,MAAM;GAAc;EAAW,CAAC;EACvF,sBAAsB,eAAe,OAAO,MAAM;GAAE,MAAM;GAAW;EAAW,CAAC;EACjF,kCAAkC,eAChC,OAAO,MAAM;GAAE,MAAM;GAAuB;EAAW,CAAC;EAC1D,qBAAqB,eAAe,OAAO,MAAM;GAAE,MAAM;GAAa;EAAW,CAAC;EAClF,uBAAuB,eAAe,OAAO,MAAM;GAAE,MAAM;GAAgB;EAAW,CAAC;EACvF,4BAA4B,aAC1B,OAAO,MAAM;GAAE,MAAM;GAAiB,YAAY;EAAS,CAAC;CAChE;AACF"}
|
|
@@ -3,6 +3,7 @@ import { Align, GridTrackType, Justify, Node } from "yoga-layout";
|
|
|
3
3
|
//#region src/layout/yoga-helpers.d.ts
|
|
4
4
|
/** Yoga nodes created and not yet freed by `freeYogaTree`. */
|
|
5
5
|
declare function liveYogaNodeCount(): number;
|
|
6
|
+
declare function yogaNodeCreationCount(): number;
|
|
6
7
|
declare function createYogaNode(): Node;
|
|
7
8
|
declare function configureAbsoluteChild(yogaChild: Node, child: SceneNode): void;
|
|
8
9
|
declare function configureNonTextLeaf(yogaChild: Node, child: SceneNode, isRow: boolean, stretchCross: boolean): void;
|
|
@@ -24,5 +25,5 @@ declare function mapAlignSelf(alignSelf: string): Align | null;
|
|
|
24
25
|
/** The axis a frame's auto layout parent stretches it along, if any. */
|
|
25
26
|
declare function parentStretchedAxis(graph: SceneGraph, frame: SceneNode): 'width' | 'height' | null;
|
|
26
27
|
//#endregion
|
|
27
|
-
export { applyLockedAspectRatio, applyMinMaxConstraints, configureAbsoluteChild, configureNonTextLeaf, createYogaNode, freeYogaTree, liveYogaNodeCount, mapAlign, mapAlignSelf, mapGridTrack, mapJustify, parentStretchedAxis };
|
|
28
|
+
export { applyLockedAspectRatio, applyMinMaxConstraints, configureAbsoluteChild, configureNonTextLeaf, createYogaNode, freeYogaTree, liveYogaNodeCount, mapAlign, mapAlignSelf, mapGridTrack, mapJustify, parentStretchedAxis, yogaNodeCreationCount };
|
|
28
29
|
//# sourceMappingURL=yoga-helpers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"yoga-helpers.d.ts","names":[],"sources":["../../src/layout/yoga-helpers.ts"],"mappings":";;;;iBAuBgB;iBAIA,kBAAkB;
|
|
1
|
+
{"version":3,"file":"yoga-helpers.d.ts","names":[],"sources":["../../src/layout/yoga-helpers.ts"],"mappings":";;;;iBAuBgB;iBAOA;iBAIA,kBAAkB;iBAMlB,uBAAuB,WAAW,MAAU,OAAO;iBAQnD,qBACd,WAAW,MACX,OAAO,WACP,gBACA;;;;;;iBA2Bc,uBACd,UAAU,MACV,MAAM,WACN,QAAQ;iBAmBM,uBAAuB,UAAU,MAAU,MAAM;iBAOjD,aAAa,OAAO;EAAc,MAAM;EAAe;;iBAWvD,aAAa,MAAM;iBAWnB,WAAW,gBAAgB;iBAe3B,SAAS,gBAAgB;iBAezB,aAAa,oBAAoB;;iBAkBjC,oBACd,OAAO,YACP,OAAO"}
|
|
@@ -13,8 +13,14 @@ let liveYogaNodes = 0;
|
|
|
13
13
|
function liveYogaNodeCount() {
|
|
14
14
|
return liveYogaNodes;
|
|
15
15
|
}
|
|
16
|
+
/** Yoga nodes created since the process started, which tests read to see a pass build what it places. */
|
|
17
|
+
let yogaNodeCreations = 0;
|
|
18
|
+
function yogaNodeCreationCount() {
|
|
19
|
+
return yogaNodeCreations;
|
|
20
|
+
}
|
|
16
21
|
function createYogaNode() {
|
|
17
22
|
liveYogaNodes += 1;
|
|
23
|
+
yogaNodeCreations += 1;
|
|
18
24
|
return Yoga.Node.create(yogaConfig);
|
|
19
25
|
}
|
|
20
26
|
function configureAbsoluteChild(yogaChild, child) {
|
|
@@ -129,6 +135,6 @@ function parentStretchedAxis(graph, frame) {
|
|
|
129
135
|
return parent.layoutMode === "VERTICAL" ? "width" : "height";
|
|
130
136
|
}
|
|
131
137
|
//#endregion
|
|
132
|
-
export { applyLockedAspectRatio, applyMinMaxConstraints, configureAbsoluteChild, configureNonTextLeaf, createYogaNode, freeYogaTree, liveYogaNodeCount, mapAlign, mapAlignSelf, mapGridTrack, mapJustify, parentStretchedAxis };
|
|
138
|
+
export { applyLockedAspectRatio, applyMinMaxConstraints, configureAbsoluteChild, configureNonTextLeaf, createYogaNode, freeYogaTree, liveYogaNodeCount, mapAlign, mapAlignSelf, mapGridTrack, mapJustify, parentStretchedAxis, yogaNodeCreationCount };
|
|
133
139
|
|
|
134
140
|
//# sourceMappingURL=yoga-helpers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"yoga-helpers.js","names":[],"sources":["../../src/layout/yoga-helpers.ts"],"sourcesContent":["import Yoga, {\n Align,\n Edge,\n GridTrackType,\n Justify,\n PositionType,\n type Node as YogaNode\n} from 'yoga-layout'\n\nimport type { GridTrack, SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { enforcedAspectRatio, layoutSizingInParent } from '@pairdraw/scene-graph/layout'\n\nconst yogaConfig = Yoga.Config.create()\nyogaConfig.setPointScaleFactor(0)\n\n/**\n * Yoga nodes built and not freed yet. Yoga's nodes live in WebAssembly memory the caller owns, so a\n * pass that leaves its tree behind holds that memory and the nodes it holds; a test reads this to\n * see one freed on every path.\n */\nlet liveYogaNodes = 0\n\n/** Yoga nodes created and not yet freed by `freeYogaTree`. */\nexport function liveYogaNodeCount(): number {\n return liveYogaNodes\n}\n\nexport function createYogaNode(): YogaNode {\n liveYogaNodes += 1\n return Yoga.Node.create(yogaConfig)\n}\n\nexport function configureAbsoluteChild(yogaChild: YogaNode, child: SceneNode): void {\n yogaChild.setPositionType(PositionType.Absolute)\n yogaChild.setPosition(Edge.Left, child.x)\n yogaChild.setPosition(Edge.Top, child.y)\n yogaChild.setWidth(child.width)\n yogaChild.setHeight(child.height)\n}\n\nexport function configureNonTextLeaf(\n yogaChild: YogaNode,\n child: SceneNode,\n isRow: boolean,\n stretchCross: boolean\n): void {\n const w = child.width\n const h = child.height\n\n if (child.layoutGrow > 0) {\n yogaChild.setFlexGrow(child.layoutGrow)\n if (!stretchCross) {\n if (isRow) yogaChild.setHeight(h)\n else yogaChild.setWidth(w)\n }\n } else {\n if (isRow) {\n yogaChild.setWidth(w)\n if (!stretchCross) yogaChild.setHeight(h)\n } else {\n yogaChild.setHeight(h)\n if (!stretchCross) yogaChild.setWidth(w)\n }\n }\n}\n\n/**\n * A locked aspect ratio sizes the axis Fill does not drive, as Figma lays it out: Fill along the\n * parent's primary axis drives when set, else Fill across it, and the other axis follows even past\n * the parent's edge. An axis that hugs keeps its own size.\n */\nexport function applyLockedAspectRatio(\n yogaNode: YogaNode,\n node: SceneNode,\n parent: SceneNode\n): void {\n const ratio = enforcedAspectRatio(node)\n if (ratio === null) return\n const width = layoutSizingInParent(parent, node, 'HORIZONTAL')\n const height = layoutSizingInParent(parent, node, 'VERTICAL')\n const primaryIsWidth = parent.layoutMode !== 'VERTICAL'\n const primary = primaryIsWidth ? width : height\n const cross = primaryIsWidth ? height : width\n let drivesWidth: boolean\n if (primary === 'FILL') drivesWidth = primaryIsWidth\n else if (cross === 'FILL') drivesWidth = !primaryIsWidth\n else return\n if ((drivesWidth ? height : width) === 'HUG') return\n yogaNode.setAspectRatio(ratio)\n if (drivesWidth) yogaNode.setHeight('auto')\n else yogaNode.setWidth('auto')\n}\n\nexport function applyMinMaxConstraints(yogaNode: YogaNode, node: SceneNode): void {\n if (node.minWidth != null) yogaNode.setMinWidth(node.minWidth)\n if (node.maxWidth != null) yogaNode.setMaxWidth(node.maxWidth)\n if (node.minHeight != null) yogaNode.setMinHeight(node.minHeight)\n if (node.maxHeight != null) yogaNode.setMaxHeight(node.maxHeight)\n}\n\nexport function mapGridTrack(track: GridTrack): { type: GridTrackType; value: number } {\n switch (track.sizing) {\n case 'FR':\n return { type: GridTrackType.Fr, value: track.value }\n case 'FIXED':\n return { type: GridTrackType.Points, value: track.value }\n default:\n return { type: GridTrackType.Auto, value: 0 }\n }\n}\n\nexport function freeYogaTree(node: YogaNode): void {\n for (let i = node.getChildCount() - 1; i >= 0; i--) {\n freeYogaTree(node.getChild(i))\n }\n // Wasm-backed nodes carry `free`, which `yoga-layout`'s type leaves out.\n if ('free' in node && typeof node.free === 'function') {\n node.free()\n liveYogaNodes -= 1\n }\n}\n\nexport function mapJustify(align: string): Justify {\n switch (align) {\n case 'CENTER':\n return Justify.Center\n case 'MAX':\n return Justify.FlexEnd\n case 'SPACE_BETWEEN':\n return Justify.SpaceBetween\n case 'SPACE_AROUND':\n return Justify.SpaceAround\n default:\n return Justify.FlexStart\n }\n}\n\nexport function mapAlign(align: string): Align {\n switch (align) {\n case 'CENTER':\n return Align.Center\n case 'MAX':\n return Align.FlexEnd\n case 'STRETCH':\n return Align.Stretch\n case 'BASELINE':\n return Align.Baseline\n default:\n return Align.FlexStart\n }\n}\n\nexport function mapAlignSelf(alignSelf: string): Align | null {\n switch (alignSelf) {\n case 'MIN':\n return Align.FlexStart\n case 'CENTER':\n return Align.Center\n case 'MAX':\n return Align.FlexEnd\n case 'STRETCH':\n return Align.Stretch\n case 'BASELINE':\n return Align.Baseline\n default:\n return null\n }\n}\n\n/** The axis a frame's auto layout parent stretches it along, if any. */\nexport function parentStretchedAxis(\n graph: SceneGraph,\n frame: SceneNode\n): 'width' | 'height' | null {\n const parent = frame.parentId ? graph.getNode(frame.parentId) : undefined\n if (!parent || frame.layoutPositioning === 'ABSOLUTE') return null\n if (parent.layoutMode !== 'HORIZONTAL' && parent.layoutMode !== 'VERTICAL') return null\n const stretched =\n frame.layoutAlignSelf === 'STRETCH' ||\n (frame.layoutAlignSelf === 'AUTO' && parent.counterAxisAlign === 'STRETCH')\n if (!stretched) return null\n return parent.layoutMode === 'VERTICAL' ? 'width' : 'height'\n}\n"],"mappings":";;;AAYA,MAAM,aAAa,KAAK,OAAO,OAAO;AACtC,WAAW,oBAAoB,CAAC;;;;;;AAOhC,IAAI,gBAAgB;;AAGpB,SAAgB,oBAA4B;CAC1C,OAAO;AACT;AAEA,SAAgB,iBAA2B;CACzC,iBAAiB;CACjB,OAAO,KAAK,KAAK,OAAO,UAAU;AACpC;AAEA,SAAgB,uBAAuB,WAAqB,OAAwB;CAClF,UAAU,gBAAgB,aAAa,QAAQ;CAC/C,UAAU,YAAY,KAAK,MAAM,MAAM,CAAC;CACxC,UAAU,YAAY,KAAK,KAAK,MAAM,CAAC;CACvC,UAAU,SAAS,MAAM,KAAK;CAC9B,UAAU,UAAU,MAAM,MAAM;AAClC;AAEA,SAAgB,qBACd,WACA,OACA,OACA,cACM;CACN,MAAM,IAAI,MAAM;CAChB,MAAM,IAAI,MAAM;CAEhB,IAAI,MAAM,aAAa,GAAG;EACxB,UAAU,YAAY,MAAM,UAA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"version":3,"file":"yoga-helpers.js","names":[],"sources":["../../src/layout/yoga-helpers.ts"],"sourcesContent":["import Yoga, {\n Align,\n Edge,\n GridTrackType,\n Justify,\n PositionType,\n type Node as YogaNode\n} from 'yoga-layout'\n\nimport type { GridTrack, SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { enforcedAspectRatio, layoutSizingInParent } from '@pairdraw/scene-graph/layout'\n\nconst yogaConfig = Yoga.Config.create()\nyogaConfig.setPointScaleFactor(0)\n\n/**\n * Yoga nodes built and not freed yet. Yoga's nodes live in WebAssembly memory the caller owns, so a\n * pass that leaves its tree behind holds that memory and the nodes it holds; a test reads this to\n * see one freed on every path.\n */\nlet liveYogaNodes = 0\n\n/** Yoga nodes created and not yet freed by `freeYogaTree`. */\nexport function liveYogaNodeCount(): number {\n return liveYogaNodes\n}\n\n/** Yoga nodes created since the process started, which tests read to see a pass build what it places. */\nlet yogaNodeCreations = 0\n\nexport function yogaNodeCreationCount(): number {\n return yogaNodeCreations\n}\n\nexport function createYogaNode(): YogaNode {\n liveYogaNodes += 1\n yogaNodeCreations += 1\n return Yoga.Node.create(yogaConfig)\n}\n\nexport function configureAbsoluteChild(yogaChild: YogaNode, child: SceneNode): void {\n yogaChild.setPositionType(PositionType.Absolute)\n yogaChild.setPosition(Edge.Left, child.x)\n yogaChild.setPosition(Edge.Top, child.y)\n yogaChild.setWidth(child.width)\n yogaChild.setHeight(child.height)\n}\n\nexport function configureNonTextLeaf(\n yogaChild: YogaNode,\n child: SceneNode,\n isRow: boolean,\n stretchCross: boolean\n): void {\n const w = child.width\n const h = child.height\n\n if (child.layoutGrow > 0) {\n yogaChild.setFlexGrow(child.layoutGrow)\n if (!stretchCross) {\n if (isRow) yogaChild.setHeight(h)\n else yogaChild.setWidth(w)\n }\n } else {\n if (isRow) {\n yogaChild.setWidth(w)\n if (!stretchCross) yogaChild.setHeight(h)\n } else {\n yogaChild.setHeight(h)\n if (!stretchCross) yogaChild.setWidth(w)\n }\n }\n}\n\n/**\n * A locked aspect ratio sizes the axis Fill does not drive, as Figma lays it out: Fill along the\n * parent's primary axis drives when set, else Fill across it, and the other axis follows even past\n * the parent's edge. An axis that hugs keeps its own size.\n */\nexport function applyLockedAspectRatio(\n yogaNode: YogaNode,\n node: SceneNode,\n parent: SceneNode\n): void {\n const ratio = enforcedAspectRatio(node)\n if (ratio === null) return\n const width = layoutSizingInParent(parent, node, 'HORIZONTAL')\n const height = layoutSizingInParent(parent, node, 'VERTICAL')\n const primaryIsWidth = parent.layoutMode !== 'VERTICAL'\n const primary = primaryIsWidth ? width : height\n const cross = primaryIsWidth ? height : width\n let drivesWidth: boolean\n if (primary === 'FILL') drivesWidth = primaryIsWidth\n else if (cross === 'FILL') drivesWidth = !primaryIsWidth\n else return\n if ((drivesWidth ? height : width) === 'HUG') return\n yogaNode.setAspectRatio(ratio)\n if (drivesWidth) yogaNode.setHeight('auto')\n else yogaNode.setWidth('auto')\n}\n\nexport function applyMinMaxConstraints(yogaNode: YogaNode, node: SceneNode): void {\n if (node.minWidth != null) yogaNode.setMinWidth(node.minWidth)\n if (node.maxWidth != null) yogaNode.setMaxWidth(node.maxWidth)\n if (node.minHeight != null) yogaNode.setMinHeight(node.minHeight)\n if (node.maxHeight != null) yogaNode.setMaxHeight(node.maxHeight)\n}\n\nexport function mapGridTrack(track: GridTrack): { type: GridTrackType; value: number } {\n switch (track.sizing) {\n case 'FR':\n return { type: GridTrackType.Fr, value: track.value }\n case 'FIXED':\n return { type: GridTrackType.Points, value: track.value }\n default:\n return { type: GridTrackType.Auto, value: 0 }\n }\n}\n\nexport function freeYogaTree(node: YogaNode): void {\n for (let i = node.getChildCount() - 1; i >= 0; i--) {\n freeYogaTree(node.getChild(i))\n }\n // Wasm-backed nodes carry `free`, which `yoga-layout`'s type leaves out.\n if ('free' in node && typeof node.free === 'function') {\n node.free()\n liveYogaNodes -= 1\n }\n}\n\nexport function mapJustify(align: string): Justify {\n switch (align) {\n case 'CENTER':\n return Justify.Center\n case 'MAX':\n return Justify.FlexEnd\n case 'SPACE_BETWEEN':\n return Justify.SpaceBetween\n case 'SPACE_AROUND':\n return Justify.SpaceAround\n default:\n return Justify.FlexStart\n }\n}\n\nexport function mapAlign(align: string): Align {\n switch (align) {\n case 'CENTER':\n return Align.Center\n case 'MAX':\n return Align.FlexEnd\n case 'STRETCH':\n return Align.Stretch\n case 'BASELINE':\n return Align.Baseline\n default:\n return Align.FlexStart\n }\n}\n\nexport function mapAlignSelf(alignSelf: string): Align | null {\n switch (alignSelf) {\n case 'MIN':\n return Align.FlexStart\n case 'CENTER':\n return Align.Center\n case 'MAX':\n return Align.FlexEnd\n case 'STRETCH':\n return Align.Stretch\n case 'BASELINE':\n return Align.Baseline\n default:\n return null\n }\n}\n\n/** The axis a frame's auto layout parent stretches it along, if any. */\nexport function parentStretchedAxis(\n graph: SceneGraph,\n frame: SceneNode\n): 'width' | 'height' | null {\n const parent = frame.parentId ? graph.getNode(frame.parentId) : undefined\n if (!parent || frame.layoutPositioning === 'ABSOLUTE') return null\n if (parent.layoutMode !== 'HORIZONTAL' && parent.layoutMode !== 'VERTICAL') return null\n const stretched =\n frame.layoutAlignSelf === 'STRETCH' ||\n (frame.layoutAlignSelf === 'AUTO' && parent.counterAxisAlign === 'STRETCH')\n if (!stretched) return null\n return parent.layoutMode === 'VERTICAL' ? 'width' : 'height'\n}\n"],"mappings":";;;AAYA,MAAM,aAAa,KAAK,OAAO,OAAO;AACtC,WAAW,oBAAoB,CAAC;;;;;;AAOhC,IAAI,gBAAgB;;AAGpB,SAAgB,oBAA4B;CAC1C,OAAO;AACT;;AAGA,IAAI,oBAAoB;AAExB,SAAgB,wBAAgC;CAC9C,OAAO;AACT;AAEA,SAAgB,iBAA2B;CACzC,iBAAiB;CACjB,qBAAqB;CACrB,OAAO,KAAK,KAAK,OAAO,UAAU;AACpC;AAEA,SAAgB,uBAAuB,WAAqB,OAAwB;CAClF,UAAU,gBAAgB,aAAa,QAAQ;CAC/C,UAAU,YAAY,KAAK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M,QAAQ,IAAI,KAAA;CAChE,IAAI,CAAC,UAAU,MAAM,sBAAsB,YAAY,OAAO;CAC9D,IAAI,OAAO,eAAe,gBAAgB,OAAO,eAAe,YAAY,OAAO;CAInF,IAAI,EAFF,MAAM,oBAAoB,aACzB,MAAM,oBAAoB,UAAU,OAAO,qBAAqB,YACnD,OAAO;CACvB,OAAO,OAAO,eAAe,aAAa,UAAU;AACtD"}
|
package/dist/layout.js
CHANGED
|
@@ -12,7 +12,7 @@ import { sizeAutoResizingText } from "./layout/text-auto-resize.js";
|
|
|
12
12
|
import { fitShapeWithTextFrame } from "./layout/shape-with-text.js";
|
|
13
13
|
import { connectorSublayers, layoutConnector } from "@pairdraw/scene-graph/connectors";
|
|
14
14
|
import { resolveNodeLayoutDirection } from "@pairdraw/scene-graph/text/direction";
|
|
15
|
-
import { layoutSizing } from "@pairdraw/scene-graph/layout";
|
|
15
|
+
import { enforcedAspectRatio, layoutSizing } from "@pairdraw/scene-graph/layout";
|
|
16
16
|
import { Direction, Display, Gutter, MeasureMode, Overflow } from "yoga-layout";
|
|
17
17
|
//#region src/layout.ts
|
|
18
18
|
function computeLayout(graph, frameId) {
|
|
@@ -216,6 +216,25 @@ function configureAutoLayoutChildSizing(yogaChild, child, parent, graph, widthSi
|
|
|
216
216
|
if (fixedDerivedMainAxis) yogaChild.setHeight(child.derivedLayout?.height ?? child.height);
|
|
217
217
|
else setMainAxisSizing(yogaChild, "height", heightSizing, child.height, child.layoutGrow);
|
|
218
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* Whether the parent's pass places this child from the size it holds: neither its content nor the
|
|
221
|
+
* parent decides its size, so its own cells keep their places while the parent moves it.
|
|
222
|
+
*/
|
|
223
|
+
function placesFromSize(child, parent, widthSizing, heightSizing) {
|
|
224
|
+
return widthSizing === "FIXED" && heightSizing === "FIXED" && child.layoutGrow === 0 && parent.counterAxisAlign !== "BASELINE" && child.layoutAlignSelf !== "BASELINE" && enforcedAspectRatio(child) === null && child.minWidth === null && child.maxWidth === null && child.minHeight === null && child.maxHeight === null;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Refuses a chain deeper than Yoga can lay out, for the subtrees a pass places from their size and
|
|
228
|
+
* does not build: the same refusal, without the Yoga nodes.
|
|
229
|
+
*/
|
|
230
|
+
function assertLayoutDepth(graph, frame, depth) {
|
|
231
|
+
if (depth > MAX_LAYOUT_DEPTH) throw new RangeError(`Layers nest more than ${MAX_LAYOUT_DEPTH} auto-layout frames deep, which the layout engine cannot lay out.`);
|
|
232
|
+
for (const child of graph.getChildren(frame.id)) {
|
|
233
|
+
if (child.layoutMode === "NONE" || !child.visible) continue;
|
|
234
|
+
if (child.layoutPositioning === "ABSOLUTE") continue;
|
|
235
|
+
assertLayoutDepth(graph, child, depth + 1);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
219
238
|
function configureChildAsAutoLayout(yogaChild, child, parent, graph, inheritedDirection, depth) {
|
|
220
239
|
if (depth > MAX_LAYOUT_DEPTH) throw new RangeError(`Layers nest more than ${MAX_LAYOUT_DEPTH} auto-layout frames deep, which the layout engine cannot lay out.`);
|
|
221
240
|
const direction = resolveNodeLayoutDirection(child, inheritedDirection);
|
|
@@ -232,6 +251,10 @@ function configureChildAsAutoLayout(yogaChild, child, parent, graph, inheritedDi
|
|
|
232
251
|
applyMinMaxConstraints(yogaChild, child);
|
|
233
252
|
return;
|
|
234
253
|
}
|
|
254
|
+
if (placesFromSize(child, parent, widthSizing, heightSizing)) {
|
|
255
|
+
assertLayoutDepth(graph, child, depth + 1);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
235
258
|
configureFlexContainer(yogaChild, child, direction);
|
|
236
259
|
const heldAxis = heldHugAxis(graph, child);
|
|
237
260
|
if (heldAxis === "width" && widthSizing === "HUG") yogaChild.setWidth(child.width);
|