Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 1 | 'use strict'; |
| 2 | const stripAnsi = require('strip-ansi'); |
| 3 | const isFullwidthCodePoint = require('is-fullwidth-code-point'); |
Tim van der Lippe | d3425b9 | 2022-01-07 14:05:09 +0100 | [diff] [blame^] | 4 | const emojiRegex = require('emoji-regex'); |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 5 | |
Tim van der Lippe | d3425b9 | 2022-01-07 14:05:09 +0100 | [diff] [blame^] | 6 | const stringWidth = string => { |
| 7 | if (typeof string !== 'string' || string.length === 0) { |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 8 | return 0; |
| 9 | } |
| 10 | |
Tim van der Lippe | d3425b9 | 2022-01-07 14:05:09 +0100 | [diff] [blame^] | 11 | string = stripAnsi(string); |
| 12 | |
| 13 | if (string.length === 0) { |
| 14 | return 0; |
| 15 | } |
| 16 | |
| 17 | string = string.replace(emojiRegex(), ' '); |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 18 | |
| 19 | let width = 0; |
| 20 | |
Tim van der Lippe | d3425b9 | 2022-01-07 14:05:09 +0100 | [diff] [blame^] | 21 | for (let i = 0; i < string.length; i++) { |
| 22 | const code = string.codePointAt(i); |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 23 | |
| 24 | // Ignore control characters |
| 25 | if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { |
| 26 | continue; |
| 27 | } |
| 28 | |
| 29 | // Ignore combining characters |
| 30 | if (code >= 0x300 && code <= 0x36F) { |
| 31 | continue; |
| 32 | } |
| 33 | |
| 34 | // Surrogates |
| 35 | if (code > 0xFFFF) { |
| 36 | i++; |
| 37 | } |
| 38 | |
| 39 | width += isFullwidthCodePoint(code) ? 2 : 1; |
| 40 | } |
| 41 | |
| 42 | return width; |
| 43 | }; |
Tim van der Lippe | d3425b9 | 2022-01-07 14:05:09 +0100 | [diff] [blame^] | 44 | |
| 45 | module.exports = stringWidth; |
| 46 | // TODO: remove this in the next major version |
| 47 | module.exports.default = stringWidth; |