语义令牌
利用语义标记进行应用中的设计决策。
概述
¥Overview
语义标记是设计用于特定上下文的标记。语义令牌包含以下属性:
¥Semantic tokens are tokens that are designed to be used in a specific context. A semantic token consists of the following properties:
-
value
:token 的值或对现有 token 的引用。 -
description
:可选的令牌用途描述。
定义语义标记
¥Defining Semantic Tokens
在大多数情况下,语义令牌的值引用现有令牌。
¥In most cases, the value of a semantic token references to an existing token.
要在语义标记中引用值,请使用标记引用 {}
语法。
theme.ts
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const config = defineConfig({
theme: {
tokens: {
colors: {
red: { value: "#EE0F0F" },
},
},
semanticTokens: {
colors: {
danger: { value: "{colors.red}" },
},
},
},
})
export default createSystem(defaultConfig, config)
使用语义标记
¥Using Semantic Tokens
定义语义令牌后,我们建议使用 Chakra CLI 为你的令牌生成主题类型。
¥After defining semantic tokens, we recommend using the Chakra CLI to generate theme typings for your tokens.
npx @chakra-ui/cli typegen ./src/theme.ts
这将为你的编辑器中的令牌提供自动补齐功能。
¥This will provide autocompletion for your tokens in your editor.
<Box color="danger">Hello World</Box>
条件标记
¥Conditional Token
语义标记也可以根据明夜间模式等条件进行更改。
¥Semantic tokens can also be changed based on the conditions like light and dark modes.
例如,如果你希望颜色根据亮色或暗色模式自动更改。
¥For example, if you want a color to change automatically based on light or dark mode.
theme.ts
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const config = defineConfig({
theme: {
semanticTokens: {
colors: {
danger: {
value: { base: "{colors.red}", _dark: "{colors.darkred}" },
},
success: {
value: { base: "{colors.green}", _dark: "{colors.darkgreen}" },
},
},
},
},
})
export default createSystem(defaultConfig, config)
语义令牌嵌套
¥Semantic Token Nesting
语义标记可以嵌套以创建标记层次结构。当你想将 token 分组在一起时,这很有用。
¥Semantic tokens can be nested to create a hierarchy of tokens. This is useful when you want to group tokens together.
使用 DEFAULT
键定义嵌套 token 的默认值。
¥Use the DEFAULT
key to define the default value of a nested token.
theme.ts
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
const config = defineConfig({
theme: {
semanticTokens: {
colors: {
bg: {
DEFAULT: { value: "{colors.gray.100}" },
primary: { value: "{colors.teal.100}" },
secondary: { value: "{colors.gray.100}" },
},
},
},
},
})
export default createSystem(defaultConfig, config)
这允许以以下方式使用 bg
令牌:
¥This allows the use of the bg
token in the following ways:
<Box bg="bg">
<Box bg="bg.primary">Hello World</Box>
<Box bg="bg.secondary">Hello World</Box>
</Box>