### Background Color Example Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Demonstrates how to apply background colors to text using picocolors. ```javascript console.log( pc.bgBlack( pc.white(`Tom appeared on the sidewalk with a bucket of whitewash and a long-handled brush.`) ) ) ``` -------------------------------- ### Check Color Support Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Provides an example of how to check if the current environment supports color output. ```javascript import pc from "picocolors" if (pc.isColorSupported) { console.log("Yay! This script can use colors and formatters") } ``` -------------------------------- ### Text Formatting Example Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Shows how to use formatting functions like bold and dim for text. ```javascript for (let task of tasks) { console.log(`${pc.bold(task.name)} ${pc.dim(task.durationMs + "ms")}`) } ``` -------------------------------- ### Red and Black Text Example Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Illustrates using different color functions to format text within a console log. ```javascript console.log(`I see a ${pc.red("red door")} and I want it painted ${pc.black("black")}`) ``` -------------------------------- ### Custom Formatter Creation Example Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/types.md Illustrates how to create a custom formatter function that adheres to the Formatter type, useful for pre-defined text styling. ```typescript import type { Formatter } from "picocolors" function createCustomFormatter(prefix: string, suffix: string): Formatter { return (input) => { return prefix + String(input) + suffix } } ``` -------------------------------- ### Nested Code Replacement Example Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Explains how picocolors transparently handles ANSI code replacement when nesting formatters, ensuring correct visual output by replacing inner close codes with outer open codes. ```javascript import pc from "picocolors" // When yellow's close code appears inside red's formatting const result = pc.red(`outer ${pc.yellow("inner")} outer`) // The inner yellow close code is automatically replaced with red's open code // so formatting continues correctly outside the yellow section ``` -------------------------------- ### Nested Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/README.md Combine multiple formatting functions to apply nested styles. For example, make text both bold and red. Ensure `picocolors` is imported as `pc`. ```javascript import pc from "picocolors" console.log(pc.bold(pc.red("important error"))) console.log(pc.bgWhite(pc.black("inverted"))) ``` -------------------------------- ### Special Number Value Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Examples of formatting special number values like 0, NaN, Infinity, and floating-point numbers using the `red` formatter. ```javascript import pc from "picocolors" console.log(pc.red(0)) // "0" in red console.log(pc.red(NaN)) // "NaN" in red console.log(pc.red(Infinity)) // "Infinity" in red console.log(pc.red(-Infinity)) // "-Infinity" in red console.log(pc.red(3.14)) // "3.14" in red ``` -------------------------------- ### Basic Coloring Usage Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Demonstrates how to use individual color functions like `red` and `green` to format console output. ```APIDOC ### Basic coloring ```javascript import pc from "picocolors" console.log(pc.red("Error message")) console.log(pc.green("Success message")) ``` ``` -------------------------------- ### File Structure Overview Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/README.md Provides a high-level overview of the picocolors project directory structure, including main entry points, type definitions, and test files. ```text picocolors/ ├── picocolors.js # Node.js main entry ├── picocolors.browser.js # Browser entry (colors disabled) ├── picocolors.d.ts # TypeScript declarations ├── types.d.ts # Type definitions ├── package.json # Package metadata └── tests/ └── test.js # Test suite ``` -------------------------------- ### Create Custom Color Instance Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Demonstrates how to create a custom instance of picocolors with specific options. This is useful for managing independent color sets. ```javascript import pc from "picocolors" export function createLogger(options = {}) { const colors = pc.createColors(options.colors) return { error: (msg) => console.error(colors.red(msg)), warn: (msg) => console.log(colors.yellow(msg)), info: (msg) => console.log(colors.blue(msg)), } } ``` -------------------------------- ### Migrate Tagged Template Literals Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Shows how to use 'colorize-template' to replace chalk's tagged template literals with picocolors. ```diff + import { createColorize } from 'colorize-template' + let colorize = createColorize(pico) - chalk.red.bold`full {yellow ${"text"}}` + colorize`{red.bold full {yellow ${"text"}}}` ``` -------------------------------- ### Import Picocolors Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Shows the basic import statement for using the picocolors library. ```javascript import pc from "picocolors" ``` -------------------------------- ### Basic Color Usage Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Demonstrates how to import and use picocolors for basic text coloring and nesting styles. ```javascript import pc from "picocolors" console.log( pc.green(`How are ${pc.italic(`you`)} doing?`) ) ``` -------------------------------- ### Custom Color Configuration Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/README.md Create custom `Colors` instances with `pc.createColors()`. Pass `true` to force colors on or `false` to force them off. Ensure `picocolors` is imported as `pc`. ```javascript import pc from "picocolors" const colors = pc.createColors(true) // Force colors const plain = pc.createColors(false) // Force no colors ``` -------------------------------- ### Respecting user configuration for color support Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Demonstrates creating a Colors object, allowing a user to explicitly force color support on or off, otherwise falling back to environment detection. ```javascript import pc from "picocolors" function getColors(options) { // Allow user to override color support if (options.forceColor !== undefined) { return pc.createColors(options.forceColor) } // Otherwise use environment detection return pc.createColors() } const colors = getColors({ forceColor: false }) console.log(colors.blue("Colored output disabled")) ``` -------------------------------- ### Build Tool with Color Control Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Integrate picocolors into a build tool, allowing user options to control color output. Defaults to environment detection if not specified. ```javascript import pc from "picocolors" export function createBuildConfig(userOptions = {}) { // User can override, otherwise use environment detection const colors = pc.createColors( userOptions.colors ?? undefined ) return { colors, onBuildStart: () => { console.log(colors.blue("Building...")) }, onBuildComplete: () => { console.log(colors.green("Build complete")) } } } ``` -------------------------------- ### Custom Color Configuration Usage Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Demonstrates the use of the `createColors` factory function to create custom color configurations, either forcing colors on, off, or using auto-detection. ```APIDOC ### Custom color configuration ```javascript import pc from "picocolors" const colorful = pc.createColors(true) // Force enable colors const plain = pc.createColors(false) // Force disable colors const auto = pc.createColors() // Use auto-detection (default) ``` ``` -------------------------------- ### Different color configurations in the same application Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Illustrates creating multiple Colors objects within the same application, each with a distinct color support configuration (forced on, forced off, auto-detected). ```javascript import pc from "picocolors" const coloredLogger = pc.createColors(true) const plainLogger = pc.createColors(false) const autoLogger = pc.createColors() console.log(coloredLogger.red("This is always red")) console.log(plainLogger.red("This is always plain")) console.log(autoLogger.red("This respects environment")) ``` -------------------------------- ### Create Custom Colors API Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Demonstrates creating a new API object with manually defined color support configuration. ```javascript import pc from "picocolors" let { red, bgWhite } = pc.createColors(options.enableColors) ``` -------------------------------- ### Creating Custom Formatters with Composition Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Shows how to create custom, reusable styling functions by composing existing picocolors formatters, such as `errorStyle`, `warningStyle`, and `successStyle`. ```javascript import pc from "picocolors" // Function-based composition function errorStyle(text) { return pc.bold(pc.red(text)) } function warningStyle(text) { return pc.bold(pc.yellow(text)) } function successStyle(text) { return pc.bold(pc.green(text)) } console.log(errorStyle("Critical error")) console.log(warningStyle("Warning")) console.log(successStyle("Operation complete")) ``` -------------------------------- ### Basic Picocolors Usage Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/README.md Demonstrates common text coloring and formatting functions exported by the picocolors library. Import the library and apply functions like red, green, bold, and dim to strings. ```javascript import pc from "picocolors" // Text colors pc.red("error") pc.green("success") pc.yellow("warning") // Text formatting pc.bold("bold") pc.dim("dimmed") pc.italic("italic") // Background colors pc.bgRed(pc.white("alert")) // Custom configuration const customColors = pc.createColors(true) // Force enable ``` -------------------------------- ### String Input Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Demonstrates formatting a string input with the `red` formatter. Shows output with and without color support. ```javascript import pc from "picocolors" const result = pc.red("Error") // Result: "\x1b[31mError\x1b[39m" (with colors enabled) // Result: "Error" (with colors disabled) ``` -------------------------------- ### Environment-Based Logging Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Configure picocolors dynamically based on environment variables for logging. Colors are enabled in development or when FORCE_COLOR is set. ```javascript import pc from "picocolors" const isDev = process.env.NODE_ENV === "development" const colors = pc.createColors(isDev || process.env.FORCE_COLOR) export function log(level, message) { const prefix = { error: colors.red("ERROR"), warn: colors.yellow("WARN"), info: colors.blue("INFO"), debug: colors.gray("DEBUG"), }[level] console.log(`${prefix} ${message}`) } ``` -------------------------------- ### Apply Bold Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Makes text bold or bright. Import 'picocolors' as 'pc' to use the 'bold' function. ```javascript import pc from "picocolors" console.log(pc.bold("Important")) ``` -------------------------------- ### Create Colors Instance with Auto-Detection Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Instantiate the Colors object using createColors() without arguments. This method relies on environment variables and other runtime factors for automatic color support detection. ```javascript const colors = pc.createColors() // Equivalent to: pc.createColors(undefined) // Uses environment-based detection ``` -------------------------------- ### Replace Chalk Import Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Shows how to change the import statement when migrating from chalk to picocolors. ```diff - import chalk from 'chalk' + import pico from 'picocolors' ``` -------------------------------- ### Replace Chalk Variable Usage Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Illustrates how to replace chalk function calls with picocolors equivalents. ```diff - chalk.red(text) + pico.red(text) ``` -------------------------------- ### Development vs Production color configuration Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Configures color support dynamically based on the NODE_ENV environment variable, enabling colors for development and potentially disabling them for production. ```javascript import pc from "picocolors" const isDev = process.env.NODE_ENV === "development" const colors = pc.createColors(isDev) console.log(colors.green("Starting application...")) ``` -------------------------------- ### Apply Underline Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Underlines the text. Import 'picocolors' as 'pc' to use the 'underline' function. ```javascript import pc from "picocolors" console.log(pc.underline("underlined")) ``` -------------------------------- ### Replace Chalk Chained Calls Source: https://github.com/alexeyraspopov/picocolors/blob/main/README.md Demonstrates converting chained chalk calls into nested picocolors calls. ```diff - chalk.red.bold(text) + pico.red(pico.bold(text)) ``` -------------------------------- ### Auto-detect color support (default) Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Creates a Colors object using default auto-detection for color support. Checks if colors are supported before logging. ```javascript import pc from "picocolors" const colors = pc.createColors() // Equivalent to: const colors = pc.createColors(undefined) if (colors.isColorSupported) { console.log(colors.red("Colors detected")) } else { console.log("Colors not supported") } ``` -------------------------------- ### Conditional Color Support Usage Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Illustrates how to use the `isColorSupported` property to conditionally apply formatting based on whether the environment supports colors. ```APIDOC ### Conditional color support ```javascript import pc from "picocolors" if (pc.isColorSupported) { console.log("Colors are supported") console.log(pc.green("This will be green")) } else { console.log("Colors are not supported") console.log("This will be plain text") } ``` ``` -------------------------------- ### Basic Coloring Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Apply basic text colors to strings for console output. ```javascript import pc from "picocolors" console.log(pc.red("Error message")) console.log(pc.green("Success message")) ``` -------------------------------- ### Node.js CommonJS Import Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/README.md Import the picocolors library in a Node.js CommonJS environment using `require`. ```javascript const pc = require("picocolors") ``` -------------------------------- ### Conditional Formatting with `createColors` Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Demonstrates creating a conditional formatter function that uses `pc.createColors` to enable or disable color output based on a flag. Includes a switch statement for different status messages. ```javascript import pc from "picocolors" function formatStatus(status, enabled = pc.isColorSupported) { const colors = pc.createColors(enabled) switch (status) { case "success": return colors.green("✓ Success") case "error": return colors.red("✗ Error") case "pending": return colors.yellow("⟳ Pending") default: return colors.gray("? Unknown") } } console.log(formatStatus("success")) console.log(formatStatus("error", false)) ``` -------------------------------- ### Respect User Preferences in CLI App Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Configure picocolors based on command-line arguments in a CLI application. This allows users to explicitly enable or disable colors. ```javascript import pc from "picocolors" function parseArgs() { return { color: process.argv.includes("--color") || process.argv.includes("--no-color") === false } } const args = parseArgs() const colors = pc.createColors(args.color ? true : false) console.log(colors.green("Configured colors")) ``` -------------------------------- ### Importing Picocolors Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Import the main picocolors object and destructure specific color and formatting functions. ```javascript import pc from "picocolors" const { red, bold, isColorSupported } = pc ``` -------------------------------- ### Custom Color Configuration Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Create custom color configurations using the createColors factory function, forcing color support on or off, or using auto-detection. ```javascript import pc from "picocolors" const colorful = pc.createColors(true) // Force enable colors const plain = pc.createColors(false) // Force disable colors const auto = pc.createColors() // Use auto-detection (default) ``` -------------------------------- ### Nested Formatting Usage Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Shows how to combine multiple color and text formatting functions by nesting them to create complex styles. ```APIDOC ### Nested formatting Functions can be nested to combine colors and styles: ```javascript import pc from "picocolors" console.log(pc.bold(pc.red("bold red text"))) console.log(pc.bgWhite(pc.black("black on white"))) ``` ``` -------------------------------- ### Null Input Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Shows how `null` input is handled by formatters, converting it to the string "null" and applying the specified color. ```javascript import pc from "picocolors" const result = pc.blue(null) // Result: "\x1b[34mnull\x1b[39m" // null becomes the string "null" ``` -------------------------------- ### Nested Function Calls for Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Picocolors does not support method chaining like chalk. Use nested function calls to apply multiple formatting styles. Ensure you import the 'picocolors' library before use. ```javascript import pc from "picocolors" // NOT supported (will error): // pc.red.bold("text") // Use nested calls instead: const result = pc.bold(pc.red("text")) ``` -------------------------------- ### Check Color Support Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Use this to determine if ANSI color codes will be applied in the current environment. Import 'picocolors' as 'pc' to access the 'isColorSupported' property. ```javascript import pc from "picocolors" if (pc.isColorSupported) { console.log(pc.green("Colors enabled")) } else { console.log("Colors not supported in this environment") } ``` -------------------------------- ### createLogger Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Creates a logger instance with customizable color support. The logger provides methods for error, warn, and info messages, each styled with specific colors. ```APIDOC ## createLogger ### Description Creates a logger instance with customizable color support. The logger provides methods for error, warn, and info messages, each styled with specific colors. ### Method ```javascript createLogger(options = {}) ``` ### Parameters #### Options Object - **colors** (object) - Optional - An object to configure colors. This object is passed to `pc.createColors`. ### Returns An object with the following methods: - **error(msg)**: Logs an error message in red. - **warn(msg)**: Logs a warning message in yellow. - **info(msg)**: Logs an informational message in blue. ### Example ```javascript import { createLogger } from "./your-module"; // Assuming createLogger is exported from your module const logger = createLogger({ colors: { // Custom color configurations if needed, otherwise defaults are used } }); logger.error("This is an error message."); logger.warn("This is a warning message."); logger.info("This is an info message."); ``` ``` -------------------------------- ### Conditional Color Support Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Check if the environment supports color before applying formatting. If not, plain text is output. ```javascript import pc from "picocolors" if (pc.isColorSupported) { console.log("Colors are supported") console.log(pc.green("This will be green")) } else { console.log("Colors are not supported") console.log("This will be plain text") } ``` -------------------------------- ### Basic Formatter Nesting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Demonstrates nesting `red` formatter inside `bold` to combine styles. Shows the resulting ANSI escape codes. ```javascript import pc from "picocolors" // Basic nesting const result1 = pc.bold(pc.red("text")) // Result: "\x1b[1m\x1b[31mtext\x1b[39m\x1b[22m" ``` -------------------------------- ### Apply Standard Background Colors Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Applies standard background colors to text. Available background colors include bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, and bgWhite. Import 'picocolors' as 'pc' to use these functions. ```javascript import pc from "picocolors" console.log(pc.bgRed(pc.white("Red background"))) console.log(pc.bgBlue(pc.yellow("Blue background"))) ``` -------------------------------- ### Respecting NO_COLOR standard automatically Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Demonstrates that createColors() with no arguments automatically respects the NO_COLOR environment variable standard for disabling color output. ```javascript import pc from "picocolors" // This respects NO_COLOR automatically const colors = pc.createColors() ``` -------------------------------- ### Undefined Input Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Demonstrates formatting for `undefined` input, including cases with no argument and explicit `undefined`. Both result in the string "undefined" being formatted. ```javascript import pc from "picocolors" const result1 = pc.green() // No argument const result2 = pc.green(undefined) // Explicit undefined // Both result in: "\x1b[32mundefined\x1b[39m" ``` -------------------------------- ### Color Detection Algorithm Logic Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Shows the explicit logic used for auto-detecting color support when no explicit configuration is provided. This logic prioritizes disabling colors based on NO_COLOR or --no-color, then enables them based on FORCE_COLOR, --color, platform, TTY status, or CI environment. ```javascript const isColorSupported = !(process.env.NO_COLOR || process.argv.includes("--no-color")) && (process.env.FORCE_COLOR || process.argv.includes("--color") || process.platform === "win32" || (process.stdout.isTTY && process.env.TERM !== "dumb") || process.env.CI) ``` -------------------------------- ### Apply Inverse Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Inverts the foreground and background colors of the text. Import 'picocolors' as 'pc' to use the 'inverse' function. ```javascript import pc from "picocolors" console.log(pc.inverse("inverted")) ``` -------------------------------- ### Creating Typed Logger Utilities Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/types.md Create a `Logger` interface using the `Formatter` type and implement a `createLogger` function that accepts `Colors` to generate type-safe logging utilities. This promotes consistent and safe logging practices. ```typescript import type { Colors, Formatter } from "picocolors" import pc from "picocolors" interface Logger { error: Formatter warn: Formatter info: Formatter debug: Formatter } function createLogger(colors: Colors): Logger { return { error: (msg) => colors.bold(colors.red(msg)), warn: (msg) => colors.yellow(msg), info: (msg) => colors.cyan(msg), debug: (msg) => colors.dim(colors.gray(msg)), } } const logger = createLogger(pc) logger.error("Something failed") ``` -------------------------------- ### Force Colors Enabled Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Create a picocolors instance with colors explicitly enabled. Useful for testing or forcing color output. ```javascript const colors = pc.createColors(true) console.log(colors.isColorSupported) // true ``` -------------------------------- ### Picocolors Function Input Handling Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Demonstrates how picocolors color functions handle different input types, including undefined, numbers, null, booleans, and strings. The functions convert these inputs to their string representations before applying color. ```javascript import pc from "picocolors" console.log(pc.red()) // "undefined" in red console.log(pc.red(undefined)) // "undefined" in red console.log(pc.red(42)) // "42" in red console.log(pc.red(null)) // "null" in red console.log(pc.red(true)) // "true" in red console.log(pc.red("text")) // "text" in red ``` -------------------------------- ### Enable Colors in CI Environments with CI Variable Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Use the CI environment variable to enable color output in continuous integration environments. This is automatically set by many CI/CD platforms. ```bash CI=true npm test ``` ```bash CI=true npm test # Colors enabled for better log readability ``` -------------------------------- ### Non-String Inputs Usage Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Shows that color and formatting functions can accept non-string inputs (numbers, null, undefined), which are converted to strings before formatting. ```APIDOC ### Non-string inputs ```javascript import pc from "picocolors" console.log(pc.red(42)) // "42" colored red console.log(pc.blue(null)) // "null" colored blue console.log(pc.yellow(undefined)) // "undefined" colored yellow ``` ``` -------------------------------- ### Apply Dim Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Makes text appear dimmed or faint. Import 'picocolors' as 'pc' to use the 'dim' function. ```javascript import pc from "picocolors" console.log(pc.dim("secondary text")) ``` -------------------------------- ### Color Support Detection Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Picocolors automatically detects color support based on environment variables, command-line arguments, platform, and TTY detection. If colors are not supported, formatting functions return plain strings. ```APIDOC ## Color Support Detection The library automatically detects whether the current environment supports colors. Detection uses the following criteria (in order of precedence): 1. Environment variables: `NO_COLOR` (disables colors), `FORCE_COLOR` (enables colors), `CI` (enables colors) 2. Command-line arguments: `--no-color` (disables), `--color` (enables) 3. Platform: Windows (`win32`) enables colors by default 4. TTY detection: checks if stdout is a TTY and TERM is not "dumb" When color support is not detected, all formatting functions return the input as a plain string. ``` -------------------------------- ### Caching Formatter Results Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Demonstrates that formatter functions are pure and safe to cache. Shows creating cached formatter functions for reuse. ```javascript import pc from "picocolors" // It's safe to cache formatter functions const { red, bold, green } = pc const redText = red("Error") const boldRed = bold(red("Important")) const greenText = green("Success") ``` -------------------------------- ### createColors Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Creates a new Colors object with custom color support configuration. This allows overriding automatic color detection and explicitly enabling or disabling colors. ```APIDOC ## createColors ### Description Creates a new `Colors` object with custom color support configuration. This allows you to override the automatic color detection and explicitly enable or disable colors. ### Function Signature ```typescript function createColors(enabled?: boolean): Colors ``` ### Parameters #### Parameters - **enabled** (boolean) - Optional - Default: Auto-detected - Whether to enable color output. When `undefined`, uses environment-based auto-detection. ### Return Type Returns a `Colors` object with all color and formatting functions configured according to the `enabled` parameter. ### Behavior - **`true`**: All formatting and color functions will output ANSI escape codes, regardless of environment. - **`false`**: All formatting and color functions will return plain text without ANSI codes, regardless of environment. - **`undefined` or omitted**: Uses automatic detection based on environment variables, TTY status, and platform. ### Examples #### Auto-detect color support (default) ```javascript import pc from "picocolors" const colors = pc.createColors() // Equivalent to: const colors = pc.createColors(undefined) if (colors.isColorSupported) { console.log(colors.red("Colors detected")) } else { console.log("Colors not supported") } ``` #### Force enable colors ```javascript import pc from "picocolors" const colors = pc.createColors(true) // Always output ANSI codes console.log(colors.green("Always colored")) console.log(colors.isColorSupported) // true ``` #### Force disable colors ```javascript import pc from "picocolors" const colors = pc.createColors(false) // Never output ANSI codes console.log(colors.red("Never colored")) console.log(colors.isColorSupported) // false ``` ### Color Detection Algorithm When `createColors()` is called without arguments or with `undefined`, the following detection occurs: ```javascript const isColorSupported = !(process.env.NO_COLOR || process.argv.includes("--no-color")) && (process.env.FORCE_COLOR || process.argv.includes("--color") || process.platform === "win32" || (process.stdout.isTTY && process.env.TERM !== "dumb") || process.env.CI) ``` **Detection criteria (in evaluation order):** 1. **Disable if:** - `NO_COLOR` environment variable is set, OR - `--no-color` command-line argument is present 2. **Enable if any of:** - `FORCE_COLOR` environment variable is set, OR - `--color` command-line argument is present, OR - Running on Windows (`process.platform === "win32"`), OR - stdout is a TTY AND TERM is not "dumb", OR - `CI` environment variable is set (common in CI/CD environments) ### Environment Variables The auto-detection respects the following environment variables: | Variable | |----------| | `NO_COLOR` | Setting this to any value disables colors (respects the no-color standard) | | `FORCE_COLOR` | Setting this to any value forces colors to be enabled | | `CI` | Presence enables colors (assumed to be a CI environment) | | `TERM` | If set to `"dumb"`, disables colors even if stdout is a TTY | ### Command-line Arguments The auto-detection also checks process arguments: | Argument | |----------| | `--color` | Forces color output enabled | | `--no-color` | Forces color output disabled | ``` -------------------------------- ### Apply Strikethrough Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Draws a line through the text, often used to indicate deprecated or removed content. Import 'picocolors' as 'pc' to use the 'strikethrough' function. ```javascript import pc from "picocolors" console.log(pc.strikethrough("deprecated")) ``` -------------------------------- ### Creating Type-Safe Custom Formatters Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/types.md Define a `createLogger` function that returns a `Record` of custom formatters, each typed as `Formatter` from 'picocolors'. This allows for creating reusable, type-safe custom styling functions. ```typescript import type { Formatter } from "picocolors" import pc from "picocolors" function createLogger(): Record { return { success: (msg) => pc.green(msg), error: (msg) => pc.red(msg), warning: (msg) => pc.yellow(msg), } } const logger = createLogger() logger.success("Task completed") ``` -------------------------------- ### Colors Interface Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/types.md The `Colors` interface provides access to all available text formatting and color methods, along with a property to check if color output is supported. ```APIDOC ## Colors Interface ### Description The main API interface containing all color and text formatting functions plus a configuration property. ### Properties #### isColorSupported - **Type:** `boolean` (read-only) - **Description:** Indicates whether color output is enabled for this Colors instance. - **Value:** `true` – Color and formatting functions will output ANSI escape codes; `false` – Functions return plain text without ANSI codes. - **Set by:** The `enabled` parameter of `createColors(enabled)` - **Determined by:** Environment detection when `createColors()` is called with no arguments ### Methods All methods follow the `Formatter` type signature: `method(input?: string | number | null | undefined): string` #### Text Formatting Methods These methods apply text styling without changing foreground color: | Method | Description | |-----------------|---------------------| | `reset` | Reset all formatting| | `bold` | Bold/bright text | | `dim` | Dimmed text | | `italic` | Italic text | | `underline` | Underlined text | | `inverse` | Inverted colors | | `hidden` | Hidden text | | `strikethrough` | Strikethrough text | #### Color Methods These methods set the foreground text color: | Method | RGB (typical) | |---------|---------------| | `black` | #000000 | | `red` | #FF0000 | | `green` | #00FF00 | | `yellow`| #FFFF00 | | `blue` | #0000FF | | `magenta`| #FF00FF | | `cyan` | #00FFFF | | `white` | #FFFFFF | | `gray` | #808080 | #### Bright Color Methods High-intensity versions of standard colors: | Method | Description | |---------------|---------------------| | `blackBright` | Black (high-intensity)| | `redBright` | Red (high-intensity) | | `greenBright` | Green (high-intensity)| | `yellowBright`| Yellow (high-intensity)| | `blueBright` | Blue (high-intensity) | | `magentaBright`| Magenta (high-intensity)| | `cyanBright` | Cyan (high-intensity) | | `whiteBright` | White (high-intensity)| #### Background Color Methods These methods set the background text color: | Method | Description | |---------------|---------------------| | `bgBlack` | Black background | | `bgRed` | Red background | | `bgGreen` | Green background | | `bgYellow` | Yellow background | | `bgBlue` | Blue background | | `bgMagenta` | Magenta background | | `bgCyan` | Cyan background | | `bgWhite` | White background | #### Bright Background Color Methods High-intensity versions of background colors: | Method | Description | |-----------------|--------------------------| | `bgBlackBright` | Black background (high-intensity) | | `bgRedBright` | Red background (high-intensity) | | `bgGreenBright` | Green background (high-intensity) | | `bgYellowBright`| Yellow background (high-intensity)| | `bgBlueBright` | Blue background (high-intensity) | | `bgMagentaBright`| Magenta background (high-intensity)| | `bgCyanBright` | Cyan background (high-intensity) | | `bgWhiteBright` | White background (high-intensity) | ``` -------------------------------- ### Number Input Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Illustrates formatting a number input with the `yellow` formatter. The number is automatically converted to its string representation. ```javascript import pc from "picocolors" const result = pc.yellow(42) // Result: "\x1b[33m42\x1b[39m" // Converts number to string automatically ``` -------------------------------- ### Apply Bright Background Colors Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Applies bright or high-intensity background colors to text. Available bright background colors include bgBlackBright, bgRedBright, bgGreenBright, bgYellowBright, bgBlueBright, bgMagentaBright, bgCyanBright, and bgWhiteBright. Import 'picocolors' as 'pc' to use these functions. ```javascript import pc from "picocolors" console.log(pc.bgRedBright(pc.white("Bright red background"))) console.log(pc.bgBlueBright("Bright blue background")) ``` -------------------------------- ### Testing with static output (disabled colors) Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Uses createColors(false) to ensure that color functions return plain text, which is useful for testing and asserting expected output without ANSI codes. ```javascript import pc from "picocolors" describe("Logger", () => { it("logs messages", () => { const colors = pc.createColors(false) const output = colors.red("Error message") expect(output).toBe("Error message") // No ANSI codes }) }) ``` -------------------------------- ### Apply Standard Text Colors Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Applies standard foreground colors to text. Available colors include black, red, green, yellow, blue, magenta, cyan, white, and gray. Import 'picocolors' as 'pc' to use these functions. ```javascript import pc from "picocolors" console.log(pc.red("Error")) console.log(pc.green("Success")) console.log(pc.blue("Info")) console.log(pc.yellow("Warning")) console.log(pc.gray("Muted")) ``` -------------------------------- ### Browser Script Tag Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/README.md Include the picocolors library in a browser environment using a script tag. Note that the browser version always has colors disabled. ```html ``` -------------------------------- ### Force Colors Enabled with --color Argument Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Pass the --color command-line argument to force color output to be enabled for the current invocation. ```bash node app.js --color ``` ```bash node app.js --color --other-args # Colors will be enabled ``` -------------------------------- ### Apply Bright Text Colors Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Applies bright or high-intensity foreground colors to text. Available bright colors include blackBright, redBright, greenBright, yellowBright, blueBright, magentaBright, cyanBright, and whiteBright. Import 'picocolors' as 'pc' to use these functions. ```javascript import pc from "picocolors" console.log(pc.redBright("Bright red")) console.log(pc.greenBright("Bright green")) console.log(pc.cyanBright("Bright cyan")) ``` -------------------------------- ### Nested Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Combine multiple color and text formatting functions by nesting them. ```javascript import pc from "picocolors" console.log(pc.bold(pc.red("bold red text"))) console.log(pc.bgWhite(pc.black("black on white"))) ``` -------------------------------- ### Test Configuration: Disable Colors Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Configure picocolors with colors disabled for testing purposes. This ensures that output does not contain ANSI escape codes. ```javascript import pc from "picocolors" const testColors = pc.createColors(false) describe("Logger", () => { it("formats messages correctly", () => { const output = testColors.red("Error") expect(output).toBe("Error") // No ANSI codes }) }) ``` -------------------------------- ### Formatter Method Signature Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/types.md Shows the general signature for all text formatting and color methods within the Colors interface. They accept an optional string, number, null, or undefined input. ```typescript method(input?: string | number | null | undefined): string ``` -------------------------------- ### Apply Hidden Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Hides the text, making it invisible. This can be useful for sensitive information. Import 'picocolors' as 'pc' to use the 'hidden' function. ```javascript import pc from "picocolors" console.log(pc.hidden("password")) ``` -------------------------------- ### Picocolors Color Detection Logic Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md This JavaScript expression outlines the logic Picocolors uses for color support detection when createColors() is called without arguments. It checks environment variables, command-line arguments, platform, TTY status, and TERM. ```javascript isColorSupported = !(NO_COLOR || argv includes "--no-color") && (FORCE_COLOR || argv includes "--color" || platform === "win32" || (stdout.isTTY && TERM !== "dumb") || CI) ``` -------------------------------- ### Apply Italic Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Makes text italic. Note that this may not be supported in all terminals. Import 'picocolors' as 'pc' to use the 'italic' function. ```javascript import pc from "picocolors" console.log(pc.italic("emphasized text")) ``` -------------------------------- ### Deep Formatter Nesting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Illustrates deep nesting of multiple formatters (`bold`, `red`, `bgWhite`, `italic`) to combine various styles. The library ensures proper nesting and closing of ANSI codes. ```javascript import pc from "picocolors" // Deep nesting const result2 = pc.bold(pc.red(pc.bgWhite(pc.italic("text")))) // All codes properly nested and closed ``` -------------------------------- ### Picocolors Exported API Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md The main Picocolors object exports various functions for terminal coloring and text formatting, along with a configuration property and a factory function. ```APIDOC ## Exported API The default export is a `Colors` object containing: - **Color functions** (50 total): text colors, background colors, and their bright variants - **Text formatting functions** (8 total): bold, dim, italic, underline, inverse, hidden, strikethrough, reset - **Configuration property**: `isColorSupported` (boolean) - **Factory function**: `createColors(enabled?: boolean)` – create custom color configurations ``` -------------------------------- ### Importing Picocolors Types Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/types.md Import `Colors` and `Formatter` types from 'picocolors' for use in function parameters and interface enforcement. This ensures type safety when working with picocolors functions. ```typescript import type { Colors, Formatter } from "picocolors" import pc from "picocolors" // Use Colors type for function parameters function logWithFormat(message: string, formatter: Formatter) { console.log(formatter(message)) } // Use for enforcing Colors interface const myColors: Colors = pc ``` -------------------------------- ### Boolean Input Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/formatters.md Shows how boolean values are formatted by picocolors formatters through JavaScript's type coercion, resulting in "true" or "false" with the specified color. ```javascript import pc from "picocolors" console.log(pc.cyan(true)) // "true" in cyan console.log(pc.cyan(false)) // "false" in cyan ``` -------------------------------- ### Force Colors Disabled Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Create a picocolors instance with colors explicitly disabled. Useful for environments where color is not supported or desired. ```javascript const colors = pc.createColors(false) console.log(colors.isColorSupported) // false ``` -------------------------------- ### Conditional Colors Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/README.md Check if color is supported using `pc.isColorSupported` before applying colors. This ensures graceful degradation in environments that do not support terminal colors. Ensure `picocolors` is imported as `pc`. ```javascript import pc from "picocolors" if (pc.isColorSupported) { console.log(pc.green("Colors enabled")) } else { console.log("Colors disabled") } ``` -------------------------------- ### Force Colors with FORCE_COLOR Environment Variable Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Use the FORCE_COLOR environment variable to globally enable color output. This overrides TTY detection and TERM checking, but not NO_COLOR. ```bash FORCE_COLOR=1 node app.js ``` ```bash FORCE_COLOR=1 node app.js > output.txt # Output file will contain ANSI color codes even though it's not a TTY ``` -------------------------------- ### Disable Colors with NO_COLOR Environment Variable Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/configuration.md Use the NO_COLOR environment variable to globally disable color output. Setting it to any value will disable colors, complying with the no-color.org standard. ```bash NO_COLOR=1 node app.js ``` ```bash NO_COLOR=1 npm test # Output will have no ANSI color codes ``` -------------------------------- ### Force enable colors Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/createColors.md Creates a Colors object that always outputs ANSI escape codes, regardless of the environment. Verifies color support is true. ```javascript import pc from "picocolors" const colors = pc.createColors(true) // Always output ANSI codes console.log(colors.green("Always colored")) console.log(colors.isColorSupported) // true ``` -------------------------------- ### Non-String Inputs Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/index.md Format non-string inputs like numbers, null, or undefined. They are converted to strings before formatting. ```javascript import pc from "picocolors" console.log(pc.red(42)) // "42" colored red console.log(pc.blue(null)) // "null" colored blue console.log(pc.yellow(undefined)) // "undefined" colored yellow ``` -------------------------------- ### Colors Interface Definition Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/types.md Defines the main API interface for Picocolors, including a boolean to check color support and numerous formatter functions for text styling and colors. ```typescript export interface Colors { isColorSupported: boolean reset: Formatter bold: Formatter dim: Formatter italic: Formatter underline: Formatter inverse: Formatter hidden: Formatter strikethrough: Formatter black: Formatter red: Formatter green: Formatter yellow: Formatter blue: Formatter magenta: Formatter cyan: Formatter white: Formatter gray: Formatter bgBlack: Formatter bgRed: Formatter bgGreen: Formatter bgYellow: Formatter bgBlue: Formatter bgMagenta: Formatter bgCyan: Formatter bgWhite: Formatter blackBright: Formatter redBright: Formatter greenBright: Formatter yellowBright: Formatter blueBright: Formatter magentaBright: Formatter cyanBright: Formatter whiteBright: Formatter bgBlackBright: Formatter bgRedBright: Formatter bgGreenBright: Formatter bgYellowBright: Formatter bgBlueBright: Formatter bgMagentaBright: Formatter bgCyanBright: Formatter bgWhiteBright: Formatter } ``` -------------------------------- ### Reset Formatting Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Applies the reset formatter to revert all text styling back to default. This is useful for ensuring subsequent text is not affected by previous formatting. ```javascript import pc from "picocolors" console.log(pc.bold("bold") + pc.reset(" not bold")) ``` -------------------------------- ### isColorSupported Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md A read-only boolean property that indicates whether ANSI color codes will be applied in the current environment. It is true if the environment supports colors (TTY, CI, or forced via FORCE_COLOR), and false otherwise. ```APIDOC ## isColorSupported ### Description A read-only boolean property that indicates whether ANSI color codes will be applied in the current environment. ### Value - `true` if the environment supports colors (TTY, CI, or forced via FORCE_COLOR) - `false` in browser environments, dumb terminals, or when NO_COLOR is set ### Example ```javascript import pc from "picocolors" if (pc.isColorSupported) { console.log(pc.green("Colors enabled")) } else { console.log("Colors not supported in this environment") } ``` ``` -------------------------------- ### Text Formatting Functions Source: https://github.com/alexeyraspopov/picocolors/blob/main/_autodocs/api-reference/colors.md Functions that apply text styling without changing the text color, such as reset, bold, dim, italic, underline, inverse, hidden, and strikethrough. ```APIDOC ## reset ### Description Resets all formatting back to default. ### Example ```javascript import pc from "picocolors" console.log(pc.bold("bold") + pc.reset(" not bold")) ``` ## bold ### Description Makes text bold/bright. ### Example ```javascript import pc from "picocolors" console.log(pc.bold("Important")) ``` ## dim ### Description Makes text dimmed/faint. ### Example ```javascript import pc from "picocolors" console.log(pc.dim("secondary text")) ``` ## italic ### Description Makes text italic (may not be supported in all terminals). ### Example ```javascript import pc from "picocolors" console.log(pc.italic("emphasized text")) ``` ## underline ### Description Underlines the text. ### Example ```javascript import pc from "picocolors" console.log(pc.underline("underlined")) ``` ## inverse ### Description Inverts foreground and background colors. ### Example ```javascript import pc from "picocolors" console.log(pc.inverse("inverted")) ``` ## hidden ### Description Hides the text (useful for sensitive information in some contexts). ### Example ```javascript import pc from "picocolors" console.log(pc.hidden("password")) ``` ## strikethrough ### Description Draws a line through the text. ### Example ```javascript import pc from "picocolors" console.log(pc.strikethrough("deprecated")) ``` ```