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'); };