@thi.ng/text-format
Version:
Customizable color text formatting with presets for ANSI & HTML
133 lines (132 loc) • 2.5 kB
JavaScript
import { U8 } from "@thi.ng/hex";
import { memoizeO } from "@thi.ng/memoize/memoizeo";
const F5 = 255 / 31;
const F6 = 255 / 63;
const formatHtml = ({
colors,
attrib,
delim,
fg,
bg,
bold,
dim,
underline
}) => {
const start = memoizeO((x) => {
let y = x & 15;
let res = `<span ${attrib}="${fg}${colors[y - 1 | x >> 1 & 8]}${delim}`;
y = x >> 5 & 15;
y && (res += `${bg}${colors[y - 1 | x >> 6 & 8]}${delim}`);
x & 1024 && (res += bold + delim);
x & 2048 && (res += dim + delim);
x & 4096 && (res += underline + delim);
return res + '">';
});
const end = "</span>";
return {
format: (code, x) => start(code) + x + end,
start,
end,
prefix: "",
suffix: "<br/>"
};
};
const FMT_HTML_INLINE_CSS = formatHtml({
colors: [
"#000",
"#a00",
"#0a0",
"#aa0",
"#00a",
"#a0a",
"#0aa",
"#aaa",
"#555",
"#f55",
"#5f5",
"#ff5",
"#55f",
"#f5f",
"#5ff",
"#fff"
],
attrib: "style",
delim: ";",
fg: "color:",
bg: "background:",
bold: "font-weight:bold",
dim: "opacity:0.5",
underline: "text-decoration:underline"
});
const TACHYON_COLORS = [
"black",
"dark-red",
"dark-green",
"gold",
"dark-blue",
"dark-pink",
"light-blue",
"moon-gray",
"mid-gray",
"red",
"green",
"yellow",
"blue",
"hot-pink",
"lightest-blue",
"white"
];
const FMT_HTML_TACHYONS = formatHtml({
colors: TACHYON_COLORS,
attrib: "class",
delim: " ",
fg: "",
bg: "bg-",
bold: "b",
dim: "o-50",
underline: "underline"
});
const FMT_HTML_MCSS = formatHtml({
colors: TACHYON_COLORS,
attrib: "class",
delim: " ",
fg: "color-",
bg: "bg-color-",
bold: "b",
dim: "o-50",
underline: "underline"
});
const FMT_HTML_CSS_VARS = (varNames) => formatHtml({
colors: varNames.map((x) => `var(--${x})`),
attrib: "style",
delim: ";",
fg: "color:",
bg: "background:",
bold: "font-weight:bold",
dim: "opacity:0.5",
underline: "text-decoration:underline"
});
const FMT_HTML565 = (prop = "color") => {
const start = memoizeO(
(x) => `<span style="${prop}:#${U8((x >> 11) * F5)}${U8(
(x >> 5 & 63) * F6
)}${U8((x & 31) * F5)}">`
);
const end = "</span>";
return {
format: (code, x) => start(code) + x + end,
start,
end,
prefix: "",
suffix: "<br/>",
zero: true
};
};
export {
FMT_HTML565,
FMT_HTML_CSS_VARS,
FMT_HTML_INLINE_CSS,
FMT_HTML_MCSS,
FMT_HTML_TACHYONS,
formatHtml
};