Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make theme='inherit' the default #1478

Merged
merged 4 commits into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/hip-moose-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@itwin/itwinui-react': major
---

ThemeProvider now defaults the `theme` value to `"inherit"` and falls back to `"light"` there is no parent theme found. Also the inherit behavior has been made more resilient for cases where react context fails.
r100-stack marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import * as React from 'react';
import { render } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import * as UseMediaQuery from '../utils/hooks/useMediaQuery.js';

import { ThemeProvider } from './ThemeProvider.js';
Expand All @@ -18,13 +18,11 @@ beforeEach(() => {

afterEach(() => useMediaSpy.mockRestore());

it.each(['default', 'light', 'dark'] as const)(
it.each(['light', 'dark'] as const)(
'should render correctly with %s theme',
(theme) => {
const { container } = render(
<ThemeProvider theme={theme === 'default' ? undefined : theme}>
Test
</ThemeProvider>,
<ThemeProvider theme={theme}>Test</ThemeProvider>,
);
const element = container.querySelector('div');
expect(element).toBeTruthy();
Expand Down Expand Up @@ -142,6 +140,7 @@ it('should apply iui-root-background to the topmost ThemeProvider', () => {
it('should default applyBackground to false when inheriting theme', () => {
const { container, rerender } = render(
<ThemeProvider theme='inherit'>Hello</ThemeProvider>,
{ wrapper: ({ children }) => <div data-iui-theme='light'>{children}</div> },
);
const element = container.querySelector('.iui-root');
expect(element).not.toHaveClass('iui-root-background');
Expand All @@ -154,3 +153,29 @@ it('should default applyBackground to false when inheriting theme', () => {
);
expect(element).toHaveClass('iui-root-background');
});

it('should inherit theme by default', () => {
const { container } = render(
<ThemeProvider theme='dark'>
<ThemeProvider id='nested'>Test</ThemeProvider>
</ThemeProvider>,
);

const nested = container.querySelector('#nested');
expect(nested).toHaveAttribute('data-iui-theme', 'dark');
});

it('should inherit theme from data attribute if no context found', () => {
const { container } = render(
<ThemeProvider id='nested'>Test</ThemeProvider>,
{ wrapper: ({ children }) => <div data-iui-theme='dark'>{children}</div> },
);
r100-stack marked this conversation as resolved.
Show resolved Hide resolved

const nested = container.querySelector('#nested');
expect(nested).toHaveAttribute('data-iui-theme', 'dark');
});

it('should default to light theme if no parent theme found', () => {
render(<ThemeProvider>Test</ThemeProvider>);
expect(screen.getByText('Test')).toHaveAttribute('data-iui-theme', 'light');
});
67 changes: 51 additions & 16 deletions packages/itwinui-react/src/core/ThemeProvider/ThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
*--------------------------------------------------------------------------------------------*/
import * as React from 'react';
import cx from 'classnames';
import { useMediaQuery, useMergedRefs, Box } from '../utils/index.js';
import {
useMediaQuery,
useMergedRefs,
Box,
useIsomorphicLayoutEffect,
} from '../utils/index.js';
import type { PolymorphicForwardRefComponent } from '../utils/index.js';
import { ThemeContext } from './ThemeContext.js';
import { ToastProvider, Toaster } from '../Toast/Toaster.js';
Expand Down Expand Up @@ -59,9 +64,11 @@ type ThemeProviderOwnProps = Pick<RootProps, 'theme'> & {
};

/**
* This component provides global styles and applies theme to the entire tree
* that it is wrapping around. The `theme` prop is optional and defaults to the
* light theme.
* This component provides global state and applies theme to the entire tree
* that it is wrapping around.
*
* The `theme` prop defaults to "inherit", which looks upwards for closest ThemeProvider
* and falls back to "light" theme if one is not found.
*
* If you want to theme the entire app, you should use this component at the root. You can also
* use this component to apply a different theme to only a part of the tree.
Expand All @@ -84,18 +91,20 @@ type ThemeProviderOwnProps = Pick<RootProps, 'theme'> & {
* <App />
* </ThemeProvider>
*/
export const ThemeProvider = React.forwardRef((props, ref) => {
const { theme: themeProp, children, themeOptions, ...rest } = props;
export const ThemeProvider = React.forwardRef((props, forwardedRef) => {
const {
theme: themeProp = 'inherit',
children,
themeOptions,
...rest
} = props;

const portalContainerRef = React.useRef<HTMLDivElement>(null);
const parentContext = React.useContext(ThemeContext);

const theme =
themeProp === 'inherit' ? parentContext?.theme ?? 'light' : themeProp;
const [parentTheme, rootRef] = useParentTheme();
const theme = themeProp === 'inherit' ? parentTheme || 'light' : themeProp;

const shouldApplyBackground =
themeOptions?.applyBackground ??
(themeProp === 'inherit' ? false : !parentContext);
const shouldApplyBackground = themeOptions?.applyBackground ?? !parentTheme;

const contextValue = React.useMemo(
() => ({ theme, themeOptions, portalContainerRef }),
Expand All @@ -108,7 +117,7 @@ export const ThemeProvider = React.forwardRef((props, ref) => {
theme={theme}
shouldApplyBackground={shouldApplyBackground}
themeOptions={themeOptions}
ref={ref}
ref={useMergedRefs(forwardedRef, rootRef)}
{...rest}
>
<ToastProvider>
Expand All @@ -124,6 +133,8 @@ export const ThemeProvider = React.forwardRef((props, ref) => {

export default ThemeProvider;

// ----------------------------------------------------------------------------

const Root = React.forwardRef((props, forwardedRef) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Might help to explain what is the purpose of Root, even though it is not exported.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it was not added in this PR though.

const {
theme,
Expand All @@ -134,8 +145,6 @@ const Root = React.forwardRef((props, forwardedRef) => {
...rest
} = props;

const ref = React.useRef<HTMLElement>(null);
const mergedRefs = useMergedRefs(ref, forwardedRef);
const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
const prefersHighContrast = useMediaQuery('(prefers-contrast: more)');
const shouldApplyDark = theme === 'dark' || (theme === 'os' && prefersDark);
Expand All @@ -150,10 +159,36 @@ const Root = React.forwardRef((props, forwardedRef) => {
)}
data-iui-theme={shouldApplyDark ? 'dark' : 'light'}
data-iui-contrast={shouldApplyHC ? 'high' : 'default'}
ref={mergedRefs}
ref={forwardedRef}
{...rest}
>
{children}
</Box>
);
}) as PolymorphicForwardRefComponent<'div', RootProps>;

// ----------------------------------------------------------------------------

/**
* Returns theme from either parent context or by reading the closest
* data-iui-theme attribute if context is not found.
*/
const useParentTheme = () => {
const parentContext = React.useContext(ThemeContext);
const rootRef = React.useRef<HTMLElement>(null);
const [parentThemeState, setParentTheme] = React.useState(
parentContext?.theme,
);

useIsomorphicLayoutEffect(() => {
setParentTheme(
(old) =>
old ||
(rootRef.current?.parentElement
?.closest('[data-iui-theme]')
?.getAttribute('data-iui-theme') as ThemeType),
);
}, []);
r100-stack marked this conversation as resolved.
Show resolved Hide resolved

return [parentContext?.theme || parentThemeState, rootRef] as const;
r100-stack marked this conversation as resolved.
Show resolved Hide resolved
};