@link-foundation/ui-style 0.0.0-stage → 0.0.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/LICENSE +24 -0
- package/README.md +255 -2
- package/package.json +49 -4
- package/src/clip-path.js +98 -0
- package/src/conditions.js +167 -0
- package/src/css.js +245 -0
- package/src/diagnostics.js +48 -0
- package/src/index.d.ts +185 -0
- package/src/index.js +31 -0
- package/src/match.js +114 -0
- package/src/materials.js +24 -0
- package/src/properties.js +291 -0
- package/src/read.js +313 -0
- package/src/resolve.js +159 -0
- package/src/types.js +55 -0
package/src/css.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `compileCss(rules, options)`: style rules as a CSS stylesheet for the DOM
|
|
3
|
+
* renderer, whose elements are `ui-KIND` with the element properties as
|
|
4
|
+
* attributes (`ui-button[variant='filled']`).
|
|
5
|
+
*
|
|
6
|
+
* Token references become `var(--color-primary)` (the naming rule of
|
|
7
|
+
* ui-tokens `cssVariable`), so a theme switch only swaps custom properties.
|
|
8
|
+
* Every identifier is escaped as by `CSS.escape` and every attribute value
|
|
9
|
+
* is a quoted, escaped CSS string. Declaration values are typed values
|
|
10
|
+
* written by ui-core `values.toCss`: no free text, and never `url(`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { cssVariable } from '@link-foundation/ui-tokens';
|
|
14
|
+
import { STATE_CSS, conditionsCss } from './conditions.js';
|
|
15
|
+
import { flatten } from './match.js';
|
|
16
|
+
import { materialCss } from './materials.js';
|
|
17
|
+
import { PROPERTIES, declarationCss } from './properties.js';
|
|
18
|
+
|
|
19
|
+
/** A theme boundary can itself be the selected control. */
|
|
20
|
+
function scopedSelector(selector, scope, atRoot) {
|
|
21
|
+
// The enclosing @scope bounds descendants, including ancestors at its root.
|
|
22
|
+
if (scope === ':scope') {
|
|
23
|
+
return `${selector}, ${atRoot}`;
|
|
24
|
+
}
|
|
25
|
+
return scope ? `${scope} ${selector}, ${atRoot}` : selector;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @typedef {import('./types.js').StyleRule} StyleRule
|
|
30
|
+
* @typedef {import('./types.js').Selector} Selector
|
|
31
|
+
*
|
|
32
|
+
* @typedef {object} CompileOptions
|
|
33
|
+
* @property {(kind: string) => string} [tagFor] the CSS selector of an
|
|
34
|
+
* element kind (default `ui-KIND`, escaped); its result is used verbatim
|
|
35
|
+
* @property {'on'|'off'} [transparency] effective transparency comfort choice
|
|
36
|
+
* @property {boolean} [reducedTransparency] omit all translucent material rules
|
|
37
|
+
* @property {string} [scope] theme boundary selector (includes the boundary itself)
|
|
38
|
+
* @property {string} [prefix] the custom property prefix of ui-tokens
|
|
39
|
+
* `toCss` (`md` gives `var(--md-color-primary)`)
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
const hex = (c) => `\\${c.codePointAt(0).toString(16)} `;
|
|
43
|
+
const disabledControl = `:is([disabled], [aria-disabled='true'], :has([data-part='input']:disabled), :has([data-part='thumb'][aria-disabled='true']))`;
|
|
44
|
+
const HOST_STATES = {
|
|
45
|
+
hover: `:hover:not(${disabledControl})`,
|
|
46
|
+
pressed: `:active:not(${disabledControl})`,
|
|
47
|
+
active: `:active:not(${disabledControl})`,
|
|
48
|
+
disabled: disabledControl,
|
|
49
|
+
checked: `:has([data-part='input']:is(:checked, [aria-checked='true']))`,
|
|
50
|
+
};
|
|
51
|
+
const isControl = (code) => code <= 0x1f || code === 0x7f;
|
|
52
|
+
const isDigit = (c) => c >= '0' && c <= '9';
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The escape of one character shared by identifiers and strings: U+0000
|
|
56
|
+
* becomes U+FFFD, control characters a hex escape; `null` otherwise.
|
|
57
|
+
*/
|
|
58
|
+
function escapeSpecial(c) {
|
|
59
|
+
const code = c.codePointAt(0);
|
|
60
|
+
if (code === 0) {
|
|
61
|
+
return '�';
|
|
62
|
+
}
|
|
63
|
+
return isControl(code) ? hex(c) : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Escape a CSS identifier as `CSS.escape` does (CSSOM, "serialize an
|
|
68
|
+
* identifier").
|
|
69
|
+
* @param {string} text
|
|
70
|
+
* @returns {string}
|
|
71
|
+
*/
|
|
72
|
+
export function escapeIdentifier(text) {
|
|
73
|
+
const chars = [...text];
|
|
74
|
+
return chars
|
|
75
|
+
.map((c, i) => {
|
|
76
|
+
const special = escapeSpecial(c);
|
|
77
|
+
if (special !== null) {
|
|
78
|
+
return special;
|
|
79
|
+
}
|
|
80
|
+
if ((i === 0 || (i === 1 && chars[0] === '-')) && isDigit(c)) {
|
|
81
|
+
return hex(c);
|
|
82
|
+
}
|
|
83
|
+
if (i === 0 && c === '-' && chars.length === 1) {
|
|
84
|
+
return '\\-';
|
|
85
|
+
}
|
|
86
|
+
return c.codePointAt(0) >= 0x80 || /[-_a-zA-Z0-9]/u.test(c)
|
|
87
|
+
? c
|
|
88
|
+
: `\\${c}`;
|
|
89
|
+
})
|
|
90
|
+
.join('');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* A CSS string in single quotes: `'`, `\` and control characters escaped.
|
|
95
|
+
* @param {string} text
|
|
96
|
+
* @returns {string}
|
|
97
|
+
*/
|
|
98
|
+
export function quoteString(text) {
|
|
99
|
+
const body = [...text]
|
|
100
|
+
.map((c) => escapeSpecial(c) ?? (c === "'" || c === '\\' ? `\\${c}` : c))
|
|
101
|
+
.join('');
|
|
102
|
+
return `'${body}'`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The selector of one element: `ui-button#ok[variant='filled']`. */
|
|
106
|
+
function compound(selector, tagFor, hostStates = '') {
|
|
107
|
+
const text =
|
|
108
|
+
(selector.type === null ? '' : tagFor(selector.type)) +
|
|
109
|
+
(selector.id === null ? '' : `#${escapeIdentifier(selector.id)}`) +
|
|
110
|
+
selector.props
|
|
111
|
+
.filter(({ name }) => name !== 'part')
|
|
112
|
+
.map(
|
|
113
|
+
({ name, value }) => `[${escapeIdentifier(name)}=${quoteString(value)}]`
|
|
114
|
+
)
|
|
115
|
+
.join('');
|
|
116
|
+
const part = selector.props.find(({ name }) => name === 'part');
|
|
117
|
+
return (
|
|
118
|
+
(text === '' ? '*' : text) +
|
|
119
|
+
hostStates +
|
|
120
|
+
(part ? ` [data-part=${quoteString(part.value)}]` : '')
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The selector with its ancestors: the first `within` is a descendant
|
|
126
|
+
* combinator, every further one an `:is(ANCESTOR *)` (same specificity).
|
|
127
|
+
* @param {Selector} selector
|
|
128
|
+
* @param {(kind: string) => string} tagFor
|
|
129
|
+
* @param {string} [suffix] pseudo-classes of the states
|
|
130
|
+
* @returns {string}
|
|
131
|
+
*/
|
|
132
|
+
function selectorCss(
|
|
133
|
+
selector,
|
|
134
|
+
tagFor,
|
|
135
|
+
suffix = '',
|
|
136
|
+
hostStates = '',
|
|
137
|
+
atRoot = ''
|
|
138
|
+
) {
|
|
139
|
+
const [first, ...rest] = selector.within;
|
|
140
|
+
const own =
|
|
141
|
+
compound(selector, tagFor, hostStates) +
|
|
142
|
+
rest.map((ancestor) => `:is(${selectorCss(ancestor, tagFor)} *)`).join('') +
|
|
143
|
+
suffix;
|
|
144
|
+
if (first !== undefined) {
|
|
145
|
+
return `${selectorCss(first, tagFor, '', '', atRoot)} ${own}`;
|
|
146
|
+
}
|
|
147
|
+
if (!atRoot) {
|
|
148
|
+
return own;
|
|
149
|
+
}
|
|
150
|
+
const part = selector.props.find(({ name }) => name === 'part');
|
|
151
|
+
if (!part) {
|
|
152
|
+
return `${atRoot}:is(${own})`;
|
|
153
|
+
}
|
|
154
|
+
const host = {
|
|
155
|
+
...selector,
|
|
156
|
+
props: selector.props.filter(({ name }) => name !== 'part'),
|
|
157
|
+
};
|
|
158
|
+
return `${atRoot}:is(${compound(host, tagFor, hostStates)}) [data-part=${quoteString(part.value)}]${suffix}`;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Keep only the last declaration of each property, at its position. */
|
|
162
|
+
function lastDeclarations(declarations) {
|
|
163
|
+
const last = new Map();
|
|
164
|
+
declarations.forEach((decl, i) => last.set(decl.property, i));
|
|
165
|
+
return declarations.filter((decl, i) => last.get(decl.property) === i);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Write the rules as a CSS stylesheet.
|
|
170
|
+
* @param {StyleRule[]} rules
|
|
171
|
+
* @param {CompileOptions} [options]
|
|
172
|
+
* @returns {string}
|
|
173
|
+
*/
|
|
174
|
+
export function compileCss(rules, options = {}) {
|
|
175
|
+
const { tagFor = (kind) => `ui-${escapeIdentifier(kind)}`, prefix = '' } =
|
|
176
|
+
options;
|
|
177
|
+
const refToVar = (ref, fallback) =>
|
|
178
|
+
`var(${cssVariable(ref.path, prefix)}${fallback === undefined ? '' : `, ${fallback}`})`;
|
|
179
|
+
const ctx = {
|
|
180
|
+
refToVar,
|
|
181
|
+
variable: (path) => refToVar({ type: 'token-ref', path }),
|
|
182
|
+
};
|
|
183
|
+
let css = '';
|
|
184
|
+
for (const entry of flatten(rules)) {
|
|
185
|
+
if (entry.declarations.length === 0) {
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const states = entry.states.map((state) => STATE_CSS[state]).join('');
|
|
189
|
+
const part = entry.selector.props.find(({ name }) => name === 'part');
|
|
190
|
+
// Control interaction states also reach non-interactive visual parts.
|
|
191
|
+
const hostStates = part
|
|
192
|
+
? entry.states
|
|
193
|
+
.filter((state) => Object.hasOwn(HOST_STATES, state))
|
|
194
|
+
.map((state) => HOST_STATES[state])
|
|
195
|
+
.join('')
|
|
196
|
+
: '';
|
|
197
|
+
const partStates = part
|
|
198
|
+
? entry.states
|
|
199
|
+
.filter((state) => !Object.hasOwn(HOST_STATES, state))
|
|
200
|
+
.map((state) => STATE_CSS[state])
|
|
201
|
+
.join('')
|
|
202
|
+
: states;
|
|
203
|
+
const selector = selectorCss(
|
|
204
|
+
entry.selector,
|
|
205
|
+
tagFor,
|
|
206
|
+
partStates,
|
|
207
|
+
hostStates
|
|
208
|
+
);
|
|
209
|
+
const atRoot = selectorCss(
|
|
210
|
+
entry.selector,
|
|
211
|
+
tagFor,
|
|
212
|
+
partStates,
|
|
213
|
+
hostStates,
|
|
214
|
+
`:where(:scope)${options.scope === ':scope' ? '' : (options.scope ?? '')}`
|
|
215
|
+
);
|
|
216
|
+
const depth = entry.at.length;
|
|
217
|
+
const pad = ' '.repeat(depth);
|
|
218
|
+
const lines = [
|
|
219
|
+
...entry.at.map(
|
|
220
|
+
({ kind, conditions }, i) =>
|
|
221
|
+
`${' '.repeat(i)}@${kind} ${conditionsCss(conditions)} {`
|
|
222
|
+
),
|
|
223
|
+
`${pad}${scopedSelector(selector, options.scope, atRoot)} {`,
|
|
224
|
+
...lastDeclarations(entry.declarations).map(
|
|
225
|
+
(decl) =>
|
|
226
|
+
`${pad} ${PROPERTIES[decl.property].css}: ${declarationCss(decl, ctx)};`
|
|
227
|
+
),
|
|
228
|
+
`${pad}}`,
|
|
229
|
+
...entry.at.map((_, i) => `${' '.repeat(depth - 1 - i)}}`),
|
|
230
|
+
];
|
|
231
|
+
css += `${lines.join('\n')}\n`;
|
|
232
|
+
const material = lastDeclarations(entry.declarations).find(
|
|
233
|
+
(decl) => decl.property === 'material'
|
|
234
|
+
);
|
|
235
|
+
if (material) {
|
|
236
|
+
css += materialCss(
|
|
237
|
+
material.value.value,
|
|
238
|
+
scopedSelector(selector, options.scope, atRoot),
|
|
239
|
+
entry.at,
|
|
240
|
+
options
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return css;
|
|
245
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diagnostics of the style reader and resolver, in the shape of ui-core
|
|
3
|
+
* diagnostics: `{ code, severity, message, at }`, where `at` names the rule,
|
|
4
|
+
* the property, the state or the condition.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const rule = (at) =>
|
|
8
|
+
at.rule === undefined || at.rule === null ? '' : ` of the rule "${at.rule}"`;
|
|
9
|
+
const text = (at) => (at.text === undefined ? '' : ` "${at.text}"`);
|
|
10
|
+
|
|
11
|
+
const MESSAGES = {
|
|
12
|
+
'anonymous-rule': () =>
|
|
13
|
+
'A style rule has no id; write (NAME: style ...) so that dev tools can name it',
|
|
14
|
+
'missing-selector': (at) =>
|
|
15
|
+
`The style${rule(at)} has no (selector ...); it matches nothing`,
|
|
16
|
+
'duplicate-selector': (at) =>
|
|
17
|
+
`The style${rule(at)} has more than one (selector ...); the last one wins`,
|
|
18
|
+
'invalid-selector': (at) =>
|
|
19
|
+
`The selector${rule(at)} has the invalid part${text(at)}; a part is (type KIND), (id ID), (PROP VALUE) or (within SELECTOR...)`,
|
|
20
|
+
'misplaced-selector': (at) =>
|
|
21
|
+
`The selector${rule(at)} is inside a state, media or container block; it must be a direct part of the rule`,
|
|
22
|
+
'unknown-property': (at) =>
|
|
23
|
+
`The style${rule(at)} has the unknown property "${at.property}"`,
|
|
24
|
+
'invalid-value': (at) =>
|
|
25
|
+
`The property "${at.property}"${rule(at)} has the invalid value${text(at)}; expected ${at.expected}`,
|
|
26
|
+
'unknown-state': (at) =>
|
|
27
|
+
`The style${rule(at)} has the unknown state${text(at)}; a state is hover, focus, pressed (or active), disabled, selected or checked`,
|
|
28
|
+
'invalid-condition': (at) =>
|
|
29
|
+
`The ${at.block} block${rule(at)} has the invalid condition${text(at)}`,
|
|
30
|
+
'css-syntax': (at) =>
|
|
31
|
+
`The style${rule(at)} contains the CSS syntax${text(at)}; ":" separates an id from a link in Links Notation, so write (state hover) or (media (max-width 640px)) instead`,
|
|
32
|
+
'unexpected-value': (at) =>
|
|
33
|
+
`The style${rule(at)} has the value${text(at)} where a (NAME VALUE...) link is expected`,
|
|
34
|
+
'unknown-token': (at) =>
|
|
35
|
+
`The property "${at.property}"${rule(at)} refers to the unknown token "${at.token}"`,
|
|
36
|
+
'type-mismatch': (at) =>
|
|
37
|
+
`The property "${at.property}"${rule(at)} expects ${at.expected} but the token "${at.token}" is a ${at.actual}`,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {string} code
|
|
42
|
+
* @param {'error'|'warning'|'info'} severity
|
|
43
|
+
* @param {Record<string, any>} at
|
|
44
|
+
* @returns {import('./types.js').Diagnostic}
|
|
45
|
+
*/
|
|
46
|
+
export function styleDiagnostic(code, severity, at) {
|
|
47
|
+
return { code, severity, message: MESSAGES[code](at), at };
|
|
48
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Diagnostic,
|
|
3
|
+
RawValue,
|
|
4
|
+
UiNode,
|
|
5
|
+
values,
|
|
6
|
+
} from '@link-foundation/ui-core';
|
|
7
|
+
|
|
8
|
+
export type { Diagnostic };
|
|
9
|
+
export type TypedValue = values.TypedValue;
|
|
10
|
+
|
|
11
|
+
/** The interaction states (Material 3 state names). */
|
|
12
|
+
export type StateName =
|
|
13
|
+
| 'hover'
|
|
14
|
+
| 'focus'
|
|
15
|
+
| 'pressed'
|
|
16
|
+
| 'active'
|
|
17
|
+
| 'disabled'
|
|
18
|
+
| 'selected'
|
|
19
|
+
| 'checked';
|
|
20
|
+
|
|
21
|
+
/** `(type KIND) (id ID) (PROP VALUE) (within SELECTOR...)`. */
|
|
22
|
+
export interface Selector {
|
|
23
|
+
type: string | null;
|
|
24
|
+
id: string | null;
|
|
25
|
+
props: { name: string; value: string }[];
|
|
26
|
+
/** Ancestors, each matched by some ancestor of the element. */
|
|
27
|
+
within: Selector[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface Decl {
|
|
31
|
+
property: string;
|
|
32
|
+
/** Typed; several values (`(padding 8px 16px)`) are a `list`. */
|
|
33
|
+
value: TypedValue;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface Condition {
|
|
37
|
+
feature:
|
|
38
|
+
| 'min-width'
|
|
39
|
+
| 'max-width'
|
|
40
|
+
| 'prefers-color-scheme'
|
|
41
|
+
| 'prefers-reduced-motion';
|
|
42
|
+
/** A dimension (px, rem, em) or an `enum`. */
|
|
43
|
+
value: TypedValue;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type Block =
|
|
47
|
+
| { kind: 'state'; condition: StateName; rule: StyleRule }
|
|
48
|
+
| { kind: 'media' | 'container'; condition: Condition[]; rule: StyleRule };
|
|
49
|
+
|
|
50
|
+
export interface StyleRule {
|
|
51
|
+
id: string;
|
|
52
|
+
/** The position of the rule in the input. */
|
|
53
|
+
order: number;
|
|
54
|
+
selector: Selector;
|
|
55
|
+
declarations: Decl[];
|
|
56
|
+
blocks: Block[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One rule or block flattened in the order `compileCss` writes it. */
|
|
60
|
+
export interface Entry {
|
|
61
|
+
id: string;
|
|
62
|
+
index: number;
|
|
63
|
+
selector: Selector;
|
|
64
|
+
states: StateName[];
|
|
65
|
+
at: { kind: 'media' | 'container'; conditions: Condition[] }[];
|
|
66
|
+
declarations: Decl[];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface StyleEnv {
|
|
70
|
+
states?: string[];
|
|
71
|
+
/** Without a width, no width media condition holds. */
|
|
72
|
+
viewport?: { width: number };
|
|
73
|
+
/** Without a width, no container condition holds. */
|
|
74
|
+
container?: { width: number };
|
|
75
|
+
/** Default `light`. */
|
|
76
|
+
colorScheme?: 'light' | 'dark';
|
|
77
|
+
/** Default `false`. */
|
|
78
|
+
reducedMotion?: boolean;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface PropertySpec {
|
|
82
|
+
css: string;
|
|
83
|
+
type: string | string[];
|
|
84
|
+
max?: number;
|
|
85
|
+
tokens: string[];
|
|
86
|
+
check?: (value: TypedValue) => boolean;
|
|
87
|
+
write?: (value: TypedValue, ctx: CssContext) => string;
|
|
88
|
+
expected?: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface CssContext {
|
|
92
|
+
refToVar: (ref: TypedValue, fallback?: string) => string;
|
|
93
|
+
variable: (path: string) => string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface CompileOptions {
|
|
97
|
+
transparency?: 'on' | 'off';
|
|
98
|
+
reducedTransparency?: boolean;
|
|
99
|
+
/** Zero-specificity theme boundary selector, including the boundary itself. */
|
|
100
|
+
/** Use ':scope' inside a CSS @scope rule to include the boundary itself. */
|
|
101
|
+
scope?: string;
|
|
102
|
+
/** Default `(kind) => 'ui-' + kind` (escaped); the result is used verbatim. */
|
|
103
|
+
tagFor?: (kind: string) => string;
|
|
104
|
+
/** The custom property prefix of ui-tokens `toCss`. */
|
|
105
|
+
prefix?: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Read every `style` element of a Links Notation text. Never throws. */
|
|
109
|
+
export function readStyles(text: string): {
|
|
110
|
+
rules: StyleRule[];
|
|
111
|
+
diagnostics: Diagnostic[];
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/** The first CSS syntax (`a:b`, `(id: ...)`) in a raw value, or `null`. */
|
|
115
|
+
export function findCssSyntax(raw: RawValue): string | null;
|
|
116
|
+
|
|
117
|
+
/** Whether `node` matches; `ancestors` go from the root to the parent. */
|
|
118
|
+
export function matches(
|
|
119
|
+
selector: Selector,
|
|
120
|
+
node: UiNode,
|
|
121
|
+
ancestors?: UiNode[]
|
|
122
|
+
): boolean;
|
|
123
|
+
|
|
124
|
+
/** `[ids, props + states, types]`. */
|
|
125
|
+
export function specificity(
|
|
126
|
+
selector: Selector,
|
|
127
|
+
states?: number
|
|
128
|
+
): [number, number, number];
|
|
129
|
+
|
|
130
|
+
export function compareSpecificity(
|
|
131
|
+
a: readonly number[],
|
|
132
|
+
b: readonly number[]
|
|
133
|
+
): number;
|
|
134
|
+
|
|
135
|
+
export function flatten(rules: StyleRule[]): Entry[];
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The style of one element in a state and environment; `sources` gives the
|
|
139
|
+
* id of the rule that won each property (R12).
|
|
140
|
+
*/
|
|
141
|
+
export function resolveStyle(
|
|
142
|
+
rules: StyleRule[],
|
|
143
|
+
tokens: Map<string, unknown>,
|
|
144
|
+
node: UiNode,
|
|
145
|
+
ancestors?: UiNode[],
|
|
146
|
+
env?: StyleEnv
|
|
147
|
+
): {
|
|
148
|
+
style: Record<string, TypedValue>;
|
|
149
|
+
sources: Record<string, string>;
|
|
150
|
+
diagnostics: Diagnostic[];
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/** The rules as a CSS stylesheet. */
|
|
154
|
+
export function compileCss(
|
|
155
|
+
rules: StyleRule[],
|
|
156
|
+
options?: CompileOptions
|
|
157
|
+
): string;
|
|
158
|
+
|
|
159
|
+
/** `CSS.escape`. */
|
|
160
|
+
export function escapeIdentifier(text: string): string;
|
|
161
|
+
/** A single-quoted, escaped CSS string. */
|
|
162
|
+
export function quoteString(text: string): string;
|
|
163
|
+
|
|
164
|
+
export const PROPERTIES: Readonly<Record<string, PropertySpec>>;
|
|
165
|
+
export function isStyleProperty(name: string): boolean;
|
|
166
|
+
export function typeDeclaration(
|
|
167
|
+
name: string,
|
|
168
|
+
raws: RawValue[],
|
|
169
|
+
at: Record<string, unknown>,
|
|
170
|
+
diagnostics: Diagnostic[]
|
|
171
|
+
): Decl | null;
|
|
172
|
+
export function declarationCss(decl: Decl, ctx: CssContext): string;
|
|
173
|
+
|
|
174
|
+
export const STATES: readonly StateName[];
|
|
175
|
+
export const STATE_CSS: Readonly<Record<StateName, string>>;
|
|
176
|
+
export const FEATURES: Readonly<
|
|
177
|
+
Record<'media' | 'container', Record<string, { type: string | string[] }>>
|
|
178
|
+
>;
|
|
179
|
+
/** The font size that `rem` and `em` widths are resolved with (16). */
|
|
180
|
+
export const ROOT_FONT_SIZE: number;
|
|
181
|
+
export function conditionHolds(
|
|
182
|
+
kind: 'media' | 'container',
|
|
183
|
+
condition: Condition,
|
|
184
|
+
env: StyleEnv
|
|
185
|
+
): boolean;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @link-foundation/ui-style: style rules written in Links Notation, matched
|
|
3
|
+
* to UI elements, resolved against ui-tokens and written as a CSS
|
|
4
|
+
* stylesheet or as the resolved style of one element.
|
|
5
|
+
*
|
|
6
|
+
* ```js
|
|
7
|
+
* import { readStyles, compileCss, resolveStyle } from '@link-foundation/ui-style';
|
|
8
|
+
*
|
|
9
|
+
* const { rules } = readStyles(text);
|
|
10
|
+
* compileCss(rules); // "ui-button[variant='filled'] {\n background-color: var(--color-primary);\n ..."
|
|
11
|
+
* resolveStyle(rules, tokens, node, ancestors, { states: ['hover'] }).style;
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export { readStyles, findCssSyntax } from './read.js';
|
|
16
|
+
export { matches, specificity, compareSpecificity, flatten } from './match.js';
|
|
17
|
+
export { resolveStyle } from './resolve.js';
|
|
18
|
+
export { compileCss, escapeIdentifier, quoteString } from './css.js';
|
|
19
|
+
export {
|
|
20
|
+
PROPERTIES,
|
|
21
|
+
isStyleProperty,
|
|
22
|
+
typeDeclaration,
|
|
23
|
+
declarationCss,
|
|
24
|
+
} from './properties.js';
|
|
25
|
+
export {
|
|
26
|
+
STATES,
|
|
27
|
+
STATE_CSS,
|
|
28
|
+
FEATURES,
|
|
29
|
+
ROOT_FONT_SIZE,
|
|
30
|
+
conditionHolds,
|
|
31
|
+
} from './conditions.js';
|
package/src/match.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Selector matching and the cascade order.
|
|
3
|
+
*
|
|
4
|
+
* - `matches(selector, node, ancestors)`: whether an element matches;
|
|
5
|
+
* `ancestors` go from the root to the parent.
|
|
6
|
+
* - `specificity(selector, states)`: `[ids, props + states, types]`, the
|
|
7
|
+
* tuple CSS computes for the selector that `compileCss` writes.
|
|
8
|
+
* - `flatten(rules)`: every rule and block as one entry in the order
|
|
9
|
+
* `compileCss` writes them, so that "later wins" means the same thing for
|
|
10
|
+
* `resolveStyle` and for a browser.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @typedef {import('./types.js').Selector} Selector
|
|
15
|
+
* @typedef {import('./types.js').UiNode} UiNode
|
|
16
|
+
* @typedef {import('./types.js').StyleRule} StyleRule
|
|
17
|
+
* @typedef {import('./types.js').Entry} Entry
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Whether `node` has the property `name` with the single value `value`. */
|
|
21
|
+
const hasProp = (node, name, value) =>
|
|
22
|
+
node.properties.some(
|
|
23
|
+
(p) => p.name === name && p.values.length === 1 && p.values[0] === value
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
/** Whether `node` matches the compound part of `selector` (no `within`). */
|
|
27
|
+
const matchesCompound = (selector, node) =>
|
|
28
|
+
(selector.type === null || node.kind === selector.type) &&
|
|
29
|
+
(selector.id === null || node.id === selector.id) &&
|
|
30
|
+
selector.props.every(({ name, value }) => hasProp(node, name, value));
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Whether `node` matches `selector`.
|
|
34
|
+
* @param {Selector} selector
|
|
35
|
+
* @param {UiNode} node
|
|
36
|
+
* @param {UiNode[]} [ancestors] from the root to the parent of `node`
|
|
37
|
+
* @returns {boolean}
|
|
38
|
+
*/
|
|
39
|
+
export function matches(selector, node, ancestors = []) {
|
|
40
|
+
return (
|
|
41
|
+
matchesCompound(selector, node) &&
|
|
42
|
+
selector.within.every((ancestor) =>
|
|
43
|
+
ancestors.some((candidate, i) =>
|
|
44
|
+
matches(ancestor, candidate, ancestors.slice(0, i))
|
|
45
|
+
)
|
|
46
|
+
)
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The specificity `[ids, props + states, types]` of a selector, `within`
|
|
52
|
+
* parts included (as for CSS descendant selectors).
|
|
53
|
+
* @param {Selector} selector
|
|
54
|
+
* @param {number} [states] how many states the entry adds
|
|
55
|
+
* @returns {[number, number, number]}
|
|
56
|
+
*/
|
|
57
|
+
export function specificity(selector, states = 0) {
|
|
58
|
+
const result = [
|
|
59
|
+
selector.id === null ? 0 : 1,
|
|
60
|
+
selector.props.length + states,
|
|
61
|
+
selector.type === null ? 0 : 1,
|
|
62
|
+
];
|
|
63
|
+
for (const ancestor of selector.within) {
|
|
64
|
+
const [a, b, c] = specificity(ancestor);
|
|
65
|
+
result[0] += a;
|
|
66
|
+
result[1] += b;
|
|
67
|
+
result[2] += c;
|
|
68
|
+
}
|
|
69
|
+
return /** @type {[number, number, number]} */ (result);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Compare two specificity tuples: negative when `a` is lower. */
|
|
73
|
+
export function compareSpecificity(a, b) {
|
|
74
|
+
for (let i = 0; i < 3; i += 1) {
|
|
75
|
+
if (a[i] !== b[i]) {
|
|
76
|
+
return a[i] - b[i];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Every rule and block as an entry, in the order `compileCss` writes them:
|
|
84
|
+
* rules in source order, a rule's own declarations before its blocks,
|
|
85
|
+
* blocks depth-first in source order.
|
|
86
|
+
* @param {StyleRule[]} rules
|
|
87
|
+
* @returns {Entry[]}
|
|
88
|
+
*/
|
|
89
|
+
export function flatten(rules) {
|
|
90
|
+
/** @type {Entry[]} */
|
|
91
|
+
const entries = [];
|
|
92
|
+
const visit = (rule, states, at) => {
|
|
93
|
+
entries.push({
|
|
94
|
+
id: rule.id,
|
|
95
|
+
index: entries.length,
|
|
96
|
+
selector: rule.selector,
|
|
97
|
+
states,
|
|
98
|
+
at,
|
|
99
|
+
declarations: rule.declarations,
|
|
100
|
+
});
|
|
101
|
+
for (const block of rule.blocks) {
|
|
102
|
+
if (block.kind === 'state') {
|
|
103
|
+
visit(block.rule, [...states, block.condition], at);
|
|
104
|
+
} else {
|
|
105
|
+
const conditions = /** @type {any} */ (block.condition);
|
|
106
|
+
visit(block.rule, states, [...at, { kind: block.kind, conditions }]);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
for (const rule of [...rules].sort((a, b) => a.order - b.order)) {
|
|
111
|
+
visit(rule, [], []);
|
|
112
|
+
}
|
|
113
|
+
return entries;
|
|
114
|
+
}
|
package/src/materials.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Opaque by default, including browsers without either feature. */
|
|
2
|
+
export function materialCss(name, selector, conditions, options = {}) {
|
|
3
|
+
if (options.transparency === 'off' || options.reducedTransparency) {
|
|
4
|
+
return '';
|
|
5
|
+
}
|
|
6
|
+
const variable = (path) =>
|
|
7
|
+
`var(--${options.prefix ? `${options.prefix}-` : ''}${path.replaceAll('.', '-')})`;
|
|
8
|
+
const filter = `blur(${variable(`material.${name}.blur`)})`;
|
|
9
|
+
const opacity = `calc(${variable(`material.${name}.opacity`)} * 100%)`;
|
|
10
|
+
// Effective comfort attributes come from ui-dom's configuration cascade.
|
|
11
|
+
const allowed = `:is(${selector}):not([data-transparency="off"], [data-transparency="off"] *)`;
|
|
12
|
+
let css = `@media (prefers-reduced-transparency: no-preference) and (forced-colors: none) {\n@supports (backdrop-filter: blur(1px)) {\n${allowed} {\n background-color: color-mix(in srgb, ${variable('color.surface')} ${opacity}, transparent);\n backdrop-filter: ${filter};\n}\n}\n}\n`;
|
|
13
|
+
for (const { kind, conditions: at } of [...conditions].reverse()) {
|
|
14
|
+
// Conditions were validated and typed by the standard style reader.
|
|
15
|
+
const query = at
|
|
16
|
+
.map(
|
|
17
|
+
({ feature, value }) =>
|
|
18
|
+
`(${feature}: ${value.value}${value.unit ?? ''})`
|
|
19
|
+
)
|
|
20
|
+
.join(' and ');
|
|
21
|
+
css = `@${kind} ${query} {\n${css}}\n`;
|
|
22
|
+
}
|
|
23
|
+
return css;
|
|
24
|
+
}
|