@nevware21/chromacon
v0.1.1
Published
Text formatting utilities to colorize your text output.
Readme
Overview
Chromacon is a powerful, TypeScript/JavaScript library for adding colors and text formatting to your console and terminal output. Built with modern development practices, it provides a comprehensive API for creating rich, colorful text output across different environments and color support levels.
Installation
npm install @nevware21/chromacon --saveRecommended Version Specification:
"@nevware21/chromacon": ">= 0.1.1 < 2.x"Key Features
- Rich Color Support - Basic 16 colors, 256-color palette, and true color (24-bit RGB)
- Text Styling - Bold, italic, underline, strikethrough, and more
- Smart Color Restoration - Automatic color context restoration when nesting color functions
- Output Optimization - Intelligent removal of redundant ANSI escape sequences for cleaner output
- Theming System - Built-in theme support with multiple themes in upcoming releases
- Automatic Detection - Intelligent color support detection for different environments
- Type Safety - Full TypeScript support with comprehensive type definitions
- Cross-Platform - Works in Node.js, browsers, and web workers
- Minimal Dependencies - Lightweight with only essential utilities
- Flexible API - Both functional and string-based usage patterns
Documentation and Details
See the Documentation Home site which includes access to the API Reference generated from source code via TypeDoc for a full list and details of all available types, functions, and interfaces with included examples.
See Browser Support for details on the supported browser environments.
Quick Start
import { red, green, blue, bold, underline, bgYellow } from "@nevware21/chromacon";
// Basic colors - function usage (wraps text and auto-resets)
console.log(red("Error: Something went wrong"));
console.log(green("Success: Operation completed"));
console.log(blue("Info: Processing data..."));
// Text styling
console.log(bold("Important message"));
console.log(underline("Underlined text"));
// Combine colors and styles
console.log(bold(red("Critical Alert")));
console.log(bgYellow(blue("Blue text on yellow background")));
// Template string usage
const status = "running";
console.log(`Status: ${green(status)}`);API Overview
Chromacon provides a flexible API with two usage patterns and intelligent color restoration.
Two Usage Patterns
1. Function Usage (Recommended)
Functions wrap your text and automatically handle color reset:
import { red, bold } from "@nevware21/chromacon";
console.log(red("This is red text"));
console.log(bold("This is bold text"));2. String Usage (Advanced)
Use color values directly as strings for manual control:
import { red, reset } from "@nevware21/chromacon";
console.log(`${red}This is red text${reset}`);
console.log(red + "This is red text" + reset);
console.log(red.concat("This is red text").concat(reset))Smart Color Restoration
When nesting color functions, Chromacon intelligently restores the previous color:
import { red, blue } from "@nevware21/chromacon";
// Nested colors with automatic restoration
console.log(red("Error in " + blue("file.ts") + " at line 42"));
// Output: "Error in" and "at line 42" are red, "file.ts" is blueNote: Color restoration only works within function call context, not in template literals where colors are used as string values.
See API Reference for full details.
Colors
| Type | Colors | |------|--------| | Foreground Colors | black; red; green; yellow; blue; magenta; cyan; white; gray; grey | | Bright Foreground Colors | brightRed; brightGreen; brightYellow; brightBlue; brightMagenta; brightCyan; brightWhite | | Background Colors | bgBlack; bgRed; bgGreen; bgYellow; bgBlue; bgMagenta; bgCyan; bgWhite; bgGray; bgGrey | | Bright Background Colors | bgBrightRed; bgBrightGreen; bgBrightYellow; bgBrightBlue; bgBrightMagenta; bgBrightCyan; bgBrightWhite |
Text Styles
| Type | Styles | |------|--------| | Font Styling | bold; dim; italic | | Text Decoration | underline; strikethrough; overlined | | Visual Effects | blink; inverse; hidden; framed; encircled | | Utility | reset |
Utility Functions
| Type | Functions | |------|-----------| | Color Support Detection | isColorSupported(); isRgb256ColorSupported(); isTrueColorSupported() | | Manual Configuration | setColorLevel(); getColorLevel(); setColorDetector() | | Text Processing | stripAnsi(); matchAnsi() |
Usage Examples
See Usage Examples for comprehensive examples including:
- Function usage vs string usage patterns
- Smart color restoration
- Combining colors and styles
- Conditional formatting
- Color level configuration
- Text processing utilities
Color Support Levels
Chromacon automatically detects and adapts to different color support levels:
| Level | Description | Colors Available |
|-------|-------------|------------------|
| None | No color support | Text only |
| Basic | Standard 16 colors | 8 basic + 8 bright colors |
| Ansi256 | 8-bit color palette | 256 colors |
| Rgb | True color support | 16.7 million colors |
TypeScript Support
Chromacon is built with TypeScript and provides comprehensive type definitions:
import { ChromaColor, ChromaStyle, ColorLevel } from "@nevware21/chromacon";
// Type-safe color functions
const errorColor: ChromaColor = red;
const titleStyle: ChromaStyle = bold;
// Enum support for color levels
const level: ColorLevel = ColorLevel.Ansi256;Theming System
Chromacon features a built-in theming system that adapts output formatting based on the current theme configuration. The default ANSI theme provides standard terminal color support, with additional themes planned for future releases.
Current Theme Support
The current implementation uses the ANSI Theme as the default:
- Standard ANSI escape sequences for colors and styles
- Automatic color level detection and adaptation
- Cross-platform compatibility
Upcoming Theme Features
Future releases will include multiple built-in themes:
- HTML Theme - Convert colors and styles to HTML markup
- Markdown Theme - Generate markdown-compatible formatting
- Plain Text Theme - Strip all formatting for plain text output
- Custom Themes - Developer-defined theme implementations
Theme Architecture
// Future theme API (planned)
import { setTheme, getTheme, createCustomTheme } from "@nevware21/chromacon";
// Switch to HTML theme (future release)
setTheme('html');
console.log(red("Error")); // Output: <span style="color: red;">Error</span>
// Switch to Markdown theme (future release)
setTheme('markdown');
console.log(bold("Important")); // Output: **Important**
// Custom theme creation (future release)
const customTheme = createCustomTheme({
colors: { /* custom color mappings */ },
styles: { /* custom style mappings */ }
});Current Theme Configuration
The current ANSI theme can be configured using existing color level settings:
import { setColorLevel, ColorLevel } from "@nevware21/chromacon";
// Configure ANSI theme behavior
setColorLevel(ColorLevel.Rgb); // Enable full color support
setColorLevel(ColorLevel.None); // Disable color formattingEnvironment Support
Test Environments
- Node.js (16, 18, 20, 22)
- Browser (Chromium - headless)
- Web Worker (Chromium - headless)
Platform Compatibility
- ✅ Node.js applications
- ✅ Browser environments
- ✅ Web Workers
- ✅ Terminal applications
- ✅ Console logging
Performance
Chromacon is designed for minimal overhead:
- Minimal runtime dependencies (@nevware21/ts-utils for cross-platform compatibility and minification improvements)
- Tree-shakable exports
- Lazy initialization
- Efficient string concatenation
- Optimized for frequent usage
Browser Support
Chromacon provides comprehensive browser support with intelligent feature detection and graceful degradation across different environments.
Supported Browsers
| Browser | Version | ANSI Support | Notes | |---------|---------|--------------|--------| | Chrome | 58+ | ✅ Full | Complete ANSI support in DevTools console | | Firefox | 55+ | ✅ Full | Complete ANSI support in DevTools console | | Safari | 11+ | ✅ Full | Complete ANSI support in DevTools console | | Edge | 16+ | ✅ Full | Complete ANSI support in DevTools console | | Opera | 45+ | ✅ Full | Complete ANSI support in DevTools console |
Console Environment Detection
Chromacon automatically detects console capabilities and adjusts output accordingly:
import { isColorSupported, red, green } from "@nevware21/chromacon";
// Automatic detection in different environments
if (isColorSupported()) {
console.log(red("Colors are supported!"));
} else {
console.log("Colors not supported - falling back to plain text");
}Browser-Specific Features
Developer Tools Console
Modern browser developer tools provide excellent ANSI escape sequence support:
- Full color palette (16.7M colors)
- Text styling (bold, italic, underline)
- Background colors
- Proper reset handling
Web Workers
Chromacon works seamlessly in web worker environments:
// In a web worker
import { blue, bold } from "@nevware21/chromacon";
self.postMessage(blue("Worker message with color"));
console.log(bold("Bold text in worker console"));Node.js Integration
When using Chromacon in Node.js applications that also run in browsers:
import { setColorDetector, red } from "@nevware21/chromacon";
// Custom detection for hybrid environments
setColorDetector(() => {
// Custom logic for your environment
return typeof window !== 'undefined' && console.log.toString().indexOf('native') > -1;
});Fallback Behavior
When ANSI support is not available, Chromacon automatically returns plain text without color codes. You can also add custom fallback behavior for better user experience:
import { isColorSupported, red, green, bold } from "@nevware21/chromacon";
function formatMessage(text: string, level: 'error' | 'success') {
const formattedText = level === 'error' ? red(bold(text)) : green(bold(text));
if (!isColorSupported()) {
// Colors not supported - so add additional text indicators as fallback
formattedText = `[${level.toUpperCase()}] ${formattedText}`;
}
// return formatted text
return formattedText;
}
// Example usage:
console.log(formatMessage("Operation failed", "error"));
// With colors: displays red bold text
// Without colors: displays "[ERROR] Operation failed"Browser Console Examples
When viewed in browser developer tools, Chromacon output provides rich visual feedback:
// This will render with actual colors in browser console
console.log(red("🔴 Error: Network timeout"));
console.log(green("🟢 Success: Data loaded"));
console.log(blue("🔵 Info: Cache updated"));
console.log(bold("📢 Important announcement"));Known Limitations
- Email/Document Export: ANSI codes don't translate to HTML (use
stripAnsi()utility) - Text Copy/Paste: ANSI codes may appear as raw text when copied from console
Contributing
We welcome contributions! Please read our Contributing Guide for details on our development process and how to submit pull requests.
Support
License
Licensed under the MIT License.
