@jskit-ai/material-web 0.1.9 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - An app's start reuses the Material 3 colours an earlier start computed for the same theme. `materialThemes` (which `createMaterialVuetifyOptions` calls at every start) computed both schemes at every call: 30 ms in Chromium, 120 ms at 4x CPU slowdown, for a seed and two app colours (medians). The colours are now computed once per input, the seed (in any case) and the app's colours with their order and `blend`: a page or process reuses them, and a browser keeps the last four inputs' colours in `localStorage` (`jskit:material-themes`), so a later start takes 1.4 ms (6.6 ms at 4x). Computing them is quicker too, 23 ms (84 ms at 4x): it built three tonal-spot schemes where two are needed, one only to list the role names, and ran `customColor` once per scheme where one call gives both. The colours are the same, byte for byte (one sha256 of three inputs' light and dark themes before and after). A changed seed or colour is another input and is computed again. Stored colours that are not a complete set of hex roles, the scheme's and the input's app colours', or were stored under an earlier revision of the generator (`THEMES_REVISION` in `colorSchemes.js`, raised whenever the same input gives other colours) are computed again, and a browser that refuses storage computes them at each start, as a server does. materialWeb.test.js holds each revision's digest of the colours and fails when they change without a new revision. Measured with Chromium and Node 26 on a 20-thread test host under load, Vibe64's theme input; a seed alone went from 34 to 22 ms on a first visit and 27 to 1.3 ms on a later start.
6
+
5
7
  - A radio group's own label and a checkbox's, radio's or switch's description are `on-surface-variant` at full strength, as a text field's label and supporting text are, instead of `on-surface` at Vuetify's medium-emphasis opacity: a group's label measured 4.19:1 in a dialog's `surface-container-high`, under WCAG's 4.5:1 (axe `color-contrast`). A control's own label was already `on-surface` at full strength, and a disabled group or control keeps its fade. `accessibility.browser.test.js` measures them in light and dark.
6
8
  - A hidden tooltip is hidden whole: `material.css` hides a `v-tooltip` overlay while its text is hidden. Vuetify 4.3 mounts a tooltip before it first shows (`eager`), and hidden it was a `role="tooltip"` element whose text alone was hidden, an empty tooltip to assistive technology (axe `aria-tooltip-name`, WCAG 4.1.2), and its activator's `aria-describedby` read nothing, since hidden text counts only when the element named is hidden itself. Now no tooltip without a name is in the accessibility tree, and the activator is described by the tooltip's text whether it shows or not; a showing or fading tooltip is untouched. The shell's menu control, Up button and icon page actions all carry one.
7
9
  - A card's subtitle is at full strength, as a list item's already was: `on-surface-variant`, Material 3's supporting text, on a surface card (JSKIT's default `surface-container-low` card included) or one without a colour, and the card's own text colour on a coloured card or one with a text colour class; a text colour class on the subtitle still wins. At Vuetify's medium-emphasis opacity it measured 4.35:1 on the default card, under WCAG 1.4.3's 4.5:1 (axe `color-contrast`).
package/README.md CHANGED
@@ -49,7 +49,15 @@ export const theme = {
49
49
  instead (a skeleton loader's bones, a linear progress indicator's track, a
50
50
  pagination's current page). There is no
51
51
  hand-picked colour and no generator command: change the seed and both schemes
52
- follow.
52
+ follow. The schemes are computed once per theme input, the seed (in any
53
+ case) and the app's colours with their order and `blend`: a page or process
54
+ reuses the ones it has, and a browser keeps the last four inputs' schemes in
55
+ `localStorage` (`jskit:material-themes`), so its next start computes none. A
56
+ changed seed or colour is another input and is computed again. Stored
57
+ schemes that are not complete sets of hex roles, or were stored under an
58
+ earlier revision of the generator (`THEMES_REVISION` in `colorSchemes.js`,
59
+ raised whenever the same input gives other colours), are computed again, and
60
+ a browser that refuses storage computes them at each start, as a server does.
53
61
  - **Icons.** Every Vuetify alias and JSKIT's own aliases are Material Symbols
54
62
  Rounded glyphs (outlined, Material Symbols' default; `$<name>Filled` for the
55
63
  active navigation item). JSKIT names are the symbol in camelCase: `$arrowBack`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/material-web",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "type": "module",
5
5
  "description": "Exact Material 3 for JSKIT Vuetify apps: seed-generated light and dark schemes, Material Symbols Rounded icon aliases, Roboto Flex and Material 3 component defaults.",
6
6
  "exports": {
@@ -110,6 +110,33 @@ const SURFACE_TONES = Object.freeze([
110
110
  "surface-light"
111
111
  ]);
112
112
 
113
+ // Vuetify-only names, each the Material 3 role it takes.
114
+ const VUETIFY_ROLE_NAMES = Object.freeze({
115
+ // Vuetify paints fields, alerts, toolbars and timelines with surface-light; Material 3 uses the highest container.
116
+ "surface-light": "surface-container-highest",
117
+ // Content on every surface tone is on-surface in Material 3; Vuetify would otherwise pick black or white for a
118
+ // bg-surface-container-* or bg-surface-dim/bright element.
119
+ ...Object.fromEntries(SURFACE_TONES.map((surface) => [`on-${surface}`, "on-surface"])),
120
+ "primary-darken-1": "on-primary-container",
121
+ "secondary-darken-1": "on-secondary-container"
122
+ });
123
+
124
+ /**
125
+ * The revision of the colours a theme input gives. A browser keeps the colours it computed for an input under this
126
+ * revision and its later starts reuse them, so bump it whenever the same input gives other colours (a role added or
127
+ * remapped, a status colour moved, another Material Color Utilities): every browser then computes them again.
128
+ * materialWeb.test.js holds the colours of each revision, read from what a browser stores, and fails when they change
129
+ * without it.
130
+ */
131
+ const THEMES_REVISION = 1;
132
+ // The browser storage item that keeps the colours of the inputs computed last, newest first.
133
+ const STORAGE_ITEM = "jskit:material-themes";
134
+ const STORED_INPUTS = 4;
135
+ // How many inputs' colours one page or process keeps, for an app that calls with many (a seed picker, say).
136
+ const REMEMBERED_INPUTS = 16;
137
+ const HEX = /^#[0-9a-f]{6}$/u;
138
+ const ROLE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;
139
+
113
140
  function kebabCase(name) {
114
141
  return name.replace(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);
115
142
  }
@@ -128,75 +155,167 @@ function customColorRoleNames(name) {
128
155
  return [role, `on-${role}`, `${role}-container`, `on-${role}-container`];
129
156
  }
130
157
 
158
+ // Every role a scheme has before the app's own colours: an app colour may not take one of their names.
159
+ const SCHEME_ROLE_NAMES = new Set([
160
+ ...ROLE_NAMES.map(kebabCase),
161
+ ...Object.keys(STATUS_COLOR_HCT).flatMap(customColorRoleNames),
162
+ ...Object.keys(VUETIFY_ROLE_NAMES)
163
+ ]);
164
+
131
165
  /**
132
- * Adds a colour's four roles, from customColor: harmonized toward the seed unless `blend` is false, as Material Theme
133
- * Builder's per-colour Blend toggle does.
134
- * @param {Record<string, number>} roles
166
+ * Adds a colour's four roles to the light and the dark scheme, from one customColor (which gives both): harmonized
167
+ * toward the seed unless `blend` is false, as Material Theme Builder's per-colour Blend toggle does.
168
+ * @param {{ light: Record<string, number>, dark: Record<string, number> }} schemes
135
169
  * @param {number} seedArgb
136
- * @param {boolean} dark
137
170
  * @param {string} name
138
171
  * @param {number} argb
139
172
  * @param {boolean} [blend]
140
173
  */
141
- function addCustomColorRoles(roles, seedArgb, dark, name, argb, blend = true) {
174
+ function addCustomColorRoles(schemes, seedArgb, name, argb, blend = true) {
142
175
  const custom = customColor(seedArgb, { name, value: argb, blend });
143
- const tones = dark ? custom.dark : custom.light;
144
176
  const [role, onRole, containerRole, onContainerRole] = customColorRoleNames(name);
145
- roles[role] = tones.color;
146
- roles[onRole] = tones.onColor;
147
- roles[containerRole] = tones.colorContainer;
148
- roles[onContainerRole] = tones.onColorContainer;
177
+ for (const [roles, tones] of [[schemes.light, custom.light], [schemes.dark, custom.dark]]) {
178
+ roles[role] = tones.color;
179
+ roles[onRole] = tones.onColor;
180
+ roles[containerRole] = tones.colorContainer;
181
+ roles[onContainerRole] = tones.onColorContainer;
182
+ }
149
183
  }
150
184
 
151
185
  /**
152
- * One scheme's colours: every Material 3 role in kebab-case, the status colours and the app's own colours with their
153
- * containers, and the Vuetify-only names mapped onto Material 3 roles.
154
- * @param {SchemeTonalSpot} scheme
186
+ * Every Material 3 role of one scheme in kebab-case.
155
187
  * @param {number} seedArgb
156
188
  * @param {boolean} dark
189
+ */
190
+ function materialRoles(seedArgb, dark) {
191
+ const scheme = new SchemeTonalSpot(Hct.fromInt(seedArgb), dark, 0);
192
+ return Object.fromEntries(ROLE_NAMES.map((name) => [kebabCase(name), MaterialDynamicColors[name].getArgb(scheme)]));
193
+ }
194
+
195
+ /**
196
+ * Both schemes' colours as hex: every Material 3 role in kebab-case, the status colours and the app's own colours
197
+ * with their containers, and the Vuetify-only names mapped onto Material 3 roles. This is the Material Color
198
+ * Utilities work; each scheme and each custom colour is computed once.
199
+ * @param {number} seedArgb
157
200
  * @param {Array<[string, number, boolean]>} appColors
201
+ * @returns {{ light: Record<string, string>, dark: Record<string, string> }}
158
202
  */
159
- function schemeColors(scheme, seedArgb, dark, appColors) {
160
- const roles = {};
161
- for (const name of ROLE_NAMES) {
162
- roles[kebabCase(name)] = MaterialDynamicColors[name].getArgb(scheme);
163
- }
203
+ function computeSchemeColors(seedArgb, appColors) {
204
+ const schemes = { light: materialRoles(seedArgb, false), dark: materialRoles(seedArgb, true) };
164
205
  for (const [name, { hue, chroma, tone }] of Object.entries(STATUS_COLOR_HCT)) {
165
- addCustomColorRoles(roles, seedArgb, dark, name, Hct.from(hue, chroma, tone).toInt());
206
+ addCustomColorRoles(schemes, seedArgb, name, Hct.from(hue, chroma, tone).toInt());
166
207
  }
167
- // Vuetify paints fields, alerts, toolbars and timelines with surface-light; Material 3 uses the highest container.
168
- roles["surface-light"] = roles["surface-container-highest"];
169
- // Content on every surface tone is on-surface in Material 3; Vuetify would otherwise pick black or white for a
170
- // bg-surface-container-* or bg-surface-dim/bright element.
171
- for (const surface of SURFACE_TONES) {
172
- roles[`on-${surface}`] = roles["on-surface"];
208
+ for (const roles of Object.values(schemes)) {
209
+ for (const [name, role] of Object.entries(VUETIFY_ROLE_NAMES)) {
210
+ roles[name] = roles[role];
211
+ }
173
212
  }
174
- roles["primary-darken-1"] = roles["on-primary-container"];
175
- roles["secondary-darken-1"] = roles["on-secondary-container"];
176
213
  for (const [name, argb, blend] of appColors) {
177
- addCustomColorRoles(roles, seedArgb, dark, name, argb, blend);
214
+ addCustomColorRoles(schemes, seedArgb, name, argb, blend);
215
+ }
216
+ const hex = (roles) => Object.fromEntries(Object.entries(roles).map(([name, value]) => [name, hexFromArgb(value)]));
217
+ return { light: hex(schemes.light), dark: hex(schemes.dark) };
218
+ }
219
+
220
+ /** A scheme's colours as a page reads them back from storage: kebab-case names, hex values and every scheme role. */
221
+ function storedColorsAreUsable(colors) {
222
+ return Boolean(
223
+ colors && typeof colors === "object" && !Array.isArray(colors) &&
224
+ Object.entries(colors).every(([name, value]) => ROLE_NAME.test(name) && HEX.test(value)) &&
225
+ [...SCHEME_ROLE_NAMES].every((name) => HEX.test(colors[name]))
226
+ );
227
+ }
228
+
229
+ /** This page's storage when it runs in a browser and may use it; null on a server or when the browser refuses it. */
230
+ function browserStorage() {
231
+ try {
232
+ return typeof window === "object" && window?.localStorage ? window.localStorage : null;
233
+ } catch {
234
+ return null;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * The inputs' colours earlier starts stored, newest first, as `[input, { light, dark }]`: none when storage holds
240
+ * another revision's, cannot be read or is not what this module wrote.
241
+ * @param {Storage} storage
242
+ */
243
+ function storedSchemeColors(storage) {
244
+ try {
245
+ const stored = JSON.parse(storage.getItem(STORAGE_ITEM) || "null");
246
+ if (stored?.revision !== THEMES_REVISION || !Array.isArray(stored.inputs)) {
247
+ return [];
248
+ }
249
+ return stored.inputs
250
+ .filter((entry) => typeof entry?.input === "string" && storedColorsAreUsable(entry.light) &&
251
+ storedColorsAreUsable(entry.dark))
252
+ .slice(0, STORED_INPUTS)
253
+ .map(({ input, light, dark }) => [input, { light, dark }]);
254
+ } catch {
255
+ return [];
256
+ }
257
+ }
258
+
259
+ // The colours this page or process has, by input, oldest first: a memo of computed and stored colours.
260
+ const rememberedSchemeColors = new Map();
261
+
262
+ function remember(input, colors) {
263
+ rememberedSchemeColors.delete(input);
264
+ rememberedSchemeColors.set(input, colors);
265
+ for (const oldest of [...rememberedSchemeColors.keys()].slice(0, -REMEMBERED_INPUTS)) {
266
+ rememberedSchemeColors.delete(oldest);
178
267
  }
179
- return roles;
180
268
  }
181
269
 
182
270
  /**
183
- * One Vuetify theme from one Material 3 scheme.
271
+ * The colours of one theme input: the ones this page or process has, or an earlier start in this browser stored,
272
+ * and otherwise computed once and stored for the next start. A changed seed or colour is another input.
273
+ * @param {string} input
184
274
  * @param {number} seedArgb
185
- * @param {boolean} dark
186
275
  * @param {Array<[string, number, boolean]>} appColors
187
276
  */
188
- function vuetifyTheme(seedArgb, dark, appColors) {
189
- const scheme = new SchemeTonalSpot(Hct.fromInt(seedArgb), dark, 0);
190
- const roles = schemeColors(scheme, seedArgb, dark, appColors);
191
- const colors = Object.fromEntries(Object.entries(roles).map(([name, argb]) => [name, hexFromArgb(argb)]));
277
+ function schemeColors(input, seedArgb, appColors) {
278
+ const remembered = rememberedSchemeColors.get(input);
279
+ if (remembered) {
280
+ return remembered;
281
+ }
282
+ const storage = browserStorage();
283
+ const stored = storage ? storedSchemeColors(storage) : [];
284
+ // The stored colours of this input, when they also hold every role of the app's own colours.
285
+ const appRoles = appColors.flatMap(([name]) => customColorRoleNames(name));
286
+ const reused = stored.find(([storedInput, { light, dark }]) => storedInput === input &&
287
+ appRoles.every((role) => HEX.test(light[role]) && HEX.test(dark[role])))?.[1];
288
+ const colors = reused || computeSchemeColors(seedArgb, appColors);
289
+ remember(input, colors);
290
+ if (storage && !reused) {
291
+ try {
292
+ storage.setItem(STORAGE_ITEM, JSON.stringify({
293
+ revision: THEMES_REVISION,
294
+ inputs: [[input, colors], ...stored.filter(([storedInput]) => storedInput !== input)].slice(0, STORED_INPUTS)
295
+ .map(([storedInput, { light, dark }]) => ({ input: storedInput, light, dark }))
296
+ }));
297
+ } catch {
298
+ // Full or refused storage: the next start computes the colours again.
299
+ }
300
+ }
301
+ return colors;
302
+ }
303
+
304
+ /**
305
+ * One Vuetify theme from one scheme's colours, its own objects each time.
306
+ * @param {Record<string, string>} schemeColorsByRole
307
+ * @param {boolean} dark
308
+ */
309
+ function vuetifyTheme(schemeColorsByRole, dark) {
310
+ const colors = { ...schemeColorsByRole };
192
311
  return {
193
312
  dark,
194
313
  colors,
195
314
  variables: {
196
315
  ...STATE_LAYER_VARIABLES,
197
316
  // Channel strings: Vuetify writes them as rgba(var(--v-border-color), var(--v-border-opacity)).
198
- "border-color": channels(roles["outline-variant"]),
199
- "shadow-color": channels(roles.shadow),
317
+ "border-color": channels(argbFromHex(colors["outline-variant"])),
318
+ "shadow-color": channels(argbFromHex(colors.shadow)),
200
319
  "theme-kbd": colors["surface-container-highest"],
201
320
  "theme-on-kbd": colors["on-surface"],
202
321
  "theme-code": colors["surface-container"],
@@ -213,15 +332,14 @@ function vuetifyTheme(seedArgb, dark, appColors) {
213
332
  * scheme roles, and each a six-digit hex value (harmonized toward the seed) or `{ value, blend }`, where
214
333
  * `blend: false` keeps the colour's own hue.
215
334
  * @param {Record<string, string | { value: string, blend?: boolean }>} colors
216
- * @param {Set<string>} schemeRoles
217
335
  * @returns {Array<[string, number, boolean]>}
218
336
  */
219
- function normalizeAppColors(colors, schemeRoles) {
337
+ function normalizeAppColors(colors) {
220
338
  return Object.entries(colors).map(([name, value]) => {
221
339
  if (!/^[a-z][A-Za-z0-9]*$/u.test(name)) {
222
340
  throw new TypeError(`Theme colour "${name}" needs a camelCase name, such as "partner" or "brandAccent".`);
223
341
  }
224
- const clash = customColorRoleNames(name).find((role) => schemeRoles.has(role));
342
+ const clash = customColorRoleNames(name).find((role) => SCHEME_ROLE_NAMES.has(role));
225
343
  if (clash) {
226
344
  throw new TypeError(`Theme colour "${name}" would replace the scheme's "${clash}" role; choose another name.`);
227
345
  }
@@ -243,7 +361,9 @@ function normalizeAppColors(colors, schemeRoles) {
243
361
  * (SchemeTonalSpot, the Material 3 default), as Vuetify themes named light and dark. Each of the app's own colours
244
362
  * adds four roles in both schemes, harmonized toward the seed as Material Theme Builder's custom colours are:
245
363
  * `partner: "#0A7D3E"` gives partner, on-partner, partner-container and on-partner-container. A brand or partner
246
- * colour that must keep its hue is `{ value: "#F5C518", blend: false }`, Theme Builder's Blend switched off.
364
+ * colour that must keep its hue is `{ value: "#F5C518", blend: false }`, Theme Builder's Blend switched off. The colours
365
+ * of one input are computed once: a page or process reuses them, and a browser keeps the last few inputs' colours for
366
+ * its later starts (see THEMES_REVISION); a changed seed or colour computes them again.
247
367
  * @param {string} seed A hex colour such as "#6750A4".
248
368
  * @param {Record<string, string | { value: string, blend?: boolean }>} [colors] The app's own colours by camelCase
249
369
  * name: hex colours, or `{ value, blend }`.
@@ -253,12 +373,12 @@ function materialThemes(seed, colors = {}) {
253
373
  if (!/^#[0-9a-f]{6}$/iu.test(normalizedSeed)) {
254
374
  throw new TypeError(`The Material theme seed must be a six-digit hex colour, not "${normalizedSeed}".`);
255
375
  }
256
- const seedArgb = argbFromHex(normalizedSeed);
257
- const schemeRoles = new Set(Object.keys(vuetifyTheme(seedArgb, false, []).colors));
258
- const appColors = normalizeAppColors(colors, schemeRoles);
376
+ const appColors = normalizeAppColors(colors);
377
+ const input = JSON.stringify([normalizedSeed.toLowerCase(), appColors]);
378
+ const { light, dark } = schemeColors(input, argbFromHex(normalizedSeed), appColors);
259
379
  return {
260
- light: vuetifyTheme(seedArgb, false, appColors),
261
- dark: vuetifyTheme(seedArgb, true, appColors)
380
+ light: vuetifyTheme(light, false),
381
+ dark: vuetifyTheme(dark, true)
262
382
  };
263
383
  }
264
384
 
@@ -1,4 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
+ import { createHash } from "node:crypto";
2
3
  import { readFile } from "node:fs/promises";
3
4
  import { createRequire } from "node:module";
4
5
  import path from "node:path";
@@ -122,6 +123,141 @@ test("theme variables carry Material 3 state layers and channel strings for bord
122
123
  assert.equal(light.variables["border-color"], "202, 196, 207");
123
124
  });
124
125
 
126
+ // A browser's localStorage for one origin; `refuse` makes it throw as blocked or full storage does.
127
+ function browserStorage({ refuse = false } = {}) {
128
+ const items = new Map();
129
+ const check = () => {
130
+ if (refuse) throw new Error("SecurityError: storage is disabled");
131
+ };
132
+ return {
133
+ items,
134
+ getItem(key) { check(); return items.has(key) ? items.get(key) : null; },
135
+ setItem(key, value) { check(); items.set(key, String(value)); },
136
+ removeItem(key) { check(); items.delete(key); }
137
+ };
138
+ }
139
+
140
+ let pageStarts = 0;
141
+ /** One app start in a browser that has `storage`: colorSchemes.js loads afresh, as on every page load. */
142
+ async function browserStart(t, storage) {
143
+ globalThis.window = { localStorage: storage };
144
+ t.after(() => delete globalThis.window);
145
+ pageStarts += 1;
146
+ return import(`../src/client/colorSchemes.js?start=${pageStarts}`);
147
+ }
148
+
149
+ const VIBE64_INPUT = ["#1867C0", { learning: { value: "#F5C518", blend: false }, subsystem: { value: "#367E70", blend: false } }];
150
+
151
+ test("a later start reuses the colours an earlier start computed for the same theme, without computing them", async (t) => {
152
+ const storage = browserStorage();
153
+ const first = (await browserStart(t, storage)).materialThemes(...VIBE64_INPUT);
154
+ assert.deepEqual(first, materialThemes(...VIBE64_INPUT));
155
+ assert.equal(storage.items.size, 1, "the first start keeps its colours for the next");
156
+ const [[item, stored]] = storage.items;
157
+ // Changed where the first start stored it, a colour the next start shows is the stored one: it was not computed.
158
+ storage.setItem(item, stored.replaceAll(`"${first.light.colors.primary}"`, '"#010203"'));
159
+ const later = await browserStart(t, storage);
160
+ const reused = later.materialThemes(...VIBE64_INPUT);
161
+ assert.equal(reused.light.colors.primary, "#010203");
162
+ assert.deepEqual(reused.dark.colors.learning, first.dark.colors.learning);
163
+ assert.equal(reused.light.variables["border-color"], first.light.variables["border-color"]);
164
+ // Each call has its own objects, so an app that changes a theme changes only its own.
165
+ reused.light.colors.primary = "#ffffff";
166
+ reused.light.variables["hover-opacity"] = 1;
167
+ const again = later.materialThemes(...VIBE64_INPUT);
168
+ assert.equal(again.light.colors.primary, "#010203");
169
+ assert.equal(again.light.variables["hover-opacity"], 0.08);
170
+ });
171
+
172
+ test("a changed seed or colour computes the theme again and keeps the last four inputs", async (t) => {
173
+ const storage = browserStorage();
174
+ (await browserStart(t, storage)).materialThemes(...VIBE64_INPUT);
175
+ const [[item, stored]] = storage.items;
176
+ // The light scheme's primary, the first one stored.
177
+ storage.setItem(item, stored.replace(/"primary":"#[0-9a-f]{6}"/u, '"primary":"#010203"'));
178
+ const start = await browserStart(t, storage);
179
+ // The seed's case is not another input: the stored colours are reused for it.
180
+ assert.equal(start.materialThemes("#1867c0", VIBE64_INPUT[1]).light.colors.primary, "#010203");
181
+ const inputs = [
182
+ ["#B3261E", VIBE64_INPUT[1]],
183
+ ["#1867C0", { ...VIBE64_INPUT[1], learning: { value: "#F5C518", blend: true } }],
184
+ ["#1867c0", { subsystem: VIBE64_INPUT[1].subsystem, learning: VIBE64_INPUT[1].learning }],
185
+ ["#6750A4"]
186
+ ];
187
+ for (const input of inputs) {
188
+ assert.deepEqual(start.materialThemes(...input), materialThemes(...input), JSON.stringify(input));
189
+ }
190
+ const kept = JSON.parse(storage.getItem(item));
191
+ assert.equal(kept.inputs.length, 4);
192
+ const next = await browserStart(t, storage);
193
+ for (const input of inputs) {
194
+ assert.deepEqual(next.materialThemes(...input), materialThemes(...input), JSON.stringify(input));
195
+ }
196
+ // The oldest input fell out of storage, so the next start computes it again.
197
+ assert.deepEqual(next.materialThemes(...VIBE64_INPUT), materialThemes(...VIBE64_INPUT));
198
+ });
199
+
200
+ test("colours stored under another revision, or that are not a scheme's, are computed again", async (t) => {
201
+ const computed = materialThemes(...VIBE64_INPUT);
202
+ const tampered = (change) => {
203
+ const storage = browserStorage();
204
+ return browserStart(t, storage).then(({ materialThemes: themes }) => {
205
+ themes(...VIBE64_INPUT);
206
+ const [[item, stored]] = storage.items;
207
+ storage.setItem(item, JSON.stringify(change(JSON.parse(stored))));
208
+ return storage;
209
+ });
210
+ };
211
+ const cases = {
212
+ "an older revision": (stored) => ({ ...stored, revision: stored.revision - 1, inputs: stored.inputs.map((entry) => ({ ...entry, light: { ...entry.light, primary: "#010203" } })) }),
213
+ "a value that is not a hex colour": (stored) => ({ ...stored, inputs: stored.inputs.map((entry) => ({ ...entry, light: { ...entry.light, primary: "red; } body { display: none" } })) }),
214
+ "a role name that is not one": (stored) => ({ ...stored, inputs: stored.inputs.map((entry) => ({ ...entry, light: { ...entry.light, "x} body {": "#010203" } })) }),
215
+ "a missing role": (stored) => ({
216
+ ...stored,
217
+ inputs: stored.inputs.map((entry) => ({ ...entry, light: Object.fromEntries(Object.entries(entry.light).filter(([role]) => role !== "primary")) }))
218
+ }),
219
+ "a missing role of an app colour": (stored) => ({
220
+ ...stored,
221
+ inputs: stored.inputs.map((entry) => ({ ...entry, dark: Object.fromEntries(Object.entries(entry.dark).filter(([role]) => role !== "on-learning-container")) }))
222
+ }),
223
+ "not this module's": () => ["#010203"]
224
+ };
225
+ for (const [name, change] of Object.entries(cases)) {
226
+ const storage = await tampered(change);
227
+ assert.deepEqual((await browserStart(t, storage)).materialThemes(...VIBE64_INPUT), computed, name);
228
+ // The computed colours replace the unusable ones: the input is stored once.
229
+ assert.equal(JSON.parse(storage.getItem("jskit:material-themes")).inputs.length, 1, name);
230
+ }
231
+ const garbage = browserStorage();
232
+ garbage.setItem("jskit:material-themes", "{not json");
233
+ assert.deepEqual((await browserStart(t, garbage)).materialThemes(...VIBE64_INPUT), computed);
234
+ assert.equal(JSON.parse(garbage.getItem("jskit:material-themes")).inputs.length, 1);
235
+ });
236
+
237
+ // The colours of each stored revision: one digest of three inputs' light and dark themes.
238
+ const REVISION_COLOURS = Object.freeze({ 1: "8e0c647d52f4394c311b8d49bfaa699997ad23a17579d8da75944818b873db63" });
239
+
240
+ test("the colours a theme input gives change only with the revision browsers store them under", async (t) => {
241
+ const storage = browserStorage();
242
+ const { materialThemes: themes } = await browserStart(t, storage);
243
+ const colours = [themes("#6750A4"), themes(...VIBE64_INPUT), themes("#B3261E", { partner: "#0A7D3E", brandAccent: "#FF6D00" })];
244
+ const { revision } = JSON.parse(storage.getItem("jskit:material-themes"));
245
+ // A browser keeps showing the colours it stored until the revision changes.
246
+ assert.equal(createHash("sha256").update(JSON.stringify(colours)).digest("hex"), REVISION_COLOURS[revision],
247
+ `The colours differ from revision ${revision}'s: bump THEMES_REVISION in colorSchemes.js and record its digest here.`);
248
+ });
249
+
250
+ test("a browser that refuses storage still gets its theme", async (t) => {
251
+ const { materialThemes: themes } = await browserStart(t, browserStorage({ refuse: true }));
252
+ assert.deepEqual(themes(...VIBE64_INPUT), materialThemes(...VIBE64_INPUT));
253
+ globalThis.window = {
254
+ get localStorage() { throw new Error("SecurityError: the document is sandboxed"); }
255
+ };
256
+ pageStarts += 1;
257
+ const sandboxed = await import(`../src/client/colorSchemes.js?start=${pageStarts}`);
258
+ assert.deepEqual(sandboxed.materialThemes(...VIBE64_INPUT), materialThemes(...VIBE64_INPUT));
259
+ });
260
+
125
261
  test("a seed that is not a six-digit hex colour is refused", () => {
126
262
  assert.throws(() => materialThemes("purple"), /six-digit hex/u);
127
263
  assert.throws(() => createMaterialVuetifyOptions({ seed: "#123" }), /six-digit hex/u);