2.0.2 • Published 7 months ago

node-lienzo v2.0.2

Weekly downloads
-
License
ISC
Repository
github
Last release
7 months ago

Node Lienzo

The most powerful feature of this library the lienzo is the customizable console that helps to automate the process of output events from your application on a fluent way.

To install the lienzo library, run the following command in the console.

  npm install node-lienzo --save-dev

Or use it from the unpkg cdn as a simple script tag via the browser.

  <script src="https://unpkg.com/node-lienzo@2.0.2/umd/index.js"><script/>

Note All of the examples in this document uses ECMA syntax to import or export code from the library, but this supports CommonJS syntax as well.

// ECMA Syntax
import { createLienzo } from "node-lienzo";

// CommonJS Syntax
const { createLienzo } = require("node-lienzo");

Index

  1. Introduction
    1. Fore Ground Color Codes
    2. Text Format Codes
    3. Custom Color Codes
  2. What is the problem?
  3. General Concepts
    1. Printer Middleware
    2. Sessions
    3. Printables and Values
    4. Printables Queue
    5. Messages Queue
    6. RGB Object (RGB)
    7. RGB String (RGBS)
  4. Brush Options
    1. RGB Option
    2. Color Option
    3. Text Format Option
    4. Value Option
  5. Creating a lienzo object
    1. Printer Middleware Option
    2. Keep Format In Session Option
    3. Default Intensity Option
    4. Default Underline Option
    5. Reset After Print Option
  6. Default Pallet
    1. Supported Color Methods
  7. Creating Custom Colors
  8. Text Format
    1. Supported Text Format Methods
    2. Keep Option
  9. Spaces
    1. Iterations Option
    2. Queue A Value After A Space Sequence Option
  10. Painting
  11. Printing
  12. Register
    1. Push
    2. Un-Push
    3. Push Code
    4. Push Value
    5. Push Color
    6. Push RGB
    7. Paint
    8. Print
  13. Default Colors

Introduction

This code is meant to have more controls on creating log messages for the console of NodeJS, these are based on the ANSI Esacape Codes standard for 24-bit Consoles (https://en.wikipedia.org/wiki/ANSI_escape_code).

These codes are sequences of bytes such that they apply actions to the Console instead of printing values.

Foreground Color Codes

These codes modify the foreground color of the console.

import { FgBlue } from "node-lienzo";

// Here the code makes the console to print in blue whatever it followed this
console.log(`${FgBlue}`);
variablecodecolor
FgBlack\x1b[30mblack
FgRed\x1b[31mred
FgGreen\x1b[32mgreen
FgYellow\x1b[33myellow
FgBlue\x1b[34mblue
FgMagenta\x1b[35mmagenta
FgCyan\x1b[36mcyan
FgWhite\x1b[37mwhite

Text Format Codes

These codes modify the text format of the console.

import { FmBold } from "node-lienzo";
// Here the code makes the console to print in bold whatever it followed this
console.log(`${FmBold}`);
variablecodeformat
FmBold\x1b[1mbold
FmFaint\x1b[2mfaint
FmNoIntensity\x1b[22mno intensity
FmUnderline\x1b[4munerline
FmNoUnderline\x1b[24mno underline

Custom Color Codes

There is an special action to print customized colors in the console, being the sequences of characters \x1b[38;2;{r};{g};{b}m, where r,g and b stands for the red green and blue respectively from the RGB color schema.

import { toANSICode } from "node-lienzo";

// Here the function will create the code '\x1b[38;2;255;140;0m' that makes the console to print in orange whatever it followed this
const orange = toANSICode({
  red: 255,
  green: 140,
  blue: 0,
});
console.log(`${orange}`);

What is the problem?

In the ansi escape codes section is shown that a single output can be formatted alone with ansi codes, but imagine doing a long string like:

import {
  ExDefault, // To return console the default state
  FgBlue,
  FgGreen,
  FgRed,
  FmBold,
  FmNoIntensity,
  toANSICode,
} from "node-lienzo";

// Note how this is almost unreadable
console.log(
  `${FgBlue}information then ${FgGreen}success then ${FgRed}some error then ${toANSICode(
    { red: 177, green: 0, blue: 177 },
  )}purple message ${toANSICode({
    red: 202,
    green: 167,
    blue: 121,
  })}caki message${ExDefault}`,
);

Although this will have the desired output is not friendly readable and difficult to change on the future.

With lienzo this can be done in the following way:

import { createLienzo } from 'node-lienzo';

const lienzo = createLienzo().register(({pushRGB}) => {
    // You can add your customized functions
    caki(value) {
        return pushRGB("#CAA779", value);
    }
});

// Note how easy is now to understand what is happening
lienzo
    .blue("information then").space()
    .green("success then").space()
    .red("some error then").space()
    .rgb("#B100B1", "purple message").space() // Custom color on the fly
    .caki("caki message").space()
    .print(); // Session ended

General Concepts

Printer Middleware

Middleware is software that lies between an operating system and the applications running on it. Essentially a layer, enables communication and data management for distributed applications. (https://azure.microsoft.com/en-us/overview/what-is-middleware/).

In this case the printer middleware is the piece of codes that resolves the collected printables and messages.

Note If not assigned the createLienzo method will print the values using the default lienzo middleware.

Session

A session for lienzo is all the actions that are taken before releasing an output with the print method. When the print method is called all the values that had been accumulated in the queues will be resolved by the assigned printer middleware.

Note By default when a session ends all the colors and formats will be reset.

Printables and Values

A printable is any set of characters or codes to be consumed by a console that supports them, while in the other hand the values are just the objects or string accumulated during a session.

Printables Queue

This an array that contains all the values and actions that had been passed during the session and will be passed to the printer middleware to be resolved.

Messages Queue

This an array that contains all the values that had been passed during the session and will be passed to the printer middleware to be resolved.

RGB Object (RGB)

RGB (Red, Green, Blue) is a scheme where each letter represents a number from 0 to 255 where into the number is higher the more solid it is the color.

// RGB object
const rgb = {
  red: 57,
  green: 177,
  blue: 124,
};

RGB String (RGBS)

The RGB object can also be written into a string (RGBS) where begins with the '#' character followed by three hexadecimal numbers from 0 to FF ordered like #{Red}{Green}{Blue}.

// RGB String
const rgbs = "#a1B2c3";

Note The string is case insensitive.

Brush Options

These are options that are shared among multiple methods from any lienzo instance.

RGB Option (rgb)

An RGB string or object that sets the color from the session.

Color Option (color)

A ForegroundColor string that sets the color from the session.

Note Usually if the rgb option is set, the color option will be ignored.

Text Format Option (format)

A TextFormat string that sets the text format from the session.

Value Option (value)

Is the value to be pushed to the queues.

Creating a lienzo object

The lienzo object will contain by default methods to customize the output, they can be accessed from an instance created by the createLienzo method.

import { createLienzo } from "node-lienzo";

// The options are passed as the first parameter as an object
const lienzo = createLienzo({
  defaultIntensity: "bold",
  defaultUnderline: "underline",
});

Below is listed the options to customize a lienzo.

Printer Middleware Option (printerMiddleware)

This middleware will resolve the printables and messages queues to print them on a console. Must be a function that receives two string arrays, in the first argument will be the printables and in the second will be the messages queue. This function should return a string containing the processed printables

import { createLienzo } from 'node-lienzo';

// This custom middleware will take the printables array and process it
// to get an output that can be passed to the console.log method
// then returns the processed printables
const myCustomPrinterMiddleWare = function(printables: string[], messages: string[]) {
    const printable = printables.reduce((printable, value) => {
        if (typeof value === 'string') {
            return printable + value;
        } else {
            return printable + JSON.stringify(value);
        }
    },"");
    process.stdout.write(printable);
    return printable;
}

const lienzo = createLienzo({
    printermiddleware: myCustomPrinterMiddleWare
});

// printable --> "\x1b[31mred\x1b[34mblue\x1b[32mgreen\r\n\x1b[0m"
const printable = lienzo.paint("red").paint("green").paint("blue").print();

Keep Format In Session Option (keepFormatInSession)

When no keep flag is set when a text format is set, it will default to this value.

Default Intensity Option (defaultIntensity)

Each time the session resets its formats the default intensity will be taken from here.

Default Underline Option (defaultUnderline)

Each time the session resets its formats the default underline state will be taken from here.

Reset After Print Option (resetAfterPrint)

When this flag is set to false All the text format and colors will not be reset after the print method is called.

Default Pallet

Once created, the lienzo instance has a ready to use default pallet. Each of these methods can be used to set a color for the current session and the can receive a value to be printed in such selected color.

import { createLienzo } from "node-lienzo";
const lienzo = createLienzo();

// This will set for the current session the blue color
lienzo.blue();
// This will set for the current session the blue color and then print a value
lienzo.blue("message");

Supported Color Methods

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • orange
  • purple
  • teal
  • aqua

Creating Custom Colors

Once created, the lienzo instance will contain an rgb method that uses the rgb schema as first argument to create custom color codes that will be pushed to the printables queue. As second parameter if a string is passed will be pushed to the messages queue after the generated color code.

import { createLienzo } from "node-lienzo";
const lienzo = createLienzo();

// This will set for the current session the #a1b2c3 color
lienzo.rgb("#a1b2c3");

Text Format

Any lienzo instance has methods to control the text format from a session. Whe used with no arguments each of these methods will set the text format for the current session, but if they receive a string value they will apply that format to this and return to the previous state. For more advanced use an options object can be passed as an argument.

import { createLienzo } from "node-lienzo";
const lienzo = createLienzo();

// This will set for the current session the bold value
lienzo.bold();
// This will remove any intensity (bold, faint) from the session
lienzo.nointensity();

Note The bold and faint formats are intensities and they are mutually exclusive, so the nointensity method will remove either is applied in the moment.

Note The options that are not mentioned here are the same as brush options

Supported Text Format Methods

  • bold
  • faint
  • nointensity
  • underline
  • nounderline

Keep Option (keep)

When this flag is set to false The format will not persist in the session after the used text format method was called.

Spaces

Once created, the lienzo instance will contain functions to create spaces, tabs and lines in texts, these methods can be invoked with no arguments to only push to the printables and messages queues some spaces. When an argument of type numberis pass this will determine the nth times that a space sequence will be repeated. To more advanced use, an option object can be passed as the first argument.

import { createLienzo } from "node-lienzo";
const lienzo = createLienzo();

// It will add a single line to the queues
lienzo.line();
// It will add 2 tabs to the queues
lienzo.tab(2);

Note The options that are not mentioned here are the same as brush options

Iterations Option (iterations)

Determines the nth times that a sequence of spaces will be pushed to the printables and messages queues.

Queue A Value After A Space Sequence Option (queueValueAfterSpace)

When this option is set if is passed determines if the value should be placed after or before the space in the queues.

Painting

Once created, the lienzo instance will have a paint method that will always accept a first argument, if this is a string, this will be passed to the queues using any colors or formats so far in the session. If instead an options object is passed this let to create a customized behaviour for the current session.

import { createLienzo } from "node-lienzo";
const lienzo = createLienzo();

// It will send the string to the queues
lienzo.paint("message");
// It will send to the printables queue the generated
// code for the RGBS then pushes the value to the queues
lienzo.paint({
  rgb: "#a1B2c3",
  value: { key: "prop" },
});

Note The options that are not mentioned here are the same as brush options

Printing

Once created, the lienzo instance will have a print method. This more or less behaves at the beginning as the paint method but with the big difference that will call the assigned printer middleware, passing to it the printables and messages queues and finally return the processed printables.

If the option keepFormatInSession is false, will resets all the collected colors and formats from the session, otherwise they will be stored for future sessions.

import { createLienzo } from "node-lienzo";
const lienzo = createLienzo();

// It will send the string to the queues then print it
lienzo.print("message");
// It will send to the printables queue the generated RGBS code
// then pushes the value to the queues
// then prints the contents from the session
lienzo.print({
  rgb: "#a1B2c3",
  value: { key: "prop" },
});

Register

Sometimes a special combination of printables in a session may be repeated multiple times. To avoid this, exists the method register.

This method will create a new lienzo instance that includes all of the new customized patterns.

The registered pattern may return:

  • Nothing (i.e., a customized print option)
  • A string (i.e., a customized print option that returns a new processed value)
  • A lienzo instance (to continue the chain)
import { createLienzo } from 'node-lienzo';

const lienzo = createLienzo().register(({ pushRGB, print }) => {
    caki(value) {
        return pushRGB("#CAA779", value); // Continues the chain
    },
    printf(value) {
        return print(value);
    }
});

const printable = lienzo.caki('caki').printf('session');

To do so, this method will receive a callback function that sends as parameters a selection of brushes, that are functions that pushes content to the queues.

Note All of the methods mentioned below returns the lienzo instance, except for the print method that returns the processed printables.

Note For simplification, many of the examples omits the fact that whenever the print method is called, a new line will be added before resetting the values.

push(code, undefined | value)

Pushes to the printables queue the code then pushes to the printables and messages queues the value (if set).

import { FgBlue, createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(({ push }) => ({
  _push(value) {
    // Pushing code alone
    push(FgBlue);
    // Pushing code alone as the value is null
    push(FgBlue, null);
    return push(FgBlue, value); // Continues the chain
  },
}));

// printable --> '\x1b[34m\x1b[34m\x1b[34mvalue\x1b[0m'
const printable = lienzo._push("value").print();

Note Pushing a text format code has not keep flag control and may result in unexpected behaviour.

unpush(code, undefined | value)

Pushes to the printables and messages queues the value (if set) then pushes to the printables queue the code

import { FgBlue, createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(({ unpush }) => ({
  _unpush(value) {
    // unpushing code alone
    unpush(FgBlue);
    // unpushing code alone as the value is null
    unpush(FgBlue, null);
    return unpush(FgBlue, value); // Continues the chain
  },
}));

// printable --> '\x1b[34m\x1b[34mvalue\x1b[34m\x1b[0m'
const printable = lienzo._unpush("value").print();

Note Pushing a text format code has not keep flag control and may result in unexpected behaviour.

pushCode(code)

Pushes to the printables queue the code.

import { FgBlue, createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(({ pushCode }) => ({
  _pushCode(code) {
    return pushCode(code); // Continues the chain
  },
}));

// printable --> '\x1b[34m\x1b[0m'
const printable = lienzo._pushCode(FgBlue).print();

Note Pushing a text format code has not keep flag control and may result in unexpected behaviour.

pushValue(undefined | value)

Pushes to the printables and messages queues the value.

import { createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(({ pushValue }) => ({
  _pushValue(value) {
    return pushValue(value); // Continues the chain
  },
}));

// printable --> 'value\x1b[0m'
const printable = lienzo._pushValue("value").print();

pushColor(color, undefined | value)

Pushes to the printables queue the color then pushes to the printables and messages queue the value (if set).

List of possible color strings to push:

  • 'black'
  • 'red'
  • 'green'
  • 'yellow'
  • 'blue'
  • 'magenta'
  • 'cyan'
  • 'white'
  • 'orange'
  • 'purple'
  • 'teal'
  • 'aqua'
import { createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(({ pushColor }) => ({
  _pushColor(value) {
    // pushes color alone
    pushColor("blue");
    // pushes color alone as the value is null
    pushColor("blue", null);
    return pushColor("blue", value); // Continues the chain
  },
}));

// printable --> '\x1b[34m\x1b[34mvalue\x1b[34m\x1b[0m'
const printable = lienzo._pushColor("value").print();

pushRGB(rgb | rgbs, undefined | value)

Pushes to the printables queue the RGB string or object then pushes to the printables and messages queue the value (if set).

import { createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(({ pushRGB }) => ({
  _pushRGB(value) {
    const rgb = {
      red: 10,
      green: 20,
      blue: 30,
    };
    // pushes rgb alone
    pushRGB(rgb);
    // pushes rgb alone as the value is null
    pushRGB(rgb, null);
    return pushRGB(rgb, value); // Continues the chain
  },
  _pushRGBS(value) {
    const rgbs = "#102030";
    // pushes rgbs alone
    pushRGB(rgbs);
    // pushes rgbs alone as the value is null
    pushRGB(rgbs, null);
    return pushRGB(rgbs, value); // Continues the chain
  },
}));

// rgb_printable --> '\x1b[38;2;10;20;30m\x1b[38;2;10;20;30mvalue\x1b[38;2;10;20;30m\x1b[0m'
const rgb_printable = lienzo._pushRGB("value").print();
// rgbs_printable --> '\x1b[38;2;10;20;30m\x1b[38;2;10;20;30mvalue\x1b[38;2;10;20;30m\x1b[0m'
const rgbs_printable = lienzo._pushRGBS("value").print();

pushFormat(format, undefined | options)

Pushes to the printables queue the text format and uses the extra options (if set) to apply along with the text format.

List of possible format strings to push:

  • 'bold'
  • 'faint'
  • 'nointensity'
  • 'underline'
  • 'nounderline'
import { createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(({ pushFormat }) => ({
  _pushFormat(value) {
    // pushes format alone
    pushFormat("bold");
    // pushes format alone as the value is null
    pushFormat("bold", null);
    return pushFormat("bold", value); // Continues the chain
  },
}));

// printable --> '\x1b[1m\x1b[1mvalue\x1b[1m\x1b[0m'
const printable = lienzo._pushColor("value").print();

pushSpace(space, undefined | itearations | options)

Pushes to the queues the value (if set) then pushes a nth number of spaces to the queues based on the iterations value. If options are passed instead is used to make a customized result when pushing the space.

List of possible space strings to push:

  • 'space'
  • 'tab'
  • 'line'
import { createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(({ pushSpace }) => ({
  _pushSpace(value) {
    // pushes one line
    pushSpace("line");
    // pushes three times tab
    pushSpace("tab", 3);
    // pushes the value before the space
    return pushSpace("tab", {
      value,
      queueValueAfterSpace: false,
    }); // Continues the chain
  },
}));

// printable --> '\r\n\t\t\tvalue\t\x1b[0m'
const printable = lienzo._pushSpace("value").print();

Note If the queueValueAfterSpace flag is set to false the value will be pushed before the space(s) in the queues.

Note Uses the same options as any space function.

resets(undefined | value)

Resets all the current applied colors and text formats then pushes to the printables and messages queue the value if (set)

import { createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(
  ({ pushValue, pushFormat, pushColor, reset }) => ({
    _reset(value) {
      pushColor("blue");
      pushFormat("bold");
      reset();
      return pushValue("value"); // Continues the chain
    },
  }),
);

// printable --> '\x1b[34m\x1b[1m\x1b[0mvalue\x1b[0m'
const printable = lienzo._reset().print();

paint(string | options)

  • If the parameter is string prints a message using the all the previously applied formats.
  • If the parameter uses options applies from the options the formats and colors then pushes the value (if set)
import { createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(({ paint }) => ({
  _paint(value) {
    // It will send the string to the queues
    paint("message");
    // It will send to the printables queue the generated
    // code for the RGBS then pushes the value to the queues
    return paint({
      rgb: "#a1B2c3",
      value: { key: "prop" },
    }); // Continues the chain
  },
}));

// printable --> 'message\x1b[38;2;161;178;195m{"key":"prop"}\x1b[0m'
const printable = lienzo._paint().print();

Note Uses the same options as the paint function.

print(undefined | string | options)

  • If parametless prints the printables queue from the session and if the logger option resetAfterPrint is not set to false will reset all color and text formats.
  • If the parameter is string prints a message using the all the previously applied formats.
  • If the parameter uses options applies from the options the formats and colors or modifies the middleware behaviour after that pushes the value (if set) and finally prints the formatted string
import { createLienzo } from "node-lienzo";

const lienzo = createLienzo().register(
  ({ pushValue, pushFormat, pushColor, print }) => ({
    _printk(value) {
      return print({
        rgb: "#a1B2c3",
        value: { key: "prop" },
      }); // Return the processed values
    },
    _printf() {
      // It will print the value
      print("message");
    },
  }),
);

// printable --> '\x1b[38;2;161;178;195m{"key":"prop"}\x1b[0m'
const printable = lienzo._printk();

// printable --> 'message\x1b[0m'
const printable = lienzo._print();

Note Uses the same options as the print function.

Default Colors

These are RGB colors that are supported by default by lienzo and can be accessed using a function like lienzo.ichor(); to print a value with that color or by importing them like a foreground color like FgExIchor or as a background color like BgExIchor.

To check all the available colors to use go to the COLORS.html file.

2.0.2

7 months ago

2.0.1

7 months ago

2.0.0

7 months ago

1.3.0

1 year ago

1.2.2

2 years ago

1.2.1

2 years ago

1.2.0

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.2.4

2 years ago

0.2.3

2 years ago

0.2.2

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago