@thi.ng/text-format
Version:
Customizable color text formatting with presets for ANSI & HTML
71 lines (70 loc) • 2.07 kB
JavaScript
import { memoizeO } from "@thi.ng/memoize/memoizeo";
import { defFormat } from "./format.js";
const ANSI_RESET = "\x1B[0m";
const ANSI_SYNC_START = "\x1BP=1s\x1B\\";
const ANSI_SYNC_END = "\x1BP=2s\x1B\\";
const ANSI_HOME = "\x1B[H";
const ANSI_HOME_LINE = "\x1B[0G";
const ANSI_HOME_PREV_LINE = "\x1B[1F";
const ANSI_CLEAR_SCREEN = "\x1B[2J";
const ANSI_CLEAR_LINE = "\x1B[2K";
const ANSI_FLAGS = ["", "1", "2", "1;2", "4", "1;4", "2;4", "1;2;4"];
const FMT_ANSI16 = {
format: (code, x) => FMT_ANSI16.start(code) + x + FMT_ANSI16.end,
start: memoizeO((x) => {
let res = [];
let y = x & 15;
y && res.push(29 + (x >> 4 & 1) * 60 + y);
y = x >> 5 & 15;
y && res.push(39 + (x >> 9 & 1) * 60 + y);
y = x >> 10;
y && res.push(ANSI_FLAGS[y]);
return "\x1B[" + res.join(";") + "m";
}),
end: ANSI_RESET,
prefix: ANSI_RESET,
suffix: "\n"
};
const FMT_ANSI256 = {
format: (code, x) => FMT_ANSI256.start(code) + x + FMT_ANSI256.end,
start: (x) => `\x1B[38;5;${x & 255};48;5;${x >>> 8}m`,
end: ANSI_RESET,
prefix: ANSI_RESET,
suffix: "\n",
zero: true
};
const F5 = 255 / 31;
const F6 = 255 / 63;
const FMT_ANSI565 = {
format: (code, x) => FMT_ANSI565.start(code) + x + FMT_ANSI565.end,
start: (x) => `\x1B[38;2;${(x >> 11 & 31) * F5 | 0};${(x >> 5 & 63) * F6 | 0};${(x & 31) * F5 | 0}m`,
end: ANSI_RESET,
prefix: ANSI_RESET,
suffix: "\n",
zero: true
};
const format256 = (fg, bg = 0) => (bg & 255) << 8 | fg & 255;
const format565 = (r, g, b) => r * 31 << 11 | g * 63 << 5 | b * 31;
const format565_8bit = (r, g, b) => r << 8 & 63488 | g << 3 & 2016 | b >> 3;
const defAnsi16 = (col) => defFormat(FMT_ANSI16, col);
const defAnsi256 = (col) => defFormat(FMT_ANSI256, col);
const defAnsi565 = (col) => defFormat(FMT_ANSI565, col);
export {
ANSI_CLEAR_LINE,
ANSI_CLEAR_SCREEN,
ANSI_HOME,
ANSI_HOME_LINE,
ANSI_HOME_PREV_LINE,
ANSI_RESET,
ANSI_SYNC_END,
ANSI_SYNC_START,
FMT_ANSI16,
FMT_ANSI256,
FMT_ANSI565,
defAnsi16,
defAnsi256,
defAnsi565,
format256,
format565,
format565_8bit
};