70160
Ce
cel-tui / files
cel-tui / packages / core / src / width.ts
5.3 KB
1import { eastAsianWidth } from "get-east-asian-width"; 2 3const 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 */ 12export 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) { 24 const char = str[j]; 25 if (char === undefined) break; 26 const code = char.charCodeAt(0); 27 if (code >= 0x40 && code <= 0x7e) break; 28 j++; 29 } 30 if (j < str.length) 31 return { code: str.substring(pos, j + 1), length: j + 1 - pos }; 32 return null; 33 } 34 35 // OSC: ESC ] ... BEL or ESC ] ... ST 36 if (next === "]") { 37 let j = pos + 2; 38 while (j < str.length) { 39 if (str[j] === "\x07") 40 return { code: str.substring(pos, j + 1), length: j + 1 - pos }; 41 if (str[j] === "\x1b" && str[j + 1] === "\\") 42 return { code: str.substring(pos, j + 2), length: j + 2 - pos }; 43 j++; 44 } 45 return null; 46 } 47 48 // APC: ESC _ ... BEL or ESC _ ... ST 49 if (next === "_") { 50 let j = pos + 2; 51 while (j < str.length) { 52 if (str[j] === "\x07") 53 return { code: str.substring(pos, j + 1), length: j + 1 - pos }; 54 if (str[j] === "\x1b" && str[j + 1] === "\\") 55 return { code: str.substring(pos, j + 2), length: j + 2 - pos }; 56 j++; 57 } 58 return null; 59 } 60 61 return null; 62} 63 64// --- Grapheme width --- 65 66const zeroWidthRegex = 67 /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v; 68const leadingNonPrintingRegex = 69 /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v; 70const rgiEmojiRegex = /^\p{RGI_Emoji}$/v; 71 72function couldBeEmoji(segment: string): boolean { 73 const cp = segment.codePointAt(0); 74 if (cp === undefined) return false; 75 return ( 76 (cp >= 0x1f000 && cp <= 0x1fbff) || 77 (cp >= 0x2300 && cp <= 0x23ff) || 78 (cp >= 0x2600 && cp <= 0x27bf) || 79 (cp >= 0x2b50 && cp <= 0x2b55) || 80 segment.includes("\uFE0F") || 81 segment.length > 2 82 ); 83} 84 85/** 86 * Calculate the terminal width of a single grapheme cluster. 87 */ 88function graphemeWidth(segment: string): number { 89 if (zeroWidthRegex.test(segment)) return 0; 90 91 if (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) return 2; 92 93 const base = segment.replace(leadingNonPrintingRegex, ""); 94 const cp = base.codePointAt(0); 95 if (cp === undefined) return 0; 96 97 // Regional indicator symbols 98 if (cp >= 0x1f1e6 && cp <= 0x1f1ff) return 2; 99 100 let width = eastAsianWidth(cp); 101 102 if (segment.length > 1) { 103 for (const char of segment.slice(1)) { 104 const c = char.codePointAt(0); 105 if (c !== undefined && c >= 0xff00 && c <= 0xffef) { 106 width += eastAsianWidth(c); 107 } 108 } 109 } 110 111 return width; 112} 113 114// --- ASCII fast path --- 115 116function isPrintableAscii(str: string): boolean { 117 for (let i = 0; i < str.length; i++) { 118 const code = str.charCodeAt(i); 119 if (code < 0x20 || code > 0x7e) return false; 120 } 121 return true; 122} 123 124// --- Cache --- 125 126const TAB_STOP = 4; 127const WIDTH_CACHE_SIZE = 512; 128const widthCache = new Map<string, number>(); 129 130/** Clear the visible-width cache. Useful for cold-cache benchmarks. */ 131export function clearVisibleWidthCache(): void { 132 widthCache.clear(); 133} 134 135function tabWidthAtColumn(column: number): number { 136 return TAB_STOP - (column % TAB_STOP); 137} 138 139function stripAnsi(str: string): string { 140 if (!str.includes("\x1b")) { 141 return str; 142 } 143 144 let stripped = ""; 145 let i = 0; 146 while (i < str.length) { 147 const ansi = extractAnsiCode(str, i); 148 if (ansi) { 149 i += ansi.length; 150 continue; 151 } 152 stripped += str[i]; 153 i++; 154 } 155 156 return stripped; 157} 158 159/** 160 * Calculate the visible width of a string in terminal columns starting from a 161 * specific visual column. This only changes behavior for tab expansion. 162 */ 163export function visibleWidthFromColumn( 164 str: string, 165 startColumn: number, 166): number { 167 if (str.length === 0) return 0; 168 169 if (startColumn === 0 && isPrintableAscii(str)) { 170 return str.length; 171 } 172 173 if (startColumn === 0) { 174 const cached = widthCache.get(str); 175 if (cached !== undefined) return cached; 176 } 177 178 const clean = stripAnsi(str); 179 let width = 0; 180 181 for (const { segment } of segmenter.segment(clean)) { 182 if (segment === "\t") { 183 width += tabWidthAtColumn(startColumn + width); 184 continue; 185 } 186 width += graphemeWidth(segment); 187 } 188 189 if (startColumn === 0) { 190 if (widthCache.size >= WIDTH_CACHE_SIZE) { 191 const firstKey = widthCache.keys().next().value; 192 if (firstKey !== undefined) widthCache.delete(firstKey); 193 } 194 widthCache.set(str, width); 195 } 196 197 return width; 198} 199 200// --- Public API --- 201 202/** 203 * Calculate the visible width of a string in terminal columns. 204 * 205 * Handles ASCII (fast path), East Asian wide characters, emoji, 206 * ANSI escape sequences, zero-width characters, and tab expansion. 207 * 208 * @param str - The string to measure. 209 * @returns Width in terminal columns. 210 */ 211export function visibleWidth(str: string): number { 212 return visibleWidthFromColumn(str, 0); 213}