refactor: rename cssinjs folder

pull/7940/head
tangjinzhou 2024-11-08 19:12:16 +08:00
parent a1e029429f
commit 3ca620a929
131 changed files with 1793 additions and 7271 deletions

View File

@ -1,33 +0,0 @@
/* 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,
};

View File

@ -1,632 +0,0 @@
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 h1h2h3
* @nameEN Font weight for heading components (such as h1, h2, h3) or selected item
* @desc h1h2h3
* @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;
}

View File

@ -1,137 +0,0 @@
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;
}

View File

@ -1,44 +0,0 @@
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<SeedToken, MapToken>;
export type OverrideToken = {
[key in keyof ComponentTokenMap]: Partial<ComponentTokenMap[key]> & Partial<AliasToken>;
};
/** 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<string>];
export type GenerateStyle<
ComponentToken extends object = AliasToken,
ReturnType = CSSInterpolation,
> = (token: ComponentToken) => ReturnType;

View File

@ -1,598 +0,0 @@
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 RateSkeleton 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 SliderSegmented 使
* @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 ResultProgress 使
* @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 ModalDrawer 使 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;
}

View File

@ -1,139 +0,0 @@
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;
}

View File

@ -1,46 +0,0 @@
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 {}

View File

@ -1,74 +0,0 @@
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;
}

View File

@ -1,43 +0,0 @@
export interface StyleMapToken {
/**
* @nameZH 线
* @nameEN Line Width
* @desc 线 ButtonInputSelect
* @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 ButtonInputSelect 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 CardModal
* @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;
}

View File

@ -1,32 +0,0 @@
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<PresetColorKey, string>;
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;
};

View File

@ -1,279 +0,0 @@
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 ResultProgress 使
* @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 codepre 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 AffixModal
* @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;
}

View File

@ -1,51 +0,0 @@
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,
};

View File

@ -1,20 +0,0 @@
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;

View File

@ -1,19 +0,0 @@
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),
};
}

View File

@ -1,27 +0,0 @@
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<SeedToken, MapToken> = (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;

View File

@ -1,9 +0,0 @@
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();
};

View File

@ -1,54 +0,0 @@
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),
};
};

View File

@ -1,49 +0,0 @@
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<SeedToken, MapToken> = (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;

View File

@ -1,9 +0,0 @@
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();
};

View File

@ -1,54 +0,0 @@
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),
};
};

View File

@ -1,53 +0,0 @@
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),
};
}

View File

@ -1,81 +0,0 @@
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;

View File

@ -1,100 +0,0 @@
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',
};
}

View File

@ -1,19 +0,0 @@
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),
};
}

View File

@ -1,13 +0,0 @@
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;

View File

@ -1,44 +0,0 @@
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;

View File

@ -1,22 +0,0 @@
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),
}));
}

View File

@ -1,59 +0,0 @@
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;

View File

@ -1,17 +0,0 @@
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
};
}

View File

@ -1,207 +0,0 @@
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<AliasToken> };
/**
* 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;
}

View File

@ -1,458 +0,0 @@
/* 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<C extends OverrideComponent> = GlobalToken &
ComponentTokenMap[C];
type ComponentToken<C extends OverrideComponent> = Exclude<OverrideToken[C], undefined>;
type ComponentTokenKey<C extends OverrideComponent> = keyof ComponentToken<C>;
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> = 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<C extends OverrideComponent> = TokenWithCommonCls<
GlobalTokenWithComponent<C>
>;
export type GenStyleFn<C extends OverrideComponent> = (
token: FullToken<C>,
info: StyleInfo,
) => CSSInterpolation;
export type GetDefaultToken<C extends OverrideComponent> =
| null
| OverrideTokenWithoutDerivative[C]
| ((
token: AliasToken & Partial<OverrideTokenWithoutDerivative[C]>,
) => OverrideTokenWithoutDerivative[C]);
const getDefaultComponentToken = <C extends OverrideComponent>(
component: C,
token: Ref<GlobalToken>,
getDefaultToken: GetDefaultToken<C>,
) => {
if (typeof getDefaultToken === 'function') {
return getDefaultToken(mergeToken<any>(token.value, token.value[component] ?? {}));
}
return getDefaultToken ?? {};
};
const getComponentToken = <C extends OverrideComponent>(
component: C,
token: Ref<GlobalToken>,
defaultToken: OverrideTokenWithoutDerivative[C],
options?: {
deprecatedTokens?: [ComponentTokenKey<C>, ComponentTokenKey<C>][];
},
) => {
const customToken = { ...(token.value[component] as ComponentToken<C>) };
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<C extends OverrideComponent>(
componentName: C | [C, string],
styleFn: GenStyleFn<C>,
getDefaultToken?: GetDefaultToken<C>,
options: {
resetStyle?: boolean;
// Deprecated token key map [["oldTokenKey", "newTokenKey"], ["oldTokenKey", "newTokenKey"]]
deprecatedTokens?: [ComponentTokenKey<C>, ComponentTokenKey<C>][];
/**
* 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<string>): 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<Parameters<typeof useStyleRegister>[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<GlobalTokenWithComponent<OverrideComponent>>
>(
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<C>, {
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<string>;
}
// Get from second argument
type RestParameters<T extends any[]> = T extends [any, ...infer Rest] ? Rest : never;
export const genSubStyleComponent: <C extends OverrideComponent>(
componentName: [C, string],
...args: RestParameters<Parameters<typeof genComponentStyleHook<C>>>
) => 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 = <C extends OverrideComponent>(
component: C,
getDefaultToken?: GetDefaultToken<C>,
options?: {
unitless?: {
[key in ComponentTokenKey<C>]: boolean;
};
deprecatedTokens?: [ComponentTokenKey<C>, ComponentTokenKey<C>][];
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<C>) => {
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<string>) => {
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 = <C extends OverrideComponent>(
component: C | [C, string],
styleFn: GenStyleFn<C>,
getDefaultToken?: GetDefaultToken<C>,
options?: {
resetStyle?: boolean;
deprecatedTokens?: [ComponentTokenKey<C>, ComponentTokenKey<C>][];
/**
* Component tokens that do not need unit.
*/
unitless?: {
[key in ComponentTokenKey<C>]: 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<string>, rootCls: Ref<string> = prefixCls) => {
const [, hashId] = useStyle(prefixCls);
const [wrapCSSVar, cssVarCls] = useCSSVar(rootCls);
return [wrapCSSVar, hashId, cssVarCls] as const;
};
};

View File

@ -1,29 +0,0 @@
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;

View File

@ -1,85 +0,0 @@
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<T extends AnyObject>(...objs: Partial<T>[]): 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<string, string | number> }
> = {};
/** @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 = <T extends AnyObject>(token: T) => {
let tokenKeys: Set<string> | undefined;
let proxy = token;
let flush: (componentName: string, componentToken: Record<string, string | number>) => void =
noop;
if (enableStatistic && typeof Proxy !== 'undefined') {
tokenKeys = new Set<string>();
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;

View File

@ -1,32 +0,0 @@
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<string, ValueType>();
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;

View File

@ -1,19 +0,0 @@
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;

View File

@ -1,194 +0,0 @@
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<string, boolean> = {};
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 <style /> on the end of Provider in server side.
*/
cache: CacheEntity;
/** Tell children that this context is default generated context */
defaultCache: boolean;
/** Use `:where` selector to reduce hashId css selector priority */
hashPriority?: HashPriority;
/** Tell cssinjs where to inject style in */
container?: Element | ShadowRoot;
/** Component wil render inline `<style />` for fallback in SSR. Not recommend. */
ssrInline?: boolean;
/** Transform css before inject in document. Please note that `transformers` do not support dynamic update */
transformers?: Transformer[];
/**
* Linters to lint css before inject in document.
* Styles will be linted after transforming.
* Please note that `linters` do not support dynamic update.
*/
linters?: Linter[];
}
const StyleContextKey: InjectionKey<ShallowRef<Partial<StyleContextProps>>> =
Symbol('StyleContextKey');
export type UseStyleProviderProps = Partial<StyleContextProps> | Ref<Partial<StyleContextProps>>;
// fix: https://github.com/vueComponent/ant-design-vue/issues/7023
const getCache = () => {
const instance = getCurrentInstance();
let cache: CacheEntity;
if (instance && instance.appContext) {
const globalCache = instance.appContext?.config?.globalProperties?.__ANTDV_CSSINJS_CACHE__;
if (globalCache) {
cache = globalCache;
} else {
cache = createCache();
if (instance.appContext.config.globalProperties) {
instance.appContext.config.globalProperties.__ANTDV_CSSINJS_CACHE__ = cache;
}
}
} else {
cache = createCache();
}
return cache;
};
const defaultStyleContext: StyleContextProps = {
cache: createCache(),
defaultCache: true,
hashPriority: 'low',
};
// fix: https://github.com/vueComponent/ant-design-vue/issues/6912
export const useStyleInject = () => {
const cache = getCache();
return inject(StyleContextKey, shallowRef({ ...defaultStyleContext, cache }));
};
export const useStyleProvider = (props: UseStyleProviderProps) => {
const parentContext = useStyleInject();
const context = shallowRef<Partial<StyleContextProps>>({
...defaultStyleContext,
cache: createCache(),
});
watch(
[() => unref(props), parentContext],
() => {
const mergedContext: Partial<StyleContextProps> = {
...parentContext.value,
};
const propsValue = unref(props);
Object.keys(propsValue).forEach(key => {
const value = propsValue[key];
if (propsValue[key] !== undefined) {
mergedContext[key] = value;
}
});
const { cache } = propsValue;
mergedContext.cache = mergedContext.cache || createCache();
mergedContext.defaultCache = !cache && parentContext.value.defaultCache;
context.value = mergedContext;
},
{ immediate: true },
);
provide(StyleContextKey, context);
return context;
};
export const styleProviderProps = () => ({
autoClear: booleanType(),
/** @private Test only. Not work in production. */
mock: stringType<'server' | 'client'>(),
/**
* Only set when you need ssr to extract style on you own.
* If not provided, it will auto create <style /> on the end of Provider in server side.
*/
cache: objectType<CacheEntity>(),
/** Tell children that this context is default generated context */
defaultCache: booleanType(),
/** Use `:where` selector to reduce hashId css selector priority */
hashPriority: stringType<HashPriority>(),
/** Tell cssinjs where to inject style in */
container: someType<Element | ShadowRoot>(),
/** Component wil render inline `<style />` for fallback in SSR. Not recommend. */
ssrInline: booleanType(),
/** Transform css before inject in document. Please note that `transformers` do not support dynamic update */
transformers: arrayType<Transformer[]>(),
/**
* Linters to lint css before inject in document.
* Styles will be linted after transforming.
* Please note that `linters` do not support dynamic update.
*/
linters: arrayType<Linter[]>(),
});
export type StyleProviderProps = Partial<ExtractPropTypes<ReturnType<typeof styleProviderProps>>>;
export const StyleProvider = withInstall(
defineComponent({
name: 'AStyleProvider',
inheritAttrs: false,
props: styleProviderProps(),
setup(props, { slots }) {
useStyleProvider(props);
return () => slots.default?.();
},
}),
);
export default {
useStyleInject,
useStyleProvider,
StyleProvider,
};

View File

@ -1,254 +0,0 @@
import hash from '@emotion/hash';
import { updateCSS } from '../../../vc-util/Dom/dynamicCSS';
import { ATTR_MARK, ATTR_TOKEN, CSS_IN_JS_INSTANCE, useStyleInject } from '../StyleContext';
import type Theme from '../theme/Theme';
import { flattenToken, memoResult, token2key, toStyleStr } from '../util';
import { transformToken } from '../util/css-variables';
import type { ExtractStyle } from './useGlobalCache';
import useGlobalCache from './useGlobalCache';
import type { Ref } from 'vue';
import { ref, computed } from 'vue';
const EMPTY_OVERRIDE = {};
// Generate different prefix to make user selector break in production env.
// This helps developer not to do style override directly on the hash id.
const hashPrefix = process.env.NODE_ENV !== 'production' ? 'css-dev-only-do-not-override' : 'css';
export interface Option<DerivativeToken, DesignToken> {
/**
* Generate token with salt.
* This is used to generate different hashId even same derivative token for different version.
*/
salt?: string;
override?: object;
/**
* Format token as you need. Such as:
*
* - rename token
* - merge token
* - delete token
*
* This should always be the same since it's one time process.
* It's ok to useMemo outside but this has better cache strategy.
*/
formatToken?: (mergedToken: any) => DerivativeToken;
/**
* Get final token with origin token, override token and theme.
* The parameters do not contain formatToken since it's passed by user.
* @param origin The original token.
* @param override Extra tokens to override.
* @param theme Theme instance. Could get derivative token by `theme.getDerivativeToken`
*/
getComputedToken?: (
origin: DesignToken,
override: object,
theme: Theme<any, any>,
) => DerivativeToken;
/**
* Transform token to css variables.
*/
cssVar?: {
/** Prefix for css variables */
prefix?: string;
/** Tokens that should not be appended with unit */
unitless?: Record<string, boolean>;
/** Tokens that should not be transformed to css variables */
ignore?: Record<string, boolean>;
/** Tokens that preserves origin value */
preserve?: Record<string, boolean>;
/** Key for current theme. Useful for customizing and should be unique */
key?: string;
};
}
const tokenKeys = new Map<string, number>();
function recordCleanToken(tokenKey: string) {
tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) + 1);
}
function removeStyleTags(key: string, instanceId: string) {
if (typeof document !== 'undefined') {
const styles = document.querySelectorAll(`style[${ATTR_TOKEN}="${key}"]`);
styles.forEach(style => {
if ((style as any)[CSS_IN_JS_INSTANCE] === instanceId) {
style.parentNode?.removeChild(style);
}
});
}
}
const TOKEN_THRESHOLD = 0;
// Remove will check current keys first
function cleanTokenStyle(tokenKey: string, instanceId: string) {
tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) - 1);
const tokenKeyList = Array.from(tokenKeys.keys());
const cleanableKeyList = tokenKeyList.filter(key => {
const count = tokenKeys.get(key) || 0;
return count <= 0;
});
// Should keep tokens under threshold for not to insert style too often
if (tokenKeyList.length - cleanableKeyList.length > TOKEN_THRESHOLD) {
cleanableKeyList.forEach(key => {
removeStyleTags(key, instanceId);
tokenKeys.delete(key);
});
}
}
export const getComputedToken = <DerivativeToken = object, DesignToken = DerivativeToken>(
originToken: DesignToken,
overrideToken: object,
theme: Theme<any, any>,
format?: (token: DesignToken) => DerivativeToken,
) => {
const derivativeToken = theme.getDerivativeToken(originToken);
// Merge with override
let mergedDerivativeToken = {
...derivativeToken,
...overrideToken,
};
// Format if needed
if (format) {
mergedDerivativeToken = format(mergedDerivativeToken);
}
return mergedDerivativeToken;
};
export const TOKEN_PREFIX = 'token';
type TokenCacheValue<DerivativeToken> = [
token: DerivativeToken & { _tokenKey: string; _themeKey: string },
hashId: string,
realToken: DerivativeToken & { _tokenKey: string },
cssVarStr: string,
cssVarKey: string,
];
/**
* Cache theme derivative token as global shared one
* @param theme Theme entity
* @param tokens List of tokens, used for cache. Please do not dynamic generate object directly
* @param option Additional config
* @returns Call Theme.getDerivativeToken(tokenObject) to get token
*/
export default function useCacheToken<DerivativeToken = object, DesignToken = DerivativeToken>(
theme: Ref<Theme<any, any>>,
tokens: Ref<Partial<DesignToken>[]>,
option: Ref<Option<DerivativeToken, DesignToken>> = ref({}),
): Ref<TokenCacheValue<DerivativeToken>> {
const styleContext = useStyleInject();
// Basic - We do basic cache here
const mergedToken = computed(() =>
memoResult(() => Object.assign({}, ...tokens.value), tokens.value),
);
const tokenStr = computed(() => flattenToken(mergedToken.value));
const overrideTokenStr = computed(() => flattenToken(option.value.override ?? EMPTY_OVERRIDE));
const cssVarStr = computed(() => (option.value.cssVar ? flattenToken(option.value.cssVar) : ''));
const cachedToken = useGlobalCache<TokenCacheValue<DerivativeToken>>(
TOKEN_PREFIX,
computed(() => [
option.value.salt ?? '',
theme.value?.id,
tokenStr.value,
overrideTokenStr.value,
cssVarStr.value,
]),
() => {
const {
salt = '',
override = EMPTY_OVERRIDE,
formatToken,
getComputedToken: compute,
cssVar,
} = option.value;
let mergedDerivativeToken = compute
? compute(mergedToken.value, override, theme.value)
: getComputedToken(mergedToken.value, override, theme.value, formatToken);
// Replace token value with css variables
const actualToken = { ...mergedDerivativeToken };
let cssVarsStr = '';
if (!!cssVar) {
[mergedDerivativeToken, cssVarsStr] = transformToken(mergedDerivativeToken, cssVar.key!, {
prefix: cssVar.prefix,
ignore: cssVar.ignore,
unitless: cssVar.unitless,
preserve: cssVar.preserve,
});
}
// Optimize for `useStyleRegister` performance
const tokenKey = token2key(mergedDerivativeToken, salt);
mergedDerivativeToken._tokenKey = tokenKey;
actualToken._tokenKey = token2key(actualToken, salt);
const themeKey = cssVar?.key ?? tokenKey;
mergedDerivativeToken._themeKey = themeKey;
recordCleanToken(themeKey);
const hashId = `${hashPrefix}-${hash(tokenKey)}`;
mergedDerivativeToken._hashId = hashId; // Not used
return [mergedDerivativeToken, hashId, actualToken, cssVarsStr, cssVar?.key || ''];
},
cache => {
// Remove token will remove all related style
cleanTokenStyle(cache[0]._themeKey, styleContext.value?.cache?.instanceId);
},
([token, , , cssVarsStr]) => {
const { cssVar } = option.value;
if (cssVar && cssVarsStr) {
const style = updateCSS(cssVarsStr, hash(`css-variables-${token._themeKey}`), {
mark: ATTR_MARK,
prepend: 'queue',
attachTo: styleContext.value?.container,
priority: -999,
});
(style as any)[CSS_IN_JS_INSTANCE] = styleContext.value?.cache?.instanceId;
// Used for `useCacheToken` to remove on batch when token removed
style.setAttribute(ATTR_TOKEN, token._themeKey);
}
},
);
return cachedToken;
}
export const extract: ExtractStyle<TokenCacheValue<any>> = (cache, _effectStyles, options) => {
const [, , realToken, styleStr, cssVarKey] = cache;
const { plain } = options || {};
if (!styleStr) {
return null;
}
const styleId = realToken._tokenKey;
const order = -999;
// ====================== Style ======================
// Used for rc-util
const sharedAttrs = {
'data-vc-order': 'prependQueue',
'data-vc-priority': `${order}`,
};
const styleText = toStyleStr(styleStr, cssVarKey, styleId, sharedAttrs, plain);
return [order, styleId, styleText];
};

View File

@ -1,115 +0,0 @@
import { useStyleInject } from '../StyleContext';
import type { KeyType } from '../Cache';
import useCompatibleInsertionEffect from './useCompatibleInsertionEffect';
import useHMR from './useHMR';
import type { ShallowRef, Ref } from 'vue';
import { onBeforeUnmount, watch, computed } from 'vue';
export type ExtractStyle<CacheValue> = (
cache: CacheValue,
effectStyles: Record<string, boolean>,
options?: {
plain?: boolean;
},
) => [order: number, styleId: string, style: string] | null;
export default function useGlobalCache<CacheType>(
prefix: string,
keyPath: Ref<KeyType[]>,
cacheFn: () => CacheType,
onCacheRemove?: (cache: CacheType, fromHMR: boolean) => void,
// Add additional effect trigger by `useInsertionEffect`
onCacheEffect?: (cachedValue: CacheType) => void,
): ShallowRef<CacheType> {
const styleContext = useStyleInject();
const globalCache = computed(() => styleContext.value?.cache);
const deps = computed(() => [prefix, ...keyPath.value].join('%'));
const HMRUpdate = useHMR();
type UpdaterArgs = [times: number, cache: CacheType];
const buildCache = (updater?: (data: UpdaterArgs) => UpdaterArgs) => {
globalCache.value.update(deps.value, prevCache => {
const [times = 0, cache] = prevCache || [undefined, undefined];
// HMR should always ignore cache since developer may change it
let tmpCache = cache;
if (process.env.NODE_ENV !== 'production' && cache && HMRUpdate) {
onCacheRemove?.(tmpCache, HMRUpdate);
tmpCache = null;
}
const mergedCache = tmpCache || cacheFn();
const data: UpdaterArgs = [times, mergedCache];
// Call updater if need additional logic
return updater ? updater(data) : data;
});
};
watch(
deps,
() => {
buildCache();
},
{ immediate: true },
);
let cacheEntity = globalCache.value.get(deps.value);
// HMR clean the cache but not trigger `useMemo` again
// Let's fallback of this
// ref https://github.com/ant-design/cssinjs/issues/127
if (process.env.NODE_ENV !== 'production' && !cacheEntity) {
buildCache();
cacheEntity = globalCache.value.get(deps.value);
}
const cacheContent = computed(
() =>
(globalCache.value.get(deps.value) && globalCache.value.get(deps.value)![1]) ||
cacheEntity![1],
);
// Remove if no need anymore
useCompatibleInsertionEffect(
() => {
onCacheEffect?.(cacheContent.value);
},
polyfill => {
// It's bad to call build again in effect.
// But we have to do this since StrictMode will call effect twice
// which will clear cache on the first time.
buildCache(([times, cache]) => {
if (polyfill && times === 0) {
onCacheEffect?.(cacheContent.value);
}
return [times + 1, cache];
});
return () => {
globalCache.value.update(deps.value, prevCache => {
const [times = 0, cache] = prevCache || [];
const nextCount = times - 1;
if (nextCount <= 0) {
if (polyfill || !globalCache.value.get(deps.value)) {
onCacheRemove?.(cache, false);
}
return null;
}
return [times - 1, cache];
});
};
},
deps,
);
onBeforeUnmount(() => {
buildCache();
});
return cacheContent;
}

View File

@ -1,34 +0,0 @@
function useProdHMR() {
return false;
}
let webpackHMR = false;
function useDevHMR() {
return webpackHMR;
}
export default process.env.NODE_ENV === 'production' ? useProdHMR : useDevHMR;
// Webpack `module.hot.accept` do not support any deps update trigger
// We have to hack handler to force mark as HRM
if (
process.env.NODE_ENV !== 'production' &&
typeof module !== 'undefined' &&
module &&
(module as any).hot &&
typeof window !== 'undefined'
) {
const win = window as any;
if (typeof win.webpackHotUpdate === 'function') {
const originWebpackHotUpdate = win.webpackHotUpdate;
win.webpackHotUpdate = (...args: any[]) => {
webpackHMR = true;
setTimeout(() => {
webpackHMR = false;
}, 0);
return originWebpackHotUpdate(...args);
};
}
}

View File

@ -1,62 +0,0 @@
import extractStyle from './extractStyle';
import useCacheToken, { getComputedToken } from './hooks/useCacheToken';
import useCSSVarRegister from './hooks/useCSSVarRegister';
import type { CSSInterpolation, CSSObject } from './hooks/useStyleRegister';
import useStyleRegister from './hooks/useStyleRegister';
import Keyframes from './Keyframes';
import type { Linter } from './linters';
import {
legacyNotSelectorLinter,
logicalPropertiesLinter,
NaNLinter,
parentSelectorLinter,
} from './linters';
import type { StyleProviderProps } from './StyleContext';
import { createCache, StyleProvider } from './StyleContext';
import type { DerivativeFunc, TokenType } from './theme';
import { createTheme, Theme } from './theme';
import type { Transformer } from './transformers/interface';
import legacyLogicalPropertiesTransformer from './transformers/legacyLogicalProperties';
import px2remTransformer from './transformers/px2rem';
import { supportLogicProps, supportWhere, unit } from './util';
import { token2CSSVar } from './util/css-variables';
export {
Theme,
createTheme,
useStyleRegister,
useCSSVarRegister,
useCacheToken,
createCache,
StyleProvider,
Keyframes,
extractStyle,
getComputedToken,
// Transformer
legacyLogicalPropertiesTransformer,
px2remTransformer,
// Linters
logicalPropertiesLinter,
legacyNotSelectorLinter,
parentSelectorLinter,
NaNLinter,
// util
token2CSSVar,
unit,
};
export type {
TokenType,
CSSObject,
CSSInterpolation,
DerivativeFunc,
Transformer,
Linter,
StyleProviderProps,
};
export const _experimental = {
supportModernCSS: () => supportWhere() && supportLogicProps(),
};

View File

@ -1,25 +0,0 @@
import type { Linter } from './interface';
import { lintWarning } from './utils';
const linter: Linter = (key, value, info) => {
if (key === 'content') {
// From emotion: https://github.com/emotion-js/emotion/blob/main/packages/serialize/src/index.js#L63
const contentValuePattern =
/(attr|counters?|url|(((repeating-)?(linear|radial))|conic)-gradient)\(|(no-)?(open|close)-quote/;
const contentValues = ['normal', 'none', 'initial', 'inherit', 'unset'];
if (
typeof value !== 'string' ||
(contentValues.indexOf(value) === -1 &&
!contentValuePattern.test(value) &&
(value.charAt(0) !== value.charAt(value.length - 1) ||
(value.charAt(0) !== '"' && value.charAt(0) !== "'")))
) {
lintWarning(
`You seem to be using a value for 'content' without quotes, try replacing it with \`content: '"${value}"'\`.`,
info,
);
}
}
};
export default linter;

View File

@ -1,15 +0,0 @@
import type { Linter } from './interface';
import { lintWarning } from './utils';
const linter: Linter = (key, value, info) => {
if (key === 'animation') {
if (info.hashId && value !== 'none') {
lintWarning(
`You seem to be using hashed animation '${value}', in which case 'animationName' with Keyframe as value is recommended.`,
info,
);
}
}
};
export default linter;

View File

@ -1,7 +0,0 @@
export { default as contentQuotesLinter } from './contentQuotesLinter';
export { default as hashedAnimationLinter } from './hashedAnimationLinter';
export type { Linter } from './interface';
export { default as legacyNotSelectorLinter } from './legacyNotSelectorLinter';
export { default as logicalPropertiesLinter } from './logicalPropertiesLinter';
export { default as NaNLinter } from './NaNLinter';
export { default as parentSelectorLinter } from './parentSelectorLinter';

View File

@ -1,9 +0,0 @@
export interface LinterInfo {
path?: string;
hashId?: string;
parentSelectors: string[];
}
export interface Linter {
(key: string, value: string | number, info: LinterInfo): void;
}

View File

@ -1,33 +0,0 @@
import type { Linter, LinterInfo } from './interface';
import { lintWarning } from './utils';
function isConcatSelector(selector: string) {
const notContent = selector.match(/:not\(([^)]*)\)/)?.[1] || '';
// split selector. e.g.
// `h1#a.b` => ['h1', #a', '.b']
const splitCells = notContent.split(/(\[[^[]*])|(?=[.#])/).filter(str => str);
return splitCells.length > 1;
}
function parsePath(info: LinterInfo) {
return info.parentSelectors.reduce((prev, cur) => {
if (!prev) {
return cur;
}
return cur.includes('&') ? cur.replace(/&/g, prev) : `${prev} ${cur}`;
}, '');
}
const linter: Linter = (_key, _value, info) => {
const parentSelectorPath = parsePath(info);
const notList = parentSelectorPath.match(/:not\([^)]*\)/g) || [];
if (notList.length > 0 && notList.some(isConcatSelector)) {
lintWarning(`Concat ':not' selector not support in legacy browsers.`, info);
}
};
export default linter;

View File

@ -1,88 +0,0 @@
import type { Linter } from './interface';
import { lintWarning } from './utils';
const linter: Linter = (key, value, info) => {
switch (key) {
case 'marginLeft':
case 'marginRight':
case 'paddingLeft':
case 'paddingRight':
case 'left':
case 'right':
case 'borderLeft':
case 'borderLeftWidth':
case 'borderLeftStyle':
case 'borderLeftColor':
case 'borderRight':
case 'borderRightWidth':
case 'borderRightStyle':
case 'borderRightColor':
case 'borderTopLeftRadius':
case 'borderTopRightRadius':
case 'borderBottomLeftRadius':
case 'borderBottomRightRadius':
lintWarning(
`You seem to be using non-logical property '${key}' which is not compatible with RTL mode. Please use logical properties and values instead. For more information: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties.`,
info,
);
return;
case 'margin':
case 'padding':
case 'borderWidth':
case 'borderStyle':
// case 'borderColor':
if (typeof value === 'string') {
const valueArr = value.split(' ').map(item => item.trim());
if (valueArr.length === 4 && valueArr[1] !== valueArr[3]) {
lintWarning(
`You seem to be using '${key}' property with different left ${key} and right ${key}, which is not compatible with RTL mode. Please use logical properties and values instead. For more information: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties.`,
info,
);
}
}
return;
case 'clear':
case 'textAlign':
if (value === 'left' || value === 'right') {
lintWarning(
`You seem to be using non-logical value '${value}' of ${key}, which is not compatible with RTL mode. Please use logical properties and values instead. For more information: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties.`,
info,
);
}
return;
case 'borderRadius':
if (typeof value === 'string') {
const radiusGroups = value.split('/').map(item => item.trim());
const invalid = radiusGroups.reduce((result, group) => {
if (result) {
return result;
}
const radiusArr = group.split(' ').map(item => item.trim());
// borderRadius: '2px 4px'
if (radiusArr.length >= 2 && radiusArr[0] !== radiusArr[1]) {
return true;
}
// borderRadius: '4px 4px 2px'
if (radiusArr.length === 3 && radiusArr[1] !== radiusArr[2]) {
return true;
}
// borderRadius: '4px 4px 2px 4px'
if (radiusArr.length === 4 && radiusArr[2] !== radiusArr[3]) {
return true;
}
return result;
}, false);
if (invalid) {
lintWarning(
`You seem to be using non-logical value '${value}' of ${key}, which is not compatible with RTL mode. Please use logical properties and values instead. For more information: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties.`,
info,
);
}
}
return;
default:
}
};
export default linter;

View File

@ -1,15 +0,0 @@
import type { Linter } from '..';
import { lintWarning } from './utils';
const linter: Linter = (_key, _value, info) => {
if (
info.parentSelectors.some(selector => {
const selectors = selector.split(',');
return selectors.some(item => item.split('&').length > 2);
})
) {
lintWarning('Should not use more than one `&` in a selector.', info);
}
};
export default linter;

View File

@ -1,13 +0,0 @@
import devWarning from '../../../vc-util/warning';
import type { LinterInfo } from './interface';
export function lintWarning(message: string, info: LinterInfo) {
const { path, parentSelectors } = info;
devWarning(
false,
`[Ant Design Vue CSS-in-JS] ${path ? `Error in ${path}: ` : ''}${message}${
parentSelectors.length ? ` Selector: ${parentSelectors.join(' | ')}` : ''
}`,
);
}

View File

@ -1,38 +0,0 @@
import warning from '../../warning';
import type { DerivativeFunc, TokenType } from './interface';
let uuid = 0;
/**
* Theme with algorithms to derive tokens from design tokens.
* Use `createTheme` first which will help to manage the theme instance cache.
*/
export default class Theme<DesignToken extends TokenType, DerivativeToken extends TokenType> {
private derivatives: DerivativeFunc<DesignToken, DerivativeToken>[];
public readonly id: number;
constructor(
derivatives:
| DerivativeFunc<DesignToken, DerivativeToken>
| DerivativeFunc<DesignToken, DerivativeToken>[],
) {
this.derivatives = Array.isArray(derivatives) ? derivatives : [derivatives];
this.id = uuid;
if (derivatives.length === 0) {
warning(
derivatives.length > 0,
'[Ant Design Vue CSS-in-JS] Theme should have at least one derivative function.',
);
}
uuid += 1;
}
getDerivativeToken(token: DesignToken): DerivativeToken {
return this.derivatives.reduce<DerivativeToken>(
(result, derivative) => derivative(token, result),
undefined as any,
);
}
}

View File

@ -1,135 +0,0 @@
import type Theme from './Theme';
import type { DerivativeFunc } from './interface';
// ================================== Cache ==================================
type ThemeCacheMap = Map<
DerivativeFunc<any, any>,
{
map?: ThemeCacheMap;
value?: [Theme<any, any>, number];
}
>;
type DerivativeOptions = DerivativeFunc<any, any>[];
export function sameDerivativeOption(left: DerivativeOptions, right: DerivativeOptions) {
if (left.length !== right.length) {
return false;
}
for (let i = 0; i < left.length; i++) {
if (left[i] !== right[i]) {
return false;
}
}
return true;
}
export default class ThemeCache {
public static MAX_CACHE_SIZE = 20;
public static MAX_CACHE_OFFSET = 5;
private readonly cache: ThemeCacheMap;
private keys: DerivativeOptions[];
private cacheCallTimes: number;
constructor() {
this.cache = new Map();
this.keys = [];
this.cacheCallTimes = 0;
}
public size(): number {
return this.keys.length;
}
private internalGet(
derivativeOption: DerivativeOptions,
updateCallTimes = false,
): [Theme<any, any>, number] | undefined {
let cache: ReturnType<ThemeCacheMap['get']> = { map: this.cache };
derivativeOption.forEach(derivative => {
if (!cache) {
cache = undefined;
} else {
cache = cache?.map?.get(derivative);
}
});
if (cache?.value && updateCallTimes) {
cache.value[1] = this.cacheCallTimes++;
}
return cache?.value;
}
public get(derivativeOption: DerivativeOptions): Theme<any, any> | undefined {
return this.internalGet(derivativeOption, true)?.[0];
}
public has(derivativeOption: DerivativeOptions): boolean {
return !!this.internalGet(derivativeOption);
}
public set(derivativeOption: DerivativeOptions, value: Theme<any, any>): void {
// New cache
if (!this.has(derivativeOption)) {
if (this.size() + 1 > ThemeCache.MAX_CACHE_SIZE + ThemeCache.MAX_CACHE_OFFSET) {
const [targetKey] = this.keys.reduce<[DerivativeOptions, number]>(
(result, key) => {
const [, callTimes] = result;
if (this.internalGet(key)![1] < callTimes) {
return [key, this.internalGet(key)![1]];
}
return result;
},
[this.keys[0], this.cacheCallTimes],
);
this.delete(targetKey);
}
this.keys.push(derivativeOption);
}
let cache = this.cache;
derivativeOption.forEach((derivative, index) => {
if (index === derivativeOption.length - 1) {
cache.set(derivative, { value: [value, this.cacheCallTimes++] });
} else {
const cacheValue = cache.get(derivative);
if (!cacheValue) {
cache.set(derivative, { map: new Map() });
} else if (!cacheValue.map) {
cacheValue.map = new Map();
}
cache = cache.get(derivative)!.map!;
}
});
}
private deleteByPath(
currentCache: ThemeCacheMap,
derivatives: DerivativeFunc<any, any>[],
): Theme<any, any> | undefined {
const cache = currentCache.get(derivatives[0])!;
if (derivatives.length === 1) {
if (!cache.map) {
currentCache.delete(derivatives[0]);
} else {
currentCache.set(derivatives[0], { map: cache.map });
}
return cache.value?.[0];
}
const result = this.deleteByPath(cache.map!, derivatives.slice(1));
if ((!cache.map || cache.map.size === 0) && !cache.value) {
currentCache.delete(derivatives[0]);
}
return result;
}
public delete(derivativeOption: DerivativeOptions): Theme<any, any> | undefined {
// If cache exists
if (this.has(derivativeOption)) {
this.keys = this.keys.filter(item => !sameDerivativeOption(item, derivativeOption));
return this.deleteByPath(this.cache, derivativeOption);
}
return undefined;
}
}

View File

@ -1,26 +0,0 @@
import ThemeCache from './ThemeCache';
import Theme from './Theme';
import type { DerivativeFunc, TokenType } from './interface';
const cacheThemes = new ThemeCache();
/**
* Same as new Theme, but will always return same one if `derivative` not changed.
*/
export default function createTheme<
DesignToken extends TokenType,
DerivativeToken extends TokenType,
>(
derivatives:
| DerivativeFunc<DesignToken, DerivativeToken>[]
| DerivativeFunc<DesignToken, DerivativeToken>,
) {
const derivativeArr = Array.isArray(derivatives) ? derivatives : [derivatives];
// Create new theme if not exist
if (!cacheThemes.has(derivativeArr)) {
cacheThemes.set(derivativeArr, new Theme(derivativeArr));
}
// Get theme from cache and return
return cacheThemes.get(derivativeArr)!;
}

View File

@ -1,4 +0,0 @@
export { default as createTheme } from './createTheme';
export { default as Theme } from './Theme';
export { default as ThemeCache } from './ThemeCache';
export type { TokenType, DerivativeFunc } from './interface';

View File

@ -1,5 +0,0 @@
export type TokenType = object;
export type DerivativeFunc<DesignToken extends TokenType, DerivativeToken extends TokenType> = (
designToken: DesignToken,
derivativeToken?: DerivativeToken,
) => DerivativeToken;

View File

@ -1,5 +0,0 @@
import type { CSSObject } from '..';
export interface Transformer {
visit?: (cssObj: CSSObject) => CSSObject;
}

View File

@ -1,173 +0,0 @@
import type { CSSObject } from '..';
import type { Transformer } from './interface';
function splitValues(value: string | number): [values: (string | number)[], important: boolean] {
if (typeof value === 'number') {
return [[value], false];
}
const rawStyle = String(value).trim();
const importantCells = rawStyle.match(/(.*)(!important)/);
const splitStyle = (importantCells ? importantCells[1] : rawStyle).trim().split(/\s+/);
// Combine styles split in brackets, like `calc(1px + 2px)`
let temp = '';
let brackets = 0;
return [
splitStyle.reduce<string[]>((list, item) => {
if (item.includes('(') || item.includes(')')) {
const left = item.split('(').length - 1;
const right = item.split(')').length - 1;
brackets += left - right;
}
if (brackets === 0) {
list.push(temp + item);
temp = '';
} else if (brackets > 0) {
temp += item;
}
return list;
}, []),
!!importantCells,
];
}
type MatchValue = string[] & {
notSplit?: boolean;
};
function noSplit(list: MatchValue): MatchValue {
list.notSplit = true;
return list;
}
const keyMap: Record<string, MatchValue> = {
// Inset
inset: ['top', 'right', 'bottom', 'left'],
insetBlock: ['top', 'bottom'],
insetBlockStart: ['top'],
insetBlockEnd: ['bottom'],
insetInline: ['left', 'right'],
insetInlineStart: ['left'],
insetInlineEnd: ['right'],
// Margin
marginBlock: ['marginTop', 'marginBottom'],
marginBlockStart: ['marginTop'],
marginBlockEnd: ['marginBottom'],
marginInline: ['marginLeft', 'marginRight'],
marginInlineStart: ['marginLeft'],
marginInlineEnd: ['marginRight'],
// Padding
paddingBlock: ['paddingTop', 'paddingBottom'],
paddingBlockStart: ['paddingTop'],
paddingBlockEnd: ['paddingBottom'],
paddingInline: ['paddingLeft', 'paddingRight'],
paddingInlineStart: ['paddingLeft'],
paddingInlineEnd: ['paddingRight'],
// Border
borderBlock: noSplit(['borderTop', 'borderBottom']),
borderBlockStart: noSplit(['borderTop']),
borderBlockEnd: noSplit(['borderBottom']),
borderInline: noSplit(['borderLeft', 'borderRight']),
borderInlineStart: noSplit(['borderLeft']),
borderInlineEnd: noSplit(['borderRight']),
// Border width
borderBlockWidth: ['borderTopWidth', 'borderBottomWidth'],
borderBlockStartWidth: ['borderTopWidth'],
borderBlockEndWidth: ['borderBottomWidth'],
borderInlineWidth: ['borderLeftWidth', 'borderRightWidth'],
borderInlineStartWidth: ['borderLeftWidth'],
borderInlineEndWidth: ['borderRightWidth'],
// Border style
borderBlockStyle: ['borderTopStyle', 'borderBottomStyle'],
borderBlockStartStyle: ['borderTopStyle'],
borderBlockEndStyle: ['borderBottomStyle'],
borderInlineStyle: ['borderLeftStyle', 'borderRightStyle'],
borderInlineStartStyle: ['borderLeftStyle'],
borderInlineEndStyle: ['borderRightStyle'],
// Border color
borderBlockColor: ['borderTopColor', 'borderBottomColor'],
borderBlockStartColor: ['borderTopColor'],
borderBlockEndColor: ['borderBottomColor'],
borderInlineColor: ['borderLeftColor', 'borderRightColor'],
borderInlineStartColor: ['borderLeftColor'],
borderInlineEndColor: ['borderRightColor'],
// Border radius
borderStartStartRadius: ['borderTopLeftRadius'],
borderStartEndRadius: ['borderTopRightRadius'],
borderEndStartRadius: ['borderBottomLeftRadius'],
borderEndEndRadius: ['borderBottomRightRadius'],
};
function wrapImportantAndSkipCheck(value: string | number, important: boolean) {
let parsedValue = value;
if (important) {
parsedValue = `${parsedValue} !important`;
}
return { _skip_check_: true, value: parsedValue };
}
/**
* Convert css logical properties to legacy properties.
* Such as: `margin-block-start` to `margin-top`.
* Transform list:
* - inset
* - margin
* - padding
* - border
*/
const transform: Transformer = {
visit: cssObj => {
const clone: CSSObject = {};
Object.keys(cssObj).forEach(key => {
const value = cssObj[key];
const matchValue = keyMap[key];
if (matchValue && (typeof value === 'number' || typeof value === 'string')) {
const [values, important] = splitValues(value);
if (matchValue.length && matchValue.notSplit) {
// not split means always give same value like border
matchValue.forEach(matchKey => {
clone[matchKey] = wrapImportantAndSkipCheck(value, important);
});
} else if (matchValue.length === 1) {
// Handle like `marginBlockStart` => `marginTop`
clone[matchValue[0]] = wrapImportantAndSkipCheck(value, important);
} else if (matchValue.length === 2) {
// Handle like `marginBlock` => `marginTop` & `marginBottom`
matchValue.forEach((matchKey, index) => {
clone[matchKey] = wrapImportantAndSkipCheck(values[index] ?? values[0], important);
});
} else if (matchValue.length === 4) {
// Handle like `inset` => `top` & `right` & `bottom` & `left`
matchValue.forEach((matchKey, index) => {
clone[matchKey] = wrapImportantAndSkipCheck(
values[index] ?? values[index - 2] ?? values[0],
important,
);
});
} else {
clone[key] = value;
}
} else {
clone[key] = value;
}
});
return clone;
},
};
export default transform;

View File

@ -1,77 +0,0 @@
/**
* respect https://github.com/cuth/postcss-pxtorem
*/
// @ts-ignore
import unitless from '@emotion/unitless';
import type { CSSObject } from '..';
import type { Transformer } from './interface';
export interface Options {
/**
* The root font size.
* @default 16
*/
rootValue?: number;
/**
* The decimal numbers to allow the REM units to grow to.
* @default 5
*/
precision?: number;
/**
* Whether to allow px to be converted in media queries.
* @default false
*/
mediaQuery?: boolean;
}
const pxRegex = /url\([^)]+\)|var\([^)]+\)|(\d*\.?\d+)px/g;
function toFixed(number: number, precision: number) {
const multiplier = Math.pow(10, precision + 1),
wholeNumber = Math.floor(number * multiplier);
return (Math.round(wholeNumber / 10) * 10) / multiplier;
}
const transform = (options: Options = {}): Transformer => {
const { rootValue = 16, precision = 5, mediaQuery = false } = options;
const pxReplace = (m: string, $1: any) => {
if (!$1) return m;
const pixels = parseFloat($1);
// covenant: pixels <= 1, not transform to rem @zombieJ
if (pixels <= 1) return m;
const fixedVal = toFixed(pixels / rootValue, precision);
return `${fixedVal}rem`;
};
const visit = (cssObj: CSSObject): CSSObject => {
const clone: CSSObject = { ...cssObj };
Object.entries(cssObj).forEach(([key, value]) => {
if (typeof value === 'string' && value.includes('px')) {
const newValue = value.replace(pxRegex, pxReplace);
clone[key] = newValue;
}
// no unit
if (!unitless[key] && typeof value === 'number' && value !== 0) {
clone[key] = `${value}px`.replace(pxRegex, pxReplace);
}
// Media queries
const mergedKey = key.trim();
if (mergedKey.startsWith('@') && mergedKey.includes('px') && mediaQuery) {
const newKey = key.replace(pxRegex, pxReplace);
clone[newKey] = clone[key];
delete clone[key];
}
});
return clone;
};
return { visit };
};
export default transform;

View File

@ -1,11 +1,14 @@
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<string, ValueType>();

View File

@ -31,7 +31,6 @@ export function createCache() {
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
// Not force move if no head
if ((style as any)[CSS_IN_JS_INSTANCE] === cssinjsInstanceId) {
document.head.insertBefore(style, firstChild);

View File

@ -1,20 +1,19 @@
import hash from '@emotion/hash';
import { ATTR_TOKEN, CSS_IN_JS_INSTANCE, useStyleInject } from '../StyleContext';
import { updateCSS } from '../../../vc-util/Dom/dynamicCSS';
import { ATTR_MARK, ATTR_TOKEN, CSS_IN_JS_INSTANCE, useStyleInject } from '../StyleContext';
import type Theme from '../theme/Theme';
import { flattenToken, memoResult, token2key, toStyleStr } from '../util';
import { transformToken } from '../util/css-variables';
import type { ExtractStyle } from './useGlobalCache';
import useGlobalCache from './useGlobalCache';
import { flattenToken, token2key } from '../util';
import type { Ref } from 'vue';
import { ref, computed } from 'vue';
const EMPTY_OVERRIDE = {};
const isProduction = process.env.NODE_ENV === 'production';
// nuxt generate when NODE_ENV is prerender
const isPrerender = process.env.NODE_ENV === 'prerender';
// Generate different prefix to make user selector break in production env.
// This helps developer not to do style override directly on the hash id.
const hashPrefix = !isProduction && !isPrerender ? 'css-dev-only-do-not-override' : 'css';
const hashPrefix = process.env.NODE_ENV !== 'production' ? 'css-dev-only-do-not-override' : 'css';
export interface Option<DerivativeToken, DesignToken> {
/**
@ -46,6 +45,22 @@ export interface Option<DerivativeToken, DesignToken> {
override: object,
theme: Theme<any, any>,
) => DerivativeToken;
/**
* Transform token to css variables.
*/
cssVar?: {
/** Prefix for css variables */
prefix?: string;
/** Tokens that should not be appended with unit */
unitless?: Record<string, boolean>;
/** Tokens that should not be transformed to css variables */
ignore?: Record<string, boolean>;
/** Tokens that preserves origin value */
preserve?: Record<string, boolean>;
/** Key for current theme. Useful for customizing and should be unique */
key?: string;
};
}
const tokenKeys = new Map<string, number>();
@ -94,6 +109,7 @@ export const getComputedToken = <DerivativeToken = object, DesignToken = Derivat
format?: (token: DesignToken) => DerivativeToken,
) => {
const derivativeToken = theme.getDerivativeToken(originToken);
// Merge with override
let mergedDerivativeToken = {
...derivativeToken,
@ -108,6 +124,16 @@ export const getComputedToken = <DerivativeToken = object, DesignToken = Derivat
return mergedDerivativeToken;
};
export const TOKEN_PREFIX = 'token';
type TokenCacheValue<DerivativeToken> = [
token: DerivativeToken & { _tokenKey: string; _themeKey: string },
hashId: string,
realToken: DerivativeToken & { _tokenKey: string },
cssVarStr: string,
cssVarKey: string,
];
/**
* Cache theme derivative token as global shared one
* @param theme Theme entity
@ -119,21 +145,27 @@ export default function useCacheToken<DerivativeToken = object, DesignToken = De
theme: Ref<Theme<any, any>>,
tokens: Ref<Partial<DesignToken>[]>,
option: Ref<Option<DerivativeToken, DesignToken>> = ref({}),
) {
const style = useStyleInject();
): Ref<TokenCacheValue<DerivativeToken>> {
const styleContext = useStyleInject();
// Basic - We do basic cache here
const mergedToken = computed(() => Object.assign({}, ...tokens.value));
const tokenStr = computed(() => flattenToken(mergedToken.value));
const overrideTokenStr = computed(() => flattenToken(option.value.override || EMPTY_OVERRIDE));
const mergedToken = computed(() =>
memoResult(() => Object.assign({}, ...tokens.value), tokens.value),
);
const cachedToken = useGlobalCache<[DerivativeToken & { _tokenKey: string }, string]>(
'token',
const tokenStr = computed(() => flattenToken(mergedToken.value));
const overrideTokenStr = computed(() => flattenToken(option.value.override ?? EMPTY_OVERRIDE));
const cssVarStr = computed(() => (option.value.cssVar ? flattenToken(option.value.cssVar) : ''));
const cachedToken = useGlobalCache<TokenCacheValue<DerivativeToken>>(
TOKEN_PREFIX,
computed(() => [
option.value.salt || '',
theme.value.id,
option.value.salt ?? '',
theme.value?.id,
tokenStr.value,
overrideTokenStr.value,
cssVarStr.value,
]),
() => {
const {
@ -141,25 +173,82 @@ export default function useCacheToken<DerivativeToken = object, DesignToken = De
override = EMPTY_OVERRIDE,
formatToken,
getComputedToken: compute,
cssVar,
} = option.value;
const mergedDerivativeToken = compute
let mergedDerivativeToken = compute
? compute(mergedToken.value, override, theme.value)
: getComputedToken(mergedToken.value, override, theme.value, formatToken);
// Replace token value with css variables
const actualToken = { ...mergedDerivativeToken };
let cssVarsStr = '';
if (!!cssVar) {
[mergedDerivativeToken, cssVarsStr] = transformToken(mergedDerivativeToken, cssVar.key!, {
prefix: cssVar.prefix,
ignore: cssVar.ignore,
unitless: cssVar.unitless,
preserve: cssVar.preserve,
});
}
// Optimize for `useStyleRegister` performance
const tokenKey = token2key(mergedDerivativeToken, salt);
mergedDerivativeToken._tokenKey = tokenKey;
recordCleanToken(tokenKey);
actualToken._tokenKey = token2key(actualToken, salt);
const themeKey = cssVar?.key ?? tokenKey;
mergedDerivativeToken._themeKey = themeKey;
recordCleanToken(themeKey);
const hashId = `${hashPrefix}-${hash(tokenKey)}`;
mergedDerivativeToken._hashId = hashId; // Not used
return [mergedDerivativeToken, hashId];
return [mergedDerivativeToken, hashId, actualToken, cssVarsStr, cssVar?.key || ''];
},
cache => {
// Remove token will remove all related style
cleanTokenStyle(cache[0]._tokenKey, style.value?.cache.instanceId);
cleanTokenStyle(cache[0]._themeKey, styleContext.value?.cache?.instanceId);
},
([token, , , cssVarsStr]) => {
const { cssVar } = option.value;
if (cssVar && cssVarsStr) {
const style = updateCSS(cssVarsStr, hash(`css-variables-${token._themeKey}`), {
mark: ATTR_MARK,
prepend: 'queue',
attachTo: styleContext.value?.container,
priority: -999,
});
(style as any)[CSS_IN_JS_INSTANCE] = styleContext.value?.cache?.instanceId;
// Used for `useCacheToken` to remove on batch when token removed
style.setAttribute(ATTR_TOKEN, token._themeKey);
}
},
);
return cachedToken;
}
export const extract: ExtractStyle<TokenCacheValue<any>> = (cache, _effectStyles, options) => {
const [, , realToken, styleStr, cssVarKey] = cache;
const { plain } = options || {};
if (!styleStr) {
return null;
}
const styleId = realToken._tokenKey;
const order = -999;
// ====================== Style ======================
// Used for rc-util
const sharedAttrs = {
'data-vc-order': 'prependQueue',
'data-vc-priority': `${order}`,
};
const styleText = toStyleStr(styleStr, cssVarKey, styleId, sharedAttrs, plain);
return [order, styleId, styleText];
};

View File

@ -1,58 +1,115 @@
import { useStyleInject } from '../StyleContext';
import type { KeyType } from '../Cache';
import useCompatibleInsertionEffect from './useCompatibleInsertionEffect';
import useHMR from './useHMR';
import type { ShallowRef, Ref } from 'vue';
import { onBeforeUnmount, watch, watchEffect, shallowRef } from 'vue';
export default function useClientCache<CacheType>(
import { onBeforeUnmount, watch, computed } from 'vue';
export type ExtractStyle<CacheValue> = (
cache: CacheValue,
effectStyles: Record<string, boolean>,
options?: {
plain?: boolean;
},
) => [order: number, styleId: string, style: string] | null;
export default function useGlobalCache<CacheType>(
prefix: string,
keyPath: Ref<KeyType[]>,
cacheFn: () => CacheType,
onCacheRemove?: (cache: CacheType, fromHMR: boolean) => void,
// Add additional effect trigger by `useInsertionEffect`
onCacheEffect?: (cachedValue: CacheType) => void,
): ShallowRef<CacheType> {
const styleContext = useStyleInject();
const fullPathStr = shallowRef('');
const res = shallowRef<CacheType>();
watchEffect(() => {
fullPathStr.value = [prefix, ...keyPath.value].join('%');
});
const globalCache = computed(() => styleContext.value?.cache);
const deps = computed(() => [prefix, ...keyPath.value].join('%'));
const HMRUpdate = useHMR();
const clearCache = (pathStr: string) => {
styleContext.value.cache.update(pathStr, prevCache => {
const [times = 0, cache] = prevCache || [];
const nextCount = times - 1;
if (nextCount === 0) {
onCacheRemove?.(cache, false);
return null;
type UpdaterArgs = [times: number, cache: CacheType];
const buildCache = (updater?: (data: UpdaterArgs) => UpdaterArgs) => {
globalCache.value.update(deps.value, prevCache => {
const [times = 0, cache] = prevCache || [undefined, undefined];
// HMR should always ignore cache since developer may change it
let tmpCache = cache;
if (process.env.NODE_ENV !== 'production' && cache && HMRUpdate) {
onCacheRemove?.(tmpCache, HMRUpdate);
tmpCache = null;
}
return [times - 1, cache];
const mergedCache = tmpCache || cacheFn();
const data: UpdaterArgs = [times, mergedCache];
// Call updater if need additional logic
return updater ? updater(data) : data;
});
};
watch(
fullPathStr,
(newStr, oldStr) => {
if (oldStr) clearCache(oldStr);
// Create cache
styleContext.value.cache.update(newStr, prevCache => {
const [times = 0, cache] = prevCache || [];
// HMR should always ignore cache since developer may change it
let tmpCache = cache;
if (process.env.NODE_ENV !== 'production' && cache && HMRUpdate) {
onCacheRemove?.(tmpCache, HMRUpdate);
tmpCache = null;
}
const mergedCache = tmpCache || cacheFn();
return [times + 1, mergedCache];
});
res.value = styleContext.value.cache.get(fullPathStr.value)![1];
deps,
() => {
buildCache();
},
{ immediate: true },
);
let cacheEntity = globalCache.value.get(deps.value);
// HMR clean the cache but not trigger `useMemo` again
// Let's fallback of this
// ref https://github.com/ant-design/cssinjs/issues/127
if (process.env.NODE_ENV !== 'production' && !cacheEntity) {
buildCache();
cacheEntity = globalCache.value.get(deps.value);
}
const cacheContent = computed(
() =>
(globalCache.value.get(deps.value) && globalCache.value.get(deps.value)![1]) ||
cacheEntity![1],
);
// Remove if no need anymore
useCompatibleInsertionEffect(
() => {
onCacheEffect?.(cacheContent.value);
},
polyfill => {
// It's bad to call build again in effect.
// But we have to do this since StrictMode will call effect twice
// which will clear cache on the first time.
buildCache(([times, cache]) => {
if (polyfill && times === 0) {
onCacheEffect?.(cacheContent.value);
}
return [times + 1, cache];
});
return () => {
globalCache.value.update(deps.value, prevCache => {
const [times = 0, cache] = prevCache || [];
const nextCount = times - 1;
if (nextCount <= 0) {
if (polyfill || !globalCache.value.get(deps.value)) {
onCacheRemove?.(cache, false);
}
return null;
}
return [times - 1, cache];
});
};
},
deps,
);
onBeforeUnmount(() => {
clearCache(fullPathStr.value);
buildCache();
});
return res;
return cacheContent;
}

View File

@ -1,91 +0,0 @@
import canUseDom from '../../../../_util/canUseDom';
import { ATTR_MARK } from '../../StyleContext';
export const ATTR_CACHE_MAP = 'data-ant-cssinjs-cache-path';
/**
* This marks style from the css file.
* Which means not exist in `<style />` tag.
*/
export const CSS_FILE_STYLE = '_FILE_STYLE__';
export function serialize(cachePathMap: Record<string, string>) {
return Object.keys(cachePathMap)
.map(path => {
const hash = cachePathMap[path];
return `${path}:${hash}`;
})
.join(';');
}
let cachePathMap: Record<string, string>;
let fromCSSFile = true;
/**
* @private Test usage only. Can save remove if no need.
*/
export function reset(mockCache?: Record<string, string>, fromFile = true) {
cachePathMap = mockCache!;
fromCSSFile = fromFile;
}
export function prepare() {
if (!cachePathMap) {
cachePathMap = {};
if (canUseDom()) {
const div = document.createElement('div');
div.className = ATTR_CACHE_MAP;
div.style.position = 'fixed';
div.style.visibility = 'hidden';
div.style.top = '-9999px';
document.body.appendChild(div);
let content = getComputedStyle(div).content || '';
content = content.replace(/^"/, '').replace(/"$/, '');
// Fill data
content.split(';').forEach(item => {
const [path, hash] = item.split(':');
cachePathMap[path] = hash;
});
// Remove inline record style
const inlineMapStyle = document.querySelector(`style[${ATTR_CACHE_MAP}]`);
if (inlineMapStyle) {
fromCSSFile = false;
inlineMapStyle.parentNode?.removeChild(inlineMapStyle);
}
document.body.removeChild(div);
}
}
}
export function existPath(path: string) {
prepare();
return !!cachePathMap[path];
}
export function getStyleAndHash(path: string): [style: string | null, hash: string] {
const hash = cachePathMap[path];
let styleStr: string | null = null;
if (hash && canUseDom()) {
if (fromCSSFile) {
styleStr = CSS_FILE_STYLE;
} else {
const style = document.querySelector(`style[${ATTR_MARK}="${cachePathMap[path]}"]`);
if (style) {
styleStr = style.innerHTML;
} else {
// Clean up since not exist anymore
delete cachePathMap[path];
}
}
}
return [styleStr, hash];
}

View File

@ -1,566 +0,0 @@
import hash from '@emotion/hash';
import type * as CSS from 'csstype';
// @ts-ignore
import unitless from '@emotion/unitless';
import { compile, serialize, stringify } from 'stylis';
import type { Theme, Transformer } from '../..';
import type Cache from '../../Cache';
import type Keyframes from '../../Keyframes';
import type { Linter } from '../../linters';
import { contentQuotesLinter, hashedAnimationLinter } from '../../linters';
import type { HashPriority } from '../../StyleContext';
import {
useStyleInject,
ATTR_CACHE_PATH,
ATTR_MARK,
ATTR_TOKEN,
CSS_IN_JS_INSTANCE,
} from '../../StyleContext';
import { supportLayer } from '../../util';
import useGlobalCache from '../useGlobalCache';
import { removeCSS, updateCSS } from '../../../../vc-util/Dom/dynamicCSS';
import type { Ref } from 'vue';
import { computed } from 'vue';
import type { VueNode } from '../../../type';
import canUseDom from '../../../../_util/canUseDom';
import {
ATTR_CACHE_MAP,
existPath,
getStyleAndHash,
serialize as serializeCacheMap,
} from './cacheMapUtil';
const isClientSide = canUseDom();
const SKIP_CHECK = '_skip_check_';
const MULTI_VALUE = '_multi_value_';
export type CSSProperties = Omit<CSS.PropertiesFallback<number | string>, 'animationName'> & {
animationName?: CSS.PropertiesFallback<number | string>['animationName'] | Keyframes;
};
export type CSSPropertiesWithMultiValues = {
[K in keyof CSSProperties]:
| CSSProperties[K]
| readonly Extract<CSSProperties[K], string>[]
| {
[SKIP_CHECK]?: boolean;
[MULTI_VALUE]?: boolean;
value: CSSProperties[K] | CSSProperties[K][];
};
};
export type CSSPseudos = { [K in CSS.Pseudos]?: CSSObject };
type ArrayCSSInterpolation = readonly CSSInterpolation[];
export type InterpolationPrimitive = null | undefined | boolean | number | string | CSSObject;
export type CSSInterpolation = InterpolationPrimitive | ArrayCSSInterpolation | Keyframes;
export type CSSOthersObject = Record<string, CSSInterpolation>;
export interface CSSObject extends CSSPropertiesWithMultiValues, CSSPseudos, CSSOthersObject {}
// ============================================================================
// == Parser ==
// ============================================================================
// Preprocessor style content to browser support one
export function normalizeStyle(styleStr: string): string {
const serialized = serialize(compile(styleStr), stringify);
return serialized.replace(/\{%%%\:[^;];}/g, ';');
}
function isCompoundCSSProperty(value: CSSObject[string]) {
return typeof value === 'object' && value && (SKIP_CHECK in value || MULTI_VALUE in value);
}
// hash
function injectSelectorHash(key: string, hashId: string, hashPriority?: HashPriority) {
if (!hashId) {
return key;
}
const hashClassName = `.${hashId}`;
const hashSelector = hashPriority === 'low' ? `:where(${hashClassName})` : hashClassName;
// hashId
const keys = key.split(',').map(k => {
const fullPath = k.trim().split(/\s+/);
// Selector HTML Element
let firstPath = fullPath[0] || '';
const htmlElement = firstPath.match(/^\w+/)?.[0] || '';
firstPath = `${htmlElement}${hashSelector}${firstPath.slice(htmlElement.length)}`;
return [firstPath, ...fullPath.slice(1)].join(' ');
});
return keys.join(',');
}
export interface ParseConfig {
hashId?: string;
hashPriority?: HashPriority;
layer?: string;
path?: string;
transformers?: Transformer[];
linters?: Linter[];
}
export interface ParseInfo {
root?: boolean;
injectHash?: boolean;
parentSelectors: string[];
}
// Global effect style will mount once and not removed
// The effect will not save in SSR cache (e.g. keyframes)
const globalEffectStyleKeys = new Set();
/**
* @private Test only. Clear the global effect style keys.
*/
export const _cf =
process.env.NODE_ENV !== 'production' ? () => globalEffectStyleKeys.clear() : undefined;
// Parse CSSObject to style content
export const parseStyle = (
interpolation: CSSInterpolation,
config: ParseConfig = {},
{ root, injectHash, parentSelectors }: ParseInfo = {
root: true,
parentSelectors: [],
},
): [
parsedStr: string,
// Style content which should be unique on all of the style (e.g. Keyframes).
// Firefox will flick with same animation name when exist multiple same keyframes.
effectStyle: Record<string, string>,
] => {
const { hashId, layer, path, hashPriority, transformers = [], linters = [] } = config;
let styleStr = '';
let effectStyle: Record<string, string> = {};
function parseKeyframes(keyframes: Keyframes) {
const animationName = keyframes.getName(hashId);
if (!effectStyle[animationName]) {
const [parsedStr] = parseStyle(keyframes.style, config, {
root: false,
parentSelectors,
});
effectStyle[animationName] = `@keyframes ${keyframes.getName(hashId)}${parsedStr}`;
}
}
function flattenList(list: ArrayCSSInterpolation, fullList: CSSObject[] = []) {
list.forEach(item => {
if (Array.isArray(item)) {
flattenList(item, fullList);
} else if (item) {
fullList.push(item as CSSObject);
}
});
return fullList;
}
const flattenStyleList = flattenList(
Array.isArray(interpolation) ? interpolation : [interpolation],
);
flattenStyleList.forEach(originStyle => {
// Only root level can use raw string
const style: CSSObject = typeof originStyle === 'string' && !root ? {} : originStyle;
if (typeof style === 'string') {
styleStr += `${style}\n`;
} else if ((style as any)._keyframe) {
// Keyframe
parseKeyframes(style as unknown as Keyframes);
} else {
const mergedStyle = transformers.reduce((prev, trans) => trans?.visit?.(prev) || prev, style);
// Normal CSSObject
Object.keys(mergedStyle).forEach(key => {
const value = mergedStyle[key];
if (
typeof value === 'object' &&
value &&
(key !== 'animationName' || !(value as Keyframes)._keyframe) &&
!isCompoundCSSProperty(value)
) {
let subInjectHash = false;
//
let mergedKey = key.trim();
// Whether treat child as root. In most case it is false.
let nextRoot = false;
//
if ((root || injectHash) && hashId) {
if (mergedKey.startsWith('@')) {
// hashId
subInjectHash = true;
} else {
// hashId
mergedKey = injectSelectorHash(key, hashId, hashPriority);
}
} else if (root && !hashId && (mergedKey === '&' || mergedKey === '')) {
// In case of `{ '&': { a: { color: 'red' } } }` or `{ '': { a: { color: 'red' } } }` without hashId,
// we will get `&{a:{color:red;}}` or `{a:{color:red;}}` string for stylis to compile.
// But it does not conform to stylis syntax,
// and finally we will get `{color:red;}` as css, which is wrong.
// So we need to remove key in root, and treat child `{ a: { color: 'red' } }` as root.
mergedKey = '';
nextRoot = true;
}
const [parsedStr, childEffectStyle] = parseStyle(value as any, config, {
root: nextRoot,
injectHash: subInjectHash,
parentSelectors: [...parentSelectors, mergedKey],
});
effectStyle = {
...effectStyle,
...childEffectStyle,
};
styleStr += `${mergedKey}${parsedStr}`;
} else {
function appendStyle(cssKey: string, cssValue: any) {
if (
process.env.NODE_ENV !== 'production' &&
(typeof value !== 'object' || !(value as any)?.[SKIP_CHECK])
) {
[contentQuotesLinter, hashedAnimationLinter, ...linters].forEach(linter =>
linter(cssKey, cssValue, { path, hashId, parentSelectors }),
);
}
//
const styleName = cssKey.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);
// Auto suffix with px
let formatValue = cssValue;
if (!unitless[cssKey] && typeof formatValue === 'number' && formatValue !== 0) {
formatValue = `${formatValue}px`;
}
// handle animationName & Keyframe value
if (cssKey === 'animationName' && (cssValue as Keyframes)?._keyframe) {
parseKeyframes(cssValue as Keyframes);
formatValue = (cssValue as Keyframes).getName(hashId);
}
styleStr += `${styleName}:${formatValue};`;
}
const actualValue = (value as any)?.value ?? value;
if (
typeof value === 'object' &&
(value as any)?.[MULTI_VALUE] &&
Array.isArray(actualValue)
) {
actualValue.forEach(item => {
appendStyle(key, item);
});
} else {
appendStyle(key, actualValue);
}
}
});
}
});
if (!root) {
styleStr = `{${styleStr}}`;
} else if (layer && supportLayer()) {
const layerCells = layer.split(',');
const layerName = layerCells[layerCells.length - 1].trim();
styleStr = `@layer ${layerName} {${styleStr}}`;
// Order of layer if needed
if (layerCells.length > 1) {
// zombieJ: stylis do not support layer order, so we need to handle it manually.
styleStr = `@layer ${layer}{%%%:%}${styleStr}`;
}
}
return [styleStr, effectStyle];
};
// ============================================================================
// == Register ==
// ============================================================================
function uniqueHash(path: (string | number)[], styleStr: string) {
return hash(`${path.join('%')}${styleStr}`);
}
// function Empty() {
// return null;
// }
/**
* Register a style to the global style sheet.
*/
export default function useStyleRegister(
info: Ref<{
theme: Theme<any, any>;
token: any;
path: string[];
hashId?: string;
layer?: string;
nonce?: string | (() => string);
clientOnly?: boolean;
/**
* Tell cssinjs the insert order of style.
* It's useful when you need to insert style
* before other style to overwrite for the same selector priority.
*/
order?: number;
}>,
styleFn: () => CSSInterpolation,
) {
const styleContext = useStyleInject();
const tokenKey = computed(() => info.value.token._tokenKey as string);
const fullPath = computed(() => [tokenKey.value, ...info.value.path]);
// Check if need insert style
let isMergedClientSide = isClientSide;
if (process.env.NODE_ENV !== 'production' && styleContext.value.mock !== undefined) {
isMergedClientSide = styleContext.value.mock === 'client';
}
// const [cacheStyle[0], cacheStyle[1], cacheStyle[2]]
useGlobalCache<
[
styleStr: string,
tokenKey: string,
styleId: string,
effectStyle: Record<string, string>,
clientOnly: boolean | undefined,
order: number,
]
>(
'style',
fullPath,
// Create cache if needed
() => {
const { path, hashId, layer, nonce, clientOnly, order = 0 } = info.value;
const cachePath = fullPath.value.join('|');
// Get style from SSR inline style directly
if (existPath(cachePath)) {
const [inlineCacheStyleStr, styleHash] = getStyleAndHash(cachePath);
if (inlineCacheStyleStr) {
return [inlineCacheStyleStr, tokenKey.value, styleHash, {}, clientOnly, order];
}
}
const styleObj = styleFn();
const { hashPriority, container, transformers, linters, cache } = styleContext.value;
const [parsedStyle, effectStyle] = parseStyle(styleObj, {
hashId,
hashPriority,
layer,
path: path.join('-'),
transformers,
linters,
});
const styleStr = normalizeStyle(parsedStyle);
const styleId = uniqueHash(fullPath.value, styleStr);
if (isMergedClientSide) {
const mergedCSSConfig: Parameters<typeof updateCSS>[2] = {
mark: ATTR_MARK,
prepend: 'queue',
attachTo: container,
priority: order,
};
const nonceStr = typeof nonce === 'function' ? nonce() : nonce;
if (nonceStr) {
mergedCSSConfig.csp = { nonce: nonceStr };
}
const style = updateCSS(styleStr, styleId, mergedCSSConfig);
(style as any)[CSS_IN_JS_INSTANCE] = cache.instanceId;
// Used for `useCacheToken` to remove on batch when token removed
style.setAttribute(ATTR_TOKEN, tokenKey.value);
// Dev usage to find which cache path made this easily
if (process.env.NODE_ENV !== 'production') {
style.setAttribute(ATTR_CACHE_PATH, fullPath.value.join('|'));
}
// Inject client side effect style
Object.keys(effectStyle).forEach(effectKey => {
if (!globalEffectStyleKeys.has(effectKey)) {
globalEffectStyleKeys.add(effectKey);
// Inject
updateCSS(normalizeStyle(effectStyle[effectKey]), `_effect-${effectKey}`, {
mark: ATTR_MARK,
prepend: 'queue',
attachTo: container,
});
}
});
}
return [styleStr, tokenKey.value, styleId, effectStyle, clientOnly, order];
},
// Remove cache if no need
([, , styleId], fromHMR) => {
if ((fromHMR || styleContext.value.autoClear) && isClientSide) {
removeCSS(styleId, { mark: ATTR_MARK });
}
},
);
return (node: VueNode) => {
return node;
// let styleNode: VueNode;
// if (!styleContext.ssrInline || isMergedClientSide || !styleContext.defaultCache) {
// styleNode = <Empty />;
// } else {
// styleNode = (
// <style
// {...{
// [ATTR_TOKEN]: cacheStyle.value[1],
// [ATTR_MARK]: cacheStyle.value[2],
// }}
// innerHTML={cacheStyle.value[0]}
// />
// );
// }
// return (
// <>
// {styleNode}
// {node}
// </>
// );
};
}
// ============================================================================
// == SSR ==
// ============================================================================
export function extractStyle(cache: Cache, plain = false) {
const matchPrefix = `style%`;
// prefix with `style` is used for `useStyleRegister` to cache style context
const styleKeys = Array.from(cache.cache.keys()).filter(key => key.startsWith(matchPrefix));
// Common effect styles like animation
const effectStyles: Record<string, boolean> = {};
// Mapping of cachePath to style hash
const cachePathMap: Record<string, string> = {};
let styleText = '';
function toStyleStr(
style: string,
tokenKey?: string,
styleId?: string,
customizeAttrs: Record<string, string> = {},
) {
const attrs: Record<string, string | undefined> = {
...customizeAttrs,
[ATTR_TOKEN]: tokenKey,
[ATTR_MARK]: styleId,
};
const attrStr = Object.keys(attrs)
.map(attr => {
const val = attrs[attr];
return val ? `${attr}="${val}"` : null;
})
.filter(v => v)
.join(' ');
return plain ? style : `<style ${attrStr}>${style}</style>`;
}
// ====================== Fill Style ======================
type OrderStyle = [order: number, style: string];
const orderStyles: OrderStyle[] = styleKeys
.map(key => {
const cachePath = key.slice(matchPrefix.length).replace(/%/g, '|');
const [styleStr, tokenKey, styleId, effectStyle, clientOnly, order]: [
string,
string,
string,
Record<string, string>,
boolean,
number,
] = cache.cache.get(key)![1];
// Skip client only style
if (clientOnly) {
return null! as OrderStyle;
}
// ====================== Style ======================
// Used for vc-util
const sharedAttrs = {
'data-vc-order': 'prependQueue',
'data-vc-priority': `${order}`,
};
let keyStyleText = toStyleStr(styleStr, tokenKey, styleId, sharedAttrs);
// Save cache path with hash mapping
cachePathMap[cachePath] = styleId;
// =============== Create effect style ===============
if (effectStyle) {
Object.keys(effectStyle).forEach(effectKey => {
// Effect style can be reused
if (!effectStyles[effectKey]) {
effectStyles[effectKey] = true;
keyStyleText += toStyleStr(
normalizeStyle(effectStyle[effectKey]),
tokenKey,
`_effect-${effectKey}`,
sharedAttrs,
);
}
});
}
const ret: OrderStyle = [order, keyStyleText];
return ret;
})
.filter(o => o);
orderStyles
.sort((o1, o2) => o1[0] - o2[0])
.forEach(([, style]) => {
styleText += style;
});
// ==================== Fill Cache Path ====================
styleText += toStyleStr(
`.${ATTR_CACHE_MAP}{content:"${serializeCacheMap(cachePathMap)}";}`,
undefined,
undefined,
{
[ATTR_CACHE_MAP]: ATTR_CACHE_MAP,
},
);
return styleText;
}

View File

@ -1,51 +1,37 @@
import useCacheToken from './hooks/useCacheToken';
import extractStyle from './extractStyle';
import useCacheToken, { getComputedToken } from './hooks/useCacheToken';
import useCSSVarRegister from './hooks/useCSSVarRegister';
import type { CSSInterpolation, CSSObject } from './hooks/useStyleRegister';
import useStyleRegister, { extractStyle } from './hooks/useStyleRegister';
import useStyleRegister from './hooks/useStyleRegister';
import Keyframes from './Keyframes';
import type { Linter } from './linters';
import { legacyNotSelectorLinter, logicalPropertiesLinter, parentSelectorLinter } from './linters';
import type { StyleContextProps, StyleProviderProps } from './StyleContext';
import { createCache, useStyleInject, useStyleProvider, StyleProvider } from './StyleContext';
import {
legacyNotSelectorLinter,
logicalPropertiesLinter,
NaNLinter,
parentSelectorLinter,
} from './linters';
import type { StyleProviderProps } from './StyleContext';
import { createCache, StyleProvider } from './StyleContext';
import type { DerivativeFunc, TokenType } from './theme';
import { createTheme, Theme } from './theme';
import type { Transformer } from './transformers/interface';
import legacyLogicalPropertiesTransformer from './transformers/legacyLogicalProperties';
import px2remTransformer from './transformers/px2rem';
import { supportLogicProps, supportWhere } from './util';
import { supportLogicProps, supportWhere, unit } from './util';
import { token2CSSVar } from './util/css-variables';
const cssinjs = {
Theme,
createTheme,
useStyleRegister,
useCacheToken,
createCache,
useStyleInject,
useStyleProvider,
Keyframes,
extractStyle,
// Transformer
legacyLogicalPropertiesTransformer,
px2remTransformer,
// Linters
logicalPropertiesLinter,
legacyNotSelectorLinter,
parentSelectorLinter,
// cssinjs
StyleProvider,
};
export {
Theme,
createTheme,
useStyleRegister,
useCSSVarRegister,
useCacheToken,
createCache,
useStyleInject,
useStyleProvider,
StyleProvider,
Keyframes,
extractStyle,
getComputedToken,
// Transformer
legacyLogicalPropertiesTransformer,
@ -55,9 +41,11 @@ export {
logicalPropertiesLinter,
legacyNotSelectorLinter,
parentSelectorLinter,
NaNLinter,
// cssinjs
StyleProvider,
// util
token2CSSVar,
unit,
};
export type {
TokenType,
@ -66,12 +54,9 @@ export type {
DerivativeFunc,
Transformer,
Linter,
StyleContextProps,
StyleProviderProps,
};
export const _experimental = {
supportModernCSS: () => supportWhere() && supportLogicProps(),
};
export default cssinjs;

View File

@ -3,4 +3,5 @@ export { default as hashedAnimationLinter } from './hashedAnimationLinter';
export type { Linter } from './interface';
export { default as legacyNotSelectorLinter } from './legacyNotSelectorLinter';
export { default as logicalPropertiesLinter } from './logicalPropertiesLinter';
export { default as NaNLinter } from './NaNLinter';
export { default as parentSelectorLinter } from './parentSelectorLinter';

View File

@ -6,8 +6,8 @@ export function lintWarning(message: string, info: LinterInfo) {
devWarning(
false,
`[Ant Design Vue CSS-in-JS] ${path ? `Error in '${path}': ` : ''}${message}${
parentSelectors.length ? ` Selector info: ${parentSelectors.join(' -> ')}` : ''
`[Ant Design Vue CSS-in-JS] ${path ? `Error in ${path}: ` : ''}${message}${
parentSelectors.length ? ` Selector: ${parentSelectors.join(' | ')}` : ''
}`,
);
}

View File

@ -1,34 +1,36 @@
import type { CSSObject } from '..';
import type { Transformer } from './interface';
function splitValues(value: string | number) {
function splitValues(value: string | number): [values: (string | number)[], important: boolean] {
if (typeof value === 'number') {
return [value];
return [[value], false];
}
const splitStyle = String(value).split(/\s+/);
const rawStyle = String(value).trim();
const importantCells = rawStyle.match(/(.*)(!important)/);
const splitStyle = (importantCells ? importantCells[1] : rawStyle).trim().split(/\s+/);
// Combine styles split in brackets, like `calc(1px + 2px)`
let temp = '';
let brackets = 0;
return splitStyle.reduce<string[]>((list, item) => {
if (item.includes('(')) {
temp += item;
brackets += item.split('(').length - 1;
} else if (item.includes(')')) {
temp += ` ${item}`;
brackets -= item.split(')').length - 1;
if (brackets === 0) {
list.push(temp);
temp = '';
return [
splitStyle.reduce<string[]>((list, item) => {
if (item.includes('(') || item.includes(')')) {
const left = item.split('(').length - 1;
const right = item.split(')').length - 1;
brackets += left - right;
}
} else if (brackets > 0) {
temp += ` ${item}`;
} else {
list.push(item);
}
return list;
}, []);
if (brackets === 0) {
list.push(temp + item);
temp = '';
} else if (brackets > 0) {
temp += item;
}
return list;
}, []),
!!importantCells,
];
}
type MatchValue = string[] & {
@ -105,8 +107,14 @@ const keyMap: Record<string, MatchValue> = {
borderEndEndRadius: ['borderBottomRightRadius'],
};
function skipCheck(value: string | number) {
return { _skip_check_: true, value };
function wrapImportantAndSkipCheck(value: string | number, important: boolean) {
let parsedValue = value;
if (important) {
parsedValue = `${parsedValue} !important`;
}
return { _skip_check_: true, value: parsedValue };
}
/**
@ -127,25 +135,28 @@ const transform: Transformer = {
const matchValue = keyMap[key];
if (matchValue && (typeof value === 'number' || typeof value === 'string')) {
const values = splitValues(value);
const [values, important] = splitValues(value);
if (matchValue.length && matchValue.notSplit) {
// not split means always give same value like border
matchValue.forEach(matchKey => {
clone[matchKey] = skipCheck(value);
clone[matchKey] = wrapImportantAndSkipCheck(value, important);
});
} else if (matchValue.length === 1) {
// Handle like `marginBlockStart` => `marginTop`
clone[matchValue[0]] = skipCheck(value);
clone[matchValue[0]] = wrapImportantAndSkipCheck(value, important);
} else if (matchValue.length === 2) {
// Handle like `marginBlock` => `marginTop` & `marginBottom`
matchValue.forEach((matchKey, index) => {
clone[matchKey] = skipCheck(values[index] ?? values[0]);
clone[matchKey] = wrapImportantAndSkipCheck(values[index] ?? values[0], important);
});
} else if (matchValue.length === 4) {
// Handle like `inset` => `top` & `right` & `bottom` & `left`
matchValue.forEach((matchKey, index) => {
clone[matchKey] = skipCheck(values[index] ?? values[index - 2] ?? values[0]);
clone[matchKey] = wrapImportantAndSkipCheck(
values[index] ?? values[index - 2] ?? values[0],
important,
);
});
} else {
clone[key] = value;

View File

@ -1,6 +1,7 @@
/**
* respect https://github.com/cuth/postcss-pxtorem
*/
// @ts-ignore
import unitless from '@emotion/unitless';
import type { CSSObject } from '..';
import type { Transformer } from './interface';

View File

@ -1,118 +0,0 @@
import hash from '@emotion/hash';
import { removeCSS, updateCSS } from '../../vc-util/Dom/dynamicCSS';
import canUseDom from '../canUseDom';
import { Theme } from './theme';
// Create a cache here to avoid always loop generate
const flattenTokenCache = new WeakMap<any, string>();
export function flattenToken(token: any) {
let str = flattenTokenCache.get(token) || '';
if (!str) {
Object.keys(token).forEach(key => {
const value = token[key];
str += key;
if (value instanceof Theme) {
str += value.id;
} else if (value && typeof value === 'object') {
str += flattenToken(value);
} else {
str += value;
}
});
// Put in cache
flattenTokenCache.set(token, str);
}
return str;
}
/**
* Convert derivative token to key string
*/
export function token2key(token: any, salt: string): string {
return hash(`${salt}_${flattenToken(token)}`);
}
const randomSelectorKey = `random-${Date.now()}-${Math.random()}`.replace(/\./g, '');
// Magic `content` for detect selector support
const checkContent = '_bAmBoO_';
function supportSelector(
styleStr: string,
handleElement: (ele: HTMLElement) => void,
supportCheck?: (ele: HTMLElement) => boolean,
): boolean {
if (canUseDom()) {
updateCSS(styleStr, randomSelectorKey);
const ele = document.createElement('div');
ele.style.position = 'fixed';
ele.style.left = '0';
ele.style.top = '0';
handleElement?.(ele);
document.body.appendChild(ele);
if (process.env.NODE_ENV !== 'production') {
ele.innerHTML = 'Test';
ele.style.zIndex = '9999999';
}
const support = supportCheck
? supportCheck(ele)
: getComputedStyle(ele).content?.includes(checkContent);
ele.parentNode?.removeChild(ele);
removeCSS(randomSelectorKey);
return support;
}
return false;
}
let canLayer: boolean | undefined = undefined;
export function supportLayer(): boolean {
if (canLayer === undefined) {
canLayer = supportSelector(
`@layer ${randomSelectorKey} { .${randomSelectorKey} { content: "${checkContent}"!important; } }`,
ele => {
ele.className = randomSelectorKey;
},
);
}
return canLayer!;
}
let canWhere: boolean | undefined = undefined;
export function supportWhere(): boolean {
if (canWhere === undefined) {
canWhere = supportSelector(
`:where(.${randomSelectorKey}) { content: "${checkContent}"!important; }`,
ele => {
ele.className = randomSelectorKey;
},
);
}
return canWhere!;
}
let canLogic: boolean | undefined = undefined;
export function supportLogicProps(): boolean {
if (canLogic === undefined) {
canLogic = supportSelector(
`.${randomSelectorKey} { inset-block: 93px !important; }`,
ele => {
ele.className = randomSelectorKey;
},
ele => getComputedStyle(ele).bottom === '93px',
);
}
return canLogic!;
}

View File

@ -3,10 +3,10 @@ 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';
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<ButtonToken, CSSObject> = token => {
const { componentCls, calc } = token;

View File

@ -1,6 +1,6 @@
import type { CSSObject } from '../../_util/_cssinjs';
import type { CSSObject } from '../../_util/cssinjs';
import type { ButtonToken } from './token';
import type { GenerateStyle } from '../../_theme/internal';
import type { GenerateStyle } from '../../theme/internal';
const genButtonBorderStyle = (buttonTypeCls: string, borderColor: string) => ({
// Border

View File

@ -1,9 +1,9 @@
import type { CSSObject } from '../../_util/_cssinjs';
import { unit } from '../../_util/_cssinjs';
import type { CSSObject } from '../../_util/cssinjs';
import { unit } from '../../_util/cssinjs';
import { genFocusStyle } from '../../style';
import type { GenerateStyle } from '../../_theme/internal';
import { genStyleHooks, mergeToken } from '../../_theme/internal';
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';

View File

@ -1,7 +1,7 @@
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';
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 {

View File

@ -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';

View File

@ -1,4 +1,4 @@
import { useToken } from '../../_theme/internal';
import { useToken } from '../../theme/internal';
import type { Ref } from 'vue';
import { computed } from 'vue';

View File

@ -1,5 +1,5 @@
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 devWarning from '../../vc-util/warning';

View File

@ -14,7 +14,7 @@ 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 defaultSeedToken from '../theme/themes/seed';
import type { ConfigProviderInnerProps, ConfigProviderProps, Theme, ThemeConfig } from './context';
import {
useConfigContextProvider,
@ -25,8 +25,8 @@ import {
} from './context';
import { useProviderSize } from './SizeContext';
import { useProviderDisabled } from './DisabledContext';
import { createTheme } from '../_util/_cssinjs';
import { defaultTheme, DesignTokenProvider } from '../_theme/context';
import { createTheme } from '../_util/cssinjs';
import { defaultTheme, DesignTokenProvider } from '../theme/context';
export type {
ConfigProviderProps,

View File

@ -1,7 +1,7 @@
import type { CSSObject } from '../../_util/_cssinjs';
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<string>) => {

View File

@ -1,9 +1,9 @@
import type { CSSObject } from '../../_util/_cssinjs';
import { unit } from '../../_util/_cssinjs';
import type { CSSObject } from '../../_util/cssinjs';
import { unit } from '../../_util/cssinjs';
import { TinyColor } from '@ctrl/tinycolor';
import { genFocusStyle, resetComponent } from '../../style';
import type { FullToken, GenerateStyle, GetDefaultToken } from '../../_theme/internal';
import { genStyleHooks, mergeToken } from '../../_theme/internal';
import type { FullToken, GenerateStyle, GetDefaultToken } from '../../theme/internal';
import { genStyleHooks, mergeToken } from '../../theme/internal';
export interface ComponentToken {
/**

View File

@ -1,9 +0,0 @@
import getAlphaColor from '../util/getAlphaColor';
describe('util', () => {
describe('getAlphaColor', () => {
it('should not process color with alpha', () => {
expect(getAlphaColor('rgba(0, 0, 0, 0.5)', 'rgba(255, 255, 255)')).toBe('rgba(0, 0, 0, 0.5)');
});
});
});

View File

@ -9,8 +9,8 @@ import {
watch,
computed,
} from 'vue';
import type { Theme } from '../_util/_cssinjs';
import { createTheme } from '../_util/_cssinjs';
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';

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
import { createTheme, getComputedToken } from '../_util/_cssinjs';
import { createTheme, getComputedToken } from '../_util/cssinjs';
import type { ThemeConfig } from '../config-provider/context';
import type { AliasToken } from './interface';
import defaultDerivative from './themes/default';

View File

@ -1,9 +1,10 @@
/* eslint-disable import/prefer-default-export */
import getDesignToken from './getDesignToken';
import type { GlobalToken, MappingAlgorithm } from './interface';
import { defaultConfig, useToken as useInternalToken } from './internal';
import type { GlobalToken } from './interface';
import defaultAlgorithm from './themes/default';
import darkAlgorithm from './themes/dark';
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.
@ -15,7 +16,7 @@ function useToken() {
return { theme, token, hashId };
}
export { type GlobalToken };
export type { GlobalToken, MappingAlgorithm };
export default {
/** @private Test Usage. Do not use in production. */
@ -28,4 +29,5 @@ export default {
defaultAlgorithm,
darkAlgorithm,
compactAlgorithm,
getDesignToken,
};

View File

@ -8,124 +8,604 @@ import type { MapToken } from './maps';
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;
/** Weak action. Such as `allowClear` or Alert close button */
/**
/**
* @nameZH
* @nameEN Weak action icon color
* @desc allowClear Alert
* @descEN Weak action. Such as `allowClear` or Alert close button
*/
colorIcon: string;
/** Weak action hover color. Such as `allowClear` or Alert close button */
/** */
/**
* @nameZH
* @nameEN Weak action icon hover color
* @desc allowClear Alert
* @descEN Weak action hover color. Such as `allowClear` or Alert close button
*/
colorIconHover: string;
colorLink: string;
colorLinkHover: string;
colorLinkActive: 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
/** Operation icon in Select, Cascader, etc. icon fontSize. Normal is same as fontSizeSM */
/**
* @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;
/** For heading like h1, h2, h3 or option selected item */
/**
* @nameZH h1h2h3
* @nameEN Font weight for heading components (such as h1, h2, h3) or selected item
* @desc h1h2h3
* @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;
/** Used for DefaultButton, Switch which has default outline */
/**
* @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

View File

@ -1,21 +1,33 @@
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 FloatButtonComponentToken } from '../../float-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 DropdownComponentToken } from '../../dropdown/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';
@ -23,9 +35,12 @@ 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';
@ -35,53 +50,55 @@ import type { ComponentToken as SkeletonComponentToken } from '../../skeleton/st
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';
import type { ComponentToken as TourComponentToken } from '../../tour/style';
import type { ComponentToken as QRCodeComponentToken } from '../../qrcode/style';
import type { ComponentToken as AppComponentToken } from '../../app/style';
import type { ComponentToken as WaveToken } from '../../_util/wave/style';
import type { ComponentToken as FlexToken } from '../../flex/style';
export interface ComponentTokenMap {
Affix?: {};
Affix?: AffixComponentToken;
Alert?: AlertComponentToken;
Anchor?: AnchorComponentToken;
Avatar?: AvatarComponentToken;
Badge?: {};
Badge?: BadgeComponentToken;
Button?: ButtonComponentToken;
Breadcrumb?: {};
Breadcrumb?: BreadcrumbComponentToken;
Card?: CardComponentToken;
Carousel?: CarouselComponentToken;
Cascader?: CascaderComponentToken;
Checkbox?: CheckboxComponentToken;
// ColorPicker?: ColorPickerComponentToken;
Collapse?: CollapseComponentToken;
Comment?: {};
Comment?: CommentComponentToken;
DatePicker?: DatePickerComponentToken;
Descriptions?: {};
Descriptions?: DescriptionsComponentToken;
Divider?: DividerComponentToken;
Drawer?: DrawerComponentToken;
Dropdown?: DropdownComponentToken;
Empty?: EmptyComponentToken;
Flex?: FlexComponentToken;
FloatButton?: FloatButtonComponentToken;
Form?: {};
Grid?: {};
Form?: FormComponentToken;
Grid?: GridComponentToken;
Image?: ImageComponentToken;
Input?: {};
Input?: InputComponentToken;
InputNumber?: InputNumberComponentToken;
Layout?: LayoutComponentToken;
List?: ListComponentToken;
Mentions?: MentionsComponentToken;
Notification?: NotificationComponentToken;
PageHeader?: {};
Pagination?: {};
PageHeader?: PageHeaderComponentToken;
Pagination?: PaginationComponentToken;
Popover?: PopoverComponentToken;
Popconfirm?: PopconfirmComponentToken;
Rate?: RateComponentToken;
@ -92,11 +109,11 @@ export interface ComponentTokenMap {
Skeleton?: SkeletonComponentToken;
Slider?: SliderComponentToken;
Spin?: SpinComponentToken;
Statistic?: {};
Switch?: {};
Statistic?: StatisticComponentToken;
Switch?: SwitchComponentToken;
Tag?: TagComponentToken;
Tree?: {};
TreeSelect?: {};
Tree?: TreeComponentToken;
TreeSelect?: TreeSelectComponentToken;
Typography?: TypographyComponentToken;
Timeline?: TimelineComponentToken;
Transfer?: TransferComponentToken;
@ -114,8 +131,7 @@ export interface ComponentTokenMap {
Tour?: TourComponentToken;
QRCode?: QRCodeComponentToken;
App?: AppComponentToken;
Flex?: FlexToken;
// /** @private Internal TS definition. Do not use. */
/** @private Internal TS definition. Do not use. */
Wave?: WaveToken;
}

View File

@ -1,5 +1,12 @@
import type { ComponentTokenMap } from './components';
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<SeedToken, MapToken>;
export type OverrideToken = {
[key in keyof ComponentTokenMap]: Partial<ComponentTokenMap[key]> & Partial<AliasToken>;
@ -8,18 +15,30 @@ export type OverrideToken = {
/** Final token which contains the components level override */
export type GlobalToken = AliasToken & ComponentTokenMap;
export { PresetColors } from './presetColors';
export type { PresetColorType, ColorPalettes, PresetColorKey } from './presetColors';
export type { SeedToken } from './seeds';
export type { AliasToken } from './alias';
export type { ComponentTokenMap } from './components';
export type {
MapToken,
ColorMapToken,
ColorNeutralMapToken,
CommonMapToken,
HeightMapToken,
SizeMapToken,
FontMapToken,
HeightMapToken,
MapToken,
SizeMapToken,
StyleMapToken,
} from './maps';
export type { AliasToken } from './alias';
export type { ComponentTokenMap } from './components';
export { PresetColors } from './presetColors';
export type {
LegacyColorPalettes,
ColorPalettes,
PresetColorKey,
PresetColorType,
} from './presetColors';
export type { SeedToken } from './seeds';
export type UseComponentStyleResult = [(node: VueNode) => VueNode, Ref<string>];
export type GenerateStyle<
ComponentToken extends object = AliasToken,
ReturnType = CSSInterpolation,
> = (token: ComponentToken) => ReturnType;

View File

@ -13,25 +13,31 @@ export interface ColorNeutralMapToken {
/**
* @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;
@ -58,24 +64,28 @@ export interface ColorNeutralMapToken {
/**
* @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 RateSkeleton 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 SliderSegmented 使
* @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;
@ -83,27 +93,39 @@ export interface ColorNeutralMapToken {
/**
* @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;
}
/**
@ -112,12 +134,15 @@ export interface ColorNeutralMapToken {
interface ColorPrimaryMapToken {
/**
* @nameZH
* @desc */
* @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
* @nameEN Light background color of primary color
* @desc
* @descEN Light background color of primary color, usually used for weak visual level selection state.
*/
@ -125,49 +150,65 @@ interface ColorPrimaryMapToken {
/**
* @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
* @desc Slider
* @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
* @desc Slider Button Hover 使
* @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
* @desc 使
* @nameEN Hover state of primary color
* @desc
* @descEN Hover state under the main color gradient.
*/
colorPrimaryHover: string; // 5
/**
* @nameZH
* @desc
* @nameEN Active state of primary color
* @desc
* @descEN Dark active state under the main color gradient.
*/
colorPrimaryActive: string; // 7
/**
* @nameZH
* @desc
* @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
* @desc
* @nameEN Text color of primary color
* @desc
* @descEN Text color under the main color gradient.
*/
colorPrimaryText: string; // 9
/**
* @nameZH
* @desc
* @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
}
@ -191,49 +232,65 @@ interface ColorSuccessMapToken {
/**
* @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 ResultProgress 使
* @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
}
@ -241,60 +298,81 @@ interface ColorSuccessMapToken {
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
}
@ -302,53 +380,81 @@ interface ColorWarningMapToken {
interface ColorInfoMapToken {
/**
* @nameZH
* @desc
* @nameEN Light background color of information color
* @desc
* @descEN Light background color of information color.
*/
colorInfoBg: string; // 1
/**
* @nameZH
* @desc
* @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
}
@ -356,62 +462,117 @@ interface ColorInfoMapToken {
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 {
ColorInfoMapToken,
ColorLinkMapToken {
/**
* @nameZH
* @desc

View File

@ -1,49 +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;
}

View File

@ -1,19 +1,31 @@
import type { ColorPalettes } from '../presetColors';
import type { ColorPalettes, LegacyColorPalettes } from '../presetColors';
import type { SeedToken } from '../seeds';
import type { SizeMapToken, HeightMapToken } from './size';
import type { ColorMapToken } from './colors';
import type { StyleMapToken } from './style';
import type { FontMapToken } from './font';
import type { HeightMapToken, SizeMapToken } from './size';
import type { StyleMapToken } from './style';
export * from './colors';
export * from './style';
export * from './size';
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;
}
@ -25,6 +37,7 @@ export interface CommonMapToken extends StyleMapToken {
export interface MapToken
extends SeedToken,
ColorPalettes,
LegacyColorPalettes,
ColorMapToken,
SizeMapToken,
HeightMapToken,

View File

@ -51,18 +51,24 @@ export interface HeightMapToken {
/**
* @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;
}

View File

@ -10,8 +10,9 @@ export interface StyleMapToken {
/**
* @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.
* @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;
@ -32,7 +33,11 @@ export interface StyleMapToken {
*/
borderRadiusLG: number;
/**
* @nameZH
* @nameEN Outer Border Radius
* @default 4
* @desc
* @descEN Outer border radius
*/
borderRadiusOuter: number;
}

Some files were not shown because too many files have changed in this diff Show More