@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":"sync.js","names":[],"sources":["../../../../../src/io/formats/design-tokens/css/sync.ts"],"sourcesContent":["import {\n readCustomProperties,\n tokenStylesheet,\n type CustomPropertyScope,\n type TokenStylesheetIssue\n} from '@pairdraw/dom-css/export'\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { knownTokens } from './known'\nimport { namesFont, readCSSTokenValue, rewriteCSSTokenValue, sameCSSTokenValue } from './values'\n\n/** A stylesheet with the document's variables written into it. */\nexport interface TokenStylesheetSync {\n css: string\n /** Declarations whose value changed. */\n updated: number\n /** Declarations added for variables the stylesheet did not have. */\n added: number\n /** Variables the token stylesheet could not write, as it reports them. */\n issues: TokenStylesheetIssue[]\n}\n\ninterface Edit {\n start: number\n end: number\n text: string\n}\n\n/** Each scope's wanted values, by condition (`''` for the base set) and property. */\ntype Wanted = Map<string, { scope: CustomPropertyScope; values: Map<string, string> }>\n\nfunction scopeKey(scope: Pick<CustomPropertyScope, 'condition'>): string {\n return scope.condition ?? ''\n}\n\nfunction wantedScopes(css: string): Wanted {\n const wanted: Wanted = new Map()\n for (const scope of readCustomProperties(css).scopes) {\n const key = scopeKey(scope)\n const entry = wanted.get(key) ?? { scope, values: new Map<string, string>() }\n for (const { name, value } of scope.declarations) entry.values.set(name, value)\n wanted.set(key, entry)\n }\n return wanted\n}\n\nfunction declarationLines(values: ReadonlyArray<[string, string]>, indent: string): string {\n return values.map(([name, value]) => `${indent}--${name}: ${value};\\n`).join('')\n}\n\n/** A new block for a scope the stylesheet has none of, as the token stylesheet writes one. */\nfunction newBlock(scope: CustomPropertyScope, values: ReadonlyArray<[string, string]>): string {\n const label = scope.label ? `/* ${scope.label.collection}: ${scope.label.mode} */\\n` : ''\n if (scope.condition === null) return `:root {\\n${declarationLines(values, ' ')}}\\n`\n if (!scope.condition.startsWith('@'))\n return `${label}${scope.condition} {\\n${declarationLines(values, ' ')}}\\n`\n return `${label}${scope.condition} {\\n :root {\\n${declarationLines(values, ' ')} }\\n}\\n`\n}\n\n/** Declarations added at the end of an existing block, after its last one. */\nfunction appendToBlock(\n css: string,\n scope: CustomPropertyScope,\n values: ReadonlyArray<[string, string]>\n): Edit[] {\n const edits: Edit[] = []\n const last = scope.declarations.at(-1)\n if (last && !css.slice(last.end, scope.insertAt).includes(';'))\n edits.push({ start: last.end, end: last.end, text: ';' })\n const lineStart = css.lastIndexOf('\\n', scope.insertAt - 1) + 1\n if (css.slice(lineStart, scope.insertAt).trim() === '') {\n edits.push({ start: lineStart, end: lineStart, text: declarationLines(values, scope.indent) })\n } else {\n const inline = values.map(([name, value]) => ` --${name}: ${value};`).join('')\n edits.push({ start: scope.insertAt, end: scope.insertAt, text: `${inline} ` })\n }\n return edits\n}\n\nfunction applyEdits(css: string, edits: Edit[]): string {\n const ordered = edits\n .map((edit, order) => ({ ...edit, order }))\n .sort((a, b) => a.start - b.start || a.order - b.order)\n let out = ''\n let at = 0\n for (const edit of ordered) {\n if (edit.start < at) continue\n out += css.slice(at, edit.start) + edit.text\n at = edit.end\n }\n return out + css.slice(at)\n}\n\n/**\n * Writes the document's variables into a stylesheet in place, as the token stylesheet would write\n * them, and leaves everything else as it is: comments, formatting, other rules, and properties the\n * document has no variable for. A value that means the same, however it is written, stays; a\n * changed color keeps its notation and a length in `rem` stays in `rem`. Variables the\n * stylesheet lacks are added to the block of their scope, or in a new block at the end. Nothing\n * is removed.\n */\nexport function patchTokenStylesheet(\n graph: SceneGraph,\n source: string,\n generated: string\n): Omit<TokenStylesheetSync, 'issues'> {\n const wanted = wantedScopes(generated)\n const base = wanted.get('')?.values ?? new Map<string, string>()\n const known = knownTokens(graph)\n\n /**\n * What a scope should declare for a property. A mode writes only what differs from its default,\n * so a property its own collection's mode leaves out takes the default value there.\n */\n function expected(key: string, name: string): string | undefined {\n if (key === '') return base.get(name)\n const scoped = wanted.get(key)?.values.get(name)\n if (scoped !== undefined) return scoped\n const variable = known.byCSSName.get(name)\n const mode = known.byCondition.get(key)\n return variable && mode && variable.collection === mode.collection ? base.get(name) : undefined\n }\n\n const edits: Edit[] = []\n const present = new Map<string, Set<string>>()\n const lastScope = new Map<string, CustomPropertyScope>()\n let updated = 0\n const target = readCustomProperties(source)\n for (const scope of target.scopes) {\n const key = scopeKey(scope)\n lastScope.set(key, scope)\n const names = present.get(key) ?? new Set<string>()\n present.set(key, names)\n for (const declaration of scope.declarations) {\n names.add(declaration.name)\n const want = expected(key, declaration.name)\n if (want === undefined) continue\n const font = namesFont(declaration.name)\n const previous = readCSSTokenValue(declaration.value, { font })\n const next = readCSSTokenValue(want, { font })\n if (sameCSSTokenValue(previous, next)) continue\n edits.push({\n start: declaration.start,\n end: declaration.end,\n text: rewriteCSSTokenValue(previous, next, want)\n })\n updated++\n }\n }\n\n // The base set as this push leaves it, which every mode's block inherits.\n const inherited = new Map<string, string>()\n for (const scope of target.scopes)\n if (scope.condition === null)\n for (const { name, value } of scope.declarations) inherited.set(name, value)\n for (const [name, value] of base) inherited.set(name, value)\n\n /** A mode's block need not declare what it already inherits from the base set. */\n function inherits(key: string, name: string, value: string): boolean {\n const from = key === '' ? undefined : inherited.get(name)\n if (from === undefined) return false\n const font = namesFont(name)\n return sameCSSTokenValue(readCSSTokenValue(from, { font }), readCSSTokenValue(value, { font }))\n }\n\n let added = 0\n const blocks: string[] = []\n for (const [key, { scope, values }] of wanted) {\n const missing = [...values].filter(\n ([name, value]) => !present.get(key)?.has(name) && !inherits(key, name, value)\n )\n if (missing.length === 0) continue\n added += missing.length\n const existing = lastScope.get(key)\n if (existing) edits.push(...appendToBlock(source, existing, missing))\n else blocks.push(newBlock(scope, missing))\n }\n\n let css = applyEdits(source, edits)\n if (blocks.length > 0) {\n let separator = '\\n\\n'\n if (css.length === 0) separator = ''\n else if (css.endsWith('\\n')) separator = '\\n'\n css = `${css}${separator}${blocks.join('\\n')}`\n }\n return { css, updated, added }\n}\n\n/**\n * The stylesheet with the document's variables written in, through `patchTokenStylesheet`, and\n * what the token stylesheet could not write.\n */\nexport async function syncTokenStylesheet(\n graph: SceneGraph,\n source: string\n): Promise<TokenStylesheetSync> {\n const generated = await tokenStylesheet(graph, { format: 'css' })\n return { ...patchTokenStylesheet(graph, source, generated.css), issues: generated.issues }\n}\n"],"mappings":";;;;AA+BA,SAAS,SAAS,OAAuD;CACvE,OAAO,MAAM,aAAa;AAC5B;AAEA,SAAS,aAAa,KAAqB;CACzC,MAAM,yBAAiB,IAAI,IAAI;CAC/B,KAAK,MAAM,SAAS,qBAAqB,GAAG,CAAC,CAAC,QAAQ;EACpD,MAAM,MAAM,SAAS,KAAK;EAC1B,MAAM,QAAQ,OAAO,IAAI,GAAG,KAAK;GAAE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AK,EAAE,OAAO,aAAa,QAAQ;EAC7C,MAAM,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,QACzB,CAAC,MAAM,WAAW,CAAC,QAAQ,IAAI,GAAG,CAAC,EAAE,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,MAAM,KAAK,CAC/E;EACA,IAAI,QAAQ,WAAW,GAAG;EAC1B,SAAS,QAAQ;EACjB,MAAM,WAAW,UAAU,IAAI,GAAG;EAClC,IAAI,UAAU,MAAM,KAAK,GAAG,cAAc,QAAQ,UAAU,OAAO,CAAC;OAC/D,OAAO,KAAK,SAAS,OAAO,OAAO,CAAC;CAC3C;CAEA,IAAI,MAAM,WAAW,QAAQ,KAAK;CAClC,IAAI,OAAO,SAAS,GAAG;EACrB,IAAI,YAAY;EAChB,IAAI,IAAI,WAAW,GAAG,YAAY;OAC7B,IAAI,IAAI,SAAS,IAAI,GAAG,YAAY;EACzC,MAAM,GAAG,MAAM,YAAY,OAAO,KAAK,IAAI;CAC7C;CACA,OAAO;EAAE;EAAK;EAAS;CAAM;AAC/B;;;;;AAMA,eAAsB,oBACpB,OACA,QAC8B;CAC9B,MAAM,YAAY,MAAM,gBAAgB,OAAO,EAAE,QAAQ,MAAM,CAAC;CAChE,OAAO;EAAE,GAAG,qBAAqB,OAAO,QAAQ,UAAU,GAAG;EAAG,QAAQ,UAAU;CAAO;AAC3F"}
|
|
1
|
+
{"version":3,"file":"sync.js","names":[],"sources":["../../../../../src/io/formats/design-tokens/css/sync.ts"],"sourcesContent":["import {\n readCustomProperties,\n tokenStylesheet,\n type CustomPropertyScope,\n type TokenStylesheetIssue\n} from '@pairdraw/dom-css/export'\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { knownTokens } from './known'\nimport { namesFont, readCSSTokenValue, rewriteCSSTokenValue, sameCSSTokenValue } from './values'\n\n/** A stylesheet with the document's variables written into it. */\nexport interface TokenStylesheetSync {\n css: string\n /** Declarations whose value changed. */\n updated: number\n /** Declarations added for variables the stylesheet did not have. */\n added: number\n /** Variables the token stylesheet could not write, as it reports them. */\n issues: TokenStylesheetIssue[]\n}\n\ninterface Edit {\n start: number\n end: number\n text: string\n}\n\n/** Each scope's wanted values, by condition (`''` for the base set) and property. */\ntype Wanted = Map<string, { scope: CustomPropertyScope; values: Map<string, string> }>\n\nfunction scopeKey(scope: Pick<CustomPropertyScope, 'condition'>): string {\n return scope.condition ?? ''\n}\n\nfunction wantedScopes(css: string): Wanted {\n const wanted: Wanted = new Map()\n for (const scope of readCustomProperties(css).scopes) {\n const key = scopeKey(scope)\n const entry = wanted.get(key) ?? { scope, values: new Map<string, string>() }\n for (const { name, value } of scope.declarations) entry.values.set(name, value)\n wanted.set(key, entry)\n }\n return wanted\n}\n\nfunction declarationLines(values: ReadonlyArray<[string, string]>, indent: string): string {\n return values.map(([name, value]) => `${indent}--${name}: ${value};\\n`).join('')\n}\n\n/** A new block for a scope the stylesheet has none of, as the token stylesheet writes one. */\nfunction newBlock(scope: CustomPropertyScope, values: ReadonlyArray<[string, string]>): string {\n const label = scope.label ? `/* ${scope.label.collection}: ${scope.label.mode} */\\n` : ''\n if (scope.condition === null) return `:root {\\n${declarationLines(values, ' ')}}\\n`\n if (!scope.condition.startsWith('@'))\n return `${label}${scope.condition} {\\n${declarationLines(values, ' ')}}\\n`\n return `${label}${scope.condition} {\\n :root {\\n${declarationLines(values, ' ')} }\\n}\\n`\n}\n\n/** Declarations added at the end of an existing block, after its last one. */\nfunction appendToBlock(\n css: string,\n scope: CustomPropertyScope,\n values: ReadonlyArray<[string, string]>\n): Edit[] {\n const edits: Edit[] = []\n const last = scope.declarations.at(-1)\n if (last && !css.slice(last.end, scope.insertAt).includes(';'))\n edits.push({ start: last.end, end: last.end, text: ';' })\n const lineStart = css.lastIndexOf('\\n', scope.insertAt - 1) + 1\n if (css.slice(lineStart, scope.insertAt).trim() === '') {\n edits.push({ start: lineStart, end: lineStart, text: declarationLines(values, scope.indent) })\n } else {\n const inline = values.map(([name, value]) => ` --${name}: ${value};`).join('')\n edits.push({ start: scope.insertAt, end: scope.insertAt, text: `${inline} ` })\n }\n return edits\n}\n\nfunction applyEdits(css: string, edits: Edit[]): string {\n const ordered = edits\n .map((edit, order) => ({ ...edit, order }))\n .sort((a, b) => a.start - b.start || a.order - b.order)\n let out = ''\n let at = 0\n for (const edit of ordered) {\n if (edit.start < at) continue\n out += css.slice(at, edit.start) + edit.text\n at = edit.end\n }\n return out + css.slice(at)\n}\n\n/**\n * Writes the document's variables into a stylesheet in place, as the token stylesheet would write\n * them, and leaves everything else as it is: comments, formatting, other rules, and properties the\n * document has no variable for. A value that means the same, however it is written, stays; a\n * changed color keeps its notation and a length in `rem` stays in `rem`. Variables the\n * stylesheet lacks are added to the block of their scope, or in a new block at the end. Nothing\n * is removed.\n */\nexport function patchTokenStylesheet(\n graph: SceneGraph,\n source: string,\n generated: string\n): Omit<TokenStylesheetSync, 'issues'> {\n const wanted = wantedScopes(generated)\n const base = wanted.get('')?.values ?? new Map<string, string>()\n const known = knownTokens(graph)\n // A color that names its own space converts into the profile, and a written one comes from it.\n const profile = graph.documentColorSpace\n\n /**\n * What a scope should declare for a property. A mode writes only what differs from its default,\n * so a property its own collection's mode leaves out takes the default value there.\n */\n function expected(key: string, name: string): string | undefined {\n if (key === '') return base.get(name)\n const scoped = wanted.get(key)?.values.get(name)\n if (scoped !== undefined) return scoped\n const variable = known.byCSSName.get(name)\n const mode = known.byCondition.get(key)\n return variable && mode && variable.collection === mode.collection ? base.get(name) : undefined\n }\n\n const edits: Edit[] = []\n const present = new Map<string, Set<string>>()\n const lastScope = new Map<string, CustomPropertyScope>()\n let updated = 0\n const target = readCustomProperties(source)\n for (const scope of target.scopes) {\n const key = scopeKey(scope)\n lastScope.set(key, scope)\n const names = present.get(key) ?? new Set<string>()\n present.set(key, names)\n for (const declaration of scope.declarations) {\n names.add(declaration.name)\n const want = expected(key, declaration.name)\n if (want === undefined) continue\n const font = namesFont(declaration.name)\n const previous = readCSSTokenValue(declaration.value, { font, profile })\n const next = readCSSTokenValue(want, { font, profile })\n if (sameCSSTokenValue(previous, next)) continue\n edits.push({\n start: declaration.start,\n end: declaration.end,\n text: rewriteCSSTokenValue(previous, next, want, profile)\n })\n updated++\n }\n }\n\n // The base set as this push leaves it, which every mode's block inherits.\n const inherited = new Map<string, string>()\n for (const scope of target.scopes)\n if (scope.condition === null)\n for (const { name, value } of scope.declarations) inherited.set(name, value)\n for (const [name, value] of base) inherited.set(name, value)\n\n /** A mode's block need not declare what it already inherits from the base set. */\n function inherits(key: string, name: string, value: string): boolean {\n const from = key === '' ? undefined : inherited.get(name)\n if (from === undefined) return false\n const font = namesFont(name)\n return sameCSSTokenValue(\n readCSSTokenValue(from, { font, profile }),\n readCSSTokenValue(value, { font, profile })\n )\n }\n\n let added = 0\n const blocks: string[] = []\n for (const [key, { scope, values }] of wanted) {\n const missing = [...values].filter(\n ([name, value]) => !present.get(key)?.has(name) && !inherits(key, name, value)\n )\n if (missing.length === 0) continue\n added += missing.length\n const existing = lastScope.get(key)\n if (existing) edits.push(...appendToBlock(source, existing, missing))\n else blocks.push(newBlock(scope, missing))\n }\n\n let css = applyEdits(source, edits)\n if (blocks.length > 0) {\n let separator = '\\n\\n'\n if (css.length === 0) separator = ''\n else if (css.endsWith('\\n')) separator = '\\n'\n css = `${css}${separator}${blocks.join('\\n')}`\n }\n return { css, updated, added }\n}\n\n/**\n * The stylesheet with the document's variables written in, through `patchTokenStylesheet`, and\n * what the token stylesheet could not write.\n */\nexport async function syncTokenStylesheet(\n graph: SceneGraph,\n source: string\n): Promise<TokenStylesheetSync> {\n const generated = await tokenStylesheet(graph, { format: 'css' })\n return { ...patchTokenStylesheet(graph, source, generated.css), issues: generated.issues }\n}\n"],"mappings":";;;;AA+BA,SAAS,SAAS,OAAuD;CACvE,OAAO,MAAM,aAAa;AAC5B;AAEA,SAAS,aAAa,KAAqB;CACzC,MAAM,yBAAiB,IAAI,IAAI;CAC/B,KAAK,MAAM,SAAS,qBAAqB,GAA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M;GAAE;GAAM;EAAQ,CAAC,GACzC,kBAAkB,OAAO;GAAE;GAAM;EAAQ,CAAC,CAC5C;CACF;CAEA,IAAI,QAAQ;CACZ,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,CAAC,KAAK,EAAE,OAAO,aAAa,QAAQ;EAC7C,MAAM,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,QACzB,CAAC,MAAM,WAAW,CAAC,QAAQ,IAAI,GAAG,CAAC,EAAE,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,MAAM,KAAK,CAC/E;EACA,IAAI,QAAQ,WAAW,GAAG;EAC1B,SAAS,QAAQ;EACjB,MAAM,WAAW,UAAU,IAAI,GAAG;EAClC,IAAI,UAAU,MAAM,KAAK,GAAG,cAAc,QAAQ,UAAU,OAAO,CAAC;OAC/D,OAAO,KAAK,SAAS,OAAO,OAAO,CAAC;CAC3C;CAEA,IAAI,MAAM,WAAW,QAAQ,KAAK;CAClC,IAAI,OAAO,SAAS,GAAG;EACrB,IAAI,YAAY;EAChB,IAAI,IAAI,WAAW,GAAG,YAAY;OAC7B,IAAI,IAAI,SAAS,IAAI,GAAG,YAAY;EACzC,MAAM,GAAG,MAAM,YAAY,OAAO,KAAK,IAAI;CAC7C;CACA,OAAO;EAAE;EAAK;EAAS;CAAM;AAC/B;;;;;AAMA,eAAsB,oBACpB,OACA,QAC8B;CAC9B,MAAM,YAAY,MAAM,gBAAgB,OAAO,EAAE,QAAQ,MAAM,CAAC;CAChE,OAAO;EAAE,GAAG,qBAAqB,OAAO,QAAQ,UAAU,GAAG;EAAG,QAAQ,UAAU;CAAO;AAC3F"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TokenUnit } from "@pairdraw/scene-graph";
|
|
1
|
+
import { ColorProfile, TokenUnit } from "@pairdraw/scene-graph";
|
|
2
2
|
import { Color } from "@pairdraw/scene-graph/primitives";
|
|
3
3
|
//#region src/io/formats/design-tokens/css/values.d.ts
|
|
4
4
|
/** How a stylesheet writes a color, so a value written back keeps its notation. */
|
|
@@ -38,8 +38,9 @@ type CSSTokenValue = {
|
|
|
38
38
|
* font family where the property names fonts, a `var()` reference, a numeric expression, or
|
|
39
39
|
* something no variable holds, such as a shadow.
|
|
40
40
|
*/
|
|
41
|
-
declare function readCSSTokenValue(css: string, { font }?: {
|
|
42
|
-
font?: boolean
|
|
41
|
+
declare function readCSSTokenValue(css: string, { font, profile }?: {
|
|
42
|
+
font?: boolean;
|
|
43
|
+
profile?: ColorProfile;
|
|
43
44
|
}): CSSTokenValue;
|
|
44
45
|
/** Whether a custom property names fonts: `--font-sans`, `--font-family-body`, `--heading-font`. */
|
|
45
46
|
declare function namesFont(name: string): boolean;
|
|
@@ -49,12 +50,12 @@ declare function namesFont(name: string): boolean;
|
|
|
49
50
|
*/
|
|
50
51
|
declare function sameCSSTokenValue(a: CSSTokenValue, b: CSSTokenValue): boolean;
|
|
51
52
|
/** A color written in a notation: `oklch(0.7 0.19 41)`, `#ff5b2e`, `16 100% 59%`. */
|
|
52
|
-
declare function formatCSSColor(color: Color, notation: ColorNotation): string;
|
|
53
|
+
declare function formatCSSColor(color: Color, notation: ColorNotation, profile?: ColorProfile): string;
|
|
53
54
|
/**
|
|
54
55
|
* `next` written as `previous` writes its kind of value: a color in the same notation, a length
|
|
55
56
|
* in `rem` where it was in `rem`. Anything else is written as `nextCSS` has it.
|
|
56
57
|
*/
|
|
57
|
-
declare function rewriteCSSTokenValue(previous: CSSTokenValue, next: CSSTokenValue, nextCSS: string): string;
|
|
58
|
+
declare function rewriteCSSTokenValue(previous: CSSTokenValue, next: CSSTokenValue, nextCSS: string, profile?: ColorProfile): string;
|
|
58
59
|
//#endregion
|
|
59
60
|
export { CSSTokenValue, ColorNotation, formatCSSColor, namesFont, readCSSTokenValue, rewriteCSSTokenValue, sameCSSTokenValue };
|
|
60
61
|
//# sourceMappingURL=values.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"values.d.ts","names":[],"sources":["../../../../../src/io/formats/design-tokens/css/values.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"values.d.ts","names":[],"sources":["../../../../../src/io/formats/design-tokens/css/values.ts"],"mappings":";;;;KAcY;;;;KAcA;EACN;EAAe,OAAO;EAAO,UAAU;;EACvC;EAAgB;EAAe,MAAM;;EACrC;EAAgB;;EAChB;EAAc;;EACd;EAAmB;;;;EAEnB;EAAoB;EAAa,MAAM;;EACvC;EAAe;;;;;;;iBAqGL,kBACd,eACE,MAAc;EAAsB;EAAgB,UAAU;IAC/D;;iBAgCa,UAAU;;;;;iBA2BV,kBAAkB,GAAG,eAAe,GAAG;;iBAiCvC,eACd,OAAO,OACP,UAAU,eACV,UAAS;;;;;iBA8CK,qBACd,UAAU,eACV,MAAM,eACN,iBACA,UAAS"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { tokenNumberFromUnit, tokenNumberInUnit } from "@pairdraw/scene-graph/variables";
|
|
2
|
-
import { colorToCSS, parseDisplayableColor } from "@pairdraw/scene-graph/color";
|
|
2
|
+
import { SRGB_SYNTAX_MODES, colorToCSS, parseDisplayableColor, tryParseColor } from "@pairdraw/scene-graph/color";
|
|
3
3
|
import { cssTokenProperty, cssValueTokens } from "@pairdraw/dom-css/export";
|
|
4
|
-
import { converter, formatHex, formatHex8 } from "culori";
|
|
4
|
+
import { converter, formatHex, formatHex8, parse } from "culori";
|
|
5
5
|
//#region src/io/formats/design-tokens/css/values.ts
|
|
6
6
|
const NUMBER = /^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)([a-z%]*)$/i;
|
|
7
7
|
const HSL_CHANNELS = /^([+-]?[\d.]+)(?:deg)?\s+([\d.]+)%\s+([\d.]+)%(?:\s*\/\s*([\d.]+%?))?$/i;
|
|
@@ -100,11 +100,21 @@ function firstFamily(css) {
|
|
|
100
100
|
return (unquote(first.trim()) ?? first).trim() || void 0;
|
|
101
101
|
}
|
|
102
102
|
/**
|
|
103
|
+
* A CSS color in the document's profile: hex, `rgb()`, `hsl()` and `hwb()` give their numbers as
|
|
104
|
+
* the document's own, as an imported stylesheet writes them, and a color that names its space,
|
|
105
|
+
* such as `oklch()` or `color(display-p3 …)`, is converted into that profile.
|
|
106
|
+
*/
|
|
107
|
+
function readColor(value, profile) {
|
|
108
|
+
const parsed = parse(value);
|
|
109
|
+
if (!parsed || SRGB_SYNTAX_MODES.has(parsed.mode)) return parseDisplayableColor(value);
|
|
110
|
+
return tryParseColor(value, profile);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
103
113
|
* A custom property's value as a token: a color, a number in a token unit, a quoted string, a
|
|
104
114
|
* font family where the property names fonts, a `var()` reference, a numeric expression, or
|
|
105
115
|
* something no variable holds, such as a shadow.
|
|
106
116
|
*/
|
|
107
|
-
function readCSSTokenValue(css, { font = false } = {}) {
|
|
117
|
+
function readCSSTokenValue(css, { font = false, profile = "srgb" } = {}) {
|
|
108
118
|
const value = css.trim();
|
|
109
119
|
const tokens = cssValueTokens(value);
|
|
110
120
|
const [only] = tokens;
|
|
@@ -127,7 +137,7 @@ function readCSSTokenValue(css, { font = false } = {}) {
|
|
|
127
137
|
notation: "hsl-channels"
|
|
128
138
|
};
|
|
129
139
|
}
|
|
130
|
-
const color =
|
|
140
|
+
const color = readColor(value, profile);
|
|
131
141
|
if (color) return {
|
|
132
142
|
kind: "color",
|
|
133
143
|
color,
|
|
@@ -201,8 +211,14 @@ const toLCH = converter("lch");
|
|
|
201
211
|
const toOklab = converter("oklab");
|
|
202
212
|
const toOklch = converter("oklch");
|
|
203
213
|
/** A color written in a notation: `oklch(0.7 0.19 41)`, `#ff5b2e`, `16 100% 59%`. */
|
|
204
|
-
function formatCSSColor(color, notation) {
|
|
205
|
-
const rgb = {
|
|
214
|
+
function formatCSSColor(color, notation, profile = "srgb") {
|
|
215
|
+
const rgb = profile === "display-p3" ? {
|
|
216
|
+
mode: "p3",
|
|
217
|
+
r: color.r,
|
|
218
|
+
g: color.g,
|
|
219
|
+
b: color.b,
|
|
220
|
+
alpha: color.a
|
|
221
|
+
} : {
|
|
206
222
|
mode: "rgb",
|
|
207
223
|
r: color.r,
|
|
208
224
|
g: color.g,
|
|
@@ -245,8 +261,8 @@ function formatCSSColor(color, notation) {
|
|
|
245
261
|
* `next` written as `previous` writes its kind of value: a color in the same notation, a length
|
|
246
262
|
* in `rem` where it was in `rem`. Anything else is written as `nextCSS` has it.
|
|
247
263
|
*/
|
|
248
|
-
function rewriteCSSTokenValue(previous, next, nextCSS) {
|
|
249
|
-
if (previous.kind === "color" && next.kind === "color" && previous.notation !== "other") return formatCSSColor(next.color, previous.notation);
|
|
264
|
+
function rewriteCSSTokenValue(previous, next, nextCSS, profile = "srgb") {
|
|
265
|
+
if (previous.kind === "color" && next.kind === "color" && previous.notation !== "other") return formatCSSColor(next.color, previous.notation, profile);
|
|
250
266
|
if (previous.kind === "number" && next.kind === "number" && previous.unit === "rem" && next.unit === "px") return `${Number(tokenNumberInUnit(next.value, "rem").toFixed(6))}rem`;
|
|
251
267
|
return nextCSS;
|
|
252
268
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"values.js","names":[],"sources":["../../../../../src/io/formats/design-tokens/css/values.ts"],"sourcesContent":["import { converter, formatHex, formatHex8 } from 'culori'\n\nimport { cssTokenProperty, cssValueTokens } from '@pairdraw/dom-css/export'\nimport type { TokenUnit } from '@pairdraw/scene-graph'\nimport { colorToCSS, parseDisplayableColor } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\nimport { tokenNumberFromUnit, tokenNumberInUnit } from '@pairdraw/scene-graph/variables'\n\n/** How a stylesheet writes a color, so a value written back keeps its notation. */\nexport type ColorNotation =\n | 'hex'\n | 'rgb'\n | 'hsl'\n /** `220 14% 96%`: HSL channels for `hsl(var(--x))`, as shadcn/ui themes wrote them. */\n | 'hsl-channels'\n | 'hwb'\n | 'lab'\n | 'lch'\n | 'oklab'\n | 'oklch'\n | 'other'\n\n/** A custom property's value as a token reads it. Numbers are stored as variables hold them. */\nexport type CSSTokenValue =\n | { kind: 'color'; color: Color; notation: ColorNotation }\n | { kind: 'number'; value: number; unit: TokenUnit }\n | { kind: 'string'; value: string }\n | { kind: 'font'; family: string }\n | { kind: 'reference'; name: string }\n /** A number only a CSS engine computes, `clamp(1rem, 4vw, 1.5rem)`; `unit` when it says one. */\n | { kind: 'expression'; css: string; unit: TokenUnit | undefined }\n | { kind: 'other'; css: string }\n\nconst NUMBER = /^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?)([a-z%]*)$/i\nconst HSL_CHANNELS = /^([+-]?[\\d.]+)(?:deg)?\\s+([\\d.]+)%\\s+([\\d.]+)%(?:\\s*\\/\\s*([\\d.]+%?))?$/i\nconst COLOR_FUNCTIONS: Record<string, ColorNotation> = {\n rgb: 'rgb',\n rgba: 'rgb',\n hsl: 'hsl',\n hsla: 'hsl',\n hwb: 'hwb',\n lab: 'lab',\n lch: 'lch',\n oklab: 'oklab',\n oklch: 'oklch'\n}\nconst LITERAL_UNITS: Partial<Record<string, TokenUnit>> = {\n '': 'none',\n px: 'px',\n rem: 'rem',\n '%': '%',\n ms: 'ms',\n s: 's',\n deg: 'deg'\n}\nconst ANGLE_UNITS = new Set(['rad', 'grad', 'turn'])\n/** Functions whose result is a number a variable can hold once a CSS engine computes it. */\nconst NUMERIC_FUNCTIONS = new Set(['calc', 'clamp', 'min', 'max', 'round', 'abs', 'var'])\n\nfunction notationOf(css: string): ColorNotation {\n if (css.startsWith('#')) return 'hex'\n const name = /^([a-z-]+)\\(/i.exec(css)?.[1]?.toLowerCase()\n return (name && COLOR_FUNCTIONS[name]) || 'other'\n}\n\n/** `16px`, `1.5rem`, `150ms`, `0.5`: the stored number and its unit, or a unit only CSS computes. */\nfunction readNumber(css: string): CSSTokenValue | undefined {\n const match = NUMBER.exec(css)\n if (!match) return undefined\n const number = Number(match[1])\n if (!Number.isFinite(number)) return undefined\n const written = match[2].toLowerCase()\n const unit = LITERAL_UNITS[written]\n if (unit) return { kind: 'number', value: tokenNumberFromUnit(number, unit), unit }\n return { kind: 'expression', css, unit: ANGLE_UNITS.has(written) ? 'deg' : 'px' }\n}\n\n/** The unit a CSS expression's own numbers are written in, if any. */\nfunction expressionUnit(css: string): TokenUnit | undefined {\n let other = false\n for (const token of cssValueTokens(css)) {\n if (token.kind !== 'number') continue\n const unit = NUMBER.exec(token.text)?.[2].toLowerCase() ?? ''\n if (!unit) continue\n const literal = LITERAL_UNITS[unit]\n if (literal) return literal\n other = true\n }\n return other ? 'px' : undefined\n}\n\nfunction readExpression(css: string): CSSTokenValue | undefined {\n const tokens = cssValueTokens(css)\n const first = tokens.at(0)\n if (first?.kind !== 'function' || !NUMERIC_FUNCTIONS.has(first.text.toLowerCase())) {\n return undefined\n }\n const last = tokens.at(-1)\n // One function call and nothing after it: `calc(…)`, not `calc(…) solid red`.\n if (last?.kind !== 'paren' || last.to !== css.length) return undefined\n return { kind: 'expression', css, unit: expressionUnit(css) }\n}\n\nfunction unquote(css: string): string | undefined {\n const match = /^([\"'])([\\s\\S]*)\\1$/.exec(css)\n if (!match) return undefined\n return match[2].replaceAll(/\\\\a\\s?/gi, '\\n').replaceAll(/\\\\([\\s\\S])/g, '$1')\n}\n\n/** The first family of a `font-family` list, unquoted. */\nfunction firstFamily(css: string): string | undefined {\n const [first = ''] = css.split(',')\n const family = (unquote(first.trim()) ?? first).trim()\n return family || undefined\n}\n\n/**\n * A custom property's value as a token: a color, a number in a token unit, a quoted string, a\n * font family where the property names fonts, a `var()` reference, a numeric expression, or\n * something no variable holds, such as a shadow.\n */\nexport function readCSSTokenValue(css: string, { font = false } = {}): CSSTokenValue {\n const value = css.trim()\n const tokens = cssValueTokens(value)\n const [only] = tokens\n if (tokens.length === 1 && only.kind === 'reference') {\n const name = cssTokenProperty(only)\n if (name) return { kind: 'reference', name: name.slice(2) }\n }\n const number = readNumber(value)\n if (number) return number\n const channels = HSL_CHANNELS.exec(value)\n if (channels) {\n const [, hue, saturation, lightness, alpha] = channels\n const color = parseDisplayableColor(\n `hsl(${hue} ${saturation}% ${lightness}%${alpha ? ` / ${alpha}` : ''})`\n )\n if (color) return { kind: 'color', color, notation: 'hsl-channels' }\n }\n const color = parseDisplayableColor(value)\n if (color) return { kind: 'color', color, notation: notationOf(value) }\n const expression = readExpression(value)\n if (expression) return expression\n if (font) {\n const family = firstFamily(value)\n if (family) return { kind: 'font', family }\n }\n const string = unquote(value)\n if (string !== undefined) return { kind: 'string', value: string }\n return { kind: 'other', css: value }\n}\n\n/** Whether a custom property names fonts: `--font-sans`, `--font-family-body`, `--heading-font`. */\nexport function namesFont(name: string): boolean {\n return name === 'font' || name.startsWith('font-') || name.endsWith('-font')\n}\n\n/** Color channels are stored as floats; this absorbs rounding through other color spaces. */\nconst CHANNEL_TOLERANCE = 1 / 512\n\nfunction sameColor(a: Color, b: Color): boolean {\n return (['r', 'g', 'b', 'a'] as const).every(\n (channel) => Math.abs(a[channel] - b[channel]) <= CHANNEL_TOLERANCE\n )\n}\n\nconst LENGTH_UNITS = new Set<TokenUnit>(['px', 'rem'])\n\nfunction sameUnitKind(a: TokenUnit, b: TokenUnit): boolean {\n return a === b || (LENGTH_UNITS.has(a) && LENGTH_UNITS.has(b))\n}\n\nfunction collapse(css: string): string {\n return css.replaceAll(/\\s+/g, ' ').trim()\n}\n\n/**\n * Whether two values mean the same token value, however each is written: `16px` and `1rem`,\n * `#fff` and `oklch(1 0 0)`, or two font lists that start with the same family.\n */\nexport function sameCSSTokenValue(a: CSSTokenValue, b: CSSTokenValue): boolean {\n if (a.kind === 'color' && b.kind === 'color') return sameColor(a.color, b.color)\n if (a.kind === 'number' && b.kind === 'number')\n return sameUnitKind(a.unit, b.unit) && Math.abs(a.value - b.value) < 1e-6\n if (a.kind === 'string' && b.kind === 'string') return a.value === b.value\n if (a.kind === 'font' && b.kind === 'font') return a.family === b.family\n if (a.kind === 'font' && b.kind === 'string') return a.family === b.value\n if (a.kind === 'string' && b.kind === 'font') return a.value === b.family\n if (a.kind === 'reference' && b.kind === 'reference') return a.name === b.name\n if (\n (a.kind === 'expression' || a.kind === 'other') &&\n (b.kind === 'expression' || b.kind === 'other')\n )\n return collapse(a.css) === collapse(b.css)\n return false\n}\n\nfunction round(value: number | undefined, digits: number): number {\n return Number((value ?? 0).toFixed(digits))\n}\n\nfunction alphaSuffix(alpha: number): string {\n return alpha < 1 ? ` / ${round(alpha, 3)}` : ''\n}\n\nconst toHSL = converter('hsl')\nconst toHWB = converter('hwb')\nconst toLab = converter('lab')\nconst toLCH = converter('lch')\nconst toOklab = converter('oklab')\nconst toOklch = converter('oklch')\n\n/** A color written in a notation: `oklch(0.7 0.19 41)`, `#ff5b2e`, `16 100% 59%`. */\nexport function formatCSSColor(color: Color, notation: ColorNotation): string {\n const rgb = { mode: 'rgb' as const, r: color.r, g: color.g, b: color.b, alpha: color.a }\n const a = alphaSuffix(color.a)\n switch (notation) {\n case 'rgb':\n return colorToCSS(color)\n case 'hsl':\n case 'hsl-channels': {\n const { h, s, l } = toHSL(rgb)\n const channels = `${round(h, 1)} ${round(s * 100, 1)}% ${round(l * 100, 1)}%`\n return notation === 'hsl' ? `hsl(${channels}${a})` : `${channels}${a}`\n }\n case 'hwb': {\n const { h, w, b } = toHWB(rgb)\n return `hwb(${round(h, 1)} ${round(w * 100, 1)}% ${round(b * 100, 1)}%${a})`\n }\n case 'lab': {\n const { l, a: x, b } = toLab(rgb)\n return `lab(${round(l, 2)} ${round(x, 2)} ${round(b, 2)}${a})`\n }\n case 'lch': {\n const { l, c, h } = toLCH(rgb)\n return `lch(${round(l, 2)} ${round(c, 2)} ${round(h, 2)}${a})`\n }\n case 'oklab': {\n const { l, a: x, b } = toOklab(rgb)\n return `oklab(${round(l, 4)} ${round(x, 4)} ${round(b, 4)}${a})`\n }\n case 'oklch': {\n const { l, c, h } = toOklch(rgb)\n return `oklch(${round(l, 4)} ${round(c, 4)} ${round(h, 2)}${a})`\n }\n default:\n return color.a < 1 ? formatHex8(rgb) : formatHex(rgb)\n }\n}\n\n/**\n * `next` written as `previous` writes its kind of value: a color in the same notation, a length\n * in `rem` where it was in `rem`. Anything else is written as `nextCSS` has it.\n */\nexport function rewriteCSSTokenValue(\n previous: CSSTokenValue,\n next: CSSTokenValue,\n nextCSS: string\n): string {\n if (previous.kind === 'color' && next.kind === 'color' && previous.notation !== 'other')\n return formatCSSColor(next.color, previous.notation)\n if (\n previous.kind === 'number' &&\n next.kind === 'number' &&\n previous.unit === 'rem' &&\n next.unit === 'px'\n )\n return `${Number(tokenNumberInUnit(next.value, 'rem').toFixed(6))}rem`\n return nextCSS\n}\n"],"mappings":";;;;;AAiCA,MAAM,SAAS;AACf,MAAM,eAAe;AACrB,MAAM,kBAAiD;CACrD,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACN,KAAK;CACL,KAAK;CACL,KAAK;CACL,OAAO;CACP,OAAO;AACT;AACA,MAAM,gBAAoD;CACxD,IAAI;CACJ,IAAI;CACJ,KAAK;CACL,KAAK;CACL,IAAI;CACJ,GAAG;CACH,KAAK;AACP;AACA,MAAM,8BAAc,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAM,CAAC;;AAEnD,MAAM,oCAAoB,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAO;CAAO;CAAS;CAAO;AAAK,CAAC;AAExF,SAAS,WAAW,KAA4B;CAC9C,IAAI,IAAI,WAAW,GAAG,GAAG,OAAO;CAChC,MAAM,OAAO,gBAAgB,KAAK,GAAG,CAAC,GAAG,EAAE,EAAE,YAAY;CACzD,OAAQ,QAAQ,gBAAgB,SAAU;AAC5C;;AAGA,SAAS,WAAW,KAAwC;CAC1D,MAAM,QAAQ,OAAO,KAAK,GAAG;CAC7B,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,SAAS,OAAO,MAAM,EAAE;CAC9B,IAAI,CAAC,OAAO,SAAS,MAAM,GAAG,OAAO,KAAA;CACrC,MA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C7B,OAAO,OAAO,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE;EAC9D;EACA,KAAK,SAAS;GACZ,MAAM,EAAE,GAAG,GAAG,GAAG,MAAM,QAAQ,GAAG;GAClC,OAAO,SAAS,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE;EAChE;EACA,KAAK,SAAS;GACZ,MAAM,EAAE,GAAG,GAAG,MAAM,QAAQ,GAAG;GAC/B,OAAO,SAAS,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE;EAChE;EACA,SACE,OAAO,MAAM,IAAI,IAAI,WAAW,GAAG,IAAI,UAAU,GAAG;CACxD;AACF;;;;;AAMA,SAAgB,qBACd,UACA,MACA,SACQ;CACR,IAAI,SAAS,SAAS,WAAW,KAAK,SAAS,WAAW,SAAS,aAAa,SAC9E,OAAO,eAAe,KAAK,OAAO,SAAS,QAAQ;CACrD,IACE,SAAS,SAAS,YAClB,KAAK,SAAS,YACd,SAAS,SAAS,SAClB,KAAK,SAAS,MAEd,OAAO,GAAG,OAAO,kBAAkB,KAAK,OAAO,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE;CACpE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"values.js","names":[],"sources":["../../../../../src/io/formats/design-tokens/css/values.ts"],"sourcesContent":["import { converter, formatHex, formatHex8, parse } from 'culori'\n\nimport { cssTokenProperty, cssValueTokens } from '@pairdraw/dom-css/export'\nimport type { ColorProfile, TokenUnit } from '@pairdraw/scene-graph'\nimport {\n colorToCSS,\n parseDisplayableColor,\n SRGB_SYNTAX_MODES,\n tryParseColor\n} from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\nimport { tokenNumberFromUnit, tokenNumberInUnit } from '@pairdraw/scene-graph/variables'\n\n/** How a stylesheet writes a color, so a value written back keeps its notation. */\nexport type ColorNotation =\n | 'hex'\n | 'rgb'\n | 'hsl'\n /** `220 14% 96%`: HSL channels for `hsl(var(--x))`, as shadcn/ui themes wrote them. */\n | 'hsl-channels'\n | 'hwb'\n | 'lab'\n | 'lch'\n | 'oklab'\n | 'oklch'\n | 'other'\n\n/** A custom property's value as a token reads it. Numbers are stored as variables hold them. */\nexport type CSSTokenValue =\n | { kind: 'color'; color: Color; notation: ColorNotation }\n | { kind: 'number'; value: number; unit: TokenUnit }\n | { kind: 'string'; value: string }\n | { kind: 'font'; family: string }\n | { kind: 'reference'; name: string }\n /** A number only a CSS engine computes, `clamp(1rem, 4vw, 1.5rem)`; `unit` when it says one. */\n | { kind: 'expression'; css: string; unit: TokenUnit | undefined }\n | { kind: 'other'; css: string }\n\nconst NUMBER = /^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?)([a-z%]*)$/i\nconst HSL_CHANNELS = /^([+-]?[\\d.]+)(?:deg)?\\s+([\\d.]+)%\\s+([\\d.]+)%(?:\\s*\\/\\s*([\\d.]+%?))?$/i\nconst COLOR_FUNCTIONS: Record<string, ColorNotation> = {\n rgb: 'rgb',\n rgba: 'rgb',\n hsl: 'hsl',\n hsla: 'hsl',\n hwb: 'hwb',\n lab: 'lab',\n lch: 'lch',\n oklab: 'oklab',\n oklch: 'oklch'\n}\nconst LITERAL_UNITS: Partial<Record<string, TokenUnit>> = {\n '': 'none',\n px: 'px',\n rem: 'rem',\n '%': '%',\n ms: 'ms',\n s: 's',\n deg: 'deg'\n}\nconst ANGLE_UNITS = new Set(['rad', 'grad', 'turn'])\n/** Functions whose result is a number a variable can hold once a CSS engine computes it. */\nconst NUMERIC_FUNCTIONS = new Set(['calc', 'clamp', 'min', 'max', 'round', 'abs', 'var'])\n\nfunction notationOf(css: string): ColorNotation {\n if (css.startsWith('#')) return 'hex'\n const name = /^([a-z-]+)\\(/i.exec(css)?.[1]?.toLowerCase()\n return (name && COLOR_FUNCTIONS[name]) || 'other'\n}\n\n/** `16px`, `1.5rem`, `150ms`, `0.5`: the stored number and its unit, or a unit only CSS computes. */\nfunction readNumber(css: string): CSSTokenValue | undefined {\n const match = NUMBER.exec(css)\n if (!match) return undefined\n const number = Number(match[1])\n if (!Number.isFinite(number)) return undefined\n const written = match[2].toLowerCase()\n const unit = LITERAL_UNITS[written]\n if (unit) return { kind: 'number', value: tokenNumberFromUnit(number, unit), unit }\n return { kind: 'expression', css, unit: ANGLE_UNITS.has(written) ? 'deg' : 'px' }\n}\n\n/** The unit a CSS expression's own numbers are written in, if any. */\nfunction expressionUnit(css: string): TokenUnit | undefined {\n let other = false\n for (const token of cssValueTokens(css)) {\n if (token.kind !== 'number') continue\n const unit = NUMBER.exec(token.text)?.[2].toLowerCase() ?? ''\n if (!unit) continue\n const literal = LITERAL_UNITS[unit]\n if (literal) return literal\n other = true\n }\n return other ? 'px' : undefined\n}\n\nfunction readExpression(css: string): CSSTokenValue | undefined {\n const tokens = cssValueTokens(css)\n const first = tokens.at(0)\n if (first?.kind !== 'function' || !NUMERIC_FUNCTIONS.has(first.text.toLowerCase())) {\n return undefined\n }\n const last = tokens.at(-1)\n // One function call and nothing after it: `calc(…)`, not `calc(…) solid red`.\n if (last?.kind !== 'paren' || last.to !== css.length) return undefined\n return { kind: 'expression', css, unit: expressionUnit(css) }\n}\n\nfunction unquote(css: string): string | undefined {\n const match = /^([\"'])([\\s\\S]*)\\1$/.exec(css)\n if (!match) return undefined\n return match[2].replaceAll(/\\\\a\\s?/gi, '\\n').replaceAll(/\\\\([\\s\\S])/g, '$1')\n}\n\n/** The first family of a `font-family` list, unquoted. */\nfunction firstFamily(css: string): string | undefined {\n const [first = ''] = css.split(',')\n const family = (unquote(first.trim()) ?? first).trim()\n return family || undefined\n}\n\n/**\n * A CSS color in the document's profile: hex, `rgb()`, `hsl()` and `hwb()` give their numbers as\n * the document's own, as an imported stylesheet writes them, and a color that names its space,\n * such as `oklch()` or `color(display-p3 …)`, is converted into that profile.\n */\nfunction readColor(value: string, profile: ColorProfile): Color | null {\n const parsed = parse(value)\n if (!parsed || SRGB_SYNTAX_MODES.has(parsed.mode)) return parseDisplayableColor(value)\n return tryParseColor(value, profile)\n}\n\n/**\n * A custom property's value as a token: a color, a number in a token unit, a quoted string, a\n * font family where the property names fonts, a `var()` reference, a numeric expression, or\n * something no variable holds, such as a shadow.\n */\nexport function readCSSTokenValue(\n css: string,\n { font = false, profile = 'srgb' }: { font?: boolean; profile?: ColorProfile } = {}\n): CSSTokenValue {\n const value = css.trim()\n const tokens = cssValueTokens(value)\n const [only] = tokens\n if (tokens.length === 1 && only.kind === 'reference') {\n const name = cssTokenProperty(only)\n if (name) return { kind: 'reference', name: name.slice(2) }\n }\n const number = readNumber(value)\n if (number) return number\n const channels = HSL_CHANNELS.exec(value)\n if (channels) {\n const [, hue, saturation, lightness, alpha] = channels\n const color = parseDisplayableColor(\n `hsl(${hue} ${saturation}% ${lightness}%${alpha ? ` / ${alpha}` : ''})`\n )\n if (color) return { kind: 'color', color, notation: 'hsl-channels' }\n }\n const color = readColor(value, profile)\n if (color) return { kind: 'color', color, notation: notationOf(value) }\n const expression = readExpression(value)\n if (expression) return expression\n if (font) {\n const family = firstFamily(value)\n if (family) return { kind: 'font', family }\n }\n const string = unquote(value)\n if (string !== undefined) return { kind: 'string', value: string }\n return { kind: 'other', css: value }\n}\n\n/** Whether a custom property names fonts: `--font-sans`, `--font-family-body`, `--heading-font`. */\nexport function namesFont(name: string): boolean {\n return name === 'font' || name.startsWith('font-') || name.endsWith('-font')\n}\n\n/** Color channels are stored as floats; this absorbs rounding through other color spaces. */\nconst CHANNEL_TOLERANCE = 1 / 512\n\nfunction sameColor(a: Color, b: Color): boolean {\n return (['r', 'g', 'b', 'a'] as const).every(\n (channel) => Math.abs(a[channel] - b[channel]) <= CHANNEL_TOLERANCE\n )\n}\n\nconst LENGTH_UNITS = new Set<TokenUnit>(['px', 'rem'])\n\nfunction sameUnitKind(a: TokenUnit, b: TokenUnit): boolean {\n return a === b || (LENGTH_UNITS.has(a) && LENGTH_UNITS.has(b))\n}\n\nfunction collapse(css: string): string {\n return css.replaceAll(/\\s+/g, ' ').trim()\n}\n\n/**\n * Whether two values mean the same token value, however each is written: `16px` and `1rem`,\n * `#fff` and `oklch(1 0 0)`, or two font lists that start with the same family.\n */\nexport function sameCSSTokenValue(a: CSSTokenValue, b: CSSTokenValue): boolean {\n if (a.kind === 'color' && b.kind === 'color') return sameColor(a.color, b.color)\n if (a.kind === 'number' && b.kind === 'number')\n return sameUnitKind(a.unit, b.unit) && Math.abs(a.value - b.value) < 1e-6\n if (a.kind === 'string' && b.kind === 'string') return a.value === b.value\n if (a.kind === 'font' && b.kind === 'font') return a.family === b.family\n if (a.kind === 'font' && b.kind === 'string') return a.family === b.value\n if (a.kind === 'string' && b.kind === 'font') return a.value === b.family\n if (a.kind === 'reference' && b.kind === 'reference') return a.name === b.name\n if (\n (a.kind === 'expression' || a.kind === 'other') &&\n (b.kind === 'expression' || b.kind === 'other')\n )\n return collapse(a.css) === collapse(b.css)\n return false\n}\n\nfunction round(value: number | undefined, digits: number): number {\n return Number((value ?? 0).toFixed(digits))\n}\n\nfunction alphaSuffix(alpha: number): string {\n return alpha < 1 ? ` / ${round(alpha, 3)}` : ''\n}\n\nconst toHSL = converter('hsl')\nconst toHWB = converter('hwb')\nconst toLab = converter('lab')\nconst toLCH = converter('lch')\nconst toOklab = converter('oklab')\nconst toOklch = converter('oklch')\n\n/** A color written in a notation: `oklch(0.7 0.19 41)`, `#ff5b2e`, `16 100% 59%`. */\nexport function formatCSSColor(\n color: Color,\n notation: ColorNotation,\n profile: ColorProfile = 'srgb'\n): string {\n // The components sit in the document's profile, so the notation is derived from that space.\n const rgb =\n profile === 'display-p3'\n ? { mode: 'p3' as const, r: color.r, g: color.g, b: color.b, alpha: color.a }\n : { mode: 'rgb' as const, r: color.r, g: color.g, b: color.b, alpha: color.a }\n const a = alphaSuffix(color.a)\n switch (notation) {\n case 'rgb':\n return colorToCSS(color)\n case 'hsl':\n case 'hsl-channels': {\n const { h, s, l } = toHSL(rgb)\n const channels = `${round(h, 1)} ${round(s * 100, 1)}% ${round(l * 100, 1)}%`\n return notation === 'hsl' ? `hsl(${channels}${a})` : `${channels}${a}`\n }\n case 'hwb': {\n const { h, w, b } = toHWB(rgb)\n return `hwb(${round(h, 1)} ${round(w * 100, 1)}% ${round(b * 100, 1)}%${a})`\n }\n case 'lab': {\n const { l, a: x, b } = toLab(rgb)\n return `lab(${round(l, 2)} ${round(x, 2)} ${round(b, 2)}${a})`\n }\n case 'lch': {\n const { l, c, h } = toLCH(rgb)\n return `lch(${round(l, 2)} ${round(c, 2)} ${round(h, 2)}${a})`\n }\n case 'oklab': {\n const { l, a: x, b } = toOklab(rgb)\n return `oklab(${round(l, 4)} ${round(x, 4)} ${round(b, 4)}${a})`\n }\n case 'oklch': {\n const { l, c, h } = toOklch(rgb)\n return `oklch(${round(l, 4)} ${round(c, 4)} ${round(h, 2)}${a})`\n }\n default:\n return color.a < 1 ? formatHex8(rgb) : formatHex(rgb)\n }\n}\n\n/**\n * `next` written as `previous` writes its kind of value: a color in the same notation, a length\n * in `rem` where it was in `rem`. Anything else is written as `nextCSS` has it.\n */\nexport function rewriteCSSTokenValue(\n previous: CSSTokenValue,\n next: CSSTokenValue,\n nextCSS: string,\n profile: ColorProfile = 'srgb'\n): string {\n if (previous.kind === 'color' && next.kind === 'color' && previous.notation !== 'other')\n return formatCSSColor(next.color, previous.notation, profile)\n if (\n previous.kind === 'number' &&\n next.kind === 'number' &&\n previous.unit === 'rem' &&\n next.unit === 'px'\n )\n return `${Number(tokenNumberInUnit(next.value, 'rem').toFixed(6))}rem`\n return nextCSS\n}\n"],"mappings":";;;;;AAsCA,MAAM,SAAS;AACf,MAAM,eAAe;AACrB,MAAM,kBAAiD;CACrD,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;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GAAG,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE;EAChE;EACA,KAAK,SAAS;GACZ,MAAM,EAAE,GAAG,GAAG,MAAM,QAAQ,GAAG;GAC/B,OAAO,SAAS,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,EAAE,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE;EAChE;EACA,SACE,OAAO,MAAM,IAAI,IAAI,WAAW,GAAG,IAAI,UAAU,GAAG;CACxD;AACF;;;;;AAMA,SAAgB,qBACd,UACA,MACA,SACA,UAAwB,QAChB;CACR,IAAI,SAAS,SAAS,WAAW,KAAK,SAAS,WAAW,SAAS,aAAa,SAC9E,OAAO,eAAe,KAAK,OAAO,SAAS,UAAU,OAAO;CAC9D,IACE,SAAS,SAAS,YAClB,KAAK,SAAS,YACd,SAAS,SAAS,SAClB,KAAK,SAAS,MAEd,OAAO,GAAG,OAAO,kBAAkB,KAAK,OAAO,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE;CACpE,OAAO;AACT"}
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { ReadToken } from "./read.js";
|
|
2
|
-
import { CodeSyntaxPlatform, TokenUnit, VariableScope, VariableType } from "@pairdraw/scene-graph";
|
|
2
|
+
import { CodeSyntaxPlatform, DocumentColorSpace, TokenUnit, VariableScope, VariableType } from "@pairdraw/scene-graph";
|
|
3
3
|
import { Color } from "@pairdraw/scene-graph/primitives";
|
|
4
4
|
//#region src/io/formats/design-tokens/decode.d.ts
|
|
5
5
|
/** A `{group.token}` reference, as its path segments. */
|
|
6
6
|
declare function referencePath(value: unknown): string[] | null;
|
|
7
7
|
/**
|
|
8
|
-
* A DTCG color in
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* A DTCG color as components in `profile`, the importing document's. The 2025.10 object form names
|
|
9
|
+
* its space; it is written as CSS and read as CSS colors are: an sRGB one keeps its numbers, as
|
|
10
|
+
* Figma takes hex, and one in another space, such as Display P3, is converted into `profile`.
|
|
11
|
+
* Earlier drafts wrote any CSS color string, which reads the same way.
|
|
11
12
|
*/
|
|
12
|
-
declare function decodeColor(value: unknown): Color | null;
|
|
13
|
+
declare function decodeColor(value: unknown, profile: DocumentColorSpace): Color | null;
|
|
13
14
|
/** A length in canvas pixels and the unit it was written in. */
|
|
14
15
|
declare function decodeDimension(value: unknown): {
|
|
15
16
|
value: number;
|
|
@@ -49,7 +50,7 @@ type DecodeFailure = 'unsupported-type' | 'invalid-value';
|
|
|
49
50
|
/** A token's type as a variable type, or undefined for an alias that must take its target's. */
|
|
50
51
|
declare function variableTypeOf(token: ReadToken): VariableType | DecodeFailure | undefined;
|
|
51
52
|
/** A token as a variable value and Pairdraw's own token fields. */
|
|
52
|
-
declare function decodeVariableToken(token: ReadToken): DecodedVariable | DecodeFailure;
|
|
53
|
+
declare function decodeVariableToken(token: ReadToken, profile: DocumentColorSpace): DecodedVariable | DecodeFailure;
|
|
53
54
|
//#endregion
|
|
54
55
|
export { DecodeFailure, DecodedValue, DecodedVariable, decodeColor, decodeDimension, decodeFontFamily, decodeFontWeight, decodeVariableToken, referencePath, variableTypeOf };
|
|
55
56
|
//# sourceMappingURL=decode.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decode.d.ts","names":[],"sources":["../../../../src/io/formats/design-tokens/decode.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"decode.d.ts","names":[],"sources":["../../../../src/io/formats/design-tokens/decode.ts"],"mappings":";;;;;iBAqBgB,cAAc;;;;;;;iBAwCd,YAAY,gBAAgB,SAAS,qBAAqB;;iBAiB1D,gBAAgB;EAAmB;EAAe,MAAM;;iBAoCxD,iBAAiB;;iBAMjB,iBAAiB;;KAkBrB;EACN;EAAiB,OAAO;;EACxB;EAAe;EAAyB;EAAqB;;;UAGlD;EACf,MAAM;EACN,OAAO;EACP,OAAO;EACP;EACA,SAAS;EACT,aAAa,QAAQ,OAAO;EAC5B;EACA;;;;;EAKA;;;KAIU;;iBAOI,eAAe,OAAO,YAAY,eAAe;;iBAuFjD,oBACd,OAAO,WACP,SAAS,qBACR,kBAAkB"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { PAIRDRAW_EXTENSION } from "./types.js";
|
|
2
2
|
import { ROOT_FONT_SIZE_PX } from "@pairdraw/scene-graph/variables";
|
|
3
|
+
import { tryParseColor } from "@pairdraw/scene-graph/color";
|
|
3
4
|
import { CODE_SYNTAX_PLATFORMS, TOKEN_UNITS, VARIABLE_SCOPES } from "@pairdraw/scene-graph";
|
|
4
5
|
import { parseCSSNumber } from "@pairdraw/scene-graph/css";
|
|
5
|
-
import { parseDisplayableColor } from "@pairdraw/scene-graph/color";
|
|
6
6
|
import * as v from "valibot";
|
|
7
7
|
//#region src/io/formats/design-tokens/decode.ts
|
|
8
8
|
/** A `{group.token}` reference, as its path segments. */
|
|
@@ -38,19 +38,20 @@ const colorObjectSchema = v.object({
|
|
|
38
38
|
hex: v.optional(v.string())
|
|
39
39
|
});
|
|
40
40
|
/**
|
|
41
|
-
* A DTCG color in
|
|
42
|
-
*
|
|
43
|
-
*
|
|
41
|
+
* A DTCG color as components in `profile`, the importing document's. The 2025.10 object form names
|
|
42
|
+
* its space; it is written as CSS and read as CSS colors are: an sRGB one keeps its numbers, as
|
|
43
|
+
* Figma takes hex, and one in another space, such as Display P3, is converted into `profile`.
|
|
44
|
+
* Earlier drafts wrote any CSS color string, which reads the same way.
|
|
44
45
|
*/
|
|
45
|
-
function decodeColor(value) {
|
|
46
|
-
if (typeof value === "string") return
|
|
46
|
+
function decodeColor(value, profile) {
|
|
47
|
+
if (typeof value === "string") return tryParseColor(value, profile);
|
|
47
48
|
const parsed = v.safeParse(colorObjectSchema, value);
|
|
48
49
|
if (!parsed.success) return null;
|
|
49
50
|
const { colorSpace, components, alpha = 1, hex } = parsed.output;
|
|
50
51
|
const parts = components.map(String);
|
|
51
52
|
const open = PREDEFINED_SPACES.has(colorSpace) ? `color(${colorSpace} ${parts.join(" ")}` : FUNCTION_SPACES[colorSpace]?.(parts);
|
|
52
|
-
if (!open) return hex ?
|
|
53
|
-
return
|
|
53
|
+
if (!open) return hex ? tryParseColor(hex, profile) : null;
|
|
54
|
+
return tryParseColor(`${open} / ${alpha})`, profile);
|
|
54
55
|
}
|
|
55
56
|
const dimensionSchema = v.object({
|
|
56
57
|
value: v.number(),
|
|
@@ -154,11 +155,11 @@ function valueInUnit(literal, unit) {
|
|
|
154
155
|
return value;
|
|
155
156
|
}
|
|
156
157
|
/** A literal in the shape its type takes, with the unit it was written in. */
|
|
157
|
-
function decodeLiteral(token) {
|
|
158
|
+
function decodeLiteral(token, profile) {
|
|
158
159
|
const { value } = token;
|
|
159
160
|
switch (token.type) {
|
|
160
161
|
case "color": {
|
|
161
|
-
const color = decodeColor(value);
|
|
162
|
+
const color = decodeColor(value, profile);
|
|
162
163
|
return color && { value: color };
|
|
163
164
|
}
|
|
164
165
|
case "dimension": return decodeDimension(value);
|
|
@@ -186,7 +187,7 @@ function impliedScopes(token) {
|
|
|
186
187
|
if (token.type === "fontWeight") return ["FONT_STYLE"];
|
|
187
188
|
}
|
|
188
189
|
/** A token as a variable value and Pairdraw's own token fields. */
|
|
189
|
-
function decodeVariableToken(token) {
|
|
190
|
+
function decodeVariableToken(token, profile) {
|
|
190
191
|
const type = variableTypeOf(token);
|
|
191
192
|
if (type === "unsupported-type" || type === "invalid-value") return type;
|
|
192
193
|
const own = v.safeParse(ownFieldsSchema, token.extensions[PAIRDRAW_EXTENSION]);
|
|
@@ -203,7 +204,7 @@ function decodeVariableToken(token) {
|
|
|
203
204
|
name: figma.success ? figma.output.targetVariableName : void 0
|
|
204
205
|
};
|
|
205
206
|
} else {
|
|
206
|
-
const literal = decodeLiteral(token);
|
|
207
|
+
const literal = decodeLiteral(token, profile);
|
|
207
208
|
if (!literal) return "invalid-value";
|
|
208
209
|
unit ??= literal.unit === "px" ? void 0 : literal.unit;
|
|
209
210
|
value = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decode.js","names":[],"sources":["../../../../src/io/formats/design-tokens/decode.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport {\n CODE_SYNTAX_PLATFORMS,\n TOKEN_UNITS,\n VARIABLE_SCOPES,\n type CodeSyntaxPlatform,\n type TokenUnit,\n type VariableScope,\n type VariableType\n} from '@pairdraw/scene-graph'\nimport { parseDisplayableColor } from '@pairdraw/scene-graph/color'\nimport { parseCSSNumber } from '@pairdraw/scene-graph/css'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\nimport { ROOT_FONT_SIZE_PX } from '@pairdraw/scene-graph/variables'\n\nimport type { ReadToken } from './read'\nimport { PAIRDRAW_EXTENSION } from './types'\n\n/** A `{group.token}` reference, as its path segments. */\nexport function referencePath(value: unknown): string[] | null {\n if (typeof value !== 'string' || !value.startsWith('{') || !value.endsWith('}')) return null\n const inner = value.slice(1, -1)\n return inner && !/[{}]/.test(inner) ? inner.split('.') : null\n}\n\n/** CSS Color 4 spaces DTCG names, as `color()` takes them. */\nconst PREDEFINED_SPACES = new Set([\n 'srgb',\n 'srgb-linear',\n 'display-p3',\n 'a98-rgb',\n 'prophoto-rgb',\n 'rec2020',\n 'xyz-d65',\n 'xyz-d50'\n])\n/** Spaces CSS writes as functions; HSL and HWB take percentages, as DTCG stores them. */\nconst FUNCTION_SPACES: Record<string, (components: string[]) => string> = {\n hsl: ([h, s, l]) => `hsl(${h} ${s}% ${l}%`,\n hwb: ([h, w, b]) => `hwb(${h} ${w}% ${b}%`,\n lab: (components) => `lab(${components.join(' ')}`,\n lch: (components) => `lch(${components.join(' ')}`,\n oklab: (components) => `oklab(${components.join(' ')}`,\n oklch: (components) => `oklch(${components.join(' ')}`\n}\n\nconst colorObjectSchema = v.object({\n colorSpace: v.string(),\n components: v.pipe(v.array(v.union([v.number(), v.literal('none')])), v.length(3)),\n alpha: v.optional(v.number()),\n hex: v.optional(v.string())\n})\n\n/**\n * A DTCG color in sRGB. The 2025.10 object form names its space; it is written as CSS and read\n * by culori, then mapped into sRGB. Earlier drafts wrote any CSS color string, which reads the\n * same way.\n */\nexport function decodeColor(value: unknown): Color | null {\n if (typeof value === 'string') return parseDisplayableColor(value)\n const parsed = v.safeParse(colorObjectSchema, value)\n if (!parsed.success) return null\n const { colorSpace, components, alpha = 1, hex } = parsed.output\n const parts = components.map(String)\n const open = PREDEFINED_SPACES.has(colorSpace)\n ? `color(${colorSpace} ${parts.join(' ')}`\n : FUNCTION_SPACES[colorSpace]?.(parts)\n if (!open) return hex ? parseDisplayableColor(hex) : null\n return parseDisplayableColor(`${open} / ${alpha})`)\n}\n\nconst dimensionSchema = v.object({ value: v.number(), unit: v.picklist(['px', 'rem']) })\nconst durationSchema = v.object({ value: v.number(), unit: v.picklist(['ms', 's']) })\n\n/** A length in canvas pixels and the unit it was written in. */\nexport function decodeDimension(value: unknown): { value: number; unit: TokenUnit } | null {\n const parsed = v.safeParse(dimensionSchema, value)\n if (parsed.success) {\n const { value: number, unit } = parsed.output\n return { value: unit === 'rem' ? number * ROOT_FONT_SIZE_PX : number, unit }\n }\n const px = typeof value === 'string' ? parseCSSNumber(value) : null\n if (px === null) return null\n return {\n value: px,\n unit: typeof value === 'string' && value.trim().endsWith('rem') ? 'rem' : 'px'\n }\n}\n\n/** Font weight keywords DTCG allows, by the weight they stand for. */\nconst FONT_WEIGHTS: Record<string, number> = {\n thin: 100,\n hairline: 100,\n 'extra-light': 200,\n 'ultra-light': 200,\n light: 300,\n normal: 400,\n regular: 400,\n book: 400,\n medium: 500,\n 'semi-bold': 600,\n 'demi-bold': 600,\n bold: 700,\n 'extra-bold': 800,\n 'ultra-bold': 800,\n black: 900,\n heavy: 900,\n 'extra-black': 950,\n 'ultra-black': 950\n}\n\nexport function decodeFontWeight(value: unknown): number | null {\n if (typeof value === 'number') return value >= 1 && value <= 1000 ? value : null\n return typeof value === 'string' ? (FONT_WEIGHTS[value.toLowerCase()] ?? null) : null\n}\n\n/** The most preferred family of a single name or a fallback list. */\nexport function decodeFontFamily(value: unknown): string | null {\n const first = Array.isArray(value) ? value[0] : value\n return typeof first === 'string' && first.trim() ? first.trim() : null\n}\n\nconst ownFieldsSchema = v.object({\n unit: v.optional(v.picklist(TOKEN_UNITS)),\n expression: v.optional(v.string()),\n scopes: v.optional(v.array(v.picklist(VARIABLE_SCOPES))),\n codeSyntax: v.optional(v.record(v.picklist(CODE_SYNTAX_PLATFORMS), v.string())),\n hiddenFromPublishing: v.optional(v.boolean())\n})\nconst figmaAliasSchema = v.object({\n targetVariableName: v.optional(v.string()),\n targetVariableSetName: v.optional(v.string())\n})\n\n/** A value that is the variable's own, or one it points at in another token. */\nexport type DecodedValue =\n | { kind: 'literal'; value: Color | number | string | boolean }\n | { kind: 'alias'; path: readonly string[]; collection?: string; name?: string }\n\n/** What a token makes of a variable. An alias without a type takes its target's. */\nexport interface DecodedVariable {\n type: VariableType | undefined\n value: DecodedValue\n unit?: TokenUnit\n expression?: string\n scopes?: VariableScope[]\n codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>\n hiddenFromPublishing?: boolean\n description?: string\n /**\n * Whether the token carries Pairdraw's own fields. Its unit, scopes, and code syntax then\n * replace a variable's, missing ones included; other tools' tokens leave them as they are.\n */\n own: boolean\n}\n\n/** Why a token does not become a variable. */\nexport type DecodeFailure = 'unsupported-type' | 'invalid-value'\n\nfunction isFigmaBoolean(token: ReadToken): boolean {\n return token.extensions['com.figma.type'] === 'boolean'\n}\n\n/** A token's type as a variable type, or undefined for an alias that must take its target's. */\nexport function variableTypeOf(token: ReadToken): VariableType | DecodeFailure | undefined {\n switch (token.type) {\n case 'color':\n return 'COLOR'\n case 'dimension':\n case 'duration':\n case 'fontWeight':\n return 'FLOAT'\n case 'number':\n return isFigmaBoolean(token) ? 'BOOLEAN' : 'FLOAT'\n case 'boolean':\n return 'BOOLEAN'\n case 'fontFamily':\n case 'string':\n return 'STRING'\n case undefined:\n return referencePath(token.value) ? undefined : 'unsupported-type'\n default:\n return 'unsupported-type'\n }\n}\n\ntype Literal = { value: Color | number | string | boolean; unit?: TokenUnit }\n\n/** A `number` token's value, or a boolean Figma writes as a number or as `true`/`false`. */\nfunction decodeNumber(token: ReadToken): Literal | null {\n const { value } = token\n if (isFigmaBoolean(token))\n return typeof value === 'boolean' || value === 0 || value === 1\n ? { value: Boolean(value) }\n : null\n return typeof value === 'number' && Number.isFinite(value) ? { value } : null\n}\n\n/**\n * A literal's value in the unit its variable keeps: a duration written in seconds, as Figma\n * requires, goes back into a variable that holds milliseconds.\n */\nfunction valueInUnit(literal: Literal, unit: TokenUnit | undefined): Literal['value'] {\n const { value } = literal\n if (typeof value !== 'number') return value\n if (literal.unit === 's' && unit === 'ms') return Number((value * 1000).toPrecision(12))\n if (literal.unit === 'ms' && unit === 's') return Number((value / 1000).toPrecision(12))\n return value\n}\n\n/** A literal in the shape its type takes, with the unit it was written in. */\nfunction decodeLiteral(token: ReadToken): Literal | null {\n const { value } = token\n switch (token.type) {\n case 'color': {\n const color = decodeColor(value)\n return color && { value: color }\n }\n case 'dimension':\n return decodeDimension(value)\n case 'duration': {\n const parsed = v.safeParse(durationSchema, value)\n return parsed.success ? parsed.output : null\n }\n case 'fontWeight': {\n const weight = decodeFontWeight(value)\n return weight === null ? null : { value: weight }\n }\n case 'fontFamily': {\n const family = decodeFontFamily(value)\n return family === null ? null : { value: family }\n }\n case 'boolean':\n return typeof value === 'boolean' ? { value } : null\n case 'number':\n return decodeNumber(token)\n case 'string':\n return typeof value === 'string' ? { value } : null\n default:\n return null\n }\n}\n\n/** Scopes a token type implies when the token does not list its own. */\nfunction impliedScopes(token: ReadToken): VariableScope[] | undefined {\n if (token.type === 'fontFamily') return ['FONT_FAMILY']\n if (token.type === 'fontWeight') return ['FONT_STYLE']\n return undefined\n}\n\n/** A token as a variable value and Pairdraw's own token fields. */\nexport function decodeVariableToken(token: ReadToken): DecodedVariable | DecodeFailure {\n const type = variableTypeOf(token)\n if (type === 'unsupported-type' || type === 'invalid-value') return type\n const own = v.safeParse(ownFieldsSchema, token.extensions[PAIRDRAW_EXTENSION])\n const fields = own.success ? own.output : {}\n const reference = referencePath(token.value)\n let value: DecodedValue\n let unit = fields.unit\n if (reference) {\n const figma = v.safeParse(figmaAliasSchema, token.extensions['com.figma.aliasData'])\n value = {\n kind: 'alias',\n path: reference,\n collection: figma.success ? figma.output.targetVariableSetName : undefined,\n name: figma.success ? figma.output.targetVariableName : undefined\n }\n } else {\n const literal = decodeLiteral(token)\n if (!literal) return 'invalid-value'\n unit ??= literal.unit === 'px' ? undefined : literal.unit\n value = { kind: 'literal', value: valueInUnit(literal, unit) }\n }\n return {\n type,\n value,\n unit: type === 'FLOAT' ? unit : undefined,\n expression: fields.expression,\n scopes: fields.scopes ?? impliedScopes(token),\n codeSyntax: fields.codeSyntax,\n hiddenFromPublishing: fields.hiddenFromPublishing,\n description: token.description,\n own: own.success\n }\n}\n"],"mappings":";;;;;;;;AAoBA,SAAgB,cAAc,OAAiC;CAC7D,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,SAAS,GAAG,GAAG,OAAO;CACxF,MAAM,QAAQ,MAAM,MAAM,GAAG,EAAE;CAC/B,OAAO,SAAS,CAAC,OAAO,KAAK,KAAK,IAAI,MAAM,MAAM,GAAG,IAAI;AAC3D;;AAGA,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAED,MAAM,kBAAoE;CACxE,MAAM,CAAC,GAAG,GAAG,OAAO,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE;CACxC,MAAM,CAAC,GAAG,GAAG,OAAO,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE;CACxC,MAAM,eAAe,OAAO,WAAW,KAAK,GAAG;CAC/C,MAAM,eAAe,OAAO,WAAW,KAAK,GAAG;CAC/C,QAAQ,eAAe,SAAS,WAAW,KAAK,GAAG;C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AAI;EAAE;CAC/D;CACA,OAAO;EACL;EACA;EACA,MAAM,SAAS,UAAU,OAAO,KAAA;EAChC,YAAY,OAAO;EACnB,QAAQ,OAAO,UAAU,cAAc,KAAK;EAC5C,YAAY,OAAO;EACnB,sBAAsB,OAAO;EAC7B,aAAa,MAAM;EACnB,KAAK,IAAI;CACX;AACF"}
|
|
1
|
+
{"version":3,"file":"decode.js","names":[],"sources":["../../../../src/io/formats/design-tokens/decode.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport {\n CODE_SYNTAX_PLATFORMS,\n TOKEN_UNITS,\n VARIABLE_SCOPES,\n type CodeSyntaxPlatform,\n type DocumentColorSpace,\n type TokenUnit,\n type VariableScope,\n type VariableType\n} from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport { parseCSSNumber } from '@pairdraw/scene-graph/css'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\nimport { ROOT_FONT_SIZE_PX } from '@pairdraw/scene-graph/variables'\n\nimport type { ReadToken } from './read'\nimport { PAIRDRAW_EXTENSION } from './types'\n\n/** A `{group.token}` reference, as its path segments. */\nexport function referencePath(value: unknown): string[] | null {\n if (typeof value !== 'string' || !value.startsWith('{') || !value.endsWith('}')) return null\n const inner = value.slice(1, -1)\n return inner && !/[{}]/.test(inner) ? inner.split('.') : null\n}\n\n/** CSS Color 4 spaces DTCG names, as `color()` takes them. */\nconst PREDEFINED_SPACES = new Set([\n 'srgb',\n 'srgb-linear',\n 'display-p3',\n 'a98-rgb',\n 'prophoto-rgb',\n 'rec2020',\n 'xyz-d65',\n 'xyz-d50'\n])\n/** Spaces CSS writes as functions; HSL and HWB take percentages, as DTCG stores them. */\nconst FUNCTION_SPACES: Record<string, (components: string[]) => string> = {\n hsl: ([h, s, l]) => `hsl(${h} ${s}% ${l}%`,\n hwb: ([h, w, b]) => `hwb(${h} ${w}% ${b}%`,\n lab: (components) => `lab(${components.join(' ')}`,\n lch: (components) => `lch(${components.join(' ')}`,\n oklab: (components) => `oklab(${components.join(' ')}`,\n oklch: (components) => `oklch(${components.join(' ')}`\n}\n\nconst colorObjectSchema = v.object({\n colorSpace: v.string(),\n components: v.pipe(v.array(v.union([v.number(), v.literal('none')])), v.length(3)),\n alpha: v.optional(v.number()),\n hex: v.optional(v.string())\n})\n\n/**\n * A DTCG color as components in `profile`, the importing document's. The 2025.10 object form names\n * its space; it is written as CSS and read as CSS colors are: an sRGB one keeps its numbers, as\n * Figma takes hex, and one in another space, such as Display P3, is converted into `profile`.\n * Earlier drafts wrote any CSS color string, which reads the same way.\n */\nexport function decodeColor(value: unknown, profile: DocumentColorSpace): Color | null {\n if (typeof value === 'string') return tryParseColor(value, profile)\n const parsed = v.safeParse(colorObjectSchema, value)\n if (!parsed.success) return null\n const { colorSpace, components, alpha = 1, hex } = parsed.output\n const parts = components.map(String)\n const open = PREDEFINED_SPACES.has(colorSpace)\n ? `color(${colorSpace} ${parts.join(' ')}`\n : FUNCTION_SPACES[colorSpace]?.(parts)\n if (!open) return hex ? tryParseColor(hex, profile) : null\n return tryParseColor(`${open} / ${alpha})`, profile)\n}\n\nconst dimensionSchema = v.object({ value: v.number(), unit: v.picklist(['px', 'rem']) })\nconst durationSchema = v.object({ value: v.number(), unit: v.picklist(['ms', 's']) })\n\n/** A length in canvas pixels and the unit it was written in. */\nexport function decodeDimension(value: unknown): { value: number; unit: TokenUnit } | null {\n const parsed = v.safeParse(dimensionSchema, value)\n if (parsed.success) {\n const { value: number, unit } = parsed.output\n return { value: unit === 'rem' ? number * ROOT_FONT_SIZE_PX : number, unit }\n }\n const px = typeof value === 'string' ? parseCSSNumber(value) : null\n if (px === null) return null\n return {\n value: px,\n unit: typeof value === 'string' && value.trim().endsWith('rem') ? 'rem' : 'px'\n }\n}\n\n/** Font weight keywords DTCG allows, by the weight they stand for. */\nconst FONT_WEIGHTS: Record<string, number> = {\n thin: 100,\n hairline: 100,\n 'extra-light': 200,\n 'ultra-light': 200,\n light: 300,\n normal: 400,\n regular: 400,\n book: 400,\n medium: 500,\n 'semi-bold': 600,\n 'demi-bold': 600,\n bold: 700,\n 'extra-bold': 800,\n 'ultra-bold': 800,\n black: 900,\n heavy: 900,\n 'extra-black': 950,\n 'ultra-black': 950\n}\n\nexport function decodeFontWeight(value: unknown): number | null {\n if (typeof value === 'number') return value >= 1 && value <= 1000 ? value : null\n return typeof value === 'string' ? (FONT_WEIGHTS[value.toLowerCase()] ?? null) : null\n}\n\n/** The most preferred family of a single name or a fallback list. */\nexport function decodeFontFamily(value: unknown): string | null {\n const first = Array.isArray(value) ? value[0] : value\n return typeof first === 'string' && first.trim() ? first.trim() : null\n}\n\nconst ownFieldsSchema = v.object({\n unit: v.optional(v.picklist(TOKEN_UNITS)),\n expression: v.optional(v.string()),\n scopes: v.optional(v.array(v.picklist(VARIABLE_SCOPES))),\n codeSyntax: v.optional(v.record(v.picklist(CODE_SYNTAX_PLATFORMS), v.string())),\n hiddenFromPublishing: v.optional(v.boolean())\n})\nconst figmaAliasSchema = v.object({\n targetVariableName: v.optional(v.string()),\n targetVariableSetName: v.optional(v.string())\n})\n\n/** A value that is the variable's own, or one it points at in another token. */\nexport type DecodedValue =\n | { kind: 'literal'; value: Color | number | string | boolean }\n | { kind: 'alias'; path: readonly string[]; collection?: string; name?: string }\n\n/** What a token makes of a variable. An alias without a type takes its target's. */\nexport interface DecodedVariable {\n type: VariableType | undefined\n value: DecodedValue\n unit?: TokenUnit\n expression?: string\n scopes?: VariableScope[]\n codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>\n hiddenFromPublishing?: boolean\n description?: string\n /**\n * Whether the token carries Pairdraw's own fields. Its unit, scopes, and code syntax then\n * replace a variable's, missing ones included; other tools' tokens leave them as they are.\n */\n own: boolean\n}\n\n/** Why a token does not become a variable. */\nexport type DecodeFailure = 'unsupported-type' | 'invalid-value'\n\nfunction isFigmaBoolean(token: ReadToken): boolean {\n return token.extensions['com.figma.type'] === 'boolean'\n}\n\n/** A token's type as a variable type, or undefined for an alias that must take its target's. */\nexport function variableTypeOf(token: ReadToken): VariableType | DecodeFailure | undefined {\n switch (token.type) {\n case 'color':\n return 'COLOR'\n case 'dimension':\n case 'duration':\n case 'fontWeight':\n return 'FLOAT'\n case 'number':\n return isFigmaBoolean(token) ? 'BOOLEAN' : 'FLOAT'\n case 'boolean':\n return 'BOOLEAN'\n case 'fontFamily':\n case 'string':\n return 'STRING'\n case undefined:\n return referencePath(token.value) ? undefined : 'unsupported-type'\n default:\n return 'unsupported-type'\n }\n}\n\ntype Literal = { value: Color | number | string | boolean; unit?: TokenUnit }\n\n/** A `number` token's value, or a boolean Figma writes as a number or as `true`/`false`. */\nfunction decodeNumber(token: ReadToken): Literal | null {\n const { value } = token\n if (isFigmaBoolean(token))\n return typeof value === 'boolean' || value === 0 || value === 1\n ? { value: Boolean(value) }\n : null\n return typeof value === 'number' && Number.isFinite(value) ? { value } : null\n}\n\n/**\n * A literal's value in the unit its variable keeps: a duration written in seconds, as Figma\n * requires, goes back into a variable that holds milliseconds.\n */\nfunction valueInUnit(literal: Literal, unit: TokenUnit | undefined): Literal['value'] {\n const { value } = literal\n if (typeof value !== 'number') return value\n if (literal.unit === 's' && unit === 'ms') return Number((value * 1000).toPrecision(12))\n if (literal.unit === 'ms' && unit === 's') return Number((value / 1000).toPrecision(12))\n return value\n}\n\n/** A literal in the shape its type takes, with the unit it was written in. */\nfunction decodeLiteral(token: ReadToken, profile: DocumentColorSpace): Literal | null {\n const { value } = token\n switch (token.type) {\n case 'color': {\n const color = decodeColor(value, profile)\n return color && { value: color }\n }\n case 'dimension':\n return decodeDimension(value)\n case 'duration': {\n const parsed = v.safeParse(durationSchema, value)\n return parsed.success ? parsed.output : null\n }\n case 'fontWeight': {\n const weight = decodeFontWeight(value)\n return weight === null ? null : { value: weight }\n }\n case 'fontFamily': {\n const family = decodeFontFamily(value)\n return family === null ? null : { value: family }\n }\n case 'boolean':\n return typeof value === 'boolean' ? { value } : null\n case 'number':\n return decodeNumber(token)\n case 'string':\n return typeof value === 'string' ? { value } : null\n default:\n return null\n }\n}\n\n/** Scopes a token type implies when the token does not list its own. */\nfunction impliedScopes(token: ReadToken): VariableScope[] | undefined {\n if (token.type === 'fontFamily') return ['FONT_FAMILY']\n if (token.type === 'fontWeight') return ['FONT_STYLE']\n return undefined\n}\n\n/** A token as a variable value and Pairdraw's own token fields. */\nexport function decodeVariableToken(\n token: ReadToken,\n profile: DocumentColorSpace\n): DecodedVariable | DecodeFailure {\n const type = variableTypeOf(token)\n if (type === 'unsupported-type' || type === 'invalid-value') return type\n const own = v.safeParse(ownFieldsSchema, token.extensions[PAIRDRAW_EXTENSION])\n const fields = own.success ? own.output : {}\n const reference = referencePath(token.value)\n let value: DecodedValue\n let unit = fields.unit\n if (reference) {\n const figma = v.safeParse(figmaAliasSchema, token.extensions['com.figma.aliasData'])\n value = {\n kind: 'alias',\n path: reference,\n collection: figma.success ? figma.output.targetVariableSetName : undefined,\n name: figma.success ? figma.output.targetVariableName : undefined\n }\n } else {\n const literal = decodeLiteral(token, profile)\n if (!literal) return 'invalid-value'\n unit ??= literal.unit === 'px' ? undefined : literal.unit\n value = { kind: 'literal', value: valueInUnit(literal, unit) }\n }\n return {\n type,\n value,\n unit: type === 'FLOAT' ? unit : undefined,\n expression: fields.expression,\n scopes: fields.scopes ?? impliedScopes(token),\n codeSyntax: fields.codeSyntax,\n hiddenFromPublishing: fields.hiddenFromPublishing,\n description: token.description,\n own: own.success\n }\n}\n"],"mappings":";;;;;;;;AAqBA,SAAgB,cAAc,OAAiC;CAC7D,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,SAAS,GAAG,GAAG,OAAO;CACxF,MAAM,QAAQ,MAAM,MAAM,GAAG,EAAE;CAC/B,OAAO,SAAS,CAAC,OAAO,KAAK,KAAK,IAAI,MAAM,MAAM,GAAG,IAAI;AAC3D;;AAGA,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;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,UAAU,kBAAkB,MAAM,WAAW,sBAAsB;EACnF,QAAQ;GACN,MAAM;GACN,MAAM;GACN,YAAY,MAAM,UAAU,MAAM,OAAO,wBAAwB,KAAA;GACjE,MAAM,MAAM,UAAU,MAAM,OAAO,qBAAqB,KAAA;EAC1D;CACF,OAAO;EACL,MAAM,UAAU,cAAc,OAAO,OAAO;EAC5C,IAAI,CAAC,SAAS,OAAO;EACrB,SAAS,QAAQ,SAAS,OAAO,KAAA,IAAY,QAAQ;EACrD,QAAQ;GAAE,MAAM;GAAW,OAAO,YAAY,SAAS,IAAI;EAAE;CAC/D;CACA,OAAO;EACL;EACA;EACA,MAAM,SAAS,UAAU,OAAO,KAAA;EAChC,YAAY,OAAO;EACnB,QAAQ,OAAO,UAAU,cAAc,KAAK;EAC5C,YAAY,OAAO;EACnB,sBAAsB,OAAO;EAC7B,aAAa,MAAM;EACnB,KAAK,IAAI;CACX;AACF"}
|
|
@@ -70,7 +70,7 @@ function variableToken(context, collection, mode, variable) {
|
|
|
70
70
|
return;
|
|
71
71
|
}
|
|
72
72
|
formula = printFormula(value.value, (id) => tokenReference(context.references.get(id) ?? []), { type: (id) => context.graph.variables.get(id)?.type });
|
|
73
|
-
$value = literalTokenValue(variable, resolved);
|
|
73
|
+
$value = literalTokenValue(variable, resolved, context.graph.documentColorSpace);
|
|
74
74
|
} else if (typeof value === "object" && "expression" in value) {
|
|
75
75
|
context.issues.push({
|
|
76
76
|
kind: "unsupported-expression",
|
|
@@ -93,7 +93,7 @@ function variableToken(context, collection, mode, variable) {
|
|
|
93
93
|
targetVariableName: target.name,
|
|
94
94
|
targetVariableSetName: targetCollection.name
|
|
95
95
|
};
|
|
96
|
-
} else $value = literalTokenValue(variable, value);
|
|
96
|
+
} else $value = literalTokenValue(variable, value, context.graph.documentColorSpace);
|
|
97
97
|
if (variable.type === "BOOLEAN") figma["com.figma.type"] = "boolean";
|
|
98
98
|
const $extensions = {
|
|
99
99
|
...figma,
|
|
@@ -152,7 +152,7 @@ function resolverDocument(collections, stylesPath) {
|
|
|
152
152
|
*/
|
|
153
153
|
function exportDesignTokens(graph) {
|
|
154
154
|
const issues = [];
|
|
155
|
-
const collections =
|
|
155
|
+
const collections = graph.getLiveCollections();
|
|
156
156
|
const references = /* @__PURE__ */ new Map();
|
|
157
157
|
const collectionOf = /* @__PURE__ */ new Map();
|
|
158
158
|
const placedByCollection = /* @__PURE__ */ new Map();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"export.js","names":[],"sources":["../../../../src/io/formats/design-tokens/export.ts"],"sourcesContent":["import { compact } from 'es-toolkit/array'\nimport { omitBy } from 'es-toolkit/object'\nimport { isEmptyObject } from 'es-toolkit/predicate'\n\nimport type {\n SceneGraph,\n Variable,\n VariableCollection,\n VariableCollectionMode\n} from '@pairdraw/scene-graph'\nimport { numberedName } from '@pairdraw/scene-graph/naming'\nimport { printFormula, variableValueReferences } from '@pairdraw/scene-graph/variables'\n\nimport { fileSegment, placeTokens, tokenPath, tokenReference, tokenTree } from './paths'\nimport { styleTokens, withOriginalName, type TokenReferences } from './styles'\nimport {\n PAIRDRAW_EXTENSION,\n RESOLVER_VERSION,\n type DesignToken,\n type DesignTokenFile,\n type DesignTokenIssue\n} from './types'\nimport { literalTokenValue, variableTokenType } from './values'\n\nexport interface DesignTokenExport {\n files: DesignTokenFile[]\n issues: DesignTokenIssue[]\n}\n\n/** The resolver document's file name, as DTCG recommends. */\nexport const RESOLVER_FILE = 'tokens.resolver.json'\n/** The composite tokens' file, apart from the mode files because Figma's import refuses them. */\nexport const STYLES_FILE = 'styles.tokens.json'\n\n/** Names made distinct by numbering repeats: `Theme`, `Theme 2`. */\nfunction distinct(names: readonly string[], reserved: readonly string[] = []): string[] {\n const taken = new Set(reserved)\n return names.map((name) => {\n const candidate = numberedName(name, taken)\n taken.add(candidate)\n return candidate\n })\n}\n\n/** The resolver set that holds the styles file, a name no collection may take there. */\nconst STYLES_SET = 'Styles'\n\n/** A JSON pointer segment: `~` and `/` are escaped as RFC 6901 requires. */\nfunction pointerSegment(name: string): string {\n return name.replaceAll('~', '~0').replaceAll('/', '~1')\n}\n\ninterface ExportContext {\n graph: SceneGraph\n references: TokenReferences\n collectionOf: ReadonlyMap<string, VariableCollection>\n issues: DesignTokenIssue[]\n}\n\n/** Pairdraw's own token fields, which DTCG has no place for. */\nfunction pairdrawFields(variable: Variable, modeId: string, formula?: string) {\n const fields = omitBy(\n {\n unit: variable.unit,\n expression: variable.expressions?.[modeId]?.css,\n formula,\n scopes: variable.scopes,\n codeSyntax: variable.codeSyntax,\n hiddenFromPublishing: variable.hiddenFromPublishing || undefined\n },\n (value) => value === undefined\n )\n return isEmptyObject(fields) ? {} : { [PAIRDRAW_EXTENSION]: fields }\n}\n\n/**\n * A variable's value in one mode as a token. An alias is a `{group.token}` reference; one to\n * another collection also names its target in `com.figma.aliasData`, the way Figma resolves it.\n */\nfunction variableToken(\n context: ExportContext,\n collection: VariableCollection,\n mode: VariableCollectionMode,\n variable: Variable\n): DesignToken | undefined {\n const where = { collection: collection.name, mode: mode.name, token: variable.name }\n if (!Object.hasOwn(variable.valuesByMode, mode.modeId)) {\n context.issues.push({ kind: 'missing-value', ...where })\n return undefined\n }\n const value = variable.valuesByMode[mode.modeId]\n const figma: Record<string, unknown> = {}\n let $value: unknown\n let formula: string | undefined\n if (typeof value === 'object' && 'expression' in value && value.expression === 'FORMULA') {\n // DTCG has no formulas: the token holds this mode's result and keeps the formula beside it.\n const resolved = context.graph.resolveVariable(variable.id, mode.modeId)\n const missing = variableValueReferences(value).some((id) => !context.references.has(id))\n if (missing || resolved === undefined) {\n context.issues.push({ kind: 'missing-alias', ...where })\n return undefined\n }\n formula = printFormula(value.value, (id) => tokenReference(context.references.get(id) ?? []), {\n type: (id) => context.graph.variables.get(id)?.type\n })\n $value = literalTokenValue(variable, resolved)\n } else if (typeof value === 'object' && 'expression' in value) {\n context.issues.push({ kind: 'unsupported-expression', ...where })\n return undefined\n } else if (typeof value === 'object' && 'aliasId' in value) {\n const path = context.references.get(value.aliasId)\n const target = context.graph.variables.get(value.aliasId)\n const targetCollection = context.collectionOf.get(value.aliasId)\n if (!path || !target || !targetCollection) {\n context.issues.push({ kind: 'missing-alias', ...where })\n return undefined\n }\n $value = tokenReference(path)\n if (targetCollection.id !== collection.id)\n figma['com.figma.aliasData'] = {\n targetVariableName: target.name,\n targetVariableSetName: targetCollection.name\n }\n } else {\n $value = literalTokenValue(variable, value)\n }\n if (variable.type === 'BOOLEAN') figma['com.figma.type'] = 'boolean'\n const $extensions = { ...figma, ...pairdrawFields(variable, mode.modeId, formula) }\n const token: DesignToken = { $type: variableTokenType(variable), $value }\n if (variable.description) token.$description = variable.description\n if (!isEmptyObject($extensions)) token.$extensions = $extensions\n return token\n}\n\n/** What a mode file says about its collection and mode, for Pairdraw to read back. */\nfunction modeExtension(collection: VariableCollection, mode: VariableCollectionMode) {\n return {\n [PAIRDRAW_EXTENSION]: omitBy(\n {\n collection: collection.name,\n mode: mode.name,\n default: mode.modeId === collection.defaultModeId,\n condition: mode.condition,\n modeAttribute: collection.modeAttribute\n },\n (value) => value === undefined\n )\n }\n}\n\ninterface CollectionFiles {\n collection: VariableCollection\n name: string\n modes: Array<{ name: string; path: string; isDefault: boolean }>\n}\n\n/** The resolver: one modifier per collection with several modes, one set per single-mode one. */\nfunction resolverDocument(collections: readonly CollectionFiles[], stylesPath: string | null) {\n const sets: Record<string, unknown> = {}\n const modifiers: Record<string, unknown> = {}\n const resolutionOrder: Array<{ $ref: string }> = []\n for (const { name, modes } of collections) {\n if (modes.length === 1) {\n sets[name] = { sources: [{ $ref: modes[0].path }] }\n resolutionOrder.push({ $ref: `#/sets/${pointerSegment(name)}` })\n continue\n }\n modifiers[name] = {\n contexts: Object.fromEntries(modes.map((mode) => [mode.name, [{ $ref: mode.path }]])),\n default: modes.find((mode) => mode.isDefault)?.name ?? modes[0].name\n }\n resolutionOrder.push({ $ref: `#/modifiers/${pointerSegment(name)}` })\n }\n if (stylesPath) {\n sets[STYLES_SET] = { sources: [{ $ref: stylesPath }] }\n resolutionOrder.push({ $ref: `#/sets/${STYLES_SET}` })\n }\n const resolver: Record<string, unknown> = { version: RESOLVER_VERSION }\n if (!isEmptyObject(sets)) resolver.sets = sets\n if (!isEmptyObject(modifiers)) resolver.modifiers = modifiers\n resolver.resolutionOrder = resolutionOrder\n return resolver\n}\n\n/**\n * The document's variables and styles as W3C design tokens: one file per collection mode, which\n * Figma imports as a mode, a file of typography and shadow tokens from text and effect styles,\n * and a resolver document that combines them. Pairdraw's own fields ride in\n * `$extensions[\"dev.pairdraw\"]`, so reading the export back loses nothing.\n */\nexport function exportDesignTokens(graph: SceneGraph): DesignTokenExport {\n const issues: DesignTokenIssue[] = []\n const collections = [...graph.variableCollections.values()]\n const references = new Map<string, string[]>()\n const collectionOf = new Map<string, VariableCollection>()\n const placedByCollection = new Map<string, Array<{ variable: Variable; path: string[] }>>()\n for (const collection of collections) {\n const variables = compact(collection.variableIds.map((id) => graph.variables.get(id)))\n const { placed, duplicates } = placeTokens(\n variables.map((variable) => ({ key: variable, path: tokenPath(variable.name) }))\n )\n for (const variable of duplicates)\n issues.push({ kind: 'duplicate-path', collection: collection.name, token: variable.name })\n placedByCollection.set(\n collection.id,\n [...placed].map(([variable, path]) => ({ variable, path }))\n )\n for (const [variable, path] of placed) {\n references.set(variable.id, path)\n collectionOf.set(variable.id, collection)\n }\n }\n const context: ExportContext = { graph, references, collectionOf, issues }\n const files: DesignTokenFile[] = []\n const styles = styleTokens(graph, references)\n issues.push(...styles.issues)\n const stylesPath = styles.tokens.length > 0 ? STYLES_FILE : null\n const folders = distinct(collections.map((collection) => fileSegment(collection.name)))\n const collectionNames = distinct(\n collections.map((collection) => collection.name),\n stylesPath ? [STYLES_SET] : []\n )\n const collectionFiles = collections.map((collection, index): CollectionFiles => {\n const fileNames = distinct(collection.modes.map((mode) => fileSegment(mode.name)))\n const modeNames = distinct(collection.modes.map((mode) => mode.name))\n const modes = collection.modes.map((mode, modeIndex) => {\n const path = `${folders[index]}/${fileNames[modeIndex]}.tokens.json`\n const tokens = (placedByCollection.get(collection.id) ?? []).flatMap(\n ({ variable, path: tokenAt }) => {\n const token = variableToken(context, collection, mode, variable)\n return token\n ? [{ path: tokenAt, token: withOriginalName(token, variable.name, tokenAt) }]\n : []\n }\n )\n files.push({\n path,\n content: { ...tokenTree(tokens), $extensions: modeExtension(collection, mode) }\n })\n return {\n name: modeNames[modeIndex],\n path,\n isDefault: mode.modeId === collection.defaultModeId\n }\n })\n return { collection, name: collectionNames[index], modes }\n })\n if (stylesPath) files.push({ path: stylesPath, content: tokenTree(styles.tokens) })\n if (files.length > 0)\n files.push({ path: RESOLVER_FILE, content: resolverDocument(collectionFiles, stylesPath) })\n return { files, issues }\n}\n"],"mappings":";;;;;;;;;;;AA8BA,MAAa,gBAAgB;;AAE7B,MAAa,cAAc;;AAG3B,SAAS,SAAS,OAA0B,WAA8B,CAAC,GAAa;CACtF,MAAM,QAAQ,IAAI,IAAI,QAAQ;CAC9B,OAAO,MAAM,KAAK,SAAS;EACzB,MAAM,YAAY,aAAa,MAAM,KAAK;EAC1C,MAAM,IAAI,SAAS;EACnB,OAAO;CACT,CAAC;AACH;;AAGA,MAAM,aAAa;;AAGnB,SAAS,eAAe,MAAsB;CAC5C,OAAO,KAAK,WAAW,KAAK,IAAI,CAAC,CAAC,WAAW,KAAK,IAAI;AACxD;;AAUA,SAAS,eAAe,UAAoB,QAAgB,SAAkB;CAC5E,MAAM,SAAS,OACb;EACE,MAAM,SAAS;EACf,YAAY,SAAS,cAAc,OAAO,EAAE;EAC5C;EACA,QAAQ,SAAS;EACjB,YAAY,SAAS;EACrB,sBAAsB,SAAS,wBAAwB,KAAA;CACzD,IACC,UAAU,UAAU,KAAA,CACvB;CACA,OAAO,cAAc,MAAM,IAAI,CAAC,IAAI,GAAG,qBAAqB,OAAO;AACrE;;;;;AAMA,SAAS,cACP,SACA,YACA,MACA,UACyB;CACzB,MAAM,QAAQ;EAAE,YA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AM,SAAS,GACjB,MAAM,KAAK;EAAE,MAAM;EAAe,SAAS,iBAAiB,iBAAiB,UAAU;CAAE,CAAC;CAC5F,OAAO;EAAE;EAAO;CAAO;AACzB"}
|
|
1
|
+
{"version":3,"file":"export.js","names":[],"sources":["../../../../src/io/formats/design-tokens/export.ts"],"sourcesContent":["import { compact } from 'es-toolkit/array'\nimport { omitBy } from 'es-toolkit/object'\nimport { isEmptyObject } from 'es-toolkit/predicate'\n\nimport type {\n SceneGraph,\n Variable,\n VariableCollection,\n VariableCollectionMode\n} from '@pairdraw/scene-graph'\nimport { numberedName } from '@pairdraw/scene-graph/naming'\nimport { printFormula, variableValueReferences } from '@pairdraw/scene-graph/variables'\n\nimport { fileSegment, placeTokens, tokenPath, tokenReference, tokenTree } from './paths'\nimport { styleTokens, withOriginalName, type TokenReferences } from './styles'\nimport {\n PAIRDRAW_EXTENSION,\n RESOLVER_VERSION,\n type DesignToken,\n type DesignTokenFile,\n type DesignTokenIssue\n} from './types'\nimport { literalTokenValue, variableTokenType } from './values'\n\nexport interface DesignTokenExport {\n files: DesignTokenFile[]\n issues: DesignTokenIssue[]\n}\n\n/** The resolver document's file name, as DTCG recommends. */\nexport const RESOLVER_FILE = 'tokens.resolver.json'\n/** The composite tokens' file, apart from the mode files because Figma's import refuses them. */\nexport const STYLES_FILE = 'styles.tokens.json'\n\n/** Names made distinct by numbering repeats: `Theme`, `Theme 2`. */\nfunction distinct(names: readonly string[], reserved: readonly string[] = []): string[] {\n const taken = new Set(reserved)\n return names.map((name) => {\n const candidate = numberedName(name, taken)\n taken.add(candidate)\n return candidate\n })\n}\n\n/** The resolver set that holds the styles file, a name no collection may take there. */\nconst STYLES_SET = 'Styles'\n\n/** A JSON pointer segment: `~` and `/` are escaped as RFC 6901 requires. */\nfunction pointerSegment(name: string): string {\n return name.replaceAll('~', '~0').replaceAll('/', '~1')\n}\n\ninterface ExportContext {\n graph: SceneGraph\n references: TokenReferences\n collectionOf: ReadonlyMap<string, VariableCollection>\n issues: DesignTokenIssue[]\n}\n\n/** Pairdraw's own token fields, which DTCG has no place for. */\nfunction pairdrawFields(variable: Variable, modeId: string, formula?: string) {\n const fields = omitBy(\n {\n unit: variable.unit,\n expression: variable.expressions?.[modeId]?.css,\n formula,\n scopes: variable.scopes,\n codeSyntax: variable.codeSyntax,\n hiddenFromPublishing: variable.hiddenFromPublishing || undefined\n },\n (value) => value === undefined\n )\n return isEmptyObject(fields) ? {} : { [PAIRDRAW_EXTENSION]: fields }\n}\n\n/**\n * A variable's value in one mode as a token. An alias is a `{group.token}` reference; one to\n * another collection also names its target in `com.figma.aliasData`, the way Figma resolves it.\n */\nfunction variableToken(\n context: ExportContext,\n collection: VariableCollection,\n mode: VariableCollectionMode,\n variable: Variable\n): DesignToken | undefined {\n const where = { collection: collection.name, mode: mode.name, token: variable.name }\n if (!Object.hasOwn(variable.valuesByMode, mode.modeId)) {\n context.issues.push({ kind: 'missing-value', ...where })\n return undefined\n }\n const value = variable.valuesByMode[mode.modeId]\n const figma: Record<string, unknown> = {}\n let $value: unknown\n let formula: string | undefined\n if (typeof value === 'object' && 'expression' in value && value.expression === 'FORMULA') {\n // DTCG has no formulas: the token holds this mode's result and keeps the formula beside it.\n const resolved = context.graph.resolveVariable(variable.id, mode.modeId)\n const missing = variableValueReferences(value).some((id) => !context.references.has(id))\n if (missing || resolved === undefined) {\n context.issues.push({ kind: 'missing-alias', ...where })\n return undefined\n }\n formula = printFormula(value.value, (id) => tokenReference(context.references.get(id) ?? []), {\n type: (id) => context.graph.variables.get(id)?.type\n })\n $value = literalTokenValue(variable, resolved, context.graph.documentColorSpace)\n } else if (typeof value === 'object' && 'expression' in value) {\n context.issues.push({ kind: 'unsupported-expression', ...where })\n return undefined\n } else if (typeof value === 'object' && 'aliasId' in value) {\n const path = context.references.get(value.aliasId)\n const target = context.graph.variables.get(value.aliasId)\n const targetCollection = context.collectionOf.get(value.aliasId)\n if (!path || !target || !targetCollection) {\n context.issues.push({ kind: 'missing-alias', ...where })\n return undefined\n }\n $value = tokenReference(path)\n if (targetCollection.id !== collection.id)\n figma['com.figma.aliasData'] = {\n targetVariableName: target.name,\n targetVariableSetName: targetCollection.name\n }\n } else {\n $value = literalTokenValue(variable, value, context.graph.documentColorSpace)\n }\n if (variable.type === 'BOOLEAN') figma['com.figma.type'] = 'boolean'\n const $extensions = { ...figma, ...pairdrawFields(variable, mode.modeId, formula) }\n const token: DesignToken = { $type: variableTokenType(variable), $value }\n if (variable.description) token.$description = variable.description\n if (!isEmptyObject($extensions)) token.$extensions = $extensions\n return token\n}\n\n/** What a mode file says about its collection and mode, for Pairdraw to read back. */\nfunction modeExtension(collection: VariableCollection, mode: VariableCollectionMode) {\n return {\n [PAIRDRAW_EXTENSION]: omitBy(\n {\n collection: collection.name,\n mode: mode.name,\n default: mode.modeId === collection.defaultModeId,\n condition: mode.condition,\n modeAttribute: collection.modeAttribute\n },\n (value) => value === undefined\n )\n }\n}\n\ninterface CollectionFiles {\n collection: VariableCollection\n name: string\n modes: Array<{ name: string; path: string; isDefault: boolean }>\n}\n\n/** The resolver: one modifier per collection with several modes, one set per single-mode one. */\nfunction resolverDocument(collections: readonly CollectionFiles[], stylesPath: string | null) {\n const sets: Record<string, unknown> = {}\n const modifiers: Record<string, unknown> = {}\n const resolutionOrder: Array<{ $ref: string }> = []\n for (const { name, modes } of collections) {\n if (modes.length === 1) {\n sets[name] = { sources: [{ $ref: modes[0].path }] }\n resolutionOrder.push({ $ref: `#/sets/${pointerSegment(name)}` })\n continue\n }\n modifiers[name] = {\n contexts: Object.fromEntries(modes.map((mode) => [mode.name, [{ $ref: mode.path }]])),\n default: modes.find((mode) => mode.isDefault)?.name ?? modes[0].name\n }\n resolutionOrder.push({ $ref: `#/modifiers/${pointerSegment(name)}` })\n }\n if (stylesPath) {\n sets[STYLES_SET] = { sources: [{ $ref: stylesPath }] }\n resolutionOrder.push({ $ref: `#/sets/${STYLES_SET}` })\n }\n const resolver: Record<string, unknown> = { version: RESOLVER_VERSION }\n if (!isEmptyObject(sets)) resolver.sets = sets\n if (!isEmptyObject(modifiers)) resolver.modifiers = modifiers\n resolver.resolutionOrder = resolutionOrder\n return resolver\n}\n\n/**\n * The document's variables and styles as W3C design tokens: one file per collection mode, which\n * Figma imports as a mode, a file of typography and shadow tokens from text and effect styles,\n * and a resolver document that combines them. Pairdraw's own fields ride in\n * `$extensions[\"dev.pairdraw\"]`, so reading the export back loses nothing.\n */\nexport function exportDesignTokens(graph: SceneGraph): DesignTokenExport {\n const issues: DesignTokenIssue[] = []\n const collections = graph.getLiveCollections()\n const references = new Map<string, string[]>()\n const collectionOf = new Map<string, VariableCollection>()\n const placedByCollection = new Map<string, Array<{ variable: Variable; path: string[] }>>()\n for (const collection of collections) {\n const variables = compact(collection.variableIds.map((id) => graph.variables.get(id)))\n const { placed, duplicates } = placeTokens(\n variables.map((variable) => ({ key: variable, path: tokenPath(variable.name) }))\n )\n for (const variable of duplicates)\n issues.push({ kind: 'duplicate-path', collection: collection.name, token: variable.name })\n placedByCollection.set(\n collection.id,\n [...placed].map(([variable, path]) => ({ variable, path }))\n )\n for (const [variable, path] of placed) {\n references.set(variable.id, path)\n collectionOf.set(variable.id, collection)\n }\n }\n const context: ExportContext = { graph, references, collectionOf, issues }\n const files: DesignTokenFile[] = []\n const styles = styleTokens(graph, references)\n issues.push(...styles.issues)\n const stylesPath = styles.tokens.length > 0 ? STYLES_FILE : null\n const folders = distinct(collections.map((collection) => fileSegment(collection.name)))\n const collectionNames = distinct(\n collections.map((collection) => collection.name),\n stylesPath ? [STYLES_SET] : []\n )\n const collectionFiles = collections.map((collection, index): CollectionFiles => {\n const fileNames = distinct(collection.modes.map((mode) => fileSegment(mode.name)))\n const modeNames = distinct(collection.modes.map((mode) => mode.name))\n const modes = collection.modes.map((mode, modeIndex) => {\n const path = `${folders[index]}/${fileNames[modeIndex]}.tokens.json`\n const tokens = (placedByCollection.get(collection.id) ?? []).flatMap(\n ({ variable, path: tokenAt }) => {\n const token = variableToken(context, collection, mode, variable)\n return token\n ? [{ path: tokenAt, token: withOriginalName(token, variable.name, tokenAt) }]\n : []\n }\n )\n files.push({\n path,\n content: { ...tokenTree(tokens), $extensions: modeExtension(collection, mode) }\n })\n return {\n name: modeNames[modeIndex],\n path,\n isDefault: mode.modeId === collection.defaultModeId\n }\n })\n return { collection, name: collectionNames[index], modes }\n })\n if (stylesPath) files.push({ path: stylesPath, content: tokenTree(styles.tokens) })\n if (files.length > 0)\n files.push({ path: RESOLVER_FILE, content: resolverDocument(collectionFiles, stylesPath) })\n return { files, issues }\n}\n"],"mappings":";;;;;;;;;;;AA8BA,MAAa,gBAAgB;;AAE7B,MAAa,cAAc;;AAG3B,SAAS,SAAS,OAA0B,WAA8B,CAAC,GAAa;CACtF,MAAM,QAAQ,IAAI,IAAI,QAAQ;CAC9B,OAAO,MAAM,KAAK,SAAS;EACzB,MAAM,YAAY,aAAa,MAAM,KAAK;EAC1C,MAAM,IAAI,SAAS;EACnB,OAAO;CACT,CAAC;AACH;;AAGA,MAAM,aAAa;;AAGnB,SAAS,eAAe,MAAsB;CAC5C,OAAO,KAAK,WAAW,KAAK,IAAI,CAAC,CAAC,WAAW,KAAK,IAAI;AACxD;;AAUA,SAAS,eAAe,UAAoB,QAAgB,SAAkB;CAC5E,MAAM,SAAS,OACb;EACE,MAAM,SAAS;EACf,YAAY,SAAS,cAAc,OAAO,EAAE;EAC5C;EACA,QAAQ,SAAS;EACjB,YAAY,SAAS;EACrB,sBAAsB,SAAS,wBAAwB,KAAA;CACzD,IACC,UAAU,UAAU,KAAA,CACvB;CACA,OAAO,cAAc,MAAM,IAAI,CAAC,IAAI,GAAG,qBAAqB,OAAO;AACrE;;;;;AAMA,SAAS,cACP,SACA,YACA,MACA,UACyB;CACzB,MAAM,QAAQ;EAAE,YAAY,WAAW;EAAM,MAAM,KAAK;EAAM,OAAO,SAAS;CAAK;CACnF,IAAI,CAAC,OAAO,OAAO,SAAS,cAAc,KAAK,MAAM,GAAG;EACtD,QAAQ,O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O;CAAO;AACzB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../../src/io/formats/design-tokens/plan/index.ts"],"mappings":";;;;;;KA+BY;EACN;EAAa;;EACb;EAAkB;;EAClB;;;KAGM;EACN;EAAa;;EACb;EAAkB;;EAClB;;;UAGW;EACf,QAAQ;EACR,OAAO;;UAGQ;EACf,aAAa;;EAEb;;EAEA;;;KAIU,mBACR;UAMa;EACf;EACA;EACA,QAAQ;;;KAIE;EACN;EAAe,OAAO;;EACtB;EAAe,OAAO;;;KAGhB;EACN;EAAkB;;EAClB;EAAiB;EAAoB;;KAE/B;EACN;EAAiB,OAAO,QAAQ;IAAgB;;;EAChD;EAAe,QAAQ;;UAEZ;EACf;EACA,MAAM;;EAEN;;EAEA,QAAQ,MAAM;EACd,aAAa;EACb,OAAO;EACP,SAAS;EACT,aAAa,QAAQ,OAAO;EAC5B;EACA;;UAGe;EACf;EACA,QAAQ,QAAQ;IAAc;;EAC9B;EACA;;UAGe;EACf;EACA,QAAQ,QAAQ;IAAoB;;EACpC,OAAO;EACP;EACA,WAAW;;UAGI;EACf,aAAa;EACb,QAAQ;EACR,SAAS;EACT;IAAU;IAAe;IAAiB;;;;iBAI5B,0BACd,OAAO,YACP,QAAQ,oBACP;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../../src/io/formats/design-tokens/plan/index.ts"],"mappings":";;;;;;KA+BY;EACN;EAAa;;EACb;EAAkB;;EAClB;;;KAGM;EACN;EAAa;;EACb;EAAkB;;EAClB;;;UAGW;EACf,QAAQ;EACR,OAAO;;UAGQ;EACf,aAAa;;EAEb;;EAEA;;;KAIU,mBACR;UAMa;EACf;EACA;EACA,QAAQ;;;KAIE;EACN;EAAe,OAAO;;EACtB;EAAe,OAAO;;;KAGhB;EACN;EAAkB;;EAClB;EAAiB;EAAoB;;KAE/B;EACN;EAAiB,OAAO,QAAQ;IAAgB;;;EAChD;EAAe,QAAQ;;UAEZ;EACf;EACA,MAAM;;EAEN;;EAEA,QAAQ,MAAM;EACd,aAAa;EACb,OAAO;EACP,SAAS;EACT,aAAa,QAAQ,OAAO;EAC5B;EACA;;UAGe;EACf;EACA,QAAQ,QAAQ;IAAc;;EAC9B;EACA;;UAGe;EACf;EACA,QAAQ,QAAQ;IAAoB;;EACpC,OAAO;EACP;EACA,WAAW;;UAGI;EACf,aAAa;EACb,QAAQ;EACR,SAAS;EACT;IAAU;IAAe;IAAiB;;;;iBAI5B,0BACd,OAAO,YACP,QAAQ,oBACP;;;;;;iBAyRa,gBACd,OAAO,YACP,QAAQ,mBACR,SAAS,qBACR"}
|
|
@@ -6,7 +6,7 @@ import { compact } from "es-toolkit/array";
|
|
|
6
6
|
//#region src/io/formats/design-tokens/plan/index.ts
|
|
7
7
|
/** Collections and modes matched by name; anything without a match is new. */
|
|
8
8
|
function defaultTokenImportOptions(graph, bundle) {
|
|
9
|
-
const existing =
|
|
9
|
+
const existing = graph.getLiveCollections().filter((collection) => !isLibraryCollection(collection));
|
|
10
10
|
const claimed = /* @__PURE__ */ new Set();
|
|
11
11
|
return {
|
|
12
12
|
collections: bundle.collections.map((collection) => {
|
|
@@ -58,7 +58,7 @@ function tokensByName(collection, modes) {
|
|
|
58
58
|
function indexesOf(planner) {
|
|
59
59
|
if (planner.indexes) return planner.indexes;
|
|
60
60
|
const variables = /* @__PURE__ */ new Map();
|
|
61
|
-
for (const variable of planner.graph.
|
|
61
|
+
for (const variable of planner.graph.getLiveVariables()) variables.set(variable.name, [...variables.get(variable.name) ?? [], variable]);
|
|
62
62
|
const planned = /* @__PURE__ */ new Map();
|
|
63
63
|
planner.collections.forEach((collection, index) => {
|
|
64
64
|
if (planned.has(collection.name)) return;
|
|
@@ -170,7 +170,8 @@ function planVariables(planner, index, collection, modeIndexes, addMissing) {
|
|
|
170
170
|
const rows = [];
|
|
171
171
|
const existingByName = variablesByName(planner.graph, planner.existingByCollection[index]);
|
|
172
172
|
for (const [name, tokens] of tokensByName(collection, modeIndexes)) {
|
|
173
|
-
const
|
|
173
|
+
const profile = planner.graph.documentColorSpace;
|
|
174
|
+
const decoded = tokens.map((token) => token ? decodeVariableToken(token, profile) : void 0);
|
|
174
175
|
const failure = decoded.find((entry) => typeof entry === "string");
|
|
175
176
|
const usable = decoded.map((entry) => typeof entry === "string" ? void 0 : entry);
|
|
176
177
|
if (usable.every((entry) => entry === void 0)) {
|