@pairdraw/dom-css 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,109 @@
1
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
2
+
3
+ import type { DesignStyleDeclaration } from '../types'
4
+ import { pickStyle } from './css-values'
5
+
6
+ /** A child the parent paints out of tree order, by its `z-index`. */
7
+ interface StackedChild {
8
+ id: string
9
+ z: number
10
+ }
11
+
12
+ /** A child as the builder made it, with the style that decides where CSS paints it. */
13
+ export interface PaintedChild {
14
+ layer: SceneNode
15
+ style: DesignStyleDeclaration
16
+ }
17
+
18
+ function isPositioned(style: DesignStyleDeclaration): boolean {
19
+ const position = pickStyle(style, 'position')?.trim()
20
+ return position !== undefined && position !== 'static'
21
+ }
22
+
23
+ function zIndexOf(style: DesignStyleDeclaration): number | null {
24
+ if (!isPositioned(style)) return null
25
+ const value = pickStyle(style, 'z-index')?.trim()
26
+ if (!value || value === 'auto') return null
27
+ const z = Number.parseInt(value, 10)
28
+ return Number.isInteger(z) ? z : null
29
+ }
30
+
31
+ /** Whether a box starts a stacking context of its own, as CSS decides it for the common cases. */
32
+ function formsStackingContext(style: DesignStyleDeclaration): boolean {
33
+ const value = (property: string) => pickStyle(style, property)?.trim()
34
+ const position = value('position')
35
+ const opacity = Number.parseFloat(value('opacity') ?? '1')
36
+ return (
37
+ zIndexOf(style) !== null ||
38
+ position === 'fixed' ||
39
+ position === 'sticky' ||
40
+ opacity < 1 ||
41
+ (value('transform') ?? 'none') !== 'none' ||
42
+ (value('filter') ?? 'none') !== 'none' ||
43
+ value('isolation') === 'isolate' ||
44
+ (value('mix-blend-mode') ?? 'normal') !== 'normal'
45
+ )
46
+ }
47
+
48
+ /**
49
+ * Puts a container's children in the order CSS paints them: negative layers first, lowest
50
+ * first, then the boxes in the flow as they were, then positioned ones, lowest first and in tree
51
+ * order at the same level. A container that is not a stacking context paints its negative layers
52
+ * under its own background, which a layer's fills cannot go under, so its fills move to a layer
53
+ * of their own above those children.
54
+ */
55
+ export function applyStacking(
56
+ graph: SceneGraph,
57
+ parent: SceneNode,
58
+ style: DesignStyleDeclaration,
59
+ parts: readonly PaintedChild[]
60
+ ): void {
61
+ if (parts.length === 0) return
62
+ const children: StackedChild[] = []
63
+ let flowAfter = false
64
+ for (const { layer, style: childStyle } of parts) {
65
+ const movable = layer.layoutPositioning === 'ABSOLUTE' || parent.layoutMode === 'NONE'
66
+ if (!isPositioned(childStyle) || !movable) {
67
+ // A positioned box before a box in the flow is painted out of tree order.
68
+ if (children.some((child) => child.z === 0)) flowAfter = true
69
+ continue
70
+ }
71
+ children.push({ id: layer.id, z: zIndexOf(childStyle) ?? 0 })
72
+ }
73
+ if (!flowAfter && children.every((child) => child.z === 0)) return
74
+
75
+ const below = children.filter((child) => child.z < 0).toSorted((a, b) => a.z - b.z)
76
+ // Sorted stably, so positioned boxes at the same level keep their tree order.
77
+ const above = children.filter((child) => child.z >= 0).toSorted((a, b) => a.z - b.z)
78
+ const moved = new Set(children.map((child) => child.id))
79
+ const order = [
80
+ ...below.map((child) => child.id),
81
+ ...parent.childIds.filter((id) => !moved.has(id)),
82
+ ...above.map((child) => child.id)
83
+ ]
84
+ for (const [index, id] of order.entries()) graph.insertChildAt(id, parent.id, index)
85
+
86
+ if (below.length > 0 && !formsStackingContext(style)) liftBackground(graph, parent, below.length)
87
+ }
88
+
89
+ /** Moves a container's fills into a layer of its own at `index`, its size and corners. */
90
+ function liftBackground(graph: SceneGraph, parent: SceneNode, index: number): void {
91
+ if (!parent.fills.some((fill) => fill.visible)) return
92
+ const background = graph.createNode('RECTANGLE', parent.id, {
93
+ name: 'background',
94
+ x: 0,
95
+ y: 0,
96
+ width: parent.width,
97
+ height: parent.height,
98
+ fills: parent.fills,
99
+ cornerRadius: parent.cornerRadius,
100
+ topLeftRadius: parent.topLeftRadius,
101
+ topRightRadius: parent.topRightRadius,
102
+ bottomRightRadius: parent.bottomRightRadius,
103
+ bottomLeftRadius: parent.bottomLeftRadius,
104
+ independentCorners: parent.independentCorners,
105
+ layoutPositioning: parent.layoutMode === 'NONE' ? 'AUTO' : 'ABSOLUTE'
106
+ })
107
+ graph.insertChildAt(background.id, parent.id, index)
108
+ graph.updateNode(parent.id, { fills: [] })
109
+ }
@@ -7,6 +7,8 @@ import type {
7
7
  DesignNode
8
8
  } from '#dom-css/types'
9
9
 
10
+ import { sandboxedDesignDocument } from './sandbox'
11
+
10
12
  export interface BrowserCSSRuntimeOptions {
11
13
  document?: Document
12
14
  sandbox?: 'shadow-root' | 'iframe'
@@ -16,7 +18,9 @@ const DEFAULT_COMPUTED_PROPERTIES = [
16
18
  'align-items',
17
19
  'aspect-ratio',
18
20
  'background-color',
21
+ 'background-clip',
19
22
  'background-image',
23
+ 'background-origin',
20
24
  'border-bottom-color',
21
25
  'border-bottom-style',
22
26
  'border-bottom-left-radius',
@@ -56,6 +60,7 @@ const DEFAULT_COMPUTED_PROPERTIES = [
56
60
  'max-height',
57
61
  'max-width',
58
62
  'min-height',
63
+ 'isolation',
59
64
  'min-width',
60
65
  'object-fit',
61
66
  'opacity',
@@ -73,7 +78,8 @@ const DEFAULT_COMPUTED_PROPERTIES = [
73
78
  'text-transform',
74
79
  'top',
75
80
  'white-space',
76
- 'width'
81
+ 'width',
82
+ 'z-index'
77
83
  ] as const
78
84
 
79
85
  function resolveBrowserDocument(documentOverride: Document | undefined): Document {
@@ -216,7 +222,7 @@ async function computeStylesInShadowRoot(
216
222
  shadow.append(style)
217
223
 
218
224
  const content = browserDocument.createElement('div')
219
- content.innerHTML = serializeHTML(designDocument)
225
+ content.innerHTML = serializeHTML(sandboxedDesignDocument(designDocument))
220
226
  shadow.append(content)
221
227
  browserDocument.body.append(host)
222
228
 
@@ -252,7 +258,7 @@ async function computeStylesInIframe(
252
258
  iframeDocument.head.append(style)
253
259
 
254
260
  const content = iframeDocument.createElement('div')
255
- content.innerHTML = serializeHTML(designDocument)
261
+ content.innerHTML = serializeHTML(sandboxedDesignDocument(designDocument))
256
262
  iframeDocument.body.append(content)
257
263
 
258
264
  // The sandbox sits offscreen, where WebKit never runs an animation frame of its own; the
@@ -0,0 +1,70 @@
1
+ import type { DesignDocument, DesignElement, DesignNode } from '#dom-css/types'
2
+
3
+ /**
4
+ * What a styling sandbox inserts, with nothing the browser would execute: imported markup reaches
5
+ * the frame as a design document, and an attribute such as `onerror` on an image runs there just as
6
+ * it would on a page. A sandboxed iframe has no `allow-scripts`, so a script that got in is blocked
7
+ * and reported; the shadow root is the app's own document, where it would really run.
8
+ *
9
+ * This is the executable-markup half of the sandbox copy. The network half, which rewrites fetchable
10
+ * addresses so a sandbox never loads a remote resource, walks the same tree: when both are present
11
+ * they are one pass over the nodes, and no pass may keep a `srcdoc`, which this one always drops.
12
+ */
13
+
14
+ /** Elements that hold a document or code of their own, which the sandbox shows as a plain box. */
15
+ const CODE_TAGS: ReadonlySet<string> = new Set(['script', 'style'])
16
+
17
+ /** Elements that load another document; their fallback content stays, the element does not. */
18
+ const EMBEDDED_TAGS: ReadonlySet<string> = new Set([
19
+ 'applet',
20
+ 'embed',
21
+ 'frame',
22
+ 'frameset',
23
+ 'iframe',
24
+ 'object'
25
+ ])
26
+
27
+ /**
28
+ * `value` without the characters a browser ignores inside a URL scheme: controls and space, so
29
+ * `java\tscript:` runs as `javascript:`.
30
+ */
31
+ function withoutSchemeNoise(value: string): string {
32
+ let plain = ''
33
+ for (const char of value) if (char.charCodeAt(0) > 0x20) plain += char
34
+ return plain
35
+ }
36
+
37
+ /** A URL a browser runs as script or reads as a document of its own. */
38
+ const EXECUTABLE_URL = /^(?:javascript|vbscript|data:text\/html)/i
39
+
40
+ /** Whether the browser would run this attribute: an event handler or an executable URL. */
41
+ function executableAttribute(name: string, value: string): boolean {
42
+ const attribute = name.toLowerCase()
43
+ if (attribute.startsWith('on') || attribute === 'srcdoc') return true
44
+ return EXECUTABLE_URL.test(withoutSchemeNoise(value))
45
+ }
46
+
47
+ function sandboxedNode(node: DesignNode): DesignNode {
48
+ if (node.type === 'text') return node
49
+ const tagName = node.tagName.toLowerCase()
50
+ const attrs = Object.fromEntries(
51
+ Object.entries(node.attrs).filter(([name, value]) => !executableAttribute(name, value))
52
+ )
53
+ const element: DesignElement = {
54
+ ...node,
55
+ tagName: CODE_TAGS.has(tagName) || EMBEDDED_TAGS.has(tagName) ? 'div' : node.tagName,
56
+ attrs,
57
+ children: CODE_TAGS.has(tagName) ? [] : node.children.map(sandboxedNode)
58
+ }
59
+ return element
60
+ }
61
+
62
+ /**
63
+ * `document` as the styling sandbox inserts it: the same layers, with every executable attribute,
64
+ * embedded document, and code element replaced by something inert. A replaced element keeps the
65
+ * attributes that decide its box where the browser draws one; a layer's own styles still come from
66
+ * the captured stylesheet, so reading computed styles answers the same question.
67
+ */
68
+ export function sandboxedDesignDocument(document: DesignDocument): DesignDocument {
69
+ return { ...document, children: document.children.map(sandboxedNode) }
70
+ }
@@ -9,9 +9,9 @@ export function collectionVariables(
9
9
  source: Pick<SceneGraph, 'variables' | 'variableCollections'>
10
10
  ): Variable[] {
11
11
  return compact(
12
- [...source.variableCollections.values()].flatMap((collection) =>
13
- collection.variableIds.map((id) => source.variables.get(id))
14
- )
12
+ [...source.variableCollections.values()]
13
+ .filter((collection) => !collection.deleted)
14
+ .flatMap((collection) => collection.variableIds.map((id) => source.variables.get(id)))
15
15
  )
16
16
  }
17
17
 
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ ColorProfile,
2
3
  SceneGraph,
3
4
  Variable,
4
5
  VariableCollection,
@@ -49,7 +50,7 @@ type ModeScope = {
49
50
  declarations: Declaration[]
50
51
  }
51
52
 
52
- type TokenSource = Pick<SceneGraph, 'variables' | 'variableCollections'>
53
+ type TokenSource = Pick<SceneGraph, 'variables' | 'variableCollections' | 'documentColorSpace'>
53
54
 
54
55
  function isAtRuleCondition(condition: string): boolean {
55
56
  return condition.trim().startsWith('@')
@@ -110,7 +111,8 @@ function modeValue(
110
111
  value: VariableValue | undefined,
111
112
  modeId: string,
112
113
  names: ReadonlyMap<string, string>,
113
- variables: ReadonlyMap<string, Variable>
114
+ variables: ReadonlyMap<string, Variable>,
115
+ profile: ColorProfile
114
116
  ): string | { issue: string } {
115
117
  const expression = variable.expressions?.[modeId]
116
118
  if (expression) return expression.css
@@ -125,7 +127,7 @@ function modeValue(
125
127
  const target = names.get(value.aliasId)
126
128
  return target ? `var(--${target})` : { issue: 'aliases a variable that does not exist' }
127
129
  }
128
- if (variable.type === 'COLOR' && typeof value === 'object') return cssColor(value)
130
+ if (variable.type === 'COLOR' && typeof value === 'object') return cssColor(value, profile)
129
131
  if (variable.type === 'FLOAT' && typeof value === 'number')
130
132
  return tokenNumberToCSS(value, variableUnit(variable))
131
133
  if (variable.type === 'STRING' && typeof value === 'string')
@@ -219,7 +221,14 @@ export function buildTokenStylesheet(
219
221
  value: VariableValue | undefined
220
222
  ): Declaration | undefined {
221
223
  const name = names.get(variable.id) ?? variable.id
222
- const css = modeValue(variable, value, modeId, names, source.variables)
224
+ const css = modeValue(
225
+ variable,
226
+ value,
227
+ modeId,
228
+ names,
229
+ source.variables,
230
+ source.documentColorSpace
231
+ )
223
232
  if (typeof css !== 'string') {
224
233
  issues.push({ message: `${variable.name} ${css.issue}`, variableId: variable.id, modeId })
225
234
  return undefined