MooColor

2.0.0 · active · verified Sun Apr 19

MooColor is a modern TypeScript library designed for comprehensive color parsing, conversion, and manipulation. Currently stable at version 2.0.0, the package maintains an active release cadence with minor updates and patches, and announces significant breaking changes with major versions. Key differentiators include its strictly immutable API, where all manipulation methods return new instances rather than mutating the original, and robust WCAG 2.1 compliance for accurate luminance and contrast ratio calculations. It provides dual ESM, CJS, and IIFE bundles, making it versatile across Node.js environments (requiring Node.js >=18 since v2) and browsers. The library is fully typed, including Template Literal Types for advanced color string representation, and supports a wide array of color models like hex, RGB, HSL, HWB, HSV, and CMYK, alongside named colors.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing various color formats, performing immutable manipulations, chaining methods, checking WCAG contrast ratios, and generating constrained random colors.

import { MooColor } from 'moo-color';

// Parse various color formats, including named colors and RGBA
const red = new MooColor('red');
const semiTransparentBlue = new MooColor('rgba(0, 0, 255, 0.7)');
const orangeHsl = new MooColor('hsl(30, 100%, 50%)');

console.log('Original Red (hex):', red.toHex()); // #ff0000

// Manipulation methods return new instances (immutable API since v2.0.0)
const lightenedRed = red.lighten(20);
const desaturatedBlue = semiTransparentBlue.desaturate(30);

console.log('Lightened Red (hex):', lightenedRed.toHex()); // Example: #ff6666
console.log('Original Red is unchanged:', red.toHex()); // #ff0000

// Chaining operations
const adjustedOrange = orangeHsl
  .rotate(60) // Rotate hue by 60 degrees
  .saturate(15) // Increase saturation
  .darken(10) // Darken the color
  .setAlpha(0.9); // Set transparency

console.log('Adjusted Orange (RGBA):', adjustedOrange.toRgba()); // Example: rgba(..., 0.9)

// WCAG contrast ratio check
const white = new MooColor('#fff');
const black = new MooColor('#000');
console.log('Contrast Ratio (Black vs White):', black.contrastRatioWith(white)); // 21

// Generate a random color with specific constraints
const randomWarmColor = MooColor.random({ hue: [0, 60], saturation: [50, 100] });
console.log('Random warm color:', randomWarmColor.toHsl());

view raw JSON →