Skip to content
Brok UI

Loading…

No results

Table Handle

Open source

Row and column handles that overlay a table for selecting, inserting and deleting rows and columns in the editor. Composed as <x-ui.editor.table-handle>; <x-ui.table-handle> stays as the compatibility tag.

Version
v1.3.2
Stability
stable
License
MIT
Related
Table
Node Resizer
Block Handle

Preview

Column 1 Column 2 Column 3
Cell 1.1 Cell 1.2 Cell 1.3
Cell 2.1 Cell 2.2 Cell 2.3
Cell 3.1 Cell 3.2 Cell 3.3
previews.components.table-handle.default.blade.php Blade
<div class="w-full flex justify-center p-6">
    <x-ui.editor.table-handle :rows="3" :cols="3" />
</div>

Installation

terminal
php artisan ui:add table-handle

Note

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

resources/js/ui/index.js JS
import './table-handle.js';

Registry contract

php artisan ui:add table-handle 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/editor/table-handle.blade.php
  • blade resources/views/components/ui/table-handle.blade.php
  • js resources/js/ui/table-handle.js
Registry dependencies
dropdown editor
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.

table-handle.md
# Brok UI: Table Handle (`table-handle`)

Row and column handles that overlay a table for selecting, inserting and deleting rows and columns in the editor. Composed as <x-ui.editor.table-handle>; <x-ui.table-handle> stays as the compatibility tag.

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

## Install

```bash
php artisan ui:add table-handle
```

## Usage

```blade
<div class="w-full flex justify-center p-6">
    <x-ui.editor.table-handle :rows="3" :cols="3" />
</div>
```

## Props

- `rows` (int, default `3`) — Initial row count used before the ResizeObserver measures the real table.
- `cols` (int, default `3`) — Initial column count used before the ResizeObserver measures the real table.

## Use when

- Use when users need rich structured authoring, annotation, or collaborative editing controls.
- Adding row and column grips over a table inside <x-ui.editor> so a reader can insert or delete rows and columns without a separate toolbar.

## Avoid when

- Do not use rich editor affordances for simple one-line or plain-text tasks.
- The table is not editable content; a static table needs no grips.

## Anti-patterns

- Rich editors for one-line or easily validated input

## Rules

- Use the `<brok:table-handle>` tag (or `<x-ui.table-handle>`) 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/table-handle
- Registry JSON (files, props, contract): https://brokui.dev/r/open/table-handle.json

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

API

manifest knowledge + registry-derived coverage

Props

Props accepted by this component: name, type, default value and description.
Prop Type Default Description
rows int 3 Initial row count used before the ResizeObserver measures the real table.
cols int 3 Initial column count used before the ResizeObserver measures the real table.

Slots

  • default —
  • x-ui.editor.table-handle — Installed subcomponent from the registry item.

Data slots

Stable hooks for CSS overrides and browser tests.

table-handle table-handle-col table-handle-grid table-handle-row

Behavior

  • Grip positions are measured live from the wrapped table's real cells with a ResizeObserver, so each grip stays aligned with its column or row as the table resizes.
  • Every insert or delete action is applied to the DOM and also announced as a bubbling table-action event, so a host document model can persist the change or call preventDefault() to apply it itself.
  • 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

Rich authoring and editing

Create or revise structured rich content.

Use when

  • Use when users need rich structured authoring, annotation, or collaborative editing controls.
  • Adding row and column grips over a table inside <x-ui.editor> so a reader can insert or delete rows and columns without a separate toolbar.

Avoid when

  • Do not use rich editor affordances for simple one-line or plain-text tasks.
  • The table is not editable content; a static table needs no grips.

Use instead

  • Textarea or plain field for simple content

Anti-patterns

  • Rich editors for one-line or easily validated input
Anatomy
root
Theming hooks
table-handle table-handle-col table-handle-grid table-handle-row

Accessibility

WCAG 2.2 AA Keyboard focus-visible RTL-ready Localized labels Dark mode
Keyboard
native
Focus
native
  • Every grip and menu control uses @mousedown.prevent so clicking a handle never drops the editor's contenteditable selection.
  • 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:ignore

Add wire:ignore to the component root because its behavior owns rendered DOM.

livewire-component.blade.php Blade
<div wire:ignore>
    <div class="w-full flex justify-center p-6">
        <x-ui.editor.table-handle :rows="3" :cols="3" />
    </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:table-handle
        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/editor/table-handle.blade.php Blade
@props([
    'rows' => 3,
    'cols' => 3,
])

{{--
    Table Handle — row and column handles over a table inside an <x-ui.editor>.
    The handles are measured from the real cells (a ResizeObserver keeps them in
    step), so each grip sits exactly over its column or beside its row: a bar
    above the table per column, a bar on the start side per row, and a corner
    dot that selects the whole table. Hovering a grip tints its column / row;
    clicking opens an <x-ui.dropdown> with insert / delete actions.

    The actions are applied to the wrapped table by `uiTableHandle` (rows and
    columns are inserted or removed in the DOM) and announced with a bubbling
    `table-action` event so a host document model can persist the change:
      { action: 'insert-col-before' | 'insert-col-after' | 'delete-col'
              | 'insert-row-above'  | 'insert-row-below'  | 'delete-row'
              | 'select-all',
        index: <zero-based axis index> }
    Call preventDefault() on the event to apply the change yourself instead.

    @mousedown.prevent on every control keeps the contenteditable selection from
    being dropped when a handle is clicked.
--}}
<div
    x-data="uiTableHandle()"
    data-slot="table-handle"
    {{ $attributes->merge(['class' => 'group/table relative inline-block max-w-full pt-4 ps-4 pe-5 pb-5']) }}
>
    {{-- ── Column grips (above the table), one per measured column ─────────── --}}
    <div data-slot="table-handle-col" class="absolute inset-x-0 top-0 h-4 ps-4" role="presentation">
        <button
            type="button"
            aria-label="{{ __('Add column') }}"
            @mousedown.prevent=""
            @click="act('insert-col-after', cols.length - 1)"
            class="absolute top-0 flex size-4 items-center justify-center rounded-sm text-muted-foreground opacity-0 transition-opacity duration-150 group-hover/table:opacity-100 group-focus-within/table:opacity-100 hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-[length:var(--ring-width)] focus-visible:ring-ring motion-reduce:transition-none"
            :style="cols.length ? `inset-inline-start:${cols[cols.length - 1].start + cols[cols.length - 1].size + 16 + 2}px` : ''"
        >
            <svg class="size-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>
        </button>
        <template x-for="(col, c) in cols" :key="c">
            <div class="absolute top-0 h-4" :style="`inset-inline-start:${col.start + 16}px; width:${col.size}px`">
                <x-ui.dropdown class="block h-full w-full">
                    <x-ui.dropdown.trigger
                        type="button"
                        ::aria-label="`{{ __('Column') }} ${c + 1}`"
                        @mousedown.prevent=""
                        @mouseenter="setActive('col', c)"
                        @mouseleave="clearActive()"
                        class="group/grip flex h-full w-full items-center justify-center rounded-sm focus-visible:outline-none focus-visible:ring-[length:var(--ring-width)] focus-visible:ring-ring"
                    >
                        <span class="h-1 w-6 rounded-full bg-border opacity-0 transition-[opacity,background-color,width] duration-150 group-hover/table:opacity-100 group-focus-within/table:opacity-100 group-hover/grip:w-8 group-hover/grip:bg-primary group-aria-expanded/grip:w-8 group-aria-expanded/grip:bg-primary group-aria-expanded/grip:opacity-100 motion-reduce:transition-none"></span>
                    </x-ui.dropdown.trigger>
                    <x-ui.dropdown.content align="start">
                        <x-ui.dropdown.item type="button" @mousedown.prevent="" @click="act('insert-col-before', c)">
                            <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="14" y="3" width="7" height="18" rx="1"/><path d="M7 8v8M3 12h8"/></svg>
                            {{ __('Insert column before') }}
                        </x-ui.dropdown.item>
                        <x-ui.dropdown.item type="button" @mousedown.prevent="" @click="act('insert-col-after', c)">
                            <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="7" height="18" rx="1"/><path d="M17 8v8M13 12h8"/></svg>
                            {{ __('Insert column after') }}
                        </x-ui.dropdown.item>
                        <x-ui.dropdown.separator />
                        <x-ui.dropdown.item type="button" @mousedown.prevent="" @click="act('delete-col', c)" class="text-destructive focus:bg-destructive/10 focus:text-destructive hover:bg-destructive/10 hover:text-destructive">
                            <svg class="size-4 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>
                            {{ __('Delete column') }}
                        </x-ui.dropdown.item>
                    </x-ui.dropdown.content>
                </x-ui.dropdown>
            </div>
        </template>
    </div>

    {{-- ── Row grips (start side), one per measured row ─────────────────────── --}}
    <div data-slot="table-handle-row" class="absolute inset-y-0 start-0 w-4 pt-4" role="presentation">
        {{-- Corner: select the whole table --}}
        <button
            type="button"
            aria-label="{{ __('Select whole table') }}"
            @mousedown.prevent=""
            @click="act('select-all', -1)"
            class="absolute start-0 top-0 flex size-4 items-center justify-center rounded-sm focus-visible:outline-none focus-visible:ring-[length:var(--ring-width)] focus-visible:ring-ring"
        >
            <span class="size-2 rounded-full bg-border opacity-0 transition-[opacity,background-color] duration-150 group-hover/table:opacity-100 group-focus-within/table:opacity-100 hover:bg-primary motion-reduce:transition-none"></span>
        </button>

        {{-- Append a row: a plus under the last row grip. --}}
        <button
            type="button"
            aria-label="{{ __('Add row') }}"
            @mousedown.prevent=""
            @click="act('insert-row-below', rows.length - 1)"
            class="absolute start-0 flex size-4 items-center justify-center rounded-sm text-muted-foreground opacity-0 transition-opacity duration-150 group-hover/table:opacity-100 group-focus-within/table:opacity-100 hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-[length:var(--ring-width)] focus-visible:ring-ring motion-reduce:transition-none"
            :style="rows.length ? `top:${rows[rows.length - 1].start + rows[rows.length - 1].size + 16 + 2}px` : ''"
        >
            <svg class="size-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>
        </button>

        <template x-for="(row, r) in rows" :key="r">
            <div class="absolute start-0 w-4" :style="`top:${row.start + 16}px; height:${row.size}px`">
                <x-ui.dropdown class="block h-full w-full">
                    <x-ui.dropdown.trigger
                        type="button"
                        ::aria-label="`{{ __('Row') }} ${r + 1}`"
                        @mousedown.prevent=""
                        @mouseenter="setActive('row', r)"
                        @mouseleave="clearActive()"
                        class="group/grip flex h-full w-full items-center justify-center rounded-sm focus-visible:outline-none focus-visible:ring-[length:var(--ring-width)] focus-visible:ring-ring"
                    >
                        <span class="h-6 w-1 rounded-full bg-border opacity-0 transition-[opacity,background-color,height] duration-150 group-hover/table:opacity-100 group-focus-within/table:opacity-100 group-hover/grip:h-8 group-hover/grip:bg-primary group-aria-expanded/grip:h-8 group-aria-expanded/grip:bg-primary group-aria-expanded/grip:opacity-100 motion-reduce:transition-none"></span>
                    </x-ui.dropdown.trigger>
                    <x-ui.dropdown.content align="start">
                        <x-ui.dropdown.item type="button" @mousedown.prevent="" @click="act('insert-row-above', r)">
                            <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="14" width="18" height="7" rx="1"/><path d="M8 7h8M12 3v8"/></svg>
                            {{ __('Insert row above') }}
                        </x-ui.dropdown.item>
                        <x-ui.dropdown.item type="button" @mousedown.prevent="" @click="act('insert-row-below', r)">
                            <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="7" rx="1"/><path d="M8 17h8M12 13v8"/></svg>
                            {{ __('Insert row below') }}
                        </x-ui.dropdown.item>
                        <x-ui.dropdown.separator />
                        <x-ui.dropdown.item type="button" @mousedown.prevent="" @click="act('delete-row', r)" class="text-destructive focus:bg-destructive/10 focus:text-destructive hover:bg-destructive/10 hover:text-destructive">
                            <svg class="size-4 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>
                            {{ __('Delete row') }}
                        </x-ui.dropdown.item>
                    </x-ui.dropdown.content>
                </x-ui.dropdown>
            </div>
        </template>
    </div>

    {{-- ── Hover tint over the active column / row ─────────────────────────── --}}
    <div
        x-show="activeAxis !== null"
        x-cloak
        aria-hidden="true"
        class="pointer-events-none absolute z-10 rounded-sm bg-primary/10 ring-1 ring-inset ring-primary/40"
        :style="activeStyle()"
    ></div>

    {{-- ── The table ───────────────────────────────────────────────────────── --}}
    <div x-ref="wrap" class="min-w-0 overflow-x-auto rounded-md border border-border">
        @if (trim($slot) !== '')
            {{ $slot }}
        @else
            <table class="w-full border-collapse text-start" data-slot="table-handle-grid">
                <thead>
                    <tr>
                        @for ($c = 0; $c < (int) $cols; $c++)
                            <th class="border-b border-e border-border bg-muted px-3 py-2 text-start text-sm font-medium text-muted-foreground last:border-e-0">
                                {{ __('Column :n', ['n' => $c + 1]) }}
                            </th>
                        @endfor
                    </tr>
                </thead>
                <tbody>
                    @for ($r = 0; $r < (int) $rows; $r++)
                        <tr>
                            @for ($c = 0; $c < (int) $cols; $c++)
                                <td class="border-b border-e border-border px-3 py-2 text-sm last:border-e-0 [tr:last-child_&]:border-b-0">
                                    {{ __('Cell') }} {{ $r + 1 }}.{{ $c + 1 }}
                                </td>
                            @endfor
                        </tr>
                    @endfor
                </tbody>
            </table>
        @endif
    </div>
</div>
resources/views/components/ui/table-handle.blade.php Blade
{{-- <x-ui.table-handle> is the install slug's compatibility tag: the part lives at
     <x-ui.editor.table-handle> (ui/editor/table-handle) with every other editor part.
     Compose the namespaced tag in new code; this file only forwards to it. --}}
@props([
    'rows' => 3,
    'cols' => 3,
])

<x-ui.editor.table-handle :rows="$rows" :cols="$cols" {{ $attributes }}>
    {{ $slot }}
</x-ui.editor.table-handle>
resources/js/ui/table-handle.js JS
/**
 * Table Handle — row/column handles measured from a real table.
 *
 * On init (and whenever the table resizes) the first row's cells and every row
 * are measured, giving `cols` / `rows` as { start, size } px offsets relative
 * to the table wrapper; the Blade positions one grip per entry so the handles
 * always line up with the cells, whatever their widths.
 *
 * `act(action, index)` dispatches a cancellable, bubbling `table-action` event
 * ({ action, index }) and — unless a host called preventDefault() — applies the
 * change to the wrapped table itself (insert / delete a row or column, select
 * the whole table), then re-measures.
 *
 * The ResizeObserver is disconnected in destroy().
 */
document.addEventListener('alpine:init', () => {
    window.Alpine.data('uiTableHandle', () => ({
        cols: [],
        rows: [],
        // 'col' | 'row' | null — which axis is currently hovered.
        activeAxis: null,
        activeIndex: null,
        _ro: null,

        init() {
            this.$nextTick(() => this.measure());
            if ('ResizeObserver' in window) {
                this._ro = new ResizeObserver(() => this.measure());
                const table = this.table();
                if (table) this._ro.observe(table);
            }
        },

        destroy() {
            this._ro?.disconnect();
            this._ro = null;
            this.clearActive();
        },

        table() {
            return this.$refs.wrap?.querySelector('table') ?? null;
        },

        measure() {
            const table = this.table();
            const wrap = this.$refs.wrap;
            if (!table || !wrap) return;
            const base = wrap.getBoundingClientRect();
            const firstRow = table.rows[0];
            this.cols = firstRow
                ? [...firstRow.cells].map((cell) => {
                      const r = cell.getBoundingClientRect();
                      return { start: r.left - base.left, size: r.width };
                  })
                : [];
            this.rows = [...table.rows].map((row) => {
                const r = row.getBoundingClientRect();
                return { start: r.top - base.top, size: r.height };
            });
        },

        setActive(axis, index) {
            this.activeAxis = axis;
            this.activeIndex = index;
        },

        clearActive() {
            this.activeAxis = null;
            this.activeIndex = null;
        },

        isActive(axis, index) {
            return this.activeAxis === axis && this.activeIndex === index;
        },

        // The tint box over the hovered column / row (offsets include the 16px
        // handle gutters on the top and start sides).
        activeStyle() {
            const wrap = this.$refs.wrap;
            if (!wrap || this.activeAxis === null) return '';
            const height = wrap.clientHeight;
            const width = wrap.clientWidth;
            if (this.activeAxis === 'col') {
                const c = this.cols[this.activeIndex];
                return c ? `top:16px; height:${height}px; inset-inline-start:${c.start + 16}px; width:${c.size}px` : '';
            }
            const r = this.rows[this.activeIndex];
            return r ? `inset-inline-start:16px; width:${width}px; top:${r.start + 16}px; height:${r.size}px` : '';
        },

        act(action, index) {
            const event = new CustomEvent('table-action', { detail: { action, index }, bubbles: true, cancelable: true });
            const proceed = this.$el.dispatchEvent(event);
            if (proceed) this.apply(action, index);
        },

        // Apply the action to the wrapped table: new cells copy the tag and
        // classes of their neighbour so a header row stays a header row.
        apply(action, index) {
            const table = this.table();
            if (!table) return;
            const rows = [...table.rows];
            const blank = (like) => {
                const cell = document.createElement(like?.tagName === 'TH' ? 'th' : 'td');
                cell.className = like?.className ?? '';
                cell.innerHTML = '<br>';
                return cell;
            };
            switch (action) {
                case 'insert-col-before':
                case 'insert-col-after':
                    rows.forEach((row) => {
                        const ref = row.cells[index];
                        if (!ref) return;
                        const cell = blank(ref);
                        action === 'insert-col-before' ? ref.before(cell) : ref.after(cell);
                    });
                    break;
                case 'delete-col':
                    if ((rows[0]?.cells.length ?? 0) <= 1) return;
                    rows.forEach((row) => row.cells[index]?.remove());
                    break;
                case 'insert-row-above':
                case 'insert-row-below': {
                    const ref = rows[index];
                    if (!ref) return;
                    const row = document.createElement('tr');
                    [...ref.cells].forEach((c) => row.appendChild(blank(action === 'insert-row-above' && index === 0 && c.tagName === 'TH' ? { tagName: 'TD', className: rows[1]?.cells[0]?.className ?? c.className } : c)));
                    action === 'insert-row-above' ? ref.before(row) : ref.after(row);
                    break;
                }
                case 'delete-row':
                    if (rows.length <= 1) return;
                    rows[index]?.remove();
                    break;
                case 'select-all': {
                    const range = document.createRange();
                    range.selectNodeContents(table);
                    const sel = window.getSelection();
                    sel.removeAllRanges();
                    sel.addRange(range);
                    break;
                }
                default:
                    return;
            }
            this.clearActive();
            this.$nextTick(() => this.measure());
        },
    }));
});

Ownership & lifecycle

Owner, release state, review evidence and adoption for this item.
Owner
Platform UI (@JoshJML)
Current version
1.3.2
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