@mapcairn/theme 0.0.0-stage → 0.1.0-rc.2

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,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # `@mapcairn/theme`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MapCairn's design tokens: typed references to CSS custom properties for colour, space, type, radius, shadow, motion and layering, with a light and a dark theme. Use it to style your own components so they match MapCairn's interface, or to check the contrast of a theme of your own. It is built with [vanilla-extract](https://vanilla-extract.style/) and has no dependency on another MapCairn package, a map engine or React.
4
+
5
+ **Status:** a release candidate, for early adopters. The API is still settling, so a breaking change can land before `0.1.0`; the [changelog](https://github.com/MapCairn/mapcairn/blob/main/CHANGELOG.md) lists each one. Until `0.1.0`, add `@next` to every package name in the install commands below.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @mapcairn/theme
11
+ pnpm add @mapcairn/theme
12
+ yarn add @mapcairn/theme
13
+ ```
14
+
15
+ The package is ESM only: it has no `main` field and no CommonJS build. A TypeScript project needs `moduleResolution` set to `node16`, `nodenext` or `bundler`; `node10` is not supported.
16
+
17
+ ## Usage
18
+
19
+ Import the token stylesheet once, in your entry module. It defines the custom properties for both themes. The `@mapcairn/map` components also need `@mapcairn/map/styles.css`, shown in the [`@mapcairn/map` README](https://github.com/MapCairn/mapcairn/tree/main/packages/map#set-up).
20
+
21
+ ```ts
22
+ import "@mapcairn/theme/tokens.css";
23
+ import { tokens } from "@mapcairn/theme";
24
+
25
+ Object.assign(document.body.style, {
26
+ fontFamily: tokens.type.family,
27
+ fontSize: tokens.type.body.size,
28
+ lineHeight: tokens.type.body.lineHeight,
29
+ color: tokens.color.text,
30
+ backgroundColor: tokens.color.pageBackground,
31
+ });
32
+ ```
33
+
34
+ Each value in `tokens` is a string of the form `var(--…)`, so it works in any style object. The package needs no vanilla-extract plugin: `dist` holds plain JavaScript and the compiled `tokens.css`. The generated custom property names are private and can change in any release, so use `tokens` and never write the names into a stylesheet of your own. [How the CSS ships](https://github.com/MapCairn/mapcairn/blob/main/DESIGN.md#how-the-css-ships) says what is and is not settled.
35
+
36
+ ## What it exports
37
+
38
+ | Export | Purpose |
39
+ | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
40
+ | `tokens` | The token contract: `tokens.color.*`, `shadow`, `effect`, `space`, `radius`, `type`, `size`, `focus`, `motion` and `z`. Each is a typed CSS variable reference, so a typo in a `.css.ts` file is a type error. The values and the light and dark switching are defined in `src/tokens.css.ts`. |
41
+ | `focusRing`, `blur`, `surfaceBlurStyle`, `surfaceBlurSupported` | Shared style fragments: the two-tone focus ring, and translucent surfaces with an opaque fallback. |
42
+ | `zLayer(name)` | The z-index variable for a named layer (map, mapOverlay, chrome, chromeRaised, sheet, toolbar, popover, toast). Components name a layer and never write a number. |
43
+ | `mapOverlayTokens` | Colours for everything drawn over the map: pin, measure line and fill, accuracy circle, scale bar and tile-error banner. |
44
+ | `checkThemeContrast(override)` | Checks a proposed partial colour override (14 interface roles, light and dark) against WCAG 2.2 AA over the worst-case map backdrops and returns the ratio, the minimum and the backdrop for each pair, as data. It never throws and does not accept or refuse a theme. Only hex, `rgb()`/`rgba()` and `oklch()` colours are supported; named colours, `hsl()`, `oklab()` and `color()` are reported as unparseable. A wrong-shaped override or an unknown key returns `invalid` entries (with `theme: null` and the reasons `malformed`, `unknown-key` or `unreadable`), and `passes` is false whenever anything is invalid. It checks only; `createThemeStylesheet` applies an override. Types: `ThemeOverride`, `ThemeColours`, `ThemeContrastCheck`, `ContrastFinding`, `InvalidColour`, `InvalidColourReason`, and the names they use: `ThemeColourRole`, `ContrastBackground`, `BackdropName`, `PairKind`, `ThemeName`. |
45
+ | `createThemeStylesheet(override, { scope })` | Turns a colour override into a stylesheet scoped to a selector the host owns (`:root`, `#id` or `.class`), or refuses. A theme below WCAG 2.2 AA, an unusable colour or an unusable scope returns `{ ok: false, css: undefined, findings, invalid, invalidScope }` and no CSS. Otherwise it returns `{ ok: true, css, findings }`: serve `css` as a same-origin file and link it after the SDK's stylesheets. The rules are written inside `(not (prefers-contrast: more))` and `(not (forced-colors: active))`, so high-contrast and forced-colours users keep the SDK's values, and it adds an opaque surface for browsers without `backdrop-filter` and for reduced transparency. Colours only; page, map and data roles are not overridable. The scope is matched as a descendant of `:root`, so a class on `<html>` does nothing (use `:root`). The custom property names it writes are generated and private, and match the SDK's stylesheet only for the same installed version of this package. Types: `ThemeStylesheet`, `ThemeStylesheetCreated`, `ThemeStylesheetRefused`, `ThemeStylesheetOptions`. |
46
+ | `tokenValues` | The raw values (colour roles for both themes, spacing, radii, type scale, motion, z layers). Used by tests and the contrast checks, not by components. |
47
+
48
+ In the repository, the token set and the contrast checks live in `src/tokens.css.ts`, `src/tokenValues.ts` and `src/contrast.ts`. The contrast tests compute every text and boundary pairing over the worst-case map backdrops in both themes.
49
+
50
+ [`DESIGN.md`](https://github.com/MapCairn/mapcairn/blob/main/DESIGN.md) describes the design system and the rules for using it.
51
+
52
+ ## Licence
53
+
54
+ `@mapcairn/theme` is licensed under AGPL-3.0-only, and the [licence text](https://github.com/MapCairn/mapcairn/blob/main/packages/theme/LICENSE) comes with the package. If you ship it in a product, or let people use a modified version over a network, you must publish the corresponding source under the same licence. The SDK packages depend only on permissively licensed packages. The [licence section of the repository README](https://github.com/MapCairn/mapcairn#licence) says more, including how to talk about other terms for closed-source use.
55
+
56
+ ## Contributing and changes
57
+
58
+ The source and the issue tracker are in the [repository](https://github.com/MapCairn/mapcairn); file a bug in the [issue tracker](https://github.com/MapCairn/mapcairn/issues). Read [`CONTRIBUTING.md`](https://github.com/MapCairn/mapcairn/blob/main/CONTRIBUTING.md) before you send a pull request. Changes between releases are listed in [`CHANGELOG.md`](https://github.com/MapCairn/mapcairn/blob/main/CHANGELOG.md).
@@ -0,0 +1,12 @@
1
+ // \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ export { __exportAll };
@@ -0,0 +1,167 @@
1
+ import { isInSrgbGamut, parseColour } from "./contrast.js";
2
+ import { contrastPairs, measurePair, opaqueRoles } from "./contrastPairs.js";
3
+ import { themeValues } from "./tokenValues.js";
4
+ // src/checkThemeContrast.ts
5
+ var themeNames = ["light", "dark"];
6
+ /** A plain object: not null, an array, a map, a class instance or one that inherits. */
7
+ function isPlainRecord(value) {
8
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
9
+ const prototype = Object.getPrototypeOf(value);
10
+ return prototype === Object.prototype || prototype === null;
11
+ }
12
+ var overridable = {
13
+ surface: true,
14
+ surfaceRaised: true,
15
+ text: true,
16
+ textMuted: true,
17
+ accent: true,
18
+ accentTint: true,
19
+ accentContrast: true,
20
+ hairline: true,
21
+ controlBoundary: true,
22
+ danger: true,
23
+ dangerTint: true,
24
+ scrim: true,
25
+ focusRing: true,
26
+ focusRingInner: true
27
+ };
28
+ function isRole(role) {
29
+ return Object.hasOwn(overridable, role);
30
+ }
31
+ function invalidReason(role, value) {
32
+ if (typeof value !== "string") return "unparseable";
33
+ try {
34
+ const colour = parseColour(value);
35
+ if (!isInSrgbGamut(value)) return "out-of-gamut";
36
+ return opaqueRoles.has(role) && colour.a < 1 ? "translucent" : null;
37
+ } catch {
38
+ return "unparseable";
39
+ }
40
+ }
41
+ function isThemeName(key) {
42
+ return themeNames.some((name) => name === key);
43
+ }
44
+ /**
45
+ * Reads the shape of an override from its own entries, reporting anything
46
+ * that is not an object, or a key that is not part of the shape. May throw
47
+ * when a getter or proxy trap throws.
48
+ */
49
+ function readProposedThemes(override) {
50
+ const result = {
51
+ proposed: {},
52
+ skipped: /* @__PURE__ */ new Set(),
53
+ invalid: []
54
+ };
55
+ const report = (theme, role, value, reason) => {
56
+ result.invalid.push({
57
+ theme,
58
+ role,
59
+ value,
60
+ reason
61
+ });
62
+ };
63
+ if (!isPlainRecord(override)) {
64
+ report(null, "override", override, "malformed");
65
+ return result;
66
+ }
67
+ for (const [key, colour] of Object.entries(override)) if (key !== "colour") report(null, key, colour, "unknown-key");
68
+ else if (colour !== void 0 && !isPlainRecord(colour)) report(null, "colour", colour, "malformed");
69
+ else readThemeSections(colour ?? {}, result, report);
70
+ return result;
71
+ }
72
+ function readThemeSections(colour, result, report) {
73
+ for (const [key, section] of Object.entries(colour)) if (!isThemeName(key)) report(null, key, section, "unknown-key");
74
+ else if (section !== void 0 && !isPlainRecord(section)) {
75
+ report(key, "colour", section, "malformed");
76
+ result.skipped.add(key);
77
+ } else if (section !== void 0) result.proposed[key] = section;
78
+ }
79
+ function resolveThemeColours(theme, proposed) {
80
+ const roles = { ...themeValues[theme].colour };
81
+ const invalidRoles = /* @__PURE__ */ new Set();
82
+ const invalid = [];
83
+ for (const [role, value] of Object.entries(proposed ?? {})) {
84
+ if (value === void 0) continue;
85
+ const reason = isRole(role) ? invalidReason(role, value) : "unknown-role";
86
+ if (reason !== null) {
87
+ invalidRoles.add(role);
88
+ invalid.push({
89
+ theme,
90
+ role,
91
+ value,
92
+ reason
93
+ });
94
+ } else Object.assign(roles, { [role]: value });
95
+ }
96
+ return {
97
+ roles,
98
+ invalidRoles,
99
+ invalid
100
+ };
101
+ }
102
+ function findingsFor(theme, { roles, invalidRoles }) {
103
+ const usable = (pair) => !invalidRoles.has(pair.foreground) && !invalidRoles.has(pair.background);
104
+ return contrastPairs.filter(usable).flatMap((pair) => (pair.backdrops.length === 0 ? [void 0] : pair.backdrops).map((backdrop) => {
105
+ const ratio = measurePair(roles, pair, backdrop);
106
+ return {
107
+ theme,
108
+ foreground: pair.foreground,
109
+ background: pair.background,
110
+ backdrop: backdrop ?? null,
111
+ kind: pair.kind,
112
+ ratio,
113
+ required: pair.required,
114
+ passes: ratio >= pair.required
115
+ };
116
+ }));
117
+ }
118
+ /**
119
+ * Checks a proposed theme against WCAG 2.2 AA: 4.5:1 for text, 3:1 for icons,
120
+ * control edges, selection and the focus ring. A role left out is checked at
121
+ * its default, so a changed `accent` is also checked against the default
122
+ * `accentTint`. Translucent surfaces are flattened over each representative
123
+ * map backdrop (white, black, a light map and the default basemap), so the
124
+ * worst case is reported.
125
+ *
126
+ * Pure and total: it never throws and never decides whether a theme is
127
+ * accepted. A colour it cannot check is reported in `invalid`, and the pairs
128
+ * that depend on it are left out of `findings`; the host decides what a
129
+ * failure means. Only the default colour set is checked: the opaque and
130
+ * `prefers-contrast: more` sets are not overridable.
131
+ *
132
+ * @param override The proposed colours for light and dark.
133
+ * @returns A finding for every checked pair and backdrop, in both themes.
134
+ */
135
+ function checkThemeContrast(override) {
136
+ const findings = [];
137
+ const invalid = [];
138
+ try {
139
+ const { proposed, skipped, invalid: shape } = readProposedThemes(override);
140
+ invalid.push(...shape);
141
+ for (const theme of themeNames.filter((name) => !skipped.has(name))) try {
142
+ const resolved = resolveThemeColours(theme, proposed[theme]);
143
+ invalid.push(...resolved.invalid);
144
+ findings.push(...findingsFor(theme, resolved));
145
+ } catch {
146
+ invalid.push(unreadable(theme));
147
+ }
148
+ } catch {
149
+ invalid.push(unreadable(null));
150
+ }
151
+ return {
152
+ passes: invalid.length === 0 && findings.every((finding) => finding.passes),
153
+ findings,
154
+ invalid
155
+ };
156
+ }
157
+ function unreadable(theme) {
158
+ return {
159
+ theme,
160
+ role: "colour",
161
+ value: void 0,
162
+ reason: "unreadable"
163
+ };
164
+ }
165
+ export { checkThemeContrast };
166
+
167
+ //# sourceMappingURL=checkThemeContrast.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkThemeContrast.js","names":[],"sources":["../src/checkThemeContrast.ts"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-only\n// Copyright MapCairn contributors\nimport { isInSrgbGamut, parseColour } from \"./contrast\";\nimport {\n type BackdropName,\n type ContrastBackground,\n type ContrastPair,\n contrastPairs,\n measurePair,\n opaqueRoles,\n type PairKind,\n type ThemeColourRole,\n} from \"./contrastPairs\";\nimport { type ColourRoles, type ThemeName, themeValues } from \"./tokenValues\";\n\n/**\n * The interface colour roles a host may override. Page and map roles, the\n * overlay roles and the data palette are not here: they carry their own\n * guarantees or belong to the host.\n */\nexport type ThemeColours = Record<ThemeColourRole, string>;\n\n/** A proposed theme: some colour roles, per theme. A role left out keeps its default. */\nexport interface ThemeOverride {\n /** Colour roles to change, per theme. */\n colour?: {\n light?: Partial<ThemeColours>;\n dark?: Partial<ThemeColours>;\n };\n}\n\n/** The measured contrast of one pair, in one theme, over one backdrop. */\nexport interface ContrastFinding {\n /** The theme the finding is for. */\n theme: ThemeName;\n /** The role drawn: text, an icon, an edge or a ring. */\n foreground: ThemeColourRole;\n /** The role it sits on, or `map` for the bare map. */\n background: ContrastBackground;\n /** The map backdrop checked over, or `null` for an opaque background. */\n backdrop: BackdropName | null;\n /** Whether the foreground is text or a non-text mark. */\n kind: PairKind;\n /** The contrast ratio, unrounded. */\n ratio: number;\n /** The WCAG 2.2 AA minimum for this kind of pair. */\n required: number;\n /** Whether `ratio` reaches `required`. */\n passes: boolean;\n}\n\n/** Why a proposed colour could not be checked. */\nexport type InvalidColourReason =\n | \"unknown-role\"\n | \"unparseable\"\n | \"out-of-gamut\"\n | \"translucent\"\n | \"unknown-key\"\n | \"malformed\"\n | \"unreadable\";\n\n/** A proposed colour that was not checked, so its pairs are missing from the findings. */\nexport interface InvalidColour {\n /** The theme it was proposed for, or `null` when it concerns the whole override. */\n theme: ThemeName | null;\n /**\n * The role, or the key or section that could not be used: `override` for\n * an override that is not a plain object, `colour` for a section that is not\n * (with `theme` set when it is one theme's section).\n */\n role: string;\n /** The value as the host supplied it. */\n value: unknown;\n /** Why it could not be checked. */\n reason: InvalidColourReason;\n}\n\n/** The result of {@link checkThemeContrast}. */\nexport interface ThemeContrastCheck {\n /** True when nothing is invalid and every finding passes. */\n passes: boolean;\n /** One finding for each pair, theme and backdrop that could be checked. */\n findings: ContrastFinding[];\n /** What could not be checked, and why. */\n invalid: InvalidColour[];\n}\n\nconst themeNames: readonly ThemeName[] = [\"light\", \"dark\"];\n\n/** A plain object: not null, an array, a map, a class instance or one that inherits. */\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nconst overridable: Record<keyof ThemeColours, true> = {\n surface: true,\n surfaceRaised: true,\n text: true,\n textMuted: true,\n accent: true,\n accentTint: true,\n accentContrast: true,\n hairline: true,\n controlBoundary: true,\n danger: true,\n dangerTint: true,\n scrim: true,\n focusRing: true,\n focusRingInner: true,\n};\n\nfunction isRole(role: string): role is keyof ThemeColours {\n return Object.hasOwn(overridable, role);\n}\n\nfunction invalidReason(\n role: keyof ThemeColours,\n value: unknown,\n): InvalidColourReason | null {\n if (typeof value !== \"string\") {\n return \"unparseable\";\n }\n try {\n const colour = parseColour(value);\n if (!isInSrgbGamut(value)) {\n return \"out-of-gamut\";\n }\n return opaqueRoles.has(role) && colour.a < 1 ? \"translucent\" : null;\n } catch {\n return \"unparseable\";\n }\n}\n\ninterface ResolvedTheme {\n roles: ColourRoles;\n invalidRoles: ReadonlySet<string>;\n invalid: InvalidColour[];\n}\n\n/** What could be read of an override's shape before any colour is looked at. */\ninterface ProposedThemes {\n proposed: Partial<Record<ThemeName, Record<string, unknown>>>;\n /** Themes whose section is not an object: nothing is checked for them. */\n skipped: Set<ThemeName>;\n invalid: InvalidColour[];\n}\n\nfunction isThemeName(key: string): key is ThemeName {\n return themeNames.some((name) => name === key);\n}\n\n/**\n * Reads the shape of an override from its own entries, reporting anything\n * that is not an object, or a key that is not part of the shape. May throw\n * when a getter or proxy trap throws.\n */\nfunction readProposedThemes(override: unknown): ProposedThemes {\n const result: ProposedThemes = {\n proposed: {},\n skipped: new Set(),\n invalid: [],\n };\n const report = (\n theme: ThemeName | null,\n role: string,\n value: unknown,\n reason: InvalidColourReason,\n ): void => {\n result.invalid.push({ theme, role, value, reason });\n };\n if (!isPlainRecord(override)) {\n report(null, \"override\", override, \"malformed\");\n return result;\n }\n for (const [key, colour] of Object.entries(override)) {\n if (key !== \"colour\") {\n report(null, key, colour, \"unknown-key\");\n } else if (colour !== undefined && !isPlainRecord(colour)) {\n report(null, \"colour\", colour, \"malformed\");\n } else {\n readThemeSections(colour ?? {}, result, report);\n }\n }\n return result;\n}\n\nfunction readThemeSections(\n colour: Record<string, unknown>,\n result: ProposedThemes,\n report: (\n theme: ThemeName | null,\n role: string,\n value: unknown,\n reason: InvalidColourReason,\n ) => void,\n): void {\n for (const [key, section] of Object.entries(colour)) {\n if (!isThemeName(key)) {\n report(null, key, section, \"unknown-key\");\n } else if (section !== undefined && !isPlainRecord(section)) {\n report(key, \"colour\", section, \"malformed\");\n result.skipped.add(key);\n } else if (section !== undefined) {\n result.proposed[key] = section;\n }\n }\n}\n\nfunction resolveThemeColours(\n theme: ThemeName,\n proposed: Record<string, unknown> | undefined,\n): ResolvedTheme {\n const roles: ColourRoles = { ...themeValues[theme].colour };\n const invalidRoles = new Set<string>();\n const invalid: InvalidColour[] = [];\n for (const [role, value] of Object.entries(proposed ?? {})) {\n if (value === undefined) {\n continue;\n }\n const reason = isRole(role) ? invalidReason(role, value) : \"unknown-role\";\n if (reason !== null) {\n invalidRoles.add(role);\n invalid.push({ theme, role, value, reason });\n } else {\n Object.assign(roles, { [role]: value });\n }\n }\n return { roles, invalidRoles, invalid };\n}\n\nfunction findingsFor(\n theme: ThemeName,\n { roles, invalidRoles }: ResolvedTheme,\n): ContrastFinding[] {\n const usable = (pair: ContrastPair): boolean =>\n !invalidRoles.has(pair.foreground) && !invalidRoles.has(pair.background);\n return contrastPairs.filter(usable).flatMap((pair) =>\n (pair.backdrops.length === 0 ? [undefined] : pair.backdrops).map(\n (backdrop): ContrastFinding => {\n const ratio = measurePair(roles, pair, backdrop);\n return {\n theme,\n foreground: pair.foreground,\n background: pair.background,\n backdrop: backdrop ?? null,\n kind: pair.kind,\n ratio,\n required: pair.required,\n passes: ratio >= pair.required,\n };\n },\n ),\n );\n}\n\n/**\n * Checks a proposed theme against WCAG 2.2 AA: 4.5:1 for text, 3:1 for icons,\n * control edges, selection and the focus ring. A role left out is checked at\n * its default, so a changed `accent` is also checked against the default\n * `accentTint`. Translucent surfaces are flattened over each representative\n * map backdrop (white, black, a light map and the default basemap), so the\n * worst case is reported.\n *\n * Pure and total: it never throws and never decides whether a theme is\n * accepted. A colour it cannot check is reported in `invalid`, and the pairs\n * that depend on it are left out of `findings`; the host decides what a\n * failure means. Only the default colour set is checked: the opaque and\n * `prefers-contrast: more` sets are not overridable.\n *\n * @param override The proposed colours for light and dark.\n * @returns A finding for every checked pair and backdrop, in both themes.\n */\nexport function checkThemeContrast(\n override: ThemeOverride,\n): ThemeContrastCheck {\n const findings: ContrastFinding[] = [];\n const invalid: InvalidColour[] = [];\n try {\n const { proposed, skipped, invalid: shape } = readProposedThemes(override);\n invalid.push(...shape);\n for (const theme of themeNames.filter((name) => !skipped.has(name))) {\n try {\n const resolved = resolveThemeColours(theme, proposed[theme]);\n invalid.push(...resolved.invalid);\n findings.push(...findingsFor(theme, resolved));\n } catch {\n invalid.push(unreadable(theme));\n }\n }\n } catch {\n invalid.push(unreadable(null));\n }\n return {\n passes: invalid.length === 0 && findings.every((finding) => finding.passes),\n findings,\n invalid,\n };\n}\n\nfunction unreadable(theme: ThemeName | null): InvalidColour {\n return { theme, role: \"colour\", value: undefined, reason: \"unreadable\" };\n}\n"],"mappings":";;;;AA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percentage of 100 stands for, per CSS Color 4. */
7
+ var OKLCH_CHROMA_AT_100_PERCENT = .4;
8
+ var MAX_CHANNEL = 255;
9
+ function cannotParse(colour) {
10
+ return /* @__PURE__ */ new Error(`Cannot parse colour: ${colour}`);
11
+ }
12
+ /** Reads a finite CSS number, or `undefined` when the text is not one. */
13
+ function readNumber(text) {
14
+ if (!NUMBER_RE.test(text)) return;
15
+ const value = Number.parseFloat(text);
16
+ return Number.isFinite(value) ? value : void 0;
17
+ }
18
+ /**
19
+ * Reads a number or a percentage as a fraction of `percentBasis`, then clamps
20
+ * it to `[min, max]` the way CSS does for out-of-range colour components.
21
+ * Returns `undefined` for anything else, including keywords such as `none`.
22
+ */
23
+ function readComponent(text, percentBasis, min, max) {
24
+ const isPercent = text.endsWith("%");
25
+ const value = readNumber(isPercent ? text.slice(0, -1) : text);
26
+ if (value === void 0) return;
27
+ const scaled = isPercent ? value / 100 * percentBasis : value;
28
+ return Math.min(max, Math.max(min, scaled));
29
+ }
30
+ /** Reads an optional alpha: a number or percentage, clamped to 0 to 1. */
31
+ function readAlpha(text) {
32
+ return text === void 0 ? 1 : readComponent(text, 1, 0, 1);
33
+ }
34
+ /** Reads a hue in degrees, with or without the `deg` unit. Other units are not supported. */
35
+ function readHue(text) {
36
+ return readNumber(text.toLowerCase().endsWith("deg") ? text.slice(0, -3) : text);
37
+ }
38
+ function isToken(text) {
39
+ return text !== "" && !/\s/.test(text);
40
+ }
41
+ /** `r, g, b` or `r, g, b, alpha`: exactly the right commas, no slash. */
42
+ function readLegacyArguments(text) {
43
+ const parts = text.split(",").map((part) => part.trim());
44
+ const [first, second, third, alpha] = parts;
45
+ if (parts.length !== 3 && parts.length !== 4 || first === void 0 || second === void 0 || third === void 0 || !parts.every(isToken)) return;
46
+ return {
47
+ components: [
48
+ first,
49
+ second,
50
+ third
51
+ ],
52
+ alpha,
53
+ legacy: true
54
+ };
55
+ }
56
+ /** `a b c` or `a b c / alpha`: spaces, and the slash only before the last argument. */
57
+ function readModernArguments(text) {
58
+ const slash = text.indexOf("/");
59
+ const alphaText = slash < 0 ? void 0 : text.slice(slash + 1).trim();
60
+ const [first, second, third, ...surplus] = (slash < 0 ? text : text.slice(0, slash)).trim().split(/\s+/);
61
+ if (alphaText?.includes("/") || surplus.length > 0 || first === void 0 || second === void 0 || third === void 0 || !isToken(first) || !isToken(second) || !isToken(third) || alphaText !== void 0 && !isToken(alphaText)) return;
62
+ return {
63
+ components: [
64
+ first,
65
+ second,
66
+ third
67
+ ],
68
+ alpha: alphaText,
69
+ legacy: false
70
+ };
71
+ }
72
+ /**
73
+ * Tokenises the inside of a functional colour the way CSS does: the commas
74
+ * syntax (only where `allowLegacy`) has exactly three or four comma-separated
75
+ * values and no slash; the spaces syntax has three values and an optional
76
+ * `/ alpha` as the last argument only. Empty arguments are refused.
77
+ */
78
+ function readArguments(inner, allowLegacy) {
79
+ const text = inner.trim();
80
+ if (!text.includes(",")) return readModernArguments(text);
81
+ return allowLegacy && !text.includes("/") ? readLegacyArguments(text) : void 0;
82
+ }
83
+ /** The text between the brackets of a matched functional colour. */
84
+ function insideBrackets(text) {
85
+ return text.slice(text.indexOf("(") + 1, -1);
86
+ }
87
+ /** Converts a gamma-encoded sRGB channel (0 to 1) to linear light. */
88
+ function srgbToLinear(channel) {
89
+ return channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4;
90
+ }
91
+ /** Converts a linear-light channel to gamma-encoded sRGB (0 to 1). */
92
+ function linearToSrgb(channel) {
93
+ return channel <= .0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - .055;
94
+ }
95
+ /**
96
+ * Converts OKLCH to linear sRGB using Björn Ottosson's matrices. Channels
97
+ * outside 0 to 1 are out of the sRGB gamut and are returned unclipped.
98
+ */
99
+ function oklchToLinearSrgb(lightness, chroma, hueDegrees) {
100
+ const hue = hueDegrees * Math.PI / 180;
101
+ const a = chroma * Math.cos(hue);
102
+ const b = chroma * Math.sin(hue);
103
+ const l = (lightness + .3963377774 * a + .2158037573 * b) ** 3;
104
+ const m = (lightness - .1055613458 * a - .0638541728 * b) ** 3;
105
+ const s = (lightness - .0894841775 * a - 1.291485548 * b) ** 3;
106
+ return [
107
+ 4.0767416621 * l - 3.3077115913 * m + .2309699292 * s,
108
+ -1.2684380046 * l + 2.6097574011 * m - .3413193965 * s,
109
+ -.0041960863 * l - .7034186147 * m + 1.707614701 * s
110
+ ];
111
+ }
112
+ /** Reads the `L C H [/ alpha]` arguments of text already matched as `oklch()`. */
113
+ function readOklch(colour) {
114
+ const args = readArguments(insideBrackets(colour.trim()), false);
115
+ if (args === void 0) throw cannotParse(colour);
116
+ const [rawL, rawC, rawH] = args.components;
117
+ const lightness = readComponent(rawL, 1, 0, 1);
118
+ const chroma = readComponent(rawC, OKLCH_CHROMA_AT_100_PERCENT, 0, Infinity);
119
+ const hue = readHue(rawH);
120
+ const alpha = readAlpha(args.alpha);
121
+ if (lightness === void 0 || chroma === void 0 || hue === void 0 || alpha === void 0) throw cannotParse(colour);
122
+ return {
123
+ lightness,
124
+ chroma,
125
+ hue,
126
+ alpha
127
+ };
128
+ }
129
+ /**
130
+ * Whether an `oklch()` colour fits inside the sRGB gamut without clipping.
131
+ * Token colours must, otherwise a wide-gamut display would render a colour
132
+ * the contrast maths never measured. Non-OKLCH colours are always in gamut.
133
+ */
134
+ function isInSrgbGamut(colour) {
135
+ if (!OKLCH_RE.test(colour.trim())) {
136
+ parseColour(colour);
137
+ return true;
138
+ }
139
+ const { lightness, chroma, hue } = readOklch(colour);
140
+ return oklchToLinearSrgb(lightness, chroma, hue).every((channel) => channel >= -1e-4 && channel <= 1.0001);
141
+ }
142
+ /**
143
+ * Parses a hex, `rgb()`/`rgba()` or `oklch()` colour to gamma-encoded sRGB.
144
+ * Numbers and percentages are read strictly: each component must be a finite
145
+ * number or percentage, the argument count must be right, and an `oklch()`
146
+ * hue may be plain or in degrees (other angle units are refused). Components
147
+ * outside their range are clamped as CSS does. OKLCH colours that fall outside the gamut are clipped per channel; use
148
+ * {@link isInSrgbGamut} to keep tokens from relying on that.
149
+ * @throws When the string is not in a supported syntax.
150
+ */
151
+ function parseColour(colour) {
152
+ const text = colour.trim();
153
+ if (text.toLowerCase() === "transparent") return {
154
+ r: 0,
155
+ g: 0,
156
+ b: 0,
157
+ a: 0
158
+ };
159
+ if (HEX_RE.test(text)) {
160
+ let digits = text.slice(1);
161
+ if (digits.length <= 4) digits = [...digits].map((digit) => digit + digit).join("");
162
+ const channel = (index) => Number.parseInt(digits.slice(index * 2, index * 2 + 2), 16);
163
+ return {
164
+ r: channel(0),
165
+ g: channel(1),
166
+ b: channel(2),
167
+ a: digits.length === 8 ? channel(3) / 255 : 1
168
+ };
169
+ }
170
+ if (RGB_RE.test(text)) {
171
+ const args = readArguments(insideBrackets(text), true);
172
+ if (args === void 0) throw cannotParse(colour);
173
+ const percents = args.components.filter((part) => part.endsWith("%"));
174
+ if (args.legacy && percents.length % 3 !== 0) throw cannotParse(colour);
175
+ const [r, g, b] = args.components.map((part) => readComponent(part, MAX_CHANNEL, 0, MAX_CHANNEL));
176
+ const a = readAlpha(args.alpha);
177
+ if (r === void 0 || g === void 0 || b === void 0 || a === void 0) throw cannotParse(colour);
178
+ return {
179
+ r,
180
+ g,
181
+ b,
182
+ a
183
+ };
184
+ }
185
+ if (OKLCH_RE.test(text)) {
186
+ const { lightness, chroma, hue, alpha } = readOklch(text);
187
+ const [r, g, b] = oklchToLinearSrgb(lightness, chroma, hue).map((channel) => Math.min(1, Math.max(0, linearToSrgb(Math.min(1, Math.max(0, channel))))) * 255);
188
+ return {
189
+ r,
190
+ g,
191
+ b,
192
+ a: alpha
193
+ };
194
+ }
195
+ throw new Error(`Cannot parse colour: ${colour}`);
196
+ }
197
+ /** Coerces a string or parsed colour to {@link Rgba}. */
198
+ function toRgba(colour) {
199
+ return typeof colour === "string" ? parseColour(colour) : colour;
200
+ }
201
+ /**
202
+ * Composites `foreground` over `backdrop` in gamma-encoded sRGB, which is
203
+ * what browsers do for `rgba()` and `oklch(... / a)`. The result is opaque
204
+ * whenever the backdrop is.
205
+ */
206
+ function compositeOver(foreground, backdrop) {
207
+ const top = toRgba(foreground);
208
+ const bottom = toRgba(backdrop);
209
+ const alpha = top.a + bottom.a * (1 - top.a);
210
+ if (alpha === 0) return {
211
+ r: 0,
212
+ g: 0,
213
+ b: 0,
214
+ a: 0
215
+ };
216
+ const mix = (front, back) => (front * top.a + back * bottom.a * (1 - top.a)) / alpha;
217
+ return {
218
+ r: mix(top.r, bottom.r),
219
+ g: mix(top.g, bottom.g),
220
+ b: mix(top.b, bottom.b),
221
+ a: alpha
222
+ };
223
+ }
224
+ /** WCAG 2.x relative luminance of an opaque colour, from 0 (black) to 1. */
225
+ function relativeLuminance(colour) {
226
+ return .2126 * srgbToLinear(colour.r / 255) + .7152 * srgbToLinear(colour.g / 255) + .0722 * srgbToLinear(colour.b / 255);
227
+ }
228
+ /**
229
+ * WCAG contrast ratio, from 1 to 21, between two opaque colours.
230
+ * @throws When either colour is translucent. Composite it over a backdrop
231
+ * with {@link compositeOver} first, because the ratio depends on it.
232
+ */
233
+ function contrastRatio(a, b) {
234
+ const first = toRgba(a);
235
+ const second = toRgba(b);
236
+ if (first.a < 1 || second.a < 1) throw new Error("Cannot compute contrast for a translucent colour");
237
+ const [lighter, darker] = [relativeLuminance(first), relativeLuminance(second)].sort((x, y) => y - x);
238
+ return (lighter + .05) / (darker + .05);
239
+ }
240
+ /** Formats a colour as `#rrggbb`, or `#rrggbbaa` when it is translucent. */
241
+ function toHex(colour) {
242
+ const byte = (value) => Math.round(Math.min(255, Math.max(0, value))).toString(16).padStart(2, "0");
243
+ const alpha = colour.a < 1 ? byte(colour.a * 255) : "";
244
+ return `#${byte(colour.r)}${byte(colour.g)}${byte(colour.b)}${alpha}`;
245
+ }
246
+ export { compositeOver, contrastRatio, isInSrgbGamut, parseColour, relativeLuminance, toHex };
247
+
248
+ //# sourceMappingURL=contrast.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contrast.js","names":[],"sources":["../src/contrast.ts"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-only\n// Copyright MapCairn contributors\n/**\n * WCAG contrast maths with no dependencies. It parses the colour syntaxes the\n * token file uses (hex, `rgb()`/`rgba()` and `oklch()`), composites alpha the\n * way browsers do and computes relative luminance and contrast ratios. The\n * token tests use it to enforce AA over the worst-case map backdrops.\n */\n\n/** A colour in gamma-encoded sRGB. Channels are 0 to 255, alpha is 0 to 1. */\nexport interface Rgba {\n r: number;\n g: number;\n b: number;\n a: number;\n}\n\n/** A colour as the token files write it, or one already parsed. */\nexport type ColourInput = string | Rgba;\n\nconst HEX_RE = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;\n// The brackets hold anything but a closing bracket, which `readArguments`\n// then splits in linear time. A lazy group between two `\\s*` runs backtracks\n// quadratically on a long run of spaces.\nconst RGB_RE = /^rgba?\\([^)]*\\)$/i;\nconst OKLCH_RE = /^oklch\\([^)]*\\)$/i;\n\nconst NUMBER_RE = /^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n/** `oklch()` chroma that a percentage of 100 stands for, per CSS Color 4. */\nconst OKLCH_CHROMA_AT_100_PERCENT = 0.4;\nconst MAX_CHANNEL = 255;\n\nfunction cannotParse(colour: string): Error {\n return new Error(`Cannot parse colour: ${colour}`);\n}\n\n/** Reads a finite CSS number, or `undefined` when the text is not one. */\nfunction readNumber(text: string): number | undefined {\n if (!NUMBER_RE.test(text)) {\n return undefined;\n }\n const value = Number.parseFloat(text);\n return Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Reads a number or a percentage as a fraction of `percentBasis`, then clamps\n * it to `[min, max]` the way CSS does for out-of-range colour components.\n * Returns `undefined` for anything else, including keywords such as `none`.\n */\nfunction readComponent(\n text: string,\n percentBasis: number,\n min: number,\n max: number,\n): number | undefined {\n const isPercent = text.endsWith(\"%\");\n const value = readNumber(isPercent ? text.slice(0, -1) : text);\n if (value === undefined) {\n return undefined;\n }\n const scaled = isPercent ? (value / 100) * percentBasis : value;\n return Math.min(max, Math.max(min, scaled));\n}\n\n/** Reads an optional alpha: a number or percentage, clamped to 0 to 1. */\nfunction readAlpha(text: string | undefined): number | undefined {\n return text === undefined ? 1 : readComponent(text, 1, 0, 1);\n}\n\n/** Reads a hue in degrees, with or without the `deg` unit. Other units are not supported. */\nfunction readHue(text: string): number | undefined {\n return readNumber(\n text.toLowerCase().endsWith(\"deg\") ? text.slice(0, -3) : text,\n );\n}\n\n/** The arguments of a functional colour, tokenised. */\ninterface ColourArguments {\n components: [string, string, string];\n alpha: string | undefined;\n /** Whether the commas syntax was used. */\n legacy: boolean;\n}\n\nfunction isToken(text: string): boolean {\n return text !== \"\" && !/\\s/.test(text);\n}\n\n/** `r, g, b` or `r, g, b, alpha`: exactly the right commas, no slash. */\nfunction readLegacyArguments(text: string): ColourArguments | undefined {\n const parts = text.split(\",\").map((part) => part.trim());\n const [first, second, third, alpha] = parts;\n if (\n (parts.length !== 3 && parts.length !== 4) ||\n first === undefined ||\n second === undefined ||\n third === undefined ||\n !parts.every(isToken)\n ) {\n return undefined;\n }\n return { components: [first, second, third], alpha, legacy: true };\n}\n\n/** `a b c` or `a b c / alpha`: spaces, and the slash only before the last argument. */\nfunction readModernArguments(text: string): ColourArguments | undefined {\n const slash = text.indexOf(\"/\");\n const alphaText = slash < 0 ? undefined : text.slice(slash + 1).trim();\n const [first, second, third, ...surplus] = (\n slash < 0 ? text : text.slice(0, slash)\n )\n .trim()\n .split(/\\s+/);\n if (\n alphaText?.includes(\"/\") ||\n surplus.length > 0 ||\n first === undefined ||\n second === undefined ||\n third === undefined ||\n !isToken(first) ||\n !isToken(second) ||\n !isToken(third) ||\n (alphaText !== undefined && !isToken(alphaText))\n ) {\n return undefined;\n }\n return {\n components: [first, second, third],\n alpha: alphaText,\n legacy: false,\n };\n}\n\n/**\n * Tokenises the inside of a functional colour the way CSS does: the commas\n * syntax (only where `allowLegacy`) has exactly three or four comma-separated\n * values and no slash; the spaces syntax has three values and an optional\n * `/ alpha` as the last argument only. Empty arguments are refused.\n */\nfunction readArguments(\n inner: string,\n allowLegacy: boolean,\n): ColourArguments | undefined {\n const text = inner.trim();\n if (!text.includes(\",\")) {\n return readModernArguments(text);\n }\n return allowLegacy && !text.includes(\"/\")\n ? readLegacyArguments(text)\n : undefined;\n}\n\n/** The text between the brackets of a matched functional colour. */\nfunction insideBrackets(text: string): string {\n return text.slice(text.indexOf(\"(\") + 1, -1);\n}\n\n/** Converts a gamma-encoded sRGB channel (0 to 1) to linear light. */\nfunction srgbToLinear(channel: number): number {\n return channel <= 0.04045\n ? channel / 12.92\n : ((channel + 0.055) / 1.055) ** 2.4;\n}\n\n/** Converts a linear-light channel to gamma-encoded sRGB (0 to 1). */\nfunction linearToSrgb(channel: number): number {\n return channel <= 0.0031308\n ? channel * 12.92\n : 1.055 * channel ** (1 / 2.4) - 0.055;\n}\n\n/**\n * Converts OKLCH to linear sRGB using Björn Ottosson's matrices. Channels\n * outside 0 to 1 are out of the sRGB gamut and are returned unclipped.\n */\nfunction oklchToLinearSrgb(\n lightness: number,\n chroma: number,\n hueDegrees: number,\n): [number, number, number] {\n const hue = (hueDegrees * Math.PI) / 180;\n const a = chroma * Math.cos(hue);\n const b = chroma * Math.sin(hue);\n const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;\n const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;\n const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;\n return [\n 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,\n ];\n}\n\n/** Reads the `L C H [/ alpha]` arguments of text already matched as `oklch()`. */\nfunction readOklch(colour: string): {\n lightness: number;\n chroma: number;\n hue: number;\n alpha: number;\n} {\n const text = colour.trim();\n const args = readArguments(insideBrackets(text), false);\n if (args === undefined) {\n throw cannotParse(colour);\n }\n const [rawL, rawC, rawH] = args.components;\n const lightness = readComponent(rawL, 1, 0, 1);\n const chroma = readComponent(rawC, OKLCH_CHROMA_AT_100_PERCENT, 0, Infinity);\n const hue = readHue(rawH);\n const alpha = readAlpha(args.alpha);\n if (\n lightness === undefined ||\n chroma === undefined ||\n hue === undefined ||\n alpha === undefined\n ) {\n throw cannotParse(colour);\n }\n return { lightness, chroma, hue, alpha };\n}\n\n/**\n * Whether an `oklch()` colour fits inside the sRGB gamut without clipping.\n * Token colours must, otherwise a wide-gamut display would render a colour\n * the contrast maths never measured. Non-OKLCH colours are always in gamut.\n */\nexport function isInSrgbGamut(colour: string): boolean {\n if (!OKLCH_RE.test(colour.trim())) {\n parseColour(colour);\n return true;\n }\n const { lightness, chroma, hue } = readOklch(colour);\n const epsilon = 1e-4;\n return oklchToLinearSrgb(lightness, chroma, hue).every(\n (channel) => channel >= -epsilon && channel <= 1 + epsilon,\n );\n}\n\n/**\n * Parses a hex, `rgb()`/`rgba()` or `oklch()` colour to gamma-encoded sRGB.\n * Numbers and percentages are read strictly: each component must be a finite\n * number or percentage, the argument count must be right, and an `oklch()`\n * hue may be plain or in degrees (other angle units are refused). Components\n * outside their range are clamped as CSS does. OKLCH colours that fall outside the gamut are clipped per channel; use\n * {@link isInSrgbGamut} to keep tokens from relying on that.\n * @throws When the string is not in a supported syntax.\n */\nexport function parseColour(colour: string): Rgba {\n const text = colour.trim();\n if (text.toLowerCase() === \"transparent\") {\n return { r: 0, g: 0, b: 0, a: 0 };\n }\n if (HEX_RE.test(text)) {\n let digits = text.slice(1);\n if (digits.length <= 4) {\n digits = [...digits].map((digit) => digit + digit).join(\"\");\n }\n const channel = (index: number): number =>\n Number.parseInt(digits.slice(index * 2, index * 2 + 2), 16);\n return {\n r: channel(0),\n g: channel(1),\n b: channel(2),\n a: digits.length === 8 ? channel(3) / 255 : 1,\n };\n }\n\n if (RGB_RE.test(text)) {\n const args = readArguments(insideBrackets(text), true);\n if (args === undefined) {\n throw cannotParse(colour);\n }\n const percents = args.components.filter((part) => part.endsWith(\"%\"));\n if (args.legacy && percents.length % 3 !== 0) {\n throw cannotParse(colour);\n }\n const [r, g, b] = args.components.map((part) =>\n readComponent(part, MAX_CHANNEL, 0, MAX_CHANNEL),\n );\n const a = readAlpha(args.alpha);\n if (\n r === undefined ||\n g === undefined ||\n b === undefined ||\n a === undefined\n ) {\n throw cannotParse(colour);\n }\n return { r, g, b, a };\n }\n\n if (OKLCH_RE.test(text)) {\n const { lightness, chroma, hue, alpha } = readOklch(text);\n const [r, g, b] = oklchToLinearSrgb(lightness, chroma, hue).map(\n (channel) =>\n Math.min(\n 1,\n Math.max(0, linearToSrgb(Math.min(1, Math.max(0, channel)))),\n ) * 255,\n ) as [number, number, number];\n return { r, g, b, a: alpha };\n }\n\n throw new Error(`Cannot parse colour: ${colour}`);\n}\n\n/** Coerces a string or parsed colour to {@link Rgba}. */\nfunction toRgba(colour: ColourInput): Rgba {\n return typeof colour === \"string\" ? parseColour(colour) : colour;\n}\n\n/**\n * Composites `foreground` over `backdrop` in gamma-encoded sRGB, which is\n * what browsers do for `rgba()` and `oklch(... / a)`. The result is opaque\n * whenever the backdrop is.\n */\nexport function compositeOver(\n foreground: ColourInput,\n backdrop: ColourInput,\n): Rgba {\n const top = toRgba(foreground);\n const bottom = toRgba(backdrop);\n const alpha = top.a + bottom.a * (1 - top.a);\n if (alpha === 0) {\n return { r: 0, g: 0, b: 0, a: 0 };\n }\n const mix = (front: number, back: number): number =>\n (front * top.a + back * bottom.a * (1 - top.a)) / alpha;\n return {\n r: mix(top.r, bottom.r),\n g: mix(top.g, bottom.g),\n b: mix(top.b, bottom.b),\n a: alpha,\n };\n}\n\n/** WCAG 2.x relative luminance of an opaque colour, from 0 (black) to 1. */\nexport function relativeLuminance(colour: Rgba): number {\n return (\n 0.2126 * srgbToLinear(colour.r / 255) +\n 0.7152 * srgbToLinear(colour.g / 255) +\n 0.0722 * srgbToLinear(colour.b / 255)\n );\n}\n\n/**\n * WCAG contrast ratio, from 1 to 21, between two opaque colours.\n * @throws When either colour is translucent. Composite it over a backdrop\n * with {@link compositeOver} first, because the ratio depends on it.\n */\nexport function contrastRatio(a: ColourInput, b: ColourInput): number {\n const first = toRgba(a);\n const second = toRgba(b);\n if (first.a < 1 || second.a < 1) {\n throw new Error(\"Cannot compute contrast for a translucent colour\");\n }\n const [lighter, darker] = [\n relativeLuminance(first),\n relativeLuminance(second),\n ].sort((x, y) => y - x) as [number, number];\n return (lighter + 0.05) / (darker + 0.05);\n}\n\n/** Formats a colour as `#rrggbb`, or `#rrggbbaa` when it is translucent. */\nexport function toHex(colour: Rgba): string {\n const byte = (value: number): string =>\n Math.round(Math.min(255, Math.max(0, value)))\n .toString(16)\n .padStart(2, \"0\");\n const alpha = colour.a < 1 ? byte(colour.a * 255) : \"\";\n return `#${byte(colour.r)}${byte(colour.g)}${byte(colour.b)}${alpha}`;\n}\n"],"mappings":";AAoBA,IAAM,SAAS;AAIf,IAAM,SAAS;AACf,IAAM,WAAW;AAEjB,IAAM,YAAY;;AAElB,IAAM,8BAA8B;AACpC,IAAM,cAAc;AAEpB,SAAS,YAAY,QAAuB;CAC1C,uBAAO,IAAI,MAAM,wBAAwB,QAAQ;AACnD;;AAGA,SAAS,WAAW,MAAkC;CACpD,IAAI,CAAC,UAAU,KAAK,IAAI,GACtB;CAEF,MAAM,QAAQ,OAAO,WAAW,IAAI;CACpC,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AAC1C;;;;;;AAOA,SAAS,cACP,MACA,cACA,KACA,KACoB;CACpB,MAAM,YAAY,KAAK,SAAS,GAAG;CACnC,MAAM,QAAQ,WAAW,YAAY,KAAK,MAAM,GAAG,EAAE,IAAI,IAAI;CAC7D,IAAI,UAAU,KAAA,GACZ;CAEF,MAAM,SAAS,YAAa,QAAQ,MAAO,eAAe;CAC1D,OAAO,KAAK,IAAI,KAAK,KAAK,IA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