Skip to content

Commit

Permalink
Code style tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Dec 26, 2018
1 parent 076f0c9 commit 587a5fb
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 49 deletions.
50 changes: 19 additions & 31 deletions index.js
@@ -1,8 +1,7 @@
'use strict';
const escapeStringRegexp = require('escape-string-regexp');
const ansiStyles = require('ansi-styles');
const stdoutColor = require('supports-color').stdout;

const {stdout: stdoutColor} = require('supports-color');
const template = require('./templates.js');

const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
Expand All @@ -15,15 +14,15 @@ const skipModels = new Set(['gray']);

const styles = Object.create(null);

function applyOptions(obj, options = {}) {
function applyOptions(object, options = {}) {
if (options.level > 3 || options.level < 0) {
throw new Error('The `level` option should be an integer from 0 to 3');
}

// Detect level if not set manually
const scLevel = stdoutColor ? stdoutColor.level : 0;
obj.level = options.level === undefined ? scLevel : options.level;
obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === undefined ? colorLevel : options.level;
object.enabled = 'enabled' in options ? options.enabled : object.level > 0;
}

function Chalk(options) {
Expand All @@ -33,7 +32,7 @@ function Chalk(options) {
const chalk = {};
applyOptions(chalk, options);

chalk.template = (...args) => chalkTag(...[chalk.template].concat(args));
chalk.template = (...args) => chalkTag(chalk.template, ...args);

Object.setPrototypeOf(chalk, Chalk.prototype);
Object.setPrototypeOf(chalk.template, chalk);
Expand All @@ -57,7 +56,7 @@ for (const key of Object.keys(ansiStyles)) {
styles[key] = {
get() {
const codes = ansiStyles[key];
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
return build.call(this, [...(this._styles || []), codes], this._empty, key);
}
};
}
Expand All @@ -84,7 +83,7 @@ for (const model of Object.keys(ansiStyles.color.ansi)) {
close: ansiStyles.color.close,
closeRe: ansiStyles.color.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
return build.call(this, [...(this._styles || []), codes], this._empty, model);
};
}
};
Expand All @@ -107,7 +106,7 @@ for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
close: ansiStyles.bgColor.close,
closeRe: ansiStyles.bgColor.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
return build.call(this, [...(this._styles || []), codes], this._empty, model);
};
}
};
Expand Down Expand Up @@ -153,23 +152,10 @@ function build(_styles, _empty, key) {
}

function applyStyle(...args) {
// Support varags, but simply cast to string in case there's only one arg
const argsLen = args.length;
let str = String(args[0]);

if (argsLen === 0) {
return '';
}

if (argsLen > 1) {
// Don't slice `arguments`, it prevents V8 optimizations
for (let a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
let string = args.join(' ');

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

// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
Expand All @@ -184,18 +170,18 @@ function applyStyle(...args) {
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
string = code.open + string.replace(code.closeRe, code.open) + code.close;

// Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS
// https://github.com/chalk/chalk/pull/92
str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
string = string.replace(/\r?\n/g, `${code.close}$&${code.open}`);
}

// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
ansiStyles.dim.open = originalDim;

return str;
return string;
}

function chalkTag(chalk, ...strings) {
Expand All @@ -211,8 +197,10 @@ function chalkTag(chalk, ...strings) {
const parts = [firstString.raw[0]];

for (let i = 1; i < firstString.length; i++) {
parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
parts.push(String(firstString.raw[i]));
parts.push(
String(args[i - 1]).replace(/[{}\\]/g, '\\$&'),
String(firstString.raw[i])
);
}

return template(chalk, parts.join(''));
Expand Down
40 changes: 22 additions & 18 deletions templates.js
Expand Up @@ -31,10 +31,11 @@ function parseArguments(name, args) {
let matches;

for (const chunk of chunks) {
if (!isNaN(chunk)) {
results.push(Number(chunk));
const number = Number(chunk);
if (!Number.isNaN(number)) {
results.push(number);
} else if ((matches = chunk.match(STRING_REGEX))) {
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
} else {
throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
}
Expand Down Expand Up @@ -73,17 +74,20 @@ function buildStyle(chalk, styles) {
}

let current = chalk;
// TODO: Use `Object.entries` when targeting Node.js 8
for (const styleName of Object.keys(enabled)) {
if (Array.isArray(enabled[styleName])) {
if (!(styleName in current)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}
if (!Array.isArray(enabled[styleName])) {
continue;
}

if (enabled[styleName].length > 0) {
current = current[styleName](...enabled[styleName]);
} else {
current = current[styleName];
}
if (!(styleName in current)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}

if (enabled[styleName].length > 0) {
current = current[styleName](...enabled[styleName]);
} else {
current = current[styleName];
}
}

Expand All @@ -96,13 +100,13 @@ module.exports = (chalk, tmp) => {
let chunk = [];

// eslint-disable-next-line max-params
tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
if (escapeChar) {
chunk.push(unescape(escapeChar));
tmp.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
if (escapeCharacter) {
chunk.push(unescape(escapeCharacter));
} else if (style) {
const str = chunk.join('');
const string = chunk.join('');
chunk = [];
chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
styles.push({inverse, styles: parseStyle(style)});
} else if (close) {
if (styles.length === 0) {
Expand All @@ -113,7 +117,7 @@ module.exports = (chalk, tmp) => {
chunk = [];
styles.pop();
} else {
chunk.push(chr);
chunk.push(character);
}
});

Expand Down

0 comments on commit 587a5fb

Please sign in to comment.