Add forceColor option to babel-code-frame (#4913)

This commit is contained in:
Joe Haddad
2016-12-01 23:43:08 -05:00
committed by Henry Zhu
parent b43191d402
commit 06820ca17d
3 changed files with 43 additions and 18 deletions

View File

@@ -40,3 +40,4 @@ name | type | default | description
highlightCode | boolean | `false` | Syntax highlight the code as JavaScript for terminals
linesAbove | number | 2 | The number of lines to show above the error
linesBelow | number | 3 | The number of lines to show below the error
forceColor | boolean | `false` | Forcibly syntax highlight the code as JavaScript (for non-terminals); overrides highlightCode

View File

@@ -1,25 +1,27 @@
import jsTokens from "js-tokens";
import esutils from "esutils";
import chalk from "chalk";
import Chalk from "chalk";
/**
* Chalk styles for token types.
*/
let defs = {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
// bracket: intentionally omitted.
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
gutter: chalk.grey,
marker: chalk.red.bold,
};
function getDefs(chalk) {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
// bracket: intentionally omitted.
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
gutter: chalk.grey,
marker: chalk.red.bold,
};
}
/**
* RegExp to test for newlines in terminal.
@@ -75,7 +77,7 @@ function getTokenType(match) {
* Highlight `text`.
*/
function highlight(text: string) {
function highlight(defs: Object, text: string) {
return text.replace(jsTokens, function (...args) {
let type = getTokenType(args);
let colorize = defs[type];
@@ -99,11 +101,16 @@ export default function (
): string {
colNumber = Math.max(colNumber, 0);
let highlighted = opts.highlightCode && chalk.supportsColor;
let highlighted = (opts.highlightCode && Chalk.supportsColor) || opts.forceColor;
let chalk = Chalk;
if (opts.forceColor) {
chalk = new Chalk.constructor({ enabled: true });
}
let maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
};
if (highlighted) rawLines = highlight(rawLines);
let defs = getDefs(chalk);
if (highlighted) rawLines = highlight(defs, rawLines);
let linesAbove = opts.linesAbove || 2;
let linesBelow = opts.linesBelow || 3;

View File

@@ -186,4 +186,21 @@ describe("babel-code-frame", function () {
" 8 | "
].join("\n"));
});
it("opts.forceColor", function() {
let marker = chalk.red.bold;
let gutter = chalk.grey;
let rawLines = [
"",
"",
"",
""
].join("\n");
assert.equal(codeFrame(rawLines, 3, null, { linesAbove: 1, linesBelow: 1, forceColor: true }), chalk.reset([
" " + gutter(" 2 | "),
marker(">") + gutter(" 3 | "),
" " + gutter(" 4 | ")
].join("\n")));
});
});