Thanks to visit codestin.com
Credit goes to github.com

Skip to content

choice-form/design-tokens

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

26 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🎨 Design Tokens Generator

A type-safe, W3C-compliant design token system that bridges the gap between design and development.

TypeScript W3C Standard Tested npm version

πŸš€ Why Choose This Library?

⚑ Optimized Developer Experience

  • Type-Safe: 100% TypeScript with strict mode, catching errors at compile time.
  • Intelligent Autocomplete: Full IDE support for autocompletion and type checking.
  • Dynamic Aliases: Intuitive aliases like background.default and text.secondary.
  • Live Reload: See changes instantly when you modify tokens.

🎯 Advanced Architecture

  • W3C Compliant: Fully adheres to the latest W3C Design Tokens specification.
  • Multi-Theme Support: Seamless light/dark mode switching with a single codebase.
  • Cross-Platform Exports: Comprehensive output formats including CSS, SCSS, JavaScript, and TypeScript.
  • Modern Toolchain: Leveraging Node.js scripts for generation and Terrazzo for transformation.

πŸ”₯ Powerful and Complete

  • 373+ Tokens: A rich set of meticulously designed tokens covering colors, typography, spacing, shadows, and more.
  • Smart Alias System: Dynamically generated from data to ensure consistency.
  • Advanced Helper Functions: Convenient APIs like color(), spacing(), and shadow().
  • Complete Test Coverage: Quality assured with both integration and unit tests.

πŸ“¦ Quick Start

Installation

# Install with npm
npm install @choiceform/design-tokens

# Install with pnpm (recommended)
pnpm add @choiceform/design-tokens

# Install with yarn
yarn add @choiceform/design-tokens

Development Setup

# Install dependencies
pnpm install

# Build tokens
pnpm run build

# Development mode (with live reload)
pnpm run dev

Usage

πŸ”₯ JavaScript/TypeScript

import { color, spacing, shadow, typography } from "@choiceform/design-tokens";

// 🎨 Colors - with theme and alias support
const styles = {
  background: color("background.default"), // β†’ var(--color-background-default)
  color: color("text.secondary", "dark"), // β†’ foreground color for dark theme
  border: color("border.strong", 0.5), // β†’ border color with 50% opacity
};

// πŸ“ Spacing - flexible and versatile
const layout = {
  padding: spacing(4), // β†’ "1rem"
  margin: spacing("1/2"), // β†’ "50%"
  gap: spacing("[10vh]"), // β†’ "10vh"
  inset: spacingList([2, 4]), // β†’ "0.5rem 1rem"
};

// ✨ Shadows - theme-aware
const elevation = {
  boxShadow: shadow("md"), // β†’ medium shadow
  dropShadow: shadow("lg", "dark"), // β†’ large shadow for dark theme
  textShadow: shadowList(["sm", "md"]), // β†’ combination of multiple shadows
};

// πŸ“ Typography - complete preset styles
const textStyles = typography("heading.large"); // β†’ full typography object
const cssString = typographyStyles("body.medium"); // β†’ CSS string

🎨 SCSS

// Import functions and mixins (in order)
@import "path/to/functions"; // Functions for individual values
@import "path/to/mixins"; // Mixins for complex operations

.my-component {
  // 🎨 Colors - identical API to JS version
  background: color("background.default");
  color: color("text.secondary", 0.8);
  border: 1px solid color("border.default");

  // πŸ“ Spacing - supports all JS features
  padding: spacing(4); // β†’ "1rem"
  margin: spacing("1/2"); // β†’ "50%"
  gap: spacing("[10vh]"); // β†’ "10vh"

  // ✨ Typography - complete preset application
  @include typography-styles("heading.large");

  // πŸ“± Responsive design
  @include up("md") {
    padding: spacing(6);
    @include typography-styles("heading.display");
  }

  // πŸŒ“ Other design tokens
  border-radius: radius("md");
  box-shadow: shadow("lg");
  z-index: z-index("modal");
}

// πŸ“± Responsive typography example
.responsive-heading {
  @include responsive-typography(
    (
      "default": "heading.small",
      "md": "heading.medium",
      "lg": "heading.large",
    )
  );
}

πŸ—οΈ Architecture

graph TB
    A["TypeScript Data Definitions"] --> B["W3C Token Generator"]
    B --> C["Standard-Compliant JSON"]
    C --> D["Terrazzo Transformer"]
    D --> E["Multi-Format Outputs"]

    F["Helper Function System"] --> G["Smart Alias Resolution"]
    G --> H["Type-Safe API"]

    C --> F
    E --> I["CSS Variables"]
    E --> J["SCSS Functions & Mixins"]
    E --> K["JS/TS Modules"]
    E --> L["Flattened JSON"]

    J --> M["functions.scss - Individual Values"]
    J --> N["mixins.scss - Complex Operations"]

    style A fill:#e1f5fe
    style C fill:#f3e5f5
    style H fill:#e8f5e8
Loading

πŸ“¦ Output Format Comparison

Format File Size Features Best For
functions.scss ~19KB 🎯 Individual values, identical JS API Component styling, utility classes
mixins.scss ~6.8KB πŸ”₯ Multi-property application, responsive Complex components, typography presets
tokens.css ~30KB 🌍 Universal browser support Runtime theming, CSS-only projects
tokens.js ~25KB ⚑ Runtime logic, conditional styling React, Vue, dynamic applications

πŸ’‘ Recommendation: Use SCSS files for build-time optimization and CSS files for runtime flexibility.

πŸ“Š Token Ecosystem

Token Type Count JS/TS Support SCSS Support Use Cases
🎨 Colors 243 color(), colorVar(), aliases color(), color-var(), identical API UI background, text, borders, icons
πŸ“ Typography 39 typography(), fontFamily(), etc typography-styles(), font-family(), etc Headings, body text, code, labels
πŸ“ Spacing Flexible spacing(), spacingList(), fractions spacing(), spacing-list(), identical API Layout, gaps, sizing
✨ Shadows 22 shadow(), shadowList(), themes shadow(), shadow-list(), themes Cards, buttons, overlays
πŸ“± Breakpoints 6 up(), down(), between(), only() @mixin up(), @mixin down(), etc Media queries, responsive design
πŸ“š Z-index 9 zIndex(), zIndexList() z-index(), z-index-list() Modals, dropdowns, sticky headers
πŸ”„ Radius 3 radius(), radiusList() radius(), radius-list() Buttons, cards, inputs

🎯 Core Strengths

πŸ’Ž SCSS Powerhouse Features

Our SCSS integration provides a complete, identical API to the JavaScript version with additional SCSS-specific superpowers:

// 🎯 1. Identical API to JavaScript
.component {
  // Same function names, same parameters, same results
  background: color(
    "background.default"
  ); // βœ“ Same as JS: color("background.default")
  padding: spacing(4); // βœ“ Same as JS: spacing(4)
  box-shadow: shadow("md"); // βœ“ Same as JS: shadow("md")
}

// πŸ”₯ 2. SCSS-Only Superpowers
.advanced {
  // Multi-property application with mixins
  @include typography-styles(
    "heading.large"
  ); // Applies 5 CSS properties at once

  // Responsive breakpoint mixins
  @include up("md") {
    @include typography-styles("heading.display");
  }

  // Utility mixins for common patterns
  @include text-ellipsis(); // Single-line text truncation
  @include text-ellipsis-multiline(3); // Multi-line text truncation
}

// 🎨 3. Zero Learning Curve
// If you know the JS API, you already know the SCSS API!
.button {
  // JS: { background: color("background.primary", { alpha: 0.9 }) }
  background: color("background.primary", 0.9); // Same result in SCSS

  // JS: { padding: spacingList([2, 4]) }
  padding: spacing-list(2, 4); // Same result in SCSS
}

1. Smart Alias System 🧠

No more memorizing complex token paths. Use intuitive aliases instead:

// ❌ Traditional Way - Hard to remember
color("color.background.surface.default.light");

// βœ… Smart Alias - Intuitive and easy
color("background.default"); // background color
color("text.secondary"); // foreground color
color("border.strong"); // border color
color("icon.primary"); // icon color

2. Zero-Cost Theming πŸŒ“

A single API provides perfect multi-theme support:

// Automatically adapts to the current theme
const button = {
  background: color("background.default"),
  color: color("text.default"),
  boxShadow: shadow("md"),
};

3. Type Safety Guaranteed πŸ›‘οΈ

Catch errors at compile time, not at runtime:

// βœ… Type check passes
color("background.default"); // Correct alias
spacing(4); // Correct value
shadow("md"); // Correct size

// ❌ Compile-time error
color("background.invalid"); // Error: Alias does not exist
spacing("invalid"); // Error: Invalid spacing value
shadow("xxx"); // Error: Undefined shadow

4. Developer Experience Boosts ⚑

// πŸ”₯ Bulk Operations
const margins = spacingList([2, 4, 6, 8]); // β†’ "0.5rem 1rem 1.5rem 2rem"
const shadows = shadowList(["sm", "md"]); // β†’ combination of multiple shadows

// 🎨 Opacity Control
color("background.default", 0.8); // β†’ rgba(..., 0.8)

// πŸ“± Responsive Breakpoints
up("md"); // β†’ "@media screen and (min-width: 48rem)"
down("lg"); // β†’ "@media screen and (max-width: 63.98rem)"
between("sm", "xl"); // β†’ "@media screen and (min-width: 40rem) and (max-width: 79.98rem)"
only("md"); // β†’ "@media screen and (min-width: 48rem) and (max-width: 63.98rem)"

// 🎯 Device-specific aliases
mobile(); // β†’ "@media screen and (min-width: 29.6875rem)"
tablet(); // β†’ "@media screen and (min-width: 48rem) and (max-width: 63.98rem)"
desktop(); // β†’ "@media screen and (min-width: 64rem)"

πŸ› οΈ Build & Deployment

Development Commands

# πŸš€ Dev Mode (Recommended)
pnpm run dev                # Start dev server + watch mode

# πŸ“¦ Build Commands
pnpm run build              # Build all tokens
pnpm run build:colors       # Build only color tokens
pnpm run build:helpers      # Build helper functions

# πŸ§ͺ Test Commands
pnpm run test               # Run all tests
pnpm run test:helpers       # Test helper functions
pnpm run test:integration   # Run integration tests

# πŸ”„ Transform Commands
pnpm run terrazzo           # Transform into multiple formats (CSS, SCSS, JS, TS)
pnpm run terrazzo:watch     # Transform in watch mode

# πŸ“ Generated Files After Build:
# dist/tokens.css           β†’ CSS Custom Properties
# dist/functions.scss       β†’ SCSS Functions (1000+ lines)
# dist/mixins.scss          β†’ SCSS Mixins (400+ lines)
# dist/tokens.js            β†’ JavaScript Helpers

Continuous Integration

# .github/workflows/tokens.yml
name: Design Tokens CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: pnpm/action-setup@v2
      - name: Install Dependencies
        run: pnpm install
      - name: Build Tokens
        run: pnpm run build
      - name: Run Tests
        run: pnpm run test
      - name: Generate Outputs
        run: pnpm run terrazzo

πŸ“ Project Structure

packages/generate-tokens/
β”œβ”€β”€ πŸ“Š data/                    # Data Definition Layer
β”‚   β”œβ”€β”€ colors-data.cjs         # Color System Definition
β”‚   β”œβ”€β”€ typography-data.cjs     # Typography System Definition
β”‚   └── spacing-data.cjs        # Spacing System Definition
β”œβ”€β”€ πŸ”„ generate/                # Transformation Script Layer
β”‚   β”œβ”€β”€ generate-w3c-*.cjs      # W3C Standard Transformers
β”‚   └── build-helpers.cjs       # Helper Function Builder
β”œβ”€β”€ 🎯 src/helpers/             # Helper Function Layer
β”‚   β”œβ”€β”€ colors.ts               # Color Helpers
β”‚   β”œβ”€β”€ spacing.ts              # Spacing Helpers
β”‚   └── shadows.ts              # Shadow Helpers
β”œβ”€β”€ πŸ“€ output/                  # W3C Output Layer
β”‚   β”œβ”€β”€ colors-w3c.json         # W3C-compliant color tokens
β”‚   └── typography-w3c.json     # W3C-compliant typography tokens
β”œβ”€β”€ πŸ“¦ dist/                    # Multi-Format Output Layer
β”‚   β”œβ”€β”€ tokens.css              # CSS Custom Properties
β”‚   β”œβ”€β”€ tokens.scss             # Sass Variables and Mixins
β”‚   β”œβ”€β”€ functions.scss          # SCSS Functions (color, spacing, typography, etc.)
β”‚   β”œβ”€β”€ mixins.scss             # SCSS Mixins (breakpoints, typography-styles, etc.)
β”‚   β”œβ”€β”€ tokens.js               # JavaScript Modules
β”‚   β”œβ”€β”€ tokens.d.ts             # TypeScript Definitions
β”‚   └── helpers.js              # Compiled Helper Functions
β”œβ”€β”€ πŸ§ͺ tests/                   # Test Suite
β”‚   β”œβ”€β”€ helpers/                # Helper Function Tests
β”‚   β”œβ”€β”€ tokens/                 # Token Tests
β”‚   └── integration/            # Integration Tests
└── πŸ“‹ docs/                    # Docs Directory
    └── README.md               # The README you are reading

🌟 Best Practices

1. Token Naming Conventions

// βœ… Recommended: Semantic Naming
color("background.default"); // Default background color
color("text.secondary"); // Secondary foreground color
color("border.default"); // Default border color

2. Theming Strategy

// 🎨 Responsive Theming
const getButtonStyles = (theme = "auto") => ({
  background: color("background.accent", theme),
  color: color("text.on-accent", theme),
  "&:hover": {
    background: color("background.accent-hover", theme),
  },
});

// πŸŒ“ System Theme Detection
const useSystemTheme = () => {
  const [theme, setTheme] = useState("light");

  useEffect(() => {
    const media = window.matchMedia("(prefers-color-scheme: dark)");
    setTheme(media.matches ? "dark" : "light");

    const handler = (e) => setTheme(e.matches ? "dark" : "light");
    media.addEventListener("change", handler);

    return () => media.removeEventListener("change", handler);
  }, []);

  return theme;
};

3. SCSS Best Practices

// πŸš€ 1. Correct Import Order (Critical!)
@import "path/to/functions"; // Must be first - provides function definitions
@import "path/to/mixins"; // Must be second - uses functions internally

// 🎯 2. Use Functions for Individual Values
.card {
  background: color("background.default");
  padding: spacing(4);
  border-radius: radius("md");
  box-shadow: shadow("sm");
}

// πŸ”₯ 3. Use Mixins for Complex Operations
.heading {
  @include typography-styles("heading.large"); // 5 properties applied at once
  @include text-ellipsis(); // Multiple utility properties
}

// πŸ“± 4. Responsive Design Patterns
.component {
  // Base styles with functions
  padding: spacing(4);
  @include typography-styles("body.medium");

  // Responsive with mixins
  @include up("md") {
    padding: spacing(6);
    @include typography-styles("body.large");
  }

  @include up("lg") {
    @include typography-styles("heading.small");
  }
}

// 🎨 5. Advanced Responsive Typography
.hero-title {
  @include responsive-typography(
    (
      "default": "heading.medium",
      // Mobile
      "md": "heading.large",
      // Tablet
      "lg": "heading.display",
      // Desktop
    )
  );
}

4. Performance Tips

// ⚑ Optimize with bulk operations
const spacing = spacingList([2, 4, 6, 8]); // One call for multiple values
const shadows = shadowList(["sm", "md"]); // Avoids multiple function calls

// 🎯 Use tree-shaking
import { color } from "@choiceform/design-tokens"; // Import only what you need

// πŸ“¦ Leverage build-time optimizations
const styles = {
  // Static values are optimized at build time
  padding: spacing(4), // β†’ "1rem"
  // Dynamic values are computed at runtime
  margin: spacing(props.size), // β†’ calculated at runtime
};
// πŸ“¦ SCSS Performance Tips
.optimized {
  // βœ… Efficient: Use functions for individual properties
  padding: spacing(4);
  color: color("text.default");

  // βœ… Efficient: Use mixins for multiple properties
  @include typography-styles("body.large");

  // ❌ Avoid: Don't call functions inside loops
  // Use variables instead when possible
  $base-spacing: spacing(4);

  &::before {
    margin: $base-spacing;
  }

  &::after {
    margin: $base-spacing;
  }
}

🀝 Contributing

We welcome all forms of contributions!

How to Contribute

  1. Fork the project β†’ Create your feature branch
  2. Commit your changes β†’ Ensure all tests pass
  3. Open a Pull Request β†’ Provide a detailed description
  4. Code Review β†’ Collaborate to improve code quality

Development Setup

# 1. Clone your fork
git clone <your-fork-url>
cd design-tokens

# 2. Install dependencies
pnpm install

# 3. Start the development server
pnpm run dev

# 4. Run tests
pnpm run test

Commit Conventions

# Add a new feature
git commit -m "feat: add shadow helper function"

# Fix a bug
git commit -m "fix: resolve color alias resolution issue"

# Update documentation
git commit -m "docs: update README with new examples"

# Add tests
git commit -m "test: add unit tests for spacing helper"

πŸ“„ License

MIT License - see the LICENSE file for details.

πŸ™ Acknowledgements

  • W3C Design Tokens Community Group - For standardizing design tokens
  • Terrazzo - For the token transformation tool
  • Vitest - For the powerful testing framework
  • TypeScript - For providing type safety

Manage your design tokens the modern way 🎨

Quick Start Β· View Examples Β· API Docs Β· Changelog

About

A type-safe, W3C-compliant design token system that bridges the gap between design and development.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published