Utilities for converting theme tokens to CSS custom properties, with support for CSS calc() expressions, token flattening, and semantic token handling. This system enables dynamic theming and runtime theme switching through CSS variables.
Core utilities for creating and managing CSS custom properties with proper naming and fallback support.
/**
* Adds prefix to CSS variable names
* @param value - The variable name
* @param prefix - Optional prefix to add
* @returns Prefixed variable name
*/
function addPrefix(value: string, prefix?: string): string;
/**
* Creates CSS variable reference with optional fallback
* @param name - CSS variable name (including --)
* @param fallback - Optional fallback value
* @returns CSS var() function string
*/
function toVarReference(name: string, fallback?: string): string;
/**
* Creates CSS variable definition with proper escaping
* @param value - Variable name
* @param prefix - Optional prefix
* @returns Escaped CSS variable name with --
*/
function toVarDefinition(value: string, prefix?: string): string;
/**
* Creates CSS variable object with both definition and reference
* @param name - Variable name (without --)
* @param fallback - Optional fallback value for reference
* @param cssVarPrefix - Optional prefix for variable name
* @returns Object with variable and reference properties
*/
function cssVar(name: string, fallback?: string, cssVarPrefix?: string): {
variable: string;
reference: string;
};
/**
* Defines multiple CSS variables with consistent scoping
* @param scope - Scope prefix for all variables
* @param keys - Array of variable names or [name, fallback] tuples
* @returns Record mapping keys to CSS variable objects
*/
function defineCssVars<K extends string>(
scope: string,
keys: Array<K | [K, string]>
): Record<K, { variable: string; reference: string }>;Usage Examples:
import { cssVar, defineCssVars, toVarReference, toVarDefinition } from "@chakra-ui/styled-system";
// Single CSS variable
const $size = cssVar("button-size");
const $color = cssVar("button-color", "blue.500");
console.log($size.variable); // "--button-size"
console.log($size.reference); // "var(--button-size)"
console.log($color.reference); // "var(--button-color, blue.500)"
// Use in styles
const buttonStyles = {
[$size.variable]: "40px",
[$color.variable]: "colors.red.500",
width: $size.reference,
backgroundColor: $color.reference
};
// Multiple variables with scoping
const tooltipVars = defineCssVars("tooltip", [
"bg",
"color",
["arrow-size", "8px"], // with fallback
"border-radius"
]);
const tooltipStyles = {
[tooltipVars.bg.variable]: "colors.gray.800",
[tooltipVars.color.variable]: "colors.white",
// arrow-size already has fallback defined
backgroundColor: tooltipVars.bg.reference,
color: tooltipVars.color.reference,
borderRadius: tooltipVars["border-radius"].reference
};
// Manual variable creation
const customVar = toVarDefinition("my-spacing", "chakra");
const customRef = toVarReference(customVar, "1rem");
// customVar: "--chakra-my-spacing"
// customRef: "var(--chakra-my-spacing, 1rem)"Chainable calculation utilities for creating complex CSS calc() expressions with proper operand handling.
/**
* Operand types for calc expressions
*/
type Operand = string | number | { reference: string };
/**
* Chainable calc expression interface
*/
interface CalcChain {
/** Add operands to the expression */
add(...operands: Array<Operand>): CalcChain;
/** Subtract operands from the expression */
subtract(...operands: Array<Operand>): CalcChain;
/** Multiply the expression by operands */
multiply(...operands: Array<Operand>): CalcChain;
/** Divide the expression by operands */
divide(...operands: Array<Operand>): CalcChain;
/** Negate the expression */
negate(): CalcChain;
/** Convert to CSS calc() string */
toString(): string;
}
/**
* Creates chainable calc expression or static calc functions
* @param x - Initial operand for chainable calc
* @returns CalcChain for method chaining
*/
function calc(x: Operand): CalcChain;
// Static calc functions
namespace calc {
/** Create addition calc expression */
function add(...operands: Array<Operand>): string;
/** Create subtraction calc expression */
function subtract(...operands: Array<Operand>): string;
/** Create multiplication calc expression */
function multiply(...operands: Array<Operand>): string;
/** Create division calc expression */
function divide(...operands: Array<Operand>): string;
/** Create negation calc expression */
function negate(x: Operand): string;
}Usage Examples:
import { calc, cssVar } from "@chakra-ui/styled-system";
// CSS variables for calc
const $spacing = cssVar("spacing");
const $multiplier = cssVar("multiplier", "2");
// Chainable calc expressions
const dynamicWidth = calc($spacing.reference)
.multiply(2)
.add("10px")
.toString();
// Result: "calc(var(--spacing) * 2 + 10px)"
const complexCalc = calc("100%")
.subtract($spacing.reference)
.divide(2)
.toString();
// Result: "calc((100% - var(--spacing)) / 2)"
// Static calc functions
const addCalc = calc.add("50%", $spacing.reference, "10px");
// Result: "calc(50% + var(--spacing) + 10px)"
const negatedValue = calc.negate($spacing.reference);
// Result: "calc(var(--spacing) * -1)"
// Use in component styles
const containerStyles = {
[$spacing.variable]: "1rem",
width: calc("100vw").subtract($spacing.reference, "20px").toString(),
height: calc($spacing.reference).multiply(10).toString(),
margin: calc.divide($spacing.reference, 2)
};
// Complex responsive calculations
const responsiveSpacing = {
[$spacing.variable]: { base: "1rem", md: "2rem" },
padding: calc($spacing.reference).multiply(1.5).toString(),
marginTop: calc.subtract("100vh", $spacing.reference, "60px")
};Utilities for flattening nested theme objects into dot-notation keys with semantic token support.
/**
* Flattened token representation
*/
type FlatToken = PlainToken | SemanticToken;
/**
* Plain (non-semantic) token
*/
type PlainToken = {
isSemantic: false;
value: string | number;
};
/**
* Semantic token with conditional values
*/
type SemanticToken = {
isSemantic: true;
value: string | number | SemanticValue<string>;
};
/**
* Semantic token value with conditions
*/
type SemanticValue<Conditions extends string, Token extends string = string> =
| Token
| Partial<Record<"default" | Conditions, Token>>;
/**
* Record of flattened tokens
*/
type FlatTokens = Record<string, FlatToken>;
/**
* Flattens nested theme object into dot-notation keys
* @param theme - Theme object with nested tokens
* @returns Flattened tokens with metadata
*/
function flattenTokens(theme: Record<string, any>): FlatTokens;Usage Examples:
import { flattenTokens } from "@chakra-ui/styled-system";
// Example theme structure
const theme = {
colors: {
red: {
50: "#fef2f2",
500: "#ef4444",
900: "#7f1d1d"
},
blue: {
500: "#3b82f6"
}
},
space: {
1: "0.25rem",
4: "1rem",
8: "2rem"
},
semanticTokens: {
colors: {
primary: {
default: "blue.500",
_dark: "blue.300"
},
danger: "red.500"
}
}
};
// Flatten the theme
const flattened = flattenTokens(theme);
console.log(flattened);
// {
// "colors.red.50": { isSemantic: false, value: "#fef2f2" },
// "colors.red.500": { isSemantic: false, value: "#ef4444" },
// "colors.red.900": { isSemantic: false, value: "#7f1d1d" },
// "colors.blue.500": { isSemantic: false, value: "#3b82f6" },
// "space.1": { isSemantic: false, value: "0.25rem" },
// "space.4": { isSemantic: false, value: "1rem" },
// "space.8": { isSemantic: false, value: "2rem" },
// "colors.primary": {
// isSemantic: true,
// value: { default: "blue.500", _dark: "blue.300" }
// },
// "colors.danger": { isSemantic: true, value: "red.500" }
// }
// Use flattened tokens
Object.entries(flattened).forEach(([path, token]) => {
if (token.isSemantic) {
console.log(`Semantic token ${path}:`, token.value);
} else {
console.log(`Plain token ${path}:`, token.value);
}
});Comprehensive theme conversion utilities that transform entire theme objects to CSS variable-enabled themes.
/**
* Type augmentation for themes with CSS variables
*/
type WithCSSVar<T> = T & {
__cssMap: Record<string, { varRef: string; reference: string }>;
__cssVars: Record<string, any>;
__breakpoints: any;
};
/**
* Converts theme object to CSS variable-enabled theme
* @param rawTheme - Original theme object
* @returns Theme augmented with CSS variable properties
*/
function toCSSVar<T extends Record<string, any>>(rawTheme: T): WithCSSVar<T>;
/**
* Theme scale type for token resolution
*/
type ThemeScale = string | Record<string, any>;Usage Examples:
import { toCSSVar } from "@chakra-ui/styled-system";
// Original theme
const originalTheme = {
colors: {
brand: {
500: "#3182ce",
600: "#2c5aa0"
},
gray: {
100: "#f7fafc",
800: "#1a202c"
}
},
space: {
4: "1rem",
8: "2rem"
},
fontSizes: {
md: "1rem",
lg: "1.125rem"
}
};
// Convert to CSS variable theme
const theme = toCSSVar(originalTheme);
// Access CSS variables
console.log(theme.__cssMap);
// {
// "colors.brand.500": {
// varRef: "--chakra-colors-brand-500",
// reference: "var(--chakra-colors-brand-500)"
// },
// "colors.brand.600": {
// varRef: "--chakra-colors-brand-600",
// reference: "var(--chakra-colors-brand-600)"
// },
// // ... more entries
// }
// CSS variables object for injection
console.log(theme.__cssVars);
// {
// "--chakra-colors-brand-500": "#3182ce",
// "--chakra-colors-brand-600": "#2c5aa0",
// "--chakra-colors-gray-100": "#f7fafc",
// "--chakra-colors-gray-800": "#1a202c",
// "--chakra-space-4": "1rem",
// "--chakra-space-8": "2rem",
// "--chakra-fontSizes-md": "1rem",
// "--chakra-fontSizes-lg": "1.125rem"
// }
// Use in CSS-in-JS
const componentStyles = {
// Inject CSS variables at root
...theme.__cssVars,
// Use CSS variable references
color: theme.__cssMap["colors.brand.500"].reference,
backgroundColor: theme.__cssMap["colors.gray.100"].reference,
padding: theme.__cssMap["space.4"].reference,
fontSize: theme.__cssMap["fontSizes.md"].reference
};
// Access original values (still available)
console.log(theme.colors.brand[500]); // "#3182ce"
console.log(theme.space[4]); // "1rem"Import Examples:
// Import all theme variable utilities
import {
cssVar,
defineCssVars,
calc,
toCSSVar,
flattenTokens,
addPrefix,
toVarReference,
toVarDefinition
} from "@chakra-ui/styled-system/create-theme-vars";
// Import specific utilities
import { cssVar, calc } from "@chakra-ui/styled-system";
// Import types
import type {
Operand,
CalcChain,
FlatTokens,
SemanticToken,
WithCSSVar
} from "@chakra-ui/styled-system";