dyeworks 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/LICENSE +9 -0
- package/README.md +134 -2
- package/dist/boot.d.ts +7 -0
- package/dist/boot.js +10 -0
- package/dist/chooser.d.ts +33 -0
- package/dist/chooser.js +99 -0
- package/dist/contract-check.d.ts +32 -0
- package/dist/contract-check.js +153 -0
- package/dist/internal/boot-text.d.ts +12 -0
- package/dist/internal/boot-text.js +23 -0
- package/dist/internal/resolve.d.ts +34 -0
- package/dist/internal/resolve.js +44 -0
- package/dist/react/IntensityControl.d.ts +8 -0
- package/dist/react/IntensityControl.js +14 -0
- package/dist/react/ThemeMenu.d.ts +5 -0
- package/dist/react/ThemeMenu.js +15 -0
- package/dist/react/index.d.ts +2 -0
- package/dist/react/index.js +3 -0
- package/dist/react/useChooser.d.ts +3 -0
- package/dist/react/useChooser.js +11 -0
- package/dist/reference.html +73 -0
- package/dist/registry.d.ts +14 -0
- package/dist/registry.js +24 -0
- package/dist/themes.css +68 -0
- package/dist/tokens.css +36 -0
- package/dist/tokens.d.ts +3 -0
- package/dist/tokens.js +2 -0
- package/package.json +83 -4
- package/slots.css +90 -0
- package/slots.json +74 -0
- package/themes/default/theme.css +65 -0
- package/themes/default/theme.json +7 -0
- package/tokens.json +233 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
Versions are git tags `v<semver>`, published to the npm registry by `release.yml`. A new Theme, Token or Slot
|
|
4
|
+
kind with an inert default is a minor; generated images are a patch; a renamed or removed Token, a changed
|
|
5
|
+
Slot treatment or a changed manifest shape is a major, recorded here.
|
|
6
|
+
|
|
7
|
+
## Unreleased
|
|
8
|
+
|
|
9
|
+
- `npm run theme-assets`: the development-time asset generation script, with its alpha check, backdrop
|
|
10
|
+
luminance clamp, budgets and `provenance.json` (`dyeworks-provenance/1`). It is not part of the published
|
|
11
|
+
package; `sharp` is a development dependency.
|
|
12
|
+
|
|
13
|
+
## 1.0.0
|
|
14
|
+
|
|
15
|
+
The first release for consumers.
|
|
16
|
+
|
|
17
|
+
- The Token contract (`tokens.json`, `dyeworks-tokens/1`) and `dist/tokens.css` with every default on `:root`.
|
|
18
|
+
- The Slot vocabulary (`slots.json`, `dyeworks-slots/1`) and the optional `slots.css`.
|
|
19
|
+
- The `default` Theme, light and dark, with inert decoration; `dist/themes.css`.
|
|
20
|
+
- `dyeworks/registry`: `themes` and `options()`, generated from the Theme directories.
|
|
21
|
+
- `dyeworks/chooser`: `createChooser({storageKey, registry, defaults?, mirrorKey?})`.
|
|
22
|
+
- `dyeworks/boot`: `bootScript({storageKey, mirrorKey?})`, the inline script applying the choice before the
|
|
23
|
+
first paint.
|
|
24
|
+
- `dyeworks/react`: `ThemeMenu` and `IntensityControl`; `react` is an optional peer dependency.
|
|
25
|
+
- `dyeworks/contract-check`: `checkContract({stylesheets, tokenMap?, allow?})`.
|
|
26
|
+
- The `themes/` directory shipped for consumers to serve at `/themes/`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Todd Staben
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,135 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dyeworks
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A theme library for web projects on any framework: one **Token contract**, a **Slot vocabulary**, and
|
|
4
|
+
**Themes** as directories that set nothing but Tokens. A page reads the Tokens; a Theme changes their
|
|
5
|
+
values; the page's layout, components and meanings stay its own.
|
|
6
|
+
|
|
7
|
+
Status: `1.0.0`, the first release for consumers. See `CHANGELOG.md`.
|
|
8
|
+
|
|
9
|
+
## What is in the package
|
|
10
|
+
|
|
11
|
+
| File | What it is |
|
|
12
|
+
|---|---|
|
|
13
|
+
| `tokens.json` | The Token contract (`dyeworks-tokens/1`): every Token with its tier, type, one-sentence meaning and default. The whole surface between a Theme and a page. |
|
|
14
|
+
| `slots.json`, `slots.css` | The Slot vocabulary (`dyeworks-slots/1`): nine kinds of place where decoration may appear, the Tokens each reads, and an optional stylesheet implementing each treatment on `[data-slot="<kind>"]`. |
|
|
15
|
+
| `themes/<id>/` | One directory per Theme: `theme.css` (Token declarations only) and `theme.json` (the manifest). |
|
|
16
|
+
| `dist/tokens.css` | Every contract default on `:root`, so a page with no Theme attribute renders as `default` light. |
|
|
17
|
+
| `dist/themes.css` | Every Theme's declarations. |
|
|
18
|
+
| `dist/registry.js` | The generated registry: `themes` (directory order, `default` first) and `options()` for a Theme menu. |
|
|
19
|
+
| `dyeworks/chooser` | `createChooser({storageKey, registry, defaults?, mirrorKey?})`: keeps the choice, resolves it and writes it on `<html>`. |
|
|
20
|
+
| `dyeworks/boot` | `bootScript({storageKey, mirrorKey?})`: the inline script that applies the choice before the first paint. |
|
|
21
|
+
| `dyeworks/react` | `ThemeMenu` and `IntensityControl` over a chooser (`react` is an optional peer dependency). |
|
|
22
|
+
| `dyeworks/contract-check` | `checkContract({stylesheets, tokenMap?, allow?})`: the Contract check a consumer runs in its own tests. |
|
|
23
|
+
| `dist/reference.html` | The contract's reference page, generated from `tokens.json` and `slots.json`. |
|
|
24
|
+
|
|
25
|
+
## Consuming it
|
|
26
|
+
|
|
27
|
+
Install an exact version (`npm install --save-exact dyeworks@1.0.0`) and import the stylesheets:
|
|
28
|
+
|
|
29
|
+
```css
|
|
30
|
+
@import "dyeworks/tokens.css";
|
|
31
|
+
@import "dyeworks/themes.css";
|
|
32
|
+
@import "dyeworks/slots.css"; /* optional */
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Serve the package's `themes/` directory at `/themes/` (copy it into your public directory at build time):
|
|
36
|
+
image Tokens resolve to `url(/themes/<id>/<file>)`.
|
|
37
|
+
|
|
38
|
+
Embed the boot script in your page's `<head>`, before your stylesheets, so the choice applies before the
|
|
39
|
+
first paint. Generate it at build time:
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
import { bootScript } from "dyeworks/boot";
|
|
43
|
+
const inline = `<script>${bootScript({ storageKey: "myapp.theme", mirrorKey: "myapp.theme.default" })}</script>`;
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Create one chooser with your own storage key, and render your own controls from the registry, or the React
|
|
47
|
+
ones:
|
|
48
|
+
|
|
49
|
+
```js
|
|
50
|
+
import * as registry from "dyeworks/registry";
|
|
51
|
+
import { createChooser } from "dyeworks/chooser";
|
|
52
|
+
import { ThemeMenu, IntensityControl } from "dyeworks/react";
|
|
53
|
+
|
|
54
|
+
const chooser = createChooser({ storageKey: "myapp.theme", registry, defaults: serverDefault, mirrorKey: "myapp.theme.default" });
|
|
55
|
+
// <ThemeMenu chooser={chooser} /> <IntensityControl chooser={chooser} />
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The stored object is `{"theme": "<id>", "scheme": "auto" | "light" | "dark", "intensity": 0..1}`; a missing
|
|
59
|
+
or malformed field reads as `default`, `auto`, `0.5`, and an unknown id as `default`. `defaults` applies only
|
|
60
|
+
while storage holds nothing; the chooser copies it to `mirrorKey` so the boot script applies it next load.
|
|
61
|
+
`chooser.get()`, `chooser.set(partial)`, `chooser.resolved()`, `chooser.subscribe(fn)` and
|
|
62
|
+
`chooser.destroy()` are the whole interface; `chooser.registry` is the registry it was given.
|
|
63
|
+
|
|
64
|
+
Read Tokens in your own stylesheet (`background: var(--bg-raised)`), give the data Tokens your own meanings
|
|
65
|
+
in one place, the Token map (`--my-kind-a: var(--series-1)`), and mark your Slots with `data-slot="<kind>"`.
|
|
66
|
+
Never set a contract Token yourself: a page maps Tokens, a Theme sets them.
|
|
67
|
+
|
|
68
|
+
## The Contract check
|
|
69
|
+
|
|
70
|
+
Run it in your own test suite over your stylesheets and inline SVG styles:
|
|
71
|
+
|
|
72
|
+
```js
|
|
73
|
+
import { checkContract } from "dyeworks/contract-check";
|
|
74
|
+
|
|
75
|
+
const findings = checkContract({
|
|
76
|
+
stylesheets: [{ path: "src/app.css", text: appCss }],
|
|
77
|
+
tokenMap: tokenMapCss, // optional
|
|
78
|
+
allow: ["color: black"], // optional: declarations you vouch for
|
|
79
|
+
});
|
|
80
|
+
expect(findings.filter((f) => !f.allowed)).toEqual([]);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Each finding is `{path, line, rule, detail, allowed}`. The rules:
|
|
84
|
+
|
|
85
|
+
1. Every `var(--…)` read is a contract Token, `--intensity`, or a custom property declared in the
|
|
86
|
+
stylesheets given (or the Token map).
|
|
87
|
+
2. No contract Token is set: a consumer maps, it never overrides.
|
|
88
|
+
3. No colour literal (hex, `rgb()`, `hsl()`, `color()`, a literal inside `color-mix()`, a named colour) in a
|
|
89
|
+
`color`, `background*`, `fill`, `stroke`, `border*`, `outline*`, `text-decoration*` or `accent-color`
|
|
90
|
+
value. Shadows (`box-shadow`, `text-shadow`, `drop-shadow()`) are exempt; `transparent` and
|
|
91
|
+
`currentcolor` are not literals. A declaration listed in `allow` is reported with `allowed: true`.
|
|
92
|
+
4. The Token map maps each `--series-*` and `--state-*` at most once and nothing else of the contract. Its
|
|
93
|
+
findings carry the path `token map`.
|
|
94
|
+
|
|
95
|
+
## Tiers
|
|
96
|
+
|
|
97
|
+
- **surface**: backgrounds, text, borders, the accent, the radius and the type faces.
|
|
98
|
+
- **data**: three categorical series colours, six state colours, and the danger and warning colours. They
|
|
99
|
+
carry no meaning of their own; a consumer assigns one.
|
|
100
|
+
- **decoration**: glow, gradient, display face and images. Their defaults are inert, so under `default`
|
|
101
|
+
every decorated Slot shows its plain treatment. A Theme reads `--intensity` (0 to 1, set on `<html>`) to
|
|
102
|
+
scale its decoration.
|
|
103
|
+
|
|
104
|
+
## Developing
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
npm ci
|
|
108
|
+
npm test # shape, manifest, contrast, provenance, Slot, build and Sweep tests
|
|
109
|
+
npm run build # writes dist/: the generated files and the compiled src/
|
|
110
|
+
npm run demo # builds, then serves the demo page at http://127.0.0.1:4173/demo/
|
|
111
|
+
npm run screenshots -- <outdir> # the demo page per Theme and Scheme at Intensity 0, 0.5 and 1
|
|
112
|
+
npm run theme-assets # a Theme author's step: generate missing images from the Prompt sheets
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`npm run theme-assets [-- --theme <id> --slot <slot> --force]` reads every Prompt sheet under
|
|
116
|
+
`themes/<id>/prompts/`, asks the image API for each asset whose image is not yet shipped (or every one with
|
|
117
|
+
`--force`), resizes and strips it, checks a transparent Slot's alpha (retrying the sheet up to three times),
|
|
118
|
+
clamps a backdrop's luminance towards `--bg` in its Scheme's direction, fails an image over its budget, writes
|
|
119
|
+
the image beside its fallback, updates `provenance.json`, and prints the manifest line to add. Its key is read
|
|
120
|
+
from the environment of the machine that runs it; without it the script prints one line, exits non-zero and
|
|
121
|
+
changes nothing. Nothing a consumer runs, and no test or build here, calls the image API: the images are
|
|
122
|
+
committed.
|
|
123
|
+
|
|
124
|
+
The Sweep checks the tracked tree for home paths, email addresses, key-shaped strings, colour literals
|
|
125
|
+
outside `themes/` and `tokens.json`, and rasters or fonts outside `themes/`. Its private layer runs when
|
|
126
|
+
`DYEWORKS_SWEEP_PRIVATE` names a file outside the repository holding one string per line.
|
|
127
|
+
|
|
128
|
+
## Releasing
|
|
129
|
+
|
|
130
|
+
Pushing a tag `v<semver>` that matches `package.json`'s version runs `.github/workflows/release.yml`: it
|
|
131
|
+
builds, tests and publishes to the npm registry by trusted publishing. No token lives in any file.
|
|
132
|
+
|
|
133
|
+
## Licence
|
|
134
|
+
|
|
135
|
+
MIT. See `LICENSE`.
|
package/dist/boot.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type BootOptions } from "./internal/boot-text.js";
|
|
2
|
+
export type { BootOptions };
|
|
3
|
+
/**
|
|
4
|
+
* The inline script text, with a compact registry of every Theme embedded. It applies the stored choice (or
|
|
5
|
+
* the mirror of the consumer's default) on `<html>` before the first paint and does nothing on any failure.
|
|
6
|
+
*/
|
|
7
|
+
export declare function bootScript(options: BootOptions): string;
|
package/dist/boot.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// `dyeworks/boot`: the inline script a consumer embeds in its page before its stylesheets.
|
|
2
|
+
import { renderBootScript } from "./internal/boot-text.js";
|
|
3
|
+
import { themes } from "./registry.js";
|
|
4
|
+
/**
|
|
5
|
+
* The inline script text, with a compact registry of every Theme embedded. It applies the stored choice (or
|
|
6
|
+
* the mirror of the consumer's default) on `<html>` before the first paint and does nothing on any failure.
|
|
7
|
+
*/
|
|
8
|
+
export function bootScript(options) {
|
|
9
|
+
return renderBootScript(themes, options);
|
|
10
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Scheme, ThemeEntry, ThemeOption } from "./registry.js";
|
|
2
|
+
import { type Stored } from "./internal/resolve.js";
|
|
3
|
+
export type { Stored };
|
|
4
|
+
export interface Resolved {
|
|
5
|
+
theme: string;
|
|
6
|
+
scheme: Scheme;
|
|
7
|
+
intensity: number;
|
|
8
|
+
}
|
|
9
|
+
export interface Registry {
|
|
10
|
+
themes: ThemeEntry[];
|
|
11
|
+
options(): ThemeOption[];
|
|
12
|
+
}
|
|
13
|
+
export interface ChooserOptions {
|
|
14
|
+
/** The consumer's storage key for the stored object. */
|
|
15
|
+
storageKey: string;
|
|
16
|
+
/** The generated registry module (`import * as registry from "dyeworks/registry"`). */
|
|
17
|
+
registry: Registry;
|
|
18
|
+
/** The consumer's server default, applied when storage holds nothing. */
|
|
19
|
+
defaults?: Partial<Stored>;
|
|
20
|
+
/** Where the default is copied so the boot script can apply it on the next load. */
|
|
21
|
+
mirrorKey?: string;
|
|
22
|
+
}
|
|
23
|
+
export type Listener = (resolved: Resolved, stored: Stored) => void;
|
|
24
|
+
export interface Chooser {
|
|
25
|
+
get(): Stored;
|
|
26
|
+
set(partial: Partial<Stored>): void;
|
|
27
|
+
resolved(): Resolved;
|
|
28
|
+
subscribe(fn: Listener): () => void;
|
|
29
|
+
destroy(): void;
|
|
30
|
+
/** The registry the chooser was created with, so a menu needs nothing but the chooser. */
|
|
31
|
+
readonly registry: Registry;
|
|
32
|
+
}
|
|
33
|
+
export declare function createChooser({ storageKey, registry, defaults, mirrorKey }: ChooserOptions): Chooser;
|
package/dist/chooser.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { applyResolution, resolveChoice } from "./internal/resolve.js";
|
|
2
|
+
const QUERY = "(prefers-color-scheme: dark)";
|
|
3
|
+
function storage() {
|
|
4
|
+
try {
|
|
5
|
+
return globalThis.localStorage ?? null;
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function read(key) {
|
|
12
|
+
try {
|
|
13
|
+
return storage()?.getItem(key) ?? null;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function write(key, value) {
|
|
20
|
+
try {
|
|
21
|
+
storage()?.setItem(key, value);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// Storage unavailable: the choice still applies for this page.
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function media() {
|
|
28
|
+
try {
|
|
29
|
+
const mm = globalThis.matchMedia;
|
|
30
|
+
return typeof mm === "function" ? mm(QUERY) : null;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function createChooser({ storageKey, registry, defaults, mirrorKey }) {
|
|
37
|
+
const themes = registry.themes;
|
|
38
|
+
const mql = media();
|
|
39
|
+
const prefersDark = () => {
|
|
40
|
+
try {
|
|
41
|
+
return !!mql?.matches;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const listeners = new Set();
|
|
48
|
+
let raw = read(storageKey);
|
|
49
|
+
if (defaults !== undefined) {
|
|
50
|
+
const normalised = resolveChoice(themes, defaults, false).stored;
|
|
51
|
+
if (mirrorKey !== undefined)
|
|
52
|
+
write(mirrorKey, JSON.stringify(normalised));
|
|
53
|
+
if (raw === null)
|
|
54
|
+
raw = normalised;
|
|
55
|
+
}
|
|
56
|
+
else if (raw === null && mirrorKey !== undefined) {
|
|
57
|
+
raw = read(mirrorKey);
|
|
58
|
+
}
|
|
59
|
+
let current = resolveChoice(themes, raw, prefersDark());
|
|
60
|
+
const resolvedOf = (r) => ({ theme: r.theme, scheme: r.scheme, intensity: r.intensity });
|
|
61
|
+
const apply = () => {
|
|
62
|
+
if (typeof document !== "undefined")
|
|
63
|
+
applyResolution(document.documentElement, current);
|
|
64
|
+
};
|
|
65
|
+
const notify = () => {
|
|
66
|
+
const resolved = resolvedOf(current);
|
|
67
|
+
for (const fn of [...listeners])
|
|
68
|
+
fn(resolved, { ...current.stored });
|
|
69
|
+
};
|
|
70
|
+
const onChange = () => {
|
|
71
|
+
const theme = themes.find((t) => t.id === current.theme);
|
|
72
|
+
if (current.stored.scheme !== "auto" || !theme || theme.schemes.length < 2)
|
|
73
|
+
return;
|
|
74
|
+
current = resolveChoice(themes, current.stored, prefersDark());
|
|
75
|
+
apply();
|
|
76
|
+
notify();
|
|
77
|
+
};
|
|
78
|
+
mql?.addEventListener?.("change", onChange);
|
|
79
|
+
apply();
|
|
80
|
+
return {
|
|
81
|
+
registry,
|
|
82
|
+
get: () => ({ ...current.stored }),
|
|
83
|
+
resolved: () => resolvedOf(current),
|
|
84
|
+
set(partial) {
|
|
85
|
+
current = resolveChoice(themes, { ...current.stored, ...partial }, prefersDark());
|
|
86
|
+
write(storageKey, JSON.stringify(current.stored));
|
|
87
|
+
apply();
|
|
88
|
+
notify();
|
|
89
|
+
},
|
|
90
|
+
subscribe(fn) {
|
|
91
|
+
listeners.add(fn);
|
|
92
|
+
return () => void listeners.delete(fn);
|
|
93
|
+
},
|
|
94
|
+
destroy() {
|
|
95
|
+
mql?.removeEventListener?.("change", onChange);
|
|
96
|
+
listeners.clear();
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface Stylesheet {
|
|
2
|
+
path: string;
|
|
3
|
+
text: string;
|
|
4
|
+
}
|
|
5
|
+
export interface CheckOptions {
|
|
6
|
+
stylesheets: Stylesheet[];
|
|
7
|
+
/** The consumer's Token map: the stylesheet text that gives the data Tokens its meanings. */
|
|
8
|
+
tokenMap?: string;
|
|
9
|
+
/** Declarations (`"property: value"`) the consumer vouches for; each is reported with `allowed: true`. */
|
|
10
|
+
allow?: string[];
|
|
11
|
+
}
|
|
12
|
+
export interface Finding {
|
|
13
|
+
path: string;
|
|
14
|
+
line: number;
|
|
15
|
+
rule: 1 | 2 | 3 | 4;
|
|
16
|
+
detail: string;
|
|
17
|
+
/** True for a declaration listed in `allow`: reported, not a violation. */
|
|
18
|
+
allowed: boolean;
|
|
19
|
+
}
|
|
20
|
+
interface Declaration {
|
|
21
|
+
property: string;
|
|
22
|
+
value: string;
|
|
23
|
+
line: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Every declaration in `text` at any depth (inside rules, at-rules and nested rules), and at the top level
|
|
27
|
+
* for inline style text that has no selector.
|
|
28
|
+
*/
|
|
29
|
+
export declare function declarations(text: string): Declaration[];
|
|
30
|
+
/** Check the consumer's stylesheets against the four rules of the Token contract. */
|
|
31
|
+
export declare function checkContract({ stylesheets, tokenMap, allow }: CheckOptions): Finding[];
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// `dyeworks/contract-check`: a consumer runs this over its own stylesheets and inline SVG styles in its test
|
|
2
|
+
// suite. It finds and never edits.
|
|
3
|
+
import { tokenNames } from "./tokens.js";
|
|
4
|
+
const CONTRACT = new Set(tokenNames);
|
|
5
|
+
const INTENSITY = "--intensity";
|
|
6
|
+
const TOKEN_MAP_PATH = "token map";
|
|
7
|
+
/** Replace comments with spaces, keeping every newline so line numbers survive. */
|
|
8
|
+
function stripComments(text) {
|
|
9
|
+
return text.replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, " "));
|
|
10
|
+
}
|
|
11
|
+
const PROPERTY = /^(--[A-Za-z0-9_-]+|-?[A-Za-z][A-Za-z0-9-]*)$/;
|
|
12
|
+
/**
|
|
13
|
+
* Every declaration in `text` at any depth (inside rules, at-rules and nested rules), and at the top level
|
|
14
|
+
* for inline style text that has no selector.
|
|
15
|
+
*/
|
|
16
|
+
export function declarations(text) {
|
|
17
|
+
const src = stripComments(text);
|
|
18
|
+
const found = [];
|
|
19
|
+
let buf = "";
|
|
20
|
+
let start = null;
|
|
21
|
+
let line = 1;
|
|
22
|
+
let paren = 0;
|
|
23
|
+
let quote = null;
|
|
24
|
+
const flush = () => {
|
|
25
|
+
const t = buf.trim();
|
|
26
|
+
const colon = t.indexOf(":");
|
|
27
|
+
if (start !== null && colon > 0 && !t.startsWith("@")) {
|
|
28
|
+
const property = t.slice(0, colon).trim();
|
|
29
|
+
if (PROPERTY.test(property))
|
|
30
|
+
found.push({ property, value: t.slice(colon + 1).trim(), line: start });
|
|
31
|
+
}
|
|
32
|
+
buf = "";
|
|
33
|
+
start = null;
|
|
34
|
+
};
|
|
35
|
+
for (const c of src) {
|
|
36
|
+
if (quote) {
|
|
37
|
+
if (c === quote)
|
|
38
|
+
quote = null;
|
|
39
|
+
}
|
|
40
|
+
else if (c === '"' || c === "'")
|
|
41
|
+
quote = c;
|
|
42
|
+
else if (c === "(")
|
|
43
|
+
paren++;
|
|
44
|
+
else if (c === ")")
|
|
45
|
+
paren = Math.max(0, paren - 1);
|
|
46
|
+
else if (paren === 0 && c === "{") {
|
|
47
|
+
buf = "";
|
|
48
|
+
start = null;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
else if (paren === 0 && (c === ";" || c === "}")) {
|
|
52
|
+
flush();
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (c === "\n")
|
|
56
|
+
line++;
|
|
57
|
+
if (start === null && !/\s/.test(c))
|
|
58
|
+
start = line;
|
|
59
|
+
buf += c;
|
|
60
|
+
}
|
|
61
|
+
flush();
|
|
62
|
+
return found;
|
|
63
|
+
}
|
|
64
|
+
/** Every custom property a value reads through `var(--name…)`, fallbacks included. */
|
|
65
|
+
function reads(value) {
|
|
66
|
+
return [...value.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)/g)].map((m) => m[1]);
|
|
67
|
+
}
|
|
68
|
+
const COLOUR_PROPERTY = /^(color|background(-[a-z-]+)?|fill|stroke|border(-[a-z-]+)?|outline(-[a-z-]+)?|text-decoration(-[a-z-]+)?|accent-color)$/;
|
|
69
|
+
const HEX_LITERAL = /#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})(?![0-9A-Za-z_-])/;
|
|
70
|
+
const COLOUR_FUNCTION = /(?<![A-Za-z0-9_-])(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(/i;
|
|
71
|
+
// The CSS named colours. `transparent` and `currentcolor` are keywords that paint no hue of their own.
|
|
72
|
+
const NAMED = new Set(("aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood " +
|
|
73
|
+
"cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray " +
|
|
74
|
+
"darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen " +
|
|
75
|
+
"darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue " +
|
|
76
|
+
"firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew " +
|
|
77
|
+
"hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan " +
|
|
78
|
+
"lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray " +
|
|
79
|
+
"lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue " +
|
|
80
|
+
"mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred " +
|
|
81
|
+
"midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid " +
|
|
82
|
+
"palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple " +
|
|
83
|
+
"rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue " +
|
|
84
|
+
"slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white " +
|
|
85
|
+
"whitesmoke yellow yellowgreen").split(" "));
|
|
86
|
+
/** The colour literal in `value`, or null. `url()` and quoted strings are never read as colours. */
|
|
87
|
+
function colourLiteral(value) {
|
|
88
|
+
const bare = value.replace(/url\([^)]*\)/gi, " ").replace(/"[^"]*"|'[^']*'/g, " ");
|
|
89
|
+
const hex = HEX_LITERAL.exec(bare);
|
|
90
|
+
if (hex)
|
|
91
|
+
return hex[0];
|
|
92
|
+
const fn = COLOUR_FUNCTION.exec(bare);
|
|
93
|
+
if (fn)
|
|
94
|
+
return `${fn[1]}()`;
|
|
95
|
+
for (const m of bare.matchAll(/(?<![A-Za-z0-9_-])([A-Za-z]+)(?![A-Za-z0-9_(-])/g)) {
|
|
96
|
+
if (NAMED.has(m[1].toLowerCase()))
|
|
97
|
+
return m[1];
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
const normalise = (declaration) => {
|
|
102
|
+
const colon = declaration.indexOf(":");
|
|
103
|
+
if (colon < 0)
|
|
104
|
+
return declaration.trim().replace(/\s+/g, " ");
|
|
105
|
+
return `${declaration.slice(0, colon).trim().toLowerCase()}: ${declaration.slice(colon + 1).trim().replace(/\s+/g, " ")}`;
|
|
106
|
+
};
|
|
107
|
+
/** Check the consumer's stylesheets against the four rules of the Token contract. */
|
|
108
|
+
export function checkContract({ stylesheets, tokenMap, allow = [] }) {
|
|
109
|
+
const parsed = stylesheets.map((s) => ({ path: s.path, declarations: declarations(s.text) }));
|
|
110
|
+
const mapDeclarations = tokenMap === undefined ? [] : declarations(tokenMap);
|
|
111
|
+
const declared = new Set();
|
|
112
|
+
for (const d of [...parsed.flatMap((p) => p.declarations), ...mapDeclarations])
|
|
113
|
+
if (d.property.startsWith("--") && !CONTRACT.has(d.property))
|
|
114
|
+
declared.add(d.property);
|
|
115
|
+
const allowed = new Set(allow.map(normalise));
|
|
116
|
+
const findings = [];
|
|
117
|
+
for (const { path, declarations: decls } of parsed) {
|
|
118
|
+
for (const d of decls) {
|
|
119
|
+
const at = { path, line: d.line };
|
|
120
|
+
// Rule 1: every read is a contract Token, --intensity, or declared by the consumer.
|
|
121
|
+
for (const name of reads(d.value)) {
|
|
122
|
+
if (!CONTRACT.has(name) && name !== INTENSITY && !declared.has(name))
|
|
123
|
+
findings.push({ ...at, rule: 1, detail: `${d.property} reads ${name}, which is neither a contract Token nor declared in the stylesheets given`, allowed: false });
|
|
124
|
+
}
|
|
125
|
+
// Rule 2: a consumer maps, it never overrides.
|
|
126
|
+
if (CONTRACT.has(d.property))
|
|
127
|
+
findings.push({ ...at, rule: 2, detail: `sets the contract Token ${d.property}, which only a Theme file may set`, allowed: false });
|
|
128
|
+
// Rule 3: no colour literal in a colour-bearing property; shadows are not among them.
|
|
129
|
+
if (COLOUR_PROPERTY.test(d.property.toLowerCase())) {
|
|
130
|
+
const literal = colourLiteral(d.value);
|
|
131
|
+
if (literal !== null) {
|
|
132
|
+
const declaration = `${d.property}: ${d.value}`;
|
|
133
|
+
findings.push({ ...at, rule: 3, detail: `colour literal ${literal} in \`${declaration}\``, allowed: allowed.has(normalise(declaration)) });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// Rule 4: each --series-* and --state-* mapped at most once, and nothing else of the contract mapped.
|
|
139
|
+
const mapped = new Set();
|
|
140
|
+
for (const d of mapDeclarations) {
|
|
141
|
+
for (const name of reads(d.value)) {
|
|
142
|
+
if (!CONTRACT.has(name))
|
|
143
|
+
continue;
|
|
144
|
+
const at = { path: TOKEN_MAP_PATH, line: d.line, rule: 4, allowed: false };
|
|
145
|
+
if (!/^--(series|state)-/.test(name))
|
|
146
|
+
findings.push({ ...at, detail: `${d.property} maps ${name}; the Token map maps only --series-* and --state-*` });
|
|
147
|
+
else if (mapped.has(name))
|
|
148
|
+
findings.push({ ...at, detail: `${d.property} maps ${name} a second time` });
|
|
149
|
+
mapped.add(name);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return findings;
|
|
153
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type CompactTheme } from "./resolve.js";
|
|
2
|
+
export interface BootOptions {
|
|
3
|
+
storageKey: string;
|
|
4
|
+
mirrorKey?: string;
|
|
5
|
+
}
|
|
6
|
+
/** Only what resolution reads: id, Schemes and assets, in registry order. */
|
|
7
|
+
export declare function compact(themes: CompactTheme[]): CompactTheme[];
|
|
8
|
+
/**
|
|
9
|
+
* The inline script: reads the storage key (or the mirror when it holds nothing), resolves, and writes the
|
|
10
|
+
* attributes and properties on `<html>`. Every failure is caught; on one, nothing is written.
|
|
11
|
+
*/
|
|
12
|
+
export declare function renderBootScript(themes: CompactTheme[], { storageKey, mirrorKey }: BootOptions): string;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// The boot script's text for a given set of Themes; `dyeworks/boot` binds it to the generated registry.
|
|
2
|
+
import { applyResolution, resolveChoice } from "./resolve.js";
|
|
3
|
+
/** A JSON literal safe inside an inline `<script>`: no `<` survives to close the element. */
|
|
4
|
+
const LS = String.fromCharCode(0x2028);
|
|
5
|
+
const PS = String.fromCharCode(0x2029);
|
|
6
|
+
const literal = (value) => JSON.stringify(value).replace(/</g, "\\u003c").split(LS).join("\\u2028").split(PS).join("\\u2029");
|
|
7
|
+
/** Only what resolution reads: id, Schemes and assets, in registry order. */
|
|
8
|
+
export function compact(themes) {
|
|
9
|
+
return themes.map((t) => ({ id: t.id, schemes: t.schemes, assets: t.assets }));
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The inline script: reads the storage key (or the mirror when it holds nothing), resolves, and writes the
|
|
13
|
+
* attributes and properties on `<html>`. Every failure is caught; on one, nothing is written.
|
|
14
|
+
*/
|
|
15
|
+
export function renderBootScript(themes, { storageKey, mirrorKey }) {
|
|
16
|
+
return ("(function(){try{" +
|
|
17
|
+
`var T=${literal(compact(themes))},K=${literal(storageKey)},M=${literal(mirrorKey ?? null)};` +
|
|
18
|
+
"var s=localStorage,raw=s.getItem(K);if(raw===null&&M!==null)raw=s.getItem(M);" +
|
|
19
|
+
'var d=false;try{d=!!matchMedia("(prefers-color-scheme: dark)").matches}catch(e){}' +
|
|
20
|
+
`var r=(${resolveChoice.toString()})(T,raw,d);` +
|
|
21
|
+
`(${applyResolution.toString()})(document.documentElement,r);` +
|
|
22
|
+
"}catch(e){}})();");
|
|
23
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Scheme } from "../registry.js";
|
|
2
|
+
/** What resolution needs of a Theme: the boot script embeds exactly these fields. */
|
|
3
|
+
export interface CompactTheme {
|
|
4
|
+
id: string;
|
|
5
|
+
schemes: Scheme[];
|
|
6
|
+
assets: Record<string, unknown>;
|
|
7
|
+
}
|
|
8
|
+
/** The stored object, as the consumer's storage key holds it. */
|
|
9
|
+
export interface Stored {
|
|
10
|
+
theme: string;
|
|
11
|
+
scheme: "auto" | Scheme;
|
|
12
|
+
intensity: number;
|
|
13
|
+
}
|
|
14
|
+
export interface Resolution {
|
|
15
|
+
/** The stored object with every missing or malformed field read as `default`, `auto`, `0.5`. */
|
|
16
|
+
stored: Stored;
|
|
17
|
+
theme: string;
|
|
18
|
+
scheme: Scheme;
|
|
19
|
+
intensity: number;
|
|
20
|
+
/** The three asset Tokens, as the inline custom properties written on `<html>`. */
|
|
21
|
+
properties: Record<string, string>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Resolve `raw` (the stored text, or an object) against `themes`. An unknown id reads as `default`;
|
|
25
|
+
* `auto` follows `prefersDark` where the Theme declares both Schemes; a single-Scheme Theme resolves to it.
|
|
26
|
+
*/
|
|
27
|
+
export declare function resolveChoice(themes: CompactTheme[], raw: unknown, prefersDark: boolean): Resolution;
|
|
28
|
+
/** Write a resolution on `<html>`: `data-theme`, `data-scheme`, `--intensity` and the asset Tokens. */
|
|
29
|
+
export declare function applyResolution(html: {
|
|
30
|
+
setAttribute(n: string, v: string): void;
|
|
31
|
+
style: {
|
|
32
|
+
setProperty(n: string, v: string): void;
|
|
33
|
+
};
|
|
34
|
+
}, r: Resolution): void;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve `raw` (the stored text, or an object) against `themes`. An unknown id reads as `default`;
|
|
3
|
+
* `auto` follows `prefersDark` where the Theme declares both Schemes; a single-Scheme Theme resolves to it.
|
|
4
|
+
*/
|
|
5
|
+
export function resolveChoice(themes, raw, prefersDark) {
|
|
6
|
+
var value = raw;
|
|
7
|
+
if (typeof value === "string") {
|
|
8
|
+
try {
|
|
9
|
+
value = JSON.parse(value);
|
|
10
|
+
}
|
|
11
|
+
catch (e) {
|
|
12
|
+
value = null;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
var o = value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
16
|
+
var theme;
|
|
17
|
+
for (var i = 0; i < themes.length; i++)
|
|
18
|
+
if (themes[i].id === o.theme)
|
|
19
|
+
theme = themes[i];
|
|
20
|
+
if (!theme)
|
|
21
|
+
for (var j = 0; j < themes.length; j++)
|
|
22
|
+
if (themes[j].id === "default")
|
|
23
|
+
theme = themes[j];
|
|
24
|
+
if (!theme)
|
|
25
|
+
theme = themes[0];
|
|
26
|
+
var scheme = o.scheme === "light" || o.scheme === "dark" ? o.scheme : "auto";
|
|
27
|
+
var intensity = typeof o.intensity === "number" && isFinite(o.intensity) && o.intensity >= 0 && o.intensity <= 1 ? o.intensity : 0.5;
|
|
28
|
+
var resolved = theme.schemes.length === 1 ? theme.schemes[0] : scheme === "auto" ? (prefersDark ? "dark" : "light") : scheme;
|
|
29
|
+
var properties = { "--intensity": String(intensity) };
|
|
30
|
+
var slots = ["backdrop", "ornament", "empty"];
|
|
31
|
+
for (var k = 0; k < slots.length; k++) {
|
|
32
|
+
var declared = theme.assets[slots[k]];
|
|
33
|
+
var entry = declared ? (typeof declared.fallback === "string" ? declared : declared[resolved]) : null;
|
|
34
|
+
properties["--asset-" + slots[k]] = entry ? "url(/themes/" + theme.id + "/" + (entry.image || entry.fallback) + ")" : "none";
|
|
35
|
+
}
|
|
36
|
+
return { stored: { theme: theme.id, scheme: scheme, intensity: intensity }, theme: theme.id, scheme: resolved, intensity: intensity, properties: properties };
|
|
37
|
+
}
|
|
38
|
+
/** Write a resolution on `<html>`: `data-theme`, `data-scheme`, `--intensity` and the asset Tokens. */
|
|
39
|
+
export function applyResolution(html, r) {
|
|
40
|
+
html.setAttribute("data-theme", r.theme);
|
|
41
|
+
html.setAttribute("data-scheme", r.scheme);
|
|
42
|
+
for (var name in r.properties)
|
|
43
|
+
html.style.setProperty(name, r.properties[name]);
|
|
44
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Chooser } from "../chooser.js";
|
|
2
|
+
/**
|
|
3
|
+
* A native range from 0 to 1 in steps of 0.05, labelled "Intensity", rendered only while the resolved Theme
|
|
4
|
+
* declares `intensity: true`. Carries no style of its own.
|
|
5
|
+
*/
|
|
6
|
+
export declare function IntensityControl({ chooser }: {
|
|
7
|
+
chooser: Chooser;
|
|
8
|
+
}): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useChooser } from "./useChooser.js";
|
|
3
|
+
/**
|
|
4
|
+
* A native range from 0 to 1 in steps of 0.05, labelled "Intensity", rendered only while the resolved Theme
|
|
5
|
+
* declares `intensity: true`. Carries no style of its own.
|
|
6
|
+
*/
|
|
7
|
+
export function IntensityControl({ chooser }) {
|
|
8
|
+
useChooser(chooser);
|
|
9
|
+
const resolved = chooser.resolved();
|
|
10
|
+
const theme = chooser.registry.themes.find((t) => t.id === resolved.theme);
|
|
11
|
+
if (!theme?.intensity)
|
|
12
|
+
return null;
|
|
13
|
+
return (_jsxs("label", { children: ["Intensity", " ", _jsx("input", { type: "range", min: "0", max: "1", step: "0.05", value: String(resolved.intensity), onChange: (e) => chooser.set({ intensity: Number(e.currentTarget.value) }) })] }));
|
|
14
|
+
}
|