(input: string)
| 70 | * when you need to process segments programmatically. |
| 71 | */ |
| 72 | export function parseAnsiSegments(input: string): AnsiSegment[] { |
| 73 | const segments: AnsiSegment[] = []; |
| 74 | let current: AnsiStyle = {}; |
| 75 | let pos = 0; |
| 76 | let textStart = 0; |
| 77 | |
| 78 | const push = (end: number) => { |
| 79 | const text = input.slice(textStart, end); |
| 80 | if (text) segments.push({ text, style: { ...current } }); |
| 81 | }; |
| 82 | |
| 83 | while (pos < input.length) { |
| 84 | const esc = input.indexOf("\x1b[", pos); |
| 85 | if (esc === -1) break; |
| 86 | push(esc); |
| 87 | |
| 88 | let seqEnd = esc + 2; |
| 89 | while (seqEnd < input.length && !/[A-Za-z]/.test(input[seqEnd])) seqEnd++; |
| 90 | const term = input[seqEnd]; |
| 91 | const params = input.slice(esc + 2, seqEnd).split(";").map(Number); |
| 92 | |
| 93 | if (term === "m") { |
| 94 | let i = 0; |
| 95 | while (i < params.length) { |
| 96 | const p = params[i]; |
| 97 | if (p === 0 || isNaN(p)) { current = {}; } |
| 98 | else if (p === 1) { current.bold = true; } |
| 99 | else if (p === 2) { current.dim = true; } |
| 100 | else if (p === 3) { current.italic = true; } |
| 101 | else if (p === 4) { current.underline = true; } |
| 102 | else if (p === 9) { current.strikethrough = true; } |
| 103 | else if (p === 22) { current.bold = false; current.dim = false; } |
| 104 | else if (p === 23) { current.italic = false; } |
| 105 | else if (p === 24) { current.underline = false; } |
| 106 | else if (p === 29) { current.strikethrough = false; } |
| 107 | else if (p >= 30 && p <= 37) { current.color = FG[p]; } |
| 108 | else if (p === 38) { |
| 109 | if (params[i+1] === 5 && params[i+2] !== undefined) { |
| 110 | current.color = get256Color(params[i+2]); i += 2; |
| 111 | } else if (params[i+1] === 2 && params[i+4] !== undefined) { |
| 112 | current.color = `rgb(${params[i+2]},${params[i+3]},${params[i+4]})`; i += 4; |
| 113 | } |
| 114 | } |
| 115 | else if (p === 39) { delete current.color; } |
| 116 | else if (p >= 40 && p <= 47) { current.background = BG[p]; } |
| 117 | else if (p === 48) { |
| 118 | if (params[i+1] === 5 && params[i+2] !== undefined) { |
| 119 | current.background = get256Color(params[i+2]); i += 2; |
| 120 | } else if (params[i+1] === 2 && params[i+4] !== undefined) { |
| 121 | current.background = `rgb(${params[i+2]},${params[i+3]},${params[i+4]})`; i += 4; |
| 122 | } |
| 123 | } |
| 124 | else if (p === 49) { delete current.background; } |
| 125 | else if (p >= 90 && p <= 97) { current.color = FG[p]; } |
| 126 | else if (p >= 100 && p <= 107) { current.background = BG[p]; } |
| 127 | i++; |
| 128 | } |
| 129 | } |
no test coverage detected