Skip to content

API Reference

Sparkle Design System API


Sparkle Design System API / theme/src

Theme configuration validator Provides comprehensive validation for design token integrity, accessibility compliance, and platform compatibility

const validator = new ThemeValidator()
const result = validator.validate(lightTokens)
if (!result.isValid) {
console.error('Theme validation failed:', result.errors)
}

validate(theme, options): ValidationResult

Validate a theme configuration

ThemeConfig

Theme configuration to validate

ValidationOptions = {}

Validation options

ValidationResult

Validation result with errors and warnings


Cross-platform token transformer Converts design tokens between web (CSS custom properties) and native (React Native StyleSheet) formats

const transformer = new TokenTransformer()
// Transform to web format
const webResult = transformer.transform(lightTokens, { platform: 'web' })
// Transform to native format
const nativeResult = transformer.transform(lightTokens, { platform: 'native' })

clearCache(): void

Clear transformation cache Useful when tokens have been updated

void

getCacheStats(): object

Get cache statistics

object

keys: string[]

size: number

toNative(tokens, options): NativeTheme

Transform tokens to native format (React Native StyleSheet)

ThemeConfig

Source theme configuration

Omit<TransformOptions, "platform"> = {}

Native-specific options

NativeTheme

Native theme object

toWeb(tokens, options): CSSCustomProperties

Transform tokens to web format (CSS custom properties)

ThemeConfig

Source theme configuration

Omit<TransformOptions, "platform"> = {}

Web-specific options

CSSCustomProperties

CSS custom properties object

transform(tokens, options): TransformResult

Transform design tokens to target platform format

ThemeConfig

Source theme configuration

TransformOptions

Transformation options

TransformResult

Transformation result with platform-specific tokens

Type for CSS custom properties object


React Native shadow style properties Platform-specific shadow handling for iOS and Android


React Native StyleSheet compatible theme object Numeric values for dimensions, hex/rgb colors for colors


Props for the NativeThemeProvider component

children: ReactNode

Child components that will have access to the theme context

optional defaultTheme: ThemeMode

Default theme mode to use on first load

'system'

optional disableSystemTheme: boolean

Whether to disable system theme detection

false

optional storageKey: string

Storage key for persisting theme preference

'sparkle-theme'

optional themes: ThemeCollection

Custom theme configurations to override defaults

{ light: lightTokens, dark: darkTokens }

optional updateStatusBar: boolean

Whether to automatically update StatusBar style based on theme

true

Theme collection mapping theme modes to their configurations


Theme context value interface providing complete theme state and controls

activeTheme: ThemeMode

Currently selected theme mode (user preference)

error: Error | null

Error state if theme loading or validation fails

isLoading: boolean

Loading state during theme initialization or transitions

setTheme: (theme) => void

Function to change the theme mode Handles persistence and CSS variable updates automatically

ThemeMode

void

systemTheme: SystemColorScheme

System detected color scheme (independent of user preference)

theme: ThemeConfig

Current active theme configuration with all design tokens


Configuration options for the theme plugin

optional darkMode: boolean

Whether to include dark mode support (default: true)

optional includeCSSVariables: boolean

Whether to include CSS custom properties in base layer (default: true)

optional prefix: string

Prefix for CSS custom properties (default: ‘theme’)

optional rootSelector: string

Selector for CSS custom properties (default: ':root')


Props for the ThemeProvider component

children: ReactNode

Child components that will have access to the theme context

optional cssSelector: string

CSS selector for injecting CSS variables

':root'

optional defaultTheme: ThemeMode

Default theme mode to use on first load

'system'

optional disableSystemTheme: boolean

Whether to disable system theme detection

false

optional storageKey: string

Storage key for persisting theme preference

'sparkle-theme'

optional themes: ThemeCollection

Custom theme configurations to override defaults

{ light: lightTokens, dark: darkTokens }

Theme examples and showcase components (Phase 5)

optional className: string

Additional CSS classes for the showcase container

optional showColorPalette: boolean

Whether to show the color palette demonstration

true

optional showComponents: boolean

Whether to show component demonstrations

true

optional showSemanticColors: boolean

Whether to show semantic color demonstrations

true

Token transformation options

optional baseFontSize: number

Base font size for rem calculations (default: 16)

optional flattenColors: boolean

Whether to flatten nested color objects for easier access (native only)

platform: Platform

Target platform for transformation

optional prefix: string

Optional prefix for CSS variables (web only)

optional selector: string

CSS selector for CSS variables (web only, default: ':root')


Result of token transformation

metadata: object

Transformation metadata

options: TransformOptions

tokenCount: number

transformedAt: string

platform: Platform

Target platform

source: ThemeConfig

Original theme configuration

tokens: NativeTheme | CSSCustomProperties

Transformed tokens (CSS variables for web, native theme for mobile)


Validation error with specific context

optional expected: string

Expected value type or format

message: string

Error message describing the validation failure

path: string

Path to the invalid property (e.g., ‘colors.primary.500’)

severity: "error" | "warning"

Severity level of the validation error

value: unknown

The invalid value that caused the error


Validation options for theme configuration

optional checkRequiredProperties: boolean

Whether to check for missing required properties (default: true)

optional minContrastRatio: number

Minimum contrast ratio for WCAG compliance (default: 4.5 for AA)

optional strictMode: boolean

Whether to treat warnings as errors (default: false)

optional validateColorContrast: boolean

Whether to validate color contrast ratios (default: true)

optional validateCSSValues: boolean

Whether to validate CSS value formats (default: true)

optional validateSpacingScale: boolean

Whether to validate spacing scale consistency (default: true)


Validation result containing errors and warnings

errors: ValidationError[]

Array of validation errors found

isValid: boolean

Whether the theme configuration is valid

summary: object

Summary of validation results

checkedProperties: number

totalErrors: number

totalWarnings: number

warnings: ValidationError[]

Array of validation warnings found

Platform = "web" | "native"

Platform target for token transformation


SystemColorScheme = "light" | "dark"

System detected color scheme


ThemeMode = "light" | "dark" | "system"

Theme mode options supporting light/dark themes and system preference

const baseTokens: ThemeConfig

Base design tokens following Design Tokens Community Group specification These tokens serve as the foundation for all theme variants

https://design-tokens.github.io/community-group/


const darkTokens: ThemeConfig

Dark theme tokens extending the base design system Optimized for dark mode interfaces with appropriate contrast ratios Following WCAG AA guidelines for accessibility


const DEFAULT_THEME_STORAGE_KEY: "sparkle-theme" = 'sparkle-theme'

Default storage key for theme persistence


const defaultTransformer: TokenTransformer

Default transformer instance for convenience


const lightTokens: ThemeConfig

Light theme tokens extending the base design system Optimized for light mode interfaces with appropriate contrast ratios


const nativePersistence: object

React Native-specific theme persistence using AsyncStorage

isSupported(): Promise<boolean>

Checks if AsyncStorage is available

Promise<boolean>

Promise resolving to true if AsyncStorage is supported and accessible

load(storageKey): Promise<ThemeMode | null>

Loads theme preference from AsyncStorage

string = DEFAULT_THEME_STORAGE_KEY

The key to use for AsyncStorage

Promise<ThemeMode | null>

Promise resolving to the stored theme mode or null if not found

remove(storageKey): Promise<void>

Removes theme preference from AsyncStorage

string = DEFAULT_THEME_STORAGE_KEY

The key to use for AsyncStorage

Promise<void>

save(theme, storageKey): Promise<void>

Saves theme preference to AsyncStorage

ThemeMode

The theme mode to save

string = DEFAULT_THEME_STORAGE_KEY

The key to use for AsyncStorage

Promise<void>


const persistenceMigration: object

Utility for migrating theme data between storage keys Useful for updating storage keys while preserving user preferences

isValidThemeMode(value): value is ThemeMode

Validates that a stored value is a valid theme mode

unknown

The value to validate

value is ThemeMode

true if the value is a valid ThemeMode

migrate(oldKey, newKey, removeOld): Promise<boolean>

Migrates theme preference from old key to new key

string

The old storage key

string

The new storage key

boolean = true

Whether to remove the old key after migration

Promise<boolean>

Promise indicating success of migration


const ThemeContext: Context<ThemeContextValue | null>

React Context for theme management across the application

This context provides access to:

  • Current theme configuration with design tokens
  • Theme switching functionality with persistence
  • System color scheme detection
  • Loading and error states

Must be used within a ThemeProvider or NativeThemeProvider

const { theme, setTheme, activeTheme } = useTheme();
// Access theme tokens
const primaryColor = theme.colors.primary[500];
// Change theme
setTheme('dark');

const themePersistence: object

Platform-agnostic theme persistence interface Automatically detects the environment and uses appropriate storage method

isSupported(): boolean | Promise<boolean>

Checks if storage is available

boolean | Promise<boolean>

boolean or Promise depending on platform

load(storageKey?): ThemeMode | Promise<ThemeMode | null> | null

Loads theme preference from appropriate storage

string

The key to use for storage

ThemeMode | Promise<ThemeMode | null> | null

Theme mode or Promise depending on platform

remove(storageKey?): void | Promise<void>

Removes theme preference from appropriate storage

string

The key to use for storage

void | Promise<void>

void or Promise depending on platform

save(theme, storageKey?): void | Promise<void>

Saves theme preference to appropriate storage

ThemeMode

The theme mode to save

string

The key to use for storage

void | Promise<void>

void or Promise depending on platform


const tokenUtils: object

Utility functions for common token transformations

compareThemes(theme1, theme2): string[]

Compare two theme configurations for differences

ThemeConfig

First theme configuration

ThemeConfig

Second theme configuration

string[]

Array of differences found

extractColorPalette(theme, colorKey): Record<string | number, string> | undefined

Extract specific color palette from theme

ThemeConfig

Theme configuration

string

Color key to extract (e.g., ‘primary’, ‘neutral’)

Record<string | number, string> | undefined

Color scale object

getColorNames(theme): string[]

Get all semantic color names from theme

ThemeConfig

Theme configuration

string[]

Array of color names

getSpacingKeys(theme): (string | number)[]

Get all spacing scale keys

ThemeConfig

Theme configuration

(string | number)[]

Array of spacing keys

mergeThemes(baseTheme, overrideTheme): ThemeConfig

Merge two theme configurations with the second overriding the first

ThemeConfig

Base theme configuration

Partial<ThemeConfig>

Theme configuration to merge on top

ThemeConfig

Merged theme configuration


const webPersistence: object

Web-specific theme persistence using localStorage

isSupported(): boolean

Checks if localStorage is available

boolean

true if localStorage is supported and accessible

load(storageKey): ThemeMode | null

Loads theme preference from localStorage

string = DEFAULT_THEME_STORAGE_KEY

The key to use for localStorage

ThemeMode | null

The stored theme mode or null if not found

remove(storageKey): void

Removes theme preference from localStorage

string = DEFAULT_THEME_STORAGE_KEY

The key to use for localStorage

void

save(theme, storageKey): void

Saves theme preference to localStorage

ThemeMode

The theme mode to save

string = DEFAULT_THEME_STORAGE_KEY

The key to use for localStorage

void

createNativeStyleUtils(nativeTheme): object

Creates a React Native StyleSheet from native theme tokens Convenience function for creating common styles

NativeTheme

Native theme object

object

Object with common style utilities

borderRadius: object

[k: string]: object

colors: object

[key: string]: { backgroundColor: string; } | { color: string; }

shadows: Record<string, NativeShadowStyle> = nativeTheme.shadows

spacing: object

[key: string]: { padding: number; } | { margin: number; }

typography: object

[k: string]: object

const theme = generateNativeTheme(lightTokens)
const styleUtils = createNativeStyleUtils(theme)
// Use in component
<View style={[styleUtils.spacing.p4, styleUtils.colors.bgPrimary]} />

createThemePlugin(themes, options): PluginWithConfig

Creates a Tailwind CSS plugin for theme integration

Record<string, ThemeConfig>

ThemePluginOptions = {}

PluginWithConfig


cssPropertiesToString(cssVariables, selector): string

Converts CSS custom properties object to CSS string for injection into stylesheets or CSS-in-JS

CSSCustomProperties

Object of CSS custom properties

string = ':root'

CSS selector to apply variables to (default: ':root')

string

CSS string with custom properties

const cssString = cssPropertiesToString(cssVars)
// Returns: ':root { --sparkle-color-primary-500: #3b82f6; }'

cssVar(category, key, fallback?, prefix?): string

Creates CSS variable reference string for use in other CSS

string

Token category (e.g., ‘color’, ‘spacing’)

string

Token key path (e.g., ‘primary-500’, ‘md’)

string

Optional fallback value

string = 'sparkle'

Optional prefix (default: ‘sparkle’)

string

CSS var() function string

cssVar('color', 'primary-500')
// Returns: 'var(--sparkle-color-primary-500)'
cssVar('spacing', 'md', '1rem', 'app')
// Returns: 'var(--app-spacing-md, 1rem)'

generateCSSVariables(tokens, prefix): CSSCustomProperties

Generates CSS custom properties (CSS variables) from design tokens for web platform integration with Tailwind CSS and other frameworks

ThemeConfig

Theme configuration object with design tokens

string = 'sparkle'

Optional prefix for CSS variable names (default: ‘sparkle’)

CSSCustomProperties

Object of CSS custom properties that can be applied to :root

const cssVars = generateCSSVariables(lightTokens)
// Returns: { '--sparkle-color-primary-500': '#3b82f6', ... }

generateNativeTheme(tokens, options): NativeTheme

Generates React Native StyleSheet compatible theme object from design tokens Converts CSS values to React Native compatible numeric and string values

ThemeConfig

Theme configuration object with design tokens

Configuration options for conversion

number

Base font size for rem conversion (default: 16)

boolean

Whether to flatten nested color objects (default: true)

NativeTheme

Native theme object compatible with React Native StyleSheet

const nativeTheme = generateNativeTheme(lightTokens)
const styles = StyleSheet.create({
container: {
backgroundColor: nativeTheme.colors.background.primary,
padding: nativeTheme.spacing[4],
}
})

generateThemeCSS(tokens, options): string

Generates CSS custom properties string directly from theme tokens Convenience function that combines generateCSSVariables and cssPropertiesToString

ThemeConfig

Theme configuration object

Configuration options

string

Optional prefix for CSS variable names (default: ‘sparkle’)

string

CSS selector to apply variables to (default: ':root')

string

CSS string ready for injection

const css = generateThemeCSS(lightTokens, { prefix: 'app' })
document.querySelector('style')?.appendChild(document.createTextNode(css))

isValidTheme(theme): boolean

Check if a theme configuration passes basic validation Quick boolean check without detailed error information

ThemeConfig

Theme configuration to check

boolean

Whether the theme is valid


NativeThemeProvider(__namedParameters): Element

NativeThemeProvider component for React Native applications

Provides theme management functionality with:

  • Automatic system theme detection using Appearance API
  • AsyncStorage persistence
  • StatusBar style integration
  • Theme validation and error handling

NativeThemeProviderProps

Element

function App() {
return (
<NativeThemeProvider defaultTheme="system">
<YourAppComponents />
</NativeThemeProvider>
);
}

parseNumericValue(value, baseFontSize): number

Converts a CSS dimension string to a React Native numeric value Handles rem, px, and numeric values

CSS dimension string (e.g., ‘1rem’, ‘16px’, ‘1.5’)

string | number

number = 16

Base font size for rem conversion (default: 16)

number

Numeric value for React Native

parseNumericValue('1rem') // Returns: 16
parseNumericValue('24px') // Returns: 24
parseNumericValue('1.5') // Returns: 1.5

parseShadow(boxShadow): NativeShadowStyle

Converts CSS box-shadow to React Native shadow properties Attempts to extract shadow values for cross-platform compatibility

string

CSS box-shadow string

NativeShadowStyle

Native shadow style object

parseShadow('0 4px 6px rgba(0, 0, 0, 0.1)')
// Returns: { shadowOffset: { width: 0, height: 4 }, shadowRadius: 6, ... }

ThemeProvider(__namedParameters): Element

ThemeProvider component for web applications

Provides theme management functionality with:

  • Automatic system theme detection
  • localStorage persistence
  • CSS variable injection
  • Theme validation and error handling

ThemeProviderProps

Element

function App() {
return (
<ThemeProvider defaultTheme="system">
<YourAppComponents />
</ThemeProvider>
);
}

ThemeShowcase(__namedParameters): Element

ThemeShowcase component demonstrating all theme features

This component provides a comprehensive demonstration of the theme system including color palettes, semantic colors, and themed UI components.

ThemeShowcaseProps

Element


useColorScheme(): "light" | "dark"

Custom hook for detecting system color scheme preference Works on both web (via matchMedia) and React Native (via Appearance API)

"light" | "dark"

Current system color scheme (‘light’ or ‘dark’)


useTheme(): ThemeContextValue

Custom hook for consuming theme context

ThemeContextValue

Theme context value with current theme and controls

Error if used outside of ThemeProvider or NativeThemeProvider


validateTheme(theme, options?): ValidationResult

Quick validation function for theme configuration Convenience function that creates a validator instance and runs validation

ThemeConfig

Theme configuration to validate

ValidationOptions

Validation options

ValidationResult

Validation result

const result = validateTheme(lightTokens, { strictMode: true })
if (!result.isValid) {
console.error('Theme validation failed')
}