@atlaskit/app-provider
Version:
A top level provider for the Design System.
53 lines (52 loc) • 1.62 kB
JavaScript
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import { useContext, useEffect, useState } from 'react';
import { getGlobalTheme } from '@atlaskit/tokens/get-global-theme';
import { ThemeMutationObserver } from '@atlaskit/tokens/theme-mutation-observer';
import { ThemeContext } from '../context/theme';
/**
* __useTheme()__
*
* Returns the current theme settings for the nearest `ThemeProvider` in the
* React tree.
*
* The returned object contains the named theme IDs for each slot: `light`,
* `dark`, `spacing`, and `typography`. Use `useSetTheme` to change these
* values at runtime.
*
* This hook can be used both inside and outside `AppProvider`. When used
* inside a nested `ThemeProvider`, it reflects the theme of that sub-tree.
*
* @returns The current theme settings object.
*
* @example
* ```tsx
* function ThemeDisplay() {
* const theme = useTheme();
*
* return (
* <p>
* Light theme: {theme.light}, Dark theme: {theme.dark}
* </p>
* );
* }
* ```
*/
export function useTheme() {
var theme = useContext(ThemeContext);
var _useState = useState(theme || getGlobalTheme()),
_useState2 = _slicedToArray(_useState, 2),
resolvedTheme = _useState2[0],
setResolvedTheme = _useState2[1];
useEffect(function () {
// We are using theme from context so no need to reference the DOM
if (theme) {
return;
}
var observer = new ThemeMutationObserver(setResolvedTheme);
observer.observe();
return function () {
return observer.disconnect();
};
}, [theme]);
return theme ? theme : resolvedTheme;
}