시맨틱 토큰

시맨틱 토큰 (Semantic Tokens)

시맨틱 토큰은 특정 컨텍스트에서 사용되도록 설계된 토큰이에요. 앱의 디자인 결정에 의미를 부여할 때 유용하답니다.

출처: 문서

본문

개요

시맨틱 토큰은 다음 속성들로 구성돼요.

  • value: 토큰의 값 또는 기존 토큰에 대한 참조
  • description: 토큰을 어떤 용도로 쓸 수 있는지에 대한 (선택) 설명

시맨틱 토큰 정의하기

대부분의 경우 시맨틱 토큰의 값은 기존 토큰을 참조해요.

시맨틱 토큰에서 값을 참조하려면 토큰 참조 문법 {}를 사용하세요.

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)

시맨틱 토큰 사용하기

시맨틱 토큰을 정의한 뒤에는 Chakra CLI를 실행해 테마 타입을 생성해요. postinstall, CI, 모노레포에서 typegen을 실행하는 방법은 CLI 문서를 참고하세요.

npx @chakra-ui/cli typegen ./src/theme.ts

이제 에디터에서 토큰에 대한 자동 완성이 제공돼요.

<Box color="danger">Hello World</Box>

조건부 토큰

시맨틱 토큰은 라이트/다크 모드 같은 조건에 따라 값이 바뀔 수도 있어요.

예를 들어 라이트/다크 모드에 따라 자동으로 바뀌는 색상을 원한다면 이렇게 하면 돼요.

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)

시맨틱 토큰에서 사용하는 조건은 at-rule 또는 부모 선택자 조건이어야 해요.

시맨틱 토큰 중첩

시맨틱 토큰은 중첩해서 토큰의 계층 구조를 만들 수 있어요. 토큰을 함께 그룹화하고 싶을 때 유용해요.

중첩 토큰의 기본 값을 정의하려면 DEFAULT 키를 사용하세요.

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 토큰을 다음 방식으로 사용할 수 있어요.

<Box bg="bg">
  <Box bg="bg.primary">Hello World</Box>
  <Box bg="bg.secondary">Hello World</Box>
</Box>

레시피에서 사용하기

시맨틱 토큰은 레시피 정의에서도 사용할 수 있어요. 이름으로 참조하면 돼요.

import { defineRecipe } from "@chakra-ui/react"

const cardRecipe = defineRecipe({
  base: {
    bg: "bg.subtle", // semantic token
    color: "fg", // semantic token
    borderColor: "border",
  },
})

더 알아보기 (Learn more)

  • 토큰 문서에서 디자인 토큰 정의 방법을 알아보세요.
  • 테마 개요에서 Chakra UI 테마 시스템 전반을 알아보세요.