Data

Data grid.

Keyboard cell ranges, typed editing and a clear review before saving.

LIVE PREVIEWTry it. It works.

Install the source

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/data-grid.json

Registry setup · Examples · API and behavior · Open the playground

COMPLETE EXAMPLES

Use it in context.

Each example includes its imports, data and state. The preview runs that same source. Include the stylesheet once in your application.

Edit a bounded local page

The host applies reported edits to local rows; no automatic server writes occur.

Loads this example when you need it.

Keyboard

  • Arrow keys move between cells; Shift extends a range.
  • Enter edits a title; Escape cancels.

States covered

  • Read-only identity
  • Editable title
  • Local draft

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-basic-data-grid.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import {useState} from 'react';
import {DataGrid,type DataColumn} from '@bld8/ui';
import '@bld8/ui/styles.css';
type Row={id:string;revision:number;title:string};
const columns:DataColumn<Row>[]=[{key:'id',label:'ID',type:'text'},{key:'title',label:'Title',type:'text',editable:true}];
export default function GridExample(){const [rows,setRows]=useState<Row[]>([{id:'EX-1',revision:1,title:'Review keyboard focus'},{id:'EX-2',revision:1,title:'Check field feedback'}]);return <div><p>Edits update this local page only.</p><DataGrid label="Example issue draft" rows={rows} columns={columns} onEdit={edits=>setRows(current=>current.map(row=>{const edit=edits.find(item=>item.id===row.id&&item.key==='title');return edit?{...row,title:String(edit.value)}:row;}))}/></div>;}

A portable column layout

Order, visibility, pinning, widths and density share one presentation object. Editing remains a local draft.

Keyboard

  • Use Columns to show, hide, pin and reorder fields without dragging.
  • Tab to a column resize separator. Left and Right adjust by 10 pixels; Home uses the minimum and End uses the maximum.
  • Arrow keys move between visible cells. Shift extends a range; Enter edits and Escape cancels.
  • Pinned start and end follow the reading direction, including right-to-left layouts.

States covered

  • controlled view
  • column order
  • column visibility
  • logical pinning
  • pointer resize
  • keyboard resize
  • density
  • right-to-left layout
  • local draft editing

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-data-grid-column-layout.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import { useState } from 'react';
import { Button, DataGrid, createDataGridViewState, type DataColumn, type DataEdit, type DataGridViewState } from '@bld8/ui';

type RecordRow = { id: string; revision: number; title: string; status: string; owner: string; estimate: number };
const columns: DataColumn<RecordRow>[] = [
  { key: 'id', label: 'Record', type: 'text', hideable: false, pinned: 'start', width: 112, minWidth: 100, sortable: false },
  { key: 'title', label: 'Summary', type: 'text', editable: true, minWidth: 180 },
  { key: 'status', label: 'Stage', type: 'select', editable: true, minWidth: 140, options: [ { value: 'draft', label: 'Draft' }, { value: 'review', label: 'Review' }, { value: 'ready', label: 'Ready' } ] },
  { key: 'owner', label: 'Coordinator', type: 'text', editable: true, minWidth: 140 },
  { key: 'estimate', label: 'Points', type: 'number', editable: true, width: 100, minWidth: 88, pinned: 'end' }
];
const initialRows: RecordRow[] = [
  { id: 'REC-21', revision: 1, title: 'Review empty-state wording', status: 'review', owner: 'Remy Cole', estimate: 3 },
  { id: 'REC-22', revision: 1, title: 'Align the schedule toolbar', status: 'draft', owner: 'Imani Bell', estimate: 5 },
  { id: 'REC-23', revision: 1, title: 'Check keyboard return focus', status: 'ready', owner: 'Remy Cole', estimate: 2 }
];
export default function PortableGridLayoutExample() {
  const [rows, setRows] = useState(initialRows);
  const [view, setView] = useState<DataGridViewState>(() => createDataGridViewState(columns));
  const [rtl, setRtl] = useState(false);
  function edit(edits: DataEdit<RecordRow>[]) {
    setRows(current => current.map(row => edits.filter(change => change.id === row.id).reduce((next, change) => {
      if (change.key === 'estimate') { const value = Number(change.value); return Number.isFinite(value) ? { ...next, estimate: value } : next; }
      if (change.key === 'title' || change.key === 'status' || change.key === 'owner') return { ...next, [change.key]: String(change.value) };
      return next;
    }, row)));
  }
  return <div style={{ display: 'grid', gap: 16, minWidth: 0 }}>
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
      <Button variant="secondary" size="sm" onClick={() => setRtl(current => !current)}>{rtl ? 'Use left-to-right layout' : 'Use right-to-left layout'}</Button>
      <Button variant="secondary" size="sm" onClick={() => setView(current => ({ ...current, visibleColumnKeys: current.visibleColumnKeys.includes('status') ? current.visibleColumnKeys.filter(key => key !== 'status') : [...current.visibleColumnKeys, 'status'] }))}>Toggle stage column</Button>
      <Button variant="ghost" size="sm" onClick={() => setView(createDataGridViewState(columns))}>Restore starting layout</Button>
    </div>
    <div dir={rtl ? 'rtl' : 'ltr'} style={{ minWidth: 0 }}>
      <DataGrid label="Portable record layout" rows={rows} columns={columns} onEdit={edit} view={view} onViewChange={setView} layoutControls resizableColumns />
    </div>
    <output aria-label="Visible column keys" style={{ overflowWrap: 'anywhere' }}>{view.columnOrderKeys.filter(key => view.visibleColumnKeys.includes(key)).join(', ')}</output>
    <output aria-label="Current grid density">{view.density}</output>
    <p className="bui-hint">These edits stay in this example. A host application validates drafts and saves them separately from the view.</p>
  </div>;
}

Multi-sort without modifier keys

Add, replace, reorder and remove sort rules with the same controls on touch and keyboard. The host applies the query.

Keyboard

  • Open Sort and use Add sort to create a rule. New rules receive focus.
  • Choose a column and direction, then use Raise or Lower sort priority to change precedence.
  • Remove sort returns focus to the remaining rule, or Add sort when none remain.
  • Column headings still support Shift-select as a shortcut.

States covered

  • controlled multi-sort
  • touch sort editor
  • keyboard priorities
  • host sorting
  • non-sortable identity
  • uncontrolled compact view

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-data-grid-priority-sorting.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import { useState } from 'react';
import { Button, DataGrid, createDataGridViewState, type DataColumn, type DataSort } from '@bld8/ui';

type Release = { id: string; revision: number; title: string; phase: string; priority: number };
const columns: DataColumn<Release>[] = [
  { key: 'id', label: 'Release', type: 'text', sortable: false, hideable: false, minWidth: 104, width: 104 },
  { key: 'title', label: 'Release summary', type: 'text', minWidth: 210 },
  { key: 'phase', label: 'Release phase', type: 'text', minWidth: 150 },
  { key: 'priority', label: 'Release priority', type: 'number', minWidth: 140 }
];
const rows: Release[] = [
  { id: 'REL-1', revision: 1, title: 'Calendar keyboard checks', phase: 'Review', priority: 2 },
  { id: 'REL-2', revision: 1, title: 'Upload retry messages', phase: 'Draft', priority: 3 },
  { id: 'REL-3', revision: 1, title: 'Chart legend contrast', phase: 'Review', priority: 3 },
  { id: 'REL-4', revision: 1, title: 'Toolbar spacing', phase: 'Ready', priority: 1 }
];
const compactView = { ...createDataGridViewState(columns), density: 'compact' as const };
export default function OrderedGridSortExample() {
  const [sorts, setSorts] = useState<DataSort[]>([{ key: 'priority', descending: true }, { key: 'title', descending: false }]);
  const orderedRows = [...rows].sort((left, right) => {
    for (const sort of sorts) {
      const a = left[sort.key as keyof Release], b = right[sort.key as keyof Release];
      const result = typeof a === 'number' && typeof b === 'number' ? a - b : String(a).localeCompare(String(b));
      if (result) return sort.descending ? -result : result;
    }
    return 0;
  });
  return <div style={{ display: 'grid', gap: 16, minWidth: 0 }}>
    <DataGrid label="Sorted release queue" rows={orderedRows} columns={columns} sorts={sorts} onSortsChange={setSorts} defaultView={compactView} />
    <div><Button variant="ghost" size="sm" onClick={() => setSorts([])}>Reset example sorting</Button></div>
    <output aria-label="Active sort rules" style={{ overflowWrap: 'anywhere' }}>{sorts.length ? sorts.map((sort, index) => (index + 1) + '. ' + sort.key + ' ' + (sort.descending ? 'descending' : 'ascending')).join('; ') : 'No sorting'}</output>
  </div>;
}

Dates, approval and people in one draft

Date-only values, native checkbox edits and multiple assignees share validation, history and one host-owned save boundary.

Keyboard

  • Enter or F2 opens a cell. Dates and assignees keep a local buffer until Apply changes.
  • In an approval cell, Space toggles the checkbox; Enter or Tab commits and Escape cancels.
  • Escape dismisses an inner calendar or option list first. Cancel or Escape from the editor discards its buffer.
  • Copy and paste use canonical date strings, true/false and JSON arrays of option IDs, not display names.

States covered

  • date editor
  • boolean editor
  • multiple assignees
  • local buffers
  • undo and redo
  • canonical clipboard
  • atomic local save
  • revision conflict

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-grid-editor-mixed.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import { useState } from 'react';
import { Button, DataGrid, UIProvider, dataValuesEqual, parseDataValue, validateDataChanges, type DataCellError, type DataColumn, type DataChange, type DataEdit } from '@bld8/ui';

type Delivery = { id: string; revision: number; title: string; due: string; approved: boolean; assignees: string[] };
const people = [
  { value: 'maya', label: 'Maya Chen', description: 'Interface systems' },
  { value: 'oliver', label: 'Oliver Reed', description: 'Frontend platform' },
  { value: 'sam', label: 'Sam Rivera', description: 'Accessibility' },
  { value: 'retired', label: 'Former contributor', disabled: true }
];
const columns: DataColumn<Delivery>[] = [
  { key: 'id', label: 'Record', type: 'text', hideable: false, width: 104, minWidth: 104 },
  { key: 'title', label: 'Delivery title', type: 'text', editable: true, required: true, maxLength: 100, minWidth: 220 },
  { key: 'due', label: 'Due date', type: 'date', editable: true, minDate: '2026-01-01', maxDate: '2027-12-31', width: 170 },
  { key: 'approved', label: 'Approved', type: 'boolean', editable: true, width: 128 },
  { key: 'assignees', label: 'Assignees', type: 'multi-select', editable: true, required: true, maxSelections: 3, options: people, minWidth: 260 }
];
const initial: Delivery[] = [
  { id: 'REC-1', revision: 1, title: 'Keyboard focus review', due: '2026-11-20', approved: false, assignees: ['maya'] },
  { id: 'REC-2', revision: 1, title: 'Responsive field spacing', due: '', approved: true, assignees: ['oliver', 'sam'] }
];
const clone = (rows: Delivery[]) => rows.map(row => ({ ...row, assignees: [...row.assignees] }));
export default function DeliveryEditorExample() {
  const [saved, setSaved] = useState(() => clone(initial)), [rows, setRows] = useState(() => clone(initial));
  const [past, setPast] = useState<Delivery[][]>([]), [future, setFuture] = useState<Delivery[][]>([]);
  const [errors, setErrors] = useState<DataCellError[]>([]), [message, setMessage] = useState('Changes stay in this example.');
  const changes: DataChange<Delivery>[] = rows.flatMap(row => {
    const base = saved.find(item => item.id === row.id)!;
    const values: Partial<Omit<Delivery, 'id' | 'revision'>> = {};
    for (const column of columns.filter(column => column.editable)) if (!dataValuesEqual(row[column.key], base[column.key])) Object.assign(values, { [column.key]: row[column.key] });
    return Object.keys(values).length ? [{ id: row.id, expectedRevision: row.revision, values }] : [];
  });
  function edit(edits: DataEdit<Delivery>[]) {
    const next = clone(rows), invalid: DataCellError[] = [];
    for (const edit of edits) {
      const row = next.find(row => row.id === edit.id), column = columns.find(column => column.key === edit.key);
      if (!row || !column) { invalid.push({ id: edit.id, key: edit.key, message: 'Choose a loaded editable field.' }); continue; }
      const parsed = parseDataValue(column, edit.value);
      if (parsed.error) invalid.push({ id: edit.id, key: edit.key, message: parsed.error }); else Object.assign(row, { [edit.key]: parsed.value });
    }
    setErrors(invalid); if (invalid.length) { setMessage('The whole edit was kept out of the draft. Correct its values and retry.'); return; }
    if (next.every((row, index) => columns.every(column => dataValuesEqual(row[column.key], rows[index][column.key])))) return;
    setPast(current => [...current.slice(-49), clone(rows)]); setFuture([]); setRows(next); setMessage('Draft updated. Review before saving.');
  }
  function undo() { const previous = past.at(-1); if (!previous) return; setFuture(current => [clone(rows), ...current]); setRows(clone(previous)); setPast(current => current.slice(0, -1)); setErrors([]); }
  function redo() { const next = future[0]; if (!next) return; setPast(current => [...current, clone(rows)]); setRows(clone(next)); setFuture(current => current.slice(1)); setErrors([]); }
  function save() {
    const invalid = validateDataChanges(saved, columns, changes); setErrors(invalid); if (invalid.length) { setMessage('Correct the draft before saving.'); return; }
    if (changes.some(change => saved.find(row => row.id === change.id)?.revision !== change.expectedRevision)) { setMessage('A revision changed. Restore the saved records before retrying; nothing was saved.'); return; }
    const next = clone(rows).map(row => changes.some(change => change.id === row.id) ? { ...row, revision: row.revision + 1 } : row);
    setSaved(clone(next)); setRows(next); setPast([]); setFuture([]); setMessage('Saved together in this local example.');
  }
  const dirty = changes.flatMap(change => Object.keys(change.values).map(key => ({ id: change.id, key })));
  return <UIProvider><div style={{ display: 'grid', gap: 16, minWidth: 0 }}>
    <DataGrid label="Delivery editor grid" rows={rows} columns={columns} onEdit={edit} cellErrors={errors} dirtyCells={dirty} onUndo={undo} onRedo={redo} canUndo={!!past.length} canRedo={!!future.length} layoutControls resizableColumns />
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      <Button size="sm" disabled={!changes.length} onClick={save}>Save delivery draft</Button>
      <Button size="sm" variant="secondary" onClick={() => { setRows(clone(saved)); setPast([]); setFuture([]); setErrors([]); setMessage('Restored the saved records.'); }}>Restore saved records</Button>
      <Button size="sm" variant="ghost" onClick={() => { setSaved(current => current.map((row, index) => index === 0 ? { ...row, revision: row.revision + 1 } : row)); setMessage('A local external revision was simulated. Save will reject stale changes atomically.'); }}>Simulate external revision</Button>
    </div>
    <p role="status" className="bui-hint">{message}</p>
    <output aria-label="Delivery canonical values" style={{ fontSize: 12, overflowWrap: 'anywhere' }}>{JSON.stringify(rows.map(({ id, due, approved, assignees }) => ({ id, due, approved, assignees })))}</output>
    <p className="bui-hint">This example keeps records in memory. Your application owns authentication, durable storage, revision checks and atomic writes.</p>
  </div></UIProvider>;
}

A hierarchical custom cell editor

Compose TreeSelect through the public render hooks. A custom popup keeps canonical leaf IDs and the same validation, focus and dismissal boundary.

Keyboard

  • Enter opens the custom team editor. Search or expand the tree and choose loaded leaf teams.
  • TreeSelect handles its own keyboard navigation; Tab reaches Apply teams and Cancel.
  • Apply teams validates canonical leaf IDs, finishes the exit motion and returns focus to the cell.
  • Escape or outside dismissal discards only the temporary editor value; outside focus is preserved.

States covered

  • custom cell display
  • custom editor hooks
  • TreeSelect composition
  • canonical leaf IDs
  • typed context
  • exit motion
  • validation
  • outside focus

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-grid-editor-custom.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import { useRef, useState } from 'react';
import { Popover } from '@base-ui/react/popover';
import { Button, DataGrid, TreeSelect, UIProvider, parseDataValue, type DataColumn, type DataEdit, type DataGridEditorContext, type TreeSelectNode } from '@bld8/ui';

type Ownership = { id: string; revision: number; title: string; teams: string[] };
const teams: TreeSelectNode[] = [
  { id: 'design', label: 'Design', children: [{ id: 'design-ui', label: 'Interface systems' }, { id: 'design-motion', label: 'Motion' }] },
  { id: 'platform', label: 'Platform', children: [{ id: 'platform-web', label: 'Web platform' }, { id: 'platform-a11y', label: 'Accessibility' }] }
];
const teamOptions = [{ value: 'design-ui', label: 'Interface systems' }, { value: 'design-motion', label: 'Motion' }, { value: 'platform-web', label: 'Web platform' }, { value: 'platform-a11y', label: 'Accessibility' }];
const columns: DataColumn<Ownership>[] = [
  { key: 'id', label: 'Record', type: 'text', width: 104, minWidth: 104 },
  { key: 'title', label: 'Ownership title', type: 'text', editable: true, required: true, minWidth: 220 },
  { key: 'teams', label: 'Teams', type: 'multi-select', editable: true, options: teamOptions, required: true, minWidth: 300 }
];
function TeamCellEditor({ context }: { context: DataGridEditorContext<Ownership> }) {
  const [open, setOpen] = useState(true), [error, setError] = useState('');
  const current = useRef(context); current.current = context;
  const pending = useRef<{ apply: boolean; value?: unknown; restore: boolean } | null>(null);
  function close(apply: boolean, restore = true) {
    if (pending.current) return;
    if (apply) { const parsed = parseDataValue(context.column, context.draftValue); if (parsed.error) { setError(parsed.error); return; } pending.current = { apply, value: parsed.value, restore }; }
    else pending.current = { apply, restore };
    setOpen(false);
  }
  return <Popover.Root open={open} onOpenChange={(next, details) => { if (!next) close(false, details.reason !== 'outside-press' && details.reason !== 'focus-out'); }} onOpenChangeComplete={next => {
    if (next || !pending.current) return;
    const action = pending.current; pending.current = null;
    if (action.apply) { if (!current.current.commit(action.value)) setOpen(true); } else current.current.cancel(action.restore);
  }}>
    <Popover.Trigger render={<Button variant="ghost" size="sm" aria-label={context.label}>Choose teams</Button>} />
    <Popover.Portal><Popover.Positioner className="bui-positioner" sideOffset={6} collisionPadding={12} align="start"><Popover.Popup {...context.portalProps} className="bui-popup" finalFocus={false} style={{ width: 'min(360px, calc(100vw - 24px))', maxHeight: 'calc(100dvh - 24px)', overflow: 'auto', display: 'grid', gap: 16, padding: 20 }}>
      <Popover.Title style={{ margin: 0, fontSize: 15 }}>Choose delivery teams</Popover.Title>
      <Popover.Description className="bui-hint" style={{ margin: 0 }}>Changes stay temporary until you apply this cell.</Popover.Description>
      <TreeSelect label={context.label} nodes={teams} value={Array.isArray(context.draftValue) ? context.draftValue.filter((value): value is string => typeof value === 'string') : []} onValueChange={value => { setError(''); context.onValueChange(value); }} inputRef={context.inputRef} popupDataAttributes={context.portalProps} density="compact" clearable disabled={context.disabled} error={error || context.error} />
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}><Button variant="ghost" size="sm" onClick={() => close(false)}>Cancel</Button><Button size="sm" onClick={() => close(true)}>Apply teams</Button></div>
    </Popover.Popup></Popover.Positioner></Popover.Portal>
  </Popover.Root>;
}
export default function CustomTeamEditorExample() {
  const [rows, setRows] = useState<Ownership[]>([{ id: 'OWN-1', revision: 1, title: 'Delivery checklist', teams: ['design-ui'] }, { id: 'OWN-2', revision: 1, title: 'Release handoff', teams: ['platform-web'] }]);
  const [message, setMessage] = useState('Edits stay in this local example.');
  function edit(edits: DataEdit<Ownership>[]) {
    const parsed = edits.map(edit => ({ ...edit, parsed: parseDataValue(columns.find(column => column.key === edit.key)!, edit.value) }));
    if (parsed.some(edit => edit.parsed.error)) { setMessage('No edits were applied: a value did not match its column.'); return; }
    setRows(current => current.map(row => parsed.filter(edit => edit.id === row.id).reduce((next, edit) => ({ ...next, [edit.key]: edit.parsed.value }), row))); setMessage('Canonical IDs applied to the local draft.');
  }
  return <UIProvider><div style={{ display: 'grid', gap: 16, minWidth: 0 }}>
    <DataGrid label="Custom team editor grid" rows={rows} columns={columns} onEdit={edit} renderCell={context => context.column.key === 'teams' ? <span className="bui-data-grid-tags">{context.row.teams.map(id => <span className="bui-data-grid-tag" key={id}>{teamOptions.find(option => option.value === id)?.label ?? id}</span>)}</span> : undefined} renderEditor={context => context.column.key === 'teams' ? <TeamCellEditor context={context} /> : undefined} />
    <Button variant="secondary" size="sm" onClick={() => setMessage('Outside action kept focus.')}>Outside editor action</Button>
    <p role="status" className="bui-hint">{message}</p><output aria-label="Custom team canonical values" style={{ fontSize: 12, overflowWrap: 'anywhere' }}>{JSON.stringify(rows.map(row => ({ id: row.id, teams: row.teams })))}</output>
    <p className="bui-hint">Custom editors render UI; the grid validates column values. The host still owns saved records and service writes.</p>
  </div></UIProvider>;
}

Edit ten thousand loaded records

A bounded row window retains the focused editor while the rest of the supplied data scrolls. Pages offer a sequential reading view.

Keyboard

  • Arrow keys and Control or Command+Home/End move through loaded records, including unmounted rows.
  • Enter edits; Escape cancels. Scrolling keeps the current editor mounted at its logical position.
  • Choose Pages for sequential reading. Finish an incomplete editor before switching views.
  • Clipboard and bulk operations still allow at most 100 records and 2,000 cells.

States covered

  • 10000 loaded records
  • row virtualization
  • retained editor
  • logical pinning
  • bounded clipboard
  • paged reading
  • loaded summaries

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-data-grid-virtualized-10000.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import { useCallback, useRef, useState } from 'react';
import { AdvancedDataGrid, Button, parseDataValue, type DataColumn, type DataEdit, type DataGridHandle, type DataSummarySpec } from '@bld8/ui';

type RecordRow={id:string;revision:number;title:string;team:string;hours:number;ready:boolean};
const columns:DataColumn<RecordRow>[]=[
  {key:'id',label:'Record',type:'text',pinned:'start',width:132,hideable:false},
  {key:'title',label:'Title',type:'text',editable:true,width:260,maxLength:120},
  {key:'team',label:'Team',type:'select',editable:true,width:150,options:[{value:'product',label:'Product'},{value:'engineering',label:'Engineering'}]},
  {key:'hours',label:'Hours',type:'number',editable:true,min:0,max:100,width:112},
  {key:'ready',label:'Ready',type:'boolean',editable:true,width:112}
];
const initialRows:RecordRow[]=Array.from({length:10000},(_,index)=>({id:'BIG-'+String(index+1).padStart(5,'0'),revision:1,title:'Review item '+(index+1),team:index%2?'engineering':'product',hours:index%8+1,ready:index%3===0}));
const summaries:DataSummarySpec<RecordRow>[]=[{id:'records',label:'Loaded records',operation:'count'},{id:'hours',label:'Total hours',operation:'sum',key:'hours'},{id:'average',label:'Average hours',operation:'average',key:'hours'}];
export default function VirtualizedRecordsExample(){
  const [rows,setRows]=useState(initialRows),[notice,setNotice]=useState('');
  const navigation=useRef<DataGridHandle|null>(null);
  const edit=useCallback((edits:DataEdit<RecordRow>[])=>{
    const changes=new Map<string,Partial<RecordRow>>();
    for(const change of edits){const column=columns.find(column=>column.key===change.key);if(!column)return;const parsed=parseDataValue(column,change.value);if(parsed.error){setNotice(parsed.error);return;}changes.set(change.id,{...changes.get(change.id),[change.key]:parsed.value});}
    setRows(current=>current.map(row=>changes.has(row.id)?{...row,...changes.get(row.id)}:row));setNotice(edits.length+' cells changed locally. No service write was made.');
  },[]);
  return <div style={{minWidth:0}}>
    <Button size="sm" variant="secondary" onClick={()=>{if(!navigation.current?.focusCell('BIG-10000','title'))setNotice('Use Scroll and finish the current editor before jumping.');}}>Focus the last record</Button>
    <AdvancedDataGrid label="Ten thousand editable records" rows={rows} columns={columns} onEdit={edit} navigationRef={navigation} height={400} rowHeight={64} layoutControls resizableColumns bulkEditing summaries={summaries}/>
    <p className="bui-hint">10,000 authored records are already loaded. Only a row window and up to three focused/editor rows stay mounted. Columns remain bounded to 30; this is row virtualization, not an infinite service loader.</p>
    <p role="status">{notice}</p>
  </div>;
}

Load children and compare scoped totals

Explicit parent IDs, recoverable child loads and separate loaded versus full-match totals keep the scope clear.

Keyboard

  • Use the first column Right arrow to expand a parent; Left collapses it or returns to its parent. Reading direction reverses these keys.
  • Collapsed and unknown children are excluded from grid ranges. Draft values remain in controlled host records.
  • Retry a failed child load; source changes abort and ignore stale responses.
  • Open a record to expand its separate detail panel without changing fixed virtual row heights.

States covered

  • treegrid
  • lazy children
  • abortable retry
  • stable row IDs
  • controlled edits
  • expanded details
  • loaded totals
  • query-matched service totals

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-data-grid-hierarchy-summaries.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import { useCallback, useMemo, useRef, useState } from 'react';
import { AdvancedDataGrid, Button, Checkbox, parseDataValue, type DataColumn, type DataEdit, type DataGridTree, type DataSummarySpec } from '@bld8/ui';

type WorkRow={id:string;revision:number;parent:string;title:string;hours:number;more:boolean};
const roots:WorkRow[]=[{id:'P-A',revision:1,parent:'',title:'Interface review',hours:0,more:true},{id:'P-B',revision:1,parent:'',title:'Release checks',hours:0,more:true}];
const children:Record<string,WorkRow[]>={
  'P-A':[{id:'A-1',revision:1,parent:'P-A',title:'Keyboard review',hours:3,more:false},{id:'A-2',revision:1,parent:'P-A',title:'Spacing review',hours:5,more:false}],
  'P-B':[{id:'B-1',revision:1,parent:'P-B',title:'Archive interaction',hours:2,more:false},{id:'B-2',revision:1,parent:'P-B',title:'Saved view restore',hours:4,more:false}]
};
const columns:DataColumn<WorkRow>[]=[{key:'id',label:'Record',type:'text',pinned:'start',width:180,hideable:false},{key:'title',label:'Title',type:'text',editable:true,width:260,maxLength:120},{key:'hours',label:'Hours',type:'number',editable:true,min:0,max:100,width:112}];
const summaries:DataSummarySpec<WorkRow>[]=[{id:'count',label:'Visible records',operation:'count'},{id:'sum',label:'Hours',operation:'sum',key:'hours'},{id:'avg',label:'Hours per record',operation:'average',key:'hours'}];
const matching={queryKey:'all-work',recordCount:6,values:[{id:'count',value:6,count:6},{id:'sum',value:14,count:6},{id:'avg',value:14/6,count:6}]};
export default function HierarchicalRecordsExample(){
  const [rows,setRows]=useState(roots),[sourceKey,setSourceKey]=useState(0),[fail,setFail]=useState(false),[stale,setStale]=useState(false),[notice,setNotice]=useState(''),[ignore,setIgnore]=useState(false),[duplicates,setDuplicates]=useState(false),[acceptedParents,setAcceptedParents]=useState<string[]>([]);const failNext=useRef(false),ignoreNext=useRef(false),duplicateNext=useRef(false),pendingChildren=useRef<{parent:WorkRow;complete:(rows:WorkRow[])=>void}[]>([]);
  const loadChildren=useCallback(async(parent:WorkRow,{signal}:{signal:AbortSignal})=>{
    if(duplicateNext.current)return new Promise<WorkRow[]>((resolve,reject)=>{
      const entry={parent,complete:(rows:WorkRow[])=>{signal.removeEventListener('abort',stop);resolve(rows);}};
      function stop(){pendingChildren.current=pendingChildren.current.filter(item=>item!==entry);reject(new DOMException('Aborted','AbortError'));}
      if(signal.aborted){stop();return;}pendingChildren.current.push(entry);signal.addEventListener('abort',stop,{once:true});
    });
    const ignoreAbort=ignoreNext.current;ignoreNext.current=false;setIgnore(false);
    await new Promise<void>((resolve,reject)=>{const timer=setTimeout(done,ignoreAbort?350:120);function stop(){clearTimeout(timer);reject(new DOMException('Aborted','AbortError'));}function done(){signal.removeEventListener('abort',stop);resolve();}if(!ignoreAbort){if(signal.aborted){stop();return;}signal.addEventListener('abort',stop,{once:true});}});
    if(failNext.current){failNext.current=false;setFail(false);throw new Error('Example child load failed.');}return children[parent.id]??[];
  },[]);
  const onChildrenLoaded=useCallback((parent:WorkRow,loaded:readonly WorkRow[])=>{setAcceptedParents(current=>[...current,parent.id]);setRows(current=>{const next=new Map(current.map(row=>[row.id,row]));loaded.forEach(row=>next.set(row.id,row));return [...next.values()];});},[]);
  const tree=useMemo<DataGridTree<WorkRow>>(()=>({parentId:row=>row.parent||null,hasChildren:row=>row.more,loadChildren,onChildrenLoaded}),[loadChildren,onChildrenLoaded]);
  function edit(edits:DataEdit<WorkRow>[]){const values=new Map<string,Partial<WorkRow>>();for(const change of edits){const column=columns.find(column=>column.key===change.key);if(!column)return;const parsed=parseDataValue(column,change.value);if(parsed.error){setNotice(parsed.error);return;}values.set(change.id,{...values.get(change.id),[change.key]:parsed.value});}setRows(current=>current.map(row=>({...row,...values.get(row.id)})));setNotice('Changes stay in this local example.');}
  return <div style={{minWidth:0}}>
    <div style={{display:'flex',gap:12,flexWrap:'wrap',alignItems:'center'}}><Checkbox label="Fail next child load" checked={fail} onCheckedChange={value=>{failNext.current=value;setFail(value);}}/><Checkbox label="Show stale totals" checked={stale} onCheckedChange={setStale}/><Checkbox label="Ignore cancellation once" checked={ignore} onCheckedChange={value=>{ignoreNext.current=value;setIgnore(value);}}/><Checkbox label="Concurrent duplicate children" checked={duplicates} onCheckedChange={value=>{duplicateNext.current=value;setDuplicates(value);}}/><Button size="sm" variant="secondary" onClick={()=>{const pending=pendingChildren.current.splice(0);pending.forEach(entry=>entry.complete([{id:'SHARED',revision:1,parent:entry.parent.id,title:'Shared child of '+entry.parent.id,hours:1,more:false}]));}}>Release pending child loads</Button><Button size="sm" variant="secondary" onClick={()=>{setSourceKey(key=>key+1);setRows(roots);setAcceptedParents([]);}}>Reset tree source</Button></div>
    <output aria-label="Accepted child batches">{JSON.stringify(acceptedParents)}</output>
    <AdvancedDataGrid label="Project task hierarchy" rows={rows} columns={columns} tree={tree} sourceKey={sourceKey} onEdit={edit} height={360} layoutControls bulkEditing summaries={summaries} queryKey={stale?'another-query':'all-work'} allMatchingSummary={matching} renderDetails={row=><p>{row.title} · {row.hours} hours · saved revision {row.revision}.</p>}/>
    <p className="bui-hint">The duplicate-child mode deliberately releases two conflicting responses in the same event turn. Only a validated batch reaches the host callback; retry after disabling it. The full-match totals above are authored fixtures representing a service response. Parents have zero hours and are included in the record count. Real services must return totals for the exact applied query. Uploads, authentication and durable writes are separate host concerns.</p><p role="status">{notice}</p>
  </div>;
}

Inventory with reviewed batch saves

Use the same typed source controller for another domain: inventory quantities, dates, approval and multiple owners. Changes across pages stay in one draft until review.

Keyboard

  • Arrow keys move between grid cells. Enter opens the appropriate editor; Escape cancels it.
  • Open record edits the complete item, including multiple owners and approval.
  • Review changes opens one batch confirmation; Undo draft reverses the last draft operation.
  • Save current view stores view settings only. Share current view puts filters and layout in the URL, never draft values.

States covered

  • typed inventory schema
  • paged source
  • canonical dates and booleans
  • multiple owners
  • explicit batch review
  • host-owned saved views
  • safe share URL
  • one-step draft undo

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-resource-inventory-drafts.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import { useEffect, useState } from 'react';
import { ResourceWorkspace, createMemoryResourceDataSource, parseResourceWorkspaceView, serializeResourceWorkspaceView, resourceWorkspaceViewUrl, type ResourceFilterField, type ResourceWorkspaceView, type SavedResourceView } from '@bld8/blocks';
import { UIProvider, type DataColumn } from '@bld8/ui';

type Item = { id: string; revision: number; name: string; stock: number; restock: string; approved: boolean; owners: string[] };
const owners = [{ value: 'maya', label: 'Maya Chen' }, { value: 'sam', label: 'Sam Rivera' }, { value: 'oliver', label: 'Oliver Reed' }];
const columns: DataColumn<Item>[] = [
  { key: 'id', label: 'SKU', type: 'text', hideable: false, minWidth: 120 },
  { key: 'name', label: 'Product', type: 'text', editable: true, required: true, minLength: 3, minWidth: 230 },
  { key: 'stock', label: 'Stock', type: 'number', editable: true, min: 0, max: 10000 },
  { key: 'restock', label: 'Restock date', type: 'date', editable: true },
  { key: 'approved', label: 'Approved', type: 'boolean', editable: true },
  { key: 'owners', label: 'Owners', type: 'multi-select', editable: true, options: owners, maxSelections: 3, minWidth: 220 }
];
const fields: ResourceFilterField<Item>[] = [
  { id: 'name', label: 'Product', kind: 'text' }, { id: 'stock', label: 'Stock', kind: 'number' },
  { id: 'restock', label: 'Restock date', kind: 'date' },
  { id: 'approved', label: 'Approved', kind: 'select', options: [{ value: 'true', label: 'Approved' }, { value: 'false', label: 'Needs approval' }] }
];
const initial: Item[] = Array.from({ length: 16 }, (_, index) => ({ id: 'SKU-' + (101 + index), revision: 1, name: ['Studio headphones', 'Desk speakers', 'Portable display', 'USB microphone'][index % 4] + (index > 3 ? ' ' + (index + 1) : ''), stock: 12 + index * 3, restock: '2026-12-' + String(index + 1).padStart(2, '0'), approved: index % 2 === 0, owners: index % 3 ? ['sam'] : ['maya', 'oliver'] }));
export default function InventoryDraftsExample() {
  const [source] = useState(() => createMemoryResourceDataSource({ rows: initial, columns, fields, searchKeys: ['id', 'name'] }));
  const [views, setViews] = useState<SavedResourceView[]>([]), [restored, setRestored] = useState<{ view?: ResourceWorkspaceView } | null>(null);
  useEffect(() => {
    const query = new URL(window.location.href).searchParams.get('inventoryView');
    const view = query ? parseResourceWorkspaceView(query, columns, fields) ?? undefined : undefined;
    try { const saved = localStorage.getItem('inventory-example-view'); if (saved) { const parsed = parseResourceWorkspaceView(saved, columns, fields); if (parsed) setViews([{ id: 'saved', label: 'My inventory view', view: parsed }]); } } catch { /* Host storage can be unavailable. */ }
    setRestored({ view });
  }, []);
  if (!restored) return <p role="status">Preparing inventory view…</p>;
  return <UIProvider><ResourceWorkspace dataSource={source} columns={columns} fields={fields} defaultView={restored.view} savedViews={views}
    labels={{ label: 'Inventory workspace', title: 'Keep stock changes together.', searchLabel: 'Search inventory', searchPlaceholder: 'SKU or product…', gridLabel: 'Inventory data grid', recordName: 'Item', emptyTitle: 'No matching inventory.' }}
    onSaveView={view => { localStorage.setItem('inventory-example-view', serializeResourceWorkspaceView(view, columns, fields)); setViews([{ id: 'saved', label: 'My inventory view', view }]); }}
    onShareView={view => { const href = resourceWorkspaceViewUrl(window.location.href, view, columns, fields, 'inventoryView'); window.history.replaceState(null, '', href); }}
  /></UIProvider>;
}

Issue editing on the same resource controller

Keep the issue schema and existing HTTP boundary while sharing the resource draft, retry, conflict and undo lifecycle. This example uses the issue adapter in memory.

Keyboard

  • Use the search field and pagination to move between loaded issue pages. Drafts from other pages are kept.
  • Enter edits a grid cell; Open record opens the issue inspector.
  • Review changes and Save confirm the whole batch. Keep editing returns without writing.

States covered

  • existing issue adapter
  • shared generic controller
  • stable issue wrapper
  • draft undo
  • review before write
  • typed filter schema

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-resource-issues-shared-controller.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import { useState } from 'react';
import { ResourceWorkspace, createMemoryIssueDataSource, issueDataColumns, issueFields, type Issue, type ResourceFilterField } from '@bld8/blocks';
import { UIProvider } from '@bld8/ui';
export default function ResourceIssuesExample() {
  const [source] = useState(() => createMemoryIssueDataSource());
  return <UIProvider><ResourceWorkspace dataSource={source} columns={issueDataColumns} fields={issueFields as readonly ResourceFilterField<Issue>[]}
    labels={{ label: 'Shared issue workspace', gridLabel: 'Shared issue grid', recordName: 'Issue', searchLabel: 'Search issues', title: 'One review for the issue draft.' }}
  /></UIProvider>;
}

Fill a range in one draft transaction

Fill down by column or apply the active value to a selection. Every destination validates first; read-only columns stay unchanged and one Undo reverses the batch.

Keyboard

  • Select a cell and use Shift+arrows to extend a loaded range. Escape collapses it.
  • Control or Command+D fills down from the top selected row; Control or Command+Enter applies the active value.
  • The toolbar provides the same actions without modifier keys. Incompatible destination columns reject the whole operation.
  • Undo reverses one host batch. Nothing is persisted until Save draft is chosen.

States covered

  • fill down
  • apply active value
  • atomic validation
  • read-only preservation
  • single-step undo
  • loaded-row bounds
  • explicit local save

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-grid-bulk-operations.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import { useRef, useState } from 'react';
import { Button, DataGrid, UIProvider, dataValuesEqual, parseDataValue, type DataColumn, type DataEdit } from '@bld8/ui';

type Task = { id: string; revision: number; title: string; estimate: number; approved: boolean; people: string[] };
const columns: DataColumn<Task>[] = [
  { key: 'id', label: 'Record', type: 'text', width: 112, minWidth: 112, hideable: false },
  { key: 'title', label: 'Task', type: 'text', editable: true, required: true, minWidth: 230 },
  { key: 'estimate', label: 'Estimate', type: 'number', editable: true, min: 0, max: 20 },
  { key: 'approved', label: 'Approved', type: 'boolean', editable: true },
  { key: 'people', label: 'People', type: 'multi-select', editable: true, options: [{ value: 'maya', label: 'Maya Chen' }, { value: 'sam', label: 'Sam Rivera' }], minWidth: 190 },
  { key: 'revision', label: 'Revision', type: 'number' }
];
const initial: Task[] = [
  { id: 'BULK-1', revision: 1, title: 'Review keyboard focus', estimate: 3, approved: true, people: ['maya'] },
  { id: 'BULK-2', revision: 2, title: 'Align field labels', estimate: 5, approved: false, people: ['sam'] },
  { id: 'BULK-3', revision: 3, title: 'Check narrow layouts', estimate: 8, approved: false, people: [] },
  { id: 'BULK-4', revision: 4, title: 'Prepare source notes', estimate: 13, approved: true, people: ['sam'] }
];
const clone = (rows: readonly Task[]) => rows.map(row => ({ ...row, people: [...row.people] }));
type History = { rows: Task[]; past: Task[][]; future: Task[][]; batches: number; lastBatch: number };
export default function GridBulkOperationsExample() {
  const [history, setHistory] = useState<History>(() => ({ rows: clone(initial), past: [], future: [], batches: 0, lastBatch: 0 }));
  const current = useRef(history); current.current = history;
  const [saved, setSaved] = useState(() => clone(initial)), [saves, setSaves] = useState(0), [disabled, setDisabled] = useState(false);
  const [message, setMessage] = useState('Select a range. Changes stay in the local draft.');
  function replace(next: History) { current.current = next; setHistory(next); }
  function edit(edits: DataEdit<Task>[]) {
    const before = current.current, next = clone(before.rows);
    // The host validates the full batch again before replacing its draft once.
    for (const edit of edits) {
      const row = next.find(row => row.id === edit.id), column = columns.find(column => column.key === edit.key);
      if (!row || !column) { setMessage('No draft values changed: a destination is no longer loaded.'); return; }
      const parsed = parseDataValue(column, edit.value);
      if (parsed.error) { setMessage('No draft values changed: ' + parsed.error); return; }
      Object.assign(row, { [edit.key]: parsed.value });
    }
    if (next.every((row, index) => columns.every(column => dataValuesEqual(row[column.key], before.rows[index][column.key])))) return;
    replace({ rows: next, past: [...before.past.slice(-49), clone(before.rows)], future: [], batches: before.batches + 1, lastBatch: edits.length });
    setMessage('One draft transaction received. Review before saving.');
  }
  function undo() { const before = current.current, previous = before.past.at(-1); if (!previous) return; replace({ ...before, rows: clone(previous), past: before.past.slice(0, -1), future: [clone(before.rows), ...before.future] }); setMessage('The entire last draft transaction was undone.'); }
  function redo() { const before = current.current, next = before.future[0]; if (!next) return; replace({ ...before, rows: clone(next), past: [...before.past, clone(before.rows)], future: before.future.slice(1) }); setMessage('The entire draft transaction was restored.'); }
  const dirty = history.rows.flatMap(row => columns.filter(column => !dataValuesEqual(row[column.key], saved.find(savedRow => savedRow.id === row.id)?.[column.key])).map(column => ({ id: row.id, key: column.key })));
  return <UIProvider><div style={{ display: 'grid', gap: 16, minWidth: 0 }}>
    <p className="bui-hint">Fill down repeats each column's top selected value. Apply active value uses the active cell for every editable destination. Mixed types may reject the whole action.</p>
    <DataGrid label="Bulk draft grid" rows={history.rows} columns={columns} onEdit={edit} bulkEditing disabled={disabled} dirtyCells={dirty} onUndo={undo} onRedo={redo} canUndo={!!history.past.length} canRedo={!!history.future.length} defaultView={{ columnOrderKeys: columns.map(column => column.key), visibleColumnKeys: columns.map(column => column.key), columnWidths: {}, columnPinning: {}, density: 'compact' }} />
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      <Button size="sm" disabled={disabled || !dirty.length} onClick={() => { setSaved(clone(current.current.rows)); setSaves(count => count + 1); setMessage('Saved to this example only. No service request was made.'); }}>Save bulk draft</Button>
      <Button size="sm" variant="secondary" onClick={() => { replace({ rows: clone(initial), past: [], future: [], batches: 0, lastBatch: 0 }); setSaved(clone(initial)); setSaves(0); setMessage('Restored the example records.'); }}>Restore bulk example</Button>
      <Button size="sm" variant="ghost" onClick={() => setDisabled(value => !value)}>{disabled ? 'Enable grid editing' : 'Disable grid editing'}</Button>
    </div>
    <p role="status" className="bui-hint">{message}</p>
    <output aria-label="Bulk transaction counts" className="bui-hint">{JSON.stringify({ batches: history.batches, lastBatch: history.lastBatch, saves })}</output>
    <output aria-label="Bulk canonical values" style={{ fontSize: 12, overflowWrap: 'anywhere' }}>{JSON.stringify(history.rows)}</output>
    <p className="bui-hint">Only these four loaded records are editable. The application owns atomic history, permissions, durable storage and service writes.</p>
  </div></UIProvider>;
}

Quick reference

React / TypeScript
<DataGrid label="Issues" rows={draftRows} columns={columns}
  onEdit={applyEdits} cellErrors={errors} dirtyCells={dirtyCells}
  sorts={query.sorts} onSortsChange={setSorts}
  onOpenRow={inspectRow} onUndo={undo} onRedo={redo}
  canUndo={canUndo} canRedo={canRedo} />

In the workspace or ZIP starter, import components from @bld8/ui and include @bld8/ui/styles.css once. Registry installations use your local bld8/ source path. Wrap overlays in UIProvider.

API & behaviour

Default ARIA grid over up to 100 loaded rows and 30 columns. Opt into fixed-height row virtualization for up to 20,000 supplied rows; columns are not virtualized. AdvancedDataGrid adds Scroll/Pages, explicit lazy tree loading, separate details and query-matched summaries. Clipboard ranges support up to 20 columns. Drag across cells or Shift-click to select a rectangle. Arrow keys move cells; Shift+arrows extend the range. A neutral fill and one perimeter outline identify it without native text highlights; text selection remains available in editors. Enter/F2 opens a native editor; Escape cancels. Copy/paste uses bounded quoted TSV; a paste cannot write read-only fields or escape the loaded page. The host owns raw drafts, validation, history, source paging and persistence. No automatic writes occur. Supply cellErrors and dirtyCells for feedback. Ctrl/Command+Z and Shift+Z route to host undo/redo when not editing a native field. Shift-click a heading adds ordered multi-sort. Use ResourceWorkspace<T> for another record domain, or DataWorkspace for the revision-checked Issue workflow and durable Next.js/Vite HTTP references. Both use one explicit draft/review/save controller. DataTable remains an independent ordinary table. Select columns use portalled choice menus with keyboard navigation and selected checks. Set DataColumn.searchable for label search (automatic above seven options); choices write canonical IDs. Escape cancels and Tab moves between cells. The cell perimeter remains the only editor boundary.

DataGrid

DataGrid public properties
PropTypeDefault
columnsRequiredreadonly DataColumn<T>[]—
labelRequiredstring—
rowsRequiredreadonly T[]—
bulkEditingboolean | undefined

Opt-in loaded-range operations. Each valid operation emits one onEdit batch; the host owns history and persistence.

false
canRedoboolean | undefined—
canUndoboolean | undefined—
cellErrorsreadonly DataCellError[] | undefined[]
defaultViewDataGridViewState | undefined—
dirtyCellsreadonly { id: string; key: string; }[] | undefined[]
disabledboolean | undefinedfalse
layoutControlsboolean | undefined

Column visibility, ordering, pinning and density controls. Opt-in.

false
navigationRefRef<DataGridHandle> | undefined—
onBulkEditError((message: string) => void) | undefined—
onCellKeyDown((context: DataGridCellContext<T>, event: KeyboardEvent<HTMLTableCellElement>) => void) | undefined

Host keyboard intent before built-in navigation.

—
onClipboardError((message: string) => void) | undefined—
onEdit((edits: DataEdit<T>[]) => void) | undefined—
onOpenRow((row: T) => void) | undefined—
onRedo(() => void) | undefined—
onSortsChange((sorts: DataSort[]) => void) | undefined—
onUndo(() => void) | undefined—
onViewChange((view: DataGridViewState) => void) | undefined—
renderCell((context: DataGridCellContext<T>) => ReactNode) | undefined

Return undefined to keep the built-in presentational cell. Do not add tab stops.

—
renderEditor((context: DataGridEditorContext<T>) => ReactNode) | undefined

Return undefined to keep the built-in editor. Render a component to use hooks.

—
resizableColumnsboolean | undefined

Pointer and keyboard resizing. Opt-in; minWidth is respected.

false
rowHierarchy((row: T) => { level: number; expanded?: boolean; }) | undefined—
sortControlsboolean | undefined

Show a touch and keyboard sort editor when onSortsChange is provided.

true
sortsreadonly DataSort[] | undefined[]
viewDataGridViewState | undefined

Optional controlled presentation, using the same fields as TableViewState.

—
virtualizationDataGridVirtualization | undefined

Opt-in fixed-height virtualization over a complete supplied dataset, up to 20,000 rows.

—

AdvancedDataGrid

AdvancedDataGrid public properties
PropTypeDefault
columnsRequiredreadonly DataColumn<T>[]—
labelRequiredstring—
rowsRequiredreadonly T[]—
allMatchingSummaryDataSummarySnapshot | undefined—
bulkEditingboolean | undefined

Opt-in loaded-range operations. Each valid operation emits one onEdit batch; the host owns history and persistence.

—
canRedoboolean | undefined—
canUndoboolean | undefined—
cellErrorsreadonly DataCellError[] | undefined—
defaultExpandedKeysreadonly string[] | undefined[]
defaultReadingView"scroll" | "pages" | undefined'scroll'
defaultViewDataGridViewState | undefined—
dirtyCellsreadonly { id: string; key: string; }[] | undefined—
disabledboolean | undefined—
heightnumber | undefined480
layoutControlsboolean | undefined

Column visibility, ordering, pinning and density controls. Opt-in.

—
navigationRefRef<DataGridHandle> | undefined—
onBulkEditError((message: string) => void) | undefined—
onCellKeyDown((context: DataGridCellContext<T>, event: KeyboardEvent<HTMLTableCellElement>) => void) | undefined

Host keyboard intent before built-in navigation.

—
onClipboardError((message: string) => void) | undefined—
onEdit((edits: DataEdit<T>[]) => void) | undefined—
onOpenRow((row: T) => void) | undefined—
onRedo(() => void) | undefined—
onSortsChange((sorts: DataSort[]) => void) | undefined—
onUndo(() => void) | undefined—
onViewChange((view: DataGridViewState) => void) | undefined—
overscannumber | undefined4
pageSize5 | 10 | 20 | 50 | 100 | undefined20
queryKeystring | undefined

Query identity accompanying host-computed totals for all matching service records.

—
renderCell((context: DataGridCellContext<T>) => ReactNode) | undefined

Return undefined to keep the built-in presentational cell. Do not add tab stops.

—
renderDetails((row: T) => ReactNode) | undefined—
renderEditor((context: DataGridEditorContext<T>) => ReactNode) | undefined

Return undefined to keep the built-in editor. Render a component to use hooks.

—
resizableColumnsboolean | undefined

Pointer and keyboard resizing. Opt-in; minWidth is respected.

—
rowHeightnumber | undefined64
rowHierarchy((row: T) => { level: number; expanded?: boolean; }) | undefined—
sortControlsboolean | undefined

Show a touch and keyboard sort editor when onSortsChange is provided.

—
sortsreadonly DataSort[] | undefined—
sourceKeystring | number | undefined

Change when the service/account changes; in-flight children are aborted and caches reset.

—
summariesreadonly DataSummarySpec<T>[] | undefined[]
treeDataGridTree<T> | undefined—
viewDataGridViewState | undefined

Optional controlled presentation, using the same fields as TableViewState.

—

DataGridTree

DataGridTree public properties
PropTypeDefault
parentIdRequired(row: T) => string | null

Flat supplied records. Roots return null; every supplied child has a supplied parent.

—
hasChildren((row: T) => boolean) | undefined—
loadChildren((parent: T, context: { signal: AbortSignal; }) => Promise<readonly T[]>) | undefined—
onChildrenLoaded((parent: T, children: readonly T[]) => void) | undefined

Add loaded records to controlled host state before editing them. Host rows override the cache.

—

DataGridVirtualization

DataGridVirtualization public properties
PropTypeDefault
heightnumber | undefined—
overscannumber | undefined—
rowHeightnumber | undefined—

DataGridHandle

DataGridHandle public properties
PropTypeDefault
focusCellRequired(id: string, key: string) => boolean—

DataTreeNode

DataTreeNode public properties
PropTypeDefault
depthRequirednumber—
expandedRequiredboolean—
hasChildrenRequiredboolean—
parentIdRequiredstring | null—
rowRequiredT—

DataSummarySpec

DataSummarySpec public properties
PropTypeDefault
idRequiredstring—
labelRequiredstring—
operationRequired"count" | "sum" | "average"—
keyExtract<keyof T, string> | undefined—

DataSummarySnapshot

DataSummarySnapshot public properties
PropTypeDefault
queryKeyRequiredstring—
recordCountRequirednumber—
valuesRequiredreadonly DataSummaryValue[]—

DataGridCellContext

DataGridCellContext public properties
PropTypeDefault
activeRequiredboolean—
columnRequiredDataColumn<T>—
columnIndexRequirednumber—
rowRequiredT—
rowIndexRequirednumber—
selectedRequiredboolean—
valueRequiredT[Extract<keyof T, string>]—

DataGridEditorContext

DataGridEditorContext public properties
PropTypeDefault
activeRequiredboolean—
cancelRequired(restoreFocus?: boolean) => void—
columnRequiredDataColumn<T>—
columnIndexRequirednumber—
commitRequired(value?: unknown) => boolean

Validate and apply one cell. False keeps the editor open with its error.

—
disabledRequiredboolean—
draftValueRequiredunknown—
inputRefRequiredRefCallback<HTMLElement>—
labelRequiredstring—
onBlurRequired(event: FocusEvent<HTMLElement>) => void—
onKeyDownRequired(event: KeyboardEvent<HTMLElement>) => void—
onValueChangeRequired(value: unknown) => void—
portalPropsRequired{ 'data-grid-choice-owner': string; }

Spread on a custom portal root so outside focus is not mistaken for editor focus.

—
rowRequiredT—
rowIndexRequirednumber—
selectedRequiredboolean—
valueRequiredT[Extract<keyof T, string>]—
errorstring | undefined—

DataColumnOption

DataColumnOption public properties
PropTypeDefault
labelRequiredstring—
valueRequiredstring—
descriptionstring | undefined—
disabledboolean | undefined—
groupstring | undefined—
searchTermsstring[] | undefined—

DataGridViewState

Pick<TableViewState,'columnOrderKeys'|'visibleColumnKeys'|'columnWidths'|'columnPinning'|'density'>

DataGridViewState public properties
PropTypeDefault
columnOrderKeysRequiredstring[]—
columnPinningRequiredRecord<string, "start" | "end">—
columnWidthsRequiredRecord<string, number>—
densityRequired"compact" | "comfortable"—
visibleColumnKeysRequiredstring[]—

GridRange

GridRange public properties
PropTypeDefault
anchorRequiredGridPoint—
focusRequiredGridPoint—

GridPoint

GridPoint public properties
PropTypeDefault
columnRequirednumber—
rowRequirednumber—

gridFillDownEdits

<T extends DataRecord>(rows: readonly T[], columns: readonly DataColumn<T>[], range: GridRange) => DataEdit<T>[]

gridFillDownEdits public parameters
ParameterTypeDefault
rowsRequiredreadonly T[]—
columnsRequiredreadonly DataColumn<T>[]—
rangeRequiredGridRange—

gridApplySelectionEdits

<T extends DataRecord>(rows: readonly T[], columns: readonly DataColumn<T>[], range: GridRange, value: unknown) => DataEdit<T>[]

gridApplySelectionEdits public parameters
ParameterTypeDefault
rowsRequiredreadonly T[]—
columnsRequiredreadonly DataColumn<T>[]—
rangeRequiredGridRange—
valueRequiredunknown—

DataColumn

DataColumn public properties
PropTypeDefault
keyRequiredExtract<keyof T, string>—
labelRequiredstring—
typeRequired"number" | "boolean" | "text" | "date" | "select" | "multi-select"—
editableboolean | undefined

Editing is opt-in. Identity and revision fields always remain read-only.

—
hideableboolean | undefined—
maxnumber | undefined—
maxDatestring | undefined—
maxLengthnumber | undefined—
maxSelectionsnumber | undefined—
minnumber | undefined—
minDatestring | undefined

Date-only bounds, inclusive. Empty dates remain an empty string.

—
minLengthnumber | undefined—
minSelectionsnumber | undefined

Multi-select values are ordered, unique option IDs, with a hard limit of 100.

—
minWidthnumber | undefined—
optionsreadonly DataColumnOption[] | undefined—
pinned"start" | "end" | undefined—
requiredboolean | undefined—
resizableboolean | undefined—
searchableboolean | undefined

Search within select choices. Defaults to true for more than seven options.

—
sortableboolean | undefined—
widthnumber | undefined

Optional presentation constraints shared with portable table views.

—

DataEdit

DataEdit public properties
PropTypeDefault
idRequiredstring—
keyRequiredExtract<keyof T, string>—
valueRequiredunknown—

DataCellError

DataCellError public properties
PropTypeDefault
idRequiredstring—
keyRequiredstring—
messageRequiredstring—

DataQuery

DataQuery public properties
PropTypeDefault
filtersRequiredAnyFilterQuery—
pageRequirednumber—
pageSizeRequirednumber—
searchRequiredstring—
sortsRequiredDataSort[]—

DataSource

DataSource public properties
PropTypeDefault
loadRequired(query: DataQuery, context: { signal: AbortSignal; }) => Promise<{ rows: T[]; total: number; }>—
saveRequired(request: DataBatchRequest<T>, context: { signal: AbortSignal; }) => Promise<BatchResult<T>>—

DataChange

DataChange public properties
PropTypeDefault
expectedRevisionRequirednumber—
idRequiredstring—
valuesRequiredPartial<Omit<T, "id" | "revision">>—

DataBatchRequest

DataBatchRequest public properties
PropTypeDefault
changesRequiredDataChange<T>[]—
requestIdRequiredstring—

BatchResult

{ok:true;rows:T[]} | {ok:false;code:'conflict'|'validation';conflicts?:T[];errors?:DataCellError[]}

BatchResult public properties
PropTypeDefault
okRequiredboolean—

DataSort

DataSort public properties
PropTypeDefault
descendingRequiredboolean—
keyRequiredstring—

Tables come from the public TypeScript declarations. Related types and function parameters are shown alongside their component. A dash means no default is declared at the public function boundary.

Related controls

Notes to self

Test this component with real content, keyboard input and both themes. The example is a starting point; labels, error handling and behaviour still need to fit the application.