@crewlethq/tokens 0.48.3 → 0.49.1

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
@@ -6,6 +6,7 @@ Single source of truth for the Crewlet design tokens: color, spacing, size, typo
6
6
  - `dist/css/themes.css` (the dark and light palettes of the default theme)
7
7
  - `dist/css/themes/<id>.css` and `dist/css/themes/all.css` (the named themes, each under its own `data-palette` attribute)
8
8
  - `dist/css/density.css`, `dist/css/base.css`, `dist/css/breakpoint.css`
9
+ - `dist/css/brand.css` and `dist/css/brand-scope.css` (the brand mapping, on the document root and on a scope of its own)
9
10
  - `dist/index.js` + `dist/index.d.ts` (typed JS object for runtime use)
10
11
 
11
12
  ## Use it from a consumer app
@@ -45,6 +46,42 @@ const accent = color.brand.accent;
45
46
  CSS variables follow Style Dictionary's `--{group}-{path}` convention,
46
47
  for example `var(--color-brand-accent)` or `var(--spacing-4)`.
47
48
 
49
+ ### Contrast at runtime
50
+
51
+ An interface that has to say whether two colours a person chose read on each other (a brand's text on its ground, a label on a fill) measures them with the same code the palette suite holds every theme to:
52
+
53
+ ```ts
54
+ import { WCAG_CONTRAST, contrast, parseHex } from '@crewlethq/tokens';
55
+
56
+ const text = parseHex(input.text); // null unless the value is #rrggbb
57
+ const ground = parseHex(input.ground);
58
+ if (text && ground) {
59
+ const ratio = contrast(text, ground); // 1 to 21, unrounded, in either order
60
+ const readable = ratio >= WCAG_CONTRAST.aa;
61
+ }
62
+ ```
63
+
64
+ | Export | What it is |
65
+ | --- | --- |
66
+ | `parseHex(hex)` | A `#rrggbb` value (any case, surrounding white space ignored) as `{ r, g, b }`, or `null` for anything else, the three and eight digit forms included. It never throws, so a half-typed value is a `null` to handle rather than an exception. |
67
+ | `contrast(a, b)` | The WCAG 2 ratio between two opaque colours, from 1 to 21, in either order. Unrounded: compare the raw ratio with a floor, and round only to display it, because a ratio that passes only once rounded does not pass. |
68
+ | `luminance(rgb)` | WCAG relative luminance, from 0 to 1. |
69
+ | `WCAG_CONTRAST` | The floors, frozen: `aa` 4.5 and `aaa` 7 for body text, `aaLarge` 3 and `aaaLarge` 4.5 for large text (24px, or 18.66px bold); `aaLarge` is also the floor for a graphical mark and a control's boundary. |
70
+ | `Rgb` | The type of a colour as channels from 0 to 255. |
71
+
72
+ The implementation is `src/color.ts`, built to `dist/color.js`. The published palette suite imports it from there and re-exports it, and the token build reads the same source to derive each palette's tints, so there is one copy of the maths.
73
+
74
+ ## Changed in 0.49.0: contrast at runtime, the brand kind and the brand mapping
75
+
76
+ The WCAG contrast maths the palette suite measures with is a runtime export, for an interface that shows whether two colours a person chose read on each other. A company's brand kit is a kind of artifact of its own, with a hue of its own. And the brand mapping (how a company's `--brand-*` inputs restyle the public tokens) lives here, as one source for the artifact kit and for an application's branded regions.
77
+
78
+ | What changed | What to change | Details |
79
+ | --- | --- | --- |
80
+ | `@crewlethq/tokens` exports `parseHex`, `contrast`, `luminance`, `WCAG_CONTRAST` and the type `Rgb`. They are the implementation `@crewlethq/tokens/test/palette` re-exports (the same functions, not copies), and `contrast` and `parseHex` keep the signatures the suite already declared. | Nothing. Replace a contrast helper of your own with these. | [Contrast at runtime](#contrast-at-runtime) |
81
+ | `css/brand` and `css/brand-scope` are new. Both are built from one source, `stylesheets/brand.css`: `css/brand` is the mapping on the document root (the layer `@crewlethq/artifact-kit` bundles into kit.css), and `css/brand-scope` is the same mapping on `.crewlet-brand-scope__layer`, with the page's own value of every token it drives captured on `.crewlet-brand-scope` one element up and a `data-mode` that pins a mode to the default theme's values for it (the stylesheet of `@crewlethq/ui`'s BrandScope). The build accepts the mapping under its three root selectors only, so a rule reaches both or neither. `brandSlots`, `brandThemeName`, `parseBrandLayer`, `brandScopeCss`, `BRAND_THEME_PREFIX`, `BRAND_SCOPE_CLASS` and `BRAND_SCOPE_LAYER_CLASS` are exported. | Nothing. Import `css/brand-scope` beside `@crewlethq/ui/styles.css` if you load the components through that bundle alone. | `stylesheets/brand.css` |
82
+ | `--color-artifact-kind-brand` with its `-ink`, `-fill` and `-line` steps: `#cc7bd1` in dark and `#8f3884` in light, an orchid apart from design's purple and HTML's rose. It is the one kind with a hue of its own, declared by every theme beside its node hues; the six node hues are unchanged and still six. | Nothing. | [Artifact kinds](#artifact-kinds) |
83
+ | In `@crewlethq/tokens/test/palette`, the rules `an artifact kind hue clears 3:1 as a mark`, `an artifact kind's ink clears 4.5:1 on its own fill and on every rung` and `artifact kind hues stay apart` are new, with the exports `ARTIFACT_KINDS`, `ARTIFACT_KIND_HUES`, `ARTIFACT_KIND_FILL_ALPHA` and `ARTIFACT_KIND_DE` (8). Every kind already cleared them in every theme. | Nothing, unless an application's own palette override repaints a kind's hue or a node hue within dE 8 of another kind's. | [The palette suite](#the-palette-suite) |
84
+
48
85
  ## Changed in 0.38.0: the hairline that finds a card
49
86
 
50
87
  The plain hairline is the edge of every card and the line inside one: the rule under a card's head, the divider between two stat tiles, a code block's edge and a quiet tag's outline. The palette suite held it to dE 3, the floor for a difference a reader looks for, and the default dark palette drew it dE 3.1 off the card (1.07:1), where a layout audit measured those lines as gone. It is now held to dE 5 on both sides of it, the most the default dark ladder allows while the rail's current row keeps dE 3 against raised. Every named theme already cleared it.
@@ -498,6 +535,22 @@ A collaborator's presence colour is the one narrow exception to "colour carries
498
535
 
499
536
  The palette suite holds the flag's name at 4.5:1 on each of the six hues, and each hue at 3:1 as a mark on every rung, in every palette of every theme. The high-contrast theme keeps the same 4.5: the hue is the collaborator's identity rather than a palette's step, and the name is also said in words wherever presence is listed.
500
537
 
538
+ ### Artifact kinds
539
+
540
+ Each kind of artifact is drawn in a hue of its own wherever its kind is pictured (a "Start a new artifact" tile, a card's ground, the kind's glyph in a bar or a list), always beside the kind's name, so the hue is identity and never state. `--color-artifact-kind-<kind>` carries the hue, and `-ink`, `-fill` and `-line` the glyph drawn on it, its tint and its boundary.
541
+
542
+ | Kind | Hue | Dark | Light |
543
+ | --- | --- | --- | --- |
544
+ | `doc` | `--color-node-blue` | `#5b7fc7` | `#4062a7` |
545
+ | `slides` | `--color-node-amber` | `#c89866` | `#865a28` |
546
+ | `design` | `--color-node-purple` | `#8e6ed4` | `#7150b3` |
547
+ | `dashboard` | `--color-node-cyan` | `#5ca8be` | `#166b80` |
548
+ | `html` | `--color-node-rose` | `#c8757f` | `#984a55` |
549
+ | `sheet` | `--color-node-green` | `#62a578` | `#2c7046` |
550
+ | `brand` | its own | `#cc7bd1` | `#8f3884` |
551
+
552
+ The first six are aliases of the six node hues, so every theme repaints them with no value of its own. `brand`, a company's brand kit, came after every node hue was taken, so every theme declares it beside its node hues (ink `#dabcdb` in dark and `#74246a` in light), and the build derives its fill and line from it at the node alphas. The palette suite holds every kind's hue at 3:1 as a mark on every rung, its ink at 4.5:1 on its own fill and on every rung, and every pair of kind hues dE 8 apart under normal vision, in every palette of every theme.
553
+
501
554
  ### The accent
502
555
 
503
556
  The accent is a violet, and it is **per palette**:
@@ -603,7 +656,7 @@ The marketing root keeps its own state and series values (`tokens/color.json`),
603
656
 
604
657
  ## The palette suite
605
658
 
606
- `test/palette.mjs` holds the rule table and the colour maths, and `test/palette.test.mjs` runs it over `dist/css` in import order, in every theme state: the base marketing root (`base`), the dark root (`dark`), light by media query (`light (media query)`) and light by attribute (`light (attribute)`), which are the keys `paletteStates()` returns. It measures every text step on every surface it can land on (the four opaque rungs in `OPAQUE_SURFACES`, and the translucent overlays composited over each of them), the step between a word and a dimmed one, every ink on its own soft tint, every fill as a mark, each status glyph's ink on its fill, the primary action's three fills under its label and the steps between them, the destructive action's fill and its hover under the same label, the focus ring, the control boundary, the rail's current row, the steps between the rungs, the hairline that finds a card and the strong hairline round a raised chip, whether a hovered and a pressed row can be seen, the hue separations under normal, protan and deuteranopic vision (the states from each other, the chart series from their neighbours and from the danger red, and every hue from the accent), and the structure of the theme file itself. A component suite that measures a colour of its own measures it on `OPAQUE_SURFACES` too, rather than on a list of surface names it keeps itself.
659
+ `test/palette.mjs` holds the rule table and the colour maths, and `test/palette.test.mjs` runs it over `dist/css` in import order, in every theme state: the base marketing root (`base`), the dark root (`dark`), light by media query (`light (media query)`) and light by attribute (`light (attribute)`), which are the keys `paletteStates()` returns. It measures every text step on every surface it can land on (the four opaque rungs in `OPAQUE_SURFACES`, and the translucent overlays composited over each of them), the step between a word and a dimmed one, every ink on its own soft tint, every fill as a mark, each status glyph's ink on its fill, the primary action's three fills under its label and the steps between them, the destructive action's fill and its hover under the same label, the focus ring, the control boundary, the rail's current row, the steps between the rungs, the hairline that finds a card and the strong hairline round a raised chip, whether a hovered and a pressed row can be seen, the hue separations under normal, protan and deuteranopic vision (the states from each other, the chart series from their neighbours and from the danger red, and every hue from the accent), each artifact kind's hue as a mark, its ink on its own fill and the kind hues apart from each other, and the structure of the theme file itself. The WCAG maths it measures with is the package's own runtime export (see [Contrast at runtime](#contrast-at-runtime)), re-exported from `test/color.mjs`. A component suite that measures a colour of its own measures it on `OPAQUE_SURFACES` too, rather than on a list of surface names it keeps itself.
607
660
 
608
661
  The module is **published**, as `@crewlethq/tokens/test/palette`, so a consumer runs the same rules over the version it installed:
609
662
 
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The brand mapping's contract, read from its one source
3
+ * (`stylesheets/brand.css`) by everything that builds on it:
4
+ *
5
+ * - the token build emits that file as `css/brand.css`, and writes
6
+ * `css/brand-scope.css` from it here (`brandScopeCss`);
7
+ * - @crewlethq/artifact-kit's build bundles `css/brand.css` into kit.css and
8
+ * moves the theme's value of every public token it declares aside to
9
+ * `--crewlet-theme-<name>` (`brandSlots`, `brandThemeName`);
10
+ * - the suites hold the two stylesheets to declaring the same mapping.
11
+ *
12
+ * Like color.ts it uses only syntax Node strips without compiling, because the
13
+ * token build imports it from source before tsc has run.
14
+ */
15
+ /** The prefix the theme's own value of a brand-driven token takes. */
16
+ export declare const BRAND_THEME_PREFIX = "--crewlet-theme-";
17
+ /** The name a token's theme value takes: `--color-brand-accent` becomes `--crewlet-theme-color-brand-accent`. */
18
+ export declare function brandThemeName(slot: string): string;
19
+ /** The scope's outer element: it carries the inputs and captures the page's values. */
20
+ export declare const BRAND_SCOPE_CLASS = "crewlet-brand-scope";
21
+ /** The scope's inner element: the mapping applies to it and everything inside it. */
22
+ export declare const BRAND_SCOPE_LAYER_CLASS = "crewlet-brand-scope__layer";
23
+ /** The mapping as the source declares it: the bare root's (dark) block and the light block. */
24
+ export interface BrandLayer {
25
+ /** Every declaration of the bare root, in order: the dark steps, the shared steps and the public tokens. */
26
+ dark: ReadonlyMap<string, string>;
27
+ /** The light steps, declared alike under the system's setting and under an explicit choice. */
28
+ light: ReadonlyMap<string, string>;
29
+ }
30
+ /** Every value the default theme declares in one mode, for a scope that pins its mode. */
31
+ export interface BrandModeValues {
32
+ light: ReadonlyMap<string, string>;
33
+ dark: ReadonlyMap<string, string>;
34
+ }
35
+ /**
36
+ * The mapping, read from the source, which is held to its shape: the bare
37
+ * root's block, the light block under the system's setting and the same block
38
+ * under an explicit choice, and nothing else. A rule added anywhere else would
39
+ * reach one of the two built stylesheets and not the other, so it stops here.
40
+ */
41
+ export declare function parseBrandLayer(css: string): BrandLayer;
42
+ /**
43
+ * Every public token the mapping declares, sorted: each custom property it
44
+ * sets that is neither one of its private steps (`--crewlet-`) nor an input
45
+ * (`--brand-`).
46
+ */
47
+ export declare function brandSlots(css: string): string[];
48
+ /**
49
+ * The scope's stylesheet, from the same source as the root layer.
50
+ *
51
+ * TWO ELEMENTS, because a custom property cannot fall back to its own earlier
52
+ * value. The outer element (`.crewlet-brand-scope`) captures the page's value
53
+ * of every public token into `--crewlet-theme-<name>`; the inner one
54
+ * (`.crewlet-brand-scope__layer`) declares the public tokens from the inputs,
55
+ * falling back to the captured values, exactly as the root layer falls back to
56
+ * the values the kit's build moved aside. The mapping's blocks are the
57
+ * source's, their selectors moved onto the inner element, so the scope follows
58
+ * the page's light or dark as the root layer does.
59
+ *
60
+ * A PINNED MODE (`data-mode` on the outer element) is that mode whatever the
61
+ * page is in: a preview that shows a brand in light beside the same brand in
62
+ * dark. The default theme's value of every public token the mapping drives is
63
+ * captured for the mode in place of the page's, every other token of the mode
64
+ * (the secondary text, the hairlines, the raised grounds) is declared on the
65
+ * layer itself, and the mapping takes the mode's own steps. Its blocks come
66
+ * last, so they win the ties.
67
+ */
68
+ export declare function brandScopeCss(css: string, modes: BrandModeValues): string;
package/dist/brand.js ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * The brand mapping's contract, read from its one source
3
+ * (`stylesheets/brand.css`) by everything that builds on it:
4
+ *
5
+ * - the token build emits that file as `css/brand.css`, and writes
6
+ * `css/brand-scope.css` from it here (`brandScopeCss`);
7
+ * - @crewlethq/artifact-kit's build bundles `css/brand.css` into kit.css and
8
+ * moves the theme's value of every public token it declares aside to
9
+ * `--crewlet-theme-<name>` (`brandSlots`, `brandThemeName`);
10
+ * - the suites hold the two stylesheets to declaring the same mapping.
11
+ *
12
+ * Like color.ts it uses only syntax Node strips without compiling, because the
13
+ * token build imports it from source before tsc has run.
14
+ */
15
+ /** The prefix the theme's own value of a brand-driven token takes. */
16
+ export const BRAND_THEME_PREFIX = '--crewlet-theme-';
17
+ /** The name a token's theme value takes: `--color-brand-accent` becomes `--crewlet-theme-color-brand-accent`. */
18
+ export function brandThemeName(slot) {
19
+ return `${BRAND_THEME_PREFIX}${slot.slice(2)}`;
20
+ }
21
+ /** The scope's outer element: it carries the inputs and captures the page's values. */
22
+ export const BRAND_SCOPE_CLASS = 'crewlet-brand-scope';
23
+ /** The scope's inner element: the mapping applies to it and everything inside it. */
24
+ export const BRAND_SCOPE_LAYER_CLASS = 'crewlet-brand-scope__layer';
25
+ /** The three selectors the source declares the mapping under, and nothing else. */
26
+ const DARK = ':root';
27
+ const LIGHT_QUERY = '@media (prefers-color-scheme: light)';
28
+ const LIGHT_MEDIA = ':root:not([data-theme="dark"])';
29
+ const LIGHT_ATTRIBUTE = ':root[data-theme="light"]';
30
+ const withoutComments = (css) => css.replace(/\/\*[\s\S]*?\*\//g, '');
31
+ /** A block's custom properties, in order, each value with its white space collapsed. */
32
+ function declarationsOf(body, where) {
33
+ const found = new Map();
34
+ for (const part of body.split(';')) {
35
+ if (part.trim() === '')
36
+ continue;
37
+ const colon = part.indexOf(':');
38
+ const name = colon < 0 ? '' : part.slice(0, colon).trim();
39
+ if (!name.startsWith('--'))
40
+ throw new Error(`${where} declares "${part.trim()}", and the brand mapping declares custom properties only`);
41
+ if (found.has(name))
42
+ throw new Error(`${where} declares ${name} twice`);
43
+ found.set(name, part.slice(colon + 1).replace(/\s+/g, ' ').trim());
44
+ }
45
+ return found;
46
+ }
47
+ /**
48
+ * The mapping, read from the source, which is held to its shape: the bare
49
+ * root's block, the light block under the system's setting and the same block
50
+ * under an explicit choice, and nothing else. A rule added anywhere else would
51
+ * reach one of the two built stylesheets and not the other, so it stops here.
52
+ */
53
+ export function parseBrandLayer(css) {
54
+ const text = withoutComments(css);
55
+ const blocks = [];
56
+ // Each open block's head, and whether a block has opened inside it: only
57
+ // the innermost blocks declare, and a wrapper (the media query) is context.
58
+ const stack = [];
59
+ let start = 0;
60
+ for (let i = 0; i < text.length; i += 1) {
61
+ const ch = text[i];
62
+ if (ch === '{') {
63
+ const parent = stack.at(-1);
64
+ if (parent)
65
+ parent.wraps = true;
66
+ stack.push({ head: text.slice(start, i).trim().replace(/\s+/g, ' '), wraps: false });
67
+ start = i + 1;
68
+ }
69
+ else if (ch === '}') {
70
+ const open = stack.pop();
71
+ if (open === undefined)
72
+ throw new Error('the brand mapping has an unbalanced "}"');
73
+ if (!open.wraps)
74
+ blocks.push({ context: stack.at(-1)?.head ?? null, selector: open.head, body: text.slice(start, i) });
75
+ start = i + 1;
76
+ }
77
+ }
78
+ if (stack.length > 0)
79
+ throw new Error('the brand mapping has an unbalanced "{"');
80
+ const shape = blocks.map((block) => `${block.context ?? ''} ${block.selector}`.trim());
81
+ const expected = [DARK, `${LIGHT_QUERY} ${LIGHT_MEDIA}`, LIGHT_ATTRIBUTE];
82
+ if (shape.join('\n') !== expected.join('\n')) {
83
+ throw new Error(`the brand mapping declares under ${JSON.stringify(shape)}; it may declare under ${JSON.stringify(expected)} only, in that order`);
84
+ }
85
+ const [dark, lightMedia, lightAttribute] = blocks.map((block) => declarationsOf(block.body, block.selector));
86
+ if (JSON.stringify([...lightMedia]) !== JSON.stringify([...lightAttribute])) {
87
+ throw new Error('the brand mapping\'s two light blocks differ; a reader\'s system setting and an explicit choice paint one light mode');
88
+ }
89
+ for (const name of lightMedia.keys()) {
90
+ if (!dark.has(name))
91
+ throw new Error(`the light block declares ${name}, which the bare root does not; every mode names the same steps`);
92
+ }
93
+ for (const [name, value] of dark) {
94
+ if (name.startsWith('--brand-'))
95
+ throw new Error(`the brand mapping declares the input ${name}; an input is set by the engine or a page, never here`);
96
+ if (/url\(/i.test(value))
97
+ throw new Error(`the brand mapping names a file in ${name}; every file is an input`);
98
+ }
99
+ return { dark, light: lightMedia };
100
+ }
101
+ /**
102
+ * Every public token the mapping declares, sorted: each custom property it
103
+ * sets that is neither one of its private steps (`--crewlet-`) nor an input
104
+ * (`--brand-`).
105
+ */
106
+ export function brandSlots(css) {
107
+ return [...parseBrandLayer(css).dark.keys()].filter((name) => !name.startsWith('--crewlet-') && !name.startsWith('--brand-')).sort();
108
+ }
109
+ const block = (selector, declarations, indent = '') => `${indent}${selector} {\n${[...declarations].map(([name, value]) => `${indent} ${name}: ${value};`).join('\n')}\n${indent}}`;
110
+ /**
111
+ * The scope's stylesheet, from the same source as the root layer.
112
+ *
113
+ * TWO ELEMENTS, because a custom property cannot fall back to its own earlier
114
+ * value. The outer element (`.crewlet-brand-scope`) captures the page's value
115
+ * of every public token into `--crewlet-theme-<name>`; the inner one
116
+ * (`.crewlet-brand-scope__layer`) declares the public tokens from the inputs,
117
+ * falling back to the captured values, exactly as the root layer falls back to
118
+ * the values the kit's build moved aside. The mapping's blocks are the
119
+ * source's, their selectors moved onto the inner element, so the scope follows
120
+ * the page's light or dark as the root layer does.
121
+ *
122
+ * A PINNED MODE (`data-mode` on the outer element) is that mode whatever the
123
+ * page is in: a preview that shows a brand in light beside the same brand in
124
+ * dark. The default theme's value of every public token the mapping drives is
125
+ * captured for the mode in place of the page's, every other token of the mode
126
+ * (the secondary text, the hairlines, the raised grounds) is declared on the
127
+ * layer itself, and the mapping takes the mode's own steps. Its blocks come
128
+ * last, so they win the ties.
129
+ */
130
+ export function brandScopeCss(css, modes) {
131
+ const layer = parseBrandLayer(css);
132
+ const slots = brandSlots(css);
133
+ const scope = `.${BRAND_SCOPE_CLASS}`;
134
+ const inner = `.${BRAND_SCOPE_LAYER_CLASS}`;
135
+ const pinned = (mode) => `${scope}[data-mode="${mode}"]`;
136
+ const capture = (values) => slots.flatMap((slot) => {
137
+ if (values === null)
138
+ return [[brandThemeName(slot), `var(${slot})`]];
139
+ const value = values.get(slot);
140
+ return value === undefined ? [] : [[brandThemeName(slot), value]];
141
+ });
142
+ // The dark steps a pinned dark scope restates over a light page: every step
143
+ // the light block also names, at the bare root's value.
144
+ const darkSteps = [...layer.dark].filter(([name]) => layer.light.has(name));
145
+ // The rest of a pinned mode's palette: every token the theme declares for it
146
+ // that the mapping does not drive (those are captured above, so the mapping
147
+ // still falls back to them).
148
+ const driven = new Set(slots);
149
+ const palette = (values) => [...values].filter(([name]) => !driven.has(name));
150
+ return [
151
+ '/* Generated by @crewlethq/tokens from stylesheets/brand.css (src/brand.ts). Do not edit. */',
152
+ '',
153
+ '/* The page\'s own values, one element above the mapping. */',
154
+ block(scope, capture(null)),
155
+ '',
156
+ block(inner, layer.dark),
157
+ '',
158
+ `${LIGHT_QUERY} {\n${block(`${LIGHT_MEDIA} ${inner}`, layer.light, ' ')}\n}`,
159
+ '',
160
+ block(`${LIGHT_ATTRIBUTE} ${inner},\n${pinned('light')} > ${inner}`, layer.light),
161
+ '',
162
+ '/* A pinned mode: the default theme\'s values for it, its own steps and the rest of its palette. */',
163
+ block(pinned('light'), capture(modes.light)),
164
+ '',
165
+ block(pinned('dark'), capture(modes.dark)),
166
+ '',
167
+ block(`${pinned('dark')} > ${inner}`, darkSteps),
168
+ '',
169
+ block(`${pinned('light')} > ${inner}`, palette(modes.light)),
170
+ '',
171
+ block(`${pinned('dark')} > ${inner}`, palette(modes.dark)),
172
+ '',
173
+ ].join('\n');
174
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Colour values and WCAG contrast: the one implementation every caller uses.
3
+ *
4
+ * Three callers, one source:
5
+ *
6
+ * - the published `@crewlethq/tokens` entry re-exports `parseHex`,
7
+ * `luminance`, `contrast` and `WCAG_CONTRAST`, so an interface that has to
8
+ * say whether two colours a person chose read on each other (a brand's text
9
+ * on its ground, a label on a fill) measures exactly as the palette suite
10
+ * does;
11
+ * - the palette suite (`test/color.mjs`, published as
12
+ * `@crewlethq/tokens/test/palette`) imports it from `dist/`, so the ratio a
13
+ * consumer's suite holds a theme to is the ratio its interface shows;
14
+ * - the token build (`scripts/build.mjs`) imports this source directly, before
15
+ * `tsc` has run, to derive each palette's tints. That is why the file uses
16
+ * only syntax Node can strip without compiling: type annotations and
17
+ * interfaces, no enums, namespaces or parameter properties.
18
+ */
19
+ /** A colour as sRGB channels from 0 to 255. Channels may be fractional (a composite over a ground). */
20
+ export interface Rgb {
21
+ r: number;
22
+ g: number;
23
+ b: number;
24
+ }
25
+ /**
26
+ * The WCAG 2 contrast floors, as ratios. `aa` and `aaa` are for body text;
27
+ * `aaLarge` and `aaaLarge` for large text (24px, or 18.66px bold) and, for
28
+ * `aaLarge`, for a graphical mark or a control's boundary. Compare the
29
+ * unrounded ratio against them: a ratio that passes only once rounded does
30
+ * not pass.
31
+ */
32
+ export declare const WCAG_CONTRAST: Readonly<{
33
+ readonly aa: 4.5;
34
+ readonly aaLarge: 3;
35
+ readonly aaa: 7;
36
+ readonly aaaLarge: 4.5;
37
+ }>;
38
+ /**
39
+ * A `#rrggbb` value as channels, or null for anything else. Surrounding white
40
+ * space is ignored and case does not matter; the three and eight digit forms,
41
+ * names and functional notations are not colours here, because every token
42
+ * and every brand colour is authored as six digits.
43
+ */
44
+ export declare function parseHex(hex: string): Rgb | null;
45
+ /** An `rgb()` or `rgba()` value as channels and an alpha, or null for anything else. */
46
+ export declare function parseRgba(value: string): {
47
+ rgb: Rgb;
48
+ a: number;
49
+ } | null;
50
+ /** The same colour at a new alpha, as the CSS value the build emits. */
51
+ export declare function withAlpha(value: string, alpha: number): string;
52
+ /** One sRGB channel, 0 to 255, as linear light, 0 to 1. */
53
+ export declare function linearChannel(value: number): number;
54
+ /** WCAG relative luminance, from 0 (black) to 1 (white). */
55
+ export declare function luminance({ r, g, b }: Rgb): number;
56
+ /**
57
+ * The WCAG 2 contrast ratio between two opaque colours, from 1 to 21, in
58
+ * either order. Unrounded: round only to display it, and compare the raw
59
+ * ratio against `WCAG_CONTRAST`.
60
+ */
61
+ export declare function contrast(a: Rgb, b: Rgb): number;
package/dist/color.js ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Colour values and WCAG contrast: the one implementation every caller uses.
3
+ *
4
+ * Three callers, one source:
5
+ *
6
+ * - the published `@crewlethq/tokens` entry re-exports `parseHex`,
7
+ * `luminance`, `contrast` and `WCAG_CONTRAST`, so an interface that has to
8
+ * say whether two colours a person chose read on each other (a brand's text
9
+ * on its ground, a label on a fill) measures exactly as the palette suite
10
+ * does;
11
+ * - the palette suite (`test/color.mjs`, published as
12
+ * `@crewlethq/tokens/test/palette`) imports it from `dist/`, so the ratio a
13
+ * consumer's suite holds a theme to is the ratio its interface shows;
14
+ * - the token build (`scripts/build.mjs`) imports this source directly, before
15
+ * `tsc` has run, to derive each palette's tints. That is why the file uses
16
+ * only syntax Node can strip without compiling: type annotations and
17
+ * interfaces, no enums, namespaces or parameter properties.
18
+ */
19
+ /**
20
+ * The WCAG 2 contrast floors, as ratios. `aa` and `aaa` are for body text;
21
+ * `aaLarge` and `aaaLarge` for large text (24px, or 18.66px bold) and, for
22
+ * `aaLarge`, for a graphical mark or a control's boundary. Compare the
23
+ * unrounded ratio against them: a ratio that passes only once rounded does
24
+ * not pass.
25
+ */
26
+ export const WCAG_CONTRAST = Object.freeze({ aa: 4.5, aaLarge: 3, aaa: 7, aaaLarge: 4.5 });
27
+ /**
28
+ * A `#rrggbb` value as channels, or null for anything else. Surrounding white
29
+ * space is ignored and case does not matter; the three and eight digit forms,
30
+ * names and functional notations are not colours here, because every token
31
+ * and every brand colour is authored as six digits.
32
+ */
33
+ export function parseHex(hex) {
34
+ const match = /^#([0-9a-f]{6})$/i.exec(hex.trim());
35
+ if (!match)
36
+ return null;
37
+ const n = Number.parseInt(match[1], 16);
38
+ return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };
39
+ }
40
+ /** An `rgb()` or `rgba()` value as channels and an alpha, or null for anything else. */
41
+ export function parseRgba(value) {
42
+ const match = /^rgba?\(([^)]+)\)$/i.exec(value.trim());
43
+ if (!match)
44
+ return null;
45
+ const [r, g, b, a] = match[1]
46
+ .split(/[,/\s]+/)
47
+ .filter(Boolean)
48
+ .map(Number);
49
+ if (r === undefined || g === undefined || b === undefined)
50
+ return null;
51
+ if ([r, g, b].some(Number.isNaN))
52
+ return null;
53
+ return { rgb: { r, g, b }, a: a === undefined ? 1 : a };
54
+ }
55
+ /** The same colour at a new alpha, as the CSS value the build emits. */
56
+ export function withAlpha(value, alpha) {
57
+ const rgb = parseHex(value) ?? parseRgba(value)?.rgb;
58
+ if (!rgb)
59
+ throw new Error(`cannot re-alpha "${value}"`);
60
+ return `rgba(${Math.round(rgb.r)}, ${Math.round(rgb.g)}, ${Math.round(rgb.b)}, ${alpha})`;
61
+ }
62
+ /** One sRGB channel, 0 to 255, as linear light, 0 to 1. */
63
+ export function linearChannel(value) {
64
+ const c = value / 255;
65
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
66
+ }
67
+ /** WCAG relative luminance, from 0 (black) to 1 (white). */
68
+ export function luminance({ r, g, b }) {
69
+ return 0.2126 * linearChannel(r) + 0.7152 * linearChannel(g) + 0.0722 * linearChannel(b);
70
+ }
71
+ /**
72
+ * The WCAG 2 contrast ratio between two opaque colours, from 1 to 21, in
73
+ * either order. Unrounded: round only to display it, and compare the raw
74
+ * ratio against `WCAG_CONTRAST`.
75
+ */
76
+ export function contrast(a, b) {
77
+ const la = luminance(a);
78
+ const lb = luminance(b);
79
+ const [hi, lo] = la > lb ? [la, lb] : [lb, la];
80
+ return (hi + 0.05) / (lo + 0.05);
81
+ }