@@ -0,0 +1,174 @@
1+import { eastAsianWidth } from "get-east-asian-width";
2+
3+const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
4+
5+// --- ANSI escape extraction ---
6+
7+/**
8+ * Extract an ANSI escape sequence starting at `pos` in `str`.
9+ * Handles CSI (ESC [), OSC (ESC ]), and APC (ESC _) sequences.
10+ * Returns null if no escape sequence starts at `pos`.
11+ */
12+export function extractAnsiCode(
13+ str: string,
14+ pos: number,
15+): { code: string; length: number } | null {
16+ if (pos >= str.length || str[pos] !== "\x1b") return null;
17+
18+ const next = str[pos + 1];
19+
20+ // CSI: ESC [ ... <terminal byte>
21+ if (next === "[") {
22+ let j = pos + 2;
23+ while (j < str.length && !/[A-Za-z]/.test(str[j]!)) j++;
24+ if (j < str.length)
25+ return { code: str.substring(pos, j + 1), length: j + 1 - pos };
26+ return null;
27+ }
28+
29+ // OSC: ESC ] ... BEL or ESC ] ... ST
30+ if (next === "]") {
31+ let j = pos + 2;
32+ while (j < str.length) {
33+ if (str[j] === "\x07")
34+ return { code: str.substring(pos, j + 1), length: j + 1 - pos };
35+ if (str[j] === "\x1b" && str[j + 1] === "\\")
36+ return { code: str.substring(pos, j + 2), length: j + 2 - pos };
37+ j++;
38+ }
39+ return null;
40+ }
41+
42+ // APC: ESC _ ... BEL or ESC _ ... ST
43+ if (next === "_") {
44+ let j = pos + 2;
45+ while (j < str.length) {
46+ if (str[j] === "\x07")
47+ return { code: str.substring(pos, j + 1), length: j + 1 - pos };
48+ if (str[j] === "\x1b" && str[j + 1] === "\\")
49+ return { code: str.substring(pos, j + 2), length: j + 2 - pos };
50+ j++;
51+ }
52+ return null;
53+ }
54+
55+ return null;
56+}
57+
58+// --- Grapheme width ---
59+
60+const zeroWidthRegex =
61+ /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;
62+const leadingNonPrintingRegex =
63+ /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;
64+const rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
65+
66+function couldBeEmoji(segment: string): boolean {
67+ const cp = segment.codePointAt(0)!;
68+ return (
69+ (cp >= 0x1f000 && cp <= 0x1fbff) ||
70+ (cp >= 0x2300 && cp <= 0x23ff) ||
71+ (cp >= 0x2600 && cp <= 0x27bf) ||
72+ (cp >= 0x2b50 && cp <= 0x2b55) ||
73+ segment.includes("\uFE0F") ||
74+ segment.length > 2
75+ );
76+}
77+
78+/**
79+ * Calculate the terminal width of a single grapheme cluster.
80+ */
81+function graphemeWidth(segment: string): number {
82+ if (zeroWidthRegex.test(segment)) return 0;
83+
84+ if (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) return 2;
85+
86+ const base = segment.replace(leadingNonPrintingRegex, "");
87+ const cp = base.codePointAt(0);
88+ if (cp === undefined) return 0;
89+
90+ // Regional indicator symbols
91+ if (cp >= 0x1f1e6 && cp <= 0x1f1ff) return 2;
92+
93+ let width = eastAsianWidth(cp);
94+
95+ if (segment.length > 1) {
96+ for (const char of segment.slice(1)) {
97+ const c = char.codePointAt(0)!;
98+ if (c >= 0xff00 && c <= 0xffef) {
99+ width += eastAsianWidth(c);
100+ }
101+ }
102+ }
103+
104+ return width;
105+}
106+
107+// --- ASCII fast path ---
108+
109+function isPrintableAscii(str: string): boolean {
110+ for (let i = 0; i < str.length; i++) {
111+ const code = str.charCodeAt(i);
112+ if (code < 0x20 || code > 0x7e) return false;
113+ }
114+ return true;
115+}
116+
117+// --- Cache ---
118+
119+const WIDTH_CACHE_SIZE = 512;
120+const widthCache = new Map<string, number>();
121+
122+// --- Public API ---
123+
124+/**
125+ * Calculate the visible width of a string in terminal columns.
126+ *
127+ * Handles ASCII (fast path), East Asian wide characters, emoji,
128+ * ANSI escape sequences, and zero-width characters.
129+ *
130+ * @param str - The string to measure.
131+ * @returns Width in terminal columns.
132+ */
133+export function visibleWidth(str: string): number {
134+ if (str.length === 0) return 0;
135+
136+ // Fast path: pure printable ASCII
137+ if (isPrintableAscii(str)) return str.length;
138+
139+ // Check cache
140+ const cached = widthCache.get(str);
141+ if (cached !== undefined) return cached;
142+
143+ // Strip ANSI escapes
144+ let clean = str;
145+ if (clean.includes("\x1b")) {
146+ let stripped = "";
147+ let i = 0;
148+ while (i < clean.length) {
149+ const ansi = extractAnsiCode(clean, i);
150+ if (ansi) {
151+ i += ansi.length;
152+ continue;
153+ }
154+ stripped += clean[i];
155+ i++;
156+ }
157+ clean = stripped;
158+ }
159+
160+ // Sum grapheme widths
161+ let width = 0;
162+ for (const { segment } of segmenter.segment(clean)) {
163+ width += graphemeWidth(segment);
164+ }
165+
166+ // Cache
167+ if (widthCache.size >= WIDTH_CACHE_SIZE) {
168+ const firstKey = widthCache.keys().next().value;
169+ if (firstKey !== undefined) widthCache.delete(firstKey);
170+ }
171+ widthCache.set(str, width);
172+
173+ return width;
174+}