# Float

Pembungkus yang membuat anaknya melayang, naik turun, mengorbit, atau bernapas dengan ritme sendiri, dengan parallax kursor dan kemunculan berurutan.

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

## Kapan dipakai

Suasana hidup di sekitar titik fokus: ikon atau logo di sekitar judul hero, badge di kartu harga, avatar di sekitar angka komunitas.

- Jaga amplitude tetap kecil (4 sampai 14) supaya gerakannya tenang
- Melayangkan beberapa item dekoratif saja, bukan teks isi atau field form
- Animasi memakai transform pada setiap anak langsung; bungkus anak yang butuh utilitas transform sendiri
- Pakai parallax pada area seukuran hero, bukan grup kecil sebaris

## Kode

### Blade

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

```blade
@props([
    'motion' => 'drift',
    'amplitude' => 10,
    'duration' => 6,
    'seed' => 1,
    'parallax' => 0,
    'entrance' => false,
])

@php
    $base = '[&>*]:transition-[translate] [&>*]:duration-700 [&>*]:ease-out motion-reduce:[&>*]:transition-none';
@endphp

{{-- Floats each child on its own loop, pauses one while it is hovered or focused, and pauses all when off screen. With parallax, children shift toward the pointer by their depth. --}}
<div
    x-data="{
        stop: null,
        init() {
            if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
            const o = { motion: @js($motion), amplitude: @js((float) $amplitude), duration: @js((float) $duration), seed: @js((float) $seed), parallax: @js((float) $parallax), entrance: @js((bool) $entrance) };
            const root = this.$el;
            const turn = 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 paths = {
                drift: (t, a) => [a * 0.6 * Math.sin(turn * t), a * 0.5 * Math.sin(turn * 2 * t), a * 0.3 * Math.sin(turn * t), 1],
                bob: (t, a) => [0, (-a * (1 - Math.cos(turn * t))) / 2, 0, 1],
                orbit: (t, a) => [a * Math.cos(turn * t), a * Math.sin(turn * t), 0, 1],
                breathe: (t, a) => {
                    const k = (1 - Math.cos(turn * t)) / 2;
                    return [0, -a * 0.3 * k, 0, 1 + (a / 100) * k];
                },
            };
            const items = [...root.children];
            const path = paths[o.motion] ?? paths.drift;
            const loops = items.map((el, i) => {
                const amp = o.amplitude * (0.7 + 0.6 * rand(o.seed, i * 4));
                const sign = rand(o.seed, i * 4 + 1) < 0.5 ? -1 : 1;
                const ms = o.duration * 1000 * (0.8 + 0.4 * rand(o.seed, i * 4 + 2));
                const frames = Array.from({ length: 13 }, (_, s) => {
                    const [x, y, r, k] = path(s / 12, amp);
                    return { transform: `translate(${x * sign}px, ${y}px) rotate(${r * sign}deg) scale(${k})` };
                });
                return el.animate?.(frames, { duration: ms, delay: -rand(o.seed, i * 4 + 3) * ms, iterations: Infinity });
            });
            const held = new Set();
            let hidden = false;
            let entered = ! o.entrance;
            {{-- Rise in one after another the first time the group scrolls into view. --}}
            const enter = () => {
                entered = true;
                items.forEach((el, i) => el.animate?.(
                    [{ opacity: 0, scale: 0.6 }, { opacity: 1, scale: 1 }],
                    { duration: 600, delay: i * 90, easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)', fill: 'backwards' },
                ));
            };
            const sync = () => loops.forEach((loop, i) => (hidden || held.has(i) ? loop?.pause() : loop?.play()));
            const hold = (on) => (e) => {
                const i = items.findIndex((el) => el.contains(e.target));
                if (i < 0 || (! on && items[i].contains(e.relatedTarget))) return;
                if (on) held.add(i);
                else held.delete(i);
                sync();
            };
            const pointer = (e) => {
                const r = root.getBoundingClientRect();
                const nx = Math.max(-1, Math.min(1, ((e.clientX - r.left) / r.width) * 2 - 1));
                const ny = Math.max(-1, Math.min(1, ((e.clientY - r.top) / r.height) * 2 - 1));
                items.forEach((el, i) => {
                    const depth = Number(el.dataset.depth ?? 0.3 + 0.7 * rand(o.seed, i * 4 + 1));
                    el.style.translate = `${nx * depth * o.parallax}px ${ny * depth * o.parallax}px`;
                });
            };
            const observer = typeof IntersectionObserver === 'undefined' ? null : new IntersectionObserver(([entry]) => {
                hidden = ! entry?.isIntersecting;
                if (! hidden && ! entered) enter();
                sync();
                if (! o.parallax) return;
                if (hidden) removeEventListener('pointermove', pointer);
                else addEventListener('pointermove', pointer);
            });
            if (observer) observer.observe(root);
            else {
                if (! entered) enter();
                if (o.parallax) addEventListener('pointermove', pointer);
            }
            const listeners = [['pointerover', hold(true)], ['pointerout', hold(false)], ['focusin', hold(true)], ['focusout', hold(false)]];
            for (const [type, fn] of listeners) root.addEventListener(type, fn);
            this.stop = () => {
                observer?.disconnect();
                removeEventListener('pointermove', pointer);
                for (const [type, fn] of listeners) root.removeEventListener(type, fn);
                for (const loop of loops) loop?.cancel();
                for (const el of items) el.style.translate = '';
            };
        },
        destroy() {
            this.stop?.();
        },
    }"
    {{ $attributes->class([$base]) }}
>
    {{ $slot }}
</div>
```

```blade
<div class="relative grid h-80 place-items-center overflow-hidden rounded-xl bg-canvas">
    <x-markas.float :parallax="14" aria-hidden="true" class="absolute inset-0">
        <span class="absolute top-[12%] left-[10%] rounded-xl bg-surface p-3">...</span>
        <span class="absolute right-[12%] bottom-[16%] rounded-xl bg-surface p-3">...</span>
    </x-markas.float>
    <h1 class="relative text-2xl font-semibold">Luncurkan idenya minggu ini</h1>
</div>
```

Butuh Alpine.js.

### React

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

```tsx
"use client";

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

const base =
  "[&>*]:transition-[translate] [&>*]:duration-700 [&>*]:ease-out motion-reduce:[&>*]:transition-none";

export type FloatMotion = "drift" | "bob" | "orbit" | "breathe";
type Options = {
  motion: FloatMotion;
  amplitude: number;
  duration: number;
  seed: number;
  parallax: number;
  entrance: boolean;
};

const STEPS = 12;
const TURN = Math.PI * 2;
const MS = 1000;
const STAGGER_MS = 90;
const ENTRANCE_MS = 600;
/** One loop of each motion: phase t (0 to 1) and amplitude a give x, y (px), rotation (deg), and scale. */
const PATHS: Record<FloatMotion, (t: number, a: number) => number[]> = {
  drift: (t, a) => [
    a * 0.6 * Math.sin(TURN * t),
    a * 0.5 * Math.sin(TURN * 2 * t),
    a * 0.3 * Math.sin(TURN * t),
    1,
  ],
  bob: (t, a) => [0, (-a * (1 - Math.cos(TURN * t))) / 2, 0, 1],
  orbit: (t, a) => [a * Math.cos(TURN * t), a * Math.sin(TURN * t), 0, 1],
  breathe: (t, a) => {
    const k = (1 - Math.cos(TURN * t)) / 2;
    return [0, -a * 0.3 * k, 0, 1 + (a / 100) * k];
  },
};

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;

/**
 * Float each child on its own loop, pause one while it is hovered or focused, and pause all
 * when off screen. With parallax, children shift toward the pointer by their depth.
 */
export function startFloat(root: HTMLElement, o: Options) {
  const items = [...root.children] as HTMLElement[];
  const path = PATHS[o.motion] ?? PATHS.drift;
  const loops = items.map((el, i) => {
    const amp = o.amplitude * (0.7 + 0.6 * rand(o.seed, i * 4));
    const sign = rand(o.seed, i * 4 + 1) < 0.5 ? -1 : 1;
    const ms = o.duration * MS * (0.8 + 0.4 * rand(o.seed, i * 4 + 2));
    const frames = Array.from({ length: STEPS + 1 }, (_, s) => {
      const [x, y, r, k] = path(s / STEPS, amp);
      return {
        transform: `translate(${x! * sign}px, ${y}px) rotate(${r! * sign}deg) scale(${k})`,
      };
    });
    return el.animate?.(frames, {
      duration: ms,
      delay: -rand(o.seed, i * 4 + 3) * ms,
      iterations: Infinity,
    });
  });
  const held = new Set<number>();
  let hidden = false;
  let entered = !o.entrance;
  /** Rise in one after another the first time the group scrolls into view. */
  const enter = () => {
    entered = true;
    items.forEach((el, i) =>
      el.animate?.(
        [
          { opacity: 0, scale: 0.6 },
          { opacity: 1, scale: 1 },
        ],
        {
          duration: ENTRANCE_MS,
          delay: i * STAGGER_MS,
          easing: "cubic-bezier(0.34, 1.56, 0.64, 1)",
          fill: "backwards",
        },
      ),
    );
  };
  const sync = () =>
    loops.forEach((loop, i) =>
      hidden || held.has(i) ? loop?.pause() : loop?.play(),
    );
  const hold = (on: boolean) => (e: Event) => {
    const i = items.findIndex((el) => el.contains(e.target as Node));
    const to = (e as FocusEvent).relatedTarget as Node | null;
    if (i < 0 || (!on && items[i]!.contains(to))) return;
    if (on) held.add(i);
    else held.delete(i);
    sync();
  };
  const pointer = (e: PointerEvent) => {
    const r = root.getBoundingClientRect();
    const nx = Math.max(
      -1,
      Math.min(1, ((e.clientX - r.left) / r.width) * 2 - 1),
    );
    const ny = Math.max(
      -1,
      Math.min(1, ((e.clientY - r.top) / r.height) * 2 - 1),
    );
    items.forEach((el, i) => {
      const depth = Number(
        el.dataset.depth ?? 0.3 + 0.7 * rand(o.seed, i * 4 + 1),
      );
      el.style.translate = `${nx * depth * o.parallax}px ${ny * depth * o.parallax}px`;
    });
  };
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver(([entry]) => {
          hidden = !entry?.isIntersecting;
          if (!hidden && !entered) enter();
          sync();
          if (!o.parallax) return;
          if (hidden) removeEventListener("pointermove", pointer);
          else addEventListener("pointermove", pointer);
        });
  if (observer) observer.observe(root);
  else {
    if (!entered) enter();
    if (o.parallax) addEventListener("pointermove", pointer);
  }
  const listeners = [
    ["pointerover", hold(true)],
    ["pointerout", hold(false)],
    ["focusin", hold(true)],
    ["focusout", hold(false)],
  ] as [string, (e: Event) => void][];
  for (const [type, fn] of listeners) root.addEventListener(type, fn);
  return () => {
    observer?.disconnect();
    removeEventListener("pointermove", pointer);
    for (const [type, fn] of listeners) root.removeEventListener(type, fn);
    for (const loop of loops) loop?.cancel();
    for (const el of items) el.style.translate = "";
  };
}

export type FloatProps = ComponentProps<"div"> & {
  /** Path each child follows: wander, rise and fall, circle, or swell. */
  motion?: FloatMotion;
  /** Distance in px each child travels, varied a little per child. For breathe, also the growth in percent. */
  amplitude?: number;
  /** Seconds for one loop, varied a little per child. */
  duration?: number;
  /** Changes the per-child timing, size, and direction. */
  seed?: number;
  /** Largest shift in px toward the pointer. 0 turns it off. */
  parallax?: number;
  /** Children pop in one after another the first time the group scrolls into view. */
  entrance?: boolean;
};

export function Float({
  motion = "drift",
  amplitude = 10,
  duration = 6,
  seed = 1,
  parallax = 0,
  entrance = false,
  className,
  children,
  ...props
}: FloatProps) {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!ref.current || still()) return;
    return startFloat(ref.current, {
      motion,
      amplitude,
      duration,
      seed,
      parallax,
      entrance,
    });
  }, [motion, amplitude, duration, seed, parallax, entrance]);
  return (
    <div ref={ref} {...props} className={cx(base, className)}>
      {children}
    </div>
  );
}
```

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

<Float
  motion="bob"
  amplitude={6}
  duration={3}
  className="absolute -top-3 right-5"
>
  <span className="rounded-full bg-primary px-3 py-1 text-xs text-on-primary">
    Hemat 20%
  </span>
</Float>;
```

### Vue

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

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

const props = withDefaults(
  defineProps<{
    /** Path each child follows: wander, rise and fall, circle, or swell. */
    motion?: "drift" | "bob" | "orbit" | "breathe";
    /** Distance in px each child travels, varied a little per child. For breathe, also the growth in percent. */
    amplitude?: number;
    /** Seconds for one loop, varied a little per child. */
    duration?: number;
    /** Changes the per-child timing, size, and direction. */
    seed?: number;
    /** Largest shift in px toward the pointer. 0 turns it off. */
    parallax?: number;
    /** Children pop in one after another the first time the group scrolls into view. */
    entrance?: boolean;
  }>(),
  {
    motion: "drift",
    amplitude: 10,
    duration: 6,
    seed: 1,
    parallax: 0,
    entrance: false,
  },
);

const base =
  "[&>*]:transition-[translate] [&>*]:duration-700 [&>*]:ease-out motion-reduce:[&>*]:transition-none";

type FloatMotion = "drift" | "bob" | "orbit" | "breathe";
type Options = {
  motion: FloatMotion;
  amplitude: number;
  duration: number;
  seed: number;
  parallax: number;
  entrance: boolean;
};

const STEPS = 12;
const TURN = Math.PI * 2;
const MS = 1000;
const STAGGER_MS = 90;
const ENTRANCE_MS = 600;
/** One loop of each motion: phase t (0 to 1) and amplitude a give x, y (px), rotation (deg), and scale. */
const PATHS: Record<FloatMotion, (t: number, a: number) => number[]> = {
  drift: (t, a) => [
    a * 0.6 * Math.sin(TURN * t),
    a * 0.5 * Math.sin(TURN * 2 * t),
    a * 0.3 * Math.sin(TURN * t),
    1,
  ],
  bob: (t, a) => [0, (-a * (1 - Math.cos(TURN * t))) / 2, 0, 1],
  orbit: (t, a) => [a * Math.cos(TURN * t), a * Math.sin(TURN * t), 0, 1],
  breathe: (t, a) => {
    const k = (1 - Math.cos(TURN * t)) / 2;
    return [0, -a * 0.3 * k, 0, 1 + (a / 100) * k];
  },
};

/** 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;

/**
 * Float each child on its own loop, pause one while it is hovered or focused, and pause all
 * when off screen. With parallax, children shift toward the pointer by their depth.
 */
function startFloat(root: HTMLElement, o: Options) {
  const items = [...root.children] as HTMLElement[];
  const path = PATHS[o.motion] ?? PATHS.drift;
  const loops = items.map((el, i) => {
    const amp = o.amplitude * (0.7 + 0.6 * rand(o.seed, i * 4));
    const sign = rand(o.seed, i * 4 + 1) < 0.5 ? -1 : 1;
    const ms = o.duration * MS * (0.8 + 0.4 * rand(o.seed, i * 4 + 2));
    const frames = Array.from({ length: STEPS + 1 }, (_, s) => {
      const [x, y, r, k] = path(s / STEPS, amp);
      return {
        transform: `translate(${x! * sign}px, ${y}px) rotate(${r! * sign}deg) scale(${k})`,
      };
    });
    return el.animate?.(frames, {
      duration: ms,
      delay: -rand(o.seed, i * 4 + 3) * ms,
      iterations: Infinity,
    });
  });
  const held = new Set<number>();
  let hidden = false;
  let entered = !o.entrance;
  /** Rise in one after another the first time the group scrolls into view. */
  const enter = () => {
    entered = true;
    items.forEach((el, i) =>
      el.animate?.(
        [
          { opacity: 0, scale: 0.6 },
          { opacity: 1, scale: 1 },
        ],
        {
          duration: ENTRANCE_MS,
          delay: i * STAGGER_MS,
          easing: "cubic-bezier(0.34, 1.56, 0.64, 1)",
          fill: "backwards",
        },
      ),
    );
  };
  const sync = () =>
    loops.forEach((loop, i) =>
      hidden || held.has(i) ? loop?.pause() : loop?.play(),
    );
  const hold = (on: boolean) => (e: Event) => {
    const i = items.findIndex((el) => el.contains(e.target as Node));
    const to = (e as FocusEvent).relatedTarget as Node | null;
    if (i < 0 || (!on && items[i]!.contains(to))) return;
    if (on) held.add(i);
    else held.delete(i);
    sync();
  };
  const pointer = (e: PointerEvent) => {
    const r = root.getBoundingClientRect();
    const nx = Math.max(
      -1,
      Math.min(1, ((e.clientX - r.left) / r.width) * 2 - 1),
    );
    const ny = Math.max(
      -1,
      Math.min(1, ((e.clientY - r.top) / r.height) * 2 - 1),
    );
    items.forEach((el, i) => {
      const depth = Number(
        el.dataset.depth ?? 0.3 + 0.7 * rand(o.seed, i * 4 + 1),
      );
      el.style.translate = `${nx * depth * o.parallax}px ${ny * depth * o.parallax}px`;
    });
  };
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver(([entry]) => {
          hidden = !entry?.isIntersecting;
          if (!hidden && !entered) enter();
          sync();
          if (!o.parallax) return;
          if (hidden) removeEventListener("pointermove", pointer);
          else addEventListener("pointermove", pointer);
        });
  if (observer) observer.observe(root);
  else {
    if (!entered) enter();
    if (o.parallax) addEventListener("pointermove", pointer);
  }
  const listeners = [
    ["pointerover", hold(true)],
    ["pointerout", hold(false)],
    ["focusin", hold(true)],
    ["focusout", hold(false)],
  ] as [string, (e: Event) => void][];
  for (const [type, fn] of listeners) root.addEventListener(type, fn);
  return () => {
    observer?.disconnect();
    removeEventListener("pointermove", pointer);
    for (const [type, fn] of listeners) root.removeEventListener(type, fn);
    for (const loop of loops) loop?.cancel();
    for (const el of items) el.style.translate = "";
  };
}

const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
let stop = () => {};
function start() {
  stop();
  stop = () => {};
  if (rootEl.value && !still()) stop = startFloat(rootEl.value, { ...props });
}
onMounted(start);
watch(() => ({ ...props }), start, { flush: "post" });
onBeforeUnmount(() => stop());
</script>

<template>
  <div ref="rootRef" :class="base">
    <slot />
  </div>
</template>
```

```vue
<template>
  <Float
    motion="orbit"
    :amplitude="8"
    entrance
    aria-hidden="true"
    class="absolute inset-0"
  >
    <span
      class="absolute top-[14%] left-[18%] size-12 rounded-full bg-primary-soft"
      >RP</span
    >
    <span
      class="absolute right-[14%] bottom-[18%] size-14 rounded-full bg-primary"
      >DP</span
    >
  </Float>
</template>
```

### Svelte

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

```svelte
<script lang="ts" module>
  export type FloatMotion = "drift" | "bob" | "orbit" | "breathe";
  type Options = {
    motion: FloatMotion;
    amplitude: number;
    duration: number;
    seed: number;
    parallax: number;
    entrance: boolean;
  };

  const STEPS = 12;
  const TURN = Math.PI * 2;
  const MS = 1000;
  const STAGGER_MS = 90;
  const ENTRANCE_MS = 600;
  /** One loop of each motion: phase t (0 to 1) and amplitude a give x, y (px), rotation (deg), and scale. */
  const PATHS: Record<FloatMotion, (t: number, a: number) => number[]> = {
    drift: (t, a) => [
      a * 0.6 * Math.sin(TURN * t),
      a * 0.5 * Math.sin(TURN * 2 * t),
      a * 0.3 * Math.sin(TURN * t),
      1,
    ],
    bob: (t, a) => [0, (-a * (1 - Math.cos(TURN * t))) / 2, 0, 1],
    orbit: (t, a) => [a * Math.cos(TURN * t), a * Math.sin(TURN * t), 0, 1],
    breathe: (t, a) => {
      const k = (1 - Math.cos(TURN * t)) / 2;
      return [0, -a * 0.3 * k, 0, 1 + (a / 100) * k];
    },
  };

  /** 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;

  /**
   * Float each child on its own loop, pause one while it is hovered or focused, and pause all
   * when off screen. With parallax, children shift toward the pointer by their depth.
   */
  export function startFloat(root: HTMLElement, o: Options) {
    const items = [...root.children] as HTMLElement[];
    const path = PATHS[o.motion] ?? PATHS.drift;
    const loops = items.map((el, i) => {
      const amp = o.amplitude * (0.7 + 0.6 * rand(o.seed, i * 4));
      const sign = rand(o.seed, i * 4 + 1) < 0.5 ? -1 : 1;
      const ms = o.duration * MS * (0.8 + 0.4 * rand(o.seed, i * 4 + 2));
      const frames = Array.from({ length: STEPS + 1 }, (_, s) => {
        const [x, y, r, k] = path(s / STEPS, amp);
        return {
          transform: `translate(${x! * sign}px, ${y}px) rotate(${r! * sign}deg) scale(${k})`,
        };
      });
      return el.animate?.(frames, {
        duration: ms,
        delay: -rand(o.seed, i * 4 + 3) * ms,
        iterations: Infinity,
      });
    });
    const held = new Set<number>();
    let hidden = false;
    let entered = !o.entrance;
    /** Rise in one after another the first time the group scrolls into view. */
    const enter = () => {
      entered = true;
      items.forEach((el, i) =>
        el.animate?.(
          [
            { opacity: 0, scale: 0.6 },
            { opacity: 1, scale: 1 },
          ],
          {
            duration: ENTRANCE_MS,
            delay: i * STAGGER_MS,
            easing: "cubic-bezier(0.34, 1.56, 0.64, 1)",
            fill: "backwards",
          },
        ),
      );
    };
    const sync = () =>
      loops.forEach((loop, i) =>
        hidden || held.has(i) ? loop?.pause() : loop?.play(),
      );
    const hold = (on: boolean) => (e: Event) => {
      const i = items.findIndex((el) => el.contains(e.target as Node));
      const to = (e as FocusEvent).relatedTarget as Node | null;
      if (i < 0 || (!on && items[i]!.contains(to))) return;
      if (on) held.add(i);
      else held.delete(i);
      sync();
    };
    const pointer = (e: PointerEvent) => {
      const r = root.getBoundingClientRect();
      const nx = Math.max(
        -1,
        Math.min(1, ((e.clientX - r.left) / r.width) * 2 - 1),
      );
      const ny = Math.max(
        -1,
        Math.min(1, ((e.clientY - r.top) / r.height) * 2 - 1),
      );
      items.forEach((el, i) => {
        const depth = Number(
          el.dataset.depth ?? 0.3 + 0.7 * rand(o.seed, i * 4 + 1),
        );
        el.style.translate = `${nx * depth * o.parallax}px ${ny * depth * o.parallax}px`;
      });
    };
    const observer =
      typeof IntersectionObserver === "undefined"
        ? undefined
        : new IntersectionObserver(([entry]) => {
            hidden = !entry?.isIntersecting;
            if (!hidden && !entered) enter();
            sync();
            if (!o.parallax) return;
            if (hidden) removeEventListener("pointermove", pointer);
            else addEventListener("pointermove", pointer);
          });
    if (observer) observer.observe(root);
    else {
      if (!entered) enter();
      if (o.parallax) addEventListener("pointermove", pointer);
    }
    const listeners = [
      ["pointerover", hold(true)],
      ["pointerout", hold(false)],
      ["focusin", hold(true)],
      ["focusout", hold(false)],
    ] as [string, (e: Event) => void][];
    for (const [type, fn] of listeners) root.addEventListener(type, fn);
    return () => {
      observer?.disconnect();
      removeEventListener("pointermove", pointer);
      for (const [type, fn] of listeners) root.removeEventListener(type, fn);
      for (const loop of loops) loop?.cancel();
      for (const el of items) el.style.translate = "";
    };
  }
</script>

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

  const base =
    "[&>*]:transition-[translate] [&>*]:duration-700 [&>*]:ease-out motion-reduce:[&>*]:transition-none";

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** Path each child follows: wander, rise and fall, circle, or swell. */
    motion?: FloatMotion;
    /** Distance in px each child travels, varied a little per child. For breathe, also the growth in percent. */
    amplitude?: number;
    /** Seconds for one loop, varied a little per child. */
    duration?: number;
    /** Changes the per-child timing, size, and direction. */
    seed?: number;
    /** Largest shift in px toward the pointer. 0 turns it off. */
    parallax?: number;
    /** Children pop in one after another the first time the group scrolls into view. */
    entrance?: boolean;
    children?: Snippet;
  };

  let {
    motion = "drift",
    amplitude = 10,
    duration = 6,
    seed = 1,
    parallax = 0,
    entrance = false,
    class: className,
    children,
    ...rest
  }: Props = $props();

  let rootEl = $state<HTMLDivElement>();

  $effect(() => {
    if (!rootEl || still()) return;
    return startFloat(rootEl, {
      motion,
      amplitude,
      duration,
      seed,
      parallax,
      entrance,
    });
  });
</script>

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

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

<Float motion="bob" amplitude={6} duration={3} class="absolute -top-3 right-5">
  <span class="rounded-full bg-primary px-3 py-1 text-xs text-on-primary">
    Save 20%
  </span>
</Float>
```

### Astro

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

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

const base =
  "[&>*]:transition-[translate] [&>*]:duration-700 [&>*]:ease-out motion-reduce:[&>*]:transition-none";

export type FloatMotion = "drift" | "bob" | "orbit" | "breathe";

type Props = HTMLAttributes<"div"> & {
  /** Path each child follows: wander, rise and fall, circle, or swell. */
  motion?: FloatMotion;
  /** Distance in px each child travels, varied a little per child. For breathe, also the growth in percent. */
  amplitude?: number;
  /** Seconds for one loop, varied a little per child. */
  duration?: number;
  /** Changes the per-child timing, size, and direction. */
  seed?: number;
  /** Largest shift in px toward the pointer. 0 turns it off. */
  parallax?: number;
  /** Children pop in one after another the first time the group scrolls into view. */
  entrance?: boolean;
};

const {
  motion = "drift",
  amplitude = 10,
  duration = 6,
  seed = 1,
  parallax = 0,
  entrance = false,
  class: className,
  ...rest
} = Astro.props;
---

<markas-float
  class="contents"
  data-motion={motion}
  data-amplitude={amplitude}
  data-duration={duration}
  data-seed={seed}
  data-parallax={parallax}
  data-entrance={entrance ? "" : undefined}
>
  <div {...rest} class:list={[base, className]}>
    <slot />
  </div>
</markas-float>

<script>
  type FloatMotion = "drift" | "bob" | "orbit" | "breathe";
  type Options = {
    motion: FloatMotion;
    amplitude: number;
    duration: number;
    seed: number;
    parallax: number;
    entrance: boolean;
  };

  const STEPS = 12;
  const TURN = Math.PI * 2;
  const MS = 1000;
  const STAGGER_MS = 90;
  const ENTRANCE_MS = 600;
  /** One loop of each motion: phase t (0 to 1) and amplitude a give x, y (px), rotation (deg), and scale. */
  const PATHS: Record<FloatMotion, (t: number, a: number) => number[]> = {
    drift: (t, a) => [
      a * 0.6 * Math.sin(TURN * t),
      a * 0.5 * Math.sin(TURN * 2 * t),
      a * 0.3 * Math.sin(TURN * t),
      1,
    ],
    bob: (t, a) => [0, (-a * (1 - Math.cos(TURN * t))) / 2, 0, 1],
    orbit: (t, a) => [a * Math.cos(TURN * t), a * Math.sin(TURN * t), 0, 1],
    breathe: (t, a) => {
      const k = (1 - Math.cos(TURN * t)) / 2;
      return [0, -a * 0.3 * k, 0, 1 + (a / 100) * k];
    },
  };

  /** 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;

  /**
   * Float each child on its own loop, pause one while it is hovered or focused, and pause all
   * when off screen. With parallax, children shift toward the pointer by their depth.
   */
  function startFloat(root: HTMLElement, o: Options) {
    const items = [...root.children] as HTMLElement[];
    const path = PATHS[o.motion] ?? PATHS.drift;
    const loops = items.map((el, i) => {
      const amp = o.amplitude * (0.7 + 0.6 * rand(o.seed, i * 4));
      const sign = rand(o.seed, i * 4 + 1) < 0.5 ? -1 : 1;
      const ms = o.duration * MS * (0.8 + 0.4 * rand(o.seed, i * 4 + 2));
      const frames = Array.from({ length: STEPS + 1 }, (_, s) => {
        const [x, y, r, k] = path(s / STEPS, amp);
        return {
          transform: `translate(${x! * sign}px, ${y}px) rotate(${r! * sign}deg) scale(${k})`,
        };
      });
      return el.animate?.(frames, {
        duration: ms,
        delay: -rand(o.seed, i * 4 + 3) * ms,
        iterations: Infinity,
      });
    });
    const held = new Set<number>();
    let hidden = false;
    let entered = !o.entrance;
    /** Rise in one after another the first time the group scrolls into view. */
    const enter = () => {
      entered = true;
      items.forEach((el, i) =>
        el.animate?.(
          [
            { opacity: 0, scale: 0.6 },
            { opacity: 1, scale: 1 },
          ],
          {
            duration: ENTRANCE_MS,
            delay: i * STAGGER_MS,
            easing: "cubic-bezier(0.34, 1.56, 0.64, 1)",
            fill: "backwards",
          },
        ),
      );
    };
    const sync = () =>
      loops.forEach((loop, i) =>
        hidden || held.has(i) ? loop?.pause() : loop?.play(),
      );
    const hold = (on: boolean) => (e: Event) => {
      const i = items.findIndex((el) => el.contains(e.target as Node));
      const to = (e as FocusEvent).relatedTarget as Node | null;
      if (i < 0 || (!on && items[i]!.contains(to))) return;
      if (on) held.add(i);
      else held.delete(i);
      sync();
    };
    const pointer = (e: PointerEvent) => {
      const r = root.getBoundingClientRect();
      const nx = Math.max(
        -1,
        Math.min(1, ((e.clientX - r.left) / r.width) * 2 - 1),
      );
      const ny = Math.max(
        -1,
        Math.min(1, ((e.clientY - r.top) / r.height) * 2 - 1),
      );
      items.forEach((el, i) => {
        const depth = Number(
          el.dataset.depth ?? 0.3 + 0.7 * rand(o.seed, i * 4 + 1),
        );
        el.style.translate = `${nx * depth * o.parallax}px ${ny * depth * o.parallax}px`;
      });
    };
    const observer =
      typeof IntersectionObserver === "undefined"
        ? undefined
        : new IntersectionObserver(([entry]) => {
            hidden = !entry?.isIntersecting;
            if (!hidden && !entered) enter();
            sync();
            if (!o.parallax) return;
            if (hidden) removeEventListener("pointermove", pointer);
            else addEventListener("pointermove", pointer);
          });
    if (observer) observer.observe(root);
    else {
      if (!entered) enter();
      if (o.parallax) addEventListener("pointermove", pointer);
    }
    const listeners = [
      ["pointerover", hold(true)],
      ["pointerout", hold(false)],
      ["focusin", hold(true)],
      ["focusout", hold(false)],
    ] as [string, (e: Event) => void][];
    for (const [type, fn] of listeners) root.addEventListener(type, fn);
    return () => {
      observer?.disconnect();
      removeEventListener("pointermove", pointer);
      for (const [type, fn] of listeners) root.removeEventListener(type, fn);
      for (const loop of loops) loop?.cancel();
      for (const el of items) el.style.translate = "";
    };
  }

  // Each group runs its own loops, so it is a custom element: it also works for markup added
  // later and for pages reached through view transitions.
  class MarkasFloat extends HTMLElement {
    private stop?: () => void;

    connectedCallback() {
      const root = this.firstElementChild;
      if (this.stop || !(root instanceof HTMLElement) || still()) return;
      const d = this.dataset;
      this.stop = startFloat(root, {
        motion: (d.motion ?? "drift") as FloatMotion,
        amplitude: Number(d.amplitude),
        duration: Number(d.duration),
        seed: Number(d.seed),
        parallax: Number(d.parallax),
        entrance: d.entrance !== undefined,
      });
    }

    disconnectedCallback() {
      this.stop?.();
      this.stop = undefined;
    }
  }

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

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

<Float motion="bob" amplitude={6} duration={3} class="absolute -top-3 right-5">
  <span class="rounded-full bg-primary px-3 py-1 text-xs text-on-primary">
    Save 20%
  </span>
</Float>
```

Setiap grup adalah custom element kecil, jadi tetap jalan setelah view transition.

### Angular

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

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

const base =
  "[&>*]:transition-[translate] [&>*]:duration-700 [&>*]:ease-out motion-reduce:[&>*]:transition-none";

export type FloatMotion = "drift" | "bob" | "orbit" | "breathe";
type Options = {
  motion: FloatMotion;
  amplitude: number;
  duration: number;
  seed: number;
  parallax: number;
  entrance: boolean;
};

const STEPS = 12;
const TURN = Math.PI * 2;
const MS = 1000;
const STAGGER_MS = 90;
const ENTRANCE_MS = 600;
/** One loop of each motion: phase t (0 to 1) and amplitude a give x, y (px), rotation (deg), and scale. */
const PATHS: Record<FloatMotion, (t: number, a: number) => number[]> = {
  drift: (t, a) => [
    a * 0.6 * Math.sin(TURN * t),
    a * 0.5 * Math.sin(TURN * 2 * t),
    a * 0.3 * Math.sin(TURN * t),
    1,
  ],
  bob: (t, a) => [0, (-a * (1 - Math.cos(TURN * t))) / 2, 0, 1],
  orbit: (t, a) => [a * Math.cos(TURN * t), a * Math.sin(TURN * t), 0, 1],
  breathe: (t, a) => {
    const k = (1 - Math.cos(TURN * t)) / 2;
    return [0, -a * 0.3 * k, 0, 1 + (a / 100) * k];
  },
};

/** 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;

/**
 * Float each child on its own loop, pause one while it is hovered or focused, and pause all
 * when off screen. With parallax, children shift toward the pointer by their depth.
 */
export function startFloat(root: HTMLElement, o: Options) {
  const items = [...root.children] as HTMLElement[];
  const path = PATHS[o.motion] ?? PATHS.drift;
  const loops = items.map((el, i) => {
    const amp = o.amplitude * (0.7 + 0.6 * rand(o.seed, i * 4));
    const sign = rand(o.seed, i * 4 + 1) < 0.5 ? -1 : 1;
    const ms = o.duration * MS * (0.8 + 0.4 * rand(o.seed, i * 4 + 2));
    const frames = Array.from({ length: STEPS + 1 }, (_, s) => {
      const [x, y, r, k] = path(s / STEPS, amp);
      return {
        transform: `translate(${x! * sign}px, ${y}px) rotate(${r! * sign}deg) scale(${k})`,
      };
    });
    return el.animate?.(frames, {
      duration: ms,
      delay: -rand(o.seed, i * 4 + 3) * ms,
      iterations: Infinity,
    });
  });
  const held = new Set<number>();
  let hidden = false;
  let entered = !o.entrance;
  /** Rise in one after another the first time the group scrolls into view. */
  const enter = () => {
    entered = true;
    items.forEach((el, i) =>
      el.animate?.(
        [
          { opacity: 0, scale: 0.6 },
          { opacity: 1, scale: 1 },
        ],
        {
          duration: ENTRANCE_MS,
          delay: i * STAGGER_MS,
          easing: "cubic-bezier(0.34, 1.56, 0.64, 1)",
          fill: "backwards",
        },
      ),
    );
  };
  const sync = () =>
    loops.forEach((loop, i) =>
      hidden || held.has(i) ? loop?.pause() : loop?.play(),
    );
  const hold = (on: boolean) => (e: Event) => {
    const i = items.findIndex((el) => el.contains(e.target as Node));
    const to = (e as FocusEvent).relatedTarget as Node | null;
    if (i < 0 || (!on && items[i]!.contains(to))) return;
    if (on) held.add(i);
    else held.delete(i);
    sync();
  };
  const pointer = (e: PointerEvent) => {
    const r = root.getBoundingClientRect();
    const nx = Math.max(
      -1,
      Math.min(1, ((e.clientX - r.left) / r.width) * 2 - 1),
    );
    const ny = Math.max(
      -1,
      Math.min(1, ((e.clientY - r.top) / r.height) * 2 - 1),
    );
    items.forEach((el, i) => {
      const depth = Number(
        el.dataset.depth ?? 0.3 + 0.7 * rand(o.seed, i * 4 + 1),
      );
      el.style.translate = `${nx * depth * o.parallax}px ${ny * depth * o.parallax}px`;
    });
  };
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver(([entry]) => {
          hidden = !entry?.isIntersecting;
          if (!hidden && !entered) enter();
          sync();
          if (!o.parallax) return;
          if (hidden) removeEventListener("pointermove", pointer);
          else addEventListener("pointermove", pointer);
        });
  if (observer) observer.observe(root);
  else {
    if (!entered) enter();
    if (o.parallax) addEventListener("pointermove", pointer);
  }
  const listeners = [
    ["pointerover", hold(true)],
    ["pointerout", hold(false)],
    ["focusin", hold(true)],
    ["focusout", hold(false)],
  ] as [string, (e: Event) => void][];
  for (const [type, fn] of listeners) root.addEventListener(type, fn);
  return () => {
    observer?.disconnect();
    removeEventListener("pointermove", pointer);
    for (const [type, fn] of listeners) root.removeEventListener(type, fn);
    for (const loop of loops) loop?.cancel();
    for (const el of items) el.style.translate = "";
  };
}

/**
 * Every projected child floats. Host stays out of layout; aria-hidden and class move to the
 * group.
 */
@Component({
  selector: "markas-float",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.aria-hidden]": "null" },
  template: `
    <div
      #groupEl
      [attr.aria-hidden]="ariaHidden() ?? null"
      [class]="rootClasses()"
    >
      <ng-content />
    </div>
  `,
})
export class Float {
  /** Path each child follows: wander, rise and fall, circle, or swell. */
  readonly motion = input<FloatMotion>("drift");
  /** Distance in px each child travels, varied a little per child. For breathe, also the growth in percent. */
  readonly amplitude = input(10, { transform: numberAttribute });
  /** Seconds for one loop, varied a little per child. */
  readonly duration = input(6, { transform: numberAttribute });
  /** Changes the per-child timing, size, and direction. */
  readonly seed = input(1, { transform: numberAttribute });
  /** Largest shift in px toward the pointer. 0 turns it off. */
  readonly parallax = input(0, { transform: numberAttribute });
  /** Children pop in one after another the first time the group scrolls into view. */
  readonly entrance = input(false, { transform: booleanAttribute });
  readonly ariaHidden = input<string | undefined>(undefined, {
    alias: "aria-hidden",
  });
  readonly userClass = input("", { alias: "class" });

  protected readonly rootClasses = computed(() =>
    [base, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly groupEl =
    viewChild.required<ElementRef<HTMLDivElement>>("groupEl");

  constructor() {
    // Runs after the children are in the DOM, and again when an option changes.
    afterRenderEffect((onCleanup) => {
      const options = {
        motion: this.motion(),
        amplitude: this.amplitude(),
        duration: this.duration(),
        seed: this.seed(),
        parallax: this.parallax(),
        entrance: this.entrance(),
      };
      if (still()) return;
      onCleanup(startFloat(this.groupEl().nativeElement, options));
    });
  }
}
```

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

@Component({
  selector: "app-save-badge",
  imports: [Float],
  template: `
    <markas-float
      motion="bob"
      [amplitude]="6"
      [duration]="3"
      class="absolute -top-3 right-5"
    >
      <span class="rounded-full bg-primary px-3 py-1 text-xs text-on-primary">
        Save 20%
      </span>
    </markas-float>
  `,
})
export class SaveBadge {}
```

`aria-hidden` dan `class` pindah dari host ke grup.

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `motion` | `"drift" \| "bob" \| "orbit" \| "breathe"` | "drift" | Jalur yang diikuti setiap anak: angka delapan pelan dengan sedikit goyang, naik turun, lingkaran kecil, atau membesar lembut. |
| `amplitude` | `number` | 10 | Jarak tempuh setiap anak dalam px, sedikit berbeda per anak. Untuk breathe juga besar pembesaran dalam persen. |
| `duration` | `number` | 6 | Detik untuk satu putaran, sedikit berbeda per anak supaya tidak pernah bergerak serempak. |
| `seed` | `number` | 1 | Mengubah waktu, ukuran, dan arah per anak. Seed yang sama selalu menghasilkan gerakan yang sama. |
| `parallax` | `number` | 0 | Pergeseran terbesar dalam px ke arah kursor. Setiap anak bergerak sesuai kedalamannya: data-depth="0.2" sampai "1", atau kedalaman dari seed. 0 mematikannya. |
| `entrance` | `boolean` | false | Anak-anak muncul satu per satu saat grup pertama kali masuk layar. |
| `children / slot` | `ReactNode / slot` | - | Item yang melayang. Setiap anak langsung bergerak sendiri; atur posisinya dengan class sendiri, misalnya absolute top-[12%] left-[10%]. |

## Aksesibilitas

- Gerakan melayang hanya dekorasi; tandai grup yang murni dekoratif dengan aria-hidden="true".
- Anak berhenti bergerak saat disorot kursor atau memegang fokus keyboard, sehingga tombol dan tautan yang melayang tetap mudah dikenai.
- Semua putaran berhenti saat grup di luar layar.
- Dengan reduced motion tidak ada yang bergerak: tanpa putaran, parallax, atau kemunculan.

## Catatan

- Setiap anak langsung melayang dengan ritmenya sendiri. `motion` memilih jalurnya: `drift` (angka delapan dengan sedikit goyang), `bob` (naik turun), `orbit` (lingkaran kecil), atau `breathe` (membesar lembut).
- Waktu, ukuran, dan arah berbeda per anak dari `seed`, sehingga seed yang sama terlihat sama di Blade, React, dan Vue.
- `parallax` menggeser anak ke arah kursor. Pasang `data-depth="0.2"` sampai `"1"` pada anak untuk mengatur seberapa jauh ia bergerak.
- `entrance` memunculkan anak satu per satu saat grup pertama kali masuk layar.
- Anak berhenti saat disorot kursor atau difokus, dan semua putaran berhenti di luar layar. Putaran menganimasikan `transform` pada setiap anak; bungkus anak yang butuh utilitas transform sendiri.
