Skip to content

Feat 4.3 spin #8213

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: css var
  • Loading branch information
tangjinzhou committed Nov 8, 2024
commit a1e029429f9eeac3f375df38f89221ca8fc6f208
37 changes: 11 additions & 26 deletions components/_theme/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,39 +64,24 @@ export interface DesignTokenProviderProps {
};
}

export const useDesignTokenInject = () => {
return inject(
DesignTokenContextKey,
computed(() => globalDesignTokenApi.value || defaultConfig),
);
};

export const useDesignTokenProvider = (props: ComputedRef<DesignTokenProviderProps>) => {
const parentContext = useDesignTokenInject();
const context = shallowRef<Partial<DesignTokenProviderProps>>(defaultConfig);
export const useDesignTokenProvider = (value: ComputedRef<DesignTokenProviderProps>) => {
provide(DesignTokenContextKey, value);
watch(
computed(() => [props.value, parentContext.value]),
([propsValue, parentContextValue]) => {
const mergedContext: Partial<DesignTokenProviderProps> = {
...parentContextValue,
};
Object.keys(propsValue).forEach(key => {
const value = propsValue[key];
if (propsValue[key] !== undefined) {
mergedContext[key] = value;
}
});

context.value = mergedContext;
globalDesignTokenApi.value = unref(mergedContext as any);
value,
() => {
globalDesignTokenApi.value = unref(value);
triggerRef(globalDesignTokenApi);
},
{ immediate: true, deep: true },
);
provide(DesignTokenContextKey, context);
return context;
};

export const useDesignTokenInject = () => {
return inject(
DesignTokenContextKey,
computed(() => globalDesignTokenApi.value || defaultConfig),
);
};
export const DesignTokenProvider = defineComponent({
props: {
value: objectType<DesignTokenProviderProps>(),
Expand Down
59 changes: 7 additions & 52 deletions components/_util/_cssinjs/hooks/useCSSVarRegister.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { updateCSS } from '../../../vc-util/Dom/dynamicCSS';
import { removeCSS, updateCSS } from '../../../vc-util/Dom/dynamicCSS';
import { ATTR_MARK, ATTR_TOKEN, CSS_IN_JS_INSTANCE, useStyleInject } from '../StyleContext';
import { isClientSide, token2key, toStyleStr } from '../util';
import { isClientSide, toStyleStr } from '../util';
import type { TokenWithCSSVar } from '../util/css-variables';
import { transformToken } from '../util/css-variables';
import type { ExtractStyle } from './useGlobalCache';
Expand All @@ -14,50 +14,10 @@ export const CSS_VAR_PREFIX = 'cssVar';
type CSSVarCacheValue<V, T extends Record<string, V> = Record<string, V>> = [
cssVarToken: TokenWithCSSVar<V, T>,
cssVarStr: string,
tokenKey: string,
styleId: string,
cssVarKey: string,
];

const tokenKeys = new Map<string, number>();
function recordCleanToken(tokenKey: string) {
tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) + 1);
}

function removeStyleTags(key: string, instanceId: string) {
if (typeof document !== 'undefined') {
const styles = document.querySelectorAll(`style[${ATTR_MARK}="${key}"]`);

styles.forEach(style => {
if ((style as any)[CSS_IN_JS_INSTANCE] === instanceId) {
style.parentNode?.removeChild(style);
}
});
}
}

const TOKEN_THRESHOLD = 0;

// Remove will check current keys first
function cleanTokenStyle(tokenKey: string, instanceId: string) {
tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) - 1);

const tokenKeyList = Array.from(tokenKeys.keys());
const cleanableKeyList = tokenKeyList.filter(key => {
const count = tokenKeys.get(key) || 0;

return count <= 0;
});

// Should keep tokens under threshold for not to insert style too often
if (tokenKeyList.length - cleanableKeyList.length > TOKEN_THRESHOLD) {
cleanableKeyList.forEach(key => {
removeStyleTags(key, instanceId);
tokenKeys.delete(key);
});
}
}

const useCSSVarRegister = <V, T extends Record<string, V>>(
config: ComputedRef<{
path: string[];
Expand Down Expand Up @@ -93,25 +53,20 @@ const useCSSVarRegister = <V, T extends Record<string, V>>(
scope: config.value.scope || '',
});

const tokenKey = token2key(mergedToken, '');

const styleId = uniqueHash(stylePath.value, cssVarsStr);

recordCleanToken(tokenKey);
return [mergedToken, cssVarsStr, tokenKey, styleId, config.value.key];
return [mergedToken, cssVarsStr, styleId, config.value.key];
},
([, , tokenKey]) => {
([, , styleId]) => {
if (isClientSide) {
// Remove token will remove all related style
cleanTokenStyle(tokenKey, styleContext.value?.cache?.instanceId);
removeCSS(styleId, { mark: ATTR_MARK });
}
},
([, cssVarsStr, tokenKey]) => {
([, cssVarsStr, styleId]) => {
if (!cssVarsStr) {
return;
}

const style = updateCSS(cssVarsStr, tokenKey, {
const style = updateCSS(cssVarsStr, styleId, {
mark: ATTR_MARK,
prepend: 'queue',
attachTo: styleContext.value.container,
Expand Down
10 changes: 7 additions & 3 deletions components/_util/_cssinjs/hooks/useGlobalCache.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,13 @@ export default function useGlobalCache<CacheType>(
});
};

watch(deps, () => {
buildCache();
});
watch(
deps,
() => {
buildCache();
},
{ immediate: true },
);

let cacheEntity = globalCache.value.get(deps.value);

Expand Down
3 changes: 2 additions & 1 deletion components/config-provider/hooks/useCssVarCls.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useToken } from '../../_theme/internal';
import type { Ref } from 'vue';
import { computed } from 'vue';

/**
* This hook is only for cssVar to add root className for components.
Expand All @@ -9,7 +10,7 @@ import type { Ref } from 'vue';
const useCSSVarCls = (prefixCls: Ref<string>) => {
const [, , , , cssVar] = useToken();

return cssVar.value ? `${prefixCls.value}-css-var` : '';
return computed(() => (cssVar.value ? `${prefixCls.value}-css-var` : ''));
};

export default useCSSVarCls;
6 changes: 2 additions & 4 deletions components/config-provider/hooks/useTheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@ import type { ThemeConfig } from '../context';
import { defaultConfig } from '../../_theme/internal';
import type { Ref } from 'vue';
import { computed } from 'vue';
import useThemeKey from './useThemeKey';
import devWarning from '../../vc-util/warning';

const themeKey = 'antdvtheme';
export default function useTheme(theme?: Ref<ThemeConfig>, parentTheme?: Ref<ThemeConfig>) {
const themeConfig = computed(() => theme?.value || {});
const parentThemeConfig = computed<ThemeConfig>(() =>
themeConfig.value.inherit === false || !parentTheme?.value ? defaultConfig : parentTheme.value,
);

const themeKey = useThemeKey();

if (process.env.NODE_ENV !== 'production') {
const cssVarEnabled = themeConfig.value.cssVar || parentThemeConfig.value.cssVar;
const validKey = !!(
Expand Down Expand Up @@ -43,6 +40,7 @@ export default function useTheme(theme?: Ref<ThemeConfig>, parentTheme?: Ref<The
});

const cssVarKey = `css-var-${themeKey.replace(/:/g, '')}`;

const mergedCssVar = (themeConfig.value.cssVar ?? parentThemeConfig.value.cssVar) && {
prefix: 'ant', // Default to ant
...(typeof parentThemeConfig.value.cssVar === 'object' ? parentThemeConfig.value.cssVar : {}),
Expand Down
12 changes: 2 additions & 10 deletions components/config-provider/hooks/useThemeKey.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
import { getCurrentInstance } from 'vue';
import _ from 'lodash';

let uid = 0;
const useThemeKey = () => {
const instance = getCurrentInstance();

if (!instance) {
return _.uniqueId() + '';
}

return instance.uid + '';
return 'themekey' + uid++;
};

export default useThemeKey;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@
"tinycolor2": "^1.6.0",
"ts-jest": "^28.0.5",
"ts-loader": "^9.1.0",
"tsx": "^3.12.10",
"tsx": "^4.0.0",
"typedoc": "^0.23.25",
"typescript": "~4.9.3",
"umi-request": "^1.3.5",
Expand Down
Loading