Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 19 additions & 12 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -290,10 +290,7 @@ function styleText(format, text, options) {

const formatArray = ArrayIsArray(format) ? format : [format];
const colors = inspect.colors;

let openCodes = '';
let closeCodes = '';
let processedText = text;
const styles = [];

for (const key of formatArray) {
if (key === 'none') continue;
Expand All @@ -305,25 +302,35 @@ function styleText(format, text, options) {
}
if (skipColorize) continue;
const { 0: r, 1: g, 2: b } = hexToRgb(key);
const hexOpenSeq = kEscape + rgbToAnsi24Bit(r, g, b) + kEscapeEnd;
openCodes += hexOpenSeq;
closeCodes = kHexCloseSeq + closeCodes;
processedText = replaceCloseCode(processedText, kHexCloseSeq, hexOpenSeq, false);
ArrayPrototypePush(styles, {
__proto__: null,
openSeq: kEscape + rgbToAnsi24Bit(r, g, b) + kEscapeEnd,
closeSeq: kHexCloseSeq,
keepClose: false,
});
continue;
}

const codes = colors[key];
if (!codes) {
validateOneOf(key, 'format', ObjectGetOwnPropertyNames(inspect.colors));
}
const { openSeq, closeSeq, keepClose } = codesToStyle(codes);
openCodes += openSeq;
closeCodes = closeSeq + closeCodes;
processedText = replaceCloseCode(processedText, closeSeq, openSeq, keepClose);
ArrayPrototypePush(styles, codesToStyle(codes));
}

if (skipColorize) return text;

let openCodes = '';
let closeCodes = '';
let processedText = text;
// Restore nested styles from the innermost format outward.
for (let i = styles.length - 1; i >= 0; i--) {
const { openSeq, closeSeq, keepClose } = styles[i];
openCodes = openSeq + openCodes;
closeCodes += closeSeq;
processedText = replaceCloseCode(processedText, closeSeq, openSeq, keepClose);
}

return `${openCodes}${processedText}${closeCodes}`;
}

Expand Down
21 changes: 21 additions & 0 deletions test/parallel/test-util-styletext-nested-array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';
require('../common');
const assert = require('node:assert');
const { styleText } = require('node:util');

// Closing a nested style must restore the outer formats in their original order.
const options = { validateStream: false };
for (const [first, second, nested] of [
['red', 'green', 'blue'],
['red', '#0f0', 'blue'],
['#f00', 'green', 'blue'],
['bgRed', 'bgGreen', 'bgBlue'],
['bold', 'dim', 'bold'],
]) {
const text = 'before' + styleText(nested, 'inside', options) + 'after';
assert.strictEqual(
styleText([first, second], text, options),
styleText(first, styleText(second, text, options), options),
`Restore ${first}, ${second} after ${nested}`,
);
}