summaryrefslogtreecommitdiff
path: root/web/src/components/grid/index.ts
blob: 0acace4147910edbe25c593dee7f5388fe41bece (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import h, { type CreateElement } from "../../html";
import cellAtCoord from "./cellAtCoord";
import drawGrid from "./drawGrid";
import "./index.css";

class NotiveGridElement extends HTMLElement {
  #gridId!: string;

  get gridId() {
    return this.#gridId;
  }

  set gridId(val: string) {
    this.#gridId = val;
    this.setAttribute("grid-id", val);
  }

  get renderedGrid() {
    return window.notive.getGrid(this.#gridId)!;
  }

  canvasEl: HTMLCanvasElement = h.canvas();

  connectedCallback() {
    if (!this.gridId) {
      throw new Error("ntv-grid requries gridId attribute");
    }

    this.canvasEl.addEventListener("mousedown", (event) => {
      const clientRect = this.canvasEl.getBoundingClientRect();
      const x = event.x - clientRect.x;
      const y = event.y - clientRect.y;
      const cellRef = cellAtCoord(this.renderedGrid, x, y);
      if (!cellRef) return;
      window.notive.selectCell(this.#gridId, cellRef);
    });

    window.addEventListener("ntv:selection-changed", () => {
      this.draw();
    });

    this.append(this.canvasEl);
    this.draw();
  }

  draw() {
    const ctx = this.canvasEl.getContext("2d");

    if (!ctx) throw new Error("Unable to get canvas context");

    const grid = window.notive.getGrid(this.gridId);

    if (!grid) return;

    this.canvasEl.setAttribute("width", grid.rect.width + "px");
    this.canvasEl.setAttribute("height", grid.rect.height + "px");

    drawGrid(
      ctx,
      grid,
      window.notive.selection,
      window.notive.pendingSelection,
    );
  }
}

customElements.define("ntv-grid", NotiveGridElement);

export default ((...args: any[]): NotiveGridElement =>
  (h as any)["ntv-grid"](...args)) as CreateElement<NotiveGridElement>;