# Float

Wrapper that makes its children drift, bob, orbit, or breathe on their own loops, with optional pointer parallax and a staggered entrance.

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

## When to use

Ambient life around a focal point: icons or logos around a hero heading, a badge on a pricing card, avatars around a community number.

- Keep amplitude small (4 to 14) so the motion stays calm
- Float a handful of decorative items, not body text or form fields
- The animation uses transform on each direct child; wrap a child if it needs its own transform utilities
- Use parallax on a hero-sized area, not on small inline groups

## Code

### Blade

Save at `resources/views/components/markas/float.blade.php`. Dependencies: 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">Ship the idea this week</h1>
</div>
```

Needs Alpine.js.

### React

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

```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">
    Save 20%
  </span>
</Float>;
```

### Vue

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

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

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

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

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

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

Each group is a small custom element, so it keeps working after view transitions.

### Angular

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

```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` and `class` move from the host to the group.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `motion` | `"drift" \| "bob" \| "orbit" \| "breathe"` | "drift" | Path each child follows: a slow figure eight with a slight sway, a rise and fall, a small circle, or a gentle swell. |
| `amplitude` | `number` | 10 | Distance in px each child travels, varied a little per child. For breathe it is also the growth in percent. |
| `duration` | `number` | 6 | Seconds for one loop, varied a little per child so they never move in step. |
| `seed` | `number` | 1 | Changes the per-child timing, size, and direction. The same seed always gives the same motion. |
| `parallax` | `number` | 0 | Largest shift in px toward the pointer. Each child moves by its depth: data-depth="0.2" to "1", or a seeded depth. 0 turns it off. |
| `entrance` | `boolean` | false | Children pop in one after another the first time the group scrolls into view. |
| `children / slot` | `ReactNode / slot` | - | The floating items. Each direct child moves on its own; position them with your own classes, such as absolute top-[12%] left-[10%]. |

## Accessibility

- Floating is decoration only; mark a purely decorative group with aria-hidden="true".
- A child stops moving while it is hovered or holds keyboard focus, so floating buttons and links stay easy to hit.
- All loops pause while the group is off screen.
- With reduced motion nothing moves: no loops, parallax, or entrance.

## Notes

- Every direct child floats on its own loop. `motion` picks the path: `drift` (figure eight with a slight sway), `bob` (rise and fall), `orbit` (small circle), or `breathe` (gentle swell).
- Timing, size, and direction vary per child from `seed`, so the same seed looks the same in Blade, React, and Vue.
- `parallax` shifts children toward the pointer. Set `data-depth="0.2"` to `"1"` on a child to control how far it moves.
- `entrance` pops the children in one after another the first time the group scrolls into view.
- A child stops while it is hovered or focused, and all loops pause off screen. The loop animates `transform` on each child; wrap a child that needs its own transform utilities.
