CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-unocss--core

The core atomic CSS engine for UnoCSS that generates CSS on-demand without any presets or default utilities.

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities and Helpers

UnoCSS Core provides a comprehensive utility library with functions for CSS processing, type manipulation, selector escaping, variant group handling, and development helpers.

Array and Type Utilities

function toArray<T>(value: T | T[] = []): T[];
function uniq<T>(value: T[]): T[];
function uniqueBy<T>(array: readonly T[], equalFn: (a: T, b: T) => boolean): T[];
function isString(s: any): s is string;
function notNull<T>(value: T | null | undefined): value is T;
function noop(): void;

Basic type and array manipulation:

  • toArray: Converts single values or arrays to arrays
  • uniq: Removes duplicate values from arrays
  • uniqueBy: Removes duplicates using custom comparison function
  • isString: Type guard for string values
  • notNull: Type guard for non-null values
  • noop: No-operation function

Usage Examples

import { toArray, uniq, uniqueBy, isString } from '@unocss/core';

// Convert to array
toArray('single') // ['single']
toArray(['already', 'array']) // ['already', 'array']

// Remove duplicates
uniq(['a', 'b', 'a', 'c']) // ['a', 'b', 'c']

// Remove duplicates with custom comparison
const items = [{ id: 1, name: 'A' }, { id: 1, name: 'B' }, { id: 2, name: 'C' }];
uniqueBy(items, (a, b) => a.id === b.id) // [{ id: 1, name: 'A' }, { id: 2, name: 'C' }]

// Type checking
if (isString(value)) {
  // TypeScript knows value is string here
  console.log(value.toUpperCase());
}

CSS Processing Utilities

function normalizeCSSEntries(obj: string | CSSEntriesInput | CSSObjectInput): string | CSSEntries;
function normalizeCSSValues(obj: CSSValueInput | string | (CSSValueInput | string)[]): (string | CSSEntries)[];
function entriesToCss(arr?: CSSEntries): string;
function clearIdenticalEntries(entry: CSSEntries): CSSEntries;

const VirtualKey: string = '__virtual_key__';

CSS data processing:

  • normalizeCSSEntries: Converts CSS objects/entries to normalized format
  • normalizeCSSValues: Normalizes various CSS value input formats
  • entriesToCss: Converts CSS entries to CSS string
  • clearIdenticalEntries: Removes duplicate CSS properties
  • VirtualKey: Special key for virtual CSS properties

CSS Processing Examples

import { normalizeCSSEntries, entriesToCss } from '@unocss/core';

// Normalize CSS input
const entries = normalizeCSSEntries({
  color: 'red',
  margin: '1rem',
  padding: '0.5rem'
});

// Convert to CSS string
const css = entriesToCss([
  ['color', 'red'],
  ['margin', '1rem'],
  ['padding', '0.5rem']
]);
// Result: "color:red;margin:1rem;padding:0.5rem;"

Object Manipulation Utilities

function mergeDeep<T>(original: T, patch: DeepPartial<T>, mergeArray?: boolean): T;
function clone<T>(val: T): T;
function isObject(item: any): item is Record<string, any>;

Deep object operations:

  • mergeDeep: Deep merges objects with optional array merging
  • clone: Creates deep copy of values (objects, arrays, primitives)
  • isObject: Type guard for plain objects

Object Utility Examples

import { mergeDeep, clone } from '@unocss/core';

// Deep merge objects
const original = { theme: { colors: { primary: 'blue' } } };
const patch = { theme: { colors: { secondary: 'red' } } };
const merged = mergeDeep(original, patch);
// Result: { theme: { colors: { primary: 'blue', secondary: 'red' } } }

// Clone objects
const original = { nested: { value: 42 } };
const cloned = clone(original);
cloned.nested.value = 100; // original.nested.value is still 42

Selector Escaping

function escapeSelector(str: string): string;
function escapeRegExp(string: string): string;
const e: typeof escapeSelector;

CSS selector escaping:

  • escapeSelector: Escapes CSS selector strings according to CSS spec
  • escapeRegExp: Escapes regex special characters
  • e: Short alias for escapeSelector

Escaping Examples

import { escapeSelector, e } from '@unocss/core';

// Escape CSS selectors
escapeSelector('bg-red-500') // '.bg-red-500'
escapeSelector('w-1/2') // '.w-1\\/2'
escapeSelector('2xl:text-lg') // '.\\32 xl\\:text-lg'

// Short alias
e('hover:bg-blue') // '.hover\\:bg-blue'

Rule and Shortcut Type Guards

function isStaticRule(rule: Rule<any>): rule is StaticRule;
function isStaticShortcut(sc: Shortcut<any>): sc is StaticShortcut;
function isRawUtil(util: ParsedUtil | RawUtil | StringifiedUtil): util is RawUtil;

Type discrimination:

  • isStaticRule: Checks if rule is static (string matcher)
  • isStaticShortcut: Checks if shortcut is static
  • isRawUtil: Checks if utility is raw CSS

Variant Group Processing

function parseVariantGroup(str: string | MagicString, separators?: string[], depth?: number): {
  prefixes: string[];
  hasChanged: boolean;
  groupsByOffset: Map<number, VariantGroup>;
  expanded: string;
};

function expandVariantGroup(str: string, separators?: string[], depth?: number): string;
function expandVariantGroup(str: MagicString, separators?: string[], depth?: number): MagicString;

function collapseVariantGroup(str: string, prefixes: string[]): string;
function makeRegexClassGroup(separators?: string[]): RegExp;

Variant group manipulation:

  • parseVariantGroup: Parses variant group syntax with detailed information
  • expandVariantGroup: Expands variant groups into individual classes
  • collapseVariantGroup: Collapses classes back into variant groups
  • makeRegexClassGroup: Creates regex for matching variant groups

Variant Group Examples

import { expandVariantGroup, collapseVariantGroup } from '@unocss/core';

// Expand variant groups
expandVariantGroup('hover:(bg-red text-white)')
// Result: 'hover:bg-red hover:text-white'

expandVariantGroup('md:(flex items-center) lg:(grid grid-cols-2)')
// Result: 'md:flex md:items-center lg:grid lg:grid-cols-2'

// Collapse back to groups
collapseVariantGroup('hover:bg-red hover:text-white', ['hover:'])
// Result: 'hover:(bg-red text-white)'

Enhanced Data Structures

CountableSet

class CountableSet<K> extends Set<K> {
  getCount(key: K): number;
  setCount(key: K, count: number): this;
  add(key: K): this;
  delete(key: K): boolean;
  clear(): void;
}

function isCountableSet<T = string>(value: any): value is CountableSet<T>;

Set that tracks occurrence frequency for each item.

TwoKeyMap

class TwoKeyMap<K1, K2, V> {
  get(key1: K1, key2: K2): V | undefined;
  getFallback(key1: K1, key2: K2, fallback: V): V;
  set(key1: K1, key2: K2, value: V): this;
  has(key1: K1, key2: K2): boolean;
  delete(key1: K1, key2: K2): boolean;
  deleteTop(key1: K1): boolean;
  map<T>(fn: (v: V, k1: K1, k2: K2) => T): T[];
}

Two-level map for nested key-value storage.

BetterMap

class BetterMap<K, V> extends Map<K, V> {
  getFallback(key: K, fallback: V): V;
  map<R>(mapFn: (value: V, key: K) => R): R[];
  flatMap<R extends readonly unknown[]>(mapFn: (value: V, key: K) => R): R[number][];
}

Enhanced Map with utility methods.

Data Structure Examples

import { CountableSet, TwoKeyMap, BetterMap } from '@unocss/core';

// CountableSet usage
const classes = new CountableSet(['flex', 'p-4', 'flex']);
classes.getCount('flex') // 2
classes.getCount('p-4') // 1

// TwoKeyMap usage
const cache = new TwoKeyMap<string, string, number>();
cache.set('theme', 'dark', 1);
cache.set('theme', 'light', 2);
cache.get('theme', 'dark') // 1

// BetterMap usage
const map = new BetterMap();
map.set('a', 1);
map.set('b', 2);
map.getFallback('c', 3) // Sets and returns 3
map.map((value, key) => `${key}:${value}`) // ['a:1', 'b:2', 'c:3']

Layer Utilities

function withLayer<T extends object>(layer: string, rules: Rule<T>[]): Rule<T>[];

Adds layer metadata to rules.

import { withLayer } from '@unocss/core';

const componentRules = [
  ['btn', { padding: '0.5rem 1rem' }],
  ['card', { border: '1px solid #ccc' }]
];

const layeredRules = withLayer('components', componentRules);
// All rules now have layer: 'components' metadata

Event System

function createNanoEvents<Events extends EventsMap = DefaultEvents>(): Emitter<Events>;

interface Emitter<Events extends EventsMap = DefaultEvents> {
  events: Partial<{ [E in keyof Events]: Events[E][] }>;
  on<K extends keyof Events>(event: K, cb: Events[K]): Unsubscribe;
  emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): void;
}

interface Unsubscribe {
  (): void;
}

Lightweight event emitter for internal communication.

Warning System

function warnOnce(msg: string): void;

Warns once per unique message to avoid spam.

import { warnOnce } from '@unocss/core';

// Only shows warning once even if called multiple times
warnOnce('Deprecated feature used');
warnOnce('Deprecated feature used'); // Silent

Validator Utilities

function isAttributifySelector(selector: string): boolean;
function isValidSelector(selector?: string): boolean;
function normalizeVariant(variant: Variant<any>): VariantObject<any>;

Validation helpers:

  • isAttributifySelector: Checks if selector uses attributify syntax
  • isValidSelector: Validates CSS selector format
  • normalizeVariant: Converts variant functions to objects

Validation Examples

import { isAttributifySelector, isValidSelector } from '@unocss/core';

// Check selector types
isAttributifySelector('[bg-red~=""]') // true
isAttributifySelector('.bg-red') // false

// Validate selectors
isValidSelector('valid-class') // true
isValidSelector('') // false
isValidSelector('123invalid') // false

Install with Tessl CLI

npx tessl i tessl/npm-unocss--core

docs

config.md

extraction.md

generator.md

index.md

rules-variants.md

types.md

utilities.md

tile.json