fix: not crash ConfigProvider.config on server side (#34118)

This commit is contained in:
二货机器人 2022-02-18 17:07:23 +08:00 committed by GitHub
parent 386ede9297
commit a09a3255f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 4 deletions

View File

@ -1,7 +1,17 @@
import { kebabCase } from 'lodash';
import canUseDom from 'rc-util/lib/Dom/canUseDom';
import ConfigProvider from '..';
import { resetWarned } from '../../_util/devWarning';
let mockCanUseDom = true;
jest.mock('rc-util/lib/Dom/canUseDom', () => () => mockCanUseDom);
describe('ConfigProvider.Theme', () => {
beforeEach(() => {
mockCanUseDom = true;
});
const colorList = ['primaryColor', 'successColor', 'warningColor', 'errorColor', 'infoColor'];
colorList.forEach(colorName => {
@ -22,4 +32,21 @@ describe('ConfigProvider.Theme', () => {
expect(themeStyle.innerHTML).toContain(`--bamboo-${kebabCase(colorName)}: rgb(0, 0, 255)`);
});
});
it('warning for SSR', () => {
resetWarned();
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
mockCanUseDom = false;
expect(canUseDom()).toBeFalsy();
ConfigProvider.config({
theme: {},
});
expect(errorSpy).toHaveBeenCalledWith(
'Warning: [antd: ConfigProvider] SSR do not support dynamic theme with css variables.',
);
errorSpy.mockRestore();
});
});

View File

@ -1,9 +1,11 @@
/* eslint-disable import/prefer-default-export, prefer-destructuring */
import { updateCSS } from 'rc-util/lib/Dom/dynamicCSS';
import canUseDom from 'rc-util/lib/Dom/canUseDom';
import { TinyColor } from '@ctrl/tinycolor';
import { generate } from '@ant-design/colors';
import { Theme } from './context';
import devWarning from '../_util/devWarning';
const dynamicStyleMark = `-ant-${Date.now()}-${Math.random()}`;
@ -86,12 +88,16 @@ export function registerTheme(globalPrefixCls: string, theme: Theme) {
key => `--${globalPrefixCls}-${key}: ${variables[key]};`,
);
updateCSS(
`
if (canUseDom()) {
updateCSS(
`
:root {
${cssList.join('\n')}
}
`,
`${dynamicStyleMark}-dynamic-theme`,
);
`${dynamicStyleMark}-dynamic-theme`,
);
} else {
devWarning(false, 'ConfigProvider', 'SSR do not support dynamic theme with css variables.');
}
}