color-fns: Modern Color Utility Library

0.1.1 · active · verified Sun Apr 19

color-fns is a modern, modular, and tree-shakable JavaScript utility library designed for comprehensive color manipulation and conversion. Inspired by the API design of `date-fns`, it emphasizes lightweight, individual function imports for optimal bundle sizes. The current stable version is 0.1.1, following a significant rewrite in version 0.1.0 that introduced a new, TypeScript-first API with reduced overloads and clearer handling of color values. The library supports multiple color models (RGB, HSL, HSV, CMYK, Hex) and offers functions for parsing, conversion, operations (like mixing), formatting to CSS-compatible output, validation, and querying (e.g., contrast, darkness). While still in pre-1.0 status, its development appears active, with a focus on type safety and modern JavaScript practices. Key differentiators include its modularity, explicit TypeScript types, and a clear, functional API.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing hex colors, converting between models (RGB to HSL), mixing colors, formatting output back to hex, and validating color strings using the `color-fns` library.

import { parseHex, toRgb, rgbToHsl, mix, formatHex, isValidHex } from 'color-fns';

// 1. Parse a hex color string into an RGB object
const hexRed = '#FF0000';
const redRgb = parseHex(hexRed); // { r: 255, g: 0, b: 0 }
console.log(`Parsed '${hexRed}' to RGB:`, redRgb);

// 2. Convert RGB to HSL
const blueRgb = { r: 0, g: 0, b: 255 };
const blueHsl = rgbToHsl(blueRgb); // { h: 240, s: 1, l: 0.5 }
console.log(`Converted RGB ${JSON.stringify(blueRgb)} to HSL:`, blueHsl);

// 3. Mix two RGB colors
const mixedRgb = mix(redRgb, blueRgb, 0.5); // Mixes red and blue 50/50 to produce purple
console.log('Mixed Red and Blue (50/50) to RGB:', mixedRgb);

// 4. Format an RGB color object back to a hex string
const formattedMixedHex = formatHex(mixedRgb);
console.log('Formatted mixed RGB to Hex string:', formattedMixedHex); // e.g., '#800080'

// 5. Validate a color string
const validHex = '#ABC';
const invalidHex = '#XYZ';
console.log(`Is '${validHex}' a valid hex string?`, isValidHex(validHex)); // true
console.log(`Is '${invalidHex}' a valid hex string?`, isValidHex(invalidHex)); // false

view raw JSON →