feat(StyleProvider): add StyleProvider handle cssinjs features (#6415)

* feat(StyleProvider): StyleProvider

* feat(StyleProvider): refactor to  use context

* chore(StyleProvider): update AStyleProviderProps type

* chore(App): reback

* chore(StyleProvider): export StyleProvider

* feat(StyleProvider): update StyleProvider docs

* feat(StyleProvider): update StyleProvider docs

* feat(StyleProvider): add StyleProvider docs routes

* chore(StyleProvider): with useStyleProvider
pull/6425/head
Cherry7 2 years ago committed by GitHub
parent 84037f8eef
commit 1151bdad0f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,9 +1,11 @@
import type { InjectionKey, Ref } from 'vue';
import { unref, computed, inject } from 'vue';
import type { App, ComputedRef, InjectionKey, Ref } from 'vue';
import { provide, defineComponent, unref, computed, inject } from 'vue';
import CacheEntity from './Cache';
import type { Linter } from './linters/interface';
import type { Transformer } from './transformers/interface';
import { arrayType, objectType } from '../type';
import PropTypes from '../vue-types';
import initDefaultProps from '../props-util/initDefaultProps';
export const ATTR_TOKEN = 'data-token-hash';
export const ATTR_MARK = 'data-css-hash';
export const ATTR_DEV_CACHE_PATH = 'data-dev-cache-path';
@ -71,41 +73,83 @@ export interface StyleContextProps {
linters?: Linter[];
}
const StyleContextKey: InjectionKey<StyleContextProps> = Symbol('StyleContextKey');
const StyleContextKey: InjectionKey<ComputedRef<Partial<StyleContextProps>>> =
Symbol('StyleContextKey');
export type StyleProviderProps = Partial<StyleContextProps> | Ref<Partial<StyleContextProps>>;
const defaultStyleContext: StyleContextProps = {
cache: createCache(),
defaultCache: true,
hashPriority: 'low',
};
export const useStyleInject = () => {
return inject(StyleContextKey, {
hashPriority: 'low',
cache: createCache(),
defaultCache: true,
});
return inject(
StyleContextKey,
computed(() => defaultStyleContext),
);
};
export const useStyleProvider = (props: StyleContextProps) => {
export const useStyleProvider = (props: StyleProviderProps) => {
const parentContext = useStyleInject();
const context = computed<StyleContextProps>(() => {
const mergedContext: StyleContextProps = {
...parentContext,
const context = computed<Partial<StyleContextProps>>(() => {
const mergedContext: Partial<StyleContextProps> = {
...parentContext.value,
};
const propsValue = unref(props);
(Object.keys(propsValue) as (keyof StyleContextProps)[]).forEach(key => {
Object.keys(propsValue).forEach(key => {
const value = propsValue[key];
if (propsValue[key] !== undefined) {
(mergedContext as any)[key] = value;
mergedContext[key] = value;
}
});
const { cache } = propsValue;
mergedContext.cache = mergedContext.cache || createCache();
mergedContext.defaultCache = !cache && parentContext.defaultCache;
mergedContext.defaultCache = !cache && parentContext.value.defaultCache;
return mergedContext;
});
provide(StyleContextKey, context);
return context;
};
const AStyleProviderProps = () => ({
autoClear: PropTypes.bool,
/** @private Test only. Not work in production. */
mock: PropTypes.oneOf(['server', 'client'] as const),
/**
* Only set when you need ssr to extract style on you own.
* If not provided, it will auto create <style /> on the end of Provider in server side.
*/
cache: objectType<CacheEntity>(),
/** Tell children that this context is default generated context */
defaultCache: PropTypes.bool,
/** Use `:where` selector to reduce hashId css selector priority */
hashPriority: PropTypes.oneOf(['low', 'high'] as const),
/** Tell cssinjs where to inject style in */
container: PropTypes.oneOfType([objectType<Element>(), objectType<ShadowRoot>()]),
/** Component wil render inline `<style />` for fallback in SSR. Not recommend. */
ssrInline: PropTypes.bool,
/** Transform css before inject in document. Please note that `transformers` do not support dynamic update */
transformers: arrayType<Transformer[]>(),
/**
* Linters to lint css before inject in document.
* Styles will be linted after transforming.
* Please note that `linters` do not support dynamic update.
*/
linters: arrayType<Linter[]>(),
});
export const StyleProvider = defineComponent({
name: 'AStyleProvider',
props: initDefaultProps(AStyleProviderProps(), defaultStyleContext),
setup(props, { slots }) {
useStyleProvider(props);
return () => slots.default?.();
},
});
StyleProvider.install = function (app: App) {
app.component(StyleProvider.name, StyleProvider);
};
export default {
useStyleInject,
useStyleProvider,

@ -17,7 +17,7 @@ export default function useClientCache<CacheType>(
});
const HMRUpdate = useHMR();
const clearCache = (pathStr: string) => {
styleContext.cache.update(pathStr, prevCache => {
styleContext.value.cache.update(pathStr, prevCache => {
const [times = 0, cache] = prevCache || [];
const nextCount = times - 1;
if (nextCount === 0) {
@ -34,7 +34,7 @@ export default function useClientCache<CacheType>(
(newStr, oldStr) => {
if (oldStr) clearCache(oldStr);
// Create cache
styleContext.cache.update(newStr, prevCache => {
styleContext.value.cache.update(newStr, prevCache => {
const [times = 0, cache] = prevCache || [];
// HMR should always ignore cache since developer may change it
@ -47,7 +47,7 @@ export default function useClientCache<CacheType>(
return [times + 1, mergedCache];
});
res.value = styleContext.cache.get(fullPathStr.value)![1];
res.value = styleContext.value.cache.get(fullPathStr.value)![1];
},
{ immediate: true },
);

@ -304,8 +304,8 @@ export default function useStyleRegister(
// Check if need insert style
let isMergedClientSide = isClientSide;
if (process.env.NODE_ENV !== 'production' && styleContext.mock !== undefined) {
isMergedClientSide = styleContext.mock === 'client';
if (process.env.NODE_ENV !== 'production' && styleContext.value.mock !== undefined) {
isMergedClientSide = styleContext.value.mock === 'client';
}
// const [cacheStyle[0], cacheStyle[1], cacheStyle[2]]
@ -315,7 +315,7 @@ export default function useStyleRegister(
// Create cache if needed
() => {
const styleObj = styleFn();
const { hashPriority, container, transformers, linters } = styleContext;
const { hashPriority, container, transformers, linters } = styleContext.value;
const { path, hashId, layer } = info.value;
const [parsedStyle, effectStyle] = parseStyle(styleObj, {
hashId,
@ -364,7 +364,7 @@ export default function useStyleRegister(
},
// Remove cache if no need
([, , styleId], fromHMR) => {
if ((fromHMR || styleContext.autoClear) && isClientSide) {
if ((fromHMR || styleContext.value.autoClear) && isClientSide) {
removeCSS(styleId, { mark: ATTR_MARK });
}
},

@ -4,7 +4,8 @@ import useStyleRegister, { extractStyle } from './hooks/useStyleRegister';
import Keyframes from './Keyframes';
import type { Linter } from './linters';
import { legacyNotSelectorLinter, logicalPropertiesLinter } from './linters';
import { createCache, useStyleInject, useStyleProvider } from './StyleContext';
import type { StyleContextProps } from './StyleContext';
import { createCache, useStyleInject, useStyleProvider, StyleProvider } from './StyleContext';
import type { DerivativeFunc, TokenType } from './theme';
import { createTheme, Theme } from './theme';
import type { Transformer } from './transformers/interface';
@ -27,5 +28,16 @@ export {
// Linters
logicalPropertiesLinter,
legacyNotSelectorLinter,
// cssinjs
StyleProvider,
};
export type {
TokenType,
CSSObject,
CSSInterpolation,
DerivativeFunc,
Transformer,
Linter,
StyleContextProps,
};
export type { TokenType, CSSObject, CSSInterpolation, DerivativeFunc, Transformer, Linter };

@ -48,7 +48,7 @@ export { default as Comment } from './comment';
export type { ConfigProviderProps } from './config-provider';
export { default as ConfigProvider } from './config-provider';
export * from './_util/cssinjs';
export type { DatePickerProps } from './date-picker';
export {
default as DatePicker,

@ -85,6 +85,16 @@ const routes = [
meta: { enTitle: 'Getting Started', title: '快速上手', category: 'docs' },
component: () => import('../vueDocs/getting-started.en-US.md'),
},
{
path: 'vue/compatible-style-cn',
meta: { enTitle: 'Compatible Style', title: '样式兼容', category: 'docs' },
component: () => import('../vueDocs/compatible-style.zh-CN.md'),
},
{
path: 'vue/compatible-style',
meta: { enTitle: 'Compatible Style', title: '样式兼容', category: 'docs' },
component: () => import('../vueDocs/compatible-style.en-US.md'),
},
{
path: 'vue/customize-theme-cn',
meta: { enTitle: 'Customize Theme', title: '定制主题', category: 'docs' },

@ -0,0 +1,59 @@
---
order: 6.5
title: CSS Compatible
---
Ant Design Vue supports the last 2 versions of modern browsers. If you need to be compatible with legacy browsers, please perform downgrade processing according to actual needs:
### Compatible adjustment
Ant Design Vue default using CSS-in-JS with `:where` Selector to reduce priority to avoid user additional adjust style cost when updating. If you want to support old browser (or some other CSS framework selector priority conflict like TailwindCSS), you can use `StyleProvider` to adjust this behavior :
```html
// `hashPriority` 默认为 `low`,配置为 `high` 后, // 会移除 `:where` 选择器封装
<template>
<a-style-provider hash-priority="high">
<MyApp />
</a-style-provider>
</template>
```
It will turn `:where` to class selector:
```diff
-- :where(.css-bAMboO).ant-btn {
++ .css-bAMboO.ant-btn {
color: #fff;
}
```
Note: After turning off the `:where` downgrade, you may need to manually adjust the priority of some styles.
### CSS Logical Properties
To unify LTR and RTL styles, Ant Design Vue uses CSS logical properties. For example, the original `margin-left` is replaced by `margin-inline-start`, so that it is the starting position spacing under both LTR and RTL. If you need to be compatible with older browsers, you can configure `transformers` through the `StyleProvider` of `@ant-design/cssinjs`:
```html
// `transformers` 提供预处理功能将样式进行转换
<template>
<a-style-provider :transformers="[legacyLogicalPropertiesTransformer]">
<MyApp />
</a-style-provider>
</template>
<script lang="ts" setup>
import { legacyLogicalPropertiesTransformer } from 'ant-design-vue';
</script>
```
When toggled, styles will downgrade CSS logical properties:
```diff
.ant-modal-root {
-- inset: 0;
++ top: 0;
++ right: 0;
++ bottom: 0;
++ left: 0;
}
```

@ -0,0 +1,59 @@
---
order: 6.5
title: 样式兼容
---
Ant Design Vue 支持最近 2 个版本的现代浏览器。如果你需要兼容旧版浏览器,请根据实际需求进行降级处理:
### `:where` 选择器
Ant Design Vue 的 CSS-in-JS 默认通过 `:where` 选择器降低 CSS Selector 优先级,以减少用户升级时额外调整自定义样式成本。在某些场景下你如果需要支持的旧版浏览器(或者如 TailwindCSS 优先级冲突),你可以使用 `StyleProvider` 取消默认的降权操作
```html
// `hashPriority` 默认为 `low`,配置为 `high` 后, // 会移除 `:where` 选择器封装
<template>
<a-style-provider hash-priority="high">
<MyApp />
</a-style-provider>
</template>
```
切换后,样式将从 `:where` 切换为类选择器:
```diff
-- :where(.css-bAMboO).ant-btn {
++ .css-bAMboO.ant-btn {
color: #fff;
}
```
注意:关闭 `:where` 降权后,你可能需要手动调整一些样式的优先级。
### CSS 逻辑属性
为了统一 LTR 和 RTL 样式Ant Design Vue 使用了 CSS 逻辑属性。例如原 `margin-left` 使用 `margin-inline-start` 代替,使其在 LTR 和 RTL 下都为起始位置间距。如果你需要兼容旧版浏览器(如 360 浏览器、QQ 浏览器 等等),可以通过 `ant-design-vue``StyleProvider` 配置 `transformers` 将其转换:
```html
// `transformers` 提供预处理功能将样式进行转换
<template>
<a-style-provider :transformers="[legacyLogicalPropertiesTransformer]">
<MyApp />
</a-style-provider>
</template>
<script lang="ts" setup>
import { legacyLogicalPropertiesTransformer } from 'ant-design-vue';
</script>
```
切换后,样式将降级 CSS 逻辑属性:
```diff
.ant-modal-root {
-- inset: 0;
++ top: 0;
++ right: 0;
++ bottom: 0;
++ left: 0;
}
```

@ -63,6 +63,8 @@ declare module 'vue' {
AConfigProvider: typeof import('ant-design-vue')['ConfigProvider'];
AStyleProvider: typeof import('ant-design-vue')['StyleProvider'];
ADatePicker: typeof import('ant-design-vue')['DatePicker'];
ADescriptions: typeof import('ant-design-vue')['Descriptions'];

Loading…
Cancel
Save