diff --git a/packages/text-canvas/src/ansi.ts b/packages/text-canvas/src/ansi.ts index d1d87704c5..0e522b409f 100644 --- a/packages/text-canvas/src/ansi.ts +++ b/packages/text-canvas/src/ansi.ts @@ -26,3 +26,22 @@ export const FMT_ANSI16: StringFormat = { prefix: ANSI_RESET, suffix: "\n", }; + +export const FMT_ANSI256: StringFormat = { + start: (x: number) => `\x1b[38;5;${x & 0xff};48;5;${x >>> 16}m`, + end: ANSI_RESET, + prefix: ANSI_RESET, + suffix: "\n", +}; + +/** + * Takes 2 ANSI256 values and returns a combined 16bit format ID. + * + * @remarks + * https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit + * + * @param fg + * @param bg + */ +export const format256 = (fg: number, bg = 0) => + ((bg & 0xff) << 8) | (fg & 0xff); diff --git a/packages/text-canvas/src/html.ts b/packages/text-canvas/src/html.ts index e13ae932f1..7474eace59 100644 --- a/packages/text-canvas/src/html.ts +++ b/packages/text-canvas/src/html.ts @@ -1,8 +1,10 @@ import { memoize1 } from "@thi.ng/memoize"; +import { U8 } from "@thi.ng/strings"; import type { HtmlFormatOpts, StringFormat } from "./api"; /** - * Constructs an HTML formatter using given config options. + * Constructs an HTML formatter using given config options and for use w/ + * default format IDs only. * * @param opts */ @@ -34,8 +36,8 @@ export const formatHtml = ({ }); /** - * Preset HTML string formatter, generating `` elements with - * inline CSS. + * Preset HTML string formatter for use w/ default format IDs, generating + * `` elements with inline CSS. */ export const FMT_HTML_INLINE_CSS = formatHtml({ colors: [ @@ -66,8 +68,8 @@ export const FMT_HTML_INLINE_CSS = formatHtml({ }); /** - * Preset HTML formatter, generating `` elements with Tachyons CSS - * classes. + * Preset HTML formatter for use w/ default format IDs, generating `` + * elements with Tachyons CSS classes. */ export const FMT_HTML_TACHYONS = formatHtml({ colors: [ @@ -96,3 +98,36 @@ export const FMT_HTML_TACHYONS = formatHtml({ dim: "o-50", underline: "underline", }); + +const S5 = 255 / 31; +const S6 = 255 / 63; + +/** + * Higher order custom HTML formatter for 16bit (RGB565) colors (without + * additional formatting flags). By default assigns text color, but can be + * assigned to any CSS property via given `prop` argument. + * + * @param prop + */ +export const FMT_HTML_565 = (prop = "color"): StringFormat => ({ + start: memoize1( + (x) => + `` + ), + end: "", + prefix: "", + suffix: "
", +}); + +/** + * Takes normalized RGB values ([0..1] range) and converts them into an RGB565 + * value. Does NOT perform clipping. + * + * @param r + * @param g + * @param b + */ +export const format565 = (r: number, g: number, b: number) => + ((r * 0x1f) << 11) | ((g * 0x3f) << 5) | (b * 0x1f);