2019-09-18 08:11:16 +00:00
|
|
|
'use strict';
|
2019-11-07 13:11:05 +00:00
|
|
|
const stripAnsi = require('strip-ansi');
|
|
|
|
const isFullwidthCodePoint = require('is-fullwidth-code-point');
|
|
|
|
const emojiRegex = require('emoji-regex')();
|
2019-09-18 08:11:16 +00:00
|
|
|
|
2019-11-07 13:11:05 +00:00
|
|
|
module.exports = input => {
|
|
|
|
input = input.replace(emojiRegex, ' ');
|
|
|
|
|
|
|
|
if (typeof input !== 'string' || input.length === 0) {
|
2019-09-18 08:11:16 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2019-11-07 13:11:05 +00:00
|
|
|
input = stripAnsi(input);
|
2019-09-18 08:11:16 +00:00
|
|
|
|
2019-11-07 13:11:05 +00:00
|
|
|
let width = 0;
|
2019-09-18 08:11:16 +00:00
|
|
|
|
2019-11-07 13:11:05 +00:00
|
|
|
for (let i = 0; i < input.length; i++) {
|
|
|
|
const code = input.codePointAt(i);
|
2019-09-18 08:11:16 +00:00
|
|
|
|
2019-11-07 13:11:05 +00:00
|
|
|
// Ignore control characters
|
|
|
|
if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
|
2019-09-18 08:11:16 +00:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2019-11-07 13:11:05 +00:00
|
|
|
// Ignore combining characters
|
|
|
|
if (code >= 0x300 && code <= 0x36F) {
|
|
|
|
continue;
|
2019-09-18 08:11:16 +00:00
|
|
|
}
|
|
|
|
|
2019-11-07 13:11:05 +00:00
|
|
|
// Surrogates
|
|
|
|
if (code > 0xFFFF) {
|
|
|
|
i++;
|
2019-09-18 08:11:16 +00:00
|
|
|
}
|
2019-11-07 13:11:05 +00:00
|
|
|
|
|
|
|
width += isFullwidthCodePoint(code) ? 2 : 1;
|
2019-09-18 08:11:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return width;
|
|
|
|
};
|