Skip to content

Commit

Permalink
[docs] Support inject dynamic theme (#42879)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vxee authored Aug 1, 2024
1 parent c105c0b commit b8815f0
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions docs/src/modules/components/DemoSandbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import DemoErrorBoundary from 'docs/src/modules/components/DemoErrorBoundary';
import { useTranslate } from '@mui/docs/i18n';
import { getDesignTokens } from '@mui/docs/branding';
import { highDensity } from 'docs/src/modules/components/ThemeContext';
import { deepmerge, unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils';

const iframeDefaultJoyTheme = extendTheme({
cssVarPrefix: 'demo-iframe',
Expand Down Expand Up @@ -139,7 +140,7 @@ DemoIframe.propTypes = {
};

// Use the default Material UI theme for the demos
function getTheme(outerTheme) {
function getTheme(outerTheme, injectTheme) {
const brandingDesignTokens = getDesignTokens(outerTheme.palette.mode);
const isCustomized =
outerTheme.palette.primary?.main &&
Expand All @@ -165,6 +166,14 @@ function getTheme(outerTheme) {
if (outerTheme.spacing) {
resultTheme.spacing = outerTheme.spacing;
}

if (injectTheme && Object.prototype.toString.call(injectTheme) === '[object Object]') {
try {
return deepmerge(resultTheme, injectTheme);
} catch (e) {
return resultTheme;
}
}
return resultTheme;
}

Expand All @@ -187,6 +196,7 @@ function DemoSandbox(props) {
usesCssVarsTheme,
...other
} = props;
const [injectTheme, setInjectTheme] = React.useState();
const Sandbox = iframe ? DemoIframe : React.Fragment;
const sandboxProps = iframe ? { name, usesCssVarsTheme, ...other } : {};

Expand All @@ -195,13 +205,28 @@ function DemoSandbox(props) {
// `childrenProp` needs to be a child of `Sandbox` since the iframe implementation rely on `cloneElement`.
const children = <Sandbox {...sandboxProps}>{childrenProp}</Sandbox>;

useEnhancedEffect(() => {
async function setupMaterialUITheme() {
if (typeof window.getInjectTheme === 'function') {
window.React = React;
const jsx = await import('react/jsx-runtime');
window.jsx = jsx;
const themeOptions = window.getInjectTheme();
setInjectTheme(themeOptions);
}
}
setupMaterialUITheme();
}, []);

return (
<DemoErrorBoundary name={name} onResetDemoClick={onResetDemoClick} t={t}>
{usesCssVarsTheme ? (
children
) : (
<StylesProvider jss={jss}>
<ThemeProvider theme={(outerTheme) => getTheme(outerTheme)}>{children}</ThemeProvider>
<ThemeProvider theme={(outerTheme) => getTheme(outerTheme, injectTheme)}>
{children}
</ThemeProvider>
</StylesProvider>
)}
</DemoErrorBoundary>
Expand Down

0 comments on commit b8815f0

Please sign in to comment.