summaryrefslogtreecommitdiff
path: root/web/src/components/grid/index.ts
blob: 829a5118741497aeb011dd9fe6e51a9734516350 (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
import h, { type CreateElement } from "../../html";
import renderGrid from "./renderGrid";
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);
  }

  canvasEl: HTMLCanvasElement = h.canvas();

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

    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;
    const renderedGrid = renderGrid(grid);
    this.canvasEl.setAttribute("width", renderedGrid.rect.width + "px");
    this.canvasEl.setAttribute("height", renderedGrid.rect.height + "px");
    drawGrid(ctx, renderedGrid);
  }
}

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

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