@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.
@@ -0,0 +1,291 @@
1
+ /**
2
+ * The style property vocabulary: every property a style rule may set, its
3
+ * value type (the value types of ui-core, #15), the CSS property it maps to
4
+ * and the token types it accepts through `(token PATH)`.
5
+ *
6
+ * Values are typed by ui-core `values.typeValue`, so only a well-formed
7
+ * colour, dimension, number or enum (or a token reference) ever reaches the
8
+ * CSS output: no free text, and never `url(`.
9
+ */
10
+
11
+ import { values } from '@link-foundation/ui-core';
12
+ import { validClipPath } from './clip-path.js';
13
+ import { styleDiagnostic } from './diagnostics.js';
14
+
15
+ /**
16
+ * @typedef {import('./types.js').TypedValue} TypedValue
17
+ * @typedef {import('./types.js').RawValue} RawValue
18
+ * @typedef {import('./types.js').Diagnostic} Diagnostic
19
+ *
20
+ * @typedef {object} PropertySpec
21
+ * @property {string} css the CSS property
22
+ * @property {string|string[]} type a ui-core value type
23
+ * @property {number} [max] how many values it takes (default 1)
24
+ * @property {string[]} tokens the token types `(token PATH)` may name;
25
+ * empty when the property takes no token
26
+ * @property {(value: TypedValue) => boolean} [check] a range check of a
27
+ * literal value
28
+ * @property {(value: TypedValue, ctx: CssContext) => string} [write] the
29
+ * CSS of a value, when it is not the ui-core `toCss` text
30
+ * @property {string} [expected] the expected value, for diagnostics
31
+ *
32
+ * @typedef {object} CssContext
33
+ * @property {(ref: TypedValue, fallback?: string) => string} refToVar
34
+ * @property {(path: string) => string} variable a token path as `var(--...)`
35
+ */
36
+
37
+ const nonNegative = (v) => v.type !== 'dimension' || v.value >= 0;
38
+
39
+ /** @type {Readonly<Record<string, PropertySpec>>} */
40
+ export const PROPERTIES = Object.freeze({
41
+ 'surface-opacity': {
42
+ css: 'background-color',
43
+ type: 'number',
44
+ tokens: ['number'],
45
+ check: (v) => v.value >= 0 && v.value <= 1,
46
+ write: (v, ctx) =>
47
+ `color-mix(in srgb, ${ctx.variable('color.surface')} calc(${values.toCss(v, ctx)} * 100%), transparent)`,
48
+ },
49
+ blur: {
50
+ css: 'backdrop-filter',
51
+ type: 'dimension',
52
+ tokens: ['dimension'],
53
+ check: nonNegative,
54
+ write: (v, ctx) => `blur(${values.toCss(v, ctx)})`,
55
+ },
56
+ glow: {
57
+ css: 'box-shadow',
58
+ type: 'number',
59
+ tokens: ['number'],
60
+ check: (v) => v.value >= 0 && v.value <= 4,
61
+ write: (v, ctx) =>
62
+ `0 0 calc(${values.toCss(v, ctx)} * 24px) ${ctx.variable('color.primary')}`,
63
+ },
64
+ scanline: {
65
+ css: 'background-image',
66
+ type: 'number',
67
+ tokens: ['number'],
68
+ check: (v) => v.value >= 0 && v.value <= 1,
69
+ write: (v, ctx) =>
70
+ `repeating-linear-gradient(transparent 0px 3px, rgb(128 128 128 / ${values.toCss(v, ctx)}) 3px 4px)`,
71
+ },
72
+ // Bounded geometry only: no arbitrary CSS functions, URLs or declarations.
73
+ 'clip-path': {
74
+ css: 'clip-path',
75
+ type: 'string',
76
+ tokens: [],
77
+ check: (v) => validClipPath(v.value),
78
+ write: (v) => v.value,
79
+ },
80
+ 'border-style': {
81
+ css: 'border-style',
82
+ type: ['enum', 'none', 'solid', 'dashed', 'dotted', 'double'],
83
+ tokens: [],
84
+ },
85
+ stroke: { css: 'stroke', type: 'color', tokens: ['color'] },
86
+ // Graph renderers consume this preference when constructing their arrowheads.
87
+ arrow: {
88
+ css: '--graph-arrow',
89
+ type: ['enum', 'none', 'triangle'],
90
+ tokens: [],
91
+ },
92
+ 'min-width': {
93
+ css: 'min-width',
94
+ type: 'dimension',
95
+ tokens: ['dimension'],
96
+ check: nonNegative,
97
+ },
98
+ 'min-height': {
99
+ css: 'min-height',
100
+ type: 'dimension',
101
+ tokens: ['dimension'],
102
+ check: nonNegative,
103
+ },
104
+ material: {
105
+ css: 'background-color',
106
+ type: ['enum', 'regular', 'thin', 'thick'],
107
+ tokens: [],
108
+ write: (_v, ctx) => ctx.variable('color.surface'),
109
+ },
110
+ background: { css: 'background-color', type: 'color', tokens: ['color'] },
111
+ color: { css: 'color', type: 'color', tokens: ['color'] },
112
+ radius: {
113
+ css: 'border-radius',
114
+ type: 'dimension',
115
+ max: 4,
116
+ tokens: ['dimension'],
117
+ check: nonNegative,
118
+ },
119
+ padding: {
120
+ css: 'padding',
121
+ type: 'dimension',
122
+ max: 4,
123
+ tokens: ['dimension'],
124
+ check: nonNegative,
125
+ },
126
+ gap: {
127
+ css: 'gap',
128
+ type: 'dimension',
129
+ max: 2,
130
+ tokens: ['dimension'],
131
+ check: nonNegative,
132
+ },
133
+ opacity: {
134
+ css: 'opacity',
135
+ type: 'number',
136
+ tokens: ['number'],
137
+ check: (v) => v.type !== 'number' || (v.value >= 0 && v.value <= 1),
138
+ expected: 'a number from 0 to 1',
139
+ },
140
+ elevation: {
141
+ css: 'box-shadow',
142
+ type: 'number',
143
+ tokens: [],
144
+ check: (v) =>
145
+ v.type === 'number' && Number.isInteger(v.value) && v.value >= 0,
146
+ write: (v, ctx) => ctx.variable(`elevation.${v.value}`),
147
+ expected: 'an elevation level (a whole number from 0)',
148
+ },
149
+ scale: {
150
+ css: 'transform',
151
+ type: 'number',
152
+ tokens: ['number'],
153
+ check: (v) => v.type !== 'number' || v.value >= 0,
154
+ write: (v, ctx) => `scale(${values.toCss(v, ctx)})`,
155
+ },
156
+ 'font-size': {
157
+ css: 'font-size',
158
+ type: 'dimension',
159
+ tokens: ['dimension'],
160
+ check: nonNegative,
161
+ },
162
+ 'font-weight': {
163
+ css: 'font-weight',
164
+ type: 'number',
165
+ tokens: ['fontWeight', 'number'],
166
+ check: (v) => v.type !== 'number' || (v.value >= 1 && v.value <= 1000),
167
+ expected: 'a font weight from 1 to 1000',
168
+ },
169
+ 'border-width': {
170
+ css: 'border-width',
171
+ type: 'dimension',
172
+ tokens: ['dimension'],
173
+ check: nonNegative,
174
+ },
175
+ 'border-color': { css: 'border-color', type: 'color', tokens: ['color'] },
176
+ 'outline-width': {
177
+ css: 'outline-width',
178
+ type: 'dimension',
179
+ tokens: ['dimension'],
180
+ check: nonNegative,
181
+ },
182
+ 'outline-offset': {
183
+ css: 'outline-offset',
184
+ type: 'dimension',
185
+ tokens: ['dimension'],
186
+ },
187
+ 'outline-color': { css: 'outline-color', type: 'color', tokens: ['color'] },
188
+ 'outline-style': {
189
+ css: 'outline-style',
190
+ type: ['enum', 'none', 'solid', 'dashed', 'dotted', 'double'],
191
+ tokens: [],
192
+ },
193
+ direction: {
194
+ css: 'flex-direction',
195
+ type: ['enum', 'horizontal', 'vertical'],
196
+ tokens: [],
197
+ write: (v) => (v.value === 'horizontal' ? 'row' : 'column'),
198
+ expected: 'horizontal or vertical',
199
+ },
200
+ });
201
+
202
+ /** Whether `name` is a style property. */
203
+ export const isStyleProperty = (name) => Object.hasOwn(PROPERTIES, name);
204
+
205
+ const expectedText = (spec) =>
206
+ spec.expected ??
207
+ `a ${Array.isArray(spec.type) ? spec.type.slice(1).join(' or ') : spec.type}${spec.tokens.length > 0 ? ' or (token PATH)' : ''}`;
208
+
209
+ const isRef = (v) => v.type === 'token-ref';
210
+
211
+ /** Whether one typed value is acceptable for the property. */
212
+ function acceptable(spec, value) {
213
+ if (isRef(value)) {
214
+ return spec.tokens.length > 0;
215
+ }
216
+ if (value.type === 'fallback') {
217
+ return (
218
+ spec.tokens.length > 0 &&
219
+ value.options.every((option) => acceptable(spec, option))
220
+ );
221
+ }
222
+ if (value.type === 'param' || value.type === 'element-ref') {
223
+ return false;
224
+ }
225
+ return spec.check === undefined || spec.check(value);
226
+ }
227
+
228
+ /** Atom text of a raw value for diagnostics. */
229
+ export const rawText = (raw) =>
230
+ values.formatValue(
231
+ typeof raw === 'string'
232
+ ? { type: 'string', value: raw }
233
+ : values.inferValue(raw)
234
+ );
235
+
236
+ /**
237
+ * Type the values of one declaration `(NAME VALUE...)`.
238
+ * @param {string} name a style property (see {@link isStyleProperty})
239
+ * @param {RawValue[]} raws
240
+ * @param {Record<string, any>} at where diagnostics point
241
+ * @param {Diagnostic[]} diagnostics
242
+ * @returns {import('./types.js').Decl|null}
243
+ */
244
+ export function typeDeclaration(name, raws, at, diagnostics) {
245
+ const spec = PROPERTIES[name];
246
+ const where = { ...at, property: name, expected: expectedText(spec) };
247
+ if (raws.length === 0 || raws.length > (spec.max ?? 1)) {
248
+ diagnostics.push(
249
+ styleDiagnostic('invalid-value', 'error', {
250
+ ...where,
251
+ text: raws.map(rawText).join(' '),
252
+ })
253
+ );
254
+ return null;
255
+ }
256
+ const typed = [];
257
+ for (const raw of raws) {
258
+ const result = values.typeValue(raw, { type: spec.type });
259
+ const value = result.value;
260
+ if (value === null || !acceptable(spec, value)) {
261
+ diagnostics.push(
262
+ styleDiagnostic('invalid-value', 'error', {
263
+ ...where,
264
+ text: rawText(raw),
265
+ })
266
+ );
267
+ return null;
268
+ }
269
+ typed.push(value);
270
+ }
271
+ return {
272
+ property: name,
273
+ value: typed.length === 1 ? typed[0] : { type: 'list', items: typed },
274
+ };
275
+ }
276
+
277
+ /**
278
+ * The CSS text of a declaration value.
279
+ * @param {import('./types.js').Decl} decl
280
+ * @param {CssContext} ctx
281
+ * @returns {string}
282
+ */
283
+ export function declarationCss(decl, ctx) {
284
+ const spec = PROPERTIES[decl.property];
285
+ // `write` sees token references only where `tokens` allows them (scale).
286
+ const one = (v) =>
287
+ spec.write === undefined ? values.toCss(v, ctx) : spec.write(v, ctx);
288
+ return decl.value.type === 'list'
289
+ ? decl.value.items.map(one).join(' ')
290
+ : one(decl.value);
291
+ }
package/src/read.js ADDED
@@ -0,0 +1,313 @@
1
+ /**
2
+ * `readStyles(text)`: style rules written in Links Notation.
3
+ *
4
+ * ```lino
5
+ * (card-style: style
6
+ * (selector (type card) (within (type dialog)))
7
+ * (padding (token space.medium))
8
+ * (media (max-width 640px)
9
+ * (padding (token space.small)))
10
+ * (container (min-width 400px)
11
+ * (direction horizontal))
12
+ * (state disabled (opacity 0.38)))
13
+ * ```
14
+ *
15
+ * The text is read by ui-core `parse` (the official `links-notation` parser
16
+ * plus path folding). A rule is a `style` element of the ui-dialect
17
+ * vocabulary; this reader gives `style` every property of the style
18
+ * vocabulary (src/properties.js) plus `container`, all multi-valued so that
19
+ * the source order of declarations is kept.
20
+ *
21
+ * CSS syntax cannot be written in bare values: `:` separates an id from a
22
+ * link, so `(state :hover)` or `(media (max-width: 640px))` reads as a link
23
+ * with an id. Such links, and any atom with a `:`, are reported as
24
+ * `css-syntax` errors and skipped, never silently accepted.
25
+ */
26
+
27
+ import { defaultVocabulary, parse, walk } from '@link-foundation/ui-core';
28
+ import { styleDiagnostic } from './diagnostics.js';
29
+ import {
30
+ PROPERTIES,
31
+ isStyleProperty,
32
+ rawText,
33
+ typeDeclaration,
34
+ } from './properties.js';
35
+ import { STATES, readConditions } from './conditions.js';
36
+
37
+ /**
38
+ * @typedef {import('./types.js').StyleRule} StyleRule
39
+ * @typedef {import('./types.js').Selector} Selector
40
+ * @typedef {import('./types.js').RawValue} RawValue
41
+ * @typedef {import('./types.js').Diagnostic} Diagnostic
42
+ */
43
+
44
+ const BLOCKS = ['selector', 'state', 'media', 'container'];
45
+
46
+ /** Whether a head starts a declaration or a block. */
47
+ const isBodyItem = (name) => BLOCKS.includes(name) || isStyleProperty(name);
48
+
49
+ let vocabulary;
50
+
51
+ /** The ui-dialect vocabulary whose `style` kind has every style property. */
52
+ function styleVocabulary() {
53
+ if (vocabulary === undefined) {
54
+ const base = defaultVocabulary();
55
+ const style = base.kinds.get('style');
56
+ const names = [...BLOCKS, ...Object.keys(PROPERTIES)];
57
+ const properties = new Map(
58
+ names.map((name) => [name, { type: 'any', multi: true }])
59
+ );
60
+ vocabulary = {
61
+ ...base,
62
+ kinds: new Map(base.kinds).set('style', { ...style, properties }),
63
+ multiValued: new Set([...base.multiValued, ...names]),
64
+ };
65
+ }
66
+ return vocabulary;
67
+ }
68
+
69
+ /** ui-core codes that this reader reports in its own terms. */
70
+ const RESTATED = new Set([
71
+ 'unknown-sublink',
72
+ 'unexpected-child',
73
+ 'unknown-kind',
74
+ ]);
75
+
76
+ /**
77
+ * The first piece of CSS syntax in a raw value: an atom with `:` or a link
78
+ * with an id (`(max-width: 640px)` reads as the id `max-width`).
79
+ * @param {RawValue} raw
80
+ * @returns {string|null}
81
+ */
82
+ export function findCssSyntax(raw) {
83
+ if (typeof raw === 'string') {
84
+ return raw.includes(':') ? raw : null;
85
+ }
86
+ if (!Array.isArray(raw)) {
87
+ return `${raw.id}:`;
88
+ }
89
+ for (const value of raw) {
90
+ const found = findCssSyntax(value);
91
+ if (found !== null) {
92
+ return found;
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ const isAtomPair = (part) =>
99
+ Array.isArray(part) &&
100
+ part.length === 2 &&
101
+ typeof part[0] === 'string' &&
102
+ typeof part[1] === 'string';
103
+
104
+ /**
105
+ * Read the parts of a selector: `(type KIND)`, `(id ID)`, `(PROP VALUE)`
106
+ * and `(within PART...)`.
107
+ * @returns {Selector|null}
108
+ */
109
+ function readSelector(parts, at, diagnostics) {
110
+ /** @type {Selector} */
111
+ const selector = { type: null, id: null, props: [], within: [] };
112
+ const invalid = (part) => {
113
+ diagnostics.push(
114
+ styleDiagnostic('invalid-selector', 'error', {
115
+ ...at,
116
+ text: rawText(part),
117
+ })
118
+ );
119
+ return null;
120
+ };
121
+ for (const part of parts) {
122
+ if (Array.isArray(part) && part[0] === 'within' && part.length > 1) {
123
+ const ancestor = readSelector(part.slice(1), at, diagnostics);
124
+ if (ancestor === null) {
125
+ return null;
126
+ }
127
+ selector.within.push(ancestor);
128
+ } else if (!isAtomPair(part)) {
129
+ return invalid(part);
130
+ } else if (part[0] === 'type' || part[0] === 'id') {
131
+ if (selector[part[0]] !== null) {
132
+ return invalid(part);
133
+ }
134
+ selector[part[0]] = part[1];
135
+ } else {
136
+ selector.props.push({ name: part[0], value: part[1] });
137
+ }
138
+ }
139
+ return parts.length === 0 ? invalid([]) : selector;
140
+ }
141
+
142
+ /**
143
+ * Read the body of a rule or a block: declarations, `state`, `media` and
144
+ * `container` blocks (any nesting), and at the top level the selector.
145
+ * @param {RawValue[]} items each item a `(NAME VALUE...)` link
146
+ * @param {StyleRule} rule the rule to fill
147
+ * @param {{ at: Record<string, any>, diagnostics: Diagnostic[], top: boolean,
148
+ * selectors: Selector[] }} ctx
149
+ */
150
+ function readBody(items, rule, ctx) {
151
+ const { at, diagnostics } = ctx;
152
+ for (const item of items) {
153
+ const css = findCssSyntax(item);
154
+ if (css !== null) {
155
+ diagnostics.push(
156
+ styleDiagnostic('css-syntax', 'error', { ...at, text: css })
157
+ );
158
+ continue;
159
+ }
160
+ if (!Array.isArray(item) || typeof item[0] !== 'string') {
161
+ diagnostics.push(
162
+ styleDiagnostic('unexpected-value', 'error', {
163
+ ...at,
164
+ text: rawText(item),
165
+ })
166
+ );
167
+ continue;
168
+ }
169
+ const [name, ...rest] = item;
170
+ if (name === 'selector') {
171
+ readSelectorItem(rest, ctx);
172
+ } else if (name === 'state') {
173
+ readState(rest, rule, ctx);
174
+ } else if (name === 'media' || name === 'container') {
175
+ readCondition(name, rest, rule, ctx);
176
+ } else if (isStyleProperty(name)) {
177
+ const decl = typeDeclaration(name, rest, at, diagnostics);
178
+ if (decl !== null) {
179
+ rule.declarations.push(decl);
180
+ }
181
+ } else {
182
+ diagnostics.push(
183
+ styleDiagnostic('unknown-property', 'error', { ...at, property: name })
184
+ );
185
+ }
186
+ }
187
+ }
188
+
189
+ function readSelectorItem(parts, ctx) {
190
+ if (!ctx.top) {
191
+ ctx.diagnostics.push(
192
+ styleDiagnostic('misplaced-selector', 'error', ctx.at)
193
+ );
194
+ return;
195
+ }
196
+ const selector = readSelector(parts, ctx.at, ctx.diagnostics);
197
+ if (selector !== null) {
198
+ ctx.selectors.push(selector);
199
+ }
200
+ }
201
+
202
+ /** An empty rule for a block of `rule`: same id, order and selector. */
203
+ const blockRule = (rule) => ({
204
+ id: rule.id,
205
+ order: rule.order,
206
+ selector: rule.selector,
207
+ declarations: [],
208
+ blocks: [],
209
+ });
210
+
211
+ function readState([name, ...body], rule, ctx) {
212
+ if (typeof name !== 'string' || !STATES.includes(name)) {
213
+ ctx.diagnostics.push(
214
+ styleDiagnostic('unknown-state', 'error', {
215
+ ...ctx.at,
216
+ text: name === undefined ? '' : rawText(name),
217
+ })
218
+ );
219
+ return;
220
+ }
221
+ const inner = blockRule(rule);
222
+ readBody(body, inner, { ...ctx, top: false, at: { ...ctx.at, state: name } });
223
+ rule.blocks.push({ kind: 'state', condition: name, rule: inner });
224
+ }
225
+
226
+ function readCondition(kind, values, rule, ctx) {
227
+ const { conditions, body } = readConditions(
228
+ kind,
229
+ values,
230
+ ctx.at,
231
+ ctx.diagnostics,
232
+ isBodyItem
233
+ );
234
+ if (conditions === null) {
235
+ return;
236
+ }
237
+ const inner = blockRule(rule);
238
+ readBody(body, inner, { ...ctx, top: false });
239
+ rule.blocks.push({ kind, condition: conditions, rule: inner });
240
+ }
241
+
242
+ /**
243
+ * Read one `style` element into a rule, or `null` when it has no selector.
244
+ * @param {import('./types.js').UiNode} node
245
+ * @param {number} order
246
+ * @param {Diagnostic[]} diagnostics
247
+ * @returns {StyleRule|null}
248
+ */
249
+ function readRule(node, order, diagnostics) {
250
+ const id = node.id ?? `style-${order + 1}`;
251
+ const at = { rule: id };
252
+ if (node.id === null) {
253
+ diagnostics.push(styleDiagnostic('anonymous-rule', 'warning', at));
254
+ }
255
+ /** @type {StyleRule} */
256
+ const rule = { id, order, selector: null, declarations: [], blocks: [] };
257
+ const selectors = [];
258
+ // Positional values, unknown sublinks and children (a `(state :hover)`
259
+ // reads as a child element with the id `state`) go through readBody too.
260
+ const items = [
261
+ ...node.positional,
262
+ ...node.properties.map((p) => [p.name, ...p.values]),
263
+ ...node.unknown,
264
+ ...node.children.map((child) =>
265
+ child.id === null ? [child.kind ?? ''] : { id: child.id, values: [] }
266
+ ),
267
+ ];
268
+ readBody(items, rule, { at, diagnostics, top: true, selectors });
269
+ if (selectors.length > 1) {
270
+ diagnostics.push(styleDiagnostic('duplicate-selector', 'warning', at));
271
+ }
272
+ if (selectors.length === 0) {
273
+ diagnostics.push(styleDiagnostic('missing-selector', 'error', at));
274
+ return null;
275
+ }
276
+ const selector = selectors[selectors.length - 1];
277
+ setSelector(rule, selector);
278
+ return rule;
279
+ }
280
+
281
+ /** Give a rule and all its blocks the selector. */
282
+ function setSelector(rule, selector) {
283
+ rule.selector = selector;
284
+ for (const block of rule.blocks) {
285
+ setSelector(block.rule, selector);
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Read every style rule (`style` element) of a Links Notation text. Other
291
+ * elements (themes, documents) are skipped.
292
+ * @param {string} text
293
+ * @returns {{ rules: StyleRule[], diagnostics: Diagnostic[] }}
294
+ */
295
+ export function readStyles(text) {
296
+ const doc = parse(text, { vocabulary: styleVocabulary(), checks: false });
297
+ const diagnostics = doc.diagnostics.filter((d) => !RESTATED.has(d.code));
298
+ /** @type {StyleRule[]} */
299
+ const rules = [];
300
+ let order = 0;
301
+ walk(doc, (node) => {
302
+ if (node.kind !== 'style') {
303
+ return undefined;
304
+ }
305
+ const rule = readRule(node, order, diagnostics);
306
+ order += 1;
307
+ if (rule !== null) {
308
+ rules.push(rule);
309
+ }
310
+ return false;
311
+ });
312
+ return { rules, diagnostics };
313
+ }