@tiavision/sinter-mail 0.0.0-stage → 0.2.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.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +113 -2
  3. package/docs/mail.md +298 -0
  4. package/docs/proposals/progressive-rendering.md +180 -0
  5. package/docs/proposals/sinter-mail.md +520 -0
  6. package/llms.txt +21 -0
  7. package/package.json +65 -4
  8. package/sinter/autolink.ts +98 -0
  9. package/sinter/components/internal/mail-a.html +5 -0
  10. package/sinter/components/internal/mail-abbr.html +5 -0
  11. package/sinter/components/internal/mail-address.html +5 -0
  12. package/sinter/components/internal/mail-article.html +5 -0
  13. package/sinter/components/internal/mail-aside.html +5 -0
  14. package/sinter/components/internal/mail-b.html +5 -0
  15. package/sinter/components/internal/mail-bdi.html +5 -0
  16. package/sinter/components/internal/mail-bdo.html +5 -0
  17. package/sinter/components/internal/mail-blockquote.html +5 -0
  18. package/sinter/components/internal/mail-br.html +5 -0
  19. package/sinter/components/internal/mail-center.html +5 -0
  20. package/sinter/components/internal/mail-cite.html +5 -0
  21. package/sinter/components/internal/mail-code.html +5 -0
  22. package/sinter/components/internal/mail-dd.html +5 -0
  23. package/sinter/components/internal/mail-del.html +5 -0
  24. package/sinter/components/internal/mail-details.html +5 -0
  25. package/sinter/components/internal/mail-dfn.html +5 -0
  26. package/sinter/components/internal/mail-div.html +5 -0
  27. package/sinter/components/internal/mail-dl.html +5 -0
  28. package/sinter/components/internal/mail-dt.html +5 -0
  29. package/sinter/components/internal/mail-em.html +5 -0
  30. package/sinter/components/internal/mail-figcaption.html +5 -0
  31. package/sinter/components/internal/mail-figure.html +5 -0
  32. package/sinter/components/internal/mail-font.html +5 -0
  33. package/sinter/components/internal/mail-footer.html +5 -0
  34. package/sinter/components/internal/mail-h1.html +5 -0
  35. package/sinter/components/internal/mail-h2.html +5 -0
  36. package/sinter/components/internal/mail-h3.html +5 -0
  37. package/sinter/components/internal/mail-h4.html +5 -0
  38. package/sinter/components/internal/mail-h5.html +5 -0
  39. package/sinter/components/internal/mail-h6.html +5 -0
  40. package/sinter/components/internal/mail-header.html +5 -0
  41. package/sinter/components/internal/mail-hr.html +5 -0
  42. package/sinter/components/internal/mail-i.html +5 -0
  43. package/sinter/components/internal/mail-img.html +5 -0
  44. package/sinter/components/internal/mail-ins.html +5 -0
  45. package/sinter/components/internal/mail-kbd.html +5 -0
  46. package/sinter/components/internal/mail-li.html +5 -0
  47. package/sinter/components/internal/mail-main.html +5 -0
  48. package/sinter/components/internal/mail-mark.html +5 -0
  49. package/sinter/components/internal/mail-nav.html +5 -0
  50. package/sinter/components/internal/mail-node.html +5 -0
  51. package/sinter/components/internal/mail-ol.html +5 -0
  52. package/sinter/components/internal/mail-orphan.html +5 -0
  53. package/sinter/components/internal/mail-p.html +5 -0
  54. package/sinter/components/internal/mail-pre.html +5 -0
  55. package/sinter/components/internal/mail-q.html +5 -0
  56. package/sinter/components/internal/mail-s.html +5 -0
  57. package/sinter/components/internal/mail-samp.html +5 -0
  58. package/sinter/components/internal/mail-section.html +5 -0
  59. package/sinter/components/internal/mail-small.html +5 -0
  60. package/sinter/components/internal/mail-span.html +5 -0
  61. package/sinter/components/internal/mail-steps.html +5 -0
  62. package/sinter/components/internal/mail-steps.ts +46 -0
  63. package/sinter/components/internal/mail-strike.html +5 -0
  64. package/sinter/components/internal/mail-strong.html +5 -0
  65. package/sinter/components/internal/mail-sub.html +5 -0
  66. package/sinter/components/internal/mail-summary.html +5 -0
  67. package/sinter/components/internal/mail-sup.html +5 -0
  68. package/sinter/components/internal/mail-table.html +5 -0
  69. package/sinter/components/internal/mail-time.html +5 -0
  70. package/sinter/components/internal/mail-tt.html +5 -0
  71. package/sinter/components/internal/mail-u.html +5 -0
  72. package/sinter/components/internal/mail-ul.html +5 -0
  73. package/sinter/components/internal/mail-var.html +5 -0
  74. package/sinter/components/internal/mail-wbr.html +5 -0
  75. package/sinter/components/mail-body.html +21 -0
  76. package/sinter/css/hints.ts +259 -0
  77. package/sinter/css/index.ts +348 -0
  78. package/sinter/css/media.ts +254 -0
  79. package/sinter/css/parse.ts +124 -0
  80. package/sinter/css/selectors.ts +530 -0
  81. package/sinter/css/tokenize.ts +279 -0
  82. package/sinter/css/values.ts +669 -0
  83. package/sinter/engine.ts +6 -0
  84. package/sinter/index.ts +5 -0
  85. package/sinter/parse.ts +359 -0
  86. package/sinter/parser/entities.ts +22 -0
  87. package/sinter/parser/index.ts +54 -0
  88. package/sinter/parser/tokenizer.ts +275 -0
  89. package/sinter/parser/tree.ts +1265 -0
  90. package/sinter/plain.ts +125 -0
  91. package/sinter/raw.ts +28 -0
  92. package/sinter/sinter.helpers.ts +11 -0
  93. package/sinter/sinter.types.ts +144 -0
  94. package/sinter/tags.ts +169 -0
  95. package/sinter/tree.ts +168 -0
@@ -0,0 +1,348 @@
1
+ // The cascade, resolved once at parse time: every element's declarations from its presentational hints,
2
+ // the email's <style> rules (by specificity, then order, `!important` after normal ones) and its style
3
+ // attribute (above the author's rules, `!important` in it above the author's `!important`), as CSS
4
+ // Cascading Level 4 orders them within the author origin. What wins for each kept property is the
5
+ // element's style, rendered inline by data-sn-style: there is no stylesheet to evaluate later, so
6
+ // `@media` is decided here too (the `media` option), and selectors are matched against the raw tree.
7
+ //
8
+ // The colour scheme is the one thing an email's styles may change with that the app's page still decides:
9
+ // `prefers-color-scheme` is evaluated for both schemes, and an element whose colours differ between them
10
+ // gets `light-dark(<light>, <dark>)`, which the browser resolves by the colour scheme the element is shown in
11
+ // (the page's, unless the app gives the email another). Anything else a dark rule changes keeps its light
12
+ // value: light-dark() takes colours only.
13
+ //
14
+ // Inheritance is not computed: the tree keeps the document's structure, so an inline style inherits in
15
+ // the app as it did in the email.
16
+ //
17
+ // Pure: no DOM, no Node APIs, only the language's globals, so sinter folds it at build time.
18
+ import { attr, type RawElement } from '../raw.js';
19
+ import { PROPERTIES } from '../tags.js';
20
+ import type { Property, Style } from '../sinter.types.js';
21
+ import { hints, legacyColor } from './hints.js';
22
+ import { matchMedia, type Media, type Scheme } from './media.js';
23
+ import { parseDeclarations, parseStylesheet, rules as parseRules, type Declaration, type Rule } from './parse.js';
24
+ import { bucketKey, exhausted, indexTree, matches, parseSelectorList, type Budget, type Complex } from './selectors.js';
25
+ import { expand, joinOverflow, joinTextDecoration, type Assignment, type Longhand } from './values.js';
26
+
27
+ export { matchMedia } from './media.js';
28
+ export { parseStylesheet, parseDeclarations } from './parse.js';
29
+ export { expand } from './values.js';
30
+ export { tokenize } from './tokenize.js';
31
+
32
+ export interface ResolveOptions {
33
+ /** the width `@media` is evaluated at: 'wide' (800 px) or 'narrow' (375 px) */
34
+ media: Media;
35
+ }
36
+
37
+ export interface Resolved {
38
+ /** every element's resolved style; elements whose style is empty have no entry */
39
+ styles: Map<RawElement, Style>;
40
+ /**
41
+ * the schemes the email is written for, `light` before `dark`: those its `color-scheme` and
42
+ * `supported-color-schemes` metas name, and the `color-scheme` property of its `<html>` and `<body>`
43
+ */
44
+ colorScheme: Scheme[];
45
+ /** some element's colours change with `prefers-color-scheme`: its style has `light-dark()` */
46
+ dark: boolean;
47
+ }
48
+
49
+ // every tracked longhand by number: an element's values are an array, not a map, since a hostile
50
+ // stylesheet can match thousands of rules on every element
51
+ const LONGHANDS: Longhand[] = [
52
+ ...(PROPERTIES.filter((p) => p !== 'text-decoration' && p !== 'overflow') as Longhand[]),
53
+ 'text-decoration-line', 'text-decoration-style', 'text-decoration-color', 'overflow-x', 'overflow-y',
54
+ 'color-scheme',
55
+ ];
56
+ const ID = new Map(LONGHANDS.map((l, i) => [l, i]));
57
+
58
+ // the colour longhands, by number, with their initial values: what light-dark() is written for, the
59
+ // initial value standing in for the scheme whose rules do not set one (`currentcolor` in `color` is the
60
+ // inherited colour)
61
+ const COLORS = new Map<number, string>([
62
+ ['color', 'currentcolor'], ['background-color', 'transparent'], ['text-decoration-color', 'currentcolor'],
63
+ ['border-top-color', 'currentcolor'], ['border-right-color', 'currentcolor'], ['border-bottom-color', 'currentcolor'], ['border-left-color', 'currentcolor'],
64
+ ].map(([l, v]) => [ID.get(l as Longhand)!, v]));
65
+ const WIDE = new Set(['inherit', 'initial', 'unset']);
66
+ const SCHEME = ID.get('color-scheme')!;
67
+
68
+ // the schemes a rule applies in, as bits
69
+ const LIGHT = 1, DARK = 2, BOTH = LIGHT | DARK;
70
+
71
+ /**
72
+ * Assignments as parallel arrays of longhand numbers and values, the last one per longhand only, and
73
+ * which longhands they set as a bit mask in three 30-bit words (small integers), so a rule whose
74
+ * longhands a higher one already set is skipped with a few integer operations.
75
+ */
76
+ interface Compiled {
77
+ props: number[];
78
+ values: string[];
79
+ m0: number;
80
+ m1: number;
81
+ m2: number;
82
+ }
83
+ if (LONGHANDS.length > 90) throw new Error('sinter/css: more longhands than the masks hold');
84
+
85
+ interface StyleRule {
86
+ normal: Compiled;
87
+ important: Compiled;
88
+ }
89
+
90
+ interface Entry {
91
+ /** unique per entry: a list of matched entries is keyed by these */
92
+ id: number;
93
+ sel: Complex;
94
+ specificity: number;
95
+ order: number;
96
+ normal: Compiled;
97
+ /** null when the rule has no !important declaration */
98
+ important: Compiled | null;
99
+ /** the schemes its `@media` (or its `<style media>`) applies in: LIGHT, DARK or BOTH */
100
+ schemes: number;
101
+ }
102
+
103
+ // the matching work allowed for one resolve (selectors.ts, budget): a 1,800-element newsletter with
104
+ // 300 rules takes 0.5 million steps; a hostile stylesheet stops matching here, in a few hundred
105
+ // milliseconds on a CI runner (test/css.test.ts, safety)
106
+ const MAX_STEPS = 2_000_000;
107
+
108
+ // the author rules kept for one resolve, every <style> together (one per selector of a list): a real
109
+ // email has hundreds; past this a hostile stylesheet's rules are dropped, so compiling them, and going
110
+ // through an element's matches, stays bounded
111
+ const MAX_RULES = 10_000;
112
+
113
+ // an element's style is shared with the elements like it when it matches at most this many rules (a real
114
+ // email's elements match a handful)
115
+ const CACHED = 64;
116
+
117
+ // `@media` nested deeper than this is dropped rather than walked
118
+ const MAX_MEDIA_DEPTH = 16;
119
+
120
+ /**
121
+ * Every element's resolved style under `options`: the kept properties only, each value re-serialized.
122
+ * Elements whose style is empty have no entry.
123
+ */
124
+ export function resolveStyles(root: RawElement, options: ResolveOptions): Map<RawElement, Style> {
125
+ return resolve(root, options).styles;
126
+ }
127
+
128
+ /** the styles of resolveStyles(), and what the email says about colour schemes */
129
+ export function resolve(root: RawElement, options: ResolveOptions): Resolved {
130
+ const media = options.media;
131
+ /** the schemes a media query list matches in, within `outer` */
132
+ const schemesOf = (list: Parameters<typeof matchMedia>[0], outer: number) =>
133
+ outer & ((matchMedia(list, media, 'light') ? LIGHT : 0) | (matchMedia(list, media, 'dark') ? DARK : 0));
134
+ const all = indexTree(root);
135
+
136
+ // the author rules, from every <style> in document order
137
+ const buckets = new Map<string, Entry[]>();
138
+ let order = 0, ids = 0;
139
+ const addRules = (list: Rule[], depth: number, schemes: number) => {
140
+ for (const r of list) {
141
+ if (r.t === 'at') {
142
+ if (r.name === 'media' && r.block && depth < MAX_MEDIA_DEPTH) {
143
+ const inner = schemesOf(r.prelude, schemes);
144
+ if (inner) addRules(parseRules(r.block.items, false), depth + 1, inner);
145
+ }
146
+ // @import, @font-face, @keyframes, @supports, @layer, @page, @charset and the rest: dropped
147
+ continue;
148
+ }
149
+ const sels = parseSelectorList(r.prelude);
150
+ if (!sels || sels.length === 0) continue;
151
+ const rule = compile(r.declarations);
152
+ // a rule that sets nothing kept is not matched at all
153
+ if (rule.normal.props.length === 0 && rule.important.props.length === 0) continue;
154
+ if (ids >= MAX_RULES) return;
155
+ const o = order++;
156
+ for (const sel of sels) {
157
+ const key = bucketKey(sel);
158
+ let b = buckets.get(key);
159
+ if (!b) buckets.set(key, (b = []));
160
+ b.push({ id: ids++, sel, specificity: sel.specificity, order: o, normal: rule.normal, important: rule.important.props.length ? rule.important : null, schemes });
161
+ }
162
+ }
163
+ };
164
+ for (const e of all) {
165
+ if (e.el.tag !== 'style' || !isCss(e.el)) continue;
166
+ const m = attr(e.el, 'media');
167
+ const schemes = m === null ? BOTH : schemesOf(m, BOTH);
168
+ if (!schemes) continue;
169
+ let text = '';
170
+ for (const c of e.el.children) if (c.type === 'text') text += c.value;
171
+ if (ids >= MAX_RULES) break;
172
+ addRules(parseStylesheet(text), 0, schemes);
173
+ }
174
+
175
+ const body = all.find((e) => e.el.tag === 'body' && e.parent?.el === root) ?? null;
176
+ const link = body ? attr(body.el, 'link') : null;
177
+ const cx = { link: link !== null ? legacyColor(link) : null };
178
+
179
+ // each bucket in cascade order, so an element's matches are merged, not sorted
180
+ const byCascade = (a: Entry, b: Entry) => a.specificity - b.specificity || a.order - b.order;
181
+ for (const b of buckets.values()) b.sort(byCascade);
182
+
183
+ const out = new Map<RawElement, Style>();
184
+ const universal = buckets.get('*');
185
+ const values: (string | undefined)[] = new Array(LONGHANDS.length);
186
+ const dark: (string | undefined)[] = new Array(LONGHANDS.length);
187
+ const colorScheme = new Set<string>();
188
+ let anyDark = false;
189
+ for (const e of all) {
190
+ if (e.el.tag !== 'meta') continue;
191
+ const name = attr(e.el, 'name')?.trim().toLowerCase();
192
+ const content = attr(e.el, 'content');
193
+ if ((name !== 'color-scheme' && name !== 'supported-color-schemes') || content === null) continue;
194
+ const v = expand('color-scheme', content)?.[0]?.[1];
195
+ if (v && !WIDE.has(v)) for (const n of v.split(' ')) colorScheme.add(n);
196
+ }
197
+ const work: Budget = { left: MAX_STEPS };
198
+ // Emails repeat themselves: builders write the same inline style and legacy attributes on every cell of
199
+ // a kind, and those cells match the same rules. So within one resolve: an inline style is parsed once
200
+ // per distinct text, the hints compiled once per distinct list, and an element's style is computed once
201
+ // per distinct (matched rules, inline style, hints) and shared, frozen with the tree, by every element
202
+ // that has the same. Bounded by the input: one entry per distinct string.
203
+ const inlines = new Map<string, StyleRule>();
204
+ const hinted = new Map<string, Compiled>();
205
+ const styles = new Map<string, Style | null>();
206
+ {
207
+ for (const e of all) {
208
+ let candidates: Entry[] = [];
209
+ const take = (list: Entry[] | undefined) => {
210
+ if (!list || exhausted(work)) return;
211
+ const m: Entry[] = [];
212
+ for (const x of list) if (matches(x.sel, e, work)) m.push(x);
213
+ if (m.length) candidates = candidates.length ? merge(candidates, m, byCascade) : m;
214
+ };
215
+ if (e.id !== null) take(buckets.get('#' + e.id));
216
+ const seen = new Set<string>();
217
+ for (const c of e.classes) if (!seen.has(c)) { seen.add(c); take(buckets.get('.' + c)); }
218
+ take(buckets.get(e.el.tag));
219
+ take(universal);
220
+
221
+ const inline = attr(e.el, 'style');
222
+ const hs = hints(e, cx);
223
+ let hkey = '';
224
+ for (const [p, v] of hs) hkey += p + ':' + v + ';';
225
+ // the hints (no `|` in them), the matched entries' ids, then the inline text: unambiguous. Not for an
226
+ // element that matches more than CACHED rules (a hostile stylesheet's thousands): its key would cost
227
+ // as much as its style, so it is computed as it is
228
+ // <html> and <body> are not shared: their `color-scheme` is read below
229
+ const rootOrBody = e.el === root || e === body;
230
+ let key: string | null = null;
231
+ if (candidates.length <= CACHED && !rootOrBody) {
232
+ key = hkey + '|';
233
+ for (const c of candidates) key += c.id + ',';
234
+ key += '|' + (inline ?? '');
235
+ const known = styles.get(key);
236
+ if (known !== undefined) {
237
+ if (known) out.set(e.el, known);
238
+ continue;
239
+ }
240
+ }
241
+
242
+ let own: StyleRule | null = null;
243
+ if (inline !== null) {
244
+ own = inlines.get(inline) ?? null;
245
+ if (!own) inlines.set(inline, (own = compile(parseDeclarations(inline))));
246
+ }
247
+ let h = hinted.get(hkey);
248
+ if (!h) hinted.set(hkey, (h = compiled(hs)));
249
+ // from the highest precedence down, each longhand taken from the first that sets it: inline
250
+ // !important, author !important (the last in cascade order first), inline, author, hints; the
251
+ // author's rules those of `scheme` only
252
+ const cascade = (into: (string | undefined)[], scheme: number) => {
253
+ into.fill(undefined);
254
+ let s0 = 0, s1 = 0, s2 = 0;
255
+ const apply = (c: Compiled) => {
256
+ if (!((c.m0 & ~s0) | (c.m1 & ~s1) | (c.m2 & ~s2))) return;
257
+ for (let i = 0; i < c.props.length; i++) if (into[c.props[i]] === undefined) into[c.props[i]] = c.values[i];
258
+ s0 |= c.m0; s1 |= c.m1; s2 |= c.m2;
259
+ };
260
+ if (own) apply(own.important);
261
+ for (let i = candidates.length - 1; i >= 0; i--) { const c = candidates[i]; if (c.important && c.schemes & scheme) apply(c.important); }
262
+ if (own) apply(own.normal);
263
+ for (let i = candidates.length - 1; i >= 0; i--) { const c = candidates[i]; if (c.schemes & scheme) apply(c.normal); }
264
+ apply(h);
265
+ };
266
+ cascade(values, LIGHT);
267
+ // rules of one scheme only: the dark cascade too, and the colours that differ as light-dark()
268
+ if (candidates.some((c) => c.schemes !== BOTH)) {
269
+ cascade(dark, DARK);
270
+ for (const [i, initial] of COLORS) {
271
+ const l = values[i], d = dark[i];
272
+ if (l === d || (l !== undefined && WIDE.has(l)) || (d !== undefined && WIDE.has(d))) continue;
273
+ values[i] = `light-dark(${l ?? initial}, ${d ?? initial})`;
274
+ anyDark = true;
275
+ }
276
+ }
277
+ if (rootOrBody) {
278
+ const v = values[SCHEME];
279
+ if (v !== undefined && !WIDE.has(v)) for (const n of v.split(' ')) colorScheme.add(n);
280
+ }
281
+ const style = finish(values);
282
+ if (key !== null) styles.set(key, style);
283
+ if (style) out.set(e.el, style);
284
+ }
285
+ }
286
+ const schemes = (['light', 'dark'] as const).filter((s) => colorScheme.has(s));
287
+ return { styles: out, colorScheme: schemes, dark: anyDark };
288
+ }
289
+
290
+ /** two lists in cascade order as one */
291
+ function merge(a: Entry[], b: Entry[], cmp: (x: Entry, y: Entry) => number): Entry[] {
292
+ const out: Entry[] = [];
293
+ let i = 0, j = 0;
294
+ while (i < a.length && j < b.length) out.push(cmp(a[i], b[j]) <= 0 ? a[i++] : b[j++]);
295
+ while (i < a.length) out.push(a[i++]);
296
+ while (j < b.length) out.push(b[j++]);
297
+ return out;
298
+ }
299
+
300
+ const isCss = (el: RawElement) => {
301
+ const t = attr(el, 'type');
302
+ if (t === null) return true;
303
+ const v = t.trim().toLowerCase();
304
+ return v === '' || v === 'text/css';
305
+ };
306
+
307
+ /** a rule's declarations as longhand assignments, normal and important apart, in declaration order */
308
+ function compile(decls: Declaration[]): StyleRule {
309
+ const normal: Assignment[] = [];
310
+ const important: Assignment[] = [];
311
+ for (const d of decls) {
312
+ const a = expand(d.name, d.value);
313
+ if (a) (d.important ? important : normal).push(...a);
314
+ }
315
+ return { normal: compiled(normal), important: compiled(important) };
316
+ }
317
+
318
+ function compiled(list: Assignment[]): Compiled {
319
+ const last = new Map<number, string>();
320
+ for (const [p, v] of list) {
321
+ const id = ID.get(p)!;
322
+ // re-inserted, so the map's order stays the order of the winning assignments
323
+ last.delete(id);
324
+ last.set(id, v);
325
+ }
326
+ const mask = [0, 0, 0];
327
+ for (const id of last.keys()) mask[Math.floor(id / 30)] |= 1 << id % 30;
328
+ return { props: [...last.keys()], values: [...last.values()], m0: mask[0], m1: mask[1], m2: mask[2] };
329
+ }
330
+
331
+ const at = (values: (string | undefined)[], l: Longhand) => values[ID.get(l)!];
332
+
333
+ /** the tracked longhands as the element's style: the kept properties, in PROPERTIES order */
334
+ function finish(values: (string | undefined)[]): Style | null {
335
+ const style: Style = {};
336
+ let any = false;
337
+ for (const p of PROPERTIES as readonly Property[]) {
338
+ let v: string | null | undefined;
339
+ if (p === 'text-decoration') v = joinTextDecoration(at(values, 'text-decoration-line'), at(values, 'text-decoration-style'), at(values, 'text-decoration-color'));
340
+ else if (p === 'overflow') v = joinOverflow(at(values, 'overflow-x'), at(values, 'overflow-y'));
341
+ else v = at(values, p);
342
+ if (v != null && safe(v)) { style[p] = v; any = true; }
343
+ }
344
+ return any ? style : null;
345
+ }
346
+
347
+ /** the runtime's own check, as a last gate: what it would refuse is never written */
348
+ const safe = (v: string) => !/\\|url\(|image\(|image-set\(/i.test(v);
@@ -0,0 +1,254 @@
1
+ // Media queries (Media Queries Level 4), evaluated once, at parse time, for one of two fixed screens:
2
+ // 'wide' is an 800 × 600 px landscape viewport, 'narrow' a 375 × 667 px portrait one, both at 1 dppx with
3
+ // a 16 px root font, colour, no hover information, in the light colour scheme (or the dark one: css/index.ts
4
+ // resolves an email whose styles change with `prefers-color-scheme` in both). There is no stylesheet to
5
+ // re-evaluate them later, so a query is a constant. Anything this does not know (a feature, a unit, a malformed query) is
6
+ // false, as a browser treats a query it cannot parse as `not all`.
7
+ import { parseComponents, type CV } from './tokenize.js';
8
+
9
+ export type Media = 'wide' | 'narrow';
10
+ export type Scheme = 'light' | 'dark';
11
+
12
+ interface Screen {
13
+ width: number;
14
+ height: number;
15
+ scheme: Scheme;
16
+ }
17
+ const SIZES: Record<Media, { width: number; height: number }> = { wide: { width: 800, height: 600 }, narrow: { width: 375, height: 667 } };
18
+
19
+ /** a media query list (`@media`'s prelude, a `media` attribute): true when any query matches */
20
+ export function matchMedia(list: CV[] | string, media: Media, scheme: Scheme = 'light'): boolean {
21
+ const items = typeof list === 'string' ? parseComponents(list) : list;
22
+ const queries = split(items);
23
+ // an empty list matches everything
24
+ if (queries.length === 1 && queries[0].length === 0) return true;
25
+ const screen: Screen = { ...SIZES[media], scheme };
26
+ return queries.some((q) => query(q, screen) === true);
27
+ }
28
+
29
+ /** split at top-level commas, whitespace trimmed */
30
+ function split(items: CV[]): CV[][] {
31
+ const out: CV[][] = [[]];
32
+ for (const v of items) {
33
+ if (v.t === ',') out.push([]);
34
+ else if (v.t !== 'ws') out[out.length - 1].push(v);
35
+ }
36
+ return out;
37
+ }
38
+
39
+ // three-valued logic: true, false, or null (unknown), which a query as a whole reads as false
40
+ type K = boolean | null;
41
+ const not = (v: K): K => (v === null ? null : !v);
42
+
43
+ const TYPES_TRUE = new Set(['all', 'screen']);
44
+ const TYPES_FALSE = new Set(['print', 'tty', 'tv', 'projection', 'handheld', 'braille', 'embossed', 'aural', 'speech']);
45
+ const RESERVED = new Set(['only', 'not', 'and', 'or', 'layer']);
46
+
47
+ function query(q: CV[], screen: Screen): K {
48
+ if (q.length === 0) return false;
49
+ const first = q[0];
50
+ if ((first.t === 'block' && first.open === '(') || (first.t === 'ident' && first.v.toLowerCase() === 'not' && q[1]?.t === 'block')) {
51
+ return condition(q, 0, screen, true) ?? false;
52
+ }
53
+ // [not | only]? <media-type> [and <condition-without-or>]?
54
+ let i = 0;
55
+ let negate = false;
56
+ const kw = (v: CV | undefined) => (v?.t === 'ident' ? v.v.toLowerCase() : null);
57
+ if (kw(q[0]) === 'not') { negate = true; i++; } else if (kw(q[0]) === 'only') i++;
58
+ const type = kw(q[i]);
59
+ if (type === null || RESERVED.has(type)) return false;
60
+ i++;
61
+ let r: K = TYPES_TRUE.has(type) ? true : TYPES_FALSE.has(type) ? false : false;
62
+ if (i < q.length) {
63
+ if (kw(q[i]) !== 'and' || i + 1 >= q.length) return false;
64
+ const c = condition(q, i + 1, screen, false);
65
+ if (c === undefined) return false;
66
+ r = r === false ? false : c === false ? false : r === true && c === true ? true : null;
67
+ }
68
+ return negate ? not(r) : r;
69
+ }
70
+
71
+ /**
72
+ * A media condition from `q[i]` to the end: `not <in-parens>`, or in-parens joined by `and` (or `or`
73
+ * when `or` is allowed: not after a media type). undefined when malformed.
74
+ */
75
+ function condition(q: CV[], i: number, screen: Screen, orAllowed: boolean): K | undefined {
76
+ const kw = (v: CV | undefined) => (v?.t === 'ident' ? v.v.toLowerCase() : null);
77
+ if (kw(q[i]) === 'not') {
78
+ if (i + 2 !== q.length) return undefined;
79
+ const v = inParens(q[i + 1], screen);
80
+ return v === undefined ? undefined : not(v);
81
+ }
82
+ let r = inParens(q[i], screen);
83
+ if (r === undefined) return undefined;
84
+ let op: string | null = null;
85
+ for (let j = i + 1; j < q.length; j += 2) {
86
+ const k = kw(q[j]);
87
+ if ((k !== 'and' && k !== 'or') || (op && k !== op) || (k === 'or' && !orAllowed)) return undefined;
88
+ op = k;
89
+ const v = inParens(q[j + 1], screen);
90
+ if (v === undefined) return undefined;
91
+ if (k === 'and') r = r === false || v === false ? false : r === true && v === true ? true : null;
92
+ else r = r === true || v === true ? true : r === false && v === false ? false : null;
93
+ }
94
+ return r;
95
+ }
96
+
97
+ /** `( <condition> )` or `( <feature> )`; a parenthesized thing that is neither is unknown */
98
+ function inParens(v: CV | undefined, screen: Screen): K | undefined {
99
+ if (!v || v.t !== 'block' || v.open !== '(') {
100
+ // a function here is <general-enclosed>: unknown
101
+ return v?.t === 'func' ? null : undefined;
102
+ }
103
+ const items = v.items.filter((x) => x.t !== 'ws');
104
+ if (items.length === 0) return undefined;
105
+ if (items[0].t === 'block' || (items[0].t === 'ident' && items[0].v.toLowerCase() === 'not')) {
106
+ const c = condition(items, 0, screen, true);
107
+ return c === undefined ? null : c;
108
+ }
109
+ return feature(items, screen);
110
+ }
111
+
112
+ // the features this knows, as numbers in px (lengths), plain numbers, or keywords
113
+ type Value = { n: number; kind: 'length' | 'number' | 'ratio' | 'resolution' } | { kw: string };
114
+
115
+ function featureValue(name: string, screen: Screen): Value | null {
116
+ switch (name) {
117
+ case 'width': case 'device-width': return { n: screen.width, kind: 'length' };
118
+ case 'height': case 'device-height': return { n: screen.height, kind: 'length' };
119
+ case 'aspect-ratio': case 'device-aspect-ratio': return { n: screen.width / screen.height, kind: 'ratio' };
120
+ case 'orientation': return { kw: screen.width > screen.height ? 'landscape' : 'portrait' };
121
+ case 'prefers-color-scheme': return { kw: screen.scheme };
122
+ case 'prefers-reduced-motion': case 'prefers-reduced-transparency': return { kw: 'no-preference' };
123
+ case 'prefers-contrast': return { kw: 'no-preference' };
124
+ case 'forced-colors': return { kw: 'none' };
125
+ case 'color': return { n: 8, kind: 'number' };
126
+ case 'color-index': case 'monochrome': case 'grid': return { n: 0, kind: 'number' };
127
+ case 'resolution': return { n: 1, kind: 'resolution' };
128
+ case '-webkit-device-pixel-ratio': return { n: 1, kind: 'number' };
129
+ case 'scan': return { kw: 'progressive' };
130
+ default: return null;
131
+ }
132
+ }
133
+
134
+ const RANGE = new Set(['width', 'height', 'device-width', 'device-height', 'aspect-ratio', 'device-aspect-ratio', 'color', 'color-index', 'monochrome', 'resolution', '-webkit-device-pixel-ratio']);
135
+
136
+ function feature(items: CV[], screen: Screen): K {
137
+ const id = (v: CV | undefined) => (v?.t === 'ident' ? v.v.toLowerCase() : null);
138
+ // (name)
139
+ if (items.length === 1) {
140
+ const name = id(items[0]);
141
+ if (name === null) return null;
142
+ const f = featureValue(name, screen);
143
+ if (!f) return null;
144
+ return 'n' in f ? f.n !== 0 : f.kw !== 'none' && f.kw !== 'no-preference';
145
+ }
146
+ // (name: value), with min-/max- prefixes
147
+ if (items[1].t === ':') {
148
+ let name = id(items[0]);
149
+ if (name === null) return null;
150
+ let cmp: '=' | '>=' | '<=' = '=';
151
+ const prefix = /^(-webkit-)?(min|max)-/.exec(name);
152
+ if (prefix) {
153
+ cmp = prefix[2] === 'min' ? '>=' : '<=';
154
+ name = (prefix[1] ?? '') + name.slice(prefix[0].length);
155
+ }
156
+ const f = featureValue(name, screen);
157
+ if (!f || (prefix && !RANGE.has(name))) return null;
158
+ const rest = items.slice(2);
159
+ if ('kw' in f) return rest.length === 1 && id(rest[0]) === f.kw ? true : rest.length === 1 && rest[0].t === 'ident' ? false : null;
160
+ const v = valueOf(rest, f.kind);
161
+ return v === null ? null : compare(f.n, cmp, v);
162
+ }
163
+ // range syntax: (name op value), (value op name), (value op name op value)
164
+ const ops: { op: string; at: number }[] = [];
165
+ for (let i = 0; i < items.length; i++) {
166
+ const v = items[i];
167
+ if (v.t === 'delim' && (v.v === '<' || v.v === '>' || v.v === '=')) {
168
+ let op = v.v;
169
+ const next = items[i + 1];
170
+ if (op !== '=' && next?.t === 'delim' && next.v === '=') { op += '='; i++; }
171
+ ops.push({ op, at: i });
172
+ }
173
+ }
174
+ if (ops.length < 1 || ops.length > 2) return null;
175
+ const parts: CV[][] = [];
176
+ let from = 0;
177
+ for (const o of ops) {
178
+ parts.push(items.slice(from, o.at - (o.op.length - 1)));
179
+ from = o.at + 1;
180
+ }
181
+ parts.push(items.slice(from));
182
+ const nameAt = parts.findIndex((p) => p.length === 1 && id(p[0]) !== null && featureValue(id(p[0])!, screen) !== null);
183
+ if (nameAt < 0) return null;
184
+ const name = id(parts[nameAt][0])!;
185
+ const f = featureValue(name, screen)!;
186
+ if ('kw' in f || !RANGE.has(name)) return null;
187
+ if (ops.length === 2) {
188
+ // both ops point the same way, neither is `=`, and the name is in the middle
189
+ if (nameAt !== 1 || ops[0].op[0] !== ops[1].op[0] || ops[0].op === '=' || ops[1].op === '=') return null;
190
+ }
191
+ let r: K = true;
192
+ for (let k = 0; k < ops.length; k++) {
193
+ const left = parts[k];
194
+ const right = parts[k + 1];
195
+ const op = ops[k].op as '<' | '<=' | '>' | '>=' | '=';
196
+ // the comparison as "feature op value"
197
+ if (k + 1 === nameAt) {
198
+ const v = valueOf(left, f.kind);
199
+ if (v === null) return null;
200
+ const flipped = ({ '<': '>', '<=': '>=', '>': '<', '>=': '<=', '=': '=' } as const)[op];
201
+ r = r && compare(f.n, flipped, v);
202
+ } else if (k === nameAt) {
203
+ const v = valueOf(right, f.kind);
204
+ if (v === null) return null;
205
+ r = r && compare(f.n, op, v);
206
+ } else return null;
207
+ }
208
+ return r;
209
+ }
210
+
211
+ function compare(a: number, op: '<' | '<=' | '>' | '>=' | '=', b: number): boolean {
212
+ // a little tolerance, so a ratio computed in floating point compares equal to the one written
213
+ const eq = Math.abs(a - b) < 1e-9;
214
+ switch (op) {
215
+ case '=': return eq;
216
+ case '<': return a < b && !eq;
217
+ case '<=': return a < b || eq;
218
+ case '>': return a > b && !eq;
219
+ case '>=': return a > b || eq;
220
+ }
221
+ }
222
+
223
+ const PX: Record<string, number> = { px: 1, em: 16, rem: 16, ex: 8, ch: 8, pt: 96 / 72, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, q: 96 / 101.6 };
224
+ const DPPX: Record<string, number> = { dppx: 1, x: 1, dpi: 1 / 96, dpcm: 2.54 / 96 };
225
+
226
+ /** a feature's value in the feature's unit (px, a plain number, a ratio, dppx), or null */
227
+ function valueOf(items: CV[], kind: 'length' | 'number' | 'ratio' | 'resolution'): number | null {
228
+ if (kind === 'ratio') {
229
+ if (items.length === 1 && items[0].t === 'number' && items[0].n >= 0) return items[0].n;
230
+ if (items.length === 3 && items[0].t === 'number' && items[1].t === 'delim' && items[1].v === '/' && items[2].t === 'number') {
231
+ const a = items[0].n;
232
+ const b = items[2].n;
233
+ if (a < 0 || b < 0) return null;
234
+ return b === 0 ? Infinity : a / b;
235
+ }
236
+ return null;
237
+ }
238
+ if (items.length !== 1) return null;
239
+ const v = items[0];
240
+ if (kind === 'length') {
241
+ if (v.t === 'number' && v.n === 0) return 0;
242
+ if (v.t === 'dimension') {
243
+ const k = PX[v.unit.toLowerCase()];
244
+ return k === undefined ? null : v.n * k;
245
+ }
246
+ return null;
247
+ }
248
+ if (kind === 'resolution') {
249
+ if (v.t !== 'dimension') return null;
250
+ const k = DPPX[v.unit.toLowerCase()];
251
+ return k === undefined ? null : v.n * k;
252
+ }
253
+ return v.t === 'number' ? v.n : null;
254
+ }