Web Dev Solutions

Catalin Mititiuc

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

const storageKey = 'pan-zoom',
  zoomFactor = 0.25;

function restorePanZoomVal(el) {
  const storedPanZoomVal = localStorage.getItem(storageKey);

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

function addEventListeners(svg, el) {
  svg.addEventListener('wheel', e => zoom(el, e, zoomFactor), { passive: false });
  svg.addEventListener('pointerdown', e => {
    if (e.button === 0) {
      e.target.setPointerCapture(e.pointerId);
      pan(svg, el, e), { passive: false };
    }
  });
  svg.addEventListener('pointermove', e => {
    console.log('clientX,clientY', `${e.clientX},${e.clientY}`);
  });
}

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

function observePanZoomChanges(el) {
  const observer = new MutationObserver(() => storePanZoomVal(el.style.transform));

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

export function start(svg) {
  const targetEl = svg.querySelector('.gameboard');

  restorePanZoomVal(targetEl);
  addEventListeners(svg, targetEl);
  observePanZoomChanges(targetEl);
}