Web Dev Solutions

Catalin Mititiuc

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

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

  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 => zoom(svg, e, this.#zoomFactor), { passive: false });
    svg.addEventListener('pointerdown', e => pan(svg, e), { passive: false });
  }
};