Last active
January 15, 2022 20:07
-
-
Save pushkine/fcba6270a8c632136e444b642b69ba36 to your computer and use it in GitHub Desktop.
Styles and colors for CLIs in TypeScript. Try it on https://replit.com/@pushkine/ColdTautSpools#index.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** MIT License github.com/pushkine */ | |
export const color = (function <C extends readonly any[], M extends {}>(colors: C, mods: M) { | |
const fn = (c1: number, c2: number, str: string) => `\x1b[${c1}m${str}\x1b[${c2}m`; | |
const fnc = (c1: number, str: string) => fn(c1, 39, str.replace(/\x1b\[39m/g, `\x1b[${c1}m`)); | |
const obj = { unstyle: (str: string) => str.replace(/\x1b\[[0-9]{1,2}m/g, ""), grey: fnc.bind(null, 90) }; | |
for (let i = 0; i < colors.length; i++) obj[colors[i]] = fnc.bind(null, 30 + i); | |
for (const key in mods) obj["" + key] = fn.bind(null, mods[key][0], mods[key][1]); | |
return obj as { [K in C[any] | keyof M | keyof typeof obj]: (str: string) => string }; | |
})( | |
["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"] as const, | |
{ bold: [1, 22], italic: [3, 23], underline: [4, 24], hidden: [8, 28] } as const | |
); | |
// Usage | |
console.log( | |
color.yellow( | |
[ | |
color.cyan("[info]"), | |
color.bold(color.underline("Easy")), | |
color.magenta(`~Fancy~`), | |
color.blue(color.italic("type") + "safe"), | |
color.green("dependency-free"), | |
color.italic("logs!"), | |
color.grey(`+ more on ${color.underline("gist.github.com/pushkine")}`), | |
].join(" "), | |
), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment