@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
- Installation
- Quick Start
- API Reference
- Utility Functions
- Color Formats
- Default Color Palette
- TypeScript Support
- Examples
- Contributing
- License
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-toolsQuick 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 definitionssetTheme?: (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:
#FF6432orFF6432 - Color Arrays:
[255, 100, 50, 1]
Default Color Palette
The library includes a default color palette with the following color names:
primary,secondarybg(background),fg(foreground)shadowgreen,reddanger,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
