From fcb9e0d1790b64a33f8f42c3e13901cc34135acb Mon Sep 17 00:00:00 2001 From: marco-ippolito Date: Mon, 11 Mar 2024 11:11:36 +0100 Subject: [PATCH] util: support array of formats in util.styelText --- doc/api/util.md | 5 +++-- lib/util.js | 16 ++++++++++++++++ test/parallel/test-util-styletext.js | 8 ++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/doc/api/util.md b/doc/api/util.md index 5839f74a6b9c29e..63c32a07c36efc5 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -1800,7 +1800,8 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); added: v21.7.0 --> -* `format` {string} A text format defined in `util.inspect.colors`. +* `format` {string | Array} A text format or an Array + of text formats defined in `util.inspect.colors`. * `text` {string} The text to to be formatted. This function returns a formatted text considering the `format` passed. @@ -1822,7 +1823,7 @@ console.log(errorMessage); ```cjs console.log( - util.styleText('underline', util.styleText('italic', 'My italic underlined message')), + util.styleText(['underline', 'italic'], 'My italic underlined message'), ); ``` diff --git a/lib/util.js b/lib/util.js index e958f27cd5a1f6a..15136c2c6d3ab11 100644 --- a/lib/util.js +++ b/lib/util.js @@ -205,6 +205,22 @@ function pad(n) { */ function styleText(format, text) { validateString(text, 'text'); + + if (ArrayIsArray(format) && format.length > 0) { + let formatCodes = ''; + let append = ''; + for (const f of format) { + const formatCode = inspect.colors[f]; + if (formatCode == null) { + validateOneOf(f, 'format', ObjectKeys(inspect.colors)); + } + formatCodes += `\u001b[${formatCode[0]}m`; + append += `\u001b[${formatCode[1]}m`; + } + + return `${formatCodes}${text}${append}`; + } + const formatCodes = inspect.colors[format]; if (formatCodes == null) { validateOneOf(format, 'format', ObjectKeys(inspect.colors)); diff --git a/test/parallel/test-util-styletext.js b/test/parallel/test-util-styletext.js index 9436133916c58c5..261459f1736e958 100644 --- a/test/parallel/test-util-styletext.js +++ b/test/parallel/test-util-styletext.js @@ -33,3 +33,11 @@ assert.throws(() => { }); assert.strictEqual(util.styleText('red', 'test'), '\u001b[31mtest\u001b[39m'); + +assert.strictEqual(util.styleText(['red', 'bold'], 'test'), '\u001b[31m\u001b[1mtest\u001b[39m\u001b[22m'); + +assert.throws(() => { + util.styleText(['invalid'], 'text'); +}, { + code: 'ERR_INVALID_ARG_VALUE', +});