Skip to content
Brok UI

Loading…

No results

Reorder

Open source

Drag-to-arrange surfaces — a kanban board, a sortable list and a swap-in-place grid.

Version
v1.1.1
Stability
stable
License
MIT
Related
Kanban
Swappable Grid

Sortable — A drag-to-reorder list that moves the way the kanban board does: the row lifts under the pointer, a live placeholder and gliding rows show where it lands; keyboard reordering from the grip, hidden inputs mirroring the order, and a change event.

Preview

previews.components.sortable.default.blade.php Blade
<div class="w-full max-w-md">
    <x-ui.sortable name="order" />
</div>

Installation

terminal
php artisan ui:add sortable

Note

This component ships an Alpine behavior module at resources/js/ui/sortable.js. Import it once from your bundle so it registers on alpine:init:

resources/js/ui/index.js JS
import './sortable.js';

Registry contract

php artisan ui:add sortable writes only the files below. The CLI validates each file hash before writing and asks before it replaces a local change, unless you pass --force.

  • blade resources/views/components/ui/sortable.blade.php
  • js resources/js/ui/sortable.js
Registry dependencies
None — installs on its own.
Packages
composer: jml/brok:^0.2
npm: alpinejs

Use with AI

A brief for your coding agent: install command, usage, props, guidance and the rules. Copy it, or open a prompt about this component in an assistant.

sortable.md
# Brok UI: Sortable (`sortable`)

A drag-to-reorder list that moves the way the kanban board does: the row lifts under the pointer, a live placeholder and gliding rows show where it lands; keyboard reordering from the grip, hidden inputs mirroring the order, and a change event.

Brok UI is a Laravel Blade component registry. Installed components are plain Blade files the app owns.

## Install

```bash
php artisan ui:add sortable
```

## Usage

```blade
<div class="w-full max-w-md">
    <x-ui.sortable name="order" />
</div>
```

## Props

- `items` (array, default `[…]`) — Array of items, each with an id, a label, and an optional meta line.
- `name` (string, default `order`) — Field name used for the hidden inputs that mirror the current order as name[].

## Use when

- Use to group related content into scannable units for browsing, prioritization, or rearrangement.
- Letting users reorder a single flat list of items, such as a priority list or a set of steps.
- Needing the new order to submit in a plain form via hidden inputs, without a full JavaScript round trip.

## Avoid when

- Do not use card-like structures when dense row-by-row comparison would be clearer in a list or table.
- Items need to move between grouped columns or lanes; use kanban instead.
- The list is a uniform grid of tiles rather than a vertical list; use swappable-grid.

## Anti-patterns

- Turning every object into a card

## Rules

- Use the `<brok:sortable>` tag (or `<x-ui.sortable>`) in Blade; do not rewrite the component.
- Prefer the documented props and variants over utility-class overrides; when a utility must win, use the `!` important modifier.
- Use semantic design tokens (`bg-primary`, `text-muted-foreground`), never raw colour utilities.
- Keep the `data-slot` attributes; they are the styling and test hooks.

## Links

- Docs: https://brokui.dev/docs/components/sortable
- Registry JSON (files, props, contract): https://brokui.dev/r/open/sortable.json

Working in Claude Code, Cursor or Codex? Give the agent the whole registry through the MCP server or the Brok UI skill.

Examples

cards.blade.php Blade
<div class="w-full max-w-md">
    <x-ui.sortable
        name="priorities"
        :items="[
            ['id' => 'design', 'label' => 'Design review', 'meta' => 'Casey Doyle, due in 2h'],
            ['id' => 'api', 'label' => 'API integration', 'meta' => 'Alex Brown, due today'],
            ['id' => 'qa', 'label' => 'QA pass', 'meta' => 'Jane Doe, due tomorrow'],
            ['id' => 'launch', 'label' => 'Launch checklist', 'meta' => 'Unassigned'],
            ['id' => 'retro', 'label' => 'Sprint retro', 'meta' => 'Friday'],
        ]"
    />
</div>

API

manifest knowledge + registry-derived coverage

Props

Props accepted by this component: name, type, default value and description.
Prop Type Default Description
items array […] Array of items, each with an id, a label, and an optional meta line.
name string order Field name used for the hidden inputs that mirror the current order as name[].

Slots

  • default —

Data slots

Stable hooks for CSS overrides and browser tests.

sortable sortable-ghost sortable-handle sortable-item

Behavior

  • Dragging the handle, or the whole row, lifts it under the pointer; a live placeholder marks its origin and other rows glide out of the way as it moves, the same interaction as the kanban board.
  • The handle also accepts arrow keys to reorder the row without a pointer.
  • Hidden inputs mirror the current order for plain form submission, and a change event fires whenever the order changes.
  • A polite live region announces reorders to assistive tech as they happen.
  • Installs a JavaScript behavior module when the registry item includes resources/js/ui files.
  • Declares registry capability flags: a11y, interactive, responsive, rtl, darkMode, localized.

Guidance

Card-based organization

Organize browsable objects into scannable units.

Use when

  • Use to group related content into scannable units for browsing, prioritization, or rearrangement.
  • Letting users reorder a single flat list of items, such as a priority list or a set of steps.
  • Needing the new order to submit in a plain form via hidden inputs, without a full JavaScript round trip.

Avoid when

  • Do not use card-like structures when dense row-by-row comparison would be clearer in a list or table.
  • Items need to move between grouped columns or lanes; use kanban instead.
  • The list is a uniform grid of tiles rather than a vertical list; use swappable-grid.

Use instead

  • Table for exact comparison
  • List for compact scanning

Anti-patterns

  • Turning every object into a card
Anatomy
root sortable-item sortable-handle sortable-ghost
Theming hooks
sortable sortable-ghost sortable-handle sortable-item

Accessibility

WCAG 2.2 AA Keyboard focus-visible RTL-ready Localized labels Dark mode
Keyboard
native
Focus
managed
  • The drag handle is a focusable button with an accessible label and full keyboard reordering, so the list is usable without a pointer.
  • A polite live region announces each reorder, giving screen reader users feedback that a drag or keyboard move completed.
  • Semantic HTML and a stable data-slot attribute for styling and scripting hooks.
  • Focus-visible rings use the ring token, so keyboard focus is always visible.
  • Disabled and invalid states are conveyed to assistive tech, not by color alone.
  • Targets WCAG 2.2 AA; verify contrast in light, dark, admin and customer surfaces in the preview.
  • Labels go through __() and layout uses logical properties (ms-*, text-start), so it mirrors under dir="rtl" — flip the preview to RTL to confirm.
  • Dark mode uses the same semantic tokens under the dark class; high contrast follows forced-color system tokens.

Livewire

Needs wire:key

Add a stable wire:key when Livewire can reorder this interactive component.

livewire-component.blade.php Blade
<div wire:key="sortable-{{ $record->id }}">
    <div class="w-full max-w-md">
        <x-ui.sortable name="order" />
    </div>
</div>

Validation

Validation support: native. Keep the error message connected with aria-describedby.

livewire-form.blade.php Blade
<form wire:submit="save" class="space-y-2">
    <brok:sortable
        wire:model="value"
        :aria-invalid="$errors->has('value') ? 'true' : 'false'"
        aria-describedby="value-error"
    />

    @error('value')
        <p id="value-error" role="alert">{{ $message }}</p>
    @enderror

    <brok:button type="submit" wire:loading.attr="disabled">
        <span wire:loading.remove>Save</span>
        <span wire:loading>Saving…</span>
    </brok:button>
</form>

Source

The exact, editable files ui:add writes into your app. Previews render this same code; there are no preview-only components.

resources/views/components/ui/sortable.blade.php Blade
@props([
    'items' => [
        ['id' => 'a', 'label' => 'Research competitors', 'meta' => 'Due Monday'],
        ['id' => 'b', 'label' => 'Draft the proposal', 'meta' => 'In review'],
        ['id' => 'c', 'label' => 'Design the landing page', 'meta' => 'Assigned'],
        ['id' => 'd', 'label' => 'Ship the release', 'meta' => 'Blocked'],
    ],
    'name' => 'order',
])

<div
    x-data="uiSortable({ items: @js(array_values($items)), name: @js($name) })"
    data-slot="sortable"
    {{ $attributes->merge(['class' => 'relative w-full']) }}
>
    <ul role="list" class="flex flex-col gap-2">
        <template x-for="(it, i) in items" :key="it.id">
            <li
                data-slot="sortable-item"
                role="listitem"
                x-bind:data-id="it.id"
                x-bind:data-index="i"
                x-bind:data-placeholder="isDragging(it.id) ? 'true' : null"
                @pointerdown="startDrag($event, i)"
                class="flex cursor-grab touch-none select-none items-center gap-3 rounded-md border border-border bg-card p-3 text-card-foreground shadow-xs transition-[box-shadow,border-color] hover:border-input active:cursor-grabbing data-[placeholder=true]:border-dashed data-[placeholder=true]:bg-muted/60 data-[placeholder=true]:shadow-none data-[placeholder=true]:[&>*]:invisible motion-reduce:transition-none"
            >
                {{-- Handle: the keyboard target (Arrow keys reorder); the whole row drags. --}}
                <button
                    type="button"
                    data-slot="sortable-handle"
                    x-bind:data-index="i"
                    @keydown="onKey($event, i)"
                    aria-label="{{ __('Drag to reorder') }}"
                    class="inline-flex shrink-0 cursor-grab items-center justify-center rounded text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background active:cursor-grabbing motion-reduce:transition-none"
                >
                    <svg viewBox="0 0 24 24" fill="currentColor" class="size-4" aria-hidden="true"><circle cx="9" cy="6" r="1.5" /><circle cx="15" cy="6" r="1.5" /><circle cx="9" cy="12" r="1.5" /><circle cx="15" cy="12" r="1.5" /><circle cx="9" cy="18" r="1.5" /><circle cx="15" cy="18" r="1.5" /></svg>
                </button>

                {{-- Label + optional meta. --}}
                <div class="min-w-0 flex-1">
                    <p class="truncate text-sm font-medium leading-snug" x-text="it.label"></p>
                    <p class="mt-0.5 truncate text-xs text-muted-foreground" x-show="it.meta" x-text="it.meta"></p>
                </div>
            </li>
        </template>
    </ul>

    {{-- Floating row that follows the pointer. --}}
    <template x-if="ghost && dragItem">
        <div
            data-slot="sortable-ghost"
            aria-hidden="true"
            class="pointer-events-none fixed z-overlay flex scale-[1.02] items-center gap-3 rounded-md border border-border bg-card p-3 text-card-foreground shadow-xl ring-1 ring-ring/40"
            x-bind:style="`left:${ghost.x}px; top:${ghost.y}px; width:${ghost.w}px; height:${ghost.h}px;`"
        >
            <span class="inline-flex shrink-0 text-muted-foreground"><svg viewBox="0 0 24 24" fill="currentColor" class="size-4" aria-hidden="true"><circle cx="9" cy="6" r="1.5" /><circle cx="15" cy="6" r="1.5" /><circle cx="9" cy="12" r="1.5" /><circle cx="15" cy="12" r="1.5" /><circle cx="9" cy="18" r="1.5" /><circle cx="15" cy="18" r="1.5" /></svg></span>
            <div class="min-w-0 flex-1">
                <p class="truncate text-sm font-medium leading-snug" x-text="dragItem.label"></p>
                <p class="mt-0.5 truncate text-xs text-muted-foreground" x-show="dragItem.meta" x-text="dragItem.meta"></p>
            </div>
        </div>
    </template>

    {{-- Mirror the current order to hidden inputs for normal form submission. --}}
    <template x-for="(it, i) in items" :key="'field-' + it.id">
        <input type="hidden" x-bind:name="hiddenName + '[]'" x-bind:value="it.id" />
    </template>

    {{-- Polite status region announces reorders to assistive tech. --}}
    <div class="sr-only" role="status" aria-live="polite" x-text="status"></div>
</div>
resources/js/ui/sortable.js JS
/**
 * Sortable list behavior — drag to reorder, the way the kanban board moves cards.
 *
 * Pointer: pointerdown on a row lifts it as a floating ghost under the pointer
 * and turns its list entry into a hollow placeholder. The placeholder moves
 * LIVE to the slot the drop would land in (the item is reordered in the data
 * as the pointer moves) and the other rows glide around it (FLIP: positions
 * measured before and after each move, the difference animated away). Release
 * settles the ghost onto the placeholder. Keyboard: the handle takes Arrow
 * Up/Down (Home/End to the ends); those moves glide too. The order is
 * mirrored to hidden `name[]` inputs, announced through the live region and
 * dispatched as `sortable:change` { order }. Reduced motion skips the glides.
 *
 * Self-registers on `alpine:init` so import order does not matter.
 */
document.addEventListener('alpine:init', () => {
    window.Alpine.data('uiSortable', (config = {}) => ({
        items: (config.items ?? []).map((it) => ({ ...it })),
        hiddenName: config.name ?? 'order',
        dragItem: null,
        dragIndex: null,
        ghost: null,
        status: '',
        root: null,
        _reduced: false,
        _origin: null,
        _move: null,
        _up: null,

        init() {
            this.root = this.$el;
            this._reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
            this._move = (e) => this.onMove(e);
            this._up = () => this.onUp();
        },

        isDragging(id) {
            return this.dragItem !== null && this.dragItem.id === id;
        },

        rows() {
            return [...this.root.querySelectorAll('[data-slot="sortable-item"]')];
        },

        // ---- Shared reorder primitive ---------------------------------------

        reorder(from, to) {
            const last = this.items.length - 1;
            const dest = Math.max(0, Math.min(to, last));
            if (from === dest) return undefined;
            const [moved] = this.items.splice(from, 1);
            this.items.splice(dest, 0, moved);
            return dest;
        },

        rowRects() {
            const rects = new Map();
            for (const el of this.rows()) rects.set(el.dataset.id, el.getBoundingClientRect());
            return rects;
        },

        glide(before) {
            if (this._reduced) return;
            this.$nextTick(() => {
                for (const el of this.rows()) {
                    const prev = before.get(el.dataset.id);
                    if (!prev || el.dataset.placeholder === 'true') continue;
                    const now = el.getBoundingClientRect();
                    const dy = prev.top - now.top;
                    if (!dy) continue;
                    el.getAnimations().forEach((a) => a.cancel());
                    el.animate([{ transform: `translateY(${dy}px)` }, { transform: 'none' }], { duration: 200, easing: 'cubic-bezier(0.22, 1, 0.36, 1)' });
                }
            });
        },

        announce(i) {
            const it = this.items[i];
            if (!it) return;
            this.status = `${it.label}, position ${i + 1} of ${this.items.length}`;
        },

        emit() {
            this.$dispatch('sortable:change', { order: this.items.map((it) => it.id) });
        },

        // ---- Keyboard reordering --------------------------------------------

        move(i, to) {
            const before = this.rowRects();
            const dest = this.reorder(i, to);
            if (dest === undefined) return;
            this.glide(before);
            this.announce(dest);
            this.emit();
            this.$nextTick(() => this.focusHandle(dest));
        },

        onKey(e, i) {
            const map = { ArrowUp: i - 1, ArrowDown: i + 1, Home: 0, End: this.items.length - 1 };
            if (!(e.key in map)) return;
            e.preventDefault();
            this.move(i, map[e.key]);
        },

        focusHandle(i) {
            this.root.querySelector(`[data-slot="sortable-handle"][data-index="${i}"]`)?.focus();
        },

        // ---- Pointer drag ---------------------------------------------------

        startDrag(e, i) {
            if (e.button !== undefined && e.button !== 0) return;
            // Links, fields and other buttons keep their own pointer behaviour.
            if (e.target.closest('a, input, textarea, select, button:not([data-slot="sortable-handle"])')) return;
            const el = e.currentTarget;
            const r = el.getBoundingClientRect();
            this.dragItem = this.items[i];
            this.dragIndex = i;
            this._origin = i;
            this.ghost = { w: r.width, h: r.height, dx: e.clientX - r.left, dy: e.clientY - r.top, x: r.left, y: r.top };
            window.addEventListener('pointermove', this._move);
            window.addEventListener('pointerup', this._up);
            window.addEventListener('pointercancel', this._up);
            e.preventDefault();
        },

        onMove(e) {
            if (!this.dragItem) return;
            this.ghost.x = e.clientX - this.ghost.dx;
            this.ghost.y = e.clientY - this.ghost.dy;
            // The slot is decided by row midpoints; the placeholder itself is skipped.
            let target = this.items.length - 1;
            for (const row of this.rows()) {
                if (row.dataset.placeholder === 'true') continue;
                const r = row.getBoundingClientRect();
                if (e.clientY < r.top + r.height / 2) {
                    const idx = Number(row.dataset.index);
                    target = idx > this.dragIndex ? idx - 1 : idx;
                    break;
                }
            }
            if (target !== this.dragIndex) {
                const before = this.rowRects();
                const dest = this.reorder(this.dragIndex, target);
                if (dest !== undefined) {
                    this.dragIndex = dest;
                    this.glide(before);
                }
            }
        },

        onUp() {
            if (!this.dragItem) return;
            window.removeEventListener('pointermove', this._move);
            window.removeEventListener('pointerup', this._up);
            window.removeEventListener('pointercancel', this._up);
            const placeholder = this.root.querySelector(`[data-slot="sortable-item"][data-id="${this.dragItem.id}"]`);
            const ghostEl = this.root.querySelector('[data-slot="sortable-ghost"]');
            const index = this.dragIndex;
            const moved = index !== this._origin;
            const finish = () => {
                this.dragItem = null;
                this.dragIndex = null;
                this.ghost = null;
                if (moved) {
                    this.announce(index);
                    this.emit();
                }
            };
            if (ghostEl && placeholder && !this._reduced) {
                const to = placeholder.getBoundingClientRect();
                const anim = ghostEl.animate(
                    [{ left: `${this.ghost.x}px`, top: `${this.ghost.y}px`, transform: 'scale(1.02)' }, { left: `${to.left}px`, top: `${to.top}px`, transform: 'none' }],
                    { duration: 180, easing: 'cubic-bezier(0.22, 1, 0.36, 1)', fill: 'forwards' },
                );
                anim.onfinish = finish;
                anim.oncancel = finish;
            } else {
                finish();
            }
        },

        destroy() {
            window.removeEventListener('pointermove', this._move);
            window.removeEventListener('pointerup', this._up);
            window.removeEventListener('pointercancel', this._up);
        },
    }));
});

Ownership & lifecycle

Owner, release state, review evidence and adoption for this item.
Owner
Platform UI (@JoshJML)
Current version
1.1.1
Status
Stable
License
open
Accessibility reviewed
No review date recorded
Last breaking change
No date recorded
Deprecation
Not deprecated
Contract
v6
Foundation
≥ 1.0.0