This commit is contained in:
Yanis Benson 2019-06-29 13:40:13 +03:00
parent f58b05c399
commit e63d61d063
2 changed files with 45 additions and 36 deletions

View file

@ -3,6 +3,11 @@ const ansiStyles = require('ansi-styles');
const {stdout: stdoutColor} = require('supports-color');
const template = require('./templates.js');
const {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
} = require('./lib/util');
// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = [
'ansi',
@ -11,39 +16,6 @@ const levelMapping = [
'ansi16m'
];
const stringReplaceAll = (str, substr, replacer) => {
let idx = str.indexOf(substr);
if (idx === -1) {
return str;
}
const subLen = substr.length;
let end = 0;
let res = '';
do {
res += str.substr(end, idx - end) + replacer;
end = idx + subLen;
idx = str.indexOf(substr, end);
} while (idx !== -1);
res += str.substr(end);
return res;
};
const stringEncaseCRLFWithFirstIndex = (str, prefix, postfix, idx) => {
let end = 0;
let res = '';
do {
const gotCR = str[idx - 1] === '\r';
res += str.substr(end, (gotCR ? idx - 1 : idx) - end) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
end = idx + 1;
idx = str.indexOf('\n', end);
} while (idx !== -1);
res += str.substr(end);
return res;
};
// `color-convert` models to exclude from the Chalk API due to conflicts and such
const skipModels = new Set(['gray']);
@ -226,9 +198,9 @@ const applyStyle = (self, string) => {
// Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS
// https://github.com/chalk/chalk/pull/92
const lfIdx = string.indexOf('\n');
if (lfIdx !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIdx);
const lfIndex = string.indexOf('\n');
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;

37
lib/util.js Normal file
View file

@ -0,0 +1,37 @@
const stringReplaceAll = (string, substring, replacer) => {
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
const subLen = substring.length;
let end = 0;
let res = '';
do {
res += string.substr(end, index - end) + replacer;
end = index + subLen;
index = string.indexOf(substring, end);
} while (index !== -1);
res += string.substr(end);
return res;
};
const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
let end = 0;
let res = '';
do {
const gotCR = string[index - 1] === '\r';
res += string.substr(end, (gotCR ? index - 1 : index) - end) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
end = index + 1;
index = string.indexOf('\n', end);
} while (index !== -1);
res += string.substr(end);
return res;
};
module.exports = {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
};