Skip to content

Commit 1151bda

Browse files
authored
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
1 parent 84037f8 commit 1151bda

File tree

9 files changed

+215
-29
lines changed

9 files changed

+215
-29
lines changed

components/_util/cssinjs/StyleContext.tsx

Lines changed: 63 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
import type { InjectionKey, Ref } from 'vue';
2-
import { unref, computed, inject } from 'vue';
1+
import type { App, ComputedRef, InjectionKey, Ref } from 'vue';
2+
import { provide, defineComponent, unref, computed, inject } from 'vue';
33
import CacheEntity from './Cache';
44
import type { Linter } from './linters/interface';
55
import type { Transformer } from './transformers/interface';
6-
6+
import { arrayType, objectType } from '../type';
7+
import PropTypes from '../vue-types';
8+
import initDefaultProps from '../props-util/initDefaultProps';
79
export const ATTR_TOKEN = 'data-token-hash';
810
export const ATTR_MARK = 'data-css-hash';
911
export const ATTR_DEV_CACHE_PATH = 'data-dev-cache-path';
@@ -71,41 +73,83 @@ export interface StyleContextProps {
7173
linters?: Linter[];
7274
}
7375

74-
const StyleContextKey: InjectionKey<StyleContextProps> = Symbol('StyleContextKey');
76+
const StyleContextKey: InjectionKey<ComputedRef<Partial<StyleContextProps>>> =
77+
Symbol('StyleContextKey');
7578

7679
export type StyleProviderProps = Partial<StyleContextProps> | Ref<Partial<StyleContextProps>>;
80+
const defaultStyleContext: StyleContextProps = {
81+
cache: createCache(),
82+
defaultCache: true,
83+
hashPriority: 'low',
84+
};
7785
export const useStyleInject = () => {
78-
return inject(StyleContextKey, {
79-
hashPriority: 'low',
80-
cache: createCache(),
81-
defaultCache: true,
82-
});
86+
return inject(
87+
StyleContextKey,
88+
computed(() => defaultStyleContext),
89+
);
8390
};
84-
export const useStyleProvider = (props: StyleContextProps) => {
91+
export const useStyleProvider = (props: StyleProviderProps) => {
8592
const parentContext = useStyleInject();
8693

87-
const context = computed<StyleContextProps>(() => {
88-
const mergedContext: StyleContextProps = {
89-
...parentContext,
94+
const context = computed<Partial<StyleContextProps>>(() => {
95+
const mergedContext: Partial<StyleContextProps> = {
96+
...parentContext.value,
9097
};
9198
const propsValue = unref(props);
92-
(Object.keys(propsValue) as (keyof StyleContextProps)[]).forEach(key => {
99+
Object.keys(propsValue).forEach(key => {
93100
const value = propsValue[key];
94101
if (propsValue[key] !== undefined) {
95-
(mergedContext as any)[key] = value;
102+
mergedContext[key] = value;
96103
}
97104
});
98105

99106
const { cache } = propsValue;
100107
mergedContext.cache = mergedContext.cache || createCache();
101-
mergedContext.defaultCache = !cache && parentContext.defaultCache;
102-
108+
mergedContext.defaultCache = !cache && parentContext.value.defaultCache;
103109
return mergedContext;
104110
});
105-
111+
provide(StyleContextKey, context);
106112
return context;
107113
};
108-
114+
const AStyleProviderProps = () => ({
115+
autoClear: PropTypes.bool,
116+
/** @private Test only. Not work in production. */
117+
mock: PropTypes.oneOf(['server', 'client'] as const),
118+
/**
119+
* Only set when you need ssr to extract style on you own.
120+
* If not provided, it will auto create <style /> on the end of Provider in server side.
121+
*/
122+
cache: objectType<CacheEntity>(),
123+
/** Tell children that this context is default generated context */
124+
defaultCache: PropTypes.bool,
125+
/** Use `:where` selector to reduce hashId css selector priority */
126+
hashPriority: PropTypes.oneOf(['low', 'high'] as const),
127+
/** Tell cssinjs where to inject style in */
128+
container: PropTypes.oneOfType([objectType<Element>(), objectType<ShadowRoot>()]),
129+
/** Component wil render inline `<style />` for fallback in SSR. Not recommend. */
130+
ssrInline: PropTypes.bool,
131+
/** Transform css before inject in document. Please note that `transformers` do not support dynamic update */
132+
transformers: arrayType<Transformer[]>(),
133+
/**
134+
* Linters to lint css before inject in document.
135+
* Styles will be linted after transforming.
136+
* Please note that `linters` do not support dynamic update.
137+
*/
138+
linters: arrayType<Linter[]>(),
139+
});
140+
141+
export const StyleProvider = defineComponent({
142+
name: 'AStyleProvider',
143+
props: initDefaultProps(AStyleProviderProps(), defaultStyleContext),
144+
setup(props, { slots }) {
145+
useStyleProvider(props);
146+
return () => slots.default?.();
147+
},
148+
});
149+
150+
StyleProvider.install = function (app: App) {
151+
app.component(StyleProvider.name, StyleProvider);
152+
};
109153
export default {
110154
useStyleInject,
111155
useStyleProvider,

components/_util/cssinjs/hooks/useGlobalCache.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export default function useClientCache<CacheType>(
1717
});
1818
const HMRUpdate = useHMR();
1919
const clearCache = (pathStr: string) => {
20-
styleContext.cache.update(pathStr, prevCache => {
20+
styleContext.value.cache.update(pathStr, prevCache => {
2121
const [times = 0, cache] = prevCache || [];
2222
const nextCount = times - 1;
2323
if (nextCount === 0) {
@@ -34,7 +34,7 @@ export default function useClientCache<CacheType>(
3434
(newStr, oldStr) => {
3535
if (oldStr) clearCache(oldStr);
3636
// Create cache
37-
styleContext.cache.update(newStr, prevCache => {
37+
styleContext.value.cache.update(newStr, prevCache => {
3838
const [times = 0, cache] = prevCache || [];
3939

4040
// HMR should always ignore cache since developer may change it
@@ -47,7 +47,7 @@ export default function useClientCache<CacheType>(
4747

4848
return [times + 1, mergedCache];
4949
});
50-
res.value = styleContext.cache.get(fullPathStr.value)![1];
50+
res.value = styleContext.value.cache.get(fullPathStr.value)![1];
5151
},
5252
{ immediate: true },
5353
);

components/_util/cssinjs/hooks/useStyleRegister.tsx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -304,8 +304,8 @@ export default function useStyleRegister(
304304

305305
// Check if need insert style
306306
let isMergedClientSide = isClientSide;
307-
if (process.env.NODE_ENV !== 'production' && styleContext.mock !== undefined) {
308-
isMergedClientSide = styleContext.mock === 'client';
307+
if (process.env.NODE_ENV !== 'production' && styleContext.value.mock !== undefined) {
308+
isMergedClientSide = styleContext.value.mock === 'client';
309309
}
310310

311311
// const [cacheStyle[0], cacheStyle[1], cacheStyle[2]]
@@ -315,7 +315,7 @@ export default function useStyleRegister(
315315
// Create cache if needed
316316
() => {
317317
const styleObj = styleFn();
318-
const { hashPriority, container, transformers, linters } = styleContext;
318+
const { hashPriority, container, transformers, linters } = styleContext.value;
319319
const { path, hashId, layer } = info.value;
320320
const [parsedStyle, effectStyle] = parseStyle(styleObj, {
321321
hashId,
@@ -364,7 +364,7 @@ export default function useStyleRegister(
364364
},
365365
// Remove cache if no need
366366
([, , styleId], fromHMR) => {
367-
if ((fromHMR || styleContext.autoClear) && isClientSide) {
367+
if ((fromHMR || styleContext.value.autoClear) && isClientSide) {
368368
removeCSS(styleId, { mark: ATTR_MARK });
369369
}
370370
},

components/_util/cssinjs/index.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ import useStyleRegister, { extractStyle } from './hooks/useStyleRegister';
44
import Keyframes from './Keyframes';
55
import type { Linter } from './linters';
66
import { legacyNotSelectorLinter, logicalPropertiesLinter } from './linters';
7-
import { createCache, useStyleInject, useStyleProvider } from './StyleContext';
7+
import type { StyleContextProps } from './StyleContext';
8+
import { createCache, useStyleInject, useStyleProvider, StyleProvider } from './StyleContext';
89
import type { DerivativeFunc, TokenType } from './theme';
910
import { createTheme, Theme } from './theme';
1011
import type { Transformer } from './transformers/interface';
@@ -27,5 +28,16 @@ export {
2728
// Linters
2829
logicalPropertiesLinter,
2930
legacyNotSelectorLinter,
31+
32+
// cssinjs
33+
StyleProvider,
34+
};
35+
export type {
36+
TokenType,
37+
CSSObject,
38+
CSSInterpolation,
39+
DerivativeFunc,
40+
Transformer,
41+
Linter,
42+
StyleContextProps,
3043
};
31-
export type { TokenType, CSSObject, CSSInterpolation, DerivativeFunc, Transformer, Linter };

components/components.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ export { default as Comment } from './comment';
4848

4949
export type { ConfigProviderProps } from './config-provider';
5050
export { default as ConfigProvider } from './config-provider';
51-
51+
export * from './_util/cssinjs';
5252
export type { DatePickerProps } from './date-picker';
5353
export {
5454
default as DatePicker,

site/src/router/index.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,16 @@ const routes = [
8585
meta: { enTitle: 'Getting Started', title: '快速上手', category: 'docs' },
8686
component: () => import('../vueDocs/getting-started.en-US.md'),
8787
},
88+
{
89+
path: 'vue/compatible-style-cn',
90+
meta: { enTitle: 'Compatible Style', title: '样式兼容', category: 'docs' },
91+
component: () => import('../vueDocs/compatible-style.zh-CN.md'),
92+
},
93+
{
94+
path: 'vue/compatible-style',
95+
meta: { enTitle: 'Compatible Style', title: '样式兼容', category: 'docs' },
96+
component: () => import('../vueDocs/compatible-style.en-US.md'),
97+
},
8898
{
8999
path: 'vue/customize-theme-cn',
90100
meta: { enTitle: 'Customize Theme', title: '定制主题', category: 'docs' },
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
---
2+
order: 6.5
3+
title: CSS Compatible
4+
---
5+
6+
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:
7+
8+
### Compatible adjustment
9+
10+
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 :
11+
12+
```html
13+
// `hashPriority` 默认为 `low`,配置为 `high` 后, // 会移除 `:where` 选择器封装
14+
<template>
15+
<a-style-provider hash-priority="high">
16+
<MyApp />
17+
</a-style-provider>
18+
</template>
19+
```
20+
21+
It will turn `:where` to class selector:
22+
23+
```diff
24+
-- :where(.css-bAMboO).ant-btn {
25+
++ .css-bAMboO.ant-btn {
26+
color: #fff;
27+
}
28+
```
29+
30+
Note: After turning off the `:where` downgrade, you may need to manually adjust the priority of some styles.
31+
32+
### CSS Logical Properties
33+
34+
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`:
35+
36+
```html
37+
// `transformers` 提供预处理功能将样式进行转换
38+
<template>
39+
<a-style-provider :transformers="[legacyLogicalPropertiesTransformer]">
40+
<MyApp />
41+
</a-style-provider>
42+
</template>
43+
44+
<script lang="ts" setup>
45+
import { legacyLogicalPropertiesTransformer } from 'ant-design-vue';
46+
</script>
47+
```
48+
49+
When toggled, styles will downgrade CSS logical properties:
50+
51+
```diff
52+
.ant-modal-root {
53+
-- inset: 0;
54+
++ top: 0;
55+
++ right: 0;
56+
++ bottom: 0;
57+
++ left: 0;
58+
}
59+
```
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
---
2+
order: 6.5
3+
title: 样式兼容
4+
---
5+
6+
Ant Design Vue 支持最近 2 个版本的现代浏览器。如果你需要兼容旧版浏览器,请根据实际需求进行降级处理:
7+
8+
### `:where` 选择器
9+
10+
Ant Design Vue 的 CSS-in-JS 默认通过 `:where` 选择器降低 CSS Selector 优先级,以减少用户升级时额外调整自定义样式成本。在某些场景下你如果需要支持的旧版浏览器(或者如 TailwindCSS 优先级冲突),你可以使用 `StyleProvider` 取消默认的降权操作 :
11+
12+
```html
13+
// `hashPriority` 默认为 `low`,配置为 `high` 后, // 会移除 `:where` 选择器封装
14+
<template>
15+
<a-style-provider hash-priority="high">
16+
<MyApp />
17+
</a-style-provider>
18+
</template>
19+
```
20+
21+
切换后,样式将从 `:where` 切换为类选择器:
22+
23+
```diff
24+
-- :where(.css-bAMboO).ant-btn {
25+
++ .css-bAMboO.ant-btn {
26+
color: #fff;
27+
}
28+
```
29+
30+
注意:关闭 `:where` 降权后,你可能需要手动调整一些样式的优先级。
31+
32+
### CSS 逻辑属性
33+
34+
为了统一 LTR 和 RTL 样式,Ant Design Vue 使用了 CSS 逻辑属性。例如原 `margin-left` 使用 `margin-inline-start` 代替,使其在 LTR 和 RTL 下都为起始位置间距。如果你需要兼容旧版浏览器(如 360 浏览器、QQ 浏览器 等等),可以通过 `ant-design-vue``StyleProvider` 配置 `transformers` 将其转换:
35+
36+
```html
37+
// `transformers` 提供预处理功能将样式进行转换
38+
<template>
39+
<a-style-provider :transformers="[legacyLogicalPropertiesTransformer]">
40+
<MyApp />
41+
</a-style-provider>
42+
</template>
43+
44+
<script lang="ts" setup>
45+
import { legacyLogicalPropertiesTransformer } from 'ant-design-vue';
46+
</script>
47+
```
48+
49+
切换后,样式将降级 CSS 逻辑属性:
50+
51+
```diff
52+
.ant-modal-root {
53+
-- inset: 0;
54+
++ top: 0;
55+
++ right: 0;
56+
++ bottom: 0;
57+
++ left: 0;
58+
}
59+
```

typings/global.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ declare module 'vue' {
6363

6464
AConfigProvider: typeof import('ant-design-vue')['ConfigProvider'];
6565

66+
AStyleProvider: typeof import('ant-design-vue')['StyleProvider'];
67+
6668
ADatePicker: typeof import('ant-design-vue')['DatePicker'];
6769

6870
ADescriptions: typeof import('ant-design-vue')['Descriptions'];

0 commit comments

Comments
 (0)