# Screensaver

Area tempat satu atau beberapa elemen memantul di dinding seperti screensaver DVD lama, berganti token warna atau memipih di setiap benturan.

- Kategori: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/screensaver.json
- CLI: `npx markasui@latest add screensaver`

## Kapan dipakai

Sentuhan ringan dan jenaka di tempat yang sepi: halaman 404, empty state, panel menunggu atau segera hadir, daftar yang sedang online.

- Beri area tinggi tetap dan latar supaya dindingnya terlihat
- Pakai satu sampai lima elemen kecil; elemen besar terus-menerus membentur dinding
- Pakai warna tone hanya untuk ikon, titik, atau teks tebal besar supaya kontras tetap terbaca
- Jangan menaruh satu-satunya tombol atau tautan halaman di dalam elemen yang memantul

## Kode

### Blade

Simpan di `resources/views/components/markas/screensaver.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'speed' => 80,
    'effect' => 'tone',
    'tones' => ['primary', 'success', 'warning', 'danger'],
    'seed' => 1,
    'pauseOnHover' => true,
])

@php
    $base = 'relative overflow-hidden [&>*]:absolute [&>*]:top-0 [&>*]:left-0 [&>*]:transition-colors [&>*]:duration-300 motion-reduce:[&>*]:transition-none';
    $toneClasses = '[&>[data-tone=primary]]:text-primary [&>[data-tone=success]]:text-success [&>[data-tone=warning]]:text-warning [&>[data-tone=danger]]:text-danger [&>[data-tone=ink]]:text-ink [&>[data-tone=muted]]:text-muted';
@endphp

{{-- Places each child at a seeded spot, then bounces it off the walls at speed px per second. Runs only while the area is on screen, the tab is visible, and nothing inside is hovered or focused. --}}
<div
    x-data="{
        stop: null,
        init() {
            const o = { speed: @js((float) $speed), effect: @js($effect), tones: @js(array_values((array) $tones)), seed: @js((float) $seed), pauseOnHover: @js((bool) $pauseOnHover) };
            const root = this.$el;
            const quarter = Math.PI / 2;
            const rand = (seed, n) => {
                const x = Math.sin(seed * 78.233 + n * 12.9898) * 43758.5453;
                return x - Math.floor(x);
            };
            const tones = o.tones.filter((t) => ['primary', 'success', 'warning', 'danger', 'ink', 'muted'].includes(t));
            const items = [...root.children].map((el, i) => {
                const angle = (0.2 + 0.6 * rand(o.seed, i * 4)) * quarter + Math.floor(rand(o.seed, i * 4 + 1) * 4) * quarter;
                const x = rand(o.seed, i * 4 + 2) * (root.clientWidth - el.offsetWidth);
                const y = rand(o.seed, i * 4 + 3) * (root.clientHeight - el.offsetHeight);
                const item = { el, x: Math.max(0, Math.round(x)), y: Math.max(0, Math.round(y)), vx: Math.cos(angle) * o.speed, vy: Math.sin(angle) * o.speed, tone: i };
                if (o.effect === 'tone' && tones.length) el.dataset.tone = tones[i % tones.length];
                else delete el.dataset.tone;
                el.style.translate = `${item.x}px ${item.y}px`;
                return item;
            });
            if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
            const bump = (item, sideways) => {
                if (o.effect === 'tone' && tones.length) item.el.dataset.tone = tones[++item.tone % tones.length];
                if (o.effect === 'squash') item.el.animate?.([{ scale: '1' }, { scale: sideways ? '0.8 1.15' : '1.15 0.8' }, { scale: '1' }], { duration: 260, easing: 'ease-out' });
            };
            let frame = 0;
            let last = 0;
            const tick = (now) => {
                const dt = last ? Math.min((now - last) / 1000, 0.05) : 0;
                last = now;
                for (const item of items) {
                    const maxX = Math.max(0, root.clientWidth - item.el.offsetWidth);
                    const maxY = Math.max(0, root.clientHeight - item.el.offsetHeight);
                    item.x += item.vx * dt;
                    item.y += item.vy * dt;
                    const sideways = (item.x <= 0 && item.vx < 0) || (item.x >= maxX && item.vx > 0);
                    const upright = (item.y <= 0 && item.vy < 0) || (item.y >= maxY && item.vy > 0);
                    if (sideways) item.vx = -item.vx;
                    if (upright) item.vy = -item.vy;
                    if (sideways || upright) bump(item, sideways);
                    item.x = Math.min(Math.max(item.x, 0), maxX);
                    item.y = Math.min(Math.max(item.y, 0), maxY);
                    item.el.style.translate = `${item.x}px ${item.y}px`;
                }
                frame = requestAnimationFrame(tick);
            };
            const state = { hover: false, focus: false, visible: true };
            const sync = () => {
                const run = state.visible && ! state.focus && ! (o.pauseOnHover && state.hover) && ! document.hidden;
                cancelAnimationFrame(frame);
                last = 0;
                if (run) frame = requestAnimationFrame(tick);
            };
            const on = (key, value) => () => {
                state[key] = value;
                sync();
            };
            const listeners = [['pointerenter', on('hover', true)], ['pointerleave', on('hover', false)], ['focusin', on('focus', true)], ['focusout', on('focus', false)]];
            for (const [type, fn] of listeners) root.addEventListener(type, fn);
            document.addEventListener('visibilitychange', sync);
            const observer = typeof IntersectionObserver === 'undefined' ? null : new IntersectionObserver(([entry]) => {
                state.visible = !! entry?.isIntersecting;
                sync();
            });
            observer?.observe(root);
            sync();
            this.stop = () => {
                cancelAnimationFrame(frame);
                observer?.disconnect();
                document.removeEventListener('visibilitychange', sync);
                for (const [type, fn] of listeners) root.removeEventListener(type, fn);
            };
        },
        destroy() {
            this.stop?.();
        },
    }"
    {{ $attributes->class([$base, $toneClasses]) }}
>
    {{ $slot }}
</div>
```

```blade
<x-markas.screensaver class="h-44 rounded-lg bg-subtle" aria-hidden="true">
    <span class="flex items-center gap-2 text-3xl font-bold">
        <svg class="size-8" aria-hidden="true">...</svg>404
    </span>
</x-markas.screensaver>
```

Butuh Alpine.js.

### React

Simpan di `src/components/markas/Screensaver.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

import { useLayoutEffect, useRef, type ComponentProps } from "react";

const base =
  "relative overflow-hidden [&>*]:absolute [&>*]:top-0 [&>*]:left-0 [&>*]:transition-colors [&>*]:duration-300 motion-reduce:[&>*]:transition-none";
const toneClasses =
  "[&>[data-tone=primary]]:text-primary [&>[data-tone=success]]:text-success [&>[data-tone=warning]]:text-warning [&>[data-tone=danger]]:text-danger [&>[data-tone=ink]]:text-ink [&>[data-tone=muted]]:text-muted";

export type ScreensaverEffect = "tone" | "squash" | "none";
export type ScreensaverTone =
  "primary" | "success" | "warning" | "danger" | "ink" | "muted";
type Options = {
  speed: number;
  effect: ScreensaverEffect;
  tones: ScreensaverTone[];
  seed: number;
  pauseOnHover: boolean;
};

const KNOWN_TONES = ["primary", "success", "warning", "danger", "ink", "muted"];
const QUARTER = Math.PI / 2;
const MAX_STEP_S = 0.05;
const SQUASH_MS = 260;

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
/** Same number for the same seed and index in every framework. */
const rand = (seed: number, n: number) => {
  const x = Math.sin(seed * 78.233 + n * 12.9898) * 43758.5453;
  return x - Math.floor(x);
};
const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

/**
 * Place each child at a seeded spot, then bounce it off the walls at `speed` px per second.
 * Runs only while the area is on screen, the tab is visible, and nothing inside is hovered or focused.
 */
export function startScreensaver(root: HTMLElement, o: Options) {
  const tones = o.tones.filter((t) => KNOWN_TONES.includes(t));
  const items = ([...root.children] as HTMLElement[]).map((el, i) => {
    const angle =
      (0.2 + 0.6 * rand(o.seed, i * 4)) * QUARTER +
      Math.floor(rand(o.seed, i * 4 + 1) * 4) * QUARTER;
    const x = rand(o.seed, i * 4 + 2) * (root.clientWidth - el.offsetWidth);
    const y = rand(o.seed, i * 4 + 3) * (root.clientHeight - el.offsetHeight);
    const item = {
      el,
      x: Math.max(0, Math.round(x)),
      y: Math.max(0, Math.round(y)),
      vx: Math.cos(angle) * o.speed,
      vy: Math.sin(angle) * o.speed,
      tone: i,
    };
    if (o.effect === "tone" && tones.length)
      el.dataset.tone = tones[i % tones.length];
    else delete el.dataset.tone;
    el.style.translate = `${item.x}px ${item.y}px`;
    return item;
  });
  if (still()) return () => {};

  const bump = (item: (typeof items)[number], sideways: boolean) => {
    if (o.effect === "tone" && tones.length)
      item.el.dataset.tone = tones[++item.tone % tones.length];
    if (o.effect === "squash")
      item.el.animate?.(
        [
          { scale: "1" },
          { scale: sideways ? "0.8 1.15" : "1.15 0.8" },
          { scale: "1" },
        ],
        { duration: SQUASH_MS, easing: "ease-out" },
      );
  };
  let frame = 0;
  let last = 0;
  const tick = (now: number) => {
    const dt = last ? Math.min((now - last) / 1000, MAX_STEP_S) : 0;
    last = now;
    for (const item of items) {
      const maxX = Math.max(0, root.clientWidth - item.el.offsetWidth);
      const maxY = Math.max(0, root.clientHeight - item.el.offsetHeight);
      item.x += item.vx * dt;
      item.y += item.vy * dt;
      const sideways =
        (item.x <= 0 && item.vx < 0) || (item.x >= maxX && item.vx > 0);
      const upright =
        (item.y <= 0 && item.vy < 0) || (item.y >= maxY && item.vy > 0);
      if (sideways) item.vx = -item.vx;
      if (upright) item.vy = -item.vy;
      if (sideways || upright) bump(item, sideways);
      item.x = Math.min(Math.max(item.x, 0), maxX);
      item.y = Math.min(Math.max(item.y, 0), maxY);
      item.el.style.translate = `${item.x}px ${item.y}px`;
    }
    frame = requestAnimationFrame(tick);
  };

  const state = { hover: false, focus: false, visible: true };
  const sync = () => {
    const run =
      state.visible &&
      !state.focus &&
      !(o.pauseOnHover && state.hover) &&
      !document.hidden;
    cancelAnimationFrame(frame);
    last = 0;
    if (run) frame = requestAnimationFrame(tick);
  };
  const on = (key: "hover" | "focus", value: boolean) => () => {
    state[key] = value;
    sync();
  };
  const listeners = [
    ["pointerenter", on("hover", true)],
    ["pointerleave", on("hover", false)],
    ["focusin", on("focus", true)],
    ["focusout", on("focus", false)],
  ] as [string, (e: Event) => void][];
  for (const [type, fn] of listeners) root.addEventListener(type, fn);
  document.addEventListener("visibilitychange", sync);
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver(([entry]) => {
          state.visible = !!entry?.isIntersecting;
          sync();
        });
  observer?.observe(root);
  sync();

  return () => {
    cancelAnimationFrame(frame);
    observer?.disconnect();
    document.removeEventListener("visibilitychange", sync);
    for (const [type, fn] of listeners) root.removeEventListener(type, fn);
  };
}

export type ScreensaverProps = ComponentProps<"div"> & {
  /** Travel speed in px per second. */
  speed?: number;
  /** What happens on each wall hit: switch to the next tone, squash and stretch, or nothing. */
  effect?: ScreensaverEffect;
  /** Color tokens cycled by the tone effect. Children should use currentColor. */
  tones?: ScreensaverTone[];
  /** Changes the starting spots and directions. */
  seed?: number;
  /** Stops while the pointer is over the area. */
  pauseOnHover?: boolean;
};

const DEFAULT_TONES: ScreensaverTone[] = [
  "primary",
  "success",
  "warning",
  "danger",
];

export function Screensaver({
  speed = 80,
  effect = "tone",
  tones = DEFAULT_TONES,
  seed = 1,
  pauseOnHover = true,
  className,
  children,
  ...props
}: ScreensaverProps) {
  const ref = useRef<HTMLDivElement>(null);
  const toneKey = tones.join(" ");
  useLayoutEffect(() => {
    if (!ref.current) return;
    return startScreensaver(ref.current, {
      speed,
      effect,
      tones: toneKey.split(" ") as ScreensaverTone[],
      seed,
      pauseOnHover,
    });
  }, [speed, effect, toneKey, seed, pauseOnHover]);
  return (
    <div ref={ref} {...props} className={cx(base, toneClasses, className)}>
      {children}
    </div>
  );
}
```

```tsx
import { Screensaver } from "@/components/markas/Screensaver";

<Screensaver
  effect="squash"
  speed={50}
  className="h-32 w-36 rounded-lg bg-subtle"
  aria-hidden="true"
>
  <span className="grid size-12 place-items-center rounded-xl bg-surface">
    ...
  </span>
</Screensaver>;
```

### Vue

Simpan di `src/components/markas/Screensaver.vue`. Tanpa dependensi tambahan.

```vue
<script setup lang="ts">
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from "vue";

const props = withDefaults(
  defineProps<{
    /** Travel speed in px per second. */
    speed?: number;
    /** What happens on each wall hit: switch to the next tone, squash and stretch, or nothing. */
    effect?: "tone" | "squash" | "none";
    /** Color tokens cycled by the tone effect. Children should use currentColor. */
    tones?: ("primary" | "success" | "warning" | "danger" | "ink" | "muted")[];
    /** Changes the starting spots and directions. */
    seed?: number;
    /** Stops while the pointer is over the area. */
    pauseOnHover?: boolean;
  }>(),
  {
    speed: 80,
    effect: "tone",
    tones: () => ["primary", "success", "warning", "danger"],
    seed: 1,
    pauseOnHover: true,
  },
);

const base =
  "relative overflow-hidden [&>*]:absolute [&>*]:top-0 [&>*]:left-0 [&>*]:transition-colors [&>*]:duration-300 motion-reduce:[&>*]:transition-none";
const toneClasses =
  "[&>[data-tone=primary]]:text-primary [&>[data-tone=success]]:text-success [&>[data-tone=warning]]:text-warning [&>[data-tone=danger]]:text-danger [&>[data-tone=ink]]:text-ink [&>[data-tone=muted]]:text-muted";

type ScreensaverEffect = "tone" | "squash" | "none";
type ScreensaverTone =
  "primary" | "success" | "warning" | "danger" | "ink" | "muted";
type Options = {
  speed: number;
  effect: ScreensaverEffect;
  tones: ScreensaverTone[];
  seed: number;
  pauseOnHover: boolean;
};

const KNOWN_TONES = ["primary", "success", "warning", "danger", "ink", "muted"];
const QUARTER = Math.PI / 2;
const MAX_STEP_S = 0.05;
const SQUASH_MS = 260;

/** Same number for the same seed and index in every framework. */
const rand = (seed: number, n: number) => {
  const x = Math.sin(seed * 78.233 + n * 12.9898) * 43758.5453;
  return x - Math.floor(x);
};
const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

/**
 * Place each child at a seeded spot, then bounce it off the walls at `speed` px per second.
 * Runs only while the area is on screen, the tab is visible, and nothing inside is hovered or focused.
 */
function startScreensaver(root: HTMLElement, o: Options) {
  const tones = o.tones.filter((t) => KNOWN_TONES.includes(t));
  const items = ([...root.children] as HTMLElement[]).map((el, i) => {
    const angle =
      (0.2 + 0.6 * rand(o.seed, i * 4)) * QUARTER +
      Math.floor(rand(o.seed, i * 4 + 1) * 4) * QUARTER;
    const x = rand(o.seed, i * 4 + 2) * (root.clientWidth - el.offsetWidth);
    const y = rand(o.seed, i * 4 + 3) * (root.clientHeight - el.offsetHeight);
    const item = {
      el,
      x: Math.max(0, Math.round(x)),
      y: Math.max(0, Math.round(y)),
      vx: Math.cos(angle) * o.speed,
      vy: Math.sin(angle) * o.speed,
      tone: i,
    };
    if (o.effect === "tone" && tones.length)
      el.dataset.tone = tones[i % tones.length];
    else delete el.dataset.tone;
    el.style.translate = `${item.x}px ${item.y}px`;
    return item;
  });
  if (still()) return () => {};

  const bump = (item: (typeof items)[number], sideways: boolean) => {
    if (o.effect === "tone" && tones.length)
      item.el.dataset.tone = tones[++item.tone % tones.length];
    if (o.effect === "squash")
      item.el.animate?.(
        [
          { scale: "1" },
          { scale: sideways ? "0.8 1.15" : "1.15 0.8" },
          { scale: "1" },
        ],
        { duration: SQUASH_MS, easing: "ease-out" },
      );
  };
  let frame = 0;
  let last = 0;
  const tick = (now: number) => {
    const dt = last ? Math.min((now - last) / 1000, MAX_STEP_S) : 0;
    last = now;
    for (const item of items) {
      const maxX = Math.max(0, root.clientWidth - item.el.offsetWidth);
      const maxY = Math.max(0, root.clientHeight - item.el.offsetHeight);
      item.x += item.vx * dt;
      item.y += item.vy * dt;
      const sideways =
        (item.x <= 0 && item.vx < 0) || (item.x >= maxX && item.vx > 0);
      const upright =
        (item.y <= 0 && item.vy < 0) || (item.y >= maxY && item.vy > 0);
      if (sideways) item.vx = -item.vx;
      if (upright) item.vy = -item.vy;
      if (sideways || upright) bump(item, sideways);
      item.x = Math.min(Math.max(item.x, 0), maxX);
      item.y = Math.min(Math.max(item.y, 0), maxY);
      item.el.style.translate = `${item.x}px ${item.y}px`;
    }
    frame = requestAnimationFrame(tick);
  };

  const state = { hover: false, focus: false, visible: true };
  const sync = () => {
    const run =
      state.visible &&
      !state.focus &&
      !(o.pauseOnHover && state.hover) &&
      !document.hidden;
    cancelAnimationFrame(frame);
    last = 0;
    if (run) frame = requestAnimationFrame(tick);
  };
  const on = (key: "hover" | "focus", value: boolean) => () => {
    state[key] = value;
    sync();
  };
  const listeners = [
    ["pointerenter", on("hover", true)],
    ["pointerleave", on("hover", false)],
    ["focusin", on("focus", true)],
    ["focusout", on("focus", false)],
  ] as [string, (e: Event) => void][];
  for (const [type, fn] of listeners) root.addEventListener(type, fn);
  document.addEventListener("visibilitychange", sync);
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver(([entry]) => {
          state.visible = !!entry?.isIntersecting;
          sync();
        });
  observer?.observe(root);
  sync();

  return () => {
    cancelAnimationFrame(frame);
    observer?.disconnect();
    document.removeEventListener("visibilitychange", sync);
    for (const [type, fn] of listeners) root.removeEventListener(type, fn);
  };
}

const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
let stop = () => {};
function start() {
  stop();
  stop = () => {};
  if (rootEl.value)
    stop = startScreensaver(rootEl.value, {
      ...props,
      tones: [...props.tones],
    });
}
onMounted(start);
watch(
  () => [
    props.speed,
    props.effect,
    props.tones.join(" "),
    props.seed,
    props.pauseOnHover,
  ],
  start,
  {
    flush: "post",
  },
);
onBeforeUnmount(() => stop());
</script>

<template>
  <div ref="rootRef" :class="[base, toneClasses]">
    <slot />
  </div>
</template>
```

```vue
<template>
  <Screensaver
    :speed="60"
    :tones="['success', 'warning']"
    class="h-52 rounded-lg bg-canvas"
  >
    <span class="flex items-center gap-2 rounded-full bg-surface px-3 py-1">
      <span class="size-2.5 rounded-full bg-current"></span>
      <span class="text-ink">Rania Putri</span>
    </span>
  </Screensaver>
</template>
```

### Svelte

Simpan di `src/lib/components/markas/Screensaver.svelte`. Tanpa dependensi tambahan.

```svelte
<script lang="ts">
  import type { Snippet } from "svelte";
  import type { HTMLAttributes } from "svelte/elements";

  const base =
    "relative overflow-hidden [&>*]:absolute [&>*]:top-0 [&>*]:left-0 [&>*]:transition-colors [&>*]:duration-300 motion-reduce:[&>*]:transition-none";
  const toneClasses =
    "[&>[data-tone=primary]]:text-primary [&>[data-tone=success]]:text-success [&>[data-tone=warning]]:text-warning [&>[data-tone=danger]]:text-danger [&>[data-tone=ink]]:text-ink [&>[data-tone=muted]]:text-muted";

  type ScreensaverEffect = "tone" | "squash" | "none";
  type ScreensaverTone =
    "primary" | "success" | "warning" | "danger" | "ink" | "muted";
  type Options = {
    speed: number;
    effect: ScreensaverEffect;
    tones: ScreensaverTone[];
    seed: number;
    pauseOnHover: boolean;
  };

  const KNOWN_TONES = [
    "primary",
    "success",
    "warning",
    "danger",
    "ink",
    "muted",
  ];
  const QUARTER = Math.PI / 2;
  const MAX_STEP_S = 0.05;
  const SQUASH_MS = 260;

  /** Same number for the same seed and index in every framework. */
  const rand = (seed: number, n: number) => {
    const x = Math.sin(seed * 78.233 + n * 12.9898) * 43758.5453;
    return x - Math.floor(x);
  };
  const still = () =>
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

  /**
   * Place each child at a seeded spot, then bounce it off the walls at `speed` px per second.
   * Runs only while the area is on screen, the tab is visible, and nothing inside is hovered or focused.
   */
  function startScreensaver(root: HTMLElement, o: Options) {
    const tones = o.tones.filter((t) => KNOWN_TONES.includes(t));
    const items = ([...root.children] as HTMLElement[]).map((el, i) => {
      const angle =
        (0.2 + 0.6 * rand(o.seed, i * 4)) * QUARTER +
        Math.floor(rand(o.seed, i * 4 + 1) * 4) * QUARTER;
      const x = rand(o.seed, i * 4 + 2) * (root.clientWidth - el.offsetWidth);
      const y = rand(o.seed, i * 4 + 3) * (root.clientHeight - el.offsetHeight);
      const item = {
        el,
        x: Math.max(0, Math.round(x)),
        y: Math.max(0, Math.round(y)),
        vx: Math.cos(angle) * o.speed,
        vy: Math.sin(angle) * o.speed,
        tone: i,
      };
      if (o.effect === "tone" && tones.length)
        el.dataset.tone = tones[i % tones.length];
      else delete el.dataset.tone;
      el.style.translate = `${item.x}px ${item.y}px`;
      return item;
    });
    if (still()) return () => {};

    const bump = (item: (typeof items)[number], sideways: boolean) => {
      if (o.effect === "tone" && tones.length)
        item.el.dataset.tone = tones[++item.tone % tones.length];
      if (o.effect === "squash")
        item.el.animate?.(
          [
            { scale: "1" },
            { scale: sideways ? "0.8 1.15" : "1.15 0.8" },
            { scale: "1" },
          ],
          { duration: SQUASH_MS, easing: "ease-out" },
        );
    };
    let frame = 0;
    let last = 0;
    const tick = (now: number) => {
      const dt = last ? Math.min((now - last) / 1000, MAX_STEP_S) : 0;
      last = now;
      for (const item of items) {
        const maxX = Math.max(0, root.clientWidth - item.el.offsetWidth);
        const maxY = Math.max(0, root.clientHeight - item.el.offsetHeight);
        item.x += item.vx * dt;
        item.y += item.vy * dt;
        const sideways =
          (item.x <= 0 && item.vx < 0) || (item.x >= maxX && item.vx > 0);
        const upright =
          (item.y <= 0 && item.vy < 0) || (item.y >= maxY && item.vy > 0);
        if (sideways) item.vx = -item.vx;
        if (upright) item.vy = -item.vy;
        if (sideways || upright) bump(item, sideways);
        item.x = Math.min(Math.max(item.x, 0), maxX);
        item.y = Math.min(Math.max(item.y, 0), maxY);
        item.el.style.translate = `${item.x}px ${item.y}px`;
      }
      frame = requestAnimationFrame(tick);
    };

    const state = { hover: false, focus: false, visible: true };
    const sync = () => {
      const run =
        state.visible &&
        !state.focus &&
        !(o.pauseOnHover && state.hover) &&
        !document.hidden;
      cancelAnimationFrame(frame);
      last = 0;
      if (run) frame = requestAnimationFrame(tick);
    };
    const on = (key: "hover" | "focus", value: boolean) => () => {
      state[key] = value;
      sync();
    };
    const listeners = [
      ["pointerenter", on("hover", true)],
      ["pointerleave", on("hover", false)],
      ["focusin", on("focus", true)],
      ["focusout", on("focus", false)],
    ] as [string, (e: Event) => void][];
    for (const [type, fn] of listeners) root.addEventListener(type, fn);
    document.addEventListener("visibilitychange", sync);
    const observer =
      typeof IntersectionObserver === "undefined"
        ? undefined
        : new IntersectionObserver(([entry]) => {
            state.visible = !!entry?.isIntersecting;
            sync();
          });
    observer?.observe(root);
    sync();

    return () => {
      cancelAnimationFrame(frame);
      observer?.disconnect();
      document.removeEventListener("visibilitychange", sync);
      for (const [type, fn] of listeners) root.removeEventListener(type, fn);
    };
  }

  const DEFAULT_TONES: ScreensaverTone[] = [
    "primary",
    "success",
    "warning",
    "danger",
  ];

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** Travel speed in px per second. */
    speed?: number;
    /** What happens on each wall hit: switch to the next tone, squash and stretch, or nothing. */
    effect?: ScreensaverEffect;
    /** Color tokens cycled by the tone effect. Children should use currentColor. */
    tones?: ScreensaverTone[];
    /** Changes the starting spots and directions. */
    seed?: number;
    /** Stops while the pointer is over the area. */
    pauseOnHover?: boolean;
    children?: Snippet;
  };

  let {
    speed = 80,
    effect: wallEffect = "tone",
    tones = DEFAULT_TONES,
    seed = 1,
    pauseOnHover = true,
    class: className,
    children,
    ...rest
  }: Props = $props();

  let root = $state<HTMLDivElement>();

  $effect(() => {
    const options = {
      speed,
      effect: wallEffect,
      tones: [...tones],
      seed,
      pauseOnHover,
    };
    if (root) return startScreensaver(root, options);
  });
</script>

<div bind:this={root} {...rest} class={[base, toneClasses, className]}>
  {@render children?.()}
</div>
```

```svelte
<script lang="ts">
  import Screensaver from "$lib/components/markas/Screensaver.svelte";
</script>

<Screensaver class="h-56 rounded-xl border border-line" aria-hidden="true">
  <span class="text-3xl font-bold">Markas</span>
</Screensaver>
```

### Astro

Simpan di `src/components/markas/Screensaver.astro`. Tanpa dependensi tambahan.

```astro
---
import type { HTMLAttributes } from "astro/types";

const base =
  "relative overflow-hidden [&>*]:absolute [&>*]:top-0 [&>*]:left-0 [&>*]:transition-colors [&>*]:duration-300 motion-reduce:[&>*]:transition-none";
const toneClasses =
  "[&>[data-tone=primary]]:text-primary [&>[data-tone=success]]:text-success [&>[data-tone=warning]]:text-warning [&>[data-tone=danger]]:text-danger [&>[data-tone=ink]]:text-ink [&>[data-tone=muted]]:text-muted";

type ScreensaverTone =
  | "primary"
  | "success"
  | "warning"
  | "danger"
  | "ink"
  | "muted";

type Props = HTMLAttributes<"div"> & {
  /** Travel speed in px per second. */
  speed?: number;
  /** What happens on each wall hit: switch to the next tone, squash and stretch, or nothing. */
  effect?: "tone" | "squash" | "none";
  /** Color tokens cycled by the tone effect. Children should use currentColor. */
  tones?: ScreensaverTone[];
  /** Changes the starting spots and directions. */
  seed?: number;
  /** Stops while the pointer is over the area. */
  pauseOnHover?: boolean;
};

const {
  speed = 80,
  effect = "tone",
  tones = ["primary", "success", "warning", "danger"],
  seed = 1,
  pauseOnHover = true,
  class: className,
  ...rest
} = Astro.props;
const options = JSON.stringify({
  speed: Number(speed),
  effect,
  tones,
  seed: Number(seed),
  pauseOnHover: Boolean(pauseOnHover),
});
---

<markas-screensaver class="contents" data-options={options}>
  <div {...rest} class:list={[base, toneClasses, className]}><slot /></div>
</markas-screensaver>

<script>
  type ScreensaverEffect = "tone" | "squash" | "none";
  type ScreensaverTone =
    "primary" | "success" | "warning" | "danger" | "ink" | "muted";
  type Options = {
    speed: number;
    effect: ScreensaverEffect;
    tones: ScreensaverTone[];
    seed: number;
    pauseOnHover: boolean;
  };

  const KNOWN_TONES = ["primary", "success", "warning", "danger", "ink", "muted"];
  const QUARTER = Math.PI / 2;
  const MAX_STEP_S = 0.05;
  const SQUASH_MS = 260;

  /** Same number for the same seed and index in every framework. */
  const rand = (seed: number, n: number) => {
    const x = Math.sin(seed * 78.233 + n * 12.9898) * 43758.5453;
    return x - Math.floor(x);
  };
  const still = () =>
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

  /**
   * Place each child at a seeded spot, then bounce it off the walls at `speed` px per second.
   * Runs only while the area is on screen, the tab is visible, and nothing inside is hovered or focused.
   */
  function startScreensaver(root: HTMLElement, o: Options) {
    const tones = o.tones.filter((t) => KNOWN_TONES.includes(t));
    const items = ([...root.children] as HTMLElement[]).map((el, i) => {
      const angle =
        (0.2 + 0.6 * rand(o.seed, i * 4)) * QUARTER +
        Math.floor(rand(o.seed, i * 4 + 1) * 4) * QUARTER;
      const x = rand(o.seed, i * 4 + 2) * (root.clientWidth - el.offsetWidth);
      const y = rand(o.seed, i * 4 + 3) * (root.clientHeight - el.offsetHeight);
      const item = {
        el,
        x: Math.max(0, Math.round(x)),
        y: Math.max(0, Math.round(y)),
        vx: Math.cos(angle) * o.speed,
        vy: Math.sin(angle) * o.speed,
        tone: i,
      };
      if (o.effect === "tone" && tones.length)
        el.dataset.tone = tones[i % tones.length];
      else delete el.dataset.tone;
      el.style.translate = `${item.x}px ${item.y}px`;
      return item;
    });
    if (still()) return () => {};

    const bump = (item: (typeof items)[number], sideways: boolean) => {
      if (o.effect === "tone" && tones.length)
        item.el.dataset.tone = tones[++item.tone % tones.length];
      if (o.effect === "squash")
        item.el.animate?.(
          [
            { scale: "1" },
            { scale: sideways ? "0.8 1.15" : "1.15 0.8" },
            { scale: "1" },
          ],
          { duration: SQUASH_MS, easing: "ease-out" },
        );
    };
    let frame = 0;
    let last = 0;
    const tick = (now: number) => {
      const dt = last ? Math.min((now - last) / 1000, MAX_STEP_S) : 0;
      last = now;
      for (const item of items) {
        const maxX = Math.max(0, root.clientWidth - item.el.offsetWidth);
        const maxY = Math.max(0, root.clientHeight - item.el.offsetHeight);
        item.x += item.vx * dt;
        item.y += item.vy * dt;
        const sideways =
          (item.x <= 0 && item.vx < 0) || (item.x >= maxX && item.vx > 0);
        const upright =
          (item.y <= 0 && item.vy < 0) || (item.y >= maxY && item.vy > 0);
        if (sideways) item.vx = -item.vx;
        if (upright) item.vy = -item.vy;
        if (sideways || upright) bump(item, sideways);
        item.x = Math.min(Math.max(item.x, 0), maxX);
        item.y = Math.min(Math.max(item.y, 0), maxY);
        item.el.style.translate = `${item.x}px ${item.y}px`;
      }
      frame = requestAnimationFrame(tick);
    };

    const state = { hover: false, focus: false, visible: true };
    const sync = () => {
      const run =
        state.visible &&
        !state.focus &&
        !(o.pauseOnHover && state.hover) &&
        !document.hidden;
      cancelAnimationFrame(frame);
      last = 0;
      if (run) frame = requestAnimationFrame(tick);
    };
    const on = (key: "hover" | "focus", value: boolean) => () => {
      state[key] = value;
      sync();
    };
    const listeners = [
      ["pointerenter", on("hover", true)],
      ["pointerleave", on("hover", false)],
      ["focusin", on("focus", true)],
      ["focusout", on("focus", false)],
    ] as [string, (e: Event) => void][];
    for (const [type, fn] of listeners) root.addEventListener(type, fn);
    document.addEventListener("visibilitychange", sync);
    const observer =
      typeof IntersectionObserver === "undefined"
        ? undefined
        : new IntersectionObserver(([entry]) => {
            state.visible = !!entry?.isIntersecting;
            sync();
          });
    observer?.observe(root);
    sync();

    return () => {
      cancelAnimationFrame(frame);
      observer?.disconnect();
      document.removeEventListener("visibilitychange", sync);
      for (const [type, fn] of listeners) root.removeEventListener(type, fn);
    };
  }


  // Per instance: each area runs its own loop while on screen and not hovered or focused.
  class Screensaver extends HTMLElement {
    #stop = () => {};

    connectedCallback() {
      const root = this.firstElementChild as HTMLElement | null;
      if (!root) return;
      this.#stop = startScreensaver(
        root,
        JSON.parse(this.dataset.options ?? "{}") as Options,
      );
    }

    disconnectedCallback() {
      this.#stop();
    }
  }

  if (!customElements.get("markas-screensaver"))
    customElements.define("markas-screensaver", Screensaver);
</script>
```

```astro
---
import Screensaver from "@/components/markas/Screensaver.astro";
---

<Screensaver class="h-56 rounded-xl border border-line" aria-hidden="true">
  <span class="text-3xl font-bold">Markas</span>
</Screensaver>
```

Satu script kecil yang dibundel menjalankan setiap area lewat elemen `markas-screensaver`.

### Angular

Simpan di `src/app/markas/screensaver.component.ts`. Tanpa dependensi tambahan.

```ts
import {
  afterRenderEffect,
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  type ElementRef,
  input,
  numberAttribute,
  viewChild,
} from "@angular/core";

const base =
  "relative overflow-hidden [&>*]:absolute [&>*]:top-0 [&>*]:left-0 [&>*]:transition-colors [&>*]:duration-300 motion-reduce:[&>*]:transition-none";
const toneClasses =
  "[&>[data-tone=primary]]:text-primary [&>[data-tone=success]]:text-success [&>[data-tone=warning]]:text-warning [&>[data-tone=danger]]:text-danger [&>[data-tone=ink]]:text-ink [&>[data-tone=muted]]:text-muted";

export type ScreensaverEffect = "tone" | "squash" | "none";
export type ScreensaverTone =
  "primary" | "success" | "warning" | "danger" | "ink" | "muted";
type Options = {
  speed: number;
  effect: ScreensaverEffect;
  tones: ScreensaverTone[];
  seed: number;
  pauseOnHover: boolean;
};

const KNOWN_TONES = ["primary", "success", "warning", "danger", "ink", "muted"];
const QUARTER = Math.PI / 2;
const MAX_STEP_S = 0.05;
const SQUASH_MS = 260;

/** Same number for the same seed and index in every framework. */
const rand = (seed: number, n: number) => {
  const x = Math.sin(seed * 78.233 + n * 12.9898) * 43758.5453;
  return x - Math.floor(x);
};
const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

/**
 * Place each child at a seeded spot, then bounce it off the walls at `speed` px per second.
 * Runs only while the area is on screen, the tab is visible, and nothing inside is hovered or focused.
 */
function startScreensaver(root: HTMLElement, o: Options) {
  const tones = o.tones.filter((t) => KNOWN_TONES.includes(t));
  const items = ([...root.children] as HTMLElement[]).map((el, i) => {
    const angle =
      (0.2 + 0.6 * rand(o.seed, i * 4)) * QUARTER +
      Math.floor(rand(o.seed, i * 4 + 1) * 4) * QUARTER;
    const x = rand(o.seed, i * 4 + 2) * (root.clientWidth - el.offsetWidth);
    const y = rand(o.seed, i * 4 + 3) * (root.clientHeight - el.offsetHeight);
    const item = {
      el,
      x: Math.max(0, Math.round(x)),
      y: Math.max(0, Math.round(y)),
      vx: Math.cos(angle) * o.speed,
      vy: Math.sin(angle) * o.speed,
      tone: i,
    };
    if (o.effect === "tone" && tones.length)
      el.dataset.tone = tones[i % tones.length];
    else delete el.dataset.tone;
    el.style.translate = `${item.x}px ${item.y}px`;
    return item;
  });
  if (still()) return () => {};

  const bump = (item: (typeof items)[number], sideways: boolean) => {
    if (o.effect === "tone" && tones.length)
      item.el.dataset.tone = tones[++item.tone % tones.length];
    if (o.effect === "squash")
      item.el.animate?.(
        [
          { scale: "1" },
          { scale: sideways ? "0.8 1.15" : "1.15 0.8" },
          { scale: "1" },
        ],
        { duration: SQUASH_MS, easing: "ease-out" },
      );
  };
  let frame = 0;
  let last = 0;
  const tick = (now: number) => {
    const dt = last ? Math.min((now - last) / 1000, MAX_STEP_S) : 0;
    last = now;
    for (const item of items) {
      const maxX = Math.max(0, root.clientWidth - item.el.offsetWidth);
      const maxY = Math.max(0, root.clientHeight - item.el.offsetHeight);
      item.x += item.vx * dt;
      item.y += item.vy * dt;
      const sideways =
        (item.x <= 0 && item.vx < 0) || (item.x >= maxX && item.vx > 0);
      const upright =
        (item.y <= 0 && item.vy < 0) || (item.y >= maxY && item.vy > 0);
      if (sideways) item.vx = -item.vx;
      if (upright) item.vy = -item.vy;
      if (sideways || upright) bump(item, sideways);
      item.x = Math.min(Math.max(item.x, 0), maxX);
      item.y = Math.min(Math.max(item.y, 0), maxY);
      item.el.style.translate = `${item.x}px ${item.y}px`;
    }
    frame = requestAnimationFrame(tick);
  };

  const state = { hover: false, focus: false, visible: true };
  const sync = () => {
    const run =
      state.visible &&
      !state.focus &&
      !(o.pauseOnHover && state.hover) &&
      !document.hidden;
    cancelAnimationFrame(frame);
    last = 0;
    if (run) frame = requestAnimationFrame(tick);
  };
  const on = (key: "hover" | "focus", value: boolean) => () => {
    state[key] = value;
    sync();
  };
  const listeners = [
    ["pointerenter", on("hover", true)],
    ["pointerleave", on("hover", false)],
    ["focusin", on("focus", true)],
    ["focusout", on("focus", false)],
  ] as [string, (e: Event) => void][];
  for (const [type, fn] of listeners) root.addEventListener(type, fn);
  document.addEventListener("visibilitychange", sync);
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver(([entry]) => {
          state.visible = !!entry?.isIntersecting;
          sync();
        });
  observer?.observe(root);
  sync();

  return () => {
    cancelAnimationFrame(frame);
    observer?.disconnect();
    document.removeEventListener("visibilitychange", sync);
    for (const [type, fn] of listeners) root.removeEventListener(type, fn);
  };
}

const DEFAULT_TONES: ScreensaverTone[] = [
  "primary",
  "success",
  "warning",
  "danger",
];

/**
 * Every projected element travels. The host stays out of layout; the user's class and aria-hidden
 * land on the area.
 */
@Component({
  selector: "markas-screensaver",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.aria-hidden]": "null" },
  template: `<div #rootEl [class]="classes()" [attr.aria-hidden]="ariaHidden()">
    <ng-content />
  </div>`,
})
export class Screensaver {
  /** Travel speed in px per second. */
  readonly speed = input(80, { transform: numberAttribute });
  /** What happens on each wall hit: switch to the next tone, squash and stretch, or nothing. */
  readonly effect = input<ScreensaverEffect>("tone");
  /** Color tokens cycled by the tone effect. Children should use currentColor. */
  readonly tones = input<ScreensaverTone[]>(DEFAULT_TONES);
  /** Changes the starting spots and directions. */
  readonly seed = input(1, { transform: numberAttribute });
  /** Stops while the pointer is over the area. */
  readonly pauseOnHover = input(true, { transform: booleanAttribute });
  /** Decorative areas pass aria-hidden="true"; it lands on the area, not the host. */
  readonly ariaHidden = input<string>(undefined, { alias: "aria-hidden" });
  readonly userClass = input("", { alias: "class" });

  protected readonly classes = computed(() =>
    [base, toneClasses, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly root = viewChild.required<ElementRef<HTMLElement>>("rootEl");

  constructor() {
    afterRenderEffect((onCleanup) => {
      const options = {
        speed: this.speed(),
        effect: this.effect(),
        tones: [...this.tones()],
        seed: this.seed(),
        pauseOnHover: this.pauseOnHover(),
      };
      onCleanup(startScreensaver(this.root().nativeElement, options));
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { Screensaver } from "./markas/screensaver.component";

@Component({
  selector: "app-idle",
  imports: [Screensaver],
  template: `
    <markas-screensaver
      effect="squash"
      class="h-56 rounded-xl border border-line"
      aria-hidden="true"
    >
      <span class="text-3xl font-bold">Markas</span>
    </markas-screensaver>
  `,
})
export class Idle {}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `speed` | `number` | 80 | Kecepatan gerak dalam px per detik. 40 sampai 60 terasa santai, 120 ke atas terasa ramai. |
| `effect` | `"tone" \| "squash" \| "none"` | "tone" | Yang terjadi di setiap benturan dinding: pindah ke token warna berikutnya, memipih dan memanjang seperti bola karet, atau tidak ada. |
| `tones` | `("primary" \| "success" \| "warning" \| "danger" \| "ink" \| "muted")[]` | ["primary", "success", "warning", "danger"] | Token warna yang diputar oleh efek tone. Setiap elemen mulai dengan tone-nya sendiri; beri gaya currentColor pada bagian yang ikut berubah. |
| `seed` | `number` | 1 | Mengubah posisi dan arah awal. Seed yang sama selalu menghasilkan awal yang sama. |
| `pauseOnHover` | `boolean` | true | Menghentikan gerakan saat kursor berada di atas area. |
| `children / slot` | `ReactNode / slot` | - | Elemen yang memantul. Setiap anak langsung bergerak sendiri. Beri area tinggi, misalnya h-44. |

## Aksesibilitas

- Gerakan hanya berjalan saat area terlihat di layar dan tab aktif, dan berhenti saat ada yang memegang fokus keyboard di dalamnya.
- Tandai area yang murni dekoratif dengan aria-hidden="true"; teks di dalam elemen yang memantul tetap dibaca seperti biasa.
- Dengan reduced motion setiap elemen diam di posisi seed dengan tone pertamanya.

## Catatan

- Setiap anak langsung mulai di posisi seed dan memantul di dinding dengan kecepatan `speed` px per detik. Beri area tinggi.
- `effect="tone"` memindahkan setiap elemen ke token berikutnya di `tones` pada setiap benturan; warnai bagian yang ikut berubah dengan `currentColor` (misalnya `bg-current` atau stroke SVG). `effect="squash"` membuatnya memipih dan memanjang, `"none"` hanya memantul.
- Gerakan berhenti saat area di luar layar, tab tersembunyi, ada yang difokus di dalamnya, atau (dengan `pauseOnHover`) kursor berada di atasnya.
- Dengan reduced motion setiap elemen diam di posisi seed dengan tone pertamanya.
