# Screensaver

Area where one or more elements bounce off the walls like an old DVD screensaver, switching color tokens or squashing on each hit.

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

## When to use

A light, playful touch in quiet places: a 404 page, an empty state, a waiting or coming soon panel, a presence list.

- Give the area a fixed height and a background so the walls are visible
- Keep one to five small elements; large ones hit the walls constantly
- Use tone colors only on icons, dots, or large bold text so contrast stays readable
- Never put the only button or link of a page inside a bouncing element

## Code

### Blade

Save at `resources/views/components/markas/screensaver.blade.php`. Dependencies: 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>
```

Needs Alpine.js.

### React

Save at `src/components/markas/Screensaver.tsx`. No extra dependencies.

```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

Save at `src/components/markas/Screensaver.vue`. No extra dependencies.

```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

Save at `src/lib/components/markas/Screensaver.svelte`. No extra dependencies.

```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

Save at `src/components/markas/Screensaver.astro`. No extra dependencies.

```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>
```

A small bundled script runs each area through the `markas-screensaver` element.

### Angular

Save at `src/app/markas/screensaver.component.ts`. No extra dependencies.

```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

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `speed` | `number` | 80 | Travel speed in px per second. 40 to 60 feels lazy, 120 and up feels busy. |
| `effect` | `"tone" \| "squash" \| "none"` | "tone" | What happens on each wall hit: switch to the next color token, squash and stretch like a rubber ball, or nothing. |
| `tones` | `("primary" \| "success" \| "warning" \| "danger" \| "ink" \| "muted")[]` | ["primary", "success", "warning", "danger"] | Color tokens the tone effect cycles through. Each element starts on its own tone; style the parts that should change with currentColor. |
| `seed` | `number` | 1 | Changes the starting spots and directions. The same seed always gives the same start. |
| `pauseOnHover` | `boolean` | true | Stops the motion while the pointer is over the area. |
| `children / slot` | `ReactNode / slot` | - | The bouncing elements. Each direct child moves on its own. Give the area a height, such as h-44. |

## Accessibility

- Motion runs only while the area is on screen and the tab is visible, and stops while anything inside has keyboard focus.
- Mark a purely decorative area with aria-hidden="true"; text inside a bouncing element is otherwise read as usual.
- With reduced motion each element rests at its seeded spot in its first tone.

## Notes

- Each direct child starts at a seeded spot and bounces off the walls at `speed` px per second. Give the area a height.
- `effect="tone"` switches each element to the next token in `tones` on every wall hit; color the parts that should change with `currentColor` (such as `bg-current` or an SVG stroke). `effect="squash"` squashes and stretches instead, `"none"` just bounces.
- Motion pauses while the area is off screen, the tab is hidden, something inside has focus, or (with `pauseOnHover`) the pointer is over it.
- With reduced motion every element rests at its seeded spot in its first tone.
