summaryrefslogtreecommitdiff
path: root/colors/main.ts
diff options
context:
space:
mode:
authorKitson Kelly <me@kitsonkelly.com>2018-12-19 15:30:44 +1100
committerRyan Dahl <ry@tinyclouds.org>2018-12-18 23:30:44 -0500
commita3d164df917536c702775af1937569825fc5ceaf (patch)
tree13442b0e8d95049d9220c4477e3da7a941768f1a /colors/main.ts
parent2d58da520fffaeaee1bceeb33b6e3dc339ea68a3 (diff)
Add colors module (denoland/deno_std#30)
Original: https://github.com/denoland/deno_std/commit/54787f172c62df7c98d8e9e534c40e317825e614
Diffstat (limited to 'colors/main.ts')
-rw-r--r--colors/main.ts33
1 files changed, 33 insertions, 0 deletions
diff --git a/colors/main.ts b/colors/main.ts
new file mode 100644
index 000000000..af4e1aace
--- /dev/null
+++ b/colors/main.ts
@@ -0,0 +1,33 @@
+// Copyright 2018 the Deno authors. All rights reserved. MIT license.
+import { styles } from "./styles.ts";
+
+type Styles = { readonly [S in keyof typeof styles]: Color };
+
+type Color = Styles & {
+ (str: string): string;
+};
+
+const styleStack: string[] = [];
+
+export const color = function color(str: string): string {
+ styleStack.reverse();
+ while (styleStack.length) {
+ const style = styleStack.pop();
+ const code = styles[style];
+ str = `${code.open}${str.replace(code.closeRe, code.open)}${
+ code.close
+ }`.replace(/\r?\n/g, `${code.close}$&${code.open}`);
+ }
+ return str;
+} as Color;
+
+for (const style of Object.keys(styles)) {
+ Object.defineProperty(color, style, {
+ get() {
+ styleStack.push(style);
+ return color;
+ },
+ enumerable: true,
+ configurable: false
+ });
+}