@pairdraw/dom-css 0.21.0 → 0.22.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/chunks/behaviours/states/layers.js +100 -15
- package/dist/chunks/behaviours/states/layers.js.map +1 -1
- package/dist/chunks/browser.js +373 -37
- package/dist/chunks/browser.js.map +1 -1
- package/dist/chunks/import/html.js +66 -11
- package/dist/chunks/import/html.js.map +1 -1
- package/dist/chunks/import/jsx/source/ast.js +207 -0
- package/dist/chunks/import/jsx/source/ast.js.map +1 -0
- package/dist/chunks/import/jsx/source/candidates.js +74 -0
- package/dist/chunks/import/jsx/source/candidates.js.map +1 -0
- package/dist/chunks/import/jsx/source/evaluate.js +213 -0
- package/dist/chunks/import/jsx/source/evaluate.js.map +1 -0
- package/dist/chunks/import/jsx/source/index.js +448 -0
- package/dist/chunks/import/jsx/source/index.js.map +1 -0
- package/dist/export.d.ts +16 -3
- package/dist/export.js +2 -2
- package/dist/index.d.ts +66 -1
- package/dist/index.js +5 -2
- package/dist/styling.d.ts +9 -2
- package/package.json +5 -3
- package/src/cssom/browser.ts +63 -0
- package/src/export/css.ts +28 -1
- package/src/export/index.ts +3 -0
- package/src/export/projection.ts +97 -13
- package/src/import/flow.ts +127 -6
- package/src/import/jsx/source/ast.ts +267 -0
- package/src/import/jsx/source/candidates.ts +72 -0
- package/src/import/jsx/source/evaluate.ts +300 -0
- package/src/import/jsx/source/index.ts +36 -0
- package/src/import/jsx/source/render.ts +543 -0
- package/src/import/jsx/source/report.ts +49 -0
- package/src/import/scene-graph.ts +19 -7
- package/src/index.ts +10 -0
- package/src/runtime/browser/runtime.ts +13 -5
- package/src/runtime/browser/sandbox.ts +176 -27
- package/src/runtime/css/scan.ts +45 -0
- package/src/runtime/css/url.ts +92 -0
- package/src/runtime/headless/styles.ts +71 -15
package/dist/index.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { serializeNode } from "./chunks/behaviours/states/tailwind.js";
|
|
2
2
|
import { STORYBOOK_FRAMEWORKS } from "./chunks/export/storybook/component.js";
|
|
3
3
|
import { STORY_MODES, exportStorybook } from "./chunks/export/storybook/export.js";
|
|
4
|
-
import { createBrowserCSSRuntime } from "./chunks/browser.js";
|
|
4
|
+
import { createBrowserCSSRuntime, decodedCSS, mentionsResource, mentionsURL, withoutResourceRules } from "./chunks/browser.js";
|
|
5
5
|
import { compileTailwindCSS, createCSSRuntime, createHeadlessCSSRuntime, htmlToDesignDocument, htmlToSceneGraph, tailwindHTMLToDesignDocument, tailwindHTMLToSceneGraph } from "./chunks/import/html.js";
|
|
6
|
+
import { CodeSourceError, CodeTooLargeError, MAX_CODE_ELEMENTS } from "./chunks/import/jsx/source/ast.js";
|
|
7
|
+
import { jsxSourceToTree } from "./chunks/import/jsx/source/index.js";
|
|
8
|
+
import { tailwindCandidates, tailwindUtilities } from "./chunks/import/jsx/source/candidates.js";
|
|
6
9
|
import { jsxToDesignDocument, jsxToSceneGraph, tailwindJSXToDesignDocument, tailwindJSXToSceneGraph } from "./chunks/import/jsx/dev-runtime.js";
|
|
7
|
-
export { STORYBOOK_FRAMEWORKS, STORY_MODES, compileTailwindCSS, createBrowserCSSRuntime, createCSSRuntime, createHeadlessCSSRuntime, exportStorybook, htmlToDesignDocument, htmlToSceneGraph, jsxToDesignDocument, jsxToSceneGraph, serializeNode, tailwindHTMLToDesignDocument, tailwindHTMLToSceneGraph, tailwindJSXToDesignDocument, tailwindJSXToSceneGraph };
|
|
10
|
+
export { CodeSourceError, CodeTooLargeError, MAX_CODE_ELEMENTS, STORYBOOK_FRAMEWORKS, STORY_MODES, compileTailwindCSS, createBrowserCSSRuntime, createCSSRuntime, createHeadlessCSSRuntime, decodedCSS, exportStorybook, htmlToDesignDocument, htmlToSceneGraph, jsxSourceToTree, jsxToDesignDocument, jsxToSceneGraph, mentionsResource, mentionsURL, serializeNode, tailwindCandidates, tailwindHTMLToDesignDocument, tailwindHTMLToSceneGraph, tailwindJSXToDesignDocument, tailwindJSXToSceneGraph, tailwindUtilities, withoutResourceRules };
|
package/dist/styling.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DesignDocument, DesignElement, DesignNode } from "./types.js";
|
|
1
|
+
import { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from "./types.js";
|
|
2
2
|
import { SceneGraph, SceneNode } from "@pairdraw/scene-graph";
|
|
3
3
|
//#region src/export/projection.d.ts
|
|
4
4
|
/**
|
|
@@ -19,6 +19,13 @@ interface SceneGraphToDesignOptions {
|
|
|
19
19
|
/** Hidden layers to project as shown, such as the tab panels a component reveals itself. */
|
|
20
20
|
shown?: ReadonlySet<string>;
|
|
21
21
|
}
|
|
22
|
+
/** Whether a projected style paints; a radius or a placement property on its own does not. */
|
|
23
|
+
declare function paintsSomething(style: DesignStyleDeclaration): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Whether a projected layer paints or writes text. A frame with no paint and no children projects
|
|
26
|
+
* to a bare element with only its size, so a selection of such layers draws nothing.
|
|
27
|
+
*/
|
|
28
|
+
declare function designNodeDraws(node: DesignNode): boolean;
|
|
22
29
|
declare function sceneGraphToDesignDocument(graph: SceneGraph, options?: SceneGraphToDesignOptions): DesignDocument;
|
|
23
30
|
/** Project one node, including its own box, instead of the children of a root. */
|
|
24
31
|
declare function sceneNodeToDesignDocument(graph: SceneGraph, nodeId: string, options?: Omit<SceneGraphToDesignOptions, 'rootId'>): DesignDocument;
|
|
@@ -94,5 +101,5 @@ declare function serializeHTML(document: DesignDocument, options?: SerializeHTML
|
|
|
94
101
|
declare const COMPONENT_STYLINGS: readonly ["css", "tailwind"];
|
|
95
102
|
type ComponentStyling = (typeof COMPONENT_STYLINGS)[number];
|
|
96
103
|
//#endregion
|
|
97
|
-
export { COMPONENT_STYLINGS, ComponentStyling, ExportHTMLBundle, ExportHTMLBundleOptions, ExportHTMLFile, SceneGraphToDesignOptions, SerializeHTMLOptions, TailwindStylesheetId, TailwindStylesheetLoader, VectorElementRenderer, WebFontFaceAsset, WebFontFaceRequest, WebFontFaceResolver, exportHTMLBundle, sceneGraphToDesignDocument, sceneNodeToDesignDocument, sceneNodesToDesignDocument, serializeHTML, serializeNode };
|
|
104
|
+
export { COMPONENT_STYLINGS, ComponentStyling, ExportHTMLBundle, ExportHTMLBundleOptions, ExportHTMLFile, SceneGraphToDesignOptions, SerializeHTMLOptions, TailwindStylesheetId, TailwindStylesheetLoader, VectorElementRenderer, WebFontFaceAsset, WebFontFaceRequest, WebFontFaceResolver, designNodeDraws, exportHTMLBundle, paintsSomething, sceneGraphToDesignDocument, sceneNodeToDesignDocument, sceneNodesToDesignDocument, serializeHTML, serializeNode };
|
|
98
105
|
//# sourceMappingURL=styling.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pairdraw/dom-css",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
12
|
"dependencies": {
|
|
13
13
|
"@acemir/cssom": "^0.9.31",
|
|
14
|
-
"@pairdraw/emit": "^0.
|
|
14
|
+
"@pairdraw/emit": "^0.22.0",
|
|
15
|
+
"acorn": "^8.18.0",
|
|
15
16
|
"css-tree": "^3.2.1",
|
|
16
17
|
"cssesc": "^3.0.0",
|
|
17
18
|
"dedent": "^1.7.2",
|
|
@@ -20,11 +21,12 @@
|
|
|
20
21
|
"js-base64": "^3.9.3",
|
|
21
22
|
"parse5": "^8.0.1",
|
|
22
23
|
"postcss-value-parser": "^4.2.0",
|
|
24
|
+
"sucrase": "^3.35.1",
|
|
23
25
|
"tailwindcss": "^4.3.3",
|
|
24
26
|
"twirlwind": "^0.4.1"
|
|
25
27
|
},
|
|
26
28
|
"peerDependencies": {
|
|
27
|
-
"@pairdraw/scene-graph": "^0.
|
|
29
|
+
"@pairdraw/scene-graph": "^0.22.0"
|
|
28
30
|
},
|
|
29
31
|
"exports": {
|
|
30
32
|
".": {
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser's own CSS object model, in place of `@acemir/cssom`.
|
|
3
|
+
*
|
|
4
|
+
* That package's browser build only defines a global on a script, so Vite's optimizer emits a
|
|
5
|
+
* dependency with no ESM exports and the app fails to boot. `vite/aliases.ts` points the package
|
|
6
|
+
* here for the app's module graph; Node and headless runs keep the package.
|
|
7
|
+
*
|
|
8
|
+
* A constructable stylesheet answers `parse` synchronously in the browsers the app supports, and
|
|
9
|
+
* its rule lists are converted to arrays because the readers recurse with `Array.isArray`.
|
|
10
|
+
*/
|
|
11
|
+
import type { CSSStyleDeclarationLike, CSSStyleRuleLike } from './types'
|
|
12
|
+
|
|
13
|
+
interface RuleLike {
|
|
14
|
+
selectorText?: string
|
|
15
|
+
style?: CSSStyleDeclarationLike
|
|
16
|
+
cssRules?: RuleLike[]
|
|
17
|
+
[key: string]: unknown
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface SheetLike {
|
|
21
|
+
replaceSync(cssText: string): void
|
|
22
|
+
readonly cssRules: ArrayLike<RuleLike>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type SheetConstructor = new () => SheetLike
|
|
26
|
+
|
|
27
|
+
/** The browser's `CSSStyleSheet`, when this runtime provides one. */
|
|
28
|
+
function browserSheet(): SheetConstructor | undefined {
|
|
29
|
+
const Constructor: unknown = Reflect.get(globalThis, 'CSSStyleSheet')
|
|
30
|
+
// A DOM constructor is a function; the cast names the shape the browser guarantees for it.
|
|
31
|
+
return typeof Constructor === 'function' ? (Constructor as SheetConstructor) : undefined
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The browser's `CSSStyleSheet`, or a clear failure on a runtime without one. */
|
|
35
|
+
function sheetConstructor(): SheetConstructor {
|
|
36
|
+
const Constructor = browserSheet()
|
|
37
|
+
if (!Constructor) throw new Error('This runtime has no constructable CSSStyleSheet')
|
|
38
|
+
return Constructor
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A rule as the package returned it: a style rule keeps its declaration, a group an array. */
|
|
42
|
+
function plainRule(rule: RuleLike): RuleLike {
|
|
43
|
+
if ('style' in rule && rule.style && typeof rule.selectorText === 'string') {
|
|
44
|
+
return { selectorText: rule.selectorText, style: rule.style } satisfies CSSStyleRuleLike
|
|
45
|
+
}
|
|
46
|
+
if ('cssRules' in rule && rule.cssRules) {
|
|
47
|
+
return { ...rule, cssRules: Array.from(rule.cssRules, plainRule) }
|
|
48
|
+
}
|
|
49
|
+
return rule
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** `@acemir/cssom`'s `parse`, answered by the browser's parser. */
|
|
53
|
+
export function parse(cssText: string): { cssRules: RuleLike[] } {
|
|
54
|
+
const sheet = new (sheetConstructor())()
|
|
55
|
+
sheet.replaceSync(cssText)
|
|
56
|
+
return { cssRules: Array.from(sheet.cssRules, plainRule) }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The constructor the dynamic fallback in `behaviours/states/css.ts` destructures. In a browser
|
|
61
|
+
* that reached that fallback the class is already absent, so the browser path never uses it.
|
|
62
|
+
*/
|
|
63
|
+
export const CSSStyleSheet = browserSheet()
|
package/src/export/css.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type {
|
|
|
3
3
|
Effect,
|
|
4
4
|
Fill,
|
|
5
5
|
GradientStop,
|
|
6
|
+
GradientTransform,
|
|
6
7
|
SceneNode,
|
|
7
8
|
ShadowEffect,
|
|
8
9
|
Stroke,
|
|
@@ -11,6 +12,7 @@ import type {
|
|
|
11
12
|
import { colorToDocumentCSS } from '@pairdraw/scene-graph/color'
|
|
12
13
|
import { blurSigma } from '@pairdraw/scene-graph/geometry'
|
|
13
14
|
import { gradientPoint } from '@pairdraw/scene-graph/gradient'
|
|
15
|
+
import type { GradientTransformRows } from '@pairdraw/scene-graph/gradient'
|
|
14
16
|
import type { Color, Vector } from '@pairdraw/scene-graph/primitives'
|
|
15
17
|
|
|
16
18
|
import type { DesignStyleDeclaration } from '../types'
|
|
@@ -41,6 +43,31 @@ function positionToCSS(point: Vector): string {
|
|
|
41
43
|
return `${cssNumber(point.x * 100)}% ${cssNumber(point.y * 100)}%`
|
|
42
44
|
}
|
|
43
45
|
|
|
46
|
+
/**
|
|
47
|
+
* A diamond gradient as the Pairdraw spelling `get_css` reads and `set_fill` parses: CSS has no
|
|
48
|
+
* diamond form, and the stops are the same colours and positions every other gradient emits.
|
|
49
|
+
*/
|
|
50
|
+
export function diamondFillToCSS(fill: Fill, profile: ColorProfile = 'srgb'): string | undefined {
|
|
51
|
+
if (fill.type !== 'GRADIENT_DIAMOND' || !fill.visible) return undefined
|
|
52
|
+
const stops = fill.gradientStops
|
|
53
|
+
if (!stops || stops.length === 0) return undefined
|
|
54
|
+
return `diamond-gradient(${stops.map((stop) => stopToCSS(stop, fill.opacity, profile)).join(', ')})`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A stored gradient transform as the matrix the geometry reads. A document or tool boundary can
|
|
59
|
+
* still hand over Figma's two rows of three, which would make every matrix field undefined and the
|
|
60
|
+
* CSS angle NaN; both shapes are accepted here.
|
|
61
|
+
*/
|
|
62
|
+
function gradientTransformMatrix(
|
|
63
|
+
transform: GradientTransform | GradientTransformRows | undefined
|
|
64
|
+
): GradientTransform | undefined {
|
|
65
|
+
if (!transform) return undefined
|
|
66
|
+
if (!Array.isArray(transform)) return transform
|
|
67
|
+
const [[m00, m01, m02], [m10, m11, m12]] = transform
|
|
68
|
+
return { m00, m01, m02, m10, m11, m12 }
|
|
69
|
+
}
|
|
70
|
+
|
|
44
71
|
/**
|
|
45
72
|
* A gradient paint as the CSS gradient that draws it in a `width` × `height` box. The transform
|
|
46
73
|
* maps the box's unit square onto gradient space; its inverse gives the line's ends, the
|
|
@@ -52,7 +79,7 @@ export function gradientFillToCSS(
|
|
|
52
79
|
height: number,
|
|
53
80
|
profile: ColorProfile = 'srgb'
|
|
54
81
|
): string | undefined {
|
|
55
|
-
const transform = fill.gradientTransform
|
|
82
|
+
const transform = gradientTransformMatrix(fill.gradientTransform)
|
|
56
83
|
const stops = fill.gradientStops
|
|
57
84
|
if (!fill.visible || !transform || !stops || stops.length === 0 || width <= 0 || height <= 0) {
|
|
58
85
|
return undefined
|
package/src/export/index.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
export { diamondFillToCSS, gradientFillToCSS } from './css'
|
|
1
2
|
// SceneGraph → HTML and JSX without the CSS runtimes, so browsers can bundle it.
|
|
2
3
|
export {
|
|
4
|
+
designNodeDraws,
|
|
5
|
+
paintsSomething,
|
|
3
6
|
sceneGraphToDesignDocument,
|
|
4
7
|
sceneNodeToDesignDocument,
|
|
5
8
|
sceneNodesToDesignDocument,
|
package/src/export/projection.ts
CHANGED
|
@@ -4,7 +4,12 @@ import { fromUint8Array } from 'js-base64'
|
|
|
4
4
|
import type { ColorProfile, SceneGraph, SceneNode, Stroke } from '@pairdraw/scene-graph'
|
|
5
5
|
import { BLACK } from '@pairdraw/scene-graph/constants'
|
|
6
6
|
import { readIcon } from '@pairdraw/scene-graph/icons'
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
imageMimeType,
|
|
9
|
+
imageSize,
|
|
10
|
+
makeImageFillLocalMatrix,
|
|
11
|
+
type ImagePlacement
|
|
12
|
+
} from '@pairdraw/scene-graph/images'
|
|
8
13
|
import { layoutSizingInParent } from '@pairdraw/scene-graph/layout'
|
|
9
14
|
import { isShaderPresetPaint, shaderOfPaint } from '@pairdraw/scene-graph/shaders'
|
|
10
15
|
import { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'
|
|
@@ -52,8 +57,33 @@ export interface SceneGraphToDesignOptions {
|
|
|
52
57
|
/** Layers whose shape only paths describe, which CSS boxes cannot draw. */
|
|
53
58
|
const VECTOR_SHAPES = new Set<SceneNode['type']>(['VECTOR', 'BOOLEAN_OPERATION', 'STAR', 'POLYGON'])
|
|
54
59
|
|
|
55
|
-
/** What a
|
|
56
|
-
const
|
|
60
|
+
/** What a vector's own SVG draws, so the placement wrapper leaves it out; a backdrop stays on the wrapper. */
|
|
61
|
+
const VECTOR_WRAPPER_PAINT = /^(background|border|box-shadow|outline|filter)/
|
|
62
|
+
|
|
63
|
+
/** Every CSS property that paints a layer, wherever its paint is written. */
|
|
64
|
+
export const PAINT_PROPERTY =
|
|
65
|
+
/^(background|backdrop-filter|border|box-shadow|outline|filter|color|fill|stroke|text-shadow)/
|
|
66
|
+
|
|
67
|
+
/** Whether a projected style paints; a radius or a placement property on its own does not. */
|
|
68
|
+
export function paintsSomething(style: DesignStyleDeclaration): boolean {
|
|
69
|
+
return Object.keys(style).some(
|
|
70
|
+
(property) => PAINT_PROPERTY.test(property) && !property.endsWith('radius')
|
|
71
|
+
)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Whether a projected layer paints or writes text. A frame with no paint and no children projects
|
|
76
|
+
* to a bare element with only its size, so a selection of such layers draws nothing.
|
|
77
|
+
*/
|
|
78
|
+
export function designNodeDraws(node: DesignNode): boolean {
|
|
79
|
+
if (node.type === 'text') return node.text.trim().length > 0
|
|
80
|
+
if (node.shader?.frame) return true
|
|
81
|
+
if (node.tagName === 'svg' || node.tagName === 'img' || node.tagName === 'canvas') return true
|
|
82
|
+
return (
|
|
83
|
+
paintsSomething({ ...node.computedStyle, ...node.inlineStyle }) ||
|
|
84
|
+
node.children.some(designNodeDraws)
|
|
85
|
+
)
|
|
86
|
+
}
|
|
57
87
|
|
|
58
88
|
/** A field's CSS: its token reference where one is faithful, otherwise the literal value. */
|
|
59
89
|
type FieldCSS = (field: string, literal: string) => string
|
|
@@ -295,12 +325,57 @@ function addShaderLayerStyle(style: DesignStyleDeclaration): void {
|
|
|
295
325
|
style.isolation = 'isolate'
|
|
296
326
|
}
|
|
297
327
|
|
|
298
|
-
|
|
328
|
+
/**
|
|
329
|
+
* Where a crop or tile puts its image in the layer, as CSS background placement. A crop or tile
|
|
330
|
+
* turned by `imageRotation` (or by rotation inside a crop transform) has no CSS background form;
|
|
331
|
+
* null keeps the image element for those, covering the box as the closest export.
|
|
332
|
+
*/
|
|
333
|
+
function backgroundImagePlacement(
|
|
334
|
+
graph: SceneGraph,
|
|
335
|
+
node: SceneNode
|
|
336
|
+
): { placement: ImagePlacement; css: Record<string, string> } | null {
|
|
337
|
+
const fill = node.fills.at(0)
|
|
338
|
+
if (fill?.type !== 'IMAGE' || !fill.visible || !fill.imageHash) return null
|
|
339
|
+
if (shaderOfPaint(node, fill)) return null
|
|
340
|
+
const mode = fill.imageScaleMode ?? 'FILL'
|
|
341
|
+
if (mode !== 'CROP' && mode !== 'TILE') return null
|
|
342
|
+
const bytes = graph.images.get(fill.imageHash)
|
|
343
|
+
const natural = bytes ? imageSize(bytes) : null
|
|
344
|
+
if (!bytes || !natural) return null
|
|
345
|
+
const [m00, m01, m02, m10, m11, m12] = makeImageFillLocalMatrix(
|
|
346
|
+
fill,
|
|
347
|
+
node,
|
|
348
|
+
natural.width,
|
|
349
|
+
natural.height
|
|
350
|
+
)
|
|
351
|
+
const straightened = Math.abs(m01) < 1e-6 && Math.abs(m10) < 1e-6 && m00 > 0 && m11 > 0
|
|
352
|
+
if (!straightened) return null
|
|
353
|
+
const url = imageDataURL(bytes)
|
|
354
|
+
return {
|
|
355
|
+
placement: { url, mode },
|
|
356
|
+
css: {
|
|
357
|
+
'background-image': `url("${url}")`,
|
|
358
|
+
'background-size': `${m00 * natural.width}px ${m11 * natural.height}px`,
|
|
359
|
+
'background-position': `${m02}px ${m12}px`,
|
|
360
|
+
'background-repeat': mode === 'TILE' ? 'repeat' : 'no-repeat'
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function addImageStyle(
|
|
366
|
+
style: DesignStyleDeclaration,
|
|
367
|
+
node: SceneNode,
|
|
368
|
+
placement: ImagePlacement | undefined
|
|
369
|
+
): void {
|
|
299
370
|
const fill = node.fills.at(0)
|
|
300
371
|
if (fill?.type !== 'IMAGE' || !fill.visible || shaderOfPaint(node, fill)) return
|
|
301
372
|
if (node.width > 0 && node.height > 0) style['aspect-ratio'] = `${node.width} / ${node.height}`
|
|
373
|
+
if (placement) return
|
|
302
374
|
if (fill.imageScaleMode === 'FIT') style['object-fit'] = 'contain'
|
|
303
375
|
if (fill.imageScaleMode === 'FILL') style['object-fit'] = 'cover'
|
|
376
|
+
// A turned crop or tile has no background form; the image element covers the box.
|
|
377
|
+
if (fill.imageScaleMode === 'CROP' || fill.imageScaleMode === 'TILE')
|
|
378
|
+
style['object-fit'] = 'cover'
|
|
304
379
|
}
|
|
305
380
|
|
|
306
381
|
/** Styles a node takes from its parent's layout, and its own rotation. */
|
|
@@ -358,17 +433,19 @@ function styleFromSceneNode(
|
|
|
358
433
|
node: SceneNode,
|
|
359
434
|
parent: SceneNode | undefined,
|
|
360
435
|
css: FieldCSS,
|
|
361
|
-
profile: ColorProfile
|
|
436
|
+
profile: ColorProfile,
|
|
437
|
+
placement: { placement: ImagePlacement; css: Record<string, string> } | null
|
|
362
438
|
): DesignStyleDeclaration {
|
|
363
439
|
const style: DesignStyleDeclaration = {}
|
|
364
440
|
addSize(style, node, parent, css)
|
|
365
441
|
addPositioning(style, node, parent)
|
|
366
442
|
addSizeConstraints(style, node, css)
|
|
443
|
+
if (placement) Object.assign(style, placement.css)
|
|
367
444
|
const fill = fillToCSS(node.fills.at(0), profile)
|
|
368
445
|
if (fill) style['background-color'] = css('fills/0/color', fill)
|
|
369
446
|
const gradients = gradientFillsToCSS(node.fills, node.width, node.height, profile)
|
|
370
447
|
if (gradients) style['background-image'] = gradients
|
|
371
|
-
addImageStyle(style, node)
|
|
448
|
+
addImageStyle(style, node, placement?.placement)
|
|
372
449
|
addStroke(style, node, css, profile)
|
|
373
450
|
Object.assign(style, effectsToCSS(node.effects, profile))
|
|
374
451
|
const visibleStrokes = node.strokes.filter((stroke) => stroke.visible)
|
|
@@ -478,6 +555,8 @@ function attrsForNode(
|
|
|
478
555
|
if (includeSourceIds) attrs['data-pairdraw-node-id'] = node.id
|
|
479
556
|
const sourceURL = imageSourceURL(node)
|
|
480
557
|
if (sourceURL) attrs.src = sourceURL
|
|
558
|
+
const placement = backgroundImagePlacement(graph, node)
|
|
559
|
+
if (placement) return attrs
|
|
481
560
|
const fill = node.fills.at(0)
|
|
482
561
|
if (fill?.type !== 'IMAGE' || !fill.imageHash || shaderOfPaint(node, fill)) return attrs
|
|
483
562
|
const bytes = graph.images.get(fill.imageHash)
|
|
@@ -485,12 +564,14 @@ function attrsForNode(
|
|
|
485
564
|
return { ...attrs, src: imageDataURL(bytes) }
|
|
486
565
|
}
|
|
487
566
|
|
|
488
|
-
function tagNameForNode(node: SceneNode): string {
|
|
567
|
+
function tagNameForNode(graph: SceneGraph, node: SceneNode): string {
|
|
489
568
|
if (node.type === 'SECTION') return 'section'
|
|
490
569
|
const fill = node.fills.at(0)
|
|
491
570
|
const image = fill?.type === 'IMAGE' && !shaderOfPaint(node, fill)
|
|
492
|
-
if ((image || imageSourceURL(node))
|
|
493
|
-
|
|
571
|
+
if (!(image || imageSourceURL(node)) || node.childIds.length > 0) return 'div'
|
|
572
|
+
// A crop or tile the CSS background can place is a box; a turned one stays an image element.
|
|
573
|
+
if (image && backgroundImagePlacement(graph, node)) return 'div'
|
|
574
|
+
return 'img'
|
|
494
575
|
}
|
|
495
576
|
|
|
496
577
|
interface ProjectionContext {
|
|
@@ -515,7 +596,7 @@ function vectorDesignNode(
|
|
|
515
596
|
const drawn = context.vectorElement?.(context.graph, node)
|
|
516
597
|
if (!drawn) return null
|
|
517
598
|
const placement = Object.fromEntries(
|
|
518
|
-
Object.entries(style).filter(([property]) => !
|
|
599
|
+
Object.entries(style).filter(([property]) => !VECTOR_WRAPPER_PAINT.test(property))
|
|
519
600
|
)
|
|
520
601
|
return {
|
|
521
602
|
...drawn,
|
|
@@ -586,10 +667,13 @@ function sceneNodeToDesignNode(
|
|
|
586
667
|
root: boolean
|
|
587
668
|
): DesignNode | null {
|
|
588
669
|
if ((!node.visible && !context.shown?.has(node.id)) || node.internalOnly) return null
|
|
670
|
+
// A slice is an export region, not a layer: no projection draws it or its absent children.
|
|
671
|
+
if (node.type === 'SLICE') return null
|
|
589
672
|
const { graph, tokens } = context
|
|
590
673
|
const parent = node.parentId ? graph.getNode(node.parentId) : undefined
|
|
591
674
|
const entered = tokens?.enter(node, inherited, root)
|
|
592
675
|
const modes = entered?.modes ?? inherited
|
|
676
|
+
const placement = backgroundImagePlacement(graph, node)
|
|
593
677
|
const attrs = { ...attrsForNode(graph, node, context), ...entered?.attrs }
|
|
594
678
|
const css: FieldCSS = (field, literal) => tokens?.reference(node, field, modes) ?? literal
|
|
595
679
|
|
|
@@ -616,7 +700,7 @@ function sceneNodeToDesignNode(
|
|
|
616
700
|
context,
|
|
617
701
|
node,
|
|
618
702
|
attrs,
|
|
619
|
-
styleFromSceneNode(node, parent, css, graph.documentColorSpace)
|
|
703
|
+
styleFromSceneNode(node, parent, css, graph.documentColorSpace, placement)
|
|
620
704
|
)
|
|
621
705
|
if (vector) return vector
|
|
622
706
|
}
|
|
@@ -634,12 +718,12 @@ function sceneNodeToDesignNode(
|
|
|
634
718
|
}
|
|
635
719
|
}
|
|
636
720
|
|
|
637
|
-
const style = styleFromSceneNode(node, parent, css, graph.documentColorSpace)
|
|
721
|
+
const style = styleFromSceneNode(node, parent, css, graph.documentColorSpace, placement)
|
|
638
722
|
const shader = layerShader(graph, node)
|
|
639
723
|
if (shader) addShaderLayerStyle(style)
|
|
640
724
|
return {
|
|
641
725
|
type: 'element',
|
|
642
|
-
tagName: tagNameForNode(node),
|
|
726
|
+
tagName: tagNameForNode(graph, node),
|
|
643
727
|
attrs,
|
|
644
728
|
inlineStyle: style,
|
|
645
729
|
sourceSceneNodeId: node.id,
|
package/src/import/flow.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { pick } from 'es-toolkit'
|
|
2
2
|
|
|
3
|
-
import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
|
|
3
|
+
import type { GridTrack, SceneGraph, SceneNode } from '@pairdraw/scene-graph'
|
|
4
4
|
import {
|
|
5
5
|
parseCSSAlignItems,
|
|
6
6
|
parseCSSFlexDirection,
|
|
7
7
|
parseCSSJustifyContent,
|
|
8
|
-
parseCSSNumber
|
|
8
|
+
parseCSSNumber,
|
|
9
|
+
splitCSSValue
|
|
9
10
|
} from '@pairdraw/scene-graph/css'
|
|
10
11
|
import {
|
|
11
12
|
autoLayoutSizingFields,
|
|
@@ -22,7 +23,7 @@ import { pickStyle } from './css-values'
|
|
|
22
23
|
* children vertically and stretches block-level ones across, a flex container is a stack in its
|
|
23
24
|
* direction that stretches items across by default, and inline-level content hugs.
|
|
24
25
|
*/
|
|
25
|
-
export type FlowKind = 'block' | 'flex' | 'inline'
|
|
26
|
+
export type FlowKind = 'block' | 'flex' | 'grid' | 'inline'
|
|
26
27
|
|
|
27
28
|
/** The layout a child is placed in: its parent's flow, or none at the top of the page. */
|
|
28
29
|
export type ParentFlow = FlowKind | 'none'
|
|
@@ -98,14 +99,120 @@ export function elementDisplay(element: DesignElement, style: DesignStyleDeclara
|
|
|
98
99
|
*/
|
|
99
100
|
export function flowOf(display: string): FlowKind {
|
|
100
101
|
if (display === 'flex' || display === 'inline-flex') return 'flex'
|
|
102
|
+
if (display === 'grid' || display === 'inline-grid') return 'grid'
|
|
101
103
|
return display === 'inline' ? 'inline' : 'block'
|
|
102
104
|
}
|
|
103
105
|
|
|
106
|
+
/** The most tracks a `repeat()` may expand to, so one value cannot grow a document. */
|
|
107
|
+
const MAX_GRID_TRACKS = 24
|
|
108
|
+
|
|
109
|
+
/** One column or row track of a grid, as CSS sizes it. */
|
|
110
|
+
function gridTrack(token: string): GridTrack | null {
|
|
111
|
+
const value = token.trim().toLowerCase()
|
|
112
|
+
if (value === 'auto' || value === 'min-content' || value === 'max-content') {
|
|
113
|
+
return { sizing: 'AUTO', value: 0 }
|
|
114
|
+
}
|
|
115
|
+
if (value.startsWith('fit-content(')) return { sizing: 'AUTO', value: 0 }
|
|
116
|
+
if (value.startsWith('minmax(')) {
|
|
117
|
+
const bounds = value.slice('minmax('.length, -1).split(',')
|
|
118
|
+
// A minimum the track cannot exceed keeps the track's smallest size; the maximum sizes it.
|
|
119
|
+
return gridTrack(bounds.at(1) ?? bounds.at(0) ?? '')
|
|
120
|
+
}
|
|
121
|
+
const fraction = /^([\d.]+)fr$/.exec(value)
|
|
122
|
+
if (fraction) return { sizing: 'FR', value: Number(fraction[1]) }
|
|
123
|
+
const length = /^(-?[\d.]+)(px|rem|em)$/.exec(value)
|
|
124
|
+
if (length) return { sizing: 'FIXED', value: Number(length[1]) }
|
|
125
|
+
if (/^-?[\d.]+$/.test(value)) return { sizing: 'FIXED', value: Number(value) }
|
|
126
|
+
return null
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The tracks a `grid-template-columns` or `grid-template-rows` value names. `undefined` when the
|
|
131
|
+
* value has a track this document cannot place, as `auto-fit` needs a width known at layout time
|
|
132
|
+
* and a percentage track a container size; the caller then keeps the content in block flow.
|
|
133
|
+
*/
|
|
134
|
+
export function gridTracks(value: string | undefined): GridTrack[] | undefined {
|
|
135
|
+
const trimmed = value?.trim()
|
|
136
|
+
if (!trimmed || trimmed === 'none' || trimmed === 'subgrid') return undefined
|
|
137
|
+
const tracks: GridTrack[] = []
|
|
138
|
+
for (const token of splitCSSValue(trimmed)) {
|
|
139
|
+
const repeat = /^repeat\(\s*([^,]+),\s*(.+)\)$/i.exec(token)
|
|
140
|
+
if (repeat) {
|
|
141
|
+
const count = Number(repeat[1])
|
|
142
|
+
if (!Number.isInteger(count) || count < 1 || count > MAX_GRID_TRACKS) return undefined
|
|
143
|
+
const inner = gridTracks(repeat[2])
|
|
144
|
+
if (!inner || inner.length === 0) return undefined
|
|
145
|
+
for (let index = 0; index < count; index++) tracks.push(...inner)
|
|
146
|
+
continue
|
|
147
|
+
}
|
|
148
|
+
const track = gridTrack(token)
|
|
149
|
+
if (!track) return undefined
|
|
150
|
+
tracks.push(track)
|
|
151
|
+
}
|
|
152
|
+
return tracks.length > 0 && tracks.length <= MAX_GRID_TRACKS ? tracks : undefined
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The lines `grid-column` or `grid-row` names: a start line and a span, or a bare span. */
|
|
156
|
+
export function gridLines(value: string | undefined): { start: number; span: number } | null {
|
|
157
|
+
const trimmed = value?.trim().toLowerCase()
|
|
158
|
+
if (!trimmed) return null
|
|
159
|
+
const span = /^span\s+(\d+)$/.exec(trimmed)
|
|
160
|
+
if (span) return { start: 0, span: Number(span[1]) }
|
|
161
|
+
const lines = /^(\d+)\s*\/\s*(?:span\s+)?(\d+)$/.exec(trimmed)
|
|
162
|
+
if (lines) {
|
|
163
|
+
const start = Number(lines[1])
|
|
164
|
+
const end = Number(lines[2])
|
|
165
|
+
return { start, span: Math.max(1, end - start) }
|
|
166
|
+
}
|
|
167
|
+
return null
|
|
168
|
+
}
|
|
169
|
+
|
|
104
170
|
/** Whether the element sits in a line rather than on its own row, so it hugs its content. */
|
|
105
171
|
function isInlineLevel(display: string): boolean {
|
|
106
172
|
return display.startsWith('inline')
|
|
107
173
|
}
|
|
108
174
|
|
|
175
|
+
/** Where a grid places a child, from `grid-column` and `grid-row`. */
|
|
176
|
+
export function applyGridPlacement(node: SceneNode, style: DesignStyleDeclaration): void {
|
|
177
|
+
const column = gridLines(pickStyle(style, 'grid-column') ?? gridColumnShorthand(style))
|
|
178
|
+
const row = gridLines(pickStyle(style, 'grid-row') ?? gridRowShorthand(style))
|
|
179
|
+
if (!column && !row) return
|
|
180
|
+
node.gridPosition = {
|
|
181
|
+
column: column?.start ?? 0,
|
|
182
|
+
row: row?.start ?? 0,
|
|
183
|
+
columnSpan: Math.max(1, column?.span ?? 1),
|
|
184
|
+
rowSpan: Math.max(1, row?.span ?? 1)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** `grid-area: 2 / 1 / 4 / 3`, as a start line and a span on each axis. */
|
|
189
|
+
function gridColumnShorthand(style: DesignStyleDeclaration): string | undefined {
|
|
190
|
+
const heading = gridAreaLines(style)
|
|
191
|
+
if (!heading) return undefined
|
|
192
|
+
return `${heading.startColumn} / ${heading.endColumn}`
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function gridRowShorthand(style: DesignStyleDeclaration): string | undefined {
|
|
196
|
+
const heading = gridAreaLines(style)
|
|
197
|
+
if (!heading) return undefined
|
|
198
|
+
return `${heading.startRow} / ${heading.endRow}`
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function gridAreaLines(style: DesignStyleDeclaration) {
|
|
202
|
+
const parts = pickStyle(style, 'grid-area')
|
|
203
|
+
?.trim()
|
|
204
|
+
.split(/\s*\/\s*/)
|
|
205
|
+
if (!parts || parts.length < 2) return null
|
|
206
|
+
const startRow = parts.at(0) ?? ''
|
|
207
|
+
const startColumn = parts.at(1) ?? ''
|
|
208
|
+
return {
|
|
209
|
+
startRow,
|
|
210
|
+
startColumn,
|
|
211
|
+
endRow: parts.at(2) ?? startRow,
|
|
212
|
+
endColumn: parts.at(3) ?? startColumn
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
109
216
|
function textAlignAxis(element: DesignElement, style: DesignStyleDeclaration) {
|
|
110
217
|
const align = pickStyle(style, 'text-align')?.trim().toLowerCase()
|
|
111
218
|
if (align === 'center') return 'CENTER'
|
|
@@ -129,7 +236,18 @@ export function applyContainerLayout(
|
|
|
129
236
|
node.layoutWrap = pickStyle(style, 'flex-wrap') === 'wrap' ? 'WRAP' : 'NO_WRAP'
|
|
130
237
|
return
|
|
131
238
|
}
|
|
132
|
-
if (flow === '
|
|
239
|
+
if (flow === 'grid') {
|
|
240
|
+
const columns = gridTracks(pickStyle(style, 'grid-template-columns'))
|
|
241
|
+
// Tracks the document cannot place, such as `auto-fit`, keep the content in block flow.
|
|
242
|
+
if (columns) {
|
|
243
|
+
node.layoutMode = 'GRID'
|
|
244
|
+
node.gridTemplateColumns = columns
|
|
245
|
+
const rows = gridTracks(pickStyle(style, 'grid-template-rows'))
|
|
246
|
+
if (rows) node.gridTemplateRows = rows
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
if (flow === 'grid' || flow === 'block') {
|
|
133
251
|
node.layoutMode = 'VERTICAL'
|
|
134
252
|
// Browsers center a button's content both ways.
|
|
135
253
|
if (CENTERED_TAGS.has(element.tagName.toLowerCase())) {
|
|
@@ -181,6 +299,7 @@ function applyParentFill(
|
|
|
181
299
|
// width of its own for block children to fill; they size it instead.
|
|
182
300
|
const block = parentFlow === 'block' && !isInlineLevel(display) && !fixedWidth
|
|
183
301
|
if (block && hasDefiniteWidth(graph, parent)) fill('HORIZONTAL')
|
|
302
|
+
// A grid item sits in its cell at its own size; only an explicit 100% fills it.
|
|
184
303
|
if (parentFlow === 'flex' && grows(style)) fill(mainAxis)
|
|
185
304
|
if (isFullSize(style, 'width')) fill('HORIZONTAL')
|
|
186
305
|
if (isFullSize(style, 'height')) fill('VERTICAL')
|
|
@@ -247,11 +366,13 @@ export function applyFlowSizing(
|
|
|
247
366
|
fixedWidth: parseCSSNumber(pickStyle(style, 'width')) !== null,
|
|
248
367
|
fixedHeight: parseCSSNumber(pickStyle(style, 'height')) !== null
|
|
249
368
|
}
|
|
250
|
-
if (node.layoutMode !== 'NONE'
|
|
369
|
+
if (node.layoutMode !== 'NONE') {
|
|
251
370
|
const own = (fixed: boolean) => (fixed ? 'FIXED' : 'HUG')
|
|
371
|
+
// A grid frame sizes itself like a row: its primary axis is the width its columns add up to.
|
|
372
|
+
const direction = node.layoutMode === 'GRID' ? 'HORIZONTAL' : node.layoutMode
|
|
252
373
|
Object.assign(
|
|
253
374
|
node,
|
|
254
|
-
autoLayoutSizingFields(
|
|
375
|
+
autoLayoutSizingFields(direction, own(size.fixedWidth), own(size.fixedHeight))
|
|
255
376
|
)
|
|
256
377
|
}
|
|
257
378
|
if (node.type === 'TEXT' && staysOnItsLines(style)) {
|