Skip to content

Commit

Permalink
feat: add ThemeProvider that don't use globals (#5326)
Browse files Browse the repository at this point in the history
* feat: add ThemeProvider that don't use globals

* chore: Update ThemeProvider to use local imports instead of globals
  • Loading branch information
romainseb committed Jun 6, 2024
1 parent 92fa169 commit 803c4e1
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/warm-pumas-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@talend/design-system": minor
---

feat: add ThemeProvider without globals
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { PropsWithChildren, useContext, useEffect, useState } from 'react';

import 'typeface-inconsolata/index.css';
import 'typeface-source-sans-pro/index.css';

// eslint-disable-next-line @talend/import-depth
import '@talend/design-tokens/dist/TalendDesignTokens.css';

import ThemeContext from './ThemeContext';

export type ThemeProviderProps = PropsWithChildren<{
theme?: string;
tokensOverride?: Record<string, string | number>;
}>;

export const ThemeProviderWithoutGlobals = ({
theme = 'light',
children,
tokensOverride,
}: ThemeProviderProps) => {
const [selectedTheme, setSelectedTheme] = useState(theme);
// Handle nested Providers: parent Provider doesn't have context, child does
const context = useContext(ThemeContext);

useEffect(() => {
document.body.dataset.theme = selectedTheme;
}, [selectedTheme]);

useEffect(() => {
setSelectedTheme(theme);
}, [theme]);

useEffect(() => {
if (tokensOverride) {
Object.keys(tokensOverride).forEach(key => {
document.body.style.setProperty(key, tokensOverride[key].toString());
});
}
}, [tokensOverride]);

const switchTheme = (newTheme: string) => setSelectedTheme(newTheme);
return (
<ThemeContext.Provider value={context.theme ? context : { switchTheme, theme: selectedTheme }}>
{children}
</ThemeContext.Provider>
);
};
4 changes: 3 additions & 1 deletion packages/design-system/src/components/ThemeProvider/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import ThemeSwitcher from './ThemeSwitcher';
import { ThemeProvider as BaseThemeProvider, ThemeProviderProps } from './ThemeProvider';
import ThemeSwitcher from './ThemeSwitcher';

export { ThemeProviderWithoutGlobals } from './ThemeProviderWithoutGlobals';

export const ThemeProvider = BaseThemeProvider as typeof BaseThemeProvider & {
ThemeSwitcher: typeof ThemeSwitcher;
Expand Down

0 comments on commit 803c4e1

Please sign in to comment.