@link-foundation/ui-style 0.0.0-stage → 0.1.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/src/resolve.js ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * `resolveStyle(rules, tokens, node, ancestors, env)`: the style of one
3
+ * element in one state and environment, with token references replaced by
4
+ * their values. This is what native renderers (React Native, SwiftUI,
5
+ * Compose) use where the DOM renderer uses CSS.
6
+ *
7
+ * The cascade is the one of CSS for the stylesheet `compileCss` writes:
8
+ * the highest specificity wins, then the later entry (see match.js).
9
+ */
10
+
11
+ import { conditionHolds } from './conditions.js';
12
+ import { styleDiagnostic } from './diagnostics.js';
13
+ import { compareSpecificity, flatten, matches, specificity } from './match.js';
14
+ import { PROPERTIES } from './properties.js';
15
+
16
+ /**
17
+ * @typedef {import('./types.js').StyleRule} StyleRule
18
+ * @typedef {import('./types.js').StyleEnv} StyleEnv
19
+ * @typedef {import('./types.js').TypedValue} TypedValue
20
+ * @typedef {import('./types.js').UiNode} UiNode
21
+ * @typedef {import('./types.js').Diagnostic} Diagnostic
22
+ */
23
+
24
+ /** Whether every state and condition of an entry holds. */
25
+ const applies = (entry, states, env) =>
26
+ entry.states.every((state) => states.has(state)) &&
27
+ entry.at.every(({ kind, conditions }) =>
28
+ conditions.every((condition) => conditionHolds(kind, condition, env))
29
+ );
30
+
31
+ /**
32
+ * A token as `{ type, value }`. `tokens` maps a path to a ui-tokens
33
+ * `ResolvedToken` (`resolveTokens`) or directly to a typed value.
34
+ * @returns {{ type: string|null, value: TypedValue }|null}
35
+ */
36
+ function lookupToken(tokens, path) {
37
+ const entry = tokens?.get(path);
38
+ if (entry === undefined || entry === null) {
39
+ return null;
40
+ }
41
+ return 'path' in entry && 'value' in entry
42
+ ? { type: entry.type, value: entry.value }
43
+ : { type: entry.type, value: entry };
44
+ }
45
+
46
+ /**
47
+ * Replace token references by their values; `null` (with a diagnostic) when
48
+ * a token is missing or of the wrong type.
49
+ * @param {TypedValue} value
50
+ * @param {Record<string, any>} at
51
+ * @param {{ tokens: Map<string, any>, diagnostics: Diagnostic[] | null }} ctx
52
+ * @returns {TypedValue|null}
53
+ */
54
+ function resolveValue(value, at, ctx) {
55
+ const spec = PROPERTIES[at.property];
56
+ switch (value.type) {
57
+ case 'token-ref': {
58
+ const token = lookupToken(ctx.tokens, value.path);
59
+ if (token === null) {
60
+ ctx.diagnostics?.push(
61
+ styleDiagnostic('unknown-token', 'error', {
62
+ ...at,
63
+ token: value.path,
64
+ })
65
+ );
66
+ return null;
67
+ }
68
+ const type = token.type ?? token.value.type;
69
+ if (!spec.tokens.includes(type)) {
70
+ ctx.diagnostics?.push(
71
+ styleDiagnostic('type-mismatch', 'error', {
72
+ ...at,
73
+ token: value.path,
74
+ expected: spec.tokens.join(' or '),
75
+ actual: type,
76
+ })
77
+ );
78
+ return null;
79
+ }
80
+ return token.value;
81
+ }
82
+ case 'fallback': {
83
+ // The first option that resolves, as `var(--a, var(--b, 1px))`.
84
+ for (const option of value.options) {
85
+ const resolved = resolveValue(option, at, {
86
+ ...ctx,
87
+ diagnostics: null,
88
+ });
89
+ if (resolved !== null) {
90
+ return resolved;
91
+ }
92
+ }
93
+ return resolveValue(value.options[value.options.length - 1], at, ctx);
94
+ }
95
+ case 'list': {
96
+ const items = value.items.map((item) => resolveValue(item, at, ctx));
97
+ return items.includes(null)
98
+ ? null
99
+ : { type: 'list', items: /** @type {TypedValue[]} */ (items) };
100
+ }
101
+ default:
102
+ return value;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * The resolved style of one element.
108
+ * @param {StyleRule[]} rules
109
+ * @param {Map<string, any>} tokens ui-tokens `resolveTokens` output, or
110
+ * any map of token path -> typed value
111
+ * @param {UiNode} node
112
+ * @param {UiNode[]} [ancestors] from the root to the parent of `node`
113
+ * @param {StyleEnv} [env]
114
+ * @returns {{ style: Record<string, TypedValue>, sources: Record<string, string>,
115
+ * diagnostics: Diagnostic[] }} `sources` gives the rule id per property
116
+ */
117
+ export function resolveStyle(rules, tokens, node, ancestors = [], env = {}) {
118
+ const states = new Set(env.states ?? []);
119
+ /** @type {Map<string, { spec: number[], decl: any, id: string }>} */
120
+ const winners = new Map();
121
+ for (const entry of flatten(rules)) {
122
+ if (
123
+ entry.declarations.length === 0 ||
124
+ !applies(entry, states, env) ||
125
+ !matches(entry.selector, node, ancestors)
126
+ ) {
127
+ continue;
128
+ }
129
+ const spec = specificity(entry.selector, entry.states.length);
130
+ for (const decl of entry.declarations) {
131
+ const current = winners.get(decl.property);
132
+ // Entries come in cascade order, so an equal specificity wins.
133
+ if (
134
+ current === undefined ||
135
+ compareSpecificity(spec, current.spec) >= 0
136
+ ) {
137
+ winners.set(decl.property, { spec, decl, id: entry.id });
138
+ }
139
+ }
140
+ }
141
+ /** @type {Record<string, TypedValue>} */
142
+ const style = {};
143
+ /** @type {Record<string, string>} */
144
+ const sources = {};
145
+ /** @type {Diagnostic[]} */
146
+ const diagnostics = [];
147
+ for (const [property, { decl, id }] of winners) {
148
+ const value = resolveValue(
149
+ decl.value,
150
+ { rule: id, property },
151
+ { tokens, diagnostics }
152
+ );
153
+ if (value !== null) {
154
+ style[property] = value;
155
+ sources[property] = id;
156
+ }
157
+ }
158
+ return { style, sources, diagnostics };
159
+ }
package/src/types.js ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * JSDoc types of `@link-foundation/ui-style` (the same types as
3
+ * src/index.d.ts).
4
+ *
5
+ * @typedef {import('@link-foundation/ui-core').Diagnostic} Diagnostic
6
+ * @typedef {import('@link-foundation/ui-core').RawValue} RawValue
7
+ * @typedef {import('@link-foundation/ui-core').UiNode} UiNode
8
+ * @typedef {import('@link-foundation/ui-core').values.TypedValue} TypedValue
9
+ *
10
+ * @typedef {'hover'|'focus'|'pressed'|'active'|'disabled'|'selected'|'checked'} StateName
11
+ *
12
+ * @typedef {object} Selector
13
+ * @property {string|null} type the element kind, `(type button)`
14
+ * @property {string|null} id the element id, `(id ok)`
15
+ * @property {Array<{ name: string, value: string }>} props `(variant filled)`
16
+ * @property {Selector[]} within ancestors, `(within (type dialog))`
17
+ *
18
+ * @typedef {object} Decl
19
+ * @property {string} property the style property, `background`
20
+ * @property {TypedValue} value typed; several values are a `list`
21
+ *
22
+ * @typedef {object} Condition
23
+ * @property {string} feature `max-width`, `prefers-color-scheme`, ...
24
+ * @property {TypedValue} value a dimension or an `enum`
25
+ *
26
+ * @typedef {object} Block
27
+ * @property {'state'|'media'|'container'} kind
28
+ * @property {StateName|Condition[]} condition a state name, or the
29
+ * conditions of a media or container block (all must hold)
30
+ * @property {StyleRule} rule the declarations and blocks inside
31
+ *
32
+ * @typedef {object} StyleRule
33
+ * @property {string} id
34
+ * @property {number} order the position of the rule in the input
35
+ * @property {Selector} selector
36
+ * @property {Decl[]} declarations
37
+ * @property {Block[]} blocks
38
+ *
39
+ * @typedef {object} Entry one rule or block flattened for the cascade
40
+ * @property {string} id
41
+ * @property {number} index the position in the flattened (CSS) order
42
+ * @property {Selector} selector
43
+ * @property {StateName[]} states
44
+ * @property {Array<{ kind: 'media'|'container', conditions: Condition[] }>} at
45
+ * @property {Decl[]} declarations
46
+ *
47
+ * @typedef {object} StyleEnv
48
+ * @property {string[]} [states]
49
+ * @property {{ width: number }} [viewport]
50
+ * @property {{ width: number }} [container]
51
+ * @property {'light'|'dark'} [colorScheme]
52
+ * @property {boolean} [reducedMotion]
53
+ */
54
+
55
+ export {};