Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: 38b6b08399eb513674c4e492d7d049c8038c1ee0 (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 { pan, zoom } from 'svg-pan-zoom';

export default class PanZoom {
  #storageKey = 'pan-zoom';

  constructor(svg) {
    this.#restorePanZoomVal(svg);
    this.#addEventListeners(svg);
    this.#observePanZoomChanges(svg);
  }

  #storePanZoomVal(transformMatrix) {
    localStorage.setItem(this.#storageKey, transformMatrix);
  }

  #observePanZoomChanges(svg) {
    const observer =
      new MutationObserver(() => this.#storePanZoomVal(svg.style.transform));

    observer.observe(svg, { attributeFilter: ['style'] });
  }

  #restorePanZoomVal(svg) {
    const storedPanZoomVal = localStorage.getItem(this.#storageKey);

    if (storedPanZoomVal) {
      svg.style.transform = storedPanZoomVal;
    }
  }

  #addEventListeners(svg) {
    svg.addEventListener('wheel', e => {
      e.preventDefault();

      zoom(svg, e);
    }, { passive: false });

    svg.addEventListener('pointerdown', e => {
      e.preventDefault();

      pan(svg, e);
    }, { passive: false });
  }
};