chalk 1.1.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/index.js +159 -61
  2. package/license +4 -16
  3. package/package.json +60 -68
  4. package/readme.md +165 -76
  5. package/templates.js +175 -0
package/index.js CHANGED
@@ -1,116 +1,214 @@
1
1
  'use strict';
2
- var escapeStringRegexp = require('escape-string-regexp');
3
- var ansiStyles = require('ansi-styles');
4
- var stripAnsi = require('strip-ansi');
5
- var hasAnsi = require('has-ansi');
6
- var supportsColor = require('supports-color');
7
- var defineProps = Object.defineProperties;
8
- var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM);
2
+ const escapeStringRegexp = require('escape-string-regexp');
3
+ const ansiStyles = require('ansi-styles');
4
+ const supportsColor = require('supports-color');
5
+
6
+ const template = require('./templates.js');
7
+
8
+ const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
9
+
10
+ // `supportsColor.level` → `ansiStyles.color[name]` mapping
11
+ const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
12
+
13
+ // `color-convert` models to exclude from the Chalk API due to conflicts and such
14
+ const skipModels = new Set(['gray']);
15
+
16
+ const styles = Object.create(null);
17
+
18
+ function applyOptions(obj, options) {
19
+ options = options || {};
20
+
21
+ // Detect level if not set manually
22
+ obj.level = options.level === undefined ? supportsColor.level : options.level;
23
+ obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
24
+ }
9
25
 
10
26
  function Chalk(options) {
11
- // detect mode if not set manually
12
- this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled;
27
+ // We check for this.template here since calling chalk.constructor()
28
+ // by itself will have a `this` of a previously constructed chalk object.
29
+ if (!this || !(this instanceof Chalk) || this.template) {
30
+ const chalk = {};
31
+ applyOptions(chalk, options);
32
+
33
+ chalk.template = function () {
34
+ const args = [].slice.call(arguments);
35
+ return chalkTag.apply(null, [chalk.template].concat(args));
36
+ };
37
+
38
+ Object.setPrototypeOf(chalk, Chalk.prototype);
39
+ Object.setPrototypeOf(chalk.template, chalk);
40
+
41
+ chalk.template.constructor = Chalk;
42
+
43
+ return chalk.template;
44
+ }
45
+
46
+ applyOptions(this, options);
13
47
  }
14
48
 
15
- // use bright blue on Windows as the normal blue color is illegible
49
+ // Use bright blue on Windows as the normal blue color is illegible
16
50
  if (isSimpleWindowsTerm) {
17
- ansiStyles.blue.open = '\u001b[94m';
51
+ ansiStyles.blue.open = '\u001B[94m';
18
52
  }
19
53
 
20
- var styles = (function () {
21
- var ret = {};
54
+ for (const key of Object.keys(ansiStyles)) {
55
+ ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
22
56
 
23
- Object.keys(ansiStyles).forEach(function (key) {
24
- ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
57
+ styles[key] = {
58
+ get() {
59
+ const codes = ansiStyles[key];
60
+ return build.call(this, this._styles ? this._styles.concat(codes) : [codes], key);
61
+ }
62
+ };
63
+ }
25
64
 
26
- ret[key] = {
27
- get: function () {
28
- return build.call(this, this._styles.concat(key));
29
- }
30
- };
31
- });
65
+ ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
66
+ for (const model of Object.keys(ansiStyles.color.ansi)) {
67
+ if (skipModels.has(model)) {
68
+ continue;
69
+ }
32
70
 
33
- return ret;
34
- })();
71
+ styles[model] = {
72
+ get() {
73
+ const level = this.level;
74
+ return function () {
75
+ const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
76
+ const codes = {
77
+ open,
78
+ close: ansiStyles.color.close,
79
+ closeRe: ansiStyles.color.closeRe
80
+ };
81
+ return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
82
+ };
83
+ }
84
+ };
85
+ }
35
86
 
36
- var proto = defineProps(function chalk() {}, styles);
87
+ ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
88
+ for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
89
+ if (skipModels.has(model)) {
90
+ continue;
91
+ }
37
92
 
38
- function build(_styles) {
39
- var builder = function () {
93
+ const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
94
+ styles[bgModel] = {
95
+ get() {
96
+ const level = this.level;
97
+ return function () {
98
+ const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
99
+ const codes = {
100
+ open,
101
+ close: ansiStyles.bgColor.close,
102
+ closeRe: ansiStyles.bgColor.closeRe
103
+ };
104
+ return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
105
+ };
106
+ }
107
+ };
108
+ }
109
+
110
+ const proto = Object.defineProperties(() => {}, styles);
111
+
112
+ function build(_styles, key) {
113
+ const builder = function () {
40
114
  return applyStyle.apply(builder, arguments);
41
115
  };
42
116
 
43
117
  builder._styles = _styles;
44
- builder.enabled = this.enabled;
45
- // __proto__ is used because we must return a function, but there is
118
+
119
+ const self = this;
120
+
121
+ Object.defineProperty(builder, 'level', {
122
+ enumerable: true,
123
+ get() {
124
+ return self.level;
125
+ },
126
+ set(level) {
127
+ self.level = level;
128
+ }
129
+ });
130
+
131
+ Object.defineProperty(builder, 'enabled', {
132
+ enumerable: true,
133
+ get() {
134
+ return self.enabled;
135
+ },
136
+ set(enabled) {
137
+ self.enabled = enabled;
138
+ }
139
+ });
140
+
141
+ // See below for fix regarding invisible grey/dim combination on Windows
142
+ builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
143
+
144
+ // `__proto__` is used because we must return a function, but there is
46
145
  // no way to create a function with a different prototype.
47
- /* eslint-disable no-proto */
48
- builder.__proto__ = proto;
146
+ builder.__proto__ = proto; // eslint-disable-line no-proto
49
147
 
50
148
  return builder;
51
149
  }
52
150
 
53
151
  function applyStyle() {
54
- // support varags, but simply cast to string in case there's only one arg
55
- var args = arguments;
56
- var argsLen = args.length;
57
- var str = argsLen !== 0 && String(arguments[0]);
152
+ // Support varags, but simply cast to string in case there's only one arg
153
+ const args = arguments;
154
+ const argsLen = args.length;
155
+ let str = argsLen !== 0 && String(arguments[0]);
58
156
 
59
157
  if (argsLen > 1) {
60
- // don't slice `arguments`, it prevents v8 optimizations
61
- for (var a = 1; a < argsLen; a++) {
158
+ // Don't slice `arguments`, it prevents V8 optimizations
159
+ for (let a = 1; a < argsLen; a++) {
62
160
  str += ' ' + args[a];
63
161
  }
64
162
  }
65
163
 
66
- if (!this.enabled || !str) {
164
+ if (!this.enabled || this.level <= 0 || !str) {
67
165
  return str;
68
166
  }
69
167
 
70
- var nestedStyles = this._styles;
71
- var i = nestedStyles.length;
72
-
73
168
  // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
74
169
  // see https://github.com/chalk/chalk/issues/58
75
170
  // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
76
- var originalDim = ansiStyles.dim.open;
77
- if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) {
171
+ const originalDim = ansiStyles.dim.open;
172
+ if (isSimpleWindowsTerm && this.hasGrey) {
78
173
  ansiStyles.dim.open = '';
79
174
  }
80
175
 
81
- while (i--) {
82
- var code = ansiStyles[nestedStyles[i]];
83
-
176
+ for (const code of this._styles.slice().reverse()) {
84
177
  // Replace any instances already present with a re-opening code
85
178
  // otherwise only the part of the string until said closing code
86
179
  // will be colored, and the rest will simply be 'plain'.
87
180
  str = code.open + str.replace(code.closeRe, code.open) + code.close;
181
+
182
+ // Close the styling before a linebreak and reopen
183
+ // after next line to fix a bleed issue on macOS
184
+ // https://github.com/chalk/chalk/pull/92
185
+ str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
88
186
  }
89
187
 
90
- // Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue.
188
+ // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
91
189
  ansiStyles.dim.open = originalDim;
92
190
 
93
191
  return str;
94
192
  }
95
193
 
96
- function init() {
97
- var ret = {};
194
+ function chalkTag(chalk, strings) {
195
+ const args = [].slice.call(arguments, 2);
98
196
 
99
- Object.keys(styles).forEach(function (name) {
100
- ret[name] = {
101
- get: function () {
102
- return build.call(this, [name]);
103
- }
104
- };
105
- });
197
+ if (!Array.isArray(strings)) {
198
+ return strings.toString();
199
+ }
200
+
201
+ const parts = [strings.raw[0]];
202
+
203
+ for (let i = 1; i < strings.length; i++) {
204
+ parts.push(args[i - 1].toString().replace(/[{}]/g, '\\$&'));
205
+ parts.push(strings.raw[i]);
206
+ }
106
207
 
107
- return ret;
208
+ return template(chalk, parts.join(''));
108
209
  }
109
210
 
110
- defineProps(Chalk.prototype, init());
211
+ Object.defineProperties(Chalk.prototype, styles);
111
212
 
112
- module.exports = new Chalk();
113
- module.exports.styles = ansiStyles;
114
- module.exports.hasColor = hasAnsi;
115
- module.exports.stripColor = stripAnsi;
213
+ module.exports = Chalk(); // eslint-disable-line new-cap
116
214
  module.exports.supportsColor = supportsColor;
package/license CHANGED
@@ -1,21 +1,9 @@
1
- The MIT License (MIT)
1
+ MIT License
2
2
 
3
3
  Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
4
4
 
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
11
6
 
12
- The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14
8
 
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
- THE SOFTWARE.
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json CHANGED
@@ -1,70 +1,62 @@
1
1
  {
2
- "name": "chalk",
3
- "version": "1.1.1",
4
- "description": "Terminal string styling done right. Much color.",
5
- "license": "MIT",
6
- "repository": "chalk/chalk",
7
- "maintainers": [
8
- "Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
9
- "Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)",
10
- "JD Ballard <i.am.qix@gmail.com> (github.com/qix-)"
11
- ],
12
- "engines": {
13
- "node": ">=0.10.0"
14
- },
15
- "scripts": {
16
- "test": "xo && mocha",
17
- "bench": "matcha benchmark.js",
18
- "coverage": "nyc npm test && nyc report",
19
- "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
20
- },
21
- "files": [
22
- "index.js"
23
- ],
24
- "keywords": [
25
- "color",
26
- "colour",
27
- "colors",
28
- "terminal",
29
- "console",
30
- "cli",
31
- "string",
32
- "str",
33
- "ansi",
34
- "style",
35
- "styles",
36
- "tty",
37
- "formatting",
38
- "rgb",
39
- "256",
40
- "shell",
41
- "xterm",
42
- "log",
43
- "logging",
44
- "command-line",
45
- "text"
46
- ],
47
- "dependencies": {
48
- "ansi-styles": "^2.1.0",
49
- "escape-string-regexp": "^1.0.2",
50
- "has-ansi": "^2.0.0",
51
- "strip-ansi": "^3.0.0",
52
- "supports-color": "^2.0.0"
53
- },
54
- "devDependencies": {
55
- "coveralls": "^2.11.2",
56
- "matcha": "^0.6.0",
57
- "mocha": "*",
58
- "nyc": "^3.0.0",
59
- "require-uncached": "^1.0.2",
60
- "resolve-from": "^1.0.0",
61
- "semver": "^4.3.3",
62
- "xo": "*"
63
- },
64
- "xo": {
65
- "envs": [
66
- "node",
67
- "mocha"
68
- ]
69
- }
2
+ "name": "chalk",
3
+ "version": "2.0.1",
4
+ "description": "Terminal string styling done right. Much color",
5
+ "license": "MIT",
6
+ "repository": "chalk/chalk",
7
+ "engines": {
8
+ "node": ">=4"
9
+ },
10
+ "scripts": {
11
+ "test": "xo && nyc mocha",
12
+ "bench": "matcha benchmark.js",
13
+ "coveralls": "nyc report --reporter=text-lcov | coveralls"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "templates.js"
18
+ ],
19
+ "keywords": [
20
+ "color",
21
+ "colour",
22
+ "colors",
23
+ "terminal",
24
+ "console",
25
+ "cli",
26
+ "string",
27
+ "str",
28
+ "ansi",
29
+ "style",
30
+ "styles",
31
+ "tty",
32
+ "formatting",
33
+ "rgb",
34
+ "256",
35
+ "shell",
36
+ "xterm",
37
+ "log",
38
+ "logging",
39
+ "command-line",
40
+ "text"
41
+ ],
42
+ "dependencies": {
43
+ "ansi-styles": "^3.1.0",
44
+ "escape-string-regexp": "^1.0.5",
45
+ "supports-color": "^4.0.0"
46
+ },
47
+ "devDependencies": {
48
+ "coveralls": "^2.11.2",
49
+ "import-fresh": "^2.0.0",
50
+ "matcha": "^0.7.0",
51
+ "mocha": "*",
52
+ "nyc": "^11.0.2",
53
+ "resolve-from": "^3.0.0",
54
+ "xo": "*"
55
+ },
56
+ "xo": {
57
+ "envs": [
58
+ "node",
59
+ "mocha"
60
+ ]
61
+ }
70
62
  }
package/readme.md CHANGED
@@ -1,7 +1,7 @@
1
1
  <h1 align="center">
2
2
  <br>
3
3
  <br>
4
- <img width="360" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
4
+ <img width="320" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
5
5
  <br>
6
6
  <br>
7
7
  <br>
@@ -9,10 +9,7 @@
9
9
 
10
10
  > Terminal string styling done right
11
11
 
12
- [![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk)
13
- [![Coverage Status](https://coveralls.io/repos/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/r/chalk/chalk?branch=master)
14
- [![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4)
15
-
12
+ [![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
16
13
 
17
14
  [colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough.
18
15
 
@@ -21,69 +18,97 @@
21
18
  ![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png)
22
19
 
23
20
 
24
- ## Why
21
+ ## Highlights
25
22
 
26
- - Highly performant
27
- - Doesn't extend `String.prototype`
28
23
  - Expressive API
24
+ - Highly performant
29
25
  - Ability to nest styles
30
- - Clean and focused
26
+ - [256/Truecolor color support](#256-and-truecolor-color-support)
31
27
  - Auto-detects color support
28
+ - Doesn't extend `String.prototype`
29
+ - Clean and focused
32
30
  - Actively maintained
33
- - [Used by ~4500 modules](https://www.npmjs.com/browse/depended/chalk) as of July 15, 2015
31
+ - [Used by ~17,000 packages](https://www.npmjs.com/browse/depended/chalk) as of June 20th, 2017
34
32
 
35
33
 
36
34
  ## Install
37
35
 
38
- ```
39
- $ npm install --save chalk
36
+ ```console
37
+ $ npm install chalk
40
38
  ```
41
39
 
42
40
 
43
41
  ## Usage
44
42
 
43
+ ```js
44
+ const chalk = require('chalk');
45
+
46
+ console.log(chalk.blue('Hello world!'));
47
+ ```
48
+
45
49
  Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
46
50
 
47
51
  ```js
48
- var chalk = require('chalk');
49
-
50
- // style a string
51
- chalk.blue('Hello world!');
52
+ const chalk = require('chalk');
53
+ const log = console.log;
52
54
 
53
- // combine styled and normal strings
54
- chalk.blue('Hello') + 'World' + chalk.red('!');
55
+ // Combine styled and normal strings
56
+ log(chalk.blue('Hello') + 'World' + chalk.red('!'));
55
57
 
56
- // compose multiple styles using the chainable API
57
- chalk.blue.bgRed.bold('Hello world!');
58
+ // Compose multiple styles using the chainable API
59
+ log(chalk.blue.bgRed.bold('Hello world!'));
58
60
 
59
- // pass in multiple arguments
60
- chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz');
61
+ // Pass in multiple arguments
62
+ log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
61
63
 
62
- // nest styles
63
- chalk.red('Hello', chalk.underline.bgBlue('world') + '!');
64
+ // Nest styles
65
+ log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
64
66
 
65
- // nest styles of the same type even (color, underline, background)
66
- chalk.green(
67
+ // Nest styles of the same type even (color, underline, background)
68
+ log(chalk.green(
67
69
  'I am a green line ' +
68
70
  chalk.blue.underline.bold('with a blue substring') +
69
71
  ' that becomes green again!'
70
- );
72
+ ));
73
+
74
+ // ES2015 template literal
75
+ log(`
76
+ CPU: ${chalk.red('90%')}
77
+ RAM: ${chalk.green('40%')}
78
+ DISK: ${chalk.yellow('70%')}
79
+ `);
80
+
81
+ // ES2015 tagged template literal
82
+ log(chalk`
83
+ CPU: {red ${cpu.totalPercent}%}
84
+ RAM: {green ${ram.used / ram.total * 100}%}
85
+ DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
86
+ `);
87
+
88
+ // Use RGB colors in terminal emulators that support it.
89
+ log(chalk.keyword('orange')('Yay for orange colored text!'));
90
+ log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
91
+ log(chalk.hex('#DEADED').bold('Bold gray!'));
71
92
  ```
72
93
 
73
- Easily define your own themes.
94
+ Easily define your own themes:
74
95
 
75
96
  ```js
76
- var chalk = require('chalk');
77
- var error = chalk.bold.red;
97
+ const chalk = require('chalk');
98
+
99
+ const error = chalk.bold.red;
100
+ const warning = chalk.keyword('orange');
101
+
78
102
  console.log(error('Error!'));
103
+ console.log(warning('Warning!'));
79
104
  ```
80
105
 
81
- Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data).
106
+ Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
82
107
 
83
108
  ```js
84
- var name = 'Sindre';
109
+ const name = 'Sindre';
85
110
  console.log(chalk.green('Hello %s'), name);
86
- //=> Hello Sindre
111
+ //=> 'Hello Sindre'
87
112
  ```
88
113
 
89
114
 
@@ -93,61 +118,46 @@ console.log(chalk.green('Hello %s'), name);
93
118
 
94
119
  Example: `chalk.red.bold.underline('Hello', 'world');`
95
120
 
96
- Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `Chalk.red.yellow.green` is equivalent to `Chalk.green`.
121
+ Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
97
122
 
98
123
  Multiple arguments will be separated by space.
99
124
 
100
125
  ### chalk.enabled
101
126
 
102
- Color support is automatically detected, but you can override it by setting the `enabled` property. You should however only do this in your own code as it applies globally to all chalk consumers.
127
+ Color support is automatically detected, as is the level (see `chalk.level`). However, if you'd like to simply enable/disable Chalk, you can do so via the `.enabled` property.
128
+
129
+ Chalk is enabled by default unless expicitly disabled via the constructor or `chalk.level` is `0`.
103
130
 
104
- If you need to change this in a reusable module create a new instance:
131
+ If you need to change this in a reusable module, create a new instance:
105
132
 
106
133
  ```js
107
- var ctx = new chalk.constructor({enabled: false});
134
+ const ctx = new chalk.constructor({enabled: false});
108
135
  ```
109
136
 
110
- ### chalk.supportsColor
111
-
112
- Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
113
-
114
- Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`.
115
-
116
- ### chalk.styles
137
+ ### chalk.level
117
138
 
118
- Exposes the styles as [ANSI escape codes](https://github.com/chalk/ansi-styles).
139
+ Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
119
140
 
120
- Generally not useful, but you might need just the `.open` or `.close` escape code if you're mixing externally styled strings with your own.
141
+ If you need to change this in a reusable module, create a new instance:
121
142
 
122
143
  ```js
123
- var chalk = require('chalk');
124
-
125
- console.log(chalk.styles.red);
126
- //=> {open: '\u001b[31m', close: '\u001b[39m'}
127
-
128
- console.log(chalk.styles.red.open + 'Hello' + chalk.styles.red.close);
144
+ const ctx = new chalk.constructor({level: 0});
129
145
  ```
130
146
 
131
- ### chalk.hasColor(string)
132
-
133
- Check whether a string [has color](https://github.com/chalk/has-ansi).
147
+ Levels are as follows:
134
148
 
135
- ### chalk.stripColor(string)
149
+ 0. All colors disabled
150
+ 1. Basic color support (16 colors)
151
+ 2. 256 color support
152
+ 3. Truecolor support (16 million colors)
136
153
 
137
- [Strip color](https://github.com/chalk/strip-ansi) from a string.
138
-
139
- Can be useful in combination with `.supportsColor` to strip color on externally styled text when it's not supported.
154
+ ### chalk.supportsColor
140
155
 
141
- Example:
156
+ Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
142
157
 
143
- ```js
144
- var chalk = require('chalk');
145
- var styledString = getText();
158
+ Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
146
159
 
147
- if (!chalk.supportsColor) {
148
- styledString = chalk.stripColor(styledString);
149
- }
150
- ```
160
+ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
151
161
 
152
162
 
153
163
  ## Styles
@@ -157,11 +167,11 @@ if (!chalk.supportsColor) {
157
167
  - `reset`
158
168
  - `bold`
159
169
  - `dim`
160
- - `italic` *(not widely supported)*
170
+ - `italic` *(Not widely supported)*
161
171
  - `underline`
162
172
  - `inverse`
163
173
  - `hidden`
164
- - `strikethrough` *(not widely supported)*
174
+ - `strikethrough` *(Not widely supported)*
165
175
 
166
176
  ### Colors
167
177
 
@@ -169,11 +179,19 @@ if (!chalk.supportsColor) {
169
179
  - `red`
170
180
  - `green`
171
181
  - `yellow`
172
- - `blue` *(on Windows the bright version is used as normal blue is illegible)*
182
+ - `blue` *(On Windows the bright version is used since normal blue is illegible)*
173
183
  - `magenta`
174
184
  - `cyan`
175
185
  - `white`
176
186
  - `gray`
187
+ - `blackBright`
188
+ - `redBright`
189
+ - `greenBright`
190
+ - `yellowBright`
191
+ - `blueBright`
192
+ - `magentaBright`
193
+ - `cyanBright`
194
+ - `whiteBright`
177
195
 
178
196
  ### Background colors
179
197
 
@@ -185,29 +203,100 @@ if (!chalk.supportsColor) {
185
203
  - `bgMagenta`
186
204
  - `bgCyan`
187
205
  - `bgWhite`
206
+ - `bgBlackBright`
207
+ - `bgRedBright`
208
+ - `bgGreenBright`
209
+ - `bgYellowBright`
210
+ - `bgBlueBright`
211
+ - `bgMagentaBright`
212
+ - `bgCyanBright`
213
+ - `bgWhiteBright`
214
+
215
+
216
+ ## Tagged template literal
217
+
218
+ Chalk can be used as a [tagged template literal](http://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
219
+
220
+ ```js
221
+ const chalk = require('chalk');
188
222
 
223
+ const miles = 18;
224
+ const calculateFeet = miles => miles * 5280;
225
+
226
+ console.log(chalk`
227
+ There are {bold 5280 feet} in a mile.
228
+ In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
229
+ `);
230
+ ```
231
+
232
+ Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
233
+
234
+ Template styles are chained exactly like normal Chalk styles. The following two statements are equivalent:
235
+
236
+ ```js
237
+ console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
238
+ console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
239
+ ```
189
240
 
190
- ## 256-colors
241
+ Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
191
242
 
192
- Chalk does not support anything other than the base eight colors, which guarantees it will work on all terminals and systems. Some terminals, specifically `xterm` compliant ones, will support the full range of 8-bit colors. For this the lower level [ansi-256-colors](https://github.com/jbnicolai/ansi-256-colors) package can be used.
243
+ All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
244
+
245
+
246
+ ## 256 and Truecolor color support
247
+
248
+ Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
249
+
250
+ Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
251
+
252
+ Examples:
253
+
254
+ - `chalk.hex('#DEADED').underline('Hello, world!')`
255
+ - `chalk.keyword('orange')('Some orange text')`
256
+ - `chalk.rgb(15, 100, 204).inverse('Hello!')`
257
+
258
+ Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
259
+
260
+ - `chalk.bgHex('#DEADED').underline('Hello, world!')`
261
+ - `chalk.bgKeyword('orange')('Some orange text')`
262
+ - `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
263
+
264
+ The following color models can be used:
265
+
266
+ - [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
267
+ - [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
268
+ - [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
269
+ - [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
270
+ - [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 1, 1).bold('Orange!')`
271
+ - [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hsl(32, 0, 50).bold('Orange!')`
272
+ - `ansi16`
273
+ - `ansi256`
193
274
 
194
275
 
195
276
  ## Windows
196
277
 
197
- If you're on Windows, do yourself a favor and use [`cmder`](http://bliker.github.io/cmder/) instead of `cmd.exe`.
278
+ If you're on Windows, do yourself a favor and use [`cmder`](http://cmder.net/) instead of `cmd.exe`.
198
279
 
199
280
 
200
281
  ## Related
201
282
 
202
283
  - [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
203
- - [ansi-styles](https://github.com/chalk/ansi-styles/) - ANSI escape codes for styling strings in the terminal
204
- - [supports-color](https://github.com/chalk/supports-color/) - Detect whether a terminal supports color
284
+ - [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
285
+ - [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
205
286
  - [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
206
287
  - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
207
288
  - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
208
289
  - [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
290
+ - [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
291
+ - [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
292
+
293
+
294
+ ## Maintainers
295
+
296
+ - [Sindre Sorhus](https://github.com/sindresorhus)
297
+ - [Josh Junon](https://github.com/qix-)
209
298
 
210
299
 
211
300
  ## License
212
301
 
213
- MIT © [Sindre Sorhus](http://sindresorhus.com)
302
+ MIT
package/templates.js ADDED
@@ -0,0 +1,175 @@
1
+ 'use strict';
2
+
3
+ function data(parent) {
4
+ return {
5
+ styles: [],
6
+ parent,
7
+ contents: []
8
+ };
9
+ }
10
+
11
+ const zeroBound = n => n < 0 ? 0 : n;
12
+ const lastIndex = a => zeroBound(a.length - 1);
13
+
14
+ const last = a => a[lastIndex(a)];
15
+
16
+ const takeWhileReverse = (array, predicate, start) => {
17
+ const out = [];
18
+
19
+ for (let i = start; i >= 0 && i <= start; i--) {
20
+ if (predicate(array[i])) {
21
+ out.unshift(array[i]);
22
+ } else {
23
+ break;
24
+ }
25
+ }
26
+
27
+ return out;
28
+ };
29
+
30
+ /**
31
+ * Checks if the character at position i in string is a normal character a.k.a a non control character.
32
+ * */
33
+ const isNormalCharacter = (string, i) => {
34
+ const char = string[i];
35
+ const backslash = '\\';
36
+
37
+ if (!(char === backslash || char === '{' || char === '}')) {
38
+ return true;
39
+ }
40
+
41
+ const n = i === 0 ? 0 : takeWhileReverse(string, x => x === '\\', zeroBound(i - 1)).length;
42
+
43
+ return n % 2 === 1;
44
+ };
45
+
46
+ const collectStyles = data => data ? collectStyles(data.parent).concat(data.styles) : ['reset'];
47
+
48
+ /**
49
+ * Computes the style for a given data based on it's style and the style of it's parent. Also accounts for !style styles
50
+ * which remove a style from the list if present.
51
+ * */
52
+ const sumStyles = data => {
53
+ const negateRegex = /^~.+/;
54
+ let out = [];
55
+
56
+ for (const style of collectStyles(data)) {
57
+ if (negateRegex.test(style)) {
58
+ const exclude = style.slice(1);
59
+ out = out.filter(x => x !== exclude);
60
+ } else {
61
+ out.push(style);
62
+ }
63
+ }
64
+
65
+ return out;
66
+ };
67
+
68
+ /**
69
+ * Takes a string and parses it into a tree of data objects which inherit styles from their parent.
70
+ * */
71
+ function parse(string) {
72
+ const root = data(null);
73
+ let pushingStyle = false;
74
+
75
+ let current = root;
76
+
77
+ for (let i = 0; i < string.length; i++) {
78
+ const char = string[i];
79
+
80
+ const addNormalCharacter = () => {
81
+ const lastChunk = last(current.contents);
82
+
83
+ if (typeof lastChunk === 'string') {
84
+ current.contents[lastIndex(current.contents)] = lastChunk + char;
85
+ } else {
86
+ current.contents.push(char);
87
+ }
88
+ };
89
+
90
+ if (pushingStyle) {
91
+ if (' \t'.indexOf(char) > -1) {
92
+ pushingStyle = false;
93
+ } else if (char === '\n') {
94
+ pushingStyle = false;
95
+ addNormalCharacter();
96
+ } else if (char === '.') {
97
+ current.styles.push('');
98
+ } else {
99
+ current.styles[lastIndex(current.styles)] = (last(current.styles) || '') + char;
100
+ }
101
+ } else if (isNormalCharacter(string, i)) {
102
+ addNormalCharacter();
103
+ } else if (char === '{') {
104
+ pushingStyle = true;
105
+ const nCurrent = data(current);
106
+ current.contents.push(nCurrent);
107
+ current = nCurrent;
108
+ } else if (char === '}') {
109
+ current = current.parent;
110
+ }
111
+ }
112
+
113
+ if (current !== root) {
114
+ throw new Error('literal template has an unclosed block');
115
+ }
116
+
117
+ return root;
118
+ }
119
+
120
+ /**
121
+ * Takes a tree of data objects and flattens it to a list of data objects with the inherited and negations styles
122
+ * accounted for.
123
+ * */
124
+ function flatten(data) {
125
+ let flat = [];
126
+
127
+ for (const content of data.contents) {
128
+ if (typeof content === 'string') {
129
+ flat.push({
130
+ styles: sumStyles(data),
131
+ content
132
+ });
133
+ } else {
134
+ flat = flat.concat(flatten(content));
135
+ }
136
+ }
137
+
138
+ return flat;
139
+ }
140
+
141
+ function assertStyle(chalk, style) {
142
+ if (!chalk[style]) {
143
+ throw new Error(`invalid Chalk style: ${style}`);
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Checks if a given style is valid and parses style functions.
149
+ * */
150
+ function parseStyle(chalk, style) {
151
+ const fnMatch = style.match(/^\s*(\w+)\s*\(\s*([^)]*)\s*\)\s*/);
152
+ if (!fnMatch) {
153
+ assertStyle(chalk, style);
154
+ return chalk[style];
155
+ }
156
+
157
+ const name = fnMatch[1].trim();
158
+ const args = fnMatch[2].split(/,/g).map(s => s.trim());
159
+
160
+ assertStyle(chalk, name);
161
+
162
+ return chalk[name].apply(chalk, args);
163
+ }
164
+
165
+ /**
166
+ * Performs the actual styling of the string, essentially lifted from cli.js.
167
+ * */
168
+ function style(chalk, flat) {
169
+ return flat.map(data => {
170
+ const fn = data.styles.reduce(parseStyle, chalk);
171
+ return fn(data.content.replace(/\n$/, ''));
172
+ }).join('');
173
+ }
174
+
175
+ module.exports = (chalk, string) => style(chalk, flatten(parse(string)));