1'use strict' 2var stringWidth = require('string-width') 3var stripAnsi = require('strip-ansi') 4 5module.exports = wideTruncate 6 7function wideTruncate (str, target) { 8 if (stringWidth(str) === 0) { 9 return str 10 } 11 if (target <= 0) { 12 return '' 13 } 14 if (stringWidth(str) <= target) { 15 return str 16 } 17 18 // We compute the number of bytes of ansi sequences here and add 19 // that to our initial truncation to ensure that we don't slice one 20 // that we want to keep in half. 21 var noAnsi = stripAnsi(str) 22 var ansiSize = str.length + noAnsi.length 23 var truncated = str.slice(0, target + ansiSize) 24 25 // we have to shrink the result to account for our ansi sequence buffer 26 // (if an ansi sequence was truncated) and double width characters. 27 while (stringWidth(truncated) > target) { 28 truncated = truncated.slice(0, -1) 29 } 30 return truncated 31} 32