CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-stylis

A lightweight CSS preprocessor that provides CSS parsing, AST manipulation, vendor prefixing, and serialization capabilities.

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities

Helper functions for string manipulation, array operations, CSS processing constants, and utility operations used throughout the Stylis library.

Capabilities

Constants and Enumerations

Vendor Prefix Constants

const MS: string;     // '-ms-' - Microsoft vendor prefix
const MOZ: string;    // '-moz-' - Mozilla vendor prefix  
const WEBKIT: string; // '-webkit-' - WebKit vendor prefix

Node Type Constants

const COMMENT: string;    // 'comm' - Comment node type identifier
const RULESET: string;    // 'rule' - Ruleset node type identifier
const DECLARATION: string; // 'decl' - Declaration node type identifier

At-Rule Constants

const PAGE: string;                  // '@page' - Page at-rule identifier
const MEDIA: string;                 // '@media' - Media query at-rule identifier
const IMPORT: string;                // '@import' - Import at-rule identifier
const CHARSET: string;               // '@charset' - Charset at-rule identifier
const VIEWPORT: string;              // '@viewport' - Viewport at-rule identifier
const SUPPORTS: string;              // '@supports' - Supports at-rule identifier
const DOCUMENT: string;              // '@document' - Document at-rule identifier
const NAMESPACE: string;             // '@namespace' - Namespace at-rule identifier
const KEYFRAMES: string;             // '@keyframes' - Keyframes at-rule identifier
const FONT_FACE: string;             // '@font-face' - Font-face at-rule identifier
const COUNTER_STYLE: string;         // '@counter-style' - Counter-style at-rule identifier
const FONT_FEATURE_VALUES: string;   // '@font-feature-values' - Font feature values at-rule identifier
const LAYER: string;                 // '@layer' - Layer at-rule identifier
const SCOPE: string;                 // '@scope' - Scope at-rule identifier

Mathematical and Conversion Functions

Basic Math Operations

const abs: function;  // Math.abs - Return absolute value of number
const from: function; // String.fromCharCode - Convert character code to string
const assign: function; // Object.assign - Copy properties between objects

Usage Examples:

import { abs, from, assign } from 'stylis';

// Absolute value
const distance = abs(-10); // 10

// Character code conversion
const character = from(65); // 'A'

// Object property assignment
const merged = assign({}, { color: 'red' }, { fontSize: '14px' });
// { color: 'red', fontSize: '14px' }

String Manipulation Functions

Hash Function

/**
 * Generate hash value from string based on first 4 characters
 * @param value - String to hash
 * @param length - Length context for hashing
 * @returns Number hash value
 */
function hash(value: string, length: number): number;

String Processing Functions

/**
 * Remove whitespace from beginning and end of string
 * @param value - String to trim
 * @returns Trimmed string
 */
function trim(value: string): string;

/**
 * Execute regular expression and return first match or null
 * @param value - String to search
 * @param pattern - Regular expression pattern
 * @returns First match string or null
 */
function match(value: string, pattern: RegExp): string | null;

/**
 * Replace substring or regex matches in string
 * @param value - Source string
 * @param pattern - String or RegExp to find
 * @param replacement - Replacement string
 * @returns String with replacements applied
 */
function replace(value: string, pattern: string | RegExp, replacement: string): string;

/**
 * Find index of substring in string
 * @param value - String to search
 * @param search - Substring to find
 * @param position - Starting position for search
 * @returns Index of substring or -1 if not found
 */
function indexof(value: string, search: string, position?: number): number;

/**
 * Get character code at specific index in string
 * @param value - Source string
 * @param index - Character index
 * @returns Character code (0 if index out of bounds)
 */
function charat(value: string, index: number): number;

/**
 * Extract substring between start and end indices
 * @param value - Source string
 * @param begin - Start index
 * @param end - End index
 * @returns Extracted substring
 */
function substr(value: string, begin: number, end: number): string;

/**
 * Get length of string
 * @param value - String to measure
 * @returns String length
 */
function strlen(value: string): number;

Usage Examples:

import { hash, trim, match, replace, indexof, charat, substr, strlen } from 'stylis';

// String hashing
const hashValue = hash('color', 5); // Numeric hash for 'color'

// String cleaning
const cleaned = trim('  padding: 20px  '); // 'padding: 20px'

// Pattern matching
const found = match('color: red;', /color:\s*(\w+)/); // 'color: red'

// String replacement
const prefixed = replace('display: flex', 'flex', '-webkit-flex'); 
// 'display: -webkit-flex'

// Substring search
const colonIndex = indexof('color: red', ':'); // 5

// Character code extraction
const firstChar = charat('color', 0); // 99 (character code for 'c')

// Substring extraction
const property = substr('color: red;', 0, 5); // 'color'

// String length
const length = strlen('padding'); // 7

Array and Collection Functions

Array Size and Manipulation

/**
 * Get length of array
 * @param value - Array to measure
 * @returns Array length
 */
function sizeof(value: any[]): number;

/**
 * Push value to array and return the value
 * @param value - Value to append
 * @param array - Target array
 * @returns The appended value
 */
function append(value: any, array: any[]): any;

/**
 * Map array through callback and join results into string
 * @param array - Source array
 * @param callback - Function to apply to each element
 * @returns Joined string result
 */
function combine(array: string[], callback: function): string;

/**
 * Filter array by removing items that match regex pattern
 * @param array - Source array
 * @param pattern - RegExp pattern to exclude
 * @returns Filtered array (items that don't match pattern)
 */
function filter(array: string[], pattern: RegExp): string[];

Usage Examples:

import { sizeof, append, combine, filter } from 'stylis';

// Array length
const selectors = ['h1', 'h2', 'h3'];
const count = sizeof(selectors); // 3

// Array append with return value
const rules = [];
const newRule = append('color: red;', rules);
console.log(newRule); // 'color: red;'
console.log(rules); // ['color: red;']

// Array transformation and joining
const properties = ['margin', 'padding', 'border'];
const cssBlock = combine(properties, (prop) => `${prop}: 0;`);
// 'margin: 0;padding: 0;border: 0;'

// Array filtering (removes matches)
const declarations = ['color: red;', '/* comment */', 'font-size: 14px;'];
const withoutComments = filter(declarations, /\/\*/);
// ['color: red;', 'font-size: 14px;']

Utility Function Patterns

String Processing Pipeline

import { trim, replace, indexof, substr } from 'stylis';

function processProperty(declaration) {
  // Clean whitespace
  const cleaned = trim(declaration);
  
  // Find property-value separator
  const colonIndex = indexof(cleaned, ':');
  if (colonIndex === -1) return null;
  
  // Extract property and value
  const property = trim(substr(cleaned, 0, colonIndex));
  const value = trim(substr(cleaned, colonIndex + 1, cleaned.length));
  
  // Add vendor prefix if needed
  const prefixed = replace(property, /^(transform|transition)/, '-webkit-$1');
  
  return { property: prefixed, value };
}

// Usage
const result = processProperty('  transform: scale(1.2)  ');
// { property: '-webkit-transform', value: 'scale(1.2)' }

Array Processing Chain

import { filter, combine, sizeof } from 'stylis';

function processSelectors(selectors, namespace) {
  // Remove empty selectors
  const cleaned = filter(selectors, /^\s*$/);
  
  // Add namespace prefix
  const namespaced = cleaned.map(selector => `${namespace} ${selector}`);
  
  // Combine into CSS selector string
  const combined = combine(namespaced, (sel) => sel);
  
  return {
    selectors: namespaced,
    css: combined,
    count: sizeof(namespaced)
  };
}

// Usage
const result = processSelectors(['h1', '', 'p'], '.component');
// {
//   selectors: ['.component h1', '.component p'],
//   css: '.component h1.component p',
//   count: 2
// }

Hash-based Property Detection

import { hash } from 'stylis';

function needsPrefix(property, length) {
  const propertyHash = hash(property, length);
  
  // Hash values for properties that need prefixes
  const prefixHashes = [
    5349, // appearance
    4246, // user-select  
    4810, // transform
    6968, // hyphens
    2756  // text-size-adjust
  ];
  
  return prefixHashes.includes(propertyHash);
}

// Usage
const shouldPrefix = needsPrefix('user-select', 11); // true

Performance Considerations

The utility functions are optimized for performance in CSS processing contexts:

  • String functions: Use native JavaScript methods with minimal overhead
  • Array functions: Designed for small arrays typical in CSS processing
  • Hash function: Fast character-based hashing for property identification
  • Character operations: Work directly with character codes for speed

Memory Management

  • Immutable operations: Most functions return new values rather than modifying inputs
  • Minimal allocations: Reuse of built-in JavaScript functions where possible
  • String interning: Character-based operations avoid unnecessary string creation

Install with Tessl CLI

npx tessl i tessl/npm-stylis

docs

index.md

middleware.md

parser.md

serialization.md

tokenization.md

utilities.md

tile.json