TheBird

sky.ts

1.2 kB · typescript · 45 lines

1type SkyApi = { pause: () => void; resume: () => void; jump: (seconds: number) => void; G: { visible: boolean } };23declare global {4  interface Window {5    Sky?: SkyApi;6  }7}89const box = document.querySelector<HTMLElement>("[data-sky]");10const still = matchMedia("(prefers-reduced-motion: reduce)");1112let loading = false;13let shown = false;1415function apply() {16  const sky = window.Sky;17  if (!sky) return;18  sky.G.visible = shown;19  if (shown && !still.matches) return sky.resume();20  sky.pause();21  if (shown) sky.jump(0);22}2324function load() {25  if (loading || !box) return;26  loading = true;27  const script = document.createElement("script");28  script.type = "module";29  script.src = box.dataset.sky ?? "";30  script.onload = () => setTimeout(apply, 0);31  document.head.appendChild(script);32}3334if (box) {35  new IntersectionObserver((entries) => entries.some((one) => one.isIntersecting) && load(), { rootMargin: "100% 0px" }).observe(box);36  new IntersectionObserver(37    (entries) => {38      shown = entries.some((one) => one.isIntersecting);39      apply();40    },41    { threshold: 0.05 },42  ).observe(box);43  document.addEventListener("visibilitychange", () => (document.hidden ? window.Sky?.pause() : apply()));44  still.addEventListener("change", apply);45}