Drag Elements
Area kartu atau stiker yang bisa diseret dengan momentum ringan di dalam batasnya. Panah menggeser item yang fokus, Escape mengembalikannya.
Brand refresh
Warm, calm, a little playful
Brand refresh
Warm, calm, a little playful
Brand refresh
Warm, calm, a little playful
Brand refresh
Warm, calm, a little playful
Brand refresh
Warm, calm, a little playful
@php
$board = 'h-80 rounded-xl border border-line bg-subtle';
$note = 'w-44 rounded-lg bg-surface p-4 shadow-overlay';
$noteTitle = 'text-sm font-semibold text-ink';
$noteText = 'mt-1 text-sm text-muted';
$sticker = 'rounded-full bg-primary px-4 py-2 text-sm font-semibold text-on-primary';
$round = 'grid size-16 place-items-center rounded-full border-2 border-dashed border-success bg-surface text-sm font-semibold text-ink';
$swatches = 'flex gap-1.5 rounded-lg bg-surface p-2 shadow-overlay';
$swatchPrimary = 'size-8 rounded-md bg-primary';
$swatchSuccess = 'size-8 rounded-md bg-success';
$swatchWarning = 'size-8 rounded-md bg-warning';
$tag = 'rounded-md border border-line bg-surface px-3 py-1.5 text-sm font-medium text-ink';
@endphp
<x-markas.drag-elements :seed="4" :class="$board" role="group" aria-label="Moodboard">
<div class="{{ $note }}">
<p class="{{ $noteTitle }}">Brand refresh</p>
<p class="{{ $noteText }}">Warm, calm, a little playful</p>
</div>
<span class="{{ $sticker }}">Kopi susu</span>
<span class="{{ $round }}">New</span>
<span class="{{ $tag }}">Batik pattern</span>
<div class="{{ $swatches }}" aria-label="Palette" role="img">
<span class="{{ $swatchPrimary }}"></span>
<span class="{{ $swatchSuccess }}"></span>
<span class="{{ $swatchWarning }}"></span>
</div>
</x-markas.drag-elements>import { DragElements } from "@/components/markas/DragElements";
const board = "h-80 rounded-xl border border-line bg-subtle";
const note = "w-44 rounded-lg bg-surface p-4 shadow-overlay";
const noteTitle = "text-sm font-semibold text-ink";
const noteText = "mt-1 text-sm text-muted";
const sticker =
"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-on-primary";
const round =
"grid size-16 place-items-center rounded-full border-2 border-dashed border-success bg-surface text-sm font-semibold text-ink";
const swatches = "flex gap-1.5 rounded-lg bg-surface p-2 shadow-overlay";
const swatchPrimary = "size-8 rounded-md bg-primary";
const swatchSuccess = "size-8 rounded-md bg-success";
const swatchWarning = "size-8 rounded-md bg-warning";
const tag =
"rounded-md border border-line bg-surface px-3 py-1.5 text-sm font-medium text-ink";
export default function DragElementsExample() {
return (
<DragElements
seed={4}
className={board}
role="group"
aria-label="Moodboard"
>
<div className={note}>
<p className={noteTitle}>Brand refresh</p>
<p className={noteText}>Warm, calm, a little playful</p>
</div>
<span className={sticker}>Kopi susu</span>
<span className={round}>New</span>
<span className={tag}>Batik pattern</span>
<div className={swatches} aria-label="Palette" role="img">
<span className={swatchPrimary}></span>
<span className={swatchSuccess}></span>
<span className={swatchWarning}></span>
</div>
</DragElements>
);
}<script setup lang="ts">
import DragElements from "@/components/markas/DragElements.vue";
const board = "h-80 rounded-xl border border-line bg-subtle";
const note = "w-44 rounded-lg bg-surface p-4 shadow-overlay";
const noteTitle = "text-sm font-semibold text-ink";
const noteText = "mt-1 text-sm text-muted";
const sticker =
"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-on-primary";
const round =
"grid size-16 place-items-center rounded-full border-2 border-dashed border-success bg-surface text-sm font-semibold text-ink";
const swatches = "flex gap-1.5 rounded-lg bg-surface p-2 shadow-overlay";
const swatchPrimary = "size-8 rounded-md bg-primary";
const swatchSuccess = "size-8 rounded-md bg-success";
const swatchWarning = "size-8 rounded-md bg-warning";
const tag =
"rounded-md border border-line bg-surface px-3 py-1.5 text-sm font-medium text-ink";
</script>
<template>
<DragElements :seed="4" :class="board" role="group" aria-label="Moodboard">
<div :class="note">
<p :class="noteTitle">Brand refresh</p>
<p :class="noteText">Warm, calm, a little playful</p>
</div>
<span :class="sticker">Kopi susu</span>
<span :class="round">New</span>
<span :class="tag">Batik pattern</span>
<div :class="swatches" aria-label="Palette" role="img">
<span :class="swatchPrimary"></span>
<span :class="swatchSuccess"></span>
<span :class="swatchWarning"></span>
</div>
</DragElements>
</template><script lang="ts">
import DragElements from "$lib/components/markas/DragElements.svelte";
const board = "h-80 rounded-xl border border-line bg-subtle";
const note = "w-44 rounded-lg bg-surface p-4 shadow-overlay";
const noteTitle = "text-sm font-semibold text-ink";
const noteText = "mt-1 text-sm text-muted";
const sticker =
"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-on-primary";
const round =
"grid size-16 place-items-center rounded-full border-2 border-dashed border-success bg-surface text-sm font-semibold text-ink";
const swatches = "flex gap-1.5 rounded-lg bg-surface p-2 shadow-overlay";
const swatchPrimary = "size-8 rounded-md bg-primary";
const swatchSuccess = "size-8 rounded-md bg-success";
const swatchWarning = "size-8 rounded-md bg-warning";
const tag =
"rounded-md border border-line bg-surface px-3 py-1.5 text-sm font-medium text-ink";
</script>
<DragElements seed={4} class={board} role="group" aria-label="Moodboard">
<div class={note}>
<p class={noteTitle}>Brand refresh</p>
<p class={noteText}>Warm, calm, a little playful</p>
</div>
<span class={sticker}>Kopi susu</span>
<span class={round}>New</span>
<span class={tag}>Batik pattern</span>
<div class={swatches} aria-label="Palette" role="img">
<span class={swatchPrimary}></span>
<span class={swatchSuccess}></span>
<span class={swatchWarning}></span>
</div>
</DragElements>---
import DragElements from "@/components/markas/DragElements.astro";
const board = "h-80 rounded-xl border border-line bg-subtle";
const note = "w-44 rounded-lg bg-surface p-4 shadow-overlay";
const noteTitle = "text-sm font-semibold text-ink";
const noteText = "mt-1 text-sm text-muted";
const sticker =
"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-on-primary";
const round =
"grid size-16 place-items-center rounded-full border-2 border-dashed border-success bg-surface text-sm font-semibold text-ink";
const swatches = "flex gap-1.5 rounded-lg bg-surface p-2 shadow-overlay";
const swatchPrimary = "size-8 rounded-md bg-primary";
const swatchSuccess = "size-8 rounded-md bg-success";
const swatchWarning = "size-8 rounded-md bg-warning";
const tag =
"rounded-md border border-line bg-surface px-3 py-1.5 text-sm font-medium text-ink";
---
<DragElements seed={4} class={board} role="group" aria-label="Moodboard">
<div class={note}>
<p class={noteTitle}>Brand refresh</p>
<p class={noteText}>Warm, calm, a little playful</p>
</div>
<span class={sticker}>Kopi susu</span>
<span class={round}>New</span>
<span class={tag}>Batik pattern</span>
<div class={swatches} aria-label="Palette" role="img">
<span class={swatchPrimary}></span>
<span class={swatchSuccess}></span>
<span class={swatchWarning}></span>
</div>
</DragElements>import { Component } from "@angular/core";
import { DragElements } from "./markas/drag-elements.component";
@Component({
selector: "markas-example",
imports: [DragElements],
template: `
<markas-drag-elements
[seed]="4"
[class]="board"
role="group"
aria-label="Moodboard"
>
<div [class]="note">
<p [class]="noteTitle">Brand refresh</p>
<p [class]="noteText">Warm, calm, a little playful</p>
</div>
<span [class]="sticker">Kopi susu</span>
<span [class]="round">New</span>
<span [class]="tag">Batik pattern</span>
<div [class]="swatches" aria-label="Palette" role="img">
<span [class]="swatchPrimary"></span>
<span [class]="swatchSuccess"></span>
<span [class]="swatchWarning"></span>
</div>
</markas-drag-elements>
`,
})
export default class DragElementsExample {
protected readonly board = "h-80 rounded-xl border border-line bg-subtle";
protected readonly note = "w-44 rounded-lg bg-surface p-4 shadow-overlay";
protected readonly noteTitle = "text-sm font-semibold text-ink";
protected readonly noteText = "mt-1 text-sm text-muted";
protected readonly sticker =
"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-on-primary";
protected readonly round =
"grid size-16 place-items-center rounded-full border-2 border-dashed border-success bg-surface text-sm font-semibold text-ink";
protected readonly swatches =
"flex gap-1.5 rounded-lg bg-surface p-2 shadow-overlay";
protected readonly swatchPrimary = "size-8 rounded-md bg-primary";
protected readonly swatchSuccess = "size-8 rounded-md bg-success";
protected readonly swatchWarning = "size-8 rounded-md bg-warning";
protected readonly tag =
"rounded-md border border-line bg-surface px-3 py-1.5 text-sm font-medium text-ink";
}Contoh
Kartu tim dengan posisi dari data-x dan data-y
@php
$board = 'h-80 rounded-xl border border-line bg-canvas';
$card = 'flex w-48 items-center gap-3 rounded-xl border border-line bg-surface p-3';
$avatar = 'grid size-10 shrink-0 place-items-center rounded-full bg-primary-soft text-sm font-semibold text-ink';
$name = 'block text-sm font-semibold text-ink';
$role = 'block text-xs text-muted';
@endphp
<x-markas.drag-elements release="stay" :rotate="0" :class="$board" role="group" aria-label="Team">
<div data-x="8" data-y="10" data-rotate="-3" class="{{ $card }}">
<span aria-hidden="true" class="{{ $avatar }}">RP</span>
<span><span class="{{ $name }}">Rania Putri</span><span class="{{ $role }}">Design lead</span></span>
</div>
<div data-x="92" data-y="30" data-rotate="2" class="{{ $card }}">
<span aria-hidden="true" class="{{ $avatar }}">BS</span>
<span><span class="{{ $name }}">Bima Saputra</span><span class="{{ $role }}">Engineering</span></span>
</div>
<div data-x="12" data-y="70" data-rotate="2" class="{{ $card }}">
<span aria-hidden="true" class="{{ $avatar }}">SA</span>
<span><span class="{{ $name }}">Sekar Ayu</span><span class="{{ $role }}">Product</span></span>
</div>
<div data-x="88" data-y="92" data-rotate="-2" class="{{ $card }}">
<span aria-hidden="true" class="{{ $avatar }}">DP</span>
<span><span class="{{ $name }}">Dimas Pratama</span><span class="{{ $role }}">Research</span></span>
</div>
</x-markas.drag-elements>import { DragElements } from "@/components/markas/DragElements";
const board = "h-80 rounded-xl border border-line bg-canvas";
const card =
"flex w-48 items-center gap-3 rounded-xl border border-line bg-surface p-3";
const avatar =
"grid size-10 shrink-0 place-items-center rounded-full bg-primary-soft text-sm font-semibold text-ink";
const name = "block text-sm font-semibold text-ink";
const role = "block text-xs text-muted";
export default function Example() {
return (
<DragElements
release="stay"
rotate={0}
className={board}
role="group"
aria-label="Team"
>
<div data-x="8" data-y="10" data-rotate="-3" className={card}>
<span aria-hidden="true" className={avatar}>
RP
</span>
<span>
<span className={name}>Rania Putri</span>
<span className={role}>Design lead</span>
</span>
</div>
<div data-x="92" data-y="30" data-rotate="2" className={card}>
<span aria-hidden="true" className={avatar}>
BS
</span>
<span>
<span className={name}>Bima Saputra</span>
<span className={role}>Engineering</span>
</span>
</div>
<div data-x="12" data-y="70" data-rotate="2" className={card}>
<span aria-hidden="true" className={avatar}>
SA
</span>
<span>
<span className={name}>Sekar Ayu</span>
<span className={role}>Product</span>
</span>
</div>
<div data-x="88" data-y="92" data-rotate="-2" className={card}>
<span aria-hidden="true" className={avatar}>
DP
</span>
<span>
<span className={name}>Dimas Pratama</span>
<span className={role}>Research</span>
</span>
</div>
</DragElements>
);
}<script setup lang="ts">
import DragElements from "@/components/markas/DragElements.vue";
const board = "h-80 rounded-xl border border-line bg-canvas";
const card =
"flex w-48 items-center gap-3 rounded-xl border border-line bg-surface p-3";
const avatar =
"grid size-10 shrink-0 place-items-center rounded-full bg-primary-soft text-sm font-semibold text-ink";
const name = "block text-sm font-semibold text-ink";
const role = "block text-xs text-muted";
</script>
<template>
<DragElements
release="stay"
:rotate="0"
:class="board"
role="group"
aria-label="Team"
>
<div data-x="8" data-y="10" data-rotate="-3" :class="card">
<span aria-hidden="true" :class="avatar">RP</span>
<span
><span :class="name">Rania Putri</span
><span :class="role">Design lead</span></span
>
</div>
<div data-x="92" data-y="30" data-rotate="2" :class="card">
<span aria-hidden="true" :class="avatar">BS</span>
<span
><span :class="name">Bima Saputra</span
><span :class="role">Engineering</span></span
>
</div>
<div data-x="12" data-y="70" data-rotate="2" :class="card">
<span aria-hidden="true" :class="avatar">SA</span>
<span
><span :class="name">Sekar Ayu</span
><span :class="role">Product</span></span
>
</div>
<div data-x="88" data-y="92" data-rotate="-2" :class="card">
<span aria-hidden="true" :class="avatar">DP</span>
<span
><span :class="name">Dimas Pratama</span
><span :class="role">Research</span></span
>
</div>
</DragElements>
</template><script lang="ts">
import DragElements from "$lib/components/markas/DragElements.svelte";
const board = "h-80 rounded-xl border border-line bg-canvas";
const card =
"flex w-48 items-center gap-3 rounded-xl border border-line bg-surface p-3";
const avatar =
"grid size-10 shrink-0 place-items-center rounded-full bg-primary-soft text-sm font-semibold text-ink";
const name = "block text-sm font-semibold text-ink";
const role = "block text-xs text-muted";
</script>
<DragElements
release="stay"
rotate={0}
class={board}
role="group"
aria-label="Team"
>
<div data-x="8" data-y="10" data-rotate="-3" class={card}>
<span aria-hidden="true" class={avatar}>RP</span>
<span>
<span class={name}>Rania Putri</span>
<span class={role}>Design lead</span>
</span>
</div>
<div data-x="92" data-y="30" data-rotate="2" class={card}>
<span aria-hidden="true" class={avatar}>BS</span>
<span>
<span class={name}>Bima Saputra</span>
<span class={role}>Engineering</span>
</span>
</div>
<div data-x="12" data-y="70" data-rotate="2" class={card}>
<span aria-hidden="true" class={avatar}>SA</span>
<span>
<span class={name}>Sekar Ayu</span>
<span class={role}>Product</span>
</span>
</div>
<div data-x="88" data-y="92" data-rotate="-2" class={card}>
<span aria-hidden="true" class={avatar}>DP</span>
<span>
<span class={name}>Dimas Pratama</span>
<span class={role}>Research</span>
</span>
</div>
</DragElements>---
import DragElements from "@/components/markas/DragElements.astro";
const board = "h-80 rounded-xl border border-line bg-canvas";
const card =
"flex w-48 items-center gap-3 rounded-xl border border-line bg-surface p-3";
const avatar =
"grid size-10 shrink-0 place-items-center rounded-full bg-primary-soft text-sm font-semibold text-ink";
const name = "block text-sm font-semibold text-ink";
const role = "block text-xs text-muted";
---
<DragElements
release="stay"
rotate={0}
class={board}
role="group"
aria-label="Team"
>
<div data-x="8" data-y="10" data-rotate="-3" class={card}>
<span aria-hidden="true" class={avatar}>RP</span>
<span>
<span class={name}>Rania Putri</span>
<span class={role}>Design lead</span>
</span>
</div>
<div data-x="92" data-y="30" data-rotate="2" class={card}>
<span aria-hidden="true" class={avatar}>BS</span>
<span>
<span class={name}>Bima Saputra</span>
<span class={role}>Engineering</span>
</span>
</div>
<div data-x="12" data-y="70" data-rotate="2" class={card}>
<span aria-hidden="true" class={avatar}>SA</span>
<span>
<span class={name}>Sekar Ayu</span>
<span class={role}>Product</span>
</span>
</div>
<div data-x="88" data-y="92" data-rotate="-2" class={card}>
<span aria-hidden="true" class={avatar}>DP</span>
<span>
<span class={name}>Dimas Pratama</span>
<span class={role}>Research</span>
</span>
</div>
</DragElements>import { Component } from "@angular/core";
import { DragElements } from "./markas/drag-elements.component";
@Component({
selector: "markas-example",
imports: [DragElements],
template: `
<markas-drag-elements
release="stay"
[rotate]="0"
[class]="board"
role="group"
aria-label="Team"
>
<div data-x="8" data-y="10" data-rotate="-3" [class]="card">
<span aria-hidden="true" [class]="avatar">RP</span>
<span>
<span [class]="name">Rania Putri</span>
<span [class]="role">Design lead</span>
</span>
</div>
<div data-x="92" data-y="30" data-rotate="2" [class]="card">
<span aria-hidden="true" [class]="avatar">BS</span>
<span>
<span [class]="name">Bima Saputra</span>
<span [class]="role">Engineering</span>
</span>
</div>
<div data-x="12" data-y="70" data-rotate="2" [class]="card">
<span aria-hidden="true" [class]="avatar">SA</span>
<span>
<span [class]="name">Sekar Ayu</span>
<span [class]="role">Product</span>
</span>
</div>
<div data-x="88" data-y="92" data-rotate="-2" [class]="card">
<span aria-hidden="true" [class]="avatar">DP</span>
<span>
<span [class]="name">Dimas Pratama</span>
<span [class]="role">Research</span>
</span>
</div>
</markas-drag-elements>
`,
})
export default class DragElementsTeamExample {
protected readonly board = "h-80 rounded-xl border border-line bg-canvas";
protected readonly card =
"flex w-48 items-center gap-3 rounded-xl border border-line bg-surface p-3";
protected readonly avatar =
"grid size-10 shrink-0 place-items-center rounded-full bg-primary-soft text-sm font-semibold text-ink";
protected readonly name = "block text-sm font-semibold text-ink";
protected readonly role = "block text-xs text-muted";
}Tag elastis yang kembali memegas
Stack we love
Pull a tag, it springs back
Stack we love
Pull a tag, it springs back
Stack we love
Pull a tag, it springs back
Stack we love
Pull a tag, it springs back
Stack we love
Pull a tag, it springs back
@php
$box = 'rounded-xl border border-line bg-surface p-5';
$title = 'text-sm font-semibold text-ink';
$hint = 'text-sm text-muted';
$board = 'mt-4 h-44 rounded-lg bg-subtle';
$chip = 'rounded-full border border-primary-line bg-primary-soft px-3 py-1.5 text-sm font-medium text-ink';
@endphp
<div class="{{ $box }}">
<p class="{{ $title }}">Stack we love</p>
<p class="{{ $hint }}">Pull a tag, it springs back</p>
<x-markas.drag-elements release="return" :rotate="12" :seed="4" :class="$board" role="group" aria-label="Skills">
<span class="{{ $chip }}">Laravel</span>
<span class="{{ $chip }}">Vue</span>
<span class="{{ $chip }}">React</span>
<span class="{{ $chip }}">Tailwind CSS</span>
<span class="{{ $chip }}">Alpine.js</span>
<span class="{{ $chip }}">Figma</span>
</x-markas.drag-elements>
</div>import { DragElements } from "@/components/markas/DragElements";
const box = "rounded-xl border border-line bg-surface p-5";
const title = "text-sm font-semibold text-ink";
const hint = "text-sm text-muted";
const board = "mt-4 h-44 rounded-lg bg-subtle";
const chip =
"rounded-full border border-primary-line bg-primary-soft px-3 py-1.5 text-sm font-medium text-ink";
export default function Example() {
return (
<div className={box}>
<p className={title}>Stack we love</p>
<p className={hint}>Pull a tag, it springs back</p>
<DragElements
release="return"
rotate={12}
seed={4}
className={board}
role="group"
aria-label="Skills"
>
<span className={chip}>Laravel</span>
<span className={chip}>Vue</span>
<span className={chip}>React</span>
<span className={chip}>Tailwind CSS</span>
<span className={chip}>Alpine.js</span>
<span className={chip}>Figma</span>
</DragElements>
</div>
);
}<script setup lang="ts">
import DragElements from "@/components/markas/DragElements.vue";
const box = "rounded-xl border border-line bg-surface p-5";
const title = "text-sm font-semibold text-ink";
const hint = "text-sm text-muted";
const board = "mt-4 h-44 rounded-lg bg-subtle";
const chip =
"rounded-full border border-primary-line bg-primary-soft px-3 py-1.5 text-sm font-medium text-ink";
</script>
<template>
<div :class="box">
<p :class="title">Stack we love</p>
<p :class="hint">Pull a tag, it springs back</p>
<DragElements
release="return"
:rotate="12"
:seed="4"
:class="board"
role="group"
aria-label="Skills"
>
<span :class="chip">Laravel</span>
<span :class="chip">Vue</span>
<span :class="chip">React</span>
<span :class="chip">Tailwind CSS</span>
<span :class="chip">Alpine.js</span>
<span :class="chip">Figma</span>
</DragElements>
</div>
</template><script lang="ts">
import DragElements from "$lib/components/markas/DragElements.svelte";
const box = "rounded-xl border border-line bg-surface p-5";
const title = "text-sm font-semibold text-ink";
const hint = "text-sm text-muted";
const board = "mt-4 h-44 rounded-lg bg-subtle";
const chip =
"rounded-full border border-primary-line bg-primary-soft px-3 py-1.5 text-sm font-medium text-ink";
</script>
<div class={box}>
<p class={title}>Stack we love</p>
<p class={hint}>Pull a tag, it springs back</p>
<DragElements
release="return"
rotate={12}
seed={4}
class={board}
role="group"
aria-label="Skills"
>
<span class={chip}>Laravel</span>
<span class={chip}>Vue</span>
<span class={chip}>React</span>
<span class={chip}>Tailwind CSS</span>
<span class={chip}>Alpine.js</span>
<span class={chip}>Figma</span>
</DragElements>
</div>---
import DragElements from "@/components/markas/DragElements.astro";
const box = "rounded-xl border border-line bg-surface p-5";
const title = "text-sm font-semibold text-ink";
const hint = "text-sm text-muted";
const board = "mt-4 h-44 rounded-lg bg-subtle";
const chip =
"rounded-full border border-primary-line bg-primary-soft px-3 py-1.5 text-sm font-medium text-ink";
---
<div class={box}>
<p class={title}>Stack we love</p>
<p class={hint}>Pull a tag, it springs back</p>
<DragElements
release="return"
rotate={12}
seed={4}
class={board}
role="group"
aria-label="Skills"
>
<span class={chip}>Laravel</span>
<span class={chip}>Vue</span>
<span class={chip}>React</span>
<span class={chip}>Tailwind CSS</span>
<span class={chip}>Alpine.js</span>
<span class={chip}>Figma</span>
</DragElements>
</div>import { Component } from "@angular/core";
import { DragElements } from "./markas/drag-elements.component";
@Component({
selector: "markas-example",
imports: [DragElements],
template: `
<div [class]="box">
<p [class]="title">Stack we love</p>
<p [class]="hint">Pull a tag, it springs back</p>
<markas-drag-elements
release="return"
[rotate]="12"
[seed]="4"
[class]="board"
role="group"
aria-label="Skills"
>
<span [class]="chip">Laravel</span>
<span [class]="chip">Vue</span>
<span [class]="chip">React</span>
<span [class]="chip">Tailwind CSS</span>
<span [class]="chip">Alpine.js</span>
<span [class]="chip">Figma</span>
</markas-drag-elements>
</div>
`,
})
export default class DragElementsReturnExample {
protected readonly box = "rounded-xl border border-line bg-surface p-5";
protected readonly title = "text-sm font-semibold text-ink";
protected readonly hint = "text-sm text-muted";
protected readonly board = "mt-4 h-44 rounded-lg bg-subtle";
protected readonly chip =
"rounded-full border border-primary-line bg-primary-soft px-3 py-1.5 text-sm font-medium text-ink";
}Paket dalam Rupiah untuk diseret berdampingan
Basic
Rp 49.000
per month
Pro
Rp 99.000
per month
Team
Rp 199.000
per month
Basic
Rp 49.000
per month
Pro
Rp 99.000
per month
Team
Rp 199.000
per month
Basic
Rp 49.000
per month
Pro
Rp 99.000
per month
Team
Rp 199.000
per month
Basic
Rp 49.000
per month
Pro
Rp 99.000
per month
Team
Rp 199.000
per month
Basic
Rp 49.000
per month
Pro
Rp 99.000
per month
Team
Rp 199.000
per month
@php
$board = 'h-72 rounded-xl border border-line bg-subtle';
$card = 'w-36 rounded-xl border border-line bg-surface p-4';
$featured = 'w-36 rounded-xl bg-primary p-4 text-on-primary';
$plan = 'text-sm font-medium';
$price = 'mt-2 text-lg font-semibold tabular-nums';
$period = 'text-xs opacity-80';
@endphp
<x-markas.drag-elements :rotate="5" :seed="3" :class="$board" role="group" aria-label="Plans to compare">
<div data-x="6" data-y="12" class="{{ $card }}">
<p class="{{ $plan }}">Basic</p>
<p class="{{ $price }}">Rp 49.000</p>
<p class="{{ $period }}">per month</p>
</div>
<div data-x="50" data-y="92" class="{{ $featured }}">
<p class="{{ $plan }}">Pro</p>
<p class="{{ $price }}">Rp 99.000</p>
<p class="{{ $period }}">per month</p>
</div>
<div data-x="94" data-y="18" class="{{ $card }}">
<p class="{{ $plan }}">Team</p>
<p class="{{ $price }}">Rp 199.000</p>
<p class="{{ $period }}">per month</p>
</div>
</x-markas.drag-elements>import { DragElements } from "@/components/markas/DragElements";
const board = "h-72 rounded-xl border border-line bg-subtle";
const card = "w-36 rounded-xl border border-line bg-surface p-4";
const featured = "w-36 rounded-xl bg-primary p-4 text-on-primary";
const plan = "text-sm font-medium";
const price = "mt-2 text-lg font-semibold tabular-nums";
const period = "text-xs opacity-80";
export default function Example() {
return (
<DragElements
rotate={5}
seed={3}
className={board}
role="group"
aria-label="Plans to compare"
>
<div data-x="6" data-y="12" className={card}>
<p className={plan}>Basic</p>
<p className={price}>Rp 49.000</p>
<p className={period}>per month</p>
</div>
<div data-x="50" data-y="92" className={featured}>
<p className={plan}>Pro</p>
<p className={price}>Rp 99.000</p>
<p className={period}>per month</p>
</div>
<div data-x="94" data-y="18" className={card}>
<p className={plan}>Team</p>
<p className={price}>Rp 199.000</p>
<p className={period}>per month</p>
</div>
</DragElements>
);
}<script setup lang="ts">
import DragElements from "@/components/markas/DragElements.vue";
const board = "h-72 rounded-xl border border-line bg-subtle";
const card = "w-36 rounded-xl border border-line bg-surface p-4";
const featured = "w-36 rounded-xl bg-primary p-4 text-on-primary";
const plan = "text-sm font-medium";
const price = "mt-2 text-lg font-semibold tabular-nums";
const period = "text-xs opacity-80";
</script>
<template>
<DragElements
:rotate="5"
:seed="3"
:class="board"
role="group"
aria-label="Plans to compare"
>
<div data-x="6" data-y="12" :class="card">
<p :class="plan">Basic</p>
<p :class="price">Rp 49.000</p>
<p :class="period">per month</p>
</div>
<div data-x="50" data-y="92" :class="featured">
<p :class="plan">Pro</p>
<p :class="price">Rp 99.000</p>
<p :class="period">per month</p>
</div>
<div data-x="94" data-y="18" :class="card">
<p :class="plan">Team</p>
<p :class="price">Rp 199.000</p>
<p :class="period">per month</p>
</div>
</DragElements>
</template><script lang="ts">
import DragElements from "$lib/components/markas/DragElements.svelte";
const board = "h-72 rounded-xl border border-line bg-subtle";
const card = "w-36 rounded-xl border border-line bg-surface p-4";
const featured = "w-36 rounded-xl bg-primary p-4 text-on-primary";
const plan = "text-sm font-medium";
const price = "mt-2 text-lg font-semibold tabular-nums";
const period = "text-xs opacity-80";
</script>
<DragElements
rotate={5}
seed={3}
class={board}
role="group"
aria-label="Plans to compare"
>
<div data-x="6" data-y="12" class={card}>
<p class={plan}>Basic</p>
<p class={price}>Rp 49.000</p>
<p class={period}>per month</p>
</div>
<div data-x="50" data-y="92" class={featured}>
<p class={plan}>Pro</p>
<p class={price}>Rp 99.000</p>
<p class={period}>per month</p>
</div>
<div data-x="94" data-y="18" class={card}>
<p class={plan}>Team</p>
<p class={price}>Rp 199.000</p>
<p class={period}>per month</p>
</div>
</DragElements>---
import DragElements from "@/components/markas/DragElements.astro";
const board = "h-72 rounded-xl border border-line bg-subtle";
const card = "w-36 rounded-xl border border-line bg-surface p-4";
const featured = "w-36 rounded-xl bg-primary p-4 text-on-primary";
const plan = "text-sm font-medium";
const price = "mt-2 text-lg font-semibold tabular-nums";
const period = "text-xs opacity-80";
---
<DragElements
rotate={5}
seed={3}
class={board}
role="group"
aria-label="Plans to compare"
>
<div data-x="6" data-y="12" class={card}>
<p class={plan}>Basic</p>
<p class={price}>Rp 49.000</p>
<p class={period}>per month</p>
</div>
<div data-x="50" data-y="92" class={featured}>
<p class={plan}>Pro</p>
<p class={price}>Rp 99.000</p>
<p class={period}>per month</p>
</div>
<div data-x="94" data-y="18" class={card}>
<p class={plan}>Team</p>
<p class={price}>Rp 199.000</p>
<p class={period}>per month</p>
</div>
</DragElements>import { Component } from "@angular/core";
import { DragElements } from "./markas/drag-elements.component";
@Component({
selector: "markas-example",
imports: [DragElements],
template: `
<markas-drag-elements
[rotate]="5"
[seed]="3"
[class]="board"
role="group"
aria-label="Plans to compare"
>
<div data-x="6" data-y="12" [class]="card">
<p [class]="plan">Basic</p>
<p [class]="price">Rp 49.000</p>
<p [class]="period">per month</p>
</div>
<div data-x="50" data-y="92" [class]="featured">
<p [class]="plan">Pro</p>
<p [class]="price">Rp 99.000</p>
<p [class]="period">per month</p>
</div>
<div data-x="94" data-y="18" [class]="card">
<p [class]="plan">Team</p>
<p [class]="price">Rp 199.000</p>
<p [class]="period">per month</p>
</div>
</markas-drag-elements>
`,
})
export default class DragElementsPricingExample {
protected readonly board = "h-72 rounded-xl border border-line bg-subtle";
protected readonly card = "w-36 rounded-xl border border-line bg-surface p-4";
protected readonly featured =
"w-36 rounded-xl bg-primary p-4 text-on-primary";
protected readonly plan = "text-sm font-medium";
protected readonly price = "mt-2 text-lg font-semibold tabular-nums";
protected readonly period = "text-xs opacity-80";
}Instalasi
npx markasui@latest add drag-elementspnpm dlx markasui@latest add drag-elementsyarn dlx markasui@latest add drag-elementsbunx --bun markasui@latest add drag-elements- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Pasang dependensi:
npm install alpinejs - Salin source komponen di bawah ini ke
resources/views/components/markas/drag-elements.blade.php.
@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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/DragElements.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>
);
}- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/DragElements.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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/lib/components/markas/DragElements.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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/DragElements.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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/app/markas/drag-elements.component.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);
});
}
}Pemakaian
<x-markas.drag-elements :seed="4" hint-label="Seret untuk memindahkan, atau pakai tombol panah. Escape mengembalikannya" 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 baru</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">Motif batik</span>
</x-markas.drag-elements>Butuh Alpine.js.
import { DragElements } from "@/components/markas/DragElements";
<DragElements
release="return"
hintLabel="Seret untuk memindahkan, atau pakai tombol panah. Escape mengembalikannya"
className="h-80 rounded-xl border border-line bg-subtle"
role="group"
aria-label="Keahlian"
>
<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>;<template>
<DragElements
release="stay"
:rotate="0"
hint-label="Seret untuk memindahkan, atau pakai tombol panah. Escape mengembalikannya"
class="h-80 rounded-xl border border-line bg-canvas"
role="group"
aria-label="Tim"
>
<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><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>---
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>Setiap area adalah custom element kecil, jadi tetap jalan setelah view transition.
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, dan class pindah dari host ke area.
- Setiap anak langsung bisa diseret dan ditaruh di posisi seed di dalam area.
data-xdandata-y(0 sampai 100) sertadata-rotatepada anak mengunci posisi awalnya. release="inertia"meluncur dan memantul di tepi,"stay"berhenti di tempat dilepas,"return"kembali memegas ke posisi awal.- Fokuskan item dengan Tab, geser dengan tombol panah (Shift untuk langkah besar), dan tekan Escape untuk mengembalikannya. Item yang disentuh naik ke depan.
- Beri area tinggi. Item tidak pernah keluar dari area. Posisi tidak disimpan; pakai untuk main-main, bukan untuk mengurutkan sungguhan.
- Ubah petunjuk screen reader lewat
hintLabel.
Props
| Nama | Tipe | Default | Keterangan |
|---|---|---|---|
release | "inertia" | "stay" | "return" | "inertia" | Perilaku item saat dilepas: meluncur dengan gesekan dan memantul di tepi, berhenti di tempat, atau kembali memegas ke posisi awal. |
rotate | number | 6 | Kemiringan acak terbesar dalam derajat untuk item tanpa data-rotate. 0 membuatnya tegak. |
seed | number | 1 | Mengubah posisi awal yang tersebar. Seed yang sama selalu menghasilkan tata letak yang sama. |
hintLabel | string | "Drag to move, or use the arrow keys. Escape puts it back" | Deskripsi yang dibacakan screen reader untuk setiap item. |
children / slot | ReactNode / slot | - | Item-itemnya. Setiap anak langsung bisa diseret. data-x dan data-y (0 sampai 100, persen dari area) serta data-rotate (derajat) pada anak menentukan posisi awalnya, bukan seed. |
Aksesibilitas
- Setiap item mendapat tabindex="0" dan deskripsi dari hintLabel, sehingga pengguna keyboard bisa menjangkau dan menggesernya.
- Tombol panah menggeser item yang fokus 10px (Shift untuk 50px) dan Escape mengembalikannya ke posisi awal; item juga naik ke depan.
- Tombol, tautan, dan field di dalam item tetap berfungsi: menekannya tidak memulai seret.
- Dengan reduced motion item tetap mengikuti pointer dan tombol, tapi tanpa luncuran, pegas, atau easing.
Komponen terkait
Komponen markasui lain dengan class yang sama di setiap framework.
- Bottom NavigationBar bawah gaya aplikasi mobile. Pill meluncur ke item terpilih, labelnya muncul, dan bar bisa menciut jadi ikon saat konten discroll.
- Card StackTumpukan kartu bertingkat. Geser, tombol panah, atau tombol navigasi membuang kartu teratas lalu kartu berikutnya naik. Berputar, dengan indikator posisi.
- Chat MessagePesan dalam percakapan AI. Gelembung user di kanan, balasan asisten dengan avatar, aksi saat hover, indikator mengetik, dan efek streaming token opsional.
- Currency InputKolom uang yang memformat saat mengetik (Rp 12.500.000), menjaga posisi kursor, dan mengirim angka murni. Opsional chip nominal cepat.
- DockDock ala macOS. Ikon membesar halus mengikuti kursor atau fokus, label muncul di atas, item terbuka bertitik, dan memantul saat dibuka.
- Dynamic IslandPill hitam terinspirasi Dynamic Island iPhone. Memuai mulus antara keadaan idle, compact, dan expanded sambil kontennya crossfade.