Initial commit: Crypto trader application

This commit is contained in:
2025-12-25 20:20:40 -05:00
commit 07a04c1bb8
47895 changed files with 2042266 additions and 0 deletions
@@ -0,0 +1,346 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _formatMuiErrorMessage from "@mui/utils/formatMuiErrorMessage";
const _excluded = ["colorSchemes", "components", "generateCssVars", "cssVarPrefix"];
import * as React from 'react';
import PropTypes from 'prop-types';
import deepmerge from '@mui/utils/deepmerge';
import { GlobalStyles } from '@mui/styled-engine';
import { useTheme as muiUseTheme } from '@mui/private-theming';
import ThemeProvider from '../ThemeProvider';
import InitColorSchemeScript, { DEFAULT_ATTRIBUTE, DEFAULT_COLOR_SCHEME_STORAGE_KEY, DEFAULT_MODE_STORAGE_KEY } from '../InitColorSchemeScript/InitColorSchemeScript';
import useCurrentColorScheme from './useCurrentColorScheme';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
export const DISABLE_CSS_TRANSITION = '*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}';
export default 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 = {},
attribute: defaultAttribute = DEFAULT_ATTRIBUTE,
modeStorageKey: defaultModeStorageKey = DEFAULT_MODE_STORAGE_KEY,
colorSchemeStorageKey: defaultColorSchemeStorageKey = DEFAULT_COLOR_SCHEME_STORAGE_KEY,
defaultMode: designSystemMode = 'light',
defaultColorScheme: designSystemColorScheme,
disableTransitionOnChange: designSystemTransitionOnChange = false,
resolveTheme,
excludeVariablesFromRoot
} = options;
if (!defaultTheme.colorSchemes || typeof designSystemColorScheme === 'string' && !defaultTheme.colorSchemes[designSystemColorScheme] || typeof designSystemColorScheme === 'object' && !defaultTheme.colorSchemes[designSystemColorScheme?.light] || typeof designSystemColorScheme === 'object' && !defaultTheme.colorSchemes[designSystemColorScheme?.dark]) {
console.error(`MUI: \`${designSystemColorScheme}\` does not exist in \`theme.colorSchemes\`.`);
}
const ColorSchemeContext = /*#__PURE__*/React.createContext(undefined);
if (process.env.NODE_ENV !== 'production') {
ColorSchemeContext.displayName = 'ColorSchemeContext';
}
const useColorScheme = () => {
const value = React.useContext(ColorSchemeContext);
if (!value) {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI: \`useColorScheme\` must be called under <CssVarsProvider />` : _formatMuiErrorMessage(19));
}
return value;
};
function CssVarsProvider(props) {
const {
children,
theme: themeProp = defaultTheme,
modeStorageKey = defaultModeStorageKey,
colorSchemeStorageKey = defaultColorSchemeStorageKey,
attribute = defaultAttribute,
defaultMode = designSystemMode,
defaultColorScheme = designSystemColorScheme,
disableTransitionOnChange = designSystemTransitionOnChange,
storageWindow = typeof window === 'undefined' ? undefined : window,
documentNode = typeof document === 'undefined' ? undefined : document,
colorSchemeNode = typeof document === 'undefined' ? undefined : document.documentElement,
colorSchemeSelector = ':root',
disableNestedContext = false,
disableStyleSheetGeneration = false
} = props;
const hasMounted = React.useRef(false);
const upperTheme = muiUseTheme();
const ctx = React.useContext(ColorSchemeContext);
const nested = !!ctx && !disableNestedContext;
const scopedTheme = themeProp[themeId];
const _ref = scopedTheme || themeProp,
{
colorSchemes = {},
components = {},
generateCssVars = () => ({
vars: {},
css: {}
}),
cssVarPrefix
} = _ref,
restThemeProp = _objectWithoutPropertiesLoose(_ref, _excluded);
const allColorSchemes = Object.keys(colorSchemes);
const defaultLightColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.light;
const defaultDarkColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.dark;
// 1. Get the data about the `mode`, `colorScheme`, and setter functions.
const {
mode: stateMode,
setMode,
systemMode,
lightColorScheme,
darkColorScheme,
colorScheme: stateColorScheme,
setColorScheme
} = useCurrentColorScheme({
supportedColorSchemes: allColorSchemes,
defaultLightColorScheme,
defaultDarkColorScheme,
modeStorageKey,
colorSchemeStorageKey,
defaultMode,
storageWindow
});
let mode = stateMode;
let colorScheme = stateColorScheme;
if (nested) {
mode = ctx.mode;
colorScheme = ctx.colorScheme;
}
const calculatedMode = (() => {
if (mode) {
return mode;
}
// This scope occurs on the server
if (defaultMode === 'system') {
return designSystemMode;
}
return defaultMode;
})();
const calculatedColorScheme = (() => {
if (!colorScheme) {
// This scope occurs on the server
if (calculatedMode === 'dark') {
return defaultDarkColorScheme;
}
// use light color scheme, if default mode is 'light' | 'system'
return defaultLightColorScheme;
}
return colorScheme;
})();
// 2. Create CSS variables and store them in objects (to be generated in stylesheets in the final step)
const {
css: rootCss,
vars: rootVars
} = generateCssVars();
// 3. Start composing the theme object
const theme = _extends({}, restThemeProp, {
components,
colorSchemes,
cssVarPrefix,
vars: rootVars,
getColorSchemeSelector: targetColorScheme => `[${attribute}="${targetColorScheme}"] &`
});
// 4. Create color CSS variables and store them in objects (to be generated in stylesheets in the final step)
// The default color scheme stylesheet is constructed to have the least CSS specificity.
// The other color schemes uses selector, default as data attribute, to increase the CSS specificity so that they can override the default color scheme stylesheet.
const defaultColorSchemeStyleSheet = {};
const otherColorSchemesStyleSheet = {};
Object.entries(colorSchemes).forEach(([key, scheme]) => {
const {
css,
vars
} = generateCssVars(key);
theme.vars = deepmerge(theme.vars, vars);
if (key === calculatedColorScheme) {
// 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] = _extends({}, theme[schemeKey], scheme[schemeKey]);
} else {
theme[schemeKey] = scheme[schemeKey];
}
});
if (theme.palette) {
theme.palette.colorScheme = key;
}
}
const resolvedDefaultColorScheme = (() => {
if (typeof defaultColorScheme === 'string') {
return defaultColorScheme;
}
if (defaultMode === 'dark') {
return defaultColorScheme.dark;
}
return defaultColorScheme.light;
})();
if (key === resolvedDefaultColorScheme) {
if (excludeVariablesFromRoot) {
const excludedVariables = {};
excludeVariablesFromRoot(cssVarPrefix).forEach(cssVar => {
excludedVariables[cssVar] = css[cssVar];
delete css[cssVar];
});
defaultColorSchemeStyleSheet[`[${attribute}="${key}"]`] = excludedVariables;
}
defaultColorSchemeStyleSheet[`${colorSchemeSelector}, [${attribute}="${key}"]`] = css;
} else {
otherColorSchemesStyleSheet[`${colorSchemeSelector === ':root' ? '' : colorSchemeSelector}[${attribute}="${key}"]`] = css;
}
});
theme.vars = deepmerge(theme.vars, rootVars);
// 5. Declaring effects
// 5.1 Updates the selector value to use the current color scheme which tells CSS to use the proper stylesheet.
React.useEffect(() => {
if (colorScheme && colorSchemeNode) {
// attaches attribute to <html> because the css variables are attached to :root (html)
colorSchemeNode.setAttribute(attribute, colorScheme);
}
}, [colorScheme, attribute, colorSchemeNode]);
// 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,
systemMode
}), [allColorSchemes, colorScheme, darkColorScheme, lightColorScheme, mode, setColorScheme, setMode, systemMode]);
let shouldGenerateStyleSheet = true;
if (disableStyleSheetGeneration || nested && upperTheme?.cssVarPrefix === cssVarPrefix) {
shouldGenerateStyleSheet = false;
}
const element = /*#__PURE__*/_jsxs(React.Fragment, {
children: [shouldGenerateStyleSheet && /*#__PURE__*/_jsxs(React.Fragment, {
children: [/*#__PURE__*/_jsx(GlobalStyles, {
styles: {
[colorSchemeSelector]: rootCss
}
}), /*#__PURE__*/_jsx(GlobalStyles, {
styles: defaultColorSchemeStyleSheet
}), /*#__PURE__*/_jsx(GlobalStyles, {
styles: otherColorSchemesStyleSheet
})]
}), /*#__PURE__*/_jsx(ThemeProvider, {
themeId: scopedTheme ? themeId : undefined,
theme: resolveTheme ? resolveTheme(theme) : theme,
children: children
})]
});
if (nested) {
return element;
}
return /*#__PURE__*/_jsx(ColorSchemeContext.Provider, {
value: contextValue,
children: element
});
}
process.env.NODE_ENV !== "production" ? CssVarsProvider.propTypes = {
/**
* The body attribute name to attach colorScheme.
*/
attribute: PropTypes.string,
/**
* The component tree.
*/
children: PropTypes.node,
/**
* The node used to attach the color-scheme attribute
*/
colorSchemeNode: PropTypes.any,
/**
* The CSS selector for attaching the generated custom properties
*/
colorSchemeSelector: PropTypes.string,
/**
* localStorage key used to store `colorScheme`
*/
colorSchemeStorageKey: PropTypes.string,
/**
* The initial color scheme used.
*/
defaultColorScheme: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
/**
* The initial mode used.
*/
defaultMode: PropTypes.string,
/**
* If `true`, the provider creates its own context and generate stylesheet as if it is a root `CssVarsProvider`.
*/
disableNestedContext: PropTypes.bool,
/**
* If `true`, the style sheet won't be generated.
*
* This is useful for controlling nested CssVarsProvider behavior.
*/
disableStyleSheetGeneration: PropTypes.bool,
/**
* Disable CSS transitions when switching between modes or color schemes.
*/
disableTransitionOnChange: PropTypes.bool,
/**
* The document to attach the attribute to.
*/
documentNode: PropTypes.any,
/**
* The key in the local storage used to store current color scheme.
*/
modeStorageKey: PropTypes.string,
/**
* The window that attaches the 'storage' event listener.
* @default window
*/
storageWindow: PropTypes.any,
/**
* The calculated theme object that will be passed through context.
*/
theme: PropTypes.object
} : void 0;
const defaultLightColorScheme = typeof designSystemColorScheme === 'string' ? designSystemColorScheme : designSystemColorScheme.light;
const defaultDarkColorScheme = typeof designSystemColorScheme === 'string' ? designSystemColorScheme : designSystemColorScheme.dark;
const getInitColorSchemeScript = params => InitColorSchemeScript(_extends({
attribute: defaultAttribute,
colorSchemeStorageKey: defaultColorSchemeStorageKey,
defaultMode: designSystemMode,
defaultLightColorScheme,
defaultDarkColorScheme,
modeStorageKey: defaultModeStorageKey
}, params));
return {
CssVarsProvider,
useColorScheme,
getInitColorSchemeScript
};
}
+16
View File
@@ -0,0 +1,16 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["cssVarPrefix", "shouldSkipGeneratingVar"];
import prepareCssVars from './prepareCssVars';
function createCssVarsTheme(theme) {
const {
cssVarPrefix,
shouldSkipGeneratingVar
} = theme,
otherTheme = _objectWithoutPropertiesLoose(theme, _excluded);
return _extends({}, theme, prepareCssVars(otherTheme, {
prefix: cssVarPrefix,
shouldSkipGeneratingVar
}));
}
export default createCssVarsTheme;
+22
View File
@@ -0,0 +1,22 @@
/**
* 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(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;
}
+128
View File
@@ -0,0 +1,128 @@
/**
* 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 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'
*/
export 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);
};
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().indexOf('opacity') >= 0) {
// 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)' } } }
*/
export default 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('-')}`;
Object.assign(css, {
[cssVar]: getCssValue(keys, value)
});
assignNestedKeys(vars, keys, `var(${cssVar})`, arrayKeys);
assignNestedKeys(varsWithDefaults, keys, `var(${cssVar}, ${value})`, arrayKeys);
}
}
}, keys => keys[0] === 'vars' // skip 'vars/*' paths
);
return {
css,
vars,
varsWithDefaults
};
}
@@ -0,0 +1,8 @@
import _extends from "@babel/runtime/helpers/esm/extends";
// TODO: remove this file in v6
import * as React from 'react';
import InitColorSchemeScript from '../InitColorSchemeScript';
import { jsx as _jsx } from "react/jsx-runtime";
export default function getInitColorSchemeScript(params) {
return /*#__PURE__*/_jsx(InitColorSchemeScript, _extends({}, params));
}
+7
View File
@@ -0,0 +1,7 @@
'use client';
export { default } from './createCssVarsProvider';
// TODO: remove this export in v6 in favor of InitColorSchemeScript
export { default as getInitColorSchemeScript } from './getInitColorSchemeScript';
export { default as prepareCssVars } from './prepareCssVars';
export { default as createCssVarsTheme } from './createCssVarsTheme';
+71
View File
@@ -0,0 +1,71 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _toPropertyKey from "@babel/runtime/helpers/esm/toPropertyKey";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["colorSchemes", "components", "defaultColorScheme"];
import deepmerge from '@mui/utils/deepmerge';
import cssVarsParser from './cssVarsParser';
function prepareCssVars(theme, parserConfig) {
// @ts-ignore - ignore components do not exist
const {
colorSchemes = {},
defaultColorScheme = 'light'
} = theme,
otherTheme = _objectWithoutPropertiesLoose(theme, _excluded);
const {
vars: rootVars,
css: rootCss,
varsWithDefaults: rootVarsWithDefaults
} = cssVarsParser(otherTheme, parserConfig);
let themeVars = rootVarsWithDefaults;
const colorSchemesMap = {};
const {
[defaultColorScheme]: light
} = colorSchemes,
otherColorSchemes = _objectWithoutPropertiesLoose(colorSchemes, [defaultColorScheme].map(_toPropertyKey));
Object.entries(otherColorSchemes || {}).forEach(([key, scheme]) => {
const {
vars,
css,
varsWithDefaults
} = cssVarsParser(scheme, parserConfig);
themeVars = deepmerge(themeVars, varsWithDefaults);
colorSchemesMap[key] = {
css,
vars
};
});
if (light) {
// default color scheme vars should be merged last to set as default
const {
css,
vars,
varsWithDefaults
} = cssVarsParser(light, parserConfig);
themeVars = deepmerge(themeVars, varsWithDefaults);
colorSchemesMap[defaultColorScheme] = {
css,
vars
};
}
const generateCssVars = colorScheme => {
if (!colorScheme) {
const css = _extends({}, rootCss);
return {
css,
vars: rootVars,
selector: parserConfig?.getSelector?.(colorScheme, css) || ':root'
};
}
const css = _extends({}, colorSchemesMap[colorScheme].css);
return {
css,
vars: colorSchemesMap[colorScheme].vars,
selector: parserConfig?.getSelector?.(colorScheme, css) || ':root'
};
};
return {
vars: themeVars,
generateCssVars
};
}
export default prepareCssVars;
@@ -0,0 +1,230 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { DEFAULT_MODE_STORAGE_KEY, DEFAULT_COLOR_SCHEME_STORAGE_KEY } from '../InitColorSchemeScript/InitColorSchemeScript';
export function getSystemMode(mode) {
if (typeof window !== 'undefined' && 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;
}
export function getColorScheme(state) {
return processState(state, mode => {
if (mode === 'light') {
return state.lightColorScheme;
}
if (mode === 'dark') {
return state.darkColorScheme;
}
return undefined;
});
}
function initializeValue(key, defaultValue) {
if (typeof window === 'undefined') {
return undefined;
}
let value;
try {
value = localStorage.getItem(key) || undefined;
if (!value) {
// the first time that user enters the site.
localStorage.setItem(key, defaultValue);
}
} catch (e) {
// Unsupported
}
return value || defaultValue;
}
export default function useCurrentColorScheme(options) {
const {
defaultMode = 'light',
defaultLightColorScheme,
defaultDarkColorScheme,
supportedColorSchemes = [],
modeStorageKey = DEFAULT_MODE_STORAGE_KEY,
colorSchemeStorageKey = DEFAULT_COLOR_SCHEME_STORAGE_KEY,
storageWindow = typeof window === 'undefined' ? undefined : window
} = options;
const joinedColorSchemes = supportedColorSchemes.join(',');
const [state, setState] = React.useState(() => {
const initialMode = initializeValue(modeStorageKey, defaultMode);
const lightColorScheme = initializeValue(`${colorSchemeStorageKey}-light`, defaultLightColorScheme);
const darkColorScheme = initializeValue(`${colorSchemeStorageKey}-dark`, defaultDarkColorScheme);
return {
mode: initialMode,
systemMode: getSystemMode(initialMode),
lightColorScheme,
darkColorScheme
};
});
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;
try {
localStorage.setItem(modeStorageKey, newMode);
} catch (e) {
// Unsupported
}
return _extends({}, currentState, {
mode: newMode,
systemMode: getSystemMode(newMode)
});
});
}, [modeStorageKey, defaultMode]);
const setColorScheme = React.useCallback(value => {
if (!value) {
setState(currentState => {
try {
localStorage.setItem(`${colorSchemeStorageKey}-light`, defaultLightColorScheme);
localStorage.setItem(`${colorSchemeStorageKey}-dark`, defaultDarkColorScheme);
} catch (e) {
// Unsupported
}
return _extends({}, 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 = _extends({}, currentState);
processState(currentState, mode => {
try {
localStorage.setItem(`${colorSchemeStorageKey}-${mode}`, value);
} catch (e) {
// Unsupported
}
if (mode === 'light') {
newState.lightColorScheme = value;
}
if (mode === 'dark') {
newState.darkColorScheme = value;
}
});
return newState;
});
}
} else {
setState(currentState => {
const newState = _extends({}, 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;
try {
localStorage.setItem(`${colorSchemeStorageKey}-light`, newLightColorScheme);
} catch (error) {
// Unsupported
}
}
}
if (newDarkColorScheme) {
if (!joinedColorSchemes.includes(newDarkColorScheme)) {
console.error(`\`${newDarkColorScheme}\` does not exist in \`theme.colorSchemes\`.`);
} else {
newState.darkColorScheme = newDarkColorScheme;
try {
localStorage.setItem(`${colorSchemeStorageKey}-dark`, newDarkColorScheme);
} catch (error) {
// Unsupported
}
}
}
return newState;
});
}
}, [joinedColorSchemes, colorSchemeStorageKey, 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 _extends({}, currentState, {
systemMode
});
});
}
}, [state.mode]);
// Ref hack to avoid adding handleMediaQuery as a dep
const mediaListener = React.useRef(handleMediaQuery);
mediaListener.current = handleMediaQuery;
React.useEffect(() => {
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);
};
}, []);
// Handle when localStorage has changed
React.useEffect(() => {
if (storageWindow) {
const handleStorage = event => {
const value = event.newValue;
if (typeof event.key === 'string' && event.key.startsWith(colorSchemeStorageKey) && (!value || joinedColorSchemes.match(value))) {
// If the key is deleted, value will be null then reset color scheme to the default one.
if (event.key.endsWith('light')) {
setColorScheme({
light: value
});
}
if (event.key.endsWith('dark')) {
setColorScheme({
dark: value
});
}
}
if (event.key === modeStorageKey && (!value || ['light', 'dark', 'system'].includes(value))) {
setMode(value || defaultMode);
}
};
// For syncing color-scheme changes between iframes
storageWindow.addEventListener('storage', handleStorage);
return () => {
storageWindow.removeEventListener('storage', handleStorage);
};
}
return undefined;
}, [setColorScheme, setMode, modeStorageKey, colorSchemeStorageKey, joinedColorSchemes, defaultMode, storageWindow]);
return _extends({}, state, {
colorScheme,
setMode,
setColorScheme
});
}