UNPKG

@atlaskit/app-provider

Version:

A top level provider for the Design System.

60 lines (58 loc) 2.4 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.useColorMode = useColorMode; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _react = require("react"); var _getGlobalTheme = require("@atlaskit/tokens/get-global-theme"); var _themeMutationObserver = require("@atlaskit/tokens/theme-mutation-observer"); var _colorMode = require("../context/color-mode"); /** * __useColorMode()__ * * Returns the active (reconciled) color mode for the current theme context. * * When the color mode is set to `'auto'`, this hook returns the resolved value * (`'light'` or `'dark'`) based on the system color scheme preference. * it will never return `'auto'`. Use `useSetColorMode` to change the color mode. * * This hook can be used both inside and outside `AppProvider`. When used inside * a nested `ThemeProvider`, it reflects the color mode of that sub-tree. * * @returns The current reconciled color mode: `'light'` or `'dark'`. * * @example * ```tsx * function MyComponent() { * const colorMode = useColorMode(); * * return <p>Current color mode: {colorMode}</p>; * } * ``` */ function useColorMode() { var value = (0, _react.useContext)(_colorMode.ColorModeContext); // TODO: This will only return 'light' or 'dark' but never 'auto', which in some cases // may be desirable. We should consider returning both the reconciled color mode (e.g. 'light' or 'dark') and the selected color mode ("auto"). var theme = (0, _getGlobalTheme.getGlobalTheme)(); var _useState = (0, _react.useState)((theme === null || theme === void 0 ? void 0 : theme.colorMode) || 'light'), _useState2 = (0, _slicedToArray2.default)(_useState, 2), resolvedColorMode = _useState2[0], setResolvedColorMode = _useState2[1]; (0, _react.useEffect)(function () { // We are using theme from context so no need to reference the DOM if (value) { return; } var observer = new _themeMutationObserver.ThemeMutationObserver(function (theme) { setResolvedColorMode((theme === null || theme === void 0 ? void 0 : theme.colorMode) || 'light'); }); observer.observe(); return function () { return observer.disconnect(); }; }, [value]); return value ? value : resolvedColorMode; }