summaryrefslogtreecommitdiff
path: root/apps/web/src/components/grid/drawGrid.ts
diff options
context:
space:
mode:
Diffstat (limited to 'apps/web/src/components/grid/drawGrid.ts')
-rw-r--r--apps/web/src/components/grid/drawGrid.ts91
1 files changed, 91 insertions, 0 deletions
diff --git a/apps/web/src/components/grid/drawGrid.ts b/apps/web/src/components/grid/drawGrid.ts
new file mode 100644
index 0000000..da83c8e
--- /dev/null
+++ b/apps/web/src/components/grid/drawGrid.ts
@@ -0,0 +1,91 @@
+import { RangeSelection, Selection } from "../../selection";
+import { CellRef } from "../../types";
+import { getRenderedCell, RenderedCell, RenderedGrid } from "./renderGrid";
+
+export interface GridStyles {
+ bgFill: string;
+ borderStroke: string;
+ cellStroke: string;
+ cellValueFont: string;
+ cellValueLineHeight: string;
+}
+
+function excursion(ctx: CanvasRenderingContext2D, f: () => void) {
+ ctx.save();
+ f();
+ ctx.restore();
+}
+
+function fillBackground(
+ ctx: CanvasRenderingContext2D,
+ styles: GridStyles,
+ grid: RenderedGrid,
+) {
+ ctx.clearRect(0, 0, grid.rect.width, grid.rect.height);
+ ctx.fillStyle = styles.bgFill;
+ ctx.fillRect(0, 0, grid.rect.width, grid.rect.height);
+}
+
+function strokeGrid(
+ ctx: CanvasRenderingContext2D,
+ styles: GridStyles,
+ grid: RenderedGrid,
+) {
+ ctx.strokeStyle = styles.borderStroke;
+ ctx.strokeRect(0.5, 0.5, grid.rect.width - 1, grid.rect.height - 1);
+}
+
+function strokeGridLines(
+ ctx: CanvasRenderingContext2D,
+ styles: GridStyles,
+ grid: RenderedGrid,
+) {
+ ctx.strokeStyle = styles.cellStroke;
+
+ grid.renderedRows.forEach((row, renderedRowIndex) => {
+ const isLastRow = renderedRowIndex === grid.renderedRows.length - 1;
+
+ row.renderedCells.forEach((cell, cellIndex) => {
+ const { topLeft, width, height } = cell.rect;
+ const isLastCell = cellIndex === row.renderedCells.length - 1;
+
+ ctx.strokeRect(
+ topLeft.x + 0.5,
+ topLeft.y + 0.5,
+ isLastCell ? width - 1 : width,
+ isLastRow ? height - 1 : height,
+ );
+ });
+ });
+}
+
+function drawCellValues(
+ ctx: CanvasRenderingContext2D,
+ styles: GridStyles,
+ grid: RenderedGrid,
+) {
+ grid.renderedRows.forEach((row) =>
+ row.renderedCells.forEach((cell) => {
+ if (!cell.value) return;
+ ctx.fillStyle = "white";
+ ctx.textAlign = "center";
+ ctx.font = styles.cellValueFont;
+ ctx.fillText(
+ cell.value,
+ cell.rect.center.x,
+ cell.rect.center.y + parseInt(styles.cellValueLineHeight) / 4,
+ );
+ }),
+ );
+}
+
+export default function drawGrid(
+ ctx: CanvasRenderingContext2D,
+ styles: GridStyles,
+ grid: RenderedGrid,
+) {
+ excursion(ctx, () => fillBackground(ctx, styles, grid));
+ excursion(ctx, () => strokeGridLines(ctx, styles, grid));
+ excursion(ctx, () => strokeGrid(ctx, styles, grid));
+ excursion(ctx, () => drawCellValues(ctx, styles, grid));
+}