UNPKG

1.77 kBJavaScriptView Raw
1/* eslint-disable import/prefer-default-export */
2import { isPlainObject } from '@mui/utils/deepmerge';
3function isSerializable(val) {
4 return isPlainObject(val) || typeof val === 'undefined' || typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number' || Array.isArray(val);
5}
6
7/**
8 * `baseTheme` usually comes from `createTheme()` or `extendTheme()`.
9 *
10 * This function is intended to be used with zero-runtime CSS-in-JS like Pigment CSS
11 * For example, in a Next.js project:
12 *
13 * ```js
14 * // next.config.js
15 * const { extendTheme } = require('@mui/material/styles');
16 *
17 * const theme = extendTheme();
18 * // `.toRuntimeSource` is Pigment CSS specific to create a theme that is available at runtime.
19 * theme.toRuntimeSource = stringifyTheme;
20 *
21 * module.exports = withPigment({
22 * theme,
23 * });
24 * ```
25 */
26export function stringifyTheme(baseTheme = {}) {
27 const serializableTheme = {
28 ...baseTheme
29 };
30 function serializeTheme(object) {
31 const array = Object.entries(object);
32 // eslint-disable-next-line no-plusplus
33 for (let index = 0; index < array.length; index++) {
34 const [key, value] = array[index];
35 if (!isSerializable(value) || key.startsWith('unstable_')) {
36 delete object[key];
37 } else if (isPlainObject(value)) {
38 object[key] = {
39 ...value
40 };
41 serializeTheme(object[key]);
42 }
43 }
44 }
45 serializeTheme(serializableTheme);
46 return `import { unstable_createBreakpoints as createBreakpoints, createTransitions } from '@mui/material/styles';
47
48const theme = ${JSON.stringify(serializableTheme, null, 2)};
49
50theme.breakpoints = createBreakpoints(theme.breakpoints || {});
51theme.transitions = createTransitions(theme.transitions || {});
52
53export default theme;`;
54}
\No newline at end of file