diff --git a/index.js b/index.js index 941a3204..90de595f 100644 --- a/index.js +++ b/index.js @@ -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; diff --git a/lib/util.js b/lib/util.js new file mode 100644 index 00000000..8ce11668 --- /dev/null +++ b/lib/util.js @@ -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 +};