Module: style - uhop/console-toolkit GitHub Wiki

The style.js module provides a way to style output. It is based on ansi/sgr-state.js.

It provides a simple user-friendly way to define states, and apply them either directly or using specialized back-quote functions.

import style, {s} from 'console-toolkit/style.js';

console.log(style.bold.text('Hello, world!'));

const warn = style.bold.bright.yellow.bg.dark.blue,
  error = warn.bg.red;

console.log(warn.text('Warning!'), error.text('Error!'));

console.log(s`Hello, ${warn}world!`);

console.log(s`{{bold}}Hello, {{save.blue}}world{{restore}}!{{reset.all}}`);

style.js

Class Style

The Style class provides a chainable way to define states. It defines SGR commands defined in ansi/sgr.js as getters and methods converting them from the snake case to the camel case, e.g., RESET_ALL to resetAll and BOLD to bold. The color names are also defined to change colors. Additionally it provides helpers to define custom colors and some helpful namespaces to make commands more readable.

All style objects are read-only and can be saved and reused freely.

The following namespaces are defined:

  • Color-only namespaces:
    • fg - foreground colors. Example: fg.red.
    • bg - background colors. Example: bg.red.
    • bright - bright colors. Example: bright.red.
    • dark - dark colors. Example: dark.red.
  • Extended color namespaces:
    • colorDecoration - colors to decorate underlines. Example: colorDecoration.red or decoration.red (using an alias).
  • Reset commands namespace:
    • reset - reset other SGR commands. Example: reset.all, reset.bold.

Namespaces effect only the next command. For example, fg.red will change the foreground to red but the next commands will be applied directly to the style itself.

Extended color namespace

Extended color namespace defines the following color helpers:

  • Standard colors:
    • black, red, green, yellow, blue, magenta, cyan, white, default.
    • The actual rendering of the above colors depends on an internal state defined by a possible bright or dark namespace.
  • Bright colors:
    • brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite.
    • These colors are always bright regardless of the current namespace.
  • Dark colors:
    • darkBlack, darkRed, darkGreen, darkYellow, darkBlue, darkMagenta, darkCyan, darkWhite.
    • These colors are always dark regardless of the current namespace.
  • Brightness namespaces:
    • bright - bright colors. Example: bright.red.
    • dark - dark colors. Example: dark.red.
  • default - the default color. Effectively it resets the color to the terminal's default.
  • Helpers for the 256 color mode:
    • color(c) - sets the color by an index.
    • stdRgb256(r, g, b), brightStdRgb256(r, g, b), darkStdRgb256(r, g, b) - sets the standard color by RGB values. RGB values are essentially boolean values.
    • rgb256(r, g, b) - sets the color by RGB values. Color components are in the range 0-255.
    • hex256(hex) - sets the color by a hex value (0xRRGGBB). Example: hex256(0xFF0000).
    • rgb6(r, g, b) - sets the color by RGB values. Color components are in the range 0-5.
    • grayscale256(gray) - sets the color by the grayscale value. The intensity component is in the range 0-255.
    • grayscale24(gray) - sets the color by the grayscale value. The intensity component is in the range 0-23.
  • Helpers for the true color mode:
    • trueColor(r, g, b) - sets the color by RGB values. Color components are in the range 0-255.
    • trueGrayscale(gray) - sets the color by the grayscale value. The intensity component is in the range 0-255.
    • hexTrueColor(hex) - sets the color by a hex value (0xRRGGBB). Example: hexTrueColor(0xFF0000).
  • Helpers for the composite color mode. It depends on the set color depth and selects the color mode (true color or 256-color) automatically:
    • rgb(r, g, b) - sets the color by RGB values. Color components are in the range 0-255.
    • grayscale(gray) - sets the color by the grayscale value. The intensity component is in the range 0-255.
    • hex(hex) - sets the color by a hex value (0xRRGGBB). Example: hex(0xFF0000).
  • Aliases:
    • stdRgb(r, g, b), brightStdRgb(r, g, b), darkStdRgb(r, g, b) - aliases for stdRgb256(), brightStdRgb256(), darkStdRgb256().

This namespace is used by the colorDecoration namespace and, indirectly, by the fg and bg namespaces.

Color namespace

Color namespace is based on the extended color namespace described above. It adds/redefines the following color helpers:

  • Standard colors:
    • stdRgb(r, g, b), brightStdRgb(r, g, b), darkStdRgb(r, g, b) - sets the standard color by RGB values. Unlike the extended color namespace, it doesn't use 256 colors but the standard color commands.

This namespace is used by the fg and bg namespaces.

Bright namespace

This namespace is used to make standard colors brighter. Using it opens up a color or an extended color (for colorDecoration) namespace.

Example: bright.red.

Dark namespace

This namespace is used to make standard colors darker. Using it opens up a color or an extended color (for colorDecoration) namespace.

Example: dark.red.

Reset namespace

This namespace defines commands, which can be reset:

  • Resettable SGR commands:
    • font, bold, dim, italic, underline, blink, rapidBlink, inverse, hidden, strikeThrough, curlyUnderline, doubleUnderline, color, bgColor overline, decorationColor. Example: reset.bold.
  • all - resets all the above. Example: reset.all.

Style namespace

This is the interface provided directly by the Style class:

  • constructor(initState, currentState = initState, colorDepth = 24) - creates a new style object.
    • The module provides a singleton exported as style and defined as new Style({}). Given that style objects are read-only it usually makes sense to use it as a starting point for all styling rather than creating a new object.
  • add(string) - adds SGR commands extracted from the string.
  • addState(state) - adds the state.
  • mark(fn) - marks the current state and calls a function with it.
  • getInitialState(fn) - if an optional function is provided, it is called with the initial state and the current style object is returned to continue chaining. Otherwise, the initial state is returned.
  • getState(fn) - if an optional function is provided, it is called with the current state and the current style object is returned to continue chaining. Otherwise, the current state is returned.
  • colorDepth - returns the current color depth. It can be 1, 4, 8, or 24.
  • setColorDepth(depth) - returns a new style object with the given color depth. It should be 1, 4, 8, or 24.
  • text(string) - returns the given string with the SGR commands applied.
  • toString() - returns the SGR commands as a string.
  • Namespaces mentioned above: fg, bg, bright, dark, reset, colorDecoration.
  • Color commands described in the color and the extended color namespaces. Used as is they will change the foreground color.
  • The color commands defined above prefixed with bg - used as is they will change the background color. Examples: bgRed, bgTrueColor(255, 0, 0).
  • Color commands defined in the extended color namespace prefixed with decoration - used as is they will change the decoration color (the underline color). Examples: decorationRed, decorationHex(0xFF0000).
  • Various aliases (see style.js for more details). The notable ones are:
    • brightBlack is aliased as grey and gray.
    • All grayXXX are aliased as greyXXX.
    • colorDecoration is aliased as decoration.
    • fg and bg are aliased as foreground and background.

Function s

The s function is a helper function for the Style class. It helps styling text. It is used as a back-quote function:

console.log(s`Hello, {{bold}}world{{reset.bold}}!`);

Static strings are interpolated using a mustache-like syntax ({{...}}). The commands inside are interpreted as Style commands described above. Only argument-less accessors are supported. If you need to use a method there is a way to do it.

Two pseudo-commands can be used with s: save and restore. save saves the current state on a stack. restore restores the state from the top of the stack. It can be used to modify the state and then return to the original state:

console.log(s`{{green}}Hello, {{save.resetAll.brightYellow.bgRed}}cruel{{restore}} world!`);

State commands can be chained but they cannot end in a namespace command. For example, this is not allowed: {{bright}}Hello{{red}}.

If an argument is a function, it is called with the current style object. The returned object should be a style object too:

console.log(s`Hello, ${style => style.hex(0xFF0000)}world!`);

const error = style.reset.all.bright.yellow.bg.red;
console.log(s`Hello, {{save}}${style => style.addState(error.getState())}world{{restore}}!`);

All other arguments will be converted to strings and inserted. They can contain SGR sequences.

Because Style defines toString(), its objects can be used to set state too:

const forceful = style.bold.black;
console.log(s`Hello, ${forceful}world!`);

By default, s uses {} as the initial state. It is possible to override it using the second form of s:

const text = s({initState: null, setState: style.red})`Danger, Will Robinson! Danger!`;

// or

const warning = s({initState: null, setState: style.red});
console.log(warning`Danger, Will Robinson! Danger!`);

Internally it creates a new style object and sets its states: new Style(initState, setState).

By the end of the string the current state will be continued:

console.log(s`Hello, {{red}}world!`, 'this will be red too');

One way to avoid that is to end with the explicit reset:

console.log(s`Hello, {{red}}world!{{reset.all}}`, 'not red anymore');

If you want to do it automatically reverting your style changes at the end of the string, use c.

Function c

c is exactly like s but it always resets the style at the end:

import {c} from 'console-toolkit/style.js';

console.log(c`Hello, {{red}}world!`, 'not red anymore');

Exports

The module exports the following names:

Name Description
RESET_STATE The reexport from ansi/sgr-state.js.
Style The main class.
style The singleton instance of the Style class.
s The s function.
c The c function.

style is defined as:

export const style = new Style({});

The default export is style.