2019-09-18 08:11:16 +00:00
|
|
|
'use strict';
|
2019-11-22 09:43:37 +00:00
|
|
|
var stripAnsi = require('strip-ansi');
|
|
|
|
var codePointAt = require('code-point-at');
|
|
|
|
var isFullwidthCodePoint = require('is-fullwidth-code-point');
|
2019-09-18 08:11:16 +00:00
|
|
|
|
2019-11-22 09:43:37 +00:00
|
|
|
// https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1345
|
|
|
|
module.exports = function (str) {
|
|
|
|
if (typeof str !== 'string' || str.length === 0) {
|
2019-09-18 08:11:16 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2019-11-22 09:43:37 +00:00
|
|
|
var width = 0;
|
2019-09-18 08:11:16 +00:00
|
|
|
|
2019-11-22 09:43:37 +00:00
|
|
|
str = stripAnsi(str);
|
2019-09-18 08:11:16 +00:00
|
|
|
|
2019-11-22 09:43:37 +00:00
|
|
|
for (var i = 0; i < str.length; i++) {
|
|
|
|
var code = codePointAt(str, i);
|
2019-09-18 08:11:16 +00:00
|
|
|
|
2019-11-22 09:43:37 +00:00
|
|
|
// ignore control characters
|
|
|
|
if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
|
2019-09-18 08:11:16 +00:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2019-11-22 09:43:37 +00:00
|
|
|
// surrogates
|
|
|
|
if (code >= 0x10000) {
|
2019-11-07 13:11:05 +00:00
|
|
|
i++;
|
2019-09-18 08:11:16 +00:00
|
|
|
}
|
2019-11-07 13:11:05 +00:00
|
|
|
|
2019-11-22 09:43:37 +00:00
|
|
|
if (isFullwidthCodePoint(code)) {
|
|
|
|
width += 2;
|
|
|
|
} else {
|
|
|
|
width++;
|
|
|
|
}
|
2019-09-18 08:11:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return width;
|
|
|
|
};
|