Tasty logoTasty
Playground

Introduction

Tasty is a styling engine for design systems that generates deterministic CSS for stateful components.

It compiles state maps into mutually exclusive selectors, so for a given property and component state, one branch wins by construction instead of competing through cascade and specificity.

That is the core guarantee: component styling resolves from declared state logic, not from source-order accidents or specificity fights.

Tasty fits best when you are building a design system or component library with intersecting states, variants, tokens, sub-elements, responsive rules, and extension semantics that need to stay predictable over time.

On top of that foundation, Tasty gives teams a governed styling model: a CSS-like DSL, tokens, recipes, typed style props, sub-elements, and multiple rendering modes.

Why Tasty

Supporting capabilities

Why It Exists

Modern component styling becomes fragile when multiple selectors can still win for the same property. Hover, disabled, theme, breakpoint, parent state, and root state rules start competing through specificity and source order.

Tasty replaces that competition with explicit state-map resolution. Each property compiles into mutually exclusive branches, so component styling stays deterministic as systems grow. For the full mechanism, jump to How It Actually Works.

Installation

pnpm add @tenphi/tasty

Requirements:

Other package managers:

npm add @tenphi/tasty
yarn add @tenphi/tasty

Start Here

For the fuller docs map beyond the quick routes above, start here:

Quick Start

Create a styled component

import { tasty } from '@tenphi/tasty';

const Card = tasty({
  as: 'div',
  styles: {
    display: 'flex',
    flow: 'column',
    padding: '24px',
    gap: '12px',
    fill: 'white',
    color: '#222',
    border: '1px solid #ddd',
    radius: '12px',
  },
});

// Just a React component
<Card>Hello World</Card>

Every value maps to CSS you'd recognize. This example is intentionally a simple first contact, not a tour of the whole DSL.

When you want a more design-system-shaped authoring model, Tasty also supports built-in units, tokens, recipes, state aliases, and color values such as okhsl(...) without extra runtime libraries.

Use configure() when you want to define shared tokens, state aliases, recipes, or other conventions for your app or design system. For a fuller onboarding path, follow Getting Started.

Add state-driven styles

const Button = tasty({
  as: 'button',
  styles: {
    padding: '1.5x 3x',
    fill: {
      '': '#primary',
      ':hover': '#primary-hover',
      ':active': '#primary-pressed',
      '[disabled]': '#surface',
    },
    color: {
      '': '#on-primary',
      '[disabled]': '#text.40',
    },
    cursor: {
      '': 'pointer',
      '[disabled]': 'not-allowed',
    },
    transition: 'theme',
  },
});

State keys support pseudo-classes first (:hover, :active), then modifiers (theme=danger), attributes ([disabled]), media/container queries, root states, and more. Tasty compiles them into exclusive selectors automatically.

Extend any component

import { Button } from 'my-ui-lib';

const DangerButton = tasty(Button, {
  styles: {
    fill: {
      '': '#danger',
      ':hover': '#danger-hover',
    },
  },
});

Child styles merge with parent styles intelligently — state maps can extend or replace parent states per-property.

Optional: configure shared conventions

import { configure } from '@tenphi/tasty';

configure({
  states: {
    '@mobile': '@media(w < 768px)',
    '@tablet': '@media(w < 1024px)',
    '@dark': '@root(schema=dark) | (!@root(schema) & @media(prefers-color-scheme: dark))',
  },
  recipes: {
    card: { padding: '4x', fill: '#surface', radius: '1r', border: true },
  },
});

Use configure() once when your app or design system needs shared aliases, tokens, recipes, or parser extensions. Predefined states turn complex selector logic into single tokens, so teams can write @mobile instead of repeating media query expressions in every component.

Props as the public API

styleProps exposes selected CSS properties as typed React props, and modProps does the same for modifier keys. Together they let design systems define a governed, typed component API without wrapper elements or styles overrides:

<Space flow="row" gap="2x" placeItems="center">
  <Button isLoading size="large" placeSelf="end">Submit</Button>
</Space>

See Style Props and Mod Props below, or the full reference in Runtime API.

Choose a Styling Approach

Once you understand the component model, pick the rendering mode that matches your app.

ApproachEntry pointBest forTrade-off
Runtime@tenphi/tastyInteractive apps with reusable stateful components and design systemsFull feature set; CSS is generated on demand at runtime
Zero-runtime@tenphi/tasty/staticStatic sites, SSG, landing pagesRequires the Babel plugin; no component-level styleProps or runtime-only APIs

If your framework can execute runtime React code on the server, you can also add SSR on top of runtime with @tenphi/tasty/ssr/*. This uses the same tasty() pipeline, but collects CSS during server rendering and hydrates the cache on the client. That is the model for Next.js, generic React SSR, and Astro islands. See Getting Started, Zero Runtime, and Server-Side Rendering.

How It Actually Works

This is the core idea that makes everything else possible.

For the end-to-end architecture — parsing state keys, building exclusive conditions, merging by output, and materializing selectors and at-rules — see Style rendering pipeline.

The structural problem with normal CSS

First, the cascade resolves conflicts by specificity and source order: when multiple selectors match, the one with the highest specificity wins, or — if specificity is equal — the last one in source order wins. That makes styles inherently fragile. Reordering imports, adding a media query, or composing components from different libraries can silently break styling.

A small example makes this tangible. Two rules for a button's background:

.btn:hover     { background: dodgerblue; }
.btn[disabled] { background: gray; }

Both selectors have specificity (0, 1, 1). When the button is hovered and disabled, both match — and the last rule in source order wins. Swap the two lines and a hovered disabled button silently turns blue instead of gray. This class of bug is invisible in code review because the logic is correct; only the ordering is wrong.

Why real state logic is hard to author by hand

Authoring selectors that capture real-world state logic is fundamentally hard. A single state like "dark mode" may depend on a root attribute, an OS preference, or both — each branch needing its own selector, proper negation of competing branches, and correct @media nesting. The example below shows the CSS you'd write by hand for just one property with one state. Scale that across dozens of properties, then add breakpoints and container queries, and the selector logic quickly becomes unmanageable.

What Tasty generates instead

Tasty solves both problems at once: every state mapping compiles into mutually exclusive selectors.

const Text = tasty({
  styles: {
    color: {
      '': '#text',
      '@dark': '#text-on-dark',
    },
    padding: {
      '': '4x',
      '@mobile': '2x',
    },
  },
});

If @dark expands to @root(schema=dark) | (!@root(schema) & @media(prefers-color-scheme: dark)), try writing the CSS by hand. A first attempt might look like this:

/* First attempt — the @media branch is too broad */
.t0 { color: var(--text-color); }
:root[data-schema="dark"] .t0 { color: var(--text-on-dark-color); }
@media (prefers-color-scheme: dark) {
  .t0 { color: var(--text-on-dark-color); }
}

The @media branch fires even when data-schema="light" is explicitly set. Fix that:

/* Second attempt — @media is scoped, but the default is still too broad */
.t0 { color: var(--text-color); }
:root[data-schema="dark"] .t0 { color: var(--text-on-dark-color); }
@media (prefers-color-scheme: dark) {
  :root:not([data-schema]) .t0 { color: var(--text-on-dark-color); }
}

Better — but the bare .t0 default still matches unconditionally. It matches in dark mode, it matches when data-schema="dark" is set, and it can beat the attribute selector by source order if another rule re-declares it later. There is no selector that says "apply this default only when none of the dark branches win."

This is just one property with one state, and getting it right already takes multiple iterations. The correct selectors require negating every other branch — which is exactly what Tasty generates automatically:

/* Branch 1: Explicit dark schema */
:root[data-schema="dark"] .t0.t0 {
  color: var(--text-on-dark-color);
}

/* Branch 2: No schema attribute + OS prefers dark */
@media (prefers-color-scheme: dark) {
  :root:not([data-schema]) .t0.t0 {
    color: var(--text-on-dark-color);
  }
}

/* Default: no schema + OS does not prefer dark */
@media (not (prefers-color-scheme: dark)) {
  :root:not([data-schema="dark"]) .t0.t0 {
    color: var(--text-color);
  }
}

/* Default: schema is set but not dark (any OS preference) */
:root:not([data-schema="dark"])[data-schema] .t0.t0 {
  color: var(--text-color);
}

What guarantee that gives you

Every rule is guarded by the negation of higher-priority rules. No two rules can match at the same time. No specificity arithmetic. No source-order dependence. Components compose and extend without collisions.

By absorbing selector complexity, Tasty makes advanced CSS patterns practical again — nested container queries, multi-condition @supports gates, and combined root-state/media branches. You stay in pure CSS instead of relying on JavaScript workarounds, so the browser can optimize layout, painting, and transitions natively. Tasty keeps the solution in CSS while removing much of the selector bookkeeping that is hard to maintain by hand.

Try it in the playground →

Capabilities

This section is a quick product tour. For the canonical guides and references, start from the Docs Hub.

Design Tokens and Custom Units

Tokens are first-class. Colors use #name syntax. Spacing, radius, and border width use multiplier units tied to CSS custom properties:

fill: '#surface',         // → var(--surface-color)
color: '#text.80',        // → 80% opacity text token
padding: '2x',            // → calc(var(--gap) * 2)
radius: '1r',             // → var(--radius)
border: '1bw solid #border',
UnitMaps toExample
x--gap multiplier2xcalc(var(--gap) * 2)
r--radius multiplier1rvar(--radius)
bw--border-width multiplier1bwvar(--border-width)
ow--outline-width multiplier1owvar(--outline-width)
cr--card-radius multiplier1crvar(--card-radius)

Define your own units via configure({ units: { ... } }).

State System

Every style property accepts a state mapping object. Keys can be combined with boolean logic:

State typeSyntaxCSS output
Data attribute (boolean modifier)disabled[data-disabled]
Data attribute (value modifier)theme=danger[data-theme="danger"]
Pseudo-class:hover:hover
Attribute selector[role="tab"][role="tab"]
Class selector (supported).is-active.is-active
Media query@media(w < 768px)@media (width < 768px)
Container query@(panel, w >= 300px)@container panel (width >= 300px)
Root state@root(schema=dark):root[data-schema="dark"]
Parent state@parent(theme=danger):is([data-theme="danger"] *)
Feature query@supports(display: grid)@supports (display: grid)
Entry animation@starting@starting-style

Combine with & (AND), | (OR), ! (NOT):

fill: {
  '': '#surface',
  'theme=danger & :hover': '#danger-hover',
  '[aria-selected="true"]': '#accent-subtle',
}

Sub-Element Styling

Compound components can style inner parts from the parent definition with capitalized keys in styles and optional elements declarations, producing typed sub-components like <Card.Title /> instead of separate wrapper components or ad hoc class naming.

Sub-elements share the root state context by default, so keys like :hover, modifiers, root states, and media queries resolve as one coordinated styling block. Use @own(...) when a sub-element should react to its own state, and use the $ selector affix when you need precise descendant targeting.

See Runtime API - Sub-element Styling, Style DSL - Advanced States, and Methodology.

Style Props

styleProps exposes selected CSS properties as typed React props. Components control which properties to open up; consumers get layout and composition knobs without styles overrides. Supports state maps for responsive values.

const Space = tasty({
  styles: { display: 'flex', flow: 'column', gap: '1x' },
  styleProps: FLOW_STYLES,
});

<Space flow="row" gap={{ '': '2x', '@tablet': '4x' }}>

See Runtime API - Style Props and Methodology - styleProps.

Mod Props

modProps exposes modifier keys as typed React props — the modifier equivalent of styleProps. Accepts an array of key names or an object with type descriptors (Boolean, String, Number, or enum arrays) for full TypeScript autocomplete.

const Button = tasty({
  as: 'button',
  modProps: { isLoading: Boolean, size: ['sm', 'md', 'lg'] as const },
  styles: {
    fill: { '': '#primary', isLoading: '#primary.5' },
    padding: { '': '2x 4x', 'size=sm': '1x 2x' },
  },
});

<Button isLoading size="lg">Submit</Button>

See Runtime API - Mod Props and Methodology - modProps.

Variants

Variants let one component expose named visual versions without pre-generating a separate class for every possible combination. In runtime mode, Tasty emits only the variant CSS that is actually used.

See Runtime API - Variants.

Recipes

Recipes are reusable style bundles defined in configure({ recipes }) and applied with the recipe style property. They are useful when your design system wants shared state logic or visual presets without forcing every component to repeat the same style map.

Use / to post-apply recipes after local styles when recipe states should win the final merge order, and use none to skip base recipes entirely.

See Style DSL - Recipes and Configuration - recipes.

Auto-Inferred @property

Tasty usually removes the need to hand-author CSS @property rules. When a custom property receives a concrete value, Tasty infers its syntax and registers the matching @property automatically, which makes transitions and animations on custom properties work without extra boilerplate.

If you prefer explicit control, disable inference with configure({ autoPropertyTypes: false }) or declare the properties yourself.

See Style DSL - Properties (@property).

Explicit @properties

Use explicit @properties only when you need to override defaults such as inherits: false or a custom initialValue.

See Style DSL - Properties (@property).

React Hooks

When you do not need a full component wrapper, use the hooks directly: useStyles for local class names, useGlobalStyles for selector-scoped global CSS, useRawCSS for raw rules, plus useKeyframes and useProperty for animation and custom-property primitives.

See Runtime API - Hooks.

Zero-Runtime Mode

Use tastyStatic when you want the same DSL and state model, but with CSS extracted at build time and no styling runtime in the client bundle. It is a strong fit for static sites, landing pages, and other build-time-first setups.

See Zero Runtime (tastyStatic) and Getting Started - Choosing a rendering mode.

tasty vs tastyStatic

tasty() returns React components and injects CSS on demand at runtime. tastyStatic() returns class names and extracts CSS during the build. Both share the same DSL, tokens, units, state mappings, and recipes, so the main choice is runtime flexibility versus build-time extraction.

See Zero Runtime (tastyStatic), Runtime API, and Comparison - Build-time vs runtime.

Server-Side Rendering

SSR layers on top of runtime tasty() rather than introducing a separate styling model. Existing components stay unchanged while Tasty collects CSS during server rendering and hydrates the cache on the client.

Use @tenphi/tasty/ssr/next for Next.js App Router, @tenphi/tasty/ssr/astro for Astro, or the core SSR API for other React SSR setups.

See the full SSR guide.

Entry Points

ImportDescriptionPlatform
@tenphi/tastyRuntime style engine (tasty, hooks, configure)Browser
@tenphi/tasty/staticZero-runtime static styles (tastyStatic)Browser
@tenphi/tasty/coreLower-level internals (config, parser, pipeline, injector, style handlers) for tooling and advanced useBrowser / Node
@tenphi/tasty/babel-pluginBabel plugin for zero-runtime CSS extractionNode
@tenphi/tasty/zeroProgrammatic extraction APINode
@tenphi/tasty/nextNext.js integration wrapperNode
@tenphi/tasty/ssrCore SSR API (collector, context, hydration)Node
@tenphi/tasty/ssr/nextNext.js App Router SSR integrationNode
@tenphi/tasty/ssr/astroAstro middleware + auto-hydrationNode / Browser

Browser Requirements

Tasty's exclusive selector system relies on modern CSS pseudo-class syntax:

Performance

Bundle Size

All sizes measured with size-limit — minified and brotli-compressed, including all dependencies.

Entry pointSize
@tenphi/tasty (runtime + SSR)~44 kB
@tenphi/tasty/core (runtime, no SSR)~41 kB
@tenphi/tasty/static (zero-runtime)~1.5 kB

Run pnpm size for exact up-to-date numbers.

Runtime Benchmarks

If you choose the runtime approach, performance is usually a non-issue in practice. The numbers below show single-call throughput for the core pipeline stages, measured with vitest bench on an Apple M1 Max (Node 22).

Operationops/secLatency (mean)
renderStyles — 5 flat properties (cold)~72,000~14 us
renderStyles — state map with media/hover/modifier (cold)~22,000~46 us
renderStyles — same styles (cached)~7,200,000~0.14 us
parseStateKey — simple key like :hover (cold)~1,200,000~0.9 us
parseStateKey — complex OR/AND/NOT key (cold)~190,000~5 us
parseStateKey — any key (cached)~3,300,000–8,900,000~0.1–0.3 us
parseStyle — value tokens like 2x 4x (cold)~345,000~3 us
parseStyle — color tokens (cold)~525,000~1.9 us
parseStyle — any value (cached)~15,500,000~0.06 us

"Cold" benchmarks use unique inputs to bypass all caches. Cached benchmarks reuse a single input and measure the LRU hot path.

Run pnpm bench to reproduce.

What This Means in Practice

How It Stays Fast

Ecosystem

Tasty is the core of a production-ready styling platform. These companion tools complete the picture:

ESLint Plugin

@tenphi/eslint-plugin-tasty — 27 total lint rules for style property names, value syntax, token existence, state keys, and best practices. The recommended preset enables 18 of them as a practical default. Catch typos and invalid styles at lint time, not at runtime.

pnpm add -D @tenphi/eslint-plugin-tasty
import tasty from '@tenphi/eslint-plugin-tasty';
export default [tasty.configs.recommended];

Glaze

@tenphi/glaze — OKHSL-based color theme generator with automatic WCAG contrast solving. Generate light, dark, and high-contrast palettes from a single hue, and export them directly as Tasty color tokens.

import { glaze } from '@tenphi/glaze';

const theme = glaze(280, 80);
theme.colors({
  surface: { lightness: 97 },
  text: { base: 'surface', lightness: '-52', contrast: 'AAA' },
});

const tokens = theme.tasty(); // Ready-to-use Tasty tokens

VS Code Extension

Syntax highlighting for Tasty styles in TypeScript, TSX, JavaScript, and JSX. Highlights color tokens, custom units, state keys, presets, and style properties inside tasty(), tastyStatic(), and related APIs.

Tasty VS Code syntax highlighting example

Built with Tasty

tasty.style (source)

The official Tasty documentation and landing page — itself built entirely with Tasty. A showcase for zero-runtime styling via tastyStatic, SSR with Next.js, and OKHSL color theming with Glaze.

Cube Cloud

Enterprise universal semantic layer platform by Cube Dev, Inc. Cube Cloud unifies data modeling, caching, access control, and APIs (REST, GraphQL, SQL, AI) for analytics at scale. Tasty has powered its frontend for over 5 years in production.

Cube Cloud for Excel and Google Sheets

A single spreadsheet add-in deployed to both Microsoft Excel and Google Sheets. Connects spreadsheets to any cloud data platform (BigQuery, Databricks, Snowflake, Redshift, and more) via Cube Cloud's universal semantic layer.

Cube UI Kit (storybook)

Open-source React UI kit built on Tasty + React Aria. 100+ production components proving Tasty works at design-system scale. A reference implementation and a ready-to-use component library.

Documentation

Start from the docs hub if you want the shortest path to the right guide for your role or styling approach.

Start here

Guides

Reference

Rendering modes

Internals

Context

License

MIT