ANSI styling for Deno
// TODO: the links may need to be changed.
import {
BackgroundCode, ForegroundCode, StyleCode, createStyle,
} from 'https://raw.githubusercontent.com/quilicicf/ColorMee/master/createStyle.ts';
import {
parse, applyStyle, StyleMode,
} from 'https://raw.githubusercontent.com/quilicicf/ColorMee/master/index.ts';
const boldCyanOnRed = createStyle({
foreground: ForegroundCode.Cyan,
background: BackgroundCode.Red,
style: StyleCode.Bold,
});
const parameter = 'this';
console.log(applyStyle(
parse`I'm styling ${parameter}, but not ${parameter}.`,
[ boldCyanOnRed, null /* Null style => no style */ ],
));
ℹ️ You can find more examples in 🔗 the tests
I was tired of reading the common pattern that mixes style and content and usually does not support batch (no-color/style) mode:
import { red, bold, blue } from 'anyLib';
console.log(`${red(commit.sha)} ${bold(blue(`<${commit.owner}>`))}`);
Compare to the following:
import { red, boldBlue } from './graphicalChart.ts'; // Codes are computed using createStyle or just strings
import { parse, applyStyle } from 'ColorMee'; // dummy URL, of course
const styleMode = computeStyleModeFromCliArgOrWhatever(); // Allows no-color mode
console.log(
applyStyle(parse`${commit.sha} ${`<${commit.author}>`}`, [ red, boldBlue ], styleMode)
);
I wrote this lib to have a lib that would allow theming for a CLI tool.
The idea is to support theming and batch-mode (understand a --no-color
mode).
index.ts
: apply styles on a template literalcreateStyle.ts
: create ANSI code with a user-friendly API. This does not need to be included in your code (it’s the heaviest module, you might want to watch bundle size) but can be used as a tool to create your templates for exampleloadTemplate.ts
: load a template and make sure it is consistent with a reference template. This allows you to create a default color scheme for your CLI tool and let anyone theme it by loading another templateThe only module that is required is the
applyStyle
module (inindex.ts
).
The goal is to follow the philosophy below:
IDE-integrated: uses real template literals!
simple: straight-forward API, I don’t handle the parsing!
maintainable: the whole algorithm is 40 lines long and annotated
efficient: the algorithm uses the smallest possible amount of ANSI codes
fail fast and hard: the lib throws ASAP if it finds an error
small:
Module | Bundled size | Minified size |
---|---|---|
applyStyle (index) | 1.6 Kb |
772.0 b |
createStyle | 5.4 Kb |
2.8 Kb |
loadTemplate | 784.0 b |
466.0 b |
My regrets:
runtypes
to check that the template conforms to the provided interface but no library of this type has been ported to Deno to my knowledge (although for runtypes
it seems to be happening)Author: quilicicf
Source Code: https://github.com/quilicicf/ColorMee
#deno #node #nodejs #javascript