# Drag Elements

Area of cards or stickers you can drag around with light momentum, kept inside its bounds. Arrow keys move a focused item, Escape puts it back.

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

## When to use

Playful spaces people can rearrange: moodboards, sticker walls, team or plan cards to compare, a hero with things to fiddle with.

- Give the area a height, such as h-80, and a background or border so its bounds are visible
- Keep three to eight items; use data-x and data-y when the layout matters
- Add role="group" and an aria-label to the area
- Do not use it for real ordering or sorting; positions are not saved or announced

## Code

### Blade

Save at `resources/views/components/markas/drag-elements.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'release' => 'inertia',
    'rotate' => 6,
    'seed' => 1,
    'hintLabel' => 'Drag to move, or use the arrow keys. Escape puts it back',
])

@php
    $base = 'relative isolate overflow-hidden [&>*]:absolute [&>*]:cursor-grab [&>*]:touch-none [&>*]:select-none [&>*]:transition-[translate,scale,box-shadow] [&>*]:duration-500 [&>*]:ease-[cubic-bezier(0.34,1.56,0.64,1)] [&>*]:focus-visible:outline-2 [&>*]:focus-visible:outline-offset-2 [&>*]:focus-visible:outline-primary [&>[data-dragging]]:scale-105 [&>[data-dragging]]:cursor-grabbing [&>[data-dragging]]:shadow-overlay [&>[data-dragging]]:transition-[scale,box-shadow] [&>[data-dragging]]:duration-150 [&>[data-gliding]]:transition-none motion-reduce:[&>*]:transition-none!';
    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-drag-elements|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $hintId = 'markas-drag-elements-'.hash('xxh32', $idKey.$idIndex);
@endphp

{{-- Scatters the children, then lets pointer and keyboard move each one inside the area. data-x, data-y (percent) and data-rotate (deg) on a child override the seeded spot. --}}
<div
    wire:ignore
    x-data="{
        stop: null,
        init() {
            const o = { release: @js($release), rotate: @js((float) $rotate), seed: @js((float) $seed), hint: @js($hintId) };
            const root = this.$el;
            const clamp = (v, min, max) => Math.min(Math.max(v, min), max);
            const rand = (seed, n) => {
                const x = Math.sin(seed * 78.233 + n * 12.9898) * 43758.5453;
                return x - Math.floor(x);
            };
            const items = () => [...root.children].filter((el) => el instanceof HTMLElement && ! el.hidden);
            const pos = new Map();
            const keys = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] };
            let top = 0;
            let frame = 0;
            let drag = null;
            items().forEach((el, i) => {
                const d = el.dataset;
                const x = Number(d.x ?? Math.round(rand(o.seed, i * 3) * 100));
                const y = Number(d.y ?? Math.round(rand(o.seed, i * 3 + 1) * 100));
                const r = Number(d.rotate ?? Math.round((rand(o.seed, i * 3 + 2) * 2 - 1) * o.rotate));
                el.style.left = `${x}%`;
                el.style.top = `${y}%`;
                el.style.transform = `translate(-${x}%, -${y}%)`;
                el.style.rotate = `${r}deg`;
                if (! el.hasAttribute('tabindex')) el.tabIndex = 0;
                el.setAttribute('aria-describedby', o.hint);
                top = i + 1;
            });
            const at = (el) => pos.get(el) ?? [0, 0];
            const set = (el, x, y) => {
                pos.set(el, [x, y]);
                el.style.translate = `${x}px ${y}px`;
            };
            const raise = (el) => (el.style.zIndex = String(++top));
            const limits = (el) => {
                const r = el.getBoundingClientRect();
                const c = root.getBoundingClientRect();
                const [x = 0, y = 0] = getComputedStyle(el).translate.split(' ').map((v) => parseFloat(v) || 0);
                return [c.left - r.left + x, c.right - r.right + x, c.top - r.top + y, c.bottom - r.bottom + y];
            };
            const item = (target) => items().find((el) => el.contains(target));
            const glide = (el, vx, vy, lim) => {
                el.dataset.gliding = '';
                const step = () => {
                    const [a, b, c, d] = lim;
                    let [x, y] = at(el);
                    x += vx;
                    y += vy;
                    if (x < a || x > b) vx *= -0.4;
                    if (y < c || y > d) vy *= -0.4;
                    vx *= 0.9;
                    vy *= 0.9;
                    set(el, clamp(x, a, b), clamp(y, c, d));
                    if (Math.hypot(vx, vy) > 0.2) frame = requestAnimationFrame(step);
                    else delete el.dataset.gliding;
                };
                frame = requestAnimationFrame(step);
            };
            const down = (e) => {
                const el = item(e.target);
                const control = e.target.closest?.('a,button,input,select,textarea,label');
                if (! el || e.button !== 0 || (control && control !== el && el.contains(control))) return;
                cancelAnimationFrame(frame);
                for (const other of items()) delete other.dataset.gliding;
                el.setPointerCapture?.(e.pointerId);
                el.dataset.dragging = '';
                raise(el);
                const [x, y] = at(el);
                drag = { el, sx: e.clientX - x, sy: e.clientY - y, lim: limits(el), vx: 0, vy: 0, lx: e.clientX, ly: e.clientY, t: e.timeStamp };
            };
            const move = (e) => {
                if (! drag) return;
                const [a, b, c, d] = drag.lim;
                const dt = Math.max(e.timeStamp - drag.t, 1);
                set(drag.el, clamp(e.clientX - drag.sx, a, b), clamp(e.clientY - drag.sy, c, d));
                drag.vx = ((e.clientX - drag.lx) / dt) * 16;
                drag.vy = ((e.clientY - drag.ly) / dt) * 16;
                drag.lx = e.clientX;
                drag.ly = e.clientY;
                drag.t = e.timeStamp;
            };
            const up = (e) => {
                if (! drag) return;
                const { el, lim, t } = drag;
                const fresh = e.timeStamp - t > 80 ? 0 : 1;
                const vx = drag.vx * fresh;
                const vy = drag.vy * fresh;
                drag = null;
                delete el.dataset.dragging;
                if (o.release === 'return') set(el, 0, 0);
                else if (o.release === 'inertia' && ! matchMedia('(prefers-reduced-motion: reduce)').matches)
                    glide(el, clamp(vx, -24, 24), clamp(vy, -24, 24), lim);
            };
            const key = (e) => {
                const el = items().find((i) => i === e.target);
                const dir = keys[e.key];
                if (! el) return;
                const [x, y] = at(el);
                if (e.key === 'Escape' && (x || y)) set(el, 0, 0);
                else if (dir) {
                    const [a, b, c, d] = limits(el);
                    const step = e.shiftKey ? 50 : 10;
                    set(el, clamp(x + dir[0] * step, a, b), clamp(y + dir[1] * step, c, d));
                } else return;
                e.preventDefault();
                raise(el);
            };
            const focus = (e) => {
                const el = item(e.target);
                if (el) raise(el);
            };
            const listeners = [['pointerdown', down], ['pointermove', move], ['pointerup', up], ['pointercancel', up], ['keydown', key], ['focusin', focus]];
            for (const [type, fn] of listeners) root.addEventListener(type, fn);
            this.stop = () => {
                cancelAnimationFrame(frame);
                for (const [type, fn] of listeners) root.removeEventListener(type, fn);
            };
        },
        destroy() {
            this.stop?.();
        },
    }"
    {{ $attributes->class([$base]) }}
>
    {{ $slot }}
    <span id="{{ $hintId }}" hidden>{{ $hintLabel }}</span>
</div>
```

```blade
<x-markas.drag-elements :seed="4" class="h-80 rounded-xl border border-line bg-subtle" role="group" aria-label="Moodboard">
    <div class="w-44 rounded-lg bg-surface p-4">Brand refresh</div>
    <span class="rounded-full bg-primary px-4 py-2 text-on-primary">Kopi susu</span>
    <span data-x="90" data-y="10" data-rotate="8" class="rounded-md border border-line bg-surface px-3 py-1.5">Batik pattern</span>
</x-markas.drag-elements>
```

Needs Alpine.js.

### React

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

```tsx
"use client";

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

const base =
  "relative isolate overflow-hidden [&>*]:absolute [&>*]:cursor-grab [&>*]:touch-none [&>*]:select-none [&>*]:transition-[translate,scale,box-shadow] [&>*]:duration-500 [&>*]:ease-[cubic-bezier(0.34,1.56,0.64,1)] [&>*]:focus-visible:outline-2 [&>*]:focus-visible:outline-offset-2 [&>*]:focus-visible:outline-primary [&>[data-dragging]]:scale-105 [&>[data-dragging]]:cursor-grabbing [&>[data-dragging]]:shadow-overlay [&>[data-dragging]]:transition-[scale,box-shadow] [&>[data-dragging]]:duration-150 [&>[data-gliding]]:transition-none motion-reduce:[&>*]:transition-none!";

export type DragRelease = "inertia" | "stay" | "return";
type Options = {
  release: DragRelease;
  rotate: number;
  seed: number;
  hint: string;
};

const KEY_STEP = 10;
const KEY_STEP_LARGE = 50;
const FRICTION = 0.9;
const BOUNCE = 0.4;
const MIN_SPEED = 0.2;
const MAX_SPEED = 24;
const FRAME_MS = 16;
const IDLE_MS = 80;
const INTERACTIVE = "a,button,input,select,textarea,label";
const KEYS: Record<string, [number, number]> = {
  ArrowLeft: [-1, 0],
  ArrowRight: [1, 0],
  ArrowUp: [0, -1],
  ArrowDown: [0, 1],
};

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
const clamp = (v: number, min: number, max: number) =>
  Math.min(Math.max(v, min), max);
/** 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;

/**
 * Scatter the children, then let pointer and keyboard move each one inside the area.
 * data-x and data-y (percent) and data-rotate (deg) on a child override the seeded spot.
 */
export function startDrag(root: HTMLElement, o: Options) {
  const items = () =>
    [...root.children].filter(
      (el): el is HTMLElement => el instanceof HTMLElement && !el.hidden,
    );
  const pos = new Map<HTMLElement, [number, number]>();
  let top = 0;
  let frame = 0;
  let drag: {
    el: HTMLElement;
    sx: number;
    sy: number;
    lim: number[];
    vx: number;
    vy: number;
    lx: number;
    ly: number;
    t: number;
  } | null = null;

  items().forEach((el, i) => {
    const d = el.dataset;
    const x = Number(d.x ?? Math.round(rand(o.seed, i * 3) * 100));
    const y = Number(d.y ?? Math.round(rand(o.seed, i * 3 + 1) * 100));
    const r = Number(
      d.rotate ?? Math.round((rand(o.seed, i * 3 + 2) * 2 - 1) * o.rotate),
    );
    el.style.left = `${x}%`;
    el.style.top = `${y}%`;
    el.style.transform = `translate(-${x}%, -${y}%)`;
    el.style.rotate = `${r}deg`;
    if (!el.hasAttribute("tabindex")) el.tabIndex = 0;
    el.setAttribute("aria-describedby", o.hint);
    top = i + 1;
  });

  const at = (el: HTMLElement) => pos.get(el) ?? [0, 0];
  const set = (el: HTMLElement, x: number, y: number) => {
    pos.set(el, [x, y]);
    el.style.translate = `${x}px ${y}px`;
  };
  const raise = (el: HTMLElement) => (el.style.zIndex = String(++top));
  /** Offsets that keep the child inside, measured from where it is drawn now. */
  const limits = (el: HTMLElement) => {
    const r = el.getBoundingClientRect();
    const c = root.getBoundingClientRect();
    const [x = 0, y = 0] = getComputedStyle(el)
      .translate.split(" ")
      .map((v) => parseFloat(v) || 0);
    return [
      c.left - r.left + x,
      c.right - r.right + x,
      c.top - r.top + y,
      c.bottom - r.bottom + y,
    ];
  };
  const item = (target: EventTarget | null) =>
    items().find((el) => el.contains(target as Node));

  const glide = (el: HTMLElement, vx: number, vy: number, lim: number[]) => {
    el.dataset.gliding = "";
    const step = () => {
      const [a, b, c, d] = lim;
      let [x, y] = at(el);
      x += vx;
      y += vy;
      if (x < a! || x > b!) vx *= -BOUNCE;
      if (y < c! || y > d!) vy *= -BOUNCE;
      vx *= FRICTION;
      vy *= FRICTION;
      set(el, clamp(x, a!, b!), clamp(y, c!, d!));
      if (Math.hypot(vx, vy) > MIN_SPEED) frame = requestAnimationFrame(step);
      else delete el.dataset.gliding;
    };
    frame = requestAnimationFrame(step);
  };

  const down = (e: PointerEvent) => {
    const el = item(e.target);
    const control = (e.target as Element).closest?.(INTERACTIVE);
    if (
      !el ||
      e.button !== 0 ||
      (control && control !== el && el.contains(control))
    )
      return;
    cancelAnimationFrame(frame);
    for (const other of items()) delete other.dataset.gliding;
    el.setPointerCapture?.(e.pointerId);
    el.dataset.dragging = "";
    raise(el);
    const [x, y] = at(el);
    const { clientX: px, clientY: py, timeStamp: t } = e;
    drag = {
      el,
      sx: px - x,
      sy: py - y,
      lim: limits(el),
      vx: 0,
      vy: 0,
      lx: px,
      ly: py,
      t,
    };
  };
  const move = (e: PointerEvent) => {
    if (!drag) return;
    const [a, b, c, d] = drag.lim;
    const dt = Math.max(e.timeStamp - drag.t, 1);
    set(
      drag.el,
      clamp(e.clientX - drag.sx, a!, b!),
      clamp(e.clientY - drag.sy, c!, d!),
    );
    drag.vx = ((e.clientX - drag.lx) / dt) * FRAME_MS;
    drag.vy = ((e.clientY - drag.ly) / dt) * FRAME_MS;
    drag.lx = e.clientX;
    drag.ly = e.clientY;
    drag.t = e.timeStamp;
  };
  const up = (e: PointerEvent) => {
    if (!drag) return;
    const { el, lim, t } = drag;
    const fresh = e.timeStamp - t > IDLE_MS ? 0 : 1;
    const vx = drag.vx * fresh;
    const vy = drag.vy * fresh;
    drag = null;
    delete el.dataset.dragging;
    if (o.release === "return") set(el, 0, 0);
    else if (o.release === "inertia" && !still())
      glide(
        el,
        clamp(vx, -MAX_SPEED, MAX_SPEED),
        clamp(vy, -MAX_SPEED, MAX_SPEED),
        lim,
      );
  };
  const key = (e: KeyboardEvent) => {
    const el = items().find((i) => i === e.target);
    const dir = KEYS[e.key];
    if (!el) return;
    const [x, y] = at(el);
    if (e.key === "Escape" && (x || y)) set(el, 0, 0);
    else if (dir) {
      const [a, b, c, d] = limits(el);
      const step = e.shiftKey ? KEY_STEP_LARGE : KEY_STEP;
      set(
        el,
        clamp(x + dir[0] * step, a!, b!),
        clamp(y + dir[1] * step, c!, d!),
      );
    } else return;
    e.preventDefault();
    raise(el);
  };
  const focus = (e: FocusEvent) => {
    const el = item(e.target);
    if (el) raise(el);
  };

  const listeners = [
    ["pointerdown", down],
    ["pointermove", move],
    ["pointerup", up],
    ["pointercancel", up],
    ["keydown", key],
    ["focusin", focus],
  ] as [string, (e: Event) => void][];
  for (const [type, fn] of listeners) root.addEventListener(type, fn);
  return () => {
    cancelAnimationFrame(frame);
    for (const [type, fn] of listeners) root.removeEventListener(type, fn);
  };
}

export type DragElementsProps = ComponentProps<"div"> & {
  /** What a child does when let go: glide on, stop, or spring back. */
  release?: DragRelease;
  /** Largest random tilt in degrees for children without data-rotate. */
  rotate?: number;
  /** Changes the scattered starting spots. */
  seed?: number;
  /** Description read for each child by screen readers. */
  hintLabel?: string;
};

export function DragElements({
  release = "inertia",
  rotate = 6,
  seed = 1,
  hintLabel = "Drag to move, or use the arrow keys. Escape puts it back",
  className,
  children,
  ...props
}: DragElementsProps) {
  const ref = useRef<HTMLDivElement>(null);
  const hint = useId();
  useLayoutEffect(
    () =>
      ref.current
        ? startDrag(ref.current, { release, rotate, seed, hint })
        : undefined,
    [release, rotate, seed, hint],
  );
  return (
    <div ref={ref} {...props} className={cx(base, className)}>
      {children}
      <span id={hint} hidden>
        {hintLabel}
      </span>
    </div>
  );
}
```

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

<DragElements
  release="return"
  className="h-80 rounded-xl border border-line bg-subtle"
  role="group"
  aria-label="Skills"
>
  <span className="rounded-full bg-primary-soft px-3 py-1.5">Laravel</span>
  <span className="rounded-full bg-primary-soft px-3 py-1.5">Vue</span>
</DragElements>;
```

### Vue

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

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

const props = withDefaults(
  defineProps<{
    /** What a child does when let go: glide on, stop, or spring back. */
    release?: "inertia" | "stay" | "return";
    /** Largest random tilt in degrees for children without data-rotate. */
    rotate?: number;
    /** Changes the scattered starting spots. */
    seed?: number;
    /** Description read for each child by screen readers. */
    hintLabel?: string;
  }>(),
  {
    release: "inertia",
    rotate: 6,
    seed: 1,
    hintLabel: "Drag to move, or use the arrow keys. Escape puts it back",
  },
);

const base =
  "relative isolate overflow-hidden [&>*]:absolute [&>*]:cursor-grab [&>*]:touch-none [&>*]:select-none [&>*]:transition-[translate,scale,box-shadow] [&>*]:duration-500 [&>*]:ease-[cubic-bezier(0.34,1.56,0.64,1)] [&>*]:focus-visible:outline-2 [&>*]:focus-visible:outline-offset-2 [&>*]:focus-visible:outline-primary [&>[data-dragging]]:scale-105 [&>[data-dragging]]:cursor-grabbing [&>[data-dragging]]:shadow-overlay [&>[data-dragging]]:transition-[scale,box-shadow] [&>[data-dragging]]:duration-150 [&>[data-gliding]]:transition-none motion-reduce:[&>*]:transition-none!";

type DragRelease = "inertia" | "stay" | "return";
type Options = {
  release: DragRelease;
  rotate: number;
  seed: number;
  hint: string;
};

const KEY_STEP = 10;
const KEY_STEP_LARGE = 50;
const FRICTION = 0.9;
const BOUNCE = 0.4;
const MIN_SPEED = 0.2;
const MAX_SPEED = 24;
const FRAME_MS = 16;
const IDLE_MS = 80;
const INTERACTIVE = "a,button,input,select,textarea,label";
const KEYS: Record<string, [number, number]> = {
  ArrowLeft: [-1, 0],
  ArrowRight: [1, 0],
  ArrowUp: [0, -1],
  ArrowDown: [0, 1],
};

const clamp = (v: number, min: number, max: number) =>
  Math.min(Math.max(v, min), max);
/** 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;

/**
 * Scatter the children, then let pointer and keyboard move each one inside the area.
 * data-x and data-y (percent) and data-rotate (deg) on a child override the seeded spot.
 */
function startDrag(root: HTMLElement, o: Options) {
  const items = () =>
    [...root.children].filter(
      (el): el is HTMLElement => el instanceof HTMLElement && !el.hidden,
    );
  const pos = new Map<HTMLElement, [number, number]>();
  let top = 0;
  let frame = 0;
  let drag: {
    el: HTMLElement;
    sx: number;
    sy: number;
    lim: number[];
    vx: number;
    vy: number;
    lx: number;
    ly: number;
    t: number;
  } | null = null;

  items().forEach((el, i) => {
    const d = el.dataset;
    const x = Number(d.x ?? Math.round(rand(o.seed, i * 3) * 100));
    const y = Number(d.y ?? Math.round(rand(o.seed, i * 3 + 1) * 100));
    const r = Number(
      d.rotate ?? Math.round((rand(o.seed, i * 3 + 2) * 2 - 1) * o.rotate),
    );
    el.style.left = `${x}%`;
    el.style.top = `${y}%`;
    el.style.transform = `translate(-${x}%, -${y}%)`;
    el.style.rotate = `${r}deg`;
    if (!el.hasAttribute("tabindex")) el.tabIndex = 0;
    el.setAttribute("aria-describedby", o.hint);
    top = i + 1;
  });

  const at = (el: HTMLElement) => pos.get(el) ?? [0, 0];
  const set = (el: HTMLElement, x: number, y: number) => {
    pos.set(el, [x, y]);
    el.style.translate = `${x}px ${y}px`;
  };
  const raise = (el: HTMLElement) => (el.style.zIndex = String(++top));
  /** Offsets that keep the child inside, measured from where it is drawn now. */
  const limits = (el: HTMLElement) => {
    const r = el.getBoundingClientRect();
    const c = root.getBoundingClientRect();
    const [x = 0, y = 0] = getComputedStyle(el)
      .translate.split(" ")
      .map((v) => parseFloat(v) || 0);
    return [
      c.left - r.left + x,
      c.right - r.right + x,
      c.top - r.top + y,
      c.bottom - r.bottom + y,
    ];
  };
  const item = (target: EventTarget | null) =>
    items().find((el) => el.contains(target as Node));

  const glide = (el: HTMLElement, vx: number, vy: number, lim: number[]) => {
    el.dataset.gliding = "";
    const step = () => {
      const [a, b, c, d] = lim;
      let [x, y] = at(el);
      x += vx;
      y += vy;
      if (x < a! || x > b!) vx *= -BOUNCE;
      if (y < c! || y > d!) vy *= -BOUNCE;
      vx *= FRICTION;
      vy *= FRICTION;
      set(el, clamp(x, a!, b!), clamp(y, c!, d!));
      if (Math.hypot(vx, vy) > MIN_SPEED) frame = requestAnimationFrame(step);
      else delete el.dataset.gliding;
    };
    frame = requestAnimationFrame(step);
  };

  const down = (e: PointerEvent) => {
    const el = item(e.target);
    const control = (e.target as Element).closest?.(INTERACTIVE);
    if (
      !el ||
      e.button !== 0 ||
      (control && control !== el && el.contains(control))
    )
      return;
    cancelAnimationFrame(frame);
    for (const other of items()) delete other.dataset.gliding;
    el.setPointerCapture?.(e.pointerId);
    el.dataset.dragging = "";
    raise(el);
    const [x, y] = at(el);
    const { clientX: px, clientY: py, timeStamp: t } = e;
    drag = {
      el,
      sx: px - x,
      sy: py - y,
      lim: limits(el),
      vx: 0,
      vy: 0,
      lx: px,
      ly: py,
      t,
    };
  };
  const move = (e: PointerEvent) => {
    if (!drag) return;
    const [a, b, c, d] = drag.lim;
    const dt = Math.max(e.timeStamp - drag.t, 1);
    set(
      drag.el,
      clamp(e.clientX - drag.sx, a!, b!),
      clamp(e.clientY - drag.sy, c!, d!),
    );
    drag.vx = ((e.clientX - drag.lx) / dt) * FRAME_MS;
    drag.vy = ((e.clientY - drag.ly) / dt) * FRAME_MS;
    drag.lx = e.clientX;
    drag.ly = e.clientY;
    drag.t = e.timeStamp;
  };
  const up = (e: PointerEvent) => {
    if (!drag) return;
    const { el, lim, t } = drag;
    const fresh = e.timeStamp - t > IDLE_MS ? 0 : 1;
    const vx = drag.vx * fresh;
    const vy = drag.vy * fresh;
    drag = null;
    delete el.dataset.dragging;
    if (o.release === "return") set(el, 0, 0);
    else if (o.release === "inertia" && !still())
      glide(
        el,
        clamp(vx, -MAX_SPEED, MAX_SPEED),
        clamp(vy, -MAX_SPEED, MAX_SPEED),
        lim,
      );
  };
  const key = (e: KeyboardEvent) => {
    const el = items().find((i) => i === e.target);
    const dir = KEYS[e.key];
    if (!el) return;
    const [x, y] = at(el);
    if (e.key === "Escape" && (x || y)) set(el, 0, 0);
    else if (dir) {
      const [a, b, c, d] = limits(el);
      const step = e.shiftKey ? KEY_STEP_LARGE : KEY_STEP;
      set(
        el,
        clamp(x + dir[0] * step, a!, b!),
        clamp(y + dir[1] * step, c!, d!),
      );
    } else return;
    e.preventDefault();
    raise(el);
  };
  const focus = (e: FocusEvent) => {
    const el = item(e.target);
    if (el) raise(el);
  };

  const listeners = [
    ["pointerdown", down],
    ["pointermove", move],
    ["pointerup", up],
    ["pointercancel", up],
    ["keydown", key],
    ["focusin", focus],
  ] as [string, (e: Event) => void][];
  for (const [type, fn] of listeners) root.addEventListener(type, fn);
  return () => {
    cancelAnimationFrame(frame);
    for (const [type, fn] of listeners) root.removeEventListener(type, fn);
  };
}

const hint = useId();
const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
let stop = () => {};
onMounted(() => {
  if (rootEl.value)
    stop = startDrag(rootEl.value, {
      release: props.release,
      rotate: props.rotate,
      seed: props.seed,
      hint,
    });
});
onBeforeUnmount(() => stop());
</script>

<template>
  <div ref="rootRef" :class="base">
    <slot />
    <span :id="hint" hidden>{{ props.hintLabel }}</span>
  </div>
</template>
```

```vue
<template>
  <DragElements
    release="stay"
    :rotate="0"
    class="h-80 rounded-xl border border-line bg-canvas"
    role="group"
    aria-label="Team"
  >
    <div data-x="8" data-y="10" class="w-48 rounded-xl bg-surface p-3">
      Rania Putri
    </div>
    <div data-x="92" data-y="30" class="w-48 rounded-xl bg-surface p-3">
      Bima Saputra
    </div>
  </DragElements>
</template>
```

### Svelte

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

```svelte
<script lang="ts" module>
  export type DragRelease = "inertia" | "stay" | "return";
  type Options = {
    release: DragRelease;
    rotate: number;
    seed: number;
    hint: string;
  };

  const KEY_STEP = 10;
  const KEY_STEP_LARGE = 50;
  const FRICTION = 0.9;
  const BOUNCE = 0.4;
  const MIN_SPEED = 0.2;
  const MAX_SPEED = 24;
  const FRAME_MS = 16;
  const IDLE_MS = 80;
  const INTERACTIVE = "a,button,input,select,textarea,label";
  const KEYS: Record<string, [number, number]> = {
    ArrowLeft: [-1, 0],
    ArrowRight: [1, 0],
    ArrowUp: [0, -1],
    ArrowDown: [0, 1],
  };

  const clamp = (v: number, min: number, max: number) =>
    Math.min(Math.max(v, min), max);
  /** 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;

  /**
   * Scatter the children, then let pointer and keyboard move each one inside the area.
   * data-x and data-y (percent) and data-rotate (deg) on a child override the seeded spot.
   */
  export function startDrag(root: HTMLElement, o: Options) {
    const items = () =>
      [...root.children].filter(
        (el): el is HTMLElement => el instanceof HTMLElement && !el.hidden,
      );
    const pos = new Map<HTMLElement, [number, number]>();
    let top = 0;
    let frame = 0;
    let drag: {
      el: HTMLElement;
      sx: number;
      sy: number;
      lim: number[];
      vx: number;
      vy: number;
      lx: number;
      ly: number;
      t: number;
    } | null = null;

    items().forEach((el, i) => {
      const d = el.dataset;
      const x = Number(d.x ?? Math.round(rand(o.seed, i * 3) * 100));
      const y = Number(d.y ?? Math.round(rand(o.seed, i * 3 + 1) * 100));
      const r = Number(
        d.rotate ?? Math.round((rand(o.seed, i * 3 + 2) * 2 - 1) * o.rotate),
      );
      el.style.left = `${x}%`;
      el.style.top = `${y}%`;
      el.style.transform = `translate(-${x}%, -${y}%)`;
      el.style.rotate = `${r}deg`;
      if (!el.hasAttribute("tabindex")) el.tabIndex = 0;
      el.setAttribute("aria-describedby", o.hint);
      top = i + 1;
    });

    const at = (el: HTMLElement) => pos.get(el) ?? [0, 0];
    const set = (el: HTMLElement, x: number, y: number) => {
      pos.set(el, [x, y]);
      el.style.translate = `${x}px ${y}px`;
    };
    const raise = (el: HTMLElement) => (el.style.zIndex = String(++top));
    /** Offsets that keep the child inside, measured from where it is drawn now. */
    const limits = (el: HTMLElement) => {
      const r = el.getBoundingClientRect();
      const c = root.getBoundingClientRect();
      const [x = 0, y = 0] = getComputedStyle(el)
        .translate.split(" ")
        .map((v) => parseFloat(v) || 0);
      return [
        c.left - r.left + x,
        c.right - r.right + x,
        c.top - r.top + y,
        c.bottom - r.bottom + y,
      ];
    };
    const item = (target: EventTarget | null) =>
      items().find((el) => el.contains(target as Node));

    const glide = (el: HTMLElement, vx: number, vy: number, lim: number[]) => {
      el.dataset.gliding = "";
      const step = () => {
        const [a, b, c, d] = lim;
        let [x, y] = at(el);
        x += vx;
        y += vy;
        if (x < a! || x > b!) vx *= -BOUNCE;
        if (y < c! || y > d!) vy *= -BOUNCE;
        vx *= FRICTION;
        vy *= FRICTION;
        set(el, clamp(x, a!, b!), clamp(y, c!, d!));
        if (Math.hypot(vx, vy) > MIN_SPEED) frame = requestAnimationFrame(step);
        else delete el.dataset.gliding;
      };
      frame = requestAnimationFrame(step);
    };

    const down = (e: PointerEvent) => {
      const el = item(e.target);
      const control = (e.target as Element).closest?.(INTERACTIVE);
      if (
        !el ||
        e.button !== 0 ||
        (control && control !== el && el.contains(control))
      )
        return;
      cancelAnimationFrame(frame);
      for (const other of items()) delete other.dataset.gliding;
      el.setPointerCapture?.(e.pointerId);
      el.dataset.dragging = "";
      raise(el);
      const [x, y] = at(el);
      const { clientX: px, clientY: py, timeStamp: t } = e;
      drag = {
        el,
        sx: px - x,
        sy: py - y,
        lim: limits(el),
        vx: 0,
        vy: 0,
        lx: px,
        ly: py,
        t,
      };
    };
    const move = (e: PointerEvent) => {
      if (!drag) return;
      const [a, b, c, d] = drag.lim;
      const dt = Math.max(e.timeStamp - drag.t, 1);
      set(
        drag.el,
        clamp(e.clientX - drag.sx, a!, b!),
        clamp(e.clientY - drag.sy, c!, d!),
      );
      drag.vx = ((e.clientX - drag.lx) / dt) * FRAME_MS;
      drag.vy = ((e.clientY - drag.ly) / dt) * FRAME_MS;
      drag.lx = e.clientX;
      drag.ly = e.clientY;
      drag.t = e.timeStamp;
    };
    const up = (e: PointerEvent) => {
      if (!drag) return;
      const { el, lim, t } = drag;
      const fresh = e.timeStamp - t > IDLE_MS ? 0 : 1;
      const vx = drag.vx * fresh;
      const vy = drag.vy * fresh;
      drag = null;
      delete el.dataset.dragging;
      if (o.release === "return") set(el, 0, 0);
      else if (o.release === "inertia" && !still())
        glide(
          el,
          clamp(vx, -MAX_SPEED, MAX_SPEED),
          clamp(vy, -MAX_SPEED, MAX_SPEED),
          lim,
        );
    };
    const key = (e: KeyboardEvent) => {
      const el = items().find((i) => i === e.target);
      const dir = KEYS[e.key];
      if (!el) return;
      const [x, y] = at(el);
      if (e.key === "Escape" && (x || y)) set(el, 0, 0);
      else if (dir) {
        const [a, b, c, d] = limits(el);
        const step = e.shiftKey ? KEY_STEP_LARGE : KEY_STEP;
        set(
          el,
          clamp(x + dir[0] * step, a!, b!),
          clamp(y + dir[1] * step, c!, d!),
        );
      } else return;
      e.preventDefault();
      raise(el);
    };
    const focus = (e: FocusEvent) => {
      const el = item(e.target);
      if (el) raise(el);
    };

    const listeners = [
      ["pointerdown", down],
      ["pointermove", move],
      ["pointerup", up],
      ["pointercancel", up],
      ["keydown", key],
      ["focusin", focus],
    ] as [string, (e: Event) => void][];
    for (const [type, fn] of listeners) root.addEventListener(type, fn);
    return () => {
      cancelAnimationFrame(frame);
      for (const [type, fn] of listeners) root.removeEventListener(type, fn);
    };
  }
</script>

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

  const base =
    "relative isolate overflow-hidden [&>*]:absolute [&>*]:cursor-grab [&>*]:touch-none [&>*]:select-none [&>*]:transition-[translate,scale,box-shadow] [&>*]:duration-500 [&>*]:ease-[cubic-bezier(0.34,1.56,0.64,1)] [&>*]:focus-visible:outline-2 [&>*]:focus-visible:outline-offset-2 [&>*]:focus-visible:outline-primary [&>[data-dragging]]:scale-105 [&>[data-dragging]]:cursor-grabbing [&>[data-dragging]]:shadow-overlay [&>[data-dragging]]:transition-[scale,box-shadow] [&>[data-dragging]]:duration-150 [&>[data-gliding]]:transition-none motion-reduce:[&>*]:transition-none!";

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** What a child does when let go: glide on, stop, or spring back. */
    release?: DragRelease;
    /** Largest random tilt in degrees for children without data-rotate. */
    rotate?: number;
    /** Changes the scattered starting spots. */
    seed?: number;
    /** Description read for each child by screen readers. */
    hintLabel?: string;
    children?: Snippet;
  };

  let {
    release = "inertia",
    rotate = 6,
    seed = 1,
    hintLabel = "Drag to move, or use the arrow keys. Escape puts it back",
    class: className,
    children,
    ...rest
  }: Props = $props();

  const hint = $props.id();
  let rootEl = $state<HTMLDivElement>();

  $effect(() =>
    rootEl ? startDrag(rootEl, { release, rotate, seed, hint }) : undefined,
  );
</script>

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

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

<DragElements
  release="return"
  class="h-80 rounded-xl border border-line bg-subtle"
  role="group"
  aria-label="Skills"
>
  <span class="rounded-full bg-primary-soft px-3 py-1.5">Laravel</span>
  <span class="rounded-full bg-primary-soft px-3 py-1.5">Vue</span>
</DragElements>
```

### Astro

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

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

const base =
  "relative isolate overflow-hidden [&>*]:absolute [&>*]:cursor-grab [&>*]:touch-none [&>*]:select-none [&>*]:transition-[translate,scale,box-shadow] [&>*]:duration-500 [&>*]:ease-[cubic-bezier(0.34,1.56,0.64,1)] [&>*]:focus-visible:outline-2 [&>*]:focus-visible:outline-offset-2 [&>*]:focus-visible:outline-primary [&>[data-dragging]]:scale-105 [&>[data-dragging]]:cursor-grabbing [&>[data-dragging]]:shadow-overlay [&>[data-dragging]]:transition-[scale,box-shadow] [&>[data-dragging]]:duration-150 [&>[data-gliding]]:transition-none motion-reduce:[&>*]:transition-none!";

export type DragRelease = "inertia" | "stay" | "return";

type Props = HTMLAttributes<"div"> & {
  /** What a child does when let go: glide on, stop, or spring back. */
  release?: DragRelease;
  /** Largest random tilt in degrees for children without data-rotate. */
  rotate?: number;
  /** Changes the scattered starting spots. */
  seed?: number;
  /** Description read for each child by screen readers. */
  hintLabel?: string;
};

const {
  release = "inertia",
  rotate = 6,
  seed = 1,
  hintLabel = "Drag to move, or use the arrow keys. Escape puts it back",
  class: className,
  ...rest
} = Astro.props;

const hint = `markas-drag-elements-${crypto.randomUUID().slice(0, 8)}`;
---

<markas-drag-elements
  class="contents"
  data-release={release}
  data-rotate={rotate}
  data-seed={seed}
  data-hint={hint}
>
  <div {...rest} class:list={[base, className]}>
    <slot />
    <span id={hint} hidden>{hintLabel}</span>
  </div>
</markas-drag-elements>

<script>
  type DragRelease = "inertia" | "stay" | "return";
  type Options = {
    release: DragRelease;
    rotate: number;
    seed: number;
    hint: string;
  };

  const KEY_STEP = 10;
  const KEY_STEP_LARGE = 50;
  const FRICTION = 0.9;
  const BOUNCE = 0.4;
  const MIN_SPEED = 0.2;
  const MAX_SPEED = 24;
  const FRAME_MS = 16;
  const IDLE_MS = 80;
  const INTERACTIVE = "a,button,input,select,textarea,label";
  const KEYS: Record<string, [number, number]> = {
    ArrowLeft: [-1, 0],
    ArrowRight: [1, 0],
    ArrowUp: [0, -1],
    ArrowDown: [0, 1],
  };

  const clamp = (v: number, min: number, max: number) =>
    Math.min(Math.max(v, min), max);
  /** 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;

  /**
   * Scatter the children, then let pointer and keyboard move each one inside the area.
   * data-x and data-y (percent) and data-rotate (deg) on a child override the seeded spot.
   */
  function startDrag(root: HTMLElement, o: Options) {
    const items = () =>
      [...root.children].filter(
        (el): el is HTMLElement => el instanceof HTMLElement && !el.hidden,
      );
    const pos = new Map<HTMLElement, [number, number]>();
    let top = 0;
    let frame = 0;
    let drag: {
      el: HTMLElement;
      sx: number;
      sy: number;
      lim: number[];
      vx: number;
      vy: number;
      lx: number;
      ly: number;
      t: number;
    } | null = null;

    items().forEach((el, i) => {
      const d = el.dataset;
      const x = Number(d.x ?? Math.round(rand(o.seed, i * 3) * 100));
      const y = Number(d.y ?? Math.round(rand(o.seed, i * 3 + 1) * 100));
      const r = Number(
        d.rotate ?? Math.round((rand(o.seed, i * 3 + 2) * 2 - 1) * o.rotate),
      );
      el.style.left = `${x}%`;
      el.style.top = `${y}%`;
      el.style.transform = `translate(-${x}%, -${y}%)`;
      el.style.rotate = `${r}deg`;
      if (!el.hasAttribute("tabindex")) el.tabIndex = 0;
      el.setAttribute("aria-describedby", o.hint);
      top = i + 1;
    });

    const at = (el: HTMLElement) => pos.get(el) ?? [0, 0];
    const set = (el: HTMLElement, x: number, y: number) => {
      pos.set(el, [x, y]);
      el.style.translate = `${x}px ${y}px`;
    };
    const raise = (el: HTMLElement) => (el.style.zIndex = String(++top));
    /** Offsets that keep the child inside, measured from where it is drawn now. */
    const limits = (el: HTMLElement) => {
      const r = el.getBoundingClientRect();
      const c = root.getBoundingClientRect();
      const [x = 0, y = 0] = getComputedStyle(el)
        .translate.split(" ")
        .map((v) => parseFloat(v) || 0);
      return [
        c.left - r.left + x,
        c.right - r.right + x,
        c.top - r.top + y,
        c.bottom - r.bottom + y,
      ];
    };
    const item = (target: EventTarget | null) =>
      items().find((el) => el.contains(target as Node));

    const glide = (el: HTMLElement, vx: number, vy: number, lim: number[]) => {
      el.dataset.gliding = "";
      const step = () => {
        const [a, b, c, d] = lim;
        let [x, y] = at(el);
        x += vx;
        y += vy;
        if (x < a! || x > b!) vx *= -BOUNCE;
        if (y < c! || y > d!) vy *= -BOUNCE;
        vx *= FRICTION;
        vy *= FRICTION;
        set(el, clamp(x, a!, b!), clamp(y, c!, d!));
        if (Math.hypot(vx, vy) > MIN_SPEED) frame = requestAnimationFrame(step);
        else delete el.dataset.gliding;
      };
      frame = requestAnimationFrame(step);
    };

    const down = (e: PointerEvent) => {
      const el = item(e.target);
      const control = (e.target as Element).closest?.(INTERACTIVE);
      if (
        !el ||
        e.button !== 0 ||
        (control && control !== el && el.contains(control))
      )
        return;
      cancelAnimationFrame(frame);
      for (const other of items()) delete other.dataset.gliding;
      el.setPointerCapture?.(e.pointerId);
      el.dataset.dragging = "";
      raise(el);
      const [x, y] = at(el);
      const { clientX: px, clientY: py, timeStamp: t } = e;
      drag = {
        el,
        sx: px - x,
        sy: py - y,
        lim: limits(el),
        vx: 0,
        vy: 0,
        lx: px,
        ly: py,
        t,
      };
    };
    const move = (e: PointerEvent) => {
      if (!drag) return;
      const [a, b, c, d] = drag.lim;
      const dt = Math.max(e.timeStamp - drag.t, 1);
      set(
        drag.el,
        clamp(e.clientX - drag.sx, a!, b!),
        clamp(e.clientY - drag.sy, c!, d!),
      );
      drag.vx = ((e.clientX - drag.lx) / dt) * FRAME_MS;
      drag.vy = ((e.clientY - drag.ly) / dt) * FRAME_MS;
      drag.lx = e.clientX;
      drag.ly = e.clientY;
      drag.t = e.timeStamp;
    };
    const up = (e: PointerEvent) => {
      if (!drag) return;
      const { el, lim, t } = drag;
      const fresh = e.timeStamp - t > IDLE_MS ? 0 : 1;
      const vx = drag.vx * fresh;
      const vy = drag.vy * fresh;
      drag = null;
      delete el.dataset.dragging;
      if (o.release === "return") set(el, 0, 0);
      else if (o.release === "inertia" && !still())
        glide(
          el,
          clamp(vx, -MAX_SPEED, MAX_SPEED),
          clamp(vy, -MAX_SPEED, MAX_SPEED),
          lim,
        );
    };
    const key = (e: KeyboardEvent) => {
      const el = items().find((i) => i === e.target);
      const dir = KEYS[e.key];
      if (!el) return;
      const [x, y] = at(el);
      if (e.key === "Escape" && (x || y)) set(el, 0, 0);
      else if (dir) {
        const [a, b, c, d] = limits(el);
        const step = e.shiftKey ? KEY_STEP_LARGE : KEY_STEP;
        set(
          el,
          clamp(x + dir[0] * step, a!, b!),
          clamp(y + dir[1] * step, c!, d!),
        );
      } else return;
      e.preventDefault();
      raise(el);
    };
    const focus = (e: FocusEvent) => {
      const el = item(e.target);
      if (el) raise(el);
    };

    const listeners = [
      ["pointerdown", down],
      ["pointermove", move],
      ["pointerup", up],
      ["pointercancel", up],
      ["keydown", key],
      ["focusin", focus],
    ] as [string, (e: Event) => void][];
    for (const [type, fn] of listeners) root.addEventListener(type, fn);
    return () => {
      cancelAnimationFrame(frame);
      for (const [type, fn] of listeners) root.removeEventListener(type, fn);
    };
  }

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

    connectedCallback() {
      const root = this.firstElementChild;
      if (this.stop || !(root instanceof HTMLElement)) return;
      const d = this.dataset;
      this.stop = startDrag(root, {
        release: (d.release ?? "inertia") as DragRelease,
        rotate: Number(d.rotate),
        seed: Number(d.seed),
        hint: d.hint ?? "",
      });
    }

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

  if (!customElements.get("markas-drag-elements"))
    customElements.define("markas-drag-elements", MarkasDragElements);
</script>
```

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

<DragElements
  release="return"
  class="h-80 rounded-xl border border-line bg-subtle"
  role="group"
  aria-label="Skills"
>
  <span class="rounded-full bg-primary-soft px-3 py-1.5">Laravel</span>
  <span class="rounded-full bg-primary-soft px-3 py-1.5">Vue</span>
</DragElements>
```

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

### Angular

Save at `src/app/markas/drag-elements.component.ts`. No extra dependencies.

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

const base =
  "relative isolate overflow-hidden [&>*]:absolute [&>*]:cursor-grab [&>*]:touch-none [&>*]:select-none [&>*]:transition-[translate,scale,box-shadow] [&>*]:duration-500 [&>*]:ease-[cubic-bezier(0.34,1.56,0.64,1)] [&>*]:focus-visible:outline-2 [&>*]:focus-visible:outline-offset-2 [&>*]:focus-visible:outline-primary [&>[data-dragging]]:scale-105 [&>[data-dragging]]:cursor-grabbing [&>[data-dragging]]:shadow-overlay [&>[data-dragging]]:transition-[scale,box-shadow] [&>[data-dragging]]:duration-150 [&>[data-gliding]]:transition-none motion-reduce:[&>*]:transition-none!";

export type DragRelease = "inertia" | "stay" | "return";
type Options = {
  release: DragRelease;
  rotate: number;
  seed: number;
  hint: string;
};

const KEY_STEP = 10;
const KEY_STEP_LARGE = 50;
const FRICTION = 0.9;
const BOUNCE = 0.4;
const MIN_SPEED = 0.2;
const MAX_SPEED = 24;
const FRAME_MS = 16;
const IDLE_MS = 80;
const INTERACTIVE = "a,button,input,select,textarea,label";
const KEYS: Record<string, [number, number]> = {
  ArrowLeft: [-1, 0],
  ArrowRight: [1, 0],
  ArrowUp: [0, -1],
  ArrowDown: [0, 1],
};

const clamp = (v: number, min: number, max: number) =>
  Math.min(Math.max(v, min), max);
/** 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;

/**
 * Scatter the children, then let pointer and keyboard move each one inside the area.
 * data-x and data-y (percent) and data-rotate (deg) on a child override the seeded spot.
 */
export function startDrag(root: HTMLElement, o: Options) {
  const items = () =>
    [...root.children].filter(
      (el): el is HTMLElement => el instanceof HTMLElement && !el.hidden,
    );
  const pos = new Map<HTMLElement, [number, number]>();
  let top = 0;
  let frame = 0;
  let drag: {
    el: HTMLElement;
    sx: number;
    sy: number;
    lim: number[];
    vx: number;
    vy: number;
    lx: number;
    ly: number;
    t: number;
  } | null = null;

  items().forEach((el, i) => {
    const d = el.dataset;
    const x = Number(d.x ?? Math.round(rand(o.seed, i * 3) * 100));
    const y = Number(d.y ?? Math.round(rand(o.seed, i * 3 + 1) * 100));
    const r = Number(
      d.rotate ?? Math.round((rand(o.seed, i * 3 + 2) * 2 - 1) * o.rotate),
    );
    el.style.left = `${x}%`;
    el.style.top = `${y}%`;
    el.style.transform = `translate(-${x}%, -${y}%)`;
    el.style.rotate = `${r}deg`;
    if (!el.hasAttribute("tabindex")) el.tabIndex = 0;
    el.setAttribute("aria-describedby", o.hint);
    top = i + 1;
  });

  const at = (el: HTMLElement) => pos.get(el) ?? [0, 0];
  const set = (el: HTMLElement, x: number, y: number) => {
    pos.set(el, [x, y]);
    el.style.translate = `${x}px ${y}px`;
  };
  const raise = (el: HTMLElement) => (el.style.zIndex = String(++top));
  /** Offsets that keep the child inside, measured from where it is drawn now. */
  const limits = (el: HTMLElement) => {
    const r = el.getBoundingClientRect();
    const c = root.getBoundingClientRect();
    const [x = 0, y = 0] = getComputedStyle(el)
      .translate.split(" ")
      .map((v) => parseFloat(v) || 0);
    return [
      c.left - r.left + x,
      c.right - r.right + x,
      c.top - r.top + y,
      c.bottom - r.bottom + y,
    ];
  };
  const item = (target: EventTarget | null) =>
    items().find((el) => el.contains(target as Node));

  const glide = (el: HTMLElement, vx: number, vy: number, lim: number[]) => {
    el.dataset.gliding = "";
    const step = () => {
      const [a, b, c, d] = lim;
      let [x, y] = at(el);
      x += vx;
      y += vy;
      if (x < a! || x > b!) vx *= -BOUNCE;
      if (y < c! || y > d!) vy *= -BOUNCE;
      vx *= FRICTION;
      vy *= FRICTION;
      set(el, clamp(x, a!, b!), clamp(y, c!, d!));
      if (Math.hypot(vx, vy) > MIN_SPEED) frame = requestAnimationFrame(step);
      else delete el.dataset.gliding;
    };
    frame = requestAnimationFrame(step);
  };

  const down = (e: PointerEvent) => {
    const el = item(e.target);
    const control = (e.target as Element).closest?.(INTERACTIVE);
    if (
      !el ||
      e.button !== 0 ||
      (control && control !== el && el.contains(control))
    )
      return;
    cancelAnimationFrame(frame);
    for (const other of items()) delete other.dataset.gliding;
    el.setPointerCapture?.(e.pointerId);
    el.dataset.dragging = "";
    raise(el);
    const [x, y] = at(el);
    const { clientX: px, clientY: py, timeStamp: t } = e;
    drag = {
      el,
      sx: px - x,
      sy: py - y,
      lim: limits(el),
      vx: 0,
      vy: 0,
      lx: px,
      ly: py,
      t,
    };
  };
  const move = (e: PointerEvent) => {
    if (!drag) return;
    const [a, b, c, d] = drag.lim;
    const dt = Math.max(e.timeStamp - drag.t, 1);
    set(
      drag.el,
      clamp(e.clientX - drag.sx, a!, b!),
      clamp(e.clientY - drag.sy, c!, d!),
    );
    drag.vx = ((e.clientX - drag.lx) / dt) * FRAME_MS;
    drag.vy = ((e.clientY - drag.ly) / dt) * FRAME_MS;
    drag.lx = e.clientX;
    drag.ly = e.clientY;
    drag.t = e.timeStamp;
  };
  const up = (e: PointerEvent) => {
    if (!drag) return;
    const { el, lim, t } = drag;
    const fresh = e.timeStamp - t > IDLE_MS ? 0 : 1;
    const vx = drag.vx * fresh;
    const vy = drag.vy * fresh;
    drag = null;
    delete el.dataset.dragging;
    if (o.release === "return") set(el, 0, 0);
    else if (o.release === "inertia" && !still())
      glide(
        el,
        clamp(vx, -MAX_SPEED, MAX_SPEED),
        clamp(vy, -MAX_SPEED, MAX_SPEED),
        lim,
      );
  };
  const key = (e: KeyboardEvent) => {
    const el = items().find((i) => i === e.target);
    const dir = KEYS[e.key];
    if (!el) return;
    const [x, y] = at(el);
    if (e.key === "Escape" && (x || y)) set(el, 0, 0);
    else if (dir) {
      const [a, b, c, d] = limits(el);
      const step = e.shiftKey ? KEY_STEP_LARGE : KEY_STEP;
      set(
        el,
        clamp(x + dir[0] * step, a!, b!),
        clamp(y + dir[1] * step, c!, d!),
      );
    } else return;
    e.preventDefault();
    raise(el);
  };
  const focus = (e: FocusEvent) => {
    const el = item(e.target);
    if (el) raise(el);
  };

  const listeners = [
    ["pointerdown", down],
    ["pointermove", move],
    ["pointerup", up],
    ["pointercancel", up],
    ["keydown", key],
    ["focusin", focus],
  ] as [string, (e: Event) => void][];
  for (const [type, fn] of listeners) root.addEventListener(type, fn);
  return () => {
    cancelAnimationFrame(frame);
    for (const [type, fn] of listeners) root.removeEventListener(type, fn);
  };
}

let nextId = 0;

/**
 * Every projected child becomes draggable. Host stays out of layout; role, aria-label, and
 * class move to the area.
 * data-x and data-y (percent) and data-rotate (deg) on a child override the seeded spot.
 */
@Component({
  selector: "markas-drag-elements",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: "contents",
    "[attr.role]": "null",
    "[attr.aria-label]": "null",
  },
  template: `
    <div
      #areaEl
      [attr.role]="role() ?? null"
      [attr.aria-label]="ariaLabel() ?? null"
      [class]="rootClasses()"
    >
      <ng-content />
      <span [id]="hint" hidden>{{ hintLabel() }}</span>
    </div>
  `,
})
export class DragElements {
  /** What a child does when let go: glide on, stop, or spring back. */
  readonly release = input<DragRelease>("inertia");
  /** Largest random tilt in degrees for children without data-rotate. */
  readonly rotate = input(6, { transform: numberAttribute });
  /** Changes the scattered starting spots. */
  readonly seed = input(1, { transform: numberAttribute });
  /** Description read for each child by screen readers. */
  readonly hintLabel = input(
    "Drag to move, or use the arrow keys. Escape puts it back",
  );
  readonly role = input<string>();
  readonly ariaLabel = input<string | undefined>(undefined, {
    alias: "aria-label",
  });
  readonly userClass = input("", { alias: "class" });

  protected readonly hint = `markas-drag-elements-${nextId++}`;
  protected readonly rootClasses = computed(() =>
    [base, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly areaEl =
    viewChild.required<ElementRef<HTMLDivElement>>("areaEl");

  constructor() {
    // Runs after the children are in the DOM, and again when release, rotate, or seed change.
    afterRenderEffect((onCleanup) => {
      const stop = startDrag(this.areaEl().nativeElement, {
        release: this.release(),
        rotate: this.rotate(),
        seed: this.seed(),
        hint: this.hint,
      });
      onCleanup(stop);
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { DragElements } from "./markas/drag-elements.component";

@Component({
  selector: "app-skills",
  imports: [DragElements],
  template: `
    <markas-drag-elements
      release="return"
      class="h-80 rounded-xl border border-line bg-subtle"
      role="group"
      aria-label="Skills"
    >
      <span class="rounded-full bg-primary-soft px-3 py-1.5">Laravel</span>
      <span class="rounded-full bg-primary-soft px-3 py-1.5">Vue</span>
    </markas-drag-elements>
  `,
})
export class Skills {}
```

`role`, `aria-label`, and `class` move from the host to the area.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `release` | `"inertia" \| "stay" \| "return"` | "inertia" | What an item does when let go: glide on with friction and bounce off the edges, stop where it is, or spring back to its starting spot. |
| `rotate` | `number` | 6 | Largest random tilt in degrees for items without data-rotate. 0 keeps them straight. |
| `seed` | `number` | 1 | Changes the scattered starting spots. The same seed always gives the same layout. |
| `hintLabel` | `string` | "Drag to move, or use the arrow keys. Escape puts it back" | Description screen readers announce for each item. |
| `children / slot` | `ReactNode / slot` | - | The items. Each direct child is draggable. data-x and data-y (0 to 100, percent of the area) and data-rotate (deg) on a child set its starting spot instead of the seed. |

## Accessibility

- Each item gets tabindex="0" and a description from hintLabel, so keyboard users can reach and move it.
- Arrow keys move the focused item 10px (Shift for 50px) and Escape returns it to where it started; the item also comes to the front.
- Buttons, links, and fields inside an item keep working: a press on them does not start a drag.
- With reduced motion items still follow the pointer and keys, but there is no glide, spring, or easing.

## Notes

- Each direct child becomes draggable and is placed at a seeded spot inside the area. `data-x` and `data-y` (0 to 100) and `data-rotate` on a child pin its start.
- `release="inertia"` glides on and bounces off the edges, `"stay"` stops where it is dropped, `"return"` springs back home.
- Focus an item with Tab, move it with the arrow keys (Shift for bigger steps), and press Escape to put it back. The item you touch comes to the front.
- Give the area a height. Items never leave it. Positions are not saved; use it for play, not for real ordering.
- Change the screen reader hint with `hintLabel`.
