@tiavision/sinter-mail 0.1.0 → 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.
package/README.md CHANGED
@@ -1,9 +1,10 @@
1
1
  # @tiavision/sinter-mail
2
2
 
3
- Email for [sinter](https://github.com/tiaforge/sinter): a parser, `mail.parse`, that turns an email's HTML
4
- body into a tree, `mail.plain` for plain-text bodies, and a component, `<mail-body>`, that renders the tree
5
- as part of the page, without an iframe. An email in a file is plain HTML at build time; an email from an
6
- API is parsed in the browser, or on the server.
3
+ Show email in your [sinter](https://github.com/tiaforge/sinter) app, without an iframe.
4
+
5
+ Hand it an email's HTML (or plain text) and it renders as a normal part of your page: it scrolls, selects,
6
+ searches and prints with the rest, and picks up your fonts where the email sets none. Nothing in an email
7
+ runs, loads from the network without your say-so, or reaches outside its box.
7
8
 
8
9
  ```html
9
10
  <sn-resource name="msg" src="/api/messages/{$url.id}"></sn-resource>
@@ -12,126 +13,101 @@ API is parsed in the browser, or on the server.
12
13
  </article>
13
14
  ```
14
15
 
15
- **Using it:** [docs/mail.md](docs/mail.md). **Why it is built this way:**
16
- [docs/proposals/sinter-mail.md](docs/proposals/sinter-mail.md).
16
+ ## Why
17
17
 
18
- The rest of this file is for working on the library: what each part is, why it is where it is, and how it
19
- is checked.
18
+ Webmail UIs usually put a message in an iframe, or sanitize its HTML and inject it with `innerHTML`.
19
+ sinter never builds HTML from data, so this library takes a third route: `mail.parse` turns the email into a
20
+ tree, and generated components render each element, with every attribute and style checked.
20
21
 
21
- ## Status
22
+ - **Safe by construction.** No script, handler, `javascript:` link, SVG, form or iframe can exist in the tree.
23
+ The page's CSP can stay strict (`script-src 'self'`, Trusted Types).
24
+ - **Private images.** Remote images are left out by default, so tracking pixels never fire. Turn them on, or
25
+ route them through your own proxy so senders never see your readers' addresses.
26
+ - **Looks like the sender's email.** The parser follows the HTML standard, and the email's styles
27
+ (`<style>` rules, inline styles, legacy attributes like `bgcolor` and `<font>`) are resolved the way a
28
+ browser's cascade would.
29
+ - **Fast where it counts.** An email in a file is folded into plain HTML at build time, with no JavaScript.
30
+ Long messages render progressively. Parse in the browser, lazily, or on your server.
31
+ - **Plain text too.** `mail.plain` handles `text/plain` bodies: links, quotes, signatures and
32
+ `format=flowed`.
22
33
 
23
- Version 0.1. It needs sinter 0.20.0 or later, the first release with the changes made for this library
24
- (tiaforge/sinter#76, #77 and #78); `sinter check` says so (SN537) when an app has an older one.
34
+ ## Install
25
35
 
26
- ## Releasing
36
+ ```sh
37
+ npm install @tiavision/sinter-mail
38
+ ```
27
39
 
28
- From GitHub's UI: Actions → Release → Run workflow (on `main`) → the version. The [Release
29
- workflow](.github/workflows/release.yml) sets package.json to it and commits on a temporary branch, checks
30
- that the package builds against a sinter from npm, runs CI on that commit, and only then tags it `v<version>`
31
- and publishes to npm with a provenance attestation; then it moves `main` to the release commit, makes the
32
- GitHub release and deletes the branch. A run that fails before the tag leaves nothing to clean up. A pre-release
33
- (`0.2.0-rc.1`) goes out under the `next` dist-tag. Publishing a GitHub release for an existing tag
34
- `v<the version in package.json>` runs the same checks and publish.
40
+ Needs sinter 0.20.0 or later.
35
41
 
36
- Publishing needs, once:
42
+ ```js
43
+ // vite.config.js
44
+ import { defineConfig } from 'vite';
45
+ import sinter from '@tiaforge-ui/sinter/vite';
37
46
 
38
- - Before the first release: the `release` environment (Settings → Environments) with the secret `NPM_TOKEN`, a
39
- granular npm token that may publish under `@tiavision`. Trusted publishing can only be set up for a package
40
- that exists, so the first publish uses it.
41
- - After it: `@tiavision/sinter-mail` → Settings → Trusted publishing → GitHub Actions: `tiavision/sinter-mail`,
42
- workflow `release.yml`, environment `release`, allowed to publish (the workflow runs `npm publish`; a
43
- publisher that may only stage is refused, with a 404). Then delete `NPM_TOKEN` and revoke the token: later
44
- releases need no secret.
47
+ export default defineConfig({
48
+ plugins: [sinter({ components: ['@tiavision/sinter-mail'] })],
49
+ });
50
+ ```
45
51
 
46
- ## The package
52
+ ```ts
53
+ // src/sinter.helpers.ts: the helpers, as the namespace `mail`
54
+ export * as mail from '@tiavision/sinter-mail';
47
55
 
56
+ // src/sinter.types.ts: the tree's types, for your own declarations
57
+ export type { Body, Element } from '@tiavision/sinter-mail';
48
58
  ```
49
- package.json "sinter": "./sinter", exports ".", "./parser" (the lazy part)
50
- sinter/
51
- components/
52
- mail-body.html public: one body, and the slots an app fills (`link`, `image`)
53
- internal/ generated from tags.ts: one component per tag, the dispatch, the table, the
54
- steps of a progressive render (mail-steps.ts beside it)
55
- sinter.types.ts the tree's types: what apps and the components name
56
- tags.ts the tag table: tags, their attributes, the properties each binds, what is dropped
57
- parse.ts mail.parse: options, the tree from the raw document and the resolved styles
58
- engine.ts what mail.parse runs, behind `@tiavision/sinter-mail/parser`: parser and cascade
59
- parser/ the HTML parser: the standard's tokenizer and tree construction; entities.ts generated
60
- css/ the cascade: tokenizer, selectors, media, values, legacy hints
61
- raw.ts the raw tree between the parser and the cascade
62
- plain.ts, autolink.ts mail.plain, with GFM's autolinks
63
- tree.ts mail.text, mail.links, mail.progressive
64
- sinter.helpers.ts the helpers, re-exported by the entry
65
- index.ts the entry
66
- scripts/
67
- build-components.mjs writes sinter/components/internal/ from tags.ts; --check
68
- build-entities.mjs writes sinter/parser/entities.ts; --check
69
- fixtures/ pages for `sinter check`, and trees as JSON
70
- test/ the tests (vitest), test/corpus/ the emails they read
71
- docs/ the guide and the proposals
59
+
60
+ ## Usage
61
+
62
+ **HTML email**
63
+
64
+ ```html
65
+ <article data-sn-let="{ body: mail.parse(msg.html) }">
66
+ <mail-body data-sn-prop="{ body }"></mail-body>
67
+ </article>
72
68
  ```
73
69
 
74
- ### Why it is built this way
75
-
76
- - **The email is a tree, rendered by templates.** sinter never creates HTML from data, so an email cannot
77
- be `innerHTML`. `mail.parse` builds a tree, and each element of it is rendered by a generated component
78
- whose root is that tag: its attributes and styles are bindings with literal names, which sinter checks
79
- at build time and sets with its checked writers at runtime.
80
- - **The parser is the HTML standard's.** The tree must be the one the browser would build from the same
81
- HTML; otherwise a page built at build time would be reparsed into another tree, and an email would look
82
- different from what its sender tested. `test/parser.test.ts` compares it with parse5 on targeted cases and
83
- thousands of random documents.
84
- - **Styles are resolved, not shipped.** A stylesheet from data would be a sink sinter does not have. The
85
- cascade runs at parse time instead and every element carries its own declarations. Email is where that
86
- costs least: email clients already drop most of what this drops.
87
- - **One table for every list.** `sinter/tags.ts` is the only place that says what an email may contain;
88
- the parser's allowlist, the tree's types and the components come from it, and
89
- `test/components.test.ts` fails when they disagree.
90
- - **The table is one component.** The HTML parser moves a component's tag written inside a `<table>` out
91
- of it, so a table's caption, columns, sections, rows and cells are literal in `mail-table`; cell content
92
- goes through `mail-node` as everywhere else.
93
- - **No whitespace between tags** in the generated components: whitespace in a component is text in the
94
- page, once per row, and would show in tables and inline content.
95
- - **Pure helpers.** `mail.parse`, `mail.plain`, `mail.text` and `mail.links` use only the language's
96
- globals and `URL`, and no module keeps state between calls, so sinter runs them at build time over a
97
- `file:` email. `mail.parse` keeps its trees with sinter's `memo()`; its options are normalized to
98
- primitives first, so equal policies share a tree.
99
- - **The parser is behind its own specifier.** `parse.ts` imports the parser and the cascade as
100
- `@tiavision/sinter-mail/parser`, so an app that lists the package in `sinter({ lazy })` loads them on
101
- demand; `plain.ts` and `tree.ts` import neither and stay ordinary helpers.
102
-
103
- ## Changing it
104
-
105
- - **A tag:** add it to `Tag` in `sinter/sinter.types.ts` and to `TAGS` in `sinter/tags.ts` (its attributes
106
- and the property groups it binds), then `npm run build:components`. A tag that only makes sense inside a
107
- table is `inTable` and goes into the table component's structure (`scripts/build-components.mjs`).
108
- - **An attribute:** add it to `Attrs`, to the tag in `TAGS`, and to `attribute()` in `sinter/parse.ts`, which
109
- checks its value.
110
- - **A property:** add it to `Property` and to a group in `sinter/tags.ts`, give it a grammar in
111
- `sinter/css/values.ts`, then `npm run build:components`. Never one that positions, loads or escapes the
112
- box (docs/mail.md, Security).
113
- - **The entity table:** `npm run build:entities` after updating `character-entities`.
114
-
115
- ## Checking and testing
70
+ **Images through your proxy**
116
71
 
117
- ```sh
118
- npm ci
119
- npx sinter check # the fixture pages: compiled, type-checked, the library's rules
120
- npm run typecheck
121
- npm test # vitest: 200 tests, Chromium included
72
+ ```js
73
+ mail.parse(html, { images: 'proxy', proxy: '/img?url={url}' })
122
74
  ```
123
75
 
124
- | Test | What it covers |
125
- | --- | --- |
126
- | `test/parser.test.ts` | the parser against parse5: targeted cases, seeded random documents, the depth bound, hostile timings, the entity table up to date, purity |
127
- | `test/css.test.ts` | tokenizer, values and shorthands, selectors and specificity, media, the cascade's order, legacy hints, hostile stylesheets |
128
- | `test/css.browser.test.ts` | the cascade against Chromium's computed styles on email-like documents, at both widths |
129
- | `test/parse.test.ts` | mail.parse: what is kept, links, ids, images, options, the cache, the corpus's invariants, 35 attacks |
130
- | `test/plain.test.ts`, `test/tree.test.ts` | mail.plain and autolinks, mail.text and mail.links |
131
- | `test/components.test.ts` | the tag table, the types, the dispatch and the files agree; the generated files are current |
132
- | `test/check.test.ts` | `sinter check --strict` over the fixtures: no error, no warning |
133
- | `test/static.test.ts` | an email folded at build time: no JavaScript, the HTML is the tree |
134
- | `test/browser.test.ts` | Chromium under `script-src 'self'; style-src 'self'; require-trusted-types-for 'script'`: no violation, the styles applied; the CSP a folded email needs; render time and size |
76
+ **Inline (`cid:`) images**
77
+
78
+ ```js
79
+ mail.parse(html, { cid: '/api/messages/42/parts?cid={cid}' })
80
+ ```
81
+
82
+ **Plain text**
83
+
84
+ ```js
85
+ mail.plain(text, { flowed: true })
86
+ ```
87
+
88
+ **An email from a file, folded at build time** (`src="file:./welcome.html"`): the page ships it as plain
89
+ HTML, with no JavaScript. See [the guide](docs/mail.md#three-places-one-function).
90
+
91
+ **Previews and search snippets**
92
+
93
+ ```js
94
+ mail.text(body) // the text, blocks separated by newlines
95
+ mail.links(body) // every link with its text
96
+ ```
97
+
98
+ Links and images can be restyled by filling the `link` and `image` slots of `<mail-body>`.
99
+
100
+ ## Documentation
101
+
102
+ - **[The guide](docs/mail.md)**: all options, what is kept and dropped, styling, proxies, progressive
103
+ rendering, slots, CSP, and the security guarantees.
104
+ - **[Design notes](docs/proposals/sinter-mail.md)**: why it is built the way it is.
105
+ - **[Contributing](CONTRIBUTING.md)**: layout, tests and the release process.
106
+
107
+ ## Limits
108
+
109
+ Only the email's own styles apply (no `:hover`, animation or web fonts), `@media` is decided once at parse
110
+ time (but for the colour scheme: colours set by `prefers-color-scheme: dark` rules follow the page's), and the library is tested in Chromium so far. [The guide](docs/mail.md#limits) has the full list.
135
111
 
136
112
  ## License
137
113
 
package/docs/mail.md CHANGED
@@ -81,8 +81,9 @@ An invalid option throws at each call (`mail.parse: \`images\` is 'block', 'allo
81
81
  same source and options give the same tree, frozen and shared: change a copy (`structuredClone(body)`).
82
82
 
83
83
  The tree (`Body`) has the email's elements (`type: 'element'`, `tag`, `attrs`, `style`, `children`) and
84
- texts, the body's own `style` (its background and font, rendered on the root), and `images.origins`: every
85
- remote image's origin, sorted, for a "show images from …" control.
84
+ texts, the body's own `style` (its background and font, rendered on the root), `images.origins`: every
85
+ remote image's origin, sorted, for a "show images from …" control, and `schemes` ([Colour
86
+ schemes](#colour-schemes)).
86
87
 
87
88
  ### What is kept
88
89
 
@@ -112,7 +113,7 @@ There is no stylesheet. `mail.parse` resolves each element's styles, as a browse
112
113
 
113
114
  It keeps 60 properties (colours, fonts, text, box, borders, table layout, display, float), each
114
115
  value re-serialized. Selectors with `:hover`, `:focus`, `::before` and the like never match; `@media` rules
115
- are evaluated at the `media` option's width; `@import`, `@font-face`, `@keyframes` and `@supports` are
116
+ are evaluated at the `media` option's width (and `prefers-color-scheme` for both schemes, below); `@import`, `@font-face`, `@keyframes` and `@supports` are
116
117
  dropped. Never kept: `position`, `z-index`, `transform`, `url()` in any value (background images
117
118
  included), `var()`, `calc()`, negative margins.
118
119
 
@@ -132,6 +133,35 @@ included), `var()`, `calc()`, negative margins.
132
133
  A wide newsletter (600 px of tables) is as wide as it is: put `<mail-body>` in a box with
133
134
  `overflow-x: auto` for narrow screens.
134
135
 
136
+ ### Colour schemes
137
+
138
+ Most emails are written for a white page: dark text, if they set a colour at all. Some say they work on a dark
139
+ one too, and `body.schemes` reports it (`['light', 'dark']`; absent when the email says nothing):
140
+
141
+ - **declared**: its `color-scheme` or `supported-color-schemes` meta, or `color-scheme` on `<html>` or
142
+ `<body>` (as a style attribute or a rule). The email's colours are kept as written: it is saying they work
143
+ on either page.
144
+ - **dark rules**: `@media (prefers-color-scheme: dark)` (or a `<style media>` with it). The cascade runs for
145
+ both schemes, and a colour that differs (`color`, `background-color`, the border and decoration colours) is
146
+ written `light-dark(<light>, <dark>)`, the initial value standing in for a scheme that does not set it
147
+ (`light-dark(currentcolor, #fff)`). The browser picks one by the colour scheme the element is shown in: the
148
+ page's (`<meta name="color-scheme" content="light dark">` follows the system), or what the app sets around
149
+ the body. Then `schemes` includes `dark`.
150
+
151
+ So an app in dark mode can show an email with `dark` in `schemes` as it is, on its own dark page, and keep any
152
+ other email that sets colours light:
153
+
154
+ ```css
155
+ .mail-light { color-scheme: light; background: Canvas; color: CanvasText; }
156
+ ```
157
+
158
+ ```html
159
+ <div data-sn-class="{ 'mail-light': !tree.schemes?.includes('dark') }"><mail-body data-sn-prop="{ body: tree }"></mail-body></div>
160
+ ```
161
+
162
+ A dark rule's other properties (a light logo hidden, a dark one shown) keep their light values:
163
+ `light-dark()` takes colours only.
164
+
135
165
  Quotes and signatures that `mail.plain` finds carry the classes `mail-quote` and `mail-signature`, for
136
166
  your styles (`.mail-signature { opacity: .7 }`).
137
167
 
@@ -258,7 +288,8 @@ yet.
258
288
 
259
289
  - Only the email's own styles and the browser's: no `:hover`, no animation, no web fonts, no background
260
290
  images.
261
- - `@media` is decided at parse time, for one width (`media`), not as the reader resizes.
291
+ - `@media` is decided at parse time, for one width (`media`), not as the reader resizes. Only the colour
292
+ scheme follows the page, and only for colours (`light-dark()`).
262
293
  - Quirks mode is not followed: class names match case-sensitively and unitless lengths are dropped.
263
294
  - The parser's size: about 32 kB gzip with the cascade, most of it the HTML standard's entity table and
264
295
  tree construction. A server that sends the tree ships none of it.
package/llms.txt CHANGED
@@ -8,6 +8,7 @@ Setup: `sinter({ components: ['@tiavision/sinter-mail'] })`; `export * as mail f
8
8
  - `mail.plain(text, { flowed, delsp })`: paragraphs, autolinks, `>` quotes (class mail-quote), `-- ` signature (class mail-signature); `flowed` for format=flowed.
9
9
  - `mail.text(node)`: the text, for previews. `mail.links(body)`: every link with its text.
10
10
  - `body.images.origins`: the origins of the remote images, for a "show images from …" control.
11
+ - `body.schemes`: `['light', 'dark']` and the like when the email declares its colour schemes (`color-scheme` meta or property, `supported-color-schemes`); `dark` also when it has `prefers-color-scheme: dark` rules, whose colours are written `light-dark(<light>, <dark>)` and follow the scheme the body is shown in. Absent: written for a white page (keep it light on a dark page: `color-scheme: light` around it).
11
12
  - `<mail-body>` slots: `link` (`$slot.node`, its children through `<slot></slot>`) and `image` (`$slot.node.attrs.src` absent when blocked).
12
13
  - `mail.progressive(tree)`: `<mail-body data-sn-prop="{ body: mail.progressive(tree) }">` renders a long body progressively, its first 200 nodes first, the rest in steps of 5 to 15 ms after a paint; a body not numbered renders whole (static pages stay script-free).
13
14
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiavision/sinter-mail",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Email bodies for sinter: HTML and plain-text mail parsed into a tree that folds at build time, rendered by mail-* components without an iframe.",
5
5
  "license": "MIT",
6
6
  "author": "Tia Heinrich",
@@ -5,6 +5,12 @@
5
5
  // element's style, rendered inline by data-sn-style: there is no stylesheet to evaluate later, so
6
6
  // `@media` is decided here too (the `media` option), and selectors are matched against the raw tree.
7
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
+ //
8
14
  // Inheritance is not computed: the tree keeps the document's structure, so an inline style inherits in
9
15
  // the app as it did in the email.
10
16
  //
@@ -13,7 +19,7 @@ import { attr, type RawElement } from '../raw.js';
13
19
  import { PROPERTIES } from '../tags.js';
14
20
  import type { Property, Style } from '../sinter.types.js';
15
21
  import { hints, legacyColor } from './hints.js';
16
- import { matchMedia, type Media } from './media.js';
22
+ import { matchMedia, type Media, type Scheme } from './media.js';
17
23
  import { parseDeclarations, parseStylesheet, rules as parseRules, type Declaration, type Rule } from './parse.js';
18
24
  import { bucketKey, exhausted, indexTree, matches, parseSelectorList, type Budget, type Complex } from './selectors.js';
19
25
  import { expand, joinOverflow, joinTextDecoration, type Assignment, type Longhand } from './values.js';
@@ -28,14 +34,40 @@ export interface ResolveOptions {
28
34
  media: Media;
29
35
  }
30
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
+
31
49
  // every tracked longhand by number: an element's values are an array, not a map, since a hostile
32
50
  // stylesheet can match thousands of rules on every element
33
51
  const LONGHANDS: Longhand[] = [
34
52
  ...(PROPERTIES.filter((p) => p !== 'text-decoration' && p !== 'overflow') as Longhand[]),
35
53
  'text-decoration-line', 'text-decoration-style', 'text-decoration-color', 'overflow-x', 'overflow-y',
54
+ 'color-scheme',
36
55
  ];
37
56
  const ID = new Map(LONGHANDS.map((l, i) => [l, i]));
38
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
+
39
71
  /**
40
72
  * Assignments as parallel arrays of longhand numbers and values, the last one per longhand only, and
41
73
  * which longhands they set as a bit mask in three 30-bit words (small integers), so a rule whose
@@ -64,6 +96,8 @@ interface Entry {
64
96
  normal: Compiled;
65
97
  /** null when the rule has no !important declaration */
66
98
  important: Compiled | null;
99
+ /** the schemes its `@media` (or its `<style media>`) applies in: LIGHT, DARK or BOTH */
100
+ schemes: number;
67
101
  }
68
102
 
69
103
  // the matching work allowed for one resolve (selectors.ts, budget): a 1,800-element newsletter with
@@ -88,16 +122,27 @@ const MAX_MEDIA_DEPTH = 16;
88
122
  * Elements whose style is empty have no entry.
89
123
  */
90
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 {
91
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));
92
134
  const all = indexTree(root);
93
135
 
94
136
  // the author rules, from every <style> in document order
95
137
  const buckets = new Map<string, Entry[]>();
96
138
  let order = 0, ids = 0;
97
- const addRules = (list: Rule[], depth: number) => {
139
+ const addRules = (list: Rule[], depth: number, schemes: number) => {
98
140
  for (const r of list) {
99
141
  if (r.t === 'at') {
100
- if (r.name === 'media' && r.block && depth < MAX_MEDIA_DEPTH && matchMedia(r.prelude, media)) addRules(parseRules(r.block.items, false), depth + 1);
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
+ }
101
146
  // @import, @font-face, @keyframes, @supports, @layer, @page, @charset and the rest: dropped
102
147
  continue;
103
148
  }
@@ -112,18 +157,19 @@ export function resolveStyles(root: RawElement, options: ResolveOptions): Map<Ra
112
157
  const key = bucketKey(sel);
113
158
  let b = buckets.get(key);
114
159
  if (!b) buckets.set(key, (b = []));
115
- b.push({ id: ids++, sel, specificity: sel.specificity, order: o, normal: rule.normal, important: rule.important.props.length ? rule.important : null });
160
+ b.push({ id: ids++, sel, specificity: sel.specificity, order: o, normal: rule.normal, important: rule.important.props.length ? rule.important : null, schemes });
116
161
  }
117
162
  }
118
163
  };
119
164
  for (const e of all) {
120
165
  if (e.el.tag !== 'style' || !isCss(e.el)) continue;
121
166
  const m = attr(e.el, 'media');
122
- if (m !== null && !matchMedia(m, media)) continue;
167
+ const schemes = m === null ? BOTH : schemesOf(m, BOTH);
168
+ if (!schemes) continue;
123
169
  let text = '';
124
170
  for (const c of e.el.children) if (c.type === 'text') text += c.value;
125
171
  if (ids >= MAX_RULES) break;
126
- addRules(parseStylesheet(text), 0);
172
+ addRules(parseStylesheet(text), 0, schemes);
127
173
  }
128
174
 
129
175
  const body = all.find((e) => e.el.tag === 'body' && e.parent?.el === root) ?? null;
@@ -137,6 +183,17 @@ export function resolveStyles(root: RawElement, options: ResolveOptions): Map<Ra
137
183
  const out = new Map<RawElement, Style>();
138
184
  const universal = buckets.get('*');
139
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
+ }
140
197
  const work: Budget = { left: MAX_STEPS };
141
198
  // Emails repeat themselves: builders write the same inline style and legacy attributes on every cell of
142
199
  // a kind, and those cells match the same rules. So within one resolve: an inline style is parsed once
@@ -168,8 +225,10 @@ export function resolveStyles(root: RawElement, options: ResolveOptions): Map<Ra
168
225
  // the hints (no `|` in them), the matched entries' ids, then the inline text: unambiguous. Not for an
169
226
  // element that matches more than CACHED rules (a hostile stylesheet's thousands): its key would cost
170
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;
171
230
  let key: string | null = null;
172
- if (candidates.length <= CACHED) {
231
+ if (candidates.length <= CACHED && !rootOrBody) {
173
232
  key = hkey + '|';
174
233
  for (const c of candidates) key += c.id + ',';
175
234
  key += '|' + (inline ?? '');
@@ -180,33 +239,52 @@ export function resolveStyles(root: RawElement, options: ResolveOptions): Map<Ra
180
239
  }
181
240
  }
182
241
 
183
- // from the highest precedence down, each longhand taken from the first that sets it: inline
184
- // !important, author !important (the last in cascade order first), inline, author, hints
185
- values.fill(undefined);
186
- let s0 = 0, s1 = 0, s2 = 0;
187
- const apply = (c: Compiled) => {
188
- if (!((c.m0 & ~s0) | (c.m1 & ~s1) | (c.m2 & ~s2))) return;
189
- for (let i = 0; i < c.props.length; i++) if (values[c.props[i]] === undefined) values[c.props[i]] = c.values[i];
190
- s0 |= c.m0; s1 |= c.m1; s2 |= c.m2;
191
- };
192
242
  let own: StyleRule | null = null;
193
243
  if (inline !== null) {
194
244
  own = inlines.get(inline) ?? null;
195
245
  if (!own) inlines.set(inline, (own = compile(parseDeclarations(inline))));
196
246
  }
197
- if (own) apply(own.important);
198
- for (let i = candidates.length - 1; i >= 0; i--) { const imp = candidates[i].important; if (imp) apply(imp); }
199
- if (own) apply(own.normal);
200
- for (let i = candidates.length - 1; i >= 0; i--) apply(candidates[i].normal);
201
247
  let h = hinted.get(hkey);
202
248
  if (!h) hinted.set(hkey, (h = compiled(hs)));
203
- apply(h);
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
+ }
204
281
  const style = finish(values);
205
282
  if (key !== null) styles.set(key, style);
206
283
  if (style) out.set(e.el, style);
207
284
  }
208
285
  }
209
- return out;
286
+ const schemes = (['light', 'dark'] as const).filter((s) => colorScheme.has(s));
287
+ return { styles: out, colorScheme: schemes, dark: anyDark };
210
288
  }
211
289
 
212
290
  /** two lists in cascade order as one */
@@ -1,25 +1,28 @@
1
1
  // Media queries (Media Queries Level 4), evaluated once, at parse time, for one of two fixed screens:
2
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, light, colour, no hover information. There is no stylesheet to re-evaluate them
4
- // later, so a query is a constant. Anything this does not know (a feature, a unit, a malformed query) is
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
5
6
  // false, as a browser treats a query it cannot parse as `not all`.
6
7
  import { parseComponents, type CV } from './tokenize.js';
7
8
 
8
9
  export type Media = 'wide' | 'narrow';
10
+ export type Scheme = 'light' | 'dark';
9
11
 
10
12
  interface Screen {
11
13
  width: number;
12
14
  height: number;
15
+ scheme: Scheme;
13
16
  }
14
- const SCREENS: Record<Media, Screen> = { wide: { width: 800, height: 600 }, narrow: { width: 375, height: 667 } };
17
+ const SIZES: Record<Media, { width: number; height: number }> = { wide: { width: 800, height: 600 }, narrow: { width: 375, height: 667 } };
15
18
 
16
19
  /** a media query list (`@media`'s prelude, a `media` attribute): true when any query matches */
17
- export function matchMedia(list: CV[] | string, media: Media): boolean {
20
+ export function matchMedia(list: CV[] | string, media: Media, scheme: Scheme = 'light'): boolean {
18
21
  const items = typeof list === 'string' ? parseComponents(list) : list;
19
22
  const queries = split(items);
20
23
  // an empty list matches everything
21
24
  if (queries.length === 1 && queries[0].length === 0) return true;
22
- const screen = SCREENS[media];
25
+ const screen: Screen = { ...SIZES[media], scheme };
23
26
  return queries.some((q) => query(q, screen) === true);
24
27
  }
25
28
 
@@ -115,7 +118,7 @@ function featureValue(name: string, screen: Screen): Value | null {
115
118
  case 'height': case 'device-height': return { n: screen.height, kind: 'length' };
116
119
  case 'aspect-ratio': case 'device-aspect-ratio': return { n: screen.width / screen.height, kind: 'ratio' };
117
120
  case 'orientation': return { kw: screen.width > screen.height ? 'landscape' : 'portrait' };
118
- case 'prefers-color-scheme': return { kw: 'light' };
121
+ case 'prefers-color-scheme': return { kw: screen.scheme };
119
122
  case 'prefers-reduced-motion': case 'prefers-reduced-transparency': return { kw: 'no-preference' };
120
123
  case 'prefers-contrast': return { kw: 'no-preference' };
121
124
  case 'forced-colors': return { kw: 'none' };
@@ -12,13 +12,15 @@ import type { Property } from '../sinter.types.js';
12
12
  import { parseComponents, type CV, type Func } from './tokenize.js';
13
13
 
14
14
  /**
15
- * What the cascade tracks: the kept properties, and the longhands of the two kept properties that are
16
- * shorthands in CSS (`text-decoration`, `overflow`), joined back when the element's style is written.
15
+ * What the cascade tracks: the kept properties, the longhands of the two kept properties that are
16
+ * shorthands in CSS (`text-decoration`, `overflow`), joined back when the element's style is written, and
17
+ * `color-scheme`, read on the email's `<html>` and `<body>` (the schemes it is written for) and never kept.
17
18
  */
18
19
  export type Longhand =
19
20
  | Exclude<Property, 'text-decoration' | 'overflow'>
20
21
  | 'text-decoration-line' | 'text-decoration-style' | 'text-decoration-color'
21
- | 'overflow-x' | 'overflow-y';
22
+ | 'overflow-x' | 'overflow-y'
23
+ | 'color-scheme';
22
24
 
23
25
  export type Assignment = [Longhand, string];
24
26
 
@@ -339,6 +341,7 @@ const SHORTHANDS: Record<string, Longhand[]> = {
339
341
  'font-family': ['font-family'],
340
342
  'border-spacing': ['border-spacing'],
341
343
  'word-wrap': ['overflow-wrap'],
344
+ 'color-scheme': ['color-scheme'],
342
345
  ...Object.fromEntries(CORNERS.map((c) => [`border-${c}-radius`, [`border-${c}-radius` as Longhand]])),
343
346
  };
344
347
 
@@ -404,10 +407,29 @@ export function expand(name: string, value: CV[] | string): Assignment[] | null
404
407
  const v = xs.length === 1 ? SINGLE['overflow-wrap']!(xs[0]) : null;
405
408
  return v === null ? null : [['overflow-wrap', v]];
406
409
  }
410
+ case 'color-scheme': {
411
+ const v = colorScheme(xs);
412
+ return v === null ? null : [['color-scheme', v]];
413
+ }
407
414
  }
408
415
  return null;
409
416
  }
410
417
 
418
+ /**
419
+ * `color-scheme`: `normal`, or the schemes (`light`, `dark`, names of others) with `only` before or after
420
+ * them; written as the known schemes, `light dark` in that order, or `normal` when it names neither
421
+ */
422
+ function colorScheme(xs: CV[]): string | null {
423
+ const names = xs.map(kw);
424
+ if (names.includes(null)) return null;
425
+ if (names.length === 1 && names[0] === 'normal') return 'normal';
426
+ if (names.includes('normal') || names.filter((n) => n === 'only').length > 1) return null;
427
+ if (names.indexOf('only') > 0 && names.indexOf('only') < names.length - 1) return null;
428
+ const known = (['light', 'dark'] as const).filter((s) => names.includes(s));
429
+ if (names.filter((n) => n !== 'only').length === 0) return null;
430
+ return known.length ? known.join(' ') : 'normal';
431
+ }
432
+
411
433
  /** `border` and `border-<side>`: width || style || colour, each at most once; the rest initial */
412
434
  function border(xs: CV[], sides: readonly (typeof SIDES)[number][]): Assignment[] | null {
413
435
  if (xs.length > 3) return null;
package/sinter/engine.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  // when a let first needs mail.parse; lazy packages are matched by import specifier, so parse.ts imports
4
4
  // them by that name and never by a relative path.
5
5
  export { parseHTML } from './parser/index.js';
6
- export { resolveStyles } from './css/index.js';
6
+ export { resolve, resolveStyles } from './css/index.js';
package/sinter/parse.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  // Pure: the same source and options give the same tree, with no globals beyond the language's and
10
10
  // `URL`, so sinter runs it at build time over a `file:` resource. The tree is kept with sinter's memo():
11
11
  // one parse per source and options, the tree frozen and shared.
12
- import { parseHTML, resolveStyles } from '@tiavision/sinter-mail/parser';
12
+ import { parseHTML, resolve } from '@tiavision/sinter-mail/parser';
13
13
  import { memo } from '@tiaforge-ui/sinter/memo';
14
14
  import type { RawElement, RawNode } from './raw.js';
15
15
  import { attr } from './raw.js';
@@ -141,7 +141,7 @@ interface Context {
141
141
 
142
142
  function build(html: string, o: Options): Body {
143
143
  const root = parseHTML(html);
144
- const styles = resolveStyles(root, { media: o.media });
144
+ const { styles, colorScheme, dark } = resolve(root, { media: o.media });
145
145
  const body = root.children.find((n): n is RawElement => n.type === 'element' && n.tag === 'body');
146
146
  const cx: Context = { o, targets: new Set(), ids: new Set(), origins: new Set(), styles, projected: new Map() };
147
147
  if (body) collectTargets(body, cx.targets);
@@ -153,7 +153,11 @@ function build(html: string, o: Options): Body {
153
153
  if (!s) continue;
154
154
  for (const p of ROOT_PROPS) if (s[p] !== undefined) style[p] = s[p];
155
155
  }
156
- return { type: 'body', style, children, images: { origins: [...cx.origins].sort() } };
156
+ const out: Body = { type: 'body', style, children, images: { origins: [...cx.origins].sort() } };
157
+ // the schemes it is written for: what it declares, and dark too when its colours change with the scheme
158
+ const schemes = (['light', 'dark'] as const).filter((s) => colorScheme.includes(s) || (s === 'dark' && dark));
159
+ if (schemes.length) out.schemes = schemes;
160
+ return out;
157
161
  }
158
162
 
159
163
  const ROOT_PROPS: readonly Property[] = [...TEXT, 'background-color'];
@@ -91,6 +91,15 @@ export interface Body {
91
91
  style: Style;
92
92
  children: Node[];
93
93
  images: ImageInfo;
94
+ /**
95
+ * The colour schemes the email is written for, `light` before `dark`; absent when it says nothing (it was
96
+ * written for a white page). Those its `color-scheme` and `supported-color-schemes` metas name, or the
97
+ * `color-scheme` property of its `<html>` or `<body>`; and `dark` whenever its colours change with
98
+ * `prefers-color-scheme`: then those colours are `light-dark(<light>, <dark>)` in the elements' styles, and
99
+ * follow the colour scheme the body is shown in. With `dark` here, the email may be shown on a dark page as
100
+ * it is; without, an app keeps it light there (`color-scheme: light` around it).
101
+ */
102
+ schemes?: ('light' | 'dark')[];
94
103
  /** set by mail.progressive: <mail-body> renders the nodes with an index below this first, the rest after the browser has painted them */
95
104
  head?: number;
96
105
  /** set by mail.progressive: the body up to `head`, the subtrees it holds whole shared with the body */