Added chalk.parse function to style any string using html-like tags
Updated readme
This commit is contained in:
parent
4c3df88472
commit
bff57b7c0f
2 changed files with 47 additions and 0 deletions
|
|
@ -18,6 +18,25 @@ const levelMapping = [
|
|||
|
||||
const styles = Object.create(null);
|
||||
|
||||
function parseTaggedString(string) {
|
||||
const tagPattern = /\<([\w, '().]+)\>([\s\S]+)\<\/\w*\>/g;
|
||||
const callPattern = /\((.*)\)/;
|
||||
return string.replace(tagPattern, (_, color, text) => {
|
||||
let carbonate = chalk;
|
||||
color.split('.').forEach(c => {
|
||||
if (callPattern.test(c)) {
|
||||
const args = JSON.parse(`[${ callPattern.exec(c)[1].replace(/'/g, '"') }]`);
|
||||
c = /(\w+)/g.exec(c)[0];
|
||||
carbonate = carbonate[c] ? carbonate[c].apply(carbonate[c], args) : carbonate;
|
||||
} else {
|
||||
carbonate = carbonate[c] || carbonate;
|
||||
}
|
||||
});
|
||||
text = carbonate(text);
|
||||
return tagPattern.test(text) ? parseTaggedString(text) : text;
|
||||
});
|
||||
}
|
||||
|
||||
const applyOptions = (object, options = {}) => {
|
||||
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
|
||||
throw new Error('The `level` option should be an integer from 0 to 3');
|
||||
|
|
@ -49,6 +68,8 @@ const chalkFactory = options => {
|
|||
};
|
||||
|
||||
chalk.template.Instance = ChalkClass;
|
||||
|
||||
chalk.template.parse = parseTaggedString;
|
||||
|
||||
return chalk.template;
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue