1
0
Fork 0

worked on GarageApp stuff

This commit is contained in:
Techognito 2025-08-25 17:46:11 +02:00
parent 60aaf17af3
commit eb606572b0
51919 changed files with 2168177 additions and 18 deletions

View file

@ -0,0 +1,141 @@
import * as React from 'react';
import InitColorSchemeScript from "../InitColorSchemeScript/index.js";
import { Result } from "./useCurrentColorScheme.js";
import type { StorageManager } from "./localStorageManager.js";
export interface ColorSchemeContextValue<SupportedColorScheme extends string> extends Result<SupportedColorScheme> {
allColorSchemes: SupportedColorScheme[];
}
export interface CssVarsProviderConfig<ColorScheme extends string> {
/**
* DOM attribute for applying color scheme
* @default 'data-color-scheme'
*/
attribute?: string;
/**
* localStorage key used to store application `mode`
* @default 'mode'
*/
modeStorageKey?: string;
/**
* localStorage key used to store `colorScheme`
* @default 'color-scheme'
*/
colorSchemeStorageKey?: string;
/**
* Design system default color scheme.
* - provides string if the design system has one default color scheme (either light or dark)
* - provides object if the design system has default light & dark color schemes
*/
defaultColorScheme: ColorScheme | {
light: ColorScheme;
dark: ColorScheme;
};
/**
* Disable CSS transitions when switching between modes or color schemes
* @default false
*/
disableTransitionOnChange?: boolean;
/**
* If `true`, theme values are recalculated when the mode changes.
* The `theme.colorSchemes.{mode}.*` nodes will be shallow merged to the top-level of the theme.
* @default false
*/
forceThemeRerender?: boolean;
}
type Identify<I extends string | undefined, T> = I extends string ? T | { [k in I]: T } : T;
export interface CreateCssVarsProviderResult<ColorScheme extends string, Identifier extends string | undefined = undefined> {
CssVarsProvider: (props: React.PropsWithChildren<Partial<CssVarsProviderConfig<ColorScheme>> & {
theme?: Identify<Identifier, {
cssVariables?: false;
cssVarPrefix?: string;
colorSchemes: Partial<Record<ColorScheme, any>>;
colorSchemeSelector?: 'media' | 'class' | 'data' | string;
}>;
/**
* The default mode when the storage is empty,
* require the theme to have `colorSchemes` with light and dark.
* @default 'system'
*/
defaultMode?: 'light' | 'dark' | 'system';
/**
* The document used to perform `disableTransitionOnChange` feature
* @default document
*/
documentNode?: Document | null;
/**
* The node used to attach the color-scheme attribute
* @default document
*/
colorSchemeNode?: Element | null;
/**
* The storage manager to be used for storing the mode and color scheme.
* @default using `window.localStorage`
*/
storageManager?: StorageManager | null;
/**
* The window that attaches the 'storage' event listener
* @default window
*/
storageWindow?: Window | null;
/**
* If `true`, the provider creates its own context and generate stylesheet as if it is a root `CssVarsProvider`.
*/
disableNestedContext?: boolean;
/**
* If `true`, the style sheet won't be generated.
*
* This is useful for controlling nested CssVarsProvider behavior.
* @default false
*/
disableStyleSheetGeneration?: boolean;
}>) => React.JSX.Element;
useColorScheme: () => ColorSchemeContextValue<ColorScheme>;
getInitColorSchemeScript: typeof InitColorSchemeScript;
}
export default function createCssVarsProvider<ColorScheme extends string, Identifier extends string | undefined = undefined>(options: CssVarsProviderConfig<ColorScheme> & {
/**
* The design system's unique id for getting the corresponded theme when there are multiple design systems.
*/
themeId?: Identifier;
/**
* Design system default theme
*
* - The structure inside `theme.colorSchemes[colorScheme]` should be exactly the same in all color schemes because
* those object of the color scheme will be used when the color scheme is active.
*
* {
* colorSchemes: {
* light: { ...lightColorSchemeValues },
* dark: { ...darkColorSchemeValues }
* }
* }
*
* - If colorScheme is 'light', the `lightColorSchemeValues` will be merged to theme as `{ ...theme, ...lightColorSchemeValues }`
* likewise, if colorScheme is 'dark', the `darkColorSchemeValues` will be merged to theme as `{ ...theme, ...darkColorSchemeValues }`
*
* - If the theme contains the same keys as the color scheme, their values will be merged.
* Ex. {
* colorSchemes: {
* light: { palette: { primary: { ... } } },
* dark: { palette: { primary: { ...} } }
* },
* palette: { shared: { ... } }
* }
*
* becomes: {
* colorSchemes: { ... },
* palette: { shared: { ... }, primary: { ... } }
* }
*/
theme: any;
/**
* A function to be called after the CSS variables are attached. The result of this function will be the final theme pass to ThemeProvider.
*
* The example usage is the variant generation in Joy. We need to combine the token from user-input and the default theme first, then generate
* variants from those tokens.
*/
resolveTheme?: (theme: any) => any; // the type is any because it depends on the design system.
}): CreateCssVarsProviderResult<ColorScheme, Identifier>;
// disable automatic export
export {};

View file

@ -0,0 +1,346 @@
"use strict";
'use client';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DISABLE_CSS_TRANSITION = void 0;
exports.default = createCssVarsProvider;
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _styledEngine = require("@mui/styled-engine");
var _privateTheming = require("@mui/private-theming");
var _useEnhancedEffect = _interopRequireDefault(require("@mui/utils/useEnhancedEffect"));
var _ThemeProvider = _interopRequireDefault(require("../ThemeProvider"));
var _InitColorSchemeScript = _interopRequireWildcard(require("../InitColorSchemeScript/InitColorSchemeScript"));
var _useCurrentColorScheme = _interopRequireDefault(require("./useCurrentColorScheme"));
var _jsxRuntime = require("react/jsx-runtime");
const DISABLE_CSS_TRANSITION = exports.DISABLE_CSS_TRANSITION = '*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}';
function createCssVarsProvider(options) {
const {
themeId,
/**
* This `theme` object needs to follow a certain structure to
* be used correctly by the finel `CssVarsProvider`. It should have a
* `colorSchemes` key with the light and dark (and any other) palette.
* It should also ideally have a vars object created using `prepareCssVars`.
*/
theme: defaultTheme = {},
modeStorageKey: defaultModeStorageKey = _InitColorSchemeScript.DEFAULT_MODE_STORAGE_KEY,
colorSchemeStorageKey: defaultColorSchemeStorageKey = _InitColorSchemeScript.DEFAULT_COLOR_SCHEME_STORAGE_KEY,
disableTransitionOnChange: designSystemTransitionOnChange = false,
defaultColorScheme,
resolveTheme
} = options;
const defaultContext = {
allColorSchemes: [],
colorScheme: undefined,
darkColorScheme: undefined,
lightColorScheme: undefined,
mode: undefined,
setColorScheme: () => {},
setMode: () => {},
systemMode: undefined
};
const ColorSchemeContext = /*#__PURE__*/React.createContext(undefined);
if (process.env.NODE_ENV !== 'production') {
ColorSchemeContext.displayName = 'ColorSchemeContext';
}
const useColorScheme = () => React.useContext(ColorSchemeContext) || defaultContext;
const defaultColorSchemes = {};
const defaultComponents = {};
function CssVarsProvider(props) {
const {
children,
theme: themeProp,
modeStorageKey = defaultModeStorageKey,
colorSchemeStorageKey = defaultColorSchemeStorageKey,
disableTransitionOnChange = designSystemTransitionOnChange,
storageManager,
storageWindow = typeof window === 'undefined' ? undefined : window,
documentNode = typeof document === 'undefined' ? undefined : document,
colorSchemeNode = typeof document === 'undefined' ? undefined : document.documentElement,
disableNestedContext = false,
disableStyleSheetGeneration = false,
defaultMode: initialMode = 'system',
forceThemeRerender = false,
noSsr
} = props;
const hasMounted = React.useRef(false);
const upperTheme = (0, _privateTheming.useTheme)();
const ctx = React.useContext(ColorSchemeContext);
const nested = !!ctx && !disableNestedContext;
const initialTheme = React.useMemo(() => {
if (themeProp) {
return themeProp;
}
return typeof defaultTheme === 'function' ? defaultTheme() : defaultTheme;
}, [themeProp]);
const scopedTheme = initialTheme[themeId];
const restThemeProp = scopedTheme || initialTheme;
const {
colorSchemes = defaultColorSchemes,
components = defaultComponents,
cssVarPrefix
} = restThemeProp;
const joinedColorSchemes = Object.keys(colorSchemes).filter(k => !!colorSchemes[k]).join(',');
const allColorSchemes = React.useMemo(() => joinedColorSchemes.split(','), [joinedColorSchemes]);
const defaultLightColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.light;
const defaultDarkColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.dark;
const defaultMode = colorSchemes[defaultLightColorScheme] && colorSchemes[defaultDarkColorScheme] ? initialMode : colorSchemes[restThemeProp.defaultColorScheme]?.palette?.mode || restThemeProp.palette?.mode;
// 1. Get the data about the `mode`, `colorScheme`, and setter functions.
const {
mode: stateMode,
setMode,
systemMode,
lightColorScheme,
darkColorScheme,
colorScheme: stateColorScheme,
setColorScheme
} = (0, _useCurrentColorScheme.default)({
supportedColorSchemes: allColorSchemes,
defaultLightColorScheme,
defaultDarkColorScheme,
modeStorageKey,
colorSchemeStorageKey,
defaultMode,
storageManager,
storageWindow,
noSsr
});
let mode = stateMode;
let colorScheme = stateColorScheme;
if (nested) {
mode = ctx.mode;
colorScheme = ctx.colorScheme;
}
if (process.env.NODE_ENV !== 'production') {
if (forceThemeRerender && !restThemeProp.vars) {
console.warn(['MUI: The `forceThemeRerender` prop should only be used with CSS theme variables.', 'Note that it will slow down the app when changing between modes, so only do this when you cannot find a better solution.'].join('\n'));
}
}
// `colorScheme` is undefined on the server and hydration phase
let calculatedColorScheme = colorScheme || restThemeProp.defaultColorScheme;
if (restThemeProp.vars && !forceThemeRerender) {
calculatedColorScheme = restThemeProp.defaultColorScheme;
}
const memoTheme = React.useMemo(() => {
// 2. get the `vars` object that refers to the CSS custom properties
const themeVars = restThemeProp.generateThemeVars?.() || restThemeProp.vars;
// 3. Start composing the theme object
const theme = {
...restThemeProp,
components,
colorSchemes,
cssVarPrefix,
vars: themeVars
};
if (typeof theme.generateSpacing === 'function') {
theme.spacing = theme.generateSpacing();
}
// 4. Resolve the color scheme and merge it to the theme
if (calculatedColorScheme) {
const scheme = colorSchemes[calculatedColorScheme];
if (scheme && typeof scheme === 'object') {
// 4.1 Merge the selected color scheme to the theme
Object.keys(scheme).forEach(schemeKey => {
if (scheme[schemeKey] && typeof scheme[schemeKey] === 'object') {
// shallow merge the 1st level structure of the theme.
theme[schemeKey] = {
...theme[schemeKey],
...scheme[schemeKey]
};
} else {
theme[schemeKey] = scheme[schemeKey];
}
});
}
}
return resolveTheme ? resolveTheme(theme) : theme;
}, [restThemeProp, calculatedColorScheme, components, colorSchemes, cssVarPrefix]);
// 5. Declaring effects
// 5.1 Updates the selector value to use the current color scheme which tells CSS to use the proper stylesheet.
const colorSchemeSelector = restThemeProp.colorSchemeSelector;
(0, _useEnhancedEffect.default)(() => {
if (colorScheme && colorSchemeNode && colorSchemeSelector && colorSchemeSelector !== 'media') {
const selector = colorSchemeSelector;
let rule = colorSchemeSelector;
if (selector === 'class') {
rule = `.%s`;
}
if (selector === 'data') {
rule = `[data-%s]`;
}
if (selector?.startsWith('data-') && !selector.includes('%s')) {
// 'data-mui-color-scheme' -> '[data-mui-color-scheme="%s"]'
rule = `[${selector}="%s"]`;
}
if (rule.startsWith('.')) {
colorSchemeNode.classList.remove(...allColorSchemes.map(scheme => rule.substring(1).replace('%s', scheme)));
colorSchemeNode.classList.add(rule.substring(1).replace('%s', colorScheme));
} else {
const matches = rule.replace('%s', colorScheme).match(/\[([^\]]+)\]/);
if (matches) {
const [attr, value] = matches[1].split('=');
if (!value) {
// for attributes like `data-theme-dark`, `data-theme-light`
// remove all the existing data attributes before setting the new one
allColorSchemes.forEach(scheme => {
colorSchemeNode.removeAttribute(attr.replace(colorScheme, scheme));
});
}
colorSchemeNode.setAttribute(attr, value ? value.replace(/"|'/g, '') : '');
} else {
colorSchemeNode.setAttribute(rule, colorScheme);
}
}
}
}, [colorScheme, colorSchemeSelector, colorSchemeNode, allColorSchemes]);
// 5.2 Remove the CSS transition when color scheme changes to create instant experience.
// credit: https://github.com/pacocoursey/next-themes/blob/b5c2bad50de2d61ad7b52a9c5cdc801a78507d7a/index.tsx#L313
React.useEffect(() => {
let timer;
if (disableTransitionOnChange && hasMounted.current && documentNode) {
const css = documentNode.createElement('style');
css.appendChild(documentNode.createTextNode(DISABLE_CSS_TRANSITION));
documentNode.head.appendChild(css);
// Force browser repaint
(() => window.getComputedStyle(documentNode.body))();
timer = setTimeout(() => {
documentNode.head.removeChild(css);
}, 1);
}
return () => {
clearTimeout(timer);
};
}, [colorScheme, disableTransitionOnChange, documentNode]);
React.useEffect(() => {
hasMounted.current = true;
return () => {
hasMounted.current = false;
};
}, []);
const contextValue = React.useMemo(() => ({
allColorSchemes,
colorScheme,
darkColorScheme,
lightColorScheme,
mode,
setColorScheme,
setMode: process.env.NODE_ENV === 'production' ? setMode : newMode => {
if (memoTheme.colorSchemeSelector === 'media') {
console.error(['MUI: The `setMode` function has no effect if `colorSchemeSelector` is `media` (`media` is the default value).', 'To toggle the mode manually, please configure `colorSchemeSelector` to use a class or data attribute.', 'To learn more, visit https://mui.com/material-ui/customization/css-theme-variables/configuration/#toggling-dark-mode-manually'].join('\n'));
}
setMode(newMode);
},
systemMode
}), [allColorSchemes, colorScheme, darkColorScheme, lightColorScheme, mode, setColorScheme, setMode, systemMode, memoTheme.colorSchemeSelector]);
let shouldGenerateStyleSheet = true;
if (disableStyleSheetGeneration || restThemeProp.cssVariables === false || nested && upperTheme?.cssVarPrefix === cssVarPrefix) {
shouldGenerateStyleSheet = false;
}
const element = /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_ThemeProvider.default, {
themeId: scopedTheme ? themeId : undefined,
theme: memoTheme,
children: children
}), shouldGenerateStyleSheet && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledEngine.GlobalStyles, {
styles: memoTheme.generateStyleSheets?.() || []
})]
});
if (nested) {
return element;
}
return /*#__PURE__*/(0, _jsxRuntime.jsx)(ColorSchemeContext.Provider, {
value: contextValue,
children: element
});
}
process.env.NODE_ENV !== "production" ? CssVarsProvider.propTypes = {
/**
* The component tree.
*/
children: _propTypes.default.node,
/**
* The node used to attach the color-scheme attribute
*/
colorSchemeNode: _propTypes.default.any,
/**
* localStorage key used to store `colorScheme`
*/
colorSchemeStorageKey: _propTypes.default.string,
/**
* The default mode when the storage is empty,
* require the theme to have `colorSchemes` with light and dark.
*/
defaultMode: _propTypes.default.string,
/**
* If `true`, the provider creates its own context and generate stylesheet as if it is a root `CssVarsProvider`.
*/
disableNestedContext: _propTypes.default.bool,
/**
* If `true`, the style sheet won't be generated.
*
* This is useful for controlling nested CssVarsProvider behavior.
*/
disableStyleSheetGeneration: _propTypes.default.bool,
/**
* Disable CSS transitions when switching between modes or color schemes.
*/
disableTransitionOnChange: _propTypes.default.bool,
/**
* The document to attach the attribute to.
*/
documentNode: _propTypes.default.any,
/**
* If `true`, theme values are recalculated when the mode changes.
*/
forceThemeRerender: _propTypes.default.bool,
/**
* The key in the local storage used to store current color scheme.
*/
modeStorageKey: _propTypes.default.string,
/**
* If `true`, the mode will be the same value as the storage without an extra rerendering after the hydration.
* You should use this option in conjuction with `InitColorSchemeScript` component.
*/
noSsr: _propTypes.default.bool,
/**
* The storage manager to be used for storing the mode and color scheme
* @default using `window.localStorage`
*/
storageManager: _propTypes.default.func,
/**
* The window that attaches the 'storage' event listener.
* @default window
*/
storageWindow: _propTypes.default.any,
/**
* The calculated theme object that will be passed through context.
*/
theme: _propTypes.default.object
} : void 0;
const defaultLightColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.light;
const defaultDarkColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.dark;
const getInitColorSchemeScript = params => (0, _InitColorSchemeScript.default)({
colorSchemeStorageKey: defaultColorSchemeStorageKey,
defaultLightColorScheme,
defaultDarkColorScheme,
modeStorageKey: defaultModeStorageKey,
...params
});
return {
CssVarsProvider,
useColorScheme,
getInitColorSchemeScript
};
}

View file

@ -0,0 +1,15 @@
import { DefaultCssVarsTheme } from "./prepareCssVars.js";
interface Theme extends DefaultCssVarsTheme {
cssVarPrefix?: string;
colorSchemeSelector?: 'media' | string;
shouldSkipGeneratingVar?: (objectPathKeys: Array<string>, value: string | number) => boolean;
}
declare function createCssVarsTheme<T extends Theme, ThemeVars extends Record<string, any>>({
colorSchemeSelector,
...theme
}: T): T & {
vars: ThemeVars;
generateThemeVars: () => ThemeVars;
generateStyleSheets: () => Record<string, any>[];
};
export default createCssVarsTheme;

28
node_modules/@mui/system/cssVars/createCssVarsTheme.js generated vendored Normal file
View file

@ -0,0 +1,28 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _prepareCssVars = _interopRequireDefault(require("./prepareCssVars"));
var _getColorSchemeSelector = require("./getColorSchemeSelector");
var _InitColorSchemeScript = require("../InitColorSchemeScript/InitColorSchemeScript");
function createCssVarsTheme({
colorSchemeSelector = `[${_InitColorSchemeScript.DEFAULT_ATTRIBUTE}="%s"]`,
...theme
}) {
const output = theme;
const result = (0, _prepareCssVars.default)(output, {
...theme,
prefix: theme.cssVarPrefix,
colorSchemeSelector
});
output.vars = result.vars;
output.generateThemeVars = result.generateThemeVars;
output.generateStyleSheets = result.generateStyleSheets;
output.colorSchemeSelector = colorSchemeSelector;
output.getColorSchemeSelector = (0, _getColorSchemeSelector.createGetColorSchemeSelector)(colorSchemeSelector);
return output;
}
var _default = exports.default = createCssVarsTheme;

View file

@ -0,0 +1,5 @@
/**
* The benefit of this function is to help developers get CSS var from theme without specifying the whole variable
* and they does not need to remember the prefix (defined once).
*/
export default function createGetCssVar<T extends string = string>(prefix?: string): <AdditionalVars extends string = never>(field: T | AdditionalVars, ...fallbacks: (T | AdditionalVars)[]) => string;

28
node_modules/@mui/system/cssVars/createGetCssVar.js generated vendored Normal file
View file

@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createGetCssVar;
/**
* The benefit of this function is to help developers get CSS var from theme without specifying the whole variable
* and they does not need to remember the prefix (defined once).
*/
function createGetCssVar(prefix = '') {
function appendVar(...vars) {
if (!vars.length) {
return '';
}
const value = vars[0];
if (typeof value === 'string' && !value.match(/(#|\(|\)|(-?(\d*\.)?\d+)(px|em|%|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc))|^(-?(\d*\.)?\d+)$|(\d+ \d+ \d+)/)) {
return `, var(--${prefix ? `${prefix}-` : ''}${value}${appendVar(...vars.slice(1))})`;
}
return `, ${value}`;
}
// AdditionalVars makes `getCssVar` less strict, so it can be use like this `getCssVar('non-mui-variable')` without type error.
const getCssVar = (field, ...fallbacks) => {
return `var(--${prefix ? `${prefix}-` : ''}${field}${appendVar(...fallbacks)})`;
};
return getCssVar;
}

64
node_modules/@mui/system/cssVars/cssVarsParser.d.ts generated vendored Normal file
View file

@ -0,0 +1,64 @@
type NestedRecord<V = any> = {
[k: string | number]: NestedRecord<V> | V;
};
/**
* This function create an object from keys, value and then assign to target
*
* @param {Object} obj : the target object to be assigned
* @param {string[]} keys
* @param {string | number} value
*
* @example
* const source = {}
* assignNestedKeys(source, ['palette', 'primary'], 'var(--palette-primary)')
* console.log(source) // { palette: { primary: 'var(--palette-primary)' } }
*
* @example
* const source = { palette: { primary: 'var(--palette-primary)' } }
* assignNestedKeys(source, ['palette', 'secondary'], 'var(--palette-secondary)')
* console.log(source) // { palette: { primary: 'var(--palette-primary)', secondary: 'var(--palette-secondary)' } }
*/
export declare const assignNestedKeys: <T extends Record<string, any> | null | undefined | string = NestedRecord, Value = any>(obj: T, keys: Array<string>, value: Value, arrayKeys?: Array<string>) => void;
/**
*
* @param {Object} obj : source object
* @param {Function} callback : a function that will be called when
* - the deepest key in source object is reached
* - the value of the deepest key is NOT `undefined` | `null`
*
* @example
* walkObjectDeep({ palette: { primary: { main: '#000000' } } }, console.log)
* // ['palette', 'primary', 'main'] '#000000'
*/
export declare const walkObjectDeep: <Value, T = Record<string, any>>(obj: T, callback: (keys: Array<string>, value: Value, arrayKeys: Array<string>) => void, shouldSkipPaths?: (keys: Array<string>) => boolean) => void;
/**
* a function that parse theme and return { css, vars }
*
* @param {Object} theme
* @param {{
* prefix?: string,
* shouldSkipGeneratingVar?: (objectPathKeys: Array<string>, value: string | number) => boolean
* }} options.
* `prefix`: The prefix of the generated CSS variables. This function does not change the value.
*
* @returns {{ css: Object, vars: Object }} `css` is the stylesheet, `vars` is an object to get css variable (same structure as theme).
*
* @example
* const { css, vars } = parser({
* fontSize: 12,
* lineHeight: 1.2,
* palette: { primary: { 500: 'var(--color)' } }
* }, { prefix: 'foo' })
*
* console.log(css) // { '--foo-fontSize': '12px', '--foo-lineHeight': 1.2, '--foo-palette-primary-500': 'var(--color)' }
* console.log(vars) // { fontSize: 'var(--foo-fontSize)', lineHeight: 'var(--foo-lineHeight)', palette: { primary: { 500: 'var(--foo-palette-primary-500)' } } }
*/
export default function cssVarsParser<T extends Record<string, any>>(theme: Record<string, any>, options?: {
prefix?: string;
shouldSkipGeneratingVar?: (objectPathKeys: Array<string>, value: string | number) => boolean;
}): {
css: Record<string, string | number>;
vars: T;
varsWithDefaults: {};
};
export {};

139
node_modules/@mui/system/cssVars/cssVarsParser.js generated vendored Normal file
View file

@ -0,0 +1,139 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.assignNestedKeys = void 0;
exports.default = cssVarsParser;
exports.walkObjectDeep = void 0;
/**
* This function create an object from keys, value and then assign to target
*
* @param {Object} obj : the target object to be assigned
* @param {string[]} keys
* @param {string | number} value
*
* @example
* const source = {}
* assignNestedKeys(source, ['palette', 'primary'], 'var(--palette-primary)')
* console.log(source) // { palette: { primary: 'var(--palette-primary)' } }
*
* @example
* const source = { palette: { primary: 'var(--palette-primary)' } }
* assignNestedKeys(source, ['palette', 'secondary'], 'var(--palette-secondary)')
* console.log(source) // { palette: { primary: 'var(--palette-primary)', secondary: 'var(--palette-secondary)' } }
*/
const assignNestedKeys = (obj, keys, value, arrayKeys = []) => {
let temp = obj;
keys.forEach((k, index) => {
if (index === keys.length - 1) {
if (Array.isArray(temp)) {
temp[Number(k)] = value;
} else if (temp && typeof temp === 'object') {
temp[k] = value;
}
} else if (temp && typeof temp === 'object') {
if (!temp[k]) {
temp[k] = arrayKeys.includes(k) ? [] : {};
}
temp = temp[k];
}
});
};
/**
*
* @param {Object} obj : source object
* @param {Function} callback : a function that will be called when
* - the deepest key in source object is reached
* - the value of the deepest key is NOT `undefined` | `null`
*
* @example
* walkObjectDeep({ palette: { primary: { main: '#000000' } } }, console.log)
* // ['palette', 'primary', 'main'] '#000000'
*/
exports.assignNestedKeys = assignNestedKeys;
const walkObjectDeep = (obj, callback, shouldSkipPaths) => {
function recurse(object, parentKeys = [], arrayKeys = []) {
Object.entries(object).forEach(([key, value]) => {
if (!shouldSkipPaths || shouldSkipPaths && !shouldSkipPaths([...parentKeys, key])) {
if (value !== undefined && value !== null) {
if (typeof value === 'object' && Object.keys(value).length > 0) {
recurse(value, [...parentKeys, key], Array.isArray(value) ? [...arrayKeys, key] : arrayKeys);
} else {
callback([...parentKeys, key], value, arrayKeys);
}
}
}
});
}
recurse(obj);
};
exports.walkObjectDeep = walkObjectDeep;
const getCssValue = (keys, value) => {
if (typeof value === 'number') {
if (['lineHeight', 'fontWeight', 'opacity', 'zIndex'].some(prop => keys.includes(prop))) {
// CSS property that are unitless
return value;
}
const lastKey = keys[keys.length - 1];
if (lastKey.toLowerCase().includes('opacity')) {
// opacity values are unitless
return value;
}
return `${value}px`;
}
return value;
};
/**
* a function that parse theme and return { css, vars }
*
* @param {Object} theme
* @param {{
* prefix?: string,
* shouldSkipGeneratingVar?: (objectPathKeys: Array<string>, value: string | number) => boolean
* }} options.
* `prefix`: The prefix of the generated CSS variables. This function does not change the value.
*
* @returns {{ css: Object, vars: Object }} `css` is the stylesheet, `vars` is an object to get css variable (same structure as theme).
*
* @example
* const { css, vars } = parser({
* fontSize: 12,
* lineHeight: 1.2,
* palette: { primary: { 500: 'var(--color)' } }
* }, { prefix: 'foo' })
*
* console.log(css) // { '--foo-fontSize': '12px', '--foo-lineHeight': 1.2, '--foo-palette-primary-500': 'var(--color)' }
* console.log(vars) // { fontSize: 'var(--foo-fontSize)', lineHeight: 'var(--foo-lineHeight)', palette: { primary: { 500: 'var(--foo-palette-primary-500)' } } }
*/
function cssVarsParser(theme, options) {
const {
prefix,
shouldSkipGeneratingVar
} = options || {};
const css = {};
const vars = {};
const varsWithDefaults = {};
walkObjectDeep(theme, (keys, value, arrayKeys) => {
if (typeof value === 'string' || typeof value === 'number') {
if (!shouldSkipGeneratingVar || !shouldSkipGeneratingVar(keys, value)) {
// only create css & var if `shouldSkipGeneratingVar` return false
const cssVar = `--${prefix ? `${prefix}-` : ''}${keys.join('-')}`;
const resolvedValue = getCssValue(keys, value);
Object.assign(css, {
[cssVar]: resolvedValue
});
assignNestedKeys(vars, keys, `var(${cssVar})`, arrayKeys);
assignNestedKeys(varsWithDefaults, keys, `var(${cssVar}, ${resolvedValue})`, arrayKeys);
}
}
}, keys => keys[0] === 'vars' // skip 'vars/*' paths
);
return {
css,
vars,
varsWithDefaults
};
}

View file

@ -0,0 +1 @@
export declare function createGetColorSchemeSelector<T extends string>(selector: 'media' | 'class' | 'data' | string): (colorScheme: T) => string;

View file

@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createGetColorSchemeSelector = createGetColorSchemeSelector;
/* eslint-disable import/prefer-default-export */
function createGetColorSchemeSelector(selector) {
return function getColorSchemeSelector(colorScheme) {
if (selector === 'media') {
if (process.env.NODE_ENV !== 'production') {
if (colorScheme !== 'light' && colorScheme !== 'dark') {
console.error(`MUI: @media (prefers-color-scheme) supports only 'light' or 'dark', but receive '${colorScheme}'.`);
}
}
return `@media (prefers-color-scheme: ${colorScheme})`;
}
if (selector) {
if (selector.startsWith('data-') && !selector.includes('%s')) {
return `[${selector}="${colorScheme}"] &`;
}
if (selector === 'class') {
return `.${colorScheme} &`;
}
if (selector === 'data') {
return `[data-${colorScheme}] &`;
}
return `${selector.replace('%s', colorScheme)} &`;
}
return '&';
};
}

8
node_modules/@mui/system/cssVars/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
export { default } from "./createCssVarsProvider.js";
export type { CreateCssVarsProviderResult, CssVarsProviderConfig, ColorSchemeContextValue } from "./createCssVarsProvider.js";
export { default as prepareCssVars } from "./prepareCssVars.js";
export { default as prepareTypographyVars } from "./prepareTypographyVars.js";
export type { ExtractTypographyTokens } from "./prepareTypographyVars.js";
export { default as createCssVarsTheme } from "./createCssVarsTheme.js";
export { createGetColorSchemeSelector } from "./getColorSchemeSelector.js";
export type { StorageManager } from "./localStorageManager.js";

41
node_modules/@mui/system/cssVars/index.js generated vendored Normal file
View file

@ -0,0 +1,41 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createCssVarsTheme", {
enumerable: true,
get: function () {
return _createCssVarsTheme.default;
}
});
Object.defineProperty(exports, "createGetColorSchemeSelector", {
enumerable: true,
get: function () {
return _getColorSchemeSelector.createGetColorSchemeSelector;
}
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return _createCssVarsProvider.default;
}
});
Object.defineProperty(exports, "prepareCssVars", {
enumerable: true,
get: function () {
return _prepareCssVars.default;
}
});
Object.defineProperty(exports, "prepareTypographyVars", {
enumerable: true,
get: function () {
return _prepareTypographyVars.default;
}
});
var _createCssVarsProvider = _interopRequireDefault(require("./createCssVarsProvider"));
var _prepareCssVars = _interopRequireDefault(require("./prepareCssVars"));
var _prepareTypographyVars = _interopRequireDefault(require("./prepareTypographyVars"));
var _createCssVarsTheme = _interopRequireDefault(require("./createCssVarsTheme"));
var _getColorSchemeSelector = require("./getColorSchemeSelector");

View file

@ -0,0 +1,34 @@
export interface StorageManager {
(options: {
key: string;
storageWindow?: Window | null;
}): {
/**
* Function to get the value from the storage
* @param defaultValue The default value to be returned if the key is not found
* @returns The value from the storage or the default value
*/
get(defaultValue: any): any;
/**
* Function to set the value in the storage
* @param value The value to be set
* @returns void
*/
set(value: any): void;
/**
* Function to subscribe to the value of the specified key triggered by external events
* @param handler The function to be called when the value changes
* @returns A function to unsubscribe the handler
* @example
* React.useEffect(() => {
* const unsubscribe = storageManager.subscribe((value) => {
* console.log(value);
* });
* return unsubscribe;
* }, []);
*/
subscribe(handler: (value: any) => void): () => void;
};
}
declare const localStorageManager: StorageManager;
export default localStorageManager;

View file

@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function noop() {}
const localStorageManager = ({
key,
storageWindow
}) => {
if (!storageWindow && typeof window !== 'undefined') {
storageWindow = window;
}
return {
get(defaultValue) {
if (typeof window === 'undefined') {
return undefined;
}
if (!storageWindow) {
return defaultValue;
}
let value;
try {
value = storageWindow.localStorage.getItem(key);
} catch {
// Unsupported
}
return value || defaultValue;
},
set: value => {
if (storageWindow) {
try {
storageWindow.localStorage.setItem(key, value);
} catch {
// Unsupported
}
}
},
subscribe: handler => {
if (!storageWindow) {
return noop;
}
const listener = event => {
const value = event.newValue;
if (event.key === key) {
handler(value);
}
};
storageWindow.addEventListener('storage', listener);
return () => {
storageWindow.removeEventListener('storage', listener);
};
}
};
};
var _default = exports.default = localStorageManager;

17
node_modules/@mui/system/cssVars/prepareCssVars.d.ts generated vendored Normal file
View file

@ -0,0 +1,17 @@
export interface DefaultCssVarsTheme {
colorSchemes?: Record<string, any>;
defaultColorScheme?: string;
}
declare function prepareCssVars<T extends DefaultCssVarsTheme, ThemeVars extends Record<string, any>>(theme: T, parserConfig?: {
prefix?: string;
colorSchemeSelector?: 'media' | 'class' | 'data' | string;
disableCssColorScheme?: boolean;
enableContrastVars?: boolean;
shouldSkipGeneratingVar?: (objectPathKeys: Array<string>, value: string | number) => boolean;
getSelector?: (colorScheme: keyof T['colorSchemes'] | undefined, css: Record<string, any>) => string | Record<string, any>;
}): {
vars: ThemeVars;
generateThemeVars: () => ThemeVars;
generateStyleSheets: () => Record<string, any>[];
};
export default prepareCssVars;

171
node_modules/@mui/system/cssVars/prepareCssVars.js generated vendored Normal file
View file

@ -0,0 +1,171 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _deepmerge = _interopRequireDefault(require("@mui/utils/deepmerge"));
var _cssVarsParser = _interopRequireDefault(require("./cssVarsParser"));
function prepareCssVars(theme, parserConfig = {}) {
const {
getSelector = defaultGetSelector,
disableCssColorScheme,
colorSchemeSelector: selector,
enableContrastVars
} = parserConfig;
// @ts-ignore - ignore components do not exist
const {
colorSchemes = {},
components,
defaultColorScheme = 'light',
...otherTheme
} = theme;
const {
vars: rootVars,
css: rootCss,
varsWithDefaults: rootVarsWithDefaults
} = (0, _cssVarsParser.default)(otherTheme, parserConfig);
let themeVars = rootVarsWithDefaults;
const colorSchemesMap = {};
const {
[defaultColorScheme]: defaultScheme,
...otherColorSchemes
} = colorSchemes;
Object.entries(otherColorSchemes || {}).forEach(([key, scheme]) => {
const {
vars,
css,
varsWithDefaults
} = (0, _cssVarsParser.default)(scheme, parserConfig);
themeVars = (0, _deepmerge.default)(themeVars, varsWithDefaults);
colorSchemesMap[key] = {
css,
vars
};
});
if (defaultScheme) {
// default color scheme vars should be merged last to set as default
const {
css,
vars,
varsWithDefaults
} = (0, _cssVarsParser.default)(defaultScheme, parserConfig);
themeVars = (0, _deepmerge.default)(themeVars, varsWithDefaults);
colorSchemesMap[defaultColorScheme] = {
css,
vars
};
}
function defaultGetSelector(colorScheme, cssObject) {
let rule = selector;
if (selector === 'class') {
rule = '.%s';
}
if (selector === 'data') {
rule = '[data-%s]';
}
if (selector?.startsWith('data-') && !selector.includes('%s')) {
// 'data-joy-color-scheme' -> '[data-joy-color-scheme="%s"]'
rule = `[${selector}="%s"]`;
}
if (colorScheme) {
if (rule === 'media') {
if (theme.defaultColorScheme === colorScheme) {
return ':root';
}
const mode = colorSchemes[colorScheme]?.palette?.mode || colorScheme;
return {
[`@media (prefers-color-scheme: ${mode})`]: {
':root': cssObject
}
};
}
if (rule) {
if (theme.defaultColorScheme === colorScheme) {
return `:root, ${rule.replace('%s', String(colorScheme))}`;
}
return rule.replace('%s', String(colorScheme));
}
}
return ':root';
}
const generateThemeVars = () => {
let vars = {
...rootVars
};
Object.entries(colorSchemesMap).forEach(([, {
vars: schemeVars
}]) => {
vars = (0, _deepmerge.default)(vars, schemeVars);
});
return vars;
};
const generateStyleSheets = () => {
const stylesheets = [];
const colorScheme = theme.defaultColorScheme || 'light';
function insertStyleSheet(key, css) {
if (Object.keys(css).length) {
stylesheets.push(typeof key === 'string' ? {
[key]: {
...css
}
} : key);
}
}
insertStyleSheet(getSelector(undefined, {
...rootCss
}), rootCss);
const {
[colorScheme]: defaultSchemeVal,
...other
} = colorSchemesMap;
if (defaultSchemeVal) {
// default color scheme has to come before other color schemes
const {
css
} = defaultSchemeVal;
const cssColorSheme = colorSchemes[colorScheme]?.palette?.mode;
const finalCss = !disableCssColorScheme && cssColorSheme ? {
colorScheme: cssColorSheme,
...css
} : {
...css
};
insertStyleSheet(getSelector(colorScheme, {
...finalCss
}), finalCss);
}
Object.entries(other).forEach(([key, {
css
}]) => {
const cssColorSheme = colorSchemes[key]?.palette?.mode;
const finalCss = !disableCssColorScheme && cssColorSheme ? {
colorScheme: cssColorSheme,
...css
} : {
...css
};
insertStyleSheet(getSelector(key, {
...finalCss
}), finalCss);
});
if (enableContrastVars) {
stylesheets.push({
':root': {
// use double underscore to indicate that these are private variables
'--__l-threshold': '0.7',
'--__l': 'clamp(0, (l / var(--__l-threshold) - 1) * -infinity, 1)',
'--__a': 'clamp(0.87, (l / var(--__l-threshold) - 1) * -infinity, 1)' // 0.87 is the default alpha value for black text.
}
});
}
return stylesheets;
};
return {
vars: themeVars,
generateThemeVars,
generateStyleSheets
};
}
var _default = exports.default = prepareCssVars;

View file

@ -0,0 +1,4 @@
type RecordPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : T[K] extends Record<string, any> ? K : never }[keyof T];
export type ExtractTypographyTokens<T> = { [K in RecordPropertyNames<T>]: string };
export default function prepareTypographyVars<T extends Record<string, any>>(typography: T): ExtractTypographyTokens<T>;
export {};

View file

@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = prepareTypographyVars;
function prepareTypographyVars(typography) {
const vars = {};
const entries = Object.entries(typography);
entries.forEach(entry => {
const [key, value] = entry;
if (typeof value === 'object') {
vars[key] = `${value.fontStyle ? `${value.fontStyle} ` : ''}${value.fontVariant ? `${value.fontVariant} ` : ''}${value.fontWeight ? `${value.fontWeight} ` : ''}${value.fontStretch ? `${value.fontStretch} ` : ''}${value.fontSize || ''}${value.lineHeight ? `/${value.lineHeight} ` : ''}${value.fontFamily || ''}`;
}
});
return vars;
}

View file

@ -0,0 +1,56 @@
import type { StorageManager } from "./localStorageManager.js";
export type Mode = 'light' | 'dark' | 'system';
export type SystemMode = Exclude<Mode, 'system'>;
export interface State<SupportedColorScheme extends string> {
/**
* User selected mode.
* Note: on the server, mode is always undefined
*/
mode: 'light' | 'dark' | 'system' | undefined;
/**
* Only valid if `mode: 'system'`, either 'light' | 'dark'.
*/
systemMode: 'light' | 'dark' | undefined;
/**
* The color scheme for the light mode.
*/
lightColorScheme: SupportedColorScheme;
/**
* The color scheme for the dark mode.
*/
darkColorScheme: SupportedColorScheme;
}
export type Result<SupportedColorScheme extends string> = State<SupportedColorScheme> & {
/**
* The current application color scheme. It is always `undefined` on the server.
*/
colorScheme: SupportedColorScheme | undefined;
/**
* `mode` is saved to internal state and localStorage
* If `mode` is null, it will be reset to the defaultMode
*/
setMode: (mode: Mode | null) => void;
/**
* `colorScheme` is saved to internal state and localStorage
* If `colorScheme` is null, it will be reset to the defaultColorScheme (light | dark)
*/
setColorScheme: (colorScheme: SupportedColorScheme | Partial<{
light: SupportedColorScheme | null;
dark: SupportedColorScheme | null;
}> | null) => void;
};
export declare function getSystemMode(mode: undefined | string): SystemMode | undefined;
export declare function getColorScheme<SupportedColorScheme extends string>(state: State<SupportedColorScheme>): SupportedColorScheme | undefined;
interface UseCurrentColoSchemeOptions<SupportedColorScheme extends string> {
defaultLightColorScheme: SupportedColorScheme;
defaultDarkColorScheme: SupportedColorScheme;
supportedColorSchemes: Array<SupportedColorScheme>;
defaultMode?: Mode;
modeStorageKey?: string;
colorSchemeStorageKey?: string;
storageWindow?: Window | null;
storageManager?: StorageManager | null;
noSsr?: boolean;
}
export default function useCurrentColorScheme<SupportedColorScheme extends string>(options: UseCurrentColoSchemeOptions<SupportedColorScheme>): Result<SupportedColorScheme>;
export {};

View file

@ -0,0 +1,237 @@
"use strict";
'use client';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useCurrentColorScheme;
exports.getColorScheme = getColorScheme;
exports.getSystemMode = getSystemMode;
var React = _interopRequireWildcard(require("react"));
var _InitColorSchemeScript = require("../InitColorSchemeScript/InitColorSchemeScript");
var _localStorageManager = _interopRequireDefault(require("./localStorageManager"));
function noop() {}
function getSystemMode(mode) {
if (typeof window !== 'undefined' && typeof window.matchMedia === 'function' && mode === 'system') {
const mql = window.matchMedia('(prefers-color-scheme: dark)');
if (mql.matches) {
return 'dark';
}
return 'light';
}
return undefined;
}
function processState(state, callback) {
if (state.mode === 'light' || state.mode === 'system' && state.systemMode === 'light') {
return callback('light');
}
if (state.mode === 'dark' || state.mode === 'system' && state.systemMode === 'dark') {
return callback('dark');
}
return undefined;
}
function getColorScheme(state) {
return processState(state, mode => {
if (mode === 'light') {
return state.lightColorScheme;
}
if (mode === 'dark') {
return state.darkColorScheme;
}
return undefined;
});
}
function useCurrentColorScheme(options) {
const {
defaultMode = 'light',
defaultLightColorScheme,
defaultDarkColorScheme,
supportedColorSchemes = [],
modeStorageKey = _InitColorSchemeScript.DEFAULT_MODE_STORAGE_KEY,
colorSchemeStorageKey = _InitColorSchemeScript.DEFAULT_COLOR_SCHEME_STORAGE_KEY,
storageWindow = typeof window === 'undefined' ? undefined : window,
storageManager = _localStorageManager.default,
noSsr = false
} = options;
const joinedColorSchemes = supportedColorSchemes.join(',');
const isMultiSchemes = supportedColorSchemes.length > 1;
const modeStorage = React.useMemo(() => storageManager?.({
key: modeStorageKey,
storageWindow
}), [storageManager, modeStorageKey, storageWindow]);
const lightStorage = React.useMemo(() => storageManager?.({
key: `${colorSchemeStorageKey}-light`,
storageWindow
}), [storageManager, colorSchemeStorageKey, storageWindow]);
const darkStorage = React.useMemo(() => storageManager?.({
key: `${colorSchemeStorageKey}-dark`,
storageWindow
}), [storageManager, colorSchemeStorageKey, storageWindow]);
const [state, setState] = React.useState(() => {
const initialMode = modeStorage?.get(defaultMode) || defaultMode;
const lightColorScheme = lightStorage?.get(defaultLightColorScheme) || defaultLightColorScheme;
const darkColorScheme = darkStorage?.get(defaultDarkColorScheme) || defaultDarkColorScheme;
return {
mode: initialMode,
systemMode: getSystemMode(initialMode),
lightColorScheme,
darkColorScheme
};
});
const [isClient, setIsClient] = React.useState(noSsr || !isMultiSchemes);
React.useEffect(() => {
setIsClient(true); // to rerender the component after hydration
}, []);
const colorScheme = getColorScheme(state);
const setMode = React.useCallback(mode => {
setState(currentState => {
if (mode === currentState.mode) {
// do nothing if mode does not change
return currentState;
}
const newMode = mode ?? defaultMode;
modeStorage?.set(newMode);
return {
...currentState,
mode: newMode,
systemMode: getSystemMode(newMode)
};
});
}, [modeStorage, defaultMode]);
const setColorScheme = React.useCallback(value => {
if (!value) {
setState(currentState => {
lightStorage?.set(defaultLightColorScheme);
darkStorage?.set(defaultDarkColorScheme);
return {
...currentState,
lightColorScheme: defaultLightColorScheme,
darkColorScheme: defaultDarkColorScheme
};
});
} else if (typeof value === 'string') {
if (value && !joinedColorSchemes.includes(value)) {
console.error(`\`${value}\` does not exist in \`theme.colorSchemes\`.`);
} else {
setState(currentState => {
const newState = {
...currentState
};
processState(currentState, mode => {
if (mode === 'light') {
lightStorage?.set(value);
newState.lightColorScheme = value;
}
if (mode === 'dark') {
darkStorage?.set(value);
newState.darkColorScheme = value;
}
});
return newState;
});
}
} else {
setState(currentState => {
const newState = {
...currentState
};
const newLightColorScheme = value.light === null ? defaultLightColorScheme : value.light;
const newDarkColorScheme = value.dark === null ? defaultDarkColorScheme : value.dark;
if (newLightColorScheme) {
if (!joinedColorSchemes.includes(newLightColorScheme)) {
console.error(`\`${newLightColorScheme}\` does not exist in \`theme.colorSchemes\`.`);
} else {
newState.lightColorScheme = newLightColorScheme;
lightStorage?.set(newLightColorScheme);
}
}
if (newDarkColorScheme) {
if (!joinedColorSchemes.includes(newDarkColorScheme)) {
console.error(`\`${newDarkColorScheme}\` does not exist in \`theme.colorSchemes\`.`);
} else {
newState.darkColorScheme = newDarkColorScheme;
darkStorage?.set(newDarkColorScheme);
}
}
return newState;
});
}
}, [joinedColorSchemes, lightStorage, darkStorage, defaultLightColorScheme, defaultDarkColorScheme]);
const handleMediaQuery = React.useCallback(event => {
if (state.mode === 'system') {
setState(currentState => {
const systemMode = event?.matches ? 'dark' : 'light';
// Early exit, nothing changed.
if (currentState.systemMode === systemMode) {
return currentState;
}
return {
...currentState,
systemMode
};
});
}
}, [state.mode]);
// Ref hack to avoid adding handleMediaQuery as a dep
const mediaListener = React.useRef(handleMediaQuery);
mediaListener.current = handleMediaQuery;
React.useEffect(() => {
if (typeof window.matchMedia !== 'function' || !isMultiSchemes) {
return undefined;
}
const handler = (...args) => mediaListener.current(...args);
// Always listen to System preference
const media = window.matchMedia('(prefers-color-scheme: dark)');
// Intentionally use deprecated listener methods to support iOS & old browsers
media.addListener(handler);
handler(media);
return () => {
media.removeListener(handler);
};
}, [isMultiSchemes]);
// Handle when localStorage has changed
React.useEffect(() => {
if (isMultiSchemes) {
const unsubscribeMode = modeStorage?.subscribe(value => {
if (!value || ['light', 'dark', 'system'].includes(value)) {
setMode(value || defaultMode);
}
}) || noop;
const unsubscribeLight = lightStorage?.subscribe(value => {
if (!value || joinedColorSchemes.match(value)) {
setColorScheme({
light: value
});
}
}) || noop;
const unsubscribeDark = darkStorage?.subscribe(value => {
if (!value || joinedColorSchemes.match(value)) {
setColorScheme({
dark: value
});
}
}) || noop;
return () => {
unsubscribeMode();
unsubscribeLight();
unsubscribeDark();
};
}
return undefined;
}, [setColorScheme, setMode, joinedColorSchemes, defaultMode, storageWindow, isMultiSchemes, modeStorage, lightStorage, darkStorage]);
return {
...state,
mode: isClient ? state.mode : undefined,
systemMode: isClient ? state.systemMode : undefined,
colorScheme: isClient ? colorScheme : undefined,
setMode,
setColorScheme
};
}