11cb0ef41Sopenharmony_ci'use strict'
21cb0ef41Sopenharmony_civar stringWidth = require('string-width')
31cb0ef41Sopenharmony_civar stripAnsi = require('strip-ansi')
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_cimodule.exports = wideTruncate
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_cifunction wideTruncate (str, target) {
81cb0ef41Sopenharmony_ci  if (stringWidth(str) === 0) {
91cb0ef41Sopenharmony_ci    return str
101cb0ef41Sopenharmony_ci  }
111cb0ef41Sopenharmony_ci  if (target <= 0) {
121cb0ef41Sopenharmony_ci    return ''
131cb0ef41Sopenharmony_ci  }
141cb0ef41Sopenharmony_ci  if (stringWidth(str) <= target) {
151cb0ef41Sopenharmony_ci    return str
161cb0ef41Sopenharmony_ci  }
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_ci  // We compute the number of bytes of ansi sequences here and add
191cb0ef41Sopenharmony_ci  // that to our initial truncation to ensure that we don't slice one
201cb0ef41Sopenharmony_ci  // that we want to keep in half.
211cb0ef41Sopenharmony_ci  var noAnsi = stripAnsi(str)
221cb0ef41Sopenharmony_ci  var ansiSize = str.length + noAnsi.length
231cb0ef41Sopenharmony_ci  var truncated = str.slice(0, target + ansiSize)
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_ci  // we have to shrink the result to account for our ansi sequence buffer
261cb0ef41Sopenharmony_ci  // (if an ansi sequence was truncated) and double width characters.
271cb0ef41Sopenharmony_ci  while (stringWidth(truncated) > target) {
281cb0ef41Sopenharmony_ci    truncated = truncated.slice(0, -1)
291cb0ef41Sopenharmony_ci  }
301cb0ef41Sopenharmony_ci  return truncated
311cb0ef41Sopenharmony_ci}
32