@adea-ai/ui 0.123.0 → 0.124.0
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/dist/NOTICE +18 -0
- package/dist/components/layout/split-layout/resize-controller-core-retry.d.ts +13 -0
- package/dist/components/layout/split-layout/resize-controller-core-retry.d.ts.map +1 -0
- package/dist/components/layout/split-layout/resize-controller-core-retry.js +63 -0
- package/dist/components/layout/split-layout/resize-controller-core-retry.js.map +1 -0
- package/dist/components/layout/split-layout/resize-controller-core.d.ts +13 -0
- package/dist/components/layout/split-layout/resize-controller-core.d.ts.map +1 -0
- package/dist/components/layout/split-layout/resize-controller-core.js +63 -0
- package/dist/components/layout/split-layout/resize-controller-core.js.map +1 -0
- package/dist/components/layout/split-layout/resize-controller-retry-2.d.ts +3 -0
- package/dist/components/layout/split-layout/resize-controller-retry-2.d.ts.map +1 -0
- package/dist/components/layout/split-layout/resize-controller-retry-2.js +2 -0
- package/dist/components/layout/split-layout/resize-controller-retry.d.ts +2 -0
- package/dist/components/layout/split-layout/resize-controller-retry.d.ts.map +1 -0
- package/dist/components/layout/split-layout/resize-controller-retry.js +2 -0
- package/dist/components/layout/split-layout/resize-controller.d.ts +2 -0
- package/dist/components/layout/split-layout/resize-controller.d.ts.map +1 -0
- package/dist/components/layout/split-layout/resize-controller.js +2 -0
- package/dist/components/layout/split-layout/split-layout.d.ts.map +1 -1
- package/dist/components/layout/split-layout/split-layout.js +171 -60
- package/dist/components/layout/split-layout/split-layout.js.map +1 -1
- package/dist/components/theme/appearance-panel.js +1 -1
- package/dist/components/theme/index.d.ts +1 -1
- package/dist/components/theme/index.d.ts.map +1 -1
- package/dist/components/theme/index.js +5 -2
- package/dist/components/theme/theme-context.d.ts +13 -0
- package/dist/components/theme/theme-context.d.ts.map +1 -0
- package/dist/components/theme/theme-context.js +41 -0
- package/dist/components/theme/theme-context.js.map +1 -0
- package/dist/components/theme/theme-document.d.ts +76 -0
- package/dist/components/theme/theme-document.d.ts.map +1 -0
- package/dist/components/theme/theme-document.js +93 -0
- package/dist/components/theme/theme-document.js.map +1 -0
- package/dist/components/theme/theme-persistence.d.ts +50 -0
- package/dist/components/theme/theme-persistence.d.ts.map +1 -0
- package/dist/components/theme/theme-persistence.js +86 -0
- package/dist/components/theme/theme-persistence.js.map +1 -0
- package/dist/components/theme/theme-provider.d.ts +43 -75
- package/dist/components/theme/theme-provider.d.ts.map +1 -1
- package/dist/components/theme/theme-provider.js +50 -116
- package/dist/components/theme/theme-provider.js.map +1 -1
- package/dist/components/theme/theme-state.d.ts +142 -0
- package/dist/components/theme/theme-state.d.ts.map +1 -0
- package/dist/components/theme/theme-state.js +104 -0
- package/dist/components/theme/theme-state.js.map +1 -0
- package/dist/components/theme/theme-toggle.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -3
- package/dist/lib/appearance-font-settings.d.ts +1 -1
- package/dist/lib/appearance-font-settings.d.ts.map +1 -1
- package/dist/lib/appearance-font-settings.js.map +1 -1
- package/dist/lib/themes.d.ts +48 -0
- package/dist/lib/themes.d.ts.map +1 -1
- package/dist/lib/themes.js +150 -36
- package/dist/lib/themes.js.map +1 -1
- package/dist/r/registry.json +46 -0
- package/dist/r/split-layout.json +26 -0
- package/dist/r/src/components/layout/split-layout/resize-controller-core-retry.tsx +66 -0
- package/dist/r/src/components/layout/split-layout/resize-controller-core.tsx +66 -0
- package/dist/r/src/components/layout/split-layout/resize-controller-retry-2.tsx +2 -0
- package/dist/r/src/components/layout/split-layout/resize-controller-retry.tsx +1 -0
- package/dist/r/src/components/layout/split-layout/resize-controller.tsx +1 -0
- package/dist/r/src/components/layout/split-layout/split-layout.tsx +197 -49
- package/dist/r/src/components/theme/index.ts +3 -0
- package/dist/r/src/components/theme/theme-context.ts +43 -0
- package/dist/r/src/components/theme/theme-document.ts +168 -0
- package/dist/r/src/components/theme/theme-persistence.ts +140 -0
- package/dist/r/src/components/theme/theme-provider.tsx +126 -253
- package/dist/r/src/components/theme/theme-state.ts +225 -0
- package/dist/r/src/lib/appearance-font-settings.ts +1 -1
- package/dist/r/src/lib/themes.ts +181 -40
- package/dist/r/theming.json +20 -0
- package/package.json +1 -1
- package/registry.json +46 -0
- package/src/components/layout/split-layout/resize-controller-core-retry.tsx +66 -0
- package/src/components/layout/split-layout/resize-controller-core.tsx +66 -0
- package/src/components/layout/split-layout/resize-controller-retry-2.tsx +2 -0
- package/src/components/layout/split-layout/resize-controller-retry.tsx +1 -0
- package/src/components/layout/split-layout/resize-controller.tsx +1 -0
- package/src/components/layout/split-layout/split-layout.tsx +197 -49
- package/src/components/theme/index.ts +3 -0
- package/src/components/theme/theme-context.ts +43 -0
- package/src/components/theme/theme-document.ts +168 -0
- package/src/components/theme/theme-persistence.ts +140 -0
- package/src/components/theme/theme-provider.tsx +126 -253
- package/src/components/theme/theme-state.ts +225 -0
- package/src/index.ts +3 -0
- package/src/lib/appearance-font-settings.ts +1 -1
- package/src/lib/themes.ts +181 -40
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { accentPresets } from "../../lib/tokens.js";
|
|
2
|
+
import { isThemeAccentId } from "../../lib/theme-accents.js";
|
|
3
|
+
import { defaultDarkThemeId, defaultLightThemeId, themeById } from "../../lib/themes.js";
|
|
4
|
+
import { normalizeAppearanceEditorFontSettings } from "../../lib/appearance-font-settings.js";
|
|
5
|
+
import { defaultThemeSelection, resolvedDensity } from "./theme-state.js";
|
|
6
|
+
//#region src/components/theme/theme-persistence.ts
|
|
7
|
+
/**
|
|
8
|
+
* The preference store, or nothing.
|
|
9
|
+
*
|
|
10
|
+
* Only ever called inside a `try`: where storage is blocked — a sandboxed iframe, a
|
|
11
|
+
* privacy mode, a denied site-data permission — merely *reading* the `localStorage`
|
|
12
|
+
* global throws ("Access is denied", `SecurityError`), so even the `typeof` guard
|
|
13
|
+
* has to sit inside the `try` rather than in front of it. Without a store the
|
|
14
|
+
* preference lives only in the provider's signal for the session.
|
|
15
|
+
*/
|
|
16
|
+
function preferenceStore() {
|
|
17
|
+
return typeof localStorage === "undefined" ? void 0 : localStorage;
|
|
18
|
+
}
|
|
19
|
+
/** The stored preference, validated against the catalogue. */
|
|
20
|
+
function readSelection(storageKey) {
|
|
21
|
+
try {
|
|
22
|
+
const raw = preferenceStore()?.getItem(storageKey);
|
|
23
|
+
if (!raw) return defaultThemeSelection;
|
|
24
|
+
const parsed = JSON.parse(raw);
|
|
25
|
+
const fonts = normalizeAppearanceEditorFontSettings(parsed.fonts, parsed.font).settings;
|
|
26
|
+
return {
|
|
27
|
+
appearance: parsed.appearance === "light" || parsed.appearance === "dark" || parsed.appearance === "system" ? parsed.appearance : defaultThemeSelection.appearance,
|
|
28
|
+
lightThemeId: themeById(parsed.lightThemeId ?? "")?.appearance === "light" ? parsed.lightThemeId : defaultLightThemeId,
|
|
29
|
+
darkThemeId: themeById(parsed.darkThemeId ?? "")?.appearance === "dark" ? parsed.darkThemeId : defaultDarkThemeId,
|
|
30
|
+
accent: typeof parsed.accent === "string" && (accentPresets.some((preset) => preset.id === parsed.accent) || isThemeAccentId(parsed.accent)) ? parsed.accent : defaultThemeSelection.accent,
|
|
31
|
+
font: fonts.ui.family,
|
|
32
|
+
fonts,
|
|
33
|
+
density: resolvedDensity(parsed)
|
|
34
|
+
};
|
|
35
|
+
} catch {
|
|
36
|
+
return defaultThemeSelection;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The default persistence: one JSON document in `localStorage` under `key`.
|
|
41
|
+
*
|
|
42
|
+
* `read` is the provider's original `readSelection`, moved here unchanged — every
|
|
43
|
+
* stored id is validated against the catalogue, so a stale preference falls back to
|
|
44
|
+
* a default rather than reaching the document. `key` may be a function so a
|
|
45
|
+
* provider whose `storageKey` prop changes writes to the key it is now given.
|
|
46
|
+
*
|
|
47
|
+
* Blocked, full or absent storage is survivable in both directions: a read answers
|
|
48
|
+
* with the defaults and a write is dropped, so the preference simply lasts the
|
|
49
|
+
* session.
|
|
50
|
+
*/
|
|
51
|
+
function localStoragePersistence(key) {
|
|
52
|
+
const keyOf = () => typeof key === "function" ? key() : key;
|
|
53
|
+
return {
|
|
54
|
+
read: () => readSelection(keyOf()),
|
|
55
|
+
write(next) {
|
|
56
|
+
try {
|
|
57
|
+
preferenceStore()?.setItem(keyOf(), JSON.stringify(next));
|
|
58
|
+
} catch {}
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* What a persistence knows, or nothing.
|
|
64
|
+
*
|
|
65
|
+
* The seam's `read` must not throw, and the provider does not rely on that: a host
|
|
66
|
+
* persistence is code the design system has not seen, and a theme provider that
|
|
67
|
+
* fails to mount because a store misbehaved has turned a lost preference into a
|
|
68
|
+
* blank application.
|
|
69
|
+
*/
|
|
70
|
+
function readPersisted(persistence) {
|
|
71
|
+
try {
|
|
72
|
+
return persistence.read();
|
|
73
|
+
} catch {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Hand a selection to the store; a store that throws loses the preference, not the switch. */
|
|
78
|
+
function writePersisted(persistence, next) {
|
|
79
|
+
try {
|
|
80
|
+
persistence.write(next);
|
|
81
|
+
} catch {}
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
export { localStoragePersistence, readPersisted, writePersisted };
|
|
85
|
+
|
|
86
|
+
//# sourceMappingURL=theme-persistence.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"theme-persistence.js","names":[],"sources":["../../../src/components/theme/theme-persistence.ts"],"sourcesContent":["import { accentPresets } from '#lib/tokens'\nimport { normalizeAppearanceEditorFontSettings } from '#lib/appearance-font-settings'\nimport { defaultDarkThemeId, defaultLightThemeId, isThemeAccentId, themeById } from '#lib/themes'\nimport { defaultThemeSelection, resolvedDensity, type ThemeSelection } from './theme-state'\n\n/**\n * Where a selection is kept between sessions.\n *\n * The provider never touches storage itself; it asks a `ThemePersistence`. The\n * default is {@link localStoragePersistence}, which is what the provider always did.\n * A host that stores the preference in a different shape, under a versioned\n * envelope, or somewhere that is not `localStorage` supplies its own and the\n * resolution and application rules stay the shared ones.\n *\n * The contract is deliberately narrow, so that an implementation cannot make the\n * provider less safe than it was:\n *\n * - `read` is synchronous and runs once, when the provider is created. It may\n * repair or quarantine what it finds, and it must not throw: the provider\n * treats a throw as \"nothing stored\" and starts from the defaults.\n * - `write` runs only from `setSelection`. Never on mount, never from `preview`,\n * never as a side effect of reading, so the first write to a store is always a\n * user's decision. A throw is swallowed, because a full or blocked store must\n * not break the switch.\n */\nexport type ThemePersistence = {\n read(): Partial<ThemeSelection> | undefined\n write(next: ThemeSelection): void\n}\n\n/**\n * The preference store, or nothing.\n *\n * Only ever called inside a `try`: where storage is blocked — a sandboxed iframe, a\n * privacy mode, a denied site-data permission — merely *reading* the `localStorage`\n * global throws (\"Access is denied\", `SecurityError`), so even the `typeof` guard\n * has to sit inside the `try` rather than in front of it. Without a store the\n * preference lives only in the provider's signal for the session.\n */\nfunction preferenceStore(): Storage | undefined {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n}\n\n/** The stored preference, validated against the catalogue. */\nfunction readSelection(storageKey: string): ThemeSelection {\n try {\n const raw = preferenceStore()?.getItem(storageKey)\n if (!raw) return defaultThemeSelection\n const parsed = JSON.parse(raw) as Partial<ThemeSelection>\n const fonts = normalizeAppearanceEditorFontSettings(parsed.fonts, parsed.font).settings\n return {\n appearance:\n parsed.appearance === 'light' ||\n parsed.appearance === 'dark' ||\n parsed.appearance === 'system'\n ? parsed.appearance\n : defaultThemeSelection.appearance,\n // An unknown id would leave the document with no theme at all, so a stale\n // preference from an older catalogue falls back rather than applying nothing.\n lightThemeId:\n themeById(parsed.lightThemeId ?? '')?.appearance === 'light'\n ? (parsed.lightThemeId as string)\n : defaultLightThemeId,\n darkThemeId:\n themeById(parsed.darkThemeId ?? '')?.appearance === 'dark'\n ? (parsed.darkThemeId as string)\n : defaultDarkThemeId,\n // A theme accent is kept whenever it names a slot, even one the stored pair\n // cannot offer: the id is role-shaped so it survives a theme switch, and an\n // unoffered slot already resolves to the theme's own primary when applied.\n accent:\n typeof parsed.accent === 'string' &&\n (accentPresets.some((preset) => preset.id === parsed.accent) ||\n isThemeAccentId(parsed.accent))\n ? parsed.accent\n : defaultThemeSelection.accent,\n font: fonts.ui.family,\n fonts,\n // Every axis has to be read back here, or it is lost twice: the provider's\n // document effect removes the `data-density` that `themeScript` set for the first paint, and\n // the next `setSelection` rewrites the store without it.\n density: resolvedDensity(parsed as ThemeSelection),\n }\n } catch {\n return defaultThemeSelection\n }\n}\n\n/**\n * The default persistence: one JSON document in `localStorage` under `key`.\n *\n * `read` is the provider's original `readSelection`, moved here unchanged — every\n * stored id is validated against the catalogue, so a stale preference falls back to\n * a default rather than reaching the document. `key` may be a function so a\n * provider whose `storageKey` prop changes writes to the key it is now given.\n *\n * Blocked, full or absent storage is survivable in both directions: a read answers\n * with the defaults and a write is dropped, so the preference simply lasts the\n * session.\n */\nexport function localStoragePersistence(key: string | (() => string)): ThemePersistence {\n const keyOf = () => (typeof key === 'function' ? key() : key)\n return {\n read: () => readSelection(keyOf()),\n write(next) {\n try {\n preferenceStore()?.setItem(keyOf(), JSON.stringify(next))\n } catch {\n // A full, blocked or unavailable store must not break the switch: the\n // preference simply does not survive the reload.\n }\n },\n }\n}\n\n/**\n * What a persistence knows, or nothing.\n *\n * The seam's `read` must not throw, and the provider does not rely on that: a host\n * persistence is code the design system has not seen, and a theme provider that\n * fails to mount because a store misbehaved has turned a lost preference into a\n * blank application.\n */\nexport function readPersisted(persistence: ThemePersistence): Partial<ThemeSelection> | undefined {\n try {\n return persistence.read()\n } catch {\n return undefined\n }\n}\n\n/** Hand a selection to the store; a store that throws loses the preference, not the switch. */\nexport function writePersisted(persistence: ThemePersistence, next: ThemeSelection): void {\n try {\n persistence.write(next)\n } catch {\n // Same contract as a full or blocked `localStorage`: the choice holds for the\n // session and does not survive the reload.\n }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B,QAAQ,CAGR;AACF"}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import type { JSX } from 'solid-js';
|
|
2
|
-
import { type
|
|
3
|
-
import type
|
|
4
|
-
import { type
|
|
2
|
+
import { type ThemeVariant } from '#lib/themes';
|
|
3
|
+
import { type ThemePersistence } from './theme-persistence';
|
|
4
|
+
import { type ThemeSelection } from './theme-state';
|
|
5
|
+
export { useOptionalTheme, useTheme } from './theme-context';
|
|
6
|
+
export { localStoragePersistence, type ThemePersistence } from './theme-persistence';
|
|
7
|
+
export { defaultThemeSelection, resolvedDensity, type ThemeContextValue, type ThemeDensity, type ThemeSelection, } from './theme-state';
|
|
5
8
|
/**
|
|
6
9
|
* ThemeProvider.
|
|
7
10
|
*
|
|
@@ -10,19 +13,17 @@ import { type ThemeAppearance, type ThemeVariant } from '#lib/themes';
|
|
|
10
13
|
*
|
|
11
14
|
* ## What a preference is
|
|
12
15
|
*
|
|
13
|
-
* Four independent choices, and keeping them independent is the
|
|
16
|
+
* Four independent choices (`ThemeSelection`), and keeping them independent is the
|
|
17
|
+
* point: appearance, a theme per appearance, an accent and fonts. They compose: a
|
|
18
|
+
* user who wants Nord with a violet accent and the system font should not need
|
|
19
|
+
* someone to author that combination.
|
|
14
20
|
*
|
|
15
|
-
*
|
|
16
|
-
* - **a theme per appearance** — so a user can run Catppuccin Mocha by night and
|
|
17
|
-
* Solarized Light by day without re-choosing when the system flips.
|
|
18
|
-
* - **an accent** — adea's six presets, or one of the accents the selected theme
|
|
19
|
-
* pair carries itself (`ansi-blue`…), which re-colour the interactive roles on
|
|
20
|
-
* top of whichever theme is active.
|
|
21
|
-
* - **fonts** — separate family and size choices for UI, content and code.
|
|
21
|
+
* ## Where the rules live
|
|
22
22
|
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
23
|
+
* This component is wiring. What a selection merges to and resolves to is
|
|
24
|
+
* `theme-state.ts`; what lands on `<html>` is `theme-document.ts`; where the
|
|
25
|
+
* preference is kept is `theme-persistence.ts`. Each is plain code a test can call,
|
|
26
|
+
* which is the reason none of it is inlined here.
|
|
26
27
|
*
|
|
27
28
|
* ## Why the variants are applied as inline properties
|
|
28
29
|
*
|
|
@@ -33,67 +34,6 @@ import { type ThemeAppearance, type ThemeVariant } from '#lib/themes';
|
|
|
33
34
|
* stylesheet. `theme.css` keeps the default theme's values so the first paint is
|
|
34
35
|
* correct before any script runs.
|
|
35
36
|
*/
|
|
36
|
-
export type ThemeSelection = {
|
|
37
|
-
/** `system` follows `prefers-color-scheme` and updates when it changes. */
|
|
38
|
-
appearance: ThemeAppearance | 'system';
|
|
39
|
-
/** The variant to use when the resolved appearance is light. */
|
|
40
|
-
lightThemeId: string;
|
|
41
|
-
/** The variant to use when the resolved appearance is dark. */
|
|
42
|
-
darkThemeId: string;
|
|
43
|
-
/**
|
|
44
|
-
* An `accentPresets` id, a theme accent id from `themeAccents()` (`ansi-blue`…),
|
|
45
|
-
* or `theme` for the variant's own primary. A theme accent the current pair does
|
|
46
|
-
* not offer falls back to the variant's own primary.
|
|
47
|
-
*/
|
|
48
|
-
accent: string;
|
|
49
|
-
/** UI-family alias for consumers of the original single-font preference. */
|
|
50
|
-
font: string;
|
|
51
|
-
/** UI, content and code font settings. Omitted legacy records are migrated from `font`. */
|
|
52
|
-
fonts?: AppearanceEditorFontSettings;
|
|
53
|
-
/**
|
|
54
|
-
* `comfortable` is the system's default geometry; `compact` moves the control
|
|
55
|
-
* ladder down one rung.
|
|
56
|
-
*
|
|
57
|
-
* Optional, and defaulted on read, so a preference stored before density existed
|
|
58
|
-
* keeps working and `ThemeSelection` stays assignable without it.
|
|
59
|
-
*/
|
|
60
|
-
density?: ThemeDensity;
|
|
61
|
-
};
|
|
62
|
-
export declare const defaultThemeSelection: ThemeSelection;
|
|
63
|
-
/**
|
|
64
|
-
* The two density rungs.
|
|
65
|
-
*
|
|
66
|
-
* `comfortable` is the geometry in `theme.css`, so it is the absence of an
|
|
67
|
-
* attribute rather than a value: a document that ships no `data-density` at all
|
|
68
|
-
* renders correctly, which is what keeps this additive.
|
|
69
|
-
*/
|
|
70
|
-
export type ThemeDensity = 'comfortable' | 'compact';
|
|
71
|
-
/**
|
|
72
|
-
* A stored selection's density, defaulted.
|
|
73
|
-
*
|
|
74
|
-
* The stored value is read through here rather than trusted, because a preference
|
|
75
|
-
* written before density existed has no `density` key and a hand-edited store may
|
|
76
|
-
* hold anything.
|
|
77
|
-
*/
|
|
78
|
-
export declare function resolvedDensity(selection: ThemeSelection): ThemeDensity;
|
|
79
|
-
export type ThemeContextValue = {
|
|
80
|
-
/** The preference as stored. */
|
|
81
|
-
selection: () => ThemeSelection;
|
|
82
|
-
/** What the preference resolves to right now, after `system`. */
|
|
83
|
-
resolvedAppearance: () => ThemeAppearance;
|
|
84
|
-
/** The variant in use. */
|
|
85
|
-
variant: () => ThemeVariant;
|
|
86
|
-
/** Update part of the preference. */
|
|
87
|
-
setSelection: (patch: Partial<ThemeSelection>) => void;
|
|
88
|
-
/** The catalogue, so a picker does not import it separately. */
|
|
89
|
-
themes: readonly ThemeVariant[];
|
|
90
|
-
/**
|
|
91
|
-
* The accents the selected light/dark pair carries, offered beside the presets.
|
|
92
|
-
* Follows the selection: a different theme pair may offer different slots.
|
|
93
|
-
*/
|
|
94
|
-
themeAccents: () => readonly AccentPreset[];
|
|
95
|
-
};
|
|
96
|
-
export declare function useTheme(): ThemeContextValue;
|
|
97
37
|
export type ThemeProviderProps = {
|
|
98
38
|
children?: JSX.Element;
|
|
99
39
|
/** Where the preference is persisted. Distinct per application. */
|
|
@@ -113,6 +53,34 @@ export type ThemeProviderProps = {
|
|
|
113
53
|
* seeds from `initial`, and persists every `setSelection`.
|
|
114
54
|
*/
|
|
115
55
|
selection?: Partial<ThemeSelection>;
|
|
56
|
+
/**
|
|
57
|
+
* Where the preference is kept, in place of `localStorage` under `storageKey`.
|
|
58
|
+
*
|
|
59
|
+
* Read once when the provider is created, so changing the prop later does not
|
|
60
|
+
* move the store. `storageKey` is ignored when this is given.
|
|
61
|
+
*/
|
|
62
|
+
persistence?: ThemePersistence;
|
|
63
|
+
/**
|
|
64
|
+
* Variants the host adds to the built-in catalogue — themes a user imported.
|
|
65
|
+
*
|
|
66
|
+
* A function is read inside the provider's reactive scope, so one that reads a
|
|
67
|
+
* signal keeps the picker and the document current when the set changes. A
|
|
68
|
+
* stored id that names no variant, built in or added, paints the default of its
|
|
69
|
+
* appearance and stays in the selection untouched.
|
|
70
|
+
*/
|
|
71
|
+
themes?: readonly ThemeVariant[] | (() => readonly ThemeVariant[]);
|
|
72
|
+
/**
|
|
73
|
+
* Rewrites the custom properties of each pass before they are written to
|
|
74
|
+
* `<html>`: the variant's roles with the accent over them. `tokensAsHex` from
|
|
75
|
+
* `lib/themes` is the one the system ships.
|
|
76
|
+
*/
|
|
77
|
+
transformTokens?: (tokens: Record<string, string>) => Record<string, string>;
|
|
78
|
+
/**
|
|
79
|
+
* Switch CSS transitions off for the frame that carries a change, so a theme
|
|
80
|
+
* switch cannot animate the whole page. Off by default: it adds a `<style>`
|
|
81
|
+
* element to `<head>` for two frames on every change.
|
|
82
|
+
*/
|
|
83
|
+
disableTransitionOnChange?: boolean;
|
|
116
84
|
};
|
|
117
85
|
export declare function ThemeProvider(props: ThemeProviderProps): JSX.Element;
|
|
118
86
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"theme-provider.d.ts","sourceRoot":"","sources":["../../../src/components/theme/theme-provider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;
|
|
1
|
+
{"version":3,"file":"theme-provider.d.ts","sourceRoot":"","sources":["../../../src/components/theme/theme-provider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAInC,OAAO,EAIL,KAAK,YAAY,EAClB,MAAM,aAAa,CAAA;AAGpB,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,qBA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,SAAoB,GAAG,MAAM,CAGlE"}
|
|
@@ -1,101 +1,29 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { isThemeAccentId } from "../../lib/theme-accents.js";
|
|
3
|
-
import { accentVariables, builtinThemes, defaultDarkThemeId, defaultLightThemeId, themeAccentsFor, themeById, themeCssVariables } from "../../lib/themes.js";
|
|
1
|
+
import { builtinThemes, themeAccentsFor } from "../../lib/themes.js";
|
|
4
2
|
import { safeScriptStringLiteral } from "../../lib/safe-script.js";
|
|
5
|
-
import {
|
|
3
|
+
import { fontSettingsBootstrapScript } from "../../lib/appearance-font-settings.js";
|
|
4
|
+
import { themeContext, useOptionalTheme, useTheme } from "./theme-context.js";
|
|
5
|
+
import { defaultThemeSelection, initialThemeSelection, mergeRegistry, mergeThemeSelection, resolveThemeState, resolvedDensity } from "./theme-state.js";
|
|
6
|
+
import { applyThemeToRoot, applyWithoutTransitions } from "./theme-document.js";
|
|
7
|
+
import { localStoragePersistence, readPersisted, writePersisted } from "./theme-persistence.js";
|
|
6
8
|
import { createComponent } from "solid-js/web";
|
|
7
|
-
import {
|
|
9
|
+
import { createEffect, createMemo, createSignal, onCleanup, splitProps } from "solid-js";
|
|
8
10
|
//#region src/components/theme/theme-provider.tsx
|
|
9
|
-
var defaultThemeSelection = {
|
|
10
|
-
appearance: "system",
|
|
11
|
-
lightThemeId: defaultLightThemeId,
|
|
12
|
-
darkThemeId: defaultDarkThemeId,
|
|
13
|
-
accent: "theme",
|
|
14
|
-
font: "system",
|
|
15
|
-
fonts: DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS,
|
|
16
|
-
density: "comfortable"
|
|
17
|
-
};
|
|
18
|
-
/**
|
|
19
|
-
* A stored selection's density, defaulted.
|
|
20
|
-
*
|
|
21
|
-
* The stored value is read through here rather than trusted, because a preference
|
|
22
|
-
* written before density existed has no `density` key and a hand-edited store may
|
|
23
|
-
* hold anything.
|
|
24
|
-
*/
|
|
25
|
-
function resolvedDensity(selection) {
|
|
26
|
-
return selection.density === "compact" ? "compact" : "comfortable";
|
|
27
|
-
}
|
|
28
|
-
var ThemeContext = createContext();
|
|
29
|
-
function useTheme() {
|
|
30
|
-
const value = useContext(ThemeContext);
|
|
31
|
-
if (!value) throw new Error("useTheme must be called inside a <ThemeProvider>.");
|
|
32
|
-
return value;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* The preference store, or nothing.
|
|
36
|
-
*
|
|
37
|
-
* Only ever called inside a `try`: where storage is blocked — a sandboxed iframe, a
|
|
38
|
-
* privacy mode, a denied site-data permission — merely *reading* the `localStorage`
|
|
39
|
-
* global throws ("Access is denied", `SecurityError`), so even the `typeof` guard
|
|
40
|
-
* has to sit inside the `try` rather than in front of it. Without a store the
|
|
41
|
-
* preference lives only in the provider's signal for the session.
|
|
42
|
-
*/
|
|
43
|
-
function preferenceStore() {
|
|
44
|
-
return typeof localStorage === "undefined" ? void 0 : localStorage;
|
|
45
|
-
}
|
|
46
|
-
/** The stored preference, validated against the catalogue. */
|
|
47
|
-
function readSelection(storageKey) {
|
|
48
|
-
try {
|
|
49
|
-
const raw = preferenceStore()?.getItem(storageKey);
|
|
50
|
-
if (!raw) return defaultThemeSelection;
|
|
51
|
-
const parsed = JSON.parse(raw);
|
|
52
|
-
const fonts = normalizeAppearanceEditorFontSettings(parsed.fonts, parsed.font).settings;
|
|
53
|
-
return {
|
|
54
|
-
appearance: parsed.appearance === "light" || parsed.appearance === "dark" || parsed.appearance === "system" ? parsed.appearance : defaultThemeSelection.appearance,
|
|
55
|
-
lightThemeId: themeById(parsed.lightThemeId ?? "")?.appearance === "light" ? parsed.lightThemeId : defaultLightThemeId,
|
|
56
|
-
darkThemeId: themeById(parsed.darkThemeId ?? "")?.appearance === "dark" ? parsed.darkThemeId : defaultDarkThemeId,
|
|
57
|
-
accent: typeof parsed.accent === "string" && (accentPresets.some((preset) => preset.id === parsed.accent) || isThemeAccentId(parsed.accent)) ? parsed.accent : defaultThemeSelection.accent,
|
|
58
|
-
font: fonts.ui.family,
|
|
59
|
-
fonts,
|
|
60
|
-
density: resolvedDensity(parsed)
|
|
61
|
-
};
|
|
62
|
-
} catch {
|
|
63
|
-
return defaultThemeSelection;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
/** Keep the deprecated single-font view synchronized with the UI axis. */
|
|
67
|
-
function mergeThemeSelection(base, patch) {
|
|
68
|
-
const merged = {
|
|
69
|
-
...base,
|
|
70
|
-
...patch
|
|
71
|
-
};
|
|
72
|
-
let fonts;
|
|
73
|
-
if (patch.fonts !== void 0) fonts = normalizeAppearanceEditorFontSettings(patch.fonts).settings;
|
|
74
|
-
else if (patch.font !== void 0) {
|
|
75
|
-
const currentFonts = normalizeAppearanceEditorFontSettings(base.fonts, base.font).settings;
|
|
76
|
-
fonts = normalizeAppearanceEditorFontSettings({
|
|
77
|
-
...currentFonts,
|
|
78
|
-
ui: {
|
|
79
|
-
...currentFonts.ui,
|
|
80
|
-
family: patch.font
|
|
81
|
-
}
|
|
82
|
-
}).settings;
|
|
83
|
-
} else fonts = normalizeAppearanceEditorFontSettings(merged.fonts, merged.font).settings;
|
|
84
|
-
return {
|
|
85
|
-
...merged,
|
|
86
|
-
fonts,
|
|
87
|
-
font: fonts.ui.family
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
11
|
function ThemeProvider(props) {
|
|
91
12
|
const [local] = splitProps(props, [
|
|
92
13
|
"children",
|
|
93
14
|
"storageKey",
|
|
94
15
|
"initial",
|
|
95
|
-
"selection"
|
|
16
|
+
"selection",
|
|
17
|
+
"persistence",
|
|
18
|
+
"themes",
|
|
19
|
+
"transformTokens",
|
|
20
|
+
"disableTransitionOnChange"
|
|
96
21
|
]);
|
|
97
22
|
const storageKey = () => local.storageKey ?? "adea-appearance";
|
|
98
|
-
const
|
|
23
|
+
const persistence = local.persistence ?? localStoragePersistence(storageKey);
|
|
24
|
+
const extraThemes = createMemo(() => typeof local.themes === "function" ? local.themes() : local.themes ?? []);
|
|
25
|
+
const registry = createMemo(() => mergeRegistry(builtinThemes, extraThemes()));
|
|
26
|
+
const [selection, setSelectionState] = createSignal(initialThemeSelection(readPersisted(persistence), local.initial));
|
|
99
27
|
createEffect(() => {
|
|
100
28
|
const incoming = local.selection;
|
|
101
29
|
if (incoming) setSelectionState((current) => mergeThemeSelection(current, incoming));
|
|
@@ -108,33 +36,34 @@ function ThemeProvider(props) {
|
|
|
108
36
|
query.addEventListener("change", onChange);
|
|
109
37
|
onCleanup(() => query.removeEventListener("change", onChange));
|
|
110
38
|
}
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
return themeById(id) ?? builtinThemes[0];
|
|
39
|
+
const committed = createMemo(() => resolveThemeState(selection(), systemAppearance(), registry()));
|
|
40
|
+
const resolvedAppearance = createMemo(() => committed().appearance);
|
|
41
|
+
const variant = createMemo(() => committed().variant);
|
|
42
|
+
const [draft, setDraft] = createSignal();
|
|
43
|
+
const shownSelection = createMemo(() => {
|
|
44
|
+
const preview = draft();
|
|
45
|
+
return preview ? mergeThemeSelection(selection(), preview) : selection();
|
|
119
46
|
});
|
|
47
|
+
const shown = createMemo(() => draft() ? resolveThemeState(shownSelection(), systemAppearance(), registry()) : committed());
|
|
48
|
+
let written;
|
|
49
|
+
let restoreTransitions;
|
|
120
50
|
createEffect(() => {
|
|
121
51
|
if (typeof document === "undefined") return;
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
if (resolvedDensity(selection()) === "comfortable") root.removeAttribute("data-density");
|
|
136
|
-
else root.dataset["density"] = resolvedDensity(selection());
|
|
52
|
+
const state = {
|
|
53
|
+
selection: shownSelection(),
|
|
54
|
+
appearance: shown().appearance,
|
|
55
|
+
variant: shown().variant
|
|
56
|
+
};
|
|
57
|
+
const options = { transformTokens: local.transformTokens };
|
|
58
|
+
const apply = () => {
|
|
59
|
+
written = applyThemeToRoot(document.documentElement, state, options, written);
|
|
60
|
+
};
|
|
61
|
+
if (local.disableTransitionOnChange) {
|
|
62
|
+
restoreTransitions?.();
|
|
63
|
+
restoreTransitions = applyWithoutTransitions(document, apply);
|
|
64
|
+
} else apply();
|
|
137
65
|
});
|
|
66
|
+
onCleanup(() => restoreTransitions?.());
|
|
138
67
|
const themeAccents = createMemo(() => themeAccentsFor(selection().lightThemeId, selection().darkThemeId));
|
|
139
68
|
const value = {
|
|
140
69
|
selection,
|
|
@@ -142,15 +71,20 @@ function ThemeProvider(props) {
|
|
|
142
71
|
variant,
|
|
143
72
|
themes: builtinThemes,
|
|
144
73
|
themeAccents,
|
|
74
|
+
allThemes: registry,
|
|
75
|
+
preview(next) {
|
|
76
|
+
setDraft(next ? { ...next } : void 0);
|
|
77
|
+
},
|
|
78
|
+
previewing: () => draft() !== void 0,
|
|
145
79
|
setSelection(patch) {
|
|
146
80
|
const next = mergeThemeSelection(selection(), patch);
|
|
147
81
|
setSelectionState(next);
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
} catch {}
|
|
82
|
+
setDraft(void 0);
|
|
83
|
+
writePersisted(persistence, next);
|
|
151
84
|
}
|
|
152
85
|
};
|
|
153
|
-
|
|
86
|
+
const Context = themeContext();
|
|
87
|
+
return createComponent(Context.Provider, {
|
|
154
88
|
value,
|
|
155
89
|
get children() {
|
|
156
90
|
return local.children;
|
|
@@ -201,6 +135,6 @@ function themeScript(storageKey = "adea-appearance") {
|
|
|
201
135
|
return `${`(function(){try{var s=localStorage.getItem(${inlineScriptLiteral(storageKey)});var p=s?JSON.parse(s):{};var a=p.appearance||'system';var d=a==='dark'||(a==='system'&&window.matchMedia('(prefers-color-scheme: dark)').matches);var r=document.documentElement;if(d)r.classList.add('dark');r.style.colorScheme=d?'dark':'light';if(p.accent&&p.accent!=='theme')r.dataset.accent=p.accent;if(p.density==='compact')r.dataset.density='compact';}catch(e){}})();`}${fontSettingsBootstrapScript(storageKey)}`;
|
|
202
136
|
}
|
|
203
137
|
//#endregion
|
|
204
|
-
export { ThemeProvider, defaultThemeSelection, inlineScriptLiteral, resolvedDensity, themeScript, useTheme };
|
|
138
|
+
export { ThemeProvider, defaultThemeSelection, inlineScriptLiteral, localStoragePersistence, resolvedDensity, themeScript, useOptionalTheme, useTheme };
|
|
205
139
|
|
|
206
140
|
//# sourceMappingURL=theme-provider.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"theme-provider.js","names":["JSX","createContext","createEffect","createMemo","createSignal","onCleanup","splitProps","useContext","accentPresets","safeScriptStringLiteral","applyAppearanceFontSettings","DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS","fontSettingsBootstrapScript","normalizeAppearanceEditorFontSettings","AppearanceEditorFontSettings","AccentPreset","accentVariables","builtinThemes","defaultDarkThemeId","defaultLightThemeId","isThemeAccentId","themeAccentsFor","themeById","themeCssVariables","ThemeAppearance","ThemeVariant","ThemeSelection","appearance","lightThemeId","darkThemeId","accent","font","fonts","density","ThemeDensity","defaultThemeSelection","resolvedDensity","selection","ThemeContextValue","resolvedAppearance","variant","setSelection","patch","Partial","themes","themeAccents","ThemeContext","useTheme","value","Error","preferenceStore","Storage","localStorage","undefined","readSelection","storageKey","raw","getItem","parsed","JSON","parse","settings","some","preset","id","ui","family","mergeThemeSelection","base","merged","currentFonts","ThemeProviderProps","children","Element","initial","ThemeProvider","props","local","setSelectionState","incoming","current","systemAppearance","setSystemAppearance","window","matchMedia","query","matches","onChange","event","MediaQueryListEvent","addEventListener","removeEventListener","preference","document","root","documentElement","active","properties","Object","assign","name","entries","style","setProperty","classList","toggle","dataset","colorScheme","removeAttribute","next","setItem","stringify","_$createComponent","Provider","inlineScriptLiteral","themeScript","script","_$createComponent"],"sources":["../../../src/components/theme/theme-provider.tsx"],"sourcesContent":["import type { JSX } from 'solid-js'\nimport {\n createContext,\n createEffect,\n createMemo,\n createSignal,\n onCleanup,\n splitProps,\n useContext,\n} from 'solid-js'\nimport { accentPresets } from '#lib/tokens'\nimport { safeScriptStringLiteral } from '#lib/safe-script'\nimport {\n applyAppearanceFontSettings,\n DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS,\n fontSettingsBootstrapScript,\n normalizeAppearanceEditorFontSettings,\n type AppearanceEditorFontSettings,\n} from '#lib/appearance-font-settings'\nimport type { AccentPreset } from '@adea-ai/themes'\nimport {\n accentVariables,\n builtinThemes,\n defaultDarkThemeId,\n defaultLightThemeId,\n isThemeAccentId,\n themeAccentsFor,\n themeById,\n themeCssVariables,\n type ThemeAppearance,\n type ThemeVariant,\n} from '#lib/themes'\n\n/**\n * ThemeProvider.\n *\n * Owns the appearance preference and applies it to the document. One provider near\n * the root; everything below reads it.\n *\n * ## What a preference is\n *\n * Four independent choices, and keeping them independent is the point:\n *\n * - **appearance** — light, dark, or follow the system.\n * - **a theme per appearance** — so a user can run Catppuccin Mocha by night and\n * Solarized Light by day without re-choosing when the system flips.\n * - **an accent** — adea's six presets, or one of the accents the selected theme\n * pair carries itself (`ansi-blue`…), which re-colour the interactive roles on\n * top of whichever theme is active.\n * - **fonts** — separate family and size choices for UI, content and code.\n *\n * Four axes rather than one list of presets, because they compose: a user who wants\n * Nord with a violet accent and the system font should not need someone to author\n * that combination.\n *\n * ## Why the variants are applied as inline properties\n *\n * The catalogue is data, and a theme is applied by writing its roles onto\n * `<html>` as custom properties. That is what makes an imported palette work\n * without a hand-written `[data-theme]` block per theme, and it is why a settings\n * UI can show a preview by reading the same object rather than by loading a\n * stylesheet. `theme.css` keeps the default theme's values so the first paint is\n * correct before any script runs.\n */\nexport type ThemeSelection = {\n /** `system` follows `prefers-color-scheme` and updates when it changes. */\n appearance: ThemeAppearance | 'system'\n /** The variant to use when the resolved appearance is light. */\n lightThemeId: string\n /** The variant to use when the resolved appearance is dark. */\n darkThemeId: string\n /**\n * An `accentPresets` id, a theme accent id from `themeAccents()` (`ansi-blue`…),\n * or `theme` for the variant's own primary. A theme accent the current pair does\n * not offer falls back to the variant's own primary.\n */\n accent: string\n /** UI-family alias for consumers of the original single-font preference. */\n font: string\n /** UI, content and code font settings. Omitted legacy records are migrated from `font`. */\n fonts?: AppearanceEditorFontSettings\n /**\n * `comfortable` is the system's default geometry; `compact` moves the control\n * ladder down one rung.\n *\n * Optional, and defaulted on read, so a preference stored before density existed\n * keeps working and `ThemeSelection` stays assignable without it.\n */\n density?: ThemeDensity\n}\n\nexport const defaultThemeSelection: ThemeSelection = {\n appearance: 'system',\n lightThemeId: defaultLightThemeId,\n darkThemeId: defaultDarkThemeId,\n accent: 'theme',\n font: 'system',\n fonts: DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS,\n density: 'comfortable',\n}\n\n/**\n * The two density rungs.\n *\n * `comfortable` is the geometry in `theme.css`, so it is the absence of an\n * attribute rather than a value: a document that ships no `data-density` at all\n * renders correctly, which is what keeps this additive.\n */\nexport type ThemeDensity = 'comfortable' | 'compact'\n\n/**\n * A stored selection's density, defaulted.\n *\n * The stored value is read through here rather than trusted, because a preference\n * written before density existed has no `density` key and a hand-edited store may\n * hold anything.\n */\nexport function resolvedDensity(selection: ThemeSelection): ThemeDensity {\n return selection.density === 'compact' ? 'compact' : 'comfortable'\n}\n\nexport type ThemeContextValue = {\n /** The preference as stored. */\n selection: () => ThemeSelection\n /** What the preference resolves to right now, after `system`. */\n resolvedAppearance: () => ThemeAppearance\n /** The variant in use. */\n variant: () => ThemeVariant\n /** Update part of the preference. */\n setSelection: (patch: Partial<ThemeSelection>) => void\n /** The catalogue, so a picker does not import it separately. */\n themes: readonly ThemeVariant[]\n /**\n * The accents the selected light/dark pair carries, offered beside the presets.\n * Follows the selection: a different theme pair may offer different slots.\n */\n themeAccents: () => readonly AccentPreset[]\n}\n\nconst ThemeContext = createContext<ThemeContextValue>()\n\nexport function useTheme(): ThemeContextValue {\n const value = useContext(ThemeContext)\n if (!value) throw new Error('useTheme must be called inside a <ThemeProvider>.')\n return value\n}\n\n/**\n * The preference store, or nothing.\n *\n * Only ever called inside a `try`: where storage is blocked — a sandboxed iframe, a\n * privacy mode, a denied site-data permission — merely *reading* the `localStorage`\n * global throws (\"Access is denied\", `SecurityError`), so even the `typeof` guard\n * has to sit inside the `try` rather than in front of it. Without a store the\n * preference lives only in the provider's signal for the session.\n */\nfunction preferenceStore(): Storage | undefined {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n}\n\n/** The stored preference, validated against the catalogue. */\nfunction readSelection(storageKey: string): ThemeSelection {\n try {\n const raw = preferenceStore()?.getItem(storageKey)\n if (!raw) return defaultThemeSelection\n const parsed = JSON.parse(raw) as Partial<ThemeSelection>\n const fonts = normalizeAppearanceEditorFontSettings(parsed.fonts, parsed.font).settings\n return {\n appearance:\n parsed.appearance === 'light' ||\n parsed.appearance === 'dark' ||\n parsed.appearance === 'system'\n ? parsed.appearance\n : defaultThemeSelection.appearance,\n // An unknown id would leave the document with no theme at all, so a stale\n // preference from an older catalogue falls back rather than applying nothing.\n lightThemeId:\n themeById(parsed.lightThemeId ?? '')?.appearance === 'light'\n ? (parsed.lightThemeId as string)\n : defaultLightThemeId,\n darkThemeId:\n themeById(parsed.darkThemeId ?? '')?.appearance === 'dark'\n ? (parsed.darkThemeId as string)\n : defaultDarkThemeId,\n // A theme accent is kept whenever it names a slot, even one the stored pair\n // cannot offer: the id is role-shaped so it survives a theme switch, and an\n // unoffered slot already resolves to the theme's own primary when applied.\n accent:\n typeof parsed.accent === 'string' &&\n (accentPresets.some((preset) => preset.id === parsed.accent) ||\n isThemeAccentId(parsed.accent))\n ? parsed.accent\n : defaultThemeSelection.accent,\n font: fonts.ui.family,\n fonts,\n // Every axis has to be read back here, or it is lost twice: the effect below\n // removes the `data-density` that `themeScript` set for the first paint, and\n // the next `setSelection` rewrites the store without it.\n density: resolvedDensity(parsed as ThemeSelection),\n }\n } catch {\n return defaultThemeSelection\n }\n}\n\n/** Keep the deprecated single-font view synchronized with the UI axis. */\nfunction mergeThemeSelection(base: ThemeSelection, patch: Partial<ThemeSelection>): ThemeSelection {\n const merged = { ...base, ...patch }\n let fonts: AppearanceEditorFontSettings\n\n if (patch.fonts !== undefined) {\n fonts = normalizeAppearanceEditorFontSettings(patch.fonts).settings\n } else if (patch.font !== undefined) {\n const currentFonts = normalizeAppearanceEditorFontSettings(base.fonts, base.font).settings\n fonts = normalizeAppearanceEditorFontSettings({\n ...currentFonts,\n ui: { ...currentFonts.ui, family: patch.font },\n }).settings\n } else {\n fonts = normalizeAppearanceEditorFontSettings(merged.fonts, merged.font).settings\n }\n\n return { ...merged, fonts, font: fonts.ui.family }\n}\n\nexport type ThemeProviderProps = {\n children?: JSX.Element\n /** Where the preference is persisted. Distinct per application. */\n storageKey?: string\n /** Start from this instead of the stored preference. */\n initial?: Partial<ThemeSelection>\n /**\n * The selection, owned by the caller.\n *\n * For a consumer that keeps the state itself — a settings store, or a workshop\n * whose selection lives in Storybook globals — rather than handing it to this\n * provider's signal. Each change lands here and the document follows; nothing is\n * written to the store, because the caller is the one who persists. A picker\n * below the provider still works, and its change is the caller's to read back.\n *\n * Absent, the provider is the whole owner: it reads `storageKey` on mount,\n * seeds from `initial`, and persists every `setSelection`.\n */\n selection?: Partial<ThemeSelection>\n}\n\nexport function ThemeProvider(props: ThemeProviderProps) {\n const [local] = splitProps(props, ['children', 'storageKey', 'initial', 'selection'])\n const storageKey = () => local.storageKey ?? 'adea-appearance'\n\n const [selection, setSelectionState] = createSignal<ThemeSelection>(\n mergeThemeSelection(readSelection(storageKey()), local.initial ?? {})\n )\n\n // The controlled half of the contract. A patch from the owner replaces the\n // matching axes; the stored preference is untouched, since the owner is the one\n // that persists. Reading `local.selection` — a prop getter, not a destructured\n // value — is what keeps this subscribed for the provider's lifetime.\n createEffect(() => {\n const incoming = local.selection\n if (incoming) setSelectionState((current) => mergeThemeSelection(current, incoming))\n })\n\n const [systemAppearance, setSystemAppearance] = createSignal<ThemeAppearance>('light')\n\n if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {\n const query = window.matchMedia('(prefers-color-scheme: dark)')\n setSystemAppearance(query.matches ? 'dark' : 'light')\n const onChange = (event: MediaQueryListEvent) =>\n setSystemAppearance(event.matches ? 'dark' : 'light')\n query.addEventListener('change', onChange)\n onCleanup(() => query.removeEventListener('change', onChange))\n }\n\n const resolvedAppearance = createMemo<ThemeAppearance>(() => {\n const preference = selection().appearance\n if (preference === 'system') return systemAppearance()\n return preference\n })\n\n const variant = createMemo<ThemeVariant>(() => {\n const id = resolvedAppearance() === 'dark' ? selection().darkThemeId : selection().lightThemeId\n return themeById(id) ?? builtinThemes[0]!\n })\n\n createEffect(() => {\n if (typeof document === 'undefined') return\n const root = document.documentElement\n const active = variant()\n\n // The variant's roles, as properties. `--primary` and `--ring` are written here\n // too, and an accent selection is layered over them below.\n //\n // The accent is applied *here* rather than left to the `[data-accent]` blocks in\n // `theme.css`, because this loop writes inline custom properties and an inline\n // declaration outranks every stylesheet selector however specific it is. The\n // blocks still exist and are still correct — they are what styles the window\n // before this runs — but they cannot win from here, so leaving the accent to\n // them meant the attribute was set, the rules were present, and nothing\n // changed on screen.\n const properties = { ...themeCssVariables(active) }\n const accent = accentVariables(selection().accent, resolvedAppearance(), selection())\n if (accent) Object.assign(properties, accent)\n\n for (const [name, value] of Object.entries(properties)) {\n root.style.setProperty(name, value)\n }\n\n root.classList.toggle('dark', resolvedAppearance() === 'dark')\n root.dataset['theme'] = active.id\n root.dataset['appearance'] = resolvedAppearance()\n root.style.colorScheme = resolvedAppearance()\n\n if (!accent) root.removeAttribute('data-accent')\n else root.dataset['accent'] = selection().accent\n\n applyAppearanceFontSettings(\n root,\n normalizeAppearanceEditorFontSettings(selection().fonts, selection().font).settings\n )\n\n // Density is a pure token shift, so unlike the colour axes there is nothing to\n // compute: the attribute selects a block in `theme.css`. It is applied here for\n // the same reason as the others — this is the one place that knows what the\n // current selection is, and it is the only writer of these attributes.\n if (resolvedDensity(selection()) === 'comfortable') root.removeAttribute('data-density')\n else root.dataset['density'] = resolvedDensity(selection())\n })\n\n const themeAccents = createMemo(() =>\n themeAccentsFor(selection().lightThemeId, selection().darkThemeId)\n )\n\n const value: ThemeContextValue = {\n selection,\n resolvedAppearance,\n variant,\n themes: builtinThemes,\n themeAccents,\n setSelection(patch) {\n const next = mergeThemeSelection(selection(), patch)\n setSelectionState(next)\n try {\n preferenceStore()?.setItem(storageKey(), JSON.stringify(next))\n } catch {\n // A full, blocked or unavailable store must not break the switch: the\n // preference simply does not survive the reload.\n }\n },\n }\n\n return <ThemeContext.Provider value={value}>{local.children}</ThemeContext.Provider>\n}\n\n/**\n * A string as a JavaScript literal that is also safe inside an inline `<script>`.\n *\n * `JSON.stringify` produces a correct JavaScript literal, and it is **not** safe\n * here: it leaves `<` and `>` alone, so a value containing `</script>` ends the tag\n * early and everything after it is parsed as HTML. That is the classic inline-script\n * injection, and it is a real one even though the value is a developer-supplied prop\n * rather than user input — a prop can come from configuration, and a key that happens\n * to contain a closing tag should not be able to execute.\n *\n * The escape is also correct JavaScript: `\\u003c` is `<` to the parser, so the value\n * is byte-identical at runtime and inert to the HTML tokenizer. `\\u2028` and `\\u2029`\n * are escaped for the neighbouring reason — they are legal inside a JSON string and\n * were, before ES2019, line terminators to a JavaScript parser.\n *\n * CodeQL flags the unescaped form as `js/bad-code-sanitization`, which is how this\n * was found; `tests/theme-script.test.ts` pins it so it cannot come back.\n */\nexport function inlineScriptLiteral(value: string): string {\n return safeScriptStringLiteral(value)\n}\n\n/**\n * The no-flash script.\n *\n * Rendered inline in `<head>` before any stylesheet that matters. Without it a dark\n * preference paints the light theme first and then swaps, which is the flash every\n * themed application has to solve and the one thing a provider cannot do from\n * inside the body.\n *\n * Deliberately tiny and dependency-free: it reads the stored preference, resolves\n * `system`, and sets the class. It does not apply the variant's roles — the default\n * theme in `theme.css` covers the first paint, and the provider writes the rest on\n * mount.\n *\n * The script reads two values out of `localStorage` and writes them to `dataset`,\n * which is a *property* assignment rather than code: a stored accent or font id can\n * set an attribute and cannot execute. The one value that reaches the source as text\n * is `storageKey`, and it goes through {@link inlineScriptLiteral} for the reason\n * documented there.\n */\nexport function themeScript(storageKey = 'adea-appearance'): string {\n const script = `(function(){try{var s=localStorage.getItem(${inlineScriptLiteral(storageKey)});var p=s?JSON.parse(s):{};var a=p.appearance||'system';var d=a==='dark'||(a==='system'&&window.matchMedia('(prefers-color-scheme: dark)').matches);var r=document.documentElement;if(d)r.classList.add('dark');r.style.colorScheme=d?'dark':'light';if(p.accent&&p.accent!=='theme')r.dataset.accent=p.accent;if(p.density==='compact')r.dataset.density='compact';}catch(e){}})();`\n return `${script}${fontSettingsBootstrapScript(storageKey)}`\n}\n"],"mappings":";;;;;;;;AA2FA,IAAamC,wBAAwC;CACnDR,YAAY;CACZC,cAAcT;CACdU,aAAaX;CACbY,QAAQ;CACRC,MAAM;CACNC,OAAOrB;CACPsB,SAAS;AACX;;;;;;;;AAkBA,SAAgBG,gBAAgBC,WAAyC;CACvE,OAAOA,UAAUJ,YAAY,YAAY,YAAY;AACvD;AAoBA,IAAMa,eAAe7C,cAAiC;AAEtD,SAAgB8C,WAA8B;CAC5C,MAAMC,QAAQzC,WAAWuC,YAAY;CACrC,IAAI,CAACE,OAAO,MAAM,IAAIC,MAAM,mDAAmD;CAC/E,OAAOD;AACT;;;;;;;;;;AAWA,SAASE,kBAAuC;CAC9C,OAAO,OAAOE,iBAAiB,cAAcC,KAAAA,IAAYD;AAC3D;;AAGA,SAASE,cAAcC,YAAoC;CACzD,IAAI;EACF,MAAMC,MAAMN,gBAAgB,CAAC,EAAEO,QAAQF,UAAU;EACjD,IAAI,CAACC,KAAK,OAAOrB;EACjB,MAAMuB,SAASC,KAAKC,MAAMJ,GAAG;EAC7B,MAAMxB,QAAQnB,sCAAsC6C,OAAO1B,OAAO0B,OAAO3B,IAAI,CAAC,CAAC8B;EAC/E,OAAO;GACLlC,YACE+B,OAAO/B,eAAe,WACtB+B,OAAO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;;;;;;;;;;;;;;;;AAqBA,SAAgBmE,YAAY5D,aAAa,mBAA2B;CAElE,OAAO,GAAG6D,8CADmDF,oBAAoB3D,UAAU,EAAC,wXACzE3C,4BAA4B2C,UAAU;AAC3D"}
|
|
1
|
+
{"version":3,"file":"theme-provider.js","names":["JSX","createEffect","createMemo","createSignal","onCleanup","splitProps","safeScriptStringLiteral","fontSettingsBootstrapScript","builtinThemes","themeAccentsFor","ThemeAppearance","ThemeVariant","themeContext","applyThemeToRoot","applyWithoutTransitions","localStoragePersistence","readPersisted","writePersisted","ThemePersistence","initialThemeSelection","mergeRegistry","mergeThemeSelection","resolveThemeState","ThemeContextValue","ThemeSelection","useOptionalTheme","useTheme","defaultThemeSelection","resolvedDensity","ThemeDensity","ThemeProviderProps","children","Element","storageKey","initial","Partial","selection","persistence","themes","transformTokens","tokens","Record","disableTransitionOnChange","ThemeProvider","props","local","extraThemes","registry","setSelectionState","incoming","current","systemAppearance","setSystemAppearance","window","matchMedia","query","matches","onChange","event","MediaQueryListEvent","addEventListener","removeEventListener","committed","resolvedAppearance","appearance","variant","draft","setDraft","shownSelection","preview","shown","written","ReadonlySet","restoreTransitions","document","state","options","apply","documentElement","themeAccents","lightThemeId","darkThemeId","value","allThemes","next","undefined","previewing","setSelection","patch","Context","_$createComponent","Provider","inlineScriptLiteral","themeScript","script","_$createComponent"],"sources":["../../../src/components/theme/theme-provider.tsx"],"sourcesContent":["import type { JSX } from 'solid-js'\nimport { createEffect, createMemo, createSignal, onCleanup, splitProps } from 'solid-js'\nimport { safeScriptStringLiteral } from '#lib/safe-script'\nimport { fontSettingsBootstrapScript } from '#lib/appearance-font-settings'\nimport {\n builtinThemes,\n themeAccentsFor,\n type ThemeAppearance,\n type ThemeVariant,\n} from '#lib/themes'\nimport { themeContext } from './theme-context'\nimport { applyThemeToRoot, applyWithoutTransitions } from './theme-document'\nimport {\n localStoragePersistence,\n readPersisted,\n writePersisted,\n type ThemePersistence,\n} from './theme-persistence'\nimport {\n initialThemeSelection,\n mergeRegistry,\n mergeThemeSelection,\n resolveThemeState,\n type ThemeContextValue,\n type ThemeSelection,\n} from './theme-state'\n\nexport { useOptionalTheme, useTheme } from './theme-context'\nexport { localStoragePersistence, type ThemePersistence } from './theme-persistence'\nexport {\n defaultThemeSelection,\n resolvedDensity,\n type ThemeContextValue,\n type ThemeDensity,\n type ThemeSelection,\n} from './theme-state'\n\n/**\n * ThemeProvider.\n *\n * Owns the appearance preference and applies it to the document. One provider near\n * the root; everything below reads it.\n *\n * ## What a preference is\n *\n * Four independent choices (`ThemeSelection`), and keeping them independent is the\n * point: appearance, a theme per appearance, an accent and fonts. They compose: a\n * user who wants Nord with a violet accent and the system font should not need\n * someone to author that combination.\n *\n * ## Where the rules live\n *\n * This component is wiring. What a selection merges to and resolves to is\n * `theme-state.ts`; what lands on `<html>` is `theme-document.ts`; where the\n * preference is kept is `theme-persistence.ts`. Each is plain code a test can call,\n * which is the reason none of it is inlined here.\n *\n * ## Why the variants are applied as inline properties\n *\n * The catalogue is data, and a theme is applied by writing its roles onto\n * `<html>` as custom properties. That is what makes an imported palette work\n * without a hand-written `[data-theme]` block per theme, and it is why a settings\n * UI can show a preview by reading the same object rather than by loading a\n * stylesheet. `theme.css` keeps the default theme's values so the first paint is\n * correct before any script runs.\n */\nexport type ThemeProviderProps = {\n children?: JSX.Element\n /** Where the preference is persisted. Distinct per application. */\n storageKey?: string\n /** Start from this instead of the stored preference. */\n initial?: Partial<ThemeSelection>\n /**\n * The selection, owned by the caller.\n *\n * For a consumer that keeps the state itself — a settings store, or a workshop\n * whose selection lives in Storybook globals — rather than handing it to this\n * provider's signal. Each change lands here and the document follows; nothing is\n * written to the store, because the caller is the one who persists. A picker\n * below the provider still works, and its change is the caller's to read back.\n *\n * Absent, the provider is the whole owner: it reads `storageKey` on mount,\n * seeds from `initial`, and persists every `setSelection`.\n */\n selection?: Partial<ThemeSelection>\n /**\n * Where the preference is kept, in place of `localStorage` under `storageKey`.\n *\n * Read once when the provider is created, so changing the prop later does not\n * move the store. `storageKey` is ignored when this is given.\n */\n persistence?: ThemePersistence\n /**\n * Variants the host adds to the built-in catalogue — themes a user imported.\n *\n * A function is read inside the provider's reactive scope, so one that reads a\n * signal keeps the picker and the document current when the set changes. A\n * stored id that names no variant, built in or added, paints the default of its\n * appearance and stays in the selection untouched.\n */\n themes?: readonly ThemeVariant[] | (() => readonly ThemeVariant[])\n /**\n * Rewrites the custom properties of each pass before they are written to\n * `<html>`: the variant's roles with the accent over them. `tokensAsHex` from\n * `lib/themes` is the one the system ships.\n */\n transformTokens?: (tokens: Record<string, string>) => Record<string, string>\n /**\n * Switch CSS transitions off for the frame that carries a change, so a theme\n * switch cannot animate the whole page. Off by default: it adds a `<style>`\n * element to `<head>` for two frames on every change.\n */\n disableTransitionOnChange?: boolean\n}\n\nexport function ThemeProvider(props: ThemeProviderProps) {\n const [local] = splitProps(props, [\n 'children',\n 'storageKey',\n 'initial',\n 'selection',\n 'persistence',\n 'themes',\n 'transformTokens',\n 'disableTransitionOnChange',\n ])\n const storageKey = () => local.storageKey ?? 'adea-appearance'\n const persistence = local.persistence ?? localStoragePersistence(storageKey)\n\n // Read before the first resolution and before the store is, so a persistence whose\n // answer depends on the extras (an id it only accepts if the theme exists) sees\n // them.\n const extraThemes = createMemo(() =>\n typeof local.themes === 'function' ? local.themes() : (local.themes ?? [])\n )\n const registry = createMemo(() => mergeRegistry(builtinThemes, extraThemes()))\n\n const [selection, setSelectionState] = createSignal<ThemeSelection>(\n initialThemeSelection(readPersisted(persistence), local.initial)\n )\n\n // The controlled half of the contract. A patch from the owner replaces the\n // matching axes; the stored preference is untouched, since the owner is the one\n // that persists. Reading `local.selection` — a prop getter, not a destructured\n // value — is what keeps this subscribed for the provider's lifetime.\n createEffect(() => {\n const incoming = local.selection\n if (incoming) setSelectionState((current) => mergeThemeSelection(current, incoming))\n })\n\n const [systemAppearance, setSystemAppearance] = createSignal<ThemeAppearance>('light')\n\n if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {\n const query = window.matchMedia('(prefers-color-scheme: dark)')\n setSystemAppearance(query.matches ? 'dark' : 'light')\n const onChange = (event: MediaQueryListEvent) =>\n setSystemAppearance(event.matches ? 'dark' : 'light')\n query.addEventListener('change', onChange)\n onCleanup(() => query.removeEventListener('change', onChange))\n }\n\n // What the stored preference resolves to. `selection()`, `variant()` and\n // `resolvedAppearance()` answer from this and never from a preview, so a picker\n // that previews a draft still reads back what is committed.\n const committed = createMemo(() => resolveThemeState(selection(), systemAppearance(), registry()))\n const resolvedAppearance = createMemo<ThemeAppearance>(() => committed().appearance)\n const variant = createMemo<ThemeVariant>(() => committed().variant)\n\n const [draft, setDraft] = createSignal<Partial<ThemeSelection> | undefined>()\n const shownSelection = createMemo(() => {\n const preview = draft()\n return preview ? mergeThemeSelection(selection(), preview) : selection()\n })\n const shown = createMemo(() =>\n draft() ? resolveThemeState(shownSelection(), systemAppearance(), registry()) : committed()\n )\n\n let written: ReadonlySet<string> | undefined\n let restoreTransitions: (() => void) | undefined\n createEffect(() => {\n if (typeof document === 'undefined') return\n const state = {\n selection: shownSelection(),\n appearance: shown().appearance,\n variant: shown().variant,\n }\n const options = { transformTokens: local.transformTokens }\n const apply = () => {\n written = applyThemeToRoot(document.documentElement, state, options, written)\n }\n if (local.disableTransitionOnChange) {\n restoreTransitions?.()\n restoreTransitions = applyWithoutTransitions(document, apply)\n } else {\n apply()\n }\n })\n onCleanup(() => restoreTransitions?.())\n\n const themeAccents = createMemo(() =>\n themeAccentsFor(selection().lightThemeId, selection().darkThemeId)\n )\n\n const value: ThemeContextValue = {\n selection,\n resolvedAppearance,\n variant,\n themes: builtinThemes,\n themeAccents,\n allThemes: registry,\n preview(next) {\n setDraft(next ? { ...next } : undefined)\n },\n previewing: () => draft() !== undefined,\n setSelection(patch) {\n const next = mergeThemeSelection(selection(), patch)\n setSelectionState(next)\n // The committed selection is now what should be showing.\n setDraft(undefined)\n writePersisted(persistence, next)\n },\n }\n\n const Context = themeContext()\n return <Context.Provider value={value}>{local.children}</Context.Provider>\n}\n\n/**\n * A string as a JavaScript literal that is also safe inside an inline `<script>`.\n *\n * `JSON.stringify` produces a correct JavaScript literal, and it is **not** safe\n * here: it leaves `<` and `>` alone, so a value containing `</script>` ends the tag\n * early and everything after it is parsed as HTML. That is the classic inline-script\n * injection, and it is a real one even though the value is a developer-supplied prop\n * rather than user input — a prop can come from configuration, and a key that happens\n * to contain a closing tag should not be able to execute.\n *\n * The escape is also correct JavaScript: `\\u003c` is `<` to the parser, so the value\n * is byte-identical at runtime and inert to the HTML tokenizer. `\\u2028` and `\\u2029`\n * are escaped for the neighbouring reason — they are legal inside a JSON string and\n * were, before ES2019, line terminators to a JavaScript parser.\n *\n * CodeQL flags the unescaped form as `js/bad-code-sanitization`, which is how this\n * was found; `tests/theme-script.test.ts` pins it so it cannot come back.\n */\nexport function inlineScriptLiteral(value: string): string {\n return safeScriptStringLiteral(value)\n}\n\n/**\n * The no-flash script.\n *\n * Rendered inline in `<head>` before any stylesheet that matters. Without it a dark\n * preference paints the light theme first and then swaps, which is the flash every\n * themed application has to solve and the one thing a provider cannot do from\n * inside the body.\n *\n * Deliberately tiny and dependency-free: it reads the stored preference, resolves\n * `system`, and sets the class. It does not apply the variant's roles — the default\n * theme in `theme.css` covers the first paint, and the provider writes the rest on\n * mount.\n *\n * The script reads two values out of `localStorage` and writes them to `dataset`,\n * which is a *property* assignment rather than code: a stored accent or font id can\n * set an attribute and cannot execute. The one value that reaches the source as text\n * is `storageKey`, and it goes through {@link inlineScriptLiteral} for the reason\n * documented there.\n */\nexport function themeScript(storageKey = 'adea-appearance'): string {\n const script = `(function(){try{var s=localStorage.getItem(${inlineScriptLiteral(storageKey)});var p=s?JSON.parse(s):{};var a=p.appearance||'system';var d=a==='dark'||(a==='system'&&window.matchMedia('(prefers-color-scheme: dark)').matches);var r=document.documentElement;if(d)r.classList.add('dark');r.style.colorScheme=d?'dark':'light';if(p.accent&&p.accent!=='theme')r.dataset.accent=p.accent;if(p.density==='compact')r.dataset.density='compact';}catch(e){}})();`\n return `${script}${fontSettingsBootstrapScript(storageKey)}`\n}\n"],"mappings":";;;;;;;;;;AAmHA,SAAgB2C,cAAcC,OAA2B;CACvD,MAAM,CAACC,SAASxC,WAAWuC,OAAO;EAChC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAA2B,CAC5B;CACD,MAAMX,mBAAmBY,MAAMZ,cAAc;CAC7C,MAAMI,cAAcQ,MAAMR,eAAetB,wBAAwBkB,UAAU;CAK3E,MAAMa,cAAc5C,iBAClB,OAAO2C,MAAMP,WAAW,aAAaO,MAAMP,OAAO,IAAKO,MAAMP,UAAU,CAAA,CACzE;CACA,MAAMS,WAAW7C,iBAAiBkB,cAAcZ,eAAesC,YAAY,CAAC,CAAC;CAE7E,MAAM,CAACV,WAAWY,qBAAqB7C,aACrCgB,sBAAsBH,cAAcqB,WAAW,GAAGQ,MAAMX,OAAO,CACjE;CAMAjC,mBAAmB;EACjB,MAAMgD,WAAWJ,MAAMT;EACvB,IAAIa,UAAUD,mBAAmBE,YAAY7B,oBAAoB6B,SAASD,QAAQ,CAAC;CACrF,CAAC;CAED,MAAM,CAACE,kBAAkBC,uBAAuBjD,aAA8B,OAAO;CAErF,IAAI,OAAOkD,WAAW,eAAe,OAAOA,OAAOC,eAAe,YAAY;EAC5E,MAAMC,QAAQF,OAAOC,WAAW,8BAA8B;EAC9DF,oBAAoBG,MAAMC,UAAU,SAAS,OAAO;EACpD,MAAMC,YAAYC,UAChBN,oBAAoBM,MAAMF,UAAU,SAAS,OAAO;EACtDD,MAAMK,iBAAiB,UAAUH,QAAQ;EACzCrD,gBAAgBmD,MAAMM,oBAAoB,UAAUJ,QAAQ,CAAC;CAC/D;CAKA,MAAMK,YAAY5D,iBAAiBoB,kBAAkBc,UAAU,GAAGe,iBAAiB,GAAGJ,SAAS,CAAC,CAAC;CACjG,MAAMgB,qBAAqB7D,iBAAkC4D,UAAU,CAAC,CAACE,UAAU;CACnF,MAAMC,U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