summaryrefslogtreecommitdiff
path: root/src/utils/grid.ts
blob: 71370da39f73abee952f1684c5fc5b91d0ce8197 (plain)
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
import type { AnsiTermColor, Grid } from '@/types/grid';
import { getAnsiColorEscape, getAnsiEscapeCodeFromDiff } from './ansi';

const defaultColor: AnsiTermColor = { foreground: null, background: null };
export const gridFromAscii = (
    ascii: string,
    color: AnsiTermColor = defaultColor,
): Grid => {
    const lineWidth = Math.max(...ascii.split('\n').map((line) => line.length));
    return ascii.split('\n').map((line, y) =>
        line
            .split('')
            .map((char, x) => ({
                char,
                color,
                x,
                y,
            }))
            .concat(
                Array(lineWidth - line.length)
                    .fill(0)
                    .map((_, x) => ({
                        char: ' ',
                        color,
                        x: x + line.length,
                        y,
                    })),
            ),
    );
};

export const gridToAnsi = (grid: Grid) => {
    const reset: AnsiTermColor = { foreground: null, background: null };
    const { fg, bg } = getAnsiColorEscape(reset);
    const resetCode = `${fg}${bg}`;

    const rows = [];
    for (let y = 0; y < grid.length; y++) {
        let row = '';
        for (let x = 0; x < grid[y].length; x++) {
            const cell = grid[y][x];
            const previousColor = x > 0 ? grid[y][x - 1].color : reset;
            row +=
                getAnsiEscapeCodeFromDiff(previousColor, cell.color) +
                cell.char;
        }
        rows.push(row);
    }
    return resetCode + rows.join(resetCode + '\n');
};