forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrap-text.ts
More file actions
74 lines (62 loc) · 1.76 KB
/
wrap-text.ts
File metadata and controls
74 lines (62 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import sliceAnsi from '../utils/sliceAnsi.js'
import { stringWidth } from './stringWidth.js'
import type { Styles } from './styles.js'
import { wrapAnsi } from './wrapAnsi.js'
const ELLIPSIS = '…'
// sliceAnsi may include a boundary-spanning wide char (e.g. CJK at position
// end-1 with width 2 overshoots by 1). Retry with a tighter bound once.
function sliceFit(text: string, start: number, end: number): string {
const s = sliceAnsi(text, start, end)
return stringWidth(s) > end - start ? sliceAnsi(text, start, end - 1) : s
}
function truncate(
text: string,
columns: number,
position: 'start' | 'middle' | 'end',
): string {
if (columns < 1) return ''
if (columns === 1) return ELLIPSIS
const length = stringWidth(text)
if (length <= columns) return text
if (position === 'start') {
return ELLIPSIS + sliceFit(text, length - columns + 1, length)
}
if (position === 'middle') {
const half = Math.floor(columns / 2)
return (
sliceFit(text, 0, half) +
ELLIPSIS +
sliceFit(text, length - (columns - half) + 1, length)
)
}
return sliceFit(text, 0, columns - 1) + ELLIPSIS
}
export default function wrapText(
text: string,
maxWidth: number,
wrapType: Styles['textWrap'],
): string {
if (wrapType === 'wrap') {
return wrapAnsi(text, maxWidth, {
trim: false,
hard: true,
})
}
if (wrapType === 'wrap-trim') {
return wrapAnsi(text, maxWidth, {
trim: true,
hard: true,
})
}
if (wrapType!.startsWith('truncate')) {
let position: 'end' | 'middle' | 'start' = 'end'
if (wrapType === 'truncate-middle') {
position = 'middle'
}
if (wrapType === 'truncate-start') {
position = 'start'
}
return truncate(text, maxWidth, position)
}
return text
}