From dab1de90bf61ee5f7d723c95c502b54f4c205074 Mon Sep 17 00:00:00 2001 From: Maxime Allanic Date: Mon, 27 Apr 2020 13:37:30 +0200 Subject: [PATCH] [ADD] nested calls template --- source/index.js | 30 +++++++++++++++++++++++++++--- test/template-literal.js | 8 ++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/source/index.js b/source/index.js index e3b2f16..032e6aa 100644 --- a/source/index.js +++ b/source/index.js @@ -135,9 +135,33 @@ const createStyler = (open, close, parent) => { const createBuilder = (self, _styler, _isEmpty) => { const 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(' ')); + if (arguments_.length === 1) { + return applyStyle(builder, String(arguments_[0])); + } + + const [firstString] = arguments_; + + if (!Array.isArray(firstString)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return applyStyle(builder, arguments_.join(' ')); + } + + arguments_ = arguments_.slice(1); + const parts = [firstString.raw[0]]; + + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } + + if (template === undefined) { + template = require('./templates'); + } + + return template(chalk, parts.join('')); }; // We alter the prototype because we must return a function, but there is diff --git a/test/template-literal.js b/test/template-literal.js index 98e01c6..ce0ded9 100644 --- a/test/template-literal.js +++ b/test/template-literal.js @@ -175,3 +175,11 @@ test('should allow bracketed Unicode escapes', t => { t.is(instance`This is a {bold \u{AB681}} test`, 'This is a \u001B[1m\u{AB681}\u001B[22m test'); t.is(instance`This is a {bold \u{10FFFF}} test`, 'This is a \u001B[1m\u{10FFFF}\u001B[22m test'); }); + +test('should support nested calls', t => { + const instance = new chalk.Instance({level: 3}); + const name = 'Sindre'; + const exclamation = 'Neat'; + const result = instance.bold`{bold Hello, {cyan.inverse ${name}!} This is a test. {green ${exclamation}!}}`; + t.is(result, '\u001B[1mHello, \u001B[22m\u001B[1m\u001B[36m\u001B[7mSindre!\u001B[27m\u001B[39m\u001B[22m\u001B[1m This is a test. \u001B[22m\u001B[1m\u001B[32mNeat!\u001B[39m\u001B[22m'); +});