defineTheme
functionDefine a theme with full type safety. Creates a theme from a definition where tokens can be: - Literal values (`'#007bff'`, `16`) - References to other tokens (`'$color.brand'`) - Computed functions (`(t) => t.spacing.base * 4`) The returned Theme object provides: - `tokens`: Fully resolved token values with autocomplete - `css`: Generated CSS custom properties string - `extend()`: Method to create derived themes with overrides
Import
import { defineTheme } from '@modular/sdk';Notes
- returns
- A fully typed Theme<T> object
- example
- ```typescript // 1. Define your token structure interface AppTokens { color: { brand: string; primary: string; secondary: string; }; spacing: { base: number; sm: number; md: number; lg: number; }; } // 2. Create a token accessor for computed values const $ = tokenAccessor<AppTokens>(); // 3. Define your base theme const baseTheme = defineTheme<AppTokens>({ color: { brand: '#1E96EB', primary: '$color.brand', // Reference syntax secondary: '#6C757D', }, spacing: { base: 4, sm: $(t => t.spacing.base * 2), // Computed: 8 md: $(t => t.spacing.base * 4), // Computed: 16 lg: $(t => t.spacing.base * 8), // Computed: 32 }, }); // 4. Access resolved tokens console.log(baseTheme.tokens.color.primary); // '#1E96EB' console.log(baseTheme.tokens.spacing.md); // 16 // 5. Use generated CSS const style = document.createElement('style'); style.textContent = `:root { ${baseTheme.css} }`; document.head.appendChild(style); // 6. Extend for variants const darkTheme = baseTheme.extend({ color: { brand: '#0A84FF', // primary automatically updates via reference }, }); ```
- example
- ```typescript // This will throw a clear error: const badTheme = defineTheme<{ a: { x: string; y: string } }>({ a: { x: '$a.y', // x depends on y y: '$a.x', // y depends on x - CIRCULAR! }, }); // Error: Circular dependencies detected in theme tokens: // a.x -> a.y -> a.x ```