Skip to content

Commit

Permalink
Add .visible for emitting text only when enabled (fixes #192)
Browse files Browse the repository at this point in the history
  • Loading branch information
danthegoodman authored and Qix- committed Oct 24, 2017
1 parent 4372d27 commit dc092b4
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 1 deletion.
10 changes: 9 additions & 1 deletion index.js
Expand Up @@ -63,6 +63,13 @@ for (const key of Object.keys(ansiStyles)) {
};
}

styles.visible = {
get() {
this._emptyIfNotVisible = true;
return build.call(this, this._styles ? this._styles : [], 'visible');
}
};

ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
for (const model of Object.keys(ansiStyles.color.ansi)) {
if (skipModels.has(model)) {
Expand Down Expand Up @@ -116,6 +123,7 @@ function build(_styles, key) {
};

builder._styles = _styles;
builder._emptyIfNotVisible = this._emptyIfNotVisible;

const self = this;

Expand Down Expand Up @@ -167,7 +175,7 @@ function applyStyle() {
}

if (!this.enabled || this.level <= 0 || !str) {
return str;
return this._emptyIfNotVisible ? '' : str;
}

// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
Expand Down
1 change: 1 addition & 0 deletions readme.md
Expand Up @@ -170,6 +170,7 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
- `inverse`
- `hidden`
- `strikethrough` *(Not widely supported)*
- `visible` (Text is emitted only if enabled)

### Colors

Expand Down
24 changes: 24 additions & 0 deletions test/visible.js
@@ -0,0 +1,24 @@
import test from 'ava';

// Spoof supports-color
require('./_supports-color')(__dirname);

const m = require('..');

test('visible: normal output when enabled', t => {
const ctx = new m.constructor({level: 3, enabled: true});
t.is(ctx.visible.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(ctx.red.visible('foo'), '\u001B[31mfoo\u001B[39m');
});

test('visible: no output when disabled', t => {
const ctx = new m.constructor({level: 3, enabled: false});
t.is(ctx.red.visible('foo'), '');
t.is(ctx.visible.red('foo'), '');
});

test('visible: no output when level is too low', t => {
const ctx = new m.constructor({level: 0, enabled: true});
t.is(ctx.visible.red('foo'), '');
t.is(ctx.red.visible('foo'), '');
});
2 changes: 2 additions & 0 deletions types/index.d.ts
Expand Up @@ -49,6 +49,8 @@ export interface Chalk {
hidden: Chalk;
strikethrough: Chalk;

visible: Chalk;

black: Chalk;
red: Chalk;
green: Chalk;
Expand Down
4 changes: 4 additions & 0 deletions types/test.ts
Expand Up @@ -45,3 +45,7 @@ chalk.rgb(1, 14, 9).bgBlue('foo');
chalk.hsl(1, 14, 9).bgBlue('foo');
chalk.hsv(1, 14, 9).bgBlue('foo');
chalk.hwb(1, 14, 9).bgBlue('foo');

chalk.visible('foo');
chalk.red.visible('foo');
chalk.visible.red('foo');

0 comments on commit dc092b4

Please sign in to comment.