---
title: "Data Grid"
description: "Data Grid component - a grid over hundreds of thousands of records: windowed rows, multisort, column filters, locked (sticky) columns, pagination, infinite scrolling and selection, every query run locally by defuss-dataview and kept in the grid's store."
slug: "data-grid"
---

import { DocPage, PageHeader, SkillPanel, SourceFiles, SourceNote, StatesSection, CodeBlock, Demo, DemoCode, ChangelogEntries, ArchBody, StatsClaim, StatsCards, PageOverlay, DocText, DocLink, H2, SkillField, SkillText, SkillRow, SkillGrid, Variant, ApiPill, Dim, CodeCard, TableCard, ApiSection } from "../../lib/components/index";

<DocPage meta={meta}>

<PageHeader slug="data-grid" title="Data Grid" component="data-grid">
  A table for data no table can hold. Only the rows on screen exist in the DOM, and every query runs locally over all of them through <a class="link" href="https://www.npmjs.com/package/defuss-dataview">defuss-dataview</a>: sort by several columns at once, filter each column, lock columns that stay put while the rest scroll, page through, or load more as you reach the end. The query is the grid's state - <code>el.store</code> - so any code can follow it, drive it or keep it. Give rows a parent and it is a <a class="link" href="tree-grid.html">tree grid</a>.
</PageHeader>

<SkillPanel component="data-grid">
  <SkillField label="Native basis">
<SkillText>An ARIA <code>grid</code> of divs: ONE scroll container holds a <code>position: sticky</code> head and a windowed body; head and rows share one CSS grid track template, so locked columns are sticky cells and nothing scrolls in JS. <code>df$.shadcn.dataGrid.setSource(el, records)</code> hands it the data; <code>df$.shadcn.dataGrid.source(el)</code> is its query source - a chart bound to it groups exactly the rows the grid's filters match (<DocLink href="charts-big-data.html">Big Data Charts</DocLink>).</SkillText>
  </SkillField>

  <SkillField label="Web Platform APIs">
<SkillRow>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky" title="head and locked columns stay put"><code>position: sticky</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-anchor" title="the runtime owns the scroll position"><code>overflow-anchor: none</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout" title="one track template for head and rows"><code>CSS Grid</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/API/Popover_API" title="the column menu: top layer, light dismiss"><code>popover</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_anchor_positioning" title="the menu hangs from its arrow"><code>anchor()</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events" title="move and resize columns by mouse, pen or finger"><code>Pointer Events</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat" title="currency / number cells"><code>Intl.NumberFormat</code></ApiPill>
    <ApiPill href="https://www.w3.org/WAI/ARIA/apg/patterns/grid/" title="cell-by-cell keyboard, aria-rowindex against the real length"><code>ARIA grid</code></ApiPill>
  </SkillRow>
  </SkillField>

  <SkillField label="Classes">
<SkillRow>
    <code>.data-grid</code>
    <code>.data-grid-viewport</code>
    <code>.data-grid-head</code>
    <code>.data-grid-row</code>
    <code>.data-grid-header</code>
    <code>.data-grid-menu-button</code>
    <code>.data-grid-resizer</code>
    <code>.data-grid-menu</code>
    <code>.data-grid-body</code>
    <code>.data-grid-cell</code>
    <code>.data-grid-footer</code>
  </SkillRow>
  </SkillField>

  <SkillField label="Data attributes">
<SkillText>Grid: <code>data-paging</code> (<code>virtual</code> · <code>pages</code> · <code>infinite</code>), <code>data-page-size</code>, <code>data-select</code>, <code>data-select-model</code> (<code>row</code> · <code>checkbox</code> · <code>cell</code> · <code>column</code> · <code>row column</code>), <code>data-drag</code> / <code>data-drop</code> (<code>move</code> · <code>copy</code>), <code>data-parent-field</code>, <code>data-persist</code> / <code>data-persist-prefix</code> / <code>data-persist-key</code>, <code>data-empty-text</code>. Header: <code>data-field</code>, <code>data-sort</code>, <code>data-sort-field</code>, <code>data-type</code>, <code>data-format</code>, <code>data-width</code>, <code>data-filter</code>, <code>data-options</code>, <code>data-locked</code>, <code>hidden</code>, <code>data-sortable</code> / <code>data-lockable</code> / <code>data-hideable</code> / <code>data-movable</code> / <code>data-resizable</code> <code>="false"</code>.</SkillText>
  </SkillField>
</SkillPanel>

```html example label="Pages" schema="none" hint="data-paging='pages' shows data-page-size rows a page and a pager below; the page is config.page (0-based), so sorting or filtering starts again at page 1."
<div
  class="data-grid"
  id="dg-pages"
  aria-label="Paged customers"
  data-paging="pages"
  data-page-size="20"
  style="height: 24rem; max-width: 36rem"
>
  <div class="data-grid-viewport">
    <div class="data-grid-head">
      <div class="data-grid-row">
        <div class="data-grid-header" data-field="id" data-type="number" data-format="" data-width="5rem">#</div>
        <div class="data-grid-header" data-field="name" data-width="minmax(10rem, 1fr)" data-filter="text">Name</div>
        <div
          class="data-grid-header"
          data-field="plan"
          data-width="7rem"
          data-filter="select"
          data-options="Free,Pro,Team"
          >Plan</div
        >
        <div class="data-grid-header" data-field="seats" data-type="number" data-width="6rem">Seats</div>
      </div>
    </div>
    <div class="data-grid-body"></div>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const plans = ['Free', 'Pro', 'Team'];
    const customers = Array.from({ length: 5000 }, (_, i) => ({
      id: i + 1,
      name: 'Customer ' + (i + 1),
      plan: plans[(i * 7) % 3],
      seats: 1 + ((i * 13) % 250),
    }));
    df$.shadcn.dataGrid.setSource(document.getElementById('dg-pages'), customers);
  });
</script>
```

```html example label="Infinite scrolling" schema="none" hint="data-paging='infinite' adds a page as you near the end: first from the records it has, then from load(offset, size) - an async function (here a fake 400 ms network) that returns the next records, or none when there are no more. The grid waits in 'loading' for the first page."
<div
  class="data-grid"
  id="dg-feed"
  aria-label="Event log"
  data-paging="infinite"
  data-page-size="50"
  style="height: 20rem; max-width: 36rem"
>
  <div class="data-grid-viewport">
    <div class="data-grid-head">
      <div class="data-grid-row">
        <div
          class="data-grid-header"
          data-field="id"
          data-type="number"
          data-format=""
          data-width="5rem"
          data-sortable="false"
          >#</div
        >
        <div class="data-grid-header" data-field="level" data-width="6rem" data-sortable="false">Level</div>
        <div class="data-grid-header" data-field="message" data-width="minmax(14rem, 1fr)" data-sortable="false"
          >Message</div
        >
      </div>
    </div>
    <div class="data-grid-body"></div>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const levels = ['info', 'info', 'info', 'warn', 'error'];
    const messages = ['User signed in', 'Cache warmed', 'Job queued', 'Slow query (812 ms)', 'Payment declined'];
    // a remote source: 1,000 events in pages, 400 ms per request
    const load = (offset, size) =>
      new Promise((resolve) =>
        setTimeout(() => {
          if (offset >= 1000) return resolve([]);
          resolve(
            Array.from({ length: Math.min(size, 1000 - offset) }, (_, i) => {
              const n = offset + i;
              return { id: n + 1, level: levels[(n * 7) % 5], message: messages[(n * 7) % 5] };
            }),
          );
        }, 400),
      );
    df$.shadcn.dataGrid.setSource(document.getElementById('dg-feed'), [], { load });
  });
</script>
```

```html example label="Custom cells" schema="none" hint="cells: { field: (el, record) } fills a column with anything - a badge, a meter. Cells are recycled with their rows; the function gets a fresh .data-grid-content element each time. A control in a cell (a field, a checkbox, a select) keeps its clicks and its keys - the grid does not take them for row selection or navigation."
<div class="data-grid" id="dg-cells" aria-label="Deployments" style="height: 16rem; max-width: 40rem">
  <div class="data-grid-viewport">
    <div class="data-grid-head">
      <div class="data-grid-row">
        <div class="data-grid-header" data-field="service" data-width="minmax(9rem, 1fr)">Service</div>
        <div class="data-grid-header" data-field="status" data-width="8rem">Status</div>
        <div class="data-grid-header" data-field="coverage" data-type="number" data-width="10rem">Coverage</div>
      </div>
    </div>
    <div class="data-grid-body"></div>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const states = [
      ['healthy', 'default'],
      ['degraded', 'secondary'],
      ['down', 'destructive'],
    ];
    const rows = Array.from({ length: 2000 }, (_, i) => ({
      id: i + 1,
      service: 'service-' + String(i + 1).padStart(4, '0'),
      status: (i * 7) % 11 === 0 ? 2 : (i * 3) % 7 === 0 ? 1 : 0,
      coverage: 40 + ((i * 13) % 60),
    }));
    df$.shadcn.dataGrid.setSource(document.getElementById('dg-cells'), rows, {
      cells: {
        status: (el, record) => {
          const [label, variant] = states[record.status];
          const badge = document.createElement('span');
          badge.className = 'badge';
          badge.dataset.variant = variant;
          badge.textContent = label;
          el.append(badge);
        },
        coverage: (el, record) => {
          const meter = document.createElement('meter');
          meter.min = 0;
          meter.max = 100;
          meter.value = record.coverage;
          meter.style.width = '5rem';
          const text = document.createElement('span');
          text.textContent = ' ' + record.coverage + '%';
          el.append(meter, text);
        },
      },
    });
  });
</script>
```

```html example label="Inline editing" schema="none" hint="A header with data-editable makes its column edit in place: double-click a cell, or press Enter / F2 on it. The editor follows data-editor (string, number, boolean, enum, color, date, text) - else the column's data-type or the value: an Input, a number Input with data-min / data-max / data-integer, a Switch, a Select of data-options, a colour or a date input. Enter or leaving the cell writes the value, Escape keeps the old one, Tab moves to the next editable cell. data-required and the number rules refuse a value with a message. Every edit replaces the record in the source and runs the query again - sorted by Stock, an edited stock moves the row. The line below listens to data-grid-edit."
<div class="data-grid" id="dg-edit" aria-label="Products" style="height: 18rem">
  <div class="data-grid-viewport">
    <div class="data-grid-head">
      <div class="data-grid-row">
        <div class="data-grid-header" data-field="sku" data-width="7rem" data-format="">SKU</div>
        <div
          class="data-grid-header"
          data-field="name"
          data-width="minmax(10rem, 1fr)"
          data-editable
          data-required
          data-filter="text"
          >Product</div
        >
        <div
          class="data-grid-header"
          data-field="stock"
          data-type="number"
          data-width="7rem"
          data-editable
          data-min="0"
          data-integer
          data-sort="desc"
          >Stock</div
        >
        <div
          class="data-grid-header"
          data-field="price"
          data-type="number"
          data-format="currency:EUR"
          data-width="8rem"
          data-editable
          data-min="0"
          data-step="0.01"
          >Price</div
        >
        <div
          class="data-grid-header"
          data-field="category"
          data-width="9rem"
          data-editable
          data-editor="enum"
          data-options="Tools, Garden, Kitchen, Office"
          data-filter="select"
          >Category</div
        >
        <div class="data-grid-header" data-field="active" data-width="6rem" data-editable data-editor="boolean"
          >Active</div
        >
        <div class="data-grid-header" data-field="color" data-width="7rem" data-editable data-editor="color"
          >Colour</div
        >
        <div class="data-grid-header" data-field="restock" data-width="9rem" data-editable data-editor="date"
          >Restock</div
        >
      </div>
    </div>
    <div class="data-grid-body"></div>
  </div>
</div>
<p class="text-sm" style="margin-block-start: 0.5rem"
  ><output id="dg-edit-log">Double-click a cell to edit it.</output></p
>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const names = ['Hammer', 'Rake', 'Kettle', 'Stapler', 'Wrench', 'Hose', 'Whisk', 'Lamp'];
    const cats = ['Tools', 'Garden', 'Kitchen', 'Office'];
    const colors = ['#2563eb', '#16a34a', '#dc2626', '#9333ea', '#ea580c'];
    const rows = Array.from({ length: 10000 }, (_, i) => ({
      id: i + 1,
      sku: 'P-' + String(i + 1).padStart(5, '0'),
      name: names[i % names.length] + ' ' + (Math.floor(i / names.length) + 1),
      stock: (i * 37) % 500,
      price: 4.5 + ((i * 53) % 9000) / 100,
      category: cats[i % cats.length],
      active: i % 5 !== 0,
      color: colors[i % colors.length],
      restock: '2026-' + String(1 + (i % 12)).padStart(2, '0') + '-' + String(1 + (i % 28)).padStart(2, '0'),
    }));
    const grid = document.getElementById('dg-edit');
    df$.shadcn.dataGrid.setSource(grid, rows);
    grid.addEventListener('data-grid-edit', (e) => {
      const { record, field, value, oldValue } = e.detail;
      document.getElementById('dg-edit-log').textContent =
        record.sku + ' ' + field + ': ' + JSON.stringify(oldValue) + ' to ' + JSON.stringify(value);
    });
  });
</script>
```

```html example label="Custom editors" schema="none" hint="setSource's getEditorFn(field, value, ctx) hands the grid any editor: an element (an input, a select) or { el, getValue, validate?, focus?, immediate? }. Here the score edits as a Rating (radio stars - a pick commits at once, immediate: true) and shows as a read-only Rating through cells; the progress edits as a Slider with its value beside it (Enter or leaving it commits); the owner is a Select of the team built from the data. validateFn(field, value, ctx) refuses across fields: a task that is done (100 %) needs an owner. Return false from getEditorFn to keep one cell from editing - archived tasks stay as they are."
<div class="data-grid" id="dg-custom" aria-label="Tasks" style="height: 18rem; max-width: 46rem">
  <div class="data-grid-viewport">
    <div class="data-grid-head">
      <div class="data-grid-row">
        <div class="data-grid-header" data-field="task" data-width="minmax(10rem, 1fr)" data-editable data-required
          >Task</div
        >
        <div
          class="data-grid-header"
          data-field="score"
          data-type="number"
          data-width="9rem"
          data-align="start"
          data-editable
          >Priority</div
        >
        <div
          class="data-grid-header"
          data-field="progress"
          data-type="number"
          data-width="11rem"
          data-align="start"
          data-editable
          >Progress</div
        >
        <div class="data-grid-header" data-field="owner" data-width="8rem" data-editable>Owner</div>
        <div class="data-grid-header" data-field="archived" data-width="6rem">Archived</div>
      </div>
    </div>
    <div class="data-grid-body"></div>
  </div>
</div>
<p class="text-sm" style="margin-block-start: 0.5rem"
  ><output id="dg-custom-log">Double-click a priority, a progress or an owner.</output></p
>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const team = ['', 'Ada', 'Grace', 'Linus', 'Margaret'];
    const rows = Array.from({ length: 5000 }, (_, i) => ({
      id: i + 1,
      task: 'Task ' + (i + 1),
      score: 1 + ((i * 7) % 5),
      progress: (i * 13) % 101,
      owner: team[(i * 3) % team.length],
      archived: i % 9 === 0 ? 'yes' : '',
    }));
    // a Rating of five radio stars - a pick commits at once
    const ratingEditor = (value) => {
      const el = document.createElement('fieldset');
      el.className = 'rating';
      el.dataset.size = 'sm';
      el.setAttribute('aria-label', 'Priority');
      const name = 'score-' + Math.random().toString(36).slice(2, 7);
      for (let n = 1; n <= 5; n++) {
        const item = document.createElement('label');
        item.className = 'rating-item';
        const input = document.createElement('input');
        input.className = 'rating-input';
        input.type = 'radio';
        input.name = name;
        input.value = String(n);
        input.checked = n === value;
        input.setAttribute('aria-label', n + (n === 1 ? ' star' : ' stars'));
        item.append(input);
        el.append(item);
      }
      return {
        el,
        immediate: true,
        getValue: () => Number(el.querySelector('input:checked')?.value ?? value),
        focus: () => (el.querySelector('input:checked') ?? el.querySelector('input')).focus(),
      };
    };
    // a Slider with its value beside it - Enter or leaving it commits
    const sliderEditor = (value) => {
      const el = document.createElement('span');
      el.style.cssText = 'display: flex; align-items: center; gap: 0.5rem; flex: 1';
      const range = document.createElement('input');
      range.type = 'range';
      range.className = 'slider';
      range.min = '0';
      range.max = '100';
      range.value = String(value);
      range.setAttribute('aria-label', 'Progress');
      range.style.flex = '1';
      const out = document.createElement('output');
      out.textContent = value + '%';
      range.addEventListener('input', () => (out.textContent = range.value + '%'));
      el.append(range, out);
      return { el, getValue: () => range.valueAsNumber, focus: () => range.focus() };
    };
    const ownerEditor = (value) => {
      const el = document.createElement('select');
      el.className = 'select';
      el.dataset.size = 'xs';
      el.setAttribute('aria-label', 'Owner');
      for (const name of team) {
        const o = document.createElement('option');
        o.value = name;
        o.textContent = name || 'Nobody';
        o.selected = name === value;
        el.append(o);
      }
      return el;
    };
    const grid = document.getElementById('dg-custom');
    df$.shadcn.dataGrid.setSource(grid, rows, {
      cells: {
        score: (el, record) => {
          const stars = document.createElement('span');
          stars.className = 'rating';
          stars.dataset.readonly = '';
          stars.dataset.size = 'sm';
          stars.style.setProperty('--rating-value', record.score);
          stars.setAttribute('role', 'img');
          stars.setAttribute('aria-label', 'Priority ' + record.score + ' of 5');
          el.append(stars);
        },
        progress: (el, record) => {
          const bar = document.createElement('progress');
          bar.className = 'progress';
          bar.max = 100;
          bar.value = record.progress;
          bar.style.width = '6rem';
          el.append(bar, ' ' + record.progress + '%');
        },
      },
      getEditorFn: (field, value, ctx) => {
        if (ctx.record.archived) return false;
        if (field === 'score') return ratingEditor(value);
        if (field === 'progress') return sliderEditor(value);
        if (field === 'owner') return ownerEditor(value);
        return null; // the built-in editor (the task's Input)
      },
      validateFn: (field, value, ctx) => {
        if (field === 'progress' && value === 100 && !ctx.record.owner) return 'A finished task needs an owner';
        if (field === 'owner' && !value && ctx.record.progress === 100) return 'A finished task keeps its owner';
      },
    });
    grid.addEventListener('data-grid-edit', (e) => {
      document.getElementById('dg-custom-log').textContent =
        e.detail.record.task + ': ' + e.detail.field + ' is now ' + JSON.stringify(e.detail.value);
    });
  });
</script>
```

```html example label="Selection models" schema="none" hint="data-select turns selection on, data-select-model says what it takes - pick one above the grid. Row: a click selects a row, Shift+click the range, Ctrl/Cmd+click toggles, Shift+Arrow Up / Down extends. Cell: a click selects a cell, Shift+click or Shift+arrows the rectangle to it, Ctrl/Cmd+click adds a cell, the arrows select as they move - like Excel. Column: a cell or a header selects its column (a header no longer sorts - its menu does). Row + column: a cell selects its row, a header its column. Checkbox: a checkbox in front of every row toggles it (Shift: the range), the one in the head selects every row or none - a row click still selects just that row. A selected cell under the pointer deepens its tint, never the soft hover. Drag across cells to select what you cross (past an edge the grid scrolls on); on a phone rest a finger on a cell first. Ctrl/Cmd+A selects everything. Ctrl/Cmd+C copies the selection as tab-separated values - paste it into Excel, Google Sheets or Docs. Ctrl/Cmd+V pastes from a spreadsheet into the editable columns (Product, Stock, Price, Category): one selected cell is where the block starts, otherwise only the selected cells change, and a single value fills them all. The line below follows the store, data-grid-copy and data-grid-paste."
<div class="flex flex-col gap-2">
  <div class="toggle-group" role="group" aria-label="Selection model" data-type="single" data-size="sm" id="dg-models">
    <button class="toggle" aria-pressed="false" value="row">Row</button>
    <button class="toggle" aria-pressed="true" value="cell">Cell</button>
    <button class="toggle" aria-pressed="false" value="column">Column</button>
    <button class="toggle" aria-pressed="false" value="row column">Row + column</button>
    <button class="toggle" aria-pressed="false" value="checkbox">Checkbox</button>
  </div>
  <div
    class="data-grid"
    id="dg-select"
    aria-label="Parts"
    data-select="multiple"
    data-select-model="cell"
    style="height: 20rem"
  >
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="sku" data-width="7rem">SKU</div>
          <div class="data-grid-header" data-field="name" data-width="minmax(9rem, 1fr)" data-editable data-required
            >Product</div
          >
          <div
            class="data-grid-header"
            data-field="stock"
            data-type="number"
            data-width="6rem"
            data-editable
            data-min="0"
            data-integer
            >Stock</div
          >
          <div
            class="data-grid-header"
            data-field="price"
            data-type="number"
            data-format="currency:EUR"
            data-width="7rem"
            data-editable
            data-min="0"
            >Price</div
          >
          <div
            class="data-grid-header"
            data-field="category"
            data-width="8rem"
            data-editable
            data-editor="enum"
            data-options="Tools, Garden, Kitchen, Office"
            >Category</div
          >
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
  <p class="text-sm"><output id="dg-select-log">Select cells, then Ctrl/Cmd+C.</output></p>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const names = ['Bolt', 'Nut', 'Washer', 'Hinge', 'Bracket', 'Spring', 'Clamp', 'Rivet'];
    const cats = ['Tools', 'Garden', 'Kitchen', 'Office'];
    const rows = Array.from({ length: 10000 }, (_, i) => ({
      id: i + 1,
      sku: 'S-' + String(i + 1).padStart(5, '0'),
      name: names[i % names.length] + ' ' + (Math.floor(i / names.length) + 1),
      stock: (i * 37) % 500,
      price: 0.5 + ((i * 53) % 2000) / 100,
      category: cats[i % cats.length],
    }));
    const grid = document.getElementById('dg-select');
    const log = document.getElementById('dg-select-log');
    const { dataGrid } = df$.shadcn;
    dataGrid.setSource(grid, rows);
    // the selection is config: the store says what is selected
    grid.store.subscribe(({ config }) => {
      const n = config.selectedRanges.length || config.selectedColumns.length || config.selected.length;
      if (!n) return;
      log.textContent =
        'selected: ' +
        JSON.stringify(
          config.selectedRanges.length
            ? config.selectedRanges
            : config.selectedColumns.length
              ? config.selectedColumns
              : config.selected.slice(0, 8),
        );
    });
    grid.addEventListener('data-grid-copy', (e) => {
      log.textContent = 'Copied ' + e.detail.rows + ' × ' + e.detail.columns + ' - paste it into a spreadsheet.';
    });
    grid.addEventListener('data-grid-paste', (e) => {
      const { written, skipped, refused } = e.detail;
      log.textContent =
        'Pasted: ' +
        written +
        ' written, ' +
        skipped +
        ' read-only' +
        (refused.length ? ', refused: ' + refused[0].text + ' (' + refused[0].message + ')' : '');
    });
    const models = document.getElementById('dg-models');
    models.addEventListener('click', () =>
      setTimeout(() => {
        const on = models.querySelector('[aria-pressed="true"]');
        if (!on || on.value === grid.dataset.selectModel) return;
        grid.dataset.selectModel = on.value;
        dataGrid.clearSelection(grid);
        log.textContent = on.textContent + ' selection.';
      }),
    );
  });
</script>
```

```html example label="Checkbox selection" schema="none" hint="data-select-model='checkbox' puts a checkbox in front of every row and one in the head. A row's box toggles that row and keeps the others; Shift+click on a box selects the range from the last one. The head's box selects every row of the query - filter first and it takes only the matches - or, when all of them are ticked, none; it shows a dash while some are. A click elsewhere in a row still selects just that row, Space toggles the focused row, Ctrl/Cmd+A selects all. The line below follows config.selected in the grid's store."
<div
  class="data-grid"
  id="dg-checks"
  aria-label="People"
  data-select="multiple"
  data-select-model="checkbox"
  data-persist="none"
  style="height: 20rem"
>
  <div class="data-grid-viewport">
    <div class="data-grid-head">
      <div class="data-grid-row">
        <div class="data-grid-header" data-field="name" data-width="minmax(9rem, 1fr)" data-filter="text">Name</div>
        <div class="data-grid-header" data-field="team" data-width="8rem" data-filter="select">Team</div>
        <div class="data-grid-header" data-field="role" data-width="9rem">Role</div>
        <div class="data-grid-header" data-field="since" data-type="number" data-format="" data-width="5rem">Since</div>
      </div>
    </div>
    <div class="data-grid-body"></div>
  </div>
</div>
<p class="text-sm" style="margin-block-start: 0.5rem"><output id="dg-checks-log">Nobody is selected.</output></p>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const first = ['Ada', 'Grace', 'Linus', 'Barbara', 'Ken', 'Margaret', 'Dennis', 'Frances', 'Alan', 'Hedy'];
    const last = [
      'Lovelace',
      'Hopper',
      'Torvalds',
      'Liskov',
      'Thompson',
      'Hamilton',
      'Ritchie',
      'Allen',
      'Kay',
      'Lamarr',
    ];
    const teams = ['Platform', 'Design', 'Data', 'Mobile', 'Support'];
    const roles = ['Engineer', 'Designer', 'Analyst', 'Lead', 'Writer', 'Manager'];
    const people = Array.from({ length: 500 }, (_, i) => ({
      id: i + 1,
      name: first[i % 10] + ' ' + last[(i * 3 + Math.floor(i / 10)) % 10],
      team: teams[(i * 7) % 5],
      role: roles[(i * 3) % 6],
      since: 2012 + ((i * 7) % 14),
    }));
    const grid = document.getElementById('dg-checks');
    const log = document.getElementById('dg-checks-log');
    df$.shadcn.dataGrid.setSource(grid, people);
    grid.store.subscribe(({ config }) => {
      const picked = df$.shadcn.dataGrid.selected(grid);
      log.textContent = picked.length
        ? picked.length +
          ' selected: ' +
          picked
            .slice(0, 3)
            .map((p) => p.name)
            .join(', ') +
          (picked.length > 3 ? ' and ' + (picked.length - 3) + ' more' : '')
        : 'Nobody is selected.';
    });
  });
</script>
```

```html example label="Drag and drop between grids" schema="none" hint="data-drag lets rows drag out, data-drop lets records drop in. Drag a row from the Backlog into the Sprint: a line shows where it lands, and it moves. Tick several rows in the Sprint (the checkbox model) or Shift+click a range in the Backlog, then drag one of them - the selected rows go together. Hold Alt (Option) or Ctrl while dragging to copy instead: the copy gets an id of its own. Rows also reorder within a grid, and a drop onto a spreadsheet or a text field pastes them as tab-separated values. Without a mouse: select rows and use the buttons - they call remove() and insert(), what a drop writes. The line below follows data-grid-drop."
<div class="flex flex-col gap-2">
  <div class="grid gap-3" style="grid-template-columns: repeat(auto-fit, minmax(17rem, 1fr))">
    <div
      class="data-grid"
      id="dg-backlog"
      aria-label="Backlog"
      data-select="multiple"
      data-drag
      data-drop
      data-persist="none"
      style="height: 18rem"
    >
      <div class="data-grid-viewport">
        <div class="data-grid-head">
          <div class="data-grid-row">
            <div class="data-grid-header" data-field="key" data-width="5rem">Key</div>
            <div class="data-grid-header" data-field="title" data-width="minmax(8rem, 1fr)">Backlog</div>
            <div class="data-grid-header" data-field="points" data-type="number" data-format="" data-width="4.5rem"
              >Pts</div
            >
          </div>
        </div>
        <div class="data-grid-body"></div>
      </div>
    </div>
    <div
      class="data-grid"
      id="dg-sprint"
      aria-label="Sprint"
      data-select="multiple"
      data-select-model="checkbox"
      data-drag
      data-drop
      data-persist="none"
      style="height: 18rem"
    >
      <div class="data-grid-viewport">
        <div class="data-grid-head">
          <div class="data-grid-row">
            <div class="data-grid-header" data-field="key" data-width="5rem">Key</div>
            <div class="data-grid-header" data-field="title" data-width="minmax(8rem, 1fr)">Sprint</div>
            <div class="data-grid-header" data-field="points" data-type="number" data-format="" data-width="4.5rem"
              >Pts</div
            >
          </div>
        </div>
        <div class="data-grid-body"></div>
      </div>
    </div>
  </div>
  <div class="flex flex-wrap items-center gap-2">
    <button class="btn" data-variant="outline" data-size="sm" id="dg-to-sprint">Move to Sprint</button>
    <button class="btn" data-variant="outline" data-size="sm" id="dg-to-backlog">Move to Backlog</button>
    <p class="text-sm"><output id="dg-dnd-log">Drag a row from one grid into the other.</output></p>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const { dataGrid } = df$.shadcn;
    const verbs = ['Fix', 'Add', 'Polish', 'Test', 'Document', 'Speed up'];
    const things = ['login', 'search', 'export', 'billing', 'onboarding', 'settings', 'reports', 'sync'];
    const tasks = Array.from({ length: 40 }, (_, i) => ({
      id: i + 1,
      key: 'T-' + (101 + i),
      title: verbs[i % verbs.length] + ' ' + things[(i * 5) % things.length],
      points: [1, 2, 3, 5, 8][(i * 3) % 5],
    }));
    const backlog = document.getElementById('dg-backlog');
    const sprint = document.getElementById('dg-sprint');
    const log = document.getElementById('dg-dnd-log');
    const name = new Map([
      [backlog, 'Backlog'],
      [sprint, 'Sprint'],
    ]);
    dataGrid.setSource(backlog, tasks.slice(3));
    dataGrid.setSource(sprint, tasks.slice(0, 3));
    for (const grid of [backlog, sprint])
      grid.addEventListener('data-grid-drop', (e) => {
        const { records, effect, source } = e.detail;
        const what = records.length === 1 ? records[0].key : records.length + ' rows';
        log.textContent =
          (effect === 'copy' ? 'Copied ' : 'Moved ') +
          what +
          (source === grid ? ' within ' : ' to ') +
          name.get(grid) +
          '.';
      });
    // the keyboard's way: what a drag does, from a button
    const move = (from, to) => {
      const ids = dataGrid.selected(from).map((r) => r.id);
      if (!ids.length) return (log.textContent = 'Select rows in ' + name.get(from) + ' first.');
      const moved = dataGrid.insert(to, dataGrid.remove(from, ids));
      dataGrid.query(to, { selected: moved.map((r) => r.id) });
      log.textContent = 'Moved ' + moved.length + ' to ' + name.get(to) + '.';
    };
    document.getElementById('dg-to-sprint').addEventListener('click', () => move(backlog, sprint));
    document.getElementById('dg-to-backlog').addEventListener('click', () => move(sprint, backlog));
  });
</script>
```

```html example label="100,000 orders" hint="Click a header to sort, Shift+click to add a column to the sort. Type in the filter row - every filter runs over all 100,000 rows (text anywhere, case-insensitive; numbers take > 500, <= 20 …). The arrow at a header's end opens its menu: sort, Lock column (it moves into the sticky group and stays while the rest scrolls sideways), a checkbox per column to show or hide it, Reset columns. Drag a header to move its column (on touch: hold it first; let go without moving for the menu), drag its end edge to resize, double-click the edge for its authored width. Click / Shift+click / Ctrl+click select rows; arrows move cell by cell. The line under the grid subscribes to the grid's store."
<div class="flex flex-col gap-2">
  <div
    class="data-grid"
    id="dg-orders"
    aria-label="Orders"
    data-select="multiple"
    data-empty-text="No orders match."
    style="height: 24rem"
  >
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div
            class="data-grid-header"
            data-field="id"
            data-type="number"
            data-format=""
            data-width="6rem"
            data-filter="number"
            data-locked
            >Order</div
          >
          <div class="data-grid-header" data-field="customer" data-width="11rem" data-filter="text">Customer</div>
          <div class="data-grid-header" data-field="country" data-width="9rem" data-filter="select">Country</div>
          <div class="data-grid-header" data-field="product" data-width="10rem" data-filter="text">Product</div>
          <div class="data-grid-header" data-field="quantity" data-type="number" data-width="6rem" data-filter="number"
            >Qty</div
          >
          <div
            class="data-grid-header"
            data-field="total"
            data-type="number"
            data-format="currency:EUR"
            data-width="8rem"
            data-filter="number"
            >Total</div
          >
          <div class="data-grid-header" data-field="status" data-width="8rem" data-filter="select">Status</div>
          <div class="data-grid-header" data-field="date" data-format="date" data-width="8rem">Date</div>
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
  <p class="text-sm text-muted-foreground m-0" id="dg-orders-query" aria-live="polite"></p>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const first = ['Sofia', 'Jackson', 'Isabella', 'William', 'Olivia', 'Liam', 'Mia', 'Noah', 'Emma', 'Lucas'];
    const countries = ['Germany', 'Portugal', 'Japan', 'Canada', 'Kenya', 'Peru', 'France', 'India'];
    const products = ['Desk lamp', 'Notebook', 'Headphones', 'Backpack', 'Mug', 'Keyboard', 'Monitor arm', 'Plant pot'];
    const statuses = ['open', 'paid', 'shipped', 'delivered', 'refunded'];
    const day = 86_400_000;
    const start = Date.UTC(2025, 0, 1);
    // deterministic synthetic data: order i always reads the same
    const orders = Array.from({ length: 100_000 }, (_, i) => {
      const quantity = 1 + ((i * 7) % 9);
      return {
        id: 100_001 + i,
        customer: first[i % 10] + ' ' + String.fromCharCode(65 + ((i * 11) % 26)) + '.',
        country: countries[(i * 3) % 8],
        product: products[(i * 5) % 8],
        quantity,
        total: Math.round(quantity * (4 + ((i * 7919) % 9600) / 100) * 100) / 100,
        status: statuses[(i * 13) % 5],
        date: start + ((i * 37) % 640) * day,
      };
    });
    const grid = document.getElementById('dg-orders');
    df$.shadcn.dataGrid.setSource(grid, orders);
    // the query IS the store: follow it
    const line = document.getElementById('dg-orders-query');
    const describe = ({ config }) => {
      const sort = config.sorters.map((s) => s.field + ' ' + s.direction).join(', ') || 'none';
      line.textContent =
        'Sorted by: ' +
        sort +
        ' · filters: ' +
        config.filters.length +
        ' · locked: ' +
        config.locked.join(', ') +
        ' · selected: ' +
        config.selected.length;
    };
    grid.store.subscribe(describe);
    describe(grid.store.value);
  });
</script>
```

```html example label="Projection: computed columns and totals" schema="none" hint="defuss-dataview/compute projects 100,000 order lines once: a rows plan selects the fields the grid shows and computes Net (quantity × unit price × (1 − discount)), VAT (net × the country's rate) and Gross - the grid gets the projected rows. The line under it is a scalar aggregate plan over the rows the grid's filters match, run again on every filter change: type > 500 in Gross or pick a country."
<div class="flex flex-col gap-2">
  <div class="data-grid" id="dg-lines" aria-label="Order lines" data-empty-text="No lines match." style="height: 22rem">
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div
            class="data-grid-header"
            data-field="id"
            data-type="number"
            data-format=""
            data-width="6rem"
            data-filter="number"
            data-locked
            >Line</div
          >
          <div class="data-grid-header" data-field="product" data-width="10rem" data-filter="text">Product</div>
          <div class="data-grid-header" data-field="country" data-width="9rem" data-filter="select">Country</div>
          <div class="data-grid-header" data-field="quantity" data-type="number" data-width="5rem" data-filter="number"
            >Qty</div
          >
          <div
            class="data-grid-header"
            data-field="discount"
            data-type="number"
            data-format="percent"
            data-width="6rem"
            data-filter="number"
            >Discount</div
          >
          <div
            class="data-grid-header"
            data-field="net"
            data-type="number"
            data-format="currency:EUR"
            data-width="8rem"
            data-filter="number"
            >Net</div
          >
          <div
            class="data-grid-header"
            data-field="vat"
            data-type="number"
            data-format="currency:EUR"
            data-width="7rem"
            data-filter="number"
            >VAT</div
          >
          <div
            class="data-grid-header"
            data-field="gross"
            data-type="number"
            data-format="currency:EUR"
            data-width="8rem"
            data-filter="number"
            >Gross</div
          >
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
  <output class="text-sm text-muted-foreground" id="dg-lines-totals" aria-live="polite"
    >Projecting 100,000 lines…</output
  >
</div>
<script type="module">
  import {
    forRows,
    createImmutableArraySource,
  } from 'https://cdn.jsdelivr.net/npm/defuss-dataview@0.10.0/dist/browser-compute.mjs';

  addEventListener('DOMContentLoaded', async () => {
    const products = ['Desk lamp', 'Notebook', 'Headphones', 'Backpack', 'Mug', 'Keyboard', 'Monitor arm', 'Plant pot'];
    const vatRates = { Germany: 0.19, Portugal: 0.23, Japan: 0.1, Canada: 0.05, Kenya: 0.16, Peru: 0.18, France: 0.2 };
    const countries = Object.keys(vatRates);
    // deterministic synthetic order lines: line i always reads the same
    const lines = Array.from({ length: 100_000 }, (_, i) => {
      const country = countries[(i * 3) % 7];
      return {
        id: 500_001 + i,
        product: products[(i * 5) % 8],
        country,
        quantity: 1 + ((i * 7) % 9),
        unitPrice: 4 + ((i * 7919) % 9600) / 100,
        discount: [0, 0, 0.05, 0.1, 0.15][(i * 11) % 5],
        vatRate: vatRates[country],
        warehouse: 'WH-' + (1 + (i % 4)),
      };
    });

    // projection: the grid's columns, three of them computed - one pass, no per-row code of ours
    const q = forRows();
    const net = q.mul(q.mul(q.field('quantity'), q.field('unitPrice')), q.sub(q.literal(1), q.field('discount')));
    const vat = q.mul(net, q.field('vatRate'));
    const projection = q.rows({
      select: {
        id: q.field('id'),
        product: q.field('product'),
        country: q.field('country'),
        quantity: q.field('quantity'),
        discount: q.field('discount'),
        net,
        vat,
        gross: q.add(net, vat),
      },
    });
    const { rows } = await projection.evaluate(createImmutableArraySource(lines), {}, { maxOutputRows: lines.length });
    const grid = document.getElementById('dg-lines');
    df$.shadcn.dataGrid.setSource(grid, rows);

    // aggregation: one row of totals over what the grid's filters match
    const totals = q.aggregate({
      measures: {
        lines: q.count(),
        units: q.sum(q.field('quantity')),
        net: q.sum(q.field('net')),
        vat: q.sum(q.field('vat')),
        gross: q.sum(q.field('gross')),
      },
    });
    const out = document.getElementById('dg-lines-totals');
    const int = new Intl.NumberFormat('en');
    const eur = new Intl.NumberFormat('en', { style: 'currency', currency: 'EUR' });
    const data = (value, text) => '<data value="' + value + '">' + text + '</data>';
    let shown = null;
    const update = async ({ config }) => {
      const key = JSON.stringify(config.filters);
      if (key === shown) return;
      shown = key;
      const started = performance.now();
      const matching = createImmutableArraySource(df$.shadcn.dataGrid.rows(grid));
      const [sum] = (await totals.evaluate(matching)).rows;
      if (key !== shown) return; // a newer filter is on its way
      const ms = Math.round(performance.now() - started);
      df$(out).html(
        data(sum.lines, int.format(sum.lines)) +
          ' lines · ' +
          data(sum.units, int.format(sum.units)) +
          ' units · net ' +
          data(sum.net ?? 0, eur.format(sum.net ?? 0)) +
          ' · VAT ' +
          data(sum.vat ?? 0, eur.format(sum.vat ?? 0)) +
          ' · gross ' +
          data(sum.gross ?? 0, eur.format(sum.gross ?? 0)) +
          ' (' +
          ms +
          ' ms)',
      );
    };
    grid.store.subscribe(update);
    update(grid.store.value);
  });
</script>
```

```html example label="Aggregation: a report that follows the grid" schema="none" hint="An aggregate plan groups the orders the upper grid's filters match and measures each group: orders, units, revenue and its average (refunds excluded through a measure's where), the largest order and the refunds. The groups are the lower grid's rows - sort them like any grid. Filter the orders (Status: refunded, Qty > 5 ...) or group by another field."
<div class="flex flex-col gap-3">
  <div
    class="data-grid"
    id="dg-report-orders"
    aria-label="Orders"
    data-empty-text="No orders match."
    style="height: 16rem"
  >
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="id" data-type="number" data-format="" data-width="6rem">Order</div>
          <div class="data-grid-header" data-field="country" data-width="9rem" data-filter="select">Country</div>
          <div class="data-grid-header" data-field="product" data-width="10rem" data-filter="select">Product</div>
          <div class="data-grid-header" data-field="status" data-width="8rem" data-filter="select">Status</div>
          <div class="data-grid-header" data-field="quantity" data-type="number" data-width="5rem" data-filter="number"
            >Qty</div
          >
          <div
            class="data-grid-header"
            data-field="total"
            data-type="number"
            data-format="currency:EUR"
            data-width="8rem"
            data-filter="number"
            >Total</div
          >
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
  <div class="flex flex-wrap items-center gap-2">
    <label class="label" for="dg-report-by">Group by</label>
    <select class="select w-auto" id="dg-report-by">
      <option value="country" selected>Country</option>
      <option value="product">Product</option>
      <option value="status">Status</option>
    </select>
    <output class="text-sm text-muted-foreground" id="dg-report-line" aria-live="polite"></output>
  </div>
  <div class="data-grid" id="dg-report" aria-label="Report" data-empty-text="No groups." style="height: 14rem">
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="group" data-width="minmax(9rem, 1fr)">Group</div>
          <div class="data-grid-header" data-field="orders" data-type="number" data-width="6rem">Orders</div>
          <div class="data-grid-header" data-field="units" data-type="number" data-width="6rem">Units</div>
          <div
            class="data-grid-header"
            data-field="revenue"
            data-type="number"
            data-format="currency:EUR"
            data-width="9rem"
            >Revenue</div
          >
          <div
            class="data-grid-header"
            data-field="average"
            data-type="number"
            data-format="currency:EUR"
            data-width="8rem"
            >Avg order</div
          >
          <div
            class="data-grid-header"
            data-field="largest"
            data-type="number"
            data-format="currency:EUR"
            data-width="8rem"
            >Largest</div
          >
          <div class="data-grid-header" data-field="refunds" data-type="number" data-width="6rem">Refunds</div>
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
</div>
<script type="module">
  import {
    forRows,
    createImmutableArraySource,
  } from 'https://cdn.jsdelivr.net/npm/defuss-dataview@0.10.0/dist/browser-compute.mjs';

  addEventListener('DOMContentLoaded', () => {
    const countries = ['Germany', 'Portugal', 'Japan', 'Canada', 'Kenya', 'Peru', 'France', 'India'];
    const products = ['Desk lamp', 'Notebook', 'Headphones', 'Backpack', 'Mug', 'Keyboard', 'Monitor arm', 'Plant pot'];
    const statuses = ['open', 'paid', 'shipped', 'delivered', 'refunded'];
    // a deterministic pseudo-random number in [0, n) for row i and a salt: row i always reads the same
    const pick = (i, salt, n) => {
      let h = Math.imul(i + 1, 0x9e3779b1) ^ Math.imul(salt + 1, 0x85ebca6b);
      h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d);
      h = Math.imul(h ^ (h >>> 12), 0x297a2d39);
      return ((h ^ (h >>> 15)) >>> 0) % n;
    };
    // synthetic orders: some countries and products sell more than others
    const orders = Array.from({ length: 100_000 }, (_, i) => {
      const product = Math.min(pick(i, 2, 8), pick(i, 3, 8));
      const quantity = 1 + pick(i, 4, 9);
      return {
        id: 100_001 + i,
        country: countries[Math.min(pick(i, 1, 8), pick(i, 5, 8))],
        product: products[product],
        status: statuses[pick(i, 6, 12) < 1 ? 4 : pick(i, 7, 4)],
        quantity,
        total: Math.round(quantity * (4 + 6 * product + pick(i, 8, 4800) / 100) * 100) / 100,
      };
    });
    const grid = document.getElementById('dg-report-orders');
    const report = document.getElementById('dg-report');
    const by = document.getElementById('dg-report-by');
    const line = document.getElementById('dg-report-line');
    df$.shadcn.dataGrid.setSource(grid, orders);

    // one prepared plan per grouping: prepare once, evaluate on every change
    const q = forRows();
    const kept = q.neq(q.field('status'), q.literal('refunded'));
    const plans = {};
    const plan = (field) =>
      (plans[field] ??= q.aggregate({
        groupBy: { group: q.field(field) },
        measures: {
          orders: q.count(),
          units: q.sum(q.field('quantity')),
          revenue: q.sum(q.field('total'), { where: kept }),
          average: q.avg(q.field('total'), { where: kept }),
          largest: q.max(q.field('total')),
          refunds: q.count(undefined, { where: q.not(kept) }),
        },
        orderBy: [{ field: 'revenue', direction: 'desc' }],
      }));

    let run = 0;
    const update = async () => {
      const mine = ++run;
      const started = performance.now();
      const matching = df$.shadcn.dataGrid.rows(grid);
      const { rows, summary } = await plan(by.value).evaluate(
        createImmutableArraySource(matching),
        {},
        { count: 'exact' },
      );
      if (mine !== run) return; // a newer filter or grouping is on its way
      df$.shadcn.dataGrid.setSource(report, rows, { idField: 'group' });
      line.textContent =
        summary.totalResultRows +
        ' groups of ' +
        matching.length.toLocaleString('en') +
        ' orders · ' +
        Math.round(performance.now() - started) +
        ' ms · strategy ' +
        summary.strategy;
    };
    let filters = null;
    grid.store.subscribe(({ config }) => {
      const key = JSON.stringify(config.filters);
      if (key === filters) return;
      filters = key;
      update();
    });
    by.addEventListener('change', update);
    filters = JSON.stringify(grid.store.value.config.filters);
    update();
  });
</script>
```

```html example label="Arranging columns" schema="none" hint="Every header has an arrow at its end: its menu sorts, locks the column and lists every column with a checkbox to show or hide it (Email starts hidden - the header carries hidden). Drag a header to move the column - into the locked group it locks -, drag a header's end edge to resize it. On a phone or tablet hold a header until it lifts, then drag it, or let go for the menu. The arrangement is the query (columns, hidden, widths, locked): the panel below only subscribes to the store, Reset columns writes the authored one back."
<div class="flex flex-col gap-3">
  <div class="data-grid" id="dg-arrange" aria-label="People" style="height: 15rem">
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="id" data-type="number" data-format="" data-width="5rem" data-locked>
            ID
          </div>
          <div class="data-grid-header" data-field="name" data-width="10rem">Name</div>
          <div class="data-grid-header" data-field="email" data-width="14rem" hidden>Email</div>
          <div class="data-grid-header" data-field="team" data-width="8rem">Team</div>
          <div class="data-grid-header" data-field="city" data-width="8rem">City</div>
          <div class="data-grid-header" data-field="since" data-type="number" data-format="" data-width="6rem"
            >Since</div
          >
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
  <div class="flex flex-wrap items-center gap-2">
    <button class="btn" data-variant="outline" data-size="sm" type="button" id="dg-arrange-reset">Reset columns</button>
  </div>
  <pre
    class="text-xs m-0 overflow-x-auto"
    id="dg-arrange-json"
    style="padding: 0.75rem; border-radius: var(--radius-md); background: var(--muted)"
  ></pre>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const first = ['Ada', 'Grace', 'Linus', 'Margaret', 'Ken', 'Barbara', 'Dennis', 'Frances'];
    const last = ['Lovelace', 'Hopper', 'Torvalds', 'Hamilton', 'Thompson', 'Liskov', 'Ritchie', 'Allen'];
    const teams = ['Platform', 'Search', 'Payments', 'Mobile', 'Data'];
    const cities = ['Berlin', 'Lisbon', 'Austin', 'Osaka', 'Nairobi', 'Toronto'];
    const people = Array.from({ length: 5_000 }, (_, i) => {
      const name = first[i % 8] + ' ' + last[(i * 3) % 8];
      return {
        id: i + 1,
        name,
        email: name.toLowerCase().replace(' ', '.') + (i + 1) + '@example.org',
        team: teams[(i * 7) % 5],
        city: cities[(i * 5) % 6],
        since: 2012 + ((i * 11) % 13),
      };
    });
    const grid = document.getElementById('dg-arrange');
    const { dataGrid } = df$.shadcn;
    dataGrid.setSource(grid, people);
    document.getElementById('dg-arrange-reset').addEventListener('click', () => dataGrid.resetColumns(grid));
    const json = document.getElementById('dg-arrange-json');
    grid.store.subscribe(
      ({ config }) => {
        json.textContent = JSON.stringify(
          { columns: config.columns, locked: config.locked, hidden: config.hidden, widths: config.widths },
          null,
          1,
        );
      },
      { immediate: true },
    );
  });
</script>
```

```html example label="The store is the query" schema="none" hint="Everything the grid shows is el.store.value.config - plain JSON. These buttons only write the query (df$.shadcn.dataGrid.query merges into it); the panel below only subscribes to the store. The grid does the rest."
<div class="flex flex-col gap-3">
  <div class="flex flex-wrap gap-2">
    <button class="btn" data-variant="outline" data-size="sm" type="button" data-q="top">Top revenue</button>
    <button class="btn" data-variant="outline" data-size="sm" type="button" data-q="eu">EU only</button>
    <button class="btn" data-variant="outline" data-size="sm" type="button" data-q="lock">Lock name + region</button>
    <button class="btn" data-variant="ghost" data-size="sm" type="button" data-q="reset">Reset</button>
  </div>
  <div class="data-grid" id="dg-driven" aria-label="Accounts" style="height: 16rem">
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="name" data-width="11rem">Account</div>
          <div class="data-grid-header" data-field="region" data-width="7rem">Region</div>
          <div
            class="data-grid-header"
            data-field="revenue"
            data-type="number"
            data-format="currency:USD"
            data-width="9rem"
            >Revenue</div
          >
          <div class="data-grid-header" data-field="growth" data-type="number" data-format="percent" data-width="7rem"
            >Growth</div
          >
          <div class="data-grid-header" data-field="owner" data-width="9rem">Owner</div>
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
  <pre
    class="text-xs m-0 overflow-x-auto"
    id="dg-driven-json"
    style="padding: 0.75rem; border-radius: var(--radius-md); background: var(--muted)"
  ></pre>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const regions = ['EU', 'NA', 'APAC', 'LATAM'];
    const owners = ['Ana', 'Ben', 'Chen', 'Dara'];
    const accounts = Array.from({ length: 20_000 }, (_, i) => ({
      id: i + 1,
      name: 'Account ' + (i + 1),
      region: regions[(i * 3) % 4],
      revenue: (i * 7919) % 2_000_000,
      growth: (((i * 37) % 80) - 20) / 100,
      owner: owners[(i * 5) % 4],
    }));
    const grid = document.getElementById('dg-driven');
    const { dataGrid } = df$.shadcn;
    dataGrid.setSource(grid, accounts);
    const queries = {
      top: { sorters: [{ field: 'revenue', direction: 'desc' }] },
      eu: { filters: [{ field: 'region', op: 'eq', value: 'EU' }] },
      lock: { locked: ['name', 'region'] },
      reset: { sorters: [], filters: [], locked: [] },
    };
    document
      .querySelectorAll('[data-q]')
      .forEach((button) => button.addEventListener('click', () => dataGrid.query(grid, queries[button.dataset.q])));
    const json = document.getElementById('dg-driven-json');
    grid.store.subscribe(
      ({ config }) => {
        json.textContent = JSON.stringify(
          { sorters: config.sorters, filters: config.filters, locked: config.locked },
          null,
          1,
        );
      },
      { immediate: true },
    );
  });
</script>
```

```html example label="A kept view" schema="none" hint="Every grid keeps its sort, filters, the arrangement of its columns (order, lock, visibility, widths) and open rows - in session storage by default, under a generated key (data-persist-prefix sets its start, data-persist-key the whole key). data-persist='local' keeps them across visits, 'none' keeps nothing; setSource's persist option does the same from code. data-sort on a header is the starting sort. This sandboxed example has no storage (the store falls back to memory), so instead of reloading: sort, filter, move or hide a column, then mount a fresh grid - it comes back as you left it."
<div class="flex flex-col gap-3" style="max-width: 36rem">
  <button class="btn" data-variant="outline" data-size="sm" type="button" id="dg-remount" style="align-self: flex-start"
    >Mount a fresh grid</button
  >
  <div id="dg-kept-host"></div>
</div>
<template id="dg-kept-template">
  <div
    class="data-grid"
    id="dg-kept"
    aria-label="Cities"
    data-persist="local"
    data-persist-key="docs:cities-grid"
    style="height: 14rem"
  >
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="city" data-width="minmax(9rem, 1fr)" data-filter="text">City</div>
          <div class="data-grid-header" data-field="country" data-width="8rem" data-filter="select">Country</div>
          <div class="data-grid-header" data-field="population" data-type="number" data-width="9rem" data-sort="desc"
            >Population</div
          >
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
</template>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const countries = ['Germany', 'Japan', 'Brazil', 'Kenya', 'Canada'];
    const cities = Array.from({ length: 10_000 }, (_, i) => ({
      id: i + 1,
      city: 'City ' + (i + 1),
      country: countries[(i * 3) % 5],
      population: 10_000 + ((i * 7919) % 5_000_000),
    }));
    const host = document.getElementById('dg-kept-host');
    // a new instance of the same markup reads the kept view on init
    const mount = () => {
      host.replaceChildren(document.getElementById('dg-kept-template').content.cloneNode(true));
      df$.shadcn.dataGrid.setSource(host.querySelector('.data-grid'), cities);
    };
    document.getElementById('dg-remount').addEventListener('click', mount);
    mount();
  });
</script>
```

```html example label="Loading and empty" schema="none" hint="A grid without records waits in 'loading' (skeleton rows, aria-busy); a query nothing matches lands in 'empty' with data-empty-text."
<div class="flex flex-wrap gap-4">
  <div class="data-grid" aria-label="Waiting for data" style="height: 11rem; flex: 1; min-width: 14rem">
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="name" data-width="minmax(8rem, 1fr)">Name</div>
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
  <div
    class="data-grid"
    id="dg-empty"
    aria-label="No matches"
    data-empty-text="Nothing matches 'zebra'."
    style="height: 11rem; flex: 1; min-width: 14rem"
  >
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="name" data-width="minmax(8rem, 1fr)">Name</div>
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const grid = document.getElementById('dg-empty');
    df$.shadcn.dataGrid.setSource(grid, [
      { id: 1, name: 'Lion' },
      { id: 2, name: 'Tiger' },
    ]);
    df$.shadcn.dataGrid.query(grid, { filters: [{ field: 'name', op: 'contains', value: 'zebra' }] });
  });
</script>
```

<StatesSection>
  <p class="text-sm text-muted-foreground m-0 mb-3">Named states via the shared State API, driven per instance through the bound <code>api</code>; the config of every state is the query (<code>filters</code>, <code>sorters</code>, <code>locked</code>, <code>page</code>, <code>expanded</code>, <code>collapsed</code>, <code>selected</code>), merged on each <code>setState</code> and observable as <code>el.store</code>:</p>
  <ul class="text-sm text-muted-foreground m-0 mb-3 ps-5">
    <li><code>default</code> - the rows of the query; a query nothing matches lands in <code>empty</code></li>
    <li><code>loading</code> - <code>aria-busy="true"</code> and skeleton rows; a grid without records starts here</li>
    <li><code>empty</code> - no rows: the <code>data-empty-text</code> message</li>
  </ul>
  <p class="text-sm text-muted-foreground">The first example carries <code>data-state-demo</code>; <code>bun run screenshots</code> drives it via <code>el.api.setState(name)</code> and captures <code>screenshots/\{mode\}/data-grid-\{state\}.png</code>.</p>

Machine contract - verified against <a class="link" href="../schemas/data-grid.schema.json"><code>data-grid.schema.json</code></a> by <code>bun run verify</code>:

```states
| State | Type | Values | Default | Description |
| --- | --- | --- | --- | --- |
| `loading` | `boolean` | `true`, `false` | `false` | aria-busy with skeleton rows (`setState('loading')`). |
| `empty` | `boolean` | `true`, `false` | `false` | No rows - shows data-empty-text (`setState('empty')`). |
```

</StatesSection>

<ApiSection component="data-grid" />

<SourceFiles component="data-grid" section="css" />

<SourceFiles component="data-grid" section="js" jsTitle="JS" />

</DocPage>
