File size: 2,420 Bytes
161cb23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export function el(tag, props = {}, children = []) {
  const node = document.createElement(tag);
  for (const [key, value] of Object.entries(props)) {
    if (value === null || value === undefined || value === false) {
      continue;
    }
    if (key === "class") {
      node.className = value;
    } else if (key === "text") {
      node.textContent = value;
    } else if (key === "style") {
      node.style.cssText = value;
    } else if (key.startsWith("on")) {
      node.addEventListener(key.slice(2), value);
    } else {
      node.setAttribute(key, value === true ? "" : value);
    }
  }
  node.append(...children);
  return node;
}

export function byId(id) {
  return document.getElementById(id);
}

export function prefersReducedMotion() {
  return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

const COPY_FEEDBACK_MS = 1200;

function flashIcon(button, icon, label, iconHref) {
  const original = { label: button.dataset.label ?? button.getAttribute("aria-label"), href: "#i-copy" };
  button.dataset.label = original.label;
  button.setAttribute("aria-label", label);
  icon.setAttribute("href", iconHref);
  clearTimeout(Number(button.dataset.flashTimer));
  const timer = setTimeout(() => {
    button.setAttribute("aria-label", original.label);
    icon.setAttribute("href", original.href);
  }, COPY_FEEDBACK_MS);
  button.dataset.flashTimer = String(timer);
}

export function copyWithIcon(button, icon, text) {
  navigator.clipboard.writeText(text).then(
    () => flashIcon(button, icon, "Copied", "#i-check"),
    () => flashIcon(button, icon, "Copy failed", "#i-copy"),
  );
}

let tweenCount = 0;

export function tweenNumber(node, from, to, durationMs) {
  if (from === to && node.dataset.tweenTo === String(to)) {
    return;
  }
  tweenCount += 1;
  const id = String(tweenCount);
  node.dataset.tween = id;
  node.dataset.tweenTo = String(to);
  if (from === to || durationMs === 0 || prefersReducedMotion()) {
    node.textContent = String(to);
    return;
  }
  const startedAt = performance.now();
  const step = (now) => {
    if (node.dataset.tween !== id) {
      return;
    }
    const progress = Math.min(1, (now - startedAt) / durationMs);
    const eased = 1 - (1 - progress) ** 3;
    node.textContent = String(Math.round(from + (to - from) * eased));
    if (progress < 1) {
      requestAnimationFrame(step);
    }
  };
  requestAnimationFrame(step);
}