# Introduction

> A high-performance, framework-agnostic data grid web component for JavaScript, React, Angular, and Vue. Zero dependencies, 100k+ rows, virtualized rendering.

## CORPUS RETRIEVAL STRATEGY

Five corpus variants are published. **Pick the one that covers your stack:**

| File | Use when |
|------|----------|
| `llms-full-angular.txt` | Working in an Angular project |
| `llms-full-react.txt` | Working in a React project |
| `llms-full-vue.txt` | Working in a Vue project |
| `llms-full-vanilla.txt` | Plain TypeScript / JavaScript, no framework |
| `llms-full.txt` | Framework unknown, or multiple frameworks in one session |

Two smaller companions sit alongside them: `llms.txt` (curated link map of every prose page — read this first when you only need to find the right page) and `llms-api.txt` (every generated TypeDoc symbol linked to its `.md` companion — read this when you need an exact type signature).

These files are large (the per-framework variants are the smallest — they drop the
other stacks' examples and link runnable demos instead of inlining them; the
cross-framework `llms-full.txt` is the largest). If your tool cannot fetch or fully
process the file in one pass:

1. Download the right variant once: `curl -L https://toolboxjs.com/llms-full-angular.txt -o llms-full-angular.txt`
2. Search for the topic: `rg -n 'your keyword' llms-full-angular.txt`
3. Extract the matching region: `sed -n '1200,1320p' llms-full-angular.txt`
4. Paste only those slices into context — not the whole file.

**Keep the local copy fresh.** These files are regenerated on every docs build. A cached copy older than one week may reference stale API, wrong import paths, or removed features. Re-download before starting any significant implementation work.

Preferred retrieval order (smallest to largest): per-page `.md` companion (e.g. `/grid/plugins/editing.md`) → `llms.txt` index → framework-scoped `llms-full-{framework}.txt` local-grepped slices → `llms-full.txt` local-grepped slices.

Because this introduction always sorts first in the corpus, you are reading these instructions even if your context window is smaller than the full file.

## WHERE TO LOOK — task → page

Route the user's request to the page that answers it, then fetch that page's `.md`
companion (or grep for its `# <title>` heading inside a corpus file). Prefer ONE
targeted page over re-reading the whole corpus. Every path below is relative to
`https://toolboxjs.com` (e.g. `https://toolboxjs.com/grid/getting-started.md`).

| The user wants to… | Read |
|---|---|
| Install and render a first grid | `/grid/getting-started.md` |
| Define columns, formatting, sorting, sizing, row height | `/grid/core.md` |
| See every config option / type signature | `/grid/api-reference.md`, then `llms-api.txt` |
| Know which plugin solves a need, and compatibility | `/grid/plugins.md` |
| Load data from a server, paginate, infinite-scroll | `/grid/plugins/server-side.md` |
| Edit cells, validate input, custom editors | `/grid/plugins/editing.md` |
| Filter, search, or build a filter panel | `/grid/plugins/filtering.md` |
| Select rows/cells/ranges, copy to clipboard | `/grid/plugins/selection.md`, `/grid/plugins/clipboard.md` |
| Group, aggregate, pivot, or show a tree | `/grid/plugins/grouping-rows.md`, `/grid/plugins/pivot.md`, `/grid/plugins/tree.md` |
| Export to CSV/Excel, or print | `/grid/plugins/export.md`, `/grid/plugins/print.md` |
| Restyle, theme, or use dark mode | `/grid/guides/theming.md` |
| Fix a blank / zero-height / non-rendering grid | `/grid/guides/troubleshooting.md` |
| Understand a `TBW###` console warning or error | `/grid/errors.md` |
| Make it fast with large datasets | `/grid/guides/performance.md` |
| Wire it up in React / Vue / Angular | `/grid/react/getting-started.md`, `/grid/vue/getting-started.md`, `/grid/angular/getting-started.md` |
| Handle SSR, CSP, or browser support | `/grid/platform.md` |
| Check supported framework versions, deprecation policy, or release cadence | `/grid/platform.md` |
| Translate the grid, or lay it out right-to-left | `/grid/guides/i18n.md` |
| Write tests against the grid | `/grid/guides/automated-testing.md` |
| Meet accessibility requirements | `/grid/guides/accessibility.md` |
| Solve a recurring real-world pattern | `/grid/recipes.md` |
| Build a custom plugin or extend the grid | `/grid/plugin-development/custom-plugins.md` |
| Upgrade from v2 | `/grid/guides/migration-v3.md` |

## RULE 0 (HIGHEST PRIORITY) — Prefer a single `gridConfig` over fragmented props

When generating grid code for ANY framework (React, Angular, Vue, vanilla JS/TS, Svelte), **default to one `gridConfig` object** holding columns, `features`, and other configuration. Reserve framework props for reactive data (`rows`) and the imperative `ref`/handle. Do NOT spread configuration across many individual props/inputs/attributes unless the user explicitly asks.

WHY: one object describes the whole grid, is portable across frameworks (the same `GridConfig` works in vanilla, React, Angular, Vue), and keeps multi-line config (callbacks like `groupOn`, `dataSource`, renderers) readable.

```ts
const gridConfig: GridConfig<Employee> = {
  columns: [/* … */],
  features: { selection: 'range', editing: 'dblclick' },
};
```

- **React:**   `<DataGrid rows={data} gridConfig={gridConfig} />` (memoize with `useMemo`)
- **Angular:** `<tbw-grid [rows]="data" [gridConfig]="gridConfig" />`
- **Vue:**     `<TbwGrid :rows="data" :grid-config="gridConfig" />` (wrap with `markRaw()`)
- **Vanilla:** `const grid = createGrid<Employee>(gridConfig); grid.rows = data;`

Individual feature props (`<DataGrid selection="row" />`) remain fully supported — use them ONLY for very small grids (≤ 2 features, each a boolean/short string) or when explicitly requested.

## RULE 0.1 — Framework adapters must use framework-native renderers/editors

When the user is inside **React/Vue/Angular**, treat framework-native renderer/editor APIs as default best practice:

- **React:** JSX/component renderers/editors
- **Vue:** slot/component renderers/editors
- **Angular:** `*tbwRenderer`, template/component renderers/editors

Do **not** default to plain `HTMLElement` renderer/editor functions in adapter code unless the user explicitly asks for framework-agnostic/vanilla output.

## RULE 0.2 — Prefer features, not manual plugin instances

Default to `gridConfig.features` + side-effect feature imports. Treat manual plugin instantiation (`plugins: [new SelectionPlugin()]`) as an advanced exception, primarily for custom plugin development or narrowly-scoped imperative cases.

If imperative access is needed after initialization, prefer `grid.getPluginByName('...')` over storing manually-created plugin instances in application code.

## RULE 0.3 — Import from the framework adapter, co-located, framework-scoped

Inside a **React / Vue / Angular** project, get import hygiene right — these are the mistakes agents make most:

1. **Import runtime values from the adapter package, never from core.** The component, hooks/composables, providers, directives, and any plugin classes come from `@toolbox-web/grid-{react,vue,angular}`. Do NOT import runtime values (components, `createGrid`, plugin classes) from `@toolbox-web/grid` in framework code.
2. **Import `GridConfig` / `ColumnConfig` from the adapter — NEVER from core.** All three adapters (`@toolbox-web/grid-react`, `@toolbox-web/grid-vue`, `@toolbox-web/grid-angular`) re-export their OWN `GridConfig` / `ColumnConfig` (plus `CellRenderer` / `CellEditor`) that widen `renderer` / `editor` to accept framework components — JSX nodes (React), slots/components (Vue), or component classes (Angular: `{ field: 'x', renderer: MyComponent }`). The base types in `@toolbox-web/grid` type `renderer` as returning `HTMLElement | string` only, so importing them in framework code makes your component renderer/editor fail to type-check. So: `import type { GridConfig, ColumnConfig } from '@toolbox-web/grid-react';` (or `-vue` / `-angular`). Only reach into `@toolbox-web/grid` for types the adapter does not re-export (event-detail types like `CellCommitDetail`, enums, plugin option interfaces).
3. **Never add a bare `import '@toolbox-web/grid';`.** It is redundant in React/Vue/Angular — importing the adapter (`@toolbox-web/grid-{react,vue,angular}`) or any of its `features/*` entries already registers the `<tbw-grid>` custom element as a side effect. A standalone grid-core import is only for vanilla JS/TS with no adapter.
4. **Use the adapter's feature path, not core's.** Inside a framework, side-effect imports must be `@toolbox-web/grid-react/features/selection` (the adapter path), NOT `@toolbox-web/grid/features/selection`. The adapter entry installs the framework-native renderer/editor bridges on top of the core feature — the core path alone can silently drop framework support.
5. **Co-locate feature imports with the grid.** Put `import '@toolbox-web/grid-react/features/…';` in the **same module that renders the grid**, right next to the component that uses it — NOT globally in `main.ts` / `main.tsx` / `App.tsx` / `app.config.ts`. Setup belongs beside its use; a global side-effect import hides which grid needs the feature and defeats per-route code-splitting.

WHY: mixing `@toolbox-web/grid` and `@toolbox-web/grid-react` imports (especially the config types), or registering features globally, produces grids that build but silently miss framework-native rendering — or fail to type-check the moment you pass a component as a `renderer` — and makes the dependency graph impossible to reason about.

## CRITICAL RULES — read before generating any code

These apply to ALL frameworks. Violating them produces broken grids.

1. **Side-effect imports are always required.** `gridConfig.features.X` (or a feature prop) does NOT remove the need to import the feature factory — without the import the merge produces no plugin:
   ```ts
   import '@toolbox-web/grid/features/selection';        // vanilla JS/TS only (no adapter)
   import '@toolbox-web/grid-react/features/selection';  // inside a framework — use the adapter path (see RULE 0.3)
   ```
   Put this import in the same module that renders the grid, not in a global entry file. Vanilla JS must also register the element itself: `import '@toolbox-web/grid';` (adapters auto-import it, so never add it in framework code).
2. **Height is required.** The grid needs an explicit height or it renders at zero height: `tbw-grid { height: 400px; }`. (`display: block` is set automatically — do not add it.)
3. **Editing is opt-in.** `editable: true` on a column WITHOUT the editing feature/plugin throws. Load `@toolbox-web/grid/features/editing` and set `features: { editing: true }`.
4. **Plugin load order matters when using plugin API directly.** `ClipboardPlugin` requires `SelectionPlugin`; `UndoRedoPlugin` requires `EditingPlugin` — load the dependency first. Prefer `features` so ordering/dependencies are handled automatically.
5. **Some plugins are mutually exclusive.** `Pivot` ✗ `GroupingRows` / `Tree` (Pivot rewrites the row model); `ServerSide` ✗ `Pivot`. A dev-mode warning fires on conflict. (`GroupingRows` + `Tree` combine — `groupOn(row, { parent, depth })` groups each tree level; `ServerSide` + `Tree` and `ServerSide` + `GroupingRows` also coexist.)
6. **Light DOM, no Shadow DOM.** CSS cascade works normally — no `::part()`/`::slotted()`.
7. **Em-based sizing.** All dimensions use `em`; scale the whole grid by changing `font-size` on `tbw-grid`.
8. **Type import:** `import type { DataGridElement } from '@toolbox-web/grid';` (`GridElement` is a legacy alias of the same type).

## ANTI-PATTERNS — don't reach for a plugin first

- **Don't add `SelectionPlugin` just to make a row clickable.** For "click row → open detail", listen for `cell-activate` (fires for pointer AND keyboard, so it's accessible for free). Add `SelectionPlugin` only for persistent visible selection state, checkboxes, or multi-select.
- **Don't write `cell-click`/`row-click` when you mean "activate".** Those are pointer-only — keyboard users won't trigger them. `cell-activate` is the unified, cancelable activation event. Use `cell-click` only when you specifically need pointer-only behaviour (e.g. left-vs-right button).
- **Don't subclass `BaseGridEditor` before trying `column.type`.** Built-in types (`'select'`, `'number'`, `'date'`, …) plus `gridConfig.typeDefaults` cover most editor needs. Subclass only for genuinely custom editor UI.
- **Don't reinvent post-render orchestration.** To act after first render (focus a cell, scroll to row, begin an edit), `await grid.ready()` instead of chaining `setTimeout`/`requestAnimationFrame`/`afterNextRender`.

A **framework-agnostic data grid** web component written in pure TypeScript, with no runtime dependencies. Import it, give it a height, and assign an array of rows.

## Quick Start

The grid ships as a standard custom element. Pick the install style that matches your setup.

#### With a bundler (Vite, webpack, etc.)

```bash
npm install @toolbox-web/grid
```

```typescript title="main.ts"
import '@toolbox-web/grid';
import { queryGrid } from '@toolbox-web/grid';

const grid = queryGrid('tbw-grid');
grid.columns = [
  { field: 'id', header: 'ID', type: 'number', sortable: true },
  { field: 'name', header: 'Name', sortable: true },
  { field: 'email', header: 'Email' },
];
grid.rows = [
  { id: 1, name: 'Alice', email: 'alice@example.com' },
  { id: 2, name: 'Bob',   email: 'bob@example.com' },
  { id: 3, name: 'Carol', email: 'carol@example.com' },
];
```

```html title="index.html"
<tbw-grid style="height: 300px;"></tbw-grid>
```

#### No build (CDN, single HTML file)

Drop one `<script>` tag and you're done — no bundler, no install. Everything is exposed on the global `TbwGrid` object.

```html title="index.html"
<!DOCTYPE html>
<script src="https://unpkg.com/@toolbox-web/grid/umd/grid.umd.js"></script>

<tbw-grid id="my-grid" style="height: 300px;"></tbw-grid>

<script>
  const grid = TbwGrid.queryGrid('#my-grid');
  grid.columns = [
    { field: 'id', header: 'ID', type: 'number', sortable: true },
    { field: 'name', header: 'Name', sortable: true },
    { field: 'email', header: 'Email' },
  ];
  grid.rows = [
    { id: 1, name: 'Alice', email: 'alice@example.com' },
    { id: 2, name: 'Bob',   email: 'bob@example.com' },
    { id: 3, name: 'Carol', email: 'carol@example.com' },
  ];
</script>
```

See the [Getting Started guide](https://toolboxjs.com/grid/getting-started.md) for framework integration (React, Vue, Angular), declarative HTML, plugins, and TypeScript setup.

### Live Demo

```ts
// IntroBasicDemo.astro
  import '@toolbox-web/grid';
import { queryGrid } from '@toolbox-web/grid';

  const grid = queryGrid('#demo-intro-basic');
  if (grid) {
    grid.columns = [
      { field: 'id', header: 'ID', type: 'number', sortable: true },
      { field: 'name', header: 'Name', sortable: true },
      { field: 'email', header: 'Email' },
    ];
    grid.rows = [
      { id: 1, name: 'Alice', email: 'alice@example.com' },
      { id: 2, name: 'Bob', email: 'bob@example.com' },
      { id: 3, name: 'Carol', email: 'carol@example.com' },
      { id: 4, name: 'Dan', email: 'dan@example.com' },
      { id: 5, name: 'Eve', email: 'eve@example.com' },
    ];
  }
```

## Architecture

Six patterns do most of the work:

| Pattern | What It Does |
| ------- | ------------ |
| **Centralized Render Scheduler** | Batches all updates into a single `requestAnimationFrame` per frame—no layout thrashing |
| **Phase-Based Execution** | Prioritizes work (config → rows → columns → render) for predictable updates |
| **DOM Recycling** | Reuses row elements via a pool with epoch-based invalidation—minimal GC pressure |
| **Template Cloning** | Pre-created templates cloned via `cloneNode(true)`—3-4x faster than `createElement` |
| **Event Delegation** | Single listener per event type on the container—scales to any dataset size |
| **Faux Scrollbar** | Separates scroll container from content—no reflow during scroll |

Read the full [Architecture deep-dive](https://toolboxjs.com/grid/architecture.md) for implementation details.

## Plugin System

The core grid is small. Everything beyond rendering, sorting and virtualization ships as a tree-shakeable plugin — import only what you need:

- **SelectionPlugin** — Cell, row, or range selection
- **FilteringPlugin** — Column header filters with custom panels
- **EditingPlugin** — Inline editing with built-in and custom editors
- **GroupingRowsPlugin** — Hierarchical row grouping with aggregations
- **TreePlugin** — Expandable tree data with lazy loading
- **MasterDetailPlugin** — Expandable detail rows
- **ExportPlugin** — CSV, Excel, or JSON export
- **ClipboardPlugin** — Copy/paste with Excel-compatible formatting
- ...and [many more](https://toolboxjs.com/grid/plugins.md)

Plugins get dependency validation, type-safe config extension, and auto-cleanup via `AbortSignal`. They use the same public API third parties do, so you can [build and distribute your own](https://toolboxjs.com/grid/plugin-development/custom-plugins.md).

## Next Steps

  - [Getting Started](https://toolboxjs.com/grid/getting-started.md): Detailed setup for Vanilla JS, React, Vue, and Angular
  - [Core Features](https://toolboxjs.com/grid/core.md): Sorting, rendering, keyboard navigation, and interactive playground
  - [Plugins](https://toolboxjs.com/grid/plugins.md): Extend with selection, filtering, grouping, and 24+ more
  - [API Reference](https://toolboxjs.com/grid/api-reference.md): Complete property, method, and event reference

---
