• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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) return str
9  if (target <= 0) return ''
10  if (stringWidth(str) <= target) return str
11
12  // We compute the number of bytes of ansi sequences here and add
13  // that to our initial truncation to ensure that we don't slice one
14  // that we want to keep in half.
15  var noAnsi = stripAnsi(str)
16  var ansiSize = str.length + noAnsi.length
17  var truncated = str.slice(0, target + ansiSize)
18
19  // we have to shrink the result to account for our ansi sequence buffer
20  // (if an ansi sequence was truncated) and double width characters.
21  while (stringWidth(truncated) > target) {
22    truncated = truncated.slice(0, -1)
23  }
24  return truncated
25}
26