File size: 1,664 Bytes
aa3b624
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { DriveStep } from "./driver";
import { refreshStage, trackActiveElement, transitionStage } from "./stage";

let previousHighlight: Element | undefined;
let activeHighlight: Element | undefined;
let isTransitioning = false;

export function highlight(step: DriveStep) {
  const { element } = step;
  const elemObj =
    typeof element === "string" ? document.querySelector(element) : element;

  if (!elemObj) {
    return;
  }

  previousHighlight = activeHighlight;
  activeHighlight = elemObj;

  transferHighlight(previousHighlight || elemObj, elemObj);
}

export function refreshActiveHighlight() {
  if (!activeHighlight) {
    return;
  }

  trackActiveElement(activeHighlight);
  refreshStage();
}

function transferHighlight(from: Element, to: Element) {
  const duration = 400;
  const start = Date.now();
  isTransitioning = true;

  const animate = () => {
    if (!isTransitioning) {
      return;
    }

    const elapsed = Date.now() - start;

    if (elapsed < duration) {
      transitionStage(elapsed, duration, from, to);
    } else {
      trackActiveElement(to);

      isTransitioning = false;
    }

    refreshStage();
    window.requestAnimationFrame(animate);
  };

  window.requestAnimationFrame(animate);

  from.classList.remove("driver-active-element");
  to.classList.add("driver-active-element");

  isTransitioning = true;
}

export function destroyHighlight() {
  activeHighlight = undefined;
  isTransitioning = false;
  previousHighlight = undefined;
  activeHighlight = undefined;

  document.querySelectorAll(".driver-active-element").forEach(element => {
    element.classList.remove("driver-active-element");
  });
}