summaryrefslogtreecommitdiff
path: root/web/src/components/app/index.ts
blob: a2c0c9db29554ea7105b5b889c3e164f6d4576d9 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { produce } from "immer";
import defaultDoc from "../../defaultDoc";
import NotiveElement, { customElement } from "../../element";
import {
  changeSelectedSubdivisions,
  getSelectedSubdivisionsCount,
} from "../../grid";
import { Doc } from "../../types";
import ntvGrid, { NotiveGridElement } from "../grid";
import renderGrid from "../grid/renderGrid";
import { GridSelection } from "../grid/selection";
import ntvToolbar from "../toolbar";
import "./index.css";

@customElement("ntv-app")
export class NotiveAppElement extends NotiveElement {
  doc: Doc = defaultDoc();

  #selectedGridId?: string;
  #selection?: GridSelection;

  setSelection(gridId: string, selection: GridSelection) {
    const grid = this.doc.grids.find((grid) => grid.id === gridId);
    if (!grid) throw new Error("Invalid grid ID");

    this.#selectedGridId = gridId;
    this.#selection = selection;
    this.#updateGridSelections();

    this.#toolbar.subdivisions = getSelectedSubdivisionsCount(grid, selection);
  }

  clearSelection() {
    this.#selectedGridId = undefined;
    this.#selection = undefined;
    this.#updateGridSelections();
    this.#toolbar.subdivisions = undefined;
  }

  #updateGridSelections() {
    this.querySelectorAll<NotiveGridElement>("ntv-grid").forEach((grid) => {
      grid.selection =
        this.#selectedGridId === grid.grid?.id ? this.#selection : undefined;
    });
  }

  #toolbar = ntvToolbar({
    onsubdivisionschange: ({ subdivisions }) => {
      if (!subdivisions) return;

      const gridId = this.#selectedGridId;
      const selection = this.#selection;

      if (!gridId || !selection) return;

      const gridIndex = this.doc.grids.findIndex((grid) => grid.id === gridId);

      this.doc = produce(this.doc, (doc) => {
        doc.grids[gridIndex] = changeSelectedSubdivisions(
          this.doc.grids[gridIndex],
          selection,
          subdivisions,
        );
      });

      this.querySelector<NotiveGridElement>(
        `ntv-grid[data-grid-id="${gridId}"]`,
      )!.grid = renderGrid(this.doc.grids[gridIndex]);

      this.clearSelection();
    },
  });

  connectedCallback() {
    this.append(
      this.#toolbar,
      ...this.doc.grids.map((grid) =>
        ntvGrid({
          grid: renderGrid(grid),
          dataset: { gridId: grid.id },
          ongridselectionchange: (event) => {
            this.setSelection(grid.id, event.selection);
          },
          oncellchange: (event) => {
            console.log(event);
          },
        }),
      ),
    );
  }
}

export default NotiveAppElement.makeFactory();