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

[docs-infra] Support inject dynamic theme #42879

Merged
merged 10 commits into from
Aug 1, 2024
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
Loading