@pairdraw/dom-css 0.19.1 → 0.20.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/browser.d.ts +16 -1
- package/dist/browser.js +2 -2
- package/dist/chunks/behaviours/controls.js +34 -2
- package/dist/chunks/behaviours/controls.js.map +1 -1
- package/dist/chunks/behaviours/states/layers.js +110 -5
- package/dist/chunks/behaviours/states/layers.js.map +1 -1
- package/dist/chunks/behaviours/states/tailwind.js +17 -2
- package/dist/chunks/behaviours/states/tailwind.js.map +1 -1
- package/dist/chunks/browser.js +208 -53
- package/dist/chunks/browser.js.map +1 -1
- package/dist/chunks/export/components/groups.js +3 -2
- package/dist/chunks/export/components/groups.js.map +1 -1
- package/dist/chunks/export/components/layers.js +50 -8
- package/dist/chunks/export/components/layers.js.map +1 -1
- package/dist/export.d.ts +9 -0
- package/dist/scene-graph2.d.ts +6 -0
- package/package.json +3 -3
- package/src/behaviours/controls.ts +49 -2
- package/src/behaviours/states/tailwind.ts +4 -1
- package/src/browser.ts +1 -0
- package/src/export/components/model.ts +60 -7
- package/src/export/components/react/index.ts +4 -0
- package/src/export/components/repeats.ts +7 -2
- package/src/export/components/vue.ts +38 -9
- package/src/export/css.ts +3 -2
- package/src/export/font-size-class.ts +13 -0
- package/src/export/html.ts +5 -1
- package/src/export/projection.ts +121 -10
- package/src/import/flow.ts +15 -0
- package/src/import/fonts.ts +40 -0
- package/src/import/scene-graph.ts +199 -55
|
@@ -2,6 +2,21 @@ import { cssName, propAttribute } from "./css.js";
|
|
|
2
2
|
import { compact } from "es-toolkit/array";
|
|
3
3
|
import { twirl } from "twirlwind";
|
|
4
4
|
import { escapeAttribute, escapeText } from "entities";
|
|
5
|
+
//#region src/export/font-size-class.ts
|
|
6
|
+
/**
|
|
7
|
+
* twirlwind names a literal font size that is a multiple of four `text-<px / 4>` (40px becomes
|
|
8
|
+
* text-10), a class Tailwind never generates. Rewrite that one token to the arbitrary value,
|
|
9
|
+
* the spelling Tailwind compiles, leaving named steps and token-bound sizes alone.
|
|
10
|
+
*
|
|
11
|
+
* `css` is the declaration string the class list was generated from.
|
|
12
|
+
*/
|
|
13
|
+
function validFontSizeClass(className, css) {
|
|
14
|
+
const fontSize = /(?:^|;)\s*font-size:\s*(\d+(?:\.\d+)?)px/.exec(css)?.[1];
|
|
15
|
+
const numeric = className.match(/(?:^|\s)text-(\d+)(?=\s|$)/);
|
|
16
|
+
if (!fontSize || !numeric || Number(numeric[1]) * 4 !== Number(fontSize)) return className;
|
|
17
|
+
return className.replace(numeric[0], numeric[0].replace(/text-\d+/, `text-[${fontSize}px]`));
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
5
20
|
//#region src/export/html.ts
|
|
6
21
|
const VOID_ELEMENTS = /* @__PURE__ */ new Set([
|
|
7
22
|
"area",
|
|
@@ -39,7 +54,7 @@ function serializeStyle(node) {
|
|
|
39
54
|
function serializeTailwindClasses(node, themeVariables = []) {
|
|
40
55
|
const style = serializeStyle(node);
|
|
41
56
|
if (!style) return void 0;
|
|
42
|
-
const className = twirl(style, { theme: { variables: themeVariables } });
|
|
57
|
+
const className = validFontSizeClass(twirl(style, { theme: { variables: themeVariables } }), style);
|
|
43
58
|
return className.length > 0 ? className : void 0;
|
|
44
59
|
}
|
|
45
60
|
function mergeClassNames(...values) {
|
|
@@ -132,7 +147,7 @@ function variant(condition, group) {
|
|
|
132
147
|
}
|
|
133
148
|
function utilities(style, options) {
|
|
134
149
|
const css = Object.entries(style).map(([property, value]) => `${property}: ${value}`).join("; ");
|
|
135
|
-
return css ? splitWhitespace(twirl(css, { theme: { variables: options.themeVariables ?? [] } })) : [];
|
|
150
|
+
return css ? splitWhitespace(validFontSizeClass(twirl(css, { theme: { variables: options.themeVariables ?? [] } }), css)) : [];
|
|
136
151
|
}
|
|
137
152
|
/** The group a rule's conditions test from `node`, or null when they test `node` itself. */
|
|
138
153
|
function testedGroup(node, on, groups, isRoot) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tailwind.js","names":[],"sources":["../../../../src/export/html.ts","../../../../src/behaviours/states/tailwind.ts"],"sourcesContent":["import { escapeAttribute, escapeText } from 'entities'\nimport { twirl } from 'twirlwind'\n\nimport type { DesignDocument, DesignElement, DesignNode, DesignText } from '../types'\n\nexport interface SerializeHTMLOptions {\n style?: 'inline' | 'tailwind'\n /** Custom properties declared in `@theme`; a `var()` naming one becomes its utility. */\n themeVariables?: readonly string[]\n /**\n * Put each child of an element that holds only elements on its own indented line, for code\n * people read. Text keeps its whitespace; whitespace between elements in a projected layer\n * changes nothing, since its children are placed by flex, grid, or absolute position.\n */\n indent?: boolean\n}\n\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr'\n])\n\nexport function splitWhitespace(value: string): string[] {\n const parts: string[] = []\n let current = ''\n for (const char of value) {\n if (char === ' ' || char === '\\n' || char === '\\t' || char === '\\r' || char === '\\f') {\n if (current.length > 0) parts.push(current)\n current = ''\n } else {\n current += char\n }\n }\n if (current.length > 0) parts.push(current)\n return parts\n}\n\nfunction serializeText(node: DesignText): string {\n return escapeText(node.text)\n}\n\nfunction serializeStyle(node: DesignElement): string | undefined {\n if (!node.inlineStyle || Object.keys(node.inlineStyle).length === 0) return undefined\n return Object.entries(node.inlineStyle)\n .filter(([, value]) => value !== '')\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n}\n\nexport function serializeTailwindClasses(\n node: DesignElement,\n themeVariables: readonly string[] = []\n): string | undefined {\n const style = serializeStyle(node)\n if (!style) return undefined\n const className = twirl(style, { theme: { variables: themeVariables } })\n return className.length > 0 ? className : undefined\n}\n\nexport function mergeClassNames(...values: Array<string | undefined>): string | undefined {\n const className = values\n .flatMap((value) => (value ? splitWhitespace(value) : []))\n .map((value) => value.trim())\n .filter((value) => value.length > 0)\n .join(' ')\n return className.length > 0 ? className : undefined\n}\n\n/**\n * Characters that end an attribute name or quote one. Imported JSX props can have any name, and\n * one holding these would write other attributes, so such a name is left out.\n */\nconst UNSAFE_ATTRIBUTE_NAME = /[\\s\"'/=>]/\n\n/**\n * HTML, SVG, and custom element names. Imported JSX can name any tag, and one holding spaces or\n * quotes would write attributes, so another name is written as a `div` with the same content.\n */\nconst SAFE_TAG_NAME = /^[a-z][\\w.:-]*$/i\n\nfunction safeTagName(tagName: string): string {\n return SAFE_TAG_NAME.test(tagName) ? tagName : 'div'\n}\n\nfunction serializeAttrs(node: DesignElement, options: SerializeHTMLOptions): string {\n const style = serializeStyle(node)\n const tailwindClass =\n options.style === 'tailwind'\n ? serializeTailwindClasses(node, options.themeVariables)\n : undefined\n const attrsWithoutStyle = { ...node.attrs }\n delete attrsWithoutStyle.style\n const sourceAttrs = options.style === 'tailwind' && tailwindClass ? attrsWithoutStyle : node.attrs\n const attrs: Record<string, string | undefined> = { ...sourceAttrs }\n if (tailwindClass) attrs.class = mergeClassNames(node.attrs.class, tailwindClass)\n if (style && options.style !== 'tailwind') attrs.style = style\n const serialized = Object.entries(attrs)\n .filter((entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1] !== '')\n .filter(([name]) => name !== '' && !UNSAFE_ATTRIBUTE_NAME.test(name))\n .map(([name, value]) => `${name}=\"${escapeAttribute(value)}\"`)\n\n if (serialized.length === 0) return ''\n return ` ${serialized.join(' ')}`\n}\n\n/** Static HTML cannot play a shader, so its layer shows the still frame behind its content. */\nconst SHADER_FRAME_STYLE =\n 'position:absolute;inset:0;width:100%;height:100%;object-fit:cover;z-index:-1;border-radius:inherit;pointer-events:none'\n\nfunction shaderFrame(node: DesignElement): string {\n const frame = node.shader?.frame\n return frame ? `<img src=\"${escapeAttribute(frame)}\" alt=\"\" style=\"${SHADER_FRAME_STYLE}\">` : ''\n}\n\nfunction serializeElement(\n node: DesignElement,\n options: SerializeHTMLOptions,\n depth: number\n): string {\n // SVG names such as `linearGradient` keep their case, as an SVG parser needs them.\n const tagName = safeTagName(node.tagName)\n const attrs = serializeAttrs(node, options)\n if (VOID_ELEMENTS.has(tagName.toLowerCase())) return `<${tagName}${attrs}>`\n const children = [\n shaderFrame(node),\n ...node.children.map((child) => serializeNode(child, options, depth + 1))\n ].filter((child) => child !== '')\n const block =\n options.indent && children.length > 0 && node.children.every((child) => child.type !== 'text')\n if (!block) return `<${tagName}${attrs}>${children.join('')}</${tagName}>`\n const inner = ' '.repeat(depth + 1)\n const outer = ' '.repeat(depth)\n return `<${tagName}${attrs}>\\n${children.map((child) => inner + child).join('\\n')}\\n${outer}</${tagName}>`\n}\n\nexport function serializeNode(\n node: DesignNode,\n options: SerializeHTMLOptions = {},\n depth = 0\n): string {\n return node.type === 'text' ? serializeText(node) : serializeElement(node, options, depth)\n}\n\n/**\n * The elements `serializeHTML` writes, in the order they open: the document's own, and `null`\n * for a shader's still frame, which it adds in front of its layer's content.\n */\nexport function serializedElements(document: DesignDocument): (DesignElement | null)[] {\n const visit = (node: DesignNode): (DesignElement | null)[] => {\n if (node.type === 'text') return []\n if (VOID_ELEMENTS.has(safeTagName(node.tagName).toLowerCase())) return [node]\n return [node, ...(node.shader?.frame ? [null] : []), ...node.children.flatMap(visit)]\n }\n return document.children.flatMap(visit)\n}\n\nexport function serializeHTML(\n document: DesignDocument,\n options: SerializeHTMLOptions = {}\n): string {\n const resolved: SerializeHTMLOptions = {\n ...options,\n themeVariables: options.themeVariables ?? document.tokens?.themeVariables()\n }\n return document.children\n .map((node) => serializeNode(node, resolved))\n .join(options.indent ? '\\n' : '')\n}\n","import { splitWhitespace } from '#dom-css/export/html'\nimport type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'\nimport { compact } from 'es-toolkit/array'\nimport { twirl } from 'twirlwind'\n\nimport { cssName, propAttribute } from './names'\nimport type { StateCondition, StateElement, StateNode, StateStyles } from './types'\n\nexport interface StateTailwindOptions {\n /** Custom properties declared in `@theme`; a `var()` naming one becomes its utility. */\n themeVariables?: readonly string[]\n}\n\n/** A value inside a variant: bare when it is a plain word, else quoted with spaces as `_`. */\nconst variantValue = (value: string) =>\n /^[\\w-]+$/.test(value) ? value : `\"${value.replace(/\\s/g, '_').replace(/\"/g, '\\\\\"')}\"`\n\n/**\n * The variant a condition adds. On the root it tests the root itself; below it, it tests the\n * root through its named group, so a control nested in another reacts only to its own root.\n */\nfunction variant(condition: StateCondition, group: string | null): string {\n const on = (name: string) => (group ? `group-${name}/${group}:` : `${name}:`)\n if (condition.type === 'state') return on(`data-[state=${variantValue(condition.value)}]`)\n if (condition.type === 'disabled') return on('data-disabled')\n if (condition.type === 'filled') return on('has-[:is(input,textarea):not(:placeholder-shown)]')\n if (condition.type === 'prop') {\n const attribute = propAttribute(condition.name).slice('data-'.length)\n return on(`data-[${attribute}=${variantValue(condition.value)}]`)\n }\n if (condition.state === 'focus') return on(condition.within ? 'focus-within' : 'focus-visible')\n // A disabled control keeps its disabled look under the pointer.\n const enabled = group ? `group-not-data-disabled/${group}:` : 'not-data-disabled:'\n return `${enabled}${on(condition.state === 'hover' ? 'hover' : 'active')}`\n}\n\nfunction utilities(style: DesignStyleDeclaration, options: StateTailwindOptions): string[] {\n const css = Object.entries(style)\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n return css\n ? splitWhitespace(twirl(css, { theme: { variables: options.themeVariables ?? [] } }))\n : []\n}\n\n/** What each element's utilities are written against. */\ninterface Groups {\n /** The control's root group. */\n root: string\n /** A named group for each layer other than the root whose state a rule tests. */\n anchors: Map<StateElement, string>\n}\n\n/** The group a rule's conditions test from `node`, or null when they test `node` itself. */\nfunction testedGroup(\n node: StateElement,\n on: StateElement | undefined,\n groups: Groups,\n isRoot: boolean\n): string | null {\n if (on) return on === node ? null : (groups.anchors.get(on) ?? null)\n return isRoot ? null : groups.root\n}\n\n/** The utilities a layer takes: its group names, its rest style, and each rule behind its variants. */\nfunction elementUtilities(\n node: StateElement,\n groups: Groups,\n isRoot: boolean,\n options: StateTailwindOptions\n): string[] {\n const anchor = groups.anchors.get(node)\n return [\n ...(isRoot ? [`group/${groups.root}`] : []),\n ...(anchor ? [`group/${anchor}`] : []),\n ...utilities(node.base, options),\n ...node.rules.flatMap((rule) => {\n const group = testedGroup(node, rule.on, groups, isRoot)\n const prefix = [\n ...rule.conditions.map((condition) => variant(condition, group)),\n ...(rule.pseudo\n ? [rule.pseudo === 'placeholder' ? 'placeholder:' : `[&::${rule.pseudo}]:`]\n : [])\n ].join('')\n return utilities(rule.style, options).map((utility) => `${prefix}${utility}`)\n })\n ]\n}\n\nfunction designNode(node: StateNode, classes: Map<StateElement, string>): DesignNode {\n if (node.type === 'text') return node\n return {\n type: 'element',\n tagName: node.tagName,\n attrs: {\n ...node.attrs,\n class: compact([\n ...(node.attrs.class ? splitWhitespace(node.attrs.class) : []),\n classes.get(node)\n ]).join(' ')\n },\n children: node.children.map((child) => designNode(child, classes)),\n shader: node.shader\n }\n}\n\n/** The layers rules test other than the root, each named after the root's group. */\nfunction anchorGroups(root: StateElement, group: string): Map<StateElement, string> {\n const anchors = new Map<StateElement, string>()\n const visit = (node: StateNode) => {\n if (node.type === 'text') return\n for (const rule of node.rules)\n if (rule.on && !anchors.has(rule.on)) anchors.set(rule.on, `${group}-${anchors.size + 1}`)\n for (const child of node.children) visit(child)\n }\n visit(root)\n return anchors\n}\n\n/**\n * Each element's Tailwind utilities for the state styles: rest utilities, and each variant's\n * changes behind the variants that show it. More stacked variants make a more specific\n * selector, so a combined variant wins over each of its parts.\n */\nexport function stateTailwindClasses(\n styles: StateStyles,\n options: StateTailwindOptions = {}\n): Map<StateElement, string> {\n const root = cssName(styles.name, 'component')\n const groups = { root, anchors: anchorGroups(styles.root, root) }\n const classes = new Map<StateElement, string>()\n const visit = (node: StateNode, isRoot: boolean) => {\n if (node.type === 'text') return\n classes.set(node, elementUtilities(node, groups, isRoot, options).join(' '))\n for (const child of node.children) visit(child, false)\n }\n visit(styles.root, true)\n return classes\n}\n\n/** The state styles as Tailwind utilities on each element of the merged markup. */\nexport function stateStylesToTailwind(\n styles: StateStyles,\n options: StateTailwindOptions = {}\n): DesignDocument {\n const classes = stateTailwindClasses(styles, options)\n return { type: 'document', children: [designNode(styles.root, classes)] }\n}\n"],"mappings":";;;;;AAiBA,MAAM,gCAAgB,IAAI,IAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,gBAAgB,OAAyB;CACvD,MAAM,QAAkB,CAAC;CACzB,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,OACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS,OAAQ,SAAS,QAAQ,SAAS,MAAM;EACpF,IAAI,QAAQ,SAAS,GAAG,MAAM,KAAK,OAAO;EAC1C,UAAU;CACZ,OACE,WAAW;CAGf,IAAI,QAAQ,SAAS,GAAG,MAAM,KAAK,OAAO;CAC1C,OAAO;AACT;AAEA,SAAS,cAAc,MAA0B;CAC/C,OAAO,WAAW,KAAK,IAAI;AAC7B;AAEA,SAAS,eAAe,MAAyC;CAC/D,IAAI,CAAC,KAAK,eAAe,OAAO,KAAK,KAAK,WAAW,CAAC,CAAC,WAAW,GAAG,OAAO,KAAA;CAC5E,OAAO,OAAO,QAAQ,KAAK,WAAW,CAAC,CACpC,QAAQ,GAAG,WAAW,UAAU,EAAE,CAAC,CACnC,KAAK,CAAC,UAAU,WAAW,GAAG,SAAS,IAAI,OAAO,CAAC,CACnD,KAAK,IAAI;AACd;AAEA,SAAgB,yBACd,MACA,iBAAoC,CAAC,GACjB;CACpB,MAAM,QAAQ,eAAe,IAAI;CACjC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,YAAY,MAAM,OAAO,EAAE,OAAO,EAAE,WAAW,eAAe,EAAE,CAAC;CACvE,OAAO,UAAU,SAAS,IAAI,YAAY,KAAA;AAC5C;AAEA,SAAgB,gBAAgB,GAAG,QAAuD;CACxF,MAAM,YA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SAAS,SAAoB;EACjC,IAAI,KAAK,SAAS,QAAQ;EAC1B,KAAK,MAAM,QAAQ,KAAK,OACtB,IAAI,KAAK,MAAM,CAAC,QAAQ,IAAI,KAAK,EAAE,GAAG,QAAQ,IAAI,KAAK,IAAI,GAAG,MAAM,GAAG,QAAQ,OAAO,GAAG;EAC3F,KAAK,MAAM,SAAS,KAAK,UAAU,MAAM,KAAK;CAChD;CACA,MAAM,IAAI;CACV,OAAO;AACT;;;;;;AAOA,SAAgB,qBACd,QACA,UAAgC,CAAC,GACN;CAC3B,MAAM,OAAO,QAAQ,OAAO,MAAM,WAAW;CAC7C,MAAM,SAAS;EAAE;EAAM,SAAS,aAAa,OAAO,MAAM,IAAI;CAAE;CAChE,MAAM,0BAAU,IAAI,IAA0B;CAC9C,MAAM,SAAS,MAAiB,WAAoB;EAClD,IAAI,KAAK,SAAS,QAAQ;EAC1B,QAAQ,IAAI,MAAM,iBAAiB,MAAM,QAAQ,QAAQ,OAAO,CAAC,CAAC,KAAK,GAAG,CAAC;EAC3E,KAAK,MAAM,SAAS,KAAK,UAAU,MAAM,OAAO,KAAK;CACvD;CACA,MAAM,OAAO,MAAM,IAAI;CACvB,OAAO;AACT;;AAGA,SAAgB,sBACd,QACA,UAAgC,CAAC,GACjB;CAChB,MAAM,UAAU,qBAAqB,QAAQ,OAAO;CACpD,OAAO;EAAE,MAAM;EAAY,UAAU,CAAC,WAAW,OAAO,MAAM,OAAO,CAAC;CAAE;AAC1E"}
|
|
1
|
+
{"version":3,"file":"tailwind.js","names":[],"sources":["../../../../src/export/font-size-class.ts","../../../../src/export/html.ts","../../../../src/behaviours/states/tailwind.ts"],"sourcesContent":["/**\n * twirlwind names a literal font size that is a multiple of four `text-<px / 4>` (40px becomes\n * text-10), a class Tailwind never generates. Rewrite that one token to the arbitrary value,\n * the spelling Tailwind compiles, leaving named steps and token-bound sizes alone.\n *\n * `css` is the declaration string the class list was generated from.\n */\nexport function validFontSizeClass(className: string, css: string): string {\n const fontSize = /(?:^|;)\\s*font-size:\\s*(\\d+(?:\\.\\d+)?)px/.exec(css)?.[1]\n const numeric = className.match(/(?:^|\\s)text-(\\d+)(?=\\s|$)/)\n if (!fontSize || !numeric || Number(numeric[1]) * 4 !== Number(fontSize)) return className\n return className.replace(numeric[0], numeric[0].replace(/text-\\d+/, `text-[${fontSize}px]`))\n}\n","import { escapeAttribute, escapeText } from 'entities'\nimport { twirl } from 'twirlwind'\n\nimport type { DesignDocument, DesignElement, DesignNode, DesignText } from '../types'\nimport { validFontSizeClass } from './font-size-class'\n\nexport interface SerializeHTMLOptions {\n style?: 'inline' | 'tailwind'\n /** Custom properties declared in `@theme`; a `var()` naming one becomes its utility. */\n themeVariables?: readonly string[]\n /**\n * Put each child of an element that holds only elements on its own indented line, for code\n * people read. Text keeps its whitespace; whitespace between elements in a projected layer\n * changes nothing, since its children are placed by flex, grid, or absolute position.\n */\n indent?: boolean\n}\n\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr'\n])\n\nexport function splitWhitespace(value: string): string[] {\n const parts: string[] = []\n let current = ''\n for (const char of value) {\n if (char === ' ' || char === '\\n' || char === '\\t' || char === '\\r' || char === '\\f') {\n if (current.length > 0) parts.push(current)\n current = ''\n } else {\n current += char\n }\n }\n if (current.length > 0) parts.push(current)\n return parts\n}\n\nfunction serializeText(node: DesignText): string {\n return escapeText(node.text)\n}\n\nfunction serializeStyle(node: DesignElement): string | undefined {\n if (!node.inlineStyle || Object.keys(node.inlineStyle).length === 0) return undefined\n return Object.entries(node.inlineStyle)\n .filter(([, value]) => value !== '')\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n}\n\nexport function serializeTailwindClasses(\n node: DesignElement,\n themeVariables: readonly string[] = []\n): string | undefined {\n const style = serializeStyle(node)\n if (!style) return undefined\n const className = validFontSizeClass(\n twirl(style, { theme: { variables: themeVariables } }),\n style\n )\n return className.length > 0 ? className : undefined\n}\n\nexport function mergeClassNames(...values: Array<string | undefined>): string | undefined {\n const className = values\n .flatMap((value) => (value ? splitWhitespace(value) : []))\n .map((value) => value.trim())\n .filter((value) => value.length > 0)\n .join(' ')\n return className.length > 0 ? className : undefined\n}\n\n/**\n * Characters that end an attribute name or quote one. Imported JSX props can have any name, and\n * one holding these would write other attributes, so such a name is left out.\n */\nconst UNSAFE_ATTRIBUTE_NAME = /[\\s\"'/=>]/\n\n/**\n * HTML, SVG, and custom element names. Imported JSX can name any tag, and one holding spaces or\n * quotes would write attributes, so another name is written as a `div` with the same content.\n */\nconst SAFE_TAG_NAME = /^[a-z][\\w.:-]*$/i\n\nfunction safeTagName(tagName: string): string {\n return SAFE_TAG_NAME.test(tagName) ? tagName : 'div'\n}\n\nfunction serializeAttrs(node: DesignElement, options: SerializeHTMLOptions): string {\n const style = serializeStyle(node)\n const tailwindClass =\n options.style === 'tailwind'\n ? serializeTailwindClasses(node, options.themeVariables)\n : undefined\n const attrsWithoutStyle = { ...node.attrs }\n delete attrsWithoutStyle.style\n const sourceAttrs = options.style === 'tailwind' && tailwindClass ? attrsWithoutStyle : node.attrs\n const attrs: Record<string, string | undefined> = { ...sourceAttrs }\n if (tailwindClass) attrs.class = mergeClassNames(node.attrs.class, tailwindClass)\n if (style && options.style !== 'tailwind') attrs.style = style\n const serialized = Object.entries(attrs)\n .filter((entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1] !== '')\n .filter(([name]) => name !== '' && !UNSAFE_ATTRIBUTE_NAME.test(name))\n .map(([name, value]) => `${name}=\"${escapeAttribute(value)}\"`)\n\n if (serialized.length === 0) return ''\n return ` ${serialized.join(' ')}`\n}\n\n/** Static HTML cannot play a shader, so its layer shows the still frame behind its content. */\nconst SHADER_FRAME_STYLE =\n 'position:absolute;inset:0;width:100%;height:100%;object-fit:cover;z-index:-1;border-radius:inherit;pointer-events:none'\n\nfunction shaderFrame(node: DesignElement): string {\n const frame = node.shader?.frame\n return frame ? `<img src=\"${escapeAttribute(frame)}\" alt=\"\" style=\"${SHADER_FRAME_STYLE}\">` : ''\n}\n\nfunction serializeElement(\n node: DesignElement,\n options: SerializeHTMLOptions,\n depth: number\n): string {\n // SVG names such as `linearGradient` keep their case, as an SVG parser needs them.\n const tagName = safeTagName(node.tagName)\n const attrs = serializeAttrs(node, options)\n if (VOID_ELEMENTS.has(tagName.toLowerCase())) return `<${tagName}${attrs}>`\n const children = [\n shaderFrame(node),\n ...node.children.map((child) => serializeNode(child, options, depth + 1))\n ].filter((child) => child !== '')\n const block =\n options.indent && children.length > 0 && node.children.every((child) => child.type !== 'text')\n if (!block) return `<${tagName}${attrs}>${children.join('')}</${tagName}>`\n const inner = ' '.repeat(depth + 1)\n const outer = ' '.repeat(depth)\n return `<${tagName}${attrs}>\\n${children.map((child) => inner + child).join('\\n')}\\n${outer}</${tagName}>`\n}\n\nexport function serializeNode(\n node: DesignNode,\n options: SerializeHTMLOptions = {},\n depth = 0\n): string {\n return node.type === 'text' ? serializeText(node) : serializeElement(node, options, depth)\n}\n\n/**\n * The elements `serializeHTML` writes, in the order they open: the document's own, and `null`\n * for a shader's still frame, which it adds in front of its layer's content.\n */\nexport function serializedElements(document: DesignDocument): (DesignElement | null)[] {\n const visit = (node: DesignNode): (DesignElement | null)[] => {\n if (node.type === 'text') return []\n if (VOID_ELEMENTS.has(safeTagName(node.tagName).toLowerCase())) return [node]\n return [node, ...(node.shader?.frame ? [null] : []), ...node.children.flatMap(visit)]\n }\n return document.children.flatMap(visit)\n}\n\nexport function serializeHTML(\n document: DesignDocument,\n options: SerializeHTMLOptions = {}\n): string {\n const resolved: SerializeHTMLOptions = {\n ...options,\n themeVariables: options.themeVariables ?? document.tokens?.themeVariables()\n }\n return document.children\n .map((node) => serializeNode(node, resolved))\n .join(options.indent ? '\\n' : '')\n}\n","import { validFontSizeClass } from '#dom-css/export/font-size-class'\nimport { splitWhitespace } from '#dom-css/export/html'\nimport type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'\nimport { compact } from 'es-toolkit/array'\nimport { twirl } from 'twirlwind'\n\nimport { cssName, propAttribute } from './names'\nimport type { StateCondition, StateElement, StateNode, StateStyles } from './types'\n\nexport interface StateTailwindOptions {\n /** Custom properties declared in `@theme`; a `var()` naming one becomes its utility. */\n themeVariables?: readonly string[]\n}\n\n/** A value inside a variant: bare when it is a plain word, else quoted with spaces as `_`. */\nconst variantValue = (value: string) =>\n /^[\\w-]+$/.test(value) ? value : `\"${value.replace(/\\s/g, '_').replace(/\"/g, '\\\\\"')}\"`\n\n/**\n * The variant a condition adds. On the root it tests the root itself; below it, it tests the\n * root through its named group, so a control nested in another reacts only to its own root.\n */\nfunction variant(condition: StateCondition, group: string | null): string {\n const on = (name: string) => (group ? `group-${name}/${group}:` : `${name}:`)\n if (condition.type === 'state') return on(`data-[state=${variantValue(condition.value)}]`)\n if (condition.type === 'disabled') return on('data-disabled')\n if (condition.type === 'filled') return on('has-[:is(input,textarea):not(:placeholder-shown)]')\n if (condition.type === 'prop') {\n const attribute = propAttribute(condition.name).slice('data-'.length)\n return on(`data-[${attribute}=${variantValue(condition.value)}]`)\n }\n if (condition.state === 'focus') return on(condition.within ? 'focus-within' : 'focus-visible')\n // A disabled control keeps its disabled look under the pointer.\n const enabled = group ? `group-not-data-disabled/${group}:` : 'not-data-disabled:'\n return `${enabled}${on(condition.state === 'hover' ? 'hover' : 'active')}`\n}\n\nfunction utilities(style: DesignStyleDeclaration, options: StateTailwindOptions): string[] {\n const css = Object.entries(style)\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n return css\n ? splitWhitespace(\n validFontSizeClass(twirl(css, { theme: { variables: options.themeVariables ?? [] } }), css)\n )\n : []\n}\n\n/** What each element's utilities are written against. */\ninterface Groups {\n /** The control's root group. */\n root: string\n /** A named group for each layer other than the root whose state a rule tests. */\n anchors: Map<StateElement, string>\n}\n\n/** The group a rule's conditions test from `node`, or null when they test `node` itself. */\nfunction testedGroup(\n node: StateElement,\n on: StateElement | undefined,\n groups: Groups,\n isRoot: boolean\n): string | null {\n if (on) return on === node ? null : (groups.anchors.get(on) ?? null)\n return isRoot ? null : groups.root\n}\n\n/** The utilities a layer takes: its group names, its rest style, and each rule behind its variants. */\nfunction elementUtilities(\n node: StateElement,\n groups: Groups,\n isRoot: boolean,\n options: StateTailwindOptions\n): string[] {\n const anchor = groups.anchors.get(node)\n return [\n ...(isRoot ? [`group/${groups.root}`] : []),\n ...(anchor ? [`group/${anchor}`] : []),\n ...utilities(node.base, options),\n ...node.rules.flatMap((rule) => {\n const group = testedGroup(node, rule.on, groups, isRoot)\n const prefix = [\n ...rule.conditions.map((condition) => variant(condition, group)),\n ...(rule.pseudo\n ? [rule.pseudo === 'placeholder' ? 'placeholder:' : `[&::${rule.pseudo}]:`]\n : [])\n ].join('')\n return utilities(rule.style, options).map((utility) => `${prefix}${utility}`)\n })\n ]\n}\n\nfunction designNode(node: StateNode, classes: Map<StateElement, string>): DesignNode {\n if (node.type === 'text') return node\n return {\n type: 'element',\n tagName: node.tagName,\n attrs: {\n ...node.attrs,\n class: compact([\n ...(node.attrs.class ? splitWhitespace(node.attrs.class) : []),\n classes.get(node)\n ]).join(' ')\n },\n children: node.children.map((child) => designNode(child, classes)),\n shader: node.shader\n }\n}\n\n/** The layers rules test other than the root, each named after the root's group. */\nfunction anchorGroups(root: StateElement, group: string): Map<StateElement, string> {\n const anchors = new Map<StateElement, string>()\n const visit = (node: StateNode) => {\n if (node.type === 'text') return\n for (const rule of node.rules)\n if (rule.on && !anchors.has(rule.on)) anchors.set(rule.on, `${group}-${anchors.size + 1}`)\n for (const child of node.children) visit(child)\n }\n visit(root)\n return anchors\n}\n\n/**\n * Each element's Tailwind utilities for the state styles: rest utilities, and each variant's\n * changes behind the variants that show it. More stacked variants make a more specific\n * selector, so a combined variant wins over each of its parts.\n */\nexport function stateTailwindClasses(\n styles: StateStyles,\n options: StateTailwindOptions = {}\n): Map<StateElement, string> {\n const root = cssName(styles.name, 'component')\n const groups = { root, anchors: anchorGroups(styles.root, root) }\n const classes = new Map<StateElement, string>()\n const visit = (node: StateNode, isRoot: boolean) => {\n if (node.type === 'text') return\n classes.set(node, elementUtilities(node, groups, isRoot, options).join(' '))\n for (const child of node.children) visit(child, false)\n }\n visit(styles.root, true)\n return classes\n}\n\n/** The state styles as Tailwind utilities on each element of the merged markup. */\nexport function stateStylesToTailwind(\n styles: StateStyles,\n options: StateTailwindOptions = {}\n): DesignDocument {\n const classes = stateTailwindClasses(styles, options)\n return { type: 'document', children: [designNode(styles.root, classes)] }\n}\n"],"mappings":";;;;;;;;;;;;AAOA,SAAgB,mBAAmB,WAAmB,KAAqB;CACzE,MAAM,WAAW,2CAA2C,KAAK,GAAG,CAAC,GAAG;CACxE,MAAM,UAAU,UAAU,MAAM,4BAA4B;CAC5D,IAAI,CAAC,YAAY,CAAC,WAAW,OAAO,QAAQ,EAAE,IAAI,MAAM,OAAO,QAAQ,GAAG,OAAO;CACjF,OAAO,UAAU,QAAQ,QAAQ,IAAI,QAAQ,EAAE,CAAC,QAAQ,YAAY,SAAS,SAAS,IAAI,CAAC;AAC7F;;;ACMA,MAAM,gCAAgB,IAAI,IAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,gBAAgB,OAAyB;CACvD,MAAM,QAAkB,CAAC;CACzB,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,OACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS,OAAQ,SAAS,QAAQ,SAAS,MAAM;EACpF,IAAI,QAAQ,SAAS,GAAG,MAAM,KAAK,OAAO;EAC1C,UAAU;CACZ,OACE,WAAW;CAGf,IAAI,QAAQ,SAAS,GAAG,MAAM,KAAK,OAAO;CAC1C,OAAO;AACT;AAEA,SAAS,cAAc,MAA0B;CAC/C,OAAO,WAAW,KAAK,IAAI;AAC7B;AAEA,SAAS,eA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3E,KAAK,MAAM,SAAS,KAAK,UAAU,MAAM,OAAO,KAAK;CACvD;CACA,MAAM,OAAO,MAAM,IAAI;CACvB,OAAO;AACT;;AAGA,SAAgB,sBACd,QACA,UAAgC,CAAC,GACjB;CAChB,MAAM,UAAU,qBAAqB,QAAQ,OAAO;CACpD,OAAO;EAAE,MAAM;EAAY,UAAU,CAAC,WAAW,OAAO,MAAM,OAAO,CAAC;CAAE;AAC1E"}
|
package/dist/chunks/browser.js
CHANGED
|
@@ -7,7 +7,7 @@ import { autoLayoutSizingFields, fillSizingFields, layoutSizing, textAutoResizeF
|
|
|
7
7
|
import { countBy } from "es-toolkit/array";
|
|
8
8
|
import { blurRadiusForSigma } from "@pairdraw/scene-graph/geometry";
|
|
9
9
|
import { pick } from "es-toolkit";
|
|
10
|
-
import { parseCSSAlignItems, parseCSSAlignSelf, parseCSSBackgroundImages, parseCSSColor, parseCSSFlexDirection, parseCSSFontFamily, parseCSSJustifyContent, parseCSSLetterSpacing, parseCSSLineHeight, parseCSSNumber, parseCSSShadows } from "@pairdraw/scene-graph/css";
|
|
10
|
+
import { GENERIC_FONT_FAMILIES_BY_CLASS, genericFontFamilyClass, parseCSSAlignItems, parseCSSAlignSelf, parseCSSBackgroundImages, parseCSSColor, parseCSSFlexDirection, parseCSSFontFamilies, parseCSSFontFamily, parseCSSJustifyContent, parseCSSLetterSpacing, parseCSSLineHeight, parseCSSNumber, parseCSSShadows } from "@pairdraw/scene-graph/css";
|
|
11
11
|
import { SceneGraph } from "@pairdraw/scene-graph";
|
|
12
12
|
import { normalizeEffects } from "@pairdraw/scene-graph/effects";
|
|
13
13
|
import { textLayerName } from "@pairdraw/scene-graph/node-defaults";
|
|
@@ -414,6 +414,16 @@ function hasDefiniteWidth(graph, node) {
|
|
|
414
414
|
return layoutSizing(graph, node, "HORIZONTAL") !== "HUG";
|
|
415
415
|
}
|
|
416
416
|
/**
|
|
417
|
+
* Whether CSS keeps the text on its lines however narrow its box, and the text starts at the
|
|
418
|
+
* box's start edge, so its own width places it as the box does. A box narrower than the text
|
|
419
|
+
* clips it rather than breaking it, which wrapping text measured in other fonts would do.
|
|
420
|
+
*/
|
|
421
|
+
function staysOnItsLines(style) {
|
|
422
|
+
const whiteSpace = pickStyle(style, "white-space")?.trim();
|
|
423
|
+
const align = pickStyle(style, "text-align")?.trim() ?? "start";
|
|
424
|
+
return (whiteSpace === "nowrap" || whiteSpace === "pre") && ["start", "left"].includes(align);
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
417
427
|
* Text wraps where its width is fixed or fills a parent with a width of its own, and hugs its
|
|
418
428
|
* content otherwise. It is measured when the document is laid out.
|
|
419
429
|
*/
|
|
@@ -438,6 +448,13 @@ function applyFlowSizing(graph, node, style, display, parentFlow) {
|
|
|
438
448
|
const own = (fixed) => fixed ? "FIXED" : "HUG";
|
|
439
449
|
Object.assign(node, autoLayoutSizingFields(node.layoutMode, own(size.fixedWidth), own(size.fixedHeight)));
|
|
440
450
|
}
|
|
451
|
+
if (node.type === "TEXT" && staysOnItsLines(style)) {
|
|
452
|
+
applyTextSizing(graph, node, {
|
|
453
|
+
fixedWidth: false,
|
|
454
|
+
fixedHeight: size.fixedHeight
|
|
455
|
+
});
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
441
458
|
applyParentFill(graph, node, style, display, parentFlow, size);
|
|
442
459
|
if (node.type === "TEXT") applyTextSizing(graph, node, size);
|
|
443
460
|
}
|
|
@@ -448,6 +465,26 @@ function mergeCSSText(...parts) {
|
|
|
448
465
|
return text.length > 0 ? text.join("\n") : void 0;
|
|
449
466
|
}
|
|
450
467
|
//#endregion
|
|
468
|
+
//#region src/import/fonts.ts
|
|
469
|
+
function defaultFamily(kind, options) {
|
|
470
|
+
const candidates = GENERIC_FONT_FAMILIES_BY_CLASS[kind];
|
|
471
|
+
return (options.isAvailable ? candidates.find((family) => options.isAvailable?.(family)) : null) ?? candidates[0];
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* The family a CSS `font-family` stack asks a document to draw: the first concrete family the
|
|
475
|
+
* font service can provide; a generic keyword maps to a concrete face of its class. Null when the
|
|
476
|
+
* list has no family.
|
|
477
|
+
*/
|
|
478
|
+
function resolveFontFamilyStack(value, options = {}) {
|
|
479
|
+
for (const family of parseCSSFontFamilies(value)) {
|
|
480
|
+
const kind = genericFontFamilyClass(family);
|
|
481
|
+
if (kind) return defaultFamily(kind, options);
|
|
482
|
+
if (options.isAvailable && !options.isAvailable(family)) continue;
|
|
483
|
+
return family;
|
|
484
|
+
}
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
//#endregion
|
|
451
488
|
//#region src/import/text.ts
|
|
452
489
|
/**
|
|
453
490
|
* What characters take from the elements around them: the properties CSS inherits, and the
|
|
@@ -793,11 +830,38 @@ const IMAGE_SOURCE_URL_KEY = "image-source-url";
|
|
|
793
830
|
* by half its blur length, which the canvas draws from the radius that gives that sigma.
|
|
794
831
|
*/
|
|
795
832
|
function cssShadows(value) {
|
|
796
|
-
return parseCSSShadows(value).map((effect) =>
|
|
797
|
-
|
|
798
|
-
|
|
833
|
+
return parseCSSShadows(value).map((effect) => {
|
|
834
|
+
if (effect.type !== "DROP_SHADOW" && effect.type !== "INNER_SHADOW") return effect;
|
|
835
|
+
return {
|
|
836
|
+
...effect,
|
|
837
|
+
radius: blurRadiusForSigma(effect.radius / 2)
|
|
838
|
+
};
|
|
799
839
|
});
|
|
800
840
|
}
|
|
841
|
+
/**
|
|
842
|
+
* The document with every element's font stack resolved to the family its text layer draws, so
|
|
843
|
+
* the per-character CSS parse sees a concrete name instead of a generic keyword.
|
|
844
|
+
*/
|
|
845
|
+
function withResolvedFontFamilies(node, resolve) {
|
|
846
|
+
if (node.type !== "element") return node;
|
|
847
|
+
const resolved = (style) => {
|
|
848
|
+
const stack = style?.["font-family"];
|
|
849
|
+
const family = stack === void 0 ? null : resolve(stack);
|
|
850
|
+
return family && family !== stack ? {
|
|
851
|
+
...style,
|
|
852
|
+
"font-family": family
|
|
853
|
+
} : style;
|
|
854
|
+
};
|
|
855
|
+
const computedStyle = resolved(node.computedStyle);
|
|
856
|
+
const inlineStyle = resolved(node.inlineStyle);
|
|
857
|
+
const next = {
|
|
858
|
+
...node,
|
|
859
|
+
children: node.children.map((child) => withResolvedFontFamilies(child, resolve))
|
|
860
|
+
};
|
|
861
|
+
if (computedStyle) next.computedStyle = computedStyle;
|
|
862
|
+
if (inlineStyle) next.inlineStyle = inlineStyle;
|
|
863
|
+
return next;
|
|
864
|
+
}
|
|
801
865
|
function textContent(node) {
|
|
802
866
|
if (node.type === "text") return node.text;
|
|
803
867
|
return node.children.map(textContent).join("");
|
|
@@ -1017,11 +1081,11 @@ function applyImageFill(graph, node, element, style) {
|
|
|
1017
1081
|
const source = element.attrs.src;
|
|
1018
1082
|
const bytes = bytesFromDataURL(source);
|
|
1019
1083
|
if (!bytes) {
|
|
1020
|
-
if (source) node.pluginData.
|
|
1084
|
+
if (source) node.pluginData = [...node.pluginData, {
|
|
1021
1085
|
pluginId: DOM_CSS_PLUGIN_ID,
|
|
1022
1086
|
key: IMAGE_SOURCE_URL_KEY,
|
|
1023
1087
|
value: source
|
|
1024
|
-
}
|
|
1088
|
+
}];
|
|
1025
1089
|
return;
|
|
1026
1090
|
}
|
|
1027
1091
|
const imageHash = computeImageHash(bytes);
|
|
@@ -1053,6 +1117,7 @@ function applyElementStyle(graph, node, element, style) {
|
|
|
1053
1117
|
}
|
|
1054
1118
|
node.strokes = strokes;
|
|
1055
1119
|
setBorderWeights(node, style, strokes[0]);
|
|
1120
|
+
node.strokesIncludedInLayout = true;
|
|
1056
1121
|
}
|
|
1057
1122
|
const effects = cssShadows(pickStyle(style, "box-shadow"));
|
|
1058
1123
|
if (effects.length > 0) node.effects = normalizeEffects(effects);
|
|
@@ -1141,55 +1206,101 @@ function linkText(node, element) {
|
|
|
1141
1206
|
style: { hyperlink }
|
|
1142
1207
|
}];
|
|
1143
1208
|
}
|
|
1209
|
+
const BOX_PROPERTIES = [
|
|
1210
|
+
"aspect-ratio",
|
|
1211
|
+
"background-color",
|
|
1212
|
+
"border-radius",
|
|
1213
|
+
"box-shadow",
|
|
1214
|
+
"display",
|
|
1215
|
+
"height",
|
|
1216
|
+
"width",
|
|
1217
|
+
"min-width",
|
|
1218
|
+
"max-width",
|
|
1219
|
+
"min-height",
|
|
1220
|
+
"max-height",
|
|
1221
|
+
"object-fit",
|
|
1222
|
+
"overflow",
|
|
1223
|
+
"position",
|
|
1224
|
+
"top",
|
|
1225
|
+
"right",
|
|
1226
|
+
"bottom",
|
|
1227
|
+
"left",
|
|
1228
|
+
"flex-wrap",
|
|
1229
|
+
"align-self"
|
|
1230
|
+
];
|
|
1231
|
+
const PADDING_PROPERTIES = [
|
|
1232
|
+
"padding",
|
|
1233
|
+
"padding-top",
|
|
1234
|
+
"padding-right",
|
|
1235
|
+
"padding-bottom",
|
|
1236
|
+
"padding-left",
|
|
1237
|
+
"padding-block",
|
|
1238
|
+
"padding-inline"
|
|
1239
|
+
];
|
|
1240
|
+
const BORDER_SIDES = [
|
|
1241
|
+
"top",
|
|
1242
|
+
"right",
|
|
1243
|
+
"bottom",
|
|
1244
|
+
"left"
|
|
1245
|
+
];
|
|
1246
|
+
/** Whether every length of a value is zero, as `0`, `0px`, and `0 0` are. */
|
|
1247
|
+
function isZeroLength(value) {
|
|
1248
|
+
return value.trim().split(/\s+/).every((part) => parseCSSNumber(part) === 0);
|
|
1249
|
+
}
|
|
1250
|
+
/** Whether any side's border draws: it has a style other than none and a width other than zero. */
|
|
1251
|
+
function drawsBorder(style) {
|
|
1252
|
+
return BORDER_SIDES.some((side) => {
|
|
1253
|
+
const borderStyle = pickStyle(style, `border-${side}-style`) ?? pickStyle(style, "border-style");
|
|
1254
|
+
if (borderStyle === void 0 || borderStyle === "none" || borderStyle === "hidden") return false;
|
|
1255
|
+
const width = pickStyle(style, `border-${side}-width`) ?? pickStyle(style, "border-width");
|
|
1256
|
+
return width === void 0 || !isZeroLength(width);
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Whether the element is a box rather than a run of the text around it. Padding and borders of
|
|
1261
|
+
* no size, which resets such as Tailwind's give every element, leave it a run.
|
|
1262
|
+
*/
|
|
1144
1263
|
function hasBoxStyle(style) {
|
|
1145
|
-
return
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
"border-top-style",
|
|
1152
|
-
"border-top-width",
|
|
1153
|
-
"border-right-style",
|
|
1154
|
-
"border-right-width",
|
|
1155
|
-
"border-bottom-style",
|
|
1156
|
-
"border-bottom-width",
|
|
1157
|
-
"border-left-style",
|
|
1158
|
-
"border-left-width",
|
|
1159
|
-
"border-radius",
|
|
1160
|
-
"box-shadow",
|
|
1161
|
-
"display",
|
|
1162
|
-
"height",
|
|
1163
|
-
"padding",
|
|
1164
|
-
"padding-top",
|
|
1165
|
-
"padding-right",
|
|
1166
|
-
"padding-bottom",
|
|
1167
|
-
"padding-left",
|
|
1168
|
-
"padding-block",
|
|
1169
|
-
"padding-inline",
|
|
1170
|
-
"width",
|
|
1171
|
-
"min-width",
|
|
1172
|
-
"max-width",
|
|
1173
|
-
"min-height",
|
|
1174
|
-
"max-height",
|
|
1175
|
-
"object-fit",
|
|
1176
|
-
"overflow",
|
|
1177
|
-
"position",
|
|
1178
|
-
"top",
|
|
1179
|
-
"right",
|
|
1180
|
-
"bottom",
|
|
1181
|
-
"left",
|
|
1182
|
-
"flex-wrap",
|
|
1183
|
-
"align-self"
|
|
1184
|
-
].some((property) => pickStyle(style, property) !== void 0);
|
|
1264
|
+
if (BOX_PROPERTIES.some((property) => pickStyle(style, property) !== void 0)) return true;
|
|
1265
|
+
if (PADDING_PROPERTIES.some((property) => {
|
|
1266
|
+
const value = pickStyle(style, property);
|
|
1267
|
+
return value !== void 0 && !isZeroLength(value);
|
|
1268
|
+
})) return true;
|
|
1269
|
+
return drawsBorder(style);
|
|
1185
1270
|
}
|
|
1186
1271
|
function hasContent(element) {
|
|
1187
1272
|
return element.children.some((child) => child.type !== "text" || child.text.trim().length > 0);
|
|
1188
1273
|
}
|
|
1274
|
+
/** Whether a child sits in a line of its parent's content or leaves it, rather than a block. */
|
|
1275
|
+
function isInLine(node) {
|
|
1276
|
+
if (node.type === "text" || node.tagName.toLowerCase() === "br") return true;
|
|
1277
|
+
const style = mergedStyle(node);
|
|
1278
|
+
const display = elementDisplay(node, style);
|
|
1279
|
+
const position = pickStyle(style, "position");
|
|
1280
|
+
return display.startsWith("inline") || display === "none" || position === "absolute" || position === "fixed";
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* Whether a block holds inline content with boxes in it, such as a paragraph with a styled
|
|
1284
|
+
* `<code>`, which CSS lays out in lines rather than stacking each run and box.
|
|
1285
|
+
*/
|
|
1286
|
+
function holdsInlineBoxes(element) {
|
|
1287
|
+
return element.children.some((child) => child.type === "element") && element.children.every(isInLine);
|
|
1288
|
+
}
|
|
1289
|
+
/** The flow a box lays its children out in, and whether they are one text instead. */
|
|
1290
|
+
function containerFlow(element, display) {
|
|
1291
|
+
const own = hasContent(element) || flowOf(display) === "flex" ? flowOf(display) : null;
|
|
1292
|
+
const richText = own !== "flex" && holdsRichText(element);
|
|
1293
|
+
const lines = own === "block" && !richText && holdsInlineBoxes(element);
|
|
1294
|
+
return {
|
|
1295
|
+
flow: lines ? "inline" : own,
|
|
1296
|
+
richText,
|
|
1297
|
+
lines
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1189
1300
|
function createElementNode(graph, parentId, element, parentFlow) {
|
|
1190
1301
|
const style = mergedStyle(element);
|
|
1191
1302
|
const display = elementDisplay(element, style);
|
|
1192
|
-
if (display === "none") return null;
|
|
1303
|
+
if (display === "none" || element.tagName.toLowerCase() === "br") return null;
|
|
1193
1304
|
if (isTextLikeElement(element) && !hasBoxStyle(style) && element.children.every((child) => child.type === "text")) {
|
|
1194
1305
|
const text = createTextNode(graph, parentId, textContent(element), style, display, parentFlow);
|
|
1195
1306
|
linkText(text, element);
|
|
@@ -1201,28 +1312,67 @@ function createElementNode(graph, parentId, element, parentFlow) {
|
|
|
1201
1312
|
clipsContent: false
|
|
1202
1313
|
});
|
|
1203
1314
|
applyElementStyle(graph, node, element, style);
|
|
1204
|
-
const flow =
|
|
1315
|
+
const { flow, richText, lines } = containerFlow(element, display);
|
|
1205
1316
|
if (flow) {
|
|
1206
1317
|
applyContainerLayout(node, element, style, flow);
|
|
1207
1318
|
if (flow === "flex") applyFlexGap(node, style);
|
|
1319
|
+
if (lines) node.layoutWrap = "WRAP";
|
|
1208
1320
|
}
|
|
1209
1321
|
applyFlowSizing(graph, node, style, display, parentFlow);
|
|
1210
|
-
if (
|
|
1322
|
+
if (richText) {
|
|
1211
1323
|
const textStyle = inheritedTextStyle(element, style);
|
|
1212
1324
|
const textDisplay = flow === "inline" ? "inline" : "block";
|
|
1213
1325
|
createRichTextNode(graph, node.id, element, textStyle, textDisplay, flow ?? "none");
|
|
1214
1326
|
return node;
|
|
1215
1327
|
}
|
|
1216
|
-
|
|
1328
|
+
const children = flow === "flex" ? element.children.toSorted(byFlexOrder) : element.children;
|
|
1329
|
+
for (const child of children) createDesignNode(graph, node.id, child, flow ?? "none", inheritedTextStyle(element, style));
|
|
1217
1330
|
return node;
|
|
1218
1331
|
}
|
|
1332
|
+
function flexOrder(node) {
|
|
1333
|
+
return node.type === "element" ? parseCSSNumber(pickStyle(mergedStyle(node), "order")) ?? 0 : 0;
|
|
1334
|
+
}
|
|
1335
|
+
/** Flex items in the order CSS places them: by `order`, then as written. */
|
|
1336
|
+
function byFlexOrder(a, b) {
|
|
1337
|
+
return flexOrder(a) - flexOrder(b);
|
|
1338
|
+
}
|
|
1219
1339
|
function createDesignNode(graph, parentId, node, parentFlow, inheritedStyle = {}) {
|
|
1220
1340
|
if (node.type === "text") {
|
|
1221
1341
|
if (node.text.trim().length === 0) return null;
|
|
1222
1342
|
const display = parentFlow === "inline" ? "inline" : "block";
|
|
1223
1343
|
return createTextNode(graph, parentId, node.text, inheritedStyle, display, parentFlow);
|
|
1224
1344
|
}
|
|
1225
|
-
return createElementNode(graph, parentId, node, parentFlow);
|
|
1345
|
+
return createElementNode(graph, parentId, withFieldText(node), parentFlow);
|
|
1346
|
+
}
|
|
1347
|
+
/** Input types whose value is text a person reads in the field. */
|
|
1348
|
+
const TEXT_INPUT_TYPES = /* @__PURE__ */ new Set([
|
|
1349
|
+
"",
|
|
1350
|
+
"text",
|
|
1351
|
+
"email",
|
|
1352
|
+
"search",
|
|
1353
|
+
"url",
|
|
1354
|
+
"tel",
|
|
1355
|
+
"number",
|
|
1356
|
+
"password"
|
|
1357
|
+
]);
|
|
1358
|
+
/**
|
|
1359
|
+
* A text field with the text a browser draws in it, its value or else its placeholder, as a
|
|
1360
|
+
* child: an `<input>` holds no content of its own. A password shows as dots.
|
|
1361
|
+
*/
|
|
1362
|
+
function withFieldText(element) {
|
|
1363
|
+
if (element.tagName.toLowerCase() !== "input" || element.children.length > 0) return element;
|
|
1364
|
+
const type = Object.hasOwn(element.attrs, "type") ? element.attrs.type.trim().toLowerCase() : "";
|
|
1365
|
+
if (!TEXT_INPUT_TYPES.has(type)) return element;
|
|
1366
|
+
const value = element.attrs.value || element.attrs.placeholder;
|
|
1367
|
+
if (!value) return element;
|
|
1368
|
+
const text = type === "password" && element.attrs.value ? "•".repeat(value.length) : value;
|
|
1369
|
+
return {
|
|
1370
|
+
...element,
|
|
1371
|
+
children: [{
|
|
1372
|
+
type: "text",
|
|
1373
|
+
text
|
|
1374
|
+
}]
|
|
1375
|
+
};
|
|
1226
1376
|
}
|
|
1227
1377
|
function fitPageToChildren(page, graph) {
|
|
1228
1378
|
const children = graph.getChildren(page.id);
|
|
@@ -1231,10 +1381,15 @@ function fitPageToChildren(page, graph) {
|
|
|
1231
1381
|
page.height = Math.max(...children.map((child) => child.y + child.height));
|
|
1232
1382
|
}
|
|
1233
1383
|
function designDocumentToSceneGraph(document, options = {}) {
|
|
1384
|
+
const resolve = options.resolveFontFamily ?? resolveFontFamilyStack;
|
|
1385
|
+
const resolved = {
|
|
1386
|
+
...document,
|
|
1387
|
+
children: document.children.map((child) => withResolvedFontFamilies(child, resolve))
|
|
1388
|
+
};
|
|
1234
1389
|
const graph = new SceneGraph();
|
|
1235
1390
|
const page = graph.getPages().find((node) => node.type === "CANVAS") ?? graph.addPage("DesignDOM");
|
|
1236
1391
|
page.name = options.pageName ?? "DesignDOM";
|
|
1237
|
-
for (const child of
|
|
1392
|
+
for (const child of resolved.children) createDesignNode(graph, page.id, child, "none");
|
|
1238
1393
|
fitPageToChildren(page, graph);
|
|
1239
1394
|
return graph;
|
|
1240
1395
|
}
|
|
@@ -1415,6 +1570,6 @@ async function browserTailwindJSXToSceneGraph(input, candidates, options = {}) {
|
|
|
1415
1570
|
return designDocumentToSceneGraph(await browserTailwindJSXToDesignDocument(input, candidates, options), options);
|
|
1416
1571
|
}
|
|
1417
1572
|
//#endregion
|
|
1418
|
-
export { Fragment, INLINE_TAGS, browserHTMLToDesignDocument, browserHTMLToSceneGraph, browserJSXToDesignDocument, browserJSXToSceneGraph, browserTailwindHTMLToDesignDocument, browserTailwindHTMLToSceneGraph, browserTailwindJSXToDesignDocument, browserTailwindJSXToSceneGraph, createBrowserCSSRuntime, designDocumentToSceneGraph, jsx, jsxToDesignDocumentCore, jsxs, mergeCSSText };
|
|
1573
|
+
export { Fragment, INLINE_TAGS, browserHTMLToDesignDocument, browserHTMLToSceneGraph, browserJSXToDesignDocument, browserJSXToSceneGraph, browserTailwindHTMLToDesignDocument, browserTailwindHTMLToSceneGraph, browserTailwindJSXToDesignDocument, browserTailwindJSXToSceneGraph, createBrowserCSSRuntime, designDocumentToSceneGraph, jsx, jsxToDesignDocumentCore, jsxs, mergeCSSText, resolveFontFamilyStack };
|
|
1419
1574
|
|
|
1420
1575
|
//# sourceMappingURL=browser.js.map
|