wishthis/node_modules/string-width/index.js

38 lines
741 B
JavaScript
Raw Normal View History

2022-01-21 08:28:41 +00:00
'use strict';
2022-04-08 10:55:35 +00:00
var stripAnsi = require('strip-ansi');
var codePointAt = require('code-point-at');
var isFullwidthCodePoint = require('is-fullwidth-code-point');
2022-01-21 08:28:41 +00:00
2022-04-08 10:55:35 +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) {
2022-01-21 08:28:41 +00:00
return 0;
}
2022-04-08 10:55:35 +00:00
var width = 0;
2022-04-07 07:06:43 +00:00
2022-04-08 10:55:35 +00:00
str = stripAnsi(str);
2022-01-21 08:28:41 +00:00
2022-04-08 10:55:35 +00:00
for (var i = 0; i < str.length; i++) {
var code = codePointAt(str, i);
2022-01-21 08:28:41 +00:00
2022-04-08 10:55:35 +00:00
// ignore control characters
if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
2022-01-21 08:28:41 +00:00
continue;
}
2022-04-08 10:55:35 +00:00
// surrogates
if (code >= 0x10000) {
2022-01-21 08:28:41 +00:00
i++;
}
2022-04-08 10:55:35 +00:00
if (isFullwidthCodePoint(code)) {
width += 2;
} else {
width++;
}
2022-01-21 08:28:41 +00:00
}
return width;
};