@mapcairn/theme 0.0.0-stage → 0.1.0-rc.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.
@@ -0,0 +1,99 @@
1
+ import { compositeOver, contrastRatio, parseColour } from "./contrast.js";
2
+ import { representativeBackdrops } from "./tokenValues.js";
3
+ // src/contrastPairs.ts
4
+ /** WCAG 2.2 AA contrast for text. */
5
+ var AA_TEXT = 4.5;
6
+ /**
7
+ * White and black bracket every map. The light map and the default basemap
8
+ * are named as well rather than assumed to fall between them: a surface's
9
+ * tint can make a mid-light backdrop the worst case for a colour that clears
10
+ * both extremes.
11
+ */
12
+ var everyBackdrop = [
13
+ "white",
14
+ "black",
15
+ "lightMap",
16
+ "defaultBasemap"
17
+ ];
18
+ var bareMapBackdrops = ["white", "black"];
19
+ var surfacePairs = ["surface", "surfaceRaised"].flatMap((background) => [...[
20
+ "text",
21
+ "textMuted",
22
+ "accent",
23
+ "danger"
24
+ ].map((foreground) => ({
25
+ foreground,
26
+ background,
27
+ kind: "text",
28
+ required: AA_TEXT,
29
+ backdrops: everyBackdrop
30
+ })), ...["controlBoundary", "focusRing"].map((foreground) => ({
31
+ foreground,
32
+ background,
33
+ kind: "non-text",
34
+ required: 3,
35
+ backdrops: everyBackdrop
36
+ }))]);
37
+ var opaquePair = (foreground, background, kind) => ({
38
+ foreground,
39
+ background,
40
+ kind,
41
+ required: kind === "text" ? AA_TEXT : 3,
42
+ backdrops: []
43
+ });
44
+ /**
45
+ * Every pair a theme must keep. Internal: the SDK's own token tests and
46
+ * `checkThemeContrast` read this one list, so they cannot drift apart. Hairlines,
47
+ * the scrim, disabled controls and the translucent map fills are exempt under
48
+ * WCAG 1.4.3 and 1.4.11 (see the note in `contrast.test.ts`).
49
+ */
50
+ var contrastPairs = [
51
+ ...surfacePairs,
52
+ opaquePair("accentContrast", "accent", "text"),
53
+ opaquePair("text", "accentTint", "text"),
54
+ opaquePair("accent", "accentTint", "text"),
55
+ opaquePair("textMuted", "accentTint", "text"),
56
+ opaquePair("controlBoundary", "accentTint", "non-text"),
57
+ opaquePair("text", "dangerTint", "text"),
58
+ opaquePair("danger", "dangerTint", "text"),
59
+ {
60
+ foreground: "focusRing",
61
+ background: "map",
62
+ kind: "non-text",
63
+ required: 3,
64
+ backdrops: bareMapBackdrops
65
+ },
66
+ opaquePair("focusRingInner", "focusRing", "non-text"),
67
+ opaquePair("text", "pageBackground", "text"),
68
+ opaquePair("textMuted", "pageBackground", "text"),
69
+ opaquePair("accent", "pageBackground", "text"),
70
+ opaquePair("text", "mapHalo", "text")
71
+ ];
72
+ /**
73
+ * Roles that act as a background in {@link contrastPairs} and so must be
74
+ * opaque for the ratio to mean anything.
75
+ */
76
+ var opaqueRoles = /* @__PURE__ */ new Set([
77
+ "accent",
78
+ "accentTint",
79
+ "dangerTint",
80
+ "focusRing",
81
+ "focusRingInner"
82
+ ]);
83
+ /**
84
+ * The contrast ratio of one pair over one backdrop, with a translucent
85
+ * foreground or surface flattened first. Pass `undefined` when the pair has no
86
+ * backdrops.
87
+ */
88
+ function measurePair(roles, pair, backdrop) {
89
+ const under = backgroundUnder(roles, pair, backdrop);
90
+ return contrastRatio(compositeOver(roles[pair.foreground], under), under);
91
+ }
92
+ function backgroundUnder(roles, pair, backdrop) {
93
+ if (backdrop === void 0) return parseColour(roles[pair.background]);
94
+ if (pair.background === "map") return parseColour(representativeBackdrops[backdrop]);
95
+ return compositeOver(roles[pair.background], representativeBackdrops[backdrop]);
96
+ }
97
+ export { AA_TEXT, contrastPairs, measurePair, opaqueRoles };
98
+
99
+ //# sourceMappingURL=contrastPairs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contrastPairs.js","names":[],"sources":["../src/contrastPairs.ts"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-only\n// Copyright MapCairn contributors\nimport { compositeOver, contrastRatio, parseColour } from \"./contrast\";\nimport { type ColourRoles, representativeBackdrops } from \"./tokenValues\";\n\n/** WCAG 2.2 AA contrast for text. */\nexport const AA_TEXT = 4.5;\n/** WCAG 2.2 AA contrast for icons, control edges, selection and the focus ring. */\nexport const AA_NON_TEXT = 3;\n\n/**\n * Name of one of the representative map backdrops: white, black, a light map\n * and the default basemap's land colour. Indexing `representativeBackdrops`\n * with it keeps the two in step at compile time.\n */\nexport type BackdropName = \"white\" | \"black\" | \"lightMap\" | \"defaultBasemap\";\n\n/** What a pair's foreground is: text, or a non-text mark such as an edge or ring. */\nexport type PairKind = \"text\" | \"non-text\";\n\n/**\n * The interface colour roles a host may override, and so the roles a\n * finding's foreground can name.\n */\nexport type ThemeColourRole =\n | \"surface\"\n | \"surfaceRaised\"\n | \"text\"\n | \"textMuted\"\n | \"accent\"\n | \"accentTint\"\n | \"accentContrast\"\n | \"hairline\"\n | \"controlBoundary\"\n | \"danger\"\n | \"dangerTint\"\n | \"scrim\"\n | \"focusRing\"\n | \"focusRingInner\";\n\n/**\n * The colour a pair's foreground sits on. `surface` and `surfaceRaised` are\n * translucent, so they are flattened over each backdrop first; `map` is the\n * bare map itself; the page background and the map halo are fixed defaults\n * a host cannot override; the rest are opaque roles.\n */\nexport type ContrastBackground =\n | ThemeColourRole\n | \"pageBackground\"\n | \"mapHalo\"\n | \"map\";\n\n/** One foreground-and-background pair that must reach a contrast ratio. */\nexport interface ContrastPair {\n foreground: ThemeColourRole;\n background: ContrastBackground;\n kind: PairKind;\n /** Minimum contrast ratio. */\n required: number;\n /**\n * The map backdrops to check over, in order. Empty when the background is\n * opaque and the backdrop does not show through.\n */\n backdrops: readonly BackdropName[];\n}\n\n/**\n * White and black bracket every map. The light map and the default basemap\n * are named as well rather than assumed to fall between them: a surface's\n * tint can make a mid-light backdrop the worst case for a colour that clears\n * both extremes.\n */\nconst everyBackdrop: readonly BackdropName[] = [\n \"white\",\n \"black\",\n \"lightMap\",\n \"defaultBasemap\",\n];\nconst bareMapBackdrops: readonly BackdropName[] = [\"white\", \"black\"];\n\nconst surfaceRoles = [\"surface\", \"surfaceRaised\"] as const;\n\nconst surfacePairs: readonly ContrastPair[] = surfaceRoles.flatMap(\n (background) => [\n ...([\"text\", \"textMuted\", \"accent\", \"danger\"] as const).map(\n (foreground): ContrastPair => ({\n foreground,\n background,\n kind: \"text\",\n required: AA_TEXT,\n backdrops: everyBackdrop,\n }),\n ),\n ...([\"controlBoundary\", \"focusRing\"] as const).map(\n (foreground): ContrastPair => ({\n foreground,\n background,\n kind: \"non-text\",\n required: AA_NON_TEXT,\n backdrops: everyBackdrop,\n }),\n ),\n ],\n);\n\nconst opaquePair = (\n foreground: ThemeColourRole,\n background: ContrastBackground,\n kind: PairKind,\n): ContrastPair => ({\n foreground,\n background,\n kind,\n required: kind === \"text\" ? AA_TEXT : AA_NON_TEXT,\n backdrops: [],\n});\n\n/**\n * Every pair a theme must keep. Internal: the SDK's own token tests and\n * `checkThemeContrast` read this one list, so they cannot drift apart. Hairlines,\n * the scrim, disabled controls and the translucent map fills are exempt under\n * WCAG 1.4.3 and 1.4.11 (see the note in `contrast.test.ts`).\n */\nexport const contrastPairs: readonly ContrastPair[] = [\n ...surfacePairs,\n // Also the checked switch: its thumb is `accentContrast` on the `accent`\n // track and its tick is `accent` on the thumb (`Switch.css.ts`). Contrast is\n // symmetric, so this 4.5:1 pair covers both, well above the 3:1 the parts\n // of a control need (WCAG 1.4.11).\n opaquePair(\"accentContrast\", \"accent\", \"text\"),\n opaquePair(\"text\", \"accentTint\", \"text\"),\n opaquePair(\"accent\", \"accentTint\", \"text\"),\n // A selected list row draws its secondary and trailing text on the tint\n // (`ListRow.css.ts`), and a switch's hover track draws the control edge on it\n // (`Switch.css.ts`).\n opaquePair(\"textMuted\", \"accentTint\", \"text\"),\n opaquePair(\"controlBoundary\", \"accentTint\", \"non-text\"),\n opaquePair(\"text\", \"dangerTint\", \"text\"),\n opaquePair(\"danger\", \"dangerTint\", \"text\"),\n {\n foreground: \"focusRing\",\n background: \"map\",\n kind: \"non-text\",\n required: AA_NON_TEXT,\n backdrops: bareMapBackdrops,\n },\n opaquePair(\"focusRingInner\", \"focusRing\", \"non-text\"),\n // Full pages and text drawn straight on the map. Their backgrounds are not\n // overridable, so a host's text and accent are held to the defaults.\n opaquePair(\"text\", \"pageBackground\", \"text\"),\n opaquePair(\"textMuted\", \"pageBackground\", \"text\"),\n opaquePair(\"accent\", \"pageBackground\", \"text\"),\n opaquePair(\"text\", \"mapHalo\", \"text\"),\n];\n\n/**\n * Roles that act as a background in {@link contrastPairs} and so must be\n * opaque for the ratio to mean anything.\n */\nexport const opaqueRoles: ReadonlySet<keyof ColourRoles> = new Set([\n \"accent\",\n \"accentTint\",\n \"dangerTint\",\n \"focusRing\",\n \"focusRingInner\",\n]);\n\n/**\n * The contrast ratio of one pair over one backdrop, with a translucent\n * foreground or surface flattened first. Pass `undefined` when the pair has no\n * backdrops.\n */\nexport function measurePair(\n roles: ColourRoles,\n pair: ContrastPair,\n backdrop: BackdropName | undefined,\n): number {\n const under = backgroundUnder(roles, pair, backdrop);\n return contrastRatio(compositeOver(roles[pair.foreground], under), under);\n}\n\nfunction backgroundUnder(\n roles: ColourRoles,\n pair: ContrastPair,\n backdrop: BackdropName | undefined,\n) {\n if (backdrop === undefined) {\n return parseColour(roles[pair.background as keyof ColourRoles]);\n }\n if (pair.background === \"map\") {\n return parseColour(representativeBackdrops[backdrop]);\n }\n return compositeOver(\n roles[pair.background],\n representativeBackdrops[backdrop],\n );\n}\n"],"mappings":";;;;AAMA,IAAa,UAAU;;;;;;;AAkEvB,IAAM,gBAAyC;CAC7C;CACA;CACA;CACA;AACF;AACA,IAAM,mBAA4C,CAAC,SAAS,OAAO;AAInE,IAAM,eAAwC,CAFxB,WAAW,eAEa,CAAA,CAAa,SACxD,eAAe,CACd,GAAI;CAAC;CAAQ;CAAa;CAAU;AAAQ,CAAC,CAAW,KACrD,gBAA8B;CAC7B;CACA;CACA,MAAM;CACN,UAAU;CACV,WAAW;AACb,EACF,GACA,GAAI,CAAC,mBAAmB,WAAW,CAAC,CAAW,KAC5C,gBAA8B;CAC7B;CACA;CACA,MAAM;CACN,UAAA;CACA,WAAW;AACb,EACF,CACF,CACF;AAEA,IAAM,cACJ,YACA,YACA,UACkB;CAClB;CACA;CACA;CACA,UAAU,SAAS,SAAS,UAAA;CAC5B,WAAW,CAAC;AACd;;;;;;;AAQA,IAAa,gBAAyC;CACpD,GAAG;CAKH,WAAW,kBAAkB,UAAU,MAAM;CAC7C,WAAW,QAAQ,cAAc,MAAM;CACvC,WAAW,UAAU,cAAc,MAAM;CAIzC,WAAW,aAAa,cAAc,MAAM;CAC5C,WAAW,mBAAmB,cAAc,UAAU;CACtD,WAAW,QAAQ,cAAc,MAAM;CACvC,WAAW,UAAU,cAAc,MAAM;CACzC;EACE,YAAY;EACZ,YAAY;EACZ,MAAM;EACN,UAAA;EACA,WAAW;CACb;CACA,WAAW,kBAAkB,aAAa,UAAU;CAGpD,WAAW,QAAQ,kBAAkB,MAAM;CAC3C,WAAW,aAAa,kBAAkB,MAAM;CAChD,WAAW,UAAU,kBAAkB,MAAM;CAC7C,WAAW,QAAQ,WAAW,MAAM;AACtC;;;;;AAMA,IAAa,8BAA8C,IAAI,IAAI;CACjE;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,SAAgB,YACd,OACA,MACA,UACQ;CACR,MAAM,QAAQ,gBAAgB,OAAO,MAAM,QAAQ;CACnD,OAAO,cAAc,cAAc,MAAM,KAAK,aAAa,KAAK,GAAG,KAAK;AAC1E;AAEA,SAAS,gBACP,OACA,MACA,UACA;CACA,IAAI,aAAa,KAAA,GACf,OAAO,YAAY,MAAM,KAAK,WAAgC;CAEhE,IAAI,KAAK,eAAe,OACtB,OAAO,YAAY,wBAAwB,SAAS;CAEtD,OAAO,cACL,MAAM,KAAK,aACX,wBAAwB,SAC1B;AACF"}
@@ -0,0 +1,225 @@
1
+ import { checkThemeContrast } from "./checkThemeContrast.js";
2
+ import { compositeOver, parseColour, toHex } from "./contrast.js";
3
+ import { surfaceBlurSupported, tokens } from "./tokens.styles.js";
4
+ import { colourRoleNames, themeValues } from "./tokenValues.js";
5
+ // src/createThemeStylesheet.ts
6
+ var themeNames = ["light", "dark"];
7
+ /** `:root`, `#id` or `.class`, with an ASCII name. Nothing else can be a scope. */
8
+ var SCOPE_PATTERN = /^(?::root|[#.][A-Za-z_][A-Za-z0-9_-]*)$/;
9
+ /**
10
+ * High-contrast and forced-colours users keep the SDK's own values, so every
11
+ * rule is written inside these conditions. A browser that does not know a
12
+ * feature treats the negated condition as false, and so does not apply the
13
+ * override either.
14
+ */
15
+ var HIGH_CONTRAST_GUARDS = ["(not (prefers-contrast: more))", "(not (forced-colors: active))"];
16
+ var REDUCED_TRANSPARENCY = "(prefers-reduced-transparency: reduce)";
17
+ var BLUR_UNSUPPORTED = `@supports not (${surfaceBlurSupported})`;
18
+ /** The surfaces that are translucent by default and so get an opaque form. */
19
+ var surfaceRoles = ["surface", "surfaceRaised"];
20
+ /**
21
+ * The four places the page's theme can come from. They never overlap, so a
22
+ * role set for one theme cannot show in the other: a declaration on the scope
23
+ * element would otherwise beat the SDK's own value however the theme was
24
+ * chosen.
25
+ */
26
+ var contexts = {
27
+ light: [{
28
+ rootState: "[data-theme=\"light\"]",
29
+ media: []
30
+ }, {
31
+ rootState: ":not([data-theme])",
32
+ media: ["(not (prefers-color-scheme: dark))"]
33
+ }],
34
+ dark: [{
35
+ rootState: "[data-theme=\"dark\"]",
36
+ media: []
37
+ }, {
38
+ rootState: ":not([data-theme])",
39
+ media: ["(prefers-color-scheme: dark)"]
40
+ }]
41
+ };
42
+ function readScope(options) {
43
+ try {
44
+ const { scope } = options;
45
+ return typeof scope === "string" && SCOPE_PATTERN.test(scope) ? scope : void 0;
46
+ } catch {
47
+ return;
48
+ }
49
+ }
50
+ /** The custom property behind a colour role, taken from the built contract. */
51
+ function propertyName(role) {
52
+ const reference = tokens.color[role];
53
+ const name = /^var\((--[\w-]+)\)$/.exec(reference)?.[1];
54
+ if (name === void 0) throw new Error(`Unexpected token reference: ${reference}`);
55
+ return name;
56
+ }
57
+ /** Writes every colour the host gave as `#rrggbb` or `#rrggbbaa`. */
58
+ function normalise(override) {
59
+ const sets = {
60
+ light: {},
61
+ dark: {}
62
+ };
63
+ for (const theme of themeNames) for (const [role, value] of Object.entries(override.colour?.[theme] ?? {})) if (value !== void 0) Object.assign(sets[theme], { [role]: toHex(parseColour(value)) });
64
+ return sets;
65
+ }
66
+ /** The colour flattened over the theme's page background, which a host cannot change. */
67
+ function flatten(theme, colour) {
68
+ return toHex(compositeOver(colour, themeValues[theme].colour.pageBackground));
69
+ }
70
+ /**
71
+ * Derives the opaque surfaces by flattening each translucent surface the host
72
+ * set over the page background, and defaults the inner focus ring to the
73
+ * opaque surface so the two-tone ring follows a changed surface.
74
+ */
75
+ function derive(theme, set) {
76
+ const opaque = {};
77
+ for (const role of surfaceRoles) {
78
+ const colour = set[role];
79
+ if (colour !== void 0) opaque[role] = flatten(theme, colour);
80
+ }
81
+ const colours = { ...set };
82
+ if (opaque.surface !== void 0 && set.focusRingInner === void 0) colours.focusRingInner = opaque.surface;
83
+ return {
84
+ colours,
85
+ opaque
86
+ };
87
+ }
88
+ function checkSets(sets) {
89
+ return checkThemeContrast({ colour: sets });
90
+ }
91
+ function declarationsOf(set) {
92
+ return colourRoleNames.flatMap((role) => {
93
+ const value = set[role];
94
+ return value === void 0 ? [] : [`${propertyName(role)}: ${value};`];
95
+ });
96
+ }
97
+ /** One rule, wrapped in the at-rules around it, each nested in the one before. */
98
+ function renderRule([outer, ...inner], selector, declarations) {
99
+ if (outer !== void 0) {
100
+ const body = renderRule(inner, selector, declarations).split("\n").map((line) => ` ${line}`);
101
+ return [
102
+ `${outer} {`,
103
+ ...body,
104
+ "}"
105
+ ].join("\n");
106
+ }
107
+ return [
108
+ `${selector} {`,
109
+ ...declarations.map((declaration) => ` ${declaration}`),
110
+ "}"
111
+ ].join("\n");
112
+ }
113
+ /**
114
+ * The selector for a context. The root scope is written twice over so it
115
+ * outranks the SDK's own rules on the same element whatever the link order.
116
+ */
117
+ function selectorFor(scope, context) {
118
+ return scope === ":root" ? `:root:root${context.rootState}` : `:root${context.rootState} ${scope}`;
119
+ }
120
+ function mediaRule(context, ...extra) {
121
+ return `@media ${[
122
+ ...context.media,
123
+ ...extra,
124
+ ...HIGH_CONTRAST_GUARDS
125
+ ].join(" and ")}`;
126
+ }
127
+ /** The rules for one theme: its colours, then its opaque surfaces where blur is off. */
128
+ function renderTheme(theme, scope, { colours, opaque }) {
129
+ const rules = [];
130
+ for (const context of contexts[theme]) {
131
+ const selector = selectorFor(scope, context);
132
+ const base = declarationsOf(colours);
133
+ const flat = declarationsOf(opaque);
134
+ if (base.length > 0) rules.push(renderRule([mediaRule(context)], selector, base));
135
+ if (flat.length > 0) rules.push(renderRule([mediaRule(context), BLUR_UNSUPPORTED], selector, flat), renderRule([mediaRule(context, REDUCED_TRANSPARENCY)], selector, flat));
136
+ }
137
+ return rules;
138
+ }
139
+ function refused(findings, invalid, invalidScope) {
140
+ return {
141
+ ok: false,
142
+ css: void 0,
143
+ findings,
144
+ invalid,
145
+ invalidScope
146
+ };
147
+ }
148
+ /**
149
+ * Generates the stylesheet that applies a colour override to the SDK's
150
+ * interface inside `options.scope`, or refuses.
151
+ *
152
+ * The host serves the result as a same-origin file, linked after the SDK's
153
+ * own stylesheet: it holds no inline style, needs no nonce and shows no flash
154
+ * under a strict policy. The names it writes are resolved from the built
155
+ * `tokens`, so they match the SDK's stylesheet only for the same installed
156
+ * version of this package, and the host never writes one.
157
+ *
158
+ * A theme below WCAG 2.2 AA is refused: the result carries the findings and
159
+ * no CSS, so a host fixes its colours first. The check measures the colours
160
+ * as written to the stylesheet, with the inner focus ring and the opaque
161
+ * surfaces derived. The opaque surface is the surface flattened over the
162
+ * theme's page background, used where `backdrop-filter` is not supported and
163
+ * under `prefers-reduced-transparency`. The page background, the map overlay
164
+ * roles and the data palette are not overridable.
165
+ *
166
+ * Every rule is written for `(not (prefers-contrast: more))` and
167
+ * `(not (forced-colors: active))`, so high-contrast and forced-colours users
168
+ * keep the SDK's own values. A colour is written back as `#rrggbb` or
169
+ * `#rrggbbaa`, parsed with the same strict reader as
170
+ * {@link checkThemeContrast}, so nothing else can enter the stylesheet.
171
+ *
172
+ * Total: it never throws. A tooltip renders in a portal outside the scope, so
173
+ * it keeps the SDK's colours in a `#id` or `.class` scope.
174
+ *
175
+ * @param override - The colours to change, per theme.
176
+ * @param options - The scope to apply them in.
177
+ * @returns The stylesheet and the findings, or the reasons it was refused.
178
+ */
179
+ function createThemeStylesheet(override, options) {
180
+ const scope = readScope(options);
181
+ try {
182
+ const initial = checkThemeContrast(override);
183
+ if (initial.invalid.length > 0 || scope === void 0) return refused(initial.findings, initial.invalid, scope === void 0);
184
+ return create(override, scope);
185
+ } catch {
186
+ return refused([], [{
187
+ theme: null,
188
+ role: "colour",
189
+ value: void 0,
190
+ reason: "unreadable"
191
+ }], scope === void 0);
192
+ }
193
+ }
194
+ function create(override, scope) {
195
+ const sets = normalise(override);
196
+ const derived = {
197
+ light: derive("light", sets.light),
198
+ dark: derive("dark", sets.dark)
199
+ };
200
+ const check = checkSets({
201
+ light: derived.light.colours,
202
+ dark: derived.dark.colours
203
+ });
204
+ const opaqueCheck = checkSets({
205
+ light: {
206
+ ...derived.light.colours,
207
+ ...derived.light.opaque
208
+ },
209
+ dark: {
210
+ ...derived.dark.colours,
211
+ ...derived.dark.opaque
212
+ }
213
+ });
214
+ const findings = [...check.findings, ...opaqueCheck.findings.filter((finding) => !finding.passes)];
215
+ if (!check.passes || !opaqueCheck.passes) return refused(findings, [...check.invalid, ...opaqueCheck.invalid], false);
216
+ const css = themeNames.flatMap((theme) => renderTheme(theme, scope, derived[theme])).join("\n");
217
+ return {
218
+ ok: true,
219
+ css: css === "" ? css : `${css}\n`,
220
+ findings
221
+ };
222
+ }
223
+ export { createThemeStylesheet };
224
+
225
+ //# sourceMappingURL=createThemeStylesheet.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createThemeStylesheet.js","names":[],"sources":["../src/createThemeStylesheet.ts"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-only\n// Copyright MapCairn contributors\nimport {\n type ContrastFinding,\n checkThemeContrast,\n type InvalidColour,\n type ThemeColours,\n type ThemeContrastCheck,\n type ThemeOverride,\n} from \"./checkThemeContrast\";\nimport { compositeOver, parseColour, toHex } from \"./contrast\";\nimport { surfaceBlurSupported, tokens } from \"./tokens.css\";\nimport { colourRoleNames, type ThemeName, themeValues } from \"./tokenValues\";\n\n/** Where a theme override applies. */\nexport interface ThemeStylesheetOptions {\n /**\n * The selector of the element that wraps the SDK's interface, written as\n * `:root`, `#id` or `.class` with an ASCII name. It must be an element the\n * host owns and puts around the map: the SDK adds no markup or attribute of\n * its own for this. The page's theme is read from `data-theme` on the root\n * element, which is where the SDK sets it, so a theme change reaches the\n * scope without any script.\n *\n * A `#id` or `.class` scope is matched as a descendant of `:root`, so a class\n * on `<html>` itself does nothing: use `:root` to theme the whole page.\n *\n * Two maps on one page take two scopes and two calls.\n */\n scope: string;\n}\n\n/** A theme override that was accepted: the stylesheet and what was measured. */\nexport interface ThemeStylesheetCreated {\n /** True: the override passed and `css` holds the stylesheet. */\n ok: true;\n /**\n * The stylesheet text, to serve as a same-origin file. It is empty when the\n * override sets no colour.\n */\n css: string;\n /**\n * One finding for each pair, theme and backdrop, measured on the colours\n * written to `css` with the surface as written (translucent). Every one\n * passes. The opaque surfaces written for reduced transparency are checked\n * as well, and a failure there refuses the theme, so no finding for them is\n * listed here.\n */\n findings: ContrastFinding[];\n}\n\n/** A theme override that was refused, with the reasons and no stylesheet. */\nexport interface ThemeStylesheetRefused {\n /** False: nothing was written. */\n ok: false;\n /** Always `undefined`: a refused theme produces no CSS. */\n css: undefined;\n /**\n * The pairs that could be measured, passing and failing. Where a colour\n * or the scope could not be used, the pairs that depend on a colour are\n * missing, as in {@link checkThemeContrast}.\n */\n findings: ContrastFinding[];\n /** The colours and keys that could not be used, and why. */\n invalid: InvalidColour[];\n /** True when `scope` is not `:root`, `#id` or `.class`, or could not be read. */\n invalidScope: boolean;\n}\n\n/** The result of {@link createThemeStylesheet}. */\nexport type ThemeStylesheet = ThemeStylesheetCreated | ThemeStylesheetRefused;\n\n/** A colour set for one theme, as the roles the host chose. */\ntype ColourSet = Partial<ThemeColours>;\n\nconst themeNames: readonly ThemeName[] = [\"light\", \"dark\"];\n\n/** `:root`, `#id` or `.class`, with an ASCII name. Nothing else can be a scope. */\nconst SCOPE_PATTERN = /^(?::root|[#.][A-Za-z_][A-Za-z0-9_-]*)$/;\n\n/**\n * High-contrast and forced-colours users keep the SDK's own values, so every\n * rule is written inside these conditions. A browser that does not know a\n * feature treats the negated condition as false, and so does not apply the\n * override either.\n */\nconst HIGH_CONTRAST_GUARDS = [\n \"(not (prefers-contrast: more))\",\n \"(not (forced-colors: active))\",\n];\n\nconst REDUCED_TRANSPARENCY = \"(prefers-reduced-transparency: reduce)\";\nconst BLUR_UNSUPPORTED = `@supports not (${surfaceBlurSupported})`;\n\n/** The surfaces that are translucent by default and so get an opaque form. */\nconst surfaceRoles = [\"surface\", \"surfaceRaised\"] as const;\n\n/** A place a theme applies: a selector on the root element and the media it needs. */\ninterface Context {\n /** The part of the selector that matches the root element. */\n rootState: string;\n /** Media conditions the context needs, ahead of the guards. */\n media: readonly string[];\n}\n\n/**\n * The four places the page's theme can come from. They never overlap, so a\n * role set for one theme cannot show in the other: a declaration on the scope\n * element would otherwise beat the SDK's own value however the theme was\n * chosen.\n */\nconst contexts: Record<ThemeName, readonly Context[]> = {\n light: [\n { rootState: '[data-theme=\"light\"]', media: [] },\n {\n rootState: \":not([data-theme])\",\n media: [\"(not (prefers-color-scheme: dark))\"],\n },\n ],\n dark: [\n { rootState: '[data-theme=\"dark\"]', media: [] },\n {\n rootState: \":not([data-theme])\",\n media: [\"(prefers-color-scheme: dark)\"],\n },\n ],\n};\n\nfunction readScope(options: ThemeStylesheetOptions): string | undefined {\n try {\n const { scope } = options;\n return typeof scope === \"string\" && SCOPE_PATTERN.test(scope)\n ? scope\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The custom property behind a colour role, taken from the built contract. */\nfunction propertyName(role: keyof ThemeColours): string {\n const reference = tokens.color[role];\n const name = /^var\\((--[\\w-]+)\\)$/.exec(reference)?.[1];\n if (name === undefined) {\n throw new Error(`Unexpected token reference: ${reference}`);\n }\n return name;\n}\n\n/** Writes every colour the host gave as `#rrggbb` or `#rrggbbaa`. */\nfunction normalise(override: ThemeOverride): Record<ThemeName, ColourSet> {\n const sets: Record<ThemeName, ColourSet> = { light: {}, dark: {} };\n for (const theme of themeNames) {\n for (const [role, value] of Object.entries(\n override.colour?.[theme] ?? {},\n )) {\n if (value !== undefined) {\n Object.assign(sets[theme], { [role]: toHex(parseColour(value)) });\n }\n }\n }\n return sets;\n}\n\n/** The colour flattened over the theme's page background, which a host cannot change. */\nfunction flatten(theme: ThemeName, colour: string): string {\n return toHex(compositeOver(colour, themeValues[theme].colour.pageBackground));\n}\n\n/** What one theme writes: the colours, and the opaque surfaces for where blur is off. */\ninterface ThemeColourSets {\n colours: ColourSet;\n opaque: ColourSet;\n}\n\n/**\n * Derives the opaque surfaces by flattening each translucent surface the host\n * set over the page background, and defaults the inner focus ring to the\n * opaque surface so the two-tone ring follows a changed surface.\n */\nfunction derive(theme: ThemeName, set: ColourSet): ThemeColourSets {\n const opaque: ColourSet = {};\n for (const role of surfaceRoles) {\n const colour = set[role];\n if (colour !== undefined) {\n opaque[role] = flatten(theme, colour);\n }\n }\n const colours = { ...set };\n if (opaque.surface !== undefined && set.focusRingInner === undefined) {\n colours.focusRingInner = opaque.surface;\n }\n return { colours, opaque };\n}\n\nfunction checkSets(sets: Record<ThemeName, ColourSet>): ThemeContrastCheck {\n return checkThemeContrast({ colour: sets });\n}\n\nfunction declarationsOf(set: ColourSet): string[] {\n return colourRoleNames.flatMap((role) => {\n const value = (set as Partial<Record<string, string>>)[role];\n return value === undefined\n ? []\n : [`${propertyName(role as keyof ThemeColours)}: ${value};`];\n });\n}\n\n/** One rule, wrapped in the at-rules around it, each nested in the one before. */\nfunction renderRule(\n [outer, ...inner]: readonly string[],\n selector: string,\n declarations: readonly string[],\n): string {\n if (outer !== undefined) {\n const body = renderRule(inner, selector, declarations)\n .split(\"\\n\")\n .map((line) => ` ${line}`);\n return [`${outer} {`, ...body, \"}\"].join(\"\\n\");\n }\n return [\n `${selector} {`,\n ...declarations.map((declaration) => ` ${declaration}`),\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * The selector for a context. The root scope is written twice over so it\n * outranks the SDK's own rules on the same element whatever the link order.\n */\nfunction selectorFor(scope: string, context: Context): string {\n return scope === \":root\"\n ? `:root:root${context.rootState}`\n : `:root${context.rootState} ${scope}`;\n}\n\nfunction mediaRule(context: Context, ...extra: string[]): string {\n return `@media ${[...context.media, ...extra, ...HIGH_CONTRAST_GUARDS].join(\" and \")}`;\n}\n\n/** The rules for one theme: its colours, then its opaque surfaces where blur is off. */\nfunction renderTheme(\n theme: ThemeName,\n scope: string,\n { colours, opaque }: ThemeColourSets,\n): string[] {\n const rules: string[] = [];\n for (const context of contexts[theme]) {\n const selector = selectorFor(scope, context);\n const base = declarationsOf(colours);\n const flat = declarationsOf(opaque);\n if (base.length > 0) {\n rules.push(renderRule([mediaRule(context)], selector, base));\n }\n if (flat.length > 0) {\n rules.push(\n renderRule([mediaRule(context), BLUR_UNSUPPORTED], selector, flat),\n renderRule([mediaRule(context, REDUCED_TRANSPARENCY)], selector, flat),\n );\n }\n }\n return rules;\n}\n\nfunction refused(\n findings: ContrastFinding[],\n invalid: InvalidColour[],\n invalidScope: boolean,\n): ThemeStylesheetRefused {\n return { ok: false, css: undefined, findings, invalid, invalidScope };\n}\n\n/**\n * Generates the stylesheet that applies a colour override to the SDK's\n * interface inside `options.scope`, or refuses.\n *\n * The host serves the result as a same-origin file, linked after the SDK's\n * own stylesheet: it holds no inline style, needs no nonce and shows no flash\n * under a strict policy. The names it writes are resolved from the built\n * `tokens`, so they match the SDK's stylesheet only for the same installed\n * version of this package, and the host never writes one.\n *\n * A theme below WCAG 2.2 AA is refused: the result carries the findings and\n * no CSS, so a host fixes its colours first. The check measures the colours\n * as written to the stylesheet, with the inner focus ring and the opaque\n * surfaces derived. The opaque surface is the surface flattened over the\n * theme's page background, used where `backdrop-filter` is not supported and\n * under `prefers-reduced-transparency`. The page background, the map overlay\n * roles and the data palette are not overridable.\n *\n * Every rule is written for `(not (prefers-contrast: more))` and\n * `(not (forced-colors: active))`, so high-contrast and forced-colours users\n * keep the SDK's own values. A colour is written back as `#rrggbb` or\n * `#rrggbbaa`, parsed with the same strict reader as\n * {@link checkThemeContrast}, so nothing else can enter the stylesheet.\n *\n * Total: it never throws. A tooltip renders in a portal outside the scope, so\n * it keeps the SDK's colours in a `#id` or `.class` scope.\n *\n * @param override - The colours to change, per theme.\n * @param options - The scope to apply them in.\n * @returns The stylesheet and the findings, or the reasons it was refused.\n */\nexport function createThemeStylesheet(\n override: ThemeOverride,\n options: ThemeStylesheetOptions,\n): ThemeStylesheet {\n const scope = readScope(options);\n try {\n const initial = checkThemeContrast(override);\n if (initial.invalid.length > 0 || scope === undefined) {\n return refused(initial.findings, initial.invalid, scope === undefined);\n }\n return create(override, scope);\n } catch {\n return refused(\n [],\n [{ theme: null, role: \"colour\", value: undefined, reason: \"unreadable\" }],\n scope === undefined,\n );\n }\n}\n\nfunction create(override: ThemeOverride, scope: string): ThemeStylesheet {\n const sets = normalise(override);\n const derived = {\n light: derive(\"light\", sets.light),\n dark: derive(\"dark\", sets.dark),\n };\n const check = checkSets({\n light: derived.light.colours,\n dark: derived.dark.colours,\n });\n const opaqueCheck = checkSets({\n light: { ...derived.light.colours, ...derived.light.opaque },\n dark: { ...derived.dark.colours, ...derived.dark.opaque },\n });\n const findings = [\n ...check.findings,\n ...opaqueCheck.findings.filter((finding) => !finding.passes),\n ];\n if (!check.passes || !opaqueCheck.passes) {\n return refused(findings, [...check.invalid, ...opaqueCheck.invalid], false);\n }\n const css = themeNames\n .flatMap((theme) => renderTheme(theme, scope, derived[theme]))\n .join(\"\\n\");\n return { ok: true, css: css === \"\" ? css : `${css}\\n`, findings };\n}\n"],"mappings":";;;;;AA2EA,IAAM,aAAmC,CAAC,SAAS,MAAM;;AAGzD,IAAM,gBAAgB;;;;;;;AAQtB,IAAM,uBAAuB,CAC3B,kCACA,+BACF;AAEA,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB,kBAAkB,qBAAqB;;AAGhE,IAAM,eAAe,CAAC,WAAW,eAAe;;;;;;;AAgBhD,IAAM,WAAkD;CACtD,OAAO,CACL;EAAE,WAAW;EAAwB,OAAO,CAAC;CAAE,GAC/C;EACE,WAAW;EACX,OAAO,CAAC,oCAAoC;CAC9C,CACF;CACA,MAAM,CACJ;EAAE,WAAW;EAAuB,OAAO,CAAC;CAAE,GAC9C;EACE,WAAW;EACX,OAAO,CAAC,8BAA8B;CACxC,CACF;AACF;AAEA,SAAS,UAAU,SAAqD;CACtE,IAAI;EACF,MAAM,EAAE,UAAU;EAClB,OAAO,OAAO,UAAU,YAAY,cAAc,KAAK,KAAK,IACxD,QACA,KAAA;CACN,QAAQ;EACN;CACF;AACF;;AAGA,SAAS,aAAa,MAAkC;CACtD,MAAM,YAAY,OAAO,MAAM;CAC/B,MAAM,OAAO,sBAAsB,KAAK,SAAS,CAAC,GAAG;CACrD,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,MAAM,+BAA+B,WAAW;CAE5D,OAAO;AACT;;AAGA,SAAS,UAAU,UAAuD;CACxE,MAAM,OAAqC;EAAE,OAAO,CAAC;EAAG,MAAM,CAAC;CAAE;CACjE,KAAK,MAAM,SAAS,YAClB,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QACjC,SAAS,SAAS,UAAU,CAAC,CAC/B,GACE,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,MAAM,YAAY,KAAK,CAAC,EAAE,CAAC;CAItE,OAAO;AACT;;AAGA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