@pairdraw/dom-css 0.19.1 → 0.19.2

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/export.d.ts CHANGED
@@ -454,6 +454,13 @@ interface BooleanModel {
454
454
  /** The value as the document's instance draws it. */
455
455
  designed: boolean;
456
456
  }
457
+ /** The variant property a tabs' choice binds, its options, and the one the instance shows. */
458
+ interface ChoiceControlModel {
459
+ definition: ComponentPropertyDefinition;
460
+ options: string[];
461
+ /** The option's index as the document's instance draws it, 0 when none does. */
462
+ designed: number;
463
+ }
457
464
  /** The variant property that draws a control's interaction states. */
458
465
  interface StatesModel {
459
466
  name: string;
@@ -470,6 +477,8 @@ interface ControlModel {
470
477
  kind: Behaviour['kind'];
471
478
  behaviour: Behaviour;
472
479
  booleans: Record<string, BooleanModel>;
480
+ /** For tabs bound to a variant property, the tabs the triggers choose among. */
481
+ choice: ChoiceControlModel | null;
473
482
  states: StatesModel | null;
474
483
  /** Each bound part's slot frame, by part id, as a layer path below the root. */
475
484
  parts: Record<string, string>;
@@ -3,6 +3,12 @@ import { SceneGraph } from "@pairdraw/scene-graph";
3
3
  //#region src/import/scene-graph.d.ts
4
4
  interface DesignDocumentToSceneGraphOptions {
5
5
  pageName?: string;
6
+ /**
7
+ * The family a CSS `font-family` stack should draw, given the stack's families; null keeps it.
8
+ * Hosts with a font service pass one that skips faces the document cannot draw; without it the
9
+ * first concrete family wins and a generic keyword maps to a concrete face of its class.
10
+ */
11
+ resolveFontFamily?: (value: string) => string | null;
6
12
  }
7
13
  declare function designDocumentToSceneGraph(document: DesignDocument, options?: DesignDocumentToSceneGraphOptions): SceneGraph;
8
14
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/dom-css",
3
- "version": "0.19.1",
3
+ "version": "0.19.2",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -11,7 +11,7 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "dependencies": {
13
13
  "@acemir/cssom": "^0.9.31",
14
- "@pairdraw/emit": "^0.19.1",
14
+ "@pairdraw/emit": "^0.19.2",
15
15
  "css-tree": "^3.2.1",
16
16
  "cssesc": "^3.0.0",
17
17
  "dedent": "^1.7.2",
@@ -24,7 +24,7 @@
24
24
  "twirlwind": "^0.4.1"
25
25
  },
26
26
  "peerDependencies": {
27
- "@pairdraw/scene-graph": "^0.19.1"
27
+ "@pairdraw/scene-graph": "^0.19.2"
28
28
  },
29
29
  "exports": {
30
30
  ".": {
@@ -13,7 +13,7 @@ import {
13
13
  } from '@pairdraw/scene-graph/behaviours'
14
14
  import { findComponentPropertyTargets } from '@pairdraw/scene-graph/components'
15
15
  import { instanceMainComponent } from '@pairdraw/scene-graph/instances'
16
- import { instanceSlotFrames, slotPropertyId } from '@pairdraw/scene-graph/slots'
16
+ import { slotPropertyId } from '@pairdraw/scene-graph/slots'
17
17
 
18
18
  /** A boolean value of a control and the property that draws it. */
19
19
  export interface BooleanModel {
@@ -24,6 +24,14 @@ export interface BooleanModel {
24
24
  designed: boolean
25
25
  }
26
26
 
27
+ /** The variant property a tabs' choice binds, its options, and the one the instance shows. */
28
+ export interface ChoiceControlModel {
29
+ definition: ComponentPropertyDefinition
30
+ options: string[]
31
+ /** The option's index as the document's instance draws it, 0 when none does. */
32
+ designed: number
33
+ }
34
+
27
35
  /** The variant property that draws a control's interaction states. */
28
36
  export interface StatesModel {
29
37
  name: string
@@ -41,6 +49,8 @@ export interface ControlModel {
41
49
  kind: Behaviour['kind']
42
50
  behaviour: Behaviour
43
51
  booleans: Record<string, BooleanModel>
52
+ /** For tabs bound to a variant property, the tabs the triggers choose among. */
53
+ choice: ChoiceControlModel | null
44
54
  states: StatesModel | null
45
55
  /** Each bound part's slot frame, by part id, as a layer path below the root. */
46
56
  parts: Record<string, string>
@@ -97,6 +107,24 @@ function statesModel(
97
107
  }
98
108
  }
99
109
 
110
+ /**
111
+ * The frames an instance binds to slot properties, which its parts are. A slot may sit inside
112
+ * another, as a slider's range in its track: Figma keeps both in the component and makes the
113
+ * inner one part of the outer one's content in an instance, so the search goes through slots
114
+ * but not into nested instances, which are controls of their own.
115
+ */
116
+ function partFrames(graph: SceneGraph, instance: SceneNode): SceneNode[] {
117
+ const frames: SceneNode[] = []
118
+ const visit = (node: SceneNode): void => {
119
+ for (const child of graph.getChildren(node.id)) {
120
+ if (slotPropertyId(child)) frames.push(child)
121
+ if (child.type !== 'INSTANCE') visit(child)
122
+ }
123
+ }
124
+ visit(instance)
125
+ return frames
126
+ }
127
+
100
128
  function controlModel(graph: SceneGraph, rootId: string, instance: SceneNode): ControlModel | null {
101
129
  const component = instanceMainComponent(graph, instance)
102
130
  const owner = component && behaviourOwner(graph, component)
@@ -116,7 +144,9 @@ function controlModel(graph: SceneGraph, rootId: string, instance: SceneNode): C
116
144
  designed: designedBoolean(graph, instance, definition, binding.on)
117
145
  }
118
146
  }
119
- const frames = instanceSlotFrames(graph, instance)
147
+ const choice = choiceModel(behaviour, properties, component)
148
+
149
+ const frames = partFrames(graph, instance)
120
150
  const parts = Object.fromEntries(
121
151
  Object.entries(behaviour.parts).flatMap(([partId, propertyId]) => {
122
152
  const frame = frames.find((item) => slotPropertyId(item) === propertyId)
@@ -160,6 +190,7 @@ function controlModel(graph: SceneGraph, rootId: string, instance: SceneNode): C
160
190
  kind: behaviour.kind,
161
191
  behaviour,
162
192
  booleans,
193
+ choice,
163
194
  states: statesModel(graph, instance, owner, behaviour),
164
195
  parts,
165
196
  texts,
@@ -170,6 +201,22 @@ function controlModel(graph: SceneGraph, rootId: string, instance: SceneNode): C
170
201
  }
171
202
  }
172
203
 
204
+ /** The variant property a tabs' choice binds, its options, and the drawn option's index. */
205
+ function choiceModel(
206
+ behaviour: Behaviour,
207
+ properties: readonly ComponentPropertyDefinition[],
208
+ component: SceneNode | undefined
209
+ ): ChoiceControlModel | null {
210
+ const binding = behaviour.kind === 'tabs' ? booleanBinding(behaviour, 'value') : undefined
211
+ const definition = properties.find(
212
+ (item) => item.id === binding?.propertyId && item.type === 'VARIANT'
213
+ )
214
+ const options = definition?.variantOptions ?? []
215
+ if (!definition || options.length === 0) return null
216
+ const designed = component?.componentPropertyValues[definition.name]
217
+ return { definition, options, designed: Math.max(0, options.indexOf(designed ?? '')) }
218
+ }
219
+
173
220
  /**
174
221
  * The controls below a root layer, by layer path, outermost first. Items of a group are listed
175
222
  * both in the group's `items` and on their own, since each keeps its own state. Preview runs
@@ -1,3 +1,4 @@
1
+ import { validFontSizeClass } from '#dom-css/export/font-size-class'
1
2
  import { splitWhitespace } from '#dom-css/export/html'
2
3
  import type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'
3
4
  import { compact } from 'es-toolkit/array'
@@ -39,7 +40,9 @@ function utilities(style: DesignStyleDeclaration, options: StateTailwindOptions)
39
40
  .map(([property, value]) => `${property}: ${value}`)
40
41
  .join('; ')
41
42
  return css
42
- ? splitWhitespace(twirl(css, { theme: { variables: options.themeVariables ?? [] } }))
43
+ ? splitWhitespace(
44
+ validFontSizeClass(twirl(css, { theme: { variables: options.themeVariables ?? [] } }), css)
45
+ )
43
46
  : []
44
47
  }
45
48
 
package/src/browser.ts CHANGED
@@ -2,6 +2,7 @@ import type { SceneGraph } from '@pairdraw/scene-graph'
2
2
 
3
3
  import { mergeCSSText } from './import/css-text'
4
4
  import { jsxToDesignDocumentCore, type JSXChild } from './import/jsx/core'
5
+ export { resolveFontFamilyStack, type FontStackOptions } from './import/fonts'
5
6
  import { designDocumentToSceneGraph, type ToSceneGraphOptions } from './import/scene-graph'
6
7
  import type { CompileTailwindCSSOptions } from './import/tailwind'
7
8
  import { createBrowserCSSRuntime, type BrowserCSSRuntimeOptions } from './runtime/browser/runtime'
@@ -7,10 +7,11 @@ import type { StateElement, StateStyles } from '#dom-css/behaviours/states/types
7
7
  import { uniq } from 'es-toolkit/array'
8
8
  import { camelCase } from 'es-toolkit/string'
9
9
 
10
- import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
10
+ import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@pairdraw/scene-graph'
11
11
  import {
12
12
  behaviourContract,
13
13
  behaviourProperties,
14
+ booleanBinding,
14
15
  layerPath,
15
16
  readBehaviour,
16
17
  textBinding,
@@ -105,6 +106,8 @@ export type ComponentBinding =
105
106
  /** A group's item: the value it stands for, which the group chooses among. */
106
107
  | { type: 'value' }
107
108
  | { type: 'prop'; prop: VariantProp; attribute: string }
109
+ /** The model's choice on the variant property it draws, as the attribute that picks it. */
110
+ | { type: 'modelProp'; name: string; attribute: string }
108
111
 
109
112
  /** A layer of the generated markup, before a framework picks its element or component. */
110
113
  export interface ComponentElement {
@@ -159,6 +162,18 @@ export type ComponentNode =
159
162
  | ComponentReference
160
163
  | IconReference
161
164
 
165
+ /**
166
+ * Whether a field's markup always draws its input, which then takes the caller's attributes. A
167
+ * field whose text is not bound yet has none, and an input inside a slot is replaced when the
168
+ * caller fills the slot; the root takes the attributes then.
169
+ */
170
+ export function drawsInput(node: ComponentElement): boolean {
171
+ return node.children.some(
172
+ (child) =>
173
+ child.type === 'input' || (child.type === 'element' && !child.slot && drawsInput(child))
174
+ )
175
+ }
176
+
162
177
  /** One component generated from a component set with a behaviour. */
163
178
  export interface ComponentModel {
164
179
  /** The component's identifier and file name. */
@@ -283,6 +298,18 @@ export interface ComponentModelOptions extends Pick<SceneGraphToDesignOptions, '
283
298
  itemOf?: GroupKind
284
299
  }
285
300
 
301
+ /** The variant props a component takes, without the property its choice draws. */
302
+ function choiceProps(
303
+ graph: SceneGraph,
304
+ set: SceneNode,
305
+ args: BehaviourArgs,
306
+ taken: Set<string>,
307
+ choice: ComponentPropertyDefinition | undefined
308
+ ): VariantProp[] {
309
+ taken.add(choice?.name ?? '')
310
+ return variantProps(graph, set, args, taken).filter((prop) => prop.property !== choice?.name)
311
+ }
312
+
286
313
  /** Each layer's behaviour part: the root, and the slot frames that draw the others. */
287
314
  function behaviourParts(
288
315
  graph: SceneGraph,
@@ -340,10 +367,14 @@ function rootBindings(
340
367
  model: string | null,
341
368
  item: boolean,
342
369
  disabled: boolean,
343
- props: readonly VariantProp[]
370
+ props: readonly VariantProp[],
371
+ choice?: { name: string; attribute: string }
344
372
  ): ComponentBinding[] {
345
373
  return [
346
374
  ...(model ? [{ type: 'model' as const, name: model }] : []),
375
+ ...(model && choice
376
+ ? [{ type: 'modelProp' as const, name: model, attribute: choice.attribute }]
377
+ : []),
347
378
  ...(item ? [{ type: 'value' as const }] : []),
348
379
  ...(disabled ? [{ type: 'disabled' as const }] : []),
349
380
  ...props.map((prop) => ({
@@ -432,14 +463,21 @@ function drawnParts(
432
463
  const parts = behaviour
433
464
  ? behaviourParts(graph, set, behaviour, root)
434
465
  : new Map<StateElement, string>([[root, 'root']])
435
- const tabs = behaviour?.kind === 'tabs' ? tabParts(parts) : null
466
+ const choiceBinding = behaviour?.kind === 'tabs' ? booleanBinding(behaviour, 'value') : undefined
467
+ const choiceProperty = choiceBinding
468
+ ? behaviourProperties(graph, set).find(
469
+ (item) => item.id === choiceBinding.propertyId && item.type === 'VARIANT'
470
+ )
471
+ : undefined
472
+ const tabs =
473
+ behaviour?.kind === 'tabs' ? tabParts(parts, choiceProperty?.variantOptions ?? []) : null
436
474
  const repeated = tabs?.repeated ?? new Map<StateElement, RepeatedPart>()
437
475
  activeTriggers(repeated)
438
476
  resetButtons(kind, parts, repeated)
439
477
  freePlacedParts(kind, parts)
440
478
  blockRoot(kind, root)
441
479
  borderBoxes(root)
442
- return { parts, tabs, repeated }
480
+ return { parts, tabs, repeated, choiceProperty }
443
481
  }
444
482
 
445
483
  /** The number or text the component holds, and the text property a field's input shows. */
@@ -474,7 +512,13 @@ export function componentModel(
474
512
  if (!kind || !styles) return null
475
513
  const name = options.name ?? identifierName(set.name, 'Component')
476
514
 
477
- const { parts, tabs, repeated } = drawnParts(graph, set, behaviour, kind, styles.root)
515
+ const { parts, tabs, repeated, choiceProperty } = drawnParts(
516
+ graph,
517
+ set,
518
+ behaviour,
519
+ kind,
520
+ styles.root
521
+ )
478
522
 
479
523
  // A group's items first, so its item component is used for them rather than a standalone one.
480
524
  const variantIds = [styles.restId, ...ownerVariants(graph, set).map((variant) => variant.id)]
@@ -499,7 +543,7 @@ export function componentModel(
499
543
  const { range, text, inputProperty } = valueModels(graph, set, kind, behaviour, args)
500
544
  const model = modelName(args, !!options.itemOf, !!(choice ?? range ?? text))
501
545
  const taken = new Set([...(model ? [model] : []), 'disabled', 'value'])
502
- const props = variantProps(graph, set, args, taken)
546
+ const props = choiceProps(graph, set, args, taken, choiceProperty)
503
547
  const disabled = drawsDisabled(args)
504
548
  const used = usedLayers(graph, styles.root, variantIds, items?.used, options.references)
505
549
  const elements = allElements(styles.root)
@@ -526,7 +570,16 @@ export function componentModel(
526
570
  shaders: shaderLayers(graph, styles.restId, elements),
527
571
  layerOf: (element) => restLayerOf(graph, styles, element)
528
572
  },
529
- rootBindings(model, !!options.itemOf, disabled, props)
573
+ rootBindings(
574
+ model,
575
+ !!options.itemOf,
576
+ disabled,
577
+ props,
578
+ choiceProperty && {
579
+ name: choiceProperty.name,
580
+ attribute: propAttribute(choiceProperty.name)
581
+ }
582
+ )
530
583
  ),
531
584
  model,
532
585
  choice,
@@ -191,6 +191,10 @@ function bindingAttributes(
191
191
  return node.bindings.flatMap((binding) => {
192
192
  if (binding.type === 'prop')
193
193
  return [jsx.attribute(binding.attribute, jsx.container(es.identifier(binding.prop.name)))]
194
+ if (binding.type === 'modelProp')
195
+ return [
196
+ jsx.attribute(binding.attribute, jsx.container(es.parseExpression(`props.${binding.name}`)))
197
+ ]
194
198
  // Radix sets `data-disabled` on its own roots; a native root needs it for the styles.
195
199
  if (binding.type === 'disabled' && native)
196
200
  return [jsx.attribute('data-disabled', jsx.container(disabledFlag(kind)))]
@@ -44,13 +44,18 @@ export function slugValues(labels: readonly string[]): string[] {
44
44
  * Tabs' triggers, the layers in its list, and its panels, the layers in its panels slot, each
45
45
  * with the value of the tab it belongs to, matched by position. The tabs start on the first.
46
46
  */
47
- export function tabParts(parts: ReadonlyMap<StateElement, string>): {
47
+ export function tabParts(
48
+ parts: ReadonlyMap<StateElement, string>,
49
+ variantOptions: readonly string[] = []
50
+ ): {
48
51
  repeated: Map<StateElement, RepeatedPart>
49
52
  choice: ChoiceModel | null
50
53
  } {
51
54
  const partElement = (id: string) => [...parts].find(([, part]) => part === id)?.[0]
52
55
  const triggers = elementsOf(partElement('list'))
53
- const values = slugValues(triggers.map(textOf))
56
+ const drawn = slugValues(triggers.map(textOf))
57
+ // A choice bound to a variant property names each trigger by that property's option.
58
+ const values = variantOptions.length === triggers.length ? [...variantOptions] : drawn
54
59
  const repeated = new Map<StateElement, RepeatedPart>()
55
60
  for (const [index, trigger] of triggers.entries())
56
61
  repeated.set(trigger, { part: 'trigger', value: values[index] ?? String(index) })
@@ -19,13 +19,14 @@ import {
19
19
  type IconImport,
20
20
  type IconPackage
21
21
  } from './icons'
22
- import type {
23
- ComponentBinding,
24
- ComponentElement,
25
- ComponentGenerator,
26
- ComponentModel,
27
- ComponentNode,
28
- GeneratedKind
22
+ import {
23
+ drawsInput,
24
+ type ComponentBinding,
25
+ type ComponentElement,
26
+ type ComponentGenerator,
27
+ type ComponentModel,
28
+ type ComponentNode,
29
+ type GeneratedKind
29
30
  } from './model'
30
31
  import type { ComponentReference, IconReference } from './references'
31
32
  import {
@@ -93,9 +94,26 @@ const REKA: Record<
93
94
  plain: { parts: {} }
94
95
  }
95
96
 
96
- /** Kinds whose two-way value is their input's, which binds it rather than the root. */
97
+ /**
98
+ * Kinds whose two-way value is their input's, which binds it rather than the root. Their input
99
+ * takes the caller's attributes too, such as `name` or `required`, and the root only `class`,
100
+ * as the React components spread the caller's props on the input.
101
+ */
97
102
  const INPUT_MODEL: ReadonlySet<GeneratedKind> = new Set(['textField', 'textarea'])
98
103
 
104
+ /** Whether the caller's attributes go to the field's input: it is a field, and draws one. */
105
+ const attrsToInput = (component: ComponentModel) =>
106
+ INPUT_MODEL.has(component.kind) && drawsInput(component.tree)
107
+
108
+ /** The caller's attributes but `class`, which the root takes, for a field's input. */
109
+ const INPUT_ATTRS = es.parseExpression('{ ...$attrs, class: undefined }')
110
+
111
+ /** The caller's `class`, which a field's root takes since its attributes go to the input. */
112
+ const ROOT_CLASS = es.parseExpression('$attrs.class')
113
+
114
+ /** The caller's attributes reach the input rather than falling through to the root. */
115
+ const NO_ATTRS_FALLTHROUGH = es.parseModule('defineOptions({ inheritAttrs: false })')
116
+
99
117
  /** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */
100
118
  const ROOT_ATTRIBUTES: Partial<Record<GeneratedKind, vue.VueAttribute[]>> = {
101
119
  toggleGroup: [vue.attribute('type', 'single')],
@@ -124,6 +142,7 @@ function bindingAttributes(
124
142
  return [vue.model(identifier(bound), REKA[kind].model === 'open' ? 'open' : undefined)]
125
143
  }
126
144
  if (binding.type === 'prop') return [vue.bound(binding.attribute, identifier(binding.prop.name))]
145
+ if (binding.type === 'modelProp') return [vue.bound(binding.attribute, identifier(binding.name))]
127
146
  if (binding.type === 'value') return [vue.bound('value', identifier('value'))]
128
147
  // Reka sets `data-disabled` on its own roots; a native root needs it for the state styles.
129
148
  return [
@@ -171,6 +190,8 @@ function inputNode(className: string, uses: TemplateUses): vue.VueElement {
171
190
  vue.attribute('class', uses.classOf(className)),
172
191
  ...(component.model ? [vue.model(identifier(component.model))] : []),
173
192
  ...(placeholder ? [vue.attribute('placeholder', placeholder)] : []),
193
+ // The caller's attributes, such as `name` or a placeholder of its own, after the design's.
194
+ vue.spread(INPUT_ATTRS),
174
195
  ...(component.disabled ? [vue.bound('disabled', identifier('disabled'))] : [])
175
196
  ])
176
197
  }
@@ -257,6 +278,7 @@ function elementAttributes(
257
278
  vue.attribute(name, value)
258
279
  ),
259
280
  vue.attribute('class', compact([node.attrs.class, uses.classOf(node.className)]).join(' ')),
281
+ ...(root && attrsToInput(uses.component) ? [vue.bound('class', ROOT_CLASS)] : []),
260
282
  ...(node.value === undefined ? [] : [vue.attribute('value', node.value)]),
261
283
  ...node.bindings.flatMap((binding) => bindingAttributes(binding, uses, native))
262
284
  ]
@@ -447,10 +469,17 @@ function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {
447
469
  const refs = uses.models.flatMap(
448
470
  (item) => es.fill(MODEL_REF, { $name: identifier(item.name) }).body
449
471
  )
472
+ const options = attrsToInput(component) ? NO_ATTRS_FALLTHROUGH.body : []
450
473
  return {
451
474
  type: 'Program',
452
475
  sourceType: 'module',
453
- body: [...scriptImports(uses), ...props, ...modelDeclaration(component, uses), ...refs]
476
+ body: [
477
+ ...scriptImports(uses),
478
+ ...options,
479
+ ...props,
480
+ ...modelDeclaration(component, uses),
481
+ ...refs
482
+ ]
454
483
  }
455
484
  }
456
485
 
@@ -0,0 +1,13 @@
1
+ /**
2
+ * twirlwind names a literal font size that is a multiple of four `text-<px / 4>` (40px becomes
3
+ * text-10), a class Tailwind never generates. Rewrite that one token to the arbitrary value,
4
+ * the spelling Tailwind compiles, leaving named steps and token-bound sizes alone.
5
+ *
6
+ * `css` is the declaration string the class list was generated from.
7
+ */
8
+ export function validFontSizeClass(className: string, css: string): string {
9
+ const fontSize = /(?:^|;)\s*font-size:\s*(\d+(?:\.\d+)?)px/.exec(css)?.[1]
10
+ const numeric = className.match(/(?:^|\s)text-(\d+)(?=\s|$)/)
11
+ if (!fontSize || !numeric || Number(numeric[1]) * 4 !== Number(fontSize)) return className
12
+ return className.replace(numeric[0], numeric[0].replace(/text-\d+/, `text-[${fontSize}px]`))
13
+ }
@@ -2,6 +2,7 @@ import { escapeAttribute, escapeText } from 'entities'
2
2
  import { twirl } from 'twirlwind'
3
3
 
4
4
  import type { DesignDocument, DesignElement, DesignNode, DesignText } from '../types'
5
+ import { validFontSizeClass } from './font-size-class'
5
6
 
6
7
  export interface SerializeHTMLOptions {
7
8
  style?: 'inline' | 'tailwind'
@@ -65,7 +66,10 @@ export function serializeTailwindClasses(
65
66
  ): string | undefined {
66
67
  const style = serializeStyle(node)
67
68
  if (!style) return undefined
68
- const className = twirl(style, { theme: { variables: themeVariables } })
69
+ const className = validFontSizeClass(
70
+ twirl(style, { theme: { variables: themeVariables } }),
71
+ style
72
+ )
69
73
  return className.length > 0 ? className : undefined
70
74
  }
71
75
 
@@ -296,6 +296,30 @@ function addBoxSizing(style: DesignStyleDeclaration): void {
296
296
  if (sized && boxed) style['box-sizing'] = 'border-box'
297
297
  }
298
298
 
299
+ /**
300
+ * The CSS keyword for a blend mode, where one paints the same mode. Linear burn would need
301
+ * `plus-darker`, which Chrome, Edge, and Firefox do not implement, so it gains no keyword and
302
+ * exports flat. A normal layer or an unscoped pass-through needs none either.
303
+ */
304
+ const CSS_BLEND_MODES: Partial<Record<SceneNode['blendMode'], string>> = {
305
+ DARKEN: 'darken',
306
+ MULTIPLY: 'multiply',
307
+ COLOR_BURN: 'color-burn',
308
+ LIGHTEN: 'lighten',
309
+ SCREEN: 'screen',
310
+ LINEAR_DODGE: 'plus-lighter',
311
+ COLOR_DODGE: 'color-dodge',
312
+ OVERLAY: 'overlay',
313
+ SOFT_LIGHT: 'soft-light',
314
+ HARD_LIGHT: 'hard-light',
315
+ DIFFERENCE: 'difference',
316
+ EXCLUSION: 'exclusion',
317
+ HUE: 'hue',
318
+ SATURATION: 'saturation',
319
+ COLOR: 'color',
320
+ LUMINOSITY: 'luminosity'
321
+ }
322
+
299
323
  function styleFromSceneNode(
300
324
  node: SceneNode,
301
325
  parent: SceneNode | undefined,
@@ -313,6 +337,8 @@ function styleFromSceneNode(
313
337
  addStroke(style, node, css)
314
338
  Object.assign(style, effectsToCSS(node.effects))
315
339
  if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))
340
+ const blend = CSS_BLEND_MODES[node.blendMode]
341
+ if (blend) style['mix-blend-mode'] = blend
316
342
  addCornerRadii(style, node, css)
317
343
  if (node.clipsContent) style.overflow = 'hidden'
318
344
  const alignSelf = alignToCSS(node.layoutAlignSelf)
@@ -203,6 +203,17 @@ function hasDefiniteWidth(graph: SceneGraph, node: SceneNode): boolean {
203
203
  return layoutSizing(graph, node, 'HORIZONTAL') !== 'HUG'
204
204
  }
205
205
 
206
+ /**
207
+ * Whether CSS keeps the text on its lines however narrow its box, and the text starts at the
208
+ * box's start edge, so its own width places it as the box does. A box narrower than the text
209
+ * clips it rather than breaking it, which wrapping text measured in other fonts would do.
210
+ */
211
+ function staysOnItsLines(style: DesignStyleDeclaration): boolean {
212
+ const whiteSpace = pickStyle(style, 'white-space')?.trim()
213
+ const align = pickStyle(style, 'text-align')?.trim() ?? 'start'
214
+ return (whiteSpace === 'nowrap' || whiteSpace === 'pre') && ['start', 'left'].includes(align)
215
+ }
216
+
206
217
  /**
207
218
  * Text wraps where its width is fixed or fills a parent with a width of its own, and hugs its
208
219
  * content otherwise. It is measured when the document is laid out.
@@ -243,6 +254,10 @@ export function applyFlowSizing(
243
254
  autoLayoutSizingFields(node.layoutMode, own(size.fixedWidth), own(size.fixedHeight))
244
255
  )
245
256
  }
257
+ if (node.type === 'TEXT' && staysOnItsLines(style)) {
258
+ applyTextSizing(graph, node, { fixedWidth: false, fixedHeight: size.fixedHeight })
259
+ return
260
+ }
246
261
  applyParentFill(graph, node, style, display, parentFlow, size)
247
262
  if (node.type === 'TEXT') applyTextSizing(graph, node, size)
248
263
  }
@@ -0,0 +1,59 @@
1
+ import { DEFAULT_FONT_FAMILY } from '@pairdraw/scene-graph/constants'
2
+ import { parseCSSFontFamilies } from '@pairdraw/scene-graph/css'
3
+
4
+ /** CSS generic families, by the concrete face class they stand for. */
5
+ const GENERIC_FAMILIES: Record<string, 'sans-serif' | 'serif' | 'monospace' | undefined> = {
6
+ 'sans-serif': 'sans-serif',
7
+ 'ui-sans-serif': 'sans-serif',
8
+ 'system-ui': 'sans-serif',
9
+ '-apple-system': 'sans-serif',
10
+ blinkmacsystemfont: 'sans-serif',
11
+ serif: 'serif',
12
+ 'ui-serif': 'serif',
13
+ monospace: 'monospace',
14
+ 'ui-monospace': 'monospace'
15
+ }
16
+
17
+ /** Known system faces of each class, best first. The app bundles Inter for sans-serif. */
18
+ const DEFAULT_FAMILIES = {
19
+ 'sans-serif': [DEFAULT_FONT_FAMILY],
20
+ serif: ['Georgia', 'Times New Roman', 'Times'],
21
+ monospace: ['Menlo', 'SF Mono', 'Consolas', 'Courier New']
22
+ } as const satisfies Record<'sans-serif' | 'serif' | 'monospace', readonly string[]>
23
+
24
+ export interface FontStackOptions {
25
+ /**
26
+ * Whether the document can draw a family, such as the font service answering. Without it every
27
+ * concrete family is taken as available, as a headless import has no faces to ask.
28
+ */
29
+ isAvailable?: (family: string) => boolean
30
+ }
31
+
32
+ function defaultFamily(
33
+ kind: 'sans-serif' | 'serif' | 'monospace',
34
+ options: FontStackOptions
35
+ ): string {
36
+ const candidates = DEFAULT_FAMILIES[kind]
37
+ return (
38
+ (options.isAvailable ? candidates.find((family) => options.isAvailable?.(family)) : null) ??
39
+ candidates[0]
40
+ )
41
+ }
42
+
43
+ /**
44
+ * The family a CSS `font-family` stack asks a document to draw: the first concrete family the
45
+ * font service can provide; a generic keyword maps to a concrete face of its class. Null when the
46
+ * list has no family.
47
+ */
48
+ export function resolveFontFamilyStack(
49
+ value: string | undefined,
50
+ options: FontStackOptions = {}
51
+ ): string | null {
52
+ for (const family of parseCSSFontFamilies(value)) {
53
+ const generic = GENERIC_FAMILIES[family.trim().toLowerCase()]
54
+ if (generic) return defaultFamily(generic, options)
55
+ if (options.isAvailable && !options.isAvailable(family)) continue
56
+ return family
57
+ }
58
+ return null
59
+ }