### Start Development Demo Source: https://github.com/bityoungjae/okhash/blob/main/AGENTS.md Starts the local development demo server using demo/vite.config.ts. ```bash npm run demo:dev ``` -------------------------------- ### Install okhash Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/quick-start.md Install the okhash package using npm. Requires Node 22.22.1+. ```sh npm i okhash ``` -------------------------------- ### ColorHash Configuration Examples Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/types.md Demonstrates various ways to configure the createColorHash function using different ChannelSpec and ChromaSpec configurations. ```typescript import { createColorHash } from "okhash"; // Constant lightness createColorHash({ lightness: 0.7 }); // Discrete hue choices createColorHash({ hue: [30, 200, 320] }); // Continuous range createColorHash({ lightness: { min: 0.6, max: 0.75 } }); // Multiple ranges (hue wrapping) createColorHash({ hue: [{ min: 330, max: 30 }, { min: 200, max: 260 }], }); ``` ```typescript const colorize = createColorHash({ lightness: { min: 0.55, max: 0.75 }, hue: [ { min: 0, max: 60 }, { min: 200, max: 280 }, ], }); ``` ```typescript createColorHash({ chroma: { min: 0.08, max: "safe" }, // automatic gamut cap per hue/lightness }); createColorHash({ chroma: { mode: "uniform", range: { min: 0.05, max: 0.15 } }, // explicit ceiling }); ``` ```typescript // Uniform chroma, 8–safe createColorHash({ chroma: { min: 0.08, max: "safe" } }); // Relative chroma, 70–90% of gamut per hue createColorHash({ chroma: { mode: "relative", range: { min: 0.7, max: 0.9 } }, }); // Multiple ranges createColorHash({ chroma: [ { min: 0.05, max: 0.08 }, { min: 0.15, max: 0.2 }, ], }); ``` -------------------------------- ### Measuring Metrics Source: https://github.com/bityoungjae/okhash/blob/main/README.md Command to measure package metrics, including distribution, gamut, and example outputs. ```shell node tools/measure-metrics.mjs # distribution, gamut, size, example outputs ``` -------------------------------- ### Install Dependencies Source: https://github.com/bityoungjae/okhash/blob/main/AGENTS.md Installs project dependencies using npm ci. Requires Node.js version 22.2.1 or higher. ```bash npm ci ``` -------------------------------- ### Create Color Hash Instance with Options Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/types.md Example of creating a color hash function with custom options, including mood, seed, normalization, and cache size. This demonstrates how to initialize the color hashing process with specific configurations. ```typescript import { createColorHash } from "okhash"; const colorize = createColorHash({ mood: "vibrant", seed: 0xc0ffee, normalize: "NFC", cache: 512, }); colorize.hex("Alice"); // "#6a60db" ``` -------------------------------- ### Foreground Color Selection Examples Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/types.md Demonstrates various ways to use the Color.foreground() method with different ForegroundOptions, including default behavior, WCAG 2 compliance, custom candidates, and custom ranking functions. ```typescript const color = hashColor("Alice"); // Default: black or white, by OKLab lightness color.foreground(); // "#000000" or "#ffffff" // WCAG 2 compliance color.foreground({ metric: "wcag2" }); // Custom candidates color.foreground({ candidates: ["#1a1a1a", "#e8e8e8", "#888888"], }); // Custom ranking (e.g., with external APCA library) import { contrast as apca } from "apca-w3"; color.foreground({ rank: apca, }); ``` -------------------------------- ### Instantiate ColorHashFn with Custom Options and Use Main Call Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Create a ColorHashFn instance with custom cache size and seed, then use its main call to get a full Color object. ```typescript import { createColorHash } from "okhash"; const colorize = createColorHash({ mood: "balanced", seed: 0x12345678, cache: 512, }); // Use the main call for full Color object const bgColor = colorize("background"); const fgColor = bgColor.foreground(); ``` -------------------------------- ### Create Color Hash with Jewel Mood Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/types.md Example of creating a color hash instance using the 'jewel' mood preset. This results in deeper, richer tones. ```typescript createColorHash({ mood: "jewel" }).hex("brand"); // deeper tone ``` -------------------------------- ### Create Color Hash with Pastel Mood Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/types.md Example of creating a color hash instance using the 'pastel' mood preset. This results in softer, lighter colors. ```typescript createColorHash({ mood: "pastel" }).hex("design"); // "#e1bbc6" ``` -------------------------------- ### Use Module Singleton hashColor for OKLCH Format Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Get the OKLCH color representation using the pre-configured hashColor singleton. ```typescript import { hashColor } from "okhash"; hashColor.oklch("Carol"); // { l: 0.696651, c: 0.082351, h: 296.496 } ``` -------------------------------- ### Import and Use okhash in Browser via CDN Source: https://github.com/bityoungjae/okhash/blob/main/README.md Import okhash directly from an ESM CDN in HTML for projects without a build step. This example shows how to set a CSS variable with the generated color. ```html ``` -------------------------------- ### Use Module Singleton hashColor for CSS Format Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Get the CSS string representation of a color using the pre-configured hashColor singleton. ```typescript import { hashColor } from "okhash"; hashColor.css("Dave"); // "oklch(0.696651 0.082351 296.496)" ``` -------------------------------- ### Use Pre-constructed Hash Color Function Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/API-SURFACE.md Shows how to use the pre-constructed `hashColor` function to get hex color codes and RGB values for input strings. ```typescript hashColor.hex("Alice"); // "#a293cb" hashColor("Bob").rgb(); // [162, 147, 203] ``` -------------------------------- ### Use Module Singleton hashColor for Hex Format Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Get the hex representation of a color using the pre-configured hashColor singleton. ```typescript import { hashColor } from "okhash"; hashColor.hex("Alice"); // "#a293cb" ``` -------------------------------- ### Getting Readable Foreground Color Source: https://github.com/bityoungjae/okhash/blob/main/README.md Demonstrates how to use the foreground() method to pick a readable text color for a given background color. Supports custom metrics and candidate sets. ```typescript const c = hashColor("Alice Park"); c.foreground(); // "#000000" — default metric, perceptual lightness difference c.foreground({ preset: "natural" }); // readable but less stark than pure black/white c.foreground({ metric: "wcag2" }); // WCAG 2 contrast ratio, for compliance contexts c.foreground({ candidates: ["#1a1a1a", "#f5f5f5"] }); // your own candidate set c.foreground({ rank: myApcaRanker }); // plug in any contrast function ``` -------------------------------- ### Color Object Methods Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/palette-api.md Demonstrates common methods available on Color objects returned by palette functions, such as getting hex, RGB, or OKLCH values. ```typescript const colors = paletteFrom("seed", 3); colors[0].hex(); // "#" colors[0].rgb(); // [r, g, b] colors[0].oklch(); // { l, c, h } colors[0].css(); // "oklch(...)" colors[0].foreground(); // "#000000" or "#ffffff" colors[0].variant("dark"); // Color adjusted for dark surface ``` -------------------------------- ### Generate Hex and CSS Colors from String Source: https://github.com/bityoungjae/okhash/blob/main/README.md Import and use the hashColor singleton to generate hex or CSS OKLCH color strings from an input string. This is a quick way to get a color without custom configuration. ```typescript import { hashColor } from "okhash"; hashColor.hex("Alice"); // "#a293cb" hashColor.css("Alice"); // "oklch(0.696651 0.082351 296.496)" ``` -------------------------------- ### Get Readable Foreground Color Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/quick-start.md Get a readable foreground color (black or white by default) for any background color, with options for WCAG 2 compliance or custom candidates. ```ts import { hashColor } from "okhash"; const bgColor = hashColor("background"); // Default: black or white bgColor.foreground(); // "#000000" or "#ffffff" // WCAG 2 compliance bgColor.foreground({ metric: "wcag2" }); // Custom candidates bgColor.foreground({ candidates: ["#1a1a1a", "#e8e8e8"], }); ``` -------------------------------- ### Building the Package Source: https://github.com/bityoungjae/okhash/blob/main/README.md Command to build the okhash package. ```shell npm run build # build the package ``` -------------------------------- ### Instantiate ColorHashFn with Custom Options and Use Shortcuts Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Create a ColorHashFn instance with custom cache size and seed, then use its shortcuts for direct format retrieval. ```typescript import { createColorHash } from "okhash"; const colorize = createColorHash({ mood: "balanced", seed: 0x12345678, cache: 512, }); // Use shortcuts when only one format is needed const hexValue = colorize.hex("background"); const cssValue = colorize.css("background"); ``` -------------------------------- ### Get RGB Color from Color Object Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Retrieve the RGB triplet representation of a color from a Color object. ```typescript const color = hashColor("Alice"); const [r, g, b] = color.rgb(); // [162, 147, 203] ``` -------------------------------- ### Core Module Exports Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/exports-summary.md The main entry point for the Okhash library provides functions to create color hash instances and a pre-configured instance. ```APIDOC ## createColorHash ### Description Factory function to create a configured color hash instance. ### Signature `(options?: OkhashOptions) => ColorHashFn` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **options** (`OkhashOptions`) - Optional - Configuration object for the color hash instance. ### Returns * **ColorHashFn** - A function that generates colors based on input strings. ### Example ```ts import { createColorHash } from "okhash"; const myHasher = createColorHash({ hue: [0, 360], lightness: [0.5, 0.7], }); const color = myHasher("my input string"); ``` ``` ```APIDOC ## hashColor ### Description Pre-configured instance with default options for color hashing. ### Signature `ColorHashFn` ### Parameters None ### Returns * **ColorHashFn** - A function that generates colors based on input strings using default configurations. ### Example ```ts import { hashColor } from "okhash"; const color = hashColor("another input string"); ``` ``` -------------------------------- ### Get Hex Color from Color Object Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Retrieve the hex string representation of a color from a Color object. ```typescript const color = hashColor("Alice"); color.hex(); // "#a293cb" ``` -------------------------------- ### Core Entry Point - hashColor Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/index.md Provides a pre-configured instance for hashing strings to colors using default options. The output is directly available in hex format. ```APIDOC ## Core Entry Point - hashColor ### Description Provides a pre-configured instance for hashing strings to colors using default options. The output is directly available in hex format. ### Method `hashColor.hex(input: string): string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { hashColor } from "okhash"; hashColor.hex("Alice"); ``` ### Response #### Success Response (string) - Returns a hex color string. #### Response Example ```json "#a293cb" ``` ``` -------------------------------- ### Full Configuration Options for okhash Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/00-START-HERE.md Illustrates the extensive configuration options available when creating a ColorHash instance, including mood, hue, lightness, chroma, HK correction, surface, CVD safety, seed, normalization, and cache settings. ```typescript createColorHash({ mood: "balanced", // "balanced" | "pastel" | "vibrant" | "jewel" | "earth" | "neon" hue: { min: 0, max: 360 }, // override mood hue lightness: 0.65, // override mood lightness chroma: { min: 0.08, max: "safe" }, // override mood chroma hk: true, // Helmholtz-Kohlrausch correction surface: "light", // "light" | "dark" cvdSafe: false, // color-vision-deficiency safe seed: 0xdeadbeef, // 32-bit seed normalize: false, // "NFC" | false cache: 256, // FIFO cache size }); ``` -------------------------------- ### Get Maximum Chroma for OKLCH Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/internal-modules.md Calculates the maximum sRGB-safe chroma for a given lightness and hue, defining the gamut boundary. ```typescript function maxChromaForLightnessHue(lightness: number, hue: number): number ``` -------------------------------- ### Basic Usage of okhash Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/00-START-HERE.md Demonstrates the basic usage of the okhash library for generating hex color codes from strings using both a pre-built instance and a custom-configured instance. ```typescript import { createColorHash, hashColor } from "okhash"; // Pre-built instance with defaults hashColor.hex("Alice"); // "#a293cb" // Custom instance const vibrant = createColorHash({ mood: "vibrant" }); vibrant.hex("Bob"); // "#6a60db" ``` -------------------------------- ### resolveOkhashConfig Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/internal-modules.md Main entry point for configuration. Returns a config object with pre-built sampler functions and validated settings. ```APIDOC ## resolveOkhashConfig ### Description Main entry point for configuration. Returns a config object with pre-built sampler functions and validated settings. ### Function Signature ```ts function resolveOkhashConfig(options?: OkhashOptions): ResolvedOkhashConfig ``` ### Returns ```ts interface ResolvedOkhashConfig { hue: Sampler; // (t: number) => number lightness: Sampler; chroma: ChromaSampler; // (t: number, lightness: number, hue: number) => number seed: number; normalize: "NFC" | false; cacheSize: number; hk: boolean; surface: "light" | "dark"; } ``` ### Implementation Details 1. Resolves mood preset or uses provided specs 2. Builds samplers for hue, lightness, and chroma 3. Validates all values and ranges 4. Throws at construction if invalid ``` -------------------------------- ### Use Module Singleton hashColor for RGB Format Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Get the RGB triplet of a color using the pre-configured hashColor singleton. ```typescript import { hashColor } from "okhash"; hashColor.rgb("Bob"); // [162, 147, 203] ``` -------------------------------- ### Core Entry Point - createColorHash Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/index.md Allows creating a custom color hashing instance with configurable options such as mood and seed. The returned instance provides methods to generate colors in various formats. ```APIDOC ## Core Entry Point - createColorHash ### Description Allows creating a custom color hashing instance with configurable options such as mood and seed. The returned instance provides methods to generate colors in various formats. ### Method `createColorHash(options: { mood?: 'vibrant' | 'muted'; seed?: number }): (input: string) => ColorObject` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { createColorHash } from "okhash"; const colorize = createColorHash({ mood: "vibrant", seed: 0xc0ffee }); colorize("user@acme.io").hex(); ``` ### Response #### Success Response (ColorObject) - Returns an object with methods to format the color (e.g., `hex()`, `rgb()`, `oklch()`, `css()`). #### Response Example ```json { "hex": () => "#6a60db", "rgb": () => "rgb(106, 96, 219)", "oklch": () => "oklch(0.56 0.38 274)", "css": () => "#6a60db" } ``` ``` -------------------------------- ### Document Map Structure Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/00-START-HERE.md Visual representation of the okhash documentation structure, showing the main 'Start Here' file and its relationship to other documentation sections. ```text 00-START-HERE.md ← You are here ├─ Quick Start (new users) ├─ API Surface (complete index) ├─ Core API (main functions) ├─ Palette API (paletteFrom, distinctAssign) ├─ Types (type definitions) ├─ Configuration (all options) ├─ Errors (error catalog) ├─ Exports Summary (what you can import) ├─ Internal Modules (how it works) ├─ Index (overview) └─ README.md (documentation guide) ``` -------------------------------- ### Format Code Source: https://github.com/bityoungjae/okhash/blob/main/AGENTS.md Formats the codebase using oxfmt. Ignores the demo/ directory. ```bash npm run format ``` -------------------------------- ### Distinct Assignment Example Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/palette-api.md Assigns distinct colors to a list of keys using specified options, including mood, threshold, and seed. ```typescript import { distinctAssign } from "okhash/palette"; const colors = distinctAssign(["a", "b", "c"], { mood: "vibrant", threshold: 0.12, seed: 0xdeadbeef, }); ``` -------------------------------- ### hashColor Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md A pre-configured instance with default `OkhashOptions`, exported as a module singleton. Provides direct access to color hashing methods. ```APIDOC ## hashColor ### Description Pre-configured instance with default `OkhashOptions`, exported as a module singleton. ### Signature ```ts const hashColor: ColorHashFn ``` ### Methods All methods are shortcuts that bypass Color object allocation when only one format is needed. | Method | Signature | Returns | |--------|-----------|---------| | `hashColor(input)` | `(input: string) => Color` | Color object with all format methods | | `hashColor.hex(input)` | `(input: string) => string` | Hex string `"#rrggbb"` | | `hashColor.rgb(input)` | `(input: string) => Rgb` | Readonly `[r, g, b]` tuple, 0–255 | | `hashColor.oklch(input)` | `(input: string) => Oklch` | `{ l, c, h }` in OKLCH space | | `hashColor.css(input)` | `(input: string) => string` | CSS string `"oklch(0.696651 0.082351 296.496)"` | ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { hashColor } from "okhash"; hashColor.hex("Alice"); // "#a293cb" hashColor.rgb("Bob"); // [162, 147, 203] hashColor.oklch("Carol"); // { l: 0.696651, c: 0.082351, h: 296.496 } hashColor.css("Dave"); // "oklch(0.696651 0.082351 296.496)" // Full Color object with lazy format computation const color = hashColor("Eve"); color.hex(); // cached, same as hashColor.hex("Eve") color.variant("dark").hex(); // dark surface variant color.foreground(); // "#000000" or "#ffffff" ``` ### Response #### Success Response (200) Depends on the method called. Returns a `Color` object or a string/tuple representation of the color. #### Response Example See Request Example. ``` -------------------------------- ### Importing okhash Components Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/00-START-HERE.md Shows how to import the main ColorHash functions and types from the 'okhash' package, as well as palette-specific functions and types from 'okhash/palette'. ```typescript // Main entry import { createColorHash, hashColor, type Color, type OkhashOptions } from "okhash"; // Palette entry import { paletteFrom, distinctAssign, type DistinctOptions } from "okhash/palette"; ``` -------------------------------- ### Get Maximum Safe Chroma in Lightness Range Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/internal-modules.md Determines the maximum chroma any hue can safely reach within a specified range of lightness values. ```typescript function maxSafeChromaInLightnessRange(min: number, max: number): number ``` -------------------------------- ### Core API Reference Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/README.md Provides details on the main factory function, singleton instance, callable interface, and the return type with its associated methods for generating colors from strings. ```APIDOC ## Core API Reference This section details the primary functions and types for generating colors from strings using the okhash library. ### `createColorHash()` - **Description**: A factory function that creates and returns a new `ColorHashFn` instance. - **Usage**: Use this function to get a fresh instance of the color hashing function, especially if you need to manage multiple independent hashers. ### `hashColor` - **Description**: A singleton instance of `ColorHashFn` that is pre-configured and ready for immediate use. - **Usage**: This is the most common way to generate colors; simply call `hashColor()` with a string. ### `ColorHashFn` - **Description**: The callable interface representing the color hashing function. It takes a string as input and returns a `Color` object. - **Signature**: `(input: string, options?: OkhashOptions) => Color` ### `Color` Object - **Description**: The return type from `hashColor` or `createColorHash`. It represents a generated color and provides methods to access its representation in various formats. - **Methods**: - `hex()`: Returns the color in hexadecimal format. - `rgb()`: Returns the color in RGB format. - `oklch()`: Returns the color in OKLCH format. - `css()`: Returns the color in CSS format. - `foreground()`: Returns a contrasting foreground color (e.g., black or white). - `variant()`: Returns a slightly modified variant of the color. ``` -------------------------------- ### Get Maximum Safe Chroma for Lightness Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/internal-modules.md Returns the maximum chroma achievable across all hues at a specific lightness, utilizing a lookup table for efficiency. ```typescript function safeChromaForLightness(lightness: number): number ``` -------------------------------- ### Create ColorHash with Default Options Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Instantiate ColorHashFn with default settings for general use. ```typescript import { createColorHash } from "okhash"; // Default options const colorize = createColorHash(); colorize("Alice"); // Color ``` -------------------------------- ### Palette Module Exports Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/exports-summary.md The palette entry point provides functions for generating color palettes and assigning distinct colors to keys. ```APIDOC ## paletteFrom ### Description Generate N colors spaced by the golden angle. ### Signature `(seed: string, n: number, options?: OkhashOptions) => Color[]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **seed** (`string`) - Required - The seed string to generate the palette from. * **n** (`number`) - Required - The number of colors to generate. * **options** (`OkhashOptions`) - Optional - Configuration options for color generation. ### Returns * **Color[]** - An array of generated Color objects. ### Example ```ts import { paletteFrom } from "okhash/palette"; const colors = paletteFrom("my project", 5); ``` ``` ```APIDOC ## distinctAssign ### Description Assign colors to keys with collision avoidance. ### Signature `(keys: readonly string[], options?: DistinctOptions) => Map` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **keys** (`readonly string[]`) - Required - An array of keys to assign colors to. * **options** (`DistinctOptions`) - Optional - Configuration options for distinct color assignment. ### Returns * **Map** - A map where keys are the input strings and values are the assigned Color objects. ### Example ```ts import { distinctAssign } from "okhash/palette"; const assignments = distinctAssign(["user1", "user2", "user3"]); ``` ``` -------------------------------- ### Get OKLCH Color Representation Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Retrieve the canonical OKLCH coordinates of a color. This is useful for understanding the color's properties in a perceptually uniform color space. ```typescript const color = hashColor("Alice"); const oklch = color.oklch(); // { l: 0.696651, c: 0.082351, h: 296.496 } ``` -------------------------------- ### Import Core Okhash Functions, Constants, and Types Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/exports-summary.md Import core functionalities along with necessary types for configuration and color representation. ```ts import { createColorHash, hashColor, type Color, type OkhashOptions, type Mood, } from "okhash"; ``` -------------------------------- ### Generate Pastel Color Source: https://github.com/bityoungjae/okhash/blob/main/README.md Example of creating a color hash with the 'pastel' mood and then converting it to a hex string. Pastels are characterized by high lightness and low chroma. ```typescript createColorHash({ mood: "pastel" }).hex("design"); // "#e1bbc6" ``` -------------------------------- ### Configure Color Hashing with OkhashOptions Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/types.md Configuration object for creating a color hash instance. Allows customization of mood, hue, lightness, chroma, and other hashing parameters. Use this to tailor the color generation to specific aesthetic needs. ```typescript interface OkhashOptions { mood?: Mood; hue?: ChannelSpec; lightness?: ChannelSpec; chroma?: ChromaSpec | { mode: "uniform" | "relative"; range: ChromaSpec }; hk?: boolean; surface?: "light" | "dark"; cvdSafe?: boolean; seed?: number; normalize?: "NFC" | false; cache?: number; } ``` -------------------------------- ### colorFromInput / rgbFromInput / hexFromInput / oklchFromInput / cssFromInput Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/internal-modules.md High-level entry points that combine hashing, sampling, OKLCH generation, and format projection in a single call. ```APIDOC ## Color Generation Entry Points ### Description High-level entry points that combine hashing, sampling, OKLCH generation, and format projection in a single call. ### Functions - `colorFromInput(input: string, config: ResolvedOkhashConfig): Color` - `rgbFromInput(input: string, config: ResolvedOkhashConfig): Rgb` - `hexFromInput(input: string, config: ResolvedOkhashConfig): string` - `oklchFromInput(input: string, config: ResolvedOkhashConfig): Oklch` - `cssFromInput(input: string, config: ResolvedOkhashConfig): string` ``` -------------------------------- ### Core API Imports Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/API-SURFACE.md Import core functions and types from the 'okhash' package. Use 'createColorHash' and 'hashColor' for hashing, and import relevant types for configuration and color representation. ```typescript // Core import { createColorHash, hashColor } from "okhash"; import type { Color, ColorHashFn, OkhashOptions, Mood, /* ... */ } from "okhash"; ``` -------------------------------- ### Generate Hex Color from String (Default) Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/index.md Use the pre-configured hashColor instance to generate a hex color string from an input string. This is the simplest way to get a deterministic color. ```typescript import { createColorHash, hashColor } from "okhash"; // Pre-configured instance with default options hashColor.hex("Alice"); // "#a293cb" ``` -------------------------------- ### Import Palette Module Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/README.md Import the necessary functions from the okhash/palette module. This is the entry point for using the palette generation features. ```typescript import { paletteFrom, distinctAssign, type DistinctOptions } from "okhash/palette"; ``` -------------------------------- ### Run Browser Tests Source: https://github.com/bityoungjae/okhash/blob/main/AGENTS.md Builds the package and runs Playwright browser tests. ```bash npm run test:browser ``` -------------------------------- ### Import Core okhash Functions and Types Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/README.md Import the necessary functions and types for using the okhash library in your project. This includes the factory function for creating color hashes, a singleton instance, and type definitions for options and return values. ```typescript import { createColorHash, hashColor, type Color, type OkhashOptions } from "okhash"; ``` -------------------------------- ### Create Color Hash with Custom Configuration Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/quick-start.md Create a color hash instance with custom configuration options like mood, seed, and cache size. ```ts import { createColorHash } from "okhash"; const colorize = createColorHash({ mood: "vibrant", seed: 0xdeadbeef, cache: 512, }); colorize.hex("user@example.com"); // consistent per app seed ``` -------------------------------- ### Assign Distinct Colors to Keys Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/API-SURFACE.md Use `distinctAssign` to create a map where keys are assigned unique colors. This is useful for consistent color allocation in UIs. Access the hex value of an assigned color using the map's `get` method. ```typescript const colors = distinctAssign(["frontend", "backend", "data"]); colors.get("frontend")?.hex(); // "#c8a447" ``` -------------------------------- ### package.json Exports Configuration Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/exports-summary.md Defines the main entry point, type declarations, and export conditions for different module systems (import/require). This configuration ensures compatibility with various environments and bundlers. ```json { "main": "./dist/index.mjs", "types": "./dist/index.d.mts", "exports": { ".": { "types": "./dist/index.d.mts", "import": "./dist/index.mjs", "require": "./dist/index.mjs" }, "./palette": { "types": "./dist/palette/index.d.mts", "import": "./dist/palette/index.mjs", "require": "./dist/palette/index.mjs" } } } ``` -------------------------------- ### Color Object Methods Source: https://github.com/bityoungjae/okhash/blob/main/README.md The Color object provides several methods to access and transform color representations. These include getting hex, RGB, OKLCH, and CSS string formats, as well as determining readable foreground colors and generating variants for different surfaces. ```APIDOC ## Color Object Methods ### Description Provides methods to interact with a generated color object. ### Methods - `hex()`: Returns the color in hexadecimal format (e.g., "#a293cb"). - `rgb()`: Returns the color as a readonly tuple of RGB values (e.g., `[162, 147, 203]`). - `oklch()`: Returns an object with the OKLCH coordinates (l, c, h). - `css()`: Returns the color in CSS OKLCH format (e.g., "oklch(0.696651 0.082351 296.496)"). - `foreground(options?: ForegroundOptions)`: Picks a readable text color for the background. Options include `preset`, `metric`, `candidates`, and `rank`. - `variant(surface: "light" | "dark")`: Returns the color adjusted for a specified surface (e.g., "dark"). ``` -------------------------------- ### Resolve Okhash Configuration Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/internal-modules.md Main entry point for configuration. Returns a config object with pre-built sampler functions and validated settings. ```typescript function resolveOkhashConfig(options?: OkhashOptions): ResolvedOkhashConfig ``` -------------------------------- ### OkhashOptions Interface Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/API-SURFACE.md Defines the configuration options available when creating a color hash function using `createColorHash`. ```APIDOC ## OkhashOptions Interface ### Description The `OkhashOptions` interface allows customization of the color hashing process when calling `createColorHash`. Options include mood, hue, lightness, chroma, gamut correction, surface variants, color blindness safety, seed, Unicode normalization, and cache size. ### Fields - **mood** (`Mood`): Affects the default hue, lightness, and chroma. Possible values: `"balanced"`, `"pastel"`, `"vibrant"`, `"jewel"`, `"earth"`, `"neon"`. Defaults to `"balanced"`. - **hue** (`ChannelSpec`): Overrides the hue derived from the mood. - **lightness** (`ChannelSpec`): Overrides the lightness derived from the mood. - **chroma** (`ChromaSpec | { mode: "uniform" | "relative"; range: ChromaSpec }`): Overrides the chroma. Can specify a mode and range. - **hk** (`boolean`): Enables Helmholtz-Kohlrausch correction for perceived brightness. Defaults to `false`. - **surface** (`"light" | "dark"`): Applies a color variant suitable for a light or dark background surface. Defaults to `"light"`. - **cvdSafe** (`boolean`): Ensures the generated colors are safe for color-vision deficiency. Defaults to `false`. - **seed** (`number`): A 32-bit unsigned integer used to seed the random number generator for consistent hashing. Defaults to `0`. - **normalize** (`"NFC" | false`): Specifies Unicode normalization form for input strings. Defaults to `false`. - **cache** (`number`): The size of the FIFO cache for storing previously generated hashes. Defaults to `256`. ### Defaults - `mood`: `"balanced"` - `surface`: `"light"` - `cvdSafe`: `false` - `seed`: `0` - `normalize`: `false` - `cache`: `256` - `hue`, `lightness`, `chroma`, `hk`: derived from mood ``` -------------------------------- ### Verify Package Exports Source: https://github.com/bityoungjae/okhash/blob/main/AGENTS.md Builds the package and verifies its exports and types. ```bash npm run test:exports ``` -------------------------------- ### Import Core Okhash Functions and Constants Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/exports-summary.md Import the primary factory function and the pre-configured singleton instance from the core 'okhash' package. ```ts import { createColorHash, hashColor } from "okhash"; ``` -------------------------------- ### Check Runtime Compatibility Source: https://github.com/bityoungjae/okhash/blob/main/AGENTS.md Runs smoke tests to ensure runtime compatibility. ```bash npm run test:runtime ``` -------------------------------- ### Run Full Check Source: https://github.com/bityoungjae/okhash/blob/main/AGENTS.md Executes format checks, linting, type checking, and Vitest unit tests. ```bash npm run check ``` -------------------------------- ### Create and Use Color Hash Function Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/API-SURFACE.md Demonstrates how to create a color hashing function with custom options and then use it to generate hex color codes for input strings. ```typescript const colorize = createColorHash({ mood: "vibrant", seed: 0x12345678 }); colorize.hex("Alice"); // "#6a60db" ``` -------------------------------- ### Import Palette Module Functions Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/exports-summary.md Import the functions for generating color palettes and assigning distinct colors from the 'okhash/palette' module. ```ts import { paletteFrom, distinctAssign } from "okhash/palette"; ``` -------------------------------- ### Create Color Hash with Custom Channels Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/quick-start.md Create a color hash instance with custom hue, lightness, and chroma settings for brand-specific colors. ```ts import { createColorHash } from "okhash"; // Brand colors: blues only const brand = createColorHash({ hue: [{ min: 200, max: 260 }], lightness: { min: 0.62, max: 0.7 }, chroma: { mode: "relative", range: { min: 0.7, max: 0.9 } }, }); brand.hex("primary"); // blue hue, punchy brand.hex("accent"); // another blue, different ``` -------------------------------- ### Generate Colors with Default and Custom Options Source: https://github.com/bityoungjae/okhash/blob/main/README.md Use the default hashColor singleton for quick color generation or create a custom instance with createColorHash for specific moods or seeds. This allows for fine-tuning color generation. ```typescript import { createColorHash, hashColor } from "okhash"; // Module singleton with default options. hashColor.hex("Alice"); // "#a293cb" hashColor.rgb("Alice"); // [162, 147, 203] hashColor.oklch("Alice"); // { l: 0.696651…, c: 0.082351…, h: 296.496… } hashColor.css("Alice"); // "oklch(0.696651 0.082351 296.496)" // A configured instance. const colorize = createColorHash({ mood: "vibrant", seed: 0xc0ffee }); const color = colorize("user@acme.io"); color.hex(); // "#6a60db" color.foreground(); // "#000000" or "#ffffff", whichever reads better color.foreground({ preset: "natural" }); // softer readable text color color.variant("dark"); // same identity, tuned for a dark surface ``` -------------------------------- ### Run Unit Tests Source: https://github.com/bityoungjae/okhash/blob/main/AGENTS.md Executes all unit tests located in the test/ directory using Vitest. ```bash npm run test ``` -------------------------------- ### Create Default Color Hash Instance Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/configuration.md Creates a color hash instance using the default 'balanced' mood configuration. This is the simplest way to initialize the library for general use. ```typescript import { createColorHash } from "okhash"; const colorize = createColorHash(); ``` -------------------------------- ### chooseForeground Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/internal-modules.md Selects the best candidate foreground color based on a ranking metric. ```APIDOC ## chooseForeground ### Description Selects the best candidate foreground color based on a ranking metric. ### Function Signature ```ts function chooseForeground(background: Rgb, options?: ForegroundOptions): string ``` ### Ranking Metrics - `"auto"` (default): OKLab lightness difference `|L_bg - L_cand|` - `"wcag2"`: WCAG 2.0 contrast ratio `(L + 0.05) / (d + 0.05)` - Custom `rank` function: user-provided ``` -------------------------------- ### Import Core Palette Functions Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/palette-api.md Imports the main palette functions `paletteFrom` and `distinctAssign` from the 'okhash/palette' module. ```typescript // Core palette functions import { paletteFrom, distinctAssign } from "okhash/palette"; ``` -------------------------------- ### Import Palette Module Functions and Types Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/exports-summary.md Import palette generation functions and specific types from the 'okhash/palette' module, including the core 'Color' type. ```ts import { paletteFrom, distinctAssign, type DistinctOptions, } from "okhash/palette"; // Color type is re-imported from core import type { Color } from "okhash"; ``` -------------------------------- ### Deterministic Output with Same Input Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Demonstrates that using the same input string with a ColorHashFn instance always produces the same output. ```typescript import { createColorHash } from "okhash"; const colorize = createColorHash({ mood: "balanced", seed: 0x12345678, cache: 512, }); // Same input, same output (deterministic) colorize.hex("same") === colorize.hex("same"); // true ``` -------------------------------- ### Migrate uniqolor Format, Saturation, and Lightness to okhash Source: https://github.com/bityoungjae/okhash/blob/main/MIGRATION.md Adapt uniqolor's format, saturation, and lightness options to okhash's method calls and OKLCH chroma/lightness ranges. ```typescript // Before uniqolor("acme", { format: "rgb", saturation: [35, 70], lightness: 25 }); // After: saturation (0-100) becomes chroma (OKLCH), lightness becomes 0-1 const c = createColorHash({ chroma: { min: 0.04, max: 0.09 }, lightness: 0.45, })("acme"); c.rgb(); ``` -------------------------------- ### Chroma Modes: Uniform vs. Relative Source: https://github.com/bityoungjae/okhash/blob/main/README.md Demonstrates setting absolute chroma ranges (uniform) and relative chroma ranges. Uniform mode aims for evenness across hues, while relative mode allows individual colors to reach their gamut ceiling. ```typescript createColorHash({ chroma: { min: 0.05, max: 0.1 } }); // uniform ``` ```typescript createColorHash({ chroma: { mode: "relative", range: { min: 0.7, max: 0.95 } } }); ``` -------------------------------- ### Create ColorHash with Custom Channel Specs Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Instantiate ColorHashFn with specific hue, lightness, and chroma ranges for precise color control. ```typescript import { createColorHash } from "okhash"; // Custom channel specs const custom = createColorHash({ hue: [{ min: 200, max: 260 }], // brand blues only lightness: { min: 0.62, max: 0.7 }, chroma: { mode: "relative", range: { min: 0.7, max: 0.9 } }, }); custom.rgb("design"); // [162, 147, 203] ``` -------------------------------- ### Migrating string-to-color to okhash for hex color generation Source: https://github.com/bityoungjae/okhash/blob/main/MIGRATION.md Before: Using 'string-to-color' to generate hex colors from various inputs. After: Using 'okhash' with JSON stringification for non-string inputs to achieve similar results. ```typescript // Before import stc from "string-to-color"; stc("string"); // "#7f1de4" stc(null); // "#1ad64b" ``` ```typescript // After import { hashColor } from "okhash"; hashColor.hex("string"); hashColor.hex(JSON.stringify(null)); // hashes the string "null" ``` -------------------------------- ### Create Color Hashes with Different Seeds Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/configuration.md Demonstrates how different seeds produce different color hashes for the same input string. Useful for isolating color generation logic for different applications or instances. ```typescript const app1 = createColorHash({ seed: 0x6d57d19d }); const app2 = createColorHash({ seed: 0xdeadbeef }); // Same input, different app seed = different colors app1.hex("Alice"); // "#a293cb" app2.hex("Alice"); // "#6a60db" (different) ``` -------------------------------- ### foreground() Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/core-api.md Picks a readable foreground color (text) for this background color from a list of candidates. It can use different contrast metrics or a custom ranking function. ```APIDOC ## foreground(options?: ForegroundOptions) ### Description Picks a readable foreground color (text) for this background. ### Parameters #### Parameters - **options** (`ForegroundOptions`) - Optional - See below #### Options (ForegroundOptions) | Option | Type | Default | Description | |---|---|---|---| | `candidates` | `readonly string[]` | `["#000000", "#ffffff"]` | Candidate colors to choose from, as 6-digit hex strings | | `metric` | `"auto" | "wcag2"` | ` ``` -------------------------------- ### Migrate ColorHash Instance to okhash Singleton Source: https://github.com/bityoungjae/okhash/blob/main/MIGRATION.md Replace ColorHash instance with the hashColor singleton for generating hex and RGB color values. ```typescript // Before import ColorHash from "color-hash"; const ch = new ColorHash(); ch.hex("Hello World"); // "#8796c5" ch.rgb("Hello World"); // [135, 150, 197] // After import { hashColor } from "okhash"; hashColor.hex("Alice"); // "#a293cb" hashColor.rgb("Alice"); // [162, 147, 203] ``` -------------------------------- ### Palette API Imports Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/API-SURFACE.md Import functions and types specifically for palette generation from the 'okhash/palette' submodule. Use 'paletteFrom' and 'distinctAssign' for palette creation. ```typescript // Palette import { paletteFrom, distinctAssign } from "okhash/palette"; import type { DistinctOptions } from "okhash/palette"; ``` -------------------------------- ### FifoCache Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/internal-modules.md Simple bounded FIFO cache for Color objects. ```APIDOC ## FifoCache ### Description Simple bounded FIFO cache for Color objects. ### Class Definition ```ts class FifoCache { constructor(limit: number); get(key: string): Value | undefined; set(key: string, value: Value): void; } ``` ### Behavior - FIFO eviction: When full, removes the oldest entry before inserting new - Size 0: Disables caching (set is a no-op) - Lookup: O(1) via Map - Insertion: O(1) average ``` -------------------------------- ### Migrate ColorHash Lightness and Saturation to okhash Chroma Source: https://github.com/bityoungjae/okhash/blob/main/MIGRATION.md Adapt ColorHash's lightness and saturation arrays to okhash's discrete choices or continuous ranges for lightness and chroma. ```typescript // Before new ColorHash({ lightness: [0.35, 0.5, 0.65], saturation: [0.35] }); // After: discrete choices, or a continuous range createColorHash({ lightness: [0.35, 0.5, 0.65], chroma: { min: 0.05, max: 0.08 }, }); ``` -------------------------------- ### Build Package Source: https://github.com/bityoungjae/okhash/blob/main/AGENTS.md Builds the TypeScript package into the dist/ directory using tsdown. ```bash npm run build ``` -------------------------------- ### Palette Entry Point - distinctAssign Source: https://github.com/bityoungjae/okhash/blob/main/_autodocs/index.md Assigns distinct colors to a list of input strings, employing collision avoidance mechanisms. ```APIDOC ## Palette Entry Point - distinctAssign ### Description Assigns distinct colors to a list of input strings, employing collision avoidance mechanisms. ### Method `distinctAssign(inputs: string[]): Map` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { distinctAssign } from "okhash/palette"; distinctAssign(["frontend", "infra", "design"]); ``` ### Response #### Success Response (Map) - Returns a Map where keys are the input strings and values are `Color` objects. #### Response Example ```json { "frontend": { "hex": () => "#...", ... }, "infra": { "hex": () => "#...", ... }, "design": { "hex": () => "#...", ... } } ``` ```