UNPKG

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