@weasel-js/theme 1.15.1 → 1.16.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/README.md +7 -4
- package/dist/{chunk-UKUFGM6D.js → chunk-44CG54ZK.js} +6 -8
- package/dist/chunk-44CG54ZK.js.map +1 -0
- package/dist/{chunk-Z675UQ26.js → chunk-7OMMT3WJ.js} +2 -2
- package/dist/{chunk-Z675UQ26.js.map → chunk-7OMMT3WJ.js.map} +1 -1
- package/dist/{chunk-Y4COX5NW.js → chunk-SFVRMAMW.js} +6 -22
- package/dist/chunk-SFVRMAMW.js.map +1 -0
- package/dist/{chunk-32JKTYS2.js → chunk-UCQC6GZR.js} +11 -24
- package/dist/chunk-UCQC6GZR.js.map +1 -0
- package/dist/{chunk-NCAQ54LO.js → chunk-X2KI4SSJ.js} +4 -3
- package/dist/chunk-X2KI4SSJ.js.map +1 -0
- package/dist/{definition-nZbgRG7A.d.ts → definition-DfbYMDu0.d.ts} +5 -1
- package/dist/engine.d.ts +3 -3
- package/dist/engine.js +6 -6
- package/dist/engine.js.map +1 -1
- package/dist/index.d.ts +15 -15
- package/dist/index.js +26 -8
- package/dist/index.js.map +1 -1
- package/dist/prefs.d.ts +8 -8
- package/dist/prefs.js +23 -20
- package/dist/prefs.js.map +1 -1
- package/dist/react.d.ts +3 -3
- package/dist/react.js +10 -23
- package/dist/react.js.map +1 -1
- package/dist/themes/platinum.d.ts +1 -1
- package/dist/themes/platinum.js +1 -1
- package/dist/themes/win9x.d.ts +1 -1
- package/dist/themes/win9x.js +1 -1
- package/package.json +5 -4
- package/dist/chunk-32JKTYS2.js.map +0 -1
- package/dist/chunk-NCAQ54LO.js.map +0 -1
- package/dist/chunk-UKUFGM6D.js.map +0 -1
- package/dist/chunk-Y4COX5NW.js.map +0 -1
package/dist/react.js
CHANGED
|
@@ -1,31 +1,18 @@
|
|
|
1
|
-
import { isColorModePreference, themeTints, applyTheme, colorSourceCss, colorSourceLiteral } from './chunk-
|
|
2
|
-
export { isColorModePreference } from './chunk-
|
|
3
|
-
import './chunk-
|
|
1
|
+
import { isColorModePreference, themeTints, applyTheme, colorSourceCss, colorSourceLiteral } from './chunk-SFVRMAMW.js';
|
|
2
|
+
export { isColorModePreference } from './chunk-SFVRMAMW.js';
|
|
3
|
+
import './chunk-44CG54ZK.js';
|
|
4
4
|
import './chunk-M3R5MV7Q.js';
|
|
5
|
-
import { themeAxes, resolveTheme } from './chunk-
|
|
6
|
-
import { weaselTheme } from './chunk-
|
|
5
|
+
import { themeAxes, resolveTheme } from './chunk-UCQC6GZR.js';
|
|
6
|
+
import { weaselTheme } from './chunk-X2KI4SSJ.js';
|
|
7
7
|
import { fullSelection, selectionKey } from './chunk-P5F3GZV6.js';
|
|
8
8
|
import { colorLiteralToHex } from '@weasel-js/paint';
|
|
9
|
-
import { createContext, useState,
|
|
9
|
+
import { createContext, useState, useCallback, useRef, useMemo, useLayoutEffect, useContext } from 'react';
|
|
10
10
|
import { isDev } from '@weasel-js/registry';
|
|
11
|
+
import { useSystemColorScheme } from '@weasel-js/react';
|
|
11
12
|
import { jsx } from 'react/jsx-runtime';
|
|
12
13
|
|
|
13
|
-
function systemQuery() {
|
|
14
|
-
if (typeof globalThis.matchMedia !== "function") return null;
|
|
15
|
-
return globalThis.matchMedia("(prefers-color-scheme: light)");
|
|
16
|
-
}
|
|
17
|
-
var systemMode = () => systemQuery()?.matches ? "light" : "dark";
|
|
18
14
|
function useResolvedColorMode(preference) {
|
|
19
|
-
const
|
|
20
|
-
useEffect(() => {
|
|
21
|
-
if (preference !== "auto") return;
|
|
22
|
-
const mq = systemQuery();
|
|
23
|
-
if (!mq) return;
|
|
24
|
-
setSystem(mq.matches ? "light" : "dark");
|
|
25
|
-
const onChange = (e) => setSystem(e.matches ? "light" : "dark");
|
|
26
|
-
mq.addEventListener("change", onChange);
|
|
27
|
-
return () => mq.removeEventListener("change", onChange);
|
|
28
|
-
}, [preference]);
|
|
15
|
+
const system = useSystemColorScheme(preference === "auto");
|
|
29
16
|
return preference === "auto" ? system : preference;
|
|
30
17
|
}
|
|
31
18
|
function defaultStorage() {
|
|
@@ -73,8 +60,8 @@ function ThemeProvider({
|
|
|
73
60
|
const ref = useRef(null);
|
|
74
61
|
const axes = themeAxes(theme);
|
|
75
62
|
const autoMode = selection?.mode === "auto" && !("auto" in (axes.mode?.values ?? {}));
|
|
76
|
-
const
|
|
77
|
-
const given = autoMode ? { ...selection, mode:
|
|
63
|
+
const systemMode = useResolvedColorMode(autoMode ? "auto" : "dark");
|
|
64
|
+
const given = autoMode ? { ...selection, mode: systemMode } : selection;
|
|
78
65
|
const full = fullSelection(axes, given);
|
|
79
66
|
warnUnknownAxisValues(theme, axes, given);
|
|
80
67
|
const key = selectionKey(axes, full);
|
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/useColorMode.ts","../src/react.tsx"],"names":["systemMode","useCallback"],"mappings":";;;;;;;;;;;;AAGA,SAAS,WAAA,GAAqC;AAC5C,EAAA,IAAI,OAAO,UAAA,CAAW,UAAA,KAAe,UAAA,EAAY,OAAO,IAAA;AACxD,EAAA,OAAO,UAAA,CAAW,WAAW,+BAA+B,CAAA;AAC9D;AAEA,IAAM,UAAA,GAAa,MAAkB,WAAA,EAAY,EAAG,UAAU,OAAA,GAAU,MAAA;AAOjE,SAAS,qBAAqB,UAAA,EAA4C;AAC/E,EAAA,MAAM,CAAC,MAAA,EAAQ,SAAS,CAAA,GAAI,SAAoB,UAAU,CAAA;AAE1D,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,eAAe,MAAA,EAAQ;AAC3B,IAAA,MAAM,KAAK,WAAA,EAAY;AACvB,IAAA,IAAI,CAAC,EAAA,EAAI;AAET,IAAA,SAAA,CAAU,EAAA,CAAG,OAAA,GAAU,OAAA,GAAU,MAAM,CAAA;AACvC,IAAA,MAAM,WAAW,CAAC,CAAA,KAA4B,UAAU,CAAA,CAAE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AAa,cAAA,CAAe,MAAA,EAAQ,GAAG,CAAA,IAAK,MAAA,EAAa,CAAC,GAAG,CAAC,CAAA;AACjH;AAQO,SAAS,WAAA,GAA8E;AAC5F,EAAA,MAAM,MAAM,QAAA,EAAS;AACrB,EAAA,OAAOA,WAAAA,CAAY,CAAC,MAAA,KAAW;AAC7B,IAAA,IAAI,MAAA,IAAU,MAAM,OAAO,MAAA;AAC3B,IAAA,MAAM,OAAA,GAAU,kBAAA,CAAmB,MAAA,EAAQ,GAAG,CAAA;AAC9C,IAAA,OAAA,CAAQ,OAAA,IAAW,iBAAA,CAAkB,OAAO,CAAA,KAAM,MAAA;AAAA,EACpD,CAAA,EAAG,CAAC,GAAG,CAAC,CAAA;AACV","file":"react.js","sourcesContent":["import { useCallback, useEffect, useState } from 'react';\nimport { isColorModePreference, type ColorMode, type ColorModePreference } from './colorMode';\n\nfunction systemQuery(): MediaQueryList | null {\n if (typeof globalThis.matchMedia !== 'function') return null;\n return globalThis.matchMedia('(prefers-color-scheme: light)');\n}\n\nconst systemMode = (): ColorMode => (systemQuery()?.matches ? 'light' : 'dark');\n\n/**\n * Resolves a preference to the mode a `ThemeProvider` selection takes.\n * `'auto'` subscribes to the OS setting and follows it live; an explicit\n * choice opts out of the subscription entirely.\n */\nexport function useResolvedColorMode(preference: ColorModePreference): ColorMode {\n const [system, setSystem] = useState<ColorMode>(systemMode);\n\n useEffect(() => {\n if (preference !== 'auto') return;\n const mq = systemQuery();\n if (!mq) return;\n // eslint-disable-next-line react-hooks/set-state-in-effect -- syncs to the OS color-scheme query\n setSystem(mq.matches ? 'light' : 'dark');\n const onChange = (e: { matches: boolean }) => setSystem(e.matches ? 'light' : 'dark');\n mq.addEventListener('change', onChange);\n return () => mq.removeEventListener('change', onChange);\n }, [preference]);\n\n return preference === 'auto' ? system : preference;\n}\n\n/** The part of `Storage` {@link useColorModePreference} reads and writes. */\nexport type ColorModeStorage = Pick<Storage, 'getItem' | 'setItem'>;\n\n/** Options for {@link useColorModePreference}. */\nexport interface ColorModePreferenceOptions {\n /** Where the choice is remembered. Unset, it lasts as long as the component. */\n readonly storageKey?: string;\n /** The store `storageKey` names a slot in. Defaults to `localStorage`. */\n readonly storage?: ColorModeStorage;\n /** The preference before the user has chosen one. Defaults to `'auto'`. */\n readonly defaultPreference?: ColorModePreference;\n}\n\n/** What {@link useColorModePreference} returns. */\nexport interface ColorModePreferenceState {\n readonly preference: ColorModePreference;\n readonly setPreference: (next: ColorModePreference) => void;\n /** `preference` resolved against the OS — what to put in the theme's `mode` axis. */\n readonly mode: ColorMode;\n}\n\nfunction defaultStorage(): ColorModeStorage | undefined {\n try {\n return globalThis.localStorage ?? undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A user's color-mode choice, optionally remembered across loads, and the mode\n * it resolves to. Storage that is missing or throws (a private window, blocked\n * site data) degrades to an unremembered choice rather than an error.\n */\nexport function useColorModePreference(\n options: ColorModePreferenceOptions = {},\n): ColorModePreferenceState {\n const { storageKey, storage, defaultPreference = 'auto' } = options;\n\n const [preference, setState] = useState<ColorModePreference>(() => {\n if (storageKey === undefined) return defaultPreference;\n try {\n const stored = (storage ?? defaultStorage())?.getItem(storageKey);\n return isColorModePreference(stored) ? stored : defaultPreference;\n } catch {\n return defaultPreference;\n }\n });\n\n const setPreference = useCallback(\n (next: ColorModePreference) => {\n setState(next);\n if (storageKey === undefined) return;\n try {\n (storage ?? defaultStorage())?.setItem(storageKey, next);\n } catch {\n // Unremembered, but still applied.\n }\n },\n [storageKey, storage],\n );\n\n return { preference, setPreference, mode: useResolvedColorMode(preference) };\n}\n","import { colorLiteralToHex, type ColorSource, type Palette } from '@weasel-js/paint';\nimport React, { createContext, useCallback, useContext, useMemo, useRef, useLayoutEffect } from 'react';\nimport { isDev } from '@weasel-js/registry';\nimport { applyTheme } from './applyTheme';\nimport { themeTints, type ColorList } from './colorList';\nimport { colorSourceCss, colorSourceLiteral } from './colorSource';\nimport { fullSelection, selectionKey, type Selection } from './axes';\nimport { resolveTheme, themeAxes, type ResolvedTheme } from './resolveTheme';\nimport { weaselTheme, type Theme } from './theme';\nimport { useResolvedColorMode } from './useColorMode';\n\nexport {\n useColorModePreference,\n useResolvedColorMode,\n type ColorModePreferenceOptions,\n type ColorModePreferenceState,\n type ColorModeStorage,\n} from './useColorMode';\nexport { isColorModePreference, type ColorMode, type ColorModePreference } from './colorMode';\n\n/** What `<ThemeProvider>` publishes: the theme, the full selection in force, the\n * fully resolved token record for that pair, and the tint list and palette in force. */\nexport interface ThemeContextValue {\n readonly theme: Theme;\n readonly selection: Selection;\n readonly resolved: ResolvedTheme;\n readonly tints: ColorList;\n readonly palette: Palette;\n}\n\n/** What `<ThemeProvider>` publishes. Provide `null` to hide an outer theme from a subtree, as a\n * boundary that renders its children the way a page with no provider would. */\nexport const ThemeContext = createContext<ThemeContextValue | null>(null);\n\nconst NO_PALETTE: Palette = { entries: [] };\n\n/** Props for `<ThemeProvider>`. */\nexport interface ThemeProviderProps {\n readonly theme?: Theme;\n /** Axis values, e.g. `{ mode: 'light' }`. A missing axis takes its default. `mode: 'auto'`\n * follows the OS setting, live; any other value the theme lacks takes the default, with a\n * warning in development. */\n readonly selection?: Selection;\n /** The colors a `tint` index picks from in this subtree. Absent: the theme's own. */\n readonly tints?: ColorList;\n /** Colors a `ColorRef` names in this subtree, answered before the theme's own names. Absent: none. */\n readonly palette?: Palette;\n /** Applied to the wrapper element, so it can be the layout element too. */\n readonly className?: string;\n readonly style?: React.CSSProperties;\n readonly children: React.ReactNode;\n}\n\n/**\n * Applies a theme to a wrapper element and publishes the resolved record.\n *\n * Consumers that draw outside the DOM (the WebGL HUD) read `resolved` and\n * never touch `getComputedStyle`.\n *\n * The wrapper is a real element in the layout. Pass `className` rather than\n * nesting your own div inside — an anonymous div between a flex parent and\n * its child breaks percentage heights.\n */\nexport function ThemeProvider({\n theme = weaselTheme,\n selection,\n tints,\n palette = NO_PALETTE,\n className,\n style,\n children,\n}: ThemeProviderProps): React.ReactElement {\n const ref = useRef<HTMLDivElement>(null);\n const axes = themeAxes(theme);\n const autoMode = selection?.mode === 'auto' && !('auto' in (axes.mode?.values ?? {}));\n const systemMode = useResolvedColorMode(autoMode ? 'auto' : 'dark');\n const given = autoMode ? { ...selection, mode: systemMode } : selection;\n const full = fullSelection(axes, given);\n warnUnknownAxisValues(theme, axes, given);\n // Keyed on the selection's content: callers pass a fresh object every render.\n const key = selectionKey(axes, full);\n\n const value = useMemo<ThemeContextValue>(\n () => ({ theme, selection: full, resolved: resolveTheme(theme, full), tints: tints ?? themeTints(theme), palette }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [theme, key, tints, palette],\n );\n\n // Applying again replaces what the element held, so only the unmount releases.\n const release = useRef<(() => void) | null>(null);\n useLayoutEffect(() => {\n if (ref.current) release.current = applyTheme(ref.current, theme, value.selection);\n }, [theme, value]);\n useLayoutEffect(() => () => release.current?.(), []);\n\n const attrs = Object.fromEntries(Object.keys(axes).map((a) => [`data-wzl-${a}`, full[a]]));\n return (\n <ThemeContext.Provider value={value}>\n <div ref={ref} className={className} style={style} data-wzl-theme={theme.name} {...attrs}>\n {children}\n </div>\n </ThemeContext.Provider>\n );\n}\n\nconst warned = new Set<string>();\n\nfunction warnUnknownAxisValues(theme: Theme, axes: ReturnType<typeof themeAxes>, selection: Selection | undefined): void {\n if (!selection || !isDev()) return;\n for (const [axis, value] of Object.entries(selection)) {\n const def = axes[axis];\n if (!def || value in def.values) continue;\n const key = `${theme.name}\\0${axis}\\0${value}`;\n if (warned.has(key)) continue;\n warned.add(key);\n console.warn(\n `[weasel theme] ThemeProvider: theme \"${theme.name}\" has no ${axis} \"${value}\"; using \"${def.default}\". Its ${axis} values: ${Object.keys(def.values).join(', ')}.`,\n );\n }\n}\n\n/** The theme in force. Throws outside a `<ThemeProvider>`; use\n * `useThemeOptional` where the provider is not guaranteed. */\nexport function useTheme(): ThemeContextValue {\n const ctx = useContext(ThemeContext);\n if (!ctx) throw new Error('useTheme must be used inside a <ThemeProvider>');\n return ctx;\n}\n\n/**\n * The theme if one is provided, `null` otherwise.\n *\n * For kit internals that should follow a theme when the app supplies one but\n * must still work in an app that never mounted a provider — `useHud` is the\n * motivating case.\n */\nexport function useThemeOptional(): ThemeContextValue | null {\n return useContext(ThemeContext);\n}\n\nlet defaultTints: ThemeContextValue | undefined;\n\n/**\n * The tint list in force and what it resolves against — the nearest\n * `<ThemeProvider>`'s, else the built-in theme's at its defaults. Pass the\n * result as `colorAt`'s context.\n */\nexport function useTints(): ThemeContextValue {\n const ctx = useContext(ThemeContext);\n if (ctx) return ctx;\n return (defaultTints ??= {\n theme: weaselTheme,\n selection: fullSelection(themeAxes(weaselTheme)),\n resolved: resolveTheme(weaselTheme),\n tints: themeTints(weaselTheme),\n palette: NO_PALETTE,\n });\n}\n\n/**\n * Turns a `ColorSource` into a CSS color under the theme, tints, and palette in\n * force: `colorSourceCss` against `useTints()`. Every component that takes a\n * color writes it through this. `undefined` for no source, and for one nothing\n * answers.\n */\nexport function useColorCss(): (source: ColorSource | null | undefined) => string | undefined {\n const ctx = useTints();\n return useCallback((source) => (source == null ? undefined : (colorSourceCss(source, ctx) ?? undefined)), [ctx]);\n}\n\n/**\n * Turns a `ColorSource` into a hex color under the theme, tints, and palette in force, for a\n * surface drawn without the cascade, such as a scene's paint. `useColorCss` may answer\n * `var(--wzl-…)`, which only the DOM resolves; this answers the value. `undefined` for no\n * source, and for one nothing answers.\n */\nexport function useColorHex(): (source: ColorSource | null | undefined) => string | undefined {\n const ctx = useTints();\n return useCallback((source) => {\n if (source == null) return undefined;\n const literal = colorSourceLiteral(source, ctx);\n return (literal && colorLiteralToHex(literal)) ?? undefined;\n }, [ctx]);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/useColorMode.ts","../src/react.tsx"],"names":["useCallback"],"mappings":";;;;;;;;;;;;;AASO,SAAS,qBAAqB,UAAA,EAA4C;AAC/E,EAAA,MAAM,MAAA,GAAS,oBAAA,CAAqB,UAAA,KAAe,MAAM,CAAA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,IAAI,MAAA,IAAU,MAAM,OAAO,MAAA;AAC3B,IAAA,MAAM,OAAA,GAAU,kBAAA,CAAmB,MAAA,EAAQ,GAAG,CAAA;AAC9C,IAAA,OAAA,CAAQ,OAAA,IAAW,iBAAA,CAAkB,OAAO,CAAA,KAAM,MAAA;AAAA,EACpD,CAAA,EAAG,CAAC,GAAG,CAAC,CAAA;AACV","file":"react.js","sourcesContent":["import { useSystemColorScheme } from '@weasel-js/react';\nimport { useCallback, useState } from 'react';\nimport { isColorModePreference, type ColorMode, type ColorModePreference } from './colorMode';\n\n/**\n * Resolves a preference to the mode a `ThemeProvider` selection takes.\n * `'auto'` subscribes to the OS setting and follows it live, dark where the OS\n * says nothing; an explicit choice opts out of the subscription entirely.\n */\nexport function useResolvedColorMode(preference: ColorModePreference): ColorMode {\n const system = useSystemColorScheme(preference === 'auto');\n return preference === 'auto' ? system : preference;\n}\n\n/** The part of `Storage` {@link useColorModePreference} reads and writes. */\nexport type ColorModeStorage = Pick<Storage, 'getItem' | 'setItem'>;\n\n/** Options for {@link useColorModePreference}. */\nexport interface ColorModePreferenceOptions {\n /** Where the choice is remembered. Unset, it lasts as long as the component. */\n readonly storageKey?: string;\n /** The store `storageKey` names a slot in. Defaults to `localStorage`. */\n readonly storage?: ColorModeStorage;\n /** The preference before the user has chosen one. Defaults to `'auto'`. */\n readonly defaultPreference?: ColorModePreference;\n}\n\n/** What {@link useColorModePreference} returns. */\nexport interface ColorModePreferenceState {\n readonly preference: ColorModePreference;\n readonly setPreference: (next: ColorModePreference) => void;\n /** `preference` resolved against the OS — what to put in the theme's `mode` axis. */\n readonly mode: ColorMode;\n}\n\nfunction defaultStorage(): ColorModeStorage | undefined {\n try {\n return globalThis.localStorage ?? undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A user's color-mode choice, optionally remembered across loads, and the mode\n * it resolves to. Storage that is missing or throws (a private window, blocked\n * site data) degrades to an unremembered choice rather than an error.\n */\nexport function useColorModePreference(\n options: ColorModePreferenceOptions = {},\n): ColorModePreferenceState {\n const { storageKey, storage, defaultPreference = 'auto' } = options;\n\n const [preference, setState] = useState<ColorModePreference>(() => {\n if (storageKey === undefined) return defaultPreference;\n try {\n const stored = (storage ?? defaultStorage())?.getItem(storageKey);\n return isColorModePreference(stored) ? stored : defaultPreference;\n } catch {\n return defaultPreference;\n }\n });\n\n const setPreference = useCallback(\n (next: ColorModePreference) => {\n setState(next);\n if (storageKey === undefined) return;\n try {\n (storage ?? defaultStorage())?.setItem(storageKey, next);\n } catch {\n // Unremembered, but still applied.\n }\n },\n [storageKey, storage],\n );\n\n return { preference, setPreference, mode: useResolvedColorMode(preference) };\n}\n","import { colorLiteralToHex, type ColorSource, type Palette } from '@weasel-js/paint';\nimport React, { createContext, useCallback, useContext, useMemo, useRef, useLayoutEffect } from 'react';\nimport { isDev } from '@weasel-js/registry';\nimport { applyTheme } from './applyTheme';\nimport { themeTints, type ColorList } from './colorListItems';\nimport { colorSourceCss, colorSourceLiteral } from './colorSource';\nimport { fullSelection, selectionKey, type Selection } from './axes';\nimport { resolveTheme, themeAxes, type ResolvedTheme } from './resolveTheme';\nimport { weaselTheme, type Theme } from './theme';\nimport { useResolvedColorMode } from './useColorMode';\n\nexport {\n useColorModePreference,\n useResolvedColorMode,\n type ColorModePreferenceOptions,\n type ColorModePreferenceState,\n type ColorModeStorage,\n} from './useColorMode';\nexport { isColorModePreference, type ColorMode, type ColorModePreference } from './colorMode';\n\n/** What `<ThemeProvider>` publishes: the theme, the full selection in force, the\n * fully resolved token record for that pair, and the tint list and palette in force. */\nexport interface ThemeContextValue {\n readonly theme: Theme;\n readonly selection: Selection;\n readonly resolved: ResolvedTheme;\n readonly tints: ColorList;\n readonly palette: Palette;\n}\n\n/** What `<ThemeProvider>` publishes. Provide `null` to hide an outer theme from a subtree, as a\n * boundary that renders its children the way a page with no provider would. */\nexport const ThemeContext = createContext<ThemeContextValue | null>(null);\n\nconst NO_PALETTE: Palette = { entries: [] };\n\n/** Props for `<ThemeProvider>`. */\nexport interface ThemeProviderProps {\n readonly theme?: Theme;\n /** Axis values, e.g. `{ mode: 'light' }`. A missing axis takes its default. `mode: 'auto'`\n * follows the OS setting, live; any other value the theme lacks takes the default, with a\n * warning in development. */\n readonly selection?: Selection;\n /** The colors a `tint` index picks from in this subtree. Absent: the theme's own. */\n readonly tints?: ColorList;\n /** Colors a `ColorRef` names in this subtree, answered before the theme's own names. Absent: none. */\n readonly palette?: Palette;\n /** Applied to the wrapper element, so it can be the layout element too. */\n readonly className?: string;\n readonly style?: React.CSSProperties;\n readonly children: React.ReactNode;\n}\n\n/**\n * Applies a theme to a wrapper element and publishes the resolved record.\n *\n * Consumers that draw outside the DOM (the WebGL HUD) read `resolved` and\n * never touch `getComputedStyle`.\n *\n * The wrapper is a real element in the layout. Pass `className` rather than\n * nesting your own div inside — an anonymous div between a flex parent and\n * its child breaks percentage heights.\n */\nexport function ThemeProvider({\n theme = weaselTheme,\n selection,\n tints,\n palette = NO_PALETTE,\n className,\n style,\n children,\n}: ThemeProviderProps): React.ReactElement {\n const ref = useRef<HTMLDivElement>(null);\n const axes = themeAxes(theme);\n const autoMode = selection?.mode === 'auto' && !('auto' in (axes.mode?.values ?? {}));\n const systemMode = useResolvedColorMode(autoMode ? 'auto' : 'dark');\n const given = autoMode ? { ...selection, mode: systemMode } : selection;\n const full = fullSelection(axes, given);\n warnUnknownAxisValues(theme, axes, given);\n // Keyed on the selection's content: callers pass a fresh object every render.\n const key = selectionKey(axes, full);\n\n const value = useMemo<ThemeContextValue>(\n () => ({ theme, selection: full, resolved: resolveTheme(theme, full), tints: tints ?? themeTints(theme), palette }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [theme, key, tints, palette],\n );\n\n // Applying again replaces what the element held, so only the unmount releases.\n const release = useRef<(() => void) | null>(null);\n useLayoutEffect(() => {\n if (ref.current) release.current = applyTheme(ref.current, theme, value.selection);\n }, [theme, value]);\n useLayoutEffect(() => () => release.current?.(), []);\n\n const attrs = Object.fromEntries(Object.keys(axes).map((a) => [`data-wzl-${a}`, full[a]]));\n return (\n <ThemeContext.Provider value={value}>\n <div ref={ref} className={className} style={style} data-wzl-theme={theme.name} {...attrs}>\n {children}\n </div>\n </ThemeContext.Provider>\n );\n}\n\nconst warned = new Set<string>();\n\nfunction warnUnknownAxisValues(theme: Theme, axes: ReturnType<typeof themeAxes>, selection: Selection | undefined): void {\n if (!selection || !isDev()) return;\n for (const [axis, value] of Object.entries(selection)) {\n const def = axes[axis];\n if (!def || value in def.values) continue;\n const key = `${theme.name}\\0${axis}\\0${value}`;\n if (warned.has(key)) continue;\n warned.add(key);\n console.warn(\n `[weasel theme] ThemeProvider: theme \"${theme.name}\" has no ${axis} \"${value}\"; using \"${def.default}\". Its ${axis} values: ${Object.keys(def.values).join(', ')}.`,\n );\n }\n}\n\n/** The theme in force. Throws outside a `<ThemeProvider>`; use\n * `useThemeOptional` where the provider is not guaranteed. */\nexport function useTheme(): ThemeContextValue {\n const ctx = useContext(ThemeContext);\n if (!ctx) throw new Error('useTheme must be used inside a <ThemeProvider>');\n return ctx;\n}\n\n/**\n * The theme if one is provided, `null` otherwise.\n *\n * For kit internals that should follow a theme when the app supplies one but\n * must still work in an app that never mounted a provider — `useHud` is the\n * motivating case.\n */\nexport function useThemeOptional(): ThemeContextValue | null {\n return useContext(ThemeContext);\n}\n\nlet defaultTints: ThemeContextValue | undefined;\n\n/**\n * The tint list in force and what it resolves against — the nearest\n * `<ThemeProvider>`'s, else the built-in theme's at its defaults. Pass the\n * result as `colorAt`'s context.\n */\nexport function useTints(): ThemeContextValue {\n const ctx = useContext(ThemeContext);\n if (ctx) return ctx;\n return (defaultTints ??= {\n theme: weaselTheme,\n selection: fullSelection(themeAxes(weaselTheme)),\n resolved: resolveTheme(weaselTheme),\n tints: themeTints(weaselTheme),\n palette: NO_PALETTE,\n });\n}\n\n/**\n * Turns a `ColorSource` into a CSS color under the theme, tints, and palette in\n * force: `colorSourceCss` against `useTints()`. Every component that takes a\n * color writes it through this. `undefined` for no source, and for one nothing\n * answers.\n */\nexport function useColorCss(): (source: ColorSource | null | undefined) => string | undefined {\n const ctx = useTints();\n return useCallback((source) => (source == null ? undefined : (colorSourceCss(source, ctx) ?? undefined)), [ctx]);\n}\n\n/**\n * Turns a `ColorSource` into a hex color under the theme, tints, and palette in force, for a\n * surface drawn without the cascade, such as a scene's paint. `useColorCss` may answer\n * `var(--wzl-…)`, which only the DOM resolves; this answers the value. `undefined` for no\n * source, and for one nothing answers.\n */\nexport function useColorHex(): (source: ColorSource | null | undefined) => string | undefined {\n const ctx = useTints();\n return useCallback((source) => {\n if (source == null) return undefined;\n const literal = colorSourceLiteral(source, ctx);\n return (literal && colorLiteralToHex(literal)) ?? undefined;\n }, [ctx]);\n}\n"]}
|
package/dist/themes/platinum.js
CHANGED
package/dist/themes/win9x.d.ts
CHANGED
package/dist/themes/win9x.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weasel-js/theme",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"description": "Design tokens shared by weasel-ui and weasel-hud — CSS variables + a parallel TS export.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -43,9 +43,10 @@
|
|
|
43
43
|
"./package.json": "./package.json"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@weasel-js/paint": "1.
|
|
47
|
-
"@weasel-js/prefs": "1.
|
|
48
|
-
"@weasel-js/
|
|
46
|
+
"@weasel-js/paint": "1.16.0",
|
|
47
|
+
"@weasel-js/prefs": "1.16.0",
|
|
48
|
+
"@weasel-js/react": "1.16.0",
|
|
49
|
+
"@weasel-js/registry": "1.16.0"
|
|
49
50
|
},
|
|
50
51
|
"peerDependencies": {
|
|
51
52
|
"react": ">=18"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dtcg/value.ts","../src/chainT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,CAAA;AACpF;AAUO,SAAS,YAAA,CAAa,KAAA,EAAc,SAAA,GAAuB,EAAC,EAAkB;AACnF,EAAA,MAAM,GAAA,GAAM,aAAA,CAAc,SAAA,CAAU,KAAK,GAAG,SAAS,CAAA;AACrD,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,cAAc,QAAA,CAAS,UAAA,CAAW,KAAK,CAAA,EAAG,GAAG,CAAC,CAAC,CAAA,MAAO,CAAA,MAAA,EAAS,IAAI,EAAE,CAAA,GAAI,KAAA;AACpH,EAAA,OAAO,GAAA;AACT","file":"chunk-32JKTYS2.js","sourcesContent":["import type { TokenValue } from './types.ts';\n\n/**\n * Quote family names containing whitespace; leave everything else bare.\n * Generic keywords (`sans-serif`) and hyphen-prefixed identifiers\n * (`-apple-system`) break if quoted, and neither contains a space.\n */\nfunction fontStack(value: readonly (string | number)[]): string {\n return value.map((f) => (typeof f === 'string' && /\\s/.test(f) ? `'${f}'` : String(f))).join(', ');\n}\n\n/**\n * A token's value as CSS renders it. A DTCG value is not always a string: a\n * `fontFamily` is a list of names and a `cubicBezier` is four numbers, and both\n * have a spelling that belongs in a stylesheet rather than in JSON.\n */\nexport function serializeTokenValue(type: string, value: TokenValue): string {\n if (Array.isArray(value)) {\n if (type === 'cubicBezier') return `cubic-bezier(${value.join(', ')})`;\n if (type === 'fontFamily') return fontStack(value);\n return value.join(', ');\n }\n return String(value);\n}\n\nconst BEZIER = /^cubic-bezier\\(\\s*([^)]*)\\)$/i;\n\n/**\n * The inverse of {@link serializeTokenValue}: text a person edited, back in the\n * shape a definition stores. Text that does not parse for its type is kept as\n * text rather than thrown away, so a half-typed value stays editable.\n */\nexport function parseTokenValue(type: string, text: string): TokenValue {\n const raw = text.trim();\n if (type === 'cubicBezier') {\n const inner = BEZIER.exec(raw)?.[1] ?? raw;\n const parts = inner.split(',').map((p) => Number(p.trim()));\n return parts.length === 4 && parts.every((n) => Number.isFinite(n)) ? parts : raw;\n }\n if (type === 'fontFamily') {\n const families = raw\n .split(',')\n .map((f) => f.trim().replace(/^['\"]|['\"]$/g, '').trim())\n .filter((f) => f !== '');\n return families.length > 0 ? families : raw;\n }\n return raw;\n}\n","import { fullSelection, mergeAxes, pick, type AxisDefs, type Selection, type Varying } from './axes.ts';\nimport type { FlatTokens, RawToken } from './dtcg/types.ts';\n\n/** One theme of an `extends` chain, as far as choosing its tokens goes. */\nexport interface ChainLink {\n readonly axes: AxisDefs;\n readonly tokens: Readonly<Record<string, Varying<RawToken>>>;\n}\n\n/**\n * The selection each theme of a root-first chain reads its own tokens at. An axis value a theme and\n * everything it extends never declared (one a descendant added) becomes that theme's default for the\n * axis, which is what the stylesheet's cascade gives it: no block of the ancestor matches the new\n * value, so its default declarations show through.\n */\nfunction localSelections(chain: readonly ChainLink[], selection: Selection): Selection[] {\n let axes: AxisDefs = {};\n return chain.map((link) => {\n axes = mergeAxes(axes, link.axes);\n return { ...selection, ...fullSelection(axes, selection) };\n });\n}\n\n/** `name` from the nearest theme of a root-first chain that has it at `selection`. */\nexport function tokenAt(chain: readonly ChainLink[], name: string, selection: Selection): RawToken | undefined {\n const local = localSelections(chain, selection);\n for (let i = chain.length - 1; i >= 0; i--) {\n const { tokens } = chain[i];\n if (!Object.hasOwn(tokens, name)) continue;\n const picked = pick(tokens[name], local[i]);\n if (picked.ok) return picked.value;\n }\n return undefined;\n}\n\n/** Every token of a root-first chain at `selection`, each from the nearest theme that has it there. */\nexport function tokensAt(chain: readonly ChainLink[], selection: Selection): FlatTokens {\n const local = localSelections(chain, selection);\n const out: Record<string, RawToken> = {};\n chain.forEach((link, i) => {\n for (const [name, v] of Object.entries(link.tokens)) {\n const picked = pick(v, local[i]);\n if (picked.ok) out[name] = picked.value;\n }\n });\n return out;\n}\n","import { parseHexBytes } from '@weasel-js/paint';\n\n/**\n * A resolved color at `alpha`, multiplied into any alpha it already carries. The\n * JS side of the alpha extension; the CSS side emits `color-mix()` instead so DOM\n * chrome keeps tracking a downstream override of the referenced token.\n *\n * Hex and `rgb()`/`rgba()` become an `rgba()` literal. Anything else — a named\n * color, `hsl()`, `oklch()`, a `var()` — becomes the same `color-mix()` the CSS\n * side writes, which the browser resolves.\n */\nexport function withAlpha(color: string, alpha: number): string {\n const rgba = parseRgba(color.trim());\n if (!rgba) return mixAlpha(color.trim(), alpha);\n const [r, g, b, a] = rgba;\n return `rgba(${r}, ${g}, ${b}, ${round(a * alpha, 3)})`;\n}\n\n/** `color` at `alpha` as a `color-mix()` with transparent, for a color only the browser can resolve. */\nexport function mixAlpha(color: string, alpha: number): string {\n return `color-mix(in srgb, ${color} ${round(alpha * 100, 4)}%, transparent)`;\n}\n\n/** A resolved color with its alpha replaced by `alpha`, as `rgb(from c r g b / alpha)` computes it. */\nexport function atAlpha(color: string, alpha: number): string {\n const rgba = parseRgba(color.trim());\n if (!rgba) return `rgb(from ${color.trim()} r g b / ${alpha})`;\n const [r, g, b] = rgba;\n return `rgba(${r}, ${g}, ${b}, ${round(alpha, 3)})`;\n}\n\ntype Rgba = [number, number, number, number];\n\nfunction round(n: number, places: number): number {\n return Number(n.toFixed(places));\n}\n\nfunction parseRgba(s: string): Rgba | null {\n if (s.toLowerCase() === 'transparent') return [0, 0, 0, 0];\n return parseHex(s) ?? parseRgbFn(s);\n}\n\nfunction parseHex(s: string): Rgba | null {\n const bytes = parseHexBytes(s);\n return bytes && [bytes[0], bytes[1], bytes[2], bytes[3] / 255];\n}\n\nfunction parseRgbFn(s: string): Rgba | null {\n const m = /^rgba?\\(([^()]*)\\)$/i.exec(s);\n if (!m) return null;\n const [channels, alphaPart, extra] = m[1].split('/');\n if (extra !== undefined) return null;\n const parts = channels.trim().split(/\\s*,\\s*|\\s+/);\n if (alphaPart !== undefined) parts.push(alphaPart.trim());\n if (parts.length !== 3 && parts.length !== 4) return null;\n\n const channel = (p: string) => (p.endsWith('%') ? (Number.parseFloat(p) / 100) * 255 : Number(p));\n const alpha = (p: string) => (p.endsWith('%') ? Number.parseFloat(p) / 100 : Number(p));\n const [r, g, b] = parts.slice(0, 3).map(channel);\n const a = parts[3] === undefined ? 1 : alpha(parts[3]);\n if (![r, g, b, a].every(Number.isFinite)) return null;\n return [Math.round(r), Math.round(g), Math.round(b), a];\n}\n","import { withAlpha } from './color.ts';\nimport type { FlatTokens, ResolvedTokenMap, TokenValue } from './types.ts';\nimport { serializeTokenValue } from './value.ts';\n\n/** `{color.gray-100}` → `gray-100`. The type group is dropped, per the naming rule. */\nconst REF = /^\\{([^}]+)\\}$/;\n\nfunction refTarget(value: TokenValue): string | null {\n if (typeof value !== 'string') return null;\n const m = REF.exec(value.trim());\n if (!m) return null;\n const path = m[1];\n const dot = path.indexOf('.');\n return dot === -1 ? path : path.slice(dot + 1);\n}\n\n/**\n * Resolve flat tokens to final CSS-ready strings.\n *\n * Merge modes before calling: this function has no notion of modes, only of a\n * complete token set.\n */\nexport function resolveTokens(tokens: FlatTokens): ResolvedTokenMap {\n const out: ResolvedTokenMap = {};\n const inProgress = new Set<string>();\n\n const resolveOne = (name: string): string => {\n const cached = out[name];\n if (cached !== undefined) return cached;\n\n const token = tokens[name];\n if (!token) throw new Error(`Unknown token \"${name}\"`);\n\n if (inProgress.has(name)) {\n throw new Error(`Reference cycle at token \"${name}\" (${[...inProgress].join(' → ')})`);\n }\n inProgress.add(name);\n\n const target = refTarget(token.value);\n let value: string;\n if (target === null) {\n value = serializeTokenValue(token.type, token.value);\n } else if (!tokens[target]) {\n throw new Error(`Token \"${name}\" references \"${target}\", which is not defined`);\n } else {\n value = resolveOne(target);\n }\n\n if (token.alpha !== undefined) value = withAlpha(value, token.alpha);\n\n inProgress.delete(name);\n out[name] = value;\n return value;\n };\n\n for (const name of Object.keys(tokens)) resolveOne(name);\n return out;\n}\n\n/** Merge a mode's tokens over the mode-invariant set. Later wins. */\nexport function mergeTokens(base: FlatTokens, mode: FlatTokens): FlatTokens {\n return { ...base, ...mode };\n}\n","import { fullSelection, mergeAxes, type AxisDefs, type Selection } from './axes.ts';\nimport { tokensAt } from './chainTokens.ts';\nimport { resolveTokens } from './dtcg/resolve.ts';\nimport type { TokenName } from './generated/themes.ts';\nimport type { Theme } from './theme.ts';\n\n/** The output of `resolveTheme`: every token of a theme, for one selection, keyed\n * by CSS custom-property name and flattened to a final CSS value. */\nexport type ResolvedTheme = Readonly<Record<TokenName, string>>;\n\n/** Root-first, so the leaf theme's tokens land last. */\nexport function themeChain(theme: Theme): Theme[] {\n const out: Theme[] = [];\n for (let t: Theme | null = theme; t; t = t.extends) out.unshift(t);\n return out;\n}\n\n/** Every axis the chain declares. An axis declared more than once keeps every value; a descendant's value entries and default win. */\nexport function themeAxes(theme: Theme): AxisDefs {\n return themeChain(theme).reduce<AxisDefs>((axes, t) => mergeAxes(axes, t.axes), {});\n}\n\n/**\n * Merge the extends chain at a selection, resolve every alias, and key the\n * result by CSS custom-property name. A missing or unknown axis value takes the\n * axis default, and a theme in the chain reads a value it never declared at its\n * own default for that axis.\n *\n * Pure — no DOM. An unresolvable reference throws rather than falling back.\n */\nexport function resolveTheme(theme: Theme, selection: Selection = {}): ResolvedTheme {\n const sel = fullSelection(themeAxes(theme), selection);\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(resolveTokens(tokensAt(themeChain(theme), sel)))) out[`--wzl-${name}`] = value;\n return out as ResolvedTheme;\n}\n"]}
|