diff --git a/components/_theme/context.ts b/components/_theme/context.ts new file mode 100644 index 000000000..46141db26 --- /dev/null +++ b/components/_theme/context.ts @@ -0,0 +1,112 @@ +import type { ShallowRef, InjectionKey, ExtractPropTypes, ComputedRef } from 'vue'; +import { + defineComponent, + inject, + provide, + shallowRef, + unref, + triggerRef, + watch, + computed, +} from 'vue'; +import type { Theme } from '../_util/_cssinjs'; +import { createTheme } from '../_util/_cssinjs'; + +import { objectType, someType } from '../_util/type'; +import type { AliasToken, MapToken, OverrideToken, SeedToken } from './interface'; +import defaultDerivative from './themes/default'; +import defaultSeedToken from './themes/seed'; + +export const defaultTheme = createTheme(defaultDerivative); + +// ================================ Context ================================= +// To ensure snapshot stable. We disable hashed in test env. +const DesignTokenContextKey: InjectionKey>> = + Symbol('DesignTokenContextKey'); + +export const globalDesignTokenApi = shallowRef(); + +export const defaultConfig = { + token: defaultSeedToken, + override: { override: defaultSeedToken }, + hashed: true, +}; + +export type ComponentsToken = { + [key in keyof OverrideToken]?: OverrideToken[key] & { + theme?: Theme; + }; +}; +export const styleProviderProps = () => ({ + token: objectType(), + theme: objectType>(), + components: objectType(), + /** Just merge `token` & `override` at top to save perf */ + override: objectType<{ override: Partial } & ComponentsToken>(), + hashed: someType(), + cssVar: someType<{ + prefix?: string; + key?: string; + }>(), +}); + +export type StyleProviderProps = Partial>>; +export interface DesignTokenProviderProps { + token: Partial; + theme?: Theme; + components?: ComponentsToken; + /** Just merge `token` & `override` at top to save perf */ + override?: { override: Partial } & ComponentsToken; + hashed?: string | boolean; + cssVar?: { + prefix?: string; + key?: string; + }; +} + +export const useDesignTokenInject = () => { + return inject( + DesignTokenContextKey, + computed(() => globalDesignTokenApi.value || defaultConfig), + ); +}; + +export const useDesignTokenProvider = (props: ComputedRef) => { + const parentContext = useDesignTokenInject(); + const context = shallowRef>(defaultConfig); + watch( + computed(() => [props.value, parentContext.value]), + ([propsValue, parentContextValue]) => { + const mergedContext: Partial = { + ...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); + triggerRef(globalDesignTokenApi); + }, + { immediate: true, deep: true }, + ); + provide(DesignTokenContextKey, context); + return context; +}; + +export const DesignTokenProvider = defineComponent({ + props: { + value: objectType(), + }, + setup(props, { slots }) { + useDesignTokenProvider(computed(() => props.value)); + return () => { + return slots.default?.(); + }; + }, +}); + +export default { useDesignTokenInject, useDesignTokenProvider, DesignTokenProvider }; diff --git a/components/_theme/getDesignToken.ts b/components/_theme/getDesignToken.ts new file mode 100644 index 000000000..d8d93b7ac --- /dev/null +++ b/components/_theme/getDesignToken.ts @@ -0,0 +1,17 @@ +import { createTheme, getComputedToken } from '../_util/_cssinjs'; +import type { ThemeConfig } from '../config-provider/context'; +import type { AliasToken } from './interface'; +import defaultDerivative from './themes/default'; +import seedToken from './themes/seed'; +import formatToken from './util/alias'; + +const getDesignToken = (config?: ThemeConfig): AliasToken => { + const theme = config?.algorithm ? createTheme(config.algorithm) : createTheme(defaultDerivative); + const mergedToken = { + ...seedToken, + ...config?.token, + }; + return getComputedToken(mergedToken, { override: config?.token }, theme, formatToken); +}; + +export default getDesignToken; diff --git a/components/_theme/index.ts b/components/_theme/index.ts new file mode 100644 index 000000000..481dd08d8 --- /dev/null +++ b/components/_theme/index.ts @@ -0,0 +1,33 @@ +/* eslint-disable import/prefer-default-export */ +import getDesignToken from './getDesignToken'; +import type { GlobalToken, MappingAlgorithm } from './interface'; +import { defaultConfig, useToken as useInternalToken } from './internal'; +import compactAlgorithm from './themes/compact'; +import darkAlgorithm from './themes/dark'; +import defaultAlgorithm from './themes/default'; + +// ZombieJ: We export as object to user but array in internal. +// This is used to minimize the bundle size for antd package but safe to refactor as object also. +// Please do not export internal `useToken` directly to avoid something export unexpected. +/** Get current context Design Token. Will be different if you are using nest theme config. */ +function useToken() { + const [theme, token, hashId] = useInternalToken(); + + return { theme, token, hashId }; +} + +export type { GlobalToken, MappingAlgorithm }; + +export default { + /** @private Test Usage. Do not use in production. */ + defaultConfig, + + /** Default seedToken */ + defaultSeed: defaultConfig.token, + + useToken, + defaultAlgorithm, + darkAlgorithm, + compactAlgorithm, + getDesignToken, +}; diff --git a/components/_theme/interface/alias.ts b/components/_theme/interface/alias.ts new file mode 100644 index 000000000..c19d62648 --- /dev/null +++ b/components/_theme/interface/alias.ts @@ -0,0 +1,632 @@ +import type { CSSProperties } from 'vue'; +import type { MapToken } from './maps'; + +// ====================================================================== +// == Alias Token == +// ====================================================================== +// 🔥🔥🔥🔥🔥🔥🔥 DO NOT MODIFY THIS. PLEASE CONTACT DESIGNER. 🔥🔥🔥🔥🔥🔥🔥 + +export interface AliasToken extends MapToken { + // Background + /** + * @nameZH 内容区域背景色(悬停) + * @nameEN Background color of content area (hover) + * @desc 控制内容区域背景色在鼠标悬停时的样式。 + * @descEN Control the style of background color of content area when mouse hovers over it. + */ + colorFillContentHover: string; + /** + * @nameZH 替代背景色 + * @nameEN Alternative background color + * @desc 控制元素替代背景色。 + * @descEN Control the alternative background color of element. + */ + colorFillAlter: string; + /** + * @nameZH 内容区域背景色 + * @nameEN Background color of content area + * @desc 控制内容区域的背景色。 + * @descEN Control the background color of content area. + */ + colorFillContent: string; + /** + * @nameZH 容器禁用态下的背景色 + * @nameEN Disabled container background color + * @desc 控制容器在禁用状态下的背景色。 + * @descEN Control the background color of container in disabled state. + */ + colorBgContainerDisabled: string; + /** + * @nameZH 文本悬停态背景色 + * @nameEN Text hover background color + * @desc 控制文本在悬停状态下的背景色。 + * @descEN Control the background color of text in hover state. + */ + colorBgTextHover: string; + /** + * @nameZH 文本激活态背景色 + * @nameEN Text active background color + * @desc 控制文本在激活状态下的背景色。 + * @descEN Control the background color of text in active state. + */ + colorBgTextActive: string; + + // Border + /** + * @nameZH 背景边框颜色 + * @nameEN Background border color + * @desc 控制元素背景边框的颜色。 + * @descEN Control the color of background border of element. + */ + colorBorderBg: string; + /** + * @nameZH 分割线颜色 + * @nameEN Separator Color + * @desc 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 + * @descEN Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. + */ + colorSplit: string; + + // Text + /** + * @nameZH 占位文本颜色 + * @nameEN Placeholder Text Color + * @desc 控制占位文本的颜色。 + * @descEN Control the color of placeholder text. + */ + colorTextPlaceholder: string; + /** + * @nameZH 禁用字体颜色 + * @nameEN Disabled Text Color + * @desc 控制禁用状态下的字体颜色。 + * @descEN Control the color of text in disabled state. + */ + colorTextDisabled: string; + /** + * @nameZH 标题字体颜色 + * @nameEN Heading Text Color + * @desc 控制标题字体颜色。 + * @descEN Control the font color of heading. + */ + colorTextHeading: string; + /** + * @nameZH 文本标签字体颜色 + * @nameEN Text label font color + * @desc 控制文本标签字体颜色。 + * @descEN Control the font color of text label. + */ + colorTextLabel: string; + /** + * @nameZH 文本描述字体颜色 + * @nameEN Text description font color + * @desc 控制文本描述字体颜色。 + * @descEN Control the font color of text description. + */ + colorTextDescription: string; + /** + * @nameZH 固定文本高亮颜色 + * @nameEN Fixed text highlight color + * @desc 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 + * @descEN Control the highlight color of text with background color, such as the text in Primary Button components. + */ + colorTextLightSolid: string; + + /** + /** + * @nameZH 弱操作图标颜色 + * @nameEN Weak action icon color + * @desc 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 + * @descEN Weak action. Such as `allowClear` or Alert close button + */ + colorIcon: string; + + /** */ + /** + * @nameZH 弱操作图标悬浮态颜色 + * @nameEN Weak action icon hover color + * @desc 控制弱操作图标在悬浮状态下的颜色,例如 allowClear 或 Alert 关闭按钮。 + * @descEN Weak action hover color. Such as `allowClear` or Alert close button + */ + colorIconHover: string; + + /** + * @nameZH 高亮颜色 + * @nameEN Highlight color + * @desc 控制页面元素高亮时的颜色。 + * @descEN Control the color of page element when highlighted. + */ + colorHighlight: string; + + /** + * @nameZH 输入组件的 Outline 颜色 + * @nameEN Input component outline color + * @desc 控制输入组件的外轮廓线颜色。 + * @descEN Control the outline color of input component. + */ + controlOutline: string; + + /** + * @nameZH 警告状态下的 Outline 颜色 + * @nameEN Warning outline color + * @desc 控制输入组件警告状态下的外轮廓线颜色。 + * @descEN Control the outline color of input component in warning state. + */ + colorWarningOutline: string; + + /** + * @nameZH 错误状态下的 Outline 颜色 + * @nameEN Error outline color + * @desc 控制输入组件错误状态下的外轮廓线颜色。 + * @descEN Control the outline color of input component in error state. + */ + colorErrorOutline: string; + + // Font + /** + * @nameZH 选择器、级联选择器等中的操作图标字体大小 + * @nameEN Operation icon font size in Select, Cascader, etc. + * @desc 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 + * @descEN Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. + */ + fontSizeIcon: number; + + /** + * @nameZH 标题类组件(如 h1、h2、h3)或选中项的字体粗细 + * @nameEN Font weight for heading components (such as h1, h2, h3) or selected item + * @desc 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 + * @descEN Control the font weight of heading components (such as h1, h2, h3) or selected item. + */ + fontWeightStrong: number; + + // Control + + /** + * @nameZH 输入组件的外轮廓线宽度 + * @nameEN Input component outline width + * @desc 控制输入组件的外轮廓线宽度。 + * @descEN Control the outline width of input component. + */ + controlOutlineWidth: number; + + /** + * @nameZH 控制组件项在鼠标悬浮时的背景颜色 + * @nameEN Background color of control component item when hovering + * @desc 控制组件项在鼠标悬浮时的背景颜色。 + * @descEN Control the background color of control component item when hovering. + */ + controlItemBgHover: string; // Note. It also is a color + + /** + * @nameZH 控制组件项在激活状态下的背景颜色 + * @nameEN Background color of control component item when active + * @desc 控制组件项在激活状态下的背景颜色。 + * @descEN Control the background color of control component item when active. + */ + controlItemBgActive: string; // Note. It also is a color + + /** + * @nameZH 控制组件项在鼠标悬浮且激活状态下的背景颜色 + * @nameEN Background color of control component item when hovering and active + * @desc 控制组件项在鼠标悬浮且激活状态下的背景颜色。 + * @descEN Control the background color of control component item when hovering and active. + */ + controlItemBgActiveHover: string; // Note. It also is a color + + /** + * @nameZH 控制组件的交互大小 + * @nameEN Interactive size of control component + * @desc 控制组件的交互大小。 + * @descEN Control the interactive size of control component. + */ + controlInteractiveSize: number; + + /** + * @nameZH 控制组件项在禁用状态下的激活背景颜色 + * @nameEN Background color of control component item when active and disabled + * @desc 控制组件项在禁用状态下的激活背景颜色。 + * @descEN Control the background color of control component item when active and disabled. + */ + controlItemBgActiveDisabled: string; // Note. It also is a color + + // Line + /** + * @nameZH 线条宽度(聚焦态) + * @nameEN Line width(focus state) + * @desc 控制线条的宽度,当组件处于聚焦态时。 + * @descEN Control the width of the line when the component is in focus state. + */ + lineWidthFocus: number; + + // Padding + /** + * @nameZH 极小内间距 + * @nameEN Extra extra small padding + * @desc 控制元素的极小内间距。 + * @descEN Control the extra extra small padding of the element. + */ + paddingXXS: number; + /** + * @nameZH 特小内间距 + * @nameEN Extra small padding + * @desc 控制元素的特小内间距。 + * @descEN Control the extra small padding of the element. + */ + paddingXS: number; + /** + * @nameZH 小内间距 + * @nameEN Small padding + * @desc 控制元素的小内间距。 + * @descEN Control the small padding of the element. + */ + paddingSM: number; + /** + * @nameZH 内间距 + * @nameEN Padding + * @desc 控制元素的内间距。 + * @descEN Control the padding of the element. + */ + padding: number; + /** + * @nameZH 中等内间距 + * @nameEN Medium padding + * @desc 控制元素的中等内间距。 + * @descEN Control the medium padding of the element. + */ + paddingMD: number; + /** + * @nameZH 大内间距 + * @nameEN Large padding + * @desc 控制元素的大内间距。 + * @descEN Control the large padding of the element. + */ + paddingLG: number; + /** + * @nameZH 特大内间距 + * @nameEN Extra large padding + * @desc 控制元素的特大内间距。 + * @descEN Control the extra large padding of the element. + */ + paddingXL: number; + + // Padding Content + /** + * @nameZH 内容水平内间距(LG) + * @nameEN Content horizontal padding (LG) + * @desc 控制内容元素水平内间距,适用于大屏幕设备。 + * @descEN Control the horizontal padding of content element, suitable for large screen devices. + */ + paddingContentHorizontalLG: number; + /** + * @nameZH 内容水平内间距 + * @nameEN Content horizontal padding + * @desc 控制内容元素水平内间距。 + * @descEN Control the horizontal padding of content element. + */ + paddingContentHorizontal: number; + /** + * @nameZH 内容水平内间距(SM) + * @nameEN Content horizontal padding (SM) + * @desc 控制内容元素水平内间距,适用于小屏幕设备。 + * @descEN Control the horizontal padding of content element, suitable for small screen devices. + */ + paddingContentHorizontalSM: number; + /** + * @nameZH 内容垂直内间距(LG) + * @nameEN Content vertical padding (LG) + * @desc 控制内容元素垂直内间距,适用于大屏幕设备。 + * @descEN Control the vertical padding of content element, suitable for large screen devices. + */ + paddingContentVerticalLG: number; + /** + * @nameZH 内容垂直内间距 + * @nameEN Content vertical padding + * @desc 控制内容元素垂直内间距。 + * @descEN Control the vertical padding of content element. + */ + paddingContentVertical: number; + /** + * @nameZH 内容垂直内间距(SM) + * @nameEN Content vertical padding (SM) + * @desc 控制内容元素垂直内间距,适用于小屏幕设备。 + * @descEN Control the vertical padding of content element, suitable for small screen devices. + */ + paddingContentVerticalSM: number; + + // Margin + /** + * @nameZH 外边距 XXS + * @nameEN Margin XXS + * @desc 控制元素外边距,最小尺寸。 + * @descEN Control the margin of an element, with the smallest size. + */ + marginXXS: number; + /** + * @nameZH 外边距 XS + * @nameEN Margin XS + * @desc 控制元素外边距,小尺寸。 + * @descEN Control the margin of an element, with a small size. + */ + marginXS: number; + /** + * @nameZH 外边距 SM + * @nameEN Margin SM + * @desc 控制元素外边距,中小尺寸。 + * @descEN Control the margin of an element, with a medium-small size. + */ + marginSM: number; + /** + * @nameZH 外边距 + * @nameEN Margin + * @desc 控制元素外边距,中等尺寸。 + * @descEN Control the margin of an element, with a medium size. + */ + margin: number; + /** + * @nameZH 外边距 MD + * @nameEN Margin MD + * @desc 控制元素外边距,中大尺寸。 + * @descEN Control the margin of an element, with a medium-large size. + */ + marginMD: number; + /** + * @nameZH 外边距 LG + * @nameEN Margin LG + * @desc 控制元素外边距,大尺寸。 + * @descEN Control the margin of an element, with a large size. + */ + marginLG: number; + /** + * @nameZH 外边距 XL + * @nameEN Margin XL + * @desc 控制元素外边距,超大尺寸。 + * @descEN Control the margin of an element, with an extra-large size. + */ + marginXL: number; + /** + * @nameZH 外边距 XXL + * @nameEN Margin XXL + * @desc 控制元素外边距,最大尺寸。 + * @descEN Control the margin of an element, with the largest size. + */ + marginXXL: number; + + // =============== Legacy: should be remove =============== + /** + * @nameZH 加载状态透明度 + * @nameEN Loading opacity + * @desc 控制加载状态的透明度。 + * @descEN Control the opacity of the loading state. + */ + opacityLoading: number; + + /** + * @nameZH 一级阴影 + * @nameEN Box shadow + * @desc 控制元素阴影样式。 + * @descEN Control the box shadow style of an element. + */ + boxShadow: string; + /** + * @nameZH 二级阴影 + * @nameEN Secondary box shadow + * @desc 控制元素二级阴影样式。 + * @descEN Control the secondary box shadow style of an element. + */ + boxShadowSecondary: string; + /** + * @nameZH 三级阴影 + * @nameEN Tertiary box shadow + * @desc 控制元素三级盒子阴影样式。 + * @descEN Control the tertiary box shadow style of an element. + */ + boxShadowTertiary: string; + + /** + * @nameZH 链接文本装饰 + * @nameEN Link text decoration + * @desc 控制链接文本的装饰样式。 + * @descEN Control the text decoration style of a link. + */ + linkDecoration: CSSProperties['textDecoration']; + /** + * @nameZH 链接鼠标悬浮时文本装饰 + * @nameEN Link text decoration on mouse hover + * @desc 控制链接鼠标悬浮时文本的装饰样式。 + * @descEN Control the text decoration style of a link on mouse hover. + */ + linkHoverDecoration: CSSProperties['textDecoration']; + /** + * @nameZH 链接聚焦时文本装饰 + * @nameEN Link text decoration on focus + * @desc 控制链接聚焦时文本的装饰样式。 + * @descEN Control the text decoration style of a link on focus. + */ + linkFocusDecoration: CSSProperties['textDecoration']; + + /** + * @nameZH 控制水平内间距 + * @nameEN Control horizontal padding + * @desc 控制元素水平内间距。 + * @descEN Control the horizontal padding of an element. + */ + controlPaddingHorizontal: number; + /** + * @nameZH 控制中小尺寸水平内间距 + * @nameEN Control horizontal padding with a small-medium size + * @desc 控制元素中小尺寸水平内间距。 + * @descEN Control the horizontal padding of an element with a small-medium size. + */ + controlPaddingHorizontalSM: number; + + // Media queries breakpoints + /** + * @nameZH 屏幕宽度(像素) - 超小屏幕 + * @nameEN Screen width (pixels) - Extra small screens + * @desc 控制超小屏幕的屏幕宽度。 + * @descEN Control the screen width of extra small screens. + */ + screenXS: number; + /** + * @nameZH 屏幕宽度(像素) - 超小屏幕最小值 + * @nameEN Screen width (pixels) - Extra small screens minimum value + * @desc 控制超小屏幕的最小宽度。 + * @descEN Control the minimum width of extra small screens. + */ + screenXSMin: number; + /** + * @nameZH 屏幕宽度(像素) - 超小屏幕最大值 + * @nameEN Screen width (pixels) - Extra small screens maximum value + * @desc 控制超小屏幕的最大宽度。 + * @descEN Control the maximum width of extra small screens. + */ + screenXSMax: number; + /** + * @nameZH 屏幕宽度(像素) - 小屏幕 + * @nameEN Screen width (pixels) - Small screens + * @desc 控制小屏幕的屏幕宽度。 + * @descEN Control the screen width of small screens. + */ + screenSM: number; + /** + * @nameZH 屏幕宽度(像素) - 小屏幕最小值 + * @nameEN Screen width (pixels) - Small screens minimum value + * @desc 控制小屏幕的最小宽度。 + * @descEN Control the minimum width of small screens. + */ + screenSMMin: number; + /** + * @nameZH 屏幕宽度(像素) - 小屏幕最大值 + * @nameEN Screen width (pixels) - Small screens maximum value + * @desc 控制小屏幕的最大宽度。 + * @descEN Control the maximum width of small screens. + */ + screenSMMax: number; + /** + * @nameZH 屏幕宽度(像素) - 中等屏幕 + * @nameEN Screen width (pixels) - Medium screens + * @desc 控制中等屏幕的屏幕宽度。 + * @descEN Control the screen width of medium screens. + */ + screenMD: number; + /** + * @nameZH 屏幕宽度(像素) - 中等屏幕最小值 + * @nameEN Screen width (pixels) - Medium screens minimum value + * @desc 控制中等屏幕的最小宽度。 + * @descEN Control the minimum width of medium screens. + */ + screenMDMin: number; + /** + * @nameZH 屏幕宽度(像素) - 中等屏幕最大值 + * @nameEN Screen width (pixels) - Medium screens maximum value + * @desc 控制中等屏幕的最大宽度。 + * @descEN Control the maximum width of medium screens. + */ + screenMDMax: number; + /** + * @nameZH 屏幕宽度(像素) - 大屏幕 + * @nameEN Screen width (pixels) - Large screens + * @desc 控制大屏幕的屏幕宽度。 + * @descEN Control the screen width of large screens. + */ + screenLG: number; + /** + * @nameZH 屏幕宽度(像素) - 大屏幕最小值 + * @nameEN Screen width (pixels) - Large screens minimum value + * @desc 控制大屏幕的最小宽度。 + * @descEN Control the minimum width of large screens. + */ + screenLGMin: number; + /** + * @nameZH 屏幕宽度(像素) - 大屏幕最大值 + * @nameEN Screen width (pixels) - Large screens maximum value + * @desc 控制大屏幕的最大宽度。 + * @descEN Control the maximum width of large screens. + */ + screenLGMax: number; + /** + * @nameZH 屏幕宽度(像素) - 超大屏幕 + * @nameEN Screen width (pixels) - Extra large screens + * @desc 控制超大屏幕的屏幕宽度。 + * @descEN Control the screen width of extra large screens. + */ + screenXL: number; + /** + * @nameZH 屏幕宽度(像素) - 超大屏幕最小值 + * @nameEN Screen width (pixels) - Extra large screens minimum value + * @desc 控制超大屏幕的最小宽度。 + * @descEN Control the minimum width of extra large screens. + */ + screenXLMin: number; + /** + * @nameZH 屏幕宽度(像素) - 超大屏幕最大值 + * @nameEN Screen width (pixels) - Extra large screens maximum value + * @desc 控制超大屏幕的最大宽度。 + * @descEN Control the maximum width of extra large screens. + */ + screenXLMax: number; + /** + * @nameZH 屏幕宽度(像素) - 超超大屏幕 + * @nameEN Screen width (pixels) - Extra extra large screens. + * @desc 控制超超大屏幕的屏幕宽度。 + * @descEN Control the screen width of extra extra large screens. + */ + screenXXL: number; + /** + * @nameZH 屏幕宽度(像素) - 超超大屏幕最小值 + * @nameEN Screen width (pixels) - Extra extra large screens minimum value + * @desc 控制超超大屏幕的最小宽度。 + * @descEN Control the minimum width of extra extra large screens. + */ + screenXXLMin: number; + /** + * @nameZH 屏幕宽度(像素) - 超超大屏幕最大值 + * @nameEN Screen width (pixels) - Extra extra large screens maximum value + * @desc 控制超超大屏幕的最大宽度。 + * @descEN Control the maximum width of extra extra large screens. + */ + screenXXLMax: number; + /** + * @nameZH 屏幕宽度(像素) - 超超超大屏幕 + * @nameEN Screen width (pixels) - Extra extra extra large screens. + * @desc 控制超超超大屏幕的屏幕宽度。 + * @descEN Control the screen width of extra extra extra large screens. + */ + screenXXXL: number; + /** + * @nameZH 屏幕宽度(像素) - 超超超大屏幕最小值 + * @nameEN Screen width (pixels) - Extra extra extra large screens minimum value + * @desc 控制超超超大屏幕的最小宽度。 + * @descEN Control the minimum width of extra extra extra large screens. + */ + screenXXXLMin: number; + + /** + * @deprecated + * Used for DefaultButton, Switch which has default outline + * @desc 默认样式的 Outline 颜色 + * @descEN Default style outline color. + */ + controlTmpOutline: string; + + // FIXME: component box-shadow, should be removed + /** @internal */ + boxShadowPopoverArrow: string; + /** @internal */ + boxShadowCard: string; + /** @internal */ + boxShadowDrawerRight: string; + /** @internal */ + boxShadowDrawerLeft: string; + /** @internal */ + boxShadowDrawerUp: string; + /** @internal */ + boxShadowDrawerDown: string; + /** @internal */ + boxShadowTabsOverflowLeft: string; + /** @internal */ + boxShadowTabsOverflowRight: string; + /** @internal */ + boxShadowTabsOverflowTop: string; + /** @internal */ + boxShadowTabsOverflowBottom: string; +} diff --git a/components/_theme/interface/components.ts b/components/_theme/interface/components.ts new file mode 100644 index 000000000..00f6a5950 --- /dev/null +++ b/components/_theme/interface/components.ts @@ -0,0 +1,137 @@ +import type { ComponentToken as WaveToken } from '../../_util/wave/style'; +import type { ComponentToken as AffixComponentToken } from '../../affix/style'; +import type { ComponentToken as AlertComponentToken } from '../../alert/style'; +import type { ComponentToken as AnchorComponentToken } from '../../anchor/style'; +import type { ComponentToken as AppComponentToken } from '../../app/style'; +import type { ComponentToken as AvatarComponentToken } from '../../avatar/style'; +import type { ComponentToken as BadgeComponentToken } from '../../badge/style'; +import type { ComponentToken as BreadcrumbComponentToken } from '../../breadcrumb/style'; +import type { ComponentToken as ButtonComponentToken } from '../../button/style'; +import type { ComponentToken as CalendarComponentToken } from '../../calendar/style'; +import type { ComponentToken as CardComponentToken } from '../../card/style'; +import type { ComponentToken as CarouselComponentToken } from '../../carousel/style'; +import type { ComponentToken as CascaderComponentToken } from '../../cascader/style'; +import type { ComponentToken as CheckboxComponentToken } from '../../checkbox/style'; +import type { ComponentToken as CollapseComponentToken } from '../../collapse/style'; +// import type { ComponentToken as ColorPickerComponentToken } from '../../color-picker/style'; +import type { ComponentToken as CommentComponentToken } from '../../comment/style'; +import type { ComponentToken as DatePickerComponentToken } from '../../date-picker/style'; +import type { ComponentToken as DescriptionsComponentToken } from '../../descriptions/style'; +import type { ComponentToken as DividerComponentToken } from '../../divider/style'; +import type { ComponentToken as DrawerComponentToken } from '../../drawer/style'; +import type { ComponentToken as DropdownComponentToken } from '../../dropdown/style'; +import type { ComponentToken as EmptyComponentToken } from '../../empty/style'; +import type { ComponentToken as FlexComponentToken } from '../../flex/style'; +import type { ComponentToken as FloatButtonComponentToken } from '../../float-button/style'; +import type { ComponentToken as FormComponentToken } from '../../form/style'; +import type { ComponentToken as GridComponentToken } from '../../grid/style'; +import type { ComponentToken as ImageComponentToken } from '../../image/style'; +import type { ComponentToken as InputNumberComponentToken } from '../../input-number/style'; +import type { ComponentToken as InputComponentToken } from '../../input/style'; +import type { ComponentToken as LayoutComponentToken } from '../../layout/style'; +import type { ComponentToken as ListComponentToken } from '../../list/style'; +import type { ComponentToken as MentionsComponentToken } from '../../mentions/style'; +import type { ComponentToken as MenuComponentToken } from '../../menu/style'; +import type { ComponentToken as MessageComponentToken } from '../../message/style'; +import type { ComponentToken as ModalComponentToken } from '../../modal/style'; +import type { ComponentToken as NotificationComponentToken } from '../../notification/style'; +import type { ComponentToken as PageHeaderComponentToken } from '../../page-header/style'; +import type { ComponentToken as PaginationComponentToken } from '../../pagination/style'; +import type { ComponentToken as PopconfirmComponentToken } from '../../popconfirm/style'; +import type { ComponentToken as PopoverComponentToken } from '../../popover/style'; +import type { ComponentToken as ProgressComponentToken } from '../../progress/style'; +import type { ComponentToken as QRCodeComponentToken } from '../../qrcode/style'; +import type { ComponentToken as RadioComponentToken } from '../../radio/style'; +import type { ComponentToken as RateComponentToken } from '../../rate/style'; +import type { ComponentToken as ResultComponentToken } from '../../result/style'; +import type { ComponentToken as SegmentedComponentToken } from '../../segmented/style'; +import type { ComponentToken as SelectComponentToken } from '../../select/style'; +import type { ComponentToken as SkeletonComponentToken } from '../../skeleton/style'; +import type { ComponentToken as SliderComponentToken } from '../../slider/style'; +import type { ComponentToken as SpaceComponentToken } from '../../space/style'; +import type { ComponentToken as SpinComponentToken } from '../../spin/style'; +import type { ComponentToken as StatisticComponentToken } from '../../statistic/style'; +import type { ComponentToken as StepsComponentToken } from '../../steps/style'; +import type { ComponentToken as SwitchComponentToken } from '../../switch/style'; +import type { ComponentToken as TableComponentToken } from '../../table/style'; +import type { ComponentToken as TabsComponentToken } from '../../tabs/style'; +import type { ComponentToken as TagComponentToken } from '../../tag/style'; +import type { ComponentToken as TimelineComponentToken } from '../../timeline/style'; +import type { ComponentToken as TooltipComponentToken } from '../../tooltip/style'; +import type { ComponentToken as TourComponentToken } from '../../tour/style'; +import type { ComponentToken as TransferComponentToken } from '../../transfer/style'; +import type { ComponentToken as TreeSelectComponentToken } from '../../tree-select/style'; +import type { ComponentToken as TreeComponentToken } from '../../tree/style'; +import type { ComponentToken as TypographyComponentToken } from '../../typography/style'; +import type { ComponentToken as UploadComponentToken } from '../../upload/style'; + +export interface ComponentTokenMap { + Affix?: AffixComponentToken; + Alert?: AlertComponentToken; + Anchor?: AnchorComponentToken; + Avatar?: AvatarComponentToken; + Badge?: BadgeComponentToken; + Button?: ButtonComponentToken; + Breadcrumb?: BreadcrumbComponentToken; + Card?: CardComponentToken; + Carousel?: CarouselComponentToken; + Cascader?: CascaderComponentToken; + Checkbox?: CheckboxComponentToken; + // ColorPicker?: ColorPickerComponentToken; + Collapse?: CollapseComponentToken; + Comment?: CommentComponentToken; + DatePicker?: DatePickerComponentToken; + Descriptions?: DescriptionsComponentToken; + Divider?: DividerComponentToken; + Drawer?: DrawerComponentToken; + Dropdown?: DropdownComponentToken; + Empty?: EmptyComponentToken; + Flex?: FlexComponentToken; + FloatButton?: FloatButtonComponentToken; + Form?: FormComponentToken; + Grid?: GridComponentToken; + Image?: ImageComponentToken; + Input?: InputComponentToken; + InputNumber?: InputNumberComponentToken; + Layout?: LayoutComponentToken; + List?: ListComponentToken; + Mentions?: MentionsComponentToken; + Notification?: NotificationComponentToken; + PageHeader?: PageHeaderComponentToken; + Pagination?: PaginationComponentToken; + Popover?: PopoverComponentToken; + Popconfirm?: PopconfirmComponentToken; + Rate?: RateComponentToken; + Radio?: RadioComponentToken; + Result?: ResultComponentToken; + Segmented?: SegmentedComponentToken; + Select?: SelectComponentToken; + Skeleton?: SkeletonComponentToken; + Slider?: SliderComponentToken; + Spin?: SpinComponentToken; + Statistic?: StatisticComponentToken; + Switch?: SwitchComponentToken; + Tag?: TagComponentToken; + Tree?: TreeComponentToken; + TreeSelect?: TreeSelectComponentToken; + Typography?: TypographyComponentToken; + Timeline?: TimelineComponentToken; + Transfer?: TransferComponentToken; + Tabs?: TabsComponentToken; + Calendar?: CalendarComponentToken; + Steps?: StepsComponentToken; + Menu?: MenuComponentToken; + Modal?: ModalComponentToken; + Message?: MessageComponentToken; + Upload?: UploadComponentToken; + Tooltip?: TooltipComponentToken; + Table?: TableComponentToken; + Space?: SpaceComponentToken; + Progress?: ProgressComponentToken; + Tour?: TourComponentToken; + QRCode?: QRCodeComponentToken; + App?: AppComponentToken; + + /** @private Internal TS definition. Do not use. */ + Wave?: WaveToken; +} diff --git a/components/_theme/interface/index.ts b/components/_theme/interface/index.ts new file mode 100644 index 000000000..8d22a3183 --- /dev/null +++ b/components/_theme/interface/index.ts @@ -0,0 +1,44 @@ +import type { CSSInterpolation, DerivativeFunc } from '../../_util/_cssinjs'; +import type { AliasToken } from './alias'; +import type { ComponentTokenMap } from './components'; +import type { MapToken } from './maps'; +import type { SeedToken } from './seeds'; +import type { VueNode } from '../..//_util/type'; +import type { Ref } from 'vue'; + +export type MappingAlgorithm = DerivativeFunc; + +export type OverrideToken = { + [key in keyof ComponentTokenMap]: Partial & Partial; +}; + +/** Final token which contains the components level override */ +export type GlobalToken = AliasToken & ComponentTokenMap; + +export type { AliasToken } from './alias'; +export type { ComponentTokenMap } from './components'; +export type { + ColorMapToken, + ColorNeutralMapToken, + CommonMapToken, + FontMapToken, + HeightMapToken, + MapToken, + SizeMapToken, + StyleMapToken, +} from './maps'; +export { PresetColors } from './presetColors'; +export type { + LegacyColorPalettes, + ColorPalettes, + PresetColorKey, + PresetColorType, +} from './presetColors'; +export type { SeedToken } from './seeds'; + +export type UseComponentStyleResult = [(node: VueNode) => VueNode, Ref]; + +export type GenerateStyle< + ComponentToken extends object = AliasToken, + ReturnType = CSSInterpolation, +> = (token: ComponentToken) => ReturnType; diff --git a/components/_theme/interface/maps/colors.ts b/components/_theme/interface/maps/colors.ts new file mode 100644 index 000000000..659209d8d --- /dev/null +++ b/components/_theme/interface/maps/colors.ts @@ -0,0 +1,598 @@ +export interface ColorNeutralMapToken { + /** + * @internal + */ + colorTextBase: string; + + /** + * @internal + */ + colorBgBase: string; + + // ---------- Text ---------- // + + /** + * @nameZH 一级文本色 + * @nameEN Text Color + * @desc 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 + * @descEN Default text color which comply with W3C standards, and this color is also the darkest neutral color. + */ + colorText: string; + + /** + * @nameZH 二级文本色 + * @nameEN Secondary Text Color + * @desc 作为第二梯度的文本色,一般用在不那么需要强化文本颜色的场景,例如 Label 文本、Menu 的文本选中态等场景。 + * @descEN The second level of text color is generally used in scenarios where text color is not emphasized, such as label text, menu text selection state, etc. + */ + colorTextSecondary: string; + + /** + * @nameZH 三级文本色 + * @desc 第三级文本色一般用于描述性文本,例如表单的中的补充说明文本、列表的描述性文本等场景。 + * @descEN The third level of text color is generally used for descriptive text, such as form supplementary explanation text, list descriptive text, etc. + */ + colorTextTertiary: string; + + /** + * @nameZH 四级文本色 + * @desc 第四级文本色是最浅的文本色,例如表单的输入提示文本、禁用色文本等。 + * @descEN The fourth level of text color is the lightest text color, such as form input prompt text, disabled color text, etc. + */ + colorTextQuaternary: string; + + // ---------- Border ---------- // + + /** + * @nameZH 一级边框色 + * @nameEN Default Border Color + * @desc 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 + * @descEN Default border color, used to separate different elements, such as: form separator, card separator, etc. + */ + colorBorder: string; + + /** + * @nameZH 二级边框色 + * @nameEN Secondary Border Color + * @desc 比默认使用的边框色要浅一级,此颜色和 colorSplit 的颜色一致。使用的是实色。 + * @descEN Slightly lighter than the default border color, this color is the same as `colorSplit`. Solid color is used. + */ + colorBorderSecondary: string; + + // ---------- Fill ---------- // + + /** + * @nameZH 一级填充色 + * @desc 最深的填充色,用于拉开与二、三级填充色的区分度,目前只用在 Slider 的 hover 效果。 + * @descEN The darkest fill color is used to distinguish between the second and third level of fill color, and is currently only used in the hover effect of Slider. + */ + colorFill: string; + + /** + * @nameZH 二级填充色 + * @desc 二级填充色可以较为明显地勾勒出元素形体,如 Rate、Skeleton 等。也可以作为三级填充色的 Hover 状态,如 Table 等。 + * @descEN The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. + */ + colorFillSecondary: string; + + /** + * @nameZH 三级填充色 + * @desc 三级填充色用于勾勒出元素形体的场景,如 Slider、Segmented 等。如无强调需求的情况下,建议使用三级填色作为默认填色。 + * @descEN The third level of fill color is used to outline the shape of the element, such as Slider, Segmented, etc. If there is no emphasis requirement, it is recommended to use the third level of fill color as the default fill color. + */ + colorFillTertiary: string; + + /** + * @nameZH 四级填充色 + * @desc 最弱一级的填充色,适用于不易引起注意的色块,例如斑马纹、区分边界的色块等。 + * @descEN The weakest level of fill color is suitable for color blocks that are not easy to attract attention, such as zebra stripes, color blocks that distinguish boundaries, etc. + */ + colorFillQuaternary: string; + + // ---------- Surface ---------- // + + /** + * @nameZH 布局背景色 + * @nameEN Layout Background Color + * @desc 该色用于页面整体布局的背景色,只有需要在页面中处于 B1 的视觉层级时才会使用该 token,其他用法都是错误的 + * @descEN This color is used for the background color of the overall layout of the page. This token will only be used when it is necessary to be at the B1 visual level in the page. Other usages are wrong. + */ + colorBgLayout: string; + + /** + * @nameZH 组件容器背景色 + * @desc 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 + * @descEN Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. + */ + colorBgContainer: string; + + /** + * @nameZH 浮层容器背景色 + * @desc 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 + * @descEN Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. + */ + colorBgElevated: string; + + /** + * @nameZH 引起注意的背景色 + * @desc 该色用于引起用户强烈关注注意的背景色,目前只用在 Tooltip 的背景色上。 + * @descEN This color is used to draw the user's strong attention to the background color, and is currently only used in the background color of Tooltip. + */ + colorBgSpotlight: string; + /** + * @nameZH 毛玻璃容器背景色 + * @nameEN Frosted glass container background color + * @desc 控制毛玻璃容器的背景色,通常为透明色。 + * @descEN Control the background color of frosted glass container, usually transparent. + */ + colorBgBlur: string; +} + +/** + * 品牌色梯度变量 + */ +interface ColorPrimaryMapToken { + /** + * @nameZH 品牌主色 + * @nameEN Primary color of the brand + * @desc 品牌色是体现产品特性和传播理念最直观的视觉元素之一,用于产品的主色调、主按钮、主图标、主文本等 + * @descEN The brand color is one of the most intuitive visual elements that reflects product characteristics and communication concepts, and is used for the main color tone, main buttons, main icons, main text, etc. of the product. + */ + colorPrimary: string; // 6 + + /** + * @nameZH 主色浅色背景色 + * @nameEN Light background color of primary color + * @desc 主色浅色背景颜色,一般用于视觉层级较弱的选中状态。 + * @descEN Light background color of primary color, usually used for weak visual level selection state. + */ + colorPrimaryBg: string; // 1 + + /** + * @nameZH 主色浅色背景悬浮态 + * @nameEN Hover state of light background color of primary color + * @desc 与主色浅色背景颜色相对应的悬浮态颜色。 + * @descEN The hover state color corresponding to the light background color of the primary color. + */ + colorPrimaryBgHover: string; // 2 + + /** + * @nameZH 主色描边色 + * @nameEN Border color of primary color + * @desc 主色梯度下的描边用色,用在 Slider 等组件的描边上。 + * @descEN The stroke color under the main color gradient, used on the stroke of components such as Slider. + */ + colorPrimaryBorder: string; // 3 + + /** + * @nameZH 主色描边色悬浮态 + * @nameEN Hover state of border color of primary color + * @desc 主色梯度下的描边用色的悬浮态,Slider 、Button 等组件的描边 Hover 时会使用。 + * @descEN The hover state of the stroke color under the main color gradient, which will be used when the stroke Hover of components such as Slider and Button. + */ + colorPrimaryBorderHover: string; // 4 + + /** + * @nameZH 主色悬浮态 + * @nameEN Hover state of primary color + * @desc 主色梯度下的悬浮态。 + * @descEN Hover state under the main color gradient. + */ + colorPrimaryHover: string; // 5 + + /** + * @nameZH 主色激活态 + * @nameEN Active state of primary color + * @desc 主色梯度下的深色激活态。 + * @descEN Dark active state under the main color gradient. + */ + colorPrimaryActive: string; // 7 + + /** + * @nameZH 主色文本悬浮态 + * @nameEN Hover state of text color of primary color + * @desc 主色梯度下的文本悬浮态。 + * @descEN Hover state of text color under the main color gradient. + */ + colorPrimaryTextHover: string; // 8 + + /** + * @nameZH 主色文本 + * @nameEN Text color of primary color + * @desc 主色梯度下的文本颜色。 + * @descEN Text color under the main color gradient. + */ + colorPrimaryText: string; // 9 + + /** + * @nameZH 主色文本激活态 + * @nameEN Active state of text color of primary color + * @desc 主色梯度下的文本激活态。 + * @descEN Active state of text color under the main color gradient. + */ + colorPrimaryTextActive: string; // 10 +} + +interface ColorSuccessMapToken { + /** + * @nameZH 成功色的浅色背景颜色 + * @nameEN Light Background Color of Success Color + * @desc 成功色的浅色背景颜色,用于 Tag 和 Alert 的成功态背景色 + * @descEN Light background color of success color, used for Tag and Alert success state background color + */ + colorSuccessBg: string; // 1 + + /** + * @nameZH 成功色的浅色背景色悬浮态 + * @nameEN Hover State Color of Light Success Background + * @desc 成功色浅色背景颜色,一般用于视觉层级较弱的选中状态,不过 antd 目前没有使用到该 token + * @descEN Light background color of success color, but antd does not use this token currently + */ + colorSuccessBgHover: string; // 2 + + /** + * @nameZH 成功色的描边色 + * @nameEN Border Color of Success Color + * @desc 成功色的描边色,用于 Tag 和 Alert 的成功态描边色 + * @descEN Border color of success color, used for Tag and Alert success state border color + */ + colorSuccessBorder: string; // 3 + + /** + * @nameZH 成功色的描边色悬浮态 + * @nameEN Hover State Color of Success Border + * @desc 成功色的描边色悬浮态 + * @descEN Hover state color of success color border + */ + colorSuccessBorderHover: string; // 4 + + /** + * @nameZH 成功色的深色悬浮态 + * @nameEN Hover State Color of Dark Success + * @desc 成功色的深色悬浮态 + * @descEN Hover state color of dark success color + */ + colorSuccessHover: string; // 5 + + /** + * @nameZH 成功色 + * @nameEN Success Color + * @desc 默认的成功色,如 Result、Progress 等组件中都有使用该颜色 + * @descEN Default success color, used in components such as Result and Progress + */ + colorSuccess: string; // 6 + + /** + * @nameZH 成功色的深色激活态 + * @nameEN Active State Color of Dark Success + * @desc 成功色的深色激活态 + * @descEN Active state color of dark success color + */ + colorSuccessActive: string; // 7 + + /** + * @nameZH 成功色的文本悬浮态 + * @nameEN Hover State Color of Success Text + * @desc 成功色的文本悬浮态 + * @descEN Hover state color of success color text + */ + colorSuccessTextHover: string; // 8 + + /** + * @nameZH 成功色的文本默认态 + * @nameEN Default State Color of Success Text + * @desc 成功色的文本默认态 + * @descEN Default state color of success color text + */ + colorSuccessText: string; // 9 + + /** + * @nameZH 成功色的文本激活态 + * @nameEN Active State Color of Success Text + * @desc 成功色的文本激活态 + * @descEN Active state color of success color text + */ + colorSuccessTextActive: string; // 10 +} + +interface ColorWarningMapToken { + /** + * @nameZH 警戒色的浅色背景颜色 + * @nameEN Warning background color + * @desc 警戒色的浅色背景颜色 + * @descEN The background color of the warning state. + */ + colorWarningBg: string; // 1 + + /** + * @nameZH 警戒色的浅色背景色悬浮态 + * @nameEN Warning background color hover state + * @desc 警戒色的浅色背景色悬浮态 + * @descEN The hover state background color of the warning state. + */ + colorWarningBgHover: string; // 2 + + /** + * @nameZH 警戒色的描边色 + * @nameEN Warning border color + * @desc 警戒色的描边色 + * @descEN The border color of the warning state. + */ + colorWarningBorder: string; // 3 + + /** + * @nameZH 警戒色的描边色悬浮态 + * @nameEN Warning border color hover state + * @desc 警戒色的描边色悬浮态 + * @descEN The hover state border color of the warning state. + */ + colorWarningBorderHover: string; // 4 + + /** + * @nameZH 警戒色的深色悬浮态 + * @nameEN Warning hover color + * @desc 警戒色的深色悬浮态 + * @descEN The hover state of the warning color. + */ + colorWarningHover: string; // 5 + + /** + * @nameZH 警戒色 + * @nameEN Warning color + * @desc 最常用的警戒色,例如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该颜色 + * @descEN The most commonly used warning color, used for warning components such as Notification, Alert, or input components. + */ + colorWarning: string; // 6 + + /** + * @nameZH 警戒色的深色激活态 + * @nameEN Warning active color + * @desc 警戒色的深色激活态 + * @descEN The active state of the warning color. + */ + colorWarningActive: string; // 7 + + /** + * @nameZH 警戒色的文本悬浮态 + * @nameEN Warning text hover state + * @desc 警戒色的文本悬浮态 + * @descEN The hover state of the text in the warning color. + */ + colorWarningTextHover: string; // 8 + + /** + * @nameZH 警戒色的文本默认态 + * @nameEN Warning text default state + * @desc 警戒色的文本默认态 + * @descEN The default state of the text in the warning color. + */ + colorWarningText: string; // 9 + + /** + * @nameZH 警戒色的文本激活态 + * @nameEN Warning text active state + * @desc 警戒色的文本激活态 + * @descEN The active state of the text in the warning color. + */ + colorWarningTextActive: string; // 10 +} + +interface ColorInfoMapToken { + /** + * @nameZH 信息色的浅色背景颜色 + * @nameEN Light background color of information color + * @desc 信息色的浅色背景颜色。 + * @descEN Light background color of information color. + */ + colorInfoBg: string; // 1 + + /** + * @nameZH 信息色的浅色背景色悬浮态 + * @nameEN Hover state of light background color of information color + * @desc 信息色的浅色背景色悬浮态。 + * @descEN Hover state of light background color of information color. + */ + colorInfoBgHover: string; // 2 + + /** + * @nameZH 信息色的描边色 + * @nameEN Border color of information color + * @desc 信息色的描边色。 + * @descEN Border color of information color. + */ + colorInfoBorder: string; // 3 + + /** + * @nameZH 信息色的描边色悬浮态 + * @nameEN Hover state of border color of information color + * @desc 信息色的描边色悬浮态。 + * @descEN Hover state of border color of information color. + */ + colorInfoBorderHover: string; // 4 + + /** + * @nameZH 信息色的深色悬浮态 + * @nameEN Hover state of dark color of information color + * @desc 信息色的深色悬浮态。 + * @descEN Hover state of dark color of information color. + */ + colorInfoHover: string; // 5 + + /** + * @nameZH 信息色 + * @nameEN Information color + * @desc 信息色。 + * @descEN Information color. + */ + colorInfo: string; // 6 + + /** + * @nameZH 信息色的深色激活态 + * @nameEN Active state of dark color of information color + * @desc 信息色的深色激活态。 + * @descEN Active state of dark color of information color. + */ + colorInfoActive: string; // 7 + + /** + * @nameZH 信息色的文本悬浮态 + * @nameEN Hover state of text color of information color + * @desc 信息色的文本悬浮态。 + * @descEN Hover state of text color of information color. + */ + colorInfoTextHover: string; // 8 + + /** + * @nameZH 信息色的文本默认态 + * @nameEN Default state of text color of information color + * @desc 信息色的文本默认态。 + * @descEN Default state of text color of information color. + */ + colorInfoText: string; // 9 + + /** + * @nameZH 信息色的文本激活态 + * @nameEN Active state of text color of information color + * @desc 信息色的文本激活态。 + * @descEN Active state of text color of information color. + */ + colorInfoTextActive: string; // 10 +} + +interface ColorErrorMapToken { + /** + * @nameZH 错误色的浅色背景颜色 + * @nameEN Error background color + * @desc 错误色的浅色背景颜色 + * @descEN The background color of the error state. + */ + colorErrorBg: string; // 1 + + /** + * @nameZH 错误色的浅色背景色悬浮态 + * @nameEN Error background color hover state + * @desc 错误色的浅色背景色悬浮态 + * @descEN The hover state background color of the error state. + */ + colorErrorBgHover: string; // 2 + + /** + * @nameZH 错误色的描边色 + * @nameEN Error border color + * @desc 错误色的描边色 + * @descEN The border color of the error state. + */ + colorErrorBorder: string; // 3 + + /** + * @nameZH 错误色的描边色悬浮态 + * @nameEN Error border color hover state + * @desc 错误色的描边色悬浮态 + * @descEN The hover state border color of the error state. + */ + colorErrorBorderHover: string; // 4 + + /** + * @nameZH 错误色的深色悬浮态 + * @nameEN Error hover color + * @desc 错误色的深色悬浮态 + * @descEN The hover state of the error color. + */ + colorErrorHover: string; // 5 + + /** + * @nameZH 错误色 + * @nameEN Error color + * @desc 错误色 + * @descEN The color of the error state. + */ + colorError: string; // 6 + + /** + * @nameZH 错误色的深色激活态 + * @nameEN Error active color + * @desc 错误色的深色激活态 + * @descEN The active state of the error color. + */ + colorErrorActive: string; // 7 + + /** + * @nameZH 错误色的文本悬浮态 + * @nameEN Error text hover state + * @desc 错误色的文本悬浮态 + * @descEN The hover state of the text in the error color. + */ + colorErrorTextHover: string; // 8 + + /** + * @nameZH 错误色的文本默认态 + * @nameEN Error text default state + * @desc 错误色的文本默认态 + * @descEN The default state of the text in the error color. + */ + colorErrorText: string; // 9 + + /** + * @nameZH 错误色的文本激活态 + * @nameEN Error text active state + * @desc 错误色的文本激活态 + * @descEN The active state of the text in the error color. + */ + colorErrorTextActive: string; // 10 +} + +export interface ColorLinkMapToken { + /** + * @nameZH 超链接颜色 + * @nameEN Hyperlink color + * @desc 控制超链接的颜色。 + * @descEN Control the color of hyperlink. + */ + colorLink: string; + /** + * @nameZH 超链接悬浮颜色 + * @nameEN Hyperlink hover color + * @desc 控制超链接悬浮时的颜色。 + * @descEN Control the color of hyperlink when hovering. + */ + colorLinkHover: string; + /** + * @nameZH 超链接激活颜色 + * @nameEN Hyperlink active color + * @desc 控制超链接被点击时的颜色。 + * @descEN Control the color of hyperlink when clicked. + */ + colorLinkActive: string; +} + +export interface ColorMapToken + extends ColorNeutralMapToken, + ColorPrimaryMapToken, + ColorSuccessMapToken, + ColorWarningMapToken, + ColorErrorMapToken, + ColorInfoMapToken, + ColorLinkMapToken { + /** + * @nameZH 纯白色 + * @desc 不随主题变化的纯白色 + * @descEN Pure white color don't changed by theme + * @default #FFFFFF + */ + colorWhite: string; + + /** + * @nameZH 浮层的背景蒙层颜色 + * @nameEN Background color of the mask + * @desc 浮层的背景蒙层颜色,用于遮罩浮层下面的内容,Modal、Drawer 等组件的蒙层使用的是该 token + * @descEN The background color of the mask, used to cover the content below the mask, Modal, Drawer and other components use this token + */ + colorBgMask: string; + + /** + * @nameZH 纯黑色 + * @desc 不随主题变化的纯黑色 + * @default #0000 + */ + // colorBlack: string; +} diff --git a/components/_theme/interface/maps/font.ts b/components/_theme/interface/maps/font.ts new file mode 100644 index 000000000..40ed00716 --- /dev/null +++ b/components/_theme/interface/maps/font.ts @@ -0,0 +1,139 @@ +export interface FontMapToken { + // Font Size + /** + * @desc 小号字体大小 + * @descEN Small font size + */ + fontSizeSM: number; + /** + * @desc 标准字体大小 + * @descEN Standard font size + */ + fontSize: number; + /** + * @desc 大号字体大小 + * @descEN Large font size + */ + fontSizeLG: number; + /** + * @desc 超大号字体大小 + * @descEN Super large font size + */ + fontSizeXL: number; + + /** + * @nameZH 一级标题字号 + * @nameEN Font size of heading level 1 + * @desc H1 标签所使用的字号 + * @descEN Font size of h1 tag. + * @default 38 + */ + fontSizeHeading1: number; + /** + * @nameZH 二级标题字号 + * @nameEN Font size of heading level 2 + * @desc h2 标签所使用的字号 + * @descEN Font size of h2 tag. + * @default 30 + */ + fontSizeHeading2: number; + /** + * @nameZH 三级标题字号 + * @nameEN Font size of heading level 3 + * @desc h3 标签使用的字号 + * @descEN Font size of h3 tag. + * @default 24 + */ + fontSizeHeading3: number; + /** + * @nameZH 四级标题字号 + * @nameEN Font size of heading level 4 + * @desc h4 标签使用的字号 + * @descEN Font size of h4 tag. + * @default 20 + */ + fontSizeHeading4: number; + /** + * @nameZH 五级标题字号 + * @nameEN Font size of heading level 5 + * @desc h5 标签使用的字号 + * @descEN Font size of h5 tag. + * @default 16 + */ + fontSizeHeading5: number; + + // LineHeight + /** + * @desc 文本行高 + * @descEN Line height of text. + */ + lineHeight: number; + /** + * @desc 大型文本行高 + * @descEN Line height of large text. + */ + lineHeightLG: number; + /** + * @desc 小型文本行高 + * @descEN Line height of small text. + */ + lineHeightSM: number; + + // TextHeight + /** + * Round of fontSize * lineHeight + * @internal + */ + fontHeight: number; + /** + * Round of fontSizeSM * lineHeightSM + * @internal + */ + fontHeightSM: number; + /** + * Round of fontSizeLG * lineHeightLG + * @internal + */ + fontHeightLG: number; + + /** + * @nameZH 一级标题行高 + * @nameEN Line height of heading level 1 + * @desc H1 标签所使用的行高 + * @descEN Line height of h1 tag. + * @default 1.4 + */ + lineHeightHeading1: number; + /** + * @nameZH 二级标题行高 + * @nameEN Line height of heading level 2 + * @desc h2 标签所使用的行高 + * @descEN Line height of h2 tag. + * @default 1.35 + */ + lineHeightHeading2: number; + /** + * @nameZH 三级标题行高 + * @nameEN Line height of heading level 3 + * @desc h3 标签所使用的行高 + * @descEN Line height of h3 tag. + * @default 1.3 + */ + lineHeightHeading3: number; + /** + * @nameZH 四级标题行高 + * @nameEN Line height of heading level 4 + * @desc h4 标签所使用的行高 + * @descEN Line height of h4 tag. + * @default 1.25 + */ + lineHeightHeading4: number; + /** + * @nameZH 五级标题行高 + * @nameEN Line height of heading level 5 + * @desc h5 标签所使用的行高 + * @descEN Line height of h5 tag. + * @default 1.2 + */ + lineHeightHeading5: number; +} diff --git a/components/_theme/interface/maps/index.ts b/components/_theme/interface/maps/index.ts new file mode 100644 index 000000000..29d3f53d7 --- /dev/null +++ b/components/_theme/interface/maps/index.ts @@ -0,0 +1,46 @@ +import type { ColorPalettes, LegacyColorPalettes } from '../presetColors'; +import type { SeedToken } from '../seeds'; +import type { ColorMapToken } from './colors'; +import type { FontMapToken } from './font'; +import type { HeightMapToken, SizeMapToken } from './size'; +import type { StyleMapToken } from './style'; + +export * from './colors'; +export * from './font'; +export * from './size'; +export * from './style'; + +export interface CommonMapToken extends StyleMapToken { + // Motion + /** + * @desc 动效播放速度,快速。用于小型元素动画交互 + * @descEN Motion speed, fast speed. Used for small element animation interaction. + */ + motionDurationFast: string; + /** + * @desc 动效播放速度,中速。用于中型元素动画交互 + * @descEN Motion speed, medium speed. Used for medium element animation interaction. + */ + motionDurationMid: string; + /** + * @desc 动效播放速度,慢速。用于大型元素如面板动画交互 + * @descEN Motion speed, slow speed. Used for large element animation interaction. + */ + motionDurationSlow: string; +} + +// ====================================================================== +// == Map Token == +// ====================================================================== +// 🔥🔥🔥🔥🔥🔥🔥 DO NOT MODIFY THIS. PLEASE CONTACT DESIGNER. 🔥🔥🔥🔥🔥🔥🔥 + +export interface MapToken + extends SeedToken, + ColorPalettes, + LegacyColorPalettes, + ColorMapToken, + SizeMapToken, + HeightMapToken, + StyleMapToken, + FontMapToken, + CommonMapToken {} diff --git a/components/_theme/interface/maps/size.ts b/components/_theme/interface/maps/size.ts new file mode 100644 index 000000000..f69f5a927 --- /dev/null +++ b/components/_theme/interface/maps/size.ts @@ -0,0 +1,74 @@ +export interface SizeMapToken { + /** + * @nameZH XXL + * @default 48 + */ + sizeXXL: number; + /** + * @nameZH XL + * @default 32 + */ + sizeXL: number; + /** + * @nameZH LG + * @default 24 + */ + sizeLG: number; + /** + * @nameZH MD + * @default 20 + */ + sizeMD: number; + /** Same as size by default, but could be larger in compact mode */ + sizeMS: number; + /** + * @nameZH 默认 + * @desc 默认尺寸 + * @default 16 + */ + size: number; + /** + * @nameZH SM + * @default 12 + */ + sizeSM: number; + /** + * @nameZH XS + * @default 8 + */ + sizeXS: number; + /** + * @nameZH XXS + * @default 4 + */ + sizeXXS: number; +} + +export interface HeightMapToken { + // Control + /** Only Used for control inside component like Multiple Select inner selection item */ + + /** + * @nameZH 更小的组件高度 + * @nameEN XS component height + * @desc 更小的组件高度 + * @descEN XS component height + */ + controlHeightXS: number; + + /** + * @nameZH 较小的组件高度 + * @nameEN SM component height + * @desc 较小的组件高度 + * @descEN SM component height + */ + controlHeightSM: number; + + /** + * @nameZH 较高的组件高度 + * @nameEN LG component height + * @desc 较高的组件高度 + * @descEN LG component height + */ + controlHeightLG: number; +} diff --git a/components/_theme/interface/maps/style.ts b/components/_theme/interface/maps/style.ts new file mode 100644 index 000000000..e4faf7dac --- /dev/null +++ b/components/_theme/interface/maps/style.ts @@ -0,0 +1,43 @@ +export interface StyleMapToken { + /** + * @nameZH 线宽 + * @nameEN Line Width + * @desc 描边类组件的默认线宽,如 Button、Input、Select 等输入类控件。 + * @descEN The default line width of the outline class components, such as Button, Input, Select, etc. + * @default 1 + */ + lineWidthBold: number; + + /** + * @nameZH XS号圆角 + * @nameEN XS Border Radius + * @desc XS号圆角,用于组件中的一些小圆角,如 Segmented 、Arrow 等一些内部圆角的组件样式中。 + * @descEN XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. + * @default 2 + */ + borderRadiusXS: number; + /** + * @nameZH SM号圆角 + * @nameEN SM Border Radius + * @desc SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 + * @descEN SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size + * @default 4 + */ + borderRadiusSM: number; + /** + * @nameZH LG号圆角 + * @nameEN LG Border Radius + * @desc LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 + * @descEN LG size border radius, used in some large border radius components, such as Card, Modal and other components. + * @default 8 + */ + borderRadiusLG: number; + /** + * @nameZH 外部圆角 + * @nameEN Outer Border Radius + * @default 4 + * @desc 外部圆角 + * @descEN Outer border radius + */ + borderRadiusOuter: number; +} diff --git a/components/_theme/interface/presetColors.ts b/components/_theme/interface/presetColors.ts new file mode 100644 index 000000000..e160935e6 --- /dev/null +++ b/components/_theme/interface/presetColors.ts @@ -0,0 +1,32 @@ +export const PresetColors = [ + 'blue', + 'purple', + 'cyan', + 'green', + 'magenta', + 'pink', + 'red', + 'orange', + 'yellow', + 'volcano', + 'geekblue', + 'lime', + 'gold', +] as const; + +export type PresetColorKey = (typeof PresetColors)[number]; + +export type PresetColorType = Record; + +type ColorPaletteKeyIndex = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; + +export type LegacyColorPalettes = { + /** + * @deprecated + */ + [key in `${keyof PresetColorType}-${ColorPaletteKeyIndex}`]: string; +}; + +export type ColorPalettes = { + [key in `${keyof PresetColorType}${ColorPaletteKeyIndex}`]: string; +}; diff --git a/components/_theme/interface/seeds.ts b/components/_theme/interface/seeds.ts new file mode 100644 index 000000000..e7ac8a234 --- /dev/null +++ b/components/_theme/interface/seeds.ts @@ -0,0 +1,279 @@ +import type { PresetColorType } from './presetColors'; +// ====================================================================== +// == Seed Token == +// ====================================================================== +// 🔥🔥🔥🔥🔥🔥🔥 DO NOT MODIFY THIS. PLEASE CONTACT DESIGNER. 🔥🔥🔥🔥🔥🔥🔥 + +export interface SeedToken extends PresetColorType { + // ---------- Color ---------- // + + /** + * @nameZH 品牌主色 + * @nameEN Brand Color + * @desc 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 + * @descEN Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. + */ + colorPrimary: string; + + /** + * @nameZH 成功色 + * @nameEN Success Color + * @desc 用于表示操作成功的 Token 序列,如 Result、Progress 等组件会使用该组梯度变量。 + * @descEN Used to represent the token sequence of operation success, such as Result, Progress and other components will use these map tokens. + */ + colorSuccess: string; + + /** + * @nameZH 警戒色 + * @nameEN Warning Color + * @desc 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 + * @descEN Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. + */ + colorWarning: string; + + /** + * @nameZH 错误色 + * @nameEN Error Color + * @desc 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 + * @descEN Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. + */ + colorError: string; + + /** + * @nameZH 信息色 + * @nameEN Info Color + * @desc 用于表示操作信息的 Token 序列,如 Alert 、Tag、 Progress 等组件都有用到该组梯度变量。 + * @descEN Used to represent the operation information of the Token sequence, such as Alert, Tag, Progress, and other components use these map tokens. + */ + colorInfo: string; + + /** + * @nameZH 基础文本色 + * @nameEN Seed Text Color + * @desc 用于派生文本色梯度的基础变量,v5 中我们添加了一层文本色的派生算法可以产出梯度明确的文本色的梯度变量。但请不要在代码中直接使用该 Seed Token ! + * @descEN Used to derive the base variable of the text color gradient. In v5, we added a layer of text color derivation algorithm to produce gradient variables of text color gradient. But please do not use this Seed Token directly in the code! + */ + colorTextBase: string; + + /** + * @nameZH 基础背景色 + * @nameEN Seed Background Color + * @desc 用于派生背景色梯度的基础变量,v5 中我们添加了一层背景色的派生算法可以产出梯度明确的背景色的梯度变量。但请不要在代码中直接使用该 Seed Token ! + * @descEN Used to derive the base variable of the background color gradient. In v5, we added a layer of background color derivation algorithm to produce map token of background color. But PLEASE DO NOT USE this Seed Token directly in the code! + */ + colorBgBase: string; + + /** + * @nameZH 超链接颜色 + * @nameEN Hyperlink color + * @desc 控制超链接的颜色。 + * @descEN Control the color of hyperlink. + */ + colorLink: string; + + // ---------- Font ---------- // + + /** + * @nameZH 字体 + * @nameEN Font family for default text + * @desc Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 + * @descEN The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. + */ + fontFamily: string; + + /** + * @nameZH 代码字体 + * @nameEN Font family for code text + * @desc 代码字体,用于 Typography 内的 code、pre 和 kbd 类型的元素 + * @descEN Code font, used for code, pre and kbd elements in Typography + */ + fontFamilyCode: string; + + /** + * @nameZH 默认字号 + * @nameEN Default Font Size + * @desc 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 + * @descEN The most widely used font size in the design system, from which the text gradient will be derived. + * @default 14 + */ + fontSize: number; + + // ---------- Line ---------- // + + /** + * @nameZH 基础线宽 + * @nameEN Base Line Width + * @desc 用于控制组件边框、分割线等的宽度 + * @descEN Border width of base components + */ + lineWidth: number; + + /** + * @nameZH 线条样式 + * @nameEN Line Style + * @desc 用于控制组件边框、分割线等的样式,默认是实线 + * @descEN Border style of base components + */ + lineType: string; + + // ---------- BorderRadius ---------- // + + /** + * @nameZH 基础圆角 + * @nameEN Base Border Radius + * @descEN Border radius of base components + * @desc 基础组件的圆角大小,例如按钮、输入框、卡片等 + */ + borderRadius: number; + + // ---------- Size ---------- // + + /** + * @nameZH 尺寸变化单位 + * @nameEN Size Change Unit + * @desc 用于控制组件尺寸的变化单位,在 Ant Design 中我们的基础单位为 4 ,便于更加细致地控制尺寸梯度 + * @descEN The unit of size change, in Ant Design, our base unit is 4, which is more fine-grained control of the size step + * @default 4 + */ + sizeUnit: number; + + /** + * @nameZH 尺寸步长 + * @nameEN Size Base Step + * @desc 用于控制组件尺寸的基础步长,尺寸步长结合尺寸变化单位,就可以派生各种尺寸梯度。通过调整步长即可得到不同的布局模式,例如 V5 紧凑模式下的尺寸步长为 2 + * @descEN The base step of size change, the size step combined with the size change unit, can derive various size steps. By adjusting the step, you can get different layout modes, such as the size step of the compact mode of V5 is 2 + * @default 4 + */ + sizeStep: number; + + /** + * @nameZH 组件箭头尺寸 + * @desc 组件箭头的尺寸 + * @descEN The size of the component arrow + */ + sizePopupArrow: number; + + /** + * @nameZH 基础高度 + * @nameEN Base Control Height + * @desc Ant Design 中按钮和输入框等基础控件的高度 + * @descEN The height of the basic controls such as buttons and input boxes in Ant Design + * @default 32 + */ + controlHeight: number; + + // ---------- zIndex ---------- // + + /** + * @nameZH 基础 zIndex + * @nameEN Base zIndex + * @desc 所有组件的基础 Z 轴值,用于一些悬浮类的组件的可以基于该值 Z 轴控制层级,例如 BackTop、 Affix 等 + * @descEN The base Z axis value of all components, which can be used to control the level of some floating components based on the Z axis value, such as BackTop, Affix, etc. + * + * @default 0 + */ + zIndexBase: number; + + /** + * @nameZH 浮层基础 zIndex + * @nameEN popup base zIndex + * @desc 浮层类组件的基础 Z 轴值,用于一些悬浮类的组件的可以基于该值 Z 轴控制层级,例如 FloatButton、 Affix、Modal 等 + * @descEN Base zIndex of component like FloatButton, Affix which can be cover by large popup + * @default 1000 + */ + zIndexPopupBase: number; + + // ---------- Opacity ---------- // + + /** + * @nameZH 图片不透明度 + * @nameEN Define default Image opacity. Useful when in dark-like theme + */ + opacityImage: number; + + // ---------- motion ---------- // + // TODO: 缺一个懂 motion 的人来收敛 Motion 相关的 Token + + /** + * @nameZH 动画时长变化单位 + * @nameEN Animation Duration Unit + * @desc 用于控制动画时长的变化单位 + * @descEN The unit of animation duration change + * @default 100ms + */ + motionUnit: number; + + /** + * @nameZH 动画基础时长。 + * @nameEN Animation Base Duration. + */ + motionBase: number; + + /** + * @desc 预设动效曲率 + * @descEN Preset motion curve. + */ + motionEaseOutCirc: string; + + /** + * @desc 预设动效曲率 + * @descEN Preset motion curve. + */ + motionEaseInOutCirc: string; + + /** + * @desc 预设动效曲率 + * @descEN Preset motion curve. + */ + motionEaseInOut: string; + + /** + * @desc 预设动效曲率 + * @descEN Preset motion curve. + */ + motionEaseOutBack: string; + + /** + * @desc 预设动效曲率 + * @descEN Preset motion curve. + */ + motionEaseInBack: string; + + /** + * @desc 预设动效曲率 + * @descEN Preset motion curve. + */ + motionEaseInQuint: string; + + /** + * @desc 预设动效曲率 + * @descEN Preset motion curve. + */ + motionEaseOutQuint: string; + + /** + * @desc 预设动效曲率 + * @descEN Preset motion curve. + */ + motionEaseOut: string; + + // ---------- Style ---------- // + + /** + * @nameZH 线框风格 + * @nameEN Wireframe Style + * @desc 用于将组件的视觉效果变为线框化,如果需要使用 V4 的效果,需要开启配置项 + * @descEN Used to change the visual effect of the component to wireframe, if you need to use the V4 effect, you need to enable the configuration item + * @default false + */ + wireframe: boolean; + + /** + * @nameZH 动画风格 + * @nameEN Motion Style + * @desc 用于配置动画效果,为 `false` 时则关闭动画 + * @descEN Used to configure the motion effect, when it is `false`, the motion is turned off + * @default false + */ + motion: boolean; +} diff --git a/components/_theme/internal.ts b/components/_theme/internal.ts new file mode 100644 index 000000000..a3061cd60 --- /dev/null +++ b/components/_theme/internal.ts @@ -0,0 +1,51 @@ +import { useStyleRegister } from '../_util/_cssinjs'; + +import type { + AliasToken, + GenerateStyle, + PresetColorKey, + PresetColorType, + SeedToken, + UseComponentStyleResult, +} from './interface'; +import { PresetColors } from './interface'; +import useToken from './useToken'; +import type { FullToken, GetDefaultToken } from './util/genComponentStyleHook'; +import genComponentStyleHook, { + genSubStyleComponent, + genStyleHooks, +} from './util/genComponentStyleHook'; +import genPresetColor from './util/genPresetColor'; +import statisticToken, { merge as mergeToken } from './util/statistic'; +import useResetIconStyle from './util/useResetIconStyle'; +import calc from './util/calc'; +import { getLineHeight } from './themes/shared/genFontSizes'; + +export { defaultConfig, DesignTokenProvider } from './context'; +export { + PresetColors, + genComponentStyleHook, + genSubStyleComponent, + genPresetColor, + genStyleHooks, + mergeToken, + statisticToken, + calc, + getLineHeight, + // hooks + useResetIconStyle, + useStyleRegister, + useToken, +}; +export type { + AliasToken, + // FIXME: Remove this type + AliasToken as DerivativeToken, + FullToken, + GenerateStyle, + PresetColorKey, + PresetColorType, + SeedToken, + UseComponentStyleResult, + GetDefaultToken, +}; diff --git a/components/_theme/themes/ColorMap.ts b/components/_theme/themes/ColorMap.ts new file mode 100644 index 000000000..0a6821076 --- /dev/null +++ b/components/_theme/themes/ColorMap.ts @@ -0,0 +1,20 @@ +import type { ColorNeutralMapToken } from '../interface'; + +export interface ColorMap { + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; +} + +export type GenerateColorMap = (baseColor: string) => ColorMap; +export type GenerateNeutralColorMap = ( + bgBaseColor: string, + textBaseColor: string, +) => ColorNeutralMapToken; diff --git a/components/_theme/themes/compact/genCompactSizeMapToken.ts b/components/_theme/themes/compact/genCompactSizeMapToken.ts new file mode 100644 index 000000000..b473808ec --- /dev/null +++ b/components/_theme/themes/compact/genCompactSizeMapToken.ts @@ -0,0 +1,19 @@ +import type { SeedToken, SizeMapToken } from '../../interface'; + +export default function genSizeMapToken(token: SeedToken): SizeMapToken { + const { sizeUnit, sizeStep } = token; + + const compactSizeStep = sizeStep - 2; + + return { + sizeXXL: sizeUnit * (compactSizeStep + 10), + sizeXL: sizeUnit * (compactSizeStep + 6), + sizeLG: sizeUnit * (compactSizeStep + 2), + sizeMD: sizeUnit * (compactSizeStep + 2), + sizeMS: sizeUnit * (compactSizeStep + 1), + size: sizeUnit * compactSizeStep, + sizeSM: sizeUnit * compactSizeStep, + sizeXS: sizeUnit * (compactSizeStep - 1), + sizeXXS: sizeUnit * (compactSizeStep - 1), + }; +} diff --git a/components/_theme/themes/compact/index.ts b/components/_theme/themes/compact/index.ts new file mode 100644 index 000000000..5980b9dc2 --- /dev/null +++ b/components/_theme/themes/compact/index.ts @@ -0,0 +1,27 @@ +import type { DerivativeFunc } from '../../../_util/_cssinjs'; +import genControlHeight from '../shared/genControlHeight'; +import type { MapToken, SeedToken } from '../../interface'; +import defaultAlgorithm from '../default'; +import genCompactSizeMapToken from './genCompactSizeMapToken'; +import genFontMapToken from '../shared/genFontMapToken'; + +const derivative: DerivativeFunc = (token, mapToken) => { + const mergedMapToken = mapToken ?? defaultAlgorithm(token); + + const fontSize = mergedMapToken.fontSizeSM; // Smaller size font-size as base + const controlHeight = mergedMapToken.controlHeight - 4; + + return { + ...mergedMapToken, + ...genCompactSizeMapToken(mapToken ?? token), + + // font + ...genFontMapToken(fontSize), + + // controlHeight + controlHeight, + ...genControlHeight({ ...mergedMapToken, controlHeight }), + }; +}; + +export default derivative; diff --git a/components/_theme/themes/dark/colorAlgorithm.ts b/components/_theme/themes/dark/colorAlgorithm.ts new file mode 100644 index 000000000..cf395bc0a --- /dev/null +++ b/components/_theme/themes/dark/colorAlgorithm.ts @@ -0,0 +1,9 @@ +import { TinyColor } from '@ctrl/tinycolor'; + +export const getAlphaColor = (baseColor: string, alpha: number) => + new TinyColor(baseColor).setAlpha(alpha).toRgbString(); + +export const getSolidColor = (baseColor: string, brightness: number) => { + const instance = new TinyColor(baseColor); + return instance.lighten(brightness).toHexString(); +}; diff --git a/components/_theme/themes/dark/colors.ts b/components/_theme/themes/dark/colors.ts new file mode 100644 index 000000000..b3342c99a --- /dev/null +++ b/components/_theme/themes/dark/colors.ts @@ -0,0 +1,54 @@ +import { generate } from '@ant-design/colors'; +import type { GenerateColorMap, GenerateNeutralColorMap } from '../ColorMap'; +import { getAlphaColor, getSolidColor } from './colorAlgorithm'; + +export const generateColorPalettes: GenerateColorMap = (baseColor: string) => { + const colors = generate(baseColor, { theme: 'dark' }); + return { + 1: colors[0], + 2: colors[1], + 3: colors[2], + 4: colors[3], + 5: colors[6], + 6: colors[5], + 7: colors[4], + 8: colors[6], + 9: colors[5], + 10: colors[4], + // 8: colors[9], + // 9: colors[8], + // 10: colors[7], + }; +}; + +export const generateNeutralColorPalettes: GenerateNeutralColorMap = ( + bgBaseColor: string, + textBaseColor: string, +) => { + const colorBgBase = bgBaseColor || '#000'; + const colorTextBase = textBaseColor || '#fff'; + + return { + colorBgBase, + colorTextBase, + + colorText: getAlphaColor(colorTextBase, 0.85), + colorTextSecondary: getAlphaColor(colorTextBase, 0.65), + colorTextTertiary: getAlphaColor(colorTextBase, 0.45), + colorTextQuaternary: getAlphaColor(colorTextBase, 0.25), + + colorFill: getAlphaColor(colorTextBase, 0.18), + colorFillSecondary: getAlphaColor(colorTextBase, 0.12), + colorFillTertiary: getAlphaColor(colorTextBase, 0.08), + colorFillQuaternary: getAlphaColor(colorTextBase, 0.04), + + colorBgElevated: getSolidColor(colorBgBase, 12), + colorBgContainer: getSolidColor(colorBgBase, 8), + colorBgLayout: getSolidColor(colorBgBase, 0), + colorBgSpotlight: getSolidColor(colorBgBase, 26), + colorBgBlur: getAlphaColor(colorTextBase, 0.04), + + colorBorder: getSolidColor(colorBgBase, 26), + colorBorderSecondary: getSolidColor(colorBgBase, 19), + }; +}; diff --git a/components/_theme/themes/dark/index.ts b/components/_theme/themes/dark/index.ts new file mode 100644 index 000000000..69e16a063 --- /dev/null +++ b/components/_theme/themes/dark/index.ts @@ -0,0 +1,49 @@ +import { generate } from '@ant-design/colors'; +import type { DerivativeFunc } from '../../../_util/_cssinjs'; +import type { + ColorPalettes, + LegacyColorPalettes, + MapToken, + PresetColorType, + SeedToken, +} from '../../interface'; +import { defaultPresetColors } from '../seed'; +import genColorMapToken from '../shared/genColorMapToken'; +import { generateColorPalettes, generateNeutralColorPalettes } from './colors'; +import defaultAlgorithm from '../default'; + +const derivative: DerivativeFunc = (token, mapToken) => { + const colorPalettes = Object.keys(defaultPresetColors) + .map((colorKey: keyof PresetColorType) => { + const colors = generate(token[colorKey], { theme: 'dark' }); + + return new Array(10).fill(1).reduce((prev, _, i) => { + prev[`${colorKey}-${i + 1}`] = colors[i]; + prev[`${colorKey}${i + 1}`] = colors[i]; + return prev; + }, {}) as ColorPalettes & LegacyColorPalettes; + }) + .reduce((prev, cur) => { + prev = { + ...prev, + ...cur, + }; + return prev; + }, {} as ColorPalettes & LegacyColorPalettes); + + const mergedMapToken = mapToken ?? defaultAlgorithm(token); + + return { + ...mergedMapToken, + + // Dark tokens + ...colorPalettes, + // Colors + ...genColorMapToken(token, { + generateColorPalettes, + generateNeutralColorPalettes, + }), + }; +}; + +export default derivative; diff --git a/components/_theme/themes/default/colorAlgorithm.ts b/components/_theme/themes/default/colorAlgorithm.ts new file mode 100644 index 000000000..5ab75e6b1 --- /dev/null +++ b/components/_theme/themes/default/colorAlgorithm.ts @@ -0,0 +1,9 @@ +import { TinyColor } from '@ctrl/tinycolor'; + +export const getAlphaColor = (baseColor: string, alpha: number) => + new TinyColor(baseColor).setAlpha(alpha).toRgbString(); + +export const getSolidColor = (baseColor: string, brightness: number) => { + const instance = new TinyColor(baseColor); + return instance.darken(brightness).toHexString(); +}; diff --git a/components/_theme/themes/default/colors.ts b/components/_theme/themes/default/colors.ts new file mode 100644 index 000000000..d0e684dd4 --- /dev/null +++ b/components/_theme/themes/default/colors.ts @@ -0,0 +1,54 @@ +import { generate } from '@ant-design/colors'; +import type { GenerateColorMap, GenerateNeutralColorMap } from '../ColorMap'; +import { getAlphaColor, getSolidColor } from './colorAlgorithm'; + +export const generateColorPalettes: GenerateColorMap = (baseColor: string) => { + const colors = generate(baseColor); + return { + 1: colors[0], + 2: colors[1], + 3: colors[2], + 4: colors[3], + 5: colors[4], + 6: colors[5], + 7: colors[6], + 8: colors[4], + 9: colors[5], + 10: colors[6], + // 8: colors[7], + // 9: colors[8], + // 10: colors[9], + }; +}; + +export const generateNeutralColorPalettes: GenerateNeutralColorMap = ( + bgBaseColor: string, + textBaseColor: string, +) => { + const colorBgBase = bgBaseColor || '#fff'; + const colorTextBase = textBaseColor || '#000'; + + return { + colorBgBase, + colorTextBase, + + colorText: getAlphaColor(colorTextBase, 0.88), + colorTextSecondary: getAlphaColor(colorTextBase, 0.65), + colorTextTertiary: getAlphaColor(colorTextBase, 0.45), + colorTextQuaternary: getAlphaColor(colorTextBase, 0.25), + + colorFill: getAlphaColor(colorTextBase, 0.15), + colorFillSecondary: getAlphaColor(colorTextBase, 0.06), + colorFillTertiary: getAlphaColor(colorTextBase, 0.04), + colorFillQuaternary: getAlphaColor(colorTextBase, 0.02), + + colorBgLayout: getSolidColor(colorBgBase, 4), + colorBgContainer: getSolidColor(colorBgBase, 0), + colorBgElevated: getSolidColor(colorBgBase, 0), + colorBgSpotlight: getAlphaColor(colorTextBase, 0.85), + colorBgBlur: 'transparent', + + colorBorder: getSolidColor(colorBgBase, 15), + colorBorderSecondary: getSolidColor(colorBgBase, 6), + }; +}; diff --git a/components/_theme/themes/default/index.ts b/components/_theme/themes/default/index.ts new file mode 100644 index 000000000..d558e2cf8 --- /dev/null +++ b/components/_theme/themes/default/index.ts @@ -0,0 +1,53 @@ +import { generate } from '@ant-design/colors'; +import genControlHeight from '../shared/genControlHeight'; +import genSizeMapToken from '../shared/genSizeMapToken'; +import type { + ColorPalettes, + LegacyColorPalettes, + MapToken, + PresetColorType, + SeedToken, +} from '../../interface'; +import { defaultPresetColors } from '../seed'; +import genColorMapToken from '../shared/genColorMapToken'; +import genCommonMapToken from '../shared/genCommonMapToken'; +import { generateColorPalettes, generateNeutralColorPalettes } from './colors'; +import genFontMapToken from '../shared/genFontMapToken'; + +export default function derivative(token: SeedToken): MapToken { + const colorPalettes = Object.keys(defaultPresetColors) + .map((colorKey: keyof PresetColorType) => { + const colors = generate(token[colorKey]); + + return new Array(10).fill(1).reduce((prev, _, i) => { + prev[`${colorKey}-${i + 1}`] = colors[i]; + prev[`${colorKey}${i + 1}`] = colors[i]; + return prev; + }, {}) as ColorPalettes & LegacyColorPalettes; + }) + .reduce((prev, cur) => { + prev = { + ...prev, + ...cur, + }; + return prev; + }, {} as ColorPalettes & LegacyColorPalettes); + + return { + ...token, + ...colorPalettes, + // Colors + ...genColorMapToken(token, { + generateColorPalettes, + generateNeutralColorPalettes, + }), + // Font + ...genFontMapToken(token.fontSize), + // Size + ...genSizeMapToken(token), + // Height + ...genControlHeight(token), + // Others + ...genCommonMapToken(token), + }; +} diff --git a/components/_theme/themes/seed.ts b/components/_theme/themes/seed.ts new file mode 100644 index 000000000..e24925bbf --- /dev/null +++ b/components/_theme/themes/seed.ts @@ -0,0 +1,81 @@ +import type { PresetColorType, SeedToken } from '../internal'; + +export const defaultPresetColors: PresetColorType = { + blue: '#1677ff', + purple: '#722ED1', + cyan: '#13C2C2', + green: '#52C41A', + magenta: '#EB2F96', + pink: '#eb2f96', + red: '#F5222D', + orange: '#FA8C16', + yellow: '#FADB14', + volcano: '#FA541C', + geekblue: '#2F54EB', + gold: '#FAAD14', + lime: '#A0D911', +}; + +const seedToken: SeedToken = { + // preset color palettes + ...defaultPresetColors, + + // Color + colorPrimary: '#1677ff', + colorSuccess: '#52c41a', + colorWarning: '#faad14', + colorError: '#ff4d4f', + colorInfo: '#1677ff', + colorLink: '', + colorTextBase: '', + + colorBgBase: '', + + // Font + fontFamily: `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, +'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', +'Noto Color Emoji'`, + fontFamilyCode: `'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace`, + fontSize: 14, + + // Line + lineWidth: 1, + lineType: 'solid', + + // Motion + motionUnit: 0.1, + motionBase: 0, + motionEaseOutCirc: 'cubic-bezier(0.08, 0.82, 0.17, 1)', + motionEaseInOutCirc: 'cubic-bezier(0.78, 0.14, 0.15, 0.86)', + motionEaseOut: 'cubic-bezier(0.215, 0.61, 0.355, 1)', + motionEaseInOut: 'cubic-bezier(0.645, 0.045, 0.355, 1)', + motionEaseOutBack: 'cubic-bezier(0.12, 0.4, 0.29, 1.46)', + motionEaseInBack: 'cubic-bezier(0.71, -0.46, 0.88, 0.6)', + motionEaseInQuint: 'cubic-bezier(0.755, 0.05, 0.855, 0.06)', + motionEaseOutQuint: 'cubic-bezier(0.23, 1, 0.32, 1)', + + // Radius + borderRadius: 6, + + // Size + sizeUnit: 4, + sizeStep: 4, + sizePopupArrow: 16, + + // Control Base + controlHeight: 32, + + // zIndex + zIndexBase: 0, + zIndexPopupBase: 1000, + + // Image + opacityImage: 1, + + // Wireframe + wireframe: false, + + // Motion + motion: true, +}; +export default seedToken; diff --git a/components/_theme/themes/shared/genColorMapToken.ts b/components/_theme/themes/shared/genColorMapToken.ts new file mode 100644 index 000000000..3a3aa8d6d --- /dev/null +++ b/components/_theme/themes/shared/genColorMapToken.ts @@ -0,0 +1,100 @@ +import { TinyColor } from '@ctrl/tinycolor'; +import type { ColorMapToken, SeedToken } from '../../interface'; +import type { GenerateColorMap, GenerateNeutralColorMap } from '../ColorMap'; + +interface PaletteGenerators { + generateColorPalettes: GenerateColorMap; + generateNeutralColorPalettes: GenerateNeutralColorMap; +} + +export default function genColorMapToken( + seed: SeedToken, + { generateColorPalettes, generateNeutralColorPalettes }: PaletteGenerators, +): ColorMapToken { + const { + colorSuccess: colorSuccessBase, + colorWarning: colorWarningBase, + colorError: colorErrorBase, + colorInfo: colorInfoBase, + colorPrimary: colorPrimaryBase, + colorBgBase, + colorTextBase, + } = seed; + + const primaryColors = generateColorPalettes(colorPrimaryBase); + const successColors = generateColorPalettes(colorSuccessBase); + const warningColors = generateColorPalettes(colorWarningBase); + const errorColors = generateColorPalettes(colorErrorBase); + const infoColors = generateColorPalettes(colorInfoBase); + const neutralColors = generateNeutralColorPalettes(colorBgBase, colorTextBase); + + // Color Link + const colorLink = seed.colorLink || seed.colorInfo; + const linkColors = generateColorPalettes(colorLink); + + return { + ...neutralColors, + + colorPrimaryBg: primaryColors[1], + colorPrimaryBgHover: primaryColors[2], + colorPrimaryBorder: primaryColors[3], + colorPrimaryBorderHover: primaryColors[4], + colorPrimaryHover: primaryColors[5], + colorPrimary: primaryColors[6], + colorPrimaryActive: primaryColors[7], + colorPrimaryTextHover: primaryColors[8], + colorPrimaryText: primaryColors[9], + colorPrimaryTextActive: primaryColors[10], + + colorSuccessBg: successColors[1], + colorSuccessBgHover: successColors[2], + colorSuccessBorder: successColors[3], + colorSuccessBorderHover: successColors[4], + colorSuccessHover: successColors[4], + colorSuccess: successColors[6], + colorSuccessActive: successColors[7], + colorSuccessTextHover: successColors[8], + colorSuccessText: successColors[9], + colorSuccessTextActive: successColors[10], + + colorErrorBg: errorColors[1], + colorErrorBgHover: errorColors[2], + colorErrorBorder: errorColors[3], + colorErrorBorderHover: errorColors[4], + colorErrorHover: errorColors[5], + colorError: errorColors[6], + colorErrorActive: errorColors[7], + colorErrorTextHover: errorColors[8], + colorErrorText: errorColors[9], + colorErrorTextActive: errorColors[10], + + colorWarningBg: warningColors[1], + colorWarningBgHover: warningColors[2], + colorWarningBorder: warningColors[3], + colorWarningBorderHover: warningColors[4], + colorWarningHover: warningColors[4], + colorWarning: warningColors[6], + colorWarningActive: warningColors[7], + colorWarningTextHover: warningColors[8], + colorWarningText: warningColors[9], + colorWarningTextActive: warningColors[10], + + colorInfoBg: infoColors[1], + colorInfoBgHover: infoColors[2], + colorInfoBorder: infoColors[3], + colorInfoBorderHover: infoColors[4], + colorInfoHover: infoColors[4], + colorInfo: infoColors[6], + colorInfoActive: infoColors[7], + colorInfoTextHover: infoColors[8], + colorInfoText: infoColors[9], + colorInfoTextActive: infoColors[10], + + colorLinkHover: linkColors[4], + colorLink: linkColors[6], + colorLinkActive: linkColors[7], + + colorBgMask: new TinyColor('#000').setAlpha(0.45).toRgbString(), + colorWhite: '#fff', + }; +} diff --git a/components/_theme/themes/shared/genCommonMapToken.ts b/components/_theme/themes/shared/genCommonMapToken.ts new file mode 100644 index 000000000..7561e9cd2 --- /dev/null +++ b/components/_theme/themes/shared/genCommonMapToken.ts @@ -0,0 +1,19 @@ +import type { CommonMapToken, SeedToken } from '../../interface'; +import genRadius from './genRadius'; + +export default function genCommonMapToken(token: SeedToken): CommonMapToken { + const { motionUnit, motionBase, borderRadius, lineWidth } = token; + + return { + // motion + motionDurationFast: `${(motionBase + motionUnit).toFixed(1)}s`, + motionDurationMid: `${(motionBase + motionUnit * 2).toFixed(1)}s`, + motionDurationSlow: `${(motionBase + motionUnit * 3).toFixed(1)}s`, + + // line + lineWidthBold: lineWidth + 1, + + // radius + ...genRadius(borderRadius), + }; +} diff --git a/components/_theme/themes/shared/genControlHeight.ts b/components/_theme/themes/shared/genControlHeight.ts new file mode 100644 index 000000000..5303b6946 --- /dev/null +++ b/components/_theme/themes/shared/genControlHeight.ts @@ -0,0 +1,13 @@ +import type { HeightMapToken, SeedToken } from '../../interface'; + +const genControlHeight = (token: SeedToken): HeightMapToken => { + const { controlHeight } = token; + + return { + controlHeightSM: controlHeight * 0.75, + controlHeightXS: controlHeight * 0.5, + controlHeightLG: controlHeight * 1.25, + }; +}; + +export default genControlHeight; diff --git a/components/_theme/themes/shared/genFontMapToken.ts b/components/_theme/themes/shared/genFontMapToken.ts new file mode 100644 index 000000000..8cd58e7e2 --- /dev/null +++ b/components/_theme/themes/shared/genFontMapToken.ts @@ -0,0 +1,44 @@ +import type { FontMapToken } from '../../interface'; +import genFontSizes from './genFontSizes'; + +const genFontMapToken = (fontSize: number): FontMapToken => { + const fontSizePairs = genFontSizes(fontSize); + const fontSizes = fontSizePairs.map(pair => pair.size); + const lineHeights = fontSizePairs.map(pair => pair.lineHeight); + + const fontSizeMD = fontSizes[1]; + const fontSizeSM = fontSizes[0]; + const fontSizeLG = fontSizes[2]; + const lineHeight = lineHeights[1]; + const lineHeightSM = lineHeights[0]; + const lineHeightLG = lineHeights[2]; + + return { + fontSizeSM, + fontSize: fontSizeMD, + fontSizeLG, + fontSizeXL: fontSizes[3], + + fontSizeHeading1: fontSizes[6], + fontSizeHeading2: fontSizes[5], + fontSizeHeading3: fontSizes[4], + fontSizeHeading4: fontSizes[3], + fontSizeHeading5: fontSizes[2], + + lineHeight, + lineHeightLG, + lineHeightSM, + + fontHeight: Math.round(lineHeight * fontSizeMD), + fontHeightLG: Math.round(lineHeightLG * fontSizeLG), + fontHeightSM: Math.round(lineHeightSM * fontSizeSM), + + lineHeightHeading1: lineHeights[6], + lineHeightHeading2: lineHeights[5], + lineHeightHeading3: lineHeights[4], + lineHeightHeading4: lineHeights[3], + lineHeightHeading5: lineHeights[2], + }; +}; + +export default genFontMapToken; diff --git a/components/_theme/themes/shared/genFontSizes.ts b/components/_theme/themes/shared/genFontSizes.ts new file mode 100644 index 000000000..47c027d49 --- /dev/null +++ b/components/_theme/themes/shared/genFontSizes.ts @@ -0,0 +1,22 @@ +export function getLineHeight(fontSize: number) { + return (fontSize + 8) / fontSize; +} + +// https://zhuanlan.zhihu.com/p/32746810 +export default function getFontSizes(base: number) { + const fontSizes = new Array(10).fill(null).map((_, index) => { + const i = index - 1; + const baseSize = base * 2.71828 ** (i / 5); + const intSize = index > 1 ? Math.floor(baseSize) : Math.ceil(baseSize); + + // Convert to even + return Math.floor(intSize / 2) * 2; + }); + + fontSizes[1] = base; + + return fontSizes.map(size => ({ + size, + lineHeight: getLineHeight(size), + })); +} diff --git a/components/_theme/themes/shared/genRadius.ts b/components/_theme/themes/shared/genRadius.ts new file mode 100644 index 000000000..0bac4c988 --- /dev/null +++ b/components/_theme/themes/shared/genRadius.ts @@ -0,0 +1,59 @@ +import type { MapToken } from '../../interface'; + +const genRadius = ( + radiusBase: number, +): Pick< + MapToken, + 'borderRadiusXS' | 'borderRadiusSM' | 'borderRadiusLG' | 'borderRadius' | 'borderRadiusOuter' +> => { + let radiusLG = radiusBase; + let radiusSM = radiusBase; + let radiusXS = radiusBase; + let radiusOuter = radiusBase; + + // radiusLG + if (radiusBase < 6 && radiusBase >= 5) { + radiusLG = radiusBase + 1; + } else if (radiusBase < 16 && radiusBase >= 6) { + radiusLG = radiusBase + 2; + } else if (radiusBase >= 16) { + radiusLG = 16; + } + + // radiusSM + if (radiusBase < 7 && radiusBase >= 5) { + radiusSM = 4; + } else if (radiusBase < 8 && radiusBase >= 7) { + radiusSM = 5; + } else if (radiusBase < 14 && radiusBase >= 8) { + radiusSM = 6; + } else if (radiusBase < 16 && radiusBase >= 14) { + radiusSM = 7; + } else if (radiusBase >= 16) { + radiusSM = 8; + } + + // radiusXS + if (radiusBase < 6 && radiusBase >= 2) { + radiusXS = 1; + } else if (radiusBase >= 6) { + radiusXS = 2; + } + + // radiusOuter + if (radiusBase > 4 && radiusBase < 8) { + radiusOuter = 4; + } else if (radiusBase >= 8) { + radiusOuter = 6; + } + + return { + borderRadius: radiusBase, + borderRadiusXS: radiusXS, + borderRadiusSM: radiusSM, + borderRadiusLG: radiusLG, + borderRadiusOuter: radiusOuter, + }; +}; + +export default genRadius; diff --git a/components/_theme/themes/shared/genSizeMapToken.ts b/components/_theme/themes/shared/genSizeMapToken.ts new file mode 100644 index 000000000..3449c24df --- /dev/null +++ b/components/_theme/themes/shared/genSizeMapToken.ts @@ -0,0 +1,17 @@ +import type { SeedToken, SizeMapToken } from '../../interface'; + +export default function genSizeMapToken(token: SeedToken): SizeMapToken { + const { sizeUnit, sizeStep } = token; + + return { + sizeXXL: sizeUnit * (sizeStep + 8), // 48 + sizeXL: sizeUnit * (sizeStep + 4), // 32 + sizeLG: sizeUnit * (sizeStep + 2), // 24 + sizeMD: sizeUnit * (sizeStep + 1), // 20 + sizeMS: sizeUnit * sizeStep, // 16 + size: sizeUnit * sizeStep, // 16 + sizeSM: sizeUnit * (sizeStep - 1), // 12 + sizeXS: sizeUnit * (sizeStep - 2), // 8 + sizeXXS: sizeUnit * (sizeStep - 3), // 4 + }; +} diff --git a/components/_theme/useToken.ts b/components/_theme/useToken.ts new file mode 100644 index 000000000..fa4e94fe5 --- /dev/null +++ b/components/_theme/useToken.ts @@ -0,0 +1,160 @@ +import type { Theme } from '../_util/_cssinjs'; +import { useCacheToken } from '../_util/_cssinjs'; + +import version from '../version'; +import type { DesignTokenProviderProps } from './context'; +import { defaultTheme, useDesignTokenInject } from './context'; +import type { AliasToken, GlobalToken, MapToken, SeedToken } from './interface'; +import defaultSeedToken from './themes/seed'; +import formatToken from './util/alias'; +import { computed } from 'vue'; +import type { ComputedRef } from 'vue'; + +export const unitless: { + [key in keyof AliasToken]?: boolean; +} = { + lineHeight: true, + lineHeightSM: true, + lineHeightLG: true, + lineHeightHeading1: true, + lineHeightHeading2: true, + lineHeightHeading3: true, + lineHeightHeading4: true, + lineHeightHeading5: true, + opacityLoading: true, + fontWeightStrong: true, + zIndexPopupBase: true, + zIndexBase: true, +}; + +export const ignore: { + [key in keyof AliasToken]?: boolean; +} = { + size: true, + sizeSM: true, + sizeLG: true, + sizeMD: true, + sizeXS: true, + sizeXXS: true, + sizeMS: true, + sizeXL: true, + sizeXXL: true, + sizeUnit: true, + sizeStep: true, + motionBase: true, + motionUnit: true, +}; + +const preserve: { + [key in keyof AliasToken]?: boolean; +} = { + screenXS: true, + screenXSMin: true, + screenXSMax: true, + screenSM: true, + screenSMMin: true, + screenSMMax: true, + screenMD: true, + screenMDMin: true, + screenMDMax: true, + screenLG: true, + screenLGMin: true, + screenLGMax: true, + screenXL: true, + screenXLMin: true, + screenXLMax: true, + screenXXL: true, + screenXXLMin: true, + screenXXLMax: true, + screenXXXL: true, + screenXXXLMin: true, +}; + +export const getComputedToken = ( + originToken: SeedToken, + overrideToken: DesignTokenProviderProps['components'] & { + override?: Partial; + }, + theme: Theme, +) => { + const derivativeToken = theme.getDerivativeToken(originToken); + + const { override, ...components } = overrideToken; + + // Merge with override + let mergedDerivativeToken = { + ...derivativeToken, + override, + }; + + // Format if needed + mergedDerivativeToken = formatToken(mergedDerivativeToken); + + if (components) { + Object.entries(components).forEach(([key, value]) => { + const { theme: componentTheme, ...componentTokens } = value; + let mergedComponentToken = componentTokens; + if (componentTheme) { + mergedComponentToken = getComputedToken( + { + ...mergedDerivativeToken, + ...componentTokens, + }, + { + override: componentTokens, + }, + componentTheme, + ); + } + mergedDerivativeToken[key] = mergedComponentToken; + }); + } + + return mergedDerivativeToken; +}; + +// ================================== Hook ================================== +export default function useToken(): [ + ComputedRef>, + ComputedRef, + ComputedRef, + ComputedRef, + ComputedRef, +] { + const designToken = useDesignTokenInject(); + + const salt = computed(() => `${version}-${designToken.value.hashed || ''}`); + + const mergedTheme = computed(() => designToken.value.theme || defaultTheme); + + const cacheToken = useCacheToken( + mergedTheme, + computed(() => [defaultSeedToken, designToken.value.token]), + computed(() => { + return { + salt: salt.value, + override: designToken.value.override, + getComputedToken, + // formatToken will not be consumed after 1.15.0 with getComputedToken. + // But token will break if @ant-design/cssinjs is under 1.15.0 without it + formatToken, + cssVar: designToken.value.cssVar && { + prefix: designToken.value.cssVar.prefix, + key: designToken.value.cssVar.key, + unitless, + ignore, + preserve, + }, + }; + }), + ); + + // cacheToken [token, hashId, realToken] + return [ + mergedTheme, + computed(() => cacheToken.value[2]), + computed(() => cacheToken.value[1]), + computed(() => cacheToken.value[0]), + computed(() => designToken.value.cssVar), + ]; +} diff --git a/components/_theme/util/alias.ts b/components/_theme/util/alias.ts new file mode 100644 index 000000000..6b8535284 --- /dev/null +++ b/components/_theme/util/alias.ts @@ -0,0 +1,207 @@ +import { TinyColor } from '@ctrl/tinycolor'; +import type { AliasToken, MapToken, OverrideToken, SeedToken } from '../interface'; +import seedToken from '../themes/seed'; +import getAlphaColor from './getAlphaColor'; + +/** Raw merge of `@ant-design/cssinjs` token. Which need additional process */ +type RawMergedToken = MapToken & OverrideToken & { override: Partial }; + +/** + * Seed (designer) > Derivative (designer) > Alias (developer). + * + * Merge seed & derivative & override token and generate alias token for developer. + */ +export default function formatToken(derivativeToken: RawMergedToken): AliasToken { + const { override, ...restToken } = derivativeToken; + const overrideTokens = { ...override }; + + Object.keys(seedToken).forEach(token => { + delete overrideTokens[token as keyof SeedToken]; + }); + + const mergedToken = { + ...restToken, + ...overrideTokens, + }; + + const screenXS = 480; + const screenSM = 576; + const screenMD = 768; + const screenLG = 992; + const screenXL = 1200; + const screenXXL = 1600; + const screenXXXL = 2000; + + // Motion + if (mergedToken.motion === false) { + const fastDuration = '0s'; + mergedToken.motionDurationFast = fastDuration; + mergedToken.motionDurationMid = fastDuration; + mergedToken.motionDurationSlow = fastDuration; + } + + // Generate alias token + const aliasToken: AliasToken = { + ...mergedToken, + + // ============== Background ============== // + colorFillContent: mergedToken.colorFillSecondary, + colorFillContentHover: mergedToken.colorFill, + colorFillAlter: mergedToken.colorFillQuaternary, + colorBgContainerDisabled: mergedToken.colorFillTertiary, + + // ============== Split ============== // + colorBorderBg: mergedToken.colorBgContainer, + colorSplit: getAlphaColor(mergedToken.colorBorderSecondary, mergedToken.colorBgContainer), + + // ============== Text ============== // + colorTextPlaceholder: mergedToken.colorTextQuaternary, + colorTextDisabled: mergedToken.colorTextQuaternary, + colorTextHeading: mergedToken.colorText, + colorTextLabel: mergedToken.colorTextSecondary, + colorTextDescription: mergedToken.colorTextTertiary, + colorTextLightSolid: mergedToken.colorWhite, + colorHighlight: mergedToken.colorError, + colorBgTextHover: mergedToken.colorFillSecondary, + colorBgTextActive: mergedToken.colorFill, + + colorIcon: mergedToken.colorTextTertiary, + colorIconHover: mergedToken.colorText, + + colorErrorOutline: getAlphaColor(mergedToken.colorErrorBg, mergedToken.colorBgContainer), + colorWarningOutline: getAlphaColor(mergedToken.colorWarningBg, mergedToken.colorBgContainer), + + // Font + fontSizeIcon: mergedToken.fontSizeSM, + + // Line + lineWidthFocus: mergedToken.lineWidth * 4, + + // Control + lineWidth: mergedToken.lineWidth, + controlOutlineWidth: mergedToken.lineWidth * 2, + // Checkbox size and expand icon size + controlInteractiveSize: mergedToken.controlHeight / 2, + + controlItemBgHover: mergedToken.colorFillTertiary, + controlItemBgActive: mergedToken.colorPrimaryBg, + controlItemBgActiveHover: mergedToken.colorPrimaryBgHover, + controlItemBgActiveDisabled: mergedToken.colorFill, + controlTmpOutline: mergedToken.colorFillQuaternary, + controlOutline: getAlphaColor(mergedToken.colorPrimaryBg, mergedToken.colorBgContainer), + + lineType: mergedToken.lineType, + borderRadius: mergedToken.borderRadius, + borderRadiusXS: mergedToken.borderRadiusXS, + borderRadiusSM: mergedToken.borderRadiusSM, + borderRadiusLG: mergedToken.borderRadiusLG, + + fontWeightStrong: 600, + + opacityLoading: 0.65, + + linkDecoration: 'none', + linkHoverDecoration: 'none', + linkFocusDecoration: 'none', + + controlPaddingHorizontal: 12, + controlPaddingHorizontalSM: 8, + + paddingXXS: mergedToken.sizeXXS, + paddingXS: mergedToken.sizeXS, + paddingSM: mergedToken.sizeSM, + padding: mergedToken.size, + paddingMD: mergedToken.sizeMD, + paddingLG: mergedToken.sizeLG, + paddingXL: mergedToken.sizeXL, + + paddingContentHorizontalLG: mergedToken.sizeLG, + paddingContentVerticalLG: mergedToken.sizeMS, + paddingContentHorizontal: mergedToken.sizeMS, + paddingContentVertical: mergedToken.sizeSM, + paddingContentHorizontalSM: mergedToken.size, + paddingContentVerticalSM: mergedToken.sizeXS, + + marginXXS: mergedToken.sizeXXS, + marginXS: mergedToken.sizeXS, + marginSM: mergedToken.sizeSM, + margin: mergedToken.size, + marginMD: mergedToken.sizeMD, + marginLG: mergedToken.sizeLG, + marginXL: mergedToken.sizeXL, + marginXXL: mergedToken.sizeXXL, + + boxShadow: ` + 0 6px 16px 0 rgba(0, 0, 0, 0.08), + 0 3px 6px -4px rgba(0, 0, 0, 0.12), + 0 9px 28px 8px rgba(0, 0, 0, 0.05) + `, + boxShadowSecondary: ` + 0 6px 16px 0 rgba(0, 0, 0, 0.08), + 0 3px 6px -4px rgba(0, 0, 0, 0.12), + 0 9px 28px 8px rgba(0, 0, 0, 0.05) + `, + boxShadowTertiary: ` + 0 1px 2px 0 rgba(0, 0, 0, 0.03), + 0 1px 6px -1px rgba(0, 0, 0, 0.02), + 0 2px 4px 0 rgba(0, 0, 0, 0.02) + `, + + screenXS, + screenXSMin: screenXS, + screenXSMax: screenSM - 1, + screenSM, + screenSMMin: screenSM, + screenSMMax: screenMD - 1, + screenMD, + screenMDMin: screenMD, + screenMDMax: screenLG - 1, + screenLG, + screenLGMin: screenLG, + screenLGMax: screenXL - 1, + screenXL, + screenXLMin: screenXL, + screenXLMax: screenXXL - 1, + screenXXL, + screenXXLMin: screenXXL, + screenXXLMax: screenXXXL - 1, + screenXXXL, + screenXXXLMin: screenXXXL, + + boxShadowPopoverArrow: '2px 2px 5px rgba(0, 0, 0, 0.05)', + boxShadowCard: ` + 0 1px 2px -2px ${new TinyColor('rgba(0, 0, 0, 0.16)').toRgbString()}, + 0 3px 6px 0 ${new TinyColor('rgba(0, 0, 0, 0.12)').toRgbString()}, + 0 5px 12px 4px ${new TinyColor('rgba(0, 0, 0, 0.09)').toRgbString()} + `, + boxShadowDrawerRight: ` + -6px 0 16px 0 rgba(0, 0, 0, 0.08), + -3px 0 6px -4px rgba(0, 0, 0, 0.12), + -9px 0 28px 8px rgba(0, 0, 0, 0.05) + `, + boxShadowDrawerLeft: ` + 6px 0 16px 0 rgba(0, 0, 0, 0.08), + 3px 0 6px -4px rgba(0, 0, 0, 0.12), + 9px 0 28px 8px rgba(0, 0, 0, 0.05) + `, + boxShadowDrawerUp: ` + 0 6px 16px 0 rgba(0, 0, 0, 0.08), + 0 3px 6px -4px rgba(0, 0, 0, 0.12), + 0 9px 28px 8px rgba(0, 0, 0, 0.05) + `, + boxShadowDrawerDown: ` + 0 -6px 16px 0 rgba(0, 0, 0, 0.08), + 0 -3px 6px -4px rgba(0, 0, 0, 0.12), + 0 -9px 28px 8px rgba(0, 0, 0, 0.05) + `, + boxShadowTabsOverflowLeft: 'inset 10px 0 8px -8px rgba(0, 0, 0, 0.08)', + boxShadowTabsOverflowRight: 'inset -10px 0 8px -8px rgba(0, 0, 0, 0.08)', + boxShadowTabsOverflowTop: 'inset 0 10px 8px -8px rgba(0, 0, 0, 0.08)', + boxShadowTabsOverflowBottom: 'inset 0 -10px 8px -8px rgba(0, 0, 0, 0.08)', + + // Override AliasToken + ...overrideTokens, + }; + + return aliasToken; +} diff --git a/components/_theme/util/calc/CSSCalculator.ts b/components/_theme/util/calc/CSSCalculator.ts new file mode 100644 index 000000000..b1c472596 --- /dev/null +++ b/components/_theme/util/calc/CSSCalculator.ts @@ -0,0 +1,87 @@ +import AbstractCalculator from './calculator'; + +const CALC_UNIT = 'CALC_UNIT'; + +function unit(value: string | number) { + if (typeof value === 'number') { + return `${value}${CALC_UNIT}`; + } + return value; +} + +export default class CSSCalculator extends AbstractCalculator { + result = ''; + + lowPriority?: boolean; + + constructor(num: number | string | AbstractCalculator) { + super(); + if (num instanceof CSSCalculator) { + this.result = `(${num.result})`; + } else if (typeof num === 'number') { + this.result = unit(num); + } else if (typeof num === 'string') { + this.result = num; + } + } + + add(num: number | string | AbstractCalculator): this { + if (num instanceof CSSCalculator) { + this.result = `${this.result} + ${num.getResult()}`; + } else if (typeof num === 'number' || typeof num === 'string') { + this.result = `${this.result} + ${unit(num)}`; + } + this.lowPriority = true; + return this; + } + + sub(num: number | string | AbstractCalculator): this { + if (num instanceof CSSCalculator) { + this.result = `${this.result} - ${num.getResult()}`; + } else if (typeof num === 'number' || typeof num === 'string') { + this.result = `${this.result} - ${unit(num)}`; + } + this.lowPriority = true; + return this; + } + + mul(num: number | string | AbstractCalculator): this { + if (this.lowPriority) { + this.result = `(${this.result})`; + } + if (num instanceof CSSCalculator) { + this.result = `${this.result} * ${num.getResult(true)}`; + } else if (typeof num === 'number' || typeof num === 'string') { + this.result = `${this.result} * ${num}`; + } + this.lowPriority = false; + return this; + } + + div(num: number | string | AbstractCalculator): this { + if (this.lowPriority) { + this.result = `(${this.result})`; + } + if (num instanceof CSSCalculator) { + this.result = `${this.result} / ${num.getResult(true)}`; + } else if (typeof num === 'number' || typeof num === 'string') { + this.result = `${this.result} / ${num}`; + } + this.lowPriority = false; + return this; + } + + getResult(force?: boolean): string { + return this.lowPriority || force ? `(${this.result})` : this.result; + } + + equal(options?: { unit?: boolean }): string { + const { unit: cssUnit = true } = options || {}; + const regexp = new RegExp(`${CALC_UNIT}`, 'g'); + this.result = this.result.replace(regexp, cssUnit ? 'px' : ''); + if (typeof this.lowPriority !== 'undefined') { + return `calc(${this.result})`; + } + return this.result; + } +} diff --git a/components/_theme/util/calc/NumCalculator.ts b/components/_theme/util/calc/NumCalculator.ts new file mode 100644 index 000000000..5e845e5f5 --- /dev/null +++ b/components/_theme/util/calc/NumCalculator.ts @@ -0,0 +1,54 @@ +import AbstractCalculator from './calculator'; + +export default class NumCalculator extends AbstractCalculator { + result = 0; + + constructor(num: number | string | AbstractCalculator) { + super(); + if (num instanceof NumCalculator) { + this.result = num.result; + } else if (typeof num === 'number') { + this.result = num; + } + } + + add(num: number | string | AbstractCalculator): this { + if (num instanceof NumCalculator) { + this.result += num.result; + } else if (typeof num === 'number') { + this.result += num; + } + return this; + } + + sub(num: number | string | AbstractCalculator): this { + if (num instanceof NumCalculator) { + this.result -= num.result; + } else if (typeof num === 'number') { + this.result -= num; + } + return this; + } + + mul(num: number | string | AbstractCalculator): this { + if (num instanceof NumCalculator) { + this.result *= num.result; + } else if (typeof num === 'number') { + this.result *= num; + } + return this; + } + + div(num: number | string | AbstractCalculator): this { + if (num instanceof NumCalculator) { + this.result /= num.result; + } else if (typeof num === 'number') { + this.result /= num; + } + return this; + } + + equal(): number { + return this.result; + } +} diff --git a/components/_theme/util/calc/calculator.ts b/components/_theme/util/calc/calculator.ts new file mode 100644 index 000000000..cfd19ab5d --- /dev/null +++ b/components/_theme/util/calc/calculator.ts @@ -0,0 +1,33 @@ +abstract class AbstractCalculator { + /** + * @descCN 计算两数的和,例如:1 + 2 + * @descEN Calculate the sum of two numbers, e.g. 1 + 2 + */ + abstract add(num: number | string | AbstractCalculator): this; + + /** + * @descCN 计算两数的差,例如:1 - 2 + * @descEN Calculate the difference between two numbers, e.g. 1 - 2 + */ + abstract sub(num: number | string | AbstractCalculator): this; + + /** + * @descCN 计算两数的积,例如:1 * 2 + * @descEN Calculate the product of two numbers, e.g. 1 * 2 + */ + abstract mul(num: number | string | AbstractCalculator): this; + + /** + * @descCN 计算两数的商,例如:1 / 2 + * @descEN Calculate the quotient of two numbers, e.g. 1 / 2 + */ + abstract div(num: number | string | AbstractCalculator): this; + + /** + * @descCN 获取计算结果 + * @descEN Get the calculation result + */ + abstract equal(options?: { unit?: boolean }): string | number; +} + +export default AbstractCalculator; diff --git a/components/_theme/util/calc/index.ts b/components/_theme/util/calc/index.ts new file mode 100644 index 000000000..1a1286d20 --- /dev/null +++ b/components/_theme/util/calc/index.ts @@ -0,0 +1,11 @@ +import NumCalculator from './NumCalculator'; +import CSSCalculator from './CSSCalculator'; +import type AbstractCalculator from './calculator'; + +const genCalc = (type: 'css' | 'js') => { + const Calculator = type === 'css' ? CSSCalculator : NumCalculator; + + return (num: number | string | AbstractCalculator) => new Calculator(num); +}; + +export default genCalc; diff --git a/components/_theme/util/genComponentStyleHook.ts b/components/_theme/util/genComponentStyleHook.ts new file mode 100644 index 000000000..540a6a475 --- /dev/null +++ b/components/_theme/util/genComponentStyleHook.ts @@ -0,0 +1,458 @@ +/* eslint-disable no-redeclare */ +import type { CSSInterpolation, CSSObject } from '../../_util/_cssinjs'; +import { token2CSSVar, useCSSVarRegister, useStyleRegister } from '../../_util/_cssinjs'; +import warning from '../../_util/warning'; +import { genCommonStyle, genLinkStyle } from '../../style'; +import type { + AliasToken, + ComponentTokenMap, + GlobalToken, + OverrideToken, + UseComponentStyleResult, +} from '../interface'; +import useToken, { ignore, unitless } from '../useToken'; +import genCalc from './calc'; +import type AbstractCalculator from './calc/calculator'; +import genMaxMin from './maxmin'; +import statisticToken, { merge as mergeToken } from './statistic'; +import useResetIconStyle from './useResetIconStyle'; + +import type { Ref } from 'vue'; +import { defineComponent, computed, createVNode, Fragment } from 'vue'; +import { useConfigContextInject } from '../../config-provider/context'; +import type { VueNode } from 'ant-design-vue/es/_util/type'; +import { objectType } from 'ant-design-vue/es/_util/type'; + +export type OverrideTokenWithoutDerivative = ComponentTokenMap; +export type OverrideComponent = keyof OverrideTokenWithoutDerivative; +export type GlobalTokenWithComponent = GlobalToken & + ComponentTokenMap[C]; + +type ComponentToken = Exclude; +type ComponentTokenKey = keyof ComponentToken; + +export interface StyleInfo { + hashId: string; + prefixCls: string; + rootPrefixCls: string; + iconPrefixCls: string; +} + +export type CSSUtil = { + calc: (number: any) => AbstractCalculator; + max: (...values: (number | string)[]) => number | string; + min: (...values: (number | string)[]) => number | string; +}; + +export type TokenWithCommonCls = T & { + /** Wrap component class with `.` prefix */ + componentCls: string; + /** Origin prefix which do not have `.` prefix */ + prefixCls: string; + /** Wrap icon class with `.` prefix */ + iconCls: string; + /** Wrap ant prefixCls class with `.` prefix */ + antCls: string; +} & CSSUtil; + +export type FullToken = TokenWithCommonCls< + GlobalTokenWithComponent +>; + +export type GenStyleFn = ( + token: FullToken, + info: StyleInfo, +) => CSSInterpolation; + +export type GetDefaultToken = + | null + | OverrideTokenWithoutDerivative[C] + | (( + token: AliasToken & Partial, + ) => OverrideTokenWithoutDerivative[C]); + +const getDefaultComponentToken = ( + component: C, + token: Ref, + getDefaultToken: GetDefaultToken, +) => { + if (typeof getDefaultToken === 'function') { + return getDefaultToken(mergeToken(token.value, token.value[component] ?? {})); + } + return getDefaultToken ?? {}; +}; + +const getComponentToken = ( + component: C, + token: Ref, + defaultToken: OverrideTokenWithoutDerivative[C], + options?: { + deprecatedTokens?: [ComponentTokenKey, ComponentTokenKey][]; + }, +) => { + const customToken = { ...(token.value[component] as ComponentToken) }; + if (options?.deprecatedTokens) { + const { deprecatedTokens } = options; + deprecatedTokens.forEach(([oldTokenKey, newTokenKey]) => { + if (process.env.NODE_ENV !== 'production') { + warning( + !customToken?.[oldTokenKey], + `Component Token \`${String( + oldTokenKey, + )}\` of ${component} is deprecated. Please use \`${String(newTokenKey)}\` instead.`, + ); + } + + // Should wrap with `if` clause, or there will be `undefined` in object. + if (customToken?.[oldTokenKey] || customToken?.[newTokenKey]) { + customToken[newTokenKey] ??= customToken?.[oldTokenKey]; + } + }); + } + const mergedToken: any = { ...defaultToken, ...customToken }; + + // Remove same value as global token to minimize size + Object.keys(mergedToken).forEach(key => { + if (mergedToken[key] === token[key as keyof GlobalToken]) { + delete mergedToken[key]; + } + }); + + return mergedToken; +}; + +const getCompVarPrefix = (component: string, prefix?: string) => + `${[ + prefix, + component.replace(/([A-Z]+)([A-Z][a-z]+)/g, '$1-$2').replace(/([a-z])([A-Z])/g, '$1-$2'), + ] + .filter(Boolean) + .join('-')}`; + +export default function genComponentStyleHook( + componentName: C | [C, string], + styleFn: GenStyleFn, + getDefaultToken?: GetDefaultToken, + options: { + resetStyle?: boolean; + // Deprecated token key map [["oldTokenKey", "newTokenKey"], ["oldTokenKey", "newTokenKey"]] + deprecatedTokens?: [ComponentTokenKey, ComponentTokenKey][]; + /** + * Only use component style in client side. Ignore in SSR. + */ + clientOnly?: boolean; + /** + * Set order of component style. Default is -999. + */ + order?: number; + injectStyle?: boolean; + } = {}, +) { + const cells = (Array.isArray(componentName) ? componentName : [componentName, componentName]) as [ + C, + string, + ]; + + const [component] = cells; + const concatComponent = cells.join('-'); + + return (_prefixCls?: Ref): UseComponentStyleResult => { + const prefixCls = computed(() => _prefixCls?.value); + const [theme, realToken, hashId, token, cssVar] = useToken(); + const { getPrefixCls, iconPrefixCls, csp } = useConfigContextInject(); + + const rootPrefixCls = computed(() => getPrefixCls()); + + const type = computed(() => (cssVar.value ? 'css' : 'js')); + const calc = computed(() => genCalc(type.value)); + const maxMin = computed(() => genMaxMin(type.value)); + + // Shared config + // const sharedConfig: Omit[0], 'path'> = { + // theme: theme.value, + // token: token.value, + // hashId: hashId.value, + // nonce: () => csp.value?.nonce!, + // clientOnly: options.clientOnly, + + // // antd is always at top of styles + // order: options.order || -999, + // }; + + const sharedConfig = computed(() => { + return { + theme: theme.value, + token: token.value, + hashId: hashId.value, + nonce: () => csp.value && csp.value.nonce, + clientOnly: options.clientOnly, + + // antd is always at top of styles + order: options.order || -999, + }; + }); + + // Generate style for all a tags in antd component. + useStyleRegister( + computed(() => ({ + ...sharedConfig.value, + clientOnly: false, + path: ['Shared', rootPrefixCls.value], + })), + () => + [ + { + // Link + '&': genLinkStyle(token.value), + }, + ] as CSSObject[], + ); + + // Generate style for icons + useResetIconStyle(iconPrefixCls, csp); + + const wrapSSR = useStyleRegister( + computed(() => ({ + ...sharedConfig.value, + path: [concatComponent, prefixCls.value, iconPrefixCls.value], + })), + () => { + if (options.injectStyle === false) { + return []; + } + + const { token: proxyToken, flush } = statisticToken(token.value); + + const defaultComponentToken = getDefaultComponentToken( + component, + realToken, + getDefaultToken, + ); + + const componentCls = `.${prefixCls.value}`; + const componentToken = getComponentToken(component, realToken, defaultComponentToken, { + deprecatedTokens: options.deprecatedTokens, + }); + + if (cssVar.value) { + Object.keys(defaultComponentToken).forEach(key => { + defaultComponentToken[key] = `var(${token2CSSVar( + key, + getCompVarPrefix(component, cssVar.value?.prefix), + )})`; + }); + } + const mergedToken = mergeToken< + TokenWithCommonCls> + >( + proxyToken, + { + componentCls, + prefixCls: prefixCls.value, + iconCls: `.${iconPrefixCls.value}`, + antCls: `.${rootPrefixCls.value}`, + calc: calc.value, + max: maxMin.value.max, + min: maxMin.value.min, + }, + cssVar.value ? defaultComponentToken : componentToken, + ); + + const styleInterpolation = styleFn(mergedToken as unknown as FullToken, { + hashId: hashId.value, + prefixCls: prefixCls.value, + rootPrefixCls: rootPrefixCls.value, + iconPrefixCls: iconPrefixCls.value, + }); + flush(component, componentToken); + return [ + options.resetStyle === false ? null : genCommonStyle(mergedToken, prefixCls.value), + styleInterpolation, + ] as CSSObject[]; + }, + ); + + return [wrapSSR, hashId]; + }; +} + +export interface SubStyleComponentProps { + prefixCls: Ref; +} + +// Get from second argument +type RestParameters = T extends [any, ...infer Rest] ? Rest : never; + +export const genSubStyleComponent: ( + componentName: [C, string], + ...args: RestParameters>> +) => any = (componentName, styleFn, getDefaultToken, options) => { + const useStyle = genComponentStyleHook(componentName, styleFn, getDefaultToken, { + resetStyle: false, + + // Sub Style should default after root one + order: -998, + ...options, + }); + + const StyledComponent = defineComponent({ + props: { + prefixCls: String, + }, + setup(props) { + const prefixCls = computed(() => props.prefixCls); + useStyle(prefixCls); + return () => { + return null; + }; + }, + }); + + return StyledComponent; +}; + +export type CSSVarRegisterProps = { + rootCls: string; + component: string; + cssVar: { + prefix?: string; + key?: string; + }; +}; + +const genCSSVarRegister = ( + component: C, + getDefaultToken?: GetDefaultToken, + options?: { + unitless?: { + [key in ComponentTokenKey]: boolean; + }; + deprecatedTokens?: [ComponentTokenKey, ComponentTokenKey][]; + + injectStyle?: boolean; + }, +) => { + function prefixToken(key: string) { + return `${component}${key.slice(0, 1).toUpperCase()}${key.slice(1)}`; + } + + const { unitless: originUnitless = {}, injectStyle = true } = options ?? {}; + const compUnitless: any = { + [prefixToken('zIndexPopup')]: true, + }; + Object.keys(originUnitless).forEach((key: keyof ComponentTokenKey) => { + compUnitless[prefixToken(key)] = originUnitless[key]; + }); + + const CSSVarRegister = defineComponent({ + props: { + rootCls: String, + component: String, + cssVar: objectType<{ + prefix: string; + key: string; + }>(), + }, + setup(props) { + const [, realToken] = useToken(); + + useCSSVarRegister( + computed(() => { + return { + path: [props.component], + prefix: props.cssVar.prefix, + key: props.cssVar.key!, + unitless: { + ...unitless, + ...compUnitless, + }, + ignore, + token: realToken.value, + scope: props.rootCls, + }; + }), + () => { + const defaultToken = getDefaultComponentToken(component, realToken, getDefaultToken); + const componentToken = getComponentToken(component, realToken, defaultToken, { + deprecatedTokens: options?.deprecatedTokens, + }); + Object.keys(defaultToken).forEach(key => { + componentToken[prefixToken(key)] = componentToken[key]; + delete componentToken[key]; + }); + return componentToken; + }, + ); + + return () => { + return null; + }; + }, + }); + + const useCSSVar = (rootCls: Ref) => { + const [, , , , cssVar] = useToken(); + + return [ + (node: VueNode): VueNode => + injectStyle && cssVar.value + ? createVNode(Fragment, null, [ + createVNode(CSSVarRegister, { + rootCls: rootCls.value, + cssVar: cssVar.value, + component, + }), + node, + ]) + : node, + computed(() => cssVar.value?.key), + ] as const; + }; + + return useCSSVar; +}; + +export const genStyleHooks = ( + component: C | [C, string], + styleFn: GenStyleFn, + getDefaultToken?: GetDefaultToken, + options?: { + resetStyle?: boolean; + deprecatedTokens?: [ComponentTokenKey, ComponentTokenKey][]; + /** + * Component tokens that do not need unit. + */ + unitless?: { + [key in ComponentTokenKey]: boolean; + }; + /** + * Only use component style in client side. Ignore in SSR. + */ + clientOnly?: boolean; + /** + * Set order of component style. + * @default -999 + */ + order?: number; + /** + * Whether generate styles + * @default true + */ + injectStyle?: boolean; + }, +) => { + const useStyle = genComponentStyleHook(component, styleFn, getDefaultToken, options); + + const useCSSVar = genCSSVarRegister( + Array.isArray(component) ? component[0] : component, + getDefaultToken, + options, + ); + + return (prefixCls: Ref, rootCls: Ref = prefixCls) => { + const [, hashId] = useStyle(prefixCls); + const [wrapCSSVar, cssVarCls] = useCSSVar(rootCls); + + return [wrapCSSVar, hashId, cssVarCls] as const; + }; +}; diff --git a/components/_theme/util/genPresetColor.ts b/components/_theme/util/genPresetColor.ts new file mode 100644 index 000000000..b5383f73c --- /dev/null +++ b/components/_theme/util/genPresetColor.ts @@ -0,0 +1,35 @@ +/* eslint-disable import/prefer-default-export */ +import type { CSSObject } from '../../_util/_cssinjs'; +import type { AliasToken, PresetColorKey } from '../internal'; +import { PresetColors } from '../interface'; +import type { TokenWithCommonCls } from './genComponentStyleHook'; + +interface CalcColor { + /** token[`${colorKey}-1`] */ + lightColor: string; + /** token[`${colorKey}-3`] */ + lightBorderColor: string; + /** token[`${colorKey}-6`] */ + darkColor: string; + /** token[`${colorKey}-7`] */ + textColor: string; +} + +type GenCSS = (colorKey: PresetColorKey, calcColor: CalcColor) => CSSObject; + +export default function genPresetColor>( + token: Token, + genCss: GenCSS, +): CSSObject { + return PresetColors.reduce((prev: CSSObject, colorKey: PresetColorKey) => { + const lightColor = token[`${colorKey}1`]; + const lightBorderColor = token[`${colorKey}3`]; + const darkColor = token[`${colorKey}6`]; + const textColor = token[`${colorKey}7`]; + + return { + ...prev, + ...genCss(colorKey, { lightColor, lightBorderColor, darkColor, textColor }), + }; + }, {} as CSSObject); +} diff --git a/components/_theme/util/getAlphaColor.ts b/components/_theme/util/getAlphaColor.ts new file mode 100644 index 000000000..7cd1d3fdb --- /dev/null +++ b/components/_theme/util/getAlphaColor.ts @@ -0,0 +1,29 @@ +import { TinyColor } from '@ctrl/tinycolor'; + +function isStableColor(color: number): boolean { + return color >= 0 && color <= 255; +} + +function getAlphaColor(frontColor: string, backgroundColor: string): string { + const { r: fR, g: fG, b: fB, a: originAlpha } = new TinyColor(frontColor).toRgb(); + if (originAlpha < 1) { + return frontColor; + } + + const { r: bR, g: bG, b: bB } = new TinyColor(backgroundColor).toRgb(); + + for (let fA = 0.01; fA <= 1; fA += 0.01) { + const r = Math.round((fR - bR * (1 - fA)) / fA); + const g = Math.round((fG - bG * (1 - fA)) / fA); + const b = Math.round((fB - bB * (1 - fA)) / fA); + if (isStableColor(r) && isStableColor(g) && isStableColor(b)) { + return new TinyColor({ r, g, b, a: Math.round(fA * 100) / 100 }).toRgbString(); + } + } + + // fallback + /* istanbul ignore next */ + return new TinyColor({ r: fR, g: fG, b: fB, a: 1 }).toRgbString(); +} + +export default getAlphaColor; diff --git a/components/_theme/util/maxmin.ts b/components/_theme/util/maxmin.ts new file mode 100644 index 000000000..13d07e8ba --- /dev/null +++ b/components/_theme/util/maxmin.ts @@ -0,0 +1,14 @@ +import { unit } from '../../_util/_cssinjs'; + +export default function genMaxMin(type: 'css' | 'js') { + if (type === 'js') { + return { + max: Math.max, + min: Math.min, + }; + } + return { + max: (...args: (string | number)[]) => `max(${args.map(value => unit(value)).join(',')})`, + min: (...args: (string | number)[]) => `min(${args.map(value => unit(value)).join(',')})`, + }; +} diff --git a/components/_theme/util/statistic.ts b/components/_theme/util/statistic.ts new file mode 100644 index 000000000..2b29ebacd --- /dev/null +++ b/components/_theme/util/statistic.ts @@ -0,0 +1,85 @@ +import type { AnyObject } from '../../_util/type'; + +declare const CSSINJS_STATISTIC: any; + +const enableStatistic = + process.env.NODE_ENV !== 'production' || typeof CSSINJS_STATISTIC !== 'undefined'; +let recording = true; + +/** + * This function will do as `Object.assign` in production. But will use Object.defineProperty:get to + * pass all value access in development. To support statistic field usage with alias token. + */ +export function merge(...objs: Partial[]): T { + /* istanbul ignore next */ + if (!enableStatistic) { + return Object.assign({}, ...objs); + } + + recording = false; + + const ret = {} as T; + + objs.forEach(obj => { + const keys = Object.keys(obj); + + keys.forEach(key => { + Object.defineProperty(ret, key, { + configurable: true, + enumerable: true, + get: () => (obj as any)[key], + }); + }); + }); + + recording = true; + return ret; +} + +/** @internal Internal Usage. Not use in your production. */ +export const statistic: Record< + string, + { global: string[]; component: Record } +> = {}; + +/** @internal Internal Usage. Not use in your production. */ +// eslint-disable-next-line camelcase +export const _statistic_build_: typeof statistic = {}; + +/* istanbul ignore next */ +function noop() {} + +/** Statistic token usage case. Should use `merge` function if you do not want spread record. */ +const statisticToken = (token: T) => { + let tokenKeys: Set | undefined; + let proxy = token; + let flush: (componentName: string, componentToken: Record) => void = + noop; + + if (enableStatistic && typeof Proxy !== 'undefined') { + tokenKeys = new Set(); + + proxy = new Proxy(token, { + get(obj: any, prop: any) { + if (recording) { + tokenKeys!.add(prop); + } + return obj[prop]; + }, + }); + + flush = (componentName, componentToken) => { + statistic[componentName] = { + global: Array.from(tokenKeys!), + component: { + ...statistic[componentName]?.component, + ...componentToken, + }, + }; + }; + } + + return { token: proxy, keys: tokenKeys, flush }; +}; + +export default statisticToken; diff --git a/components/_theme/util/useResetIconStyle.ts b/components/_theme/util/useResetIconStyle.ts new file mode 100644 index 000000000..6ff3c698a --- /dev/null +++ b/components/_theme/util/useResetIconStyle.ts @@ -0,0 +1,35 @@ +import type { CSSObject } from '../../_util/_cssinjs'; +import { useStyleRegister } from '../../_util/_cssinjs'; +import { resetIcon } from '../../style'; +import type { CSPConfig } from '../../config-provider'; +import useToken from '../useToken'; +import type { Ref } from 'vue'; +import { computed } from 'vue'; + +const useResetIconStyle = (iconPrefixCls: Ref, csp?: Ref) => { + const [theme, token] = useToken(); + + // Generate style for icons + return useStyleRegister( + computed(() => ({ + theme: theme.value, + token, + hashId: '', + path: ['ant-design-icons', iconPrefixCls.value], + nonce: () => csp.value && csp.value.nonce, + })), + () => + [ + { + [`.${iconPrefixCls}`]: { + ...resetIcon(), + [`.${iconPrefixCls} .${iconPrefixCls}-icon`]: { + display: 'block', + }, + }, + }, + ] as CSSObject[], + ); +}; + +export default useResetIconStyle; diff --git a/components/_util/_cssinjs/Cache.ts b/components/_util/_cssinjs/Cache.ts new file mode 100644 index 000000000..cff14b475 --- /dev/null +++ b/components/_util/_cssinjs/Cache.ts @@ -0,0 +1,32 @@ +export type KeyType = string | number; +type ValueType = [number, any]; // [times, realValue] + +const SPLIT = '%'; + +class Entity { + instanceId: string; + constructor(instanceId: string) { + this.instanceId = instanceId; + } + + /** @private Internal cache map. Do not access this directly */ + cache = new Map(); + + get(keys: KeyType[] | string): ValueType | null { + return this.cache.get(Array.isArray(keys) ? keys.join(SPLIT) : keys) || null; + } + + update(keys: KeyType[] | string, valueFn: (origin: ValueType | null) => ValueType | null) { + const path = Array.isArray(keys) ? keys.join(SPLIT) : keys; + const prevValue = this.cache.get(path)!; + const nextValue = valueFn(prevValue); + + if (nextValue === null) { + this.cache.delete(path); + } else { + this.cache.set(path, nextValue); + } + } +} + +export default Entity; diff --git a/components/_util/_cssinjs/Keyframes.ts b/components/_util/_cssinjs/Keyframes.ts new file mode 100644 index 000000000..64b99e27c --- /dev/null +++ b/components/_util/_cssinjs/Keyframes.ts @@ -0,0 +1,19 @@ +import type { CSSInterpolation } from './hooks/useStyleRegister'; + +class Keyframe { + private name: string; + style: CSSInterpolation; + + constructor(name: string, style: CSSInterpolation) { + this.name = name; + this.style = style; + } + + getName(hashId = ''): string { + return hashId ? `${hashId}-${this.name}` : this.name; + } + + _keyframe = true; +} + +export default Keyframe; diff --git a/components/_util/_cssinjs/StyleContext.tsx b/components/_util/_cssinjs/StyleContext.tsx new file mode 100644 index 000000000..6d062eece --- /dev/null +++ b/components/_util/_cssinjs/StyleContext.tsx @@ -0,0 +1,194 @@ +import type { ShallowRef, ExtractPropTypes, InjectionKey, Ref } from 'vue'; +import { + provide, + defineComponent, + unref, + inject, + watch, + shallowRef, + getCurrentInstance, +} from 'vue'; +import CacheEntity from './Cache'; +import type { Linter } from './linters/interface'; +import type { Transformer } from './transformers/interface'; +import { arrayType, booleanType, objectType, someType, stringType, withInstall } from '../type'; +export const ATTR_TOKEN = 'data-token-hash'; +export const ATTR_MARK = 'data-css-hash'; +export const ATTR_CACHE_PATH = 'data-cache-path'; + +// Mark css-in-js instance in style element +export const CSS_IN_JS_INSTANCE = '__cssinjs_instance__'; + +export function createCache() { + const cssinjsInstanceId = Math.random().toString(12).slice(2); + + // Tricky SSR: Move all inline style to the head. + // PS: We do not recommend tricky mode. + if (typeof document !== 'undefined' && document.head && document.body) { + const styles = document.body.querySelectorAll(`style[${ATTR_MARK}]`) || []; + const { firstChild } = document.head; + + Array.from(styles).forEach(style => { + (style as any)[CSS_IN_JS_INSTANCE] = (style as any)[CSS_IN_JS_INSTANCE] || cssinjsInstanceId; + + // Not force move if no head + if ((style as any)[CSS_IN_JS_INSTANCE] === cssinjsInstanceId) { + document.head.insertBefore(style, firstChild); + } + }); + + // Deduplicate of moved styles + const styleHash: Record = {}; + Array.from(document.querySelectorAll(`style[${ATTR_MARK}]`)).forEach(style => { + const hash = style.getAttribute(ATTR_MARK)!; + if (styleHash[hash]) { + if ((style as any)[CSS_IN_JS_INSTANCE] === cssinjsInstanceId) { + style.parentNode?.removeChild(style); + } + } else { + styleHash[hash] = true; + } + }); + } + + return new CacheEntity(cssinjsInstanceId); +} + +export type HashPriority = 'low' | 'high'; + +export interface StyleContextProps { + autoClear?: boolean; + /** @private Test only. Not work in production. */ + mock?: 'server' | 'client'; + /** + * Only set when you need ssr to extract style on you own. + * If not provided, it will auto create `; +} diff --git a/components/_util/hooks/useLayoutEffect.ts b/components/_util/hooks/useLayoutEffect.ts new file mode 100644 index 000000000..6f17aedaa --- /dev/null +++ b/components/_util/hooks/useLayoutEffect.ts @@ -0,0 +1,48 @@ +import type { Ref, ShallowRef } from 'vue'; + +import { shallowRef, ref, watch, nextTick, onMounted, onUnmounted } from 'vue'; + +function useLayoutEffect( + fn: (mount: boolean) => void | VoidFunction, + deps?: Ref | Ref[] | ShallowRef | ShallowRef[], +) { + const firstMount = shallowRef(true); + const cleanupFn = ref(null); + let stopWatch = null; + + stopWatch = watch( + deps, + () => { + nextTick(() => { + if (cleanupFn.value) { + cleanupFn.value(); + } + cleanupFn.value = fn(firstMount.value); + }); + }, + { immediate: true, flush: 'post' }, + ); + + onMounted(() => { + firstMount.value = false; + }); + + onUnmounted(() => { + if (cleanupFn.value) { + cleanupFn.value(); + } + if (stopWatch) { + stopWatch(); + } + }); +} + +export const useLayoutUpdateEffect = (callback, deps) => { + useLayoutEffect(firstMount => { + if (!firstMount) { + return callback(); + } + }, deps); +}; + +export default useLayoutEffect; diff --git a/components/affix/style/index.ts b/components/affix/style/index.ts index c33c3176e..f97731ae5 100644 --- a/components/affix/style/index.ts +++ b/components/affix/style/index.ts @@ -2,6 +2,8 @@ import type { CSSObject } from '../../_util/cssinjs'; import type { FullToken, GenerateStyle } from '../../theme/internal'; import { genComponentStyleHook, mergeToken } from '../../theme/internal'; +export interface ComponentToken {} + interface AffixToken extends FullToken<'Affix'> { zIndexPopup: number; } diff --git a/components/badge/style/index.ts b/components/badge/style/index.ts index 7589799b6..aa7e1a2ef 100644 --- a/components/badge/style/index.ts +++ b/components/badge/style/index.ts @@ -4,6 +4,8 @@ import type { FullToken, GenerateStyle } from '../../theme/internal'; import { genComponentStyleHook, mergeToken } from '../../theme/internal'; import { genPresetColor, resetComponent } from '../../style'; +export interface ComponentToken {} + interface BadgeToken extends FullToken<'Badge'> { badgeFontHeight: number; badgeZIndex: number | string; diff --git a/components/breadcrumb/style/index.ts b/components/breadcrumb/style/index.ts index 9d3b24d9c..d19010fba 100644 --- a/components/breadcrumb/style/index.ts +++ b/components/breadcrumb/style/index.ts @@ -3,6 +3,8 @@ import type { FullToken, GenerateStyle } from '../../theme/internal'; import { genComponentStyleHook, mergeToken } from '../../theme/internal'; import { genFocusStyle, resetComponent } from '../../style'; +export interface ComponentToken {} + interface BreadcrumbToken extends FullToken<'Breadcrumb'> { breadcrumbBaseColor: string; breadcrumbFontSize: number; diff --git a/components/button/button-group.tsx b/components/button/button-group.tsx index 140338265..a97f14ad9 100644 --- a/components/button/button-group.tsx +++ b/components/button/button-group.tsx @@ -45,7 +45,11 @@ export default defineComponent({ break; default: // eslint-disable-next-line no-console - devWarning(!size, 'Button.Group', 'Invalid prop `size`.'); + devWarning( + !size || ['large', 'small', 'middle'].includes(size), + 'Button.Group', + 'Invalid prop `size`.', + ); } return { [`${prefixCls.value}`]: true, diff --git a/components/button/button.tsx b/components/button/button.tsx index 32fdf9e21..e71f27805 100644 --- a/components/button/button.tsx +++ b/components/button/button.tsx @@ -45,7 +45,7 @@ export default defineComponent({ // emits: ['click', 'mousedown'], setup(props, { slots, attrs, emit, expose }) { const { prefixCls, autoInsertSpaceInButton, direction, size } = useConfigInject('btn', props); - const [wrapSSR, hashId] = useStyle(prefixCls); + const [wrapCSSVar, hashId, cssVarCls] = useStyle(prefixCls); const groupSizeContext = GroupSizeContext.useInject(); const disabledContext = useInjectDisabled(); const mergedDisabled = computed(() => props.disabled ?? disabledContext.value); @@ -95,6 +95,7 @@ export default defineComponent({ compactItemClassnames.value, { [hashId.value]: true, + [cssVarCls.value]: true, [`${pre}`]: true, [`${pre}-${shape}`]: shape !== 'default' && shape, [`${pre}-${type}`]: type, @@ -216,7 +217,7 @@ export default defineComponent({ ); if (href !== undefined) { - return wrapSSR( + return wrapCSSVar( {iconNode} {kids} @@ -239,7 +240,7 @@ export default defineComponent({ ); } - return wrapSSR(buttonNode); + return wrapCSSVar(buttonNode); }; }, }); diff --git a/components/button/style/compactCmp.ts b/components/button/style/compactCmp.ts new file mode 100644 index 000000000..1fb4dd9ef --- /dev/null +++ b/components/button/style/compactCmp.ts @@ -0,0 +1,72 @@ +// Style as inline component +import type { ButtonToken } from './token'; +import { prepareComponentToken, prepareToken } from './token'; +import { genCompactItemStyle } from '../../style/compact-item'; +import { genCompactItemVerticalStyle } from '../../style/compact-item-vertical'; +import type { GenerateStyle } from '../../_theme/internal'; +import { genSubStyleComponent } from '../../_theme/internal'; +import type { CSSObject } from '../../_util/_cssinjs'; +import { unit } from '../../_util/_cssinjs'; + +const genButtonCompactStyle: GenerateStyle = token => { + const { componentCls, calc } = token; + + return { + [componentCls]: { + // Special styles for Primary Button + [`&-compact-item${componentCls}-primary`]: { + [`&:not([disabled]) + ${componentCls}-compact-item${componentCls}-primary:not([disabled])`]: + { + position: 'relative', + + '&:before': { + position: 'absolute', + top: calc(token.lineWidth).mul(-1).equal(), + insetInlineStart: calc(token.lineWidth).mul(-1).equal(), + display: 'inline-block', + width: token.lineWidth, + height: `calc(100% + ${unit(token.lineWidth)} * 2)`, + backgroundColor: token.colorPrimaryHover, + content: '""', + }, + }, + }, + // Special styles for Primary Button + '&-compact-vertical-item': { + [`&${componentCls}-primary`]: { + [`&:not([disabled]) + ${componentCls}-compact-vertical-item${componentCls}-primary:not([disabled])`]: + { + position: 'relative', + + '&:before': { + position: 'absolute', + top: calc(token.lineWidth).mul(-1).equal(), + insetInlineStart: calc(token.lineWidth).mul(-1).equal(), + display: 'inline-block', + width: `calc(100% + ${unit(token.lineWidth)} * 2)`, + height: token.lineWidth, + backgroundColor: token.colorPrimaryHover, + content: '""', + }, + }, + }, + }, + }, + }; +}; + +// ============================== Export ============================== +export default genSubStyleComponent( + ['Button', 'compact'], + token => { + const buttonToken = prepareToken(token); + + return [ + // Space Compact + genCompactItemStyle(buttonToken), + genCompactItemVerticalStyle(buttonToken), + genButtonCompactStyle(buttonToken), + ] as CSSObject[]; + }, + prepareComponentToken, +); diff --git a/components/button/style/group.ts b/components/button/style/group.ts index 0bc094bc6..82d036eca 100644 --- a/components/button/style/group.ts +++ b/components/button/style/group.ts @@ -1,5 +1,6 @@ -import type { ButtonToken } from '.'; -import type { GenerateStyle } from '../../theme/internal'; +import type { CSSObject } from '../../_util/_cssinjs'; +import type { ButtonToken } from './token'; +import type { GenerateStyle } from '../../_theme/internal'; const genButtonBorderStyle = (buttonTypeCls: string, borderColor: string) => ({ // Border @@ -22,8 +23,8 @@ const genButtonBorderStyle = (buttonTypeCls: string, borderColor: string) => ({ }, }); -const genGroupStyle: GenerateStyle = token => { - const { componentCls, fontSize, lineWidth, colorPrimaryHover, colorErrorHover } = token; +const genGroupStyle: GenerateStyle = token => { + const { componentCls, fontSize, lineWidth, groupBorderColor, colorErrorHover } = token; return { [`${componentCls}-group`]: [ @@ -41,7 +42,7 @@ const genGroupStyle: GenerateStyle = token => { }, '&:not(:first-child)': { - marginInlineStart: -lineWidth, + marginInlineStart: token.calc(lineWidth).mul(-1).equal(), [`&, & > ${componentCls}`]: { borderStartStartRadius: 0, @@ -71,7 +72,7 @@ const genGroupStyle: GenerateStyle = token => { }, // Border Color - genButtonBorderStyle(`${componentCls}-primary`, colorPrimaryHover), + genButtonBorderStyle(`${componentCls}-primary`, groupBorderColor), genButtonBorderStyle(`${componentCls}-danger`, colorErrorHover), ], }; diff --git a/components/button/style/index.ts b/components/button/style/index.ts index 20dfe069b..84ebab32d 100644 --- a/components/button/style/index.ts +++ b/components/button/style/index.ts @@ -1,51 +1,59 @@ -import type { CSSInterpolation, CSSObject } from '../../_util/cssinjs'; -import type { FullToken, GenerateStyle } from '../../theme/internal'; -import { genComponentStyleHook, mergeToken } from '../../theme/internal'; -import genGroupStyle from './group'; -import { genFocusStyle } from '../../style'; -import { genCompactItemStyle } from '../../style/compact-item'; -import { genCompactItemVerticalStyle } from '../../style/compact-item-vertical'; +import type { CSSObject } from '../../_util/_cssinjs'; +import { unit } from '../../_util/_cssinjs'; -/** Component only token. Which will handle additional calculation of alias token */ -export interface ComponentToken {} +import { genFocusStyle } from '../../style'; +import type { GenerateStyle } from '../../_theme/internal'; +import { genStyleHooks, mergeToken } from '../../_theme/internal'; +import genGroupStyle from './group'; +import type { ButtonToken, ComponentToken } from './token'; +import { prepareComponentToken, prepareToken } from './token'; -export interface ButtonToken extends FullToken<'Button'> { - // FIXME: should be removed - colorOutlineDefault: string; - buttonPaddingHorizontal: number; -} +export type { ComponentToken }; // ============================== Shared ============================== const genSharedButtonStyle: GenerateStyle = (token): CSSObject => { - const { componentCls, iconCls } = token; + const { componentCls, iconCls, fontWeight } = token; return { [componentCls]: { outline: 'none', position: 'relative', display: 'inline-block', - fontWeight: 400, + fontWeight, whiteSpace: 'nowrap', textAlign: 'center', backgroundImage: 'none', - backgroundColor: 'transparent', - border: `${token.lineWidth}px ${token.lineType} transparent`, + background: 'transparent', + border: `${unit(token.lineWidth)} ${token.lineType} transparent`, cursor: 'pointer', transition: `all ${token.motionDurationMid} ${token.motionEaseInOut}`, userSelect: 'none', touchAction: 'manipulation', - lineHeight: token.lineHeight, color: token.colorText, + '&:disabled > *': { + pointerEvents: 'none', + }, + '> span': { display: 'inline-block', }, + [`${componentCls}-icon`]: { + lineHeight: 0, + }, + // Leave a space between icon and text. [`> ${iconCls} + span, > span + ${iconCls}`]: { marginInlineStart: token.marginXS, }, + [`&:not(${componentCls}-icon-only) > ${componentCls}-icon`]: { + [`&${componentCls}-loading-icon, &:not(:last-child)`]: { + marginInlineEnd: token.marginXS, + }, + }, + '> a': { color: 'currentColor', }, @@ -54,54 +62,29 @@ const genSharedButtonStyle: GenerateStyle = (token): CSS ...genFocusStyle(token), }, + [`&${componentCls}-two-chinese-chars::first-letter`]: { + letterSpacing: '0.34em', + }, + + [`&${componentCls}-two-chinese-chars > *:not(${iconCls})`]: { + marginInlineEnd: '-0.34em', + letterSpacing: '0.34em', + }, + // make `btn-icon-only` not too narrow [`&-icon-only${componentCls}-compact-item`]: { flex: 'none', }, - // Special styles for Primary Button - [`&-compact-item${componentCls}-primary`]: { - [`&:not([disabled]) + ${componentCls}-compact-item${componentCls}-primary:not([disabled])`]: - { - position: 'relative', - - '&:before': { - position: 'absolute', - top: -token.lineWidth, - insetInlineStart: -token.lineWidth, - display: 'inline-block', - width: token.lineWidth, - height: `calc(100% + ${token.lineWidth * 2}px)`, - backgroundColor: token.colorPrimaryHover, - content: '""', - }, - }, - }, - // Special styles for Primary Button - '&-compact-vertical-item': { - [`&${componentCls}-primary`]: { - [`&:not([disabled]) + ${componentCls}-compact-vertical-item${componentCls}-primary:not([disabled])`]: - { - position: 'relative', - - '&:before': { - position: 'absolute', - top: -token.lineWidth, - insetInlineStart: -token.lineWidth, - display: 'inline-block', - width: `calc(100% + ${token.lineWidth * 2}px)`, - height: token.lineWidth, - backgroundColor: token.colorPrimaryHover, - content: '""', - }, - }, - }, - }, }, - }; + } as CSSObject; }; -const genHoverActiveButtonStyle = (hoverStyle: CSSObject, activeStyle: CSSObject): CSSObject => ({ - '&:not(:disabled)': { +const genHoverActiveButtonStyle = ( + btnCls: string, + hoverStyle: CSSObject, + activeStyle: CSSObject, +): CSSObject => ({ + [`&:not(:disabled):not(${btnCls}-disabled)`]: { '&:hover': hoverStyle, '&:active': activeStyle, }, @@ -117,21 +100,22 @@ const genCircleButtonStyle: GenerateStyle = token => ({ const genRoundButtonStyle: GenerateStyle = token => ({ borderRadius: token.controlHeight, - paddingInlineStart: token.controlHeight / 2, - paddingInlineEnd: token.controlHeight / 2, + paddingInlineStart: token.calc(token.controlHeight).div(2).equal(), + paddingInlineEnd: token.calc(token.controlHeight).div(2).equal(), }); // =============================== Type =============================== const genDisabledStyle: GenerateStyle = token => ({ cursor: 'not-allowed', - borderColor: token.colorBorder, + borderColor: token.borderColorDisabled, color: token.colorTextDisabled, - backgroundColor: token.colorBgContainerDisabled, + background: token.colorBgContainerDisabled, boxShadow: 'none', }); const genGhostButtonStyle = ( btnCls: string, + background: string, textColor: string | false, borderColor: string | false, textColorDisabled: string | false, @@ -141,17 +125,18 @@ const genGhostButtonStyle = ( ): CSSObject => ({ [`&${btnCls}-background-ghost`]: { color: textColor || undefined, - backgroundColor: 'transparent', + background, borderColor: borderColor || undefined, boxShadow: 'none', ...genHoverActiveButtonStyle( + btnCls, { - backgroundColor: 'transparent', + background, ...hoverStyle, }, { - backgroundColor: 'transparent', + background, ...activeStyle, }, ), @@ -165,7 +150,7 @@ const genGhostButtonStyle = ( }); const genSolidDisabledButtonStyle: GenerateStyle = token => ({ - '&:disabled': { + [`&:disabled, &${token.componentCls}-disabled`]: { ...genDisabledStyle(token), }, }); @@ -175,7 +160,7 @@ const genSolidButtonStyle: GenerateStyle = token => ({ }); const genPureDisabledButtonStyle: GenerateStyle = token => ({ - '&:disabled': { + [`&:disabled, &${token.componentCls}-disabled`]: { cursor: 'not-allowed', color: token.colorTextDisabled, }, @@ -185,12 +170,14 @@ const genPureDisabledButtonStyle: GenerateStyle = token const genDefaultButtonStyle: GenerateStyle = token => ({ ...genSolidButtonStyle(token), - backgroundColor: token.colorBgContainer, - borderColor: token.colorBorder, + background: token.defaultBg, + borderColor: token.defaultBorderColor, + color: token.defaultColor, - boxShadow: `0 ${token.controlOutlineWidth}px 0 ${token.controlTmpOutline}`, + boxShadow: token.defaultShadow, ...genHoverActiveButtonStyle( + token.componentCls, { color: token.colorPrimaryHover, borderColor: token.colorPrimaryHover, @@ -203,8 +190,9 @@ const genDefaultButtonStyle: GenerateStyle = token => ({ ...genGhostButtonStyle( token.componentCls, - token.colorBgContainer, - token.colorBgContainer, + token.ghostBg, + token.defaultGhostColor, + token.defaultGhostBorderColor, token.colorTextDisabled, token.colorBorder, ), @@ -214,6 +202,7 @@ const genDefaultButtonStyle: GenerateStyle = token => ({ borderColor: token.colorError, ...genHoverActiveButtonStyle( + token.componentCls, { color: token.colorErrorHover, borderColor: token.colorErrorBorderHover, @@ -226,6 +215,7 @@ const genDefaultButtonStyle: GenerateStyle = token => ({ ...genGhostButtonStyle( token.componentCls, + token.ghostBg, token.colorError, token.colorError, token.colorTextDisabled, @@ -239,24 +229,26 @@ const genDefaultButtonStyle: GenerateStyle = token => ({ const genPrimaryButtonStyle: GenerateStyle = token => ({ ...genSolidButtonStyle(token), - color: token.colorTextLightSolid, - backgroundColor: token.colorPrimary, + color: token.primaryColor, + background: token.colorPrimary, - boxShadow: `0 ${token.controlOutlineWidth}px 0 ${token.controlOutline}`, + boxShadow: token.primaryShadow, ...genHoverActiveButtonStyle( + token.componentCls, { color: token.colorTextLightSolid, - backgroundColor: token.colorPrimaryHover, + background: token.colorPrimaryHover, }, { color: token.colorTextLightSolid, - backgroundColor: token.colorPrimaryActive, + background: token.colorPrimaryActive, }, ), ...genGhostButtonStyle( token.componentCls, + token.ghostBg, token.colorPrimary, token.colorPrimary, token.colorTextDisabled, @@ -272,20 +264,23 @@ const genPrimaryButtonStyle: GenerateStyle = token => ({ ), [`&${token.componentCls}-dangerous`]: { - backgroundColor: token.colorError, - boxShadow: `0 ${token.controlOutlineWidth}px 0 ${token.colorErrorOutline}`, + background: token.colorError, + boxShadow: token.dangerShadow, + color: token.dangerColor, ...genHoverActiveButtonStyle( + token.componentCls, { - backgroundColor: token.colorErrorHover, + background: token.colorErrorHover, }, { - backgroundColor: token.colorErrorActive, + background: token.colorErrorActive, }, ), ...genGhostButtonStyle( token.componentCls, + token.ghostBg, token.colorError, token.colorError, token.colorTextDisabled, @@ -314,8 +309,10 @@ const genLinkButtonStyle: GenerateStyle = token => ({ color: token.colorLink, ...genHoverActiveButtonStyle( + token.componentCls, { color: token.colorLinkHover, + background: token.linkHoverBg, }, { color: token.colorLinkActive, @@ -328,6 +325,7 @@ const genLinkButtonStyle: GenerateStyle = token => ({ color: token.colorError, ...genHoverActiveButtonStyle( + token.componentCls, { color: token.colorErrorHover, }, @@ -343,13 +341,14 @@ const genLinkButtonStyle: GenerateStyle = token => ({ // Type: Text const genTextButtonStyle: GenerateStyle = token => ({ ...genHoverActiveButtonStyle( + token.componentCls, { color: token.colorText, - backgroundColor: token.colorBgTextHover, + background: token.textHoverBg, }, { color: token.colorText, - backgroundColor: token.colorBgTextActive, + background: token.colorBgTextActive, }, ), @@ -360,26 +359,19 @@ const genTextButtonStyle: GenerateStyle = token => ({ ...genPureDisabledButtonStyle(token), ...genHoverActiveButtonStyle( + token.componentCls, { color: token.colorErrorHover, - backgroundColor: token.colorErrorBg, + background: token.colorErrorBg, }, { color: token.colorErrorHover, - backgroundColor: token.colorErrorBg, + background: token.colorErrorBg, }, ), }, }); -// Href and Disabled -const genDisabledButtonStyle: GenerateStyle = token => ({ - ...genDisabledStyle(token), - [`&${token.componentCls}:hover`]: { - ...genDisabledStyle(token), - }, -}); - const genTypeButtonStyle: GenerateStyle = token => { const { componentCls } = token; @@ -389,26 +381,30 @@ const genTypeButtonStyle: GenerateStyle = token => { [`${componentCls}-dashed`]: genDashedButtonStyle(token), [`${componentCls}-link`]: genLinkButtonStyle(token), [`${componentCls}-text`]: genTextButtonStyle(token), - [`${componentCls}-disabled`]: genDisabledButtonStyle(token), + [`${componentCls}-ghost`]: genGhostButtonStyle( + token.componentCls, + token.ghostBg, + token.colorBgContainer, + token.colorBgContainer, + token.colorTextDisabled, + token.colorBorder, + ), }; }; // =============================== Size =============================== -const genSizeButtonStyle = (token: ButtonToken, sizePrefixCls: string = ''): CSSInterpolation => { +const genSizeButtonStyle = (token: ButtonToken, sizePrefixCls: string = '') => { const { componentCls, - iconCls, controlHeight, fontSize, lineHeight, - lineWidth, borderRadius, buttonPaddingHorizontal, + iconCls, + buttonPaddingVertical, } = token; - const paddingVertical = Math.max(0, (controlHeight - fontSize * lineHeight) / 2 - lineWidth); - const paddingHorizontal = buttonPaddingHorizontal - lineWidth; - const iconOnlyCls = `${componentCls}-icon-only`; return [ @@ -416,8 +412,9 @@ const genSizeButtonStyle = (token: ButtonToken, sizePrefixCls: string = ''): CSS { [`${componentCls}${sizePrefixCls}`]: { fontSize, + lineHeight, height: controlHeight, - padding: `${paddingVertical}px ${paddingHorizontal}px`, + padding: `${unit(buttonPaddingVertical!)} ${unit(buttonPaddingHorizontal!)}`, borderRadius, [`&${iconOnlyCls}`]: { @@ -427,8 +424,8 @@ const genSizeButtonStyle = (token: ButtonToken, sizePrefixCls: string = ''): CSS [`&${componentCls}-round`]: { width: 'auto', }, - '> span': { - transform: 'scale(1.143)', // 14px -> 16px + [iconCls]: { + fontSize: token.buttonIconOnlyFontSize, }, }, @@ -441,10 +438,6 @@ const genSizeButtonStyle = (token: ButtonToken, sizePrefixCls: string = ''): CSS [`${componentCls}-loading-icon`]: { transition: `width ${token.motionDurationSlow} ${token.motionEaseInOut}, opacity ${token.motionDurationSlow} ${token.motionEaseInOut}`, }, - - [`&:not(${iconOnlyCls}) ${componentCls}-loading-icon > ${iconCls}`]: { - marginInlineEnd: token.marginXS, - }, }, }, @@ -458,14 +451,24 @@ const genSizeButtonStyle = (token: ButtonToken, sizePrefixCls: string = ''): CSS ]; }; -const genSizeBaseButtonStyle: GenerateStyle = token => genSizeButtonStyle(token); +const genSizeBaseButtonStyle: GenerateStyle = token => + genSizeButtonStyle( + mergeToken(token, { + fontSize: token.contentFontSize, + lineHeight: token.contentLineHeight, + }), + ); const genSizeSmallButtonStyle: GenerateStyle = token => { const smallToken = mergeToken(token, { controlHeight: token.controlHeightSM, + fontSize: token.contentFontSizeSM, + lineHeight: token.contentLineHeightSM, padding: token.paddingXS, - buttonPaddingHorizontal: 8, // Fixed padding + buttonPaddingHorizontal: token.paddingInlineSM, + buttonPaddingVertical: token.paddingBlockSM, borderRadius: token.borderRadiusSM, + buttonIconOnlyFontSize: token.onlyIconSizeSM, }); return genSizeButtonStyle(smallToken, `${token.componentCls}-sm`); @@ -474,8 +477,12 @@ const genSizeSmallButtonStyle: GenerateStyle = token => { const genSizeLargeButtonStyle: GenerateStyle = token => { const largeToken = mergeToken(token, { controlHeight: token.controlHeightLG, - fontSize: token.fontSizeLG, + fontSize: token.contentFontSizeLG, + lineHeight: token.contentLineHeightLG, + buttonPaddingHorizontal: token.paddingInlineLG, + buttonPaddingVertical: token.paddingBlockLG, borderRadius: token.borderRadiusLG, + buttonIconOnlyFontSize: token.onlyIconSizeLG, }); return genSizeButtonStyle(largeToken, `${token.componentCls}-lg`); @@ -493,33 +500,37 @@ const genBlockButtonStyle: GenerateStyle = token => { }; // ============================== Export ============================== -export default genComponentStyleHook('Button', token => { - const { controlTmpOutline, paddingContentHorizontal } = token; - const buttonToken = mergeToken(token, { - colorOutlineDefault: controlTmpOutline, - buttonPaddingHorizontal: paddingContentHorizontal, - }); +export default genStyleHooks( + 'Button', + token => { + const buttonToken = prepareToken(token); - return [ - // Shared - genSharedButtonStyle(buttonToken), + return [ + // Shared + genSharedButtonStyle(buttonToken), - // Size - genSizeSmallButtonStyle(buttonToken), - genSizeBaseButtonStyle(buttonToken), - genSizeLargeButtonStyle(buttonToken), + // Size + genSizeSmallButtonStyle(buttonToken), + genSizeBaseButtonStyle(buttonToken), + genSizeLargeButtonStyle(buttonToken), - // Block - genBlockButtonStyle(buttonToken), + // Block + genBlockButtonStyle(buttonToken), - // Group (type, ghost, danger, disabled, loading) - genTypeButtonStyle(buttonToken), + // Group (type, ghost, danger, loading) + genTypeButtonStyle(buttonToken), - // Button Group - genGroupStyle(buttonToken), - - // Space Compact - genCompactItemStyle(token, { focus: false }), - genCompactItemVerticalStyle(token), - ]; -}); + // Button Group + genGroupStyle(buttonToken), + ]; + }, + prepareComponentToken, + { + unitless: { + fontWeight: true, + contentLineHeight: true, + contentLineHeightSM: true, + contentLineHeightLG: true, + }, + }, +); diff --git a/components/button/style/token.ts b/components/button/style/token.ts new file mode 100644 index 000000000..ecf31a2f9 --- /dev/null +++ b/components/button/style/token.ts @@ -0,0 +1,234 @@ +import type { CSSProperties } from 'vue'; +import type { FullToken, GetDefaultToken } from '../../_theme/internal'; +import { getLineHeight, mergeToken } from '../../_theme/internal'; +import type { GenStyleFn } from '../../_theme/util/genComponentStyleHook'; + +/** Component only token. Which will handle additional calculation of alias token */ +export interface ComponentToken { + /** + * @desc 文字字重 + * @descEN Font weight of text + */ + fontWeight: CSSProperties['fontWeight']; + /** + * @desc 默认按钮阴影 + * @descEN Shadow of default button + */ + defaultShadow: string; + /** + * @desc 主要按钮阴影 + * @descEN Shadow of primary button + */ + primaryShadow: string; + /** + * @desc 危险按钮阴影 + * @descEN Shadow of danger button + */ + dangerShadow: string; + /** + * @desc 主要按钮文本颜色 + * @descEN Text color of primary button + */ + primaryColor: string; + /** + * @desc 默认按钮文本颜色 + * @descEN Text color of default button + */ + defaultColor: string; + /** + * @desc 默认按钮背景色 + * @descEN Background color of default button + */ + defaultBg: string; + /** + * @desc 默认按钮边框颜色 + * @descEN Border color of default button + */ + defaultBorderColor: string; + /** + * @desc 危险按钮文本颜色 + * @descEN Text color of danger button + */ + dangerColor: string; + /** + * @desc 禁用状态边框颜色 + * @descEN Border color of disabled button + */ + borderColorDisabled: string; + /** + * @desc 默认幽灵按钮文本颜色 + * @descEN Text color of default ghost button + */ + defaultGhostColor: string; + /** + * @desc 幽灵按钮背景色 + * @descEN Background color of ghost button + */ + ghostBg: string; + /** + * @desc 默认幽灵按钮边框颜色 + * @descEN Border color of default ghost button + */ + defaultGhostBorderColor: string; + /** + * @desc 按钮横向内间距 + * @descEN Horizontal padding of button + */ + paddingInline: CSSProperties['paddingInline']; + /** + * @desc 大号按钮横向内间距 + * @descEN Horizontal padding of large button + */ + paddingInlineLG: CSSProperties['paddingInline']; + /** + * @desc 小号按钮横向内间距 + * @descEN Horizontal padding of small button + */ + paddingInlineSM: CSSProperties['paddingInline']; + /** + * @desc 按钮横向内间距 + * @descEN Horizontal padding of button + */ + paddingBlock: CSSProperties['paddingInline']; + /** + * @desc 大号按钮横向内间距 + * @descEN Horizontal padding of large button + */ + paddingBlockLG: CSSProperties['paddingInline']; + /** + * @desc 小号按钮横向内间距 + * @descEN Horizontal padding of small button + */ + paddingBlockSM: CSSProperties['paddingInline']; + /** + * @desc 只有图标的按钮图标尺寸 + * @descEN Icon size of button which only contains icon + */ + onlyIconSize: number; + /** + * @desc 大号只有图标的按钮图标尺寸 + * @descEN Icon size of large button which only contains icon + */ + onlyIconSizeLG: number; + /** + * @desc 小号只有图标的按钮图标尺寸 + * @descEN Icon size of small button which only contains icon + */ + onlyIconSizeSM: number; + /** + * @desc 按钮组边框颜色 + * @descEN Border color of button group + */ + groupBorderColor: string; + /** + * @desc 链接按钮悬浮态背景色 + * @descEN Background color of link button when hover + */ + linkHoverBg: string; + /** + * @desc 文本按钮悬浮态背景色 + * @descEN Background color of text button when hover + */ + textHoverBg: string; + /** + * @desc 按钮内容字体大小 + * @descEN Font size of button content + */ + contentFontSize: number; + /** + * @desc 大号按钮内容字体大小 + * @descEN Font size of large button content + */ + contentFontSizeLG: number; + /** + * @desc 小号按钮内容字体大小 + * @descEN Font size of small button content + */ + contentFontSizeSM: number; + /** + * @desc 按钮内容字体行高 + * @descEN Line height of button content + */ + contentLineHeight: number; + /** + * @desc 大号按钮内容字体行高 + * @descEN Line height of large button content + */ + contentLineHeightLG: number; + /** + * @desc 小号按钮内容字体行高 + * @descEN Line height of small button content + */ + contentLineHeightSM: number; +} + +export interface ButtonToken extends FullToken<'Button'> { + buttonPaddingHorizontal: CSSProperties['paddingInline']; + buttonPaddingVertical: CSSProperties['paddingBlock']; + buttonIconOnlyFontSize: number; +} + +export const prepareToken: (token: Parameters>[0]) => ButtonToken = token => { + const { paddingInline, onlyIconSize, paddingBlock } = token; + + const buttonToken = mergeToken(token, { + buttonPaddingHorizontal: paddingInline, + buttonPaddingVertical: paddingBlock, + buttonIconOnlyFontSize: onlyIconSize, + }); + + return buttonToken; +}; + +export const prepareComponentToken: GetDefaultToken<'Button'> = token => { + const contentFontSize = token.contentFontSize ?? token.fontSize; + const contentFontSizeSM = token.contentFontSizeSM ?? token.fontSize; + const contentFontSizeLG = token.contentFontSizeLG ?? token.fontSizeLG; + const contentLineHeight = token.contentLineHeight ?? getLineHeight(contentFontSize); + const contentLineHeightSM = token.contentLineHeightSM ?? getLineHeight(contentFontSizeSM); + const contentLineHeightLG = token.contentLineHeightLG ?? getLineHeight(contentFontSizeLG); + + return { + fontWeight: 400, + defaultShadow: `0 ${token.controlOutlineWidth}px 0 ${token.controlTmpOutline}`, + primaryShadow: `0 ${token.controlOutlineWidth}px 0 ${token.controlOutline}`, + dangerShadow: `0 ${token.controlOutlineWidth}px 0 ${token.colorErrorOutline}`, + primaryColor: token.colorTextLightSolid, + dangerColor: token.colorTextLightSolid, + borderColorDisabled: token.colorBorder, + defaultGhostColor: token.colorBgContainer, + ghostBg: 'transparent', + defaultGhostBorderColor: token.colorBgContainer, + paddingInline: token.paddingContentHorizontal - token.lineWidth, + paddingInlineLG: token.paddingContentHorizontal - token.lineWidth, + paddingInlineSM: 8 - token.lineWidth, + onlyIconSize: token.fontSizeLG, + onlyIconSizeSM: token.fontSizeLG - 2, + onlyIconSizeLG: token.fontSizeLG + 2, + groupBorderColor: token.colorPrimaryHover, + linkHoverBg: 'transparent', + textHoverBg: token.colorBgTextHover, + defaultColor: token.colorText, + defaultBg: token.colorBgContainer, + defaultBorderColor: token.colorBorder, + defaultBorderColorDisabled: token.colorBorder, + contentFontSize, + contentFontSizeSM, + contentFontSizeLG, + contentLineHeight, + contentLineHeightSM, + contentLineHeightLG, + paddingBlock: Math.max( + (token.controlHeight - contentFontSize * contentLineHeight) / 2 - token.lineWidth, + 0, + ), + paddingBlockSM: Math.max( + (token.controlHeightSM - contentFontSizeSM * contentLineHeightSM) / 2 - token.lineWidth, + 0, + ), + paddingBlockLG: Math.max( + (token.controlHeightLG - contentFontSizeLG * contentLineHeightLG) / 2 - token.lineWidth, + 0, + ), + }; +}; diff --git a/components/config-provider/context.ts b/components/config-provider/context.ts index f21907595..ea81b7489 100644 --- a/components/config-provider/context.ts +++ b/components/config-provider/context.ts @@ -5,9 +5,9 @@ import type { RequiredMark } from '../form/Form'; import type { RenderEmptyHandler } from './renderEmpty'; import type { TransformCellTextProps } from '../table/interface'; import type { Locale } from '../locale-provider'; -import type { DerivativeFunc } from '../_util/cssinjs'; -import type { AliasToken, SeedToken } from '../theme/internal'; -import type { MapToken, OverrideToken } from '../theme/interface'; +import type { DerivativeFunc } from '../_util/_cssinjs'; +import type { AliasToken, SeedToken } from '../_theme/internal'; +import type { MapToken, OverrideToken } from '../_theme/interface'; import type { VueNode } from '../_util/type'; import { objectType } from '../_util/type'; @@ -57,6 +57,18 @@ export interface ThemeConfig { algorithm?: MappingAlgorithm | MappingAlgorithm[]; hashed?: boolean; inherit?: boolean; + cssVar?: + | { + /** + * Prefix for css variable, default to `antd`. + */ + prefix?: string; + /** + * Unique key for theme, should be set manually < react@18. + */ + key?: string; + } + | boolean; } export const configProviderProps = () => ({ diff --git a/components/config-provider/hooks/useCssVarCls.ts b/components/config-provider/hooks/useCssVarCls.ts new file mode 100644 index 000000000..4ebf486b2 --- /dev/null +++ b/components/config-provider/hooks/useCssVarCls.ts @@ -0,0 +1,15 @@ +import { useToken } from '../../_theme/internal'; +import type { Ref } from 'vue'; + +/** + * This hook is only for cssVar to add root className for components. + * If root ClassName is needed, this hook could be refactored with `-root` + * @param prefixCls + */ +const useCSSVarCls = (prefixCls: Ref) => { + const [, , , , cssVar] = useToken(); + + return cssVar.value ? `${prefixCls.value}-css-var` : ''; +}; + +export default useCSSVarCls; diff --git a/components/config-provider/hooks/useSize.ts b/components/config-provider/hooks/useSize.ts new file mode 100644 index 000000000..85fac8d98 --- /dev/null +++ b/components/config-provider/hooks/useSize.ts @@ -0,0 +1,32 @@ +import type { SizeType } from '../SizeContext'; +import { useInjectSize } from '../SizeContext'; +import type { Ref } from 'vue'; +import { computed, shallowRef, watch } from 'vue'; + +const useSize = (customSize?: T | ((ctxSize: SizeType) => T)): Ref => { + const size = useInjectSize(); + + const mergedSize = shallowRef(null); + + watch( + computed(() => { + return [customSize, size.value]; + }), + () => { + if (!customSize) { + mergedSize.value = size.value as T; + } + if (typeof customSize === 'string') { + mergedSize.value = customSize ?? (size.value as T); + } + if (customSize instanceof Function) { + mergedSize.value = customSize(size.value) as T; + } + }, + { immediate: true }, + ); + + return mergedSize; +}; + +export default useSize; diff --git a/components/config-provider/hooks/useTheme.ts b/components/config-provider/hooks/useTheme.ts index 0ed451193..1a8c8d8f6 100644 --- a/components/config-provider/hooks/useTheme.ts +++ b/components/config-provider/hooks/useTheme.ts @@ -1,7 +1,9 @@ import type { ThemeConfig } from '../context'; -import { defaultConfig } from '../../theme/internal'; +import { defaultConfig } from '../../_theme/internal'; import type { Ref } from 'vue'; import { computed } from 'vue'; +import useThemeKey from './useThemeKey'; +import devWarning from '../../vc-util/warning'; export default function useTheme(theme?: Ref, parentTheme?: Ref) { const themeConfig = computed(() => theme?.value || {}); @@ -9,6 +11,20 @@ export default function useTheme(theme?: Ref, parentTheme?: Ref { if (!theme?.value) { return parentTheme?.value; @@ -26,6 +42,16 @@ export default function useTheme(theme?: Ref, parentTheme?: Ref, parentTheme?: Ref { + const instance = getCurrentInstance(); + + if (!instance) { + return _.uniqueId() + ''; + } + + return instance.uid + ''; +}; + +export default useThemeKey; diff --git a/components/config-provider/index.tsx b/components/config-provider/index.tsx index 036238ccb..68198c2e7 100644 --- a/components/config-provider/index.tsx +++ b/components/config-provider/index.tsx @@ -15,8 +15,8 @@ import defaultLocale from '../locale/en_US'; import type { ValidateMessages } from '../form/interface'; import useStyle from './style'; import useTheme from './hooks/useTheme'; -import defaultSeedToken from '../theme/themes/seed'; -import type { ConfigProviderInnerProps, ConfigProviderProps, Theme } from './context'; +import defaultSeedToken from '../_theme/themes/seed'; +import type { ConfigProviderInnerProps, ConfigProviderProps, Theme, ThemeConfig } from './context'; import { useConfigContextProvider, useConfigContextInject, @@ -26,8 +26,8 @@ import { } from './context'; import { useProviderSize } from './SizeContext'; import { useProviderDisabled } from './DisabledContext'; -import { createTheme } from '../_util/cssinjs'; -import { DesignTokenProvider } from '../theme/internal'; +import { createTheme } from '../_util/_cssinjs'; +import { defaultTheme, DesignTokenProvider } from '../_theme/context'; export type { ConfigProviderProps, @@ -227,19 +227,47 @@ const ConfigProvider = defineComponent({ // ================================ Dynamic theme ================================ const memoTheme = computed(() => { - const { algorithm, token, ...rest } = mergedTheme.value || {}; + const { algorithm, token, components, cssVar, ...rest } = mergedTheme.value || {}; const themeObj = algorithm && (!Array.isArray(algorithm) || algorithm.length > 0) ? createTheme(algorithm) - : undefined; + : defaultTheme; + + const parsedComponents: any = {}; + Object.entries(components || {}).forEach(([componentName, componentToken]) => { + const parsedToken: typeof componentToken & { theme?: typeof defaultTheme } = { + ...componentToken, + }; + if ('algorithm' in parsedToken) { + if (parsedToken.algorithm === true) { + parsedToken.theme = themeObj; + } else if ( + Array.isArray(parsedToken.algorithm) || + typeof parsedToken.algorithm === 'function' + ) { + parsedToken.theme = createTheme(parsedToken.algorithm as any); + } + delete parsedToken.algorithm; + } + parsedComponents[componentName] = parsedToken; + }); + + const mergedToken = { + ...defaultSeedToken, + ...token, + }; + return { ...rest, theme: themeObj, - token: { - ...defaultSeedToken, - ...token, + token: mergedToken, + components: parsedComponents, + override: { + override: mergedToken, + ...parsedComponents, }, + cssVar: cssVar as Exclude, }; }); const validateMessagesRef = computed(() => { diff --git a/components/config-provider/style/index.ts b/components/config-provider/style/index.ts index 77ed478a0..762e6e495 100644 --- a/components/config-provider/style/index.ts +++ b/components/config-provider/style/index.ts @@ -1,6 +1,7 @@ -import { useStyleRegister } from '../../_util/cssinjs'; +import type { CSSObject } from '../../_util/_cssinjs'; +import { useStyleRegister } from '../../_util/_cssinjs'; import { resetIcon } from '../../style'; -import { useToken } from '../../theme/internal'; +import { useToken } from '../../_theme/internal'; import { computed, Ref } from 'vue'; const useStyle = (iconPrefixCls: Ref) => { @@ -13,16 +14,17 @@ const useStyle = (iconPrefixCls: Ref) => { hashId: '', path: ['ant-design-icons', iconPrefixCls.value], })), - () => [ - { - [`.${iconPrefixCls.value}`]: { - ...resetIcon(), - [`.${iconPrefixCls.value} .${iconPrefixCls.value}-icon`]: { - display: 'block', + () => + [ + { + [`.${iconPrefixCls.value}`]: { + ...resetIcon(), + [`.${iconPrefixCls.value} .${iconPrefixCls.value}-icon`]: { + display: 'block', + }, }, }, - }, - ], + ] as CSSObject[], ); }; diff --git a/components/date-picker/style/index.ts b/components/date-picker/style/index.ts index 4e92852fd..5675e6736 100644 --- a/components/date-picker/style/index.ts +++ b/components/date-picker/style/index.ts @@ -22,6 +22,8 @@ import type { TokenWithCommonCls } from '../../theme/util/genComponentStyleHook' import { resetComponent, roundedArrow, textEllipsis } from '../../style'; import { genCompactItemStyle } from '../../style/compact-item'; +export interface ComponentToken {} + export interface ComponentToken { presetsWidth: number; presetsMaxWidth: number; diff --git a/components/descriptions/style/index.ts b/components/descriptions/style/index.ts index 037edb550..c4289b7de 100644 --- a/components/descriptions/style/index.ts +++ b/components/descriptions/style/index.ts @@ -3,6 +3,8 @@ import type { FullToken, GenerateStyle } from '../../theme/internal'; import { genComponentStyleHook, mergeToken } from '../../theme/internal'; import { resetComponent, textEllipsis } from '../../style'; +export interface ComponentToken {} + interface DescriptionsToken extends FullToken<'Descriptions'> { descriptionsTitleMarginBottom: number; descriptionsExtraColor: string; diff --git a/components/form/style/index.ts b/components/form/style/index.ts index dad4aa62f..394a3db89 100644 --- a/components/form/style/index.ts +++ b/components/form/style/index.ts @@ -5,6 +5,8 @@ import { genComponentStyleHook, mergeToken } from '../../theme/internal'; import { resetComponent } from '../../style'; import genFormValidateMotionStyle from './explain'; +export interface ComponentToken {} + export interface FormToken extends FullToken<'Form'> { formItemCls: string; rootPrefixCls: string; diff --git a/components/grid/style/index.ts b/components/grid/style/index.ts index 137b50251..895b5b01c 100644 --- a/components/grid/style/index.ts +++ b/components/grid/style/index.ts @@ -2,6 +2,8 @@ import type { CSSObject } from '../../_util/cssinjs'; import type { FullToken, GenerateStyle } from '../../theme/internal'; import { genComponentStyleHook, mergeToken } from '../../theme/internal'; +export interface ComponentToken {} + interface GridRowToken extends FullToken<'Grid'> {} interface GridColToken extends FullToken<'Grid'> { diff --git a/components/input/style/index.ts b/components/input/style/index.ts index 7653f7870..dec232d66 100644 --- a/components/input/style/index.ts +++ b/components/input/style/index.ts @@ -5,6 +5,8 @@ import type { GlobalToken } from '../../theme/interface'; import { clearFix, resetComponent } from '../../style'; import { genCompactItemStyle } from '../../style/compact-item'; +export interface ComponentToken {} + export type InputToken> = T & { inputAffixPadding: number; inputPaddingVertical: number; diff --git a/components/page-header/style/index.ts b/components/page-header/style/index.ts index 2ed353779..99717577d 100644 --- a/components/page-header/style/index.ts +++ b/components/page-header/style/index.ts @@ -4,6 +4,8 @@ import { genComponentStyleHook, mergeToken } from '../../theme/internal'; import { resetComponent, textEllipsis } from '../../style'; import { operationUnit } from '../../style'; +export interface ComponentToken {} + interface PageHeaderToken extends FullToken<'PageHeader'> { pageHeaderPadding: number; pageHeaderPaddingVertical: number; diff --git a/components/pagination/style/index.tsx b/components/pagination/style/index.tsx index 9f94de9ab..56d620134 100644 --- a/components/pagination/style/index.tsx +++ b/components/pagination/style/index.tsx @@ -9,6 +9,8 @@ import type { FullToken, GenerateStyle } from '../../theme/internal'; import { genComponentStyleHook, mergeToken } from '../../theme/internal'; import { genFocusOutline, genFocusStyle, resetComponent } from '../../style'; +export interface ComponentToken {} + interface PaginationToken extends InputToken> { paginationItemSize: number; paginationFontFamily: string; diff --git a/components/statistic/style/index.tsx b/components/statistic/style/index.tsx index d70e31b0c..b18081926 100644 --- a/components/statistic/style/index.tsx +++ b/components/statistic/style/index.tsx @@ -3,6 +3,8 @@ import type { FullToken, GenerateStyle } from '../../theme/internal'; import { genComponentStyleHook, mergeToken } from '../../theme/internal'; import { resetComponent } from '../../style'; +export interface ComponentToken {} + interface StatisticToken extends FullToken<'Statistic'> { statisticTitleFontSize: number; statisticContentFontSize: number; diff --git a/components/switch/index.tsx b/components/switch/index.tsx index 2bc6e5a81..09a2cf461 100644 --- a/components/switch/index.tsx +++ b/components/switch/index.tsx @@ -98,7 +98,7 @@ const Switch = defineComponent({ ); const { prefixCls, direction, size } = useConfigInject('switch', props); - const [wrapSSR, hashId] = useStyle(prefixCls); + const [wrapCSSVar, hashId, cssVarCls] = useStyle(prefixCls); const refSwitchNode = ref(); const focus = () => { refSwitchNode.value?.focus(); @@ -159,10 +159,11 @@ const Switch = defineComponent({ [prefixCls.value]: true, [`${prefixCls.value}-rtl`]: direction.value === 'rtl', [hashId.value]: true, + [cssVarCls.value]: true, })); return () => - wrapSSR( + wrapCSSVar(