npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ptbarnum/color-tools

v0.2.0

Published

Color tools

Readme

Color Tools

A powerful TypeScript library for managing, manipulating, and switching between color themes in web applications. Provides a comprehensive set of tools for working with colors including theme management, color adjustments, contrast calculations, and format conversions.

Features

  • 🎨 Theme Management: Easy switching between light/dark themes with custom theme support
  • 🔧 Color Manipulation: Adjust brightness, opacity, and lightness of colors
  • 📏 Accessibility: Built-in contrast ratio calculations following WCAG guidelines
  • 🎯 Type Safety: Full TypeScript support with comprehensive type definitions
  • 🔄 Format Conversion: Convert between RGB, RGBA, and HEX color formats
  • 🛠️ Extensible: Add custom methods and properties to your color tools instance

Installation

npm install @ptbarnum/color-tools

Quick Start

import ColorTools from '@ptbarnum/color-tools';

const colorTools = new ColorTools({
  mode: 'light',
  themes: {
    light: {
      bg: 'rgba(232, 236, 240, 1.00)',
      fg: 'rgba(100, 0, 254, 1.00)',
    },
    dark: {
      bg: 'rgba(30, 34, 38, 1.00)',
      fg: 'rgba(60, 255, 180, 1.00)',
    },
    common: {
      red: 'rgba(255, 50, 50, 1.00)',
    },
  },
  setTheme: (newThemeMode: string) => {
    console.log(`Theme changed to: ${newThemeMode}`);
  },
});

// Get current theme mode
console.log(colorTools.mode); // 'light'

// Get a color from the current theme
console.log(colorTools.get('fg')); // 'rgba(100, 0, 254, 1.00)'

// Toggle between light and dark themes
colorTools.toggle(); // returns 'dark'

// Color is now from dark theme
console.log(colorTools.get('fg')); // 'rgba(60, 255, 180, 1.00)'

API Reference

Constructor

new ColorTools(options: ColorToolsArgs)

Options:

  • mode?: string - Initial theme mode (default: 'dark')
  • themes?: ThemeOptions - Custom theme definitions
  • setTheme?: (mode: string) => void - Callback function called when theme changes

Core Methods

Theme Management

// Set a specific theme
colorTools.setTheme('dark');

// Toggle between light and dark themes
const newMode = colorTools.toggle(); // returns the new mode

// Check if currently in light mode
if (colorTools.isLightMode) {
  // Handle light mode specific logic
}

Color Retrieval

// Get a color from the current theme
const backgroundColor = colorTools.get('bg');

// Get RGB values as comma-separated string
const rgbString = colorTools.asRgb('primary', 1); // "255, 100, 50"

Color Manipulation

// Adjust opacity/alpha
const semiTransparent = colorTools.alpha('bg', 0.5);

// Make colors lighter or darker
const lighter = colorTools.lighter('primary', 2);
const darker = colorTools.darker('primary', 1.5);

// Generic lightness adjustment
const adjusted = colorTools.lightness('secondary', -0.5);

// Advanced color adjustments
const customColor = colorTools.adjust('primary', {
  lighter: 1,
  alpha: 0.8,
});

Theme-Specific Colors

// Different colors for different themes
const adaptiveColor = colorTools.alternate(
  'primary',
  { lighter: 1 }, // light theme options
  { darker: 0.5 }, // dark theme options
);

// Switch between different colors/options based on theme
const themeSpecificColor = colorTools.switch(
  'lightModeColor', // for light theme
  'darkModeColor', // for dark theme
);

// Or with adjustment options
const complexSwitch = colorTools.switch(
  { color: 'primary', lighter: 1 }, // light theme
  { color: 'secondary', alpha: 0.9 }, // dark theme
);

Accessibility & Contrast

// Calculate contrast ratio between two colors
const ratio = colorTools.contrast('bg', 'fg'); // returns number (e.g., 4.5)

// Check if contrast meets WCAG standards
if (ratio >= 4.5) {
  console.log('Colors meet WCAG AA standards');
}

CSS Integration

// Generate CSS custom properties
const cssVars = colorTools.cssVarsToString();
// Returns: "--ct-bg: rgba(232, 236, 240, 1.00);
--ct-fg: rgba(100, 0, 254, 1.00);"

Extensibility

// Add custom methods
colorTools.addMethod('customBlend', function (color1, color2, ratio) {
  // Custom color blending logic
  return blendedColor;
});

// Use custom method
const blended = colorTools.call('customBlend', 'primary', 'secondary', 0.5);

// Add custom properties
colorTools.addProp('customConfig', { specialValue: 42 });

// Access custom properties
const config = colorTools.props.get('customConfig');

Utility Functions

The library also exports standalone utility functions for color manipulation:

import {
  adjustColorLightness,
  adjustAlpha,
  contrastRatio,
  toHex,
  toRgba,
  rgbaToString,
} from '@ptbarnum/color-tools';

// Adjust color lightness
const lighter = adjustColorLightness([255, 100, 50, 1], 2);

// Modify alpha channel
const transparent = adjustAlpha([255, 100, 50, 1], 0.5);

// Calculate contrast ratio
const ratio = contrastRatio([0, 0, 0, 1], [255, 255, 255, 1]); // 21

// Convert colors
const hex = toHex('rgba(255, 100, 50, 1)'); // "#FF6432"
const rgba = toRgba('#FF6432'); // "rgba(255,100,50,1)"

Color Formats

The library supports multiple color formats:

  • RGBA: rgba(255, 100, 50, 1.0)
  • RGB: rgb(255, 100, 50)
  • HEX: #FF6432 or FF6432
  • Color Arrays: [255, 100, 50, 1]

Default Color Palette

The library includes a default color palette with the following color names:

  • primary, secondary
  • bg (background), fg (foreground)
  • shadow
  • green, red
  • danger, warn, info

You can extend or override these in your theme configuration.

TypeScript Support

Full TypeScript support with comprehensive type definitions:

import type {
  ColorName,
  ColorAdjustOptions,
  ThemeOptions,
  TColorRGBA,
} from '@ptbarnum/color-tools';

// Type-safe color names
const colorName: ColorName = 'primary';

// Type-safe adjustment options
const options: ColorAdjustOptions = {
  lighter: 1,
  alpha: 0.8,
};

Examples

React Integration

import React, { createContext, useContext, useState } from 'react';
import ColorTools from '@ptbarnum/color-tools';

const ColorContext = createContext<ColorTools | null>(null);

export function ColorProvider({ children }: { children: React.ReactNode }) {
  const [, setThemeMode] = useState('light');

  const colorTools = new ColorTools({
    mode: 'light',
    setTheme: (mode) => {
      setThemeMode(mode);
      document.documentElement.setAttribute('data-theme', mode);
    },
  });

  return (
    <ColorContext.Provider value={colorTools}>{children}</ColorContext.Provider>
  );
}

export function useColors() {
  const context = useContext(ColorContext);
  if (!context) throw new Error('useColors must be used within ColorProvider');
  return context;
}

// Usage in component
function MyComponent() {
  const colors = useColors();

  return (
    <div
      style={{
        backgroundColor: colors.get('bg'),
        color: colors.get('fg'),
        borderColor: colors.alpha('primary', 0.3),
      }}
    >
      <button onClick={() => colors.toggle()}>
        Switch to {colors.isLightMode ? 'Dark' : 'Light'} Theme
      </button>
    </div>
  );
}

CSS Variables Integration

const colorTools = new ColorTools({
  mode: 'light',
  setTheme: (mode) => {
    // Update CSS custom properties
    const cssVars = colorTools.cssVarsToString();
    const styleSheet = document.createElement('style');
    styleSheet.textContent = `:root { ${cssVars} }`;
    document.head.appendChild(styleSheet);
  },
});

// Your CSS can now use:
// background-color: var(--ct-bg);
// color: var(--ct-fg);

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

ISC