From 7d238e2ebb769996de7d7f273cc3d71afa4476ff Mon Sep 17 00:00:00 2001 From: Toon Baeyens Date: Mon, 30 Mar 2020 12:33:28 +0200 Subject: [PATCH] template literals with a style tag, fixes #341 --- source/index.js | 5 +++++ test/template-literal.js | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/source/index.js b/source/index.js index 53fcc16..73135fe 100644 --- a/source/index.js +++ b/source/index.js @@ -134,6 +134,11 @@ const createStyler = (open, close, parent) => { const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => { + if (Array.isArray(arguments_[0])) { + // Called as a template litteral, e.g. chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } + // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); diff --git a/test/template-literal.js b/test/template-literal.js index ece1428..dc4b67b 100644 --- a/test/template-literal.js +++ b/test/template-literal.js @@ -30,6 +30,14 @@ test('correctly perform template substitutions', t => { instance.bold('Hello,', instance.cyan.inverse(name + '!'), 'This is a') + ' test. ' + instance.green(exclamation + '!')); }); +test('correctly perform nested template substitutions', t => { + const instance = new chalk.Instance({level: 0}); + const name = 'Sindre'; + const exclamation = 'Neat'; + t.is(instance.bold`Hello, {cyan.inverse ${name}!} This is a` + ' test. ' + instance.green`${exclamation}!`, + instance.bold('Hello,', instance.cyan.inverse(name + '!'), 'This is a') + ' test. ' + instance.green(exclamation + '!')); +}); + test('correctly parse and evaluate color-convert functions', t => { const instance = new chalk.Instance({level: 3}); t.is(instance`{bold.rgb(144,10,178).inverse Hello, {~inverse there!}}`,