CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-color

A Collection of Color Pickers from Sketch, Photoshop, Chrome & more

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

color-utilities.mddocs/

Color Utilities

Helper functions for color validation, conversion, and manipulation. These utilities provide the underlying functionality used by color picker components and can be used independently for color operations.

Core imports for helper functions:

// Color helper functions
import { 
  simpleCheckForValidColor, 
  toState, 
  isValidHex, 
  getContrastingColor,
  red,
  isvalidColorString 
} from 'react-color/lib/helpers/color';

// Checkboard utilities  
import { render, get } from 'react-color/lib/helpers/checkboard';

// Alternative: Import all helpers
import * as colorHelpers from 'react-color/lib/helpers';

Capabilities

Color Validation

Functions for validating color data and format strings.

simpleCheckForValidColor

Validates color data object to ensure all provided color properties are valid numbers or percentage strings.

/**
 * Validates color data object
 * @param data - Color data object with properties like r, g, b, a, h, s, l, v
 * @returns Validated data object or false if invalid
 */
function simpleCheckForValidColor(data: ColorData): ColorData | false;

interface ColorData {
  r?: number;
  g?: number; 
  b?: number;
  a?: number;
  h?: number;
  s?: number | string; // Accepts percentage strings like "50%"
  l?: number | string; // Accepts percentage strings like "50%"
  v?: number;
  hex?: string;
}

Usage Example:

import { simpleCheckForValidColor } from 'react-color/lib/helpers/color';

const validColor = simpleCheckForValidColor({ r: 255, g: 0, b: 0, a: 1 });
// Returns: { r: 255, g: 0, b: 0, a: 1 }

const invalidColor = simpleCheckForValidColor({ r: 'invalid', g: 0, b: 0 });
// Returns: false

isValidHex

Validates hex color string format, supporting both 3 and 6 character hex codes as well as the special "transparent" value.

/**
 * Validates hex color string
 * @param hex - Hex color string (with or without # prefix)
 * @returns True if valid hex color
 */
function isValidHex(hex: string): boolean;

Usage Example:

import { isValidHex } from 'react-color/lib/helpers/color';

console.log(isValidHex('#ff0000'));     // true
console.log(isValidHex('ff0000'));      // true  
console.log(isValidHex('#f00'));        // true
console.log(isValidHex('transparent')); // true
console.log(isValidHex('#gggggg'));     // false

isvalidColorString

Validates color string for specific color format types.

/**
 * Validates color string for specific type
 * @param string - Color value string
 * @param type - Color type identifier
 * @returns True if valid color string for the given type
 */
function isvalidColorString(string: string, type: string): boolean;

Usage Example:

import { isvalidColorString } from 'react-color/lib/helpers/color';

console.log(isvalidColorString('180', 'hsl')); // true
console.log(isvalidColorString('360°', 'hsl')); // true (degree symbol removed)

Color Conversion

Functions for converting between different color formats and creating normalized color state objects.

toState

Converts color data to a normalized state object containing all color format representations (HSL, RGB, HSV, hex).

/**
 * Converts color data to normalized state object
 * @param data - Color data in any supported format
 * @param oldHue - Previous hue value to preserve when saturation is 0
 * @returns Normalized color state with all format representations
 */
function toState(data: ColorData | string, oldHue?: number): ColorState;

interface ColorState {
  /** HSL color representation */
  hsl: { h: number; s: number; l: number; a: number };
  /** Hex color string (with # prefix) */
  hex: string;
  /** RGB color representation */
  rgb: { r: number; g: number; b: number; a: number };
  /** HSV color representation */
  hsv: { h: number; s: number; v: number; a: number };
  /** Previous hue value */
  oldHue: number;
  /** Source of the color data */
  source?: string;
}

Usage Example:

import { toState } from 'react-color/lib/helpers/color';

// From hex string
const state1 = toState('#ff0000');
console.log(state1.rgb); // { r: 255, g: 0, b: 0, a: 1 }
console.log(state1.hsl); // { h: 0, s: 1, l: 0.5, a: 1 }

// From RGB object
const state2 = toState({ r: 0, g: 255, b: 0 });
console.log(state2.hex); // "#00ff00"

// From HSL with preserved hue
const state3 = toState({ h: 0, s: 0, l: 0.5 }, 180);
console.log(state3.oldHue); // 180 (preserved when saturation is 0)

Color Analysis

Functions for analyzing color properties and determining appropriate contrast colors.

getContrastingColor

Determines the best contrasting color (black or white) for text displayed over a given background color using YIQ color space calculations.

/**
 * Returns contrasting color (black/white) for given color
 * @param data - Color data to analyze
 * @returns "#000" for light colors, "#fff" for dark colors, or rgba for transparent
 */
function getContrastingColor(data: ColorData): string;

Usage Example:

import { getContrastingColor } from 'react-color/lib/helpers/color';

const lightBg = getContrastingColor({ r: 255, g: 255, b: 255 });
console.log(lightBg); // "#000" (black text on white background)

const darkBg = getContrastingColor({ r: 0, g: 0, b: 0 });
console.log(darkBg); // "#fff" (white text on black background)

const transparentBg = getContrastingColor({ hex: 'transparent' });
console.log(transparentBg); // "rgba(0,0,0,0.4)"

Color Constants

Pre-defined color objects for common use cases.

red

Pre-defined red color object containing all color format representations.

/**
 * Predefined red color constant
 */
const red: {
  hsl: { a: 1; h: 0; l: 0.5; s: 1 };
  hex: '#ff0000';
  rgb: { r: 255; g: 0; b: 0; a: 1 };
  hsv: { h: 0; s: 1; v: 1; a: 1 };
};

Usage Example:

import { red } from 'react-color/lib/helpers/color';

console.log(red.hex); // "#ff0000"
console.log(red.rgb); // { r: 255, g: 0, b: 0, a: 1 }

Checkboard Utilities

Functions for generating transparent background checkboard patterns used to visualize alpha transparency in color pickers.

render

Renders a checkboard pattern to a canvas and returns a data URL representation.

/**
 * Renders checkboard pattern to canvas
 * @param c1 - First color (typically white)
 * @param c2 - Second color (typically light gray)  
 * @param size - Size of each checkboard square in pixels
 * @param serverCanvas - Optional server-side canvas implementation
 * @returns Data URL string of the checkboard pattern
 */
function render(c1: string, c2: string, size: number, serverCanvas?: any): string | null;

Usage Example:

import { render } from 'react-color/lib/helpers/checkboard';

const checkboardDataUrl = render('#ffffff', '#e6e6e6', 8);
// Returns: "data:image/png;base64,..." (base64 encoded checkboard pattern)

get

Gets a cached checkboard pattern or generates a new one if not cached.

/**
 * Gets cached checkboard pattern or generates new one
 * @param c1 - First color (typically white)
 * @param c2 - Second color (typically light gray)
 * @param size - Size of each checkboard square in pixels
 * @param serverCanvas - Optional server-side canvas implementation
 * @returns Cached data URL string of the checkboard pattern
 */
function get(c1: string, c2: string, size: number, serverCanvas?: any): string | null;

Usage Example:

import { get } from 'react-color/lib/helpers/checkboard';

// First call generates and caches the pattern
const pattern1 = get('#ffffff', '#e6e6e6', 8);
// Subsequent calls with same parameters return cached result
const pattern2 = get('#ffffff', '#e6e6e6', 8); // Same as pattern1 (cached)

Helper Usage Patterns

Validating User Input

import { isValidHex, simpleCheckForValidColor } from 'react-color/lib/helpers/color';

function handleColorInput(userInput) {
  // Check if it's a valid hex string
  if (typeof userInput === 'string' && isValidHex(userInput)) {
    return { hex: userInput };
  }
  
  // Check if it's valid color data object
  const validatedColor = simpleCheckForValidColor(userInput);
  if (validatedColor) {
    return validatedColor;
  }
  
  // Invalid input
  return null;
}

Converting Between Formats

import { toState } from 'react-color/lib/helpers/color';

function convertColor(input, outputFormat) {
  const colorState = toState(input);
  
  switch (outputFormat) {
    case 'hex':
      return colorState.hex;
    case 'rgb':
      return `rgb(${colorState.rgb.r}, ${colorState.rgb.g}, ${colorState.rgb.b})`;
    case 'hsl':
      return `hsl(${Math.round(colorState.hsl.h)}, ${Math.round(colorState.hsl.s * 100)}%, ${Math.round(colorState.hsl.l * 100)}%)`;
    default:
      return colorState;
  }
}

Accessible Color Combinations

import { getContrastingColor, toState } from 'react-color/lib/helpers/color';

function createAccessiblePair(backgroundColor) {
  const bgState = toState(backgroundColor);
  const textColor = getContrastingColor(bgState);
  
  return {
    backgroundColor: bgState.hex,
    color: textColor,
    // These colors provide sufficient contrast for accessibility
  };
}

Type Definitions

interface ColorData {
  hex?: string;
  r?: number;
  g?: number;
  b?: number;
  a?: number;
  h?: number;
  s?: number | string;
  l?: number | string;
  v?: number;
  source?: string;
}

interface ColorState {
  hsl: { h: number; s: number; l: number; a: number };
  hex: string;
  rgb: { r: number; g: number; b: number; a: number };
  hsv: { h: number; s: number; v: number; a: number };
  oldHue: number;
  source?: string;
}

Install with Tessl CLI

npx tessl i tessl/npm-react-color

docs

building-blocks.md

color-pickers.md

color-utilities.md

index.md

tile.json