@pairdraw/dom-css 0.0.0-stage → 0.16.1
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/LICENSE +21 -0
- package/README.md +219 -2
- package/dist/browser.d.ts +29 -0
- package/dist/browser.js +2 -0
- package/dist/chunks/behaviours/args.js +59 -0
- package/dist/chunks/behaviours/args.js.map +1 -0
- package/dist/chunks/behaviours/controls.js +109 -0
- package/dist/chunks/behaviours/controls.js.map +1 -0
- package/dist/chunks/behaviours/reset.js +40 -0
- package/dist/chunks/behaviours/reset.js.map +1 -0
- package/dist/chunks/behaviours/roles.js +51 -0
- package/dist/chunks/behaviours/roles.js.map +1 -0
- package/dist/chunks/behaviours/states/conditions.js +103 -0
- package/dist/chunks/behaviours/states/conditions.js.map +1 -0
- package/dist/chunks/behaviours/states/css.js +172 -0
- package/dist/chunks/behaviours/states/css.js.map +1 -0
- package/dist/chunks/behaviours/states/layers.js +1736 -0
- package/dist/chunks/behaviours/states/layers.js.map +1 -0
- package/dist/chunks/behaviours/states/model.js +144 -0
- package/dist/chunks/behaviours/states/model.js.map +1 -0
- package/dist/chunks/behaviours/states/tailwind.js +198 -0
- package/dist/chunks/behaviours/states/tailwind.js.map +1 -0
- package/dist/chunks/browser.js +1352 -0
- package/dist/chunks/browser.js.map +1 -0
- package/dist/chunks/export/bundle.js +337 -0
- package/dist/chunks/export/bundle.js.map +1 -0
- package/dist/chunks/export/components/drawn.js +60 -0
- package/dist/chunks/export/components/drawn.js.map +1 -0
- package/dist/chunks/export/components/fields.js +178 -0
- package/dist/chunks/export/components/fields.js.map +1 -0
- package/dist/chunks/export/components/groups.js +297 -0
- package/dist/chunks/export/components/groups.js.map +1 -0
- package/dist/chunks/export/components/icons.js +260 -0
- package/dist/chunks/export/components/icons.js.map +1 -0
- package/dist/chunks/export/components/layers.js +1599 -0
- package/dist/chunks/export/components/layers.js.map +1 -0
- package/dist/chunks/export/index.js +477 -0
- package/dist/chunks/export/index.js.map +1 -0
- package/dist/chunks/export/storybook/component.js +448 -0
- package/dist/chunks/export/storybook/component.js.map +1 -0
- package/dist/chunks/export/storybook/export.js +410 -0
- package/dist/chunks/export/storybook/export.js.map +1 -0
- package/dist/chunks/import/html.js +406 -0
- package/dist/chunks/import/html.js.map +1 -0
- package/dist/chunks/import/jsx/dev-runtime.js +37 -0
- package/dist/chunks/import/jsx/dev-runtime.js.map +1 -0
- package/dist/chunks/tokens/cssom-validator.js +10 -0
- package/dist/chunks/tokens/cssom-validator.js.map +1 -0
- package/dist/export.d.ts +594 -0
- package/dist/export.js +13 -0
- package/dist/index.d.ts +115 -0
- package/dist/index.js +7 -0
- package/dist/jsx-dev-runtime.d.ts +8 -0
- package/dist/jsx-dev-runtime.js +3 -0
- package/dist/jsx-runtime.d.ts +20 -0
- package/dist/jsx-runtime.js +3 -0
- package/dist/rolldown-runtime.js +13 -0
- package/dist/runtime.d.ts +10 -0
- package/dist/scene-graph.d.ts +2 -0
- package/dist/scene-graph.js +2 -0
- package/dist/scene-graph2.d.ts +10 -0
- package/dist/styling.d.ts +93 -0
- package/dist/tailwind.d.ts +39 -0
- package/dist/types.d.ts +89 -0
- package/package.json +88 -4
- package/src/behaviours/args.ts +85 -0
- package/src/behaviours/controls.ts +195 -0
- package/src/behaviours/index.ts +11 -0
- package/src/behaviours/reset.ts +37 -0
- package/src/behaviours/roles.ts +44 -0
- package/src/behaviours/states/conditions.ts +105 -0
- package/src/behaviours/states/css.ts +123 -0
- package/src/behaviours/states/index.ts +4 -0
- package/src/behaviours/states/layers.ts +205 -0
- package/src/behaviours/states/model.ts +175 -0
- package/src/behaviours/states/names.ts +39 -0
- package/src/behaviours/states/tailwind.ts +148 -0
- package/src/behaviours/states/types.ts +56 -0
- package/src/browser.ts +146 -0
- package/src/cssom.d.ts +38 -0
- package/src/export/bundle.ts +461 -0
- package/src/export/components/drawn.ts +73 -0
- package/src/export/components/fields.ts +178 -0
- package/src/export/components/groups.ts +78 -0
- package/src/export/components/icons.ts +230 -0
- package/src/export/components/layers.ts +121 -0
- package/src/export/components/model.ts +544 -0
- package/src/export/components/properties.ts +167 -0
- package/src/export/components/react/fields.ts +129 -0
- package/src/export/components/react/index.ts +412 -0
- package/src/export/components/react/props.ts +151 -0
- package/src/export/components/react/radix.ts +52 -0
- package/src/export/components/react/shared.ts +76 -0
- package/src/export/components/references.ts +212 -0
- package/src/export/components/repeats.ts +128 -0
- package/src/export/components/shaders.ts +125 -0
- package/src/export/components/styling.ts +31 -0
- package/src/export/components/tree.ts +72 -0
- package/src/export/components/vue.ts +517 -0
- package/src/export/css.ts +57 -0
- package/src/export/grid.ts +42 -0
- package/src/export/html.ts +163 -0
- package/src/export/index.ts +44 -0
- package/src/export/projection.ts +581 -0
- package/src/export/storybook/component.ts +334 -0
- package/src/export/storybook/export.ts +430 -0
- package/src/export/storybook/groups.ts +161 -0
- package/src/export/storybook/module.ts +319 -0
- package/src/export/storybook/names.ts +51 -0
- package/src/export/tailwind-jsx.ts +156 -0
- package/src/export/text.ts +415 -0
- package/src/import/css-text.ts +4 -0
- package/src/import/css-values.ts +31 -0
- package/src/import/flow.ts +248 -0
- package/src/import/html.ts +88 -0
- package/src/import/jsx/core.ts +130 -0
- package/src/import/jsx/dev-runtime.ts +8 -0
- package/src/import/jsx/runtime.ts +76 -0
- package/src/import/scene-graph.ts +582 -0
- package/src/import/style-attribute.ts +25 -0
- package/src/import/tailwind.ts +54 -0
- package/src/import/text.ts +518 -0
- package/src/index.ts +51 -0
- package/src/runtime/browser/runtime.ts +301 -0
- package/src/runtime/headless/runtime.ts +99 -0
- package/src/runtime/headless/styles.ts +330 -0
- package/src/runtime/index.ts +11 -0
- package/src/tokens/conditions.ts +66 -0
- package/src/tokens/cssom-validator.ts +8 -0
- package/src/tokens/custom-properties.ts +331 -0
- package/src/tokens/expression.ts +128 -0
- package/src/tokens/formula.ts +140 -0
- package/src/tokens/index.ts +43 -0
- package/src/tokens/names.ts +161 -0
- package/src/tokens/references.ts +201 -0
- package/src/tokens/stylesheet.ts +304 -0
- package/src/tokens/validate.ts +86 -0
- package/src/tokens/values.ts +44 -0
- package/src/types.ts +59 -0
package/src/browser.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import type { SceneGraph } from '@pairdraw/scene-graph'
|
|
2
|
+
|
|
3
|
+
import { mergeCSSText } from './import/css-text'
|
|
4
|
+
import { jsxToDesignDocumentCore, type JSXChild } from './import/jsx/core'
|
|
5
|
+
import { designDocumentToSceneGraph, type ToSceneGraphOptions } from './import/scene-graph'
|
|
6
|
+
import type { CompileTailwindCSSOptions } from './import/tailwind'
|
|
7
|
+
import { createBrowserCSSRuntime, type BrowserCSSRuntimeOptions } from './runtime/browser/runtime'
|
|
8
|
+
import type { CSSComputeOptions, DesignDocument } from './types'
|
|
9
|
+
|
|
10
|
+
export { Fragment, jsx, jsxs } from './import/jsx/core'
|
|
11
|
+
export type { JSXChild, JSXElementProps, JSXStyleInput, JSXTag } from './import/jsx/core'
|
|
12
|
+
|
|
13
|
+
export interface BrowserToDesignDocumentOptions extends BrowserCSSRuntimeOptions {
|
|
14
|
+
cssText?: string
|
|
15
|
+
compute?: CSSComputeOptions
|
|
16
|
+
signal?: AbortSignal
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type BrowserHTMLToDesignDocumentOptions = BrowserToDesignDocumentOptions
|
|
20
|
+
|
|
21
|
+
export interface BrowserHTMLToSceneGraphOptions
|
|
22
|
+
extends BrowserToDesignDocumentOptions, ToSceneGraphOptions {}
|
|
23
|
+
|
|
24
|
+
export interface BrowserTailwindHTMLToDesignDocumentOptions
|
|
25
|
+
extends Omit<BrowserHTMLToDesignDocumentOptions, 'cssText'>, CompileTailwindCSSOptions {}
|
|
26
|
+
|
|
27
|
+
export interface BrowserTailwindHTMLToSceneGraphOptions
|
|
28
|
+
extends BrowserTailwindHTMLToDesignDocumentOptions, ToSceneGraphOptions {}
|
|
29
|
+
|
|
30
|
+
export interface BrowserToSceneGraphOptions
|
|
31
|
+
extends BrowserToDesignDocumentOptions, ToSceneGraphOptions {}
|
|
32
|
+
|
|
33
|
+
export interface BrowserTailwindToDesignDocumentOptions
|
|
34
|
+
extends Omit<BrowserToDesignDocumentOptions, 'cssText'>, CompileTailwindCSSOptions {}
|
|
35
|
+
|
|
36
|
+
export interface BrowserTailwindToSceneGraphOptions
|
|
37
|
+
extends BrowserTailwindToDesignDocumentOptions, ToSceneGraphOptions {}
|
|
38
|
+
|
|
39
|
+
function createRuntime(options: BrowserCSSRuntimeOptions) {
|
|
40
|
+
return createBrowserCSSRuntime({ sandbox: 'iframe', ...options })
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function compileBrowserTailwindCSS(
|
|
44
|
+
candidates: string | Iterable<string>,
|
|
45
|
+
options: CompileTailwindCSSOptions
|
|
46
|
+
): Promise<string> {
|
|
47
|
+
const { compileTailwindCSS } = await import('./import/tailwind')
|
|
48
|
+
return compileTailwindCSS(candidates, options)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function resolveBrowserDocument(documentOverride: Document | undefined): Document {
|
|
52
|
+
if (documentOverride) return documentOverride
|
|
53
|
+
if (typeof document === 'undefined') {
|
|
54
|
+
throw new TypeError('Browser DOM/CSS helpers require a DOM document')
|
|
55
|
+
}
|
|
56
|
+
return document
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function extractEmbeddedCSSText(html: string, browserDocument: Document): string | undefined {
|
|
60
|
+
const Parser = browserDocument.defaultView?.DOMParser
|
|
61
|
+
if (!Parser) throw new TypeError('Browser DOM/CSS helpers require DOMParser')
|
|
62
|
+
const parsed = new Parser().parseFromString(html, 'text/html')
|
|
63
|
+
const styles = Array.from(parsed.querySelectorAll('style'))
|
|
64
|
+
.map((style) => (style.textContent ? style.textContent.trim() : ''))
|
|
65
|
+
.filter((css): css is string => !!css)
|
|
66
|
+
return styles.length > 0 ? styles.join('\n') : undefined
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function browserHTMLToDesignDocument(
|
|
70
|
+
html: string,
|
|
71
|
+
options: BrowserHTMLToDesignDocumentOptions = {}
|
|
72
|
+
): Promise<DesignDocument> {
|
|
73
|
+
options.signal?.throwIfAborted()
|
|
74
|
+
const browserDocument = resolveBrowserDocument(options.document)
|
|
75
|
+
const runtime = createRuntime({ ...options, document: browserDocument })
|
|
76
|
+
const document = runtime.parseHTML(html)
|
|
77
|
+
const cssText = mergeCSSText(extractEmbeddedCSSText(html, browserDocument), options.cssText)
|
|
78
|
+
return runtime.computeStyles(document, cssText, options.compute)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function browserHTMLToSceneGraph(
|
|
82
|
+
html: string,
|
|
83
|
+
options: BrowserHTMLToSceneGraphOptions = {}
|
|
84
|
+
): Promise<SceneGraph> {
|
|
85
|
+
const document = await browserHTMLToDesignDocument(html, options)
|
|
86
|
+
options.signal?.throwIfAborted()
|
|
87
|
+
const graph = designDocumentToSceneGraph(document, options)
|
|
88
|
+
options.signal?.throwIfAborted()
|
|
89
|
+
return graph
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function browserTailwindHTMLToDesignDocument(
|
|
93
|
+
html: string,
|
|
94
|
+
candidates: string | Iterable<string>,
|
|
95
|
+
options: BrowserTailwindHTMLToDesignDocumentOptions = {}
|
|
96
|
+
): Promise<DesignDocument> {
|
|
97
|
+
const cssText = await compileBrowserTailwindCSS(candidates, options)
|
|
98
|
+
return browserHTMLToDesignDocument(html, { ...options, cssText })
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function browserTailwindHTMLToSceneGraph(
|
|
102
|
+
html: string,
|
|
103
|
+
candidates: string | Iterable<string>,
|
|
104
|
+
options: BrowserTailwindHTMLToSceneGraphOptions = {}
|
|
105
|
+
): Promise<SceneGraph> {
|
|
106
|
+
const document = await browserTailwindHTMLToDesignDocument(html, candidates, options)
|
|
107
|
+
options.signal?.throwIfAborted()
|
|
108
|
+
const graph = designDocumentToSceneGraph(document, options)
|
|
109
|
+
options.signal?.throwIfAborted()
|
|
110
|
+
return graph
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function browserJSXToDesignDocument(
|
|
114
|
+
input: JSXChild,
|
|
115
|
+
options: BrowserToDesignDocumentOptions = {}
|
|
116
|
+
): Promise<DesignDocument> {
|
|
117
|
+
const document = jsxToDesignDocumentCore(input)
|
|
118
|
+
const runtime = createRuntime(options)
|
|
119
|
+
return runtime.computeStyles(document, options.cssText, options.compute)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function browserJSXToSceneGraph(
|
|
123
|
+
input: JSXChild,
|
|
124
|
+
options: BrowserToSceneGraphOptions = {}
|
|
125
|
+
): Promise<SceneGraph> {
|
|
126
|
+
const document = await browserJSXToDesignDocument(input, options)
|
|
127
|
+
return designDocumentToSceneGraph(document, options)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export async function browserTailwindJSXToDesignDocument(
|
|
131
|
+
input: JSXChild,
|
|
132
|
+
candidates: string | Iterable<string>,
|
|
133
|
+
options: BrowserTailwindToDesignDocumentOptions = {}
|
|
134
|
+
): Promise<DesignDocument> {
|
|
135
|
+
const cssText = await compileBrowserTailwindCSS(candidates, options)
|
|
136
|
+
return browserJSXToDesignDocument(input, { ...options, cssText })
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export async function browserTailwindJSXToSceneGraph(
|
|
140
|
+
input: JSXChild,
|
|
141
|
+
candidates: string | Iterable<string>,
|
|
142
|
+
options: BrowserTailwindToSceneGraphOptions = {}
|
|
143
|
+
): Promise<SceneGraph> {
|
|
144
|
+
const document = await browserTailwindJSXToDesignDocument(input, candidates, options)
|
|
145
|
+
return designDocumentToSceneGraph(document, options)
|
|
146
|
+
}
|
package/src/cssom.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
declare module '@acemir/cssom' {
|
|
2
|
+
export interface CSSStyleDeclarationLike {
|
|
3
|
+
readonly length: number
|
|
4
|
+
readonly [index: number]: string
|
|
5
|
+
getPropertyValue(property: string): string
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface CSSStyleRuleLike {
|
|
9
|
+
selectorText: string
|
|
10
|
+
style: CSSStyleDeclarationLike
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class CSSFontFaceRule {
|
|
14
|
+
readonly cssText: string
|
|
15
|
+
readonly style: {
|
|
16
|
+
setProperty(property: string, value: string, priority?: string): void
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class CSSStyleSheet {
|
|
21
|
+
readonly cssRules: ArrayLike<{
|
|
22
|
+
readonly style: { setProperty(property: string, value: string): void }
|
|
23
|
+
}>
|
|
24
|
+
/** Parses `rule`, throwing on an invalid selector, and returns its index. */
|
|
25
|
+
insertRule(rule: string, index?: number): number
|
|
26
|
+
toString(): string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface CSSGroupingRuleLike {
|
|
30
|
+
cssRules: unknown[]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface CSSStyleSheetLike {
|
|
34
|
+
cssRules: unknown[]
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function parse(cssText: string): CSSStyleSheetLike
|
|
38
|
+
}
|
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
import type { CSSFontFaceRule } from '@acemir/cssom'
|
|
2
|
+
import { isValid, toUint8Array } from 'js-base64'
|
|
3
|
+
import { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5'
|
|
4
|
+
|
|
5
|
+
import { normalizeFontFamily } from '@pairdraw/scene-graph/font-style'
|
|
6
|
+
|
|
7
|
+
import { tokenStylesheet, type TokenStylesheetFormat } from '../tokens/stylesheet'
|
|
8
|
+
import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
|
|
9
|
+
import { mergeClassNames, serializeHTML, splitWhitespace } from './html'
|
|
10
|
+
|
|
11
|
+
/** A font face the exported text uses. */
|
|
12
|
+
export interface WebFontFaceRequest {
|
|
13
|
+
family: string
|
|
14
|
+
weight: number
|
|
15
|
+
style?: 'normal' | 'italic'
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A font file to ship next to the page, described as an `@font-face` rule. */
|
|
19
|
+
export interface WebFontFaceAsset {
|
|
20
|
+
family: string
|
|
21
|
+
weight: string | number | [number, number]
|
|
22
|
+
style: string
|
|
23
|
+
display?: string
|
|
24
|
+
stretch?: string
|
|
25
|
+
unicodeRange?: string[]
|
|
26
|
+
format: 'woff2' | 'woff' | 'opentype' | 'truetype'
|
|
27
|
+
path: string
|
|
28
|
+
content: Uint8Array
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Finds font files for the requested faces; paths start with `assetBasePath`. */
|
|
32
|
+
export type WebFontFaceResolver = (
|
|
33
|
+
fonts: WebFontFaceRequest[],
|
|
34
|
+
assetBasePath: string
|
|
35
|
+
) => Promise<WebFontFaceAsset[]>
|
|
36
|
+
|
|
37
|
+
export interface ExportHTMLBundleOptions {
|
|
38
|
+
html?: 'fragment' | 'standalone'
|
|
39
|
+
style?: 'inline' | 'tailwind'
|
|
40
|
+
assets?: 'inline' | 'external'
|
|
41
|
+
/** Resolves font files to include with external assets; `none` includes no fonts. */
|
|
42
|
+
fonts?: 'none' | WebFontFaceResolver
|
|
43
|
+
assetBasePath?: string
|
|
44
|
+
/**
|
|
45
|
+
* Reads one of Tailwind's stylesheets, `tailwindcss/theme.css` or `tailwindcss/utilities.css`,
|
|
46
|
+
* for a standalone Tailwind page. Browsers pass one; Node and Bun read the installed package.
|
|
47
|
+
*/
|
|
48
|
+
loadTailwindStylesheet?: TailwindStylesheetLoader
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type TailwindStylesheetLoader = (id: TailwindStylesheetId) => Promise<string>
|
|
52
|
+
export type TailwindStylesheetId = 'tailwindcss/theme.css' | 'tailwindcss/utilities.css'
|
|
53
|
+
|
|
54
|
+
export interface ExportHTMLFile {
|
|
55
|
+
path: string
|
|
56
|
+
content: string | Uint8Array
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ExportHTMLBundle {
|
|
60
|
+
entrypoint: string
|
|
61
|
+
files: ExportHTMLFile[]
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface StandaloneBounds {
|
|
65
|
+
minX: number
|
|
66
|
+
minY: number
|
|
67
|
+
width: number
|
|
68
|
+
height: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
type ParseNode = DefaultTreeAdapterTypes.Node
|
|
72
|
+
type ParseParent = DefaultTreeAdapterTypes.ParentNode
|
|
73
|
+
type ParseElement = DefaultTreeAdapterTypes.Element
|
|
74
|
+
|
|
75
|
+
const RESET_CSS =
|
|
76
|
+
'*,*::before,*::after{box-sizing:border-box}html,body{margin:0;padding:0}body{font-family:system-ui,sans-serif;background:#fff}'
|
|
77
|
+
|
|
78
|
+
function styleToCSS(style: DesignStyleDeclaration): string {
|
|
79
|
+
return Object.entries(style)
|
|
80
|
+
.filter(([, value]) => value !== '')
|
|
81
|
+
.map(([property, value]) => `${property}: ${value}`)
|
|
82
|
+
.join('; ')
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function cloneNode(node: DesignNode): DesignNode {
|
|
86
|
+
if (node.type === 'text') return { ...node }
|
|
87
|
+
return {
|
|
88
|
+
...node,
|
|
89
|
+
attrs: { ...node.attrs },
|
|
90
|
+
inlineStyle: node.inlineStyle ? { ...node.inlineStyle } : undefined,
|
|
91
|
+
children: node.children.map(cloneNode)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function standaloneStyleForNode(
|
|
96
|
+
node: DesignElement,
|
|
97
|
+
parent: DesignElement | undefined,
|
|
98
|
+
origin: StandaloneBounds
|
|
99
|
+
): DesignStyleDeclaration {
|
|
100
|
+
const style = { ...node.inlineStyle }
|
|
101
|
+
const source = node.sourceSceneNode
|
|
102
|
+
if (!source) return style
|
|
103
|
+
|
|
104
|
+
style.position = 'absolute'
|
|
105
|
+
style.left = `${source.x - (parent ? 0 : origin.minX)}px`
|
|
106
|
+
style.top = `${source.y - (parent ? 0 : origin.minY)}px`
|
|
107
|
+
return style
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function standaloneNode(
|
|
111
|
+
node: DesignNode,
|
|
112
|
+
origin: StandaloneBounds,
|
|
113
|
+
parent?: DesignElement
|
|
114
|
+
): DesignNode {
|
|
115
|
+
if (node.type === 'text') return cloneNode(node)
|
|
116
|
+
const standalone: DesignElement = {
|
|
117
|
+
...node,
|
|
118
|
+
attrs: { ...node.attrs },
|
|
119
|
+
inlineStyle: standaloneStyleForNode(node, parent, origin),
|
|
120
|
+
children: []
|
|
121
|
+
}
|
|
122
|
+
standalone.children = node.children.map((child) => standaloneNode(child, origin, node))
|
|
123
|
+
return standalone
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function nodeBounds(node: DesignNode): StandaloneBounds | undefined {
|
|
127
|
+
if (node.type === 'text' || !node.sourceSceneNode) return undefined
|
|
128
|
+
return {
|
|
129
|
+
minX: node.sourceSceneNode.x,
|
|
130
|
+
minY: node.sourceSceneNode.y,
|
|
131
|
+
width: node.sourceSceneNode.width,
|
|
132
|
+
height: node.sourceSceneNode.height
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function standaloneSize(document: DesignDocument): StandaloneBounds {
|
|
137
|
+
const bounds = document.children
|
|
138
|
+
.map(nodeBounds)
|
|
139
|
+
.filter((value): value is NonNullable<typeof value> => value !== undefined)
|
|
140
|
+
const minX = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minX)) : 0
|
|
141
|
+
const minY = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minY)) : 0
|
|
142
|
+
const maxX = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minX + bound.width)) : 1
|
|
143
|
+
const maxY = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minY + bound.height)) : 1
|
|
144
|
+
return { minX, minY, width: Math.max(1, maxX - minX), height: Math.max(1, maxY - minY) }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function standaloneDocument(document: DesignDocument, size: StandaloneBounds): DesignDocument {
|
|
148
|
+
return {
|
|
149
|
+
...document,
|
|
150
|
+
children: document.children.map((node) => standaloneNode(node, size))
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function cssClassName(index: number): string {
|
|
155
|
+
return `op-${index.toString(36)}`
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function extractInlineStyles(
|
|
159
|
+
node: DesignNode,
|
|
160
|
+
rules: string[],
|
|
161
|
+
nextIndex: { value: number }
|
|
162
|
+
): DesignNode {
|
|
163
|
+
if (node.type === 'text') return node
|
|
164
|
+
const children = node.children.map((child) => extractInlineStyles(child, rules, nextIndex))
|
|
165
|
+
if (!node.inlineStyle || Object.keys(node.inlineStyle).length === 0) return { ...node, children }
|
|
166
|
+
|
|
167
|
+
const className = cssClassName(nextIndex.value)
|
|
168
|
+
nextIndex.value += 1
|
|
169
|
+
rules.push(`.${className}{${styleToCSS(node.inlineStyle)}}`)
|
|
170
|
+
return {
|
|
171
|
+
...node,
|
|
172
|
+
attrs: { ...node.attrs, class: mergeClassNames(node.attrs.class, className) ?? className },
|
|
173
|
+
inlineStyle: undefined,
|
|
174
|
+
children
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function isElement(node: ParseNode): node is ParseElement {
|
|
179
|
+
return 'attrs' in node && 'tagName' in node
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function walkParseTree(node: ParseNode | ParseParent, visit: (node: ParseElement) => void): void {
|
|
183
|
+
if (isElement(node)) visit(node)
|
|
184
|
+
if ('childNodes' in node) {
|
|
185
|
+
for (const child of node.childNodes) walkParseTree(child, visit)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function classNamesFromHTML(html: string): string[] {
|
|
190
|
+
const fragment = parseFragment(html)
|
|
191
|
+
const classes = new Set<string>()
|
|
192
|
+
walkParseTree(fragment, (element) => {
|
|
193
|
+
const classAttr = element.attrs.find((attr) => attr.name === 'class')
|
|
194
|
+
if (!classAttr) return
|
|
195
|
+
for (const className of splitWhitespace(classAttr.value)) classes.add(className)
|
|
196
|
+
})
|
|
197
|
+
return [...classes]
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* The stylesheet for the tokens the document references, in the format the page needs: plain
|
|
202
|
+
* custom properties for inline styles, `@theme` for Tailwind, so token utilities compile.
|
|
203
|
+
*/
|
|
204
|
+
async function tokenCSS(document: DesignDocument, format: TokenStylesheetFormat): Promise<string> {
|
|
205
|
+
const { tokens, sourceGraph } = document
|
|
206
|
+
if (!tokens || !sourceGraph || tokens.used.size === 0) return ''
|
|
207
|
+
const variables = tokens.stylesheetVariables()
|
|
208
|
+
const { css } = await tokenStylesheet(sourceGraph, {
|
|
209
|
+
format,
|
|
210
|
+
include: (variable) => variables.has(variable.id)
|
|
211
|
+
})
|
|
212
|
+
return css
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function readInstalledTailwindStylesheet(id: TailwindStylesheetId): Promise<string> {
|
|
216
|
+
const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')
|
|
217
|
+
return readFile(new URL(import.meta.resolve(id)), 'utf8')
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function compileTailwindClasses(
|
|
221
|
+
classNames: string[],
|
|
222
|
+
tokens: string,
|
|
223
|
+
load: TailwindStylesheetLoader = readInstalledTailwindStylesheet
|
|
224
|
+
): Promise<string> {
|
|
225
|
+
if (classNames.length === 0) return ''
|
|
226
|
+
const [{ compile }, themeCSS, utilitiesCSS] = await Promise.all([
|
|
227
|
+
import('tailwindcss'),
|
|
228
|
+
load('tailwindcss/theme.css'),
|
|
229
|
+
load('tailwindcss/utilities.css')
|
|
230
|
+
])
|
|
231
|
+
const compiler = await compile(`${themeCSS}\n${tokens}\n${utilitiesCSS}`)
|
|
232
|
+
return compiler.build(classNames)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function collectFontRequests(node: DesignNode, fonts: Map<string, WebFontFaceRequest>): void {
|
|
236
|
+
if (node.type === 'text') return
|
|
237
|
+
const source = node.sourceSceneNode
|
|
238
|
+
if (source?.type === 'TEXT') {
|
|
239
|
+
const family = normalizeFontFamily(source.fontFamily)
|
|
240
|
+
const style = source.italic ? 'italic' : 'normal'
|
|
241
|
+
const key = `${family}|${source.fontWeight}|${style}`
|
|
242
|
+
fonts.set(key, { family, weight: source.fontWeight, style })
|
|
243
|
+
}
|
|
244
|
+
for (const child of node.children) collectFontRequests(child, fonts)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function serializeFontWeight(weight: string | number | [number, number]): string {
|
|
248
|
+
return Array.isArray(weight) ? weight.join(' ') : String(weight)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* A relative file path as a URL that points at it: each folder and file name percent-encoded,
|
|
253
|
+
* so a page named `Card #1` finds `Card #1.assets/` rather than reading `#1` as a fragment.
|
|
254
|
+
*/
|
|
255
|
+
function assetURL(path: string): string {
|
|
256
|
+
return path.split('/').map(encodeURIComponent).join('/')
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function fontSourceValue(asset: WebFontFaceAsset, from: string): string {
|
|
260
|
+
// Relative to the stylesheet's folder, which the asset's path may start with.
|
|
261
|
+
const path =
|
|
262
|
+
from && asset.path.startsWith(`${from}/`) ? asset.path.slice(from.length + 1) : asset.path
|
|
263
|
+
return [
|
|
264
|
+
'url(',
|
|
265
|
+
JSON.stringify(assetURL(path)),
|
|
266
|
+
') format(',
|
|
267
|
+
JSON.stringify(asset.format),
|
|
268
|
+
')'
|
|
269
|
+
].join('')
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
interface FontFaceCSSOptions {
|
|
273
|
+
/** The folder the stylesheet is in, which font paths are written relative to. */
|
|
274
|
+
from: string
|
|
275
|
+
/** `font-display` for every face, rather than each face's own. */
|
|
276
|
+
display?: string
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function fontFaceCSS(
|
|
280
|
+
FontFaceRule: typeof CSSFontFaceRule,
|
|
281
|
+
asset: WebFontFaceAsset,
|
|
282
|
+
options: FontFaceCSSOptions
|
|
283
|
+
): string {
|
|
284
|
+
const rule = new FontFaceRule()
|
|
285
|
+
rule.style.setProperty('font-family', JSON.stringify(asset.family))
|
|
286
|
+
rule.style.setProperty('src', fontSourceValue(asset, options.from))
|
|
287
|
+
rule.style.setProperty('font-weight', serializeFontWeight(asset.weight))
|
|
288
|
+
rule.style.setProperty('font-style', asset.style)
|
|
289
|
+
rule.style.setProperty('font-display', options.display ?? asset.display ?? 'swap')
|
|
290
|
+
if (asset.stretch) rule.style.setProperty('font-stretch', asset.stretch)
|
|
291
|
+
if (asset.unicodeRange && asset.unicodeRange.length > 0) {
|
|
292
|
+
rule.style.setProperty('unicode-range', asset.unicodeRange.join(','))
|
|
293
|
+
}
|
|
294
|
+
return rule.cssText
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Every font face a document's text uses, once each. */
|
|
298
|
+
export function designFontRequests(document: DesignDocument): WebFontFaceRequest[] {
|
|
299
|
+
const requests = new Map<string, WebFontFaceRequest>()
|
|
300
|
+
for (const child of document.children) collectFontRequests(child, requests)
|
|
301
|
+
return [...requests.values()]
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** `@font-face` rules for font files, as a stylesheet in the folder `options.from`. */
|
|
305
|
+
export async function fontFaceStylesheet(
|
|
306
|
+
assets: readonly WebFontFaceAsset[],
|
|
307
|
+
options: FontFaceCSSOptions
|
|
308
|
+
): Promise<string> {
|
|
309
|
+
if (assets.length === 0) return ''
|
|
310
|
+
// Loaded only when fonts ship as files; the CSS object model is not bundled for browsers.
|
|
311
|
+
const cssom = await import('@acemir/cssom')
|
|
312
|
+
return assets.map((asset) => fontFaceCSS(cssom.CSSFontFaceRule, asset, options)).join('')
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async function fontFaceAssets(
|
|
316
|
+
document: DesignDocument,
|
|
317
|
+
options: ResolvedBundleOptions
|
|
318
|
+
): Promise<{ css: string; files: ExportHTMLFile[] }> {
|
|
319
|
+
if (options.fonts === 'none' || options.assets !== 'external') return { css: '', files: [] }
|
|
320
|
+
const assets = await options.fonts(designFontRequests(document), `${options.assetBasePath}/fonts`)
|
|
321
|
+
// The page's stylesheet sits in the asset folder, beside the fonts' own folder.
|
|
322
|
+
return {
|
|
323
|
+
css: await fontFaceStylesheet(assets, { from: options.assetBasePath }),
|
|
324
|
+
files: assets
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function dataImageParts(value: string): { mime: string; base64: string } | undefined {
|
|
329
|
+
if (!value.startsWith('data:image/')) return undefined
|
|
330
|
+
const marker = ';base64,'
|
|
331
|
+
const markerIndex = value.indexOf(marker)
|
|
332
|
+
if (markerIndex === -1) return undefined
|
|
333
|
+
const base64 = value.slice(markerIndex + marker.length)
|
|
334
|
+
// Documents can come from parsed HTML; an invalid payload stays inline rather than decoding to other bytes.
|
|
335
|
+
if (!isValid(base64)) return undefined
|
|
336
|
+
return { mime: value.slice('data:'.length, markerIndex), base64 }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function extensionForMime(mime: string): string {
|
|
340
|
+
if (mime === 'image/jpeg') return 'jpg'
|
|
341
|
+
if (mime === 'image/webp') return 'webp'
|
|
342
|
+
if (mime === 'image/gif') return 'gif'
|
|
343
|
+
if (mime === 'image/svg+xml') return 'svg'
|
|
344
|
+
return 'png'
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Inline images moved into files under `assetBasePath`, the HTML pointing at them. */
|
|
348
|
+
export function extractImageAssets(
|
|
349
|
+
html: string,
|
|
350
|
+
assetBasePath: string
|
|
351
|
+
): { html: string; files: ExportHTMLFile[] } {
|
|
352
|
+
const fragment = parseFragment(html)
|
|
353
|
+
const files: ExportHTMLFile[] = []
|
|
354
|
+
const sources = new Map<string, string>()
|
|
355
|
+
walkParseTree(fragment, (element) => {
|
|
356
|
+
const src = element.attrs.find((attr) => attr.name === 'src')
|
|
357
|
+
if (!src) return
|
|
358
|
+
const parts = dataImageParts(src.value)
|
|
359
|
+
if (!parts) return
|
|
360
|
+
const cachedPath = sources.get(src.value)
|
|
361
|
+
if (cachedPath) {
|
|
362
|
+
src.value = assetURL(cachedPath)
|
|
363
|
+
return
|
|
364
|
+
}
|
|
365
|
+
const path = `${assetBasePath}/images/image-${sources.size + 1}.${extensionForMime(parts.mime)}`
|
|
366
|
+
sources.set(src.value, path)
|
|
367
|
+
files.push({ path, content: toUint8Array(parts.base64) })
|
|
368
|
+
src.value = assetURL(path)
|
|
369
|
+
})
|
|
370
|
+
return { html: serialize(fragment), files }
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function stylesheetLink(path: string): string {
|
|
374
|
+
return `<link rel="stylesheet" href="${assetURL(path)}">`
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function styleTag(css: string): string {
|
|
378
|
+
return css ? `<style>${css}</style>` : ''
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
type ResolvedBundleOptions = Required<Omit<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>> &
|
|
382
|
+
Pick<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>
|
|
383
|
+
|
|
384
|
+
async function exportStandaloneHTML(
|
|
385
|
+
document: DesignDocument,
|
|
386
|
+
options: ResolvedBundleOptions
|
|
387
|
+
): Promise<ExportHTMLBundle> {
|
|
388
|
+
const size = standaloneSize(document)
|
|
389
|
+
const doc = standaloneDocument(document, size)
|
|
390
|
+
const stageCSS = `.pairdraw-stage{position:relative;width:${size.width}px;height:${size.height}px;overflow:hidden;background:transparent}`
|
|
391
|
+
let body: string
|
|
392
|
+
let css = `${RESET_CSS}${stageCSS}`
|
|
393
|
+
|
|
394
|
+
if (options.style === 'tailwind') {
|
|
395
|
+
body = serializeHTML(doc, { style: 'tailwind' })
|
|
396
|
+
css += await compileTailwindClasses(
|
|
397
|
+
classNamesFromHTML(body),
|
|
398
|
+
await tokenCSS(document, 'tailwind'),
|
|
399
|
+
options.loadTailwindStylesheet
|
|
400
|
+
)
|
|
401
|
+
} else {
|
|
402
|
+
css += await tokenCSS(document, 'css')
|
|
403
|
+
const rules: string[] = []
|
|
404
|
+
const index = { value: 0 }
|
|
405
|
+
const styledDocument: DesignDocument = {
|
|
406
|
+
...doc,
|
|
407
|
+
children: doc.children.map((node) => extractInlineStyles(node, rules, index))
|
|
408
|
+
}
|
|
409
|
+
body = serializeHTML(styledDocument)
|
|
410
|
+
css += rules.join('')
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
if (options.assets === 'external') {
|
|
414
|
+
const [extracted, fonts] = await Promise.all([
|
|
415
|
+
Promise.resolve(extractImageAssets(body, options.assetBasePath)),
|
|
416
|
+
fontFaceAssets(document, options)
|
|
417
|
+
])
|
|
418
|
+
body = extracted.html
|
|
419
|
+
const cssPath = `${options.assetBasePath}/pairdraw.css`
|
|
420
|
+
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${stylesheetLink(cssPath)}</head><body><main data-pairdraw-html="standalone" class="pairdraw-stage">${body}</main></body></html>`
|
|
421
|
+
return {
|
|
422
|
+
entrypoint: 'index.html',
|
|
423
|
+
files: [
|
|
424
|
+
{ path: 'index.html', content: html },
|
|
425
|
+
{ path: cssPath, content: `${fonts.css}${css}` },
|
|
426
|
+
...fonts.files,
|
|
427
|
+
...extracted.files
|
|
428
|
+
]
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${styleTag(css)}</head><body><main data-pairdraw-html="standalone" class="pairdraw-stage">${body}</main></body></html>`
|
|
433
|
+
return { entrypoint: 'index.html', files: [{ path: 'index.html', content: html }] }
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
export async function exportHTMLBundle(
|
|
437
|
+
document: DesignDocument,
|
|
438
|
+
options: ExportHTMLBundleOptions = {}
|
|
439
|
+
): Promise<ExportHTMLBundle> {
|
|
440
|
+
const resolvedOptions: ResolvedBundleOptions = {
|
|
441
|
+
html: options.html ?? 'fragment',
|
|
442
|
+
style: options.style ?? 'inline',
|
|
443
|
+
assets: options.assets ?? 'inline',
|
|
444
|
+
fonts: options.fonts ?? 'none',
|
|
445
|
+
assetBasePath: options.assetBasePath ?? 'assets',
|
|
446
|
+
loadTailwindStylesheet: options.loadTailwindStylesheet
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
if (resolvedOptions.html === 'standalone') return exportStandaloneHTML(document, resolvedOptions)
|
|
450
|
+
|
|
451
|
+
const fragment = serializeHTML(document, { style: resolvedOptions.style })
|
|
452
|
+
if (resolvedOptions.assets !== 'external') {
|
|
453
|
+
return { entrypoint: 'index.html', files: [{ path: 'index.html', content: fragment }] }
|
|
454
|
+
}
|
|
455
|
+
// A fragment has no stylesheet to declare fonts in, so only its images become files.
|
|
456
|
+
const extracted = extractImageAssets(fragment, resolvedOptions.assetBasePath)
|
|
457
|
+
return {
|
|
458
|
+
entrypoint: 'index.html',
|
|
459
|
+
files: [{ path: 'index.html', content: extracted.html }, ...extracted.files]
|
|
460
|
+
}
|
|
461
|
+
}
|