@adea-ai/ui 0.125.0 → 0.128.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 +40 -0
- 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 +4 -3
- package/dist/components/theme/theme-document.d.ts +37 -2
- package/dist/components/theme/theme-document.d.ts.map +1 -1
- package/dist/components/theme/theme-document.js +23 -3
- package/dist/components/theme/theme-document.js.map +1 -1
- package/dist/components/theme/theme-persistence.d.ts +87 -0
- package/dist/components/theme/theme-persistence.d.ts.map +1 -1
- package/dist/components/theme/theme-persistence.js +63 -2
- package/dist/components/theme/theme-persistence.js.map +1 -1
- package/dist/components/theme/theme-provider.d.ts +55 -41
- package/dist/components/theme/theme-provider.d.ts.map +1 -1
- package/dist/components/theme/theme-provider.js +59 -52
- package/dist/components/theme/theme-provider.js.map +1 -1
- package/dist/components/theme/theme-script.d.ts +100 -0
- package/dist/components/theme/theme-script.d.ts.map +1 -0
- package/dist/components/theme/theme-script.js +57 -0
- package/dist/components/theme/theme-script.js.map +1 -0
- package/dist/components/theme/theme-state.d.ts +58 -0
- package/dist/components/theme/theme-state.d.ts.map +1 -1
- package/dist/components/theme/theme-state.js +22 -1
- package/dist/components/theme/theme-state.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -4
- package/dist/lib/font-zoom.d.ts +25 -0
- package/dist/lib/font-zoom.d.ts.map +1 -0
- package/dist/lib/font-zoom.js +45 -0
- package/dist/lib/font-zoom.js.map +1 -0
- package/dist/lib/preference-store.d.ts +126 -0
- package/dist/lib/preference-store.d.ts.map +1 -0
- package/dist/lib/preference-store.js +126 -0
- package/dist/lib/preference-store.js.map +1 -0
- package/dist/lib/theme-surface.d.ts +71 -0
- package/dist/lib/theme-surface.d.ts.map +1 -0
- package/dist/lib/theme-surface.js +62 -0
- package/dist/lib/theme-surface.js.map +1 -0
- package/dist/lib/themes.d.ts +57 -1
- package/dist/lib/themes.d.ts.map +1 -1
- package/dist/lib/themes.js +81 -4
- package/dist/lib/themes.js.map +1 -1
- package/dist/lib/tokens.d.ts.map +1 -1
- package/dist/lib/tokens.js +15 -0
- package/dist/lib/tokens.js.map +1 -1
- package/dist/r/lib.json +15 -0
- package/dist/r/registry.json +26 -1
- package/dist/r/src/components/theme/index.ts +7 -0
- package/dist/r/src/components/theme/theme-document.ts +77 -2
- package/dist/r/src/components/theme/theme-persistence.ts +167 -0
- package/dist/r/src/components/theme/theme-provider.tsx +132 -50
- package/dist/r/src/components/theme/theme-script.ts +201 -0
- package/dist/r/src/components/theme/theme-state.ts +72 -0
- package/dist/r/src/lib/font-zoom.ts +74 -0
- package/dist/r/src/lib/preference-store.ts +216 -0
- package/dist/r/src/lib/theme-surface.ts +110 -0
- package/dist/r/src/lib/themes.ts +115 -2
- package/dist/r/src/lib/tokens.ts +17 -0
- package/dist/r/src/styles/theme-variants.css +3010 -0
- package/dist/r/src/styles/theme.css +38 -0
- package/dist/r/theme.json +6 -1
- package/dist/r/theming.json +5 -0
- package/package.json +2 -1
- package/registry.json +26 -1
- package/src/components/theme/index.ts +7 -0
- package/src/components/theme/theme-document.ts +77 -2
- package/src/components/theme/theme-persistence.ts +167 -0
- package/src/components/theme/theme-provider.tsx +132 -50
- package/src/components/theme/theme-script.ts +201 -0
- package/src/components/theme/theme-state.ts +72 -0
- package/src/index.ts +29 -0
- package/src/lib/font-zoom.ts +74 -0
- package/src/lib/preference-store.ts +216 -0
- package/src/lib/theme-surface.ts +110 -0
- package/src/lib/themes.ts +115 -2
- package/src/lib/tokens.ts +17 -0
- package/src/styles/theme-variants.css +3010 -0
- package/src/styles/theme.css +38 -0
|
@@ -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;AAInC,OAAO,
|
|
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,EAGL,KAAK,eAAe,EAEpB,KAAK,YAAY,EAClB,MAAM,aAAa,CAAA;AAGpB,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EASL,KAAK,cAAc,EACpB,MAAM,eAAe,CAAA;AAEtB,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAA;AAC5D,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,EACvB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACnB,KAAK,2BAA2B,GACjC,MAAM,qBAAqB,CAAA;AAC5B,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACtD,YAAY,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAClD,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AAC1F,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,KAAK,iBAAiB,EACtB,KAAK,YAAY,EACjB,KAAK,cAAc,GACpB,MAAM,eAAe,CAAA;AAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,EAAE,GAAG,CAAC,OAAO,CAAA;IACtB,mEAAmE;IACnE,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,wDAAwD;IACxD,OAAO,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IACjC;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IACnC;;;;;OAKG;IACH,WAAW,CAAC,EAAE,gBAAgB,CAAA;IAC9B;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,SAAS,YAAY,EAAE,GAAG,CAAC,MAAM,SAAS,YAAY,EAAE,CAAC,CAAA;IAClE;;;;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;IACnC;;;;;;;OAOG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG;QAAE,kBAAkB,CAAC,EAAE,OAAO,GAAG,CAAC,MAAM,OAAO,CAAC,CAAA;KAAE,CAAA;IACtE;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,QAAQ,GAAG,YAAY,CAAA;IACjC;;;;;;;;;;;OAWG;IACH,WAAW,CAAC,EAAE,eAAe,CAAA;IAC7B;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB,CAAA;AASD,wBAAgB,aAAa,CAAC,KAAK,EAAE,kBAAkB,eAqLtD"}
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import { builtinThemes, themeAccentsFor } from "../../lib/themes.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { fontZoomShortcut } from "../../lib/font-zoom.js";
|
|
3
|
+
import { REDUCED_TRANSPARENCY_QUERY, resolveSurfaceState } from "../../lib/theme-surface.js";
|
|
4
4
|
import { themeContext, useOptionalTheme, useTheme } from "./theme-context.js";
|
|
5
|
-
import { accentRolesForState, defaultThemeSelection, initialThemeSelection, mergeRegistry, mergeThemeSelection, resolveThemeState, resolvedDensity } from "./theme-state.js";
|
|
5
|
+
import { accentRolesForState, defaultThemeSelection, initialThemeSelection, mergeRegistry, mergeThemeSelection, resolveTerminalVariant, resolveThemeState, resolvedDensity, zoomedFontSettings } from "./theme-state.js";
|
|
6
6
|
import { applyThemeToRoot, applyWithoutTransitions } from "./theme-document.js";
|
|
7
|
-
import { localStoragePersistence, readPersisted, writePersisted } from "./theme-persistence.js";
|
|
7
|
+
import { createVersionedPersistence, localStoragePersistence, readPersisted, writePersisted } from "./theme-persistence.js";
|
|
8
|
+
import { inlineScriptLiteral, themeScript } from "./theme-script.js";
|
|
8
9
|
import { createComponent } from "solid-js/web";
|
|
9
|
-
import { createEffect, createMemo, createSignal, onCleanup, splitProps } from "solid-js";
|
|
10
|
+
import { createEffect, createMemo, createSignal, onCleanup, splitProps, untrack } from "solid-js";
|
|
10
11
|
//#region src/components/theme/theme-provider.tsx
|
|
12
|
+
/** The operating system's Reduce Transparency query, where there is a window to ask. */
|
|
13
|
+
function reducedTransparencyMedia() {
|
|
14
|
+
return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(REDUCED_TRANSPARENCY_QUERY) : void 0;
|
|
15
|
+
}
|
|
11
16
|
function ThemeProvider(props) {
|
|
12
17
|
const [local] = splitProps(props, [
|
|
13
18
|
"children",
|
|
@@ -18,7 +23,11 @@ function ThemeProvider(props) {
|
|
|
18
23
|
"themes",
|
|
19
24
|
"transformTokens",
|
|
20
25
|
"disableTransitionOnChange",
|
|
21
|
-
"accentContrastFloor"
|
|
26
|
+
"accentContrastFloor",
|
|
27
|
+
"surface",
|
|
28
|
+
"palette",
|
|
29
|
+
"editorRoles",
|
|
30
|
+
"fontZoom"
|
|
22
31
|
]);
|
|
23
32
|
const storageKey = () => local.storageKey ?? "adea-appearance";
|
|
24
33
|
const persistence = local.persistence ?? localStoragePersistence(storageKey);
|
|
@@ -46,6 +55,27 @@ function ThemeProvider(props) {
|
|
|
46
55
|
return preview ? mergeThemeSelection(selection(), preview) : selection();
|
|
47
56
|
});
|
|
48
57
|
const shown = createMemo(() => draft() ? resolveThemeState(shownSelection(), systemAppearance(), registry()) : committed());
|
|
58
|
+
const surfaceOn = (candidate) => local.surface === true || typeof local.surface === "object" || candidate.surface !== void 0;
|
|
59
|
+
const nativeTranslucency = () => {
|
|
60
|
+
const capability = typeof local.surface === "object" ? local.surface.nativeTranslucency : false;
|
|
61
|
+
return (typeof capability === "function" ? capability() : capability) === true;
|
|
62
|
+
};
|
|
63
|
+
const [osReducedTransparency, setOsReducedTransparency] = createSignal(surfaceOn(untrack(shownSelection)) ? reducedTransparencyMedia()?.matches ?? false : false);
|
|
64
|
+
const axisOn = createMemo(() => surfaceOn(shownSelection()));
|
|
65
|
+
createEffect(() => {
|
|
66
|
+
const query = axisOn() ? reducedTransparencyMedia() : void 0;
|
|
67
|
+
setOsReducedTransparency(query?.matches ?? false);
|
|
68
|
+
if (!query) return;
|
|
69
|
+
const onChange = (event) => setOsReducedTransparency(event.matches);
|
|
70
|
+
query.addEventListener("change", onChange);
|
|
71
|
+
onCleanup(() => query.removeEventListener("change", onChange));
|
|
72
|
+
});
|
|
73
|
+
const surfaceStateOf = (candidate) => resolveSurfaceState(candidate.surface, {
|
|
74
|
+
osReducedTransparency: osReducedTransparency(),
|
|
75
|
+
userReducedTransparency: candidate.reduceTransparency === true,
|
|
76
|
+
nativeTranslucency: nativeTranslucency()
|
|
77
|
+
});
|
|
78
|
+
const committedSurface = createMemo(() => surfaceOn(selection()) ? surfaceStateOf(selection()) : void 0);
|
|
49
79
|
let written;
|
|
50
80
|
let restoreTransitions;
|
|
51
81
|
createEffect(() => {
|
|
@@ -53,11 +83,15 @@ function ThemeProvider(props) {
|
|
|
53
83
|
const state = {
|
|
54
84
|
selection: shownSelection(),
|
|
55
85
|
appearance: shown().appearance,
|
|
56
|
-
variant: shown().variant
|
|
86
|
+
variant: shown().variant,
|
|
87
|
+
terminalVariant: resolveTerminalVariant(shownSelection().terminalThemeId, registry()),
|
|
88
|
+
surface: axisOn() ? surfaceStateOf(shownSelection()) : void 0
|
|
57
89
|
};
|
|
58
90
|
const options = {
|
|
59
91
|
transformTokens: local.transformTokens,
|
|
60
|
-
accentContrastFloor: local.accentContrastFloor
|
|
92
|
+
accentContrastFloor: local.accentContrastFloor,
|
|
93
|
+
palette: local.palette,
|
|
94
|
+
editorRoles: local.editorRoles
|
|
61
95
|
};
|
|
62
96
|
const apply = () => {
|
|
63
97
|
written = applyThemeToRoot(document.documentElement, state, options, written);
|
|
@@ -69,6 +103,19 @@ function ThemeProvider(props) {
|
|
|
69
103
|
});
|
|
70
104
|
onCleanup(() => restoreTransitions?.());
|
|
71
105
|
const themeAccents = createMemo(() => themeAccentsFor(selection().lightThemeId, selection().darkThemeId));
|
|
106
|
+
const zoomFonts = (intent) => value.setSelection({ fonts: zoomedFontSettings(selection(), intent) });
|
|
107
|
+
const onKeyDown = (event) => {
|
|
108
|
+
if (event.defaultPrevented) return;
|
|
109
|
+
const intent = fontZoomShortcut(event);
|
|
110
|
+
if (!intent) return;
|
|
111
|
+
event.preventDefault();
|
|
112
|
+
zoomFonts(intent);
|
|
113
|
+
};
|
|
114
|
+
createEffect(() => {
|
|
115
|
+
if (!local.fontZoom || typeof window === "undefined") return;
|
|
116
|
+
window.addEventListener("keydown", onKeyDown, { capture: true });
|
|
117
|
+
onCleanup(() => window.removeEventListener("keydown", onKeyDown, { capture: true }));
|
|
118
|
+
});
|
|
72
119
|
const value = {
|
|
73
120
|
selection,
|
|
74
121
|
resolvedAppearance,
|
|
@@ -86,6 +133,9 @@ function ThemeProvider(props) {
|
|
|
86
133
|
registry: registry(),
|
|
87
134
|
accentContrastFloor: local.accentContrastFloor
|
|
88
135
|
}),
|
|
136
|
+
effectiveSurface: () => committedSurface()?.surface ?? "opaque",
|
|
137
|
+
reduceTransparencyActive: () => committedSurface()?.reduceTransparencyActive ?? false,
|
|
138
|
+
zoomFonts,
|
|
89
139
|
setSelection(patch) {
|
|
90
140
|
const next = mergeThemeSelection(selection(), patch);
|
|
91
141
|
setSelectionState(next);
|
|
@@ -101,50 +151,7 @@ function ThemeProvider(props) {
|
|
|
101
151
|
}
|
|
102
152
|
});
|
|
103
153
|
}
|
|
104
|
-
/**
|
|
105
|
-
* A string as a JavaScript literal that is also safe inside an inline `<script>`.
|
|
106
|
-
*
|
|
107
|
-
* `JSON.stringify` produces a correct JavaScript literal, and it is **not** safe
|
|
108
|
-
* here: it leaves `<` and `>` alone, so a value containing `<\/script>` ends the tag
|
|
109
|
-
* early and everything after it is parsed as HTML. That is the classic inline-script
|
|
110
|
-
* injection, and it is a real one even though the value is a developer-supplied prop
|
|
111
|
-
* rather than user input — a prop can come from configuration, and a key that happens
|
|
112
|
-
* to contain a closing tag should not be able to execute.
|
|
113
|
-
*
|
|
114
|
-
* The escape is also correct JavaScript: `\u003c` is `<` to the parser, so the value
|
|
115
|
-
* is byte-identical at runtime and inert to the HTML tokenizer. `\u2028` and `\u2029`
|
|
116
|
-
* are escaped for the neighbouring reason — they are legal inside a JSON string and
|
|
117
|
-
* were, before ES2019, line terminators to a JavaScript parser.
|
|
118
|
-
*
|
|
119
|
-
* CodeQL flags the unescaped form as `js/bad-code-sanitization`, which is how this
|
|
120
|
-
* was found; `tests/theme-script.test.ts` pins it so it cannot come back.
|
|
121
|
-
*/
|
|
122
|
-
function inlineScriptLiteral(value) {
|
|
123
|
-
return safeScriptStringLiteral(value);
|
|
124
|
-
}
|
|
125
|
-
/**
|
|
126
|
-
* The no-flash script.
|
|
127
|
-
*
|
|
128
|
-
* Rendered inline in `<head>` before any stylesheet that matters. Without it a dark
|
|
129
|
-
* preference paints the light theme first and then swaps, which is the flash every
|
|
130
|
-
* themed application has to solve and the one thing a provider cannot do from
|
|
131
|
-
* inside the body.
|
|
132
|
-
*
|
|
133
|
-
* Deliberately tiny and dependency-free: it reads the stored preference, resolves
|
|
134
|
-
* `system`, and sets the class. It does not apply the variant's roles — the default
|
|
135
|
-
* theme in `theme.css` covers the first paint, and the provider writes the rest on
|
|
136
|
-
* mount.
|
|
137
|
-
*
|
|
138
|
-
* The script reads two values out of `localStorage` and writes them to `dataset`,
|
|
139
|
-
* which is a *property* assignment rather than code: a stored accent or font id can
|
|
140
|
-
* set an attribute and cannot execute. The one value that reaches the source as text
|
|
141
|
-
* is `storageKey`, and it goes through {@link inlineScriptLiteral} for the reason
|
|
142
|
-
* documented there.
|
|
143
|
-
*/
|
|
144
|
-
function themeScript(storageKey = "adea-appearance") {
|
|
145
|
-
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)}`;
|
|
146
|
-
}
|
|
147
154
|
//#endregion
|
|
148
|
-
export { ThemeProvider, defaultThemeSelection, inlineScriptLiteral, localStoragePersistence, resolvedDensity, themeScript, useOptionalTheme, useTheme };
|
|
155
|
+
export { ThemeProvider, createVersionedPersistence, defaultThemeSelection, inlineScriptLiteral, localStoragePersistence, resolvedDensity, themeScript, useOptionalTheme, useTheme };
|
|
149
156
|
|
|
150
157
|
//# sourceMappingURL=theme-provider.js.map
|
|
@@ -1 +1 @@
|
|
|
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","accentRolesForState","initialThemeSelection","mergeRegistry","mergeThemeSelection","resolveThemeState","ThemeContextValue","ThemeSelection","useOptionalTheme","useTheme","defaultThemeSelection","resolvedDensity","ThemeDensity","ThemeProviderProps","children","Element","storageKey","initial","Partial","selection","persistence","themes","transformTokens","tokens","Record","disableTransitionOnChange","accentContrastFloor","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","accentRolesFor","accent","variantId","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 accentRolesForState,\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 * The contrast ratio an accent is held to against the variant's background,\n * repaired to the nearest passing colour when it falls short. Absent, presets\n * are painted verbatim — the catalogue measured them for its own themes — and\n * only a custom `#rrggbb` is held to 3:1. A host that adds themes the catalogue\n * never measured passes 3 to hold the presets to it as well; for the catalogue's\n * own themes the floor changes no preset.\n */\n accentContrastFloor?: number\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 'accentContrastFloor',\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 = {\n transformTokens: local.transformTokens,\n accentContrastFloor: local.accentContrastFloor,\n }\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 accentRolesFor: (accent, variantId) =>\n accentRolesForState(accent, variantId, {\n selection: selection(),\n variant: variant(),\n registry: registry(),\n accentContrastFloor: local.accentContrastFloor,\n }),\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":";;;;;;;;;;AA6HA,SAAgB6C,cAAcC,OAA2B;CACvD,MA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AAoBe,UAAU,GAAGwD,KAAK;GACnD3C,kBAAkBoC,IAAI;GAEtBjB,SAASkB,KAAAA,CAAS;GAClBtE,eAAeqB,aAAagD,IAAI;EAClC;CACF;CAEA,MAAMQ,UAAUlF,aAAa;CAC7B,OAAAmF,gBAAQD,QAAQE,UAAQ;EAAQZ;EAAK,IAAApD,WAAA;GAAA,OAAGe,MAAMf;EAAQ;CAAA,CAAA;AACxD;;;;;;;;;;;;;;;;;;;AAoBA,SAAgBiE,oBAAoBb,OAAuB;CACzD,OAAO9E,wBAAwB8E,KAAK;AACtC;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgBc,YAAYhE,aAAa,mBAA2B;CAElE,OAAO,GAAGiE,8CADmDF,oBAAoB/D,UAAU,EAAC,wXACzE3B,4BAA4B2B,UAAU;AAC3D"}
|
|
1
|
+
{"version":3,"file":"theme-provider.js","names":["JSX","createEffect","createMemo","createSignal","onCleanup","splitProps","untrack","fontZoomShortcut","FontZoomIntent","REDUCED_TRANSPARENCY_QUERY","resolveSurfaceState","builtinThemes","themeAccentsFor","EditorRolesMode","ThemeAppearance","ThemeVariant","themeContext","applyThemeToRoot","applyWithoutTransitions","localStoragePersistence","readPersisted","writePersisted","ThemePersistence","accentRolesForState","initialThemeSelection","mergeRegistry","mergeThemeSelection","resolveTerminalVariant","resolveThemeState","zoomedFontSettings","ThemeContextValue","ThemeSelection","useOptionalTheme","useTheme","createVersionedPersistence","ThemeStorageSchema","VersionedCodec","VersionedPersistenceOptions","ThemeSurface","inlineScriptLiteral","themeScript","ThemeScriptOptions","defaultThemeSelection","resolvedDensity","ThemeDensity","ThemeProviderProps","children","Element","storageKey","initial","Partial","selection","persistence","themes","transformTokens","tokens","Record","disableTransitionOnChange","accentContrastFloor","surface","nativeTranslucency","palette","editorRoles","fontZoom","reducedTransparencyMedia","MediaQueryList","window","matchMedia","undefined","ThemeProvider","props","local","extraThemes","registry","setSelectionState","incoming","current","systemAppearance","setSystemAppearance","query","matches","onChange","event","MediaQueryListEvent","addEventListener","removeEventListener","committed","resolvedAppearance","appearance","variant","draft","setDraft","shownSelection","preview","shown","surfaceOn","candidate","capability","osReducedTransparency","setOsReducedTransparency","axisOn","surfaceStateOf","userReducedTransparency","reduceTransparency","committedSurface","written","ReadonlySet","restoreTransitions","document","state","terminalVariant","terminalThemeId","options","apply","documentElement","themeAccents","lightThemeId","darkThemeId","zoomFonts","intent","value","setSelection","fonts","onKeyDown","KeyboardEvent","defaultPrevented","preventDefault","capture","allThemes","next","previewing","accentRolesFor","accent","variantId","effectiveSurface","reduceTransparencyActive","patch","Context","_$createComponent","Provider","_$createComponent"],"sources":["../../../src/components/theme/theme-provider.tsx"],"sourcesContent":["import type { JSX } from 'solid-js'\nimport { createEffect, createMemo, createSignal, onCleanup, splitProps, untrack } from 'solid-js'\nimport { fontZoomShortcut, type FontZoomIntent } from '#lib/font-zoom'\nimport { REDUCED_TRANSPARENCY_QUERY, resolveSurfaceState } from '#lib/theme-surface'\nimport {\n builtinThemes,\n themeAccentsFor,\n type EditorRolesMode,\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 accentRolesForState,\n initialThemeSelection,\n mergeRegistry,\n mergeThemeSelection,\n resolveTerminalVariant,\n resolveThemeState,\n zoomedFontSettings,\n type ThemeContextValue,\n type ThemeSelection,\n} from './theme-state'\n\nexport { useOptionalTheme, useTheme } from './theme-context'\nexport {\n createVersionedPersistence,\n localStoragePersistence,\n type ThemePersistence,\n type ThemeStorageSchema,\n type VersionedCodec,\n type VersionedPersistenceOptions,\n} from './theme-persistence'\nexport type { ThemeSurface } from '#lib/theme-surface'\nexport type { EditorRolesMode } from '#lib/themes'\nexport { inlineScriptLiteral, themeScript, type ThemeScriptOptions } from './theme-script'\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 * The contrast ratio an accent is held to against the variant's background,\n * repaired to the nearest passing colour when it falls short. Absent, presets\n * are painted verbatim — the catalogue measured them for its own themes — and\n * only a custom `#rrggbb` is held to 3:1. A host that adds themes the catalogue\n * never measured passes 3 to hold the presets to it as well; for the catalogue's\n * own themes the floor changes no preset.\n */\n accentContrastFloor?: number\n /**\n * Turns the surface axis on: `selection.surface` and `selection.reduceTransparency`\n * are resolved against the operating system's Reduce Transparency setting and the\n * host's capability, and `data-surface`, `data-reduce-transparency` and\n * `--surface-alpha` are written to `<html>` (the frost rule in `theme.css` reads\n * them). Off by default: a provider that never opts in writes none of them, adds no\n * media-query listener, and stores nothing new.\n *\n * An object also states the host's capability. `nativeTranslucency` is whether the\n * window can render the OS's own translucency; without it a `translucent`\n * preference paints the tokenized `frosted` surface instead of pretending to\n * vibrancy. A function is read inside the provider's reactive scope, for a\n * capability that is learned after mount.\n *\n * A selection that already carries a `surface` turns the axis on for itself, so a\n * host that stores the field gets the same document without the prop.\n */\n surface?: boolean | { nativeTranslucency?: boolean | (() => boolean) }\n /**\n * Where a catalogue variant's palette comes from. `inline` (the default) writes\n * every role onto `<html>`. `stylesheet` leaves a catalogue variant to the host's\n * `[data-theme]` stylesheet and writes inline only what no stylesheet can know: a\n * host's own `themes`, the accent, the pinned terminal palette, the surface alpha\n * and the fonts. Switching from a host variant back to a catalogue one removes the\n * properties the host variant wrote.\n */\n palette?: 'inline' | 'stylesheet'\n /**\n * The projection behind the `--editor-*` ramp. `syntax` (the default) is the\n * catalogue's quiet syntax roles, a comment among them deliberately below\n * body-text contrast. `floor` holds all sixteen roles to 4.5:1 on the canvas, as\n * hex, for a host that renders code as content (a diff, a file view) rather than\n * as decoration.\n *\n * Applies to catalogue variants; a host's own `themes` keep their `editor` and\n * their `tokens`. With `palette=\"stylesheet\"` it is the one palette property a\n * catalogue variant still writes inline, because `theme-variants.css` is generated\n * for `syntax`. Absent, nothing changes.\n */\n editorRoles?: EditorRolesMode\n /**\n * Bind the platform zoom chords (Cmd or Ctrl with `=`, `+`, `-`, `0`) to the three\n * text sizes instead of the browser's page zoom: stepping them together is zoom\n * inside the persisted type system. Off by default: it adds a capturing `keydown`\n * listener to `window`, and an event already handled elsewhere is left alone.\n * `zoomFonts` on the context does the same from a menu or a host's own binding.\n */\n fontZoom?: boolean\n}\n\n/** The operating system's Reduce Transparency query, where there is a window to ask. */\nfunction reducedTransparencyMedia(): MediaQueryList | undefined {\n return typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia(REDUCED_TRANSPARENCY_QUERY)\n : undefined\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 'accentContrastFloor',\n 'surface',\n 'palette',\n 'editorRoles',\n 'fontZoom',\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 // The surface axis. Off, none of this reads the operating system: the media query\n // is subscribed only while the axis is on, so a provider that never opts in adds no\n // listener and no repaint.\n const surfaceOn = (candidate: ThemeSelection) =>\n local.surface === true || typeof local.surface === 'object' || candidate.surface !== undefined\n const nativeTranslucency = () => {\n const capability = typeof local.surface === 'object' ? local.surface.nativeTranslucency : false\n return (typeof capability === 'function' ? capability() : capability) === true\n }\n const [osReducedTransparency, setOsReducedTransparency] = createSignal(\n surfaceOn(untrack(shownSelection)) ? (reducedTransparencyMedia()?.matches ?? false) : false\n )\n const axisOn = createMemo(() => surfaceOn(shownSelection()))\n createEffect(() => {\n const query = axisOn() ? reducedTransparencyMedia() : undefined\n setOsReducedTransparency(query?.matches ?? false)\n if (!query) return\n const onChange = (event: MediaQueryListEvent) => setOsReducedTransparency(event.matches)\n query.addEventListener('change', onChange)\n onCleanup(() => query.removeEventListener('change', onChange))\n })\n const surfaceStateOf = (candidate: ThemeSelection) =>\n resolveSurfaceState(candidate.surface, {\n osReducedTransparency: osReducedTransparency(),\n userReducedTransparency: candidate.reduceTransparency === true,\n nativeTranslucency: nativeTranslucency(),\n })\n const committedSurface = createMemo(() =>\n surfaceOn(selection()) ? surfaceStateOf(selection()) : undefined\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 terminalVariant: resolveTerminalVariant(shownSelection().terminalThemeId, registry()),\n surface: axisOn() ? surfaceStateOf(shownSelection()) : undefined,\n }\n const options = {\n transformTokens: local.transformTokens,\n accentContrastFloor: local.accentContrastFloor,\n palette: local.palette,\n editorRoles: local.editorRoles,\n }\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 zoomFonts = (intent: FontZoomIntent) =>\n value.setSelection({ fonts: zoomedFontSettings(selection(), intent) })\n\n // The platform zoom chords drive the three text sizes, captured like the other\n // global chords; an event something else already handled never double-steps.\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.defaultPrevented) return\n const intent = fontZoomShortcut(event)\n if (!intent) return\n event.preventDefault()\n zoomFonts(intent)\n }\n createEffect(() => {\n if (!local.fontZoom || typeof window === 'undefined') return\n window.addEventListener('keydown', onKeyDown, { capture: true })\n onCleanup(() => window.removeEventListener('keydown', onKeyDown, { capture: true }))\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 accentRolesFor: (accent, variantId) =>\n accentRolesForState(accent, variantId, {\n selection: selection(),\n variant: variant(),\n registry: registry(),\n accentContrastFloor: local.accentContrastFloor,\n }),\n effectiveSurface: () => committedSurface()?.surface ?? 'opaque',\n reduceTransparencyActive: () => committedSurface()?.reduceTransparencyActive ?? false,\n zoomFonts,\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"],"mappings":";;;;;;;;;;;;AA2LA,SAASgE,2BAAuD;CAC9D,OAAO,OAAOE,WAAW,eAAe,OAAOA,OAAOC,eAAe,aACjED,OAAOC,WAAW1D,0BAA0B,IAC5C2D,KAAAA;AACN;AAEA,SAAgBC,cAAcC,OAA2B;CACvD,MAAM,CAACC,SAASlE,WAAWiE,OAAO;EAChC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAAU,CACX;CACD,MAAMtB,mBAAmBuB,MAAMvB,cAAc;CAC7C,MAAMI,cAAcmB,MAAMnB,eAAejC,wBAAwB6B,UAAU;CAK3E,MAAMwB,cAActE,iBAClB,OAAOqE,MAAMlB,WAAW,aAAakB,MAAMlB,OAAO,IAAKkB,MAAMlB,UAAU,CAAA,CACzE;CACA,MAAMoB,WAAWvE,iBAAiBuB,cAAcd,eAAe6D,YAAY,CAAC,CAAC;CAE7E,MAAM,CAACrB,WAAWuB,qBAAqBvE,aACrCqB,sBAAsBJ,cAAcgC,WAAW,GAAGmB,MAAMtB,OAAO,CACjE;CAMAhD,mBAAmB;EACjB,MAAM0E,WAAWJ,MAAMpB;EACvB,IAAIwB,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ChFjB;EACAG,aAAae,OAAO;GAClB,MAAMP,OAAOvG,oBAAoByB,UAAU,GAAGqF,KAAK;GACnD9D,kBAAkBuD,IAAI;GAEtBtC,SAASvB,KAAAA,CAAS;GAClB/C,eAAe+B,aAAa6E,IAAI;EAClC;CACF;CAEA,MAAMQ,UAAUzH,aAAa;CAC7B,OAAA0H,gBAAQD,QAAQE,UAAQ;EAAQnB;EAAK,IAAA1E,WAAA;GAAA,OAAGyB,MAAMzB;EAAQ;CAAA,CAAA;AACxD"}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { ThemeStorageSchema } from './theme-persistence';
|
|
2
|
+
/**
|
|
3
|
+
* A string as a JavaScript literal that is also safe inside an inline `<script>`.
|
|
4
|
+
*
|
|
5
|
+
* `JSON.stringify` produces a correct JavaScript literal, and it is **not** safe
|
|
6
|
+
* here: it leaves `<` and `>` alone, so a value containing `</script>` ends the tag
|
|
7
|
+
* early and everything after it is parsed as HTML. That is the classic inline-script
|
|
8
|
+
* injection, and it is a real one even though the value is a developer-supplied prop
|
|
9
|
+
* rather than user input — a prop can come from configuration, and a key that happens
|
|
10
|
+
* to contain a closing tag should not be able to execute.
|
|
11
|
+
*
|
|
12
|
+
* The escape is also correct JavaScript: `\u003c` is `<` to the parser, so the value
|
|
13
|
+
* is byte-identical at runtime and inert to the HTML tokenizer. `\u2028` and `\u2029`
|
|
14
|
+
* are escaped for the neighbouring reason — they are legal inside a JSON string and
|
|
15
|
+
* were, before ES2019, line terminators to a JavaScript parser.
|
|
16
|
+
*
|
|
17
|
+
* CodeQL flags the unescaped form as `js/bad-code-sanitization`, which is how this
|
|
18
|
+
* was found; `tests/theme-script.test.ts` pins it so it cannot come back.
|
|
19
|
+
*/
|
|
20
|
+
export declare function inlineScriptLiteral(value: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* Options for the host-shaped no-flash script: the document's {@link ThemeStorageSchema}
|
|
23
|
+
* plus what the script paints from it.
|
|
24
|
+
*/
|
|
25
|
+
export type ThemeScriptOptions = ThemeStorageSchema & {
|
|
26
|
+
/**
|
|
27
|
+
* The accent painted when the document has none, an unrecognised one, or the
|
|
28
|
+
* legacy `theme` spelling — the host's default (adea: `violet`). Without it those
|
|
29
|
+
* cases paint no `data-accent`, which is what the provider writes for `theme`.
|
|
30
|
+
* Setting it means the `[data-accent]` block of the default preset paints on the
|
|
31
|
+
* first frame instead of after hydration.
|
|
32
|
+
*/
|
|
33
|
+
defaultAccent?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Also resolve the surface axis (`data-surface`, `data-reduce-transparency`,
|
|
36
|
+
* `--surface-alpha`) from the document and the operating system's Reduce
|
|
37
|
+
* Transparency setting. A `translucent` preference resolves to `frosted`: the
|
|
38
|
+
* host's translucency capability is not known until the provider mounts, and the
|
|
39
|
+
* provider re-resolves it then. Match the provider's `surface` prop.
|
|
40
|
+
*/
|
|
41
|
+
surface?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Match the provider's `palette` prop. The attributes written are the same either
|
|
44
|
+
* way: a catalogue variant's palette is the host stylesheet's job (`stylesheet`) or
|
|
45
|
+
* the provider's, at mount (`inline`), and a stored theme's own tokens are written
|
|
46
|
+
* inline in both.
|
|
47
|
+
*/
|
|
48
|
+
palette?: 'inline' | 'stylesheet';
|
|
49
|
+
/** The only `version` of the library document read. Default `1`. */
|
|
50
|
+
libraryVersion?: number;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* The no-flash script.
|
|
54
|
+
*
|
|
55
|
+
* Rendered inline in `<head>` before any stylesheet that matters. Without it a dark
|
|
56
|
+
* preference paints the light theme first and then swaps, which is the flash every
|
|
57
|
+
* themed application has to solve and the one thing a provider cannot do from
|
|
58
|
+
* inside the body.
|
|
59
|
+
*
|
|
60
|
+
* ## The string form
|
|
61
|
+
*
|
|
62
|
+
* `themeScript('key')` serves a provider that stores an unversioned
|
|
63
|
+
* `localStorage[key]` document. Deliberately tiny and dependency-free: it reads the
|
|
64
|
+
* stored preference, resolves `system`, and sets the class. It does not apply the
|
|
65
|
+
* variant's roles — the default theme in `theme.css` covers the first paint, and the
|
|
66
|
+
* provider writes the rest on mount. Its output is a compatibility surface (a
|
|
67
|
+
* consumer may have it in a snapshot), so it does not change.
|
|
68
|
+
*
|
|
69
|
+
* ## The options form
|
|
70
|
+
*
|
|
71
|
+
* `themeScript({ key, ... })` serves a host with a versioned document (see
|
|
72
|
+
* `createVersionedPersistence`) and writes what the provider will write, so mounting
|
|
73
|
+
* repaints nothing:
|
|
74
|
+
*
|
|
75
|
+
* - `class="dark"`, `color-scheme`, `data-theme`, `data-appearance` and, for a
|
|
76
|
+
* compact document, `data-density`;
|
|
77
|
+
* - `data-accent`: a preset id as stored, `custom` for a `#rrggbb` (never the hex
|
|
78
|
+
* itself, which is the worst possible attribute content), `defaultAccent` when the
|
|
79
|
+
* document has none, nothing for a theme-derived `ansi-*` accent (it has no
|
|
80
|
+
* stylesheet block; the provider paints it inline);
|
|
81
|
+
* - the theme: the stored id when the catalogue or the stored library holds it, else
|
|
82
|
+
* the default of the resolved appearance, exactly as the provider resolves it. A
|
|
83
|
+
* library theme's own tokens are written inline, so an imported theme paints on the
|
|
84
|
+
* first frame;
|
|
85
|
+
* - the surface axis, when `surface` is set;
|
|
86
|
+
* - the font settings, guarded to the document's `version`.
|
|
87
|
+
*
|
|
88
|
+
* The document's `version`, when the schema names one, must match exactly. The legacy
|
|
89
|
+
* key is read only while the main key is absent: an unreadable main document is not
|
|
90
|
+
* "no preference", so it does not resurrect an older value.
|
|
91
|
+
*
|
|
92
|
+
* The script reads values out of `localStorage` and writes them to `dataset` and
|
|
93
|
+
* `style`, which are *property* assignments rather than code: a stored id, accent or
|
|
94
|
+
* token can set an attribute and cannot execute. The values that reach the source as
|
|
95
|
+
* text (keys, ids, the default accent) go through {@link inlineScriptLiteral} for the
|
|
96
|
+
* reason documented there.
|
|
97
|
+
*/
|
|
98
|
+
export declare function themeScript(storageKey?: string): string;
|
|
99
|
+
export declare function themeScript(options: ThemeScriptOptions): string;
|
|
100
|
+
//# sourceMappingURL=theme-script.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"theme-script.d.ts","sourceRoot":"","sources":["../../../src/components/theme/theme-script.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAE7D;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,kBAAkB,GAAG;IACpD;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,QAAQ,GAAG,YAAY,CAAA;IACjC,oEAAoE;IACpE,cAAc,CAAC,EAAE,MAAM,CAAA;CACxB,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,wBAAgB,WAAW,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;AACxD,wBAAgB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,MAAM,CAAA"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { accentPresets } from "../../lib/tokens.js";
|
|
2
|
+
import { isCustomAccent } from "../../lib/accent-roles.js";
|
|
3
|
+
import { builtinThemes, defaultDarkThemeId, defaultLightThemeId } from "../../lib/themes.js";
|
|
4
|
+
import { safeScriptStringLiteral } from "../../lib/safe-script.js";
|
|
5
|
+
import { fontSettingsBootstrapScript } from "../../lib/appearance-font-settings.js";
|
|
6
|
+
import { REDUCED_TRANSPARENCY_QUERY, surfaceAlpha } from "../../lib/theme-surface.js";
|
|
7
|
+
//#region src/components/theme/theme-script.ts
|
|
8
|
+
/**
|
|
9
|
+
* A string as a JavaScript literal that is also safe inside an inline `<script>`.
|
|
10
|
+
*
|
|
11
|
+
* `JSON.stringify` produces a correct JavaScript literal, and it is **not** safe
|
|
12
|
+
* here: it leaves `<` and `>` alone, so a value containing `<\/script>` ends the tag
|
|
13
|
+
* early and everything after it is parsed as HTML. That is the classic inline-script
|
|
14
|
+
* injection, and it is a real one even though the value is a developer-supplied prop
|
|
15
|
+
* rather than user input — a prop can come from configuration, and a key that happens
|
|
16
|
+
* to contain a closing tag should not be able to execute.
|
|
17
|
+
*
|
|
18
|
+
* The escape is also correct JavaScript: `\u003c` is `<` to the parser, so the value
|
|
19
|
+
* is byte-identical at runtime and inert to the HTML tokenizer. `\u2028` and `\u2029`
|
|
20
|
+
* are escaped for the neighbouring reason — they are legal inside a JSON string and
|
|
21
|
+
* were, before ES2019, line terminators to a JavaScript parser.
|
|
22
|
+
*
|
|
23
|
+
* CodeQL flags the unescaped form as `js/bad-code-sanitization`, which is how this
|
|
24
|
+
* was found; `tests/theme-script.test.ts` pins it so it cannot come back.
|
|
25
|
+
*/
|
|
26
|
+
function inlineScriptLiteral(value) {
|
|
27
|
+
return safeScriptStringLiteral(value);
|
|
28
|
+
}
|
|
29
|
+
function themeScript(input = "adea-appearance") {
|
|
30
|
+
if (typeof input === "string") return stringFormScript(input);
|
|
31
|
+
return optionsFormScript(input);
|
|
32
|
+
}
|
|
33
|
+
function stringFormScript(storageKey) {
|
|
34
|
+
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)}`;
|
|
35
|
+
}
|
|
36
|
+
var literal = safeScriptStringLiteral;
|
|
37
|
+
function optionsFormScript(options) {
|
|
38
|
+
const field = options.appearanceField ?? "appearance";
|
|
39
|
+
const versionGuard = options.version === void 0 ? "" : `&&x.version===${Number(options.version)}`;
|
|
40
|
+
const presets = accentPresets.filter((preset) => preset.id !== "theme").map((preset) => literal(preset.id));
|
|
41
|
+
const defaultAccent = options.defaultAccent === void 0 ? "" : isCustomAccent(options.defaultAccent) ? "custom" : options.defaultAccent;
|
|
42
|
+
const parts = [];
|
|
43
|
+
parts.push(`(function(){try{`, `var r=document.documentElement,s=r.style;`, `var q=function(m){try{return window.matchMedia(m).matches}catch(e){return false}};`, `var get=function(k){try{return localStorage.getItem(k)}catch(e){return null}};`, `var raw=get(${literal(options.key)}),doc=null,legacy=null;`, `if(raw!==null){try{var x=JSON.parse(raw);if(x&&typeof x==='object'&&!Array.isArray(x)${versionGuard})doc=x}catch(e){}}`);
|
|
44
|
+
if (options.legacyAppearanceKey !== void 0) parts.push(`else legacy=get(${literal(options.legacyAppearanceKey)});`);
|
|
45
|
+
parts.push(`var m=doc?doc[${literal(field)}]:legacy;`, `var mode=m==='light'||m==='dark'?m:'system';`, `var dark=mode==='dark'||(mode==='system'&&q('(prefers-color-scheme: dark)'));`, `var fallback=dark?${literal(defaultDarkThemeId)}:${literal(defaultLightThemeId)};`, `var want=doc?(dark?doc.darkThemeId:doc.lightThemeId):null;`, `if(typeof want!=='string')want=fallback;`, `var ids=[${builtinThemes.map((theme) => literal(theme.id)).join(",")}];`, `var id=ids.indexOf(want)!==-1?want:null,tokens=null;`);
|
|
46
|
+
if (options.libraryKey !== void 0) parts.push(`if(id===null){try{var lib=JSON.parse(get(${literal(options.libraryKey)})||'null');`, `if(lib&&typeof lib==='object'&&lib.version===${Number(options.libraryVersion ?? 1)}&&Array.isArray(lib.themes)){`, `for(var i=0;i!==lib.themes.length;i++){var t=lib.themes[i];`, `if(t&&t.id===want&&t.flatTokens&&typeof t.flatTokens==='object'){id=want;tokens=t.flatTokens;break}}}}catch(e){}}`);
|
|
47
|
+
parts.push(`if(id===null)id=fallback;`, `r.classList.toggle('dark',dark);`, `s.colorScheme=dark?'dark':'light';`, `r.dataset.theme=id;`, `r.dataset.appearance=dark?'dark':'light';`);
|
|
48
|
+
if (options.libraryKey !== void 0) parts.push(`if(tokens){for(var n in tokens){if(Object.prototype.hasOwnProperty.call(tokens,n)&&n.slice(0,2)==='--'&&typeof tokens[n]==='string')s.setProperty(n,tokens[n])}}`);
|
|
49
|
+
parts.push(`var a=doc&&typeof doc.accent==='string'?doc.accent:'';`, `var accent=[${presets.join(",")}].indexOf(a)!==-1?a:/^#[0-9a-fA-F]{6}$/.test(a)?'custom':a.slice(0,5)==='ansi-'?'':${literal(defaultAccent)};`, `if(accent)r.dataset.accent=accent;`, `if(doc&&doc.density==='compact')r.dataset.density='compact';`);
|
|
50
|
+
if (options.surface) parts.push(`var reduce=q(${literal(REDUCED_TRANSPARENCY_QUERY)})||!!(doc&&doc.reduceTransparency===true);`, `var surface=reduce?'opaque':doc&&(doc.surface==='frosted'||doc.surface==='translucent')?'frosted':'opaque';`, `r.dataset.surface=surface;`, `r.dataset.reduceTransparency=reduce?'true':'false';`, `s.setProperty('--surface-alpha',${JSON.stringify(surfaceAlpha)}[surface]);`);
|
|
51
|
+
parts.push(`}catch(e){}})();`);
|
|
52
|
+
return `${parts.join("")}${fontSettingsBootstrapScript(options.key, options.version)}`;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { inlineScriptLiteral, themeScript };
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=theme-script.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"theme-script.js","names":[],"sources":["../../../src/components/theme/theme-script.ts"],"sourcesContent":["import { fontSettingsBootstrapScript } from '#lib/appearance-font-settings'\nimport { isCustomAccent } from '#lib/accent-roles'\nimport { safeScriptStringLiteral } from '#lib/safe-script'\nimport { REDUCED_TRANSPARENCY_QUERY, surfaceAlpha } from '#lib/theme-surface'\nimport { accentPresets } from '#lib/tokens'\nimport { builtinThemes, defaultDarkThemeId, defaultLightThemeId } from '#lib/themes'\nimport type { ThemeStorageSchema } from './theme-persistence'\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 * Options for the host-shaped no-flash script: the document's {@link ThemeStorageSchema}\n * plus what the script paints from it.\n */\nexport type ThemeScriptOptions = ThemeStorageSchema & {\n /**\n * The accent painted when the document has none, an unrecognised one, or the\n * legacy `theme` spelling — the host's default (adea: `violet`). Without it those\n * cases paint no `data-accent`, which is what the provider writes for `theme`.\n * Setting it means the `[data-accent]` block of the default preset paints on the\n * first frame instead of after hydration.\n */\n defaultAccent?: string\n /**\n * Also resolve the surface axis (`data-surface`, `data-reduce-transparency`,\n * `--surface-alpha`) from the document and the operating system's Reduce\n * Transparency setting. A `translucent` preference resolves to `frosted`: the\n * host's translucency capability is not known until the provider mounts, and the\n * provider re-resolves it then. Match the provider's `surface` prop.\n */\n surface?: boolean\n /**\n * Match the provider's `palette` prop. The attributes written are the same either\n * way: a catalogue variant's palette is the host stylesheet's job (`stylesheet`) or\n * the provider's, at mount (`inline`), and a stored theme's own tokens are written\n * inline in both.\n */\n palette?: 'inline' | 'stylesheet'\n /** The only `version` of the library document read. Default `1`. */\n libraryVersion?: number\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 * ## The string form\n *\n * `themeScript('key')` serves a provider that stores an unversioned\n * `localStorage[key]` document. Deliberately tiny and dependency-free: it reads the\n * stored preference, resolves `system`, and sets the class. It does not apply the\n * variant's roles — the default theme in `theme.css` covers the first paint, and the\n * provider writes the rest on mount. Its output is a compatibility surface (a\n * consumer may have it in a snapshot), so it does not change.\n *\n * ## The options form\n *\n * `themeScript({ key, ... })` serves a host with a versioned document (see\n * `createVersionedPersistence`) and writes what the provider will write, so mounting\n * repaints nothing:\n *\n * - `class=\"dark\"`, `color-scheme`, `data-theme`, `data-appearance` and, for a\n * compact document, `data-density`;\n * - `data-accent`: a preset id as stored, `custom` for a `#rrggbb` (never the hex\n * itself, which is the worst possible attribute content), `defaultAccent` when the\n * document has none, nothing for a theme-derived `ansi-*` accent (it has no\n * stylesheet block; the provider paints it inline);\n * - the theme: the stored id when the catalogue or the stored library holds it, else\n * the default of the resolved appearance, exactly as the provider resolves it. A\n * library theme's own tokens are written inline, so an imported theme paints on the\n * first frame;\n * - the surface axis, when `surface` is set;\n * - the font settings, guarded to the document's `version`.\n *\n * The document's `version`, when the schema names one, must match exactly. The legacy\n * key is read only while the main key is absent: an unreadable main document is not\n * \"no preference\", so it does not resurrect an older value.\n *\n * The script reads values out of `localStorage` and writes them to `dataset` and\n * `style`, which are *property* assignments rather than code: a stored id, accent or\n * token can set an attribute and cannot execute. The values that reach the source as\n * text (keys, ids, the default accent) go through {@link inlineScriptLiteral} for the\n * reason documented there.\n */\nexport function themeScript(storageKey?: string): string\nexport function themeScript(options: ThemeScriptOptions): string\nexport function themeScript(input: string | ThemeScriptOptions = 'adea-appearance'): string {\n if (typeof input === 'string') return stringFormScript(input)\n return optionsFormScript(input)\n}\n\nfunction stringFormScript(storageKey: string): 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\nconst literal = safeScriptStringLiteral\n\nfunction optionsFormScript(options: ThemeScriptOptions): string {\n const field = options.appearanceField ?? 'appearance'\n const versionGuard =\n options.version === undefined ? '' : `&&x.version===${Number(options.version)}`\n const presets = accentPresets\n .filter((preset) => preset.id !== 'theme')\n .map((preset) => literal(preset.id))\n const defaultAccent =\n options.defaultAccent === undefined\n ? ''\n : isCustomAccent(options.defaultAccent)\n ? 'custom'\n : options.defaultAccent\n\n const parts: string[] = []\n parts.push(\n `(function(){try{`,\n `var r=document.documentElement,s=r.style;`,\n `var q=function(m){try{return window.matchMedia(m).matches}catch(e){return false}};`,\n `var get=function(k){try{return localStorage.getItem(k)}catch(e){return null}};`,\n // The main document. `raw !== null` rather than truthiness: an empty string is a\n // stored (corrupt) value, so it does not fall through to the legacy key.\n `var raw=get(${literal(options.key)}),doc=null,legacy=null;`,\n `if(raw!==null){try{var x=JSON.parse(raw);if(x&&typeof x==='object'&&!Array.isArray(x)${versionGuard})doc=x}catch(e){}}`\n )\n if (options.legacyAppearanceKey !== undefined) {\n parts.push(`else legacy=get(${literal(options.legacyAppearanceKey)});`)\n }\n parts.push(\n `var m=doc?doc[${literal(field)}]:legacy;`,\n `var mode=m==='light'||m==='dark'?m:'system';`,\n `var dark=mode==='dark'||(mode==='system'&&q('(prefers-color-scheme: dark)'));`,\n `var fallback=dark?${literal(defaultDarkThemeId)}:${literal(defaultLightThemeId)};`,\n `var want=doc?(dark?doc.darkThemeId:doc.lightThemeId):null;`,\n `if(typeof want!=='string')want=fallback;`,\n `var ids=[${builtinThemes.map((theme) => literal(theme.id)).join(',')}];`,\n `var id=ids.indexOf(want)!==-1?want:null,tokens=null;`\n )\n if (options.libraryKey !== undefined) {\n parts.push(\n `if(id===null){try{var lib=JSON.parse(get(${literal(options.libraryKey)})||'null');`,\n `if(lib&&typeof lib==='object'&&lib.version===${Number(options.libraryVersion ?? 1)}&&Array.isArray(lib.themes)){`,\n `for(var i=0;i!==lib.themes.length;i++){var t=lib.themes[i];`,\n `if(t&&t.id===want&&t.flatTokens&&typeof t.flatTokens==='object'){id=want;tokens=t.flatTokens;break}}}}catch(e){}}`\n )\n }\n parts.push(\n `if(id===null)id=fallback;`,\n `r.classList.toggle('dark',dark);`,\n `s.colorScheme=dark?'dark':'light';`,\n `r.dataset.theme=id;`,\n `r.dataset.appearance=dark?'dark':'light';`\n )\n if (options.libraryKey !== undefined) {\n parts.push(\n `if(tokens){for(var n in tokens){if(Object.prototype.hasOwnProperty.call(tokens,n)&&n.slice(0,2)==='--'&&typeof tokens[n]==='string')s.setProperty(n,tokens[n])}}`\n )\n }\n parts.push(\n `var a=doc&&typeof doc.accent==='string'?doc.accent:'';`,\n `var accent=[${presets.join(',')}].indexOf(a)!==-1?a:/^#[0-9a-fA-F]{6}$/.test(a)?'custom':a.slice(0,5)==='ansi-'?'':${literal(defaultAccent)};`,\n `if(accent)r.dataset.accent=accent;`,\n `if(doc&&doc.density==='compact')r.dataset.density='compact';`\n )\n if (options.surface) {\n parts.push(\n // Reduce Transparency forces the opaque surface; a translucent request resolves\n // to frosted because the host's capability is unknown before the provider mounts.\n `var reduce=q(${literal(REDUCED_TRANSPARENCY_QUERY)})||!!(doc&&doc.reduceTransparency===true);`,\n `var surface=reduce?'opaque':doc&&(doc.surface==='frosted'||doc.surface==='translucent')?'frosted':'opaque';`,\n `r.dataset.surface=surface;`,\n `r.dataset.reduceTransparency=reduce?'true':'false';`,\n `s.setProperty('--surface-alpha',${JSON.stringify(surfaceAlpha)}[surface]);`\n )\n }\n parts.push(`}catch(e){}})();`)\n\n return `${parts.join('')}${fontSettingsBootstrapScript(options.key, options.version)}`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,oBAAoB,OAAuB;CACzD,OAAO,wBAAwB,KAAK;AACtC;AAkFA,SAAgB,YAAY,QAAqC,mBAA2B;CAC1F,IAAI,OAAO,UAAU,UAAU,OAAO,iBAAiB,KAAK;CAC5D,OAAO,kBAAkB,KAAK;AAChC;AAEA,SAAS,iBAAiB,YAA4B;CAEpD,OAAO,GAAG,8CADmD,oBAAoB,UAAU,EAAE,wXAC1E,4BAA4B,UAAU;AAC3D;AAEA,IAAM,UAAU;AAEhB,SAAS,kBAAkB,SAAqC;CAC9D,MAAM,QAAQ,QAAQ,mBAAmB;CACzC,MAAM,eACJ,QAAQ,YAAY,KAAA,IAAY,KAAK,iBAAiB,OAAO,QAAQ,OAAO;CAC9E,MAAM,UAAU,cACb,QAAQ,WAAW,OAAO,OAAO,OAAO,CAAC,CACzC,KAAK,WAAW,QAAQ,OAAO,EAAE,CAAC;CACrC,MAAM,gBACJ,QAAQ,kBAAkB,KAAA,IACtB,KACA,eAAe,QAAQ,aAAa,IAClC,WACA,QAAQ;CAEhB,MAAM,QAAkB,CAAC;CACzB,MAAM,KACJ,oBACA,6CACA,sFACA,kFAGA,eAAe,QAAQ,QAAQ,GAAG,EAAE,0BACpC,wFAAwF,aAAa,mBACvG;CACA,IAAI,QAAQ,wBAAwB,KAAA,GAClC,MAAM,KAAK,mBAAmB,QAAQ,QAAQ,mBAAmB,EAAE,GAAG;CAExE,MAAM,KACJ,iBAAiB,QAAQ,KAAK,EAAE,YAChC,gDACA,iFACA,qBAAqB,QAAQ,kBAAkB,EAAE,GAAG,QAAQ,mBAAmB,EAAE,IACjF,8DACA,4CACA,YAAY,cAAc,KAAK,UAAU,QAAQ,MAAM,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,KACtE,sDACF;CACA,IAAI,QAAQ,eAAe,KAAA,GACzB,MAAM,KACJ,4CAA4C,QAAQ,QAAQ,UAAU,EAAE,cACxE,gDAAgD,OAAO,QAAQ,kBAAkB,CAAC,EAAE,gCACpF,+DACA,mHACF;CAEF,MAAM,KACJ,6BACA,oCACA,sCACA,uBACA,2CACF;CACA,IAAI,QAAQ,eAAe,KAAA,GACzB,MAAM,KACJ,kKACF;CAEF,MAAM,KACJ,0DACA,eAAe,QAAQ,KAAK,GAAG,EAAE,qFAAqF,QAAQ,aAAa,EAAE,IAC7I,sCACA,8DACF;CACA,IAAI,QAAQ,SACV,MAAM,KAGJ,gBAAgB,QAAQ,0BAA0B,EAAE,6CACpD,+GACA,8BACA,uDACA,mCAAmC,KAAK,UAAU,YAAY,EAAE,YAClE;CAEF,MAAM,KAAK,kBAAkB;CAE7B,OAAO,GAAG,MAAM,KAAK,EAAE,IAAI,4BAA4B,QAAQ,KAAK,QAAQ,OAAO;AACrF"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type AppearanceEditorFontSettings } from '#lib/appearance-font-settings';
|
|
2
2
|
import type { AccentPreset } from '@adea-ai/themes';
|
|
3
3
|
import { type AccentRoles } from '#lib/accent-roles';
|
|
4
|
+
import { type FontZoomIntent } from '#lib/font-zoom';
|
|
5
|
+
import type { ThemeSurface } from '#lib/theme-surface';
|
|
4
6
|
import { type ThemeAppearance, type ThemeVariant } from '#lib/themes';
|
|
5
7
|
/**
|
|
6
8
|
* The pure half of the theme provider: what a selection is, how two selections
|
|
@@ -50,6 +52,30 @@ export type ThemeSelection = {
|
|
|
50
52
|
* keeps working and `ThemeSelection` stays assignable without it.
|
|
51
53
|
*/
|
|
52
54
|
density?: ThemeDensity;
|
|
55
|
+
/**
|
|
56
|
+
* The terminal either follows the interface theme (`theme`, or absent) or is pinned
|
|
57
|
+
* to another theme's terminal palette by that theme's id. The pin is written over
|
|
58
|
+
* the interface variant's own `--terminal-*` properties, so a light interface can
|
|
59
|
+
* carry a dark terminal.
|
|
60
|
+
*
|
|
61
|
+
* An id the registry does not hold paints the interface palette and stays in the
|
|
62
|
+
* selection, the same rule as an unknown theme id.
|
|
63
|
+
*
|
|
64
|
+
* Optional and not defaulted: see {@link defaultThemeSelection}.
|
|
65
|
+
*/
|
|
66
|
+
terminalThemeId?: string;
|
|
67
|
+
/**
|
|
68
|
+
* How opaque elevated panels are. Written to `<html>` only when the provider's
|
|
69
|
+
* `surface` prop is on or this is set; absent, a host paints no surface axis at
|
|
70
|
+
* all. Resolved against the OS and the host's capability before it is painted —
|
|
71
|
+
* see `resolveSurface` — so the value stored is a preference, never the outcome.
|
|
72
|
+
*/
|
|
73
|
+
surface?: ThemeSurface;
|
|
74
|
+
/**
|
|
75
|
+
* The user's own Reduce Transparency switch, which forces the `opaque` surface the
|
|
76
|
+
* same way the operating system's setting does.
|
|
77
|
+
*/
|
|
78
|
+
reduceTransparency?: boolean;
|
|
53
79
|
};
|
|
54
80
|
/**
|
|
55
81
|
* The two density rungs.
|
|
@@ -116,6 +142,24 @@ export type ThemeContextValue = {
|
|
|
116
142
|
* registry does not hold: each means "keep the inherited accent".
|
|
117
143
|
*/
|
|
118
144
|
accentRolesFor: (accent: string | null, variantId?: string) => AccentRoles | undefined;
|
|
145
|
+
/**
|
|
146
|
+
* The surface the committed selection paints, after Reduce Transparency and the
|
|
147
|
+
* host's translucency capability. `opaque` when the axis is off. Follows the
|
|
148
|
+
* committed selection, not a preview, like {@link ThemeContextValue.variant}.
|
|
149
|
+
*/
|
|
150
|
+
effectiveSurface: () => ThemeSurface;
|
|
151
|
+
/**
|
|
152
|
+
* True while the operating system or the selection's `reduceTransparency` forces
|
|
153
|
+
* opaque surfaces. Always false when the surface axis is off, because nothing is
|
|
154
|
+
* then listening to the operating system.
|
|
155
|
+
*/
|
|
156
|
+
reduceTransparencyActive: () => boolean;
|
|
157
|
+
/**
|
|
158
|
+
* Step the three text sizes together, or put them back to the defaults: what the
|
|
159
|
+
* `fontZoom` prop's chords do, for a host that binds its own keys or a menu. Goes
|
|
160
|
+
* through {@link ThemeContextValue.setSelection}, so it persists and ends a preview.
|
|
161
|
+
*/
|
|
162
|
+
zoomFonts: (intent: FontZoomIntent) => void;
|
|
119
163
|
};
|
|
120
164
|
/** Keep the deprecated single-font view synchronized with the UI axis. */
|
|
121
165
|
export declare function mergeThemeSelection(base: ThemeSelection, patch: Partial<ThemeSelection>): ThemeSelection;
|
|
@@ -145,6 +189,20 @@ export declare function resolveThemeState(selection: ThemeSelection, system: The
|
|
|
145
189
|
appearance: ThemeAppearance;
|
|
146
190
|
variant: ThemeVariant;
|
|
147
191
|
};
|
|
192
|
+
/**
|
|
193
|
+
* The variant whose terminal palette is pinned, or `undefined` when the terminal
|
|
194
|
+
* follows the interface theme.
|
|
195
|
+
*
|
|
196
|
+
* `theme`, an absent id and an id the registry does not hold all mean the interface
|
|
197
|
+
* palette: a terminal must never resolve to a blank or half-painted palette because a
|
|
198
|
+
* theme was deleted after it was pinned.
|
|
199
|
+
*/
|
|
200
|
+
export declare function resolveTerminalVariant(terminalThemeId: string | undefined, registry: readonly ThemeVariant[]): ThemeVariant | undefined;
|
|
201
|
+
/**
|
|
202
|
+
* The font settings a zoom chord asks for: one pixel up or down on every axis, or
|
|
203
|
+
* the defaults for `reset`.
|
|
204
|
+
*/
|
|
205
|
+
export declare function zoomedFontSettings(selection: ThemeSelection, intent: FontZoomIntent): AppearanceEditorFontSettings;
|
|
148
206
|
/**
|
|
149
207
|
* The registry a provider resolves against: the catalogue, then the host's extras.
|
|
150
208
|
*
|
|
@@ -1 +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,EAAyB,KAA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B,4BAA4B,CAG9B;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAC3B,OAAO,EAAE,SAAS,YAAY,EAAE,EAChC,KAAK,EAAE,SAAS,YAAY,EAAE,GAAG,SAAS,GACzC,SAAS,YAAY,EAAE,CAEzB;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,KAAK,EAAE;IACL,SAAS,EAAE,cAAc,CAAA;IACzB,OAAO,EAAE,YAAY,CAAA;IACrB,QAAQ,EAAE,SAAS,YAAY,EAAE,CAAA;IACjC,mBAAmB,CAAC,EAAE,MAAM,CAAA;CAC7B,GACA,WAAW,GAAG,SAAS,CAYzB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { normalizeCustomAccent } from "../../lib/accent-roles.js";
|
|
2
2
|
import { accentRolesForSelection, defaultDarkThemeId, defaultLightThemeId, resolveVariant } from "../../lib/themes.js";
|
|
3
3
|
import { DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS, normalizeAppearanceEditorFontSettings } from "../../lib/appearance-font-settings.js";
|
|
4
|
+
import { stepAppearanceFontSizes } from "../../lib/font-zoom.js";
|
|
4
5
|
//#region src/components/theme/theme-state.ts
|
|
5
6
|
/**
|
|
6
7
|
* Deliberately lists only the fields every consumer has always had. A field added
|
|
@@ -92,6 +93,26 @@ function resolveThemeState(selection, system, registry) {
|
|
|
92
93
|
};
|
|
93
94
|
}
|
|
94
95
|
/**
|
|
96
|
+
* The variant whose terminal palette is pinned, or `undefined` when the terminal
|
|
97
|
+
* follows the interface theme.
|
|
98
|
+
*
|
|
99
|
+
* `theme`, an absent id and an id the registry does not hold all mean the interface
|
|
100
|
+
* palette: a terminal must never resolve to a blank or half-painted palette because a
|
|
101
|
+
* theme was deleted after it was pinned.
|
|
102
|
+
*/
|
|
103
|
+
function resolveTerminalVariant(terminalThemeId, registry) {
|
|
104
|
+
if (terminalThemeId === void 0 || terminalThemeId === "theme") return void 0;
|
|
105
|
+
return registry.find((candidate) => candidate.id === terminalThemeId);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The font settings a zoom chord asks for: one pixel up or down on every axis, or
|
|
109
|
+
* the defaults for `reset`.
|
|
110
|
+
*/
|
|
111
|
+
function zoomedFontSettings(selection, intent) {
|
|
112
|
+
if (intent === "reset") return { ...DEFAULT_APPEARANCE_EDITOR_FONT_SETTINGS };
|
|
113
|
+
return stepAppearanceFontSizes(selection.fonts, intent === "in" ? 1 : -1);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
95
116
|
* The registry a provider resolves against: the catalogue, then the host's extras.
|
|
96
117
|
*
|
|
97
118
|
* The catalogue wins an id collision, because it is listed first and `resolveVariant`
|
|
@@ -117,6 +138,6 @@ function accentRolesForState(accent, variantId, state) {
|
|
|
117
138
|
});
|
|
118
139
|
}
|
|
119
140
|
//#endregion
|
|
120
|
-
export { accentRolesForState, defaultThemeSelection, initialThemeSelection, mergeRegistry, mergeThemeSelection, resolveAppearance, resolveThemeState, resolvedDensity, selectedThemeId };
|
|
141
|
+
export { accentRolesForState, defaultThemeSelection, initialThemeSelection, mergeRegistry, mergeThemeSelection, resolveAppearance, resolveTerminalVariant, resolveThemeState, resolvedDensity, selectedThemeId, zoomedFontSettings };
|
|
121
142
|
|
|
122
143
|
//# sourceMappingURL=theme-state.js.map
|