aboutsummaryrefslogtreecommitdiff
path: root/src/component/MosaicBackground.astro
blob: c39a802c9dc75f3c49c8af0eac5c8b1f25789783 (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
44
45
46
47
48
49
50
---
const { height = "400" } = Astro.props;
---

<div class="bg" data-height={height}>
  <slot />
</div>

<script>
  window.addEventListener("load", () => {
    // because Astro doesn't support defer
    document.querySelectorAll(".bg").forEach((e) => {
      const children = e.children;
      const max = e.clientWidth;
      const height = e.getAttribute("data-height");
      if (height == null) throw new Error(`Height is null`);
      const newChildren = [];

      let line = document.createElement("div");
      let currentWidth = 0;
      let i = 0;

      while (i < children.length) {
        // adding elements
        while (i < children.length && currentWidth <= max) {
          let current = children[i++];
          if (!(current instanceof HTMLScriptElement)) {
            let ratio = current.clientWidth / current.clientHeight;
            if (!isNaN(ratio)) {
              line.appendChild(current.cloneNode(true));
              currentWidth += ratio * height;
            } else {
              console.error("is NaN", current);
            }
          }
        }
        // setting height
        let h = (max * height) / currentWidth;
        line.style.height = `${h - 0.01}px`;
        newChildren.push(line);
        if (i < children.length) {
          line = document.createElement("div");
          currentWidth = 0;
        }
      }
      e.replaceChildren(...newChildren);
      e.dispatchEvent(new Event("updatevideo"));
    });
  });
</script>