@wix/css-property-parser
TypeScript icon, indicating that this package has built-in type declarations

1.7.0 • Public • Published

CSS Property Parser

A comprehensive TypeScript library for parsing and serializing CSS property values with full MDN specification compliance.

Test all CSS property parsers live in your browser with real-time parsing and examples.

🚀 Features

  • 73 CSS Property Evaluators - Complete parsing support for layout, typography, colors, and more
  • MDN Compliant - Follows official CSS specifications exactly
  • TypeScript First - Full type safety with comprehensive type definitions
  • Round-Trip Stable - Parse → serialize → parse produces identical results
  • CSS Functions - Supports calc(), min(), max(), clamp(), gradients, and more
  • CSS Variables - Handles custom properties with fallback values
  • Performance Optimized - Fast parsing with minimal memory footprint
  • 6,326+ Tests - Comprehensive test coverage across 82 test suites with 99.98% pass rate
  • Shared Evaluator Pattern - 95% code reduction through intelligent code reuse

📦 Installation

npm install @wix/css-property-parser

🎯 Quick Start

import { Width, Height, Background, Font } from '@wix/css-property-parser';

// Parse CSS values
const width = Width.parse('calc(100% - 20px)');
const height = Height.parse('50vh');
const background = Background.parse('linear-gradient(45deg, red, blue)');

// Serialize back to CSS
const widthCSS = Width.toCSSValue(width);     // "calc(100% - 20px)"
const heightCSS = Height.toCSSValue(height);  // "50vh"
const bgCSS = Background.toCSSValue(background); // "linear-gradient(45deg, red, blue)"

📋 API Reference

Core API Pattern

Every property evaluator follows the same consistent API:

interface PropertyEvaluator<T> {
  parse(value: string): T | null;
  toCSSValue(parsed: T | null): string | null;
}

Property Evaluators

Layout Properties

import { Width, Height, MinWidth, MaxWidth, MinHeight, MaxHeight } from '@wix/css-property-parser';

// Sizing properties support lengths, percentages, and keywords
const width = Width.parse('50%');        // { value: 50, unit: '%' }
const height = Height.parse('auto');     // { keyword: 'auto' }
const minWidth = MinWidth.parse('0');    // { value: 0, unit: 'px' }

Spacing Properties

import { Margin, Padding, Gap, ColumnGap, RowGap } from '@wix/css-property-parser';

// Shorthand properties expand to constituent parts
const margin = Margin.parse('10px 20px');    // Expands to top/right/bottom/left
const padding = Padding.parse('1em');        // Expands to all sides
const gap = Gap.parse('10px 20px');         // Row and column gaps

Typography Properties

import { FontSize, FontWeight, FontFamily, LineHeight, LetterSpacing } from '@wix/css-property-parser';

// Font properties with comprehensive keyword support
const fontSize = FontSize.parse('1.2em');           // { value: 1.2, unit: 'em' }
const fontWeight = FontWeight.parse('bold');        // { keyword: 'bold' }
const lineHeight = LineHeight.parse('1.5');         // { value: 1.5 } (unitless)

Complex Properties

import { Background, Border, Font, TextShadow } from '@wix/css-property-parser';

// Multi-value and shorthand properties
const background = Background.parse('url(bg.jpg) no-repeat center / cover');
const border = Border.parse('2px solid red');
const font = Font.parse('bold 16px/1.4 "Helvetica Neue", Arial, sans-serif');
const textShadow = TextShadow.parse('2px 2px 4px rgba(0,0,0,0.5)');

Type Evaluators

For parsing individual CSS data types:

import { 
  LengthEvaluator, 
  PercentageEvaluator, 
  Color, 
  AngleEvaluator,
  NumberEvaluator 
} from '@wix/css-property-parser';

// Parse individual CSS types
const length = LengthEvaluator.parse('10px');        // { value: 10, unit: 'px' }
const percentage = PercentageEvaluator.parse('50%');  // { value: 50, unit: '%' }
const color = Color.parse('#ff0000');                // { type: 'hex', value: 'ff0000' }
const angle = AngleEvaluator.parse('45deg');         // { value: 45, unit: 'deg' }

🔧 Advanced Usage

CSS Variables

import { Width, CssVariable } from '@wix/css-property-parser';

// CSS variables are parsed but not resolved
const width = Width.parse('var(--main-width)');
// Returns: { CSSvariable: '--main-width' }

const widthWithFallback = Width.parse('var(--main-width, 100px)');
// Returns: { CSSvariable: '--main-width', defaultValue: '100px' }

CSS Functions

import { Width, FontSize } from '@wix/css-property-parser';

// Calc expressions
const width = Width.parse('calc(100% - 20px)');
// Returns: { expression: '100% - 20px', function: 'calc' }

// Min/max/clamp functions
const fontSize = FontSize.parse('clamp(1rem, 2.5vw, 2rem)');
// Returns: { expression: '1rem, 2.5vw, 2rem', function: 'clamp' }

Round-Trip Stability

import { Background } from '@wix/css-property-parser';

const originalValue = 'linear-gradient(45deg, red 0%, blue 100%)';
const parsed = Background.parse(originalValue);
const serialized = Background.toCSSValue(parsed);

console.log(serialized === originalValue); // true

🎨 Use Cases

Design Systems

import { FontSize, Color, Margin } from '@wix/css-property-parser';

// Validate design tokens
function validateDesignToken(property: string, value: string): boolean {
  switch (property) {
    case 'font-size':
      return FontSize.parse(value) !== null;
    case 'color':
      return Color.parse(value) !== null;
    case 'margin':
      return Margin.parse(value) !== null;
    default:
      return false;
  }
}

CSS-in-JS Libraries

import { Width, Height, Background } from '@wix/css-property-parser';

// Parse and transform CSS values
function processStyles(styles: Record<string, string>) {
  const processed: Record<string, any> = {};
  
  for (const [property, value] of Object.entries(styles)) {
    switch (property) {
      case 'width':
        processed.width = Width.parse(value);
        break;
      case 'height':
        processed.height = Height.parse(value);
        break;
      case 'background':
        processed.background = Background.parse(value);
        break;
    }
  }
  
  return processed;
}

CSS Optimization Tools

import { Color, Background } from '@wix/css-property-parser';

// Optimize CSS values
function optimizeColor(value: string): string {
  const parsed = Color.parse(value);
  if (parsed && parsed.type === 'hex') {
    // Convert to shortest hex format
    return Color.toCSSValue(parsed);
  }
  return value;
}

📚 Documentation

🧪 Testing

# Run all tests
npm test

# Run tests for specific property
npm test -- width.test.ts

# Run tests with coverage
npm test:coverage

# Watch mode for development
npm test:watch

🏗️ Development

# Install dependencies
npm install

# Build TypeScript
npm run build

# Build with watch mode
npm run build:watch

# Run development server
npm run dev

📊 Supported Properties

Sizing Properties (6 properties)

  • width, height, min-width, max-width, min-height, max-height

Spacing Properties (16 properties)

  • Shorthand: margin, padding, gap, column-gap, row-gap
  • Individual Margins: margin-top, margin-right, margin-bottom, margin-left
  • Individual Paddings: padding-top, padding-right, padding-bottom, padding-left
  • Legacy Grid: grid-gap, grid-column-gap, grid-row-gap

Typography Properties (12 properties)

  • Font Properties: font-size, font-weight, font-style, font-variant, font-stretch, font
  • Text Properties: text-align, text-transform, text-decoration, text-shadow
  • Spacing: line-height, letter-spacing

Border Properties (21 properties)

  • Main: border, border-radius, border-color, border-style, border-width
  • Individual Widths: border-top-width, border-right-width, border-bottom-width, border-left-width
  • Individual Colors: border-top-color, border-right-color, border-bottom-color, border-left-color
  • Individual Styles: border-top-style, border-right-style, border-bottom-style, border-left-style
  • Individual Shorthand: border-top, border-right, border-bottom, border-left

Visual Properties (4 properties)

  • color, background, opacity, box-shadow

Layout Alignment (4 properties)

  • align-items, align-self, justify-content, flex-direction

Data Types (10 types)

  • length, percentage, number, angle, time, color
  • position, string, css-variable, blend-mode, length-percentage

Shared Evaluators (8 shared)

  • Sizing Properties: Shared evaluator for width/height variants (95% code reduction)
  • Spacing Properties: Shared evaluators for gap, margin, padding variants
  • Border Width Properties: Shared evaluator for border-width variants
  • Border Style Properties: Shared evaluator for border-style variants
  • Border Color Properties: Shared evaluator for border-color variants
  • Border Individual Properties: Shared evaluator for border shorthand variants

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add comprehensive tests (20+ tests minimum)
  4. Ensure all tests pass
  5. Follow the Evaluator Guide
  6. Submit a pull request

📄 License

ISC License - see LICENSE file for details.

🙏 Acknowledgments

  • Built with MDN CSS specifications as the authoritative reference
  • Inspired by the need for robust CSS parsing in modern web applications
  • Comprehensive testing ensures production-ready reliability
  • Enhanced and documented with assistance from Claude (Anthropic AI)

Package Sidebar

Install

npm i @wix/css-property-parser

Weekly Downloads

236

Version

1.7.0

License

ISC

Unpacked Size

492 kB

Total Files

249

Last publish

Collaborators

  • yoav
  • wix-ci
  • shahata
  • wixnpm
  • wix-ambassador
  • netanelgilad
  • wix-ci-publisher
  • wix-bi-publisher
  • galil-team
  • lxgreen
  • ariki
  • liorgwix
  • usability-sessions
  • yurynix
  • oferb-wix
  • domasmak
  • mayaco
  • amitde007
  • tombenezra
  • itaytay
  • haimbrum-wix
  • youngshinobi
  • varzager
  • benblayer-wix