nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
493 lines (492 loc) • 21.5 kB
TypeScript
import type { CSSColor, Hex } from '../colors/types';
import { ANSI_16_COLORS } from './constants';
/** Non-color text styles */
export type TextStyle = 'bold' | 'bolder' | 'dim' | 'italic' | 'underline' | 'strikethrough' | 'inverse';
/** Represents `ANSI-16` color names available in `LogStyler` */
export type Ansi16Color = keyof typeof ANSI_16_COLORS;
/** Represents `ANSI-16` color names with `css-` prefix available in `LogStyler` */
export type CSS16Color = `css-${Ansi16Color}`;
/** Represents the value of `ANSI-16` color codes */
export type Ansi16Value = (typeof ANSI_16_COLORS)[Ansi16Color];
/** Represents a css color starting with `bg` (e.g. `"bgRed"`). */
export type BGColor = `bg${Capitalize<CSSColor>}`;
/** Styles allowed for `LogStyler` or `Stylog` */
export type Styles = CSSColor | BGColor | TextStyle;
/** A `tuple of strings` that represents `ANSI` color code with special closing and ending */
export type AnsiSequence = [string, string];
/**
* * Type representing a fully chainable `LogStyler` instance.
*
* @remarks
* - Each property corresponds to a style and returns a new `Stylog` instance, allowing fluent chaining.
* - **This type combines:**
* - The methods of `LogStyler` (e.g., `.style()`, `.log()`)
* - Dynamically generated properties for all available `Styles` that return another `Stylog` instance for chaining.
*
* @example
* Stylog.green.bold.bgBlue.log('Hello World');
*/
export type StylogChain = LogStyler & {
[K in Styles]: StylogChain;
};
/**
* * Detects color support level of the current terminal/shell.
* @returns `0 = none`, `1 = basic (16 colors)`, `2 = 256 colors`, `3 = truecolor`
*/
export declare function detectColorSupport(): 0 | 1 | 2 | 3;
/**
* * Convert `RGB` color components into an `ANSI` escape code sequence.
*
* @param r Red component (`0-255`).
* @param g Green component (`0-255`).
* @param b Blue component (`0-255`).
* @param isBg Whether the color should be applied as background (`true`) or foreground (`false`). Defaults to `false`.
* @returns Tuple containing the opening and closing `ANSI` escape sequences.
*/
export declare function rgbToAnsi(r: number, g: number, b: number, isBg?: boolean): AnsiSequence;
/**
* * Convert a HEX color into an `ANSI` escape code sequence.
*
* @param hex HEX color string. e.g. `#000000`
* @param isBg Whether the color should be applied as background (`true`) or foreground (`false`). Defaults to `false`.
* @returns Tuple containing the opening and closing `ANSI` escape sequences.
*/
export declare function hexToAnsi(hex: Hex, isBg?: boolean): AnsiSequence;
/** * Check if a string represents a valid `CSSColor`. */
export declare function isCSSColor(value: string): value is CSSColor;
/** * Check if a string represents `bgColor` with valid CSS color name. */
export declare function isBGColor(value: string): value is BGColor;
/** * Check if a string represent `TextStyle` used in `LogStyler`. */
export declare function isTextStyle(value: string): value is TextStyle;
/**
* @class Utility class for styling console log output with `ANSI` (`Node.js`) or `CSS` (Browser).
*
* @remarks
* - Allows chaining of style methods or initializing with predefined styles.
* - For fluent, chainable styling with zero configuration use {@link https://toolbox.nazmul-nhb.dev/docs/utilities/misc/stylog Stylog} (`LogStyler` chainable wrapper).
*
* @example
* const styled = new LogStyler(['red', 'bold']);
* styled.log('Hello World');
*
* const logger = new LogStyler();
* logger.style('blue', 'dim', 'bold').log('Hello Blue');
* logger.style('blue', 'dim', 'bold').toANSI('Hello Blue');
* logger.style('blue', 'dim', 'bold').toCSS('Hello Blue');
*/
export declare class LogStyler {
#private;
/**
* * Creates a new `LogStyler` instance.
*
* @param styles - Optional array of initial styles to apply (e.g., ['red', 'bold']). Defaults to an empty array.
*
* @example
* const styled = new LogStyler(['red', 'bold']);
* styled.log('Hello World');
*
* const logger = new LogStyler();
* logger.style('blue', 'dim', 'bold').log('Hello Blue');
* logger.style('blue', 'dim', 'bold').toANSI('Hello Blue');
* logger.style('blue', 'dim', 'bold').toCSS('Hello Blue');
*/
constructor(styles?: Styles[]);
/**
* * Chain multiple styles to the input.
*
* @param style - One or more styles to apply (color, background, or text style).
* @returns A new StylogChain instance with the additional styles applied.
*
* @remarks
* - When chaining similar styles, only the last one(s) takes effect.
* - All colors applied through `style()` method are `truecolor` in form, to apply `ANSI-16` colors, use `ansi16()` method.
*
* @example
* // Single style
* Stylog.style('red').log('Red text');
* Stylog.style('red').toANSI('Red text');
* Stylog.style('red').toCSS('Red text');
*
* @example
* // Multiple styles at once
* Stylog.style('red', 'bold', 'underline').log('Red bold underlined text');
* Stylog.style('red', 'bold', 'underline').toANSI('Red bold underlined text');
* Stylog.style('red', 'bold', 'underline').toCSS('Red bold underlined text');
*
* @example
* // Mixed foreground and background
* Stylog.style('white', 'bgBlue').log('White text on blue background');
* Stylog.style('white', 'bgBlue').toANSI('White text on blue background');
* Stylog.style('white', 'bgBlue').toCSS('White text on blue background');
*
* @example
* // Building on existing styles
* const errorStyle = Stylog.style('red', 'bold');
* errorStyle.style('underline').log('Red bold underlined error');
* errorStyle.style('underline').toANSI('Red bold underlined error');
* errorStyle.style('underline').toCSS('Red bold underlined error');
*/
style(...style: Styles[]): StylogChain;
/**
* * Apply ANSI 16-color styling to the text.
*
* @param color - ANSI 16-color name (e.g., 'red', 'cyanBright', 'bgRed').
* @returns A new `StylogChain` instance with the `ANSI 16-color` style applied.
*
* @remarks
* - Only one argument (color) can be passed on a single call.
* - Color applied through `ansi16()` method is `truecolor` in form, to apply `truecolor` colors, use `style()` method.
*
* @example
* // Basic usage
* Stylog.ansi16('red').log('Error message');
*
* @example
* // Chaining with other styles
* Stylog.ansi16('redBright').bold.italic.log('Bright red bold italic');
* Stylog.ansi16('redBright').bold.italic.toANSI('Bright red bold italic');
* Stylog.ansi16('redBright').bold.italic.toCSS('Bright red bold italic');
*
* @example
* // Background colors
* Stylog.ansi16('bgRed').log('Red background');
* Stylog.ansi16('bgRed').toANSI('Red background');
* Stylog.ansi16('bgRed').toCSS('Red background');
*/
ansi16(color: Ansi16Color): StylogChain;
/**
* * Returns styled tuple `[format, cssList]` for Browser.
*
* @remarks
* - This method is specifically designed for browser environments and returns a tuple containing the formatted string with `%c` placeholder and an array of CSS styles (`string[]`).
* - Use this when you need direct access to the CSS styling for custom browser output.
* - If you want to format with ANSI escape codes, consider using {@link https://toolbox.nazmul-nhb.dev/docs/classes/LogStyler#toansiinput-stringify toANSI} method.
*
* @param input - Input to style before printing in the shell.
* @param stringify - Whether to apply `JSON.stringify()` before styling. Defaults to `false`.
* @returns Tuple `[format, cssList]` where:
* - `format`: String with `%c` placeholder for CSS styling
* - `cssList`: Array of CSS style strings
*
* @example
* // Basic usage in browser
* const styler = new LogStyler(['red', 'bold']);
* const [format, cssList] = styler.toCSS('Error message');
* // format: "%cError message"
* // cssList: ["color: #FF0000", "font-weight: bold"]
*
* @example
* // Custom browser output handling
* const styled = new LogStyler(['blue', 'bgYellow', 'italic']);
* const [format, styles] = styled.toCSS('Warning', true);
*
* // Use with custom logging function
* function customLog(formatted: string, styles: string[]) {
* const styleString = styles.join('; ');
* console.log(formatted, styleString);
* }
* customLog(format, styles);
*
* @example
* // With object stringification
* const dataOutput = new LogStyler(['green']).toCSS({ id: 123 }, true);
* // format: "%c{\"id\":123}"
* // cssList: ["color: #008000"]
*/
toCSS(input: unknown, stringify?: boolean): [`%c${string}`, string[]];
/**
* * Returns the input as a styled string with ANSI escape codes.
*
* @remarks
* - This method returns ANSI-formatted strings suitable for environments that support ANSI escape codes (terminals, modern browser consoles, etc.).
* - For unsupported browsers, consider using the {@link https://toolbox.nazmul-nhb.dev/docs/classes/LogStyler#loginput-stringify log} method to print directly or {@link https://toolbox.nazmul-nhb.dev/docs/classes/LogStyler#tocssinput-stringify toCSS} to get styled tuple `[format, cssList]` for Browser.
*
* @param input - Input to style before printing in the shell.
* @param stringify - Whether to apply `JSON.stringify()` before styling. Defaults to `false`.
* @returns The styled string with ANSI escape codes.
*
* @example
* const styled = new LogStyler(['red', 'bold']);
* const errorMessage = styled.toANSI('Error occurred, using LogStyler');
* // Or with Stylog
* const errorMessage = Stylog.red.bold.toANSI('Error occurred, using Stylog');
* // Returns: "\x1b[31m\x1b[1mError occurred, using Stylog\xx1b[22m\x1b[39m"
*
* @example
* // Use in console (terminal or modern browser consoles)
* console.error(errorMessage);
* console.info(Stylog.red.bold.toANSI('I support ANSI!'));
*/
toANSI(input: unknown, stringify?: boolean): string;
/**
* * Print styled input to the console.
*
* @param input Input to print to the shell/console.
* @param stringify Whether to apply `JSON.stringify()` before printing. Defaults to `false`.
*/
log(input: unknown, stringify?: boolean): void;
/**
* * Apply a HEX color to the text foreground.
*
* @param code - HEX color string (e.g., `'#4682B4'` or `'4682B4'`).
* @returns A new `StylogChain` instance with the HEX color applied.
*
* @example
* // With hash prefix
* Stylog.hex('#4682B4').log('Steel blue text');
* Stylog.hex('#4682B4').toANSI('Steel blue text');
* Stylog.hex('#4682B4').toCSS('Steel blue text');
*
* @example
* // Without hash prefix
* Stylog.hex('4682B4').log('Steel blue text');
* Stylog.hex('4682B4').toANSI('Steel blue text');
* Stylog.hex('4682B4').toCSS('Steel blue text');
*
* @example
* // Chaining with other styles
* Stylog.hex('#FF0000').bold.log('Red bold text');
* Stylog.hex('#FF0000').bold.toANSI('Red bold text');
* Stylog.hex('#FF0000').bold.toCSS('Red bold text');
*/
hex(code: string): StylogChain;
/**
* * Apply a HEX color to the text background.
*
* @param code - HEX color string (e.g., `'#4682B4'` or `'4682B4'`).
* @returns A new StylogChain instance with the HEX background color applied.
*
* @example
* // With hash prefix
* Stylog.bgHex('#4682B4').log('Steel blue background');
* Stylog.bgHex('#4682B4').toANSI('Steel blue background');
* Stylog.bgHex('#4682B4').toCSS('Steel blue background');
*
* @example
* // Without hash prefix
* Stylog.bgHex('4682B4').log('Steel blue background');
* Stylog.bgHex('4682B4').toANSI('Steel blue background');
* Stylog.bgHex('4682B4').toCSS('Steel blue background');
*
* @example
* // Chaining with foreground color
* Stylog.white.bgHex('#000000').log('White text on black background');
* Stylog.white.bgHex('#000000').toANSI('White text on black background');
* Stylog.white.bgHex('#000000').toCSS('White text on black background');
*/
bgHex(code: string): StylogChain;
/**
* * Apply an RGB color to the text foreground using a CSS-like string.
*
* @param code - RGB color string (e.g., `'rgb(11, 45, 1)'` or `'11, 45, 1'`).
* @returns A new `StylogChain` instance with the RGB color applied.
*
* @example
* // Full rgb() syntax
* Stylog.rgb('rgb(11, 45, 1)').log('Dark green text');
* Stylog.rgb('rgb(11, 45, 1)').toANSI('Dark green text');
* Stylog.rgb('rgb(11, 45, 1)').toCSS('Dark green text');
*
* @example
* // Comma-separated values
* Stylog.rgb('11, 45, 1').log('Dark green text');
* Stylog.rgb('11, 45, 1').toANSI('Dark green text');
* Stylog.rgb('11, 45, 1').toCSS('Dark green text');
*
* @example
* // Chaining with other styles
* Stylog.rgb('255, 0, 0').bold.log('Red bold text');
* Stylog.rgb('255, 0, 0').bold.toANSI('Red bold text');
* Stylog.rgb('255, 0, 0').bold.toCSS('Red bold text');
*/
rgb(code: string): StylogChain;
/**
* * Apply an RGB color to the text foreground using individual components.
*
* @param red - Red component (`0-255`).
* @param green - Green component (`0-255`).
* @param blue - Blue component (`0-255`).
* @returns A new `StylogChain` instance with the RGB color applied.
*
* @example
* // Individual components
* Stylog.rgb(255, 0, 0).log('Red text');
* Stylog.rgb(255, 0, 0).toANSI('Red text');
* Stylog.rgb(255, 0, 0).toCSS('Red text');
*
* @example
* // With other styles
* Stylog.rgb(0, 255, 0).underline.log('Green underlined text');
* Stylog.rgb(0, 255, 0).underline.toANSI('Green underlined text');
* Stylog.rgb(0, 255, 0).underline.toCSS('Green underlined text');
*/
rgb(red: number, green: number, blue: number): StylogChain;
/**
* * Apply an RGB color to the text background using a CSS-like string.
*
* @param code - RGB color string (e.g., `'rgb(225, 169, 196)'` or `'225, 169, 196'`).
* @returns A new `StylogChain` instance with the RGB background color applied.
*
* @example
* // Full rgb() syntax
* Stylog.bgRGB('rgb(225, 169, 196)').log('Pink background');
* Stylog.bgRGB('rgb(225, 169, 196)').toANSI('Pink background');
* Stylog.bgRGB('rgb(225, 169, 196)').toCSS('Pink background');
*
* @example
* // Comma-separated values
* Stylog.bgRGB('225, 169, 196').log('Pink background');
* Stylog.bgRGB('225, 169, 196').toANSI('Pink background');
* Stylog.bgRGB('225, 169, 196').toCSS('Pink background');
*
* @example
* // With foreground color
* Stylog.black.bgRGB('255, 255, 255').log('Black text on white background');
* Stylog.black.bgRGB('255, 255, 255').toANSI('Black text on white background');
* Stylog.black.bgRGB('255, 255, 255').toCSS('Black text on white background');
*/
bgRGB(code: string): StylogChain;
/**
* * Apply an RGB color to the text background using individual components.
*
* @param red - Red component (`0-255`).
* @param green - Green component (`0-255`).
* @param blue - Blue component (`0-255`).
* @returns A new `StylogChain` instance with the RGB background color applied.
*
* @example
* // Individual components
* Stylog.bgRGB(0, 0, 255).log('Blue background');
* Stylog.bgRGB(0, 0, 255).toANSI('Blue background');
* Stylog.bgRGB(0, 0, 255).toCSS('Blue background');
*
* @example
* // With text styles
* Stylog.bgRGB(255, 255, 0).bold.log('Bold text on yellow background');
* Stylog.bgRGB(255, 255, 0).bold.toANSI('Bold text on yellow background');
* Stylog.bgRGB(255, 255, 0).bold.toCSS('Bold text on yellow background');
*/
bgRGB(red: number, green: number, blue: number): StylogChain;
/**
* * Apply an HSL color to the text foreground using a CSS-like string.
*
* @param code - HSL color string (e.g., `'hsl(50 80.5% 40%)'`).
* @returns A new `StylogChain` instance with the HSL color applied.
*
* @example
* // Standard HSL syntax
* Stylog.hsl('hsl(50 80.5% 40%)').log('Gold text');
* Stylog.hsl('hsl(50 80.5% 40%)').toANSI('Gold text');
* Stylog.hsl('hsl(50 80.5% 40%)').toCSS('Gold text');
*
* @example
* // With commas
* Stylog.hsl('50, 80.5%, 40%').log('Gold text');
* Stylog.hsl('50, 80.5%, 40%').toANSI('Gold text');
* Stylog.hsl('50, 80.5%, 40%').toCSS('Gold text');
*
* @example
* // Chaining with other styles
* Stylog.hsl('120, 100%, 50%').italic.log('Green italic text');
* Stylog.hsl('120, 100%, 50%').italic.toANSI('Green italic text');
* Stylog.hsl('120, 100%, 50%').italic.toCSS('Green italic text');
*/
hsl(code: string): StylogChain;
/**
* * Apply an HSL color to the text foreground using individual components.
*
* @param hue - Hue component (`0-360`).
* @param saturation - Saturation component (`0-100`).
* @param lightness - Lightness component (`0-100`).
* @returns A new `StylogChain` instance with the HSL color applied.
*
* @example
* // Individual components
* Stylog.hsl(0, 100, 50).log('Red text');
* Stylog.hsl(0, 100, 50).toANSI('Red text');
* Stylog.hsl(0, 100, 50).toCSS('Red text');
*
* @example
* // With percentage values
* Stylog.hsl(240, 100, 50).log('Blue text');
* Stylog.hsl(240, 100, 50).toANSI('Blue text');
* Stylog.hsl(240, 100, 50).toCSS('Blue text');
*/
hsl(hue: number, saturation: number, lightness: number): StylogChain;
/**
* * Apply an HSL color to the text background using a CSS-like string.
*
* @param code - HSL color string (e.g., `'hsl(50 80.5% 40%)'`).
* @returns A new `StylogChain` instance with the HSL background color applied.
*
* @example
* // Standard HSL syntax
* Stylog.bgHSL('hsl(50 80.5% 40%)').log('Gold background');
* Stylog.bgHSL('hsl(50 80.5% 40%)').toANSI('Gold background');
* Stylog.bgHSL('hsl(50 80.5% 40%)').toCSS('Gold background');
*
* @example
* // With commas
* Stylog.bgHSL('50, 80.5%, 40%').log('Gold background');
* Stylog.bgHSL('50, 80.5%, 40%').toANSI('Gold background');
* Stylog.bgHSL('50, 80.5%, 40%').toCSS('Gold background');
*
* @example
* // With foreground color
* Stylog.white.bgHSL('0, 100%, 50%').log('White text on red background');
* Stylog.white.bgHSL('0, 100%, 50%').toANSI('White text on red background');
* Stylog.white.bgHSL('0, 100%, 50%').toCSS('White text on red background');
*/
bgHSL(code: string): StylogChain;
/**
* * Apply an HSL color to the text background using individual components.
*
* @param hue - Hue component (`0-360`).
* @param saturation - Saturation component (`0-100`).
* @param lightness - Lightness component (`0-100`).
* @returns A new StylogChain instance with the HSL background color applied.
*
* @example
* // Individual components
* Stylog.bgHSL(120, 100, 50).log('Green background');
* Stylog.bgHSL(120, 100, 50).toANSI('Green background');
* Stylog.bgHSL(120, 100, 50).toCSS('Green background');
*
* @example
* // With text styles
* Stylog.bgHSL(300, 100, 50).bold.log('Bold text on purple background');
* Stylog.bgHSL(300, 100, 50).bold.toANSI('Bold text on purple background');
* Stylog.bgHSL(300, 100, 50).bold.toCSS('Bold text on purple background');
*/
bgHSL(hue: number, saturation: number, lightness: number): StylogChain;
}
/**
* * Styled console logger with chainable, type-safe color and text effects for both `Node.js` (`ANSI true-color`) and browsers (`CSS` via `%c`).
*
* @remarks
* - Chain any mix of foreground colors (e.g. `green`), background colors (e.g. `bgBlue`), and text styles (e.g. `bold`, `italic`, `underline`).
* - In browsers, styles are applied using `CSS`; in `Node.js`, `ANSI` escape codes are used.
* - When multiple styles of the same category are chained, the last one wins.
* - Use `.log(value, stringify?)` to print; set `stringify` to `true` to serialize with `JSON.stringify`.
* - If you need custom reusable style configurations, use {@link https://toolbox.nazmul-nhb.dev/docs/classes/LogStyler Stylog} class.
*
* @example
* // Simple color
* Stylog.green.log('Ready');
*
* @example
* // Foreground + background + effect, with JSON stringification
* Stylog.green.bgBlue.bold.log({ a: 121 }, true);
*
* @example
* // Reusable base chain
* const base = Stylog.underline;
* base.red.log('Error');
* base.error.log('Error');
* base.bgYellow.bold.log('Caution');
*
* @example
* // Works in the browser console too
* Stylog.cornflowerblue.italic.log('Hello from the browser');
*/
export declare const Stylog: StylogChain;