MCPcopy Create free account
hub / github.com/AnukarOP/claude-code-leaked / stringWidthJavaScript

Function stringWidthJavaScript

source code/ink/stringWidth.ts:22–92  ·  view source on GitHub ↗

* Fallback JavaScript implementation of stringWidth when Bun.stringWidth is not available. * * Get the display width of a string as it would appear in a terminal. * * This is a more accurate alternative to the string-width package that correctly handles * characters like ⚠ (U+26A0) which string

(str: string)

Source from the content-addressed store, hash-verified

20 * recommended by the Unicode standard for Western contexts.
21 */
22function stringWidthJavaScript(str: string): number {
23 if (typeof str !== 'string' || str.length === 0) {
24 return 0
25 }
26
27 // Fast path: pure ASCII string (no ANSI codes, no wide chars)
28 let isPureAscii = true
29 for (let i = 0; i < str.length; i++) {
30 const code = str.charCodeAt(i)
31 // Check for non-ASCII or ANSI escape (0x1b)
32 if (code >= 127 || code === 0x1b) {
33 isPureAscii = false
34 break
35 }
36 }
37 if (isPureAscii) {
38 // Count printable characters (exclude control chars)
39 let width = 0
40 for (let i = 0; i < str.length; i++) {
41 const code = str.charCodeAt(i)
42 if (code > 0x1f) {
43 width++
44 }
45 }
46 return width
47 }
48
49 // Strip ANSI if escape character is present
50 if (str.includes('\x1b')) {
51 str = stripAnsi(str)
52 if (str.length === 0) {
53 return 0
54 }
55 }
56
57 // Fast path: simple Unicode (no emoji, variation selectors, or joiners)
58 if (!needsSegmentation(str)) {
59 let width = 0
60 for (const char of str) {
61 const codePoint = char.codePointAt(0)!
62 if (!isZeroWidth(codePoint)) {
63 width += eastAsianWidth(codePoint, { ambiguousAsWide: false })
64 }
65 }
66 return width
67 }
68
69 let width = 0
70
71 for (const { segment: grapheme } of getGraphemeSegmenter().segment(str)) {
72 // Check for emoji first (most emoji sequences are width 2)
73 EMOJI_REGEX.lastIndex = 0
74 if (EMOJI_REGEX.test(grapheme)) {
75 width += getEmojiWidth(grapheme)
76 continue
77 }
78
79 // Calculate width for non-emoji graphemes

Callers

nothing calls this directly

Calls 5

needsSegmentationFunction · 0.85
isZeroWidthFunction · 0.85
getGraphemeSegmenterFunction · 0.85
getEmojiWidthFunction · 0.85
segmentMethod · 0.80

Tested by

no test coverage detected