11cb0ef41Sopenharmony_ci'use strict'; 21cb0ef41Sopenharmony_ciconst stripAnsi = require('strip-ansi'); 31cb0ef41Sopenharmony_ciconst isFullwidthCodePoint = require('is-fullwidth-code-point'); 41cb0ef41Sopenharmony_ciconst emojiRegex = require('emoji-regex'); 51cb0ef41Sopenharmony_ci 61cb0ef41Sopenharmony_ciconst stringWidth = string => { 71cb0ef41Sopenharmony_ci if (typeof string !== 'string' || string.length === 0) { 81cb0ef41Sopenharmony_ci return 0; 91cb0ef41Sopenharmony_ci } 101cb0ef41Sopenharmony_ci 111cb0ef41Sopenharmony_ci string = stripAnsi(string); 121cb0ef41Sopenharmony_ci 131cb0ef41Sopenharmony_ci if (string.length === 0) { 141cb0ef41Sopenharmony_ci return 0; 151cb0ef41Sopenharmony_ci } 161cb0ef41Sopenharmony_ci 171cb0ef41Sopenharmony_ci string = string.replace(emojiRegex(), ' '); 181cb0ef41Sopenharmony_ci 191cb0ef41Sopenharmony_ci let width = 0; 201cb0ef41Sopenharmony_ci 211cb0ef41Sopenharmony_ci for (let i = 0; i < string.length; i++) { 221cb0ef41Sopenharmony_ci const code = string.codePointAt(i); 231cb0ef41Sopenharmony_ci 241cb0ef41Sopenharmony_ci // Ignore control characters 251cb0ef41Sopenharmony_ci if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { 261cb0ef41Sopenharmony_ci continue; 271cb0ef41Sopenharmony_ci } 281cb0ef41Sopenharmony_ci 291cb0ef41Sopenharmony_ci // Ignore combining characters 301cb0ef41Sopenharmony_ci if (code >= 0x300 && code <= 0x36F) { 311cb0ef41Sopenharmony_ci continue; 321cb0ef41Sopenharmony_ci } 331cb0ef41Sopenharmony_ci 341cb0ef41Sopenharmony_ci // Surrogates 351cb0ef41Sopenharmony_ci if (code > 0xFFFF) { 361cb0ef41Sopenharmony_ci i++; 371cb0ef41Sopenharmony_ci } 381cb0ef41Sopenharmony_ci 391cb0ef41Sopenharmony_ci width += isFullwidthCodePoint(code) ? 2 : 1; 401cb0ef41Sopenharmony_ci } 411cb0ef41Sopenharmony_ci 421cb0ef41Sopenharmony_ci return width; 431cb0ef41Sopenharmony_ci}; 441cb0ef41Sopenharmony_ci 451cb0ef41Sopenharmony_cimodule.exports = stringWidth; 461cb0ef41Sopenharmony_ci// TODO: remove this in the next major version 471cb0ef41Sopenharmony_cimodule.exports.default = stringWidth; 48