Skip to content

Commit db9e5c3

Browse files
committed
fix(web): harden theme palette edge cases
1 parent a1bc6d5 commit db9e5c3

2 files changed

Lines changed: 55 additions & 32 deletions

File tree

‎apps/web/src/themePalette.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,7 @@ describe("theme files", () => {
618618
colors: { accent: "#5b6cff" },
619619
}),
620620
),
621-
).toThrow(`Failed to write the theme library to ${CUSTOM_THEMES_STORAGE_KEY}.`);
621+
).toThrow(`Failed to read the theme library from ${CUSTOM_THEMES_STORAGE_KEY}.`);
622622
expect(setItem).not.toHaveBeenCalled();
623623

624624
vi.unstubAllGlobals();

‎apps/web/src/themePalette.ts‎

Lines changed: 54 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,8 @@ type CustomThemeLibrarySnapshot =
137137
storedThemes: ReadonlyArray<unknown>;
138138
themes: ReadonlyArray<ThemeDefinition>;
139139
}>
140-
| Readonly<{ status: "unavailable"; cause: unknown }>;
140+
| Readonly<{ status: "unavailable"; reason: "malformed" }>
141+
| Readonly<{ status: "unavailable"; reason: "storage-unavailable"; cause: unknown }>;
141142

142143
let customThemeLibrarySnapshot: CustomThemeLibrarySnapshot | null = null;
143144
const themePreviewListeners = new Set<() => void>();
@@ -239,29 +240,31 @@ function readCustomThemeLibrarySnapshot(): CustomThemeLibrarySnapshot {
239240
return { status: "ready", storedThemes: [], themes: [] };
240241
}
241242

243+
let raw: string | null;
242244
try {
243-
const raw = window.localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
244-
if (!raw) return { status: "ready", storedThemes: [], themes: [] };
245-
const parsed: unknown = JSON.parse(raw);
246-
if (!Array.isArray(parsed)) {
247-
return {
248-
status: "unavailable",
249-
cause: new Error("The stored theme library is not an array."),
250-
};
251-
}
245+
raw = window.localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
246+
} catch (cause) {
247+
return { status: "unavailable", reason: "storage-unavailable", cause };
248+
}
249+
if (!raw) return { status: "ready", storedThemes: [], themes: [] };
252250

253-
const themes: ThemeDefinition[] = [];
254-
for (const value of parsed) {
255-
const theme = parseStoredTheme(value);
256-
if (theme && !themes.some((existing) => existing.id === theme.id)) {
257-
themes.push(theme);
258-
}
259-
}
251+
let parsed: unknown;
252+
try {
253+
parsed = JSON.parse(raw);
254+
} catch {
255+
return { status: "unavailable", reason: "malformed" };
256+
}
257+
if (!Array.isArray(parsed)) return { status: "unavailable", reason: "malformed" };
260258

261-
return { status: "ready", storedThemes: parsed, themes };
262-
} catch (cause) {
263-
return { status: "unavailable", cause };
259+
const themes: ThemeDefinition[] = [];
260+
for (const value of parsed) {
261+
const theme = parseStoredTheme(value);
262+
if (theme && !themes.some((existing) => existing.id === theme.id)) {
263+
themes.push(theme);
264+
}
264265
}
266+
267+
return { status: "ready", storedThemes: parsed, themes };
265268
}
266269

267270
function getCustomThemeLibrarySnapshot(): CustomThemeLibrarySnapshot {
@@ -861,18 +864,25 @@ function oklchToRgbUnclamped({ L, C, h }: ThemeOklch): { r: number; g: number; b
861864
};
862865
}
863866

864-
/** Walk chroma toward grey until the color is representable in sRGB. */
867+
/** Find the greatest chroma along the same lightness and hue that fits in sRGB. */
865868
function mapThemeOklchToSrgbGamut(color: ThemeOklch): ThemeOklch {
866-
let { C } = color;
867-
for (let step = 0; step < 12; step += 1) {
869+
const isInGamut = (C: number) => {
868870
const linear = oklchToRgbUnclamped({ ...color, C });
869-
const inGamut = [linear.r, linear.g, linear.b].every(
871+
return [linear.r, linear.g, linear.b].every(
870872
(channel) => channel >= -0.0001 && channel <= 1.0001,
871873
);
872-
if (inGamut) return { ...color, C };
873-
C *= 0.82;
874+
};
875+
if (isInGamut(color.C)) return color;
876+
877+
let low = 0;
878+
let high = color.C;
879+
const steps = Math.max(1, Math.ceil(Math.log2(Math.max(color.C, 0.000001) / 0.000001)));
880+
for (let step = 0; step < steps; step += 1) {
881+
const mid = (low + high) / 2;
882+
if (isInGamut(mid)) low = mid;
883+
else high = mid;
874884
}
875-
return { ...color, C: 0 };
885+
return { ...color, C: low };
876886
}
877887

878888
/** Convert to sRGB after applying the palette engine's gamut mapping. */
@@ -1554,10 +1564,16 @@ export function themeIdFromName(name: string): string {
15541564

15551565
export class ThemeLibraryStorageError extends Schema.TaggedErrorClass<ThemeLibraryStorageError>()(
15561566
"ThemeLibraryStorageError",
1557-
{ storageKey: Schema.String, cause: Schema.Defect() },
1567+
{
1568+
storageKey: Schema.String,
1569+
operation: Schema.Literals(["read", "write"]),
1570+
reason: Schema.Literals(["malformed", "storage-unavailable"]),
1571+
cause: Schema.optional(Schema.Defect()),
1572+
},
15581573
) {
15591574
override get message(): string {
1560-
return `Failed to write the theme library to ${this.storageKey}.`;
1575+
const direction = this.operation === "read" ? "from" : "to";
1576+
return `Failed to ${this.operation} the theme library ${direction} ${this.storageKey}.`;
15611577
}
15621578
}
15631579

@@ -1572,7 +1588,12 @@ function saveCustomThemes(
15721588
window.localStorage.setItem(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify(storedThemes));
15731589
customThemeLibrarySnapshot = { status: "ready", storedThemes, themes };
15741590
} catch (cause) {
1575-
throw new ThemeLibraryStorageError({ storageKey: CUSTOM_THEMES_STORAGE_KEY, cause });
1591+
throw new ThemeLibraryStorageError({
1592+
storageKey: CUSTOM_THEMES_STORAGE_KEY,
1593+
operation: "write",
1594+
reason: "storage-unavailable",
1595+
cause,
1596+
});
15761597
}
15771598
notifyCustomThemeListeners();
15781599
}
@@ -1582,7 +1603,9 @@ function getWritableCustomThemeLibrary(): Extract<CustomThemeLibrarySnapshot, {
15821603
if (snapshot.status === "unavailable") {
15831604
throw new ThemeLibraryStorageError({
15841605
storageKey: CUSTOM_THEMES_STORAGE_KEY,
1585-
cause: snapshot.cause,
1606+
operation: "read",
1607+
reason: snapshot.reason,
1608+
...("cause" in snapshot ? { cause: snapshot.cause } : {}),
15861609
});
15871610
}
15881611
return snapshot;

0 commit comments

Comments
 (0)