summaryrefslogtreecommitdiff
path: root/src/utils/grid.ts
diff options
context:
space:
mode:
authorElizabeth Hunt <me@liz.coffee>2025-10-04 18:36:10 -0700
committerElizabeth Hunt <me@liz.coffee>2025-10-04 18:36:10 -0700
commit35add63ec4dce39710095f17abd86777de9e5b49 (patch)
tree1afdf952f310e09a663e85541474efdc95155a73 /src/utils/grid.ts
parent507c972ecafeceaf4f8962ad881f8fb50c9b86c1 (diff)
downloadansicolor-35add63ec4dce39710095f17abd86777de9e5b49.tar.gz
ansicolor-35add63ec4dce39710095f17abd86777de9e5b49.zip
Working history state
Diffstat (limited to 'src/utils/grid.ts')
-rw-r--r--src/utils/grid.ts50
1 files changed, 50 insertions, 0 deletions
diff --git a/src/utils/grid.ts b/src/utils/grid.ts
new file mode 100644
index 0000000..71370da
--- /dev/null
+++ b/src/utils/grid.ts
@@ -0,0 +1,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');
+};