@adea-ai/ui 0.123.1 → 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.
Files changed (57) hide show
  1. package/dist/NOTICE +18 -0
  2. package/dist/components/theme/appearance-panel.js +1 -1
  3. package/dist/components/theme/index.d.ts +1 -1
  4. package/dist/components/theme/index.d.ts.map +1 -1
  5. package/dist/components/theme/index.js +5 -2
  6. package/dist/components/theme/theme-context.d.ts +13 -0
  7. package/dist/components/theme/theme-context.d.ts.map +1 -0
  8. package/dist/components/theme/theme-context.js +41 -0
  9. package/dist/components/theme/theme-context.js.map +1 -0
  10. package/dist/components/theme/theme-document.d.ts +76 -0
  11. package/dist/components/theme/theme-document.d.ts.map +1 -0
  12. package/dist/components/theme/theme-document.js +93 -0
  13. package/dist/components/theme/theme-document.js.map +1 -0
  14. package/dist/components/theme/theme-persistence.d.ts +50 -0
  15. package/dist/components/theme/theme-persistence.d.ts.map +1 -0
  16. package/dist/components/theme/theme-persistence.js +86 -0
  17. package/dist/components/theme/theme-persistence.js.map +1 -0
  18. package/dist/components/theme/theme-provider.d.ts +43 -75
  19. package/dist/components/theme/theme-provider.d.ts.map +1 -1
  20. package/dist/components/theme/theme-provider.js +50 -116
  21. package/dist/components/theme/theme-provider.js.map +1 -1
  22. package/dist/components/theme/theme-state.d.ts +142 -0
  23. package/dist/components/theme/theme-state.d.ts.map +1 -0
  24. package/dist/components/theme/theme-state.js +104 -0
  25. package/dist/components/theme/theme-state.js.map +1 -0
  26. package/dist/components/theme/theme-toggle.js +1 -1
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +6 -3
  30. package/dist/lib/appearance-font-settings.d.ts +1 -1
  31. package/dist/lib/appearance-font-settings.d.ts.map +1 -1
  32. package/dist/lib/appearance-font-settings.js.map +1 -1
  33. package/dist/lib/themes.d.ts +48 -0
  34. package/dist/lib/themes.d.ts.map +1 -1
  35. package/dist/lib/themes.js +150 -36
  36. package/dist/lib/themes.js.map +1 -1
  37. package/dist/r/registry.json +20 -0
  38. package/dist/r/src/components/theme/index.ts +3 -0
  39. package/dist/r/src/components/theme/theme-context.ts +43 -0
  40. package/dist/r/src/components/theme/theme-document.ts +168 -0
  41. package/dist/r/src/components/theme/theme-persistence.ts +140 -0
  42. package/dist/r/src/components/theme/theme-provider.tsx +126 -253
  43. package/dist/r/src/components/theme/theme-state.ts +225 -0
  44. package/dist/r/src/lib/appearance-font-settings.ts +1 -1
  45. package/dist/r/src/lib/themes.ts +181 -40
  46. package/dist/r/theming.json +20 -0
  47. package/package.json +1 -1
  48. package/registry.json +20 -0
  49. package/src/components/theme/index.ts +3 -0
  50. package/src/components/theme/theme-context.ts +43 -0
  51. package/src/components/theme/theme-document.ts +168 -0
  52. package/src/components/theme/theme-persistence.ts +140 -0
  53. package/src/components/theme/theme-provider.tsx +126 -253
  54. package/src/components/theme/theme-state.ts +225 -0
  55. package/src/index.ts +3 -0
  56. package/src/lib/appearance-font-settings.ts +1 -1
  57. package/src/lib/themes.ts +181 -40
@@ -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;AAYnC,OAAO,EAKL,KAAK,4BAA4B,EAClC,MAAM,+BAA+B,CAAA;AACtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AACnD,OAAO,EASL,KAAK,eAAe,EACpB,KAAK,YAAY,EAClB,MAAM,aAAa,CAAA;AAEpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,2EAA2E;IAC3E,UAAU,EAAE,eAAe,GAAG,QAAQ,CAAA;IACtC,gEAAgE;IAChE,YAAY,EAAE,MAAM,CAAA;IACpB,+DAA+D;IAC/D,WAAW,EAAE,MAAM,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;;OAIG;IACH,eAAe,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC5E;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAA;CACpC,CAAA;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,kBAAkB,eA8GtD;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,WAAW,CAAC,UAAU,SAAoB,GAAG,MAAM,CAGlE"}
@@ -1,101 +1,29 @@
1
- import { accentPresets } from "../../lib/tokens.js";
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 { DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS, applyAppearanceFontSettings, fontSettingsBootstrapScript, normalizeAppearanceEditorFontSettings } from "../../lib/appearance-font-settings.js";
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 { createContext, createEffect, createMemo, createSignal, onCleanup, splitProps, useContext } from "solid-js";
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 [selection, setSelectionState] = createSignal(mergeThemeSelection(readSelection(storageKey()), local.initial ?? {}));
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 resolvedAppearance = createMemo(() => {
112
- const preference = selection().appearance;
113
- if (preference === "system") return systemAppearance();
114
- return preference;
115
- });
116
- const variant = createMemo(() => {
117
- const id = resolvedAppearance() === "dark" ? selection().darkThemeId : selection().lightThemeId;
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 root = document.documentElement;
123
- const active = variant();
124
- const properties = { ...themeCssVariables(active) };
125
- const accent = accentVariables(selection().accent, resolvedAppearance(), selection());
126
- if (accent) Object.assign(properties, accent);
127
- for (const [name, value] of Object.entries(properties)) root.style.setProperty(name, value);
128
- root.classList.toggle("dark", resolvedAppearance() === "dark");
129
- root.dataset["theme"] = active.id;
130
- root.dataset["appearance"] = resolvedAppearance();
131
- root.style.colorScheme = resolvedAppearance();
132
- if (!accent) root.removeAttribute("data-accent");
133
- else root.dataset["accent"] = selection().accent;
134
- applyAppearanceFontSettings(root, normalizeAppearanceEditorFontSettings(selection().fonts, selection().font).settings);
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
- try {
149
- preferenceStore()?.setItem(storageKey(), JSON.stringify(next));
150
- } catch {}
82
+ setDraft(void 0);
83
+ writePersisted(persistence, next);
151
84
  }
152
85
  };
153
- return createComponent(ThemeContext.Provider, {
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 `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AjF,sCAAsCwB,UAAU,CAAC,CAACL,OAAOK,UAAU,CAAC,CAACN,IAAI,CAAC,CAAC8B,QAC7E;EAMA,IAAIzB,gBAAgBC,UAAU,CAAC,MAAM,eAAeyD,KAAKc,gBAAgB,cAAc;OAClFd,KAAKY,QAAQ,aAAatE,gBAAgBC,UAAU,CAAC;CAC5D,CAAC;CAED,MAAMQ,eAAe1C,iBACnBkB,gBAAgBgB,UAAU,CAAC,CAACT,cAAcS,UAAU,CAAC,CAACR,WAAW,CACnE;CAEA,MAAMmB,QAA2B;EAC/BX;EACAE;EACAC;EACAI,QAAQ3B;EACR4B;EACAJ,aAAaC,OAAO;GAClB,MAAMmE,OAAO1C,oBAAoB9B,UAAU,GAAGK,KAAK;GACnDoC,kBAAkB+B,IAAI;GACtB,IAAI;IACF3D,gBAAgB,CAAC,EAAE4D,QAAQvD,WAAW,GAAGI,KAAKoD,UAAUF,IAAI,CAAC;GAC/D,QAAQ,CAEN;EAEJ;CACF;CAEA,OAAAG,gBAAQlE,aAAamE,UAAQ;EAAQjE;EAAK,IAAAwB,WAAA;GAAA,OAAGK,MAAML;EAAQ;CAAA,CAAA;AAC7D;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB0C,oBAAoBlE,OAAuB;CACzD,OAAOvC,wBAAwBuC,KAAK;AACtC;;;;;;;;;;;;;;;;;;;;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,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zE1B,4BAA4B0B,UAAU;AAC3D"}
@@ -0,0 +1,142 @@
1
+ import { type AppearanceEditorFontSettings } from '#lib/appearance-font-settings';
2
+ import type { AccentPreset } from '@adea-ai/themes';
3
+ import { type ThemeAppearance, type ThemeVariant } from '#lib/themes';
4
+ /**
5
+ * The pure half of the theme provider: what a selection is, how two selections
6
+ * merge, and what a selection resolves to.
7
+ *
8
+ * Nothing here touches the document, storage or a signal, so each rule can be
9
+ * tested by calling it. `ThemeProvider` owns the reactivity and wires these to it;
10
+ * `theme-document.ts` owns the writes; `theme-persistence.ts` owns the store.
11
+ */
12
+ /**
13
+ * Four independent choices, and keeping them independent is the point:
14
+ *
15
+ * - **appearance** — light, dark, or follow the system.
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.
22
+ */
23
+ export type ThemeSelection = {
24
+ /** `system` follows `prefers-color-scheme` and updates when it changes. */
25
+ appearance: ThemeAppearance | 'system';
26
+ /** The variant to use when the resolved appearance is light. */
27
+ lightThemeId: string;
28
+ /** The variant to use when the resolved appearance is dark. */
29
+ darkThemeId: string;
30
+ /**
31
+ * An `accentPresets` id, a theme accent id from `themeAccents()` (`ansi-blue`…),
32
+ * or `theme` for the variant's own primary. A theme accent the current pair does
33
+ * not offer falls back to the variant's own primary.
34
+ */
35
+ accent: string;
36
+ /** UI-family alias for consumers of the original single-font preference. */
37
+ font: string;
38
+ /** UI, content and code font settings. Omitted legacy records are migrated from `font`. */
39
+ fonts?: AppearanceEditorFontSettings;
40
+ /**
41
+ * `comfortable` is the system's default geometry; `compact` moves the control
42
+ * ladder down one rung.
43
+ *
44
+ * Optional, and defaulted on read, so a preference stored before density existed
45
+ * keeps working and `ThemeSelection` stays assignable without it.
46
+ */
47
+ density?: ThemeDensity;
48
+ };
49
+ /**
50
+ * The two density rungs.
51
+ *
52
+ * `comfortable` is the geometry in `theme.css`, so it is the absence of an
53
+ * attribute rather than a value: a document that ships no `data-density` at all
54
+ * renders correctly, which is what keeps this additive.
55
+ */
56
+ export type ThemeDensity = 'comfortable' | 'compact';
57
+ /**
58
+ * Deliberately lists only the fields every consumer has always had. A field added
59
+ * to {@link ThemeSelection} later gets no default here: `JSON.stringify` drops an
60
+ * `undefined`, so a store written by a consumer that never sets the field stays
61
+ * byte-identical to what it was before the field existed.
62
+ */
63
+ export declare const defaultThemeSelection: ThemeSelection;
64
+ /**
65
+ * A stored selection's density, defaulted.
66
+ *
67
+ * The stored value is read through here rather than trusted, because a preference
68
+ * written before density existed has no `density` key and a hand-edited store may
69
+ * hold anything.
70
+ */
71
+ export declare function resolvedDensity(selection: ThemeSelection): ThemeDensity;
72
+ export type ThemeContextValue = {
73
+ /** The preference as stored. A {@link ThemeContextValue.preview} does not change it. */
74
+ selection: () => ThemeSelection;
75
+ /** What the preference resolves to right now, after `system`. */
76
+ resolvedAppearance: () => ThemeAppearance;
77
+ /** The variant in use. */
78
+ variant: () => ThemeVariant;
79
+ /** Update part of the preference. */
80
+ setSelection: (patch: Partial<ThemeSelection>) => void;
81
+ /**
82
+ * The built-in catalogue, so a picker does not import it separately. A plain
83
+ * array: {@link ThemeContextValue.allThemes} is the one that follows a host's
84
+ * extra themes.
85
+ */
86
+ themes: readonly ThemeVariant[];
87
+ /**
88
+ * The accents the selected light/dark pair carries, offered beside the presets.
89
+ * Follows the selection: a different theme pair may offer different slots.
90
+ */
91
+ themeAccents: () => readonly AccentPreset[];
92
+ /**
93
+ * The built-in catalogue followed by the provider's `themes` prop. Reactive when
94
+ * that prop is a function that reads signals.
95
+ */
96
+ allThemes: () => readonly ThemeVariant[];
97
+ /**
98
+ * Paint the document from `draft` laid over the stored selection, without
99
+ * persisting it or changing what {@link ThemeContextValue.selection} returns.
100
+ * `undefined` ends the preview. A {@link ThemeContextValue.setSelection} ends it
101
+ * too, because the committed selection is then what should be showing.
102
+ */
103
+ preview: (draft: Partial<ThemeSelection> | undefined) => void;
104
+ /** True while a {@link ThemeContextValue.preview} draft is on the document. */
105
+ previewing: () => boolean;
106
+ };
107
+ /** Keep the deprecated single-font view synchronized with the UI axis. */
108
+ export declare function mergeThemeSelection(base: ThemeSelection, patch: Partial<ThemeSelection>): ThemeSelection;
109
+ /**
110
+ * The selection a provider starts from: the defaults, then whatever the store
111
+ * returned, then `initial`.
112
+ *
113
+ * `initial` wins over the store on every mount. That precedence is part of the
114
+ * contract Cortana relies on (its `initial` pins `appearance` and `font`), and it
115
+ * is why the store's answer is only the middle layer. A store that returned
116
+ * nothing, or threw, or answered with explicit `undefined`s, leaves the defaults
117
+ * standing for those fields.
118
+ */
119
+ export declare function initialThemeSelection(stored: Partial<ThemeSelection> | undefined, initial: Partial<ThemeSelection> | undefined): ThemeSelection;
120
+ /** `system` resolved against what the operating system reports. */
121
+ export declare function resolveAppearance(preference: ThemeSelection['appearance'], system: ThemeAppearance): ThemeAppearance;
122
+ /** The theme id the selection names for a resolved appearance. */
123
+ export declare function selectedThemeId(selection: ThemeSelection, appearance: ThemeAppearance): string;
124
+ /**
125
+ * What a selection paints: the resolved appearance and the variant for it.
126
+ *
127
+ * An id the registry does not hold resolves to the appearance's default rather than
128
+ * being rewritten (see `resolveVariant`), so the selection a host stores is never
129
+ * changed by being unresolvable.
130
+ */
131
+ export declare function resolveThemeState(selection: ThemeSelection, system: ThemeAppearance, registry: readonly ThemeVariant[]): {
132
+ appearance: ThemeAppearance;
133
+ variant: ThemeVariant;
134
+ };
135
+ /**
136
+ * The registry a provider resolves against: the catalogue, then the host's extras.
137
+ *
138
+ * The catalogue wins an id collision, because it is listed first and `resolveVariant`
139
+ * takes the first match: a host's variant can add a theme but cannot shadow one.
140
+ */
141
+ export declare function mergeRegistry(builtin: readonly ThemeVariant[], extra: readonly ThemeVariant[] | undefined): readonly ThemeVariant[];
142
+ //# sourceMappingURL=theme-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"theme-state.d.ts","sourceRoot":"","sources":["../../../src/components/theme/theme-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,4BAA4B,EAClC,MAAM,+BAA+B,CAAA;AACtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AACnD,OAAO,EAIL,KAAK,eAAe,EACpB,KAAK,YAAY,EAClB,MAAM,aAAa,CAAA;AAEpB;;;;;;;GAOG;AAEH;;;;;;;;;;GAUG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,2EAA2E;IAC3E,UAAU,EAAE,eAAe,GAAG,QAAQ,CAAA;IACtC,gEAAgE;IAChE,YAAY,EAAE,MAAM,CAAA;IACpB,+DAA+D;IAC/D,WAAW,EAAE,MAAM,CAAA;IACnB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAA;IACd,4EAA4E;IAC5E,IAAI,EAAE,MAAM,CAAA;IACZ,2FAA2F;IAC3F,KAAK,CAAC,EAAE,4BAA4B,CAAA;IACpC;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,YAAY,CAAA;CACvB,CAAA;AAED;;;;;;GAMG;AACH,MAAM,MAAM,YAAY,GAAG,aAAa,GAAG,SAAS,CAAA;AAEpD;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,EAAE,cAQnC,CAAA;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,cAAc,GAAG,YAAY,CAEvE;AAED,MAAM,MAAM,iBAAiB,GAAG;IAC9B,wFAAwF;IACxF,SAAS,EAAE,MAAM,cAAc,CAAA;IAC/B,iEAAiE;IACjE,kBAAkB,EAAE,MAAM,eAAe,CAAA;IACzC,0BAA0B;IAC1B,OAAO,EAAE,MAAM,YAAY,CAAA;IAC3B,qCAAqC;IACrC,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,cAAc,CAAC,KAAK,IAAI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EzB"}
@@ -0,0 +1,104 @@
1
+ import { defaultDarkThemeId, defaultLightThemeId, resolveVariant } from "../../lib/themes.js";
2
+ import { DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS, normalizeAppearanceEditorFontSettings } from "../../lib/appearance-font-settings.js";
3
+ //#region src/components/theme/theme-state.ts
4
+ /**
5
+ * Deliberately lists only the fields every consumer has always had. A field added
6
+ * to {@link ThemeSelection} later gets no default here: `JSON.stringify` drops an
7
+ * `undefined`, so a store written by a consumer that never sets the field stays
8
+ * byte-identical to what it was before the field existed.
9
+ */
10
+ var defaultThemeSelection = {
11
+ appearance: "system",
12
+ lightThemeId: defaultLightThemeId,
13
+ darkThemeId: defaultDarkThemeId,
14
+ accent: "theme",
15
+ font: "system",
16
+ fonts: DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS,
17
+ density: "comfortable"
18
+ };
19
+ /**
20
+ * A stored selection's density, defaulted.
21
+ *
22
+ * The stored value is read through here rather than trusted, because a preference
23
+ * written before density existed has no `density` key and a hand-edited store may
24
+ * hold anything.
25
+ */
26
+ function resolvedDensity(selection) {
27
+ return selection.density === "compact" ? "compact" : "comfortable";
28
+ }
29
+ /** A selection with the `undefined` keys of a patch left out. */
30
+ function definedOnly(value) {
31
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
32
+ }
33
+ /** Keep the deprecated single-font view synchronized with the UI axis. */
34
+ function mergeThemeSelection(base, patch) {
35
+ const merged = {
36
+ ...base,
37
+ ...patch
38
+ };
39
+ let fonts;
40
+ if (patch.fonts !== void 0) fonts = normalizeAppearanceEditorFontSettings(patch.fonts).settings;
41
+ else if (patch.font !== void 0) {
42
+ const currentFonts = normalizeAppearanceEditorFontSettings(base.fonts, base.font).settings;
43
+ fonts = normalizeAppearanceEditorFontSettings({
44
+ ...currentFonts,
45
+ ui: {
46
+ ...currentFonts.ui,
47
+ family: patch.font
48
+ }
49
+ }).settings;
50
+ } else fonts = normalizeAppearanceEditorFontSettings(merged.fonts, merged.font).settings;
51
+ return {
52
+ ...merged,
53
+ fonts,
54
+ font: fonts.ui.family
55
+ };
56
+ }
57
+ /**
58
+ * The selection a provider starts from: the defaults, then whatever the store
59
+ * returned, then `initial`.
60
+ *
61
+ * `initial` wins over the store on every mount. That precedence is part of the
62
+ * contract Cortana relies on (its `initial` pins `appearance` and `font`), and it
63
+ * is why the store's answer is only the middle layer. A store that returned
64
+ * nothing, or threw, or answered with explicit `undefined`s, leaves the defaults
65
+ * standing for those fields.
66
+ */
67
+ function initialThemeSelection(stored, initial) {
68
+ return mergeThemeSelection(mergeThemeSelection(defaultThemeSelection, definedOnly(stored ?? {})), initial ?? {});
69
+ }
70
+ /** `system` resolved against what the operating system reports. */
71
+ function resolveAppearance(preference, system) {
72
+ return preference === "system" ? system : preference;
73
+ }
74
+ /** The theme id the selection names for a resolved appearance. */
75
+ function selectedThemeId(selection, appearance) {
76
+ return appearance === "dark" ? selection.darkThemeId : selection.lightThemeId;
77
+ }
78
+ /**
79
+ * What a selection paints: the resolved appearance and the variant for it.
80
+ *
81
+ * An id the registry does not hold resolves to the appearance's default rather than
82
+ * being rewritten (see `resolveVariant`), so the selection a host stores is never
83
+ * changed by being unresolvable.
84
+ */
85
+ function resolveThemeState(selection, system, registry) {
86
+ const appearance = resolveAppearance(selection.appearance, system);
87
+ return {
88
+ appearance,
89
+ variant: resolveVariant(registry, selectedThemeId(selection, appearance), appearance)
90
+ };
91
+ }
92
+ /**
93
+ * The registry a provider resolves against: the catalogue, then the host's extras.
94
+ *
95
+ * The catalogue wins an id collision, because it is listed first and `resolveVariant`
96
+ * takes the first match: a host's variant can add a theme but cannot shadow one.
97
+ */
98
+ function mergeRegistry(builtin, extra) {
99
+ return extra && extra.length > 0 ? [...builtin, ...extra] : builtin;
100
+ }
101
+ //#endregion
102
+ export { defaultThemeSelection, initialThemeSelection, mergeRegistry, mergeThemeSelection, resolveAppearance, resolveThemeState, resolvedDensity, selectedThemeId };
103
+
104
+ //# sourceMappingURL=theme-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"theme-state.js","names":[],"sources":["../../../src/components/theme/theme-state.ts"],"sourcesContent":["import {\n DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS,\n normalizeAppearanceEditorFontSettings,\n type AppearanceEditorFontSettings,\n} from '#lib/appearance-font-settings'\nimport type { AccentPreset } from '@adea-ai/themes'\nimport {\n defaultDarkThemeId,\n defaultLightThemeId,\n resolveVariant,\n type ThemeAppearance,\n type ThemeVariant,\n} from '#lib/themes'\n\n/**\n * The pure half of the theme provider: what a selection is, how two selections\n * merge, and what a selection resolves to.\n *\n * Nothing here touches the document, storage or a signal, so each rule can be\n * tested by calling it. `ThemeProvider` owns the reactivity and wires these to it;\n * `theme-document.ts` owns the writes; `theme-persistence.ts` owns the store.\n */\n\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 */\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\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 * Deliberately lists only the fields every consumer has always had. A field added\n * to {@link ThemeSelection} later gets no default here: `JSON.stringify` drops an\n * `undefined`, so a store written by a consumer that never sets the field stays\n * byte-identical to what it was before the field existed.\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 * 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. A {@link ThemeContextValue.preview} does not change it. */\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 /**\n * The built-in catalogue, so a picker does not import it separately. A plain\n * array: {@link ThemeContextValue.allThemes} is the one that follows a host's\n * extra themes.\n */\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 * The built-in catalogue followed by the provider's `themes` prop. Reactive when\n * that prop is a function that reads signals.\n */\n allThemes: () => readonly ThemeVariant[]\n /**\n * Paint the document from `draft` laid over the stored selection, without\n * persisting it or changing what {@link ThemeContextValue.selection} returns.\n * `undefined` ends the preview. A {@link ThemeContextValue.setSelection} ends it\n * too, because the committed selection is then what should be showing.\n */\n preview: (draft: Partial<ThemeSelection> | undefined) => void\n /** True while a {@link ThemeContextValue.preview} draft is on the document. */\n previewing: () => boolean\n}\n\n/** A selection with the `undefined` keys of a patch left out. */\nfunction definedOnly<T extends object>(value: T): Partial<T> {\n return Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined)\n ) as Partial<T>\n}\n\n/** Keep the deprecated single-font view synchronized with the UI axis. */\nexport function mergeThemeSelection(\n base: ThemeSelection,\n patch: Partial<ThemeSelection>\n): 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\n/**\n * The selection a provider starts from: the defaults, then whatever the store\n * returned, then `initial`.\n *\n * `initial` wins over the store on every mount. That precedence is part of the\n * contract Cortana relies on (its `initial` pins `appearance` and `font`), and it\n * is why the store's answer is only the middle layer. A store that returned\n * nothing, or threw, or answered with explicit `undefined`s, leaves the defaults\n * standing for those fields.\n */\nexport function initialThemeSelection(\n stored: Partial<ThemeSelection> | undefined,\n initial: Partial<ThemeSelection> | undefined\n): ThemeSelection {\n const base = mergeThemeSelection(defaultThemeSelection, definedOnly(stored ?? {}))\n return mergeThemeSelection(base, initial ?? {})\n}\n\n/** `system` resolved against what the operating system reports. */\nexport function resolveAppearance(\n preference: ThemeSelection['appearance'],\n system: ThemeAppearance\n): ThemeAppearance {\n return preference === 'system' ? system : preference\n}\n\n/** The theme id the selection names for a resolved appearance. */\nexport function selectedThemeId(selection: ThemeSelection, appearance: ThemeAppearance): string {\n return appearance === 'dark' ? selection.darkThemeId : selection.lightThemeId\n}\n\n/**\n * What a selection paints: the resolved appearance and the variant for it.\n *\n * An id the registry does not hold resolves to the appearance's default rather than\n * being rewritten (see `resolveVariant`), so the selection a host stores is never\n * changed by being unresolvable.\n */\nexport function resolveThemeState(\n selection: ThemeSelection,\n system: ThemeAppearance,\n registry: readonly ThemeVariant[]\n): { appearance: ThemeAppearance; variant: ThemeVariant } {\n const appearance = resolveAppearance(selection.appearance, system)\n return {\n appearance,\n variant: resolveVariant(registry, selectedThemeId(selection, appearance), appearance),\n }\n}\n\n/**\n * The registry a provider resolves against: the catalogue, then the host's extras.\n *\n * The catalogue wins an id collision, because it is listed first and `resolveVariant`\n * takes the first match: a host's variant can add a theme but cannot shadow one.\n */\nexport function mergeRegistry(\n builtin: readonly ThemeVariant[],\n extra: readonly ThemeVariant[] | undefined\n): readonly ThemeVariant[] {\n return extra && extra.length > 0 ? [...builtin, ...extra] : builtin\n}\n"],"mappings":";;;;;;;;;AA4EA,IAAa,wBAAwC;CACnD,YAAY;CACZ,cAAc;CACd,aAAa;CACb,QAAQ;CACR,MAAM;CACN,OAAO;CACP,SAAS;AACX;;;;;;;;AASA,SAAgB,gBAAgB,WAAyC;CACvE,OAAO,UAAU,YAAY,YAAY,YAAY;AACvD;;AAuCA,SAAS,YAA8B,OAAsB;CAC3D,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS,CACjE;AACF;;AAGA,SAAgB,oBACd,MACA,OACgB;CAChB,MAAM,SAAS;EAAE,GAAG;EAAM,GAAG;CAAM;CACnC,IAAI;CAEJ,IAAI,MAAM,UAAU,KAAA,GAClB,QAAQ,sCAAsC,MAAM,KAAK,CAAC,CAAC;MACtD,IAAI,MAAM,SAAS,KAAA,GAAW;EACnC,MAAM,eAAe,sCAAsC,KAAK,OAAO,KAAK,IAAI,CAAC,CAAC;EAClF,QAAQ,sCAAsC;GAC5C,GAAG;GACH,IAAI;IAAE,GAAG,aAAa;IAAI,QAAQ,MAAM;GAAK;EAC/C,CAAC,CAAC,CAAC;CACL,OACE,QAAQ,sCAAsC,OAAO,OAAO,OAAO,IAAI,CAAC,CAAC;CAG3E,OAAO;EAAE,GAAG;EAAQ;EAAO,MAAM,MAAM,GAAG;CAAO;AACnD;;;;;;;;;;;AAYA,SAAgB,sBACd,QACA,SACgB;CAEhB,OAAO,oBADM,oBAAoB,uBAAuB,YAAY,UAAU,CAAC,CAAC,CACrD,GAAM,WAAW,CAAC,CAAC;AAChD;;AAGA,SAAgB,kBACd,YACA,QACiB;CACjB,OAAO,eAAe,WAAW,SAAS;AAC5C;;AAGA,SAAgB,gBAAgB,WAA2B,YAAqC;CAC9F,OAAO,eAAe,SAAS,UAAU,cAAc,UAAU;AACnE;;;;;;;;AASA,SAAgB,kBACd,WACA,QACA,UACwD;CACxD,MAAM,aAAa,kBAAkB,UAAU,YAAY,MAAM;CACjE,OAAO;EACL;EACA,SAAS,eAAe,UAAU,gBAAgB,WAAW,UAAU,GAAG,UAAU;CACtF;AACF;;;;;;;AAQA,SAAgB,cACd,SACA,OACyB;CACzB,OAAO,SAAS,MAAM,SAAS,IAAI,CAAC,GAAG,SAAS,GAAG,KAAK,IAAI;AAC9D"}
@@ -1,6 +1,6 @@
1
1
  import { cn } from "../../lib/utils.js";
2
2
  import { ToggleGroup, ToggleGroupItem } from "../ui/toggle-group/toggle-group.js";
3
- import { useTheme } from "./theme-provider.js";
3
+ import { useTheme } from "./theme-context.js";
4
4
  import { createComponent, insert, memo, mergeProps, template } from "solid-js/web";
5
5
  import { Monitor, Moon, Sun } from "lucide-solid";
6
6
  import { For, splitProps } from "solid-js";
package/dist/index.d.ts CHANGED
@@ -104,7 +104,7 @@ export * from './components/composites/help-center';
104
104
  export * from './components/composites/workspace-mark';
105
105
  export { cn } from './lib/utils';
106
106
  export { controlInteractive, controlSize, controlSizeIcon, controlSizes, cva, surfaceInteractive, type ControlSize, type VariantProps, } from './lib/variants';
107
- export { appearancePreviewThemes, builtinThemes, contrastRatio, defaultDarkThemeId, defaultLightThemeId, isThemeAccentId, resolveAccentPreset, themeAccentsFor, themeById, themeCssVariables, themeFamilies, themeRecordById, themeRecords, themesForAppearance, validateTheme, validateThemeRegistry, withAccent, type ThemeAppearance, type ThemeColors, type ThemeEditorPalette, type ThemeFinding, type ThemeProvenance, type ThemeTerminalPalette, type ThemeVariant, } from './lib/themes';
107
+ export { appearancePreviewThemes, builtinThemes, contrastRatio, defaultDarkThemeId, defaultLightThemeId, isThemeAccentId, resolveAccentPreset, resolveVariant, themeAccentsFor, themeById, themeCssVariables, themeFamilies, themeRecordById, themeRecords, themesForAppearance, tokensAsHex, validateTheme, validateThemeRegistry, variantFromRecord, withAccent, type ThemeAppearance, type ThemeColors, type ThemeEditorPalette, type ThemeFinding, type ThemeProvenance, type ThemeTerminalPalette, type ThemeVariant, } from './lib/themes';
108
108
  export { keyedRows, type KeyedRow } from './lib/keyed-rows';
109
109
  export { writeClipboardText } from './lib/clipboard';
110
110
  export { formatBytes, formatReleaseDate, plainTextFromMarkdown } from './lib/version-notes';