# Birch UI documentation (v0.1) > Birch UI is a family of framework-agnostic JavaScript UI components built on one vanilla TypeScript engine: Birch UI Grid (MIT data grid), Grid Pro (grouping, aggregation, pivot, tree data, range selection, clipboard, Excel export), the Excel Engine (xlsx reader and writer), the Scheduler (resource timeline), Gantt (project scheduling with dependencies and critical path), the Event Calendar (month, week, day, agenda and year views with recurrence), Charts (canvas charts with SVG and PNG export), Diagram (flow and diagram editor with auto-layout), the Spreadsheet (Excel-compatible formula engine and editor), the Document Editor (paginated Word-style editor with DOCX import and export, track changes and comments), PDF (PDF viewer and annotation editor with forms, page tools and save), Pivot Studio (pivot report builder for BI embeds) and Forms (MIT JSON form renderer with a commercial visual Form Builder). Adapters exist for React, Vue, Angular, Svelte, Solid and Web Components. Paid products are a one-time purchase per developer with free updates forever, unlimited apps and unlimited end users. --- Source: https://docs.birchui.com/getting-started/introduction/ # Introduction > What Birch UI is, which products it includes, and what is free versus paid. Birch UI is a set of JavaScript components for data-heavy business applications: a data grid, an analytics layer on top of it, a pivot report builder, an Excel engine, a resource scheduler, a Gantt chart, an event calendar, charts, a diagram editor, a spreadsheet, and a form renderer with a visual form builder. Every product is written once in vanilla TypeScript and works the same in React, Vue, Angular, Svelte, Solid, as a Web Component, or with no framework at all. The core grid and the form renderer are MIT-licensed and free. The paid products are a **one-time purchase per developer with free updates forever**, including major versions. There is no subscription, no renewal and no limit on apps or end users. **Live demo: Orders grid** (runs on the HTML version of this page). Source of `demos/basic-grid.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { docsTheme, formatCurrency, makeOrders, onDocsThemeChange, revenueOf, type Order } from './_shared'; export const meta = { title: 'Orders grid', height: 420 }; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 180 }, { field: 'region', header: 'Region', width: 140 }, { field: 'product', header: 'Product', width: 190 }, { field: 'quantity', header: 'Qty', type: 'number', width: 80 }, { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency }, { field: 'orderDate', header: 'Ordered', type: 'date', width: 120 }, ]; export default function mount(el: HTMLElement): () => void { const grid = createGrid(el, { columns, rows: makeOrders(500), getRowId: (order) => order.id, theme: docsTheme(), ariaLabel: 'Customer orders', }); const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { stopTheme(); grid.destroy(); }; } ``` ## Products | Product | Package | License | What it does | | --- | --- | --- | --- | | Birch UI Grid | `@birchui/core` | MIT, free | Virtualized data grid: sorting, filtering, quick filter, inline editing, column resize, reorder, pin and hide, row selection, pagination, CSV export, keyboard navigation and ARIA, light and dark themes. | | Grid Pro | `@birchui/grid-pro` | Commercial, $349 | Row grouping, aggregation, tree data, pivot mode, range selection, clipboard copy and paste, fill handle, master/detail, status bar, styled Excel export and import. | | Pivot Studio | `@birchui/pivot-studio` | Commercial, $349 | A pivot-first report builder for embedded analytics: drag fields into rows, columns, values and filters, with subtotals, drill-through, conditional formatting, saved reports, styled Excel export and optional pivot charts. Runs in the browser with no server. | | Excel Engine | `@birchui/excel` | Commercial, $299, included with Grid Pro | Standalone xlsx writer and reader with styles, number formats, merged cells, freeze panes, outlines and autofilter. Runs in a worker or in Node. | | Scheduler | `@birchui/scheduler` | Commercial, $399 | Resource timeline with drag, resize and drag-to-create, snapping, zoom presets, overlap lanes, working-time shading, time zones and virtualization in both directions. | | Gantt | `@birchui/gantt` | Commercial, $399 | Project scheduling with a task tree and timeline: critical-path scheduling on working calendars, FS, SS, FF and SF links with lag, constraints, baselines, MS Project XML import and export, and a headless engine. Its task grid is the free Birch UI Grid, so it needs no Grid Pro license. | | Event Calendar | `@birchui/calendar` | Commercial, $299 | Month, week, day, N-day, agenda and year views with RFC 5545 recurrence, IANA time zones, iCalendar import and export, and drag, resize and select-to-create. | | Charts | `@birchui/charts` | Commercial, $299 | Canvas charts: line, area, column and bar, scatter and bubble, pie and donut, heatmap, combination charts with a secondary axis, and sparklines. SVG and PNG export, and charts from a Grid Pro range. | | Diagram | `@birchui/diagram` | Commercial, $399 | Flow and diagram editor with ports, orthogonal edge routing around obstacles, layered, tree, force and grid auto-layout, groups and swimlanes, a minimap, undo and redo, and SVG, PNG and JSON export. | | Spreadsheet | `@birchui/spreadsheet` | Commercial, $399 | Embeddable spreadsheet with an Excel-compatible formula engine (over 300 functions, dynamic arrays, incremental recalculation), a virtualized keyboard-complete component and `.xlsx` round-trips. | | Forms | `@birchui/forms` | MIT, free | Renders accessible multi-page forms from a JSON schema, with conditional logic, computed fields, repeatable sections, validation, i18n, and JSON Schema import and export. | | Form Builder | `@birchui/forms/builder` | Commercial, $349 | A visual, keyboard-accessible designer for form schemas, with drag and drop, a property panel, an expression editor, undo and redo, a JSON view and a live preview. | | Framework adapters | `@birchui/react`, `vue`, `angular`, `svelte`, `solid`, `element` | MIT, free | Thin wrappers that turn the grid and scheduler into native components for your framework. The same factories wrap Pivot Studio, Gantt, the Event Calendar, Charts, Diagram, Spreadsheet, Forms and the Form Builder. | | License | `@birchui/license` | MIT, free | Offline key verification. Installed automatically with the paid packages. | See [Pricing](https://docs.birchui.com/getting-started/pricing.md) for seat tiers and bundles. ## Free and paid features Birch UI Grid covers what most CRUD screens and admin tables need. Grid Pro adds the features that turn a table into an analysis tool. The split is by feature, not by row count or performance: the free grid scrolls a million rows just as fast as the paid one. | You need | Free grid | Grid Pro | | --- | --- | --- | | Large datasets with row and column virtualization | Yes | Yes | | Sorting, multi-column sorting, filters, quick filter | Yes | Yes | | Inline editing with text, number, select, checkbox and date editors | Yes | Yes | | Pinned, resizable, reorderable and hideable columns | Yes | Yes | | Row selection with checkboxes, pagination, CSV export | Yes | Yes | | Row grouping with a drag-and-drop group panel | | Yes | | Aggregation (`sum`, `avg`, `min`, `max`, `count`, `first`, `last`, `distinct`, custom) | | Yes | | Tree data and pivot tables with totals | | Yes | | Range selection, clipboard copy and paste, fill handle | | Yes | | Master/detail rows, status bar | | Yes | | Styled Excel export and import | | Yes | Paid features are never locked. Without a license key they work fully: widgets show a small watermark on non-local hosts, and the Excel Engine only logs a console warning. Read [Licensing and activation](https://docs.birchui.com/getting-started/licensing.md) for the details. ## How it is built Every Birch UI product follows one widget contract. You create a widget on a container element and get back an object you can update, listen to and destroy: ```ts title="orders-grid.ts" import { createGrid } from '@birchui/core'; interface Order { id: string; customer: string; region: 'EMEA' | 'Americas' | 'APAC'; total: number; } const grid = createGrid(document.querySelector('#orders')!, { columns: [ { field: 'id', header: 'Order', width: 120 }, { field: 'customer', header: 'Customer', flex: 1 }, { field: 'region', header: 'Region', filter: 'set' }, { field: 'total', header: 'Total', type: 'number', align: 'right' }, ], rows: [ { id: 'SO-10421', customer: 'Northwind Traders', region: 'EMEA', total: 1840.5 }, { id: 'SO-10422', customer: 'Contoso Ltd', region: 'Americas', total: 312 }, ], getRowId: (order) => order.id, }); grid.on('cellValueChanged', ({ row, colId, newValue }) => { console.info(`Order ${row.id}: ${colId} is now ${String(newValue)}`); }); grid.update({ theme: 'dark' }); ``` The framework adapters are small wrappers around this contract, so a feature that ships in the engine is available in every framework on the same day. The same applies to every other product: `createScheduler`, `createGantt`, `createPivotStudio`, `createCalendar`, `createChart`, `createDiagram`, `createSpreadsheet`, `createForm` and `createFormBuilder` all return widgets with the same `update`, `on` and `destroy` methods. Other design rules you can rely on: - **ESM only and tree-shakeable.** Paid features are separate modules that you register with `modules: [...]`, so you only ship what you use. - **SSR-safe.** Importing a package never touches `window` or `document`. DOM work starts when you create a widget. - **No Shadow DOM.** Your CSS reaches every cell. Theming uses CSS custom properties prefixed `--lq-`. - **Accessible.** The grid follows the WAI-ARIA grid and treegrid patterns, keeps `aria-rowcount` and `aria-rowindex` correct while virtualized, and uses a roving tabindex. - **Your callbacks cannot break the widget.** If an event listener, renderer or other callback throws, the error is reported with `console.error` and the widget keeps working. - **No network calls.** License checks run offline in the browser. ## Where to go next - [Installation](https://docs.birchui.com/getting-started/installation.md) lists the packages for each product and how styles are loaded. - [Quick start](https://docs.birchui.com/getting-started/quick-start.md) builds the same orders grid in each framework. - [Birch UI Grid overview](https://docs.birchui.com/grid/overview.md) walks through columns, rows, sorting, filtering and editing. - [Grid Pro overview](https://docs.birchui.com/grid-pro/overview.md) covers grouping, pivoting and Excel export. - [Pivot Studio overview](https://docs.birchui.com/pivot-studio/overview.md) covers the report builder for end users. - [Scheduler overview](https://docs.birchui.com/scheduler/overview.md) covers the resource timeline. - [Gantt overview](https://docs.birchui.com/gantt/overview.md) covers tasks, dependencies and the critical path. - [Event Calendar overview](https://docs.birchui.com/calendar/overview.md) covers month, week, day, agenda and year views. - [Charts overview](https://docs.birchui.com/charts/overview.md) covers chart types, axes and export. - [Diagram overview](https://docs.birchui.com/diagram/overview.md) covers nodes, edges, routing and auto-layout. - [Spreadsheet overview](https://docs.birchui.com/spreadsheet/overview.md) covers formulas, sheets and xlsx files. - [Forms overview](https://docs.birchui.com/forms/overview.md) covers the free form renderer and the Form Builder. - Switching from another grid? See [Migrating from AG Grid](https://docs.birchui.com/getting-started/migrating-from-ag-grid.md) or [Migrating from MUI X](https://docs.birchui.com/getting-started/migrating-from-mui-x.md). > **Using a coding assistant?** > > Every page of these docs is also available as plain Markdown: add `.md` to the page URL, for example `/grid/sorting.md`. The [llms.txt](https://docs.birchui.com/llms.txt) file lists every page, and [llms-full.txt](https://docs.birchui.com/llms-full.txt) contains the whole documentation in one file. --- Source: https://docs.birchui.com/getting-started/installation/ # Installation > Install the Birch UI packages for each product and framework, and choose between auto-injected styles and a CSS import. All Birch UI packages are published to npm under the `@birchui` scope. They are ESM only, ship their own TypeScript types and have no runtime dependencies apart from each other (and `@noble/ed25519` inside the license package). ## Pick your packages Install the engine for the product you use, plus the adapter for your framework. Plain JavaScript and TypeScript apps need only the engine. ### Birch UI Grid (free) **npm** ```bash npm install @birchui/core ``` **pnpm** ```bash pnpm add @birchui/core ``` **yarn** ```bash yarn add @birchui/core ``` ### Grid Pro Grid Pro builds on the free grid. The Excel Engine and the license package are installed with it as dependencies, so you do not list them yourself. **npm** ```bash npm install @birchui/core @birchui/grid-pro ``` **pnpm** ```bash pnpm add @birchui/core @birchui/grid-pro ``` **yarn** ```bash yarn add @birchui/core @birchui/grid-pro ``` ### Pivot Studio Pivot Studio renders its pivot table with Birch UI Grid and exports through the Excel Engine; both are installed with it. Add `@birchui/charts` only if you use pivot charts from the `@birchui/pivot-studio/charts` entry point. **npm** ```bash npm install @birchui/core @birchui/pivot-studio ``` **pnpm** ```bash pnpm add @birchui/core @birchui/pivot-studio ``` **yarn** ```bash yarn add @birchui/core @birchui/pivot-studio ``` ### Excel Engine on its own Use the Excel Engine without a grid to generate or read `.xlsx` files in the browser, in a worker or in Node. **npm** ```bash npm install @birchui/excel ``` **pnpm** ```bash pnpm add @birchui/excel ``` **yarn** ```bash yarn add @birchui/excel ``` ### Scheduler **npm** ```bash npm install @birchui/core @birchui/scheduler ``` **pnpm** ```bash pnpm add @birchui/core @birchui/scheduler ``` **yarn** ```bash yarn add @birchui/core @birchui/scheduler ``` ### Gantt The Gantt shares its time axis with the Scheduler package, which is installed with it as a dependency. Its task grid is the free Birch UI Grid, and neither a Scheduler nor a Grid Pro license is needed. **npm** ```bash npm install @birchui/gantt ``` **pnpm** ```bash pnpm add @birchui/gantt ``` **yarn** ```bash yarn add @birchui/gantt ``` ### Event Calendar **npm** ```bash npm install @birchui/calendar ``` **pnpm** ```bash pnpm add @birchui/calendar ``` **yarn** ```bash yarn add @birchui/calendar ``` ### Charts **npm** ```bash npm install @birchui/core @birchui/charts ``` **pnpm** ```bash pnpm add @birchui/core @birchui/charts ``` **yarn** ```bash yarn add @birchui/core @birchui/charts ``` ### Diagram **npm** ```bash npm install @birchui/core @birchui/diagram ``` **pnpm** ```bash pnpm add @birchui/core @birchui/diagram ``` **yarn** ```bash yarn add @birchui/core @birchui/diagram ``` ### Spreadsheet The Spreadsheet reads and writes `.xlsx` files through the Excel Engine, which is installed with it as a dependency. **npm** ```bash npm install @birchui/core @birchui/spreadsheet ``` **pnpm** ```bash pnpm add @birchui/core @birchui/spreadsheet ``` **yarn** ```bash yarn add @birchui/core @birchui/spreadsheet ``` ### Forms and the Form Builder The free renderer and the paid Form Builder ship in one package. Import the renderer from `@birchui/forms` and the builder from `@birchui/forms/builder`. **npm** ```bash npm install @birchui/forms ``` **pnpm** ```bash pnpm add @birchui/forms ``` **yarn** ```bash yarn add @birchui/forms ``` ## Framework adapters Each adapter wraps every product. The grid component comes from the main entry point; the scheduler component comes from the `/scheduler` subpath, so grid-only apps never load scheduler code. | Framework | Package | Peer dependency | Grid import | Scheduler import | | --- | --- | --- | --- | --- | | React | `@birchui/react` | `react` and `react-dom` 18 or later | `BirchGrid` from `@birchui/react` | `BirchScheduler` from `@birchui/react/scheduler` | | Vue | `@birchui/vue` | `vue` 3.3 or later | `BirchGrid` from `@birchui/vue` | `BirchScheduler` from `@birchui/vue/scheduler` | | Angular | `@birchui/angular` | `@angular/core` 17.3 or later | `BirchGridComponent` from `@birchui/angular` | `BirchSchedulerComponent` from `@birchui/angular/scheduler` | | Svelte | `@birchui/svelte` | `svelte` 5 or later | `BirchGrid` and the `birchGrid` action from `@birchui/svelte` | `BirchScheduler` from `@birchui/svelte/scheduler` | | Solid | `@birchui/solid` | `solid-js` 1.8 or later | `BirchGrid` from `@birchui/solid` | `BirchScheduler` from `@birchui/solid/scheduler` | | Web Component | `@birchui/element` | none | `defineBirchGrid()` from `@birchui/element` | `defineBirchScheduler()` from `@birchui/element/scheduler` | For example, a React app that uses Grid Pro: ```bash npm install @birchui/core @birchui/grid-pro @birchui/react ``` `@birchui/scheduler` is an optional peer dependency of every adapter. Install it only when you use the scheduler component. The Svelte components ship as `.svelte` source and are resolved through the `svelte` export condition, which Vite and SvelteKit use by default. The adapters have no entry points for Pivot Studio, Gantt, the Event Calendar, Charts, Diagram, Spreadsheet or Forms. Use `createPivotStudio`, `createGantt`, `createCalendar`, `createChart`, `createDiagram`, `createSpreadsheet`, `createForm` and `createFormBuilder` directly, or wrap `pivotStudioDefinition`, `ganttDefinition`, `calendarDefinition`, `chartDefinition`, `diagramDefinition`, `spreadsheetDefinition`, `formDefinition` or `formBuilderDefinition` with your adapter's factory (`createReactComponent`, `createVueComponent`, `createSolidComponent`, `createSvelteAction` or `createElementRegistration`). Each framework guide shows how. See the [Pivot Studio](https://docs.birchui.com/pivot-studio/overview.md), [Gantt](https://docs.birchui.com/gantt/overview.md), [Event Calendar](https://docs.birchui.com/calendar/overview.md), [Charts](https://docs.birchui.com/charts/overview.md), [Diagram](https://docs.birchui.com/diagram/overview.md), [Spreadsheet](https://docs.birchui.com/spreadsheet/overview.md) and [Forms](https://docs.birchui.com/forms/overview.md) overviews. ## Styles Every widget needs its stylesheet. You can let Birch UI inject it, or import the CSS file yourself. ### Auto-injected styles (default) When you create a grid or scheduler, Birch UI adds a single ` ``` **Solid** (`OrdersGrid.tsx`) ```tsx import { BirchGrid } from '@birchui/solid'; import type { GridApi } from '@birchui/core'; import { columns, getRowId, orders, type Order } from './orders'; export function OrdersGrid() { let grid: GridApi | undefined; return ( <> ref={(api) => (grid = api)} style={{ height: '420px' }} columns={columns} rows={orders} getRowId={getRowId} floatingFilters rowSelection="multiple" checkboxSelection onCellValueChanged={({ row, colId, newValue }) => console.info(row.id, colId, newValue)} /> ); } ``` **Web Component** (`index.html`) ```html ``` **JavaScript** (`main.ts`) ```ts import { createGrid } from '@birchui/core'; import { columns, getRowId, orders, type Order } from './orders'; const container = document.querySelector('#orders')!; container.style.height = '420px'; const grid = createGrid(container, { columns, rows: orders, getRowId, floatingFilters: true, rowSelection: 'multiple', checkboxSelection: true, }); grid.on('cellValueChanged', ({ row, colId, newValue }) => console.info(row.id, colId, newValue)); document.querySelector('#export')?.addEventListener('click', () => { grid.downloadCsv({ fileName: 'orders.csv' }); }); ``` > **Give the grid a height** > > The grid virtualizes its rows, so it needs a container with a height. Use a fixed height, `height: 100%` inside a sized parent, or a flex or grid layout that gives it space. ## 4. Try it With the grid on screen: - **Sort:** click a header. Shift-click another header to add a second sort column. - **Filter:** type in the row under the headers. In the Total column, try `>1000` or `300..2000`. - **Edit:** double-click a customer or status cell, or focus it and start typing. Press Enter to commit or Escape to cancel. - **Select:** tick the checkboxes, or use the header checkbox to select every row. - **Navigate:** click a cell, then move with the arrow keys. The full key map is in [Keyboard navigation and accessibility](https://docs.birchui.com/grid/accessibility.md). - **Resize and reorder:** drag a header edge to resize, or drag a header to move the column. ## 5. Update the data Keep a reference to the grid API and change rows without rebuilding the grid: ```ts grid.applyTransaction({ add: [{ id: 'SO-10427', customer: 'Proseware Inc', region: 'EMEA', placedAt: '2026-11-08', status: 'open', total: 1330 }], update: [{ ...orders[0], status: 'shipped' }], remove: ['SO-10423'], }); ``` Rows are matched by the id from `getRowId`, so only the rows that changed are updated and selection stays with the same rows. See [Updating data](https://docs.birchui.com/grid/updating-data.md). ## Next steps - Learn what each column option does in [Columns](https://docs.birchui.com/grid/columns.md). - Read your framework guide: [React](https://docs.birchui.com/frameworks/react.md), [Vue](https://docs.birchui.com/frameworks/vue.md), [Angular](https://docs.birchui.com/frameworks/angular.md), [Svelte](https://docs.birchui.com/frameworks/svelte.md), [Solid](https://docs.birchui.com/frameworks/solid.md) or [Web Component](https://docs.birchui.com/frameworks/web-component.md). - Add grouping, aggregation and Excel export with [Grid Pro](https://docs.birchui.com/grid-pro/overview.md). - Switch themes and density in [Theming](https://docs.birchui.com/grid/theming.md). --- Source: https://docs.birchui.com/getting-started/examples/ # Examples gallery > Sixteen complete starter apps, one per framework and product, that you can open in StackBlitz, clone, or copy out of the repository. Every starter in the repository's `examples/` folder is a standalone npm project that installs the published `@birchui/*` packages. Open one in StackBlitz to try it in the browser, or copy the folder and run it locally. Each one is small enough to read in a few minutes and shows one product wired into one framework the way you would ship it. ```sh cd examples/react-vite-grid-pro npm install npm run dev ``` ## Data grid | Starter | Stack | Licence | What it shows | Open | | --- | --- | --- | --- | --- | | `react-vite-grid-pro` | React, Vite | Grid Pro | 5,000 sales orders grouped by region and country with sum aggregates and a totals row, a drag-and-drop group panel, range selection, copy as TSV and a status bar | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/react-vite-grid-pro) · [Source](https://github.com/OWNER/REPO/tree/main/examples/react-vite-grid-pro) | | `nextjs-app-router-grid` | Next.js App Router | MIT | A server component loads 2,000 orders and hands them to a `"use client"` grid; quick search, floating filters, inline editing, pagination, selection and CSV export | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/nextjs-app-router-grid) · [Source](https://github.com/OWNER/REPO/tree/main/examples/nextjs-app-router-grid) | | `vue-vite-grid-pro` | Vue 3, Vite | Grid Pro | Grouping with subtotals and a group panel, plus a checkbox that switches the same grid into pivot mode; rows held in a `shallowRef` | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/vue-vite-grid-pro) · [Source](https://github.com/OWNER/REPO/tree/main/examples/vue-vite-grid-pro) | | `nuxt-grid` | Nuxt | MIT | A Nitro server route returns orders, `useFetch` loads them during server rendering, and the grid mounts inside `` | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/nuxt-grid) · [Source](https://github.com/OWNER/REPO/tree/main/examples/nuxt-grid) | | `angular-grid-pro` | Angular 21 | Grid Pro | A standalone, zoneless, `OnPush` component with signal inputs; grouping, range selection, clipboard, status bar and Excel export | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/angular-grid-pro) · [Source](https://github.com/OWNER/REPO/tree/main/examples/angular-grid-pro) | | `sveltekit-grid` | SvelteKit, Svelte 5 | MIT | A prerendered page whose `load` provides 2,000 orders, the `` component with runes and `bind:api`, and the `use:birchGrid` action | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/sveltekit-grid) · [Source](https://github.com/OWNER/REPO/tree/main/examples/sveltekit-grid) | | `solid-vite-grid` | Solid, Vite | MIT | A grid driven by signals and `createMemo` filters, inline editing, and CSV export through the API `ref` | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/solid-vite-grid) · [Source](https://github.com/OWNER/REPO/tree/main/examples/solid-vite-grid) | | `vanilla-web-component-grid` | Web Components | MIT | `` declared in HTML, configured through properties and attributes, with DOM `CustomEvent`s and a typed element | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/vanilla-web-component-grid) · [Source](https://github.com/OWNER/REPO/tree/main/examples/vanilla-web-component-grid) | ## Scheduling and planning | Starter | Stack | Licence | What it shows | Open | | --- | --- | --- | --- | --- | | `react-scheduler` | React, Vite | Scheduler | A dispatch board with six technicians in two depots and 75 jobs; drag, resize and drag-to-create, working-time shading, a Europe/London time zone, 15-minute snapping and drop validation | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/react-scheduler) · [Source](https://github.com/OWNER/REPO/tree/main/examples/react-scheduler) | | `vue-scheduler` | Vue 3, Vite | Scheduler | The same dispatch board with jobs in a `shallowRef`, `@event-drop` and `@event-create` handlers, and a computed hours-booked figure | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/vue-scheduler) · [Source](https://github.com/OWNER/REPO/tree/main/examples/vue-scheduler) | | `angular-scheduler` | Angular 21 | Scheduler | `` in a standalone, zoneless app, jobs in a signal updated from `(eventDrop)`, and `(eventCreate)` booking a callout | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/angular-scheduler) · [Source](https://github.com/OWNER/REPO/tree/main/examples/angular-scheduler) | | `vanilla-gantt` | TypeScript, Vite | Gantt | An office fit-out programme with three phases, FS and SS links with lag, milestones and bank holidays; critical path, undo and redo, zoom | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/vanilla-gantt) · [Source](https://github.com/OWNER/REPO/tree/main/examples/vanilla-gantt) | ## Analytics, documents and forms | Starter | Stack | Licence | What it shows | Open | | --- | --- | --- | --- | --- | | `react-pivot-studio` | React, Vite | Pivot Studio | A pivot report over 20,000 orders with data bars, a status filter, drill-through and the pivot chart; the report is saved to `localStorage` on every change | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/react-pivot-studio) · [Source](https://github.com/OWNER/REPO/tree/main/examples/react-pivot-studio) | | `vanilla-spreadsheet` | TypeScript, Vite | Spreadsheet | A delivery project budget with `SUM`, `SUMIF`, percentage shares and `XLOOKUP`, frozen panes, number formats and header styles | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/vanilla-spreadsheet) · [Source](https://github.com/OWNER/REPO/tree/main/examples/vanilla-spreadsheet) | | `vanilla-charts` | TypeScript, Vite | Charts | A revenue dashboard with grouped bars, an area chart against a target line and a donut; stacking toggled at runtime, `pointClick` events and PNG or SVG download | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/vanilla-charts) · [Source](https://github.com/OWNER/REPO/tree/main/examples/vanilla-charts) | | `react-form-builder` | React, Vite | Form Builder | The visual Form Builder editing a two-page booking form, with a live preview rendered by the MIT form renderer on every `schemaChange` | [StackBlitz](https://stackblitz.com/github/OWNER/REPO/tree/main/examples/react-form-builder) · [Source](https://github.com/OWNER/REPO/tree/main/examples/react-form-builder) | ## Licence keys in the starters Commercial products work without a key. They show a small watermark on hosts other than `localhost` and log one console warning. Every starter reads its key from an environment variable listed in its `.env.example`: | Stack | Variable | | --- | --- | | Vite (React, Vue, Solid, SvelteKit, plain TypeScript) | `VITE_BIRCHUI_LICENSE_KEY` | | Next.js | `NEXT_PUBLIC_BIRCHUI_LICENSE_KEY` | | Nuxt | `NUXT_PUBLIC_BIRCHUI_LICENSE_KEY` | | Angular CLI | `BIRCHUI_LICENSE_KEY` | Never commit a real key. See [Licensing](https://docs.birchui.com/getting-started/licensing.md) for how keys are verified offline. > **Tip** > > In StackBlitz, add the variable under **Settings → Environment variables** or create a `.env.local` file in the project root, then restart the dev server. ## Opening a starter elsewhere CodeSandbox imports the same folders: replace `stackblitz.com/github/` with `codesandbox.io/p/github/` and drop `/tree` from the path. To use a starter as the base of a new app, copy its folder out of the repository; it has no links back to the monorepo. ## Next steps - [Quick start](https://docs.birchui.com/getting-started/quick-start.md) walks through the grid from an empty page. - The framework guides cover [React](https://docs.birchui.com/frameworks/react.md), [Vue](https://docs.birchui.com/frameworks/vue.md), [Angular](https://docs.birchui.com/frameworks/angular.md), [Svelte](https://docs.birchui.com/frameworks/svelte.md), [Solid](https://docs.birchui.com/frameworks/solid.md) and [Web Components](https://docs.birchui.com/frameworks/web-component.md). - The [Recipes](https://docs.birchui.com/recipes.md) section has task-focused guides for every product. --- Source: https://docs.birchui.com/getting-started/licensing/ # Licensing and activation > How Birch UI license keys work, how to activate them, what the watermark does, and who needs a seat. Birch UI's paid products are licensed **per developer, as a one-time purchase, with free updates forever**. A license key is a signed string that you set once in your app. It is checked offline, it never expires, and it never switches features off. ## The short version - **Free to evaluate.** Every paid feature works without a key. Unlicensed widgets show a small watermark on non-local hosts and log one console warning. The Excel Engine, which has no widget, only logs the warning. - **One-time purchase.** You pay once per developer seat. There is no subscription and no renewal. - **Free updates forever.** Paid keys have no expiry date, so a key bought today works with every future version, major releases included. - **Unlimited apps and end users.** Use your license in as many internal tools, customer-facing apps and SaaS deployments as you like. - **Offline.** Keys are verified in the browser with an embedded public key. Birch UI never makes a network request. - **Seats are for developers who write code against Birch UI.** Colleagues who only build, test or deploy the app do not need a seat. ## Which packages need a key | Package | Product id | Needs a key | | --- | --- | --- | | `@birchui/core` | none | No, MIT | | `@birchui/react`, `vue`, `angular`, `svelte`, `solid`, `element` | none | No, MIT | | `@birchui/license` | none | No, MIT | | `@birchui/grid-pro` | `grid-pro` | Yes | | `@birchui/pivot-studio` | `pivot-studio` | Yes. Watermark and console warning. Covers the Excel Engine; it does not need a Grid Pro key. Pivot charts from `@birchui/pivot-studio/charts` need a Charts or Complete key | | `@birchui/excel` | `excel` | Yes. Keys for Grid Pro, Pivot Studio, Spreadsheet or all products (`*`) also cover it. Console warning only, never a watermark | | `@birchui/scheduler` | `scheduler` | Yes | | `@birchui/gantt` | `gantt` | Yes. Watermark and console warning. Needs no Scheduler or Grid Pro key, even though it uses the scheduler's time axis and the free grid | | `@birchui/calendar` | `calendar` | Yes. Watermark and console warning, like the grid and scheduler | | `@birchui/charts` | `charts` | Yes. Watermark and console warning | | `@birchui/diagram` | `diagram` | Yes. Watermark and console warning | | `@birchui/spreadsheet` | `spreadsheet` | Yes. Watermark and console warning. A Spreadsheet key also covers the Excel Engine | | `@birchui/forms` (renderer) | none | No, MIT. The renderer never checks a key | | `@birchui/forms/builder` (Form Builder) | `forms` | Yes. Watermark and console warning | The free grid and the form renderer never check a key, never show a watermark and never log a license warning. Only the paid packages do. A Birch UI Complete key (`products: ["*"]`) covers every paid product, Pivot Studio, Gantt, Charts, Diagram, Spreadsheet and the Form Builder included. A Project Suite key covers the Scheduler, the Gantt and the Event Calendar. ## Activate your key ### Option 1: set it once at startup (recommended) Call `setLicenseKey` before or after your widgets are created. Widgets that are already on the page re-check the new key and remove their watermark, so the order does not matter. ```ts title="main.ts" import { setLicenseKey } from '@birchui/license'; setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY); ``` Where to call it in each framework: **React** (`main.tsx`) ```tsx import { createRoot } from 'react-dom/client'; import { setLicenseKey } from '@birchui/license'; import { App } from './App'; setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY); createRoot(document.getElementById('root')!).render(); ``` **Vue** (`main.ts`) ```vue import { createApp } from 'vue'; import { setLicenseKey } from '@birchui/license'; import App from './App.vue'; setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY); createApp(App).mount('#app'); ``` **Angular** (`main.ts`) ```ts import { bootstrapApplication } from '@angular/platform-browser'; import { setLicenseKey } from '@birchui/license'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; import { environment } from './environments/environment'; setLicenseKey(environment.birchLicenseKey); bootstrapApplication(AppComponent, appConfig).catch((error) => console.error(error)); ``` **Svelte** (`src/routes/+layout.svelte`) ```svelte {@render children()} ``` **Solid** (`index.tsx`) ```tsx import { render } from 'solid-js/web'; import { setLicenseKey } from '@birchui/license'; import { App } from './App'; setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY); render(() => , document.getElementById('root')!); ``` **JavaScript** (`main.ts`) ```ts import { setLicenseKey } from '@birchui/license'; import { mountReports } from './reports'; setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY); mountReports(document.querySelector('#reports')!); ``` In Next.js, expose the key as `NEXT_PUBLIC_BIRCHUI_LICENSE_KEY` and call `setLicenseKey(process.env.NEXT_PUBLIC_BIRCHUI_LICENSE_KEY)` at the top of a Client Component that wraps your app, or in the module that renders your grid. Calling it on the server is harmless; it simply has no widgets to update there. ### Option 2: pass it to a widget Every paid widget accepts a `licenseKey` option: the grid (for Grid Pro), Pivot Studio, the scheduler, the Gantt, the event calendar, charts, the diagram, the spreadsheet and the Form Builder. A key passed this way applies to that widget only, and that widget ignores the global key. ```ts title="regional-sales.ts" import { createGrid } from '@birchui/core'; import { AllProModules } from '@birchui/grid-pro'; const grid = createGrid(document.querySelector('#regional-sales')!, { columns: [ { field: 'region', header: 'Region', rowGroup: true }, { field: 'revenue', header: 'Revenue', type: 'number', aggFunc: 'sum' }, ], modules: AllProModules, licenseKey: 'LQ1.eyJ2IjoxLCJpZCI6ImxpY18zZjlh…', }); ``` Use this when one app holds two separate keys, for example a Grid Pro key and an Event Calendar key bought at different times: set one globally with `setLicenseKey` and pass the other through `licenseKey` on the widgets that need it. ### The Excel Engine `@birchui/excel` checks its key offline too, the first time you write or read a workbook. It uses the global key from `setLicenseKey`, or a key you pass in the options: ```ts title="export-invoices.ts" import { downloadXlsx, readXlsx, writeXlsx, type XlsxWorkbook } from '@birchui/excel'; const licenseKey = import.meta.env.VITE_BIRCHUI_LICENSE_KEY; export async function exportInvoices(workbook: XlsxWorkbook) { await downloadXlsx(workbook, 'invoices-2026-11.xlsx', { licenseKey }); } export async function invoiceBytes(workbook: XlsxWorkbook) { return writeXlsx(workbook, { licenseKey }); } export async function importPriceList(file: File) { return readXlsx(file, { licenseKey }); } ``` `writeXlsxSync(workbook, { licenseKey })` takes the same option. Each distinct key is checked once per page or process. Because the Excel Engine has no visible widget, an unlicensed copy never shows a watermark. It logs one console warning per page and works normally: ```text [Birch UI] No license key is set for Birch UI Excel Engine. All features keep working. Purchase a license at https://birchui.com/pricing ``` A key for `excel` activates it, and so does a key for Grid Pro, Pivot Studio, Spreadsheet or all products (`*`). Grid Pro's Excel export and import pass the grid's own key to the engine, so a Grid Pro key covers them without extra setup. > **Web workers and Node** > > A worker or a Node process has its own copy of `@birchui/license`, so a key set with `setLicenseKey` on the main page does not reach it. Call `setLicenseKey` inside the worker, or pass `licenseKey` to `writeXlsx` and `readXlsx` there. > **The key is not a secret** > > A license key identifies the licensee and is verified offline, so it is meant to ship in your client bundle. Treat it like a serial number, not a password. Keeping it in an environment variable is still convenient, because it keeps the key out of your repository history. ## What happens without a valid key Nothing stops working. When a paid widget finds no key, or a key that does not cover it: 1. **All features keep working**, exactly as with a key. 2. **One console warning** is logged per product per page load. It states the reason and links to the pricing page, for example: `[Birch UI] No license key is set for Birch UI Grid Pro. All features keep working; a watermark is shown on non-local hosts until a valid license key is set. Purchase a license at https://birchui.com/pricing` 3. **A small watermark** appears in the bottom-right corner of the widget, such as "Birch UI Grid Pro · unlicensed copy". It ignores the pointer and is hidden from assistive technology. As soon as a valid key is set, the watermark is removed from every widget on the page without a reload. The Excel Engine skips step 3: it only logs the warning, because it has nothing on screen to mark. The reasons a key can be rejected: | Status | Meaning | What to do | | --- | --- | --- | | `missing` | No key is set | Call `setLicenseKey` or pass `licenseKey` | | `malformed` | The string is not a Birch UI key: wrong prefix, bad encoding or invalid payload | Copy the key again in full; whitespace and line breaks are ignored | | `bad-signature` | The key was altered or not issued by Birch UI | Use the key exactly as issued | | `wrong-product` | The key is valid but does not include this product | Use the key for this product, or pass it per widget | | `expired` | A trial key is past its last day | Buy a license; the trial watermark reads "trial expired" | ### Localhost and development No watermark is shown when the page runs on a local host: `localhost`, `127.0.0.1`, `[::1]`, any `*.localhost` or `*.local` name, `file:` pages, and during server rendering. The console warning is still logged once, so you notice a missing key before you deploy. Staging and preview hosts, such as `staging.example.com` or a Vercel preview URL, are not local. Set the key there too. ## Offline verification A key is verified entirely in the browser (or in Node): - The signature is checked with Ed25519 against a public key embedded in `@birchui/license`. - It uses WebCrypto when available and falls back to a bundled implementation on plain-HTTP intranet pages, where `crypto.subtle` does not exist. - There are no network requests, no telemetry and no activation server. Air-gapped networks and offline apps work the same as any other. - Importing the package never touches `window`, `document` or `location`, so it is safe for server rendering. ## Key format A key looks like this: ```text LQ1.. ``` - `LQ1` is the format prefix. - `payload` is the unpadded base64url encoding of a UTF-8 JSON object. - `signature` is the unpadded base64url encoding of the 64-byte Ed25519 signature over the ASCII bytes of `LQ1.`. The payload fields: | Field | Meaning | | --- | --- | | `v` | Format version, always `1` | | `id` | License id, for example `lic_3f9a0c2e7b14d685` | | `to` | Licensee, for example `Northwind Traders` | | `email` | Optional contact address | | `products` | Product ids such as `["grid-pro", "scheduler"]`, or `["*"]` for every product, including future ones | | `seats` | Number of developer seats | | `tier` | `developer`, `team`, `company`, `oem` or `trial` | | `iat` | Issue date, `YYYY-MM-DD` | | `exp` | Trial keys only: last valid day, `YYYY-MM-DD`, inclusive, in UTC | Paid keys never carry `exp`. That is how "free updates forever" works without a license server: there is no date after which a paid key stops being valid. ## Inspect a key in code `verifyLicenseKey` checks a key against a product and resolves to a result object. It is asynchronous because signature verification uses WebCrypto. ```ts title="license-status.ts" import { verifyLicenseKey } from '@birchui/license'; const result = await verifyLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY, 'grid-pro'); if (result.status === 'valid') { console.info(`${result.message} Seats: ${result.license?.seats}`); } else { console.warn(`Grid Pro license problem (${result.status}): ${result.message}`); } ``` `decodeLicenseKey` reads the payload without checking the signature, which is handy for showing "Licensed to Northwind Traders" in an about dialog. Do not use it to decide whether a key is genuine. ```ts import { decodeLicenseKey, licenseCovers } from '@birchui/license'; const payload = decodeLicenseKey(key); if (payload && licenseCovers(payload, 'excel')) { console.info(`Excel Engine licensed to ${payload.to}`); } ``` **`LicenseCheck`** (interface from `@birchui/license`, full reference: https://docs.birchui.com/api/license.md) ```ts interface LicenseCheck ``` | Property | Type | Description | | --- | --- | --- | | `status` | `LicenseStatus` | | | `product` | `ProductId` | | | `license?` | `LicensePayload` | | | `message` | `string` | | **`LicensePayload`** (interface from `@birchui/license`, full reference: https://docs.birchui.com/api/license.md) ```ts interface LicensePayload ``` | Property | Type | Description | | --- | --- | --- | | `v` | `1` | | | `id` | `string` | | | `to` | `string` | | | `email?` | `string` | | | `products` | `(ProductId \| '*')[]` | | | `seats` | `number` | | | `tier` | `LicenseTier` | | | `iat` | `string` | | | `exp?` | `string` | | The full list of functions is in the [@birchui/license API reference](https://docs.birchui.com/api/license.md). ## Trials You can evaluate without any key: see [What happens without a valid key](#what-happens-without-a-valid-key). If you want to try a paid product without the watermark, for example on a staging server you show to stakeholders, request a trial key. It arrives by email and is valid for 30 days. Each email address can hold one active trial per product. Trial keys use the `trial` tier and carry an `exp` date. Until that day ends (UTC) they behave like a paid key. Afterwards the widget logs one warning and shows a "trial expired" watermark. Features still work, so an expired trial never breaks a demo in front of a customer. Add your paid key once you buy; nothing else changes in your code. ## Seats: who needs one A seat is for a **developer who writes code that uses Birch UI**: someone who configures the grid or scheduler, writes column definitions, event handlers or cell renderers, or maintains a wrapper component around them. You do **not** need a seat for colleagues who only: - build, compile or deploy the app, including CI servers and release engineers; - work on other parts of the codebase, such as the backend or unrelated front-end screens; - test the app, design it or use it. Each tier covers a different team shape: | Tier | Covers | Notes | | --- | --- | --- | | Developer | One named developer | | | Team | Up to 5 developers | Seats are transferable when people change roles | | Company | Unlimited developers in one organization | Priority email and read access to the private source repository | | OEM | Products that expose Birch UI to *their* customers' developers | For low-code platforms, admin-panel builders and component libraries. Quoted individually | Every tier includes unlimited apps, unlimited end users and unlimited deployments: internal tools, customer-facing apps and multi-tenant SaaS alike. See [Pricing](https://docs.birchui.com/getting-started/pricing.md) for prices. ## Lifetime updates Your license covers every release of the products you bought, forever, including major versions. You do not need to renew to upgrade, and there is no "licensed version" to stay on. Upgrading is a normal `npm install`. ## Getting your key 1. **Checkout.** Payment is handled by Paddle, the merchant of record, which charges any sales tax or VAT and issues your invoice. 2. **License email.** When the order completes, your key is emailed to the address you used at checkout. The email lists, for each product you bought, the licensee name, the tier and seats, the license ID, the key itself, the packages to install and a snippet that activates the key. 3. **One key per product line.** An order with Grid Pro and the Scheduler gives you two keys. Seats are the quantity times the seats in the tier: a Team license covers 5 developers per unit, a Company license an unlimited number. 4. **Support packs** come without a key. Open a ticket on the support site and quote your order reference. ### The licensee name The licensee (`to` in the payload) is the company name you entered at checkout, or your email address if you did not enter one. The payload can be read by anyone who opens your JavaScript bundle, so if your key carries your email address and you would rather it showed your company, reissue it from the license portal with a different licensee name. ### The license portal Every license email links to the license portal. Sign in with the email address you bought with: the portal emails you a sign-in link, which expires after a short time. The portal lists your active licenses and their keys, so it is also where you recover a lost key. From the portal you can **reissue** a key, for example after a company name change. The new key keeps the same license ID, products, tier and seats. Because keys are verified offline, the previous key keeps working too; switch to the new one at your convenience. ## Troubleshooting - **The watermark is still visible after setting the key.** Check the console warning: it names the status. `wrong-product` usually means a Scheduler key was used for Grid Pro, or the other way round. - **No watermark locally, but one in production.** The key is missing from the production build. Check that the environment variable is defined at build time (Vite and Next.js inline public variables during the build). - **Two products, two keys.** Pass the second key with the widget's `licenseKey` option. - **Lost key.** Sign in to the license portal with the email address you bought with; it lists every active key. - **The warning appears twice.** It is logged once per product. Grid Pro and Scheduler each log their own. --- Source: https://docs.birchui.com/getting-started/pricing/ # Pricing > One-time prices per developer for every Birch UI product and bundle, with seat tiers, support packs and lifetime updates. Every paid Birch UI product is a **one-time purchase per developer** with **free updates forever**, major versions included. Every license covers unlimited apps, unlimited end users and unlimited deployments. The data grid, the form renderer and all framework adapters are free under the MIT license. ## Products | Product | Developer seat | What you get | | --- | --- | --- | | **Birch UI Grid** | Free (MIT) | Virtualized data grid with sorting, filtering, quick filter, inline editing, column resize, pin, reorder and hide, row selection, pagination, CSV export, keyboard navigation, ARIA and light and dark themes | | **Grid Pro** | **$349** | Row grouping, aggregation, tree data, pivot mode, range selection, clipboard copy and paste, fill handle, master/detail, status bar, styled Excel export and import. **Includes the Excel Engine** | | **Pivot Studio** | **$349** | Pivot-first report builder for embedded analytics: field list, drill-through, conditional formatting, saved reports and styled Excel export; pivot charts with a Charts license. **Includes the Excel Engine** | | **Excel Engine** | **$299** | Standalone xlsx writer and reader: styles, number formats, merged cells, freeze panes, outlines and autofilter; runs in a worker or in Node | | **Scheduler** | **$399** | Resource timeline with drag, resize and drag-to-create, snapping, zoom presets, overlap lanes, working-time shading, time zones and virtualization in both directions | | **Birch UI Forms** | Free (MIT) | JSON-schema form renderer with multi-page forms, conditional logic, computed fields, repeatable sections, validation, i18n, and JSON Schema import and export | | **Charts** | **$299** | Canvas charts: line, area, column and bar, scatter and bubble, pie and donut, heatmap, combination charts and sparklines; SVG and PNG export; charts from a Grid Pro range | | **Diagram** | **$399** | Flow and diagram editor: ports, orthogonal routing, layered, tree, force and grid auto-layout, groups and swimlanes, minimap, undo and redo, SVG, PNG and JSON export | | **Spreadsheet** | **$399** | Embeddable spreadsheet: Excel-compatible formula engine with over 300 functions and dynamic arrays, a virtualized component and `.xlsx` import and export. **Includes the Excel Engine** | | **Form Builder** | **$349** | Visual designer for Birch UI Forms schemas, with drag and drop, a property panel, an expression editor, undo and redo, a JSON view and a live preview | | **Gantt** | **$399** | Project scheduling: task tree and timeline, critical path on working calendars, all four link types with lag, constraints, baselines, MS Project XML import and export, and a headless engine. Uses the free grid, so no Grid Pro license is needed | | **Event Calendar** | **$299** | Month, week, day, N-day, agenda and year views; RFC 5545 recurrence with exceptions; IANA time zones; iCalendar import and export; drag, resize and select-to-create | | **Project Suite** | **$699** | The Scheduler, Gantt and Event Calendar in one license | | **Birch UI Complete** | **$1,799** | Every Birch UI product, including every product released in the future | Prices are in US dollars. Sales tax and VAT are calculated at checkout. > **Grid Pro includes the Excel Engine** > > A Grid Pro key also activates `@birchui/excel`, so you can generate workbooks outside the grid without a second purchase. ## Seat tiers The same tiers apply to every product. Team costs about 3.7 times the developer price and Company about 10 times, rounded to the nearest $100 less one dollar: | Product | Developer | Team (up to 5 developers) | Company (unlimited developers) | | --- | --- | --- | --- | | Grid Pro, including the Excel Engine | $349 | $1,299 | $3,499 | | Pivot Studio, including the Excel Engine | $349 | $1,299 | $3,499 | | Excel Engine | $299 | $1,099 | $2,999 | | Scheduler | $399 | $1,499 | $3,999 | | Gantt | $399 | $1,499 | $3,999 | | Event Calendar | $299 | $1,099 | $2,999 | | Charts | $299 | $1,099 | $2,999 | | Diagram | $399 | $1,499 | $3,999 | | Spreadsheet, including the Excel Engine | $399 | $1,499 | $3,999 | | Form Builder | $349 | $1,299 | $3,499 | | Project Suite | $699 | $2,599 | $6,999 | | Birch UI Complete | $1,799 | $6,699 | $17,999 | | Tier | Who it covers | | --- | --- | | Developer | One named developer | | Team | Up to 5 developers, with transferable seats | | Company | Unlimited developers in one organization, priority email and read access to the private source repository | | OEM and redistribution | From $4,999, quoted individually. For products that expose Birch UI to their customers' developers, such as low-code platforms and admin-panel builders | Growing teams can add seats at any time. Upgrading from Team to Company costs the difference between the two prices. Only developers who write code against Birch UI need a seat. Colleagues who only build, compile, test or deploy the app do not. Read [Seats: who needs one](https://docs.birchui.com/getting-started/licensing.md#seats-who-needs-one) for the exact rule. ## What "free updates forever" means - Your key never expires. Every future version of the products you bought, including major versions, works with it. - There is no renewal, no maintenance fee and no "update window". - Updates are ordinary npm releases. You upgrade when you choose to. New products are separate purchases unless you own Birch UI Complete, which includes every future product. ## Support Every license includes community support in GitHub Discussions and best-effort email support. For guaranteed response times or hands-on help, buy a one-time support pack: | Pack | Price | Includes | | --- | --- | --- | | Priority Pack | $299 | 10 tickets with a response within 1 business day | | Integration Pack | $1,499 | A 1:1 migration session and a custom example built for your use case | Need a feature that Birch UI does not have yet? Paid custom features are scoped and quoted individually, and they ship to every customer afterwards. ## Evaluate before you buy You do not need a trial key to evaluate. Install the packages and use every feature: unlicensed widgets show a small watermark on non-local hosts and log one console warning, and nothing is disabled. On `localhost` there is no watermark at all. See [What happens without a valid key](https://docs.birchui.com/getting-started/licensing.md#what-happens-without-a-valid-key). ## What comes next Every product in the catalog has shipped. The next planned addition is a Kanban board, which will be free. Birch UI Complete owners automatically get every paid product released in the future, with the same lifetime updates. ## Common questions **Is the price per app?** No. It is per developer. One seat covers every app that developer works on. **Can I use a license in a SaaS product?** Yes. Unlimited end users, tenants and deployments are included in every tier. **Do I need OEM?** Only if your customers' developers build with Birch UI inside your product, for example a low-code builder that offers a Birch UI grid as a building block. Shipping an app that uses Birch UI to end users never needs OEM. More answers are in the [FAQ](https://docs.birchui.com/getting-started/faq.md). --- Source: https://docs.birchui.com/getting-started/migrating-from-ag-grid/ # Migrating from AG Grid > Map AG Grid grid options, column definitions, API calls, events and filter models to their Birch UI Grid equivalents. Birch UI Grid uses many of the same concepts as AG Grid: column definitions, a row id callback, transactions, column state and modules. Most migrations are a rename of options plus a simplification of callbacks, because Birch UI callbacks receive your row object directly instead of a `params` wrapper. This guide maps the options you are most likely to use. Features marked Pro need [Grid Pro](https://docs.birchui.com/grid-pro/overview.md), Birch UI's equivalent of AG Grid Enterprise. To convert a codebase automatically, run the [migration tool](https://docs.birchui.com/getting-started/migration-tool.md), which applies these mappings and lists what is left to do by hand. ## Before and after An AG Grid setup in plain JavaScript: ```ts title="orders-grid.ts (AG Grid)" import { createGrid, ModuleRegistry, AllCommunityModule } from 'ag-grid-community'; ModuleRegistry.registerModules([AllCommunityModule]); const api = createGrid(document.querySelector('#orders')!, { columnDefs: [ { field: 'id', headerName: 'Order', width: 120, pinned: 'left' }, { field: 'customer', headerName: 'Customer', flex: 1, filter: 'agTextColumnFilter' }, { field: 'total', headerName: 'Total', type: 'numericColumn', valueFormatter: (params) => usd.format(params.value), }, ], defaultColDef: { sortable: true, resizable: true, floatingFilter: true }, rowData: orders, getRowId: (params) => params.data.id, rowSelection: { mode: 'multiRow' }, pagination: true, paginationPageSize: 50, onCellValueChanged: (event) => saveOrder(event.data), }); ``` The same grid in Birch UI: ```ts title="orders-grid.ts (Birch UI)" import { createGrid } from '@birchui/core'; const grid = createGrid(document.querySelector('#orders')!, { columns: [ { field: 'id', header: 'Order', width: 120, pinned: 'left' }, { field: 'customer', header: 'Customer', flex: 1, filter: 'text' }, { field: 'total', header: 'Total', type: 'number', format: (value) => usd.format(Number(value)), }, ], defaultColumn: { sortable: true, resizable: true }, floatingFilters: true, rows: orders, getRowId: (order) => order.id, rowSelection: 'multiple', pagination: { pageSize: 50 }, }); grid.on('cellValueChanged', ({ row }) => saveOrder(row)); ``` The main differences: - `columnDefs` becomes `columns`, `rowData` becomes `rows`, `headerName` becomes `header`. - Callbacks receive your row (and value) directly: `getRowId: (order) => order.id` instead of `(params) => params.data.id`. - Events are subscribed with `grid.on(name, handler)`, which returns an unsubscribe function. Framework components expose them as props or outputs. - There is no global module registry. Pass Grid Pro modules per grid with `modules: [...]`. - Floating filters are switched on for the whole grid with `floatingFilters: true`. ## Grid options | AG Grid | Birch UI | Notes | | --- | --- | --- | | `columnDefs` | `columns` | | | `rowData` | `rows` | Or `api.setRows(rows)` | | `getRowId: (params) => params.data.id` | `getRowId: (row, index) => row.id` | | | `defaultColDef` | `defaultColumn` | | | `rowHeight` | `rowHeight` | A number | | `getRowHeight` | `rowHeight` as a function | Receives the display row | | `headerHeight` | `headerHeight` | | | `defaultColDef.floatingFilter` | `floatingFilters: true` | One switch for the grid | | `quickFilterText` | `quickFilter` | Or `api.setQuickFilter(text)`. Searches every column, hidden ones included, and every word must match | | `rowSelection: 'single'` or `{ mode: 'singleRow' }` | `rowSelection: 'single'` | | | `rowSelection: 'multiple'` or `{ mode: 'multiRow' }` | `rowSelection: 'multiple'` | | | `checkboxSelection` on a column, or `rowSelection.checkboxes` | `checkboxSelection: true` | Adds a pinned checkbox column; needs `rowSelection` | | `pagination` and `paginationPageSize` | `pagination: { pageSize: 50 }` | `pagination: true` uses 100 rows per page | | `multiSortKey`, `alwaysMultiSort` | `multiSort` | Shift-click adds a sort column | | `className="ag-theme-quartz-dark"` or `theme` | `theme: 'dark'` | `'light'`, `'dark'` or `'auto'` | | `rowClass`, `getRowClass` | `rowClass: (row) => className` | | | `overlayNoRowsTemplate` | `emptyMessage` | Plain text | | `rowBuffer` | `overscanRows` | Column overscan: `overscanColumns` | | `ModuleRegistry.registerModules([...])` | `modules: [...]` | Per grid, not global | | `LicenseManager.setLicenseKey(key)` | `setLicenseKey(key)` from `@birchui/license` | Or the `licenseKey` option | | `groupDisplayType`, `autoGroupColumnDef` | `groupColumn` | Pro | | `groupDefaultExpanded` | `groupDefaultExpanded` | Pro | | `rowGroupPanelShow: 'always'` | `groupPanel: true` | Pro | | `grandTotalRow`, `groupTotalRow` | `groupTotals: true` | Pro | | `treeData` and `getDataPath` | `treeData` and `getDataPath` | Pro. Or `getParentId` for flat parent references | | `pivotMode: true` | `pivot: { enabled: true, rows, columns, values }` | Pro | | `cellSelection` or `enableRangeSelection` | `rangeSelection: true` | Pro | | `enableFillHandle` | `fillHandle: true` | Pro | | `masterDetail` and `detailCellRenderer` | `masterDetail: { render(row, container) }` | Pro | | `statusBar: { statusPanels }` | `statusBar: true` or `{ rowCount, selectedCount, aggregates }` | Pro | ## Column definitions | AG Grid | Birch UI | Notes | | --- | --- | --- | | `field` | `field` | | | `colId` | `id` | Defaults to `field` | | `headerName` | `header` | | | `headerTooltip` | `headerTooltip` | | | `width`, `minWidth`, `maxWidth`, `flex` | same names | | | `pinned: 'left'` | `pinned: 'left'` | Free in Birch UI | | `hide` | `hidden` | | | `sortable`, `resizable` | same names | | | `suppressMovable: true` | `reorderable: false` | | | `filter: 'agTextColumnFilter'` | `filter: 'text'` | | | `filter: 'agNumberColumnFilter'` | `filter: 'number'` | | | `filter: 'agDateColumnFilter'` | `filter: 'date'` | | | `filter: 'agSetColumnFilter'` | `filter: 'set'` | Free in Birch UI | | `filter: true` | `filter: true` | Picks the filter from the column `type`, or `set` when the column has `options` | | `cellDataType: 'number'`, `type: 'numericColumn'` | `type: 'number'` | Right-aligned by default. Types: `text`, `number`, `date`, `boolean` | | `editable` | `editable` | Boolean or `(ctx) => boolean` | | `cellEditor: 'agTextCellEditor'` | `editor: 'text'` | | | `cellEditor: 'agNumberCellEditor'` | `editor: 'number'` | | | `cellEditor: 'agDateCellEditor'` | `editor: 'date'` | | | `cellEditor: 'agCheckboxCellEditor'` | `editor: 'checkbox'` | | | `cellEditor: 'agSelectCellEditor'`, `cellEditorParams: { values }` | `editor: 'select'`, `options: [...]` | Options can be `{ value, label }` | | Custom `cellEditor` component | `editor: (params) => CellEditor` | A factory returning `{ element, getValue, focus }` | | `valueGetter: (params) => params.data.price * params.data.quantity` | `valueGetter: (row) => row.price * row.quantity` | | | `valueSetter: (params) => { ...; return true }` | `valueSetter: (row, value) => { ... }` | No return value | | `valueParser: (params) => Number(params.newValue)` | `valueParser: (input, row) => Number(input)` | | | `valueFormatter: (params) => ...` | `format: (value, row) => string` | | | `cellRenderer` | `cell: (ctx) => string \| Node` | Return text or a DOM node | | `cellClass` | `cellClass` | String or `(ctx) => string` | | `cellClassRules` | `cellClass` as a function | | | `headerClass` | `headerClass` | | | `comparator: (a, b, nodeA, nodeB)` | `comparator: (a, b, rowA, rowB)` | Receives rows, not nodes | | `aggFunc: 'sum'` | `aggFunc: 'sum'` | Pro. Also `'distinct'` or a function | | `rowGroup`, `rowGroupIndex` | same names | Pro | | `pivot`, `pivotIndex` | same names | Pro | | `context`, custom properties | `meta` | Free-form data for your own code | ## Grid API | AG Grid | Birch UI | | --- | --- | | `api.setGridOption('rowData', rows)` | `api.setRows(rows)` or `api.update({ rows })`. Selection is kept for rows whose id still exists and dropped for the rest | | `api.setGridOption('columnDefs', cols)` | `api.setColumns(cols)` | | `api.setGridOption(key, value)` | `api.update({ [key]: value })` | | `api.applyTransaction({ add, update, remove })` | `api.applyTransaction({ add, update, remove })`. `remove` also accepts row ids | | `api.getRowNode(id)` | `api.getRowById(id)`, which returns your row object | | `api.getDisplayedRowAtIndex(i)` | `api.getDisplayRow(i)` for an index on the current page, or `api.getAllDisplayRows()[i]` across pages | | `api.getDisplayedRowCount()` | `api.getAllDisplayRows().length` | | `api.forEachNodeAfterFilterAndSort(fn)` | `api.getAllDisplayRows().forEach(fn)`; each display row's `data` is your row | | `api.forEachNode(fn)` | `api.getRows().forEach(fn)` | | `api.getSelectedRows()` | `api.getSelectedRows()` | | `api.selectAll()`, `api.deselectAll()` | same names | | `node.setSelected(true)` | `api.setRowSelected(id, true)` | | `api.getColumnState()` | `api.getColumnState()` | | `api.applyColumnState({ state })` | `api.applyColumnState(state)` | | `api.setColumnsVisible([id], false)` | `api.setColumnHidden(id, true)` | | `api.setColumnsPinned([id], 'left')` | `api.setColumnPinned(id, 'left')` | | `api.moveColumns([id], index)` | `api.moveColumn(id, index)` | | `api.setColumnWidths([{ key, newWidth }])` | `api.setColumnWidth(id, width)` | | `api.autoSizeColumns([id])`, `api.autoSizeAllColumns()` | `api.autosizeColumn(id)`, `api.autosizeColumns()` | | `api.applyColumnState({ state: [{ colId, sort }] })` for sorting | `api.setSort([{ colId, dir: 'asc' }])` | | `api.setFilterModel(model)` | `api.setFilterModel(model)`. The model shape differs; see below | | `api.setColumnFilterModel(id, model)` | `api.setFilter(id, model)` | | `api.setGridOption('quickFilterText', text)` | `api.setQuickFilter(text)` | | `api.ensureIndexVisible(i, 'middle')` | `api.scrollToRow(i, 'center')` | | `api.ensureColumnVisible(id)` | `api.scrollToColumn(id)` | | `api.setFocusedCell(i, id)` | `api.focusCell(i, id)` | | `api.getFocusedCell()` | `api.getFocusedCell()` | | `api.startEditingCell({ rowIndex, colKey })` | `api.startEdit(rowIndex, colId)` | | `api.stopEditing(cancel)` | `api.stopEdit(cancel)` | | `api.refreshCells()` | `api.refresh()` | | `api.redrawRows()` | `api.redraw()` | | `api.expandAll()`, `api.collapseAll()` | same names | | `node.setExpanded(true)` | `api.setExpanded(rowId, true)`, which also takes an array of ids | | `node.expanded` | `api.isExpanded(rowId)`; pass `{ ignoreExpandAll: true }` to ignore `expandAll()` and `collapseAll()` | | `api.setRowGroupColumns(cols)` | `api.setGroupBy?.(cols)` (Pro) | | `api.getRowGroupColumns()` | `api.getGroupBy?.()` (Pro) | | Expanding groups to a depth | `api.expandToLevel?.(level)` (Pro) | | `api.setGridOption('pivotMode', true)` with `setPivotColumns` and `setValueColumns` | `api.setPivot?.({ enabled: true, rows, columns, values })` (Pro) | | `api.getPivotResultColumns()` | `api.getPivotResult?.()` (Pro) | | Aggregates shown in the status bar | `api.getColumnAggregate?.(colId, 'sum')` (Pro) | | `api.paginationGoToPage(n)` | `api.setPage(n)` | | `api.paginationGetCurrentPage()` | `api.getPage()` | | `api.paginationGetTotalPages()` | `api.getPageCount()` | | `api.getDataAsCsv(params)` | `api.exportCsv(options)`, which returns a string | | `api.exportDataAsCsv(params)` | `api.downloadCsv(options)` | | `api.exportDataAsExcel(params)` | `await api.exportExcel?.({ fileName, sheetName, onlySelected, allRows })` (Pro, with `ExcelModule`). Exports the filtered and sorted rows of every page, not just the current one, and leaves collapsed groups collapsed; `allRows: true` also writes the rows inside collapsed groups as hidden outline rows | | `api.getDataAsExcel(params)` | `await api.getExcelBlob?.(options)` (Pro, with `ExcelModule`) | | No equivalent: import an `.xlsx` file into the grid | `await api.importExcel?.(file)` (Pro, with `ExcelModule`) | | `api.addEventListener(name, fn)` | `api.on(name, fn)`, which returns an unsubscribe function | | `api.isDestroyed()`, `api.destroy()` | `api.destroy()` | Grid Pro modules add their methods to `GridApi`: the Excel methods come from `ExcelModule`, and the grouping, pivot and aggregate methods from the analytics modules. TypeScript therefore declares them as optional. Call them with `?.`, as above, or check that they exist first. The Excel methods return promises. See the full [GridApi reference](https://docs.birchui.com/api/core.md#gridapi). ## Events | AG Grid | Birch UI | Payload | | --- | --- | --- | | `onGridReady` | `ready` | `{ api }` | | `onCellClicked` | `cellClick` | `{ row, displayRow, rowIndex, colId, value, event }` | | `onCellDoubleClicked` | `cellDoubleClick` | same as `cellClick` | | `onCellKeyDown` | `cellKeyDown` | same as `cellClick` | | `onCellValueChanged` | `cellValueChanged` | `{ row, rowIndex, colId, oldValue, newValue, source }` | | `onRowClicked` | `rowClick` | `{ row, displayRow, rowIndex, event }` | | `onSelectionChanged` | `selectionChanged` | `{ selected }`, the selected rows | | `onSortChanged` | `sortChanged` | `{ sort }`. Also fires for changes made with `setSort` or `update({ sort })` | | `onFilterChanged` | `filterChanged` | `{ filterModel, quickFilter }`. Also fires for changes made through the API or `update()` | | `onColumnResized` | `columnResized` | `{ colId, width }` | | `onColumnMoved` | `columnMoved` | `{ colId, toIndex }` | | `onColumnPinned` | `columnPinned` | `{ colId, pinned }` | | `onColumnVisible` | `columnVisible` | `{ colId, hidden }` | | Any column event, to persist state | `columnStateChanged` | `{ state }` | | `onModelUpdated` | `modelUpdated` | `{ rowCount, displayRowCount }` | | `onCellFocused` | `focusChanged` | `{ cell }` | | `onBodyScroll` | `viewportScroll` | `{ top, left }` | | `onPaginationChanged` | `pageChanged` | `{ page, pageCount }` | | `onRowGroupOpened` | `rowExpanded` | `{ rowId, expanded }` | | `onCellEditingStarted` | `editStart` | `{ rowIndex, colId }` | | `onCellEditingStopped` | `editStop` | `{ rowIndex, colId, cancelled }` | `cellValueChanged.source` tells you whether the change came from an `edit`, a clipboard `paste`, the `fill` handle or the `api`. See the [events reference](https://docs.birchui.com/grid/events.md). ## Filter models AG Grid stores a `filterType` and a `type` per column. Birch UI stores a `type` and an `op`: ```ts title="AG Grid" api.setFilterModel({ customer: { filterType: 'text', type: 'contains', filter: 'traders' }, total: { filterType: 'number', type: 'inRange', filter: 100, filterTo: 500 }, placedAt: { filterType: 'date', type: 'lessThan', dateFrom: '2026-11-01' }, region: { filterType: 'set', values: ['EMEA', 'APAC'] }, }); ``` ```ts title="Birch UI" grid.setFilterModel({ customer: { type: 'text', op: 'contains', value: 'traders' }, total: { type: 'number', op: 'between', value: 100, valueTo: 500 }, placedAt: { type: 'date', op: 'before', value: '2026-11-01' }, region: { type: 'set', values: ['EMEA', 'APAC'] }, }); ``` | AG Grid `type` | Birch UI `op` | | --- | --- | | `contains`, `notContains`, `equals`, `notEqual`, `startsWith`, `endsWith` (text) | `contains`, `notContains`, `equals`, `notEquals`, `startsWith`, `endsWith` | | `equals`, `notEqual` (number) | `eq`, `ne` | | `lessThan`, `lessThanOrEqual`, `greaterThan`, `greaterThanOrEqual` (number) | `lt`, `lte`, `gt`, `gte` | | `inRange` (number or date) | `between` with `value` and `valueTo` | | `equals`, `lessThan`, `greaterThan` (date) | `eq`, `before`, `after` | | `blank`, `notBlank` | `blank`, `notBlank` | AG Grid allows two conditions per column joined with `AND` or `OR`. Birch UI has one condition per column; for compound rules, use a `custom` filter with a `test` function: ```ts grid.setFilter('total', { type: 'custom', test: (value) => Number(value) < 50 || Number(value) > 5000, }); ``` Floating filters also accept expressions such as `>100` or `10..20` in number columns. See [Filtering](https://docs.birchui.com/grid/filtering.md). ## Cell renderers AG Grid cell renderers are components or functions that receive `params`. A Birch UI `cell` function receives a context object and returns a string or a DOM node: ```ts const statusColumn: ColumnDef = { field: 'status', header: 'Status', cell: ({ value }) => { const badge = document.createElement('span'); badge.className = `order-status order-status-${String(value)}`; badge.textContent = String(value); return badge; }, }; ``` The context contains `row`, `value`, `formatted` (the result of `format`), `column`, `rowIndex`, `displayRow` and `api`. Return a string for plain text; it is inserted as text, not HTML. See [Columns](https://docs.birchui.com/grid/columns.md). ## Modules AG Grid registers modules globally. Birch UI passes them per grid, so two grids on one page can use different feature sets: ```ts import { createGrid } from '@birchui/core'; import { RowGroupingModule, AggregationModule, ExcelModule } from '@birchui/grid-pro'; createGrid(container, { columns, rows, modules: [RowGroupingModule, AggregationModule, ExcelModule], groupBy: ['region'], }); ``` `AllProModules` contains every Grid Pro module. See [Modules](https://docs.birchui.com/grid/modules.md). ## Licensing differences | | AG Grid Enterprise | Birch UI Grid Pro | | --- | --- | --- | | Purchase | Perpetual license with one year of updates | One-time purchase with updates forever, majors included | | Who needs a seat | Every front-end developer on the project | Only developers who write code against Birch UI; build-only colleagues need none | | Without a key | Watermark and console messages | Watermark on non-local hosts and one console warning; every feature works | | Key check | Offline | Offline, no network calls | | Apps and end users | Depends on the license type | Unlimited in every tier | Read [Licensing and activation](https://docs.birchui.com/getting-started/licensing.md) for the details. ## Features without a direct equivalent Plan around these when you migrate: - **Server-side row model and infinite row model.** Birch UI works with rows held in memory and virtualizes rendering. Load data in pages yourself and call `applyTransaction` or `setRows`. The grid is built to handle a million rows in memory. - **Integrated charts and sparklines.** Birch UI Charts (`@birchui/charts`, a separate license) covers both: `chartFromRange(values, headers)` builds chart options from a Grid Pro range for `createChart`, and `sparklineSVG(values)` returns SVG markup for sparklines. See the [Charts overview](https://docs.birchui.com/charts/overview.md). - **Side bar and tool panels.** Not available. Build your own panel with `getColumns`, `setColumnHidden` and `applyColumnState`. - **Row dragging.** Not available. - **Framework components as cell renderers.** `cell` returns a string or a DOM node. ## Migration checklist 1. Install `@birchui/core` (plus `@birchui/grid-pro` if you use Enterprise features) and your [framework adapter](https://docs.birchui.com/getting-started/installation.md#framework-adapters). 2. Rename grid options and column properties using the tables above. 3. Rewrite `params` callbacks to take the row or value directly. 4. Replace `api.addEventListener` and `on*` grid options with `grid.on(...)` or the adapter's event props. 5. Convert saved filter models and column state. 6. Move Enterprise modules into `modules: [...]` on each grid. 7. Replace the AG Grid theme class with `theme` and the `--lq-*` CSS variables. See [Theming](https://docs.birchui.com/grid/theming.md). 8. Set your key with `setLicenseKey`. --- Source: https://docs.birchui.com/getting-started/migrating-from-mui-x/ # Migrating from MUI X Data Grid > Map MUI X DataGrid, DataGridPro and DataGridPremium props, column definitions, apiRef calls and models to Birch UI Grid. MUI X Data Grid and Birch UI Grid share a lot of vocabulary: `rows`, `columns`, `field`, `getRowId`, `checkboxSelection`, `density`. The biggest differences are that Birch UI works in every framework, cell renderers return DOM content instead of React elements, and models such as sorting and filtering use slightly different shapes. Pinned columns, column reordering and the set filter, which are Pro features in MUI X, are free in Birch UI Grid. MUI X Premium features such as row grouping, aggregation, Excel export and cell selection map to [Grid Pro](https://docs.birchui.com/grid-pro/overview.md). To convert a codebase automatically, run the [migration tool](https://docs.birchui.com/getting-started/migration-tool.md), which applies these mappings and lists what is left to do by hand. ## Before and after ```tsx title="OrdersGrid.tsx (MUI X)" import { DataGrid, type GridColDef } from '@mui/x-data-grid'; const columns: GridColDef[] = [ { field: 'id', headerName: 'Order', width: 120 }, { field: 'customer', headerName: 'Customer', flex: 1, editable: true }, { field: 'total', headerName: 'Total', type: 'number', valueFormatter: (value) => usd.format(value), }, ]; export function OrdersGrid({ orders }: { orders: Order[] }) { return (
row.id} checkboxSelection initialState={{ pagination: { paginationModel: { pageSize: 50 } } }} pageSizeOptions={[50]} processRowUpdate={(updated) => saveOrder(updated)} />
); } ``` ```tsx title="OrdersGrid.tsx (Birch UI)" 'use client'; import { BirchGrid } from '@birchui/react'; import type { CellValueChangedEvent, ColumnDef } from '@birchui/core'; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 120 }, { field: 'customer', header: 'Customer', flex: 1, editable: true }, { field: 'total', header: 'Total', type: 'number', format: (value) => usd.format(Number(value)), }, ]; const getRowId = (order: Order) => order.id; const pagination = { pageSize: 50 }; export function OrdersGrid({ orders }: { orders: Order[] }) { return ( style={{ height: 480 }} rows={orders} columns={columns} getRowId={getRowId} rowSelection="multiple" checkboxSelection pagination={pagination} onCellValueChanged={(event: CellValueChangedEvent) => saveOrder(event.row)} /> ); } ``` Things to notice: - `headerName` becomes `header`, and `valueFormatter` becomes `format`. - Number columns are right-aligned and boolean columns centered by default; override with `align`. - `checkboxSelection` needs `rowSelection: 'multiple'` (or `'single'`). - There is no `processRowUpdate`. The grid applies the edit to your row, then emits `cellValueChanged`. - The grid fills the element you size with `style` or `className`; there is no wrapper `div` to add. - Keep `columns`, `getRowId` and other option props stable between renders. See [Props and updates](https://docs.birchui.com/frameworks/react.md#props-and-updates). ## Props | MUI X | Birch UI | Notes | | --- | --- | --- | | `rows` | `rows` | | | `columns` | `columns` | | | `getRowId={(row) => row.sku}` | `getRowId={(row, index) => row.sku}` | | | `apiRef={useGridApiRef()}` | `ref={useRef>(null)}` | The ref is the full `GridApi` | | `rowHeight={52}` | `rowHeight={52}` | | | `getRowHeight` | `rowHeight` as a function | | | `columnHeaderHeight` | `headerHeight` | | | `density="compact" \| "standard" \| "comfortable"` | `density="compact" \| "normal" \| "comfortable"` | | | `checkboxSelection` | `checkboxSelection` | Together with `rowSelection` | | `disableMultipleRowSelection` | `rowSelection="single"` | | | `rowSelectionModel`, `onRowSelectionModelChange` | `api.setRowSelected(id, selected)`, `onSelectionChanged` | `onSelectionChanged` receives `{ selected }` rows | | `sortModel={[{ field, sort: 'asc' }]}` | `sort={[{ colId, dir: 'asc' }]}` | | | `onSortModelChange` | `onSortChanged` | Receives `{ sort }`. Also fires when you change `sort` through props or the API | | `filterModel={{ items: [...] }}` | `filterModel={{ [colId]: model }}` | See [Filter models](#filter-models) | | `filterModel.quickFilterValues` | `quickFilter` | A single string. Every word must match, and hidden columns are searched too | | `onFilterModelChange` | `onFilterChanged` | Receives `{ filterModel, quickFilter }`. Also fires when you change filters through props or the API | | `pagination`, `paginationModel={{ page, pageSize }}` | `pagination={{ page, pageSize }}` | `page` is zero-based in both | | `onPaginationModelChange` | `onPageChanged` | Receives `{ page, pageCount }` | | `pinnedColumns={{ left: ['id'] }}` (Pro) | `pinned: 'left'` on the column | Free in Birch UI | | `columnVisibilityModel` | `hidden` on the column, or `api.applyColumnState` | | | `slots.noRowsOverlay` | `emptyMessage` | Plain text | | `slots.toolbar` with `GridToolbarQuickFilter` | Your own toolbar calling `api.setQuickFilter` | | | `slots.toolbar` with `GridToolbarExport` | Your own button calling `api.downloadCsv()` | | | `showCellVerticalBorder`, `getRowClassName` | `--lq-border` and `rowClass` | | | `rowGroupingModel={['region']}` (Premium) | `groupBy={['region']}` | Pro | | `groupingColDef` (Premium) | `groupColumn` | Pro | | `defaultGroupingExpansionDepth` (Premium) | `groupDefaultExpanded` | Pro | | `aggregationModel={{ revenue: 'sum' }}` (Premium) | `aggFunc: 'sum'` on the column | Pro | | `treeData`, `getTreeDataPath` (Pro) | `treeData`, `getDataPath` | Pro | | `getDetailPanelContent`, `getDetailPanelHeight` (Pro) | `masterDetail={{ render, height }}` | Pro | | `cellSelection` (Premium) | `rangeSelection` | Pro | | Clipboard paste (Premium) | `clipboard` | Pro | | Excel export (Premium) | `api.exportExcel?.()` with `ExcelModule` | Pro. Exports every page; `allRows: true` adds rows inside collapsed groups as hidden outline rows | | Pivoting (Premium) | `pivot={{ enabled: true, rows, columns, values }}` | Pro | ## Column definitions | MUI X `GridColDef` | Birch UI `ColumnDef` | Notes | | --- | --- | --- | | `field` | `field` | | | `headerName` | `header` | | | `description` | `headerTooltip` | | | `width`, `minWidth`, `maxWidth`, `flex` | same names | | | `type: 'number'` | `type: 'number'` | Right-aligned by default | | `type: 'date'`, `'dateTime'` | `type: 'date'` | | | `type: 'boolean'` | `type: 'boolean'` | | | `type: 'singleSelect'`, `valueOptions` | `editor: 'select'`, `options` | Add `filter: 'set'` for a set filter | | `type: 'actions'`, `getActions` | `cell` returning buttons | | | `editable` | `editable` | Or a function of the cell context | | `sortable`, `resizable` | same names | | | `filterable` | `filter` | `true` or `'text' \| 'number' \| 'date' \| 'set' \| 'boolean'` | | `disableReorder: true` | `reorderable: false` | | | `hideable` | No column-level switch | Hide columns with `hidden` or `api.setColumnHidden` | | `align`, `headerAlign` | `align` | | | `valueGetter: (value, row) => ...` | `valueGetter: (row) => ...` | | | `valueSetter: (value, row) => ({ ...row, x: value })` | `valueSetter: (row, value) => { row.x = value }` | Birch UI updates the row in place | | `valueParser: (value, row) => ...` | `valueParser: (input, row) => ...` | | | `valueFormatter: (value, row) => ...` | `format: (value, row) => string` | | | `renderCell: (params) => ` | `cell: (ctx) => string \| Node` | Returns text or a DOM node | | `renderEditCell` | `editor: (params) => CellEditor` | | | `cellClassName` | `cellClass` | String or function | | `headerClassName` | `headerClass` | | | `sortComparator: (v1, v2, p1, p2)` | `comparator: (a, b, rowA, rowB)` | | | `aggregable`, `availableAggregationFunctions` (Premium) | `aggFunc` | Pro | | `groupable` (Premium) | `rowGroup` | Pro | ## apiRef calls | MUI X `apiRef.current` | Birch UI `GridApi` | | --- | --- | | `updateRows([{ id, ...changes }])` | `applyTransaction({ update: [row] })` | | `updateRows([{ id, _action: 'delete' }])` | `applyTransaction({ remove: [id] })` | | `setRows(rows)` | `setRows(rows)` | | `getRow(id)` | `getRowById(id)` | | `getAllRowIds()` | `getRows().map((row) => grid.getRowId(row))` | | `gridFilteredSortedRowEntriesSelector(apiRef)` | `getAllDisplayRows()`, the rows after filtering, sorting and grouping on every page | | `setRowChildrenExpansion(id, true)` | `setExpanded(id, true)`, which also takes an array of ids | | `setRowGroupingModel(['region'])` (Premium) | `setGroupBy?.(['region'])` (Pro) | | `setAggregationModel(model)` (Premium) | `aggFunc` on the column; read a total with `getColumnAggregate?.(colId, 'sum')` (Pro) | | `setPivotModel(model)` (Premium) | `setPivot?.({ enabled: true, rows, columns, values })` (Pro) | | `getSelectedRows()` | `getSelectedRows()`, which returns an array | | `selectRow(id, true)` | `setRowSelected(id, true)` | | `setSortModel(model)` | `setSort(sort)` | | `setFilterModel(model)` | `setFilterModel(model)` | | `setQuickFilterValues(['north'])` | `setQuickFilter('north')` | | `setPage(n)` | `setPage(n)` | | `setColumnVisibility(field, false)` | `setColumnHidden(colId, true)` | | `setColumnWidth(field, width)` | `setColumnWidth(colId, width)` | | `setColumnIndex(field, index)` | `moveColumn(colId, index)` | | `pinColumn(field, 'left')` | `setColumnPinned(colId, 'left')` | | `autosizeColumns()` | `autosizeColumns()` | | `exportState()`, `restoreState()` | `getColumnState()`, `applyColumnState()` plus `getSort()` and `getFilterModel()` | | `scrollToIndexes({ rowIndex, colIndex })` | `scrollToRow(rowIndex)`, `scrollToColumn(colId)` | | `setCellFocus(id, field)` | `focusCell(rowIndex, colId)` | | `startCellEditMode({ id, field })` | `startEdit(rowIndex, colId)` | | `stopCellEditMode({ id, field })` | `stopEdit()` | | `exportDataAsCsv()` | `downloadCsv()` | | `exportDataAsExcel()` (Premium) | `exportExcel?.()` (Pro, with `ExcelModule`) | | `subscribeEvent('cellClick', fn)` | `on('cellClick', fn)` | Methods that Grid Pro modules add, such as `setGroupBy`, `setPivot`, `getColumnAggregate` and `exportExcel`, are optional in the `GridApi` type, so call them with `?.`. ## Filter models MUI X keeps a list of filter items. Birch UI keeps one model per column id: ```ts title="MUI X" const filterModel = { items: [ { field: 'customer', operator: 'contains', value: 'traders' }, { field: 'total', operator: '>', value: 1000 }, { field: 'region', operator: 'isAnyOf', value: ['EMEA', 'APAC'] }, ], quickFilterValues: ['priority'], }; ``` ```ts title="Birch UI" const filterModel = { customer: { type: 'text', op: 'contains', value: 'traders' }, total: { type: 'number', op: 'gt', value: 1000 }, region: { type: 'set', values: ['EMEA', 'APAC'] }, } satisfies Record; const quickFilter = 'priority'; ``` | MUI X operator | Birch UI | | --- | --- | | `contains`, `doesNotContain`, `equals`, `doesNotEqual`, `startsWith`, `endsWith` | `text` with `contains`, `notContains`, `equals`, `notEquals`, `startsWith`, `endsWith` | | `isEmpty`, `isNotEmpty` | `blank`, `notBlank` | | `isAnyOf` | `{ type: 'set', values }` | | `=`, `!=`, `<`, `<=`, `>`, `>=` | `number` with `eq`, `ne`, `lt`, `lte`, `gt`, `gte` | | `is`, `before`, `after` (date) | `date` with `eq`, `before`, `after` | | `is` (boolean) | `{ type: 'boolean', value: true }` | MUI X combines items with `logicOperator`. Birch UI combines columns with AND; for an OR across conditions in one column, use a `custom` filter. See [Filtering](https://docs.birchui.com/grid/filtering.md). ## Cell rendering MUI X renders React elements in cells. A Birch UI `cell` function returns a string or a DOM node, which keeps scrolling fast in every framework: ```ts const columns: ColumnDef[] = [ { field: 'status', header: 'Status', cell: ({ value }) => { const chip = document.createElement('span'); chip.className = `status-chip status-chip-${String(value)}`; chip.textContent = String(value); return chip; }, }, { id: 'actions', header: '', width: 96, sortable: false, cell: ({ row }) => { const button = document.createElement('button'); button.type = 'button'; button.textContent = 'Refund'; button.addEventListener('click', () => row && openRefundDialog(row)); return button; }, }, ]; ``` Strings are inserted as text, so values from your data cannot inject HTML. ## Editing and persistence MUI X calls `processRowUpdate` and waits for it. In Birch UI, the edit is applied first, then `cellValueChanged` fires with the old and new values. Persist it there, and revert with `setValue` if the server rejects it: ```tsx async function handleChange({ row, colId, oldValue, newValue }: CellValueChangedEvent) { try { await saveOrder(row); } catch { grid.current?.setValue(row, colId, oldValue, 'api'); showToast(`Could not save ${colId} for ${row.id}; the previous value was restored.`); } } ``` Use `valueParser` to convert input and `editable: (ctx) => boolean` to lock cells. See [Editing](https://docs.birchui.com/grid/editing.md). ## Licensing differences | | MUI X Pro and Premium | Birch UI Grid Pro | | --- | --- | --- | | Purchase | Annual subscription per developer | One-time purchase, free updates forever | | Frameworks | React | React, Vue, Angular, Svelte, Solid, Web Components and plain JavaScript | | Pinned columns, reordering, set filter | Pro | Free | | Grouping, aggregation, Excel export, cell selection | Premium | Grid Pro | | Without a key | Watermark and console message | Watermark on non-local hosts and one console warning; features keep working | See [Licensing and activation](https://docs.birchui.com/getting-started/licensing.md) and [Pricing](https://docs.birchui.com/getting-started/pricing.md). ## Migration checklist 1. Install `@birchui/core` and `@birchui/react` (plus `@birchui/grid-pro` for Premium features). 2. Rename props and column fields with the tables above. 3. Convert `renderCell` components to `cell` functions that return text or DOM nodes. 4. Replace `apiRef` with a React ref typed as `GridApi`. 5. Convert sort, filter and pagination models. 6. Replace `processRowUpdate` with an `onCellValueChanged` handler. 7. Move styling from `sx` and theme overrides to the `--lq-*` CSS variables. See [Theming](https://docs.birchui.com/grid/theming.md). 8. Read the [React guide](https://docs.birchui.com/frameworks/react.md) for Next.js and server rendering. --- Source: https://docs.birchui.com/getting-started/migration-tool/ # Migration tool > Convert AG Grid and MUI X Data Grid code to Birch UI Grid with the birchui-migrate codemod, or paste a configuration into the playground and see the result live. `@birchui/migrate` converts AG Grid and MUI X Data Grid code to Birch UI Grid. The `birchui-migrate` command rewrites whole projects in React, Vue, Angular and plain JavaScript or TypeScript, and the same converters run in the browser below. Every mapping follows the [AG Grid](https://docs.birchui.com/getting-started/migrating-from-ag-grid.md) and [MUI X](https://docs.birchui.com/getting-started/migrating-from-mui-x.md) migration guides. ## Playground Paste AG Grid `columnDefs` or `gridOptions`, or MUI X `columns` and props, as JSON or as a JavaScript object literal. The playground shows the converted configuration, the notes for anything that needs your attention, and a live grid with sample rows generated from the column fields. **Live demo: Migration playground** (runs on the HTML version of this page). Source of `demos/migration-tool.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef, type GridApi, type GridModule, type GridOptions, type RowData, } from '@birchui/core'; import { AggregationModule, ClipboardModule, ExcelModule, FillHandleModule, MasterDetailModule, PivotModule, RangeSelectionModule, RowGroupingModule, StatusBarModule, TreeDataModule, } from '@birchui/grid-pro'; import { convertSnippet, stripCode, type MigrationSource, type MigrationWarning, type SnippetConversion, } from '@birchui/migrate'; import { button, docsTheme, field, layout, onDocsThemeChange, seededRandom } from './_shared'; export const meta = { title: 'Migration playground', height: 780 }; interface Sample { id: string; label: string; from: MigrationSource; source: string; } const SAMPLES: Sample[] = [ { id: 'orders', label: 'AG Grid: orders with grouping', from: 'ag-grid', source: `const gridOptions = { columnDefs: [ { field: 'region', rowGroup: true, hide: true }, { field: 'orderId', headerName: 'Order', width: 120, pinned: 'left' }, { field: 'customer', filter: 'agTextColumnFilter', flex: 1, minWidth: 180 }, { field: 'product', filter: 'agSetColumnFilter' }, { field: 'quantity', headerName: 'Qty', type: 'numericColumn', aggFunc: 'sum', editable: true }, { field: 'revenue', type: 'numericColumn', aggFunc: 'sum', valueFormatter: (params) => usd.format(params.value) }, { field: 'orderDate', headerName: 'Ordered', cellDataType: 'dateString', sort: 'desc' }, { field: 'status', cellRenderer: StatusBadge }, ], defaultColDef: { sortable: true, resizable: true, floatingFilter: true }, autoGroupColumnDef: { headerName: 'Region', minWidth: 200 }, groupDefaultExpanded: 1, rowSelection: { mode: 'multiRow', checkboxes: true }, cellSelection: true, statusBar: { statusPanels: [{ statusPanel: 'agAggregationComponent' }] }, sideBar: true, onCellValueChanged: (event) => saveOrder(event.data), };`, }, { id: 'crm', label: 'AG Grid: CRM master/detail', from: 'ag-grid', source: `const gridOptions = { columnDefs: [ { field: 'name', cellRenderer: 'agGroupCellRenderer' }, { field: 'account' }, { field: 'calls', type: 'numericColumn' }, { field: 'minutes', valueFormatter: "x.toLocaleString() + 'm'" }, ], defaultColDef: { flex: 1 }, masterDetail: true, detailRowHeight: 240, detailCellRendererParams: { detailGridOptions: { columnDefs: [{ field: 'callId' }, { field: 'direction' }, { field: 'number' }, { field: 'duration' }], defaultColDef: { flex: 1 }, }, getDetailRowData: (params) => params.successCallback(params.data.callRecords), }, };`, }, { id: 'mui', label: 'MUI X: DataGridPremium with aggregation', from: 'mui', source: `const columns = [ { field: 'region', headerName: 'Region', width: 140 }, { field: 'rep', headerName: 'Sales rep', flex: 1 }, { field: 'closedAt', headerName: 'Closed', type: 'date' }, { field: 'units', headerName: 'Units', type: 'number' }, { field: 'revenue', headerName: 'Revenue', type: 'number', valueFormatter: (value) => currency.format(value) }, { field: 'stage', type: 'singleSelect', valueOptions: ['Won', 'Lost', 'Pending'], renderCell: (params) => }, ]; const props = { rows: sales, columns, checkboxSelection: true, rowGroupingModel: ['region'], aggregationModel: { units: 'sum', revenue: 'sum' }, initialState: { pinnedColumns: { left: ['rep'] } }, pagination: true, };`, }, ]; const PRO_MODULES: Record = { AggregationModule, ClipboardModule, ExcelModule, FillHandleModule, MasterDetailModule, PivotModule, RangeSelectionModule, RowGroupingModule, StatusBarModule, TreeDataModule, }; const COMPANIES = [ 'Northwind Traders', 'Blue Harbor Foods', 'Alpine Outfitters', 'Kestrel Logistics', 'Maison Duval', 'Sakura Retail Group', ]; const PEOPLE = ['Amelia Hart', 'Jonas Becker', 'Priya Natarajan', 'Diego Alvarez', 'Hana Sato', 'Liam O’Connor']; const PRODUCTS = ['Standing desk', 'Ergonomic chair', 'Monitor arm', '27" 4K monitor', 'USB-C dock', 'Desk lamp']; const COUNTRIES = ['United States', 'Germany', 'France', 'Japan', 'Brazil', 'Canada']; const REGIONS = ['North America', 'Europe', 'Asia Pacific', 'Latin America']; const STATUSES = ['Open', 'Shipped', 'Delivered', 'Cancelled']; const PANEL = 'display:flex;flex-direction:column;min-width:0;min-height:0;border:1px solid var(--line);border-radius:8px;background:var(--bg);overflow:hidden'; const PANEL_TITLE = 'margin:0;padding:6px 10px;font-size:12px;font-weight:600;color:var(--muted);border-bottom:1px solid var(--line)'; const MONO = 'font-family:var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);font-size:12px;line-height:1.5'; function panel(title: string): { root: HTMLElement; content: HTMLElement } { const root = document.createElement('section'); root.style.cssText = PANEL; const heading = document.createElement('h3'); heading.style.cssText = PANEL_TITLE; heading.textContent = title; const content = document.createElement('div'); content.style.cssText = 'flex:1;min-height:0;position:relative;overflow:auto'; root.append(heading, content); return { root, content }; } function leafColumns(columns: unknown[]): ColumnDef[] { return columns.flatMap((column) => { const children = (column as { children?: unknown[] }).children; return Array.isArray(children) ? leafColumns(children) : [column as ColumnDef]; }); } function sampleValue(column: ColumnDef, index: number, random: () => number): unknown { const pick = (list: readonly T[]): T => list[Math.floor(random() * list.length)]; const name = (column.field ?? column.id ?? '').toString(); const key = name.toLowerCase(); const options = column.options; if (Array.isArray(options) && options.length) { const option = pick(options); return typeof option === 'object' && option !== null ? (option as { value: unknown }).value : option; } if (column.type === 'boolean' || /^(is|has)[A-Z]|active|shipped|paid|discontinued/.test(name)) return random() < 0.5; if (column.type === 'date' || /date|time|day/.test(key) || /[a-z](At|On)$/.test(name)) return new Date(Date.UTC(2026, 0, 1) + Math.floor(random() * 330) * 86_400_000).toISOString().slice(0, 10); if (/^id$|orderid|number|no$|code|sku|tracking|callid/.test(key)) return `${name.slice(0, 3).toUpperCase()}-${10001 + index}`; if (/email/.test(key)) return `${pick(PEOPLE).split(' ')[0].toLowerCase()}@example.com`; if (/country/.test(key)) return pick(COUNTRIES); if (/region/.test(key)) return pick(REGIONS); if (/customer|company|account|client/.test(key)) return pick(COMPANIES); if (/name|rep|owner|agent|manager/.test(key)) return pick(PEOPLE); if (/product|item/.test(key)) return pick(PRODUCTS); if (/status|stage/.test(key)) return pick(STATUSES); if (/direction/.test(key)) return pick(['In', 'Out']); if (/qty|quantity|units|count|calls|stock|minutes|duration/.test(key)) return 1 + Math.floor(random() * 40); if (column.type === 'number' || /price|total|amount|revenue|cost|sales|value|balance/.test(key)) return Math.round(random() * 500000) / 100; return `${name.charAt(0).toUpperCase()}${name.slice(1)} ${index + 1}`; } function sampleRows(columns: ColumnDef[], count: number): RowData[] { const random = seededRandom(42); return Array.from({ length: count }, (_, index) => { const row: RowData = { __rowId: `row-${index}` }; for (const column of columns) if (column.field) row[column.field] = sampleValue(column, index, random); return row; }); } function previewOptions(result: SnippetConversion): GridOptions | null { const value = stripCode(result.value); const options = (result.kind === 'columns' ? { columns: Array.isArray(value) ? value : [value] } : value) as Record< string, unknown >; if (!options || !Array.isArray(options.columns)) return null; const columns = leafColumns(options.columns).filter((column) => column.field || column.id); if (!columns.length) return null; const preview: Record = { ...options }; for (const key of [ 'rows', 'getRowId', 'rowModel', 'datasource', 'licenseKey', 'modules', 'theme', 'rowHeight', 'getDataPath', 'getParentId', ]) delete preview[key]; const masterDetail = preview.masterDetail as { render?: unknown } | undefined; if (masterDetail && typeof masterDetail.render !== 'function') delete preview.masterDetail; if (preview.treeData) delete preview.treeData; const modules = result.modules .filter((name) => !(name === 'MasterDetailModule' && !preview.masterDetail) && !(name === 'TreeDataModule')) .map((name) => PRO_MODULES[name]) .filter(Boolean); return { ...(preview as Partial), columns, rows: sampleRows(columns, 48), getRowId: (row) => String(row.__rowId), modules, theme: docsTheme(), ariaLabel: 'Preview of the converted grid with sample rows', }; } const SEVERITY_LABELS: Record = { manual: 'Manual', warning: 'Check', info: 'Note', }; const SEVERITY_COLORS: Record = { manual: 'var(--warn)', warning: 'var(--accent)', info: 'var(--muted)', }; function renderWarnings(list: HTMLElement, warnings: readonly MigrationWarning[]): void { list.replaceChildren(); const ordered = [...warnings].sort( (a, b) => ['manual', 'warning', 'info'].indexOf(a.severity) - ['manual', 'warning', 'info'].indexOf(b.severity), ); if (!ordered.length) { const empty = document.createElement('p'); empty.style.cssText = 'margin:0;padding:10px;font-size:13px;color:var(--muted)'; empty.textContent = 'Everything converted without notes.'; list.append(empty); return; } for (const warning of ordered) { const item = document.createElement('li'); item.style.cssText = 'padding:6px 10px;border-bottom:1px solid var(--line);font-size:12.5px;line-height:1.45;color:var(--text)'; const badge = document.createElement('strong'); badge.style.cssText = `display:inline-block;min-width:52px;margin-right:6px;font-size:11px;text-transform:uppercase;letter-spacing:.03em;color:${SEVERITY_COLORS[warning.severity]}`; badge.textContent = SEVERITY_LABELS[warning.severity]; const path = document.createElement('code'); path.style.cssText = `${MONO};color:var(--ink)`; path.textContent = warning.path; const message = document.createElement('span'); message.textContent = ` ${warning.message} `; const link = document.createElement('a'); link.href = warning.docsUrl.replace(/^https:\/\/birchui\.com/, ''); link.textContent = 'Docs'; item.append(badge, path, message, link); list.append(item); } } export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); body.style.cssText = 'flex:1;min-height:0;position:relative;display:grid;gap:10px;padding:10px;grid-template-columns:repeat(auto-fit,minmax(min(100%,320px),1fr));grid-auto-rows:minmax(260px,1fr);overflow:auto;background:var(--bg-soft)'; const sampleSelect = document.createElement('select'); for (const sample of SAMPLES) sampleSelect.add(new Option(sample.label, sample.id)); const fromSelect = document.createElement('select'); fromSelect.add(new Option('AG Grid', 'ag-grid')); fromSelect.add(new Option('MUI X Data Grid', 'mui')); const input = panel('Paste AG Grid or MUI X configuration (JSON or a JavaScript object literal)'); const textarea = document.createElement('textarea'); textarea.spellcheck = false; textarea.wrap = 'off'; textarea.setAttribute('aria-label', 'Configuration to convert'); textarea.style.cssText = `${MONO};width:100%;height:100%;box-sizing:border-box;border:0;padding:10px;resize:none;background:var(--code-bg, var(--bg));color:var(--ink);outline-offset:-2px`; input.content.append(textarea); const output = panel('Birch UI Grid configuration'); const code = document.createElement('pre'); code.setAttribute('aria-live', 'polite'); code.style.cssText = `${MONO};margin:0;padding:10px;min-height:100%;box-sizing:border-box;white-space:pre;background:var(--code-bg, var(--bg));color:var(--ink)`; output.content.append(code); const notes = panel('Warnings and manual steps'); const list = document.createElement('ul'); list.style.cssText = 'list-style:none;margin:0;padding:0'; notes.content.append(list); const preview = panel('Live preview with sample rows'); const stage = document.createElement('div'); stage.style.cssText = 'position:absolute;inset:0'; preview.content.append(stage); body.append(input.root, output.root, notes.root, preview.root); let grid: GridApi | null = null; let timer: ReturnType | null = null; let converted = ''; const showPreview = (result: SnippetConversion | null) => { grid?.destroy(); grid = null; stage.replaceChildren(); const options = result ? previewOptions(result) : null; if (!options) { const empty = document.createElement('p'); empty.style.cssText = 'margin:0;padding:10px;font-size:13px;color:var(--muted)'; empty.textContent = 'The preview appears once the configuration has columns.'; stage.append(empty); return; } grid = createGrid(stage, options); }; const convert = () => { const from = fromSelect.value as MigrationSource; try { const result = convertSnippet(textarea.value, from); converted = result.output; code.textContent = result.output; renderWarnings(list, result.warnings); showPreview(result); const manual = result.warnings.filter((w) => w.severity === 'manual').length; const checks = result.warnings.filter((w) => w.severity === 'warning').length; status.textContent = `Converted ${result.kind === 'columns' ? 'column definitions' : 'grid options'}: ${manual} manual step${manual === 1 ? '' : 's'}, ${checks} to check${result.modules.length ? `, Grid Pro modules: ${result.modules.join(', ')}` : ''}.`; } catch (error) { converted = ''; code.textContent = (error as Error).message; renderWarnings(list, []); showPreview(null); status.textContent = 'The configuration could not be parsed. Nothing is evaluated, so function calls must be replaced by values.'; } }; const schedule = () => { if (timer) clearTimeout(timer); timer = setTimeout(convert, 250); }; const loadSample = () => { const sample = SAMPLES.find((s) => s.id === sampleSelect.value) ?? SAMPLES[0]; fromSelect.value = sample.from; textarea.value = sample.source; convert(); }; const copy = button('Copy result', () => { if (!converted) return; navigator.clipboard?.writeText(converted).then( () => (status.textContent = 'Copied the converted configuration.'), () => (status.textContent = 'Copying is not allowed here; select the text instead.'), ); }); toolbar.append(field('Example', sampleSelect), field('Library', fromSelect), copy); sampleSelect.addEventListener('change', loadSample); fromSelect.addEventListener('change', convert); textarea.addEventListener('input', schedule); const stopTheme = onDocsThemeChange((theme) => grid?.update({ theme })); loadSample(); return () => { if (timer) clearTimeout(timer); sampleSelect.removeEventListener('change', loadSample); fromSelect.removeEventListener('change', convert); textarea.removeEventListener('input', schedule); stopTheme(); grid?.destroy(); }; } ``` Nothing you paste is evaluated. Functions and variable names are kept as placeholders, callbacks are rewritten as text (`(params) => params.data.price` becomes `(row) => row.price`), and the preview leaves out anything that would need your own code to run, such as cell renderers and formatters. ## Run the codemod Install the tool next to TypeScript, which it uses to parse your files: ```sh npm install --save-dev @birchui/migrate typescript ``` Start with a dry run. It prints a unified diff and a summary and does not change any file: ```sh npx birchui-migrate "src/**/*.{ts,tsx,js,jsx,vue,html}" --report migration-report.md ``` ```text 14 files scanned, 6 would change. 83 converted, 7 manual steps, 12 warnings. Estimated effort: about 3 hours. Run again with --write to apply the changes. ``` When the diff looks right, commit your work, apply the changes and format the files: ```sh npx birchui-migrate "src/**/*.{ts,tsx,js,jsx,vue,html}" --write npx prettier --write src ``` | Option | Description | | --- | --- | | `` | Files, directories or globs. `node_modules`, `dist` and `build` are skipped | | `--from ag-grid` or `--from mui` | Only convert one library. By default it is detected from the imports | | `--framework react\|vue\|angular\|js` | Override the framework detected from the imports | | `--write` | Write the converted files | | `--report ` | Write a markdown report | | `--quiet` | Print only the summary | Running the tool again on converted files changes nothing, so you can migrate a large codebase folder by folder. ## What it converts | Code | Result | | --- | --- | | React `` | `` with converted props and `on…` event props. Grid Pro modules are hoisted to a constant, the `ag-theme-*` class of the wrapper becomes `theme`, and `gridRef.current.api.x()` calls go to the ref, which is the full `GridApi` | | `createGrid(el, options)` and `new Grid(el, options)` | `createGrid` from `@birchui/core`. Event handlers move to `grid.on(name, handler)` after the call | | Vue `` | `` with kebab-case bindings and `@event` handlers. Declarations in ` ``` **Angular** ```ts import { Component, input } from '@angular/core'; import { BirchGridComponent } from '@birchui/angular'; @Component({ selector: 'app-orders-grid', standalone: true, imports: [BirchGridComponent], template: ``, }) export class OrdersGridComponent { orders = input.required(); columns = columns; onSelection(event: { selected: Order[] }) { console.info(event.selected.length, 'orders selected'); } } ``` **Svelte** ```svelte
console.info(selected.length, 'orders selected')} />
``` **Solid** ```tsx import { BirchGrid } from '@birchui/solid'; export function OrdersGrid(props: { orders: Order[] }) { return ( style={{ height: '420px' }} columns={columns} rows={props.orders} rowSelection="multiple" onSelectionChanged={({ selected }) => console.info(selected.length, 'orders selected')} /> ); } ``` **Web Component** ```html ``` > **Note** > > Event names follow each framework's conventions: `onSelectionChanged` props in React, Svelte and Solid, `@selection-changed` in Vue, `(selectionChanged)` outputs in Angular and `selection-changed` DOM events, with the payload in `event.detail`, on ``. See [React](https://docs.birchui.com/frameworks/react.md), [Vue](https://docs.birchui.com/frameworks/vue.md), [Angular](https://docs.birchui.com/frameworks/angular.md), [Svelte](https://docs.birchui.com/frameworks/svelte.md), [Solid](https://docs.birchui.com/frameworks/solid.md) and [Web Component](https://docs.birchui.com/frameworks/web-component.md) for the exact bindings. ## What is included Everything below ships in `@birchui/core` under the MIT license, with no license key and no watermark. | Area | Features | Guide | | --- | --- | --- | | Data | Plain arrays of objects, stable row IDs, transactions for add, update and remove | [Rows](https://docs.birchui.com/grid/rows.md), [Updating data](https://docs.birchui.com/grid/updating-data.md) | | Columns | Text, number, date and boolean types, `flex` sizing, value getters, setters, formatters and cell renderers | [Columns](https://docs.birchui.com/grid/columns.md) | | Sorting | Single and multi-column sorting, type-aware comparison, custom comparators | [Sorting](https://docs.birchui.com/grid/sorting.md) | | Filtering | Floating filters with an expression syntax, text, number, date, set and boolean filters, quick filter, custom predicates | [Filtering](https://docs.birchui.com/grid/filtering.md) | | Editing | Text, number, select, checkbox and date editors, custom editors, value parsing | [Editing](https://docs.birchui.com/grid/editing.md) | | Selection | Single or multiple row selection, checkbox column | [Selection](https://docs.birchui.com/grid/selection.md) | | Column operations | Resize, reorder, pin, hide, autosize, persistable column state | [Column operations](https://docs.birchui.com/grid/column-operations.md) | | Pagination | Client-side pages with a page size | [Pagination](https://docs.birchui.com/grid/pagination.md) | | Performance | Row and column virtualization, variable row heights, a million rows in the browser | [Virtualization](https://docs.birchui.com/grid/virtualization.md) | | Accessibility | WAI-ARIA grid pattern, roving tabindex, correct `aria-rowcount` while virtualized | [Accessibility](https://docs.birchui.com/grid/accessibility.md) | | Theming | CSS custom properties, light, dark and auto themes, three densities | [Theming](https://docs.birchui.com/grid/theming.md) | | Export | CSV export as a string or a file download | [CSV export](https://docs.birchui.com/grid/csv-export.md) | | Extensibility | A module system with pipeline stages, cell decorators, key handlers and UI slots | [Modules](https://docs.birchui.com/grid/modules.md) | ## When you need Grid Pro > **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md** > > Row grouping, aggregation, tree data, pivoting, range selection, clipboard copy and paste, the fill handle, master/detail rows, the status bar and styled Excel import and export live in `@birchui/grid-pro`. They plug into the same grid through the `modules` option, so upgrading never means rewriting your columns or event handlers. ```ts import { createGrid } from '@birchui/core'; import { RowGroupingModule, AggregationModule } from '@birchui/grid-pro'; createGrid(container, { columns, rows: orders, modules: [RowGroupingModule, AggregationModule], groupBy: ['region'], }); ``` Start with the [Grid Pro overview](https://docs.birchui.com/grid-pro/overview.md) to see what each module adds, or read [Licensing](https://docs.birchui.com/getting-started/licensing.md) for how keys work. ## Next steps - Follow the [Quick start](https://docs.birchui.com/getting-started/quick-start.md) for your framework. - Read [Columns](https://docs.birchui.com/grid/columns.md) to learn how values flow from rows to cells. - Browse the [API reference](https://docs.birchui.com/grid/api-reference.md) for every method on `GridApi`. --- Source: https://docs.birchui.com/grid/columns/ # Columns > Define what each column shows and how it behaves with ColumnDef, from field paths and types to value getters, formatters and cell renderers. Columns are described by an array of `ColumnDef` objects passed as `columns`. A column definition says where a value comes from, how it is compared, filtered and edited, and how it is displayed. Only one of `field` or `id` is required; every other property has a sensible default. ```ts title="invoice-columns.ts" import { createGrid, type ColumnDef } from '@birchui/core'; interface Invoice { number: string; customer: { name: string; country: string }; issued: string; due: string; amount: number; paid: boolean; } const columns: ColumnDef[] = [ { field: 'number', header: 'Invoice', width: 130, pinned: 'left' }, { field: 'customer.name', header: 'Customer', flex: 2, minWidth: 200 }, { field: 'customer.country', header: 'Country', width: 120, filter: true }, { field: 'issued', type: 'date', width: 130 }, { field: 'due', type: 'date', width: 130 }, { field: 'amount', type: 'number', width: 140, format: (v) => `€${Number(v).toLocaleString('de-DE', { minimumFractionDigits: 2 })}` }, { field: 'paid', type: 'boolean', width: 90 }, ]; createGrid(document.querySelector('#invoices')!, { columns, rows: invoices, getRowId: (i) => i.number }); ``` ## Column IDs and headers Every column has an ID used by the API, sort and filter models, column state and events. It is resolved in this order: 1. `id`, when set. 2. `field`, when set. 3. `col`, the position in the `columns` array. If two columns resolve to the same ID, the later one gets a suffix, so set an explicit `id` whenever you show the same field twice. IDs starting with two underscores are reserved for columns the grid generates, such as the selection checkbox column `__select`. When `header` is omitted, the grid derives a label from the ID: it takes the last segment of a dotted path, turns underscores and hyphens into spaces, splits camelCase words and capitalizes the first letter. `orderDate` becomes "Order Date" and `customer.country` becomes "Country". `headerTooltip` sets the native tooltip on the header cell. ```ts const columns: ColumnDef[] = [ { field: 'amount', header: 'Net amount', headerTooltip: 'Excluding VAT' }, { id: 'amountGross', field: 'amount', header: 'Gross amount', valueGetter: (row) => row.amount * 1.19 }, ]; ``` ## Fields and nested paths `field` is a property name or a dotted path into the row. `customer.name` reads `row.customer.name` and returns `undefined` if any segment is missing, so incomplete rows never throw. When a cell with a nested `field` is edited, the grid writes back along the same path and creates missing intermediate objects. ## Column types `type` controls default comparison, filtering, editing, alignment and formatting. It defaults to `'text'`. | Type | Sorting | Default format | Default editor | Default alignment | Filter when `filter: true` | | --- | --- | --- | --- | --- | --- | | `text` | Locale-aware, case-insensitive, numeric-aware ("Order 2" before "Order 10") | `String(value)` | Text input | Left | `text` | | `number` | Numeric | `Intl.NumberFormat` with up to 2 fraction digits | Text input with a decimal keypad | Right | `number` | | `date` | Chronological | `Intl.DateTimeFormat` with year, short month and day ("Mar 4, 2026") | Native date input | Left | `date` | | `boolean` | `false` before `true` | "Yes" or "No" | Checkbox | Center | `boolean` | Date columns accept `Date` objects, epoch milliseconds and ISO strings. A plain `YYYY-MM-DD` string is read as local midnight, so a due date of `2026-04-30` never shifts to the previous day in western time zones. Number columns accept numbers and numeric strings, including thousands separators such as `"12,500"`. Formatting uses the grid's `locale` option, which defaults to the browser locale: ```ts createGrid(container, { columns, rows, locale: 'de-DE' }); ``` Blank values (`null`, `undefined`, an empty string or `NaN`) render as an empty cell and always sort last. ## Width, flex and limits | Property | Default | Meaning | | --- | --- | --- | | `width` | `150` | Width in pixels. | | `minWidth` | `40` | Lower bound for resizing, flex and autosize. | | `maxWidth` | none | Upper bound for resizing, flex and autosize. | | `flex` | none | Share of the remaining horizontal space. | Columns with `flex` divide the space left over after fixed-width columns in proportion to their flex values, clamped by `minWidth` and `maxWidth`. A flex column that the user resizes keeps the width they chose and stops flexing. ```ts const columns: ColumnDef[] = [ { field: 'number', width: 120 }, { field: 'customer.name', flex: 2, minWidth: 180 }, { field: 'customer.country', flex: 1, maxWidth: 220 }, { field: 'amount', type: 'number', width: 140 }, ]; ``` ## Behaviour flags | Property | Default | Meaning | | --- | --- | --- | | `sortable` | `true` | Header click sorts. See [Sorting](https://docs.birchui.com/grid/sorting.md). | | `resizable` | `true` | The header edge can be dragged. See [Column operations](https://docs.birchui.com/grid/column-operations.md). | | `reorderable` | `true` | The header can be dragged to a new position. | | `filter` | `false` | `true` picks a filter from the column type, or name one: `'text'`, `'number'`, `'date'`, `'set'`, `'boolean'`. See [Filtering](https://docs.birchui.com/grid/filtering.md). | | `editable` | `false` | `true` or a function of the cell context. See [Editing](https://docs.birchui.com/grid/editing.md). | | `pinned` | `null` | `'left'` or `'right'` keeps the column in view while scrolling horizontally. | | `hidden` | `false` | Hides the column without removing it. | When `filter: true` is set and the column has `options`, the grid uses a set filter. ## Reading values: valueGetter By default a cell's value is `row[field]`. A `valueGetter` computes it instead. Its result is what the grid sorts, filters, exports and passes to `format` and `cell`. ```ts interface OrderLine { sku: string; quantity: number; unitPrice: number; discountRate: number; } const columns: ColumnDef[] = [ { field: 'sku', header: 'SKU' }, { field: 'quantity', type: 'number' }, { field: 'unitPrice', header: 'Unit price', type: 'number' }, { id: 'lineTotal', header: 'Line total', type: 'number', valueGetter: (line) => line.quantity * line.unitPrice * (1 - line.discountRate), }, ]; ``` Value getters run often: on every render of a visible cell and for every row while sorting or filtering. Keep them cheap and pure. If a getter throws, the grid reports it with `console.error` and treats the value as `undefined`. See [Virtualization & performance](https://docs.birchui.com/grid/virtualization.md#keep-value-getters-cheap) for large datasets. ## Writing values: valueSetter When an editable cell commits, the grid writes the new value to `row[field]`. Columns that use a `valueGetter` need a `valueSetter` to be editable in a meaningful way: ```ts const fullName: ColumnDef<{ firstName: string; lastName: string }> = { id: 'name', header: 'Technician', editable: true, valueGetter: (t) => `${t.firstName} ${t.lastName}`, valueSetter: (t, value) => { const [first, ...rest] = String(value).trim().split(/\s+/); t.firstName = first ?? ''; t.lastName = rest.join(' '); }, }; ``` ## Formatting: format `format(value, row)` returns the display string. It replaces the type's default formatter and is also used by the quick filter and by CSV export when `formatted: true`. `row` is `undefined` for rows that do not carry data, such as group rows in Grid Pro. ```ts const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); const shortDate = new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: 'short' }); const columns: ColumnDef[] = [ { field: 'revenue', type: 'number', format: (v) => (v == null ? '' : usd.format(Number(v))) }, { field: 'orderDate', type: 'date', format: (v) => shortDate.format(new Date(String(v))) }, { field: 'quantity', type: 'number', format: (v, row) => `${v} ${row?.unit ?? 'pcs'}` }, ]; ``` Sorting and filtering always use the raw value, never the formatted string, so a currency column still sorts numerically. ## Cell renderers: cell `cell(ctx)` takes over the cell's content. Return a string (inserted as text, never as HTML), a DOM `Node`, `null` for an empty cell, or nothing (`undefined`) to keep the formatted value. If the renderer throws, the grid reports the error with `console.error` and shows the formatted value. The context gives you the raw `value`, the `formatted` string, the `row`, the `column`, the `rowIndex` and the `api`. ```ts import type { CellContext, ColumnDef } from '@birchui/core'; const statusColors: Record = { Shipped: '#1a7f37', Pending: '#9a6700', Backordered: '#cf222e', Cancelled: '#656d76', }; function statusBadge(ctx: CellContext): Node { const badge = document.createElement('span'); badge.className = 'status-badge'; badge.textContent = ctx.formatted; badge.style.color = statusColors[String(ctx.value)] ?? 'inherit'; return badge; } const columns: ColumnDef[] = [ { field: 'status', cell: statusBadge }, { id: 'actions', header: '', width: 110, sortable: false, cell: (ctx) => { const button = document.createElement('button'); button.type = 'button'; button.textContent = 'Open'; button.addEventListener('click', () => openOrder(ctx.row!.id)); return button; }, }, ]; ``` > **Tip** > > Cells are recycled while scrolling. Build the node from `ctx` every time and avoid holding references to rendered cells. For heavy content, keep the renderer small and see [Virtualization & performance](https://docs.birchui.com/grid/virtualization.md). ## Styling cells: cellClass, headerClass and align `cellClass` adds classes to the cell element: a fixed string or a function of the cell context. `headerClass` adds classes to the header cell. `align` overrides the type's default alignment. ```ts const columns: ColumnDef[] = [ { field: 'due', type: 'date', cellClass: (ctx) => (!ctx.row?.paid && new Date(String(ctx.value)) < new Date() ? 'invoice-overdue' : undefined), }, { field: 'amount', type: 'number', headerClass: 'header-emphasis', align: 'right' }, { field: 'number', align: 'center' }, ]; ``` ```css title="invoices.css" .lq-grid .invoice-overdue { color: #cf222e; font-weight: 600; } .lq-grid .header-emphasis { font-weight: 700; } ``` ## Shared defaults: defaultColumn `defaultColumn` is merged under every column definition. Properties set on a column always win. ```ts createGrid(container, { defaultColumn: { filter: true, minWidth: 100, resizable: true }, columns: [ { field: 'customer', flex: 1 }, { field: 'region' }, { field: 'revenue', type: 'number', filter: 'number' }, { id: 'actions', filter: false, sortable: false, cell: renderActions }, ], rows: orders, }); ``` ## Your own data: meta `meta` is a free-form object the grid never reads. Use it for anything your renderers, modules or toolbars need, such as a unit, a permission or an analytics label. ```ts const columns: ColumnDef[] = [ { field: 'revenue', type: 'number', meta: { unit: 'USD', sensitive: true } }, ]; const sensitiveIds = grid.getColumns().filter((c) => c.def.meta?.sensitive).map((c) => c.id); ``` ## Resolved columns The grid turns each `ColumnDef` into a `ResolvedColumn` with every default filled in. `getColumns()` returns them in display order, `getDisplayColumns()` only the visible ones (left-pinned, then unpinned, then right-pinned), and `getColumn(colId)` one by ID. The original definition is always available as `column.def`. ```ts const revenue = grid.getColumn('revenue'); console.info(revenue?.width, revenue?.align, revenue?.filter); ``` **`ResolvedColumn`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface ResolvedColumn ``` | Property | Type | Description | | --- | --- | --- | | `id` | `string` | | | `def` | `ColumnDef` | | | `header` | `string` | | | `type` | `ColumnType` | | | `width` | `number` | | | `minWidth` | `number` | | | `maxWidth` | `number` | | | `pinned` | `'left' \| 'right' \| null` | | | `hidden` | `boolean` | | | `sortable` | `boolean` | | | `resizable` | `boolean` | | | `reorderable` | `boolean` | | | `rowHeader` | `boolean` | | | `filter` | `FilterKind \| null` | | | `align` | `'left' \| 'center' \| 'right'` | | | `generated` | `boolean` | | ## Grid Pro column properties > **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md** > > `aggFunc`, `rowGroup`, `rowGroupIndex`, `pivot` and `pivotIndex` are read by Grid Pro modules. Without those modules installed they have no effect. See [Row grouping](https://docs.birchui.com/grid-pro/row-grouping.md), [Aggregation](https://docs.birchui.com/grid-pro/aggregation.md) and [Pivoting](https://docs.birchui.com/grid-pro/pivoting.md). ## ColumnDef reference **`ColumnDef`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface ColumnDef ``` | Property | Type | Description | | --- | --- | --- | | `id?` | `string` | | | `field?` | `string` | | | `header?` | `string` | | | `headerTooltip?` | `string` | | | `type?` | `ColumnType` | | | `width?` | `number` | | | `minWidth?` | `number` | | | `maxWidth?` | `number` | | | `flex?` | `number` | | | `pinned?` | `'left' \| 'right' \| null` | | | `hidden?` | `boolean` | | | `sortable?` | `boolean` | | | `resizable?` | `boolean` | | | `reorderable?` | `boolean` | | | `rowHeader?` | `boolean` | | | `filter?` | `boolean \| FilterKind` | | | `editable?` | `boolean \| ((ctx: CellContext) => boolean)` | | | `editor?` | `EditorKind \| CellEditorFactory` | | | `options?` | `readonly SelectOption[]` | | | `valueGetter?` | `(row: TRow) => unknown` | | | `valueSetter?` | `(row: TRow, value: unknown) => void` | | | `valueParser?` | `(input: string, row: TRow) => unknown` | | | `format?` | `(value: unknown, row: TRow \| undefined) => string` | | | `cell?` | `(ctx: CellContext) => string \| Node \| null \| void` | | | `cellClass?` | `string \| ((ctx: CellContext) => string \| undefined)` | | | `headerClass?` | `string` | | | `align?` | `'left' \| 'center' \| 'right'` | | | `comparator?` | `(a: unknown, b: unknown, rowA: TRow, rowB: TRow) => number` | | | `aggFunc?` | `AggFuncName \| AggFunc` | | | `rowGroup?` | `boolean` | | | `rowGroupIndex?` | `number` | | | `pivot?` | `boolean` | | | `pivotIndex?` | `number` | | | `meta?` | `Record` | | | `columnGroupShow?` | `'open' \| 'closed'` | | | `autoHeight?` | `boolean` | | | `wrapText?` | `boolean` | | | `rowDrag?` | `boolean` | | ## Changing columns at runtime Replace the full column list with `setColumns()` or `update({ columns })`. Widths, pinning, visibility and order that the user changed are kept for columns whose ID survives. See [Updating data](https://docs.birchui.com/grid/updating-data.md#changing-columns). --- Source: https://docs.birchui.com/grid/rows/ # Rows & row IDs > Pass rows as plain objects, give them stable IDs with getRowId, and understand the display rows the grid renders. Rows are plain JavaScript objects passed as the `rows` option. The grid never clones or wraps them: the objects you pass are the objects you get back from `getRows()`, `getSelectedRows()` and every event payload. Type them once with the grid's generic parameter and the whole API follows. ```ts title="technicians-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; interface Technician { employeeId: string; name: string; region: string; skills: string[]; openTickets: number; certifiedUntil: string; } const technicians: Technician[] = [ { employeeId: 'T-0142', name: 'Amira Haddad', region: 'North', skills: ['HVAC', 'Electrical'], openTickets: 3, certifiedUntil: '2027-01-31' }, { employeeId: 'T-0187', name: 'Lukas Brandt', region: 'Central', skills: ['Plumbing'], openTickets: 7, certifiedUntil: '2026-09-30' }, { employeeId: 'T-0203', name: 'Priya Nair', region: 'South', skills: ['Electrical', 'Solar'], openTickets: 1, certifiedUntil: '2027-04-15' }, ]; const columns: ColumnDef[] = [ { field: 'employeeId', header: 'ID', width: 100 }, { field: 'name', flex: 1 }, { field: 'region' }, { id: 'skills', header: 'Skills', valueGetter: (t) => t.skills.join(', ') }, { field: 'openTickets', header: 'Open tickets', type: 'number' }, { field: 'certifiedUntil', header: 'Certified until', type: 'date' }, ]; const grid = createGrid(document.querySelector('#technicians')!, { columns, rows: technicians, getRowId: (t) => t.employeeId, }); ``` ## Row IDs Every row has a string ID. IDs drive selection, expansion state, transactions, `getRowById()` and focus restoration after data changes. ### Provide getRowId whenever rows have a key `getRowId(row, index)` returns the ID for a row. Use your primary key: ```ts createGrid(container, { columns, rows: orders, getRowId: (order) => order.id, }); ``` With `getRowId`, a row keeps its identity even when you replace the object, for example after re-fetching from the server. Selection survives a refresh and `applyTransaction({ update })` can match fresh objects to existing rows. ### Without getRowId If you omit `getRowId`, the grid assigns IDs such as `r1`, `r2` and remembers them per object instance. Passing the same objects again keeps their IDs. Passing new objects, even with identical contents, creates new rows with new IDs, which clears their selection and expansion state. > **Duplicate IDs** > > IDs must be unique. If `getRowId` returns the same value for two rows, the grid keeps both rows but suffixes the second ID with `#`, so `getRowById()` finds only the first. Fix the key rather than relying on the suffix. ### Looking rows up ```ts const id = grid.getRowId(technicians[0]); const lukas = grid.getRowById('T-0187'); const all = grid.getRows(); ``` **`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridApi extends Widget, GridEvents>, GridFeatureApi ``` | Property | Type | Description | | --- | --- | --- | | `getRows` | `() => readonly TRow[]` | | | `getRowId` | `(row: TRow) => string` | | | `getRowById` | `(id: string) => TRow \| undefined` | | | `getDisplayRows` | `() => readonly DisplayRow[]` | | | `getAllDisplayRows` | `() => readonly DisplayRow[]` | | | `getRenderedRows` | `() => readonly DisplayRow[]` | | | `getDisplayRow` | `(rowIndex: number) => DisplayRow \| undefined` | | ## Source rows and display rows The grid keeps two lists: - **Source rows** are your objects, in the order you passed them. `getRows()` returns them. - **Display rows** are what the grid renders after filtering, sorting, pagination and any module stages such as grouping. `getDisplayRows()` returns them, and every `rowIndex` in the API and in events is an index into this list. - **All display rows** are the same list before pagination slices it into pages. `getAllDisplayRows()` returns them. Without pagination the two lists are identical; with pagination, `getDisplayRows()` holds only the current page. ```ts const onThisPage = grid.getDisplayRows().length; const matchingFilters = grid.getAllDisplayRows().filter((row) => row.kind === 'data').length; pageInfo.textContent = `${onThisPage} shown, ${matchingFilters} technicians match`; ``` Each display row is a `DisplayRow` that wraps your data with rendering state: ```ts const first = grid.getDisplayRow(0); if (first?.kind === 'data') { console.info(first.id, first.data?.name, first.sourceIndex); } ``` | Kind | Produced by | `data` | | --- | --- | --- | | `data` | Every source row that passes the filters | The source row | | `group` | Row grouping and tree data (Grid Pro) | `undefined`, see `group` and `aggregates` | | `detail` | Master/detail (Grid Pro) | The master row | | `total` | Group totals and pivot totals (Grid Pro) | `undefined`, see `aggregates` | **`DisplayRow`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface DisplayRow ``` | Property | Type | Description | | --- | --- | --- | | `kind` | `DisplayRowKind` | | | `id` | `string` | | | `data` | `TRow \| undefined` | | | `depth` | `number` | | | `sourceIndex` | `number` | | | `expandable` | `boolean` | | | `expanded` | `boolean` | | | `parentId?` | `string` | | | `group?` | `DisplayRowGroup` | | | `aggregates?` | `Record` | | | `fullWidth?` | `boolean` | | | `height?` | `number` | | `getRenderedRows()` returns only the display rows that currently have DOM elements, which is the visible window plus the overscan. See [Virtualization & performance](https://docs.birchui.com/grid/virtualization.md). ## Converting between indexes and rows Events report both the row and its `rowIndex`. To go the other way: ```ts grid.on('cellClick', ({ row, rowIndex, colId }) => { const displayRow = grid.getDisplayRow(rowIndex); console.info(colId, row?.name, displayRow?.id); }); const index = grid.getDisplayRows().findIndex((r) => r.id === 'T-0203'); if (index >= 0) grid.scrollToRow(index, 'center'); ``` ## Row classes and stripes `rowClass(displayRow)` returns classes for a row element. It runs for every rendered row, so keep it cheap. ```ts createGrid(container, { columns, rows: technicians, getRowId: (t) => t.employeeId, stripes: true, rowClass: (row) => (row.data && row.data.openTickets > 5 ? 'row-overloaded' : undefined), }); ``` ```css .lq-grid .lq-row.row-overloaded { background: #fff8e6; } ``` Every row element also carries built-in classes you can target: `lq-row`, `lq-row-even` or `lq-row-odd`, `lq-row-data`, `lq-row-group`, `lq-row-detail` or `lq-row-total` by kind, `lq-row-selected` and `lq-row-focused`. `stripes: true` shades odd rows with `--lq-row-alt`. Because the grid's own row rules use two classes, give your overrides at least three (as above) so they win regardless of stylesheet order. See [Theming](https://docs.birchui.com/grid/theming.md#overriding-styles). ## Row height `rowHeight` is a number for uniform rows or a function of the display row for variable heights. Without it, the height follows `density`: 28 pixels for `compact`, 34 for `normal` and 42 for `comfortable`. ```ts createGrid(container, { columns, rows: technicians, rowHeight: (row) => (row.data && row.data.skills.length > 2 ? 56 : 36), }); ``` Uniform heights are the fastest path. Variable heights are supported at any scale; the grid measures offsets once per data change, not per scroll. If the function throws or returns something that is not a positive number, that row falls back to the default height and a thrown error is reported with `console.error`. See [Virtualization & performance](https://docs.birchui.com/grid/virtualization.md#variable-row-heights). ## Empty grids When no display rows remain, either because `rows` is empty or because filters removed everything, the grid shows `emptyMessage` in the body. The default is "No rows to show". ```ts createGrid(container, { columns, rows: [], emptyMessage: 'No technicians match these filters', }); ``` ## Related - [Updating data](https://docs.birchui.com/grid/updating-data.md) covers `setRows`, `applyTransaction` and `update()`. - [Selection](https://docs.birchui.com/grid/selection.md) relies on stable row IDs. - [Tree data](https://docs.birchui.com/grid-pro/tree-data.md) and [Row grouping](https://docs.birchui.com/grid-pro/row-grouping.md) add `group` rows. --- Source: https://docs.birchui.com/grid/updating-data/ # Updating data > Replace rows with setRows, apply incremental changes with applyTransaction, change any option with update(), and know when to refresh or redraw. The grid owns no data of its own. It renders the rows you pass and re-runs its pipeline (filter, sort, paginate and any module stages) whenever you tell it the data changed. There are three ways to do that, from coarse to fine. | You want to | Use | Keeps selection, focus and scroll | | --- | --- | --- | | Load a new dataset | `setRows(rows)` or `update({ rows })` | Yes, for rows whose ID survives | | Add, change or remove a few rows | `applyTransaction({ add, update, remove })` | Yes | | Change any other option | `update({ ...partial })` | Yes | | Re-render after mutating a row object in place | `refresh()` | Yes | ## Replacing all rows: setRows ```ts title="load-orders.ts" import { createGrid, type ColumnDef } from '@birchui/core'; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: [], getRowId: (order) => order.id, emptyMessage: 'Loading orders…', }); async function loadOrders(region: string) { const response = await fetch(`/api/orders?region=${encodeURIComponent(region)}`); grid.setRows(await response.json()); } await loadOrders('EMEA'); ``` `setRows()` keeps the current sort, filters, quick filter and column state, and keeps the current page when it still exists. With `getRowId`, selected rows stay selected if they are still present. Selected rows that are missing from the new data are deselected, and `selectionChanged` fires when that happens. `setRows(rows)` is shorthand for `update({ rows })`, which is what framework adapters call when the `rows` prop changes. > **Pass a new array** > > `update()` only applies keys whose value changed by identity. Calling `setRows(rows)` with the same array you passed before, even after pushing to it, does nothing. Pass a new array (`setRows([...rows])`), or use `applyTransaction()` for incremental changes. ## Incremental changes: applyTransaction A transaction adds, updates and removes rows in one pass and one re-render. It is the right tool for live feeds, websocket pushes and optimistic UI. ```ts grid.applyTransaction({ add: [{ id: 'SO-10431', customer: 'Fjord Outfitters', region: 'EMEA', orderDate: '2026-03-09', quantity: 20, revenue: 9100, status: 'Pending' }], update: [{ ...grid.getRowById('SO-10422')!, status: 'Shipped' }], remove: ['SO-10398', 'SO-10401'], }); ``` **`RowTransaction`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface RowTransaction ``` | Property | Type | Description | | --- | --- | --- | | `add?` | `TRow[]` | | | `update?` | `TRow[]` | | | `remove?` | `(TRow \| string)[]` | | The parts run in a fixed order: 1. **remove** takes row objects or row IDs. Rows that are not present are ignored. 2. **update** replaces existing rows, matched by ID, keeping their position in the source order. Rows that do not match an existing ID are ignored. 3. **add** appends new rows to the end of the source rows. Sorting still decides where they appear. Removed rows also leave the selection, and `selectionChanged` fires if any of them was selected. > **Updates need stable IDs** > > `update` finds rows by ID. With `getRowId`, a freshly built object such as `{ ...row, status: 'Shipped' }` matches the existing row. Without `getRowId`, IDs are tied to object instances, so only the original objects match. Set `getRowId` for any grid that receives updates. ### Streaming updates Batch high-frequency messages and apply them once per animation frame: ```ts const pending: Order[] = []; let scheduled = false; socket.addEventListener('message', (event) => { pending.push(JSON.parse(event.data)); if (scheduled) return; scheduled = true; requestAnimationFrame(() => { grid.applyTransaction({ update: pending.splice(0) }); scheduled = false; }); }); ``` ## Changing options: update() `update(partial)` applies only the keys you pass and never recreates the grid. Anything in `GridOptions` can change at runtime. ```ts grid.update({ theme: 'dark', density: 'compact' }); grid.update({ quickFilter: 'kestrel' }); grid.update({ sort: [{ colId: 'revenue', dir: 'desc' }] }); grid.update({ pagination: { pageSize: 50 } }); ``` Keys you leave out keep their current value, and keys whose value is identical to the current one are skipped. To clear an option, pass its empty value explicitly, for example `update({ quickFilter: '' })` or `update({ filterModel: {} })`. Read the current options with `getOptions()`. Changing `pagination` returns to the page given in it, or to the first page. State options applied through `update()` fire the same events as the dedicated methods: `sort` fires `sortChanged`, and `filterModel` or `quickFilter` fire `filterChanged` and return to the first page. Changing `modules` uninstalls modules that are no longer listed and installs new ones. ## Changing columns Replace the column list with `setColumns(columns)` or `update({ columns })`. The grid keeps user changes (width, pinning, visibility and order) for every column whose ID still exists, so you can add a column without resetting the layout the user arranged. ```ts const withMargin: ColumnDef[] = [ ...columns, { id: 'margin', header: 'Margin', type: 'number', valueGetter: (o) => o.revenue - o.cost }, ]; grid.setColumns(withMargin); ``` To reset the layout instead, apply a saved column state or the defaults. See [Column operations](https://docs.birchui.com/grid/column-operations.md#saving-and-restoring-column-state). ## Editing values from code `setValue(row, colId, value, source?)` writes through the column's `valueSetter` or `field`, re-renders the row and fires `cellValueChanged` with `source: 'api'` unless you pass another source. It returns `false`, and fires nothing, when the column does not exist, when the new value is identical to the current one, or when the `valueSetter` throws. ```ts const order = grid.getRowById('SO-10423')!; grid.setValue(order, 'status', 'Shipped'); ``` ## Mutating rows in place: refresh and redraw If you change a row object directly, the grid cannot know. Call one of: - `refresh()` re-runs the row pipeline (filter, sort, module stages, pagination) and re-renders. Use it after in-place mutations that can affect sorting or filtering. - `redraw()` re-renders the header and every visible cell without re-running the pipeline. Use it after changing something that only affects rendering, such as a lookup table a cell renderer reads. ```ts const order = grid.getRowById('SO-10421')!; order.revenue = 19250; grid.refresh(); exchangeRates.EUR = 1.09; grid.redraw(); ``` > **Tip** > > Prefer `applyTransaction({ update: [...] })` or `setValue()` over mutate-then-refresh. They tell the grid exactly which rows changed, keep the quick filter's cached search text in sync and fire the right events. After an in-place mutation, the quick filter may still match the row's old text until the row is replaced. ## Knowing when the model changed `modelUpdated` fires after every pipeline run with the number of source rows and display rows: ```ts grid.on('modelUpdated', ({ rowCount, displayRowCount }) => { summary.textContent = `${displayRowCount} of ${rowCount} orders`; }); ``` ## Related - [Rows & row IDs](https://docs.birchui.com/grid/rows.md) - [Editing](https://docs.birchui.com/grid/editing.md) for user edits and `cellValueChanged` - [Virtualization & performance](https://docs.birchui.com/grid/virtualization.md) for very large or fast-changing datasets --- Source: https://docs.birchui.com/grid/sorting/ # Sorting > Sort by one or many columns from the header or from code, with type-aware comparison and custom comparators. Every column is sortable unless you set `sortable: false`. Clicking a header cycles through ascending, descending and unsorted. The grid compares raw values according to the column type, so numbers, dates and booleans sort correctly even when they are formatted for display. **Live demo: Sorting, floating filters and quick filter** (runs on the HTML version of this page). Source of `demos/sorting-filtering.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { docsTheme, field, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order, } from './_shared'; export const meta = { title: 'Sorting, floating filters and quick filter', height: 480 }; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 150 }, { field: 'region', header: 'Region', width: 130, filter: 'set' }, { field: 'status', header: 'Status', width: 116, filter: 'set' }, { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency }, { field: 'orderDate', header: 'Ordered', type: 'date', width: 120 }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const search = document.createElement('input'); search.type = 'search'; search.placeholder = 'Customer, product, rep…'; toolbar.append(field('Quick filter', search), 'Shift+click a header to add a sort level. Try >5000 in Revenue.'); const grid = createGrid(body, { columns, rows: makeOrders(2000), getRowId: (order) => order.id, defaultColumn: { sortable: true, filter: true }, floatingFilters: true, multiSort: true, sort: [{ colId: 'revenue', dir: 'desc' }], theme: docsTheme(), ariaLabel: 'Orders with sorting and filtering', }); const describe = () => { const sort = grid .getSort() .map((s) => `${s.colId} ${s.dir}`) .join(', ') || 'none'; const filters = Object.keys(grid.getFilterModel()).join(', ') || 'none'; const shown = grid.getDisplayRows().length; status.textContent = `${shown.toLocaleString()} of ${grid.getRows().length.toLocaleString()} orders. Sort: ${sort}. Filters: ${filters}.`; }; const onInput = () => grid.setQuickFilter(search.value); search.addEventListener('input', onInput); const offs = [ grid.on('modelUpdated', describe), grid.on('sortChanged', describe), grid.on('filterChanged', describe), ]; const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); describe(); return () => { search.removeEventListener('input', onInput); for (const off of offs) off(); stopTheme(); grid.destroy(); }; } ``` ## The sort model The current sort is an array of `SortItem` objects. The first item is the primary sort key, the second breaks ties in the first, and so on. **`SortItem`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface SortItem ``` | Property | Type | Description | | --- | --- | --- | | `colId` | `string` | | | `dir` | `SortDirection` | | Set an initial sort with the `sort` option: ```ts title="orders-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (o) => o.id, sort: [ { colId: 'region', dir: 'asc' }, { colId: 'revenue', dir: 'desc' }, ], }); ``` `colId` is the column ID, which is the `id` or `field` of the column. Items that refer to a missing column are ignored. ## Multi-column sorting Hold Shift, Ctrl or Cmd while clicking a header to add that column to the existing sort instead of replacing it. Modifier-clicking a column that is already sorted moves it through descending and then out of the sort, leaving the other columns in place. The header shows ▲ or ▼, followed by the column's position in the sort when more than one column is sorted. From the keyboard, focus a header and press Enter or Space to sort, or Shift+Enter to add the column to a multi-column sort. Every change is announced to screen readers, for example "Sorted by Revenue, descending". Multi-column sorting is on by default. Set `multiSort: false` to make modifier clicks behave like plain clicks, so only one column is ever sorted: ```ts createGrid(container, { columns, rows: orders, multiSort: false }); ``` The header's column menu also offers **Sort ascending**, **Sort descending** and **Clear sort**. Open it with the menu button on the header, a right-click, or Alt+Arrow Down on a focused header. ## How values are compared Without a comparator the grid compares by column type: | Type | Comparison | | --- | --- | | `text` | `Intl.Collator` with numeric collation and base sensitivity: case-insensitive and accent-insensitive, and "Invoice 9" sorts before "Invoice 10". Uses the grid's `locale`. | | `number` | Numeric. Numeric strings such as `"1,250"` are parsed first. | | `date` | By timestamp. `Date` objects, epoch milliseconds and ISO strings can be mixed. | | `boolean` | `false` before `true`. | Two rules hold for every column: - **Blank values sort last** in both directions. `null`, `undefined`, empty strings and `NaN` are blank. - **Sorting is stable.** Rows that compare equal keep their previous relative order, so sorting by region and then by revenue behaves the way users expect. The value compared is the column value, meaning the result of `valueGetter` when one is set, never the output of `format`. ## Custom comparators A `comparator(a, b, rowA, rowB)` returns a negative number, zero or a positive number, like `Array.prototype.sort`. Write it for ascending order; the grid flips it for descending. ```ts const statusRank: Record = { Backordered: 0, Pending: 1, Shipped: 2, Cancelled: 3, }; const columns: ColumnDef[] = [ { field: 'status', comparator: (a, b) => statusRank[a as Order['status']] - statusRank[b as Order['status']], }, { field: 'customer', comparator: (a, b, rowA, rowB) => rowB.lifetimeValue - rowA.lifetimeValue || String(a).localeCompare(String(b)), }, ]; ``` Blank values (`null`, `undefined` and empty strings) are sorted last before your comparator is consulted, so a comparator only ever compares two non-blank values. If a comparator throws, the grid reports the error with `console.error` and treats the pair as equal. ## Sorting from code ```ts grid.setSort([{ colId: 'orderDate', dir: 'desc' }]); grid.setSort([]); const current = grid.getSort(); ``` `update({ sort })` applies a sort the same way and also fires `sortChanged`; framework adapters use it when a bound `sort` prop changes. **`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridApi extends Widget, GridEvents>, GridFeatureApi ``` | Property | Type | Description | | --- | --- | --- | | `setSort` | `(sort: SortItem[]) => void` | | | `getSort` | `() => SortItem[]` | | ## Reacting to sort changes `sortChanged` fires whenever the sort changes, from the header or from code. Use it to persist the sort or to sort on the server. ```ts grid.on('sortChanged', ({ sort }) => { localStorage.setItem('orders.sort', JSON.stringify(sort)); }); const saved = localStorage.getItem('orders.sort'); if (saved) grid.setSort(JSON.parse(saved)); ``` ### Server-side sorting To let a backend sort, keep the rows in server order and turn the header clicks into requests. Use a comparator that returns `0` on every column so the grid's stable sort keeps the order you loaded: ```ts const serverOrder = () => 0; const grid = createGrid(container, { columns: columns.map((c) => ({ ...c, comparator: serverOrder })), rows: [], getRowId: (o) => o.id, }); grid.on('sortChanged', async ({ sort }) => { const params = new URLSearchParams(sort.map((s) => ['sort', `${s.colId}:${s.dir}`])); const response = await fetch(`/api/orders?${params}`); grid.setRows(await response.json()); }); ``` ## Disabling sorting ```ts const columns: ColumnDef[] = [ { id: 'actions', header: '', sortable: false, cell: renderActions }, ]; createGrid(container, { columns, rows, defaultColumn: { sortable: false } }); ``` A column with `sortable: false` ignores header clicks, but you can still sort it from code with `setSort()`. ## Related - [Filtering](https://docs.birchui.com/grid/filtering.md) runs before sorting in the pipeline. - [Row grouping](https://docs.birchui.com/grid-pro/row-grouping.md) sorts within each group. --- Source: https://docs.birchui.com/grid/filtering/ # Filtering > Filter rows with floating filters and their expression syntax, typed filter models for text, number, date, set and boolean columns, a quick filter and custom predicates. Birch UI Grid filters rows in three complementary ways, and all of them combine with AND: - **Column filters**, one `FilterModel` per column, set from floating filters in the header or from code. - **The quick filter**, one search string matched against every visible column. - **Custom filters**, a predicate function you supply as a filter model. Filtering runs before sorting and pagination, on raw values, never on formatted text. **Live demo: Sorting, floating filters and quick filter** (runs on the HTML version of this page). Source of `demos/sorting-filtering.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { docsTheme, field, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order, } from './_shared'; export const meta = { title: 'Sorting, floating filters and quick filter', height: 480 }; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 150 }, { field: 'region', header: 'Region', width: 130, filter: 'set' }, { field: 'status', header: 'Status', width: 116, filter: 'set' }, { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency }, { field: 'orderDate', header: 'Ordered', type: 'date', width: 120 }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const search = document.createElement('input'); search.type = 'search'; search.placeholder = 'Customer, product, rep…'; toolbar.append(field('Quick filter', search), 'Shift+click a header to add a sort level. Try >5000 in Revenue.'); const grid = createGrid(body, { columns, rows: makeOrders(2000), getRowId: (order) => order.id, defaultColumn: { sortable: true, filter: true }, floatingFilters: true, multiSort: true, sort: [{ colId: 'revenue', dir: 'desc' }], theme: docsTheme(), ariaLabel: 'Orders with sorting and filtering', }); const describe = () => { const sort = grid .getSort() .map((s) => `${s.colId} ${s.dir}`) .join(', ') || 'none'; const filters = Object.keys(grid.getFilterModel()).join(', ') || 'none'; const shown = grid.getDisplayRows().length; status.textContent = `${shown.toLocaleString()} of ${grid.getRows().length.toLocaleString()} orders. Sort: ${sort}. Filters: ${filters}.`; }; const onInput = () => grid.setQuickFilter(search.value); search.addEventListener('input', onInput); const offs = [ grid.on('modelUpdated', describe), grid.on('sortChanged', describe), grid.on('filterChanged', describe), ]; const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); describe(); return () => { search.removeEventListener('input', onInput); for (const off of offs) off(); stopTheme(); grid.destroy(); }; } ``` ## Enabling filters Mark columns as filterable with `filter`, and turn on the filter row under the headers with `floatingFilters`: ```ts title="orders-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', filter: 'text' }, { field: 'customer', flex: 1, filter: true }, { field: 'region', filter: 'set', options: ['EMEA', 'North America', 'APAC', 'LATAM'] }, { field: 'orderDate', header: 'Ordered', type: 'date', filter: true }, { field: 'revenue', type: 'number', filter: true }, { field: 'priority', type: 'boolean', filter: true }, ]; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (o) => o.id, floatingFilters: true, }); ``` `filter: true` chooses the filter from the column: | Column | Filter kind | | --- | --- | | Has `options` | `set` | | `type: 'number'` | `number` | | `type: 'date'` | `date` | | `type: 'boolean'` | `boolean` | | Anything else | `text` | Pass a kind explicitly (`'text'`, `'number'`, `'date'`, `'set'` or `'boolean'`) to override the choice. `defaultColumn: { filter: true }` makes every column filterable. ## Floating filters With `floatingFilters: true` the header gets a second row with one filter control per filterable column: - **Text, number and date columns** get a text box. Users type a short expression (below) and the grid applies it 200 ms after they stop typing. The placeholder hints at the syntax: `>100, 10..20` for numbers and `>2026-01-01` for dates. An empty box clears the column's filter. - **Set and boolean columns** get a dropdown. Boolean columns offer All, Yes and No. Set columns list the column's `options`, or, without options, up to 200 distinct values found in the data, sorted naturally. Choosing All clears the filter. Keyboard users reach the filter row by pressing Arrow Down on a header, and leave it with Arrow Down (to the first row) or Arrow Up (back to the header). A header whose column is filtered shows a dotted underline under its label. ## Floating filter syntax The text box understands the same expressions as `parseFilterInput(kind, text)`, which `@birchui/core` exports so you can reuse the syntax in your own search fields. ### Number columns | Input | Meaning | Filter model | | --- | --- | --- | | `250` or `=250` or `==250` | Equal to 250 | `{ type: 'number', op: 'eq', value: 250 }` | | `!=0` or `<>0` | Not equal to 0 | `{ op: 'ne', value: 0 }` | | `>100` | Greater than 100 | `{ op: 'gt', value: 100 }` | | `>=100` | At least 100 | `{ op: 'gte', value: 100 }` | | `<50` | Less than 50 | `{ op: 'lt', value: 50 }` | | `<=50` | At most 50 | `{ op: 'lte', value: 50 }` | | `10..20`, `10 to 20` or `10–20` | Between 10 and 20, inclusive | `{ op: 'between', value: 10, valueTo: 20 }` | | `blank` or `(blank)` | Empty cells | `{ op: 'blank' }` | | `!blank` or `(not blank)` | Non-empty cells | `{ op: 'notBlank' }` | Numbers may include thousands separators, so `>12,500` works. A range can be typed in either order: `20..10` matches the same rows as `10..20`. ### Date columns | Input | Meaning | Filter model | | --- | --- | --- | | `2026-03-15` or `=2026-03-15` | On that day | `{ type: 'date', op: 'eq', value: '2026-03-15' }` | | `<2026-03-15` | Before that day | `{ op: 'before', value: '2026-03-15' }` | | `>2026-03-15` | After that day | `{ op: 'after', value: '2026-03-15' }` | | `2026-01-01..2026-03-31` or `2026-01-01 to 2026-03-31` | Between two days, inclusive | `{ op: 'between', value: '2026-01-01', valueTo: '2026-03-31' }` | | `blank` / `!blank` | Empty or non-empty | `{ op: 'blank' }` / `{ op: 'notBlank' }` | Date filters compare calendar days in local time, ignoring the time of day. `<=` and `>=` are accepted and behave like `<` and `>`; use a range when you need an inclusive bound. ### Text columns | Input | Meaning | Filter model `op` | | --- | --- | --- | | `harbor` | Contains "harbor" | `contains` | | `!harbor` | Does not contain "harbor" | `notContains` | | `=Northwind Traders` | Equals, ignoring case | `equals` | | `!=Northwind Traders` | Does not equal | `notEquals` | | `^North` | Starts with | `startsWith` | | `Foods$` | Ends with | `endsWith` | | `blank` / `!blank` | Empty or non-empty | `blank` / `notBlank` | Text matching is always case-insensitive. ### Set and boolean values `parseFilterInput('set', 'EMEA, APAC')` returns `{ type: 'set', values: ['EMEA', 'APAC'] }`, and `parseFilterInput('boolean', 'yes')` returns `{ type: 'boolean', value: true }`. Booleans accept `yes`, `true`, `y`, `1`, `on` or `x` for true and `no`, `false`, `n`, `0` or `off` for false. The floating filter UI uses dropdowns for these kinds, so this syntax matters when you build your own inputs: ```ts import { parseFilterInput } from '@birchui/core'; regionSearch.addEventListener('change', () => { grid.setFilter('region', parseFilterInput('set', regionSearch.value)); }); ``` `parseFilterInput()` returns `null` for empty or unparseable input, which `setFilter()` treats as "remove this filter". ## Filter popup Every filterable column gets a **Filter…** item in its column menu. Ctrl+Shift+F (⌘+Shift+F on macOS) on a focused header or cell opens the same dialog for that column. It works with or without floating filters. | Filter kind | Controls | | --- | --- | | `text` | Two conditions (contains, does not contain, equals, does not equal, starts with, ends with, blank, not blank) joined by AND or OR | | `number`, `date` | The same, with **Between** taking a from and a to value | | `set` | A searchable checklist with row counts and **Select all**. Values come from the column's `options`, or from the rows when it has none. Lists longer than 500 values are virtualized | | `boolean` | All, Yes or No | **Apply** (or Enter) sets the filter, **Reset** clears it, and **Close** (or Escape) leaves it as it was. Focus stays inside the dialog while it is open and returns to the column header when it closes. Invalid input, such as a missing second value for **Between**, is reported inside the dialog and nothing is applied. Two conditions are stored as a `combined` model, which you can also set from code: ```ts grid.setFilter('total', { type: 'combined', op: 'or', conditions: [ { type: 'number', op: 'lt', value: 100 }, { type: 'number', op: 'gt', value: 10000 }, ], }); ``` The floating filter shows and accepts the same filter as `<100 OR >10000`. AND binds more tightly than OR. Every label in the dialog can be translated; see [Localization](https://docs.birchui.com/grid/localization.md). ## Filter models The filter state is a record from column ID to `FilterModel`. You can set it up front with `filterModel`, change it with the API and read it back to persist it. **`FilterModel`** (type from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts type FilterModel = | { type: 'text'; op: TextFilterOp; value?: string } | { type: 'number'; op: NumberFilterOp; value?: number; valueTo?: number } | { type: 'date'; op: DateFilterOp; value?: string | number | Date; valueTo?: string | number | Date } | { type: 'set'; values: readonly unknown[] } | { type: 'boolean'; value: boolean } | { type: 'custom'; test: (value: unknown, row: any) => boolean } | { type: 'combined'; op: 'and' | 'or'; conditions: FilterModel[] }; ``` ### Text ```ts { type: 'text', op: 'contains', value: 'logistics' } ``` `op` is one of `contains`, `notContains`, `equals`, `notEquals`, `startsWith`, `endsWith`, `blank` and `notBlank`. Values are compared as lowercase strings; blank cells count as an empty string, so `notContains` keeps them. ### Number ```ts { type: 'number', op: 'between', value: 1000, valueTo: 5000 } ``` `op` is one of `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `between`, `blank` and `notBlank`. `lt`, `lte`, `gt`, `gte` and `between` never match blank cells. `ne` keeps blank cells, since a blank is not equal to the value. ### Date ```ts { type: 'date', op: 'after', value: '2026-01-31' } { type: 'date', op: 'between', value: new Date(2026, 0, 1), valueTo: new Date(2026, 2, 31) } ``` `op` is one of `eq`, `before`, `after`, `between`, `blank` and `notBlank`. `value` and `valueTo` accept a `Date`, epoch milliseconds or a date string. ### Set ```ts { type: 'set', values: ['EMEA', 'APAC'] } ``` Keeps rows whose value is strictly equal to one of `values`. `Date` values are compared by timestamp. ### Boolean ```ts { type: 'boolean', value: true } ``` Truthy strings such as `"yes"` and numbers other than `0` count as true. Blank cells count as false. ### Custom ```ts { type: 'custom', test: (value, row) => boolean } ``` See [Custom filters](#custom-filters). ## Filtering from code ```ts grid.setFilter('region', { type: 'set', values: ['EMEA'] }); grid.setFilter('revenue', { type: 'number', op: 'gte', value: 10000 }); grid.setFilter('region', null); grid.setFilterModel({ status: { type: 'text', op: 'notEquals', value: 'Cancelled' }, orderDate: { type: 'date', op: 'between', value: '2026-01-01', valueTo: '2026-03-31' }, }); const model = grid.getFilterModel(); ``` `setFilter(colId, null)` removes one column's filter. `setFilterModel({})` clears all column filters. Entries for columns that do not exist are ignored. The initial `filterModel` option and `update({ filterModel })` behave like `setFilterModel()`. Every filter change, from the UI, these methods or `update({ filterModel })` and `update({ quickFilter })`, fires `filterChanged` and returns a paginated grid to its first page. **`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridApi extends Widget, GridEvents>, GridFeatureApi ``` | Property | Type | Description | | --- | --- | --- | | `setFilter` | `(colId: string, model: FilterModel \| null) => void` | | | `getFilterModel` | `() => Record` | | | `setFilterModel` | `(model: Record) => void` | | | `setQuickFilter` | `(text: string) => void` | | ## Quick filter The quick filter searches every visible column at once, the way a search box above a table usually does. ```ts const search = document.querySelector('#order-search')!; search.addEventListener('input', () => grid.setQuickFilter(search.value)); ``` Or set it as an option: `createGrid(container, { quickFilter: 'harbor' })` or `grid.update({ quickFilter: '' })`. How it matches: - The text is split on whitespace and **every term must match**, in any column. `harbor pending` finds Blue Harbor Foods orders that are pending. - Matching is case-insensitive and finds substrings. - Each column contributes its **formatted** text when it has a `format` function, otherwise its raw value as a string. A revenue column formatted as `$18,400.00` matches `18,400`. - Every column you defined is searched, including hidden ones, so users can find rows by a value they cannot see, such as an internal account code. Generated columns, like the selection checkbox column, are skipped. To keep a column out of the quick filter, leave it out of `columns` and read the value in a `valueGetter` or renderer instead. The grid caches the searchable text of each row and rebuilds it when rows change, so typing stays fast on large datasets. ## Custom filters A `custom` filter model carries a predicate. It receives the column value and the row and returns `true` to keep the row. ```ts const today = new Date(); grid.setFilter('due', { type: 'custom', test: (value, row) => !row.paid && new Date(String(value)) < today, }); ``` A custom filter can also express conditions across columns. Attach it to the column the user would expect to see it on: ```ts grid.setFilter('customer', { type: 'custom', test: (_value, row) => row.region === 'EMEA' && row.revenue > 20000, }); ``` > **Note** > > Custom filters hold functions, so they cannot be serialized. When you persist the filter model, skip entries with `type: 'custom'` and recreate them from your own state. ## Reacting to filter changes `filterChanged` fires when a column filter or the quick filter changes, from the UI or from code: ```ts grid.on('filterChanged', ({ filterModel, quickFilter }) => { const serializable = Object.fromEntries(Object.entries(filterModel).filter(([, m]) => m.type !== 'custom')); const params = new URLSearchParams({ q: quickFilter, filters: JSON.stringify(serializable) }); history.replaceState(null, '', `?${params}`); }); grid.on('modelUpdated', ({ rowCount, displayRowCount }) => { counter.textContent = `Showing ${displayRowCount} of ${rowCount} orders`; }); ``` ## Related - [Sorting](https://docs.birchui.com/grid/sorting.md) runs after filtering. - [Tree data](https://docs.birchui.com/grid-pro/tree-data.md) keeps the ancestors of matching rows visible. - [Events reference](https://docs.birchui.com/grid/events.md) lists every payload. --- Source: https://docs.birchui.com/grid/editing/ # Editing > Make cells editable with built-in text, number, select, checkbox and date editors or your own, parse input with valueParser and react to cellValueChanged. Cells become editable with `editable` on the column. The grid picks an editor from the column type, parses what the user typed, writes the value back to the row and fires `cellValueChanged`. Everything is keyboard-first: users can tab through a row editing as they go without touching the mouse. **Live demo: Inline editing** (runs on the HTML version of this page). Source of `demos/editing.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { docsTheme, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order } from './_shared'; export const meta = { title: 'Inline editing', height: 440 }; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 170, editable: true }, { field: 'status', header: 'Status', width: 130, editable: true, editor: 'select', options: ['Pending', 'Shipped', 'Delivered', 'Returned'], }, { field: 'quantity', header: 'Qty', type: 'number', width: 90, editable: true, editor: 'number', valueParser: (input) => Math.max(1, Math.round(Number(input))), }, { field: 'shipped', header: 'Shipped', type: 'boolean', width: 100, editable: true, editor: 'checkbox' }, { field: 'orderDate', header: 'Ordered', type: 'date', width: 130, editable: true, editor: 'date' }, { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); toolbar.append('Double-click, press Enter or F2, or just start typing. Escape cancels, Enter or Tab commits.'); const grid = createGrid(body, { columns, rows: makeOrders(200, 7), getRowId: (order) => order.id, theme: docsTheme(), ariaLabel: 'Editable orders', }); status.textContent = 'No changes yet.'; const off = grid.on('cellValueChanged', ({ row, colId, oldValue, newValue }) => { status.textContent = `${row.id}: ${colId} changed from ${String(oldValue)} to ${String(newValue)}`; }); const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { off(); stopTheme(); grid.destroy(); }; } ``` ## Making columns editable `editable` is `true`, `false` or a function of the cell context, so you can lock cells per row. ```ts title="invoice-editing.ts" import { createGrid, type ColumnDef } from '@birchui/core'; interface InvoiceLine { id: string; description: string; quantity: number; unitPrice: number; taxCode: 'STD' | 'RED' | 'ZERO'; billable: boolean; serviceDate: string; locked: boolean; } const columns: ColumnDef[] = [ { field: 'description', flex: 1, editable: (ctx) => !ctx.row?.locked }, { field: 'quantity', type: 'number', editable: true, width: 100 }, { field: 'unitPrice', header: 'Unit price', type: 'number', editable: true, width: 120 }, { field: 'taxCode', header: 'Tax', editable: true, options: [ { value: 'STD', label: 'Standard 20%' }, { value: 'RED', label: 'Reduced 5%' }, { value: 'ZERO', label: 'Zero-rated' }, ], format: (v) => ({ STD: 'Standard 20%', RED: 'Reduced 5%', ZERO: 'Zero-rated' })[v as InvoiceLine['taxCode']] ?? '', }, { field: 'billable', type: 'boolean', editable: true, width: 90 }, { field: 'serviceDate', header: 'Service date', type: 'date', editable: true }, ]; const grid = createGrid(document.querySelector('#invoice-lines')!, { columns, rows: lines, getRowId: (line) => line.id, }); grid.on('cellValueChanged', async ({ row, colId, newValue, oldValue, source }) => { if (source !== 'edit') return; const response = await fetch(`/api/invoice-lines/${row.id}`, { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ [colId]: newValue }), }); if (!response.ok) grid.setValue(row, colId, oldValue); }); ``` To make a whole grid editable, set `defaultColumn: { editable: true }` and opt individual columns out with `editable: false`. ## Built-in editors Without an `editor`, the grid chooses one: | Column | Editor | Value written | | --- | --- | --- | | Has `options` | `select`: a native select listing the options | The option's `value` | | `type: 'boolean'` | `checkbox` | `true` or `false` | | `type: 'date'` | `date`: a native date input | Same representation as the old value: an ISO string stays a `YYYY-MM-DD` string, a number stays epoch milliseconds, otherwise a `Date` | | `type: 'number'` | `number`: a text input with a decimal keypad on touch devices | A number, or `null` when cleared | | Anything else | `text` | The string typed | Force a specific editor with `editor: 'text' | 'number' | 'select' | 'checkbox' | 'date'`. ### Select options `options` is a list of strings, numbers or `{ value, label }` pairs. Labels are shown, values are written. The select editor commits as soon as the user picks an option. ```ts const columns: ColumnDef[] = [ { field: 'priority', editable: true, options: ['Low', 'Normal', 'High', 'Urgent'] }, { field: 'technicianId', header: 'Technician', editable: true, options: technicians.map((t) => ({ value: t.employeeId, label: t.name })), format: (id) => technicians.find((t) => t.employeeId === id)?.name ?? 'Unassigned', }, ]; ``` Use `format` to show the label in the cell as well, as above; the grid displays the raw value otherwise. ## Parsing input: valueParser Text-based editors (`text`, `number` and `date`) produce a string. The grid converts it by column type: numbers through a lenient parser that accepts thousands separators (an empty input becomes `null`), dates through `Date` parsing (an invalid date keeps the previous value), and booleans from words such as `yes` and `no`. `valueParser(input, row)` replaces that conversion. ```ts const columns: ColumnDef[] = [ { field: 'unitPrice', type: 'number', editable: true, valueParser: (input) => { const normalized = input.replace(/[^\d,.-]/g, '').replace(',', '.'); const value = Number.parseFloat(normalized); return Number.isFinite(value) ? Math.round(value * 100) / 100 : null; }, }, { field: 'description', editable: true, valueParser: (input) => input.trim().replace(/\s+/g, ' '), }, ]; ``` ## Writing values: valueSetter The parsed value is written with the column's `valueSetter`, or to `field` when there is none. Use a setter to update derived fields, validate, or write to a nested structure: ```ts const columns: ColumnDef[] = [ { field: 'quantity', type: 'number', editable: true, valueSetter: (line, value) => { const quantity = Math.max(0, Math.round(Number(value) || 0)); line.quantity = quantity; line.total = quantity * line.unitPrice; }, }, ]; ``` ## Keyboard and mouse | Input | When | Action | | --- | --- | --- | | Enter or F2 | A cell is focused | Start editing with the current value selected | | Any printable character | A cell is focused | Start editing and replace the value with the typed character | | Space | A checkbox cell is focused and row selection is off | Start editing and toggle the checkbox | | Delete or Backspace | An editable cell is focused | Clear the value: an empty string for text columns, `null` for other types | | Double-click | Any editable cell | Start editing | | Enter | Editing | Commit | | Tab / Shift+Tab | Editing | Commit and start editing the next or previous editable cell, wrapping across rows | | Escape | Editing | Cancel and keep the previous value | To change what a key does on a focused cell, listen to `cellKeyDown` and call `preventDefault()`. The grid then skips its own handling, so you can replace Delete with your own action or stop typing from opening an editor: ```ts grid.on('cellKeyDown', ({ event, row, colId }) => { const key = event as KeyboardEvent; if (key.key === 'Delete' && row) { key.preventDefault(); if (confirm(`Remove "${row.description}" from the invoice?`)) grid.applyTransaction({ remove: [row] }); } else if (colId === 'serviceDate' && row?.locked && key.key.length === 1) { key.preventDefault(); } }); ``` `cellKeyDown` does not fire while an editor is open; keys inside an editor belong to the editor. A select editor commits as soon as an option is chosen. Starting an edit in another cell, from the keyboard or with `startEdit()`, commits the edit in progress first. Clearing a cell with Delete fires `cellValueChanged` with `source: 'edit'`. Only data rows can be edited. Group, total and detail rows and generated columns such as the selection checkbox column are never editable. See [Keyboard navigation & accessibility](https://docs.birchui.com/grid/accessibility.md) for the complete key map. ## Custom editors An `editor` can be a factory function. It receives `CellEditorParams` (the cell context plus `initialInput`, `commit()` and `cancel()`) and returns a `CellEditor`: an element, a `getValue()` function, a `focus()` function and an optional `destroy()`. **`CellEditor`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface CellEditor ``` | Property | Type | Description | | --- | --- | --- | | `element` | `HTMLElement` | | | `getValue` | `() => unknown` | | | `focus` | `() => void` | | | `destroy?` | `() => void` | | ```ts title="currency-editor.ts" import type { CellEditorFactory } from '@birchui/core'; export const currencyEditor: CellEditorFactory = (params) => { const wrapper = document.createElement('div'); wrapper.className = 'currency-editor'; const symbol = document.createElement('span'); symbol.textContent = '€'; const input = document.createElement('input'); input.inputMode = 'decimal'; input.setAttribute('aria-label', params.column.header); input.value = params.initialInput ?? String(params.value ?? ''); input.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); params.commit(); } else if (event.key === 'Escape') { event.preventDefault(); params.cancel(); } event.stopPropagation(); }); wrapper.append(symbol, input); return { element: wrapper, getValue: () => Number.parseFloat(input.value.replace(',', '.')), focus: () => { input.focus(); if (params.initialInput === undefined) input.select(); }, }; }; ``` ```ts const columns: ColumnDef[] = [ { field: 'unitPrice', header: 'Unit price', type: 'number', editable: true, editor: currencyEditor }, ]; ``` Notes for custom editors: - `getValue()` returns the final value. `valueParser` is not applied to values from custom editors (or from the select and checkbox editors), so return the type you want stored. - Call `params.commit()` and `params.cancel()` from your own key handling. Stop propagation of keys your editor uses so the grid does not treat them as navigation. - `initialInput` is the character the user typed to start editing, or `undefined` when editing started with Enter, F2, a double click or the API. - Release anything you registered outside your element in `destroy()`. ## Editing from code ```ts grid.startEdit(3, 'quantity'); grid.startEdit(3, 'description', 'R'); grid.stopEdit(); grid.stopEdit(true); grid.isEditing(); ``` `startEdit(rowIndex, colId, initialInput?)` focuses and scrolls to the cell and returns `false` when the row or column does not exist or the cell is not editable. `stopEdit(cancel?)` commits, or cancels when passed `true`; it does nothing when no editor is open. **`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridApi extends Widget, GridEvents>, GridFeatureApi ``` | Property | Type | Description | | --- | --- | --- | | `setValue` | `(row: TRow, colId: string, value: unknown, source?: CellValueChangedEvent['source']) => boolean` | | | `startEdit` | `(rowIndex: number, colId: string, initialInput?: string) => boolean` | | | `stopEdit` | `(cancel?: boolean) => void` | | | `isEditing` | `() => boolean` | | ## Edit events ```ts grid.on('editStart', ({ rowIndex, colId }) => toolbar.classList.add('is-editing')); grid.on('editStop', ({ rowIndex, colId, cancelled }) => toolbar.classList.remove('is-editing')); grid.on('cellValueChanged', ({ row, rowIndex, colId, oldValue, newValue, source }) => { if (source === 'edit') audit.push({ invoiceLine: row.id, field: colId, from: oldValue, to: newValue }); }); ``` `cellValueChanged` fires after the value is written, and only when the value actually changed: committing an editor without changing the value fires `editStop` but not `cellValueChanged`. `source` tells you where the change came from: | `source` | Origin | | --- | --- | | `edit` | A user edit in a cell editor | | `api` | `setValue()` from your code | | `paste` | Clipboard paste ([Grid Pro](https://docs.birchui.com/grid-pro/clipboard.md)) | | `fill` | Fill handle drag ([Grid Pro](https://docs.birchui.com/grid-pro/fill-handle.md)) | **`CellValueChangedEvent`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface CellValueChangedEvent ``` | Property | Type | Description | | --- | --- | --- | | `row` | `TRow` | | | `rowIndex` | `number` | | | `colId` | `string` | | | `oldValue` | `unknown` | | | `newValue` | `unknown` | | | `source` | `'edit' \| 'paste' \| 'fill' \| 'api' \| 'undo' \| 'redo'` | | ### Validation and rollback Validate in `valueSetter` to reject values before they are stored. If a `valueSetter` throws, the grid reports the error with `console.error`, keeps the old value and fires no `cellValueChanged`. To roll back after an asynchronous save fails, call `setValue(row, colId, oldValue)` as in the first example on this page. ## Related - [Columns](https://docs.birchui.com/grid/columns.md) for `valueGetter`, `format` and `cell`. - [Clipboard](https://docs.birchui.com/grid-pro/clipboard.md) and [Fill handle](https://docs.birchui.com/grid-pro/fill-handle.md) for bulk edits in Grid Pro. --- Source: https://docs.birchui.com/grid/undo-redo/ # Undo and redo > Record cell edits, pastes and fills, undo them with Ctrl+Z, and keep your save handler in sync with undo and redo. With `undoRedo` on, the grid records every change that fires `cellValueChanged`: inline edits, `setValue()` calls, and paste and fill from Grid Pro. Undo is part of the MIT grid in `@birchui/core`. ```ts title="orders-grid.ts" import { createGrid } from '@birchui/core'; const grid = createGrid(el, { columns, rows: orders, getRowId: (order) => order.id, undoRedo: { limit: 50 }, }); ``` `undoRedo: true` keeps the last 100 steps. `{ limit }` sets another positive whole number; an invalid limit logs one warning and falls back to 100. Setting `undoRedo` to `false` with `update()` clears the history. **`UndoRedoOptions`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface UndoRedoOptions ``` | Property | Type | Description | | --- | --- | --- | | `limit?` | `number` | | ## Keys and methods | Keys (Windows, Linux) | macOS | Action | | --- | --- | --- | | Ctrl+Z | ⌘+Z | Undo | | Ctrl+Y or Ctrl+Shift+Z | ⌘+Shift+Z | Redo | The keys work while the grid has focus and no cell is being edited; inside an editor they belong to the text box. After undo or redo, focus moves to the restored cell. **`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridApi extends Widget, GridEvents>, GridFeatureApi ``` | Property | Type | Description | | --- | --- | --- | | `undo` | `() => boolean` | | | `redo` | `() => boolean` | | | `canUndo` | `() => boolean` | | | `canRedo` | `() => boolean` | | | `clearHistory` | `() => void` | | ```ts undoButton.addEventListener('click', () => grid.undo()); redoButton.addEventListener('click', () => grid.redo()); grid.on('cellValueChanged', () => { undoButton.disabled = !grid.canUndo(); redoButton.disabled = !grid.canRedo(); }); ``` ## Steps Writes made in the same task form one step. Pasting a 10 by 4 range, dragging the fill handle, or a listener that writes three cells in one go are each undone at once. ## Saving changes Undo and redo write through `setValue()`, so `cellValueChanged` fires with `source: 'undo'` or `source: 'redo'`. A save handler written for edits keeps working: ```ts grid.on('cellValueChanged', ({ row, colId, newValue, source }) => { void api.patchOrder(row.id, { [colId]: newValue }, { reason: source }); }); ``` Writes made by undo and redo, and writes your listeners make in response to them, are not recorded again. ## Limits - Rows are matched by `getRowId`. Give the grid one; changes to rows that have since been removed are skipped. - `setRows()` keeps the history. Call `clearHistory()` when you load a different dataset, or after a successful save if users should not undo past it. - Only cell values are recorded. Sorting, filtering, column moves and row transactions are not undoable; use [saved state](https://docs.birchui.com/grid/saving-state.md) for view changes. ## Related - [Editing](https://docs.birchui.com/grid/editing.md) - [Clipboard](https://docs.birchui.com/grid-pro/clipboard.md) and [fill handle](https://docs.birchui.com/grid-pro/fill-handle.md) - [Events](https://docs.birchui.com/grid/events.md) --- Source: https://docs.birchui.com/grid/selection/ # Selection > Let users select one or many rows, add a checkbox column, and drive selection from code with stable row IDs. Row selection is off by default. Turn it on with `rowSelection`, optionally add a checkbox column with `checkboxSelection`, and listen to `selectionChanged`. ```ts title="dispatch-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; interface WorkOrder { id: string; site: string; technician: string; scheduled: string; status: 'Open' | 'Assigned' | 'Done'; } const columns: ColumnDef[] = [ { field: 'id', header: 'Work order', width: 130 }, { field: 'site', flex: 1 }, { field: 'technician' }, { field: 'scheduled', type: 'date' }, { field: 'status' }, ]; const grid = createGrid(document.querySelector('#work-orders')!, { columns, rows: workOrders, getRowId: (w) => w.id, rowSelection: 'multiple', checkboxSelection: true, }); const assignButton = document.querySelector('#assign')!; grid.on('selectionChanged', ({ selected }) => { assignButton.disabled = selected.length === 0; assignButton.textContent = selected.length ? `Assign ${selected.length} work orders` : 'Assign'; }); ``` ## Selection modes | `rowSelection` | Behaviour | | --- | --- | | `false` (default) | Rows cannot be selected. Clicking a cell only focuses it. | | `'single'` | Clicking a row selects it and deselects any other row. | | `'multiple'` | Clicking a row selects only that row. Ctrl+click or Cmd+click toggles a row while keeping the others. Shift+click selects the range from the last clicked row; add Ctrl or Cmd to add the range to the existing selection. | Clicks on buttons, links and form controls inside cells never change the selection, so action buttons in a [cell renderer](https://docs.birchui.com/grid/columns.md#cell-renderers-cell) work as expected. With the keyboard: | Key | Action | | --- | --- | | Space | Toggle the focused row | | Shift+Space | Select the range from the last toggled row to the focused row (`'multiple'`) | | Ctrl+A or Cmd+A | Select all rows (`'multiple'`) | The grid root reports `aria-multiselectable="true"` in `'multiple'` mode, and every row reports `aria-selected`. See [Keyboard navigation & accessibility](https://docs.birchui.com/grid/accessibility.md). ## Checkbox column `checkboxSelection: true` adds a 44-pixel checkbox column pinned to the left, with the ID `__select`. It is only added when `rowSelection` is set. - Clicking a checkbox toggles that row without affecting the others. Shift+click selects a range. - In `'multiple'` mode the header has a select-all checkbox. It selects every data row that passes the current filters, across all pages, and shows an indeterminate state when only some of them are selected. In `'single'` mode it is hidden. - With a checkbox column, clicking elsewhere in a row focuses the cell but does not change the selection. Users select with the checkboxes only, which avoids accidental deselection on screens where people also edit cells. The checkbox column is generated by the grid: it is not part of `columns`, cannot be edited, sorted, filtered, resized or moved, is excluded from the quick filter and CSV export, and is reported with `generated: true` by `getColumns()`. ## Reading the selection ```ts const rows = grid.getSelectedRows(); const ids = grid.getSelectedIds(); ``` `getSelectedRows()` returns your row objects. `getSelectedIds()` returns their IDs, which is what you usually send to a server. ## Changing the selection from code ```ts grid.setRowSelected('WO-2291', true); grid.setRowSelected('WO-2288', false); grid.selectAll(); grid.deselectAll(); ``` All of these fire `selectionChanged` when the selection actually changes. `selectAll()` selects every data row that passes the current filters, on every page, and does nothing in `'single'` mode. In `'single'` mode, `setRowSelected(id, true)` replaces the current selection. To restore a saved selection after loading data: ```ts const saved: string[] = JSON.parse(sessionStorage.getItem('dispatch.selection') ?? '[]'); grid.setRows(await fetchWorkOrders()); for (const id of saved) grid.setRowSelected(id, true); grid.on('selectionChanged', () => { sessionStorage.setItem('dispatch.selection', JSON.stringify(grid.getSelectedIds())); }); ``` **`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridApi extends Widget, GridEvents>, GridFeatureApi ``` | Property | Type | Description | | --- | --- | --- | | `getSelectedRows` | `() => TRow[]` | | | `getSelectedIds` | `() => string[]` | | | `setRowSelected` | `(id: string, selected: boolean) => void` | | | `selectAll` | `() => void` | | | `deselectAll` | `() => void` | | ## Selection and data changes Selection is stored by row ID, which is why `getRowId` matters: - With `getRowId`, a selected row stays selected after `setRows()` or `applyTransaction({ update })` replaces its object, as long as the ID is still present. - Rows removed with `applyTransaction({ remove })`, and rows missing from new data passed to `setRows()` or `update({ rows })`, leave the selection. The grid fires `selectionChanged` when that removes any selected row, so a toolbar bound to the selection stays correct after a refresh. - Filtering hides rows but does not deselect them. `getSelectedRows()` still includes selected rows that are filtered out. ## Styling selected rows Selected rows get the `lq-row-selected` class and the `--lq-selection-bg` background. Override the property on the grid element itself: ```css #work-orders .lq-grid { --lq-selection-bg: rgba(26, 127, 55, 0.14); } ``` ## Acting on clicks without selecting To open a record on click instead of selecting it, keep `rowSelection: false` and listen to `rowClick` or `cellClick`: ```ts grid.on('rowClick', ({ row, event }) => { if (!row) return; if (event.metaKey || event.ctrlKey) window.open(`/work-orders/${row.id}`, '_blank'); else router.navigate(`/work-orders/${row.id}`); }); ``` ## Related - [Range selection](https://docs.birchui.com/grid-pro/range-selection.md) selects rectangular cell ranges in Grid Pro. - [CSV export](https://docs.birchui.com/grid/csv-export.md) can export only the selected rows. --- Source: https://docs.birchui.com/grid/column-operations/ # Column operations > Resize, reorder, pin, hide and autosize columns from the UI or the API, and save and restore the layout with ColumnState. Users can rearrange columns directly in the header, and everything they can do is also available from code. The resulting layout is captured as plain `ColumnState` objects you can store and restore. **Live demo: Pinned columns** (runs on the HTML version of this page). Source of `demos/pinned-columns.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { button, currency, docsTheme, layout, onDocsThemeChange, seededRandom } from './_shared'; export const meta = { title: 'Pinned columns', height: 440 }; interface AccountRevenue { account: string; owner: string; months: number[]; } const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const ACCOUNTS = [ 'Northwind Traders', 'Blue Harbor Foods', 'Alpine Outfitters', 'Kestrel Logistics', 'Maison Duval', 'Oakridge Clinics', 'Sakura Retail Group', 'Harbourline Marine', 'Lotus Electronics', 'Andes Coffee Co.', 'Rio Verde Agro', 'Cedar & Stone', ]; const OWNERS = ['Amelia Hart', 'Jonas Becker', 'Priya Natarajan', 'Diego Alvarez']; function makeAccounts(): AccountRevenue[] { const random = seededRandom(42); return Array.from({ length: 60 }, (_, i) => ({ account: `${ACCOUNTS[i % ACCOUNTS.length]}${i >= ACCOUNTS.length ? ` (${Math.floor(i / ACCOUNTS.length) + 1})` : ''}`, owner: OWNERS[i % OWNERS.length], months: MONTHS.map(() => Math.round(8000 + random() * 42000)), })); } const money = (value: unknown) => (typeof value === 'number' ? currency.format(value) : ''); const columns: ColumnDef[] = [ { field: 'account', header: 'Account', width: 210, pinned: 'left' }, { field: 'owner', header: 'Owner', width: 150 }, ...MONTHS.map((month, index): ColumnDef => ({ id: month.toLowerCase(), header: month, type: 'number', width: 110, valueGetter: (row) => row.months[index], format: money, })), { id: 'total', header: 'Total', type: 'number', width: 130, pinned: 'right', valueGetter: (row) => row.months.reduce((sum, value) => sum + value, 0), format: money, cellClass: 'demo-total', }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const grid = createGrid(body, { columns, rows: makeAccounts(), getRowId: (row) => row.account, theme: docsTheme(), ariaLabel: 'Monthly revenue by account', }); let ownerPinned = false; toolbar.append( button('Pin or unpin Owner', () => { ownerPinned = !ownerPinned; grid.setColumnPinned('owner', ownerPinned ? 'left' : null); }), button('Autosize all', () => grid.autosizeColumns()), button('Reset layout', () => { ownerPinned = false; grid.setColumns(columns); }), ); const describe = () => { const pinned = grid .getColumnState() .filter((c) => c.pinned) .map((c) => `${c.colId} (${c.pinned})`); status.textContent = `Pinned: ${pinned.join(', ') || 'none'}. Drag a header to reorder, or drag its edge to resize.`; }; const off = grid.on('columnStateChanged', describe); describe(); const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { off(); stopTheme(); grid.destroy(); }; } ``` ## Resizing Drag the right edge of a header cell to resize a column. Widths are clamped to the column's `minWidth` (40 pixels by default) and `maxWidth`. Set `resizable: false` to lock a column. ```ts title="resizing.ts" import { createGrid, type ColumnDef } from '@birchui/core'; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 120, resizable: false }, { field: 'customer', width: 240, minWidth: 160, maxWidth: 420 }, { field: 'revenue', type: 'number', width: 140 }, ]; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders }); grid.setColumnWidth('customer', 300); grid.on('columnResized', ({ colId, width }) => console.info(`${colId} is now ${width}px`)); ``` A flex column that is resized keeps its new width and stops flexing. ### Autosizing Double-click a header's resize edge to fit the column to its content. From code, `autosizeColumn(colId)` does the same and `autosizeColumns()` fits every visible, resizable column. ```ts grid.autosizeColumns(); grid.autosizeColumn('customer'); ``` The grid measures the header label and the formatted text of up to the first 1,000 display rows, adds room for padding and the header controls, and caps the result at 640 pixels before applying `minWidth` and `maxWidth`. Because it measures display rows, autosizing after a filter or sort can produce a different width. Call it once after the first data load, or in a `ready` listener. ## Reordering Drag a header to a new position to reorder columns. A drop indicator shows where the column will land. Dropping a column among pinned columns pins it to that side, and dropping a pinned column among unpinned ones unpins it. Set `reorderable: false` to keep a column in place. From code, `moveColumn(colId, toIndex)` moves a column to a position in the full column order, including hidden columns. ```ts grid.moveColumn('revenue', 1); grid.on('columnMoved', ({ colId, toIndex }) => console.info(`${colId} moved to ${toIndex}`)); ``` ## Pinning Pinned columns stay visible while the rest of the grid scrolls horizontally. Left-pinned columns are drawn first, then unpinned columns, then right-pinned columns. ```ts const columns: ColumnDef[] = [ { field: 'id', header: 'Order', pinned: 'left', width: 120 }, { field: 'customer', pinned: 'left', width: 220 }, { field: 'region' }, { field: 'product' }, { field: 'quantity', type: 'number' }, { field: 'unitPrice', type: 'number' }, { field: 'revenue', type: 'number', pinned: 'right' }, ]; grid.setColumnPinned('region', 'left'); grid.setColumnPinned('customer', null); grid.on('columnPinned', ({ colId, pinned }) => console.info(colId, pinned ?? 'unpinned')); ``` > **Tip** > > Keep pinned areas narrow. Pinned columns never scroll, so on a small screen a wide pinned area leaves little room for everything else. A common pattern is to pin only the identifying column on the left and a total or action column on the right. ## Hiding `hidden: true` in the column definition starts a column hidden. `setColumnHidden(colId, hidden)` toggles it at runtime. Hidden columns keep their width, position and pin state. They are still searched by the quick filter, but they are left out of CSV export. ```ts const toggles = document.querySelectorAll('[data-column-toggle]'); for (const toggle of toggles) { toggle.checked = !grid.getColumn(toggle.value)?.hidden; toggle.addEventListener('change', () => grid.setColumnHidden(toggle.value, !toggle.checked)); } grid.on('columnVisible', ({ colId, hidden }) => console.info(colId, hidden ? 'hidden' : 'shown')); ``` ## The column menu Each header has a menu button that appears on hover and focus. Right-clicking a header, pressing Alt+Arrow Down or the context menu key on a focused header opens the same menu. It offers: | Group | Items | | --- | --- | | Sort (sortable columns) | Sort ascending, Sort descending, Clear sort | | Pin | Pin left, Pin right, Unpin | | Size | Autosize this column, Autosize all columns | | Visibility | Hide column (disabled for the last visible column), Show all columns, when some are hidden | Modules can add items with `addColumnMenuItems`; Grid Pro adds **Group by this column**, **Ungroup** and **Export to Excel** this way. See [Modules](https://docs.birchui.com/grid/modules.md#column-menu-items). ## Scrolling to a column `scrollToColumn(colId)` scrolls horizontally until the column is in view. Pinned columns are always in view. ```ts grid.scrollToColumn('unitPrice'); ``` ## Saving and restoring column state `getColumnState()` returns one `ColumnState` per column with its current width, pin state, visibility and position. `applyColumnState(state)` applies a saved state. Each entry only changes the properties it contains, so a partial state such as `[{ colId: 'revenue', hidden: true }]` is valid. **`ColumnState`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface ColumnState ``` | Property | Type | Description | | --- | --- | --- | | `colId` | `string` | | | `width?` | `number` | | | `pinned?` | `'left' \| 'right' \| null` | | | `hidden?` | `boolean` | | | `order?` | `number` | | ### Persisting the layout in localStorage ```ts title="persist-columns.ts" import { createGrid, type ColumnState } from '@birchui/core'; const STORAGE_KEY = 'orders-grid.columns.v1'; function loadColumnState(): ColumnState[] | null { try { const raw = localStorage.getItem(STORAGE_KEY); return raw ? (JSON.parse(raw) as ColumnState[]) : null; } catch { return null; } } const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (o) => o.id, }); const saved = loadColumnState(); if (saved) grid.applyColumnState(saved); grid.on('columnStateChanged', ({ state }) => { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); }); document.querySelector('#reset-layout')!.addEventListener('click', () => { localStorage.removeItem(STORAGE_KEY); grid.applyColumnState( columns.map((def, order) => ({ colId: def.id ?? def.field!, width: def.flex ? undefined : (def.width ?? 150), pinned: def.pinned ?? null, hidden: def.hidden ?? false, order, })), ); }); ``` `columnStateChanged` fires after any resize, move, pin or visibility change, with the full state, so one listener is enough to persist everything. Columns in a saved state that no longer exist are ignored, and new columns that are missing from it keep their defaults, so old saved layouts keep working when you add columns. Version the storage key when you change column IDs. > **Note** > > Column state covers layout only. Sort and filters have their own models: save `getSort()` and `getFilterModel()` alongside it if you want to restore the whole view. See [Sorting](https://docs.birchui.com/grid/sorting.md#reacting-to-sort-changes) and [Filtering](https://docs.birchui.com/grid/filtering.md#reacting-to-filter-changes). ## API summary **`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridApi extends Widget, GridEvents>, GridFeatureApi ``` | Property | Type | Description | | --- | --- | --- | | `getColumns` | `() => readonly ResolvedColumn[]` | | | `getDisplayColumns` | `() => readonly ResolvedColumn[]` | | | `getColumn` | `(colId: string) => ResolvedColumn \| undefined` | | | `getColumnState` | `() => ColumnState[]` | | | `applyColumnState` | `(state: ColumnState[]) => void` | | | `setColumnWidth` | `(colId: string, width: number) => void` | | | `autosizeColumn` | `(colId: string) => void` | | | `autosizeColumns` | `() => void` | | | `moveColumn` | `(colId: string, toIndex: number) => void` | | | `setColumnPinned` | `(colId: string, pinned: 'left' \| 'right' \| null) => void` | | | `setColumnHidden` | `(colId: string, hidden: boolean) => void` | | | `scrollToColumn` | `(colId: string) => void` | | ## Column events | Event | Payload | Fires when | | --- | --- | --- | | `columnResized` | `{ colId, width }` | A column width changes | | `columnMoved` | `{ colId, toIndex }` | A column moves | | `columnPinned` | `{ colId, pinned }` | A column is pinned or unpinned | | `columnVisible` | `{ colId, hidden }` | A column is hidden or shown | | `columnStateChanged` | `{ state }` | After any of the above | See the [Events reference](https://docs.birchui.com/grid/events.md) for every grid event. --- Source: https://docs.birchui.com/grid/column-groups/ # Column groups > Nest columns under group headers to build multi-row headers, with collapsible groups that show a summary or the full detail. Column groups put a header above related columns, such as **Customer** over name and region, or **Billing** over total, tax and currency. Groups nest to any depth, and each level adds one header row. They are part of the MIT grid in `@birchui/core`; no module is needed. ## Defining groups Anywhere a column definition is accepted, `columns` and `setColumns()` also accept a `ColumnGroupDef`: an object with a `header` and `children`. ```ts title="orders-grid.ts" import { createGrid, type ColumnDef, type ColumnGroupDef } from '@birchui/core'; interface Order { id: string; customer: string; region: string; total: number; tax: number; currency: string; } const columns: (ColumnDef | ColumnGroupDef)[] = [ { field: 'id', header: 'Order', pinned: 'left' }, { groupId: 'customer', header: 'Customer', children: [{ field: 'customer', flex: 1 }, { field: 'region' }], }, { groupId: 'billing', header: 'Billing', collapsible: true, children: [ { field: 'total', type: 'number' }, { field: 'tax', type: 'number', columnGroupShow: 'open' }, { field: 'currency', columnGroupShow: 'open' }, ], }, ]; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (order) => order.id, }); ``` **`ColumnGroupDef`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface ColumnGroupDef extends Partial< Record, 'header' | 'headerClass'>, never> > ``` | Property | Type | Description | | --- | --- | --- | | `groupId?` | `string` | | | `header` | `string` | | | `children` | `(ColumnDef \| ColumnGroupDef)[]` | | | `headerClass?` | `string` | | | `collapsible?` | `boolean` | | | `openByDefault?` | `boolean` | | | `id?` | `undefined` | | | `field?` | `undefined` | | | `headerTooltip?` | `undefined` | | | `type?` | `undefined` | | | `width?` | `undefined` | | | `minWidth?` | `undefined` | | | `maxWidth?` | `undefined` | | | `flex?` | `undefined` | | | `pinned?` | `undefined` | | | `hidden?` | `undefined` | | | `sortable?` | `undefined` | | | `resizable?` | `undefined` | | | `reorderable?` | `undefined` | | | `rowHeader?` | `undefined` | | | `filter?` | `undefined` | | | `editable?` | `undefined` | | | `editor?` | `undefined` | | | `options?` | `undefined` | | | `valueGetter?` | `undefined` | | | `valueSetter?` | `undefined` | | | `valueParser?` | `undefined` | | | `format?` | `undefined` | | | `cell?` | `undefined` | | | `cellClass?` | `undefined` | | | `align?` | `undefined` | | | `comparator?` | `undefined` | | | `aggFunc?` | `undefined` | | | `rowGroup?` | `undefined` | | | `rowGroupIndex?` | `undefined` | | | `pivot?` | `undefined` | | | `pivotIndex?` | `undefined` | | | `meta?` | `undefined` | | | `columnGroupShow?` | `undefined` | | | `autoHeight?` | `undefined` | | | `wrapText?` | `undefined` | | | `rowDrag?` | `undefined` | | | `sparkline?` | `undefined` | | A group cannot carry column settings such as `field`, `width` or `sort`; the type rejects them. Put those on the children, or use `defaultColumn` for settings shared by every column. ## Collapsible groups Set `collapsible: true` and mark children with `columnGroupShow`: | `columnGroupShow` | Column is visible | | --- | --- | | `'open'` | Only while the group is open | | `'closed'` | Only while the group is closed | | not set | Always | Groups start closed unless `openByDefault: true`. `columnGroupShow` refers to the nearest collapsible group above the column. A chevron in the group header opens and closes it; keyboard users press Enter or Space on the focused group header. ```ts grid.setColumnGroupOpen('billing', true); grid.on('columnGroupOpened', ({ groupId, open }) => { console.info(`${groupId} is now ${open ? 'open' : 'closed'}`); }); ``` ## Reading the group tree `getColumnGroups()` returns the resolved groups in display order. A group without a `groupId` gets one from its position, such as `group-1` or `group-1-0`, so give groups stable ids when you save their state or open them from code. **`ResolvedColumnGroup`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface ResolvedColumnGroup ``` | Property | Type | Description | | --- | --- | --- | | `groupId` | `string` | | | `header` | `string` | | | `def` | `ColumnGroupDef` | | | `depth` | `number` | | | `parentId` | `string \| null` | | | `collapsible` | `boolean` | | | `open` | `boolean` | | | `children` | `ColumnTreeItem[]` | | | `columnIds` | `string[]` | | | `displayedColumnIds` | `string[]` | | ## Behaviour - A group header spans its visible columns. When a group's columns are split between the pinned and scrolling areas, the header appears in each area. - Dragging a column moves it only within its own group. Dragging a group header moves the whole group. `moveColumn()` and `applyColumnState()` keep groups together too. - Column stages from modules still receive the flat list of leaf columns, so grouping, pivoting and exports work unchanged. - Group headers are `columnheader` cells with `aria-colspan`, and `aria-rowcount` and `aria-rowindex` include the extra header rows. Arrow Up and Arrow Down move between group headers and column headers. ## Related - [Columns](https://docs.birchui.com/grid/columns.md) for every column option. - [Column operations](https://docs.birchui.com/grid/column-operations.md) for moving, pinning and hiding columns. - [Saving and restoring state](https://docs.birchui.com/grid/saving-state.md) to persist column layout. --- Source: https://docs.birchui.com/grid/context-menu/ # Context menu > The built-in cell context menu, how to add, replace or remove items, and how modules contribute their own. Right-click a cell, or press Shift+F10 or the context menu key on a focused cell, to open the grid's cell menu. By default it offers: | Item | Result | | --- | --- | | **Copy cell** | Copies the cell's formatted value | | **Copy row** | Copies the row as tab-separated text; when the row is part of a multi-row selection, every selected row is copied (**Copy selected rows**) | | **Copy with headers** | The same, with a header line first | | **Export CSV** | Calls `downloadCsv()` | Copied text is tab-separated, so it pastes cleanly into Excel, Google Sheets or the [Birch UI Spreadsheet](https://docs.birchui.com/spreadsheet/overview.md). Grid Pro modules add their own items, such as copying a range. ## Changing the items `contextMenu` takes `true` (the default), `false`, or a function that receives the cell and the default items and returns the items to show: ```ts title="orders-grid.ts" import { createGrid, type MenuItem } from '@birchui/core'; const grid = createGrid(el, { columns, rows: orders, getRowId: (order) => order.id, contextMenu: (ctx, defaults) => { const order = ctx.row; if (!order) return defaults; const items: MenuItem[] = [ { label: 'Open order', action: () => openOrder(order.id) }, { label: 'Mark as shipped', disabled: order.status !== 'Pending', action: () => markShipped(order.id) }, { label: 'Flag for review', checked: order.flagged, action: () => toggleFlag(order.id) }, ]; return [...items, { ...defaults[0], separatorBefore: true }, ...defaults.slice(1)]; }, }); ``` Return an empty array to show no menu for that cell; the browser's own menu then stays out of the way only when you call `preventDefault` yourself, so prefer `contextMenu: false` to restore the native menu everywhere. **`MenuItem`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface MenuItem ``` | Property | Type | Description | | --- | --- | --- | | `label` | `string` | | | `action` | `() => void` | | | `checked?` | `boolean` | | | `disabled?` | `boolean` | | | `separatorBefore?` | `boolean` | | ## Behaviour - The menu does not open on full-width rows (group rows rendered full width, master/detail panels) or while a cell is being edited; the editor keeps the browser's menu for spelling suggestions and paste. - Opening the menu focuses the cell it was opened on, and closing it returns focus there. - Items are buttons in a `menu` with arrow-key navigation. Escape closes the menu. - User callbacks run inside a try/catch, so an error in an `action` is reported with `console.error` and the grid keeps working. ## The column menu Every header has a separate column menu (the button at the right of the header, or Alt+Arrow Down on a focused header). It holds sort, pin, autosize, hide and show items, and **Filter…** for filterable columns, which opens the [filter popup](https://docs.birchui.com/grid/filtering.md#filter-popup). ## From a module Modules contribute cell menu items with `internals.addContextMenuItems((ctx) => items)` and column menu items with `internals.addColumnMenuItems((column) => items)`. Both return a function that removes the provider. See [Modules](https://docs.birchui.com/grid/modules.md). ## Related - [Keyboard and accessibility](https://docs.birchui.com/grid/accessibility.md) - [CSV export](https://docs.birchui.com/grid/csv-export.md) - [Clipboard](https://docs.birchui.com/grid-pro/clipboard.md) in Grid Pro --- Source: https://docs.birchui.com/grid/pagination/ # Pagination > Split rows into client-side pages, choose a page size and control the current page from code. Birch UI Grid virtualizes rows, so it does not need pagination for performance: a hundred thousand rows scroll smoothly. Use pagination when the interface calls for pages, for example in an admin table where users refer to "page 3", or when a design puts the grid inside a fixed-height card. ## Turning pagination on ```ts title="paged-invoices.ts" import { createGrid, type ColumnDef } from '@birchui/core'; const columns: ColumnDef[] = [ { field: 'number', header: 'Invoice', width: 130 }, { field: 'customer', flex: 1 }, { field: 'issued', type: 'date' }, { field: 'amount', type: 'number' }, { field: 'paid', type: 'boolean' }, ]; const grid = createGrid(document.querySelector('#invoices')!, { columns, rows: invoices, getRowId: (i) => i.number, pagination: { pageSize: 25 }, }); ``` `pagination` accepts: | Value | Meaning | | --- | --- | | `false` or omitted | No pagination. All display rows are scrollable. | | `true` | Pagination with 100 rows per page. | | `{ pageSize, page? }` | Pagination with your page size, optionally starting on a page other than the first. | **`PaginationOptions`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface PaginationOptions ``` | Property | Type | Description | | --- | --- | --- | | `pageSize` | `number` | | | `page?` | `number` | | Pages are zero-based: `page: 0` is the first page. Pagination runs after every stage of the row pipeline, including filtering, sorting and module stages such as grouping, so each page holds a slice of the final display rows. ## Navigating pages The grid renders a pager in its bottom slot, with first, previous, next and last buttons, the range shown ("101–200 of 1,250") and "Page 2 of 13". The page label is a polite live region, so screen readers announce page changes. From code: ```ts grid.setPage(0); grid.setPage(grid.getPage() + 1); grid.setPage(grid.getPageCount() - 1); ``` `setPage()` clamps to the valid range, so you do not need to check bounds before calling it. It scrolls the grid back to the top and fires `pageChanged`. **`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridApi extends Widget, GridEvents>, GridFeatureApi ``` | Property | Type | Description | | --- | --- | --- | | `setPage` | `(page: number) => void` | | | `getPage` | `() => number` | | | `getPageCount` | `() => number` | | ## Building your own pager Listen to `pageChanged` to keep custom controls in sync. It fires whenever the current page changes: through the pager, `setPage()` or `update({ pagination })`, when a filter change returns the grid to the first page, and when new data leaves fewer pages than the current one. A change in the page count alone, such as rows added to the last page, does not fire it, so also refresh your controls on `modelUpdated`. ```ts const label = document.querySelector('#page-label')!; const prev = document.querySelector('#prev-page')!; const next = document.querySelector('#next-page')!; function render(page: number, pageCount: number) { label.textContent = pageCount === 0 ? 'No invoices' : `Page ${page + 1} of ${pageCount}`; prev.disabled = page <= 0; next.disabled = page >= pageCount - 1; } grid.on('pageChanged', ({ page, pageCount }) => render(page, pageCount)); grid.on('modelUpdated', () => render(grid.getPage(), grid.getPageCount())); prev.addEventListener('click', () => grid.setPage(grid.getPage() - 1)); next.addEventListener('click', () => grid.setPage(grid.getPage() + 1)); render(grid.getPage(), grid.getPageCount()); ``` ## Changing the page size ```ts const sizeSelect = document.querySelector('#page-size')!; sizeSelect.addEventListener('change', () => { grid.update({ pagination: { pageSize: Number(sizeSelect.value), page: 0 } }); }); ``` Changing `pagination` through `update()` moves to the `page` given in the new value, or to the first page when it is omitted. ## Pagination and other features - **Display rows are the current page.** Pagination is applied after the row pipeline, so `getDisplayRows()` returns the rows of the current page, and row indexes in events and in calls such as `focusCell()` and `scrollToRow()` refer to positions within that page. `getAllDisplayRows()` returns the display rows of every page, which is what CSV export and the select-all checkbox work on. - **Filters reset the page.** Any filter or quick filter change, from the UI, the API or `update()`, returns to the first page and fires `pageChanged` when the page actually changes. - **Sorting and filtering** apply to all rows, then the result is paged. `modelUpdated` reports the total number of source rows in `rowCount`. - **Selection** is stored by row ID, so selected rows stay selected when the user changes pages. `selectAll()` and the select-all checkbox select matching rows on every page. - **Accessibility**: `aria-rowcount` reports all rows across pages and each row's `aria-rowindex` is its position in the full result, so screen readers announce "row 230 of 1,250" on page 3. - **CSV export** includes the matching rows of every page, not only the current one. ## Server-side paging For datasets that live on a server, keep pagination off in the grid and load one page at a time with `setRows()`: ```ts let page = 0; const pageSize = 100; async function loadPage(nextPage: number) { const response = await fetch(`/api/invoices?offset=${nextPage * pageSize}&limit=${pageSize}`); const { items, total } = await response.json(); page = nextPage; grid.setRows(items); label.textContent = `Page ${page + 1} of ${Math.ceil(total / pageSize)}`; } grid.on('sortChanged', () => loadPage(0)); grid.on('filterChanged', () => loadPage(0)); await loadPage(0); ``` --- Source: https://docs.birchui.com/grid/virtualization/ # Virtualization & performance > How the grid renders only what is visible, how to use variable row heights, and what to do to keep a million rows fast. Birch UI Grid renders only the rows and columns that are on screen, plus a small buffer. The cost of a render is proportional to the number of visible cells, not to the size of your dataset, so 100 rows and 1,000,000 rows scroll the same way. **Live demo: 100,000 rows, virtualized** (runs on the HTML version of this page). Source of `demos/virtualization-100k.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { button, docsTheme, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order, } from './_shared'; export const meta = { title: '100,000 rows, virtualized', height: 480 }; const ROW_COUNT = 100_000; const columns: ColumnDef[] = [ { field: 'orderNo', header: '#', type: 'number', width: 90 }, { field: 'id', header: 'Order', width: 120 }, { field: 'customer', header: 'Customer', width: 200 }, { field: 'country', header: 'Country', width: 150 }, { field: 'region', header: 'Region', width: 140 }, { field: 'product', header: 'Product', width: 200 }, { field: 'category', header: 'Category', width: 130 }, { field: 'rep', header: 'Sales rep', width: 160 }, { field: 'quantity', header: 'Qty', type: 'number', width: 80 }, { field: 'unitPrice', header: 'Unit price', type: 'number', width: 110, format: formatCurrency }, { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency }, { field: 'status', header: 'Status', width: 110 }, { field: 'orderDate', header: 'Ordered', type: 'date', width: 120 }, { field: 'quarter', header: 'Quarter', width: 100 }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const started = performance.now(); const rows = makeOrders(ROW_COUNT, 99); const grid = createGrid(body, { columns, rows, getRowId: (order) => order.id, defaultColumn: { sortable: true }, theme: docsTheme(), ariaLabel: 'One hundred thousand orders', }); const ready = performance.now() - started; status.textContent = `${ROW_COUNT.toLocaleString()} rows generated and rendered in ${Math.round(ready)} ms. Only visible rows and columns are in the DOM.`; toolbar.append( button('Jump to row 50,000', () => grid.scrollToRow(49_999, 'center')), button('Jump to last row', () => grid.scrollToRow(grid.getDisplayRows().length - 1, 'end')), button('Sort by revenue', () => { const t = performance.now(); grid.setSort([{ colId: 'revenue', dir: 'desc' }]); status.textContent = `Sorted ${ROW_COUNT.toLocaleString()} rows in ${Math.round(performance.now() - t)} ms.`; }), ); const offScroll = grid.on('viewportScroll', () => { const rendered = grid.getRenderedRows(); if (!rendered.length) return; status.textContent = `Rows in the DOM: ${rendered.length} of ${ROW_COUNT.toLocaleString()}.`; }); const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { offScroll(); stopTheme(); grid.destroy(); }; } ``` ## Row virtualization The grid computes which display rows intersect the viewport, renders those plus `overscanRows` extra rows above and below, and recycles row elements as you scroll. Elements that leave the buffer are reused for rows that enter it, so scrolling creates almost no garbage. ```ts title="large-ledger.ts" import { createGrid, type ColumnDef } from '@birchui/core'; interface LedgerEntry { id: number; posted: string; account: string; costCenter: string; description: string; debit: number; credit: number; } const accounts = ['4000 Revenue', '5000 COGS', '6100 Travel', '6200 Software', '6300 Facilities']; const costCenters = ['Sales EMEA', 'Sales NA', 'Field Service', 'R&D', 'Finance']; const entries: LedgerEntry[] = Array.from({ length: 1_000_000 }, (_, i) => ({ id: i + 1, posted: new Date(Date.UTC(2026, 0, 1) + (i % 365) * 86_400_000).toISOString().slice(0, 10), account: accounts[i % accounts.length], costCenter: costCenters[(i * 7) % costCenters.length], description: `Journal ${100000 + i}`, debit: i % 2 ? Math.round((i % 9973) * 1.37 * 100) / 100 : 0, credit: i % 2 ? 0 : Math.round((i % 7919) * 2.11 * 100) / 100, })); const columns: ColumnDef[] = [ { field: 'id', header: 'Entry', type: 'number', width: 100 }, { field: 'posted', type: 'date', width: 120 }, { field: 'account', width: 160, filter: true }, { field: 'costCenter', header: 'Cost center', width: 150, filter: true }, { field: 'description', flex: 1, minWidth: 200 }, { field: 'debit', type: 'number', width: 120 }, { field: 'credit', type: 'number', width: 120 }, ]; createGrid(document.querySelector('#ledger')!, { columns, rows: entries, getRowId: (e) => String(e.id), rowHeight: 32, floatingFilters: true, }); ``` ### Very tall grids Browsers cap how tall a scrollable element can be. When the total height of all rows exceeds 10,000,000 pixels (about 312,000 rows at 32 pixels), the grid maps the scrollbar range onto the virtual height. Scrolling, `scrollToRow()` and keyboard navigation keep working exactly, and the scrollbar thumb simply covers more rows per pixel. ## Column virtualization Unpinned columns are virtualized horizontally in the same way, with `overscanColumns` extra columns on each side. Pinned columns are always rendered. Wide grids with hundreds of columns, such as a pivot result or a monthly forecast, stay as fast as narrow ones. ## Overscan | Option | Default | Meaning | | --- | --- | --- | | `overscanRows` | `6` | Extra rows rendered above and below the viewport. | | `overscanColumns` | `2` | Extra unpinned columns rendered left and right of the viewport. | A larger overscan reduces the chance of seeing blank space during very fast scrolling, at the cost of rendering more cells per frame. The defaults suit most grids; raise them slightly for grids with cheap cells and lower them for grids with expensive cell renderers. ```ts createGrid(container, { columns, rows, overscanRows: 8, overscanColumns: 2 }); ``` ## Variable row heights `rowHeight` can be a function of the display row: ```ts createGrid(container, { columns, rows: tickets, rowHeight: (row) => { if (row.kind !== 'data' || !row.data) return 36; return row.data.notes.length > 120 ? 64 : 36; }, }); ``` The grid calls the function once per display row whenever the row model changes, stores the offsets in a typed array, and finds the visible rows with a binary search while scrolling. That keeps variable heights fast even with a million rows, but the function itself runs a million times per data change, so keep it to simple arithmetic on the row. Return a positive number of pixels. A function that throws or returns something else falls back to the density's row height for that row (34 pixels at the default density). Uniform heights (`rowHeight: 32`) skip the offset table entirely and are the fastest option. Grid Pro rows that carry their own height, such as master/detail panels, switch the grid to the offset table automatically. ## Guidance for a million rows The grid's own work is bounded by what is visible. What you put into it is not. These practices keep large grids responsive. ### Always set getRowId Stable IDs let the grid preserve selection and focus across updates and match `applyTransaction` updates in a single pass. Use a primitive key that already exists on the row. ### Update with transactions, not setRows `setRows()` re-indexes every row. `applyTransaction()` touches only what changed. For live data, batch changes once per animation frame as shown in [Updating data](https://docs.birchui.com/grid/updating-data.md#streaming-updates). ### Keep value getters cheap `valueGetter` runs for every row when sorting or filtering by that column and for every visible cell when rendering. Avoid allocating objects, formatting dates or searching arrays inside it. Precompute derived fields when you load data: ```ts const rows = raw.map((entry) => ({ ...entry, net: entry.debit - entry.credit })); const columns: ColumnDef[] = [{ field: 'net', type: 'number' }]; ``` Reuse formatter instances instead of creating them per call: ```ts const eur = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }); const columns: ColumnDef[] = [ { field: 'debit', type: 'number', format: (v) => (v ? eur.format(Number(v)) : '') }, ]; ``` ### Keep cell renderers light A `cell` renderer runs every time a cell scrolls into view. Return a string where you can, build small DOM trees, and never attach listeners to `document` from a renderer. For click handling across many cells, listen once to the grid's `cellClick` event instead of adding a listener per cell. ```ts grid.on('cellClick', ({ colId, row }) => { if (colId === 'actions' && row) openEntry(row.id); }); ``` ### Mind the quick filter on huge datasets The quick filter builds one search string per row, from every column you defined including hidden ones, the first time it runs, and reuses it until the rows change. Wide grids with many hidden columns therefore pay for those columns too; leave purely technical fields out of `columns` if they should never be searched. The first keystroke on a million rows does the most work; debounce the input for very large datasets (the built-in floating filters already wait 200 ms): ```ts let timer = 0; search.addEventListener('input', () => { clearTimeout(timer); timer = window.setTimeout(() => grid.setQuickFilter(search.value), 150); }); ``` ### Load data off the main thread Parsing a large JSON payload can take longer than rendering it. Fetch and parse in a worker, then pass the array to the grid in one call. ## Measuring `getRenderedRows()` returns the display rows that currently have DOM elements. It is useful in tests and when profiling: ```ts grid.on('viewportScroll', () => { console.info('rendered rows', grid.getRenderedRows().length); }); ``` ### Reference timings The core package's performance tests enforce a budget for creating, sorting, filtering and scrolling 200,000 rows. Measured with 1,000,000 rows on a development machine under heavy load: | Operation | Time | | --- | --- | | Sort by a numeric column | about 1.2 s | | Filter | about 0.4 s | | One scroll frame | under 3 ms | Sorting and filtering scale with the number of rows; scrolling does not. Numeric, date and boolean columns without a custom comparator take a faster sort path than text columns or columns with a `comparator`. ## Related - [Rows & row IDs](https://docs.birchui.com/grid/rows.md) - [Updating data](https://docs.birchui.com/grid/updating-data.md) - [Pagination](https://docs.birchui.com/grid/pagination.md) when you want pages for design reasons --- Source: https://docs.birchui.com/grid/accessibility/ # Keyboard navigation & accessibility > The grid follows the WAI-ARIA grid pattern with a roving tabindex, a complete keyboard map and correct row and column counts while virtualized. Birch UI Grid implements the [WAI-ARIA grid pattern](https://www.w3.org/WAI/ARIA/apg/patterns/grid/). Everything a mouse user can do is available from the keyboard, focus is always visible, and screen readers announce the real size of the dataset and the position of the focused cell even though only a fraction of the rows exist in the DOM. ## Structure and roles | Element | Role and attributes | | --- | --- | | Grid viewport | `role="grid"`, or `role="treegrid"` when any row is nested or expandable; `aria-label` from the `ariaLabel` option; `aria-rowcount`; `aria-colcount`; `aria-multiselectable="true"` when `rowSelection` is `'multiple'` or `rangeSelection` is on | | Header row | `role="row"` with `aria-rowindex="1"` | | Floating filter row | `role="row"` with `aria-rowindex="2"`, each cell with the column's `aria-colindex` and each control labelled "Filter <column>" | | Header cell | `role="columnheader"`, `aria-colindex`, named by its label through `aria-labelledby`, and `aria-sort` (`ascending`, `descending` or `none`) on sortable columns. With a multi-column sort only the primary column carries `aria-sort`; the order of the others is shown visually | | Body row | `role="row"`, `aria-rowindex`, `aria-selected` when selection is enabled, `aria-level` in a treegrid, `aria-expanded` on expandable rows | | Body cell | `role="gridcell"` and `aria-colindex`, or `role="rowheader"` in a column with `rowHeader: true` | | Full-width row content | `role="gridcell"` with `aria-colspan` covering every column | | Column menu button | `aria-haspopup="menu"`, `aria-expanded`, labelled "<column> column menu" | | Pager | A `nav` landmark labelled "Pagination", with a polite live region for the page label | ### Counts under virtualization Only the visible window of rows and columns is rendered, so the DOM alone would tell assistive technology that the grid has 30 rows. The grid sets `aria-rowcount` to the number of display rows plus the header rows (one, or two with floating filters), and gives every rendered row its true `aria-rowindex`. With pagination, counts and indexes cover the whole result, not only the current page. Columns get `aria-colcount` and `aria-colindex` the same way. A screen reader therefore announces "row 48,213 of 1,000,001" while users move through a large grid. ### Announcements The grid owns a visually hidden polite live region. Sort changes are announced there, for example "Sorted by Revenue, descending" or "Sort cleared for Revenue", so users who sort from the keyboard hear the result without moving focus. ### Name the grid Give every grid an accessible name that describes its content: ```ts title="accessible-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; createGrid(document.querySelector('#orders')!, { columns, rows: orders, ariaLabel: 'Open sales orders, EMEA', emptyMessage: 'No open orders in EMEA', }); ``` ## Focus model The grid uses a roving tabindex: exactly one cell, header cell or the viewport itself is in the page's tab order at any time. Tab moves focus into the grid at that cell, and the next Tab leaves the grid. Inside the grid, arrow keys move between cells, and Arrow Up from the first row moves into the header. When data changes, focus stays at the same row index and column. If the column disappears, focus moves to the first column; if the row index no longer exists, focus moves to the last row. ```ts grid.focusCell(0, 'customer'); const cell = grid.getFocusedCell(); grid.on('focusChanged', ({ cell }) => { if (cell) statusLine.textContent = `${cell.colId}, row ${cell.rowIndex + 1}`; }); ``` `focusCell()` scrolls the cell into view and moves DOM focus to it. A `rowIndex` of `-1` refers to the header row. **`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridApi extends Widget, GridEvents>, GridFeatureApi ``` | Property | Type | Description | | --- | --- | --- | | `scrollToRow` | `(rowIndex: number, align?: 'auto' \| 'start' \| 'center' \| 'end') => void` | | | `scrollToColumn` | `(colId: string) => void` | | | `focusCell` | `(rowIndex: number, colId: string) => void` | | | `getFocusedCell` | `() => CellPosition \| null` | | ## Keyboard map ### Moving around | Key | Action | | --- | --- | | Arrow keys | Move one cell. Arrow Up from the first row moves to the header. | | Home / End | First or last column of the current row | | Ctrl+Home / Ctrl+End | First column of the first row, or last column of the last row | | Page Up / Page Down | Up or down by one screen of rows | | Tab / Shift+Tab | Leave the grid (when not editing) | On macOS, Cmd works wherever Ctrl is listed. ### Headers and filters | Key | Action | | --- | --- | | Enter or Space on a header | Sort by that column | | Shift+Enter or Shift+Space on a header | Add the column to a multi-column sort | | Alt+Arrow Down or the context menu key on a header | Open the column menu | | Arrow Down on a header | Move to the column's floating filter when the filter row is shown, otherwise to the first row | | Arrow Down / Arrow Up in a floating filter | Move to the first row, or back to the header | The column menu also holds the keyboard and single-pointer alternatives to dragging a header: **Move left**, **Move right**, **Move to first** and **Move to last** (within the column's pinned section and column group, skipping columns with `reorderable: false`), and **Autosize this column**, **Increase width** and **Decrease width** (20 px steps, within `minWidth` and `maxWidth`). They call `moveColumn` and `setColumnWidth`, so the usual `columnMoved` and `columnResized` events fire. ### Selection | Key | Action | | --- | --- | | Space | Toggle selection of the focused row, when `rowSelection` is set | | Shift+Space | Select the range from the last toggled row to the focused row (`'multiple'`) | | Ctrl+A | Select all rows (`'multiple'`) | ### Editing | Key | Action | | --- | --- | | Enter or F2 | Start editing the focused cell | | Printable character | Start editing, replacing the value with that character | | Space on a checkbox cell | Start editing and toggle the checkbox, when row selection is off | | Delete or Backspace | Clear an editable cell (an empty string for text columns, `null` otherwise) | | Enter while editing | Commit | | Tab / Shift+Tab while editing | Commit and start editing the next or previous editable cell, wrapping to the next or previous row | | Escape while editing | Cancel | ### Expandable rows | Key | Action | | --- | --- | | Enter on a non-editable cell of an expandable row | Toggle expansion | | Space on an expandable row, when row selection is off | Toggle expansion | Expandable rows come from Grid Pro features such as [row grouping](https://docs.birchui.com/grid-pro/row-grouping.md), [tree data](https://docs.birchui.com/grid-pro/tree-data.md) and [master/detail](https://docs.birchui.com/grid-pro/master-detail.md). Grid Pro modules add their own keys through key handlers, for example for [range selection](https://docs.birchui.com/grid-pro/range-selection.md) and [clipboard](https://docs.birchui.com/grid-pro/clipboard.md) copy and paste. ## Adding your own keys There are two ways to add keys, and both run before the built-in key map whenever no editor is open. **`cellKeyDown`** fires for every key pressed on a focused body cell. Call `event.preventDefault()` to stop the grid from handling the key itself. This suits app-level shortcuts and blocking keys you do not want: ```ts title="ledger-keys.ts" grid.on('cellKeyDown', ({ event, row, colId }) => { const key = event as KeyboardEvent; if (key.key === 'Delete' && row) { key.preventDefault(); if (confirm(`Archive order ${row.id}?`)) grid.applyTransaction({ remove: [row] }); return; } if (colId === 'amount' && key.key.length === 1) { key.preventDefault(); } }); ``` The second branch blocks typing into the locked `amount` column, so a stray keystroke never opens its editor, while arrow keys keep navigating. **Module key handlers** see keys in header cells too and receive the focused position. Register them with `addKeyHandler` in a [module](https://docs.birchui.com/grid/modules.md#key-handlers) and return `true` when you handle the key; the grid then calls `preventDefault()` and skips its own handling. ```ts title="order-shortcuts.ts" import { createGrid, type GridModule } from '@birchui/core'; const OpenOrderShortcut: GridModule = { name: 'openOrderShortcut', install(grid) { return grid.addKeyHandler((event, focused) => { if (event.key !== 'o' || !focused || focused.rowIndex < 0) return false; const order = grid.api.getDisplayRow(focused.rowIndex)?.data; if (order) window.location.assign(`/orders/${order.id}`); return true; }); }, }; createGrid(container, { columns, rows: orders, modules: [OpenOrderShortcut] }); ``` `cellKeyDown` listeners run before module key handlers, so a key that a listener cancels never reaches them. Modules can also listen to the internal `keyDown` event, which runs before both. See [Order of key handling](https://docs.birchui.com/grid/modules.md#order-of-key-handling). ## Row headers Mark the column that names each row with `rowHeader: true` so screen readers announce it as the row header when users move across the other cells: ```ts title="row-header.ts" const columns: ColumnDef[] = [ { field: 'customer', header: 'Customer', rowHeader: true }, { field: 'total', header: 'Total', type: 'number' }, ]; ``` Grid Pro sets it on the group and pivot label column. ## Treegrid for grouped and tree data When any display row is nested or expandable, the viewport switches to `role="treegrid"`. Each row then carries `aria-level` (1 for top-level rows), and expandable rows carry `aria-expanded`. Screen readers announce the hierarchy as users move, for example "EMEA, expanded, level 1". ## Visual accessibility - **Focus** is drawn as a 2-pixel inset ring in `--lq-focus-ring` on the focused cell, header or filter control, and as an outline on menu items. If you change the color, keep a 3:1 contrast ratio with the cell background. - **Forced colors**: in Windows High Contrast and other `forced-colors: active` modes, focus is drawn as a real outline in the system `Highlight` colour and selected rows use `Highlight` and `HighlightText`. - **Selection**: with `rowSelection` but no checkbox column, selected rows use `--lq-selection-strong-bg` and `--lq-selection-strong-fg`, so selection does not rely on a faint tint. With `checkboxSelection` the lighter `--lq-selection-bg` tint is used and the checkbox shows the state. - **Inputs**: filter inputs use `--lq-input-border` for their outline and `--lq-placeholder-fg` for hint text, both chosen to pass WCAG contrast in the bundled themes. Set them too if you override the theme. - **Themes**: the bundled light and dark themes meet WCAG 2.2 AA contrast for text, and their accent colors meet the 3:1 minimum for non-text UI such as sort indicators and the focus ring. See the [contrast table](https://docs.birchui.com/grid/theming.md#contrast). `theme: 'auto'` follows `prefers-color-scheme`. - **Motion**: the grid respects `prefers-reduced-motion` and does not animate scrolling or data changes. - **Zoom**: text sizes come from `--lq-font-size`, so browser zoom and your own font-size overrides scale the grid. ## Checklist for your grid - Set `ariaLabel` to a name that describes the data. - Give icon-only cells and buttons in renderers an `aria-label`. - Keep `emptyMessage` meaningful; the default is "No rows to show". - Do not put interactive controls in cells without handling their keys: stop propagation of the keys your control uses, like the [custom editors](https://docs.birchui.com/grid/editing.md#custom-editors) example does. - Test with a screen reader in focus mode; the grid is a composite widget and expects focus mode for navigation. --- Source: https://docs.birchui.com/grid/localization/ # Localization and RTL > Translate every grid string with localeText or a locale pack, format values for a locale, and lay the grid out right to left. Every piece of text the grid renders or announces, from menu items and filter labels to the pager and screen reader announcements, goes through one translator. You can replace any of it per grid with `localeText`, for every widget on the page with `setDefaultLocaleText()`, or with a ready-made locale pack. Values are formatted with `Intl` for the `locale` option, and `rtl` mirrors the layout. ## Translating one grid `localeText` takes a map of message keys to text. Keys you leave out keep their English default. ```ts title="orders-grid-de.ts" import { createGrid } from '@birchui/core'; const grid = createGrid(el, { columns, rows: orders, locale: 'de-DE', localeText: { 'grid.noRows': 'Keine Aufträge gefunden', 'grid.filter.placeholder': 'Filtern…', 'grid.pager.page': 'Seite {page} von {pageCount}', 'grid.menu.showAllColumns': { one: 'Ausgeblendete Spalte anzeigen', other: 'Alle Spalten anzeigen ({count} ausgeblendet)', }, }, }); ``` - `{name}` placeholders are replaced with values such as `{column}`, `{count}` or `{page}`. Unknown placeholders are left as written. - A message can be a plural object (`zero`, `one`, `two`, `few`, `many`, `other`). The category is chosen with `Intl.PluralRules` for the pack's locale from the `count` parameter; `other` is required and used as the fallback. - `grid.update({ localeText, locale })` switches language at runtime without recreating the grid. ## Locale packs A locale pack is `{ locale, text }`. `@birchui/core` exports packs for English, German, French, Spanish, Portuguese, Japanese and Chinese, each with the strings of every Birch UI product, so one pack translates the grid, scheduler, calendar, charts and the rest: ```ts import { createGrid, localeDe } from '@birchui/core'; const grid = createGrid(el, { columns, rows: orders, locale: 'de-DE', localeText: localeDe }); ``` Each pack is also a separate entry point, so you can load it on demand and ship only the languages you use: ```ts const { localeJa } = await import('@birchui/core/locales/ja'); grid.update({ locale: 'ja-JP', localeText: localeJa }); ``` | Export | Entry point | Locale | | --- | --- | --- | | `localeEn` | `@birchui/core/locales/en` | `en` | | `localeDe` | `@birchui/core/locales/de` | `de` | | `localeFr` | `@birchui/core/locales/fr` | `fr` | | `localeEs` | `@birchui/core/locales/es` | `es` | | `localePt` | `@birchui/core/locales/pt` | `pt` | | `localeJa` | `@birchui/core/locales/ja` | `ja` | | `localeZh` | `@birchui/core/locales/zh` | `zh` | To adjust a pack, spread it: `{ locale: 'de', text: { ...localeDe.text, 'grid.noRows': 'Keine Daten' } }`. > **Note** > > Messages missing from a pack fall back to the page-wide default, then to the English text built into the component, so a partial pack never shows raw keys. ## A default for the whole page `setDefaultLocaleText(pack)` sets the text used by every widget that does not override a key with its own `localeText`. Call it once at startup, before creating widgets: ```ts title="main.ts" import { setDefaultLocaleText, localeFr } from '@birchui/core'; setDefaultLocaleText(localeFr); ``` The lookup order for every message is: the widget's `localeText`, then the default pack, then the built-in English text. ## Formatting values `locale` is a BCP 47 tag passed to `Intl.NumberFormat` and `Intl.DateTimeFormat` for `number` and `date` columns, and to the plural rules of messages. Without it, the browser's locale is used. Columns with a `format` function format themselves, so build those formatters with the same locale: ```ts const eur = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }); const columns: ColumnDef[] = [{ field: 'total', type: 'number', format: (value) => eur.format(Number(value)) }]; ``` ## Right-to-left layout The grid lays itself out right to left when its container, or any ancestor, has `dir="rtl"`. Set `rtl: true` or `rtl: false` to override what the page says: ```ts const grid = createGrid(el, { columns, rows: orders, locale: 'ar-EG', rtl: true }); grid.getDirection(); ``` In RTL the first column is on the right, `pinned: 'left'` pins to the inline start (the right edge), horizontal scrolling and Arrow Left and Arrow Right follow the reading direction, and the root element gets `dir="rtl"`. `update({ rtl })` switches direction at runtime. ## Translating your own UI The same helpers are exported for your toolbars and status lines, so all text follows one pack: | Export | Purpose | | --- | --- | | `t(key, fallback, params?)` | Look up a key in the default pack | | `createTranslator(localeText?, locale?)` | A `Translate` function with its own overrides on top of the default pack | | `formatMessage(message, locale, params?)` | Fill placeholders and pick the plural form of one message | | `setDefaultLocaleText(pack)` / `getDefaultLocaleText()` | Set or read the page-wide pack | | `resolveDirection(element, rtl?)` | `'ltr'` or `'rtl'` from an explicit flag or the nearest `dir` attribute | | `grid.translate(key, fallback, params?)` | Translate with the grid's own `localeText` | ```ts import { t } from '@birchui/core'; status.textContent = t('orders.selected', '{count} orders selected', { count: grid.getSelectedIds().length }); ``` **`LocalePack`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface LocalePack ``` | Property | Type | Description | | --- | --- | --- | | `readonly locale` | `string` | | | `readonly text` | `LocaleText` | | **`PluralText`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface PluralText ``` | Property | Type | Description | | --- | --- | --- | | `zero?` | `string` | | | `one?` | `string` | | | `two?` | `string` | | | `few?` | `string` | | | `many?` | `string` | | | `other` | `string` | | ## Message keys The grid uses these keys. Grid Pro, the scheduler and the other products use their own prefixes (`gridPro.`, `scheduler.`, `calendar.` and so on) in the same packs. | Key | English text | | --- | --- | | `grid.announce.copiedCell` | Copied cell | | `grid.announce.filterApplied` | Filter applied to {column} | | `grid.announce.filterCleared` | Filter cleared for {column} | | `grid.announce.sortCleared` | Sort cleared for {column} | | `grid.announce.sortedAsc` | Sorted by {column}, ascending | | `grid.announce.sortedDesc` | Sorted by {column}, descending | | `grid.contextMenu.copyCell` | Copy cell | | `grid.contextMenu.copyRow` | Copy row | | `grid.contextMenu.copySelectedRows` | Copy selected rows | | `grid.contextMenu.copyWithHeaders` | Copy with headers | | `grid.contextMenu.exportCsv` | Export CSV | | `grid.filter.all` | All | | `grid.filter.and` | AND | | `grid.filter.apply` | Apply | | `grid.filter.blanks` | (Blanks) | | `grid.filter.close` | Close | | `grid.filter.columnLabel` | Filter {column} | | `grid.filter.combine` | Combine conditions with | | `grid.filter.condition` | Condition {index} | | `grid.filter.enterBoth` | Enter both values | | `grid.filter.enterDate` | Enter a valid date | | `grid.filter.enterNumber` | Enter a number | | `grid.filter.from` | From | | `grid.filter.matchCount` | {matches} of {count} values | | `grid.filter.noMatches` | No matching values | | `grid.filter.no` | No | | `grid.filter.operator` | Operator | | `grid.filter.or` | OR | | `grid.filter.placeholder` | Filter… | | `grid.filter.reset` | Reset | | `grid.filter.search` | Search | | `grid.filter.searchValues` | Search {column} values | | `grid.filter.selectAll` | Select all | | `grid.filter.to` | To | | `grid.filter.values` | {column} values | | `grid.filter.value` | Value | | `grid.filter.yes` | Yes | | `grid.group.collapse` | Collapse {group} | | `grid.group.expand` | Expand {group} | | `grid.group.unnamed` | column group | | `grid.header.columnMenu` | {column} column menu | | `grid.menu.autosizeAll` | Autosize all columns | | `grid.menu.autosizeColumn` | Autosize this column | | `grid.menu.clearSort` | Clear sort | | `grid.menu.decreaseWidth` | Decrease width | | `grid.menu.filter` | Filter… | | `grid.menu.hideColumn` | Hide column | | `grid.menu.increaseWidth` | Increase width | | `grid.menu.moveFirst` | Move to first | | `grid.menu.moveLast` | Move to last | | `grid.menu.moveLeft` | Move left | | `grid.menu.moveRight` | Move right | | `grid.menu.pinLeft` | Pin left | | `grid.menu.pinRight` | Pin right | | `grid.menu.showAllColumns` | Show all columns ({count} hidden) | | `grid.menu.sortAsc` | Sort ascending | | `grid.menu.sortDesc` | Sort descending | | `grid.menu.unpin` | Unpin | | `grid.noRows` | No rows to show | | `grid.pager.first` | First page | | `grid.pager.label` | Pagination | | `grid.pager.last` | Last page | | `grid.pager.next` | Next page | | `grid.pager.page` | Page {page} of {pageCount} | | `grid.pager.previous` | Previous page | | `grid.pager.range` | {from}–{to} of {total} | | `grid.selection.selectAll` | Select all rows | | `grid.selection.selectRow` | Select row {row} | | `grid.value.false` | No | | `grid.value.true` | Yes | ## Related - [Accessibility](https://docs.birchui.com/grid/accessibility.md) for the announcements these strings feed. - [Forms localization](https://docs.birchui.com/forms/i18n.md) for the form renderer's own message catalogue. - [Time zones](https://docs.birchui.com/scheduler/time-zones.md) in the scheduler. --- Source: https://docs.birchui.com/grid/theming/ # Theming > Style the grid with --lq-* CSS custom properties, switch between light, dark and auto themes, pick a density, and ship styles as a CSS file when you need to. The grid is styled entirely through CSS custom properties prefixed with `--lq-`. There is no Shadow DOM, every element has a class prefixed with `lq-`, and the built-in selectors are kept to one or two classes, so your own CSS can reach and override anything. **Live demo: Themes, density and custom properties** (runs on the HTML version of this page). Source of `demos/theming.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef, type GridOptions } from '@birchui/core'; import { docsTheme, field, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order, } from './_shared'; export const meta = { title: 'Themes, density and custom properties', height: 460 }; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 170 }, { field: 'status', header: 'Status', width: 120 }, { field: 'quantity', header: 'Qty', type: 'number', width: 80 }, { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency }, ]; const ACCENTS: Record = { Default: '', Teal: '#0f766e', Plum: '#7e22ce', Amber: '#b45309' }; function select(values: string[], initial: string): HTMLSelectElement { const el = document.createElement('select'); for (const value of values) el.add(new Option(value, value, value === initial, value === initial)); return el; } export default function mount(el: HTMLElement): () => void { const { toolbar, body } = layout(el); const theme = select(['Follow docs', 'light', 'dark'], 'Follow docs'); const density = select(['compact', 'normal', 'comfortable'], 'normal'); const accent = select(Object.keys(ACCENTS), 'Default'); const stripes = document.createElement('input'); stripes.type = 'checkbox'; toolbar.append(field('Theme', theme), field('Density', density), field('Accent', accent), field('Stripes', stripes)); const grid = createGrid(body, { columns, rows: makeOrders(300, 11), getRowId: (order) => order.id, checkboxSelection: true, rowSelection: 'multiple', theme: docsTheme(), ariaLabel: 'Theme playground', }); const resolvedTheme = () => (theme.value === 'Follow docs' ? docsTheme() : (theme.value as 'light' | 'dark')); const apply = () => { grid.update({ theme: resolvedTheme(), density: density.value as GridOptions['density'], stripes: stripes.checked, }); const color = ACCENTS[accent.value]; for (const name of ['--lq-accent', '--lq-focus-ring']) { if (color) grid.element.style.setProperty(name, color); else grid.element.style.removeProperty(name); } if (color) grid.element.style.setProperty('--lq-selection-bg', `color-mix(in srgb, ${color} 14%, transparent)`); else grid.element.style.removeProperty('--lq-selection-bg'); }; for (const control of [theme, density, accent, stripes]) control.addEventListener('change', apply); const stopTheme = onDocsThemeChange(() => { if (theme.value === 'Follow docs') apply(); }); return () => { for (const control of [theme, density, accent, stripes]) control.removeEventListener('change', apply); stopTheme(); grid.destroy(); }; } ``` ## Built-in themes ```ts title="themed-grid.ts" import { createGrid } from '@birchui/core'; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, theme: 'auto', }); document.querySelector('#theme')!.addEventListener('change', (event) => { grid.update({ theme: (event.target as HTMLSelectElement).value }); }); ``` The `theme` option becomes a class on the grid root, `lq-theme-`: | `theme` | Root class | Result | | --- | --- | --- | | Not set (default) | None | Inherits from the nearest ancestor with `lq-theme-dark` or `lq-theme-auto`; light when there is none | | `'light'` | `lq-theme-light` | The light palette, even inside a dark ancestor | | `'dark'` | `lq-theme-dark` | The dark palette, with `color-scheme: dark` so native inputs and scrollbars match | | `'auto'` | `lq-theme-auto` | Light, switching to dark when the user's system prefers a dark color scheme | | `'harbor'` | `lq-theme-harbor` | Your own theme, see [A custom theme](#a-custom-theme) | The root also always has `lq-grid`, a density class (`lq-density-normal` by default) and `lq-stripes` when `stripes: true`. ### Inheriting the theme from your page Leave `theme` unset and put the theme class on any ancestor, such as `` or your app shell. Every grid inside picks it up, and switching the class switches every grid at once without calling `update()`: ```html
``` ```ts createGrid(document.querySelector('#orders')!, { columns, rows }); document.body.classList.replace('lq-theme-dark', 'lq-theme-auto'); ``` `lq-theme-auto` on an ancestor follows the operating system's color scheme. A grid with an explicit `theme` keeps its own palette regardless of its ancestors. ### Following your app's dark mode If your app already has its own dark mode class and you'd rather not add `lq-theme-dark` to the page, pass the resolved value instead: ```ts const appTheme = () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light'); const grid = createGrid(container, { columns, rows, theme: appTheme() }); new MutationObserver(() => grid.update({ theme: appTheme() })).observe(document.documentElement, { attributes: true, attributeFilter: ['class'], }); ``` ## CSS custom properties The light values are defined on `.lq-grid` and `.lq-theme-light`; `.lq-theme-dark` and `.lq-theme-auto` (in dark mode) redefine the color properties. | Property | Light | Dark | Used for | | --- | --- | --- | --- | | `--lq-font-family` | `system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif` | same | All grid text | | `--lq-font-size` | `13px` | same | Cell and header text | | `--lq-cell-padding` | `10px` | same | Horizontal padding in cells and headers | | `--lq-fg` | `#1f2328` | `#e6edf3` | Cell text | | `--lq-bg` | `#ffffff` | `#0d1117` | Grid and cell background | | `--lq-muted-fg` | `#59636e` | `#9198a1` | Secondary text, empty message, icons | | `--lq-border` | `#d1d9e0` | `#30363d` | Outer border, header and pinned-column edges | | `--lq-border-subtle` | `#e6eaef` | `#21262d` | Row separators, filter row, menu separators | | `--lq-header-bg` | `#f6f8fa` | `#161b22` | Header, filter row, top and bottom slots, pager | | `--lq-header-fg` | `#1f2328` | `#e6edf3` | Header text | | `--lq-row-alt` | `#f9fafb` | `#11161d` | Odd rows when `stripes: true` | | `--lq-row-hover` | `#eef3f9` | `#1a2230` | Hovered rows and menu items | | `--lq-accent` | `#1f6feb` | `#4493f8` | Sort indicators, active filters, resize and drop indicators | | `--lq-accent-fg` | `#ffffff` | `#0d1117` | Text on accent backgrounds | | `--lq-selection-bg` | `rgba(31, 111, 235, 0.12)` | `rgba(68, 147, 248, 0.18)` | Selected rows | | `--lq-range-bg` | `rgba(31, 111, 235, 0.14)` | `rgba(68, 147, 248, 0.2)` | Selected cell ranges ([Grid Pro](https://docs.birchui.com/grid-pro/range-selection.md)) | | `--lq-focus-ring` | `#1f6feb` | `#4493f8` | Focus ring on cells, headers, filters and pager buttons | | `--lq-pinned-shadow` | `rgba(15, 23, 42, 0.12)` | `rgba(0, 0, 0, 0.45)` | Shadow at the edge of pinned columns | | `--lq-menu-bg` | `#ffffff` | `#161b22` | Column menu background | | `--lq-menu-shadow` | `0 8px 24px rgba(15, 23, 42, 0.16)` | `0 8px 24px rgba(0, 0, 0, 0.5)` | Column menu shadow | | `--lq-input-bg` | `#ffffff` | `#0d1117` | Floating filter inputs and editors | | `--lq-radius` | `6px` | same | Outer corners and controls | Two more properties are set inline on the root from your options: `--lq-row-height` and `--lq-header-height`. Read them in your own CSS, for example to size icons in a cell renderer, but change them through `rowHeight`, `headerHeight` and `density`. ## Contrast Both bundled themes meet WCAG 2.2 AA: at least 4.5:1 for text and 3:1 for non-text UI. Ratios computed from the default colors: | Pair | Light | Dark | Requirement | | --- | --- | --- | --- | | Text (`--lq-fg`) on background (`--lq-bg`) | 15.8:1 | 16.0:1 | 4.5:1 | | Text on a hovered row (`--lq-row-hover`) | 14.2:1 | 13.5:1 | 4.5:1 | | Text on a striped row (`--lq-row-alt`) | 15.1:1 | 15.4:1 | 4.5:1 | | Header text on header background | 14.8:1 | 14.6:1 | 4.5:1 | | Muted text (`--lq-muted-fg`) on background | 6.1:1 | 6.5:1 | 4.5:1 | | Muted text on header background | 5.7:1 | 5.9:1 | 4.5:1 | | Accent (sort indicator, focus ring) on background | 4.6:1 | 6.1:1 | 3:1 | | Accent on header background | 4.4:1 | 5.6:1 | 3:1 | | Accent on a hovered row | 4.2:1 | 5.2:1 | 3:1 | | Accent text color (`--lq-accent-fg`) on accent | 4.6:1 | 6.1:1 | 4.5:1 | When you build a custom theme, keep text colors at 4.5:1 or more against every background they appear on (cell, header, hovered, striped and selected rows), and keep `--lq-accent`, `--lq-focus-ring` and `--lq-border` used as the only indicator of state at 3:1 or more. Check the combinations, not just text on `--lq-bg`: muted text on the header background is usually the tightest pair. ## Overriding styles The grid injects its stylesheet into the document head when the first grid is created, which places it after the stylesheets already on the page. At equal specificity the injected rules win, so write overrides with at least one class more than the rule you are overriding: ```css title="orders-grid.css" #orders .lq-grid { --lq-accent: #1a7f37; --lq-selection-bg: rgba(26, 127, 55, 0.14); } .lq-grid.lq-theme-light { --lq-header-bg: #f3f6f9; } .lq-grid .lq-row.lq-row-total { font-weight: 800; } ``` > **Set properties on the grid element** > > The grid root defines every `--lq-*` property on itself, so values set on an ancestor such as `body` or your container are not inherited into the grid. Target the `.lq-grid` element, as above. ## A custom theme Write a rule for `.lq-grid.lq-theme-` and pass the name as `theme`: ```css title="harbor-theme.css" .lq-grid.lq-theme-harbor { --lq-font-family: 'Inter', system-ui, sans-serif; --lq-font-size: 14px; --lq-fg: #0f2a3d; --lq-bg: #fbfdff; --lq-muted-fg: #5b7184; --lq-border: #d3e1ec; --lq-border-subtle: #e4edf4; --lq-header-bg: #eef5fb; --lq-header-fg: #0f2a3d; --lq-row-alt: #f5f9fc; --lq-row-hover: #e6f0f8; --lq-accent: #0a6c9e; --lq-accent-fg: #ffffff; --lq-selection-bg: rgba(10, 108, 158, 0.12); --lq-range-bg: rgba(10, 108, 158, 0.16); --lq-focus-ring: #0a6c9e; --lq-radius: 4px; } ``` ```ts createGrid(container, { columns, rows, theme: 'harbor' }); ``` Properties you leave out keep their light defaults, so a theme can be as small as an accent color. ### A dark variant of your theme Scope the dark values under an ancestor class your app already toggles, such as one on ``: ```css .app-dark .lq-grid.lq-theme-harbor { --lq-fg: #e3eef7; --lq-bg: #0d1b26; --lq-muted-fg: #8aa2b6; --lq-border: #22394b; --lq-border-subtle: #1a2f3e; --lq-header-bg: #132634; --lq-header-fg: #e3eef7; --lq-row-alt: #102230; --lq-row-hover: #17303f; --lq-selection-bg: rgba(77, 171, 222, 0.2); --lq-focus-ring: #4dabde; --lq-menu-bg: #132634; --lq-input-bg: #0d1b26; color-scheme: dark; } ``` ```ts document.documentElement.classList.toggle('app-dark', isDark); ``` The grid keeps `theme: 'harbor'`; the cascade does the rest, so no grid update is needed when the mode changes. ## Density `density` sets the default row height, header height, font size and cell padding together: | `density` | Row height | Header height | Font size | Cell padding | | --- | --- | --- | --- | --- | | `'compact'` | 28px | 32px | 12px | 8px | | `'normal'` (default) | 34px | 38px | 13px | 10px | | `'comfortable'` | 42px | 46px | 14px | 14px | ```ts grid.update({ density: 'compact' }); ``` An explicit `rowHeight` number or `headerHeight` always wins over the density preset. The header height defaults to the row height plus 4 pixels. ## Targeting elements with classes Every element the grid renders has an `lq-` class. Useful hooks include `lq-header-cell`, `lq-cell`, `lq-cell-editable`, `lq-cell-editing`, `lq-cell-focused`, `lq-cell-pinned`, `lq-row`, `lq-row-selected`, `lq-row-odd`, `lq-row-group`, `lq-filter-input`, `lq-pager` and `lq-empty`. For anything tied to your data, add your own classes with `cellClass`, `headerClass` and `rowClass` instead of relying on structure: ```ts const columns: ColumnDef[] = [ { field: 'revenue', type: 'number', headerClass: 'col-money', cellClass: 'col-money' }, ]; ``` ```css .lq-grid .col-money { font-weight: 600; letter-spacing: -0.01em; } ``` The grid already uses tabular figures for all text, so numbers line up without extra CSS. See [Columns](https://docs.birchui.com/grid/columns.md#styling-cells-cellclass-headerclass-and-align) and [Rows](https://docs.birchui.com/grid/rows.md#row-classes-and-stripes). ## Sizing the grid The root fills its container (`width: 100%; height: 100%`) with a minimum height of 120 pixels. Give the container an explicit height, or place it in a flex or grid layout that sizes it: ```css .orders-panel { display: flex; flex-direction: column; height: calc(100vh - 64px); } .orders-panel > #orders { flex: 1; min-height: 0; } ``` ## How styles are loaded By default the grid injects its stylesheet, as a ` ``` The component renders one `div` and creates the grid inside it on mount. Size that `div` with `class` or `style`. ## Passing options There are two ways to pass grid options, and you can combine them. **As attributes.** Any attribute other than `class`, `style`, `id` and event listeners is treated as a grid option. Kebab-case names are converted to camelCase, so `:get-row-id` and `:getRowId` both set `getRowId`. ```vue ``` **As one object.** The `options` prop takes any part of [`GridOptions`](https://docs.birchui.com/api/core.md#gridoptions). This is the easiest way to get full type checking in templates: ```vue ``` When both are given, attributes win over keys in `options`. Remember that boolean options need a bound value. Write `:checkbox-selection="true"`, not a bare `checkbox-selection` attribute, which Vue passes as an empty string. ## Events Every grid event is emitted with its kebab-case name. The listener receives the payload object: | Grid event | Vue listener | | --- | --- | | `ready` | `@ready` | | `cellClick`, `cellDoubleClick`, `cellKeyDown` | `@cell-click`, `@cell-double-click`, `@cell-key-down` | | `cellValueChanged` | `@cell-value-changed` | | `rowClick`, `selectionChanged` | `@row-click`, `@selection-changed` | | `sortChanged`, `filterChanged` | `@sort-changed`, `@filter-changed` | | `columnResized`, `columnMoved`, `columnPinned`, `columnVisible`, `columnStateChanged` | `@column-resized`, `@column-moved`, `@column-pinned`, `@column-visible`, `@column-state-changed` | | `modelUpdated`, `focusChanged`, `viewportScroll`, `pageChanged` | `@model-updated`, `@focus-changed`, `@viewport-scroll`, `@page-changed` | | `rowExpanded`, `editStart`, `editStop` | `@row-expanded`, `@edit-start`, `@edit-stop` | ## The grid API The component exposes `api`, the [`GridApi`](https://docs.birchui.com/api/core.md#gridapi) of the grid it created. Read it through a template ref. It is `null` until the component is mounted: ```ts const grid = ref<{ api: GridApi | null } | null>(null); function showLatestFirst() { grid.value?.api?.setSort([{ colId: 'placedAt', dir: 'desc' }]); grid.value?.api?.scrollToRow(0, 'start'); } ``` The `ready` event also carries the API: `@ready="({ api }) => api.autosizeColumns()"`. If you keep the API in a variable of your own, use `shallowRef`. The API object is a class instance, which Vue never wraps in a reactive proxy, and `shallowRef` keeps it that way while still letting templates react when you assign it: ```ts const gridApi = shallowRef | null>(null); function onReady({ api }: { api: GridApi }) { gridApi.value = api; } ``` ## Reactivity and updates The grid is created once in `onMounted`. After that, the component compares each option with the value it last sent, by identity, and calls `api.update()` with only the changed keys. It never recreates the grid. - **Replace arrays instead of mutating them.** `orders.value.push(order)` keeps the same array, so nothing is sent. Write `orders.value = [...orders.value, order]`, or call `grid.value?.api?.applyTransaction({ add: [order] })`. - **Use `shallowRef` for row data.** A deep `ref` makes every row object reactive, which costs memory and time with tens of thousands of rows and gives the grid proxies instead of your objects. `shallowRef` keeps rows as plain objects and still triggers updates when you assign a new array. - **Keep columns and callbacks stable.** Define `columns`, `getRowId` and `modules` once in ` ``` Set the license key once in `main.ts` with `setLicenseKey` from `@birchui/license`. See [Licensing and activation](https://docs.birchui.com/getting-started/licensing.md). ## Registering globally Import the component where you use it, as above, or register it once: ```ts title="main.ts" import { createApp } from 'vue'; import { BirchGrid } from '@birchui/vue'; import App from './App.vue'; createApp(App).component('BirchGrid', BirchGrid).mount('#app'); ``` ## Nuxt The component creates the grid in `onMounted`, which only runs in the browser. During server rendering it outputs its empty container, so it works in Nuxt pages without extra setup. Give the container a height so the layout does not shift when the grid appears. To skip server rendering of the grid completely, for example to show a skeleton instead, wrap it in ``: ```vue title="pages/orders.vue" ``` Set the license key in a client plugin: ```ts title="plugins/birchui.client.ts" import { setLicenseKey } from '@birchui/license'; export default defineNuxtPlugin(() => { setLicenseKey(useRuntimeConfig().public.birchLicenseKey as string); }); ``` ## Wrapping your own widgets `createVueComponent(definition)` turns any widget that follows the Birch UI widget contract into a Vue component with the same attribute, `options`, event and `api` behaviour. `BirchGrid` and `BirchScheduler` are built with it. ```ts import { createVueComponent } from '@birchui/vue'; import { shipmentMapDefinition } from './shipment-map'; export const ShipmentMap = createVueComponent(shipmentMapDefinition); ``` ## Event Calendar `@birchui/vue` has no calendar entry point. The Event Calendar follows the same widget contract, so the adapter's generic factory wraps it in one line. See the [Event Calendar overview](https://docs.birchui.com/calendar/overview.md) for its options and events. ```ts title="event-calendar.ts" import { createVueComponent } from '@birchui/vue'; import { calendarDefinition } from '@birchui/calendar'; export const EventCalendar = createVueComponent(calendarDefinition); ``` ```vue title="ClinicCalendar.vue" ``` ### Other Birch UI products Gantt, Pivot Studio, Charts, the diagram editor, the spreadsheet, the form renderer and the Form Builder work the same way: pass `ganttDefinition` from `@birchui/gantt`, `pivotStudioDefinition` from `@birchui/pivot-studio`, `chartDefinition` from `@birchui/charts`, `diagramDefinition` from `@birchui/diagram`, `spreadsheetDefinition` from `@birchui/spreadsheet`, `formDefinition` from `@birchui/forms` or `formBuilderDefinition` from `@birchui/forms/builder` to `createVueComponent`. The [Gantt](https://docs.birchui.com/gantt/overview.md), [Pivot Studio](https://docs.birchui.com/pivot-studio/overview.md), [Charts](https://docs.birchui.com/charts/overview.md), [Diagram](https://docs.birchui.com/diagram/overview.md), [Spreadsheet](https://docs.birchui.com/spreadsheet/overview.md) and [Forms](https://docs.birchui.com/forms/overview.md) overviews have complete examples. ## Next steps - [Using the Scheduler in your framework](https://docs.birchui.com/frameworks/scheduler.md) for `BirchScheduler`. - [Updating data](https://docs.birchui.com/grid/updating-data.md) for transactions and row ids. - The [@birchui/vue API reference](https://docs.birchui.com/api/vue.md). --- Source: https://docs.birchui.com/frameworks/angular/ # Angular > Use Birch UI Grid in Angular with the standalone BirchGridComponent, signal inputs, typed outputs, the grid API and server-side rendering. `@birchui/angular` provides standalone components with `OnPush` change detection, signal inputs and `output()` events. `BirchGridComponent` (selector `birchui-grid`) wraps the MIT grid from `@birchui/core`. It supports Angular 17.3 and later, with zone.js or zoneless change detection, and is safe for server-side rendering. ## Install ```bash npm install @birchui/angular @birchui/core ``` ## A complete example ```ts title="orders.component.ts" import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core'; import { BirchGridComponent } from '@birchui/angular'; import type { CellEvent, CellValueChangedEvent, ColumnDef, GridOptions } from '@birchui/core'; interface Order { id: string; customer: string; placedAt: string; status: 'open' | 'shipped' | 'cancelled'; total: number; } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); @Component({ selector: 'app-orders', standalone: true, imports: [BirchGridComponent], changeDetection: ChangeDetectionStrategy.OnPush, template: `
{{ selected().length }} selected
`, styles: ` .orders { height: 480px; } `, }) export class OrdersComponent { private readonly grid = viewChild.required>(BirchGridComponent); readonly search = signal(''); readonly selected = signal([]); readonly orders = signal([ { id: 'SO-10421', customer: 'Northwind Traders', placedAt: '2026-11-02', status: 'open', total: 1840.5 }, { id: 'SO-10422', customer: 'Contoso Ltd', placedAt: '2026-11-03', status: 'shipped', total: 312 }, { id: 'SO-10423', customer: 'Fabrikam Inc', placedAt: '2026-11-03', status: 'cancelled', total: 96.4 }, ]); readonly columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 120, pinned: 'left' }, { field: 'customer', header: 'Customer', flex: 1, filter: 'text', editable: true }, { field: 'placedAt', header: 'Placed', type: 'date', filter: 'date' }, { field: 'status', header: 'Status', filter: 'set', editable: true, editor: 'select', options: ['open', 'shipped', 'cancelled'] }, { field: 'total', header: 'Total', type: 'number', format: (value) => usd.format(Number(value)) }, ]; readonly options: Partial> = { getRowId: (order) => order.id, rowSelection: 'multiple', checkboxSelection: true, pagination: { pageSize: 50 }, sort: [{ colId: 'placedAt', dir: 'desc' }], }; openOrder(event: CellEvent): void { if (event.row && event.colId === 'id') console.info('Open order', event.row.id); } saveChange({ row, colId, newValue }: CellValueChangedEvent): void { console.info(`Order ${row.id}: ${colId} is now ${String(newValue)}`); } exportCsv(): void { this.grid().api?.downloadCsv({ fileName: 'orders.csv' }); } } ``` The host element is `display: block`. Give it a height in your styles; the grid fills it. ## Inputs | Input | Type | Notes | | --- | --- | --- | | `options` | `Partial>` | Any [grid option](https://docs.birchui.com/api/core.md#gridoptions) | | `columns` | `ColumnDef[]` | Shortcut for `options.columns` | | `rows` | `TRow[]` | Shortcut for `options.rows` | | `theme` | `'light' \| 'dark' \| 'auto'` or a theme class suffix | Shortcut for `options.theme` | | `quickFilter` | `string` | Shortcut for `options.quickFilter` | | `licenseKey` | `string` | Shortcut for `options.licenseKey` | The inputs are merged into one options object, and a shortcut input with a defined value overrides the same key in `options`. After each change, only the keys whose value changed by identity are sent to `update()`. The grid is never recreated. To change rows, columns or nested options, pass a new array or object. Mutating one in place is not detected: ```ts addOrder(order: Order): void { this.orders.update((orders) => [...orders, order]); } ``` For high-frequency updates, use the API instead: `this.grid().api?.applyTransaction({ update: [order] })`. ## Outputs There is one output for every grid event, with the same name and a typed payload: `ready`, `cellClick`, `cellDoubleClick`, `cellKeyDown`, `cellValueChanged`, `rowClick`, `selectionChanged`, `sortChanged`, `filterChanged`, `columnResized`, `columnMoved`, `columnPinned`, `columnVisible`, `columnStateChanged`, `modelUpdated`, `focusChanged`, `viewportScroll`, `pageChanged`, `rowExpanded`, `editStart` and `editStop`. ```html ``` Payload types are listed in the [events reference](https://docs.birchui.com/grid/events.md). ## Typed generics `BirchGridComponent` is generic over the row type. Templates infer `TRow` from `[rows]` and `[columns]`, so `$event.row` in every output is typed. For `viewChild`, pass the type argument explicitly: `viewChild.required>(BirchGridComponent)`. ## The grid API The component's `api` property returns the [`GridApi`](https://docs.birchui.com/api/core.md#gridapi) once the grid exists. It is `undefined` before the first browser render and after the component is destroyed. Read it in event handlers, after `(ready)`, or from `afterNextRender`: ```ts import { afterNextRender, Component, input, viewChild } from '@angular/core'; import { BirchGridComponent } from '@birchui/angular'; import type { ColumnDef } from '@birchui/core'; interface Technician { id: string; name: string; depot: string; openJobs: number; } @Component({ selector: 'app-technicians', standalone: true, imports: [BirchGridComponent], template: ``, }) export class TechniciansComponent { private readonly grid = viewChild.required>(BirchGridComponent); readonly technicians = input.required(); readonly columns: ColumnDef[] = [ { field: 'name', header: 'Technician', flex: 1 }, { field: 'depot', header: 'Depot', filter: 'set' }, { field: 'openJobs', header: 'Open jobs', type: 'number' }, ]; constructor() { afterNextRender(() => { const saved = localStorage.getItem('technician-columns'); if (saved) this.grid().api?.applyColumnState(JSON.parse(saved)); }); } } ``` The `ready` output carries the API as well: `(ready)="$event.api.autosizeColumns()"`. ## Grid Pro Pass modules and Pro options through `options`, and set the license key once at startup: ```ts title="main.ts" import { bootstrapApplication } from '@angular/platform-browser'; import { setLicenseKey } from '@birchui/license'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; import { environment } from './environments/environment'; setLicenseKey(environment.birchLicenseKey); bootstrapApplication(AppComponent, appConfig).catch((error) => console.error(error)); ``` ```ts title="revenue.component.ts" import { Component, input } from '@angular/core'; import { BirchGridComponent } from '@birchui/angular'; import { AllProModules } from '@birchui/grid-pro'; import type { ColumnDef, GridOptions } from '@birchui/core'; interface Sale { region: string; country: string; revenue: number; } @Component({ selector: 'app-revenue', standalone: true, imports: [BirchGridComponent], template: ``, styles: `.revenue { height: 520px; }`, }) export class RevenueComponent { readonly sales = input.required(); readonly columns: ColumnDef[] = [ { field: 'region', header: 'Region', rowGroup: true }, { field: 'country', header: 'Country' }, { field: 'revenue', header: 'Revenue', type: 'number', aggFunc: 'sum' }, ]; readonly options: Partial> = { modules: AllProModules, groupDefaultExpanded: 1, groupPanel: true, statusBar: { rowCount: true, aggregates: ['sum', 'avg'] }, }; } ``` You can also pass a key per grid with the `[licenseKey]` input. ## SSR and hydration Importing the package has no side effects and never touches `window` or `document`. On the server, `` renders as an empty host element. The grid is created in `afterNextRender`, which runs only in the browser after hydration, so no extra configuration is needed for `@angular/ssr`. Give the host a height in your CSS so the server-rendered page reserves the space and nothing shifts when the grid mounts. ## Change detection The grid and its DOM listeners run outside the Angular zone, so scrolling and pointer movement do not trigger change detection. An output re-enters the zone only when it emits and something is listening to it. Zoneless apps that use `provideZonelessChangeDetection()` need no extra setup; signal updates in your output handlers schedule rendering as usual. ## Wrapping your own widgets `injectBirchWidget(definition, outputs, options)` is the helper the grid component is built on. Call it in the injection context of your own standalone component to wrap any widget that follows the Birch UI widget contract. It creates the widget after the first browser render, sends changed options to `update()`, forwards events to your outputs and destroys the widget with the component. `withOverrides(base, overrides)` merges an `options` input with shortcut inputs the same way the grid component does. ## Event Calendar `@birchui/angular` has no calendar component. Wrap `calendarDefinition` from `@birchui/calendar` in a standalone component of your own with `injectBirchWidget`, as described in [Wrapping your own widgets](#wrapping-your-own-widgets). Declare one output per calendar event, or call `createCalendar` yourself inside `afterNextRender`. See the [Event Calendar overview](https://docs.birchui.com/calendar/overview.md) for its options and events. ### Other Birch UI products Gantt, Pivot Studio, Charts, the diagram editor, the spreadsheet, the form renderer and the Form Builder work the same way: pass `ganttDefinition` from `@birchui/gantt`, `pivotStudioDefinition` from `@birchui/pivot-studio`, `chartDefinition` from `@birchui/charts`, `diagramDefinition` from `@birchui/diagram`, `spreadsheetDefinition` from `@birchui/spreadsheet`, `formDefinition` from `@birchui/forms` or `formBuilderDefinition` from `@birchui/forms/builder` to `injectBirchWidget`. The [Gantt](https://docs.birchui.com/gantt/overview.md), [Pivot Studio](https://docs.birchui.com/pivot-studio/overview.md), [Charts](https://docs.birchui.com/charts/overview.md), [Diagram](https://docs.birchui.com/diagram/overview.md), [Spreadsheet](https://docs.birchui.com/spreadsheet/overview.md) and [Forms](https://docs.birchui.com/forms/overview.md) overviews have complete examples. ## Scheduler `BirchSchedulerComponent` comes from the secondary entry point `@birchui/angular/scheduler`, so apps that only use the grid never load scheduler code. See [Using the Scheduler in your framework](https://docs.birchui.com/frameworks/scheduler.md). ## Next steps - [Columns](https://docs.birchui.com/grid/columns.md), [filtering](https://docs.birchui.com/grid/filtering.md) and [editing](https://docs.birchui.com/grid/editing.md). - The [@birchui/angular API reference](https://docs.birchui.com/api/angular.md). --- Source: https://docs.birchui.com/frameworks/svelte/ # Svelte > Use Birch UI Grid in Svelte 5 and SvelteKit with the BirchGrid component or the use:birchGrid action. `@birchui/svelte` gives you two ways to use a Birch UI widget in Svelte 5: - **`BirchGrid`**, a component that takes grid options as props, events as `on…` props and exposes the grid API with `bind:api`. - **`birchGrid`**, an action you attach to any element with `use:birchGrid={params}`. Both create the grid in the browser only, so they work in SvelteKit with server rendering. The components ship as `.svelte` source files that your app compiles. They are exposed as named exports through the `svelte` export condition, which Vite and SvelteKit (`@sveltejs/vite-plugin-svelte`) use by default, so `import { BirchGrid } from '@birchui/svelte'` works without extra configuration. ## Install ```bash npm install @birchui/core @birchui/svelte ``` ## The BirchGrid component ```svelte title="OrdersGrid.svelte"
{selectedCount} selected
(selectedCount = selected.length)} onCellValueChanged={saveChange} /> ``` The component renders one `div` and creates the grid inside it. Size it with the `class` or `style` prop. Because the `div` belongs to the component, target the class with `:global(...)` from a parent's ` ``` Use the action when you want the container in your own markup and styles. Both forms accept options typed for your row type. ## Updates and reactivity The grid is created once. Whenever the props or the action parameter change, the adapter compares each option with the value it last sent, by identity, and passes only the changed keys to `api.update()`. Event handlers are always read from the latest props and never cause an update. - **Use `$state.raw` for rows and for the API.** `$state` turns every row into a deep proxy, which is slow for large datasets, and mutating it in place (`orders.push(order)`) keeps the same array, so the grid is not told. With `$state.raw`, assign a new array: `orders = [...orders, order]`. - **Use transactions for frequent changes.** `api.applyTransaction({ add, update, remove })` updates individual rows without replacing the data set. - **Keep columns and callbacks stable.** Declare `columns`, `getRowId` and `modules` in ` ``` ## SvelteKit Both the component and the action create the grid only in the browser: the component in an effect, the action when the element mounts. During server rendering the component outputs its empty container. No `browser` checks or dynamic imports are needed. Load data in a `load` function and pass it to the page: ```ts title="src/routes/orders/+page.server.ts" import type { PageServerLoad } from './$types'; import { listOrders } from '$lib/server/orders'; export const load: PageServerLoad = async () => ({ orders: await listOrders({ status: 'open' }), }); ``` ```svelte title="src/routes/orders/+page.svelte" ``` Set the license key once in the root layout: ```svelte title="src/routes/+layout.svelte" {@render children()} ``` ## Wrapping your own widgets `createSvelteAction(definition)` builds an action for any widget that follows the Birch UI widget contract, with the same `on` and `onReady` parameters. `toActionParams(definition, props)` converts component-style props (`onCellClick`) into action parameters (`on: { cellClick }`), which is how the `BirchGrid` component is built. ## Scheduler `BirchScheduler` and the `birchScheduler` action come from `@birchui/svelte/scheduler`. See [Using the Scheduler in your framework](https://docs.birchui.com/frameworks/scheduler.md). ## Event Calendar `@birchui/svelte` has no calendar entry point. The Event Calendar follows the same widget contract, so the adapter's generic factory wraps it in one line. See the [Event Calendar overview](https://docs.birchui.com/calendar/overview.md) for its options and events. ```svelte title="ClinicCalendar.svelte"
console.info('Open appointment', event.id) }, }} >
``` ### Other Birch UI products Gantt, Pivot Studio, Charts, the diagram editor, the spreadsheet, the form renderer and the Form Builder work the same way: pass `ganttDefinition` from `@birchui/gantt`, `pivotStudioDefinition` from `@birchui/pivot-studio`, `chartDefinition` from `@birchui/charts`, `diagramDefinition` from `@birchui/diagram`, `spreadsheetDefinition` from `@birchui/spreadsheet`, `formDefinition` from `@birchui/forms` or `formBuilderDefinition` from `@birchui/forms/builder` to `createSvelteAction`. The [Gantt](https://docs.birchui.com/gantt/overview.md), [Pivot Studio](https://docs.birchui.com/pivot-studio/overview.md), [Charts](https://docs.birchui.com/charts/overview.md), [Diagram](https://docs.birchui.com/diagram/overview.md), [Spreadsheet](https://docs.birchui.com/spreadsheet/overview.md) and [Forms](https://docs.birchui.com/forms/overview.md) overviews have complete examples. ## Next steps - [Columns](https://docs.birchui.com/grid/columns.md) and [filtering](https://docs.birchui.com/grid/filtering.md). - The [@birchui/svelte API reference](https://docs.birchui.com/api/svelte.md). --- Source: https://docs.birchui.com/frameworks/solid/ # Solid > Use Birch UI Grid in Solid and SolidStart with the generic BirchGrid component, reactive props and a ref to the grid API. `@birchui/solid` wraps every Birch UI widget as a Solid component. `BirchGrid` is generic over your row type, takes every grid option as a reactive prop and every grid event as an `on…` prop, and hands you the grid API through `ref`. It supports Solid 1.8 and later. ## Install ```bash npm install @birchui/core @birchui/solid ``` ## A complete example ```tsx title="OrdersGrid.tsx" import { createSignal } from 'solid-js'; import { BirchGrid } from '@birchui/solid'; import type { CellValueChangedEvent, ColumnDef, GridApi } from '@birchui/core'; export interface Order { id: string; customer: string; region: 'EMEA' | 'Americas' | 'APAC'; placedAt: string; total: number; } const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 120, pinned: 'left' }, { field: 'customer', header: 'Customer', flex: 1, filter: 'text', editable: true }, { field: 'region', header: 'Region', filter: 'set' }, { field: 'placedAt', header: 'Placed', type: 'date', filter: 'date' }, { field: 'total', header: 'Total', type: 'number', format: (value) => usd.format(Number(value)) }, ]; const getRowId = (order: Order) => order.id; export function OrdersGrid(props: { orders: Order[] }) { let grid: GridApi | undefined; const [search, setSearch] = createSignal(''); const [selectedCount, setSelectedCount] = createSignal(0); function saveChange({ row, colId, newValue }: CellValueChangedEvent) { console.info(`Order ${row.id}: ${colId} is now ${String(newValue)}`); } return (
setSearch(event.currentTarget.value)} /> {selectedCount()} selected
ref={(api) => (grid = api)} class="orders-grid" style={{ height: '480px' }} columns={columns} rows={props.orders} getRowId={getRowId} quickFilter={search()} rowSelection="multiple" checkboxSelection onSelectionChanged={({ selected }) => setSelectedCount(selected.length)} onCellValueChanged={saveChange} />
); } ``` `BirchGrid` renders one `div` and creates the grid inside it on mount. Size it with `class` or `style`. ## Props - Every [grid option](https://docs.birchui.com/api/core.md#gridoptions) is a prop with the same name and type. - Every [grid event](https://docs.birchui.com/grid/events.md) is a prop named `on` plus the capitalized event name, for example `onCellClick`, `onCellValueChanged`, `onSortChanged`, `onColumnStateChanged` and `onReady`. - `class`, `style` (an object or a string) and `id` are applied to the container. - `ref` receives the [`GridApi`](https://docs.birchui.com/api/core.md#gridapi) once the grid is created. ## Reactive updates Option props are tracked like any other Solid props. When a signal you pass changes, the component compares each option with the value it last sent, by identity, and calls `api.update()` with only the changed keys. The grid is never recreated. Event handlers are read when the event fires, so swapping a handler never touches the grid. - **Pass new arrays.** Updating a store or signal so that `rows` is the same array mutated in place is not detected. Produce a new array, or call `grid.applyTransaction(...)`. - **Avoid stores for large row sets.** A Solid store wraps each row in a proxy. For thousands of rows, keep data in a signal holding a plain array and update it immutably, or use transactions. - **Keep columns and callbacks stable.** Define them outside the component or once at the top of it. ```tsx const [orders, setOrders] = createSignal([]); async function loadOrders() { const response = await fetch('/api/orders?status=open'); setOrders(await response.json()); } function addOrder(order: Order) { setOrders((current) => [...current, order]); } ``` ## The grid API Pass a callback to `ref` to receive the API. In Solid, `ref={grid}` with a `let grid` variable compiles to the same callback: ```tsx export function LargestOrders(props: { orders: Order[] }) { let grid: GridApi | undefined; function showBiggestFirst() { grid?.setSort([{ colId: 'total', dir: 'desc' }]); grid?.scrollToRow(0, 'start'); } return ( <> ref={grid} style={{ height: '420px' }} columns={columns} rows={props.orders} /> ); } ``` The `onReady` prop also receives the API: `onReady={({ api }) => api.autosizeColumns()}`. ## Grid Pro ```tsx title="RevenueByRegion.tsx" import { BirchGrid } from '@birchui/solid'; import { AllProModules } from '@birchui/grid-pro'; import type { ColumnDef } from '@birchui/core'; interface Sale { region: string; country: string; revenue: number; } const columns: ColumnDef[] = [ { field: 'region', header: 'Region', rowGroup: true }, { field: 'country', header: 'Country' }, { field: 'revenue', header: 'Revenue', type: 'number', aggFunc: 'sum' }, ]; export function RevenueByRegion(props: { sales: Sale[] }) { return ( style={{ height: '520px' }} columns={columns} rows={props.sales} modules={AllProModules} groupDefaultExpanded={1} groupPanel statusBar /> ); } ``` Set the license key once in your entry file with `setLicenseKey` from `@birchui/license`. See [Licensing and activation](https://docs.birchui.com/getting-started/licensing.md). ## SolidStart and server rendering On the server, `BirchGrid` renders its empty container `div` with your `class`, `style` and `id`. The grid is created in `onMount`, which only runs in the browser, so no `clientOnly` wrapper is required. Give the container a height so the layout is stable when the grid appears. ## Wrapping your own widgets `createSolidComponent(definition)` turns any widget that follows the Birch UI widget contract into a Solid component with the same props, events and `ref` behaviour. `BirchGrid` and `BirchScheduler` are built with it. ## Scheduler `BirchScheduler` comes from `@birchui/solid/scheduler`. See [Using the Scheduler in your framework](https://docs.birchui.com/frameworks/scheduler.md). ## Event Calendar `@birchui/solid` has no calendar entry point. The Event Calendar follows the same widget contract, so the adapter's generic factory wraps it in one line. See the [Event Calendar overview](https://docs.birchui.com/calendar/overview.md) for its options and events. ```tsx title="ClinicCalendar.tsx" import { createSolidComponent } from '@birchui/solid'; import { calendarDefinition, type CalendarEvent } from '@birchui/calendar'; const EventCalendar = createSolidComponent(calendarDefinition); export function ClinicCalendar(props: { appointments: CalendarEvent[] }) { return ( console.info('Open appointment', event.id)} /> ); } ``` ### Other Birch UI products Gantt, Pivot Studio, Charts, the diagram editor, the spreadsheet, the form renderer and the Form Builder work the same way: pass `ganttDefinition` from `@birchui/gantt`, `pivotStudioDefinition` from `@birchui/pivot-studio`, `chartDefinition` from `@birchui/charts`, `diagramDefinition` from `@birchui/diagram`, `spreadsheetDefinition` from `@birchui/spreadsheet`, `formDefinition` from `@birchui/forms` or `formBuilderDefinition` from `@birchui/forms/builder` to `createSolidComponent`. The [Gantt](https://docs.birchui.com/gantt/overview.md), [Pivot Studio](https://docs.birchui.com/pivot-studio/overview.md), [Charts](https://docs.birchui.com/charts/overview.md), [Diagram](https://docs.birchui.com/diagram/overview.md), [Spreadsheet](https://docs.birchui.com/spreadsheet/overview.md) and [Forms](https://docs.birchui.com/forms/overview.md) overviews have complete examples. ## Next steps - [Updating data](https://docs.birchui.com/grid/updating-data.md) and [selection](https://docs.birchui.com/grid/selection.md). - The [@birchui/solid API reference](https://docs.birchui.com/api/solid.md). --- Source: https://docs.birchui.com/frameworks/web-component/ # Web Component > Use the custom element from @birchui/element with properties, attributes and DOM events, in plain HTML or any framework. `@birchui/element` registers Birch UI widgets as custom elements. `` works in plain HTML pages, server-rendered templates, CMS pages and any framework that can render custom elements. It does not use Shadow DOM, so your CSS reaches every cell. ## Install and register ```bash npm install @birchui/core @birchui/element ``` Call `defineBirchGrid()` once before the element is used: ```ts title="main.ts" import { defineBirchGrid } from '@birchui/element'; defineBirchGrid(); ``` `defineBirchGrid(tagName = 'birchui-grid')` registers the element and returns its constructor. Calling it again returns the existing registration. Pass another name to register the element under your own tag, for example `defineBirchGrid('orders-grid')`. On the server, where `customElements` does not exist, it does nothing and returns `undefined`, so the call is safe in shared code. ## A complete example ```html title="orders.html" 0 selected ``` Custom elements are inline by default. Give `birchui-grid` `display: block` and a height; the grid fills the element. ## When the grid is created The element creates its grid when it is connected to the document **and** its `columns` property is set. Set the other properties first, in any order, and set `columns` last if you want the grid to start with everything in place. Properties set before `defineBirchGrid()` runs are picked up when the element upgrades. To create the grid immediately, without columns, call `grid.create()`. It returns the grid API, or `null` if the element is not connected yet (the grid is then created on connection). ## Properties Every grid option is available as a property with the same name: `columns`, `rows`, `getRowId`, `rowHeight`, `headerHeight`, `floatingFilters`, `quickFilter`, `sort`, `multiSort`, `filterModel`, `rowSelection`, `checkboxSelection`, `pagination`, `theme`, `density`, `defaultColumn`, `modules`, `licenseKey`, `overscanRows`, `overscanColumns`, `rowClass`, `emptyMessage`, `injectStyles`, `locale`, `stripes` and every Grid Pro option (`groupBy`, `groupDefaultExpanded`, `groupPanel`, `groupColumn`, `groupTotals`, `treeData`, `getDataPath`, `getParentId`, `pivot`, `rangeSelection`, `fillHandle`, `clipboard`, `statusBar`, `masterDetail`). `ariaLabel` is not a property, because `HTMLElement` already defines one. Set it with `set` or `options`. Each assignment sends only that option to the grid. Values are compared by identity, so assign a new array or object to change `rows`, `columns` or nested options. Three more members cover everything else: | Member | Description | | --- | --- | | `api` | The [`GridApi`](https://docs.birchui.com/api/core.md#gridapi), or `null` before the grid exists and after it is destroyed | | `set(key, value)` | Sets one option. `undefined` removes it | | `options` | Reads all options as an object. **Assigning replaces the whole set**: keys you leave out are reset | | `create()` | Creates the grid now, even without `columns` | ```js grid.set('ariaLabel', 'Open orders'); grid.set('sort', [{ colId: 'total', dir: 'desc' }]); grid.options = { ...grid.options, density: 'compact', stripes: true }; grid.api?.applyTransaction({ add: [{ id: 'SO-10424', customer: 'Litware Inc', region: 'EMEA', total: 2210 }] }); ``` ## Attributes A few string and number options can be set as HTML attributes, which is convenient in server-rendered markup: | Attribute | Option | Type | | --- | --- | --- | | `theme` | `theme` | string: `light`, `dark` or `auto` | | `density` | `density` | string: `compact`, `normal` or `comfortable` | | `row-height` | `rowHeight` | number | | `header-height` | `headerHeight` | number | | `quick-filter` | `quickFilter` | string | | `license-key` | `licenseKey` | string | | `locale` | `locale` | string | Changing an attribute updates the grid. Removing it removes the option. Everything else, including `columns` and `rows`, is set as a property. ## Events Every grid event is dispatched as a DOM `CustomEvent` on the element, with a kebab-case name and the payload in `event.detail`. Events bubble and cross shadow roots, so you can listen on an ancestor. | Grid event | DOM event | | --- | --- | | `ready` | `ready` | | `cellClick`, `cellDoubleClick`, `cellKeyDown` | `cell-click`, `cell-double-click`, `cell-key-down` | | `cellValueChanged` | `cell-value-changed` | | `rowClick`, `selectionChanged` | `row-click`, `selection-changed` | | `sortChanged`, `filterChanged` | `sort-changed`, `filter-changed` | | `columnResized`, `columnMoved`, `columnPinned`, `columnVisible`, `columnStateChanged` | `column-resized`, `column-moved`, `column-pinned`, `column-visible`, `column-state-changed` | | `modelUpdated`, `focusChanged`, `viewportScroll`, `pageChanged` | `model-updated`, `focus-changed`, `viewport-scroll`, `page-changed` | | `rowExpanded`, `editStart`, `editStop` | `row-expanded`, `edit-start`, `edit-stop` | ```js document.body.addEventListener('column-state-changed', (event) => { if (event.target.id === 'orders') localStorage.setItem('orders-columns', JSON.stringify(event.detail.state)); }); ``` ## Moving and removing the element Moving the element to another place in the document keeps its grid, rows and state. When the element is removed and not re-inserted in the same task, the grid is destroyed and `api` becomes `null`. Inserting it again creates a fresh grid from the element's current options. ## TypeScript `@birchui/element` adds `birchui-grid` to `HTMLElementTagNameMap`, so `document.querySelector('birchui-grid')` is typed. Cast to `BirchGridElement` for your row type: ```ts import { defineBirchGrid, type BirchGridElement } from '@birchui/element'; import type { ColumnDef } from '@birchui/core'; interface WorkOrder { id: string; site: string; technician: string; dueAt: string; priority: 'low' | 'normal' | 'urgent'; } defineBirchGrid(); const grid = document.querySelector('#work-orders') as BirchGridElement; const columns: ColumnDef[] = [ { field: 'id', header: 'Work order', width: 130 }, { field: 'site', header: 'Site', flex: 1 }, { field: 'technician', header: 'Technician', filter: 'set' }, { field: 'dueAt', header: 'Due', type: 'date' }, { field: 'priority', header: 'Priority', filter: 'set' }, ]; grid.getRowId = (order) => order.id; grid.columns = columns; grid.addEventListener('row-click', (event) => { if (event.detail.row) console.info('Open work order', event.detail.row.id); }); ``` ## Grid Pro Set `modules` like any other property: ```ts import { defineBirchGrid } from '@birchui/element'; import { AllProModules } from '@birchui/grid-pro'; import { setLicenseKey } from '@birchui/license'; setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY); defineBirchGrid(); const grid = document.querySelector('birchui-grid')!; grid.modules = AllProModules; grid.groupBy = ['region']; grid.statusBar = true; grid.columns = [ { field: 'region', header: 'Region' }, { field: 'customer', header: 'Customer', flex: 1 }, { field: 'revenue', header: 'Revenue', type: 'number', aggFunc: 'sum' }, ]; ``` The `license-key` attribute works too, for pages where the key is rendered by the server. ## Without a bundler The packages are standard ES modules, so a page can load them with an import map. Copy the `dist` folders of `@birchui/core` and `@birchui/element` to your static files and map the package names: ```html ``` ## Inside other frameworks The framework adapters are usually the better fit, but the element works anywhere: - **Angular:** add `CUSTOM_ELEMENTS_SCHEMA` to the component's `schemas` and bind properties with `[columns]="columns"`. Listen with `(cell-value-changed)="onChange($event.detail)"`. - **Vue:** tell the compiler the tag is a custom element (`compilerOptions.isCustomElement = (tag) => tag.startsWith('birchui-')`), then bind properties with `.prop`, for example `:columns.prop="columns"`. - **Svelte:** Svelte sets known element properties directly, so `` works. ## Extending the element `getBirchGridElement()` returns the element class without registering it, so you can subclass it and register the subclass under your own tag: ```ts import { getBirchGridElement } from '@birchui/element'; import { orderColumns } from './orders'; class OrdersGridElement extends getBirchGridElement() { constructor() { super(); this.columns = orderColumns; this.getRowId = (order) => order.id; this.density = 'compact'; } } customElements.define('orders-grid', OrdersGridElement); ``` `` now brings its own columns, so a page only has to set `rows`. ## Custom elements for your own widgets `createElementRegistration(definition, config)` and `createElementClass(definition, config)` build custom elements for any widget that follows the Birch UI widget contract. `config` lists the option keys to expose as properties, the observed attributes with their types (`'string'`, `'number'` or `'boolean'`) and the options required before the widget is created. ## Event Calendar `@birchui/element` has no calendar entry point. Register the Event Calendar as a custom element with `createElementRegistration`, choosing the options to expose as properties and attributes. See the [Event Calendar overview](https://docs.birchui.com/calendar/overview.md) for its options and events. ```ts title="calendar-element.ts" import { createElementRegistration } from '@birchui/element'; import { calendarDefinition } from '@birchui/calendar'; const calendarElement = createElementRegistration(calendarDefinition, { optionKeys: ['events', 'view', 'date', 'timeZone'], attributes: { view: 'string', 'time-zone': 'string', 'license-key': 'string' }, }); calendarElement.define(); ``` `define()` registers ``. Without `requiredOptions`, the element creates its calendar as soon as it is connected and has any option. Events arrive as kebab-case `CustomEvent`s such as `event-click` and `event-drop`. ### Other Birch UI products Gantt, Pivot Studio, Charts, the diagram editor, the spreadsheet, the form renderer and the Form Builder work the same way: pass `ganttDefinition` from `@birchui/gantt`, `pivotStudioDefinition` from `@birchui/pivot-studio`, `chartDefinition` from `@birchui/charts`, `diagramDefinition` from `@birchui/diagram`, `spreadsheetDefinition` from `@birchui/spreadsheet`, `formDefinition` from `@birchui/forms` or `formBuilderDefinition` from `@birchui/forms/builder` to `createElementRegistration`. The [Gantt](https://docs.birchui.com/gantt/overview.md), [Pivot Studio](https://docs.birchui.com/pivot-studio/overview.md), [Charts](https://docs.birchui.com/charts/overview.md), [Diagram](https://docs.birchui.com/diagram/overview.md), [Spreadsheet](https://docs.birchui.com/spreadsheet/overview.md) and [Forms](https://docs.birchui.com/forms/overview.md) overviews have complete examples. ## Scheduler `defineBirchScheduler()` from `@birchui/element/scheduler` registers ``. See [Using the Scheduler in your framework](https://docs.birchui.com/frameworks/scheduler.md#web-component). ## Next steps - [Theming](https://docs.birchui.com/grid/theming.md) for the `--lq-*` CSS variables. - The [@birchui/element API reference](https://docs.birchui.com/api/element.md). --- Source: https://docs.birchui.com/frameworks/scheduler/ # Using the Scheduler in your framework > Render Birch UI Scheduler in React, Vue, Angular, Svelte, Solid or as a Web Component through each adapter's /scheduler entry point. Every framework adapter includes a scheduler component. It lives in a separate `/scheduler` entry point, so apps that only use the grid never load scheduler code, and `@birchui/scheduler` stays an optional peer dependency. > **Scheduler: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md** > > Birch UI Scheduler is a paid product. It works fully without a key and shows a watermark on non-local hosts until you set one. See [Licensing and activation](https://docs.birchui.com/getting-started/licensing.md). ## Install Install the scheduler next to your adapter: ```bash npm install @birchui/core @birchui/scheduler @birchui/react ``` Replace `@birchui/react` with `vue`, `angular`, `svelte`, `solid` or `element` as needed. | Framework | Import | | --- | --- | | React | `import { BirchScheduler } from '@birchui/react/scheduler'` | | Vue | `import { BirchScheduler } from '@birchui/vue/scheduler'` | | Angular | `import { BirchSchedulerComponent } from '@birchui/angular/scheduler'` | | Svelte | `import { BirchScheduler, birchScheduler } from '@birchui/svelte/scheduler'` | | Solid | `import { BirchScheduler } from '@birchui/solid/scheduler'` | | Web Component | `import { defineBirchScheduler } from '@birchui/element/scheduler'` | | JavaScript | `import { createScheduler } from '@birchui/scheduler'` | Each scheduler component follows the same conventions as the grid component of its adapter: options as props or inputs, events in the framework's style, and the scheduler API through a ref. Read your framework's grid guide first: [React](https://docs.birchui.com/frameworks/react.md), [Vue](https://docs.birchui.com/frameworks/vue.md), [Angular](https://docs.birchui.com/frameworks/angular.md), [Svelte](https://docs.birchui.com/frameworks/svelte.md), [Solid](https://docs.birchui.com/frameworks/solid.md) or [Web Component](https://docs.birchui.com/frameworks/web-component.md). ## Shared data for the examples All examples below render a field-service dispatch board: technicians as resources and jobs as events. ```ts title="dispatch-data.ts" import type { SchedulerEvent, SchedulerResource, WorkingTime } from '@birchui/scheduler'; export const technicians: SchedulerResource[] = [ { id: 'north', name: 'North depot' }, { id: 'tech-ana', name: 'Ana Ruiz', parentId: 'north', color: '#2563eb' }, { id: 'tech-omar', name: 'Omar Haddad', parentId: 'north', color: '#0d9488' }, { id: 'south', name: 'South depot' }, { id: 'tech-lena', name: 'Lena Fischer', parentId: 'south', color: '#9333ea' }, { id: 'tech-kofi', name: 'Kofi Mensah', parentId: 'south', color: '#c2410c' }, ]; export const jobs: SchedulerEvent[] = [ { id: 'WO-5521', resourceId: 'tech-ana', title: 'Boiler service, Harbor Cafe', start: '2026-11-30T08:00:00+01:00', end: '2026-11-30T10:30:00+01:00' }, { id: 'WO-5522', resourceId: 'tech-ana', title: 'Heat pump install, 14 Elm Road', start: '2026-11-30T12:00:00+01:00', end: '2026-11-30T17:00:00+01:00' }, { id: 'WO-5523', resourceId: 'tech-omar', title: 'Chiller inspection, Lakeside Clinic', start: '2026-11-30T09:00:00+01:00', end: '2026-11-30T11:00:00+01:00' }, { id: 'WO-5524', resourceId: 'tech-lena', title: 'Emergency leak repair, Grand Hotel', start: '2026-12-01T07:30:00+01:00', end: '2026-12-01T09:00:00+01:00', color: '#dc2626' }, { id: 'WO-5525', resourceId: 'tech-kofi', title: 'Annual maintenance, Riverside School', start: '2026-12-01T10:00:00+01:00', end: '2026-12-01T15:00:00+01:00' }, ]; export const workingTime: WorkingTime = { days: [1, 2, 3, 4, 5], startHour: 7, endHour: 18 }; ``` Every scheduler needs `resources`, `start` and `end`. `events`, `viewPreset`, `timeZone`, `snap` (in minutes, `'tick'` or `false`), `workingTime`, `readOnly` and the other options are optional. See [Resources and events](https://docs.birchui.com/scheduler/resources-and-events.md) and [View presets and zoom](https://docs.birchui.com/scheduler/view-presets.md). ## React ```tsx title="DispatchBoard.tsx" 'use client'; import { useRef } from 'react'; import { BirchScheduler } from '@birchui/react/scheduler'; import type { SchedulerApi, SchedulerEvents } from '@birchui/scheduler'; import { jobs, technicians, workingTime } from './dispatch-data'; let nextJob = 6000; export function DispatchBoard() { const scheduler = useRef(null); async function saveMove({ event, start, end, resourceId, previous }: SchedulerEvents['eventDrop']) { const response = await fetch(`/api/jobs/${event.id}`, { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ start, end, resourceId }), }); if (!response.ok) scheduler.current?.updateEvent(event.id, previous); } function createJob({ start, end, resourceId }: SchedulerEvents['eventCreate']) { scheduler.current?.addEvent({ id: `WO-${nextJob++}`, resourceId, start, end, title: 'New job' }); } return ( <>
console.info('Open job', event.id)} /> ); } ``` As with `BirchGrid`, option props are compared by identity and only changed ones are sent to the scheduler, so keep `resources`, `events` and `workingTime` stable between renders. Event props are `on` plus the capitalized event name: `onEventClick`, `onEventDrop`, `onEventResize`, `onEventCreate`, `onEventRemove`, `onScheduleClick`, `onRangeChanged` and so on. ## Vue ```vue title="DispatchBoard.vue" ``` Events use kebab-case names: `@event-click`, `@event-drop`, `@event-resize`, `@event-create`, `@event-remove`, `@schedule-click`, `@range-changed`. The template ref exposes `api`. ## Angular ```ts title="dispatch-board.component.ts" import { ChangeDetectionStrategy, Component, viewChild } from '@angular/core'; import { BirchSchedulerComponent } from '@birchui/angular/scheduler'; import type { SchedulerEvents, SchedulerOptions } from '@birchui/scheduler'; import { jobs, technicians, workingTime } from './dispatch-data'; @Component({ selector: 'app-dispatch-board', standalone: true, imports: [BirchSchedulerComponent], changeDetection: ChangeDetectionStrategy.OnPush, template: ` `, styles: `.board { height: 560px; }`, }) export class DispatchBoardComponent { readonly scheduler = viewChild.required(BirchSchedulerComponent); readonly technicians = technicians; readonly jobs = jobs; readonly options: Partial = { timeZone: 'Europe/Berlin', snap: 15, workingTime }; saveMove({ event, start, end, resourceId }: SchedulerEvents['eventDrop']): void { console.info(`${event.id} moved to ${resourceId}`, start, end); } openJob(id: string): void { console.info('Open job', id); } } ``` `BirchSchedulerComponent` (selector `birchui-scheduler`) has the inputs `options`, `resources`, `events`, `start`, `end`, `viewPreset`, `theme` and `licenseKey`, and one output per scheduler event. Shortcut inputs override the same key in `options`. The `api` property returns the scheduler API after the first browser render. ## Svelte ```svelte title="DispatchBoard.svelte" console.info(`${event.id} moved to ${resourceId}`)} /> ``` The `birchScheduler` action takes the same options plus `on` and `onReady`, exactly like the [`birchGrid` action](https://docs.birchui.com/frameworks/svelte.md#the-birchuigrid-action): ```svelte
console.info('New job for', resourceId, start) }, }} >
``` ## Solid ```tsx title="DispatchBoard.tsx" import { BirchScheduler } from '@birchui/solid/scheduler'; import type { SchedulerApi } from '@birchui/scheduler'; import { jobs, technicians, workingTime } from './dispatch-data'; export function DispatchBoard() { let scheduler: SchedulerApi | undefined; return ( <> (scheduler = api)} style={{ height: '560px' }} resources={technicians} events={jobs} start="2026-11-30T00:00:00+01:00" end="2026-12-05T00:00:00+01:00" viewPreset="hourAndDay" timeZone="Europe/Berlin" snap={15} workingTime={workingTime} onEventResize={({ event, start, end }) => console.info(`${event.id} now ${start} to ${end}`)} /> ); } ``` ## Web Component `defineBirchScheduler()` registers ``. Unlike ``, the scheduler element has no per-option properties or attributes: configure it through `options` or `set(key, value)`. The scheduler is created as soon as the connected element has any option, so assign all required options in one step with `options`: ```html title="dispatch.html" ``` Later changes can use `board.set('readOnly', true)` or `board.options = { ...board.options, viewPreset: 'dayAndWeek' }`. Remember that assigning `options` replaces the whole set. Events are dispatched as `CustomEvent`s named `event-click`, `event-drop`, `event-resize`, `event-create`, `event-remove`, `schedule-click`, `range-changed` and so on, with the payload in `event.detail`. ## JavaScript ```ts title="dispatch.ts" import { createScheduler } from '@birchui/scheduler'; import { jobs, technicians, workingTime } from './dispatch-data'; const scheduler = createScheduler(document.querySelector('#dispatch')!, { resources: technicians, events: jobs, start: '2026-11-30T00:00:00+01:00', end: '2026-12-05T00:00:00+01:00', viewPreset: 'hourAndDay', timeZone: 'Europe/Berlin', snap: 15, workingTime, }); scheduler.on('eventDrop', ({ event, resourceId, start, end }) => { console.info(`${event.id} moved to ${resourceId}`, start, end); }); scheduler.update({ viewPreset: 'dayAndWeek' }); ``` ## Scheduler events These events are available in every adapter, under each framework's naming convention: | Event | Payload | | --- | --- | | `ready` | `{ api }` | | `eventClick`, `eventDoubleClick`, `eventContextMenu` | `{ event, resource, domEvent }` | | `eventDrop` | `{ event, start, end, resourceId, previous, source }` | | `eventResize` | `{ event, start, end, edge, previous, source }` | | `eventCreate` | `{ start, end, resourceId, resource }` | | `eventRemove` | `{ event, source }` | | `resourceClick` | `{ resource, domEvent }` | | `resourceToggle` | `{ resource, isExpanded }` | | `scheduleClick` | `{ date, resourceId, resource, domEvent }` | | `rangeChanged` | `{ start, end }` | | `viewPresetChanged` | `{ preset, previous }` | | `viewportScroll` | `{ left, top, visibleStart, visibleEnd }` | | `selectionChanged` | `{ selected, previous }` | `source` is `'pointer'` or `'keyboard'` (and `'api'` for `eventRemove`). To reject a move before it happens, use the `validateDrop` and `validateResize` options. See [Drag, drop, resize and create](https://docs.birchui.com/scheduler/interactions.md). ## Server rendering The scheduler components follow the same rules as the grid components: importing them is safe on the server, and the scheduler is created in the browser after mount. In Next.js, mark the file that renders `BirchScheduler` with `'use client'`. Give the container a fixed height. ## Next steps - [Scheduler overview](https://docs.birchui.com/scheduler/overview.md) - [Scheduler API and events](https://docs.birchui.com/scheduler/api.md) - [Time zones](https://docs.birchui.com/scheduler/time-zones.md) and [working time](https://docs.birchui.com/scheduler/working-time.md) --- Source: https://docs.birchui.com/frameworks/troubleshooting/ # Troubleshooting > Fix the common problems with the React, Vue, Svelte, Angular, Solid and Web Component adapters, from double mounts to reactive proxies and zone change detection. The adapters in `@birchui/react`, `@birchui/vue`, `@birchui/svelte`, `@birchui/angular`, `@birchui/solid` and `@birchui/element` share one model: the widget is created once when the component mounts, later prop changes are compared by identity and sent to `update()`, and the widget is destroyed when the component unmounts. Most problems on this page come from code that works against that model. | Symptom | Jump to | | --- | --- | | The widget is empty or zero pixels tall | [The widget has no height](#the-widget-has-no-height) | | `createGrid` runs twice in development | [The widget is created twice in development](#the-widget-is-created-twice-in-development) | | New rows or edited rows do not appear | [Changes to rows do not reach the widget](#changes-to-rows-do-not-reach-the-widget) | | Scrolling or typing gets slower after each render | [The widget updates on every render](#the-widget-updates-on-every-render) | | Large data sets are slow in Vue | [Vue makes large data slow](#vue-makes-large-data-slow) | | Large data sets are slow in Svelte 5 | [Svelte state makes large data slow](#svelte-state-makes-large-data-slow) | | An Angular template does not refresh after a grid event | [Angular views do not update after a widget event](#angular-views-do-not-update-after-a-widget-event) | | Angular runs change detection constantly | [Angular change detection runs too often](#angular-change-detection-runs-too-often) | | The ref or `api` is `null` | [The API is null](#the-api-is-null) | | `document is not defined` or a blank server-rendered page | [Server rendering errors](#server-rendering-errors) | | The watermark shows in production but not locally | [The license key is not applied with server rendering](#the-license-key-is-not-applied-with-server-rendering) | ## The widget has no height **Cause.** Each adapter renders one container element and creates the widget inside it. The grid fills its container (`height: 100%`, with a 120 pixel minimum), so a container without a height gives a short or empty grid. In Angular the host element is `display: block` but has no height of its own. **Fix.** Size the container through the adapter: **React** ```tsx ``` **Vue** ```vue ``` **Svelte** ```svelte ``` **Angular** ```css birchui-grid { height: 480px; } ``` In a flex layout, give the container `flex: 1` and `min-height: 0`. See [Sizing the grid](https://docs.birchui.com/grid/theming.md#sizing-the-grid). ## The widget is created twice in development **Cause.** React Strict Mode mounts, unmounts and mounts every component again in development. `BirchGrid` and components made with `createReactComponent` create the widget in a layout effect and call `destroy()` in its cleanup, so you see two creations and one destruction. The final instance is the one your ref points to. Production builds mount once. **Fix.** Nothing is needed for the adapter components. Problems appear only in code that creates a widget itself: - Do not call `createGrid`, `createScheduler` or any other `create…` function in the component body or in `useMemo`. Render runs more than once and the cleanup never runs there. - When you create a widget in your own effect, destroy it in the cleanup: ```tsx title="SalesChart.tsx" import { useEffect, useRef } from 'react'; import { createChart, type ChartDatum } from '@birchui/charts'; export function SalesChart({ data }: { data: ChartDatum[] }) { const host = useRef(null); useEffect(() => { const chart = createChart(host.current!, { data, series: [{ type: 'column', xKey: 'month', yKey: 'revenue' }], }); return () => chart.destroy(); }, []); return
; } ``` Better still, wrap the widget with `createReactComponent(chartDefinition)` as shown in [Wrapping your own widgets](https://docs.birchui.com/frameworks/react.md#wrapping-your-own-widgets), which handles Strict Mode and prop updates for you. ## Changes to rows do not reach the widget **Cause.** Adapters compare each option with the value they last sent using `Object.is`. `orders.push(order)` or `orders[3].status = 'Shipped'` keeps the same array, so nothing is sent. **Fix.** Pass a new array, or call the API for incremental changes: ```ts setOrders((current) => [...current, order]); gridRef.current?.applyTransaction({ update: [{ ...order, status: 'Shipped' }] }); ``` Set `getRowId` so updated objects match existing rows. See [Updating data](https://docs.birchui.com/grid/updating-data.md#incremental-changes-applytransaction). ## The widget updates on every render **Cause.** An inline array, object or function, such as `columns={[...]}` or `getRowId={(row) => row.id}`, is a new value on each render. The adapter sends it to `update()` every time, and a new `columns` array re-resolves every column. **Fix.** Define `columns`, `getRowId`, `modules`, `pagination` and similar values outside the component, or memoize them with `useMemo` and `useCallback` (React), `const` in ` order.id} /> ``` See [Updates and reactivity](https://docs.birchui.com/frameworks/svelte.md#updates-and-reactivity). ## Angular views do not update after a widget event **Cause.** `injectBirchWidget` creates the widget and its DOM listeners outside the Angular zone. Outputs such as `(cellClick)` re-enter the zone when they emit. A handler you register directly on the widget, for example `grid.instance?.on('selectionChanged', ...)`, runs outside the zone, so a zone-based app does not run change detection for it. **Fix.** Prefer the component outputs. When you subscribe directly, re-enter the zone: ```ts import { Component, NgZone, afterNextRender, inject, signal, viewChild } from '@angular/core'; import { BirchGridComponent } from '@birchui/angular'; @Component({ selector: 'app-orders', standalone: true, imports: [BirchGridComponent], template: `

{{ selected() }} selected

`, }) export class OrdersComponent { private readonly zone = inject(NgZone); private readonly grid = viewChild.required>(BirchGridComponent); readonly selected = signal(0); constructor() { afterNextRender(() => { this.grid().instance?.on('selectionChanged', ({ selected }) => this.zone.run(() => this.selected.set(selected.length)), ); }); } } ``` Zoneless apps that use `provideZonelessChangeDetection()` need no `zone.run()`. See [Change detection](https://docs.birchui.com/frameworks/angular.md#change-detection). ## Angular change detection runs too often **Cause.** Work you start yourself, such as a `setInterval` or a websocket that calls `applyTransaction`, runs inside the zone and triggers change detection on every tick. **Fix.** Start it with `zone.runOutsideAngular(() => ...)`. The widget does not need the zone to render, and only state your templates read needs `zone.run()`. ## The API is null **Cause.** The widget is created after the first render: in a layout effect (React), `onMounted` (Vue), an effect (Svelte, Solid) or `afterNextRender` (Angular). Before that, and after unmount, the ref, `api` or `instance` is `null` or `undefined`. **Fix.** Use optional chaining (`gridRef.current?.setQuickFilter('emea')`), call the API from event handlers, or listen for the `ready` event (`onReady` in React and Svelte, `@ready` in Vue, `(ready)` in Angular). ## Server rendering errors **Cause.** Every package is safe to import on the server, and the adapters create widgets only in the browser. Errors such as `document is not defined` come from calling a `create…` function yourself during server rendering, or, in the Next.js App Router, from rendering `BirchGrid` in a Server Component. **Fix.** Create widgets only in browser lifecycle hooks, and mark the Next.js file that renders an adapter component with `'use client'`. Pass serializable data from the server and define columns, which usually hold functions, in the client file. See [Next.js and server rendering](https://docs.birchui.com/frameworks/react.md#nextjs-and-server-rendering) and [SvelteKit](https://docs.birchui.com/frameworks/svelte.md#sveltekit). ## The license key is not applied with server rendering **Cause.** `setLicenseKey` stores the key in the copy of `@birchui/license` that runs it. A call that runs only on the server never reaches the browser bundle. A key read from a private environment variable is also `undefined` in the browser, because frameworks inline only public variables into client code. **Fix.** Call `setLicenseKey` in code that runs in the browser, and expose the key through a public variable: | Framework | Variable | Where to call `setLicenseKey` | | --- | --- | --- | | Next.js | `NEXT_PUBLIC_BIRCHUI_LICENSE_KEY` | A `'use client'` module in the root layout | | Vite, Vue, React, Solid | `VITE_BIRCHUI_LICENSE_KEY` | `main.ts` before mounting the app | | SvelteKit | `PUBLIC_BIRCHUI_LICENSE_KEY` from `$env/static/public` | `src/routes/+layout.svelte` | | Nuxt | `runtimeConfig.public` | A client plugin | | Angular | `environment.birchLicenseKey` | `main.ts` before `bootstrapApplication` | The variable must be defined when the production bundle is built. Widgets re-check the key when it changes, so order does not matter. The console warning names the reason a key was rejected; see [What happens without a valid key](https://docs.birchui.com/getting-started/licensing.md#what-happens-without-a-valid-key). ## Related - [React](https://docs.birchui.com/frameworks/react.md), [Vue](https://docs.birchui.com/frameworks/vue.md), [Svelte](https://docs.birchui.com/frameworks/svelte.md), [Angular](https://docs.birchui.com/frameworks/angular.md), [Solid](https://docs.birchui.com/frameworks/solid.md) and [Web Component](https://docs.birchui.com/frameworks/web-component.md) - [Licensing and activation](https://docs.birchui.com/getting-started/licensing.md) - [API reference: @birchui/react](https://docs.birchui.com/api/react.md), [@birchui/vue](https://docs.birchui.com/api/vue.md), [@birchui/svelte](https://docs.birchui.com/api/svelte.md) --- Source: https://docs.birchui.com/recipes/ # Recipes > Task-focused guides with complete code for every Birch UI product, from persisting grid state to importing MS Project files. Each recipe solves one concrete task end to end: the setup, complete code you can paste, how it works, and the pitfalls. Most include a live demo. There are 33 recipes. ## Data grid | Recipe | What you build | | --- | --- | | [Persist grid state to localStorage](https://docs.birchui.com/recipes/grid-persist-state.md) | Save sorting, filters, column layout, selection and expansion with getState() and restore them with setState() on the next visit. | | [Load rows from a REST API](https://docs.birchui.com/recipes/grid-server-side-rest.md) | Connect the server-side row model to a REST endpoint with fetch, translate each block request into a query string and cancel stale requests with AbortSignal. | | [Load rows from GraphQL](https://docs.birchui.com/recipes/grid-server-side-graphql.md) | Back the server-side row model with a GraphQL query, passing sort, filters and the requested block as variables and cancelling stale queries. | | [Excel export with custom styles](https://docs.birchui.com/recipes/grid-excel-custom-styles.md) | Export the grid view to .xlsx and restyle it to match your brand, with a title row, coloured headers, conditional fills and number formats. | | [Editable grid with validation and undo](https://docs.birchui.com/recipes/grid-editing-validation-undo.md) | Validate user input with valueParser and editable callbacks, show feedback, and let users undo and redo edits with undoRedo, api.undo() and api.redo(). | | [Nested grids in master/detail](https://docs.birchui.com/recipes/grid-master-detail-nested.md) | Show each customer's orders in a nested grid, and each order's lines in a third level, with MasterDetailModule and correct cleanup. | | [Show a million rows](https://docs.birchui.com/recipes/grid-million-rows.md) | Render, sort and scroll one million client-side rows with row and column virtualization, and the habits that keep a large grid fast. | | [Keyboard-only workflows](https://docs.birchui.com/recipes/grid-keyboard-workflows.md) | Set up a grid that power users and keyboard-only users can drive end to end, from navigation and editing to menus, filters, undo, ranges and the clipboard. | | [Translate the grid and support right-to-left](https://docs.birchui.com/recipes/grid-i18n-rtl.md) | Run the grid in German with a bundled locale pack, add your own Arabic strings with plural forms, and lay it out right to left. | | [Migrate an AG Grid app with the CLI](https://docs.birchui.com/recipes/grid-migrate-ag-grid-cli.md) | Move an existing AG Grid code base to Birch UI Grid with birchui-migrate, from a dry run and report to applying the changes and clearing manual steps. | | [Match your design system](https://docs.birchui.com/recipes/grid-design-system-theme.md) | Map your design tokens onto the grid's --lq-* custom properties to build a named theme with light and dark variants, density and accessible contrast. | | [Birch UI Grid in the Next.js App Router](https://docs.birchui.com/recipes/grid-nextjs-ssr.md) | Render the grid from a Client Component in the Next.js App Router, load data in a Server Component, lazy-load Grid Pro and pass the license key from an environment variable. | | [Grid Pro in an Angular standalone app](https://docs.birchui.com/recipes/grid-angular-standalone.md) | Use the birchui-grid component in a standalone, zoneless Angular app with signal inputs, a computed options object, outputs and Grid Pro modules. | | [Collapsible column groups](https://docs.birchui.com/recipes/grid-column-groups.md) | Group related columns under shared headers with ColumnGroupDef, make groups collapsible with columnGroupShow, and open or close them from code. | | [Custom cell context menu](https://docs.birchui.com/recipes/grid-context-menu.md) | Add row actions to the grid's right-click menu, keep or drop the built-in copy and export items, and disable the menu entirely with the contextMenu option. | | [Streaming live updates](https://docs.birchui.com/recipes/grid-live-updates.md) | Apply a stream of WebSocket messages to the grid with batched applyTransaction calls, flash changed cells and keep sorting and selection stable. | | [Import an Excel file into a grid](https://docs.birchui.com/recipes/grid-import-xlsx.md) | Read an uploaded .xlsx file with readXlsx, turn its rows into typed records with sheetToObjects, validate them and show them in a grid for review. | ## Pivot Studio | Recipe | What you build | | --- | --- | | [Save and load pivot layouts](https://docs.birchui.com/recipes/pivot-saved-layouts.md) | Let users save named Pivot Studio layouts as PivotReport JSON, keep them in localStorage or on your server, and open them again. | | [Load pivot data from an API or CSV](https://docs.birchui.com/recipes/pivot-from-api.md) | Fetch records from a JSON API or a CSV export, clean them with parseCsv or csvToRecords, and load them into Pivot Studio with loading and error states. | ## Scheduler | Recipe | What you build | | --- | --- | | [Validate scheduler drag and drop](https://docs.birchui.com/recipes/scheduler-drag-validation.md) | Combine validateDrop and validateResize to block double bookings, keep jobs inside working hours and only assign work to qualified technicians. | | [Schedule recurring maintenance jobs](https://docs.birchui.com/recipes/scheduler-recurring-jobs.md) | Model planned maintenance with SchedulerEvent.rrule and exdates, let users edit one occurrence or the whole series, and store detached occurrences. | | [Undo and redo in the scheduler](https://docs.birchui.com/recipes/scheduler-undo-redo.md) | Turn on scheduler history with the undoRedo option, add undo and redo buttons driven by historyChange, and keep a server in step when users undo. | | [Save scheduler changes to a server](https://docs.birchui.com/recipes/scheduler-save-to-server.md) | Persist every scheduler edit from historyChange, batch requests, roll back changes the server rejects, and apply updates from other users without echoing them back. | ## Gantt | Recipe | What you build | | --- | --- | | [Import and export MS Project files](https://docs.birchui.com/recipes/gantt-ms-project-import.md) | Let users open MS Project XML files in the Gantt with a preview step, keep your own task fields across a round trip, and export the schedule back to XML. | | [Build a critical path report](https://docs.birchui.com/recipes/gantt-critical-path-report.md) | Use the headless Gantt engine to compute the critical path, slack and constraint conflicts of a project, and render them as a report or an Excel file. | ## Spreadsheet | Recipe | What you build | | --- | --- | | [Add custom worksheet functions](https://docs.birchui.com/recipes/spreadsheet-custom-functions.md) | Define reusable workbook functions with LAMBDA and defined names, share them across sheets, and test them with the headless formula engine. | | [Load and save xlsx files](https://docs.birchui.com/recipes/spreadsheet-load-save-xlsx.md) | Open xlsx files from a file input, a URL or drag and drop, save them back to a server as xlsx or workbook JSON, and convert files on the server without the component. | ## Forms | Recipe | What you build | | --- | --- | | [Save Form Builder schemas and render them](https://docs.birchui.com/recipes/forms-builder-save-schemas.md) | Persist schemas from the Form Builder with versioning and server-side checks, then load the published version and render it with createForm. | | [Validate form submissions on the server](https://docs.birchui.com/recipes/forms-server-validation.md) | Re-check submitted answers on the server with JSON Schema and the expression engine, run async checks while users type, and show the server's errors next to the right fields. | ## Event Calendar | Recipe | What you build | | --- | --- | | [Publish and subscribe to iCalendar feeds](https://docs.birchui.com/recipes/calendar-ical-feed.md) | Serve a team's events as a subscribable .ics feed with toICS, show external feeds in the Event Calendar with parseICS, and import .ics files without duplicates. | ## Charts | Recipe | What you build | | --- | --- | | [Build a chart dashboard from a grid](https://docs.birchui.com/recipes/charts-dashboard-from-grid.md) | Drive several charts from the rows a Birch UI Grid shows, so filtering the grid updates the dashboard, and chart a selected range with chartFromRange. | ## Diagram | Recipe | What you build | | --- | --- | | [Save, load and auto-arrange diagrams](https://docs.birchui.com/recipes/diagram-save-load-layout.md) | Persist diagrams as DiagramDocument JSON, restore them with fromJSON, lay out graphs that arrive without coordinates, and keep layout results out of your change log. | ## Excel Engine | Recipe | What you build | | --- | --- | | [Build a multi-sheet Excel report](https://docs.birchui.com/recipes/excel-report-workbook.md) | Write a styled monthly report with a summary sheet, a detail sheet and per-depot outlines using writeXlsx, with cross-sheet formulas and cached values. | ## More help - [Examples gallery](https://docs.birchui.com/getting-started/examples.md) for complete starter apps. - Troubleshooting pages in each product section, starting with the [grid](https://docs.birchui.com/grid/troubleshooting.md). --- Source: https://docs.birchui.com/recipes/grid-persist-state/ # Persist grid state to localStorage > Save sorting, filters, column layout, selection and expansion with getState() and restore them with setState() on the next visit. Users expect a grid to look the way they left it. This recipe saves the whole view state, not only the column layout, to `localStorage` whenever it changes and restores it when the page loads. **Live demo: Persist grid state** (runs on the HTML version of this page). Source of `demos/recipe-grid-persist-state.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef, type GridState } from '@birchui/core'; import { button, docsTheme, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order, } from './_shared'; export const meta = { title: 'Persist grid state', height: 440 }; const STORAGE_KEY = 'birchui-docs:orders-grid-state'; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 170, filter: 'text' }, { field: 'region', header: 'Region', width: 140, filter: 'set' }, { field: 'status', header: 'Status', width: 120, filter: 'set' }, { field: 'orderDate', header: 'Ordered', type: 'date', width: 130 }, { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency }, ]; function loadState(): Partial | null { try { const saved = localStorage.getItem(STORAGE_KEY); return saved ? (JSON.parse(saved) as Partial) : null; } catch { return null; } } function saveState(state: GridState): void { try { const { scroll: _scroll, focusedCell: _focus, ...durable } = state; localStorage.setItem(STORAGE_KEY, JSON.stringify(durable)); } catch { // Storage can be full or disabled; the grid keeps working without it. } } function clearState(): void { try { localStorage.removeItem(STORAGE_KEY); } catch { // Ignored for the same reason as in saveState. } } export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const grid = createGrid(body, { columns, rows: makeOrders(300, 11), getRowId: (order) => order.id, floatingFilters: true, rowSelection: 'multiple', theme: docsTheme(), ariaLabel: 'Orders with saved layout', }); const saved = loadState(); if (saved) grid.setState(saved); status.textContent = saved ? 'Restored the saved layout.' : 'Sort, filter, resize or select, then reload the page.'; let timer: ReturnType | undefined; const offState = grid.on('stateChanged', ({ state }) => { clearTimeout(timer); timer = setTimeout(() => { saveState(state); status.textContent = `Saved: ${state.sort.length} sort keys, ${Object.keys(state.filterModel).length} filters, ${state.selectedRowIds.length} selected rows.`; }, 300); }); toolbar.append( 'Changes are saved to localStorage.', button('Reset layout', () => { clearTimeout(timer); clearState(); grid.setState({ sort: [], filterModel: {}, quickFilter: '', selectedRowIds: [] }); status.textContent = 'Saved layout cleared.'; }), ); const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { clearTimeout(timer); offState(); stopTheme(); grid.destroy(); }; } ``` ## 1. Read and write the state `getState()` returns a plain, JSON-serializable `GridState` object. `setState()` accepts all of it or any subset. ```ts title="grid-state-storage.ts" import type { GridState } from '@birchui/core'; const STORAGE_KEY = 'orders-grid-state:v1'; export function loadGridState(): Partial | null { try { const saved = localStorage.getItem(STORAGE_KEY); return saved ? (JSON.parse(saved) as Partial) : null; } catch { return null; } } export function saveGridState(state: GridState): void { const { scroll, focusedCell, ...durable } = state; try { localStorage.setItem(STORAGE_KEY, JSON.stringify(durable)); } catch { // Quota exceeded or storage disabled: keep the in-memory layout only. } } ``` The `scroll` and `focusedCell` fields are dropped here because a restored scroll position on a fresh page load is usually surprising. Keep them if you restore state inside a single-page app when the user navigates back. ## 2. Restore on load and save on change ```ts title="orders-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; import { loadGridState, saveGridState } from './grid-state-storage'; import type { Order } from './orders'; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, filter: 'text' }, { field: 'region', header: 'Region', filter: 'set' }, { field: 'status', header: 'Status', filter: 'set' }, { field: 'total', header: 'Total', type: 'number' }, ]; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (order) => order.id, rowSelection: 'multiple', floatingFilters: true, }); const saved = loadGridState(); if (saved) grid.setState(saved); let timer: ReturnType | undefined; grid.on('stateChanged', ({ state }) => { clearTimeout(timer); timer = setTimeout(() => saveGridState(state), 300); }); ``` Call `setState()` after the rows are loaded. Selected and expanded row ids only apply to rows that exist, so restoring before an asynchronous fetch finishes loses them. ## How it works `GridState` contains: | Field | Contents | | --- | --- | | `columns` | Width, pinning, visibility and order of each column, the same as `getColumnState()` | | `sort`, `filterModel`, `quickFilter` | The sort and filter models | | `page` | The current page when pagination is on | | `expandedRowIds`, `selectedRowIds` | Ids from `getRowId` | | `focusedCell`, `scroll` | Focus and scroll position | | `modules` | State contributed by installed modules, keyed by module | `stateChanged` is batched: several changes in the same task, such as a sort followed by a filter in one handler, produce one event. Scrolling also emits it, which is why the save is debounced. **`GridState`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface GridState ``` | Property | Type | Description | | --- | --- | --- | | `columns` | `ColumnState[]` | | | `sort` | `SortItem[]` | | | `filterModel` | `Record` | | | `quickFilter` | `string` | | | `page` | `number` | | | `expandedRowIds` | `string[]` | | | `selectedRowIds` | `string[]` | | | `focusedCell` | `CellPosition \| null` | | | `scroll` | `{ top: number; left: number }` | | | `modules` | `Record` | | ## Pitfalls - **Custom filters are not serializable.** A `{ type: 'custom', test }` filter holds a function, so it is left out of the saved filter model. Recreate it in code after `setState()`. - **Version the key.** When you rename or remove columns, saved state can refer to columns that no longer exist. Bump the suffix in `STORAGE_KEY` when the column set changes. `setState()` ignores invalid values and logs a warning naming them. - **Set `getRowId`.** Without it row ids are positions, and a saved selection points at different rows after the data changes. - **Storage can throw.** Private browsing modes and full quotas make `setItem` throw; always wrap storage calls. ## Related - [Saving and restoring column state](https://docs.birchui.com/grid/column-operations.md#saving-and-restoring-column-state) for the column layout alone. - [Filter models](https://docs.birchui.com/grid/filtering.md#filter-models) and [the sort model](https://docs.birchui.com/grid/sorting.md#the-sort-model). - [Row IDs](https://docs.birchui.com/grid/rows.md#row-ids). - [`GridApi` reference](https://docs.birchui.com/api/core.md). --- Source: https://docs.birchui.com/recipes/grid-server-side-rest/ # Load rows from a REST API > Connect the server-side row model to a REST endpoint with fetch, translate each block request into a query string and cancel stale requests with AbortSignal. With the server-side row model the grid asks your server for one block of rows at a time as the user scrolls. Sorting, filtering and grouping happen on the server, so the browser only holds the blocks it has loaded. This recipe wires it to a REST endpoint such as `GET /api/orders?offset=0&limit=100&sort=-total`. > **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md** > > The server-side row model requires `ServerSideRowModelModule` from `@birchui/grid-pro`. It is not part of `AllProModules`; add it yourself. **Live demo: Server-side row model** (runs on the HTML version of this page). Source of `demos/recipe-grid-server-side.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { ServerSideRowModelModule, createInMemoryDatasource, type ServerSideApi } from '@birchui/grid-pro'; import { button, docsTheme, formatCurrency, layout, makeOrders, onDocsThemeChange, type Order } from './_shared'; export const meta = { title: 'Server-side row model', height: 460 }; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 170, filter: 'text' }, { field: 'region', header: 'Region', width: 140, filter: 'text' }, { field: 'status', header: 'Status', width: 120, filter: 'text' }, { field: 'quantity', header: 'Qty', type: 'number', width: 90, filter: 'number' }, { field: 'unitPrice', header: 'Unit price', type: 'number', width: 110, format: formatCurrency }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const datasource = createInMemoryDatasource(makeOrders(20_000, 17), { latencyMs: 350, reportRowCount: true }); let requests = 0; const grid = createGrid(body, { columns, getRowId: (order) => order.id, modules: [ServerSideRowModelModule], rowModel: 'server', serverSide: { blockSize: 100, maxBlocksInCache: 20, debounceMs: 100, datasource: { getRows(request) { requests++; status.textContent = `Request ${requests}: rows ${request.startRow}-${request.endRow}, ${request.sort.length} sort keys, ${Object.keys(request.filterModel).length} filters.`; return datasource.getRows(request); }, }, }, floatingFilters: true, theme: docsTheme(), ariaLabel: 'Orders loaded from a server', }); const server = grid as typeof grid & ServerSideApi; toolbar.append( 'Each block of 100 rows is fetched with 350 ms of simulated latency.', button('Refresh', () => server.refreshServerSide({ purge: true })), ); const offError = server.onServerSideError((event) => { status.textContent = `Rows ${event.startRow}-${event.endRow} failed to load.`; }); const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { offError(); stopTheme(); grid.destroy(); }; } ``` The demo answers requests with `createInMemoryDatasource()` and simulated latency, so it runs without a backend. ## 1. Turn a request into a query string Each call to `getRows` receives a `ServerSideRequest`: **`ServerSideRequest`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface ServerSideRequest ``` | Property | Type | Description | | --- | --- | --- | | `startRow` | `number` | | | `endRow` | `number` | | | `sort` | `SortItem[]` | | | `filterModel` | `Record` | | | `quickFilter` | `string` | | | `groupKeys` | `string[]` | | | `rowGroupCols` | `string[]` | | | `valueCols` | `ServerSideValueColumn[]` | | | `signal` | `AbortSignal` | | Map it to the parameters your API understands: ```ts title="orders-query.ts" import type { FilterModel, ServerSideRequest } from '@birchui/core'; function filterParam(colId: string, model: FilterModel): [string, string][] { switch (model.type) { case 'text': return model.value ? [[`${colId}[${model.op}]`, model.value]] : []; case 'number': return model.value === undefined ? [] : [[`${colId}[${model.op}]`, String(model.value)]]; case 'set': return [[`${colId}[in]`, model.values.map(String).join(',')]]; case 'boolean': return [[colId, String(model.value)]]; default: return []; } } export function toQueryString(request: ServerSideRequest): string { const params = new URLSearchParams({ offset: String(request.startRow), limit: String(request.endRow - request.startRow), }); if (request.sort.length > 0) { params.set('sort', request.sort.map(({ colId, dir }) => (dir === 'desc' ? `-${colId}` : colId)).join(',')); } if (request.quickFilter) params.set('q', request.quickFilter); for (const [colId, model] of Object.entries(request.filterModel)) { for (const [key, value] of filterParam(colId, model)) params.append(key, value); } return params.toString(); } ``` Extend `filterParam` for the filter types your columns use: date filters, `between` ranges with `valueTo`, and `combined` filters with nested `conditions`. ## 2. Write the datasource ```ts title="orders-datasource.ts" import type { ServerSideDatasource } from '@birchui/core'; import { toQueryString } from './orders-query'; import type { Order } from './orders'; interface OrdersPage { items: Order[]; total: number; } export const ordersDatasource: ServerSideDatasource = { async getRows(request) { const response = await fetch(`/api/orders?${toQueryString(request)}`, { headers: { Accept: 'application/json' }, signal: request.signal, }); if (!response.ok) throw new Error(`GET /api/orders failed with status ${response.status}`); const page = (await response.json()) as OrdersPage; return { rows: page.items, rowCount: page.total }; }, }; ``` Return `rowCount` when the server knows the total; the scrollbar is then exact from the first block. If it does not, return only `rows`: a block shorter than the block size tells the grid it has reached the end. `lastRow` is accepted as an alias of `rowCount`. ## 3. Create the grid ```ts title="orders-grid.ts" import { createGrid } from '@birchui/core'; import { ServerSideRowModelModule, type ServerSideApi } from '@birchui/grid-pro'; import { ordersDatasource } from './orders-datasource'; import type { Order } from './orders'; const grid = createGrid(document.querySelector('#orders')!, { modules: [ServerSideRowModelModule], rowModel: 'server', serverSide: { datasource: ordersDatasource, blockSize: 100, maxBlocksInCache: 50, debounceMs: 80, }, getRowId: (order) => order.id, floatingFilters: true, columns: [ { field: 'id', header: 'Order', width: 120 }, { field: 'customer', header: 'Customer', flex: 1, filter: 'text' }, { field: 'status', header: 'Status', filter: 'set', options: ['Pending', 'Shipped', 'Delivered'] }, { field: 'total', header: 'Total', type: 'number', filter: 'number' }, ], }); const server = grid as typeof grid & ServerSideApi; server.onServerSideError(({ error, startRow, endRow, retry }) => { console.warn(`Orders ${startRow}-${endRow} failed to load`, error); setTimeout(retry, 2000); }); document.querySelector('#refresh')!.addEventListener('click', () => server.refreshServerSide({ purge: true })); ``` **`ServerSideApi`** (interface from `@birchui/grid-pro`, full reference: https://docs.birchui.com/api/grid-pro.md) ```ts interface ServerSideApi ``` | Property | Type | Description | | --- | --- | --- | | `refreshServerSide` | `(options?: ServerSideRefreshOptions) => void` | | | `getServerSideCacheState` | `() => ServerSideCacheState` | | | `onServerSideError` | `(listener: (event: ServerSideErrorEvent) => void) => () => void` | | | `isAllSelected` | `() => boolean` | | ## How it works - The grid requests the blocks that cover the visible rows. `blockSize` defaults to 100 rows. With `maxBlocksInCache` set, blocks beyond that limit are dropped and fetched again when the user scrolls back. - A change to the sort, filter model or quick filter discards the cached blocks and aborts their requests through `signal`. `debounceMs` waits for typing in a floating filter to settle before requesting. - When `getRows` rejects, the block shows a load error. Listeners registered with `onServerSideError` receive the error and a `retry()` function; without a listener the error is logged with `console.error`. - `refreshServerSide()` reloads the loaded blocks; `{ purge: true }` also clears them first. ## Pitfalls - **Pass `signal` to `fetch`.** Without it, a slow response for an old sort can still arrive and waste bandwidth. The grid ignores stale responses either way, but the server keeps working on them. - **Sort and filter on the server.** The grid sends the models and shows rows in the order you return them. A server that ignores `sort` makes the header arrows lie. - **Ids must be unique across blocks.** Set `getRowId` to a database key so selection survives reloads. - **Pivot mode is not available** with the server-side row model and is ignored with a warning. ## Related - [Load rows from GraphQL](https://docs.birchui.com/recipes/grid-server-side-graphql.md) uses the same datasource contract. - [Filter models](https://docs.birchui.com/grid/filtering.md#filter-models) lists every shape `filterModel` can hold. - [Server-side sorting](https://docs.birchui.com/grid/sorting.md#server-side-sorting) and [server-side paging](https://docs.birchui.com/grid/pagination.md#server-side-paging). - [Grid Pro overview](https://docs.birchui.com/grid-pro/overview.md) for module registration and license keys. --- Source: https://docs.birchui.com/recipes/grid-server-side-graphql/ # Load rows from GraphQL > Back the server-side row model with a GraphQL query, passing sort, filters and the requested block as variables and cancelling stale queries. The server-side row model only needs an object with a `getRows(request)` method that returns a promise, so a GraphQL API fits as well as REST. This recipe sends each block request as one query with variables. > **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md** > > Requires `ServerSideRowModelModule` from `@birchui/grid-pro`. ## 1. The schema The recipe assumes a query like this on the server: ```graphql title="schema.graphql" enum SortDirection { ASC DESC } input OrderSort { field: String!, direction: SortDirection! } input OrderFilter { field: String!, op: String!, value: String, values: [String!] } type OrderPage { nodes: [Order!]!, totalCount: Int! } type Query { orders(offset: Int!, limit: Int!, sort: [OrderSort!], filters: [OrderFilter!], search: String): OrderPage! } ``` ## 2. Build the variables ```ts title="orders-graphql.ts" import type { FilterModel, ServerSideDatasource, ServerSideRequest } from '@birchui/core'; import type { Order } from './orders'; const ORDERS_QUERY = ` query Orders($offset: Int!, $limit: Int!, $sort: [OrderSort!], $filters: [OrderFilter!], $search: String) { orders(offset: $offset, limit: $limit, sort: $sort, filters: $filters, search: $search) { totalCount nodes { id customer region status total placedAt } } } `; interface OrderFilter { field: string; op: string; value?: string; values?: string[]; } function toFilter(field: string, model: FilterModel): OrderFilter | null { switch (model.type) { case 'text': case 'number': return model.value === undefined ? { field, op: model.op } : { field, op: model.op, value: String(model.value) }; case 'date': return { field, op: model.op, value: model.value === undefined ? undefined : String(model.value) }; case 'set': return { field, op: 'in', values: model.values.map(String) }; case 'boolean': return { field, op: 'eq', value: String(model.value) }; default: return null; } } function toVariables(request: ServerSideRequest) { return { offset: request.startRow, limit: request.endRow - request.startRow, sort: request.sort.map(({ colId, dir }) => ({ field: colId, direction: dir === 'desc' ? 'DESC' : 'ASC' })), filters: Object.entries(request.filterModel) .map(([field, model]) => toFilter(field, model)) .filter((filter): filter is OrderFilter => filter !== null), search: request.quickFilter || null, }; } interface OrdersResponse { data?: { orders: { nodes: Order[]; totalCount: number } }; errors?: { message: string }[]; } export const ordersDatasource: ServerSideDatasource = { async getRows(request) { const response = await fetch('/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: ORDERS_QUERY, variables: toVariables(request) }), signal: request.signal, }); const body = (await response.json()) as OrdersResponse; if (!response.ok || body.errors?.length || !body.data) { throw new Error(body.errors?.map((error) => error.message).join('; ') ?? `GraphQL request failed: ${response.status}`); } return { rows: body.data.orders.nodes, rowCount: body.data.orders.totalCount }; }, }; ``` GraphQL servers often answer errors with status 200, so check `errors` as well as `response.ok`. Throwing makes the grid show the block as failed and notify `onServerSideError` listeners. ## 3. Create the grid ```ts title="orders-grid.ts" import { createGrid } from '@birchui/core'; import { ServerSideRowModelModule } from '@birchui/grid-pro'; import { ordersDatasource } from './orders-graphql'; createGrid(document.querySelector('#orders')!, { modules: [ServerSideRowModelModule], rowModel: 'server', serverSide: { datasource: ordersDatasource, blockSize: 200, debounceMs: 100 }, getRowId: (order) => order.id, floatingFilters: true, columns: [ { field: 'id', header: 'Order', width: 120 }, { field: 'customer', header: 'Customer', flex: 1, filter: 'text' }, { field: 'region', header: 'Region', filter: 'set', options: ['Europe', 'North America', 'Asia Pacific'] }, { field: 'status', header: 'Status', filter: 'set', options: ['Pending', 'Shipped', 'Delivered'] }, { field: 'placedAt', header: 'Placed', type: 'date', filter: 'date' }, { field: 'total', header: 'Total', type: 'number', filter: 'number' }, ], }); ``` ## Pitfalls - **Apollo, urql and other clients.** If you use a GraphQL client, pass the request's `signal` through its fetch options (for example `context: { fetchOptions: { signal } }` in Apollo) and turn off its normalized cache for this query; the grid already caches blocks. - **Column ids are field names.** The request uses column ids. If they differ from your schema's field names, map them in `toVariables`. - **Grouping.** With `groupBy`, requests carry `groupKeys` and `rowGroupCols`; your resolver must return group rows for the top levels. See the request type in the [REST recipe](https://docs.birchui.com/recipes/grid-server-side-rest.md#1-turn-a-request-into-a-query-string). ## Related - [Load rows from a REST API](https://docs.birchui.com/recipes/grid-server-side-rest.md) covers caching, errors and refreshes. - [Filter models](https://docs.birchui.com/grid/filtering.md#filter-models). - [`@birchui/grid-pro` API reference](https://docs.birchui.com/api/grid-pro.md). --- Source: https://docs.birchui.com/recipes/grid-excel-custom-styles/ # Excel export with custom styles > Export the grid view to .xlsx and restyle it to match your brand, with a title row, coloured headers, conditional fills and number formats. `exportExcel()` writes a clean, neutral workbook. For a report that goes to customers or finance you usually want your own header colours, a title above the table and highlighted rows. Build the workbook with `buildExcelWorkbook()`, restyle it, and write it with `downloadXlsx()` from `@birchui/excel`. > **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md** > > Requires `ExcelModule` from `@birchui/grid-pro`. A Grid Pro license also covers `@birchui/excel`. ## 1. Set number formats on the columns Number formats travel with the columns, so set them once with `meta.excelNumFmt`: ```ts title="columns.ts" import type { ColumnDef } from '@birchui/core'; import type { Order } from './orders'; export const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', width: 200 }, { field: 'status', header: 'Status', width: 110 }, { field: 'orderedOn', header: 'Ordered', type: 'date', meta: { excelNumFmt: 'd mmm yyyy' } }, { field: 'total', header: 'Total', type: 'number', meta: { excelNumFmt: '"$"#,##0.00' } }, { field: 'margin', header: 'Margin', type: 'number', meta: { excelNumFmt: '0.0%' } }, ]; ``` ## 2. Restyle the workbook `buildExcelWorkbook()` returns an `XlsxWorkbook` whose first sheet has one header row followed by one row per grid row, each as `{ cells: XlsxCell[] }`. Change styles in place and insert extra rows above the header: ```ts title="export-orders.ts" import { createGrid } from '@birchui/core'; import { ExcelModule } from '@birchui/grid-pro'; import { columnLetter, downloadXlsx, type XlsxCell, type XlsxCellStyle, type XlsxRow } from '@birchui/excel'; import { columns } from './columns'; const BRAND = { navy: '#1F3A5F', mist: '#EEF3F8', alert: '#FEF3F2', alertText: '#B42318' }; const headerStyle: XlsxCellStyle = { font: { name: 'Arial', bold: true, color: '#FFFFFF' }, fill: BRAND.navy, align: 'center', border: { bottom: { style: 'medium', color: BRAND.navy } }, }; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (order) => order.id, modules: [ExcelModule], }); function asRow(row: XlsxRow | XlsxCell[]): XlsxRow { return Array.isArray(row) ? { cells: row } : row; } function style(cell: XlsxRow['cells'][number], extra: XlsxCellStyle): XlsxCell { const base: XlsxCell = cell !== null && typeof cell === 'object' && 'value' in cell ? cell : { value: cell }; return { ...base, style: { ...base.style, ...extra } }; } export async function exportOrders(): Promise { const workbook = grid.buildExcelWorkbook?.({ sheetName: 'Orders' }); if (!workbook) return; const sheet = workbook.sheets[0]; const [header, ...body] = sheet.rows.map((row) => asRow(row as XlsxRow | XlsxCell[])); const statusIndex = grid.getDisplayColumns().findIndex((column) => column.id === 'status'); header.cells = header.cells.map((cell) => style(cell, headerStyle)); header.height = 22; body.forEach((row, index) => { const cells = row.cells.map((cell) => style(cell, { font: { name: 'Arial' } })); const returned = statusIndex >= 0 && style(cells[statusIndex], {}).value === 'Returned'; row.cells = cells.map((cell) => returned ? style(cell, { fill: BRAND.alert, color: BRAND.alertText }) : index % 2 === 1 ? style(cell, { fill: BRAND.mist }) : (cell as XlsxCell), ); }); const lastColumn = columnLetter(header.cells.length - 1); sheet.rows = [ { cells: [{ value: 'Northwind Traders: open orders', style: { font: { name: 'Arial', size: 16, bold: true, color: BRAND.navy } } }], height: 28 }, [`Exported ${new Date().toLocaleDateString('en-US', { dateStyle: 'long' })}`], [], header, ...body, ]; sheet.merges = [...(sheet.merges ?? []), `A1:${lastColumn}1`]; sheet.freeze = { ...sheet.freeze, rows: 4 }; sheet.autoFilter = false; sheet.tabColor = BRAND.navy; await downloadXlsx(workbook, 'open-orders.xlsx'); } ``` `columnLetter()` takes a zero-based column index and returns `A`, `B`, ... `AA`. ## How it works - Every cell has a `value` and an optional `style`. Styles merge on top of what the grid wrote, such as the number format and the bold group rows, because the code spreads `base.style` first. - `freeze.rows` moves with the inserted title rows: the header is now on row 4, so the first four rows stay visible. - The grid turns on `autoFilter` for flat grids. An autofilter covers the first row of the sheet, so turn it off when you insert rows above the header, or set it to a range string such as `'A4:F4'`. **`XlsxCellStyle`** (interface from `@birchui/excel`, full reference: https://docs.birchui.com/api/excel.md) ```ts interface XlsxCellStyle ``` | Property | Type | Description | | --- | --- | --- | | `font?` | `XlsxFont` | | | `bold?` | `boolean` | | | `italic?` | `boolean` | | | `color?` | `string` | | | `fill?` | `string` | | | `numFmt?` | `string` | | | `align?` | `'left' \| 'center' \| 'right'` | | | `valign?` | `'top' \| 'center' \| 'bottom'` | | | `wrap?` | `boolean` | | | `indent?` | `number` | | | `border?` | `XlsxBorderSide \| XlsxBorderSides` | | ## Pitfalls - **Colours are hex strings** such as `#1F3A5F`. Named CSS colours are not translated. - **Row indexes change** when you insert rows. Read the status column from the cells, as above, not from the grid's row index, because grouped exports add group rows. - **Keep values native.** Do not replace numbers with formatted strings to change their look; use `numFmt` so Excel can still sum the column. ## Related - [Excel export and import](https://docs.birchui.com/grid-pro/excel-export.md#customise-the-workbook). - [Styles and number formats](https://docs.birchui.com/excel/styles.md) in the Excel Engine. - [Writing files](https://docs.birchui.com/excel/writing.md) for the full workbook model. --- Source: https://docs.birchui.com/recipes/grid-editing-validation-undo/ # Editable grid with validation and undo > Validate user input with valueParser and editable callbacks, show feedback, and let users undo and redo edits with undoRedo, api.undo() and api.redo(). A data-entry grid needs three things: rules about which cells can change, checks on what users type, and a way back from mistakes. Birch UI Grid covers all three in the free package. **Live demo: Validation with undo and redo** (runs on the HTML version of this page). Source of `demos/recipe-grid-undo-validation.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { button, docsTheme, layout, makeOrders, onDocsThemeChange, type Order } from './_shared'; export const meta = { title: 'Validation with undo and redo', height: 440 }; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const report = (message: string) => { status.textContent = message; }; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 170, editable: true }, { field: 'quantity', header: 'Qty', type: 'number', width: 90, editable: true, editor: 'number', valueParser: (input, order) => { const quantity = Number(input); if (Number.isInteger(quantity) && quantity >= 1 && quantity <= 500) return quantity; report(`${order.id}: quantity must be a whole number from 1 to 500. Kept ${order.quantity}.`); return order.quantity; }, }, { field: 'discount', header: 'Discount', type: 'number', width: 110, editable: true, format: (value) => `${Math.round(Number(value) * 100)}%`, valueParser: (input, order) => { const percent = Number(String(input).replace('%', '')); if (Number.isFinite(percent) && percent >= 0 && percent <= 30) return percent / 100; report(`${order.id}: discount must be between 0% and 30%. Kept ${Math.round(order.discount * 100)}%.`); return order.discount; }, }, { field: 'status', header: 'Status', width: 130, editable: (ctx) => ctx.row?.status !== 'Returned', editor: 'select', options: ['Pending', 'Shipped', 'Delivered', 'Returned'], }, ]; const grid = createGrid(body, { columns, rows: makeOrders(120, 21), getRowId: (order) => order.id, undoRedo: { limit: 50 }, theme: docsTheme(), ariaLabel: 'Editable orders with undo', }); const undoButton = button('Undo', () => grid.undo()); const redoButton = button('Redo', () => grid.redo()); const sync = () => { undoButton.disabled = !grid.canUndo(); redoButton.disabled = !grid.canRedo(); }; sync(); toolbar.append(undoButton, redoButton, 'Ctrl+Z undoes, Ctrl+Y or Ctrl+Shift+Z redoes.'); report('Try a quantity of 0 or a discount of 45%.'); const offChange = grid.on('cellValueChanged', ({ row, colId, newValue, source }) => { sync(); report(`${row.id}: ${colId} set to ${String(newValue)} (${source}).`); }); const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { offChange(); stopTheme(); grid.destroy(); }; } ``` ## 1. Lock cells that must not change `editable` accepts a function of the cell context, so rules can depend on the row: ```ts { field: 'status', header: 'Status', editor: 'select', options: ['Pending', 'Shipped', 'Delivered', 'Returned'], editable: (ctx) => ctx.row?.status !== 'Returned', } ``` ## 2. Validate input in `valueParser` `valueParser(input, row)` receives the raw text from the editor and returns the value to store. To reject input, return the current value: the cell does not change and no `cellValueChanged` fires. ```ts title="order-columns.ts" import type { ColumnDef } from '@birchui/core'; import type { OrderLine } from './orders'; import { showFieldError } from './feedback'; export const columns: ColumnDef[] = [ { field: 'sku', header: 'SKU', width: 120 }, { field: 'product', header: 'Product', flex: 1, editable: true }, { field: 'quantity', header: 'Qty', type: 'number', editor: 'number', editable: true, valueParser: (input, line) => { const quantity = Number(input); if (Number.isInteger(quantity) && quantity >= 1 && quantity <= 500) return quantity; showFieldError(`${line.sku}: quantity must be a whole number from 1 to 500`); return line.quantity; }, }, { field: 'discount', header: 'Discount', type: 'number', editable: true, format: (value) => `${Math.round(Number(value) * 100)}%`, valueParser: (input, line) => { const percent = Number(input.replace('%', '')); if (Number.isFinite(percent) && percent >= 0 && percent <= 30) return percent / 100; showFieldError(`${line.sku}: discount must be between 0% and 30%`); return line.discount; }, }, ]; ``` For rules that involve several fields, or a value that arrives through `setValue()`, validate in `valueSetter` instead. A `valueSetter` that throws keeps the old value and fires no `cellValueChanged`, but the error is reported with `console.error`, so prefer `valueParser` for ordinary user mistakes. ## 3. Turn on undo and redo ```ts title="order-lines-grid.ts" import { createGrid } from '@birchui/core'; import { columns } from './order-columns'; const grid = createGrid(document.querySelector('#lines')!, { columns, rows: lines, getRowId: (line) => line.sku, undoRedo: { limit: 50 }, }); const undoButton = document.querySelector('#undo')!; const redoButton = document.querySelector('#redo')!; const syncButtons = () => { undoButton.disabled = !grid.canUndo(); redoButton.disabled = !grid.canRedo(); }; undoButton.addEventListener('click', () => grid.undo()); redoButton.addEventListener('click', () => grid.redo()); grid.on('cellValueChanged', syncButtons); syncButtons(); ``` `undoRedo: true` keeps the last 100 steps; pass `{ limit }` to change that. With focus in the grid, Ctrl+Z undoes, and Ctrl+Y or Ctrl+Shift+Z redoes (Cmd on macOS). **`UndoRedoOptions`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface UndoRedoOptions ``` | Property | Type | Description | | --- | --- | --- | | `limit?` | `number` | | ## 4. Save changes, including undos Undo and redo write values back through the normal path, so `cellValueChanged` fires with `source: 'undo'` or `'redo'`. A save handler that listens to the event therefore persists undos too: ```ts grid.on('cellValueChanged', async ({ row, colId, oldValue, newValue, source }) => { try { await fetch(`/api/order-lines/${row.sku}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ [colId]: newValue }), }); } catch { if (source !== 'undo') grid.setValue(row, colId, oldValue); } }); ``` ## How it works - Every value change is recorded: edits, `setValue()` calls, paste and fill handle changes. Changes made in the same task form one step, so undoing a paste of 200 cells restores all of them at once. - Undo stops an edit in progress, scrolls to the first restored cell and announces the result to screen readers. - A new change after an undo clears the redo stack. - `clearHistory()` empties both stacks, for example after a successful bulk save. Setting `undoRedo: false` with `update()` clears them as well. - The keyboard shortcuts are ignored while a cell editor or any other text input has focus, so the browser's own undo works inside the editor. ## Pitfalls - **Set `getRowId`.** History stores row ids; without stable ids an undo after a sort or a `setRows()` can target the wrong row. - **`setRows()` does not clear history.** If you load a different data set, call `clearHistory()`. - **Undo is per grid.** Two grids on one page keep separate stacks. ## Related - [Editing](https://docs.birchui.com/grid/editing.md), especially [Parsing input: valueParser](https://docs.birchui.com/grid/editing.md#parsing-input-valueparser) and [Validation and rollback](https://docs.birchui.com/grid/editing.md#validation-and-rollback). - [Keyboard-only workflows](https://docs.birchui.com/recipes/grid-keyboard-workflows.md). - [`cellValueChanged`](https://docs.birchui.com/grid/events.md#cellvaluechanged). --- Source: https://docs.birchui.com/recipes/grid-master-detail-nested/ # Nested grids in master/detail > Show each customer's orders in a nested grid, and each order's lines in a third level, with MasterDetailModule and correct cleanup. A customer list that expands into that customer's orders, where each order expands into its lines, is a common back-office screen. Master/detail renders any DOM into a full-width panel, so each level is simply another Birch UI grid with its own `masterDetail` option. > **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md** > > Requires `MasterDetailModule` from `@birchui/grid-pro` in every grid that has detail panels. ## 1. The data ```ts title="customers.ts" export interface OrderLine { sku: string; product: string; quantity: number; unitPrice: number; } export interface Order { id: string; orderedOn: string; status: 'Open' | 'Shipped' | 'Invoiced'; total: number; lines: OrderLine[]; } export interface Customer { id: string; name: string; country: string; accountManager: string; orders: Order[]; } ``` ## 2. Build each level as a function Writing each level as a function that mounts a grid into an element and returns its cleanup keeps the nesting readable: ```ts title="customer-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; import { MasterDetailModule } from '@birchui/grid-pro'; import type { Customer, Order, OrderLine } from './customers'; const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); const money = (value: unknown) => usd.format(Number(value)); const lineColumns: ColumnDef[] = [ { field: 'sku', header: 'SKU', width: 120 }, { field: 'product', header: 'Product', flex: 1 }, { field: 'quantity', header: 'Qty', type: 'number', width: 90 }, { field: 'unitPrice', header: 'Unit price', type: 'number', format: money }, ]; const orderColumns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 130 }, { field: 'orderedOn', header: 'Ordered', type: 'date' }, { field: 'status', header: 'Status' }, { field: 'total', header: 'Total', type: 'number', format: money }, ]; const customerColumns: ColumnDef[] = [ { field: 'name', header: 'Customer', flex: 1 }, { field: 'country', header: 'Country', filter: 'set' }, { field: 'accountManager', header: 'Account manager' }, { id: 'orderCount', header: 'Orders', type: 'number', valueGetter: (customer) => customer.orders.length }, ]; function mountLines(panel: HTMLElement, order: Order): () => void { const grid = createGrid(panel, { columns: lineColumns, rows: order.lines, getRowId: (line) => line.sku, density: 'compact', ariaLabel: `Lines of order ${order.id}`, }); return () => grid.destroy(); } function mountOrders(panel: HTMLElement, customer: Customer): () => void { const grid = createGrid(panel, { columns: orderColumns, rows: customer.orders, getRowId: (order) => order.id, density: 'compact', ariaLabel: `Orders of ${customer.name}`, modules: [MasterDetailModule], masterDetail: { isExpandable: (order) => order.lines.length > 0, height: (order) => Math.min(72 + order.lines.length * 32, 260), render: (order, linesPanel) => mountLines(linesPanel, order), }, }); return () => grid.destroy(); } export function mountCustomers(container: HTMLElement, customers: Customer[]) { return createGrid(container, { columns: customerColumns, rows: customers, getRowId: (customer) => customer.id, ariaLabel: 'Customers', modules: [MasterDetailModule], masterDetail: { isExpandable: (customer) => customer.orders.length > 0, height: 340, render: (customer, ordersPanel) => mountOrders(ordersPanel, customer), }, }); } ``` ## 3. Open a panel from code ```ts const customers = mountCustomers(document.querySelector('#customers')!, data); customers.setDetailExpanded?.('CUST-0042', true); ``` ## How it works - `render` is called with the row and an empty panel element whenever the panel is rendered. The function it returns runs when the panel leaves the DOM: on collapse, when it scrolls out of the rendered window, and when the outer grid is destroyed. Destroying the outer grid therefore tears down every nested grid. - Nested grids are independent. They have their own sorting, filtering, selection and keyboard focus. Keyboard input inside a panel stays in the panel. - `height` is fixed per panel. The panel does not grow with its content, so size it from the data, as above, and let the nested grid scroll. ## Pitfalls - **Panels are recreated.** Because rows are virtualized, a panel can be rendered several times. Keep state you need, such as a nested grid's sort, in your own map keyed by row id and apply it in `render`. `getState()` and `setState()` on the nested grid make that easy. - **Every level needs the module.** A nested grid without `MasterDetailModule` ignores its `masterDetail` option. - **License keys.** Set the key once with `setLicenseKey()` so nested grids are covered too, instead of passing `licenseKey` to the outer grid only. - **Excel export** writes the master rows only; detail panels are not exported. ## Related - [Master/detail](https://docs.birchui.com/grid-pro/master-detail.md) reference. - [Persist grid state](https://docs.birchui.com/recipes/grid-persist-state.md) for saving the nested grids' state. - [Activate your license key](https://docs.birchui.com/grid-pro/overview.md#activate-your-license-key). --- Source: https://docs.birchui.com/recipes/grid-million-rows/ # Show a million rows > Render, sort and scroll one million client-side rows with row and column virtualization, and the habits that keep a large grid fast. Birch UI Grid only creates DOM for the rows and columns in view, so a million rows scroll as smoothly as a hundred. What does cost time is the work you put around the grid: building the array, value getters and renderers. This recipe loads 1,000,000 trades and keeps that work small. **Live demo: One million rows** (runs on the HTML version of this page). Source of `demos/recipe-grid-million-rows.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { button, currency, docsTheme, layout, onDocsThemeChange } from './_shared'; export const meta = { title: 'One million rows', height: 460 }; const ROW_COUNT = 1_000_000; interface Trade { id: number; account: string; symbol: string; side: 'Buy' | 'Sell'; quantity: number; price: number; } const ACCOUNTS = ['Northwind Pension', 'Kestrel Capital', 'Harbourline Trust', 'Andes Holdings', 'Cedar & Stone']; const SYMBOLS = ['ACME', 'GLOBX', 'INIT', 'NWND', 'KSTR', 'HRBR', 'SKRA', 'LOTS']; function makeTrades(count: number): Trade[] { const trades: Trade[] = new Array(count); for (let i = 0; i < count; i++) { trades[i] = { id: i + 1, account: ACCOUNTS[i % ACCOUNTS.length], symbol: SYMBOLS[(i * 7) % SYMBOLS.length], side: i % 3 === 0 ? 'Sell' : 'Buy', quantity: 10 + ((i * 37) % 990), price: 20 + ((i * 7919) % 18000) / 100, }; } return trades; } const columns: ColumnDef[] = [ { field: 'id', header: 'Trade', type: 'number', width: 110 }, { field: 'account', header: 'Account', width: 200 }, { field: 'symbol', header: 'Symbol', width: 100 }, { field: 'side', header: 'Side', width: 90 }, { field: 'quantity', header: 'Quantity', type: 'number', width: 110 }, { field: 'price', header: 'Price', type: 'number', width: 110, format: (value) => currency.format(Number(value)) }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const started = performance.now(); const grid = createGrid(body, { columns, rows: makeTrades(ROW_COUNT), getRowId: (trade) => String(trade.id), theme: docsTheme(), ariaLabel: 'One million trades', }); status.textContent = `${ROW_COUNT.toLocaleString('en-US')} rows ready in ${Math.round(performance.now() - started)} ms.`; toolbar.append( button('Jump to row 500,000', () => grid.scrollToRow(499_999, 'center')), button('Last row', () => grid.scrollToRow(ROW_COUNT - 1, 'end')), button('Sort by quantity', () => { const t = performance.now(); grid.setSort([{ colId: 'quantity', dir: 'desc' }]); status.textContent = `Sorted in ${Math.round(performance.now() - t)} ms.`; }), ); const offScroll = grid.on('viewportScroll', () => { status.textContent = `Rows in the DOM: ${grid.getRenderedRows().length} of ${ROW_COUNT.toLocaleString('en-US')}.`; }); const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { offScroll(); stopTheme(); grid.destroy(); }; } ``` ## 1. Build compact rows ```ts title="trades.ts" export interface Trade { id: number; account: string; symbol: string; side: 'Buy' | 'Sell'; quantity: number; price: number; } export function decodeTrades(buffer: ArrayBuffer, accounts: string[], symbols: string[]): Trade[] { const view = new DataView(buffer); const count = view.byteLength / 16; const trades: Trade[] = new Array(count); for (let i = 0; i < count; i++) { const offset = i * 16; trades[i] = { id: view.getUint32(offset), account: accounts[view.getUint16(offset + 4)], symbol: symbols[view.getUint16(offset + 6)], side: view.getUint8(offset + 8) === 1 ? 'Sell' : 'Buy', quantity: view.getUint16(offset + 10), price: view.getFloat32(offset + 12), }; } return trades; } ``` Flat objects with primitive fields sort and filter fastest. Precompute derived values such as `notional = quantity * price` while decoding instead of in a `valueGetter`. For very large payloads, decode in a Web Worker and post the array back. ## 2. Create the grid ```ts title="trades-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; import type { Trade } from './trades'; const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); const columns: ColumnDef[] = [ { field: 'id', header: 'Trade', type: 'number', width: 110 }, { field: 'account', header: 'Account', width: 200, filter: 'set' }, { field: 'symbol', header: 'Symbol', width: 100, filter: 'set' }, { field: 'side', header: 'Side', width: 90 }, { field: 'quantity', header: 'Quantity', type: 'number', width: 110 }, { field: 'price', header: 'Price', type: 'number', width: 110, format: (value) => usd.format(Number(value)) }, ]; export function mountTrades(container: HTMLElement, trades: Trade[]) { return createGrid(container, { columns, rows: trades, getRowId: (trade) => String(trade.id), rowHeight: 32, ariaLabel: 'Trades', }); } ``` Give the container a fixed height, or a height from its layout such as `flex: 1` inside a sized parent. A grid in a container without height renders no rows. ## 3. Update in place Replace rows only when the whole data set changes. For corrections and new trades, use a transaction: ```ts grid.applyTransaction({ add: newTrades, update: correctedTrades, remove: cancelledIds }); ``` ## How it works - Row virtualization renders the visible rows plus `overscanRows` on each side. Column virtualization does the same horizontally with `overscanColumns`. - Browsers limit element height to a few million pixels. The grid scales its scroll range above that limit, so the last of a million 32 px rows stays reachable. - Numeric, date and boolean columns without a custom `comparator` use a faster sort path than text columns. ## Pitfalls - **Debounce the quick filter.** The first quick filter on a million rows builds a search string per row. Wait 150 ms after typing before calling `setQuickFilter()`. - **Keep `format` and `cell` cheap.** They run for every cell that scrolls into view. Create `Intl` formatters once, as above. - **Do not call `setRows()` per tick.** It re-indexes every row. See [Streaming live updates](https://docs.birchui.com/recipes/grid-live-updates.md). - **Consider the server.** If a million rows is only the first page of what exists, use the [server-side row model](https://docs.birchui.com/recipes/grid-server-side-rest.md) instead of shipping everything to the browser. ## Related - [Virtualization](https://docs.birchui.com/grid/virtualization.md), including [Guidance for a million rows](https://docs.birchui.com/grid/virtualization.md#guidance-for-a-million-rows) and [reference timings](https://docs.birchui.com/grid/virtualization.md#reference-timings). - [Updating data](https://docs.birchui.com/grid/updating-data.md). --- Source: https://docs.birchui.com/recipes/grid-keyboard-workflows/ # Keyboard-only workflows > Set up a grid that power users and keyboard-only users can drive end to end, from navigation and editing to menus, filters, undo, ranges and the clipboard. Data-entry teams often never touch the mouse. This recipe configures a grid where every common task has a key, and lists the keys to put in your onboarding notes. ## 1. Configure the grid ```ts title="invoice-lines-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; import { ClipboardModule, RangeSelectionModule } from '@birchui/grid-pro'; import type { InvoiceLine } from './invoices'; const columns: ColumnDef[] = [ { field: 'sku', header: 'SKU', width: 120, rowHeader: true }, { field: 'description', header: 'Description', flex: 1, editable: true, filter: 'text' }, { field: 'quantity', header: 'Qty', type: 'number', editable: true, filter: 'number' }, { field: 'unitPrice', header: 'Unit price', type: 'number', editable: true }, { field: 'taxCode', header: 'Tax', editable: true, editor: 'select', options: ['STD', 'RED', 'ZERO'], filter: 'set' }, ]; export const grid = createGrid(document.querySelector('#lines')!, { columns, rows: lines, getRowId: (line) => line.sku, ariaLabel: 'Invoice lines', undoRedo: true, modules: [RangeSelectionModule, ClipboardModule], rangeSelection: true, clipboard: true, }); document.addEventListener('keydown', (event) => { if (event.altKey && event.key === 'g') { event.preventDefault(); grid.focusCell(0, 'description'); } }); ``` Range selection and the clipboard are Grid Pro features; everything else on this page works in the free package. The Alt+G shortcut is an application-level way to jump into the grid from anywhere on the page. ## 2. The key map On macOS, use Cmd wherever Ctrl is listed. ### Moving and editing | Keys | Action | | --- | --- | | Arrow keys, Home, End, Page Up, Page Down | Move focus | | Ctrl+Home / Ctrl+End | First or last cell | | Enter or F2 | Edit the focused cell | | Any printable character | Start editing with that character | | Tab / Shift+Tab while editing | Commit and edit the next or previous editable cell | | Enter / Escape while editing | Commit or cancel | | Delete or Backspace | Clear an editable cell | | Ctrl+Z | Undo (with `undoRedo`) | | Ctrl+Y or Ctrl+Shift+Z | Redo | ### Menus and filters | Keys | Action | | --- | --- | | Shift+F10 or the context menu key on a cell | Open the cell [context menu](https://docs.birchui.com/recipes/grid-context-menu.md) | | Alt+Arrow Down or the context menu key on a header | Open the column menu | | Ctrl+Shift+F | Open the filter popup for the focused column | | Enter or Space on a header | Sort; add Shift for multi-column sort | | Arrow Up from the first row | Move to the header row | Inside a menu, arrow keys move between items, Enter runs one and Escape closes the menu and returns focus to the cell. ### Ranges and clipboard (Grid Pro) | Keys | Action | | --- | --- | | Shift+arrow keys | Extend the range | | Shift+Ctrl+arrow keys | Extend to the edge of the data | | Ctrl+A | Select every cell | | Ctrl+C / Ctrl+X / Ctrl+V | Copy, cut and paste as tab-separated text | | Escape | Clear the range | A paste of many cells is one undo step, so Ctrl+Z reverts the whole paste. ## 3. Add your own keys Listen to `cellKeyDown` for shortcuts that act on the focused row: ```ts grid.on('cellKeyDown', ({ event, row }) => { if (!(event instanceof KeyboardEvent) || !row) return; if ((event.ctrlKey || event.metaKey) && event.key === 'd') { event.preventDefault(); grid.applyTransaction({ add: [{ ...row, sku: nextSku() }] }); } }); ``` ## Pitfalls - **Name the grid.** Set `ariaLabel` so screen reader users know which grid they are in. - **Tab leaves the grid** when no cell is being edited. That is deliberate: the grid is one tab stop, and arrow keys move inside it. - **Browser shortcuts.** Ctrl+Shift+F is free in common browsers, but some screen readers and extensions use it. Mention the column menu, which has a **Filter…** item, as the alternative. - **Shortcuts are inactive while editing.** Inside an editor, Ctrl+Z and Shift+arrows belong to the text input. ## Related - [Accessibility](https://docs.birchui.com/grid/accessibility.md) and its full [keyboard map](https://docs.birchui.com/grid/accessibility.md#keyboard-map). - [Range selection keyboard](https://docs.birchui.com/grid-pro/range-selection.md#keyboard) and [Clipboard](https://docs.birchui.com/grid-pro/clipboard.md). - [Editable grid with validation and undo](https://docs.birchui.com/recipes/grid-editing-validation-undo.md). - [Key handlers](https://docs.birchui.com/grid/modules.md#key-handlers) for shortcuts inside a module. --- Source: https://docs.birchui.com/recipes/grid-i18n-rtl/ # Translate the grid and support right-to-left > Run the grid in German with a bundled locale pack, add your own Arabic strings with plural forms, and lay it out right to left. This recipe localizes an order screen for two markets: German, which ships as a locale pack, and Arabic, which you translate yourself and which needs a right-to-left layout. Strings, number and date formatting, and direction are three separate settings, so you can mix them freely. ## 1. German with a bundled pack `@birchui/core` exports a locale pack per language: `localeEn`, `localeDe`, `localeFr`, `localeEs`, `localePt`, `localeJa` and `localeZh`. A pack is a `LocalePack`, an object with a `locale` code and a `text` map of message keys. Pass it as `localeText`, and set `locale` for number and date formatting: ```ts title="orders-grid.de.ts" import { createGrid, localeDe } from '@birchui/core'; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (order) => order.id, localeText: localeDe, locale: 'de-DE', pagination: { pageSize: 50 }, }); ``` `locale` is passed to `Intl` for `number` and `date` columns and to locale-aware sorting, so `1234.5` shows as `1.234,5`. Each pack is also published as its own entry point, such as `@birchui/core/locales/de`, if you want to load only the language in use. ## 2. One language for every widget To set the language once for the whole app, including Grid Pro panels and other Birch UI products, use `setDefaultLocaleText()` before creating widgets: ```ts title="i18n.ts" import { setDefaultLocaleText, localeDe } from '@birchui/core'; setDefaultLocaleText(localeDe); ``` A grid's own `localeText` wins over the default, key by key. Keys missing from both fall back to the English text built into the component. ## 3. Arabic strings with plural forms There is no bundled Arabic pack, so write one. Messages are strings with `{name}` placeholders, or `PluralText` objects whose categories follow `Intl.PluralRules` for the pack's locale: ```ts title="locale-ar.ts" import type { LocalePack } from '@birchui/core'; export const localeAr: LocalePack = { locale: 'ar', text: { 'grid.noRows': 'لا توجد صفوف لعرضها', 'grid.pager.page': 'الصفحة {page} من {pageCount}', 'grid.pager.next': 'الصفحة التالية', 'grid.pager.previous': 'الصفحة السابقة', 'grid.filter.placeholder': 'تصفية…', 'grid.filter.valueCount': { zero: 'لا توجد قيم', one: 'قيمة واحدة', two: 'قيمتان', few: '{count} قيم', many: '{count} قيمة', other: '{count} قيمة', }, 'grid.announce.copiedRows': { one: 'تم نسخ صف', two: 'تم نسخ صفين', other: 'تم نسخ {count} صفوف' }, }, }; ``` The keys are the ones the grid passes to its translator, such as `grid.noRows`, `grid.pager.page` and `grid.filter.placeholder`. The English pack, `localeEn.text`, lists every key with its default text, which makes a good translation template. ## 4. Right to left ```ts title="orders-grid.ar.ts" import { createGrid } from '@birchui/core'; import { localeAr } from './locale-ar'; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (order) => order.id, localeText: localeAr, locale: 'ar-EG', }); grid.getDirection(); ``` Leave `rtl` unset and the grid reads the `dir` attribute of its container or the nearest ancestor, so `` is enough. Set `rtl: true` or `rtl: false` to override the page. `getDirection()` returns the resolved `'ltr'` or `'rtl'`. In right-to-left mode the layout is mirrored: columns run from right to left, and the left and right arrow keys follow the visual order. ## 5. Switch language at runtime ```ts import { localeDe, localeEn } from '@birchui/core'; import { localeAr } from './locale-ar'; const packs = { en: localeEn, de: localeDe, ar: localeAr }; export function setLanguage(language: keyof typeof packs): void { document.documentElement.lang = language; document.documentElement.dir = language === 'ar' ? 'rtl' : 'ltr'; grid.update({ localeText: packs[language], locale: language, rtl: language === 'ar' }); } ``` Changing `localeText`, `locale` or `rtl` with `update()` re-renders the grid without recreating it. Changing only the `dir` attribute on the page is not observed; pass `rtl` as well, as above. ## Your own strings Use the same machinery for strings in your toolbar so one pack covers everything: ```ts import { createTranslator, formatMessage, t } from '@birchui/core'; const translate = createTranslator({ 'orders.selected': { one: '{count} order selected', other: '{count} orders selected' } }, 'en'); translate('orders.selected', '{count} orders selected', { count: 3 }); t('grid.noRows', 'No rows to show'); formatMessage({ one: '{count} line', other: '{count} lines' }, 'en', { count: 1 }); ``` `createTranslator(overrides, locale)` returns a function that looks in the overrides, then in the default pack from `setDefaultLocaleText()`, then uses the fallback. `t()` reads the default pack only. `resolveDirection(element, rtl)` applies the same direction rules as the grid to any element. ## Pitfalls - **Column headers are yours.** `header` text is not translated by the grid; build column definitions from your own translations. - **`format` functions are yours.** `locale` only affects columns without a `format`. Create `Intl.NumberFormat` instances per language in your own formatters. - **Packs may be partial.** Missing keys show English. Check `localeEn.text` against your pack when upgrading. ## Related - [Localization](https://docs.birchui.com/grid/localization.md), the reference for locale packs and message keys. - [`@birchui/core` API reference](https://docs.birchui.com/api/core.md) for `LocalePack`, `PluralText` and the translation functions. - [Accessibility](https://docs.birchui.com/grid/accessibility.md#announcements), since announcements are translated too. - [Forms localization](https://docs.birchui.com/forms/i18n.md). --- Source: https://docs.birchui.com/recipes/grid-migrate-ag-grid-cli/ # Migrate an AG Grid app with the CLI > Move an existing AG Grid code base to Birch UI Grid with birchui-migrate, from a dry run and report to applying the changes and clearing manual steps. `birchui-migrate` rewrites AG Grid imports, components, column definitions, options, events and API calls across a code base and tells you what is left to do by hand. This recipe walks through a migration of a React app on a branch, in the order that keeps the diff reviewable. ## 1. Install ```sh git switch -c migrate-to-birchui npm install --save-dev @birchui/migrate typescript npm install @birchui/core @birchui/react ``` Add `@birchui/grid-pro` if the app uses AG Grid Enterprise modules. The CLI adds the right Birch UI modules to the code, but not to `package.json`. ## 2. Dry run with a report ```sh npx birchui-migrate "src/**/*.{ts,tsx,js,jsx}" --from ag-grid --report migration-report.md ``` Nothing is written. The output is a unified diff and a summary such as: ```text 14 files scanned, 6 would change. 83 converted, 7 manual steps, 12 warnings. Estimated effort: about 3 hours. Run again with --write to apply the changes. ``` `migration-report.md` lists, per file, what was converted, the manual steps as a checklist and the warnings. Share it with the team before you start; it doubles as the migration ticket. | Option | Use | | --- | --- | | `--from ag-grid` | Skip MUI X detection in a mixed code base | | `--framework react\|vue\|angular\|js` | Override the framework detected from imports | | `--quiet` | Print only the summary, useful in CI | | `--write` | Apply the changes | ## 3. Apply and format ```sh npx birchui-migrate "src/**/*.{ts,tsx,js,jsx}" --from ag-grid --write npx prettier --write src git add -A && git commit -m "refactor: migrate grids to Birch UI" ``` Commit the tool's output on its own, before any manual change, so reviewers can tell generated edits from hand-written ones. Running the tool again on converted files changes nothing. ## 4. Work through the manual steps Each manual step leaves a marker comment with a link to the relevant docs section: ```tsx { field: 'status', /* birchui-migrate: cellRenderer: StatusBadge is a framework component; rewrite it as cell: (ctx) => string | Node, or mount the component into a DOM node you return (https://birchui.com/getting-started/migrating-from-ag-grid/#cell-renderers) */ cell: StatusBadge, }, ``` Find them all and fix them one by one: ```sh grep -rn "birchui-migrate:" src ``` A typical fix for a cell renderer returns DOM instead of a component: ```ts { field: 'status', header: 'Status', cell: ({ value }) => { const badge = document.createElement('span'); badge.className = `status-badge status-${String(value).toLowerCase()}`; badge.textContent = String(value); return badge; }, } ``` Delete each marker once it is handled. When `grep` finds none, the code side of the migration is done. ## 5. Review the warnings Warnings mark code that was converted but behaves differently, for example a filter option with a different default. They do not leave markers, so go through the list in `migration-report.md` and tick them off. ## 6. Remove AG Grid ```sh npm uninstall ag-grid-community ag-grid-enterprise ag-grid-react npx tsc --noEmit ``` Type errors after the uninstall point at AG Grid types the tool could not reach, usually values built in another module. ## Pitfalls - **Run it on everything at once.** Column definitions imported from another file are only converted when that file is part of the run. - **Commit first.** `--write` edits files in place. - **Theme classes.** `ag-theme-*` wrappers become the `theme` option; custom AG Grid CSS needs to be redone with [CSS custom properties](https://docs.birchui.com/grid/theming.md#css-custom-properties). - **License keys.** `LicenseManager.setLicenseKey` calls are converted, but you need a Birch UI key. See [Licensing](https://docs.birchui.com/getting-started/licensing.md). ## Related - [Migration tool](https://docs.birchui.com/getting-started/migration-tool.md), including the playground and [known gaps](https://docs.birchui.com/getting-started/migration-tool.md#known-gaps). - [Migrating from AG Grid](https://docs.birchui.com/getting-started/migrating-from-ag-grid.md) for the concept mapping and the [migration checklist](https://docs.birchui.com/getting-started/migrating-from-ag-grid.md#migration-checklist). - [`@birchui/migrate` API reference](https://docs.birchui.com/api/migrate.md) for the converters. --- Source: https://docs.birchui.com/recipes/grid-design-system-theme/ # Match your design system > Map your design tokens onto the grid's --lq-* custom properties to build a named theme with light and dark variants, density and accessible contrast. Your app already has tokens for colour, type and spacing. Instead of overriding grid selectors one by one, map those tokens onto the grid's CSS custom properties in one named theme. The grid then follows your design system, including dark mode, without JavaScript. ## 1. Start from your tokens Assume a design system that exposes tokens as custom properties on `:root`: ```css title="tokens.css" :root { --ds-font-sans: 'Inter', system-ui, sans-serif; --ds-text-sm: 13px; --ds-space-3: 12px; --ds-radius-md: 6px; --ds-color-text: #101828; --ds-color-text-subtle: #475467; --ds-color-surface: #ffffff; --ds-color-surface-raised: #f9fafb; --ds-color-surface-sunken: #f2f4f7; --ds-color-border: #d0d5dd; --ds-color-border-subtle: #eaecf0; --ds-color-brand: #6941c6; --ds-color-on-brand: #ffffff; --ds-color-brand-tint: rgba(105, 65, 198, 0.12); --ds-color-danger: #b42318; } :root.dark { --ds-color-text: #f5f5f6; --ds-color-text-subtle: #94969c; --ds-color-surface: #0c111d; --ds-color-surface-raised: #161b26; --ds-color-surface-sunken: #1f242f; --ds-color-border: #333741; --ds-color-border-subtle: #1f242f; --ds-color-brand: #9e77ed; --ds-color-on-brand: #0c111d; --ds-color-brand-tint: rgba(158, 119, 237, 0.2); } ``` ## 2. Map them onto a grid theme The grid root defines every `--lq-*` property on itself, so set them on `.lq-grid.lq-theme-`, not on an ancestor. Because the values reference your tokens with `var()`, the theme switches to dark automatically when your tokens do: ```css title="grid-theme.css" .lq-grid.lq-theme-acme { --lq-font-family: var(--ds-font-sans); --lq-font-size: var(--ds-text-sm); --lq-cell-padding: var(--ds-space-3); --lq-radius: var(--ds-radius-md); --lq-fg: var(--ds-color-text); --lq-muted-fg: var(--ds-color-text-subtle); --lq-bg: var(--ds-color-surface); --lq-header-bg: var(--ds-color-surface-sunken); --lq-header-fg: var(--ds-color-text); --lq-row-alt: var(--ds-color-surface-raised); --lq-row-hover: var(--ds-color-surface-sunken); --lq-border: var(--ds-color-border); --lq-border-subtle: var(--ds-color-border-subtle); --lq-accent: var(--ds-color-brand); --lq-accent-fg: var(--ds-color-on-brand); --lq-focus-ring: var(--ds-color-brand); --lq-selection-bg: var(--ds-color-brand-tint); --lq-range-bg: var(--ds-color-brand-tint); --lq-menu-bg: var(--ds-color-surface); --lq-input-bg: var(--ds-color-surface); --lq-danger: var(--ds-color-danger); } :root.dark .lq-grid.lq-theme-acme { color-scheme: dark; } ``` ## 3. Use the theme ```ts title="orders-grid.ts" import { createGrid } from '@birchui/core'; import './grid-theme.css'; createGrid(document.querySelector('#orders')!, { columns, rows: orders, theme: 'acme', density: 'compact', stripes: true, }); ``` `theme: 'acme'` adds the class `lq-theme-acme` to the grid root. Properties you do not set keep the light defaults. ## 4. Style individual parts For details tokens cannot express, target the grid's classes with one class more than the built-in rule: ```css .lq-grid.lq-theme-acme .lq-header-cell { font-weight: 600; text-transform: uppercase; letter-spacing: 0.02em; } ``` The class names are listed in [Targeting elements with classes](https://docs.birchui.com/grid/theming.md#targeting-elements-with-classes). ## Pitfalls - **Setting properties on `body` does nothing.** The grid redefines them on its root. Always target `.lq-grid`. - **Check contrast on every surface.** Text must reach 4.5:1 on the cell, header, hovered, striped and selected backgrounds, and the accent and focus ring 3:1. A brand tint used as `--lq-selection-bg` is the most common failure. See [Contrast](https://docs.birchui.com/grid/theming.md#contrast). - **Fonts.** Load the web font before the grid measures columns for autosizing, or call `autosizeColumns()` after `document.fonts.ready`. - **Specificity.** The grid injects its stylesheet after your stylesheets, so equal-specificity rules lose. Use the two-class selectors above. ## Related - [Theming](https://docs.birchui.com/grid/theming.md), with the full [property table](https://docs.birchui.com/grid/theming.md#css-custom-properties) and [density](https://docs.birchui.com/grid/theming.md#density). - [How styles are loaded](https://docs.birchui.com/grid/theming.md#how-styles-are-loaded) for shipping CSS as a file. --- Source: https://docs.birchui.com/recipes/grid-nextjs-ssr/ # Birch UI Grid in the Next.js App Router > Render the grid from a Client Component in the Next.js App Router, load data in a Server Component, lazy-load Grid Pro and pass the license key from an environment variable. In the App Router, pages are Server Components by default and the grid needs the browser. The pattern is simple: fetch data on the server, pass plain data to a Client Component, and create the grid there. The `examples/nextjs-app-router-grid` project in the Birch UI repository follows this recipe. ## 1. Install ```sh npm install @birchui/core @birchui/react ``` ## 2. Load data in a Server Component ```tsx title="app/orders/page.tsx" import { OrdersGrid } from './orders-grid'; import { listOrders } from '@/lib/orders'; export default async function OrdersPage() { const orders = await listOrders({ status: 'open' }); return (

Open orders

); } ``` Only serializable data crosses into the Client Component, so pass rows, not column definitions. ## 3. Render the grid in a Client Component ```tsx title="app/orders/orders-grid.tsx" 'use client'; import { useRef, useState } from 'react'; import { BirchGrid } from '@birchui/react'; import type { ColumnDef, GridApi } from '@birchui/core'; import type { Order } from '@/lib/orders'; const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110, pinned: 'left' }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 180, filter: 'text' }, { field: 'region', header: 'Region', filter: 'set' }, { field: 'placedAt', header: 'Placed', type: 'date', filter: 'date' }, { field: 'total', header: 'Total', type: 'number', format: (value) => usd.format(Number(value)) }, ]; const getRowId = (order: Order) => order.id; export function OrdersGrid({ orders }: { orders: Order[] }) { const grid = useRef>(null); const [search, setSearch] = useState(''); return ( <> setSearch(event.target.value)} /> ref={grid} style={{ height: 'calc(100vh - 200px)' }} columns={columns} rows={orders} getRowId={getRowId} quickFilter={search} floatingFilters theme="auto" licenseKey={process.env.NEXT_PUBLIC_BIRCHUI_LICENSE_KEY} /> ); } ``` During server rendering `BirchGrid` outputs its empty container; the grid is created after hydration. Give it a height in CSS or `style`, so the space is reserved and the page does not shift. Keep `columns` and callbacks such as `getRowId` at module level or memoized. A new array on every render is treated as a column change. ## 4. The license key Next.js inlines variables prefixed with `NEXT_PUBLIC_` into the client bundle at build time: ```sh title=".env.local" NEXT_PUBLIC_BIRCHUI_LICENSE_KEY=LQ1.your-key-here ``` The core grid is MIT licensed and ignores the key; wiring it now means Grid Pro modules need no further setup. Birch UI keys are verified offline and are meant to ship in client code, but keep real keys out of the repository. To set the key once for every widget instead of per grid, call `setLicenseKey()` from `@birchui/license` at module level in a `'use client'` provider that your root layout renders. ## 5. Lazy-load Grid Pro Grid Pro adds weight that a page may not need until the user opens a report. Load the module and the component with `next/dynamic`: ```tsx title="app/reports/revenue-grid.tsx" 'use client'; import { BirchGrid } from '@birchui/react'; import { RowGroupingModule, AggregationModule } from '@birchui/grid-pro'; import type { ColumnDef } from '@birchui/core'; import type { Sale } from '@/lib/sales'; const modules = [RowGroupingModule, AggregationModule]; const columns: ColumnDef[] = [ { field: 'region', header: 'Region', rowGroup: true }, { field: 'product', header: 'Product' }, { field: 'revenue', header: 'Revenue', type: 'number', aggFunc: 'sum' }, ]; export default function RevenueGrid({ sales }: { sales: Sale[] }) { return ( style={{ height: 520 }} columns={columns} rows={sales} modules={modules} groupDefaultExpanded={1} licenseKey={process.env.NEXT_PUBLIC_BIRCHUI_LICENSE_KEY} /> ); } ``` ```tsx title="app/reports/revenue-panel.tsx" 'use client'; import dynamic from 'next/dynamic'; import type { Sale } from '@/lib/sales'; const RevenueGrid = dynamic(() => import('./revenue-grid'), { ssr: false, loading: () =>
, }); export function RevenuePanel({ sales }: { sales: Sale[] }) { return ; } ``` `ssr: false` is only allowed inside Client Components, which is why the dynamic import lives in `revenue-panel.tsx`. The grid itself does not need it, since it is safe to import on the server; it only keeps the Pro code out of the initial bundle. ## Pitfalls - **`'use client'` is required** on the file that renders `BirchGrid`. Without it, React reports hooks used in a Server Component. - **Functions cannot be props from the server.** Define columns, formatters and `getRowId` in the client file. - **Strict Mode** mounts the grid twice in development. That is expected; the second instance is the one the ref points to. - **Without a key on a public host**, Grid Pro features still work but show a small watermark. ## Related - [React](https://docs.birchui.com/frameworks/react.md) and its [Next.js section](https://docs.birchui.com/frameworks/react.md#nextjs-and-server-rendering). - [Licensing](https://docs.birchui.com/getting-started/licensing.md#activate-your-key). - [Grid Pro overview](https://docs.birchui.com/grid-pro/overview.md). --- Source: https://docs.birchui.com/recipes/grid-angular-standalone/ # Grid Pro in an Angular standalone app > Use the birchui-grid component in a standalone, zoneless Angular app with signal inputs, a computed options object, outputs and Grid Pro modules. This recipe builds a sales order screen in Angular with standalone components and signals: grouping with totals, range selection, clipboard, a status bar and Excel export. The `examples/angular-grid-pro` project in the Birch UI repository is the complete version. ## 1. Install ```sh npm install @birchui/core @birchui/angular @birchui/grid-pro @birchui/license ``` ## 2. Set the license key at startup ```ts title="src/main.ts" import { bootstrapApplication } from '@angular/platform-browser'; import { setLicenseKey } from '@birchui/license'; import { App } from './app/app'; import { appConfig } from './app/app.config'; import { environment } from './environments/environment'; setLicenseKey(environment.birchLicenseKey); bootstrapApplication(App, appConfig).catch((error: unknown) => console.error(error)); ``` Without a key every feature works; on hosts other than `localhost` a small watermark appears. You can also pass a key to one grid with the `[licenseKey]` input. ## 3. The component ```ts title="src/app/app.ts" import { ChangeDetectionStrategy, Component, computed, signal, viewChild } from '@angular/core'; import { BirchGridComponent } from '@birchui/angular'; import { AllProModules } from '@birchui/grid-pro'; import type { CellValueChangedEvent, ColumnDef, GridOptions } from '@birchui/core'; import { createOrders, type Order } from './orders'; const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); type Layout = 'region' | 'category' | 'flat'; const GROUPINGS: Record = { region: ['region', 'country'], category: ['category', 'product'], flat: [], }; @Component({ selector: 'app-root', imports: [BirchGridComponent], changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './app.html', }) export class App { private readonly grid = viewChild.required>(BirchGridComponent); readonly orders = signal(createOrders(5000)); readonly search = signal(''); readonly layout = signal('region'); readonly lastEdit = signal(''); readonly columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110, pinned: 'left' }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 180, filter: 'text', editable: true }, { field: 'units', header: 'Units', type: 'number', aggFunc: 'sum', editable: true }, { field: 'total', header: 'Total', type: 'number', aggFunc: 'sum', format: (value) => usd.format(Number(value)) }, { field: 'region', header: 'Region', filter: 'set' }, { field: 'country', header: 'Country', filter: 'set' }, { field: 'category', header: 'Category', filter: 'set' }, { field: 'product', header: 'Product', minWidth: 200 }, ]; readonly options = computed>>(() => ({ modules: [...AllProModules], getRowId: (order) => order.id, groupBy: GROUPINGS[this.layout()], groupDefaultExpanded: 1, groupTotals: true, rangeSelection: true, clipboard: true, statusBar: true, undoRedo: true, theme: 'auto', })); setLayout(value: string): void { this.layout.set(value as Layout); } onEdit({ row, colId, newValue }: CellValueChangedEvent): void { this.lastEdit.set(`${row.id}: ${colId} set to ${String(newValue)}`); } exportExcel(): void { void this.grid().api?.exportExcel?.({ fileName: 'orders', sheetName: 'Orders' }); } } ``` ```html title="src/app/app.html"
{{ lastEdit() }}
``` ```css title="src/styles.css" .orders { height: calc(100vh - 160px); } ``` ## How it works - `[columns]`, `[rows]`, `[quickFilter]`, `[theme]` and `[licenseKey]` are shortcuts; everything else goes in `[options]`. After each change only the keys whose value changed by identity are passed to the grid's `update()`. The grid is never recreated, so switching the grouping keeps scroll position and selection. - Every grid event is an output with a typed payload, including `stateChanged` and `columnGroupOpened`. - The `api` property of the component is the `GridApi`. It is `undefined` until the first browser render, so read it in event handlers or after `(ready)`. - The grid is created in `afterNextRender`, so the component works with `@angular/ssr` without changes. ## Pitfalls - **Pass new arrays.** `this.orders.update((orders) => [...orders, order])` is detected; `orders().push(order)` is not. For frequent row changes use `this.grid().api?.applyTransaction({ update: [order] })`. - **Give the host a height.** `` is a block element with no intrinsic height; without one it renders no rows. - **Pro methods are optional.** Call `exportExcel?.()` with optional chaining, as Pro API methods are optional on `GridApi`. ## Related - [Angular](https://docs.birchui.com/frameworks/angular.md), with the [inputs](https://docs.birchui.com/frameworks/angular.md#inputs) and [outputs](https://docs.birchui.com/frameworks/angular.md#outputs) tables. - [Grid Pro overview](https://docs.birchui.com/grid-pro/overview.md) and [Excel export](https://docs.birchui.com/grid-pro/excel-export.md). --- Source: https://docs.birchui.com/recipes/grid-column-groups/ # Collapsible column groups > Group related columns under shared headers with ColumnGroupDef, make groups collapsible with columnGroupShow, and open or close them from code. Wide grids read better when related columns share a header: customer details, pricing, shipping. This recipe groups an order grid's columns and lets users collapse each group to a summary column. **Live demo: Collapsible column groups** (runs on the HTML version of this page). Source of `demos/recipe-grid-column-groups.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef, type ColumnGroupDef } from '@birchui/core'; import { button, docsTheme, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order, } from './_shared'; export const meta = { title: 'Collapsible column groups', height: 440 }; const columns: (ColumnDef | ColumnGroupDef)[] = [ { field: 'id', header: 'Order', width: 110, pinned: 'left' }, { groupId: 'customer', header: 'Customer', collapsible: true, openByDefault: true, children: [ { field: 'customer', header: 'Name', width: 180 }, { field: 'country', header: 'Country', width: 140, columnGroupShow: 'open' }, { field: 'region', header: 'Region', width: 140, columnGroupShow: 'open' }, ], }, { groupId: 'pricing', header: 'Pricing', collapsible: true, children: [ { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency }, { field: 'quantity', header: 'Qty', type: 'number', width: 90, columnGroupShow: 'open' }, { field: 'unitPrice', header: 'Unit price', type: 'number', width: 110, format: formatCurrency, columnGroupShow: 'open', }, { field: 'discount', header: 'Discount', type: 'number', width: 100, format: (value) => `${Math.round(Number(value) * 100)}%`, columnGroupShow: 'open', }, ], }, { field: 'status', header: 'Status', width: 120 }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const grid = createGrid(body, { columns, rows: makeOrders(150, 5), getRowId: (order) => order.id, theme: docsTheme(), ariaLabel: 'Orders with column groups', }); toolbar.append( button('Expand pricing', () => grid.setColumnGroupOpen('pricing', true)), button('Collapse all groups', () => { grid.setColumnGroupOpen('customer', false); grid.setColumnGroupOpen('pricing', false); }), ); status.textContent = 'Click the toggle in a group header, or focus it and press Enter.'; const off = grid.on('columnGroupOpened', ({ groupId, open }) => { status.textContent = `${groupId} ${open ? 'expanded' : 'collapsed'}: ${grid.getDisplayColumns().length} columns shown.`; }); const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { off(); stopTheme(); grid.destroy(); }; } ``` ## 1. Define the groups A `ColumnGroupDef` has a `header` and `children`, which can be columns or further groups. Mix groups and plain columns freely in `columns`: ```ts title="order-columns.ts" import type { ColumnDef, ColumnGroupDef } from '@birchui/core'; import type { Order } from './orders'; const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); const money = (value: unknown) => usd.format(Number(value)); export const columns: (ColumnDef | ColumnGroupDef)[] = [ { field: 'id', header: 'Order', width: 110, pinned: 'left' }, { groupId: 'customer', header: 'Customer', collapsible: true, openByDefault: true, children: [ { field: 'customer', header: 'Name', width: 180 }, { field: 'country', header: 'Country', columnGroupShow: 'open' }, { field: 'region', header: 'Region', columnGroupShow: 'open' }, ], }, { groupId: 'pricing', header: 'Pricing', collapsible: true, children: [ { id: 'revenue', header: 'Revenue', type: 'number', valueGetter: (o) => o.quantity * o.unitPrice, format: money }, { field: 'quantity', header: 'Qty', type: 'number', columnGroupShow: 'open' }, { field: 'unitPrice', header: 'Unit price', type: 'number', format: money, columnGroupShow: 'open' }, ], }, { field: 'status', header: 'Status' }, ]; ``` ## 2. Decide what shows when In a group with `collapsible: true`, each child's `columnGroupShow` decides when it is visible: | `columnGroupShow` | Visible when the group is | | --- | --- | | not set | Open and closed | | `'open'` | Open only | | `'closed'` | Closed only | Use `'closed'` for a summary column that replaces the details, such as a combined address. Groups start closed unless `openByDefault` is `true`. If closing a group would hide every one of its columns, the grid keeps them visible. ## 3. Control groups from code ```ts title="orders-grid.ts" import { createGrid } from '@birchui/core'; import { columns } from './order-columns'; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (order) => order.id, }); document.querySelector('#show-pricing')!.addEventListener('click', () => grid.setColumnGroupOpen('pricing', true)); grid.on('columnGroupOpened', ({ groupId, open }) => { try { localStorage.setItem(`orders-group:${groupId}`, String(open)); } catch { // Storage unavailable; the group simply opens with its default next time. } }); for (const group of grid.getColumnGroups()) { try { const saved = localStorage.getItem(`orders-group:${group.groupId}`); if (saved !== null) grid.setColumnGroupOpen(group.groupId, saved === 'true'); } catch { break; } } ``` `getColumnGroups()` returns the resolved groups with their `open` state and the ids of their columns. Group open state is not part of `getState()`, so persist it separately as above. **`ColumnGroupDef`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface ColumnGroupDef extends Partial< Record, 'header' | 'headerClass'>, never> > ``` | Property | Type | Description | | --- | --- | --- | | `groupId?` | `string` | | | `header` | `string` | | | `children` | `(ColumnDef \| ColumnGroupDef)[]` | | | `headerClass?` | `string` | | | `collapsible?` | `boolean` | | | `openByDefault?` | `boolean` | | | `id?` | `undefined` | | | `field?` | `undefined` | | | `headerTooltip?` | `undefined` | | | `type?` | `undefined` | | | `width?` | `undefined` | | | `minWidth?` | `undefined` | | | `maxWidth?` | `undefined` | | | `flex?` | `undefined` | | | `pinned?` | `undefined` | | | `hidden?` | `undefined` | | | `sortable?` | `undefined` | | | `resizable?` | `undefined` | | | `reorderable?` | `undefined` | | | `rowHeader?` | `undefined` | | | `filter?` | `undefined` | | | `editable?` | `undefined` | | | `editor?` | `undefined` | | | `options?` | `undefined` | | | `valueGetter?` | `undefined` | | | `valueSetter?` | `undefined` | | | `valueParser?` | `undefined` | | | `format?` | `undefined` | | | `cell?` | `undefined` | | | `cellClass?` | `undefined` | | | `align?` | `undefined` | | | `comparator?` | `undefined` | | | `aggFunc?` | `undefined` | | | `rowGroup?` | `undefined` | | | `rowGroupIndex?` | `undefined` | | | `pivot?` | `undefined` | | | `pivotIndex?` | `undefined` | | | `meta?` | `undefined` | | | `columnGroupShow?` | `undefined` | | | `autoHeight?` | `undefined` | | | `wrapText?` | `undefined` | | | `rowDrag?` | `undefined` | | | `sparkline?` | `undefined` | | ## How it works - The header gets one row per nesting level, and each group header cell spans its visible children. - A collapsible group shows a toggle button in its header. Users can click it, or focus the header with the arrow keys and press Enter or Space. - `setColumnGroupOpen()` fires `columnGroupOpened`, announces the change to screen readers and moves focus to a visible column if the focused one was hidden. ## Pitfalls - **Give groups a `groupId`.** Without one the grid generates an id from the group's position, which changes when you reorder `columns`. Duplicate ids are renamed with a warning. - **Groups have no column properties.** `ColumnGroupDef` only accepts `groupId`, `header`, `children`, `headerClass`, `collapsible` and `openByDefault`; TypeScript rejects `width` or `field` on a group. ## Related - [Columns](https://docs.birchui.com/grid/columns.md) and [Column operations](https://docs.birchui.com/grid/column-operations.md). - [Persist grid state](https://docs.birchui.com/recipes/grid-persist-state.md). --- Source: https://docs.birchui.com/recipes/grid-context-menu/ # Custom cell context menu > Add row actions to the grid's right-click menu, keep or drop the built-in copy and export items, and disable the menu entirely with the contextMenu option. Right-clicking a cell opens a menu with **Copy cell**, **Copy row**, **Copy with headers** and **Export CSV**. This recipe adds order actions to that menu with the `contextMenu` option. **Live demo: Custom context menu** (runs on the HTML version of this page). Source of `demos/recipe-grid-context-menu.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef, type GridApi } from '@birchui/core'; import { docsTheme, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order } from './_shared'; export const meta = { title: 'Custom context menu', height: 440 }; const columns: ColumnDef[] = [ { field: 'id', header: 'Order', width: 110 }, { field: 'customer', header: 'Customer', flex: 1, minWidth: 170 }, { field: 'product', header: 'Product', width: 190 }, { field: 'status', header: 'Status', width: 120 }, { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); toolbar.append('Right-click a cell, or focus one and press Shift+F10.'); const setStatus = (api: GridApi, order: Order, next: Order['status']) => { api.setValue(order, 'status', next); status.textContent = `${order.id} marked as ${next}.`; }; const grid = createGrid(body, { columns, rows: makeOrders(150, 3), getRowId: (order) => order.id, theme: docsTheme(), ariaLabel: 'Orders with a context menu', contextMenu: (ctx, defaults) => { const order = ctx.row; if (!order) return defaults; return [ { label: 'Mark as shipped', disabled: order.status !== 'Pending', action: () => setStatus(ctx.api, order, 'Shipped'), }, { label: 'Mark as returned', disabled: order.status !== 'Delivered', action: () => setStatus(ctx.api, order, 'Returned'), }, { label: `Filter to ${order.customer}`, separatorBefore: true, action: () => ctx.api.setQuickFilter(order.customer), }, { label: 'Clear filter', action: () => ctx.api.setQuickFilter('') }, ...defaults.map((item, index) => (index === 0 ? { ...item, separatorBefore: true } : item)), ]; }, }); status.textContent = 'Custom actions appear above the built-in copy and export items.'; const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { stopTheme(); grid.destroy(); }; } ``` ## 1. Add your items `contextMenu` is `true` (the default), `false`, or a function that receives the cell context and the default items and returns the items to show: ```ts title="orders-grid.ts" import { createGrid, type MenuItem } from '@birchui/core'; import { openOrderDrawer, shipOrder } from './orders-actions'; const grid = createGrid(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (order) => order.id, contextMenu: (ctx, defaults) => { const order = ctx.row; if (!order) return defaults; const actions: MenuItem[] = [ { label: 'Open order', action: () => openOrderDrawer(order.id) }, { label: 'Mark as shipped', disabled: order.status !== 'Pending', action: async () => { await shipOrder(order.id); ctx.api.setValue(order, 'status', 'Shipped'); }, }, { label: `Show only ${order.customer}`, separatorBefore: true, action: () => ctx.api.setFilter('customer', { type: 'text', op: 'equals', value: order.customer }), }, ]; return [...actions, ...defaults.map((item, i) => (i === 0 ? { ...item, separatorBefore: true } : item))]; }, }); ``` The context gives you the row (`ctx.row`), the column (`ctx.column`), the raw and formatted value, the display row and the grid API. **`MenuItem`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md) ```ts interface MenuItem ``` | Property | Type | Description | | --- | --- | --- | | `label` | `string` | | | `action` | `() => void` | | | `checked?` | `boolean` | | | `disabled?` | `boolean` | | | `separatorBefore?` | `boolean` | | ## 2. Per-column menus Return different items depending on the column: ```ts contextMenu: (ctx, defaults) => { if (ctx.column.id === 'customer' && ctx.row) { return [{ label: `Email ${ctx.row.customer}`, action: () => composeEmail(ctx.row!.customerEmail) }, ...defaults]; } return defaults; }, ``` ## 3. Remove the menu ```ts createGrid(container, { columns, rows, contextMenu: false }); ``` With `false`, right-click shows the browser's own menu. Returning an empty array from the function also suppresses the grid menu for that cell, which is how to disable it only on some columns. ## How it works - The menu opens on right-click, and from the keyboard with Shift+F10 or the context menu key on a focused cell. Focus returns to the cell when the menu closes. - Installed Grid Pro modules contribute their own items, for example the fill handle's **Fill down**. They are part of `defaults`, after the built-in items. - Opening the menu stops any edit in progress and focuses the clicked cell. - Right-clicking inside an editor or another text input shows the browser menu, so spell-check and paste keep working. - If your function throws or returns something other than an array, the grid shows the default items and logs the problem. ## Pitfalls - **Labels are not translated for you.** Use your own translations for item labels; the built-in items follow the grid's `localeText`. - **Keep actions quick.** `action` runs when the item is chosen; for slow work, update the UI optimistically or show progress elsewhere, since the menu closes immediately. - **Group and detail rows.** `ctx.row` is `undefined` on group rows, so check it before reading fields. Full-width rows such as detail panels open no menu. ## Related - [Keyboard-only workflows](https://docs.birchui.com/recipes/grid-keyboard-workflows.md). - [Column menu items](https://docs.birchui.com/grid/modules.md#column-menu-items) for the header menu. - [Clipboard](https://docs.birchui.com/grid-pro/clipboard.md) for range copy and paste. --- Source: https://docs.birchui.com/recipes/grid-live-updates/ # Streaming live updates > Apply a stream of WebSocket messages to the grid with batched applyTransaction calls, flash changed cells and keep sorting and selection stable. Prices, stock levels and job statuses change many times a second. Calling `setRows()` for each message rebuilds the whole model; `applyTransaction()` touches only the rows that changed. This recipe batches messages per animation frame and highlights what changed. **Live demo: Streaming updates** (runs on the HTML version of this page). Source of `demos/recipe-grid-live-updates.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createGrid, type ColumnDef } from '@birchui/core'; import { button, docsTheme, layout, onDocsThemeChange, seededRandom } from './_shared'; export const meta = { title: 'Streaming updates', height: 420 }; interface Quote { symbol: string; company: string; bid: number; ask: number; volume: number; } const COMPANIES = [ ['NWND', 'Northwind Traders'], ['KSTR', 'Kestrel Logistics'], ['HRBR', 'Harbourline Marine'], ['SKRA', 'Sakura Retail Group'], ['LOTS', 'Lotus Electronics'], ['ANDS', 'Andes Coffee Co.'], ['RVAG', 'Rio Verde Agro'], ['CDST', 'Cedar & Stone'], ] as const; const price = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const columns: ColumnDef[] = [ { field: 'symbol', header: 'Symbol', width: 100 }, { field: 'company', header: 'Company', flex: 1, minWidth: 180 }, { field: 'bid', header: 'Bid', type: 'number', width: 100, format: (v) => price.format(Number(v)) }, { field: 'ask', header: 'Ask', type: 'number', width: 100, format: (v) => price.format(Number(v)) }, { field: 'volume', header: 'Volume', type: 'number', width: 120 }, ]; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const random = seededRandom(42); const quotes = new Map( COMPANIES.map(([symbol, company]) => { const bid = 20 + Math.round(random() * 18000) / 100; return [symbol, { symbol, company, bid, ask: bid + 0.05, volume: 0 }]; }), ); const grid = createGrid(body, { columns, rows: [...quotes.values()], getRowId: (quote) => quote.symbol, theme: docsTheme(), ariaLabel: 'Live quotes', }); const pending = new Map(); let frame = 0; let applied = 0; const flush = () => { frame = 0; const update = [...pending.values()]; pending.clear(); grid.applyTransaction({ update }); grid.flashCells({ rows: update, columns: ['bid', 'ask', 'volume'] }); applied += update.length; status.textContent = `${applied} updates applied in batches, one transaction per frame.`; }; const receive = (quote: Quote) => { pending.set(quote.symbol, quote); if (!frame) frame = requestAnimationFrame(flush); }; let timer: ReturnType | undefined; const tick = () => { for (let i = 0; i < 3; i++) { const [symbol] = COMPANIES[Math.floor(random() * COMPANIES.length)]; const current = pending.get(symbol) ?? quotes.get(symbol)!; const bid = Math.max(1, Math.round((current.bid + (random() - 0.5)) * 100) / 100); const next = { ...current, bid, ask: bid + 0.05, volume: current.volume + Math.ceil(random() * 500) }; quotes.set(symbol, next); receive(next); } }; const start = () => { if (timer === undefined) timer = setInterval(tick, 250); }; const stop = () => { clearInterval(timer); timer = undefined; }; toolbar.append(button('Start feed', start), button('Pause feed', stop)); status.textContent = 'Start the feed to stream quotes into the grid.'; const stopTheme = onDocsThemeChange((theme) => grid.update({ theme })); return () => { stop(); if (frame) cancelAnimationFrame(frame); stopTheme(); grid.destroy(); }; } ``` ## 1. Create the grid with stable ids ```ts title="quotes-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; export interface Quote { symbol: string; company: string; bid: number; ask: number; volume: number; } const price = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const columns: ColumnDef[] = [ { field: 'symbol', header: 'Symbol', width: 100 }, { field: 'company', header: 'Company', flex: 1 }, { field: 'bid', header: 'Bid', type: 'number', format: (v) => price.format(Number(v)) }, { field: 'ask', header: 'Ask', type: 'number', format: (v) => price.format(Number(v)) }, { field: 'volume', header: 'Volume', type: 'number' }, ]; export const grid = createGrid(document.querySelector('#quotes')!, { columns, rows: await loadSnapshot(), getRowId: (quote) => quote.symbol, flashDuration: 600, }); ``` `getRowId` is what lets a transaction find the row to update. Without it, row ids are positions, and an update cannot be matched to the row it belongs to. ## 2. Batch messages per frame ```ts title="quotes-stream.ts" import { grid, type Quote } from './quotes-grid'; type QuoteMessage = | { type: 'quote'; quote: Quote } | { type: 'listed'; quote: Quote } | { type: 'delisted'; symbol: string }; const updates = new Map(); const added: Quote[] = []; const removed = new Set(); let frame = 0; function flush(): void { frame = 0; const update = [...updates.values()]; grid.applyTransaction({ add: added.splice(0), update, remove: [...removed] }); grid.flashCells({ rows: update, columns: ['bid', 'ask', 'volume'] }); updates.clear(); removed.clear(); } function schedule(): void { if (!frame) frame = requestAnimationFrame(flush); } const socket = new WebSocket('wss://quotes.example.com/stream'); socket.addEventListener('message', (event) => { const message = JSON.parse(event.data) as QuoteMessage; if (message.type === 'quote') updates.set(message.quote.symbol, message.quote); else if (message.type === 'listed') added.push(message.quote); else removed.add(message.symbol); schedule(); }); ``` A `Map` keyed by id keeps only the latest message per row, so 50 ticks for one symbol within a frame become one update. ## How it works - `applyTransaction({ add, update, remove })` adds rows, replaces rows with the same id, and removes rows given as objects or ids. Sorting, filtering and grouping are reapplied to the result. - Selection, focus and expansion are kept, because they are stored by row id. - `flashCells()` briefly highlights the given cells. Its duration comes from `flashDuration` (500 ms by default) or the `duration` parameter. Set `flashCells: true` to flash every cell changed by an edit or `setValue()` automatically; transactions are flashed only when you call `flashCells()`. - When a sort is active, an updated row moves to its new position. If rows jumping around is distracting, pause the stream while the user hovers or edits, or remove the sort. ## Pitfalls - **Do not mutate rows in place** and expect a redraw. Pass a new object in `update`, or call `refresh()` after mutating. - **Updates for unknown ids are ignored.** Send a `listed` message, or use `add`, for new rows. - **Hidden tabs.** `requestAnimationFrame` does not run in background tabs, so messages pile up in the map, which is fine: the next visible frame applies them in one transaction. - **Close the socket** when the grid is destroyed, and cancel a pending frame with `cancelAnimationFrame`. ## Related - [Updating data](https://docs.birchui.com/grid/updating-data.md), including [Streaming updates](https://docs.birchui.com/grid/updating-data.md#streaming-updates). - [Show a million rows](https://docs.birchui.com/recipes/grid-million-rows.md). - [`RowTransaction`](https://docs.birchui.com/api/core.md) in the API reference. --- Source: https://docs.birchui.com/recipes/grid-import-xlsx/ # Import an Excel file into a grid > Read an uploaded .xlsx file with readXlsx, turn its rows into typed records with sheetToObjects, validate them and show them in a grid for review. Users often arrive with a spreadsheet: a price list, a customer export, a stock count. This recipe reads the file in the browser with the Excel Engine, validates each row, and shows the result in a grid where bad rows are flagged before anything is saved. > **Excel Engine: Paid product. Fully functional without a key; without one it logs a single console warning and never shows a watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md** > > `readXlsx` and `sheetToObjects` come from `@birchui/excel`, which needs an Excel Engine or Grid Pro license. If you already use Grid Pro, `ExcelModule`'s [`importExcel()`](https://docs.birchui.com/grid-pro/excel-export.md#import-a-spreadsheet) loads a sheet straight into an existing grid; use this recipe when you need your own validation step. ## 1. Read the file ```ts title="read-price-list.ts" import { readXlsx, sheetToObjects, type XlsxPrimitive } from '@birchui/excel'; export async function readPriceList(file: File): Promise[]> { const workbook = await readXlsx(file); const sheet = workbook.sheets.find((candidate) => candidate.name === 'Prices') ?? workbook.sheets[0]; if (!sheet) throw new Error(`${file.name} contains no worksheets`); return sheetToObjects(sheet); } ``` `readXlsx` accepts a `File`, `Blob`, `ArrayBuffer` or `Uint8Array` and returns every sheet as rows of values: strings, numbers, booleans, `Date` for date-formatted cells, and `null` for empty cells. `sheetToObjects` uses the first row as keys and skips empty rows. Pass `{ headerRow: 2 }` when the header is on the third row, below a title. ## 2. Validate and convert ```ts title="price-rows.ts" import type { XlsxPrimitive } from '@birchui/excel'; export interface PriceRow { id: string; sku: string; product: string; unitPrice: number | null; validFrom: string | null; problems: string[]; } const isoDate = (value: Date) => `${value.getUTCFullYear()}-${String(value.getUTCMonth() + 1).padStart(2, '0')}-${String(value.getUTCDate()).padStart(2, '0')}`; export function toPriceRows(records: Record[]): PriceRow[] { const seen = new Set(); return records.map((record, index) => { const problems: string[] = []; const sku = String(record['SKU'] ?? '').trim(); const price = record['Unit price']; const validFrom = record['Valid from']; if (!sku) problems.push('SKU is missing'); else if (seen.has(sku)) problems.push('Duplicate SKU'); seen.add(sku); if (typeof price !== 'number' || price <= 0) problems.push('Unit price must be a positive number'); if (validFrom !== null && validFrom !== undefined && !(validFrom instanceof Date)) { problems.push('Valid from is not a date'); } return { id: `row-${index + 2}`, sku, product: String(record['Product'] ?? ''), unitPrice: typeof price === 'number' ? price : null, validFrom: validFrom instanceof Date ? isoDate(validFrom) : null, problems, }; }); } ``` The id uses the spreadsheet row number (`index + 2`, after the header), so users can find a flagged row in Excel. Dates are read in UTC; format them with the `getUTC*` methods, as above, to keep the calendar date the sheet shows. ## 3. Show the rows for review ```ts title="price-import.ts" import { createGrid, type ColumnDef } from '@birchui/core'; import { readPriceList } from './read-price-list'; import { toPriceRows, type PriceRow } from './price-rows'; const columns: ColumnDef[] = [ { id: 'line', header: 'Row', width: 80, valueGetter: (row) => Number(row.id.slice(4)), type: 'number' }, { field: 'sku', header: 'SKU', width: 130, editable: true }, { field: 'product', header: 'Product', flex: 1, editable: true }, { field: 'unitPrice', header: 'Unit price', type: 'number', editable: true }, { field: 'validFrom', header: 'Valid from', type: 'date', editable: true, editor: 'date' }, { id: 'problems', header: 'Problems', width: 280, valueGetter: (row) => row.problems.join('; '), cellClass: (ctx) => (ctx.row?.problems.length ? 'import-problem' : undefined), }, ]; const grid = createGrid(document.querySelector('#import-preview')!, { columns, rows: [], getRowId: (row) => row.id, rowClass: (row) => (row.data?.problems.length ? 'import-row-invalid' : undefined), emptyMessage: 'Choose a price list to preview it here.', }); const input = document.querySelector('#price-file')!; const summary = document.querySelector('#import-summary')!; input.addEventListener('change', async () => { const file = input.files?.[0]; if (!file) return; try { const rows = toPriceRows(await readPriceList(file)); grid.setRows(rows); const invalid = rows.filter((row) => row.problems.length > 0).length; summary.textContent = `${rows.length} rows read, ${invalid} need attention.`; } catch (error) { summary.textContent = `Could not read ${file.name}: ${error instanceof Error ? error.message : String(error)}`; } }); ``` ```css title="price-import.css" .lq-grid .lq-row.import-row-invalid { background: color-mix(in srgb, var(--lq-danger) 8%, var(--lq-bg)); } .lq-grid .lq-cell.import-problem { color: var(--lq-danger); } ``` Users can fix values in place. Re-run the validation on edit to update the flags: ```ts grid.on('cellValueChanged', () => grid.setRows(toPriceRows(grid.getRows().map(toRecord)))); function toRecord(row: PriceRow): Record { return { SKU: row.sku, Product: row.product, 'Unit price': row.unitPrice, 'Valid from': row.validFrom ? new Date(`${row.validFrom}T00:00:00Z`) : null, }; } ``` ## Pitfalls - **Headers must match exactly.** `sheetToObjects` uses header text as keys, including spaces and case. Normalize them if your users edit the template. - **Formulas give cached results.** A formula cell returns the value Excel last calculated. Files produced by tools that do not store results give `null`. - **Large files.** `readXlsx` also runs in a Web Worker, which keeps the page responsive for files with hundreds of thousands of rows; see [Workers](https://docs.birchui.com/excel/workers.md). - **Password-protected workbooks** are not supported and make `readXlsx` reject. ## Related - [Reading files](https://docs.birchui.com/excel/reading.md), including [Records with `sheetToObjects`](https://docs.birchui.com/excel/reading.md#records-with-sheettoobjects). - [Excel export and import](https://docs.birchui.com/grid-pro/excel-export.md) for the built-in Grid Pro import. - [Editing](https://docs.birchui.com/grid/editing.md). --- Source: https://docs.birchui.com/recipes/pivot-saved-layouts/ # Save and load pivot layouts > Let users save named Pivot Studio layouts as PivotReport JSON, keep them in localStorage or on your server, and open them again. Analysts build the same few views over and over: revenue by depot, hours by technician, first-time fix rate by job type. This recipe adds a layout picker to a Pivot Studio report so each view is built once, saved under a name, and opened again with one click. Layouts are stored as `PivotReport` JSON, first in `localStorage` and then on a server. **Live demo: Saved pivot layouts** (runs on the HTML version of this page). Source of `demos/recipe-pivot-saved-layouts.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createPivotStudio, type PivotReport } from '@birchui/pivot-studio'; import { button, docsTheme, field, layout, onDocsThemeChange, seededRandom } from './_shared'; export const meta = { title: 'Saved pivot layouts', height: 600 }; const STORAGE_KEY = 'birchui-docs:work-order-layouts'; interface WorkOrder { region: string; depot: string; technician: string; jobType: string; month: string; hours: number; revenue: number; firstTimeFix: number; } const DEPOTS: [string, string, string[]][] = [ ['North', 'Leeds', ['Ana Ruiz', 'Omar Haddad']], ['North', 'Manchester', ['Li Wei', 'Sam Patel']], ['South', 'Bristol', ['Nora Lindqvist', 'Ben Mensah']], ['South', 'Southampton', ['Priya Natarajan', 'Diego Alvarez']], ['London', 'Croydon', ['Hana Sato', 'Jonas Becker']], ]; const JOB_TYPES: [string, number, number][] = [ ['Boiler service', 1.5, 95], ['Heat pump install', 14, 1850], ['EV charger fit', 5, 640], ['Fault finding', 2.5, 180], ['Annual inspection', 1, 75], ]; function makeWorkOrders(): WorkOrder[] { const random = seededRandom(47); const orders: WorkOrder[] = []; for (let m = 0; m < 6; m++) { const month = `2026-${String(m + 7).padStart(2, '0')}`; for (const [region, depot, crew] of DEPOTS) { for (const technician of crew) { for (const [jobType, hours, price] of JOB_TYPES) { const count = 1 + Math.floor(random() * 6); orders.push({ region, depot, technician, jobType, month, hours: Math.round(count * hours * (0.8 + random() * 0.4) * 10) / 10, revenue: Math.round(count * price * (0.9 + random() * 0.2)), firstTimeFix: random() < 0.82 ? 1 : 0, }); } } } } return orders; } const BUILT_IN: Record = { 'Revenue by depot': { version: 1, slice: { rows: [{ field: 'region' }, { field: 'depot' }], columns: [{ field: 'month' }], values: [{ field: 'revenue', aggregation: 'sum', caption: 'Revenue' }], }, formats: { revenue: { style: 'currency', currency: 'GBP', decimals: 0 } }, }, 'Hours by technician': { version: 1, slice: { rows: [{ field: 'technician', sortBy: { measure: 'sum(hours)', dir: 'desc' } }], columns: [{ field: 'jobType' }], values: [{ field: 'hours', aggregation: 'sum', caption: 'Hours' }], }, options: { columnSubtotals: false }, }, 'First-time fix rate': { version: 1, slice: { rows: [{ field: 'jobType' }], columns: [{ field: 'region' }], values: [{ field: 'firstTimeFix', aggregation: 'avg', caption: 'First-time fix' }], }, formats: { firstTimeFix: { style: 'percent', decimals: 0 } }, }, }; function readSaved(): Record { try { const text = window.localStorage.getItem(STORAGE_KEY); const parsed: unknown = text ? JSON.parse(text) : {}; return parsed && typeof parsed === 'object' ? (parsed as Record) : {}; } catch { return {}; } } function writeSaved(layouts: Record): boolean { try { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(layouts)); return true; } catch { return false; } } export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); let saved = readSaved(); const picker = document.createElement('select'); const nameInput = document.createElement('input'); nameInput.type = 'text'; nameInput.placeholder = 'Layout name'; nameInput.value = 'My layout'; const allLayouts = () => ({ ...BUILT_IN, ...saved }); const renderPicker = (selected: string) => { picker.replaceChildren( ...Object.keys(allLayouts()).map((name) => new Option(name, name, false, name === selected)), ); }; const studio = createPivotStudio(body, { data: makeWorkOrders(), report: BUILT_IN['Revenue by depot'], theme: docsTheme(), height: '100%', fileName: 'work-orders-h2-2026', ariaLabel: 'Work order pivot report', }); const saveButton = button('Save layout', () => { const name = nameInput.value.trim(); if (!name) { status.textContent = 'Enter a name for the layout first.'; return; } saved = { ...saved, [name]: studio.getReport() }; const stored = writeSaved(saved); renderPicker(name); status.textContent = stored ? `Saved "${name}". It is still here after a reload.` : `Saved "${name}" for this visit only; browser storage is unavailable.`; }); const deleteButton = button('Delete', () => { const name = picker.value; if (!(name in saved)) { status.textContent = `"${name}" is a built-in layout and cannot be deleted.`; return; } saved = Object.fromEntries(Object.entries(saved).filter(([key]) => key !== name)); writeSaved(saved); renderPicker('Revenue by depot'); studio.setReport(BUILT_IN['Revenue by depot']); status.textContent = `Deleted "${name}".`; }); const onPick = () => { const report = allLayouts()[picker.value]; if (report) studio.setReport(report); status.textContent = `Opened "${picker.value}".`; }; picker.addEventListener('change', onPick); renderPicker('Revenue by depot'); toolbar.append(field('Layout', picker), field('Save as', nameInput), saveButton, deleteButton); const offs = [ studio.on('error', ({ message }) => { status.textContent = message; }), ]; status.textContent = 'Rearrange the fields, then save the layout under a name.'; const stopTheme = onDocsThemeChange((theme) => studio.update({ theme })); return () => { picker.removeEventListener('change', onPick); for (const off of offs) off(); stopTheme(); studio.destroy(); }; } ``` ## Steps 1. Define the built-in layouts your team ships as `PivotReport` objects. 2. Read the user's saved layouts on start-up and merge them with the built-in ones. 3. On **Save layout**, store `studio.getReport()` under the chosen name. 4. On selection, call `studio.setReport(report)`. The data stays loaded; only the layout changes. ## Built-in layouts A report needs only the `slice`; every other key falls back to its default. ```ts title="work-order-layouts.ts" import type { PivotReport } from '@birchui/pivot-studio'; export const BUILT_IN_LAYOUTS: Record = { 'Revenue by depot': { version: 1, slice: { rows: [{ field: 'region' }, { field: 'depot' }], columns: [{ field: 'month' }], values: [{ field: 'revenue', aggregation: 'sum', caption: 'Revenue' }], }, formats: { revenue: { style: 'currency', currency: 'GBP', decimals: 0 } }, }, 'Hours by technician': { version: 1, slice: { rows: [{ field: 'technician', sortBy: { measure: 'sum(hours)', dir: 'desc' } }], columns: [{ field: 'jobType' }], values: [{ field: 'hours', aggregation: 'sum', caption: 'Hours' }], }, options: { columnSubtotals: false }, }, 'First-time fix rate': { version: 1, slice: { rows: [{ field: 'jobType' }], columns: [{ field: 'region' }], values: [{ field: 'firstTimeFix', aggregation: 'avg', caption: 'First-time fix' }], }, formats: { firstTimeFix: { style: 'percent', decimals: 0 } }, }, }; ``` ## Save to localStorage `localStorage` can throw: in private windows, when storage is full, or when the user has blocked site data. Wrap every access so the report keeps working without it. ```ts title="layout-store.ts" import type { PivotReport } from '@birchui/pivot-studio'; const STORAGE_KEY = 'work-orders:pivot-layouts'; export function readLayouts(): Record { try { const text = window.localStorage.getItem(STORAGE_KEY); const parsed: unknown = text ? JSON.parse(text) : {}; return parsed && typeof parsed === 'object' ? (parsed as Record) : {}; } catch { return {}; } } export function writeLayouts(layouts: Record): boolean { try { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(layouts)); return true; } catch { return false; } } ``` ## Wire up the picker ```ts title="work-order-report.ts" import { createPivotStudio } from '@birchui/pivot-studio'; import { BUILT_IN_LAYOUTS } from './work-order-layouts'; import { readLayouts, writeLayouts } from './layout-store'; const picker = document.querySelector('#layout-picker')!; const nameInput = document.querySelector('#layout-name')!; let saved = readLayouts(); const allLayouts = () => ({ ...BUILT_IN_LAYOUTS, ...saved }); function renderPicker(selected: string) { picker.replaceChildren(...Object.keys(allLayouts()).map((name) => new Option(name, name, false, name === selected))); } const studio = createPivotStudio(document.querySelector('#work-orders')!, { data: workOrders, report: BUILT_IN_LAYOUTS['Revenue by depot'], fileName: 'work-orders-h2-2026', }); picker.addEventListener('change', () => studio.setReport(allLayouts()[picker.value])); document.querySelector('#save-layout')!.addEventListener('click', () => { const name = nameInput.value.trim(); if (!name) return; saved = { ...saved, [name]: studio.getReport() }; writeLayouts(saved); renderPicker(name); }); renderPicker('Revenue by depot'); ``` ## Save to a server For layouts that follow the user across devices, or that a team shares, store them on your server. Clean reports with `normalizeReport()` before you store them, so a hand-edited or outdated report never reaches the database: ```ts title="server/layouts.ts" import { normalizeReport, type PivotReport } from '@birchui/pivot-studio'; export async function saveLayout(userId: string, name: string, body: unknown): Promise { const report = normalizeReport(body, (message) => logger.warn({ userId, name }, message)); await db.pivotLayouts.upsert({ userId, name, report: JSON.stringify(report), updatedAt: new Date() }); return report; } ``` In the browser, replace `writeLayouts` with a request: ```ts title="layout-api.ts" import type { PivotReport } from '@birchui/pivot-studio'; export async function saveLayoutToServer(name: string, report: PivotReport): Promise { const response = await fetch(`/api/pivot-layouts/${encodeURIComponent(name)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(report), }); if (!response.ok) throw new Error(`Layout "${name}" could not be saved (${response.status})`); } export async function loadLayoutsFromServer(): Promise> { const response = await fetch('/api/pivot-layouts'); return response.ok ? ((await response.json()) as Record) : {}; } ``` To remember the layout a user was last looking at, save on `reportChange` with a debounce, as in [Saving and loading reports](https://docs.birchui.com/pivot-studio/saving-reports.md#saving-and-loading). ## How it works - `getReport()` returns the whole layout: fields in each zone, filters, sorts, number formats, conditional formats, layout options and which members are expanded. - `setReport(report)` replaces the layout and recomputes the table without reloading the data. - Reports are validated on load. Fields that no longer exist are ignored with a console warning, so an old layout never breaks the widget. ## Pitfalls - **Renamed fields.** Layouts refer to field names. When you rename a column in your data, migrate stored layouts or keep the old name as an alias column. See the tip in [Saving and loading reports](https://docs.birchui.com/pivot-studio/saving-reports.md#robust-loading). - **Several datasets.** If one page can show different datasets, store the dataset id in `dataSource.ref` and load the matching data before calling `setReport()`. See [The data source reference](https://docs.birchui.com/pivot-studio/saving-reports.md#the-data-source-reference). - **Saving on every change.** `reportChange` fires several times while a chip is dragged. Save named layouts on an explicit action, and debounce automatic saves. ## Related - [Saving and loading reports](https://docs.birchui.com/pivot-studio/saving-reports.md) for every key of the report format. - [Load pivot data from an API or CSV](https://docs.birchui.com/recipes/pivot-from-api.md). - [Pivot Studio API](https://docs.birchui.com/pivot-studio/api.md). --- Source: https://docs.birchui.com/recipes/pivot-from-api/ # Load pivot data from an API or CSV > Fetch records from a JSON API or a CSV export, clean them with parseCsv or csvToRecords, and load them into Pivot Studio with loading and error states. Pivot Studio never fetches data itself: you hand it records or text. This recipe loads work orders from a JSON endpoint, falls back to a nightly CSV export, fixes the column types and date formats that automatic detection gets wrong, and shows loading and error states. ## Steps 1. Create the studio with an empty array and a saved report. 2. Fetch the data with an `AbortController`, so a second request cancels the first. 3. For CSV, parse it with `csvToRecords()` and force the types of code columns. 4. Convert dates that are not ISO, such as `14/03/2026`, before loading. 5. Call `setData(records)` and report the row count from `dataLoaded`. ## Fetch and load ```ts title="work-order-pivot.ts" import { createPivotStudio, csvToRecords, type PivotReport } from '@birchui/pivot-studio'; interface WorkOrder { orderNo: string; depot: string; technician: string; jobType: string; completedOn: string; hours: number; revenue: number; } const report: PivotReport = { slice: { rows: [{ field: 'depot' }, { field: 'technician' }], columns: [{ field: 'completedOn.quarter' }], values: [{ field: 'revenue', aggregation: 'sum' }, { field: 'hours', aggregation: 'sum' }], }, formats: { revenue: { style: 'currency', currency: 'GBP', decimals: 0 } }, }; const status = document.querySelector('#pivot-status')!; const studio = createPivotStudio(document.querySelector('#work-order-pivot')!, { data: [], report, fields: [ { name: 'orderNo', type: 'string', caption: 'Work order' }, { name: 'completedOn', dateParts: ['year', 'quarter', 'month'] }, ], }); studio.on('dataLoaded', ({ rowCount }) => { status.textContent = `${rowCount.toLocaleString()} work orders loaded`; }); studio.on('error', ({ message }) => { status.textContent = `${message}. The previous data is still shown.`; }); let controller: AbortController | undefined; export async function loadWorkOrders(from: string, to: string): Promise { controller?.abort(); controller = new AbortController(); status.textContent = 'Loading work orders…'; try { const response = await fetch(`/api/work-orders?from=${from}&to=${to}`, { signal: controller.signal }); if (!response.ok) throw new Error(`The work order API returned ${response.status}`); studio.setData((await response.json()) as WorkOrder[]); } catch (error) { if ((error as Error).name === 'AbortError') return; await loadFromCsvExport(); } } ``` ## Load a CSV export `csvToRecords()` detects the delimiter, reads the header row and converts each column to its detected type. Pass `types` for columns that look numeric but are codes: ```ts title="csv-fallback.ts" const UK_DATE = /^(\d{2})\/(\d{2})\/(\d{4})$/; function toIsoDate(value: unknown): unknown { const match = typeof value === 'string' ? UK_DATE.exec(value) : null; return match ? `${match[3]}-${match[2]}-${match[1]}` : value; } async function loadFromCsvExport(): Promise { const text = await fetch('/exports/work-orders-latest.csv').then((r) => r.text()); const { records, columns, delimiter } = csvToRecords(text, { types: { orderNo: 'string', depotCode: 'string', completedOn: 'string' }, }); for (const record of records) record.completedOn = toIsoDate(record.completedOn); console.info(`Read ${records.length} rows with ${columns.length} columns, separated by "${delimiter}"`); studio.setData(records as unknown as WorkOrder[]); } ``` `completedOn` is read as text first, so the conversion sees the original `dd/mm/yyyy` string; after `setData()` the ISO dates are detected as dates and get the year, quarter and month levels the report uses. ## Work with raw rows When a file needs more cleanup than a type override, read it as rows with `parseCsv()`: ```ts title="parse-rows.ts" import { parseCsv, sniffDelimiter } from '@birchui/pivot-studio'; const delimiter = sniffDelimiter(text); const [header, ...rows] = parseCsv(text, { delimiter }); const hoursColumn = header.indexOf('Hours worked'); const records = rows .filter((row) => row[0] !== '' && !row[0].startsWith('Total')) .map((row) => ({ orderNo: row[0], depot: row[1], technician: row[2], hours: Number(row[hoursColumn].replace(',', '.')), })); ``` This handles exports with summary rows at the bottom and decimal commas, which a plain type override cannot. ## Pass the text straight in If the CSV is already clean, skip the parsing step: `setData(text)` accepts CSV and JSON text and uses the same parser. ```ts studio.setData(await fetch('/exports/work-orders-latest.csv').then((r) => r.text()), { format: 'csv' }); ``` ## Pitfalls - **Leading zeros.** Codes such as `007` stay text automatically, but codes without leading zeros, such as depot `1042`, are detected as numbers and summed. Force them to `'string'` with `types` or a field definition. - **Dates in local notation.** Only ISO dates are detected as dates. Convert `dd/mm/yyyy` or `mm/dd/yyyy` text before loading. - **Errors keep old data.** When text cannot be parsed, the widget keeps its previous data and fires `error`. Show the message so users know the view is stale. - **Mutating records.** If you change record objects after loading, call `refresh()` so the widget re-reads them. ## Related - [Data](https://docs.birchui.com/pivot-studio/data.md) for detection rules and [field definitions](https://docs.birchui.com/pivot-studio/data.md#field-definitions). - [CSV parsing rules](https://docs.birchui.com/pivot-studio/data.md#csv). - [Save and load pivot layouts](https://docs.birchui.com/recipes/pivot-saved-layouts.md). **`CsvRecordsOptions`** (interface from `@birchui/pivot-studio`, full reference: https://docs.birchui.com/api/pivot-studio.md) ```ts interface CsvRecordsOptions ``` | Property | Type | Description | | --- | --- | --- | | `delimiter?` | `string` | | | `header?` | `boolean` | | | `types?` | `Record` | | | `limits?` | `Partial` | | --- Source: https://docs.birchui.com/recipes/scheduler-drag-validation/ # Validate scheduler drag and drop > Combine validateDrop and validateResize to block double bookings, keep jobs inside working hours and only assign work to qualified technicians. A dispatcher drags jobs between technicians all day. Three rules keep the plan valid: a technician cannot be in two places at once, jobs stay inside working hours, and a job only goes to someone qualified for it. This recipe enforces all three with `validateDrop` and `validateResize`, and tells the dispatcher which rule blocked a move. **Live demo: Drag validation: overlaps, working hours and trades** (runs on the HTML version of this page). Source of `demos/recipe-scheduler-drag-validation.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createScheduler, type DropContext, type ResizeContext } from '@birchui/scheduler'; import { docsTheme, layout, onDocsThemeChange } from './_shared'; import { WEEK_START, serviceJobs, technicians, type ServiceJob, type Technician } from './_scheduler-data'; export const meta = { title: 'Drag validation: overlaps, working hours and trades', height: 480 }; const WORK_START_HOUR = 8; const WORK_END_HOUR = 18; const ELECTRICAL_JOBS = new Set(['tech-sam', 'tech-nora', 'tech-ben']); interface TradeJob extends ServiceJob { trade: string; } function withinWorkingHours(start: Date, end: Date): boolean { const last = new Date(end.getTime() - 1); const startHour = start.getHours() + start.getMinutes() / 60; const endHour = end.getHours() + end.getMinutes() / 60 || 24; return start.toDateString() === last.toDateString() && startHour >= WORK_START_HOUR && endHour <= WORK_END_HOUR; } export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); toolbar.append( 'Try to drop a job onto another job, outside 08:00 to 18:00, or onto a technician from the other team. Rejected positions turn red.', ); const end = new Date(WEEK_START); end.setDate(end.getDate() + 5); const jobs: TradeJob[] = serviceJobs().map((job) => ({ ...job, trade: ELECTRICAL_JOBS.has(job.resourceId) ? 'elec' : 'hvac', })); let lastReason = ''; const overlaps = (id: string, start: Date, finish: Date, resourceId: string) => scheduler.getEventsInRange(start, finish, resourceId).some((other) => other.id !== id); function reasonForDrop({ event, start, end: finish, resourceId, resource }: DropContext) { if (!resource?.parentId) return 'Jobs can only be assigned to a technician, not a team.'; if (resource.parentId !== event.trade) return `${resource.name} is not qualified for ${event.title.toLowerCase()}.`; if (!withinWorkingHours(start, finish)) return 'Jobs must stay within 08:00 to 18:00 on one day.'; if (overlaps(event.id, start, finish, resourceId)) return `${resource.name} already has a job at that time.`; return ''; } function reasonForResize({ event, start, end: finish }: ResizeContext) { if (!withinWorkingHours(start, finish)) return 'Jobs must stay within 08:00 to 18:00 on one day.'; if (overlaps(event.id, start, finish, event.resourceId)) return 'The new length overlaps another job.'; return ''; } const scheduler = createScheduler(body, { resources: technicians, events: jobs, start: WEEK_START, end, viewPreset: 'hourAndDay', snap: 15, createOnDrag: false, workingTime: { days: [1, 2, 3, 4, 5], startHour: WORK_START_HOUR, endHour: WORK_END_HOUR }, validateDrop: (context) => { lastReason = reasonForDrop(context); return lastReason === ''; }, validateResize: (context) => { lastReason = reasonForResize(context); return lastReason === ''; }, theme: docsTheme(), height: '100%', ariaLabel: 'Field service schedule with drag validation', }); const onPointerUp = () => { if (lastReason) status.textContent = `Rejected: ${lastReason}`; lastReason = ''; }; body.addEventListener('pointerup', onPointerUp); const offs = [ scheduler.on('eventDrop', ({ event, resourceId }) => { lastReason = ''; status.textContent = `${event.title} accepted for ${scheduler.getResourceById(resourceId)?.name ?? resourceId}.`; }), scheduler.on('eventResize', ({ event }) => { lastReason = ''; status.textContent = `${event.title} resized.`; }), ]; status.textContent = 'Validation results appear here.'; const stopTheme = onDocsThemeChange((theme) => scheduler.update({ theme })); return () => { body.removeEventListener('pointerup', onPointerUp); for (const off of offs) off(); stopTheme(); scheduler.destroy(); }; } ``` ## Steps 1. Add the fields your rules need to your event and resource types, such as a job's `trade` and a technician's team. 2. Write each rule as a small function that returns a reason, or an empty string when the change is allowed. 3. Call the rules from `validateDrop` and `validateResize`, and return `false` when any of them gives a reason. 4. Show the reason after the pointer is released. Validators run on every snapped position during a drag, so they must not show messages themselves. ## The rules ```ts title="dispatch-rules.ts" import type { SchedulerApi, SchedulerEvent, SchedulerResource } from '@birchui/scheduler'; export interface Technician extends SchedulerResource { trades: string[]; } export interface WorkOrder extends SchedulerEvent { trade: 'hvac' | 'electrical' | 'plumbing'; customer: string; } const WORK_START_HOUR = 8; const WORK_END_HOUR = 18; export function outsideWorkingHours(start: Date, end: Date): string { const last = new Date(end.getTime() - 1); const startHour = start.getHours() + start.getMinutes() / 60; const endHour = end.getHours() + end.getMinutes() / 60 || 24; const sameDay = start.toDateString() === last.toDateString(); return sameDay && startHour >= WORK_START_HOUR && endHour <= WORK_END_HOUR ? '' : 'Work orders must stay within 08:00 to 18:00 on one day.'; } export function notQualified(job: WorkOrder, technician: Technician | undefined): string { if (!technician) return 'Work orders can only be assigned to a technician.'; return technician.trades.includes(job.trade) ? '' : `${technician.name} is not qualified for ${job.trade} work.`; } export function doubleBooked( scheduler: SchedulerApi, jobId: string, start: Date, end: Date, technicianId: string, ): string { const clash = scheduler.getEventsInRange(start, end, technicianId).find((other) => other.id !== jobId); return clash ? `Clashes with ${clash.title} for ${clash.customer}.` : ''; } ``` ## Apply them ```ts title="dispatch-board.ts" import { createScheduler } from '@birchui/scheduler'; import { doubleBooked, notQualified, outsideWorkingHours, type Technician, type WorkOrder } from './dispatch-rules'; let rejection = ''; const scheduler = createScheduler(document.querySelector('#dispatch')!, { resources: technicians, events: workOrders, start: '2026-12-07', end: '2026-12-12', viewPreset: 'hourAndDay', snap: 15, workingTime: { days: [1, 2, 3, 4, 5], startHour: 8, endHour: 18 }, validateDrop: ({ event, start, end, resourceId, resource }) => { rejection = notQualified(event, resource) || outsideWorkingHours(start, end) || doubleBooked(scheduler, event.id, start, end, resourceId); return rejection === ''; }, validateResize: ({ event, start, end }) => { rejection = outsideWorkingHours(start, end) || doubleBooked(scheduler, event.id, start, end, event.resourceId); return rejection === ''; }, }); scheduler.element.addEventListener('pointerup', () => { if (rejection) showToast(rejection); rejection = ''; }); ``` The validators refer to `scheduler`, which is safe: they run only during user interaction, after `createScheduler` has returned. ## How it works - While the user drags, the validator runs on every snapped position. A rejected position turns the drag preview red, and releasing there leaves the event where it was. No `eventDrop` or `eventResize` is emitted for a rejected change. - The `||` chain stops at the first rule that fails, so the cheapest checks go first and the range query runs last. - `rejection` holds the reason from the last position checked. When the pointer is released on a valid position, the last check passed and the string is empty, so no message is shown. - Keyboard moves (Alt + arrow keys) run the same validators once per step. ## Pitfalls - **Validators must be synchronous.** For checks only the server can make, accept the move and roll back in the `eventDrop` listener. See [Server-side checks](https://docs.birchui.com/scheduler/interactions.md#server-side-checks) and [Save scheduler changes to a server](https://docs.birchui.com/recipes/scheduler-save-to-server.md). - **Ignore the event itself.** `getEventsInRange` returns the job being dragged at its old position too. Always filter it out by id. - **Time zones.** `getHours()` reads the browser's zone. If the scheduler has a `timeZone` option, read the hour in that zone, as in [Keep jobs inside working hours](https://docs.birchui.com/scheduler/interactions.md#keep-jobs-inside-working-hours). - **New events.** `validateDrop` does not run for drag-to-create. Run the same rules in your `eventCreate` listener before calling `addEvent`. - **Throwing validators** are logged with `console.error` and reject the change. ## Related - [Validation](https://docs.birchui.com/scheduler/interactions.md#validation) in the interactions guide. - [Working time](https://docs.birchui.com/scheduler/working-time.md) for shading non-working hours. - [Recurring jobs](https://docs.birchui.com/recipes/scheduler-recurring-jobs.md), where validators also apply to occurrences. **`DropContext`** (interface from `@birchui/scheduler`, full reference: https://docs.birchui.com/api/scheduler.md) ```ts interface DropContext ``` | Property | Type | Description | | --- | --- | --- | | `event` | `TEvent` | | | `start` | `Date` | | | `end` | `Date` | | | `resourceId` | `string` | | | `resource` | `TResource \| undefined` | | | `previous` | `{ start: Date; end: Date; resourceId: string }` | | --- Source: https://docs.birchui.com/recipes/scheduler-recurring-jobs/ # Schedule recurring maintenance jobs > Model planned maintenance with SchedulerEvent.rrule and exdates, let users edit one occurrence or the whole series, and store detached occurrences. Planned preventive maintenance repeats: a boiler check every Monday, Wednesday and Friday, a daily visit to a dental practice. This recipe stores each series once with an RFC 5545 rule, lets dispatchers move a single visit or the whole series, and shows how to save the resulting data. **Live demo: Recurring maintenance jobs** (runs on the HTML version of this page). Source of `demos/recipe-scheduler-recurring.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createScheduler, type EditScope } from '@birchui/scheduler'; import { docsTheme, field, layout, onDocsThemeChange } from './_shared'; import { WEEK_START, at, technicians, type ServiceJob, type Technician } from './_scheduler-data'; export const meta = { title: 'Recurring maintenance jobs', height: 480 }; function recurringJobs(): ServiceJob[] { return [ { id: 'ppm-riverside', resourceId: 'tech-ana', title: 'Planned maintenance: Riverside Dental', customer: 'Riverside Dental', start: at(0, 8), end: at(0, 10), rrule: 'FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR', }, { id: 'ppm-northside', resourceId: 'tech-omar', title: 'Boiler check: Northside School', customer: 'Northside School', start: at(0, 13), end: at(0, 15), rrule: 'FREQ=WEEKLY;BYDAY=MO,WE,FR', exdates: [at(2, 13)], }, { id: 'ppm-chargers', resourceId: 'tech-sam', title: 'Charger inspection: Cedar & Stone', customer: 'Cedar & Stone', start: at(1, 9), end: at(1, 11), rrule: 'FREQ=WEEKLY;BYDAY=TU,TH', }, { id: 'job-inverter', resourceId: 'tech-nora', title: 'Inverter swap', customer: 'Alpine Outfitters', start: at(0, 13), end: at(0, 17), }, ]; } const time = (d: Date) => d.toLocaleString('en-GB', { weekday: 'short', hour: '2-digit', minute: '2-digit' }); export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const wholeSeries = document.createElement('input'); wholeSeries.type = 'checkbox'; toolbar.append( field('Apply to the whole series', wholeSeries), 'Drag or resize an occurrence, or select one and press Delete.', ); const end = new Date(WEEK_START); end.setDate(end.getDate() + 5); const scheduler = createScheduler(body, { resources: technicians, events: recurringJobs(), start: WEEK_START, end, viewPreset: 'hourAndDay', snap: 15, createOnDrag: false, theme: docsTheme(), height: '100%', ariaLabel: 'Recurring maintenance schedule', }); const chosenScope = (): EditScope => (wholeSeries.checked ? 'all' : 'this'); const describe = (scope: EditScope) => (scope === 'all' ? 'every occurrence' : 'this occurrence only'); const offs = [ scheduler.on('eventDrop', (change) => { if (!change.occurrence) { status.textContent = `${change.event.title} moved to ${time(change.start)}.`; return; } change.scope = chosenScope(); status.textContent = `Moved ${describe(change.scope)} of ${change.occurrence.event.title} from ${time(change.occurrence.start)} to ${time(change.start)}.`; }), scheduler.on('eventResize', (change) => { if (!change.occurrence) return; change.scope = chosenScope(); status.textContent = `Resized ${describe(change.scope)} of ${change.occurrence.event.title}.`; }), scheduler.on('eventRemove', (change) => { if (!change.occurrence) { status.textContent = `${change.event.title} removed.`; return; } change.scope = chosenScope(); const series = scheduler.getEventById(change.occurrence.id); const skipped = (series?.exdates?.length ?? 0) + (change.scope === 'this' ? 1 : 0); status.textContent = change.scope === 'all' ? `Removed the series ${change.occurrence.event.title}.` : `Skipped ${time(change.occurrence.start)}. The series now has ${skipped} exception dates.`; }), ]; status.textContent = 'Changes to recurring jobs appear here.'; const stopTheme = onDocsThemeChange((theme) => scheduler.update({ theme })); return () => { for (const off of offs) off(); stopTheme(); scheduler.destroy(); }; } ``` ## Steps 1. Give the master event an `rrule`, and optionally `exdates` for visits that are skipped. 2. In `eventDrop`, `eventResize` and `eventRemove`, check for `occurrence` and set `scope` to `'this'` or `'all'`. 3. Persist the masters and any detached occurrences, matched by `recurringEventId` and `recurrenceId`. ## Define a series ```ts title="maintenance-plan.ts" import type { SchedulerEvent } from '@birchui/scheduler'; interface MaintenanceJob extends SchedulerEvent { site: string; contractRef: string; } export const maintenanceJobs: MaintenanceJob[] = [ { id: 'ppm-northside', resourceId: 'tech-omar', title: 'Boiler check', site: 'Northside School', contractRef: 'PPM-2026-118', start: '2026-12-07T13:00', end: '2026-12-07T15:00', rrule: 'FREQ=WEEKLY;BYDAY=MO,WE,FR;UNTIL=20270331T150000', exdates: ['2026-12-23T13:00', '2026-12-25T13:00'], }, { id: 'ppm-riverside', resourceId: 'tech-ana', title: 'Daily plant room check', site: 'Riverside Dental', contractRef: 'PPM-2026-131', start: '2026-12-07T08:00', end: '2026-12-07T08:45', rrule: 'FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR', }, ]; ``` `start` and `end` describe the first visit; the rule repeats it. The rules are read by the same engine as `@birchui/calendar`, so `FREQ`, `INTERVAL`, `COUNT`, `UNTIL`, `BYDAY` (including `1MO` and `-1FR`), `BYMONTHDAY`, `BYMONTH` and `BYSETPOS` all work. Occurrences are generated only for the visible range. Each occurrence is shown as an event with the id `'@'`, such as `'ppm-northside@2026-12-09T13:00:00'`, and carries `recurringEventId` (the series id) and `recurrenceId` (its original start). `getEvents()` returns the series once; `getEventById` and `getEventsInRange` also find occurrences. ## Ask for the scope When a user drags, resizes or deletes an occurrence, the event payload has an `occurrence` and `scope: 'this'`. The change is applied after your listener returns, with whatever `scope` the payload has then: ```ts title="recurring-edits.ts" import type { EditScope } from '@birchui/scheduler'; const wholeSeries = document.querySelector('#apply-to-series')!; const chosenScope = (): EditScope => (wholeSeries.checked ? 'all' : 'this'); scheduler.on('eventDrop', (change) => { if (change.occurrence) change.scope = chosenScope(); }); scheduler.on('eventResize', (change) => { if (change.occurrence) change.scope = chosenScope(); }); scheduler.on('eventRemove', (change) => { if (!change.occurrence) return; change.scope = window.confirm(`Cancel every visit of ${change.occurrence.event.title}?`) ? 'all' : 'this'; }); ``` | Scope | Move or resize | Remove | | --- | --- | --- | | `'this'` | Adds the occurrence's `recurrenceId` to the series' `exdates` and adds a detached event for the moved visit. | Adds the occurrence to `exdates`. | | `'all'` | Shifts the whole series by the same amount. Moving to another weekday shifts `BYDAY` and the existing `exdates` with it. | Removes the series. | The `occurrence` object describes the visit that was touched: **`SchedulerOccurrence`** (interface from `@birchui/scheduler`, full reference: https://docs.birchui.com/api/scheduler.md) ```ts interface SchedulerOccurrence ``` | Property | Type | Description | | --- | --- | --- | | `id` | `string` | | | `occurrenceId` | `string` | | | `recurrenceId` | `string` | | | `start` | `Date` | | | `end` | `Date` | | | `event` | `TEvent` | | `occurrence.event` is the master; `occurrence.start` and `occurrence.end` are the visit's times before the change. ## The detached occurrence With scope `'this'`, the moved visit becomes its own event: a copy of the master without `rrule` and `exdates`, with the occurrence id, `recurringEventId` and `recurrenceId`: ```json { "id": "ppm-northside@2026-12-09T13:00:00", "resourceId": "tech-omar", "title": "Boiler check", "site": "Northside School", "contractRef": "PPM-2026-118", "start": "2026-12-09T15:30:00.000Z", "end": "2026-12-09T17:30:00.000Z", "recurringEventId": "ppm-northside", "recurrenceId": "2026-12-09T13:00:00" } ``` Store detached events next to their master. When you load the schedule again, pass both: the master's `exdates` hide the original visit and the detached event shows the moved one. ## Save the result The payloads of `eventDrop` and friends fire **before** the change is applied, so they cannot tell you the final master. Persist from `historyChange` instead, which reports every event that changed, including both halves of a detached edit: ```ts title="persist-recurring.ts" scheduler.on('historyChange', ({ action, changes }) => { if (action === 'clear') return; for (const { id, after } of changes) { if (after) void api.put(`/api/maintenance-jobs/${encodeURIComponent(id)}`, after); else void api.delete(`/api/maintenance-jobs/${encodeURIComponent(id)}`); } }); ``` A `'this'` move produces two changes: the master with a new `exdates` entry, and the new detached event. See [Save scheduler changes to a server](https://docs.birchui.com/recipes/scheduler-save-to-server.md) for batching and error handling. ## Edit from code `updateEvent(occurrenceId, patch)` and `removeEvent(occurrenceId)` edit a single occurrence the same way scope `'this'` does. To change the series, update the master by its own id: ```ts scheduler.updateEvent('ppm-northside@2026-12-16T13:00:00', { resourceId: 'tech-li' }); scheduler.removeEvent('ppm-riverside@2026-12-24T08:00:00'); scheduler.updateEvent('ppm-riverside', { rrule: 'FREQ=WEEKLY;BYDAY=MO,WE,FR' }); ``` ## Pitfalls - **Set `scope` synchronously.** The scheduler reads it as soon as your listener returns. For an asynchronous dialog, leave scope at `'this'`; if the user then picks the whole series, call `undo()` to revert the single-visit edit and change the master with `updateEvent`. - **`historyChange` needs history.** It does not fire when `undoRedo` is `false`. - **Invalid rules.** An `rrule` that cannot be parsed shows the event once, with a console warning. Unsupported rule parts are ignored with a warning. - **Wall-clock time.** Occurrences keep their wall-clock time in the scheduler's `timeZone` across daylight saving changes. ## Related - [Recurrence in the Event Calendar](https://docs.birchui.com/calendar/recurrence.md#editing-occurrences), which follows the same rules. - [iCalendar feeds](https://docs.birchui.com/recipes/calendar-ical-feed.md), which read and write the same detached-occurrence shape. - [Undo and redo in the scheduler](https://docs.birchui.com/recipes/scheduler-undo-redo.md). --- Source: https://docs.birchui.com/recipes/scheduler-undo-redo/ # Undo and redo in the scheduler > Turn on scheduler history with the undoRedo option, add undo and redo buttons driven by historyChange, and keep a server in step when users undo. Dispatchers move many jobs in a row and sometimes move the wrong one. The scheduler records moves, resizes, removals and API edits, and undoes them with Ctrl + Z. This recipe adds toolbar buttons, a history limit, and persistence that also covers undo and redo. **Live demo: Undo and redo schedule changes** (runs on the HTML version of this page). Source of `demos/recipe-scheduler-undo-redo.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createScheduler } from '@birchui/scheduler'; import { button, docsTheme, layout, onDocsThemeChange } from './_shared'; import { WEEK_START, serviceJobs, technicians, type ServiceJob, type Technician } from './_scheduler-data'; export const meta = { title: 'Undo and redo schedule changes', height: 480 }; export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); const end = new Date(WEEK_START); end.setDate(end.getDate() + 5); const scheduler = createScheduler(body, { resources: technicians, events: serviceJobs(), start: WEEK_START, end, viewPreset: 'hourAndDay', snap: 15, createOnDrag: false, undoRedo: { limit: 50 }, theme: docsTheme(), height: '100%', ariaLabel: 'Field service schedule with undo and redo', }); const undoButton = button('Undo', () => scheduler.undo()); const redoButton = button('Redo', () => scheduler.redo()); const clearButton = button('Clear history', () => scheduler.clearHistory()); const sync = () => { undoButton.disabled = !scheduler.canUndo(); redoButton.disabled = !scheduler.canRedo(); }; toolbar.append(undoButton, redoButton, clearButton, 'Move or resize jobs, then step back and forward.'); sync(); const offs = [ scheduler.on('historyChange', ({ action, kind, changes }) => { sync(); if (action === 'clear') { status.textContent = 'History cleared.'; return; } const titles = changes.map(({ before, after }) => (after ?? before)?.title ?? 'job').join(', '); const verb = action === 'record' ? 'Recorded' : action === 'undo' ? 'Undid' : 'Redid'; status.textContent = `${verb} ${kind ?? 'change'}: ${titles}.`; }), ]; status.textContent = 'History changes appear here.'; const stopTheme = onDocsThemeChange((theme) => scheduler.update({ theme })); return () => { for (const off of offs) off(); stopTheme(); scheduler.destroy(); }; } ``` ## Steps 1. Set `undoRedo` to `true` (the default, 100 steps) or `{ limit }`. 2. Call `undo()` and `redo()` from your buttons, and enable them from `canUndo()` and `canRedo()`. 3. Update the buttons in a `historyChange` listener, which fires after every recorded change, undo, redo and clear. 4. Persist from `historyChange` too, because undo and redo do not emit `eventDrop` or `eventResize`. ## Buttons ```ts title="dispatch-history.ts" import { createScheduler } from '@birchui/scheduler'; const scheduler = createScheduler(document.querySelector('#dispatch')!, { resources: technicians, events: workOrders, start: '2026-12-07', end: '2026-12-12', viewPreset: 'hourAndDay', undoRedo: { limit: 50 }, }); const undoButton = document.querySelector('#undo')!; const redoButton = document.querySelector('#redo')!; function syncButtons() { undoButton.disabled = !scheduler.canUndo(); redoButton.disabled = !scheduler.canRedo(); } undoButton.addEventListener('click', () => scheduler.undo()); redoButton.addEventListener('click', () => scheduler.redo()); scheduler.on('historyChange', syncButtons); syncButtons(); ``` `undo()` and `redo()` return `false` when there is nothing to undo or redo. The keyboard shortcuts work while focus is inside the scheduler: Ctrl + Z to undo, Ctrl + Shift + Z or Ctrl + Y to redo (Cmd on macOS). ## The historyChange payload | Field | Description | | --- | --- | | `action` | `'record'` for a new change, `'undo'`, `'redo'` or `'clear'`. | | `kind` | `'move'`, `'resize'`, `'add'`, `'update'` or `'remove'`; `null` for `'clear'`. | | `changes` | `{ id, before, after }` for every event touched. `after` is the event as it is now, or `null` once removed. | | `canUndo`, `canRedo` | Whether a step is available after this action. | For undo, `before` and `after` are already swapped, so `after` is always the current state. One user action can produce several changes: moving one occurrence of a recurring series changes the master and adds a detached event. ## Persist undo and redo ```ts title="persist-history.ts" scheduler.on('historyChange', ({ action, changes }) => { if (action !== 'undo' && action !== 'redo') return; for (const { id, after } of changes) { if (after) void api.put(`/api/work-orders/${encodeURIComponent(id)}`, after); else void api.delete(`/api/work-orders/${encodeURIComponent(id)}`); } }); ``` If you already save from `eventDrop` and `eventResize`, add only this listener for undo and redo. To save everything in one place, handle `'record'` the same way; see [Save scheduler changes to a server](https://docs.birchui.com/recipes/scheduler-save-to-server.md). ## Clear the history Call `clearHistory()` when earlier steps no longer make sense, for example after the dispatcher publishes the day's plan to technicians: ```ts publishButton.addEventListener('click', async () => { await api.post('/api/dispatch/publish', { day: '2026-12-07' }); scheduler.clearHistory(); }); ``` `setEvents()` and `update({ events })` start a new history as well. ## What is recorded | Recorded | Not recorded | | --- | --- | | Drag, resize and keyboard moves | Changes rejected by `validateDrop` or `validateResize` | | Removing an event with Delete | Replacing all events with `setEvents()` | | `addEvent`, `updateEvent`, `removeEvent` | View changes: range, zoom, scrolling, selection | ## Pitfalls - **`undoRedo: false` turns off `historyChange`.** With no history, nothing is recorded and the event never fires. - **Rollback after a failed save is a new step.** When the server rejects a move and you call `updateEvent(id, previous)`, that call is itself recorded. Call `undo()` instead to remove the failed step from the history. - **Read-only mode.** Keyboard undo is ignored while the scheduler is `readOnly`. ## Related - [Save scheduler changes to a server](https://docs.birchui.com/recipes/scheduler-save-to-server.md). - [Scheduler API](https://docs.birchui.com/scheduler/api.md). **`UndoRedoOptions`** (interface from `@birchui/scheduler`, full reference: https://docs.birchui.com/api/scheduler.md) ```ts interface UndoRedoOptions ``` | Property | Type | Description | | --- | --- | --- | | `limit?` | `number` | | --- Source: https://docs.birchui.com/recipes/scheduler-save-to-server/ # Save scheduler changes to a server > Persist every scheduler edit from historyChange, batch requests, roll back changes the server rejects, and apply updates from other users without echoing them back. The scheduler applies a user's change to its own copy of the data and then tells you about it. Saving is up to you. This recipe sends each change to a REST API in small batches, undoes changes the server refuses, and applies changes pushed by other dispatchers without sending them back. ## Choose the events to listen to | Approach | Listen to | Use it when | | --- | --- | --- | | Per action | `eventDrop`, `eventResize`, `eventRemove`, plus `historyChange` for undo and redo | Your API has one endpoint per action, such as "reschedule job". | | Per change | `historyChange` only | Your API stores events. One listener covers moves, resizes, removals, API edits, undo, redo and recurring series. | This recipe uses the second approach. The first is shown in [Keeping a server in sync](https://docs.birchui.com/scheduler/resources-and-events.md#keeping-a-server-in-sync). ## Steps 1. Collect `{ id, after }` pairs from `historyChange` into a pending map, so several edits to one job become one request. 2. Flush the map after a short pause. 3. When the server rejects the batch, call `undo()` and tell the user. 4. Apply changes from other users with a flag set, so the listener skips them. ## Save in batches ```ts title="schedule-sync.ts" import type { SchedulerApi } from '@birchui/scheduler'; type JobPatch = { id: string; job: WorkOrder | null }; export function syncToServer(scheduler: SchedulerApi, notify: (message: string) => void) { const pending = new Map(); let timer: ReturnType | undefined; let applyingRemote = false; async function flush() { const batch: JobPatch[] = [...pending].map(([id, job]) => ({ id, job })); pending.clear(); if (batch.length === 0) return; const response = await fetch('/api/dispatch/jobs', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch), }); if (response.ok) return; const { message } = (await response.json().catch(() => ({ message: 'The change could not be saved.' }))) as { message: string; }; applyingRemote = true; scheduler.undo(); applyingRemote = false; notify(message); } const off = scheduler.on('historyChange', ({ action, changes }) => { if (action === 'clear' || applyingRemote) return; for (const { id, after } of changes) pending.set(id, after); clearTimeout(timer); timer = setTimeout(() => void flush(), 400); }); function applyRemote(update: JobPatch) { applyingRemote = true; try { if (!update.job) scheduler.removeEvent(update.id); else if (scheduler.getEventById(update.id)) scheduler.updateEvent(update.id, update.job); else scheduler.addEvent(update.job); } finally { applyingRemote = false; } } return { applyRemote, stop: off }; } ``` Wire it to a WebSocket or server-sent events stream: ```ts title="dispatch-board.ts" const sync = syncToServer(scheduler, showToast); const stream = new EventSource('/api/dispatch/stream'); stream.addEventListener('job', (message) => sync.applyRemote(JSON.parse(message.data))); ``` ## The server side The server receives the full event for each id, or `null` for a removal. Validate it there too: client-side rules can be bypassed. ```ts title="server/dispatch-jobs.ts" app.patch('/api/dispatch/jobs', async (request, response) => { const batch = request.body as { id: string; job: WorkOrder | null }[]; for (const { id, job } of batch) { if (job && (await jobs.overlapsForTechnician(job.resourceId, job.start, job.end, id))) { return response.status(409).json({ message: `${job.title} overlaps another job for this technician.` }); } } await db.transaction(async (tx) => { for (const { id, job } of batch) { if (job) await tx.jobs.upsert({ ...job, id }); else await tx.jobs.delete(id); } }); broadcast(batch); response.status(204).end(); }); ``` ## How it works - `historyChange` fires once per recorded step with every event it touched. `after` is the event as it is now, or `null` when it was removed, so one upsert-or-delete loop handles all kinds of edits. - Moving one occurrence of a recurring series yields two changes: the master with a new `exdates` entry, and the detached occurrence. Both are saved by the same loop. See [Schedule recurring maintenance jobs](https://docs.birchui.com/recipes/scheduler-recurring-jobs.md). - Because `undo()` reverses the last step, the rejected change disappears from the screen and from the history, and `historyChange` fires with `action: 'undo'`. The `applyingRemote` flag stops that undo from being sent back to the server. - Remote updates applied with `addEvent`, `updateEvent` and `removeEvent` are recorded in the history as well. Skipping them in the listener keeps the server from receiving its own data. ## Pitfalls - **History must be on.** `historyChange` does not fire with `undoRedo: false`. Keep the default or set a `limit`. - **Undo after several batches.** `undo()` reverses only the latest step. If the user made another change before the server answered, that change is undone instead. For busy boards, save each change on its own and roll back with `updateEvent(id, before)` from the `historyChange` payload. - **Remote updates join the user's undo stack.** A dispatcher pressing Ctrl + Z can undo a colleague's change. If that matters, call `setEvents()` with fresh data for large remote updates, which starts a new history. - **Dates on the wire.** `after.start` and `after.end` are `Date` objects after a drag. `JSON.stringify` writes them as UTC ISO strings. ## Related - [Validate scheduler drag and drop](https://docs.birchui.com/recipes/scheduler-drag-validation.md) to block invalid changes before they happen. - [Undo and redo in the scheduler](https://docs.birchui.com/recipes/scheduler-undo-redo.md). - [Updating data](https://docs.birchui.com/scheduler/resources-and-events.md#updating-data). --- Source: https://docs.birchui.com/recipes/gantt-ms-project-import/ # Import and export MS Project files > Let users open MS Project XML files in the Gantt with a preview step, keep your own task fields across a round trip, and export the schedule back to XML. Project managers keep plans in MS Project, ProjectLibre or a PPM tool and want to open them in your app, edit them, and send them back. This recipe adds an **Import** button with a preview of what the file contains, merges your own task fields back in after import, and exports the result as MS Project XML. ## Steps 1. Read the file as text and parse it with `readMSProjectXML()` to show a preview without touching the Gantt. 2. On confirmation, load it with `fromMSProjectXML()`, or with `fromJSON()` after merging your own fields. 3. Export with `toMSProjectXML()` and offer it as a download. ## Preview the file `readMSProjectXML(xml, warn?)` returns plain project data in the shape of `toJSON()` output, so you can inspect it before it replaces anything: ```ts title="project-import.ts" import { readMSProjectXML, type MspImportResult } from '@birchui/gantt'; export interface ImportPreview { data: MspImportResult; warnings: string[]; summary: string; } export async function previewProjectFile(file: File): Promise { const warnings: string[] = []; const data = readMSProjectXML(await file.text(), (message) => warnings.push(message)); const milestones = data.tasks.filter((task) => task.type === 'milestone').length; const summary = `${data.name ?? file.name}: ${data.tasks.length} tasks, ${milestones} milestones, ` + `${data.dependencies?.length ?? 0} links, ${data.calendars?.length ?? 0} calendars`; return { data, warnings, summary }; } ``` Text without a `` element throws a `SyntaxError`. Catch it to show a friendly message: ```ts title="import-button.ts" fileInput.addEventListener('change', async () => { const file = fileInput.files?.[0]; if (!file) return; try { const preview = await previewProjectFile(file); const ok = await confirmDialog(preview.summary, preview.warnings); if (ok) applyImport(preview.data); } catch (error) { showToast(error instanceof SyntaxError ? `${file.name} is not an MS Project XML file.` : String(error)); } finally { fileInput.value = ''; } }); ``` ## Keep your own fields MS Project XML does not carry your own task fields, task colors or `resourceIds`. The export writes your task ids to the **Text1** custom field and the import reads them back, so you can merge the fields you keep in your database by id: ```ts title="apply-import.ts" import type { GanttTask, MspImportResult } from '@birchui/gantt'; interface SiteTask extends GanttTask { costCode?: string; siteManager?: string; } function applyImport(data: MspImportResult) { const current = new Map((gantt.toJSON().tasks as SiteTask[]).map((task) => [task.id, task])); const tasks = data.tasks.map((task) => { const existing = current.get(task.id); return existing ? { ...task, costCode: existing.costCode, siteManager: existing.siteManager, color: existing.color } : task; }); gantt.fromJSON({ ...data, tasks }); } ``` If you do not need to merge anything, `gantt.fromMSProjectXML(xml)` parses and loads in one call. ## Export ```ts title="export-button.ts" function downloadProjectXml(fileName: string) { const xml = gantt.toMSProjectXML(); const url = URL.createObjectURL(new Blob([xml], { type: 'application/xml' })); const link = document.createElement('a'); link.href = url; link.download = fileName; link.click(); URL.revokeObjectURL(url); } exportButton.addEventListener('click', () => downloadProjectXml('warehouse-fit-out.xml')); ``` ## Convert on a server The reader and writer need no DOM. A route that accepts an upload and stores it as JSON: ```ts title="server/import-project.ts" import { createGanttProject } from '@birchui/gantt'; app.post('/api/projects/:id/import', async (request, response) => { const warnings: string[] = []; const project = createGanttProject({ timeZone: 'Europe/London', warn: (message) => warnings.push(message) }); try { project.fromMSProjectXML(await request.text()); } catch { return response.status(400).json({ error: 'The file is not MS Project XML.' }); } await db.projects.update(request.params.id, { data: project.toJSON() }); response.json({ finish: project.getProjectRange().end, warnings }); }); ``` ## Pitfalls - **Imports clear the undo history.** `fromMSProjectXML()` and `fromJSON()` replace the project. Ask for confirmation first, as above. - **Ids from other tools.** A file that never went through your app has no Text1 values, so task ids are the file's UIDs and links get ids such as `'survey->permit'`. Match by name or WBS if you need to merge such files. - **Percentage lags** are imported as no lag, with a warning. Show the warnings from the preview. - **Time zones.** Dates in MS Project XML have no zone. They are read and written as wall-clock time in the Gantt's `timeZone`, so set the same zone on the server and in the browser. - **Resources are not exchanged.** Keep assignments in your own data. See [What is not exchanged](https://docs.birchui.com/gantt/ms-project.md#what-is-not-exchanged). ## Related - [MS Project XML](https://docs.birchui.com/gantt/ms-project.md) for the full field mapping. - [Headless engine](https://docs.birchui.com/gantt/headless.md). - [Critical path report](https://docs.birchui.com/recipes/gantt-critical-path-report.md). --- Source: https://docs.birchui.com/recipes/gantt-critical-path-report/ # Build a critical path report > Use the headless Gantt engine to compute the critical path, slack and constraint conflicts of a project, and render them as a report or an Excel file. Steering meetings ask the same questions every week: when do we finish, which tasks drive that date, and how much room do the others have? This recipe answers them with `createGanttProject()`, the Gantt's scheduling engine without a user interface, so the report runs in a browser, a worker or a nightly job on a server. ## Steps 1. Load the project data into `createGanttProject()`. It is scheduled as soon as it is created. 2. Read the critical path with `getCriticalPath()` and the finish date with `getProjectRange()`. 3. Read each task's slack, early and late dates from `getTasks()`. 4. Write the result as a table, JSON, or an xlsx file. ## Compute the report ```ts title="critical-path-report.ts" import { createGanttProject, type ProjectData } from '@birchui/gantt'; export interface CriticalPathRow { wbs: string; name: string; start: Date; end: Date; totalSlackDays: number; freeSlackDays: number; isCritical: boolean; hasConflict: boolean; } export function criticalPathReport(data: ProjectData, timeZone = 'Europe/London') { const warnings: string[] = []; const project = createGanttProject({ ...data, timeZone, warn: (message) => warnings.push(message) }); const { taskIds } = project.getCriticalPath(); const range = project.getProjectRange(); const conflicts = project.lastResult?.conflicts ?? []; const rows: CriticalPathRow[] = project .getTasks() .filter((task) => task.type !== 'summary') .map((task) => ({ wbs: task.wbs, name: task.name, start: task.start, end: task.end, totalSlackDays: Math.round(task.totalSlack * 10) / 10, freeSlackDays: Math.round(task.freeSlack * 10) / 10, isCritical: task.isCritical, hasConflict: task.hasConflict === true, })) .sort((a, b) => a.totalSlackDays - b.totalSlackDays || a.start.getTime() - b.start.getTime()); return { name: data.name ?? 'Project', start: range.start, finish: range.end, criticalTasks: taskIds.map((id) => project.getTask(id)?.name ?? id), conflicts: conflicts.map((id) => project.getTask(id)?.name ?? id), rows, warnings, }; } ``` Sorting by total slack puts the critical tasks first, followed by the tasks closest to becoming critical. Tasks with negative slack, which are already late for a constraint, sort above everything else. ## Render it ```ts title="render-report.ts" const day = new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }); export function renderReport(host: HTMLElement, report: ReturnType) { host.innerHTML = ''; const heading = document.createElement('h2'); heading.textContent = `${report.name}: finish ${day.format(report.finish)}`; const table = document.createElement('table'); table.innerHTML = 'WBSTaskStartFinishTotal slack (days)'; const body = table.createTBody(); for (const row of report.rows) { const tr = body.insertRow(); tr.className = row.isCritical ? 'is-critical' : ''; for (const text of [row.wbs, row.name, day.format(row.start), day.format(row.end), String(row.totalSlackDays)]) { tr.insertCell().textContent = text; } } host.append(heading, table); } ``` ## Export to Excel The rows map directly onto an [Excel Engine](https://docs.birchui.com/excel/overview.md) workbook: ```ts title="report-xlsx.ts" import { writeXlsx, type XlsxWorkbook } from '@birchui/excel'; export function reportWorkbook(report: ReturnType): Promise { const header = { bold: true, fill: '#E8EEF7' }; const workbook: XlsxWorkbook = { title: `${report.name} critical path`, sheets: [ { name: 'Critical path', freeze: { rows: 1 }, autoFilter: true, columns: [ { width: 8 }, { width: 36 }, { width: 14, style: { numFmt: 'dd mmm yyyy' } }, { width: 14, style: { numFmt: 'dd mmm yyyy' } }, { width: 12, style: { numFmt: '0.0' } }, { width: 10 }, ], rows: [ ['WBS', 'Task', 'Start', 'Finish', 'Total slack', 'Critical'].map((value) => ({ value, style: header })), ...report.rows.map((row) => ({ cells: [row.wbs, row.name, row.start, row.end, row.totalSlackDays, row.isCritical], style: row.isCritical ? { color: '#B42318' } : undefined, })), ], }, ], }; return writeXlsx(workbook); } ``` ## Answer "what if" questions Edits on the headless project reschedule it like the widget does, so the report can compare scenarios: ```ts const project = createGanttProject({ ...data, timeZone: 'Europe/London' }); const before = project.getProjectRange().end; project.transaction('Steel delivery slips one week', () => { project.updateTask('steel-delivery', { duration: 15 }); }); const after = project.getProjectRange().end; const slipDays = (after.getTime() - before.getTime()) / 86_400_000; project.undo(); ``` `transaction()` makes several edits one scheduling run and one undo step, and `undo()` restores the original plan for the next scenario. ## Pitfalls - **Slack is in working days** of `hoursPerDay` hours, not calendar days. Pass the same `hoursPerDay`, `calendars` and `timeZone` as the Gantt your users see, or the numbers will differ. - **Summaries.** Summary tasks roll up their children; filter them out of task-level tables as above. - **Constraint conflicts.** A task whose constraint overrides its links has `hasConflict: true` and gives its predecessors negative slack. List `conflicts` separately so they are not mistaken for ordinary delays. - **Dates in Excel.** The Excel Engine writes `Date` values in UTC. See [Cells](https://docs.birchui.com/excel/writing.md#cells). ## Related - [Slack and the critical path](https://docs.birchui.com/gantt/scheduling.md#slack-and-the-critical-path). - [Scheduled fields](https://docs.birchui.com/gantt/tasks.md#scheduled-fields). - [Headless engine](https://docs.birchui.com/gantt/headless.md). - [Build a multi-sheet Excel report](https://docs.birchui.com/recipes/excel-report-workbook.md). --- Source: https://docs.birchui.com/recipes/spreadsheet-custom-functions/ # Add custom worksheet functions > Define reusable workbook functions with LAMBDA and defined names, share them across sheets, and test them with the headless formula engine. A costing sheet repeats the same calculation in every row: labour with overtime after eight hours, a total with VAT. Instead of copying a long formula down the column, define it once as a named `LAMBDA` and call it like a built-in function: `=LabourCost(C2, D2)`. The definitions live in the workbook, so they are saved with it, exported to xlsx and work in the headless engine. **Live demo: Custom worksheet functions with LAMBDA** (runs on the HTML version of this page). Source of `demos/recipe-spreadsheet-custom-functions.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs. ```ts import { createSpreadsheet, type CellJSON } from '@birchui/spreadsheet'; import { docsTheme, layout, onDocsThemeChange } from './_shared'; export const meta = { title: 'Custom worksheet functions with LAMBDA', height: 520 }; const header = { bold: true, fill: '#1f3a5f', color: '#ffffff' }; const money = { numberFormat: '#,##0.00' }; const workOrders: [string, string, number, number, number][] = [ ['WO-24101', 'Ana Ruiz', 6.5, 48, 120], ['WO-24102', 'Omar Haddad', 10, 52, 340.5], ['WO-24103', 'Li Wei', 3, 45, 0], ['WO-24104', 'Sam Patel', 9.25, 55, 612], ['WO-24105', 'Nora Lindqvist', 7.75, 50, 88.4], ['WO-24106', 'Ben Mensah', 12, 48, 1290], ]; function cells(): Record { const result: Record = { A1: { value: 'Work order', style: header }, B1: { value: 'Technician', style: header }, C1: { value: 'Hours', style: header }, D1: { value: 'Rate', style: header }, E1: { value: 'Parts', style: header }, F1: { value: 'Labour', style: header }, G1: { value: 'Total inc. VAT', style: header }, }; workOrders.forEach(([order, technician, hours, rate, parts], index) => { const r = index + 2; result[`A${r}`] = { value: order }; result[`B${r}`] = { value: technician }; result[`C${r}`] = { value: hours }; result[`D${r}`] = { value: rate, style: money }; result[`E${r}`] = { value: parts, style: money }; result[`F${r}`] = { formula: `=LabourCost(C${r}, D${r})`, style: money }; result[`G${r}`] = { formula: `=WithVat(F${r} + E${r})`, style: money }; }); const total = workOrders.length + 2; result[`A${total}`] = { value: 'Total', style: { bold: true } }; result[`G${total}`] = { formula: `=SUM(G2:G${total - 1})`, style: { ...money, bold: true } }; result.I1 = { value: 'VAT rate', style: { bold: true } }; result.J1 = { value: 0.2, style: { numberFormat: '0%' } }; result.I2 = { value: 'Overtime after', style: { bold: true } }; result.J2 = { value: 8 }; return result; } export default function mount(el: HTMLElement): () => void { const { toolbar, body, status } = layout(el); toolbar.append( 'Columns F and G call LabourCost and WithVat, two workbook functions defined with LAMBDA. Change hours, rates or the VAT rate in J1.', ); const sheet = createSpreadsheet(body, { theme: docsTheme(), height: '100%', data: { version: 1, sheets: [ { name: 'Work orders', freeze: { rows: 1, columns: 0 }, columnWidths: { A: 100, B: 140, F: 110, G: 130, I: 120 }, cells: cells(), }, ], names: [ { name: 'VatRate', formula: "='Work orders'!$J$1" }, { name: 'OvertimeAfter', formula: "='Work orders'!$J$2" }, { name: 'LabourCost', formula: '=LAMBDA(hours, rate, IF(hours > OvertimeAfter, OvertimeAfter * rate + (hours - OvertimeAfter) * rate * 1.5, hours * rate))', }, { name: 'WithVat', formula: '=LAMBDA(amount, ROUND(amount * (1 + VatRate), 2))' }, ], }, }); const totalCell = `G${workOrders.length + 2}`; const offs = [ sheet.on('cellChange', ({ address, source }) => { if (source !== 'edit' && source !== 'paste') return; status.textContent = `${address} changed. Invoice total is now ${sheet.getDisplayText(totalCell)}.`; }), ]; status.textContent = `Invoice total ${sheet.getDisplayText(totalCell)}. Labour for WO-24102 (10 hours) is ${sheet.getDisplayText('F3')}.`; const stopTheme = onDocsThemeChange((theme) => sheet.update({ theme })); return () => { for (const off of offs) off(); stopTheme(); sheet.destroy(); }; } ``` ## Steps 1. Put the inputs your functions depend on, such as the VAT rate, in cells and give them names. 2. Define each function as a name whose formula is a `LAMBDA`. 3. Call the functions from cells like any other function. 4. Test them with `createFormulaEngine()` in a unit test. ## Define the functions In the component, call `defineName(name, formula, sheet?)`: ```ts title="work-order-costing.ts" import { createSpreadsheet } from '@birchui/spreadsheet'; const sheet = createSpreadsheet(document.querySelector('#costing')!, { data: costingWorkbook }); sheet.defineName('VatRate', "='Work orders'!$J$1"); sheet.defineName('OvertimeAfter', "='Work orders'!$J$2"); sheet.defineName( 'LabourCost', '=LAMBDA(hours, rate, IF(hours > OvertimeAfter, OvertimeAfter * rate + (hours - OvertimeAfter) * rate * 1.5, hours * rate))', ); sheet.defineName('WithVat', '=LAMBDA(amount, ROUND(amount * (1 + VatRate), 2))'); sheet.setFormula('F2', '=LabourCost(C2, D2)'); sheet.setFormula('G2', '=WithVat(F2 + E2)'); ``` Or ship them in the workbook JSON, under `names`: ```ts title="costing-workbook.ts" import type { WorkbookJSON } from '@birchui/spreadsheet'; export const costingWorkbook: WorkbookJSON = { version: 1, sheets: [ { name: 'Work orders', cells: { A1: { value: 'Work order' }, C1: { value: 'Hours' }, D1: { value: 'Rate' }, E1: { value: 'Parts' }, F1: { value: 'Labour' }, G1: { value: 'Total inc. VAT' }, A2: { value: 'WO-24102' }, C2: { value: 10 }, D2: { value: 52 }, E2: { value: 340.5 }, F2: { formula: '=LabourCost(C2, D2)' }, G2: { formula: '=WithVat(F2 + E2)' }, J1: { value: 0.2 }, J2: { value: 8 }, }, }, ], names: [ { name: 'VatRate', formula: "='Work orders'!$J$1" }, { name: 'OvertimeAfter', formula: "='Work orders'!$J$2" }, { name: 'LabourCost', formula: '=LAMBDA(hours, rate, IF(hours > OvertimeAfter, OvertimeAfter * rate + (hours - OvertimeAfter) * rate * 1.5, hours * rate))', }, { name: 'WithVat', formula: '=LAMBDA(amount, ROUND(amount * (1 + VatRate), 2))' }, ], }; ``` Here `F2` is `572` (8 hours at 52, plus 2 hours at 78) and `G2` is `1095`. ## Apply a function to a whole column `MAP`, `BYROW` and `REDUCE` take a `LAMBDA`, including a named one, so one formula can fill a column: ```text =MAP(C2:C7, D2:D7, LabourCost) =REDUCE(0, G2:G7, LAMBDA(total, value, total + value)) ``` The first formula spills six labour costs down from the cell it is in. ## Test the functions The headless engine evaluates the same formulas without a DOM, so the functions can have unit tests: ```ts title="labour-cost.test.ts" import { createFormulaEngine } from '@birchui/spreadsheet'; import { describe, expect, it } from 'vitest'; import { costingWorkbook } from './costing-workbook'; describe('LabourCost', () => { const engine = createFormulaEngine(); engine.fromJSON(costingWorkbook); it('pays time and a half after eight hours', () => { expect(engine.evaluate('=LabourCost(10, 52)')).toBe(572); }); it('pays the plain rate up to eight hours', () => { expect(engine.evaluate('=LabourCost(6.5, 48)')).toBe(312); }); it('adds VAT and rounds to pence', () => { expect(engine.evaluate('=WithVat(912.5)')).toBe(1095); }); }); ``` ## How it works - A defined name whose formula is a `LAMBDA` becomes a function for the whole workbook. Without a sheet argument it is workbook-wide; with one it is scoped to that sheet. - Names inside the `LAMBDA` body, such as `VatRate`, are resolved when the function runs, so changing `J1` recalculates every cell that calls `WithVat`. - Names are stored in `WorkbookJSON.names`, so `toJSON()` and `fromJSON()` keep them, and they are written to and read from xlsx files. ## Pitfalls - **Name rules.** Names start with a letter, underscore or backslash and cannot look like a cell address: `defineName('VAT1', …)` throws an error, `VatRate` is fine. - **Wrong argument count** gives `#VALUE!`. `=LabourCost(10)` with one argument is an error, not a default. - **No JavaScript functions.** Worksheet functions are written in the formula language. For logic that needs your code or your server, compute the value in JavaScript and write it into a cell with `setCell` or `setRange`. - **Not in `listFunctions()`.** Named functions are part of the workbook, so they do not appear in the function list or in the [function reference](https://docs.birchui.com/spreadsheet/functions.md). ## Related - [LET and LAMBDA](https://docs.birchui.com/spreadsheet/formulas.md#let-and-lambda). - [Defined names](https://docs.birchui.com/spreadsheet/formulas.md#defined-names). - [Headless engine](https://docs.birchui.com/spreadsheet/headless-engine.md). - [Load and save xlsx files](https://docs.birchui.com/recipes/spreadsheet-load-save-xlsx.md). --- Source: https://docs.birchui.com/recipes/spreadsheet-load-save-xlsx/ # Load and save xlsx files > Open xlsx files from a file input, a URL or drag and drop, save them back to a server as xlsx or workbook JSON, and convert files on the server without the component. Users bring budgets and rate cards as Excel files and expect to get Excel files back. This recipe opens xlsx files in the spreadsheet component from a file picker, a URL and drag and drop, saves edits to a server, and converts files on the server without the component. ## Steps 1. Pass a `File`, `Blob`, `ArrayBuffer` or `Uint8Array` to `importXlsx()`. 2. Get the file back as bytes with `exportXlsx()`, or as JSON with `toJSON()`. 3. Report failures from the `error` event, whose `code` is `'import'` or `'export'`. 4. On a server, use `xlsxToJSON()` and `jsonToXlsx()`, which need no DOM. ## Open a file ```ts title="rate-card-editor.ts" import { createSpreadsheet } from '@birchui/spreadsheet'; const sheet = createSpreadsheet(document.querySelector('#rate-card')!, { height: 560 }); const fileInput = document.querySelector('#open-xlsx')!; fileInput.addEventListener('change', async () => { const file = fileInput.files?.[0]; if (!file) return; await sheet.importXlsx(file).catch(() => undefined); fileInput.value = ''; }); sheet.on('error', ({ code, message }) => { if (code === 'import' || code === 'export') showToast(message); }); sheet.on('sheetChange', () => { statusLine.textContent = `${sheet.getSheetNames().length} sheets loaded`; }); ``` `importXlsx()` replaces the workbook, clears the undo history and emits `sheetChange`. When the file cannot be read, the promise rejects and the `error` event fires, so catching the promise and showing the event's message is enough. ### From a URL ```ts async function openFromServer(url: string) { const response = await fetch(url); if (!response.ok) throw new Error(`Could not download ${url} (${response.status})`); await sheet.importXlsx(await response.arrayBuffer()); } await openFromServer('/api/rate-cards/2027/file'); ``` ### By drag and drop ```ts const host = sheet.element; host.addEventListener('dragover', (event) => event.preventDefault()); host.addEventListener('drop', (event) => { event.preventDefault(); const file = [...(event.dataTransfer?.files ?? [])].find((f) => f.name.toLowerCase().endsWith('.xlsx')); if (file) void sheet.importXlsx(file).catch(() => undefined); }); ``` ## Save Choose the format by what happens next. Store xlsx when people download the file again; store workbook JSON when your own code reads it, for example to recalculate it on a server. **xlsx** (`save-xlsx.ts`) ```ts async function saveAsXlsx(rateCardId: string) { const bytes = await sheet.exportXlsx(); const response = await fetch(`/api/rate-cards/${rateCardId}/file`, { method: 'PUT', headers: { 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }, body: bytes, }); if (!response.ok) throw new Error(`Saving failed (${response.status})`); } ``` **JSON** (`save-json.ts`) ```ts async function saveAsJson(rateCardId: string) { const response = await fetch(`/api/rate-cards/${rateCardId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(sheet.toJSON()), }); if (!response.ok) throw new Error(`Saving failed (${response.status})`); } ``` For a plain download, call `sheet.downloadXlsx('rate-card-2027.xlsx')`. ### Save automatically Listen to `cellChange` and `sheetChange` and save after a pause: ```ts let timer: ReturnType | undefined; const scheduleSave = () => { clearTimeout(timer); timer = setTimeout(() => void saveAsJson('2027'), 1500); }; sheet.on('cellChange', scheduleSave); sheet.on('sheetChange', scheduleSave); ``` ## Convert on a server `xlsxToJSON()` and `jsonToXlsx()` run in Node and workers. Combined with the [headless engine](https://docs.birchui.com/spreadsheet/headless-engine.md), a server can open an uploaded file, change inputs, recalculate and return a new file: ```ts title="server/rate-card.ts" import { createFormulaEngine, isCellError, jsonToXlsx, xlsxToJSON } from '@birchui/spreadsheet'; const licenseKey = process.env.BIRCHUI_LICENSE_KEY; export async function applyIndexation(upload: Uint8Array, indexRate: number) { const workbook = await xlsxToJSON(upload, { licenseKey }); const engine = createFormulaEngine(); engine.fromJSON(workbook); engine.setCell('Assumptions', 'B2', indexRate); const total = engine.getValue('Summary', 'B10'); if (isCellError(total)) throw new Error(`The rate card returned ${total.code} in Summary!B10`); return { total, file: await jsonToXlsx(engine.toJSON(), { licenseKey }) }; } ``` ## Pitfalls - **Unsaved edits are replaced.** `importXlsx()` replaces the whole workbook and clears undo. Ask before opening a file over edited data. - **Formulas Excel recalculates.** Some functions are evaluated differently, or only by Excel. See [What round-trips](https://docs.birchui.com/spreadsheet/xlsx.md#what-round-trips) before promising identical results. - **License key on the server.** The component uses its own `licenseKey`; the standalone functions take `{ licenseKey }` on each call. - **Large files.** Pass `{ compress: false }` to `exportXlsx()` for a faster, larger file when saving often. ## Related - [xlsx import and export](https://docs.birchui.com/spreadsheet/xlsx.md). - [The workbook JSON](https://docs.birchui.com/spreadsheet/sheets.md#the-workbook-json). - [Add custom worksheet functions](https://docs.birchui.com/recipes/spreadsheet-custom-functions.md). --- Source: https://docs.birchui.com/recipes/forms-builder-save-schemas/ # Save Form Builder schemas and render them > Persist schemas from the Form Builder with versioning and server-side checks, then load the published version and render it with createForm. Operations teams design their own inspection and intake forms in the Form Builder; technicians fill them in on site. This recipe saves drafts while the designer works, publishes numbered versions after a schema check, and renders the published version with `createForm` so every submission records which version it answered. ## Steps 1. Load the latest draft into `createFormBuilder()`. 2. Auto-save drafts on `schemaChange`, debounced, and save explicitly on `save`. 3. Publish: check the schema with `validateSchema()` on the server and store it as a new version. 4. In the field app, fetch the published version and pass it to `createForm()`. 5. Submit the answers together with the schema version. ## The designer ```ts title="inspection-designer.ts" import { createFormBuilder } from '@birchui/forms/builder'; import type { FormSchema } from '@birchui/forms'; const formId = 'site-inspection'; const draft = await fetch(`/api/forms/${formId}/draft`).then((r) => r.json() as Promise); const builder = createFormBuilder(document.querySelector('#designer')!, { schema: draft, licenseKey: import.meta.env.VITE_BIRCHUI_LICENSE_KEY, customValidators: { inServiceArea: () => true }, }); async function saveDraft(schema: FormSchema) { await fetch(`/api/forms/${formId}/draft`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(schema), }); statusLine.textContent = 'Draft saved'; } let timer: ReturnType | undefined; builder.on('schemaChange', ({ schema }) => { clearTimeout(timer); statusLine.textContent = 'Unsaved changes'; timer = setTimeout(() => void saveDraft(schema), 1000); }); builder.on('save', ({ schema }) => { clearTimeout(timer); void saveDraft(schema); }); publishButton.addEventListener('click', async () => { const response = await fetch(`/api/forms/${formId}/versions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(builder.getSchema()), }); const result = (await response.json()) as { version?: number; issues?: { path: string; message: string }[] }; statusLine.textContent = response.ok ? `Published version ${result.version}` : `Fix before publishing: ${result.issues?.map((issue) => `${issue.path || 'form'}: ${issue.message}`).join('; ')}`; }); ``` `save` fires for the toolbar's **Save** button, Ctrl + S and `builder.save()`. The builder stores nothing itself. The builder's preview runs custom validators, so register stand-ins for the ones your schemas reference, as with `inServiceArea` above. The real implementations live in the app that renders the form. ## Publish on the server Check every schema before it becomes a version technicians see. `validateSchema()` reports unknown element types, duplicate names, broken expressions and more. Pass the names of your custom expression functions so they are not reported as unknown: ```ts title="server/form-versions.ts" import { validateSchema, type FormSchema } from '@birchui/forms'; app.post('/api/forms/:formId/versions', async (request, response) => { const schema = request.body as FormSchema; const issues = validateSchema(schema, { functions: ['businessDaysBetween'] }).filter( (issue) => issue.severity === 'error', ); if (issues.length) return response.status(422).json({ issues }); const version = await db.formVersions.nextVersion(request.params.formId); await db.formVersions.insert({ formId: request.params.formId, version, schema: JSON.stringify(schema), publishedBy: request.user.id, publishedAt: new Date(), }); response.status(201).json({ version }); }); ``` Store each version as a new row instead of overwriting: answers submitted against version 3 should still make sense when version 4 renames a field. ## Render the published form ```ts title="field-app/inspection.ts" import { createForm, type FormSchema } from '@birchui/forms'; const { version, schema } = await fetch('/api/forms/site-inspection/published').then( (r) => r.json() as Promise<{ version: number; schema: FormSchema }>, ); const form = createForm(document.querySelector('#inspection')!, { schema, customValidators: { inServiceArea }, }); form.on('formSubmit', async ({ data }) => { await fetch('/api/inspections', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ formId: 'site-inspection', version, answers: data }), }); }); ``` To switch an open form to a newer version without losing answers, call `form.setSchema(newSchema)`. The current data is kept, defaults are applied to new fields, and the form returns to its first page. ## Pitfalls - **Do not save on every keystroke.** `schemaChange` fires for each edit, including undo and redo. Debounce it. - **`getSchema()` always uses pages.** A schema loaded with top-level `elements` comes back as a one-page `pages` schema. Both render the same. - **Unregistered validators.** If the rendered form names a custom validator that is not registered, `formError` fires and the value is accepted. Keep the list of validators in one shared module. - **Renamed fields.** Field names are the keys of the submitted data. Renaming a field in a new version starts a new key; migrate reports that read old submissions. ## Related - [Form Builder](https://docs.birchui.com/forms/builder.md) and the [builder API](https://docs.birchui.com/forms/builder-api.md). - [Check a schema](https://docs.birchui.com/forms/schema.md#check-a-schema). - [Validate form submissions on the server](https://docs.birchui.com/recipes/forms-server-validation.md). --- Source: https://docs.birchui.com/recipes/forms-server-validation/ # Validate form submissions on the server > Re-check submitted answers on the server with JSON Schema and the expression engine, run async checks while users type, and show the server's errors next to the right fields. Client-side validation helps users fill in a form; it does not protect your data. This recipe validates a service request three times: built-in rules in the browser, a live server check for one field while the user types, and a full check of the submission on the server whose errors are shown next to the fields they belong to. ## Steps 1. Share one schema module between the browser and the server. 2. Use a custom validator for checks that need the server while the user types. 3. On the server, validate the submission with JSON Schema from `toJSONSchema()`, plus rules that JSON Schema cannot express. 4. Return errors keyed by field name, and show them in the form with a custom validator and `validate()`. ## The shared schema ```ts title="shared/service-request.ts" import type { FormSchema } from '@birchui/forms'; export const serviceRequest: FormSchema = { title: 'Book a service visit', elements: [ { type: 'text', name: 'contactName', title: 'Your name', required: true }, { type: 'email', name: 'email', title: 'Email', required: true }, { type: 'text', name: 'postcode', title: 'Postcode', required: true, validators: [{ type: 'custom', name: 'inServiceArea' }, { type: 'custom', name: 'server' }], }, { type: 'select', name: 'appliance', title: 'Appliance', required: true, choices: ['Boiler', 'Heat pump', 'EV charger'] }, { type: 'text', name: 'serialNumber', title: 'Serial number', validators: [{ type: 'custom', name: 'server' }] }, { type: 'date', name: 'preferredDate', title: 'Preferred date', required: true, validators: [{ type: 'custom', name: 'server' }] }, ], }; ``` Every field that the server may reject gets a `server` custom validator. It shows errors from the last submission; see below. ## Live check while typing A custom validator can return a promise. Older results are discarded when the user keeps typing, so a slow response never overwrites a newer one: ```ts title="validators.ts" import type { CustomValidator } from '@birchui/forms'; export const inServiceArea: CustomValidator = async (value) => { const response = await fetch(`/api/coverage?postcode=${encodeURIComponent(String(value))}`); if (!response.ok) return true; const { covered } = (await response.json()) as { covered: boolean }; return covered ? true : `We do not cover ${String(value)} yet. Call 0161 496 0000 to arrange a visit.`; }; ``` Returning `true` when the coverage service is down keeps the form usable; the server checks the postcode again on submit. ## Show the server's errors The form has no method to set errors from outside, but a custom validator can read them from a map. After a rejected submission, fill the map and call `validate()`: ```ts title="service-request-form.ts" import { createForm, type CustomValidator } from '@birchui/forms'; import { serviceRequest } from './shared/service-request'; import { inServiceArea } from './validators'; const serverErrors = new Map(); const server: CustomValidator = (value, { name }) => { const message = serverErrors.get(name); return message ?? true; }; const form = createForm(document.querySelector('#service-request')!, { schema: serviceRequest, customValidators: { inServiceArea, server }, }); form.on('valueChange', ({ name }) => serverErrors.delete(name)); form.on('formSubmit', async ({ data }) => { const response = await fetch('/api/service-requests', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }); if (response.status === 422) { const { errors } = (await response.json()) as { errors: Record }; for (const [name, message] of Object.entries(errors)) serverErrors.set(name, message); const { errors: shown } = await form.validate(); if (shown[0]) form.focusField(shown[0].name); return; } if (!response.ok) { showToast('The request could not be sent. Please try again.'); return; } showConfirmation(); }); ``` `validate()` re-runs every rule, so the server's messages appear below their fields and in the error summary. Changing a field removes its server error, and the next check passes. ## Validate on the server ```ts title="server/service-requests.ts" import Ajv2020 from 'ajv/dist/2020'; import addFormats from 'ajv-formats'; import { toJSONSchema } from '@birchui/forms'; import { serviceRequest } from '../shared/service-request'; const ajv = new Ajv2020({ strict: false, allErrors: true }); addFormats(ajv); const validateShape = ajv.compile(toJSONSchema(serviceRequest, { extensions: false })); app.post('/api/service-requests', async (request, response) => { const body = request.body as Record; const errors: Record = {}; if (!validateShape(body)) { for (const error of validateShape.errors ?? []) { const name = error.instancePath.slice(1) || String(error.params.missingProperty ?? 'form'); errors[name] ??= `This value is not valid: ${error.message}.`; } } if (typeof body.postcode === 'string' && !(await coverage.covers(body.postcode))) { errors.postcode = `We do not cover ${body.postcode} yet.`; } if (typeof body.serialNumber === 'string' && body.serialNumber !== '') { const registered = await appliances.findBySerial(body.serialNumber); if (!registered) errors.serialNumber = 'We cannot find this serial number. Check the label on the appliance.'; } if (typeof body.preferredDate === 'string' && !(await capacity.hasSlot(body.preferredDate))) { errors.preferredDate = 'That day is fully booked. Choose another date.'; } if (Object.keys(errors).length) return response.status(422).json({ errors }); const id = await serviceRequests.insert(body); response.status(201).json({ id }); }); ``` ## How it works - `toJSONSchema()` turns the form schema into a JSON Schema that any validator, here Ajv, can check: required fields, types, formats, lengths and choices. - Business rules that need data, such as booked capacity, run as ordinary server code and return messages keyed by the field's `name`. - Inside repeating sections, use the field's data path as the key, such as `lineItems[1].amount`; it is the `name` the custom validator receives. ## Pitfalls - **Custom validators run only on fields with a value.** A server error for an empty field will not show through the `server` validator. Mark such fields `required` so the built-in rule catches them first. - **`requiredIf` is not in JSON Schema.** Re-check conditional rules with [`evaluateExpression()`](https://docs.birchui.com/forms/expressions.md#using-expressions-outside-a-form) on the server. - **Files.** File fields hold `File` objects in the browser while JSON Schema describes strings; validate uploads separately. - **Hidden fields.** The submitted data leaves out answers of hidden questions by default (`clearHiddenValues: 'onSubmit'`), so do not require them on the server. ## Related - [Validation](https://docs.birchui.com/forms/validation.md), including [custom validators](https://docs.birchui.com/forms/validation.md#custom-validators). - [Validate submissions on the server](https://docs.birchui.com/forms/json-schema.md#validate-submissions-on-the-server) with JSON Schema. - [Save Form Builder schemas and render them](https://docs.birchui.com/recipes/forms-builder-save-schemas.md). --- Source: https://docs.birchui.com/recipes/calendar-ical-feed/ # Publish and subscribe to iCalendar feeds > Serve a team's events as a subscribable .ics feed with toICS, show external feeds in the Event Calendar with parseICS, and import .ics files without duplicates. Technicians want their visits in the calendar app on their phone, and the office wants public holidays and supplier schedules next to its own events. This recipe publishes a feed URL that Outlook, Google Calendar and Apple Calendar can subscribe to, shows external feeds in the Event Calendar, and imports `.ics` files without creating duplicates. ## Steps 1. On the server, load a team's events and return `toICS(events)` with the `text/calendar` content type. 2. In the browser, fetch external feeds in an `eventSource` and convert them with `parseICS()`. 3. For file imports, merge parsed events by `id`, which comes from the iCalendar `UID`. ## Publish a feed ```ts title="server/calendar-feed.ts" import { toICS, type IcsEvent } from '@birchui/calendar'; app.get('/feeds/teams/:teamId/:token.ics', async (request, response) => { const team = await db.teams.findByFeedToken(request.params.teamId, request.params.token); if (!team) return response.status(404).end(); const visits = await db.visits.forTeam(team.id, { from: monthsAgo(3), to: monthsAhead(12) }); const events: IcsEvent[] = visits.map((visit) => ({ id: visit.id, title: `${visit.jobType}: ${visit.customerName}`, start: visit.start, end: visit.end, timeZone: team.timeZone, location: visit.siteAddress, description: `Work order ${visit.workOrderNo}\nAccess: ${visit.accessNotes ?? 'none'}`, status: visit.cancelled ? 'CANCELLED' : 'CONFIRMED', rrule: visit.rrule ?? undefined, exdates: visit.exdates ?? undefined, recurrenceId: visit.recurrenceId ?? undefined, recurringEventId: visit.seriesId ?? undefined, })); response .type('text/calendar; charset=utf-8') .set('Cache-Control', 'private, max-age=900') .send(toICS(events, { calendarName: `${team.name} visits` })); }); ``` Users add the URL in their calendar app as a subscription (in Outlook: **Add calendar › Subscribe from web**; in Google Calendar: **Other calendars › From URL**). Apps refresh subscriptions on their own schedule, typically every few hours. How `toICS` writes events: - Zoned events get a `TZID`, UTC instants are written in UTC, all-day events use `VALUE=DATE`. - Series keep their `RRULE` and `EXDATE`s. Detached occurrences, the events with `recurrenceId` and `recurringEventId`, are written as `RECURRENCE-ID` overrides under the master's `UID`, so moved visits show up correctly. - `description`, `location`, `url`, `status` and `categories` are written; your other fields are not. ## Show an external feed An `eventSource` is called with the visible range. Fetch the feed, parse it and return the events: ```ts title="team-calendar.ts" import { createCalendar, parseICS, type EventSourceRequest } from '@birchui/calendar'; const FEEDS = ['/feeds/proxy/uk-bank-holidays.ics', '/feeds/proxy/supplier-deliveries.ics']; async function loadFeeds({ signal }: EventSourceRequest) { const [ownVisits, ...external] = await Promise.all([ fetch('/api/visits', { signal }).then((r) => r.json()), ...FEEDS.map((url) => fetch(url, { signal }) .then((r) => (r.ok ? r.text() : '')) .then((text) => parseICS(text).map((event) => ({ ...event, editable: false, color: 'slategray' }))), ), ]); return [...ownVisits, ...external.flat()]; } const calendar = createCalendar(document.querySelector('#team-calendar')!, { view: 'month', timeZone: 'Europe/London', eventSource: loadFeeds, }); ``` Most calendar providers do not send CORS headers, so fetch third-party feeds through a small proxy on your own server, as the `/feeds/proxy/` URLs above do. ## Import a file without duplicates `parseICS()` sets each event's `id` from its `UID`, and detached occurrences get `'@'`. Importing the same file twice therefore produces the same ids. Merge by id instead of appending: ```ts title="import-ics.ts" import { parseICS } from '@birchui/calendar'; async function importIcsFile(file: File) { const imported = parseICS(await file.text()); const byId = new Map(calendar.getEvents().map((event) => [String(event.id), event])); let added = 0; for (const event of imported) { if (!byId.has(String(event.id))) added += 1; byId.set(String(event.id), event); } calendar.setEvents([...byId.values()]); statusLine.textContent = `${added} new and ${imported.length - added} updated events from ${file.name}`; } ``` With an `eventSource`, send the parsed events to your server instead and call `calendar.refetch()`. ## Pitfalls - **Keep `UID`s stable.** Calendar apps match events by `UID`. Use your database id as the event `id`; never generate a new one per request, or subscribers see every event twice after a refresh. - **Protect private feeds.** Subscription URLs cannot send cookies or headers, so put an unguessable token in the URL and let users reset it. - **Time zones.** `VTIMEZONE` blocks are not written or read; zones are referred to by IANA name, which the major calendar apps resolve. Windows zone names in Outlook files are mapped to IANA names on import. - **Custom fields.** Only standard properties survive a round trip. Keep the rest in your database keyed by `id`. ## Related - [iCalendar import and export](https://docs.birchui.com/calendar/ical.md). - [Event sources](https://docs.birchui.com/calendar/event-sources.md). - [Recurrence](https://docs.birchui.com/calendar/recurrence.md#the-detached-occurrence). - [Schedule recurring maintenance jobs](https://docs.birchui.com/recipes/scheduler-recurring-jobs.md). --- Source: https://docs.birchui.com/recipes/charts-dashboard-from-grid/ # Build a chart dashboard from a grid > Drive several charts from the rows a Birch UI Grid shows, so filtering the grid updates the dashboard, and chart a selected range with chartFromRange. An operations dashboard usually starts as a table: one row per work order. This recipe puts three charts above a [Birch UI Grid](https://docs.birchui.com/grid/overview.md) and keeps them in step with it. When the user filters or searches the grid, the charts show only the rows that are left. With Grid Pro, a fourth chart shows whatever range of cells the user selects. ## Steps 1. Create the grid and the charts once. 2. On the grid's `modelUpdated` event, collect the data rows from `getAllDisplayRows()`. 3. Aggregate them into small arrays and pass each to a chart with `setData()`. 4. Optionally, chart a selected range with `chartFromRange()`. ## The grid ```ts title="work-order-grid.ts" import { createGrid, type ColumnDef } from '@birchui/core'; export interface WorkOrder { id: string; depot: string; technician: string; jobType: string; completed: string; hours: number; revenue: number; firstTimeFix: boolean; } const gbp = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP', maximumFractionDigits: 0 }); const columns: ColumnDef[] = [ { field: 'id', header: 'Work order', width: 120 }, { field: 'depot', header: 'Depot', filter: true }, { field: 'technician', header: 'Technician', filter: true }, { field: 'jobType', header: 'Job type', filter: true }, { field: 'completed', header: 'Completed', type: 'date' }, { field: 'hours', header: 'Hours', type: 'number' }, { field: 'revenue', header: 'Revenue', type: 'number', format: (v) => gbp.format(Number(v)) }, { field: 'firstTimeFix', header: 'First-time fix', type: 'boolean' }, ]; export const grid = createGrid(document.querySelector('#work-orders')!, { columns, rows: workOrders, getRowId: (row) => row.id, }); ``` ## The charts ```ts title="dashboard-charts.ts" import { createChart } from '@birchui/charts'; export const revenueByDepot = createChart(document.querySelector('#revenue-by-depot')!, { title: 'Revenue by depot', data: [], series: [{ type: 'column', xKey: 'depot', yKey: 'revenue', name: 'Revenue' }], height: 260, }); export const jobMix = createChart(document.querySelector('#job-mix')!, { title: 'Jobs by type', data: [], series: [{ type: 'donut', xKey: 'jobType', yKey: 'jobs', name: 'Jobs' }], height: 260, }); export const weeklyHours = createChart(document.querySelector('#weekly-hours')!, { title: 'Hours per week', data: [], series: [{ type: 'line', xKey: 'week', yKey: 'hours', name: 'Hours', markers: true }], height: 260, }); ``` ## Keep them in step ```ts title="dashboard.ts" import { grid, type WorkOrder } from './work-order-grid'; import { jobMix, revenueByDepot, weeklyHours } from './dashboard-charts'; function totals(rows: WorkOrder[], key: (row: WorkOrder) => string, value: (row: WorkOrder) => number) { const result = new Map(); for (const row of rows) result.set(key(row), (result.get(key(row)) ?? 0) + value(row)); return [...result]; } function weekStart(isoDate: string): string { const date = new Date(`${isoDate}T00:00:00Z`); date.setUTCDate(date.getUTCDate() - ((date.getUTCDay() + 6) % 7)); return date.toISOString().slice(0, 10); } let pending = 0; function refreshCharts() { const rows = grid .getAllDisplayRows() .filter((row) => row.kind === 'data' && row.data) .map((row) => row.data as WorkOrder); revenueByDepot.setData( totals(rows, (r) => r.depot, (r) => r.revenue) .map(([depot, revenue]) => ({ depot, revenue })) .sort((x, y) => y.revenue - x.revenue), ); jobMix.setData(totals(rows, (r) => r.jobType, () => 1).map(([jobType, jobs]) => ({ jobType, jobs }))); weeklyHours.setData( totals(rows, (r) => weekStart(r.completed), (r) => r.hours) .map(([week, hours]) => ({ week, hours: Math.round(hours * 10) / 10 })) .sort((x, y) => x.week.localeCompare(y.week)), ); } grid.on('modelUpdated', () => { window.clearTimeout(pending); pending = window.setTimeout(refreshCharts, 100); }); refreshCharts(); ``` `modelUpdated` fires after every run of the grid's row pipeline: new rows, transactions, sorting, filtering, paging and grouping. The short debounce turns a burst of filter keystrokes into one redraw. ## Chart a selected range With Grid Pro's range selection, `chartFromRange()` builds chart options from the selected cells. Numeric columns become series and the first text column becomes the category axis: ```ts title="selection-chart.ts" import { RangeSelectionModule } from '@birchui/grid-pro'; import { chartFromRange, createChart, type ChartApi } from '@birchui/charts'; let selectionChart: ChartApi | null = null; function chartSelection() { const values = grid.getRangeValues?.() ?? []; const range = grid.getCellRanges?.().at(-1); if (!range || values.length === 0) return; const display = grid.getDisplayColumns(); const from = display.findIndex((column) => column.id === range.startCol); const to = display.findIndex((column) => column.id === range.endCol); const headers = display.slice(Math.min(from, to), Math.max(from, to) + 1).map((column) => column.header); const options = chartFromRange(values, headers, { title: 'Selected work orders' }); if (selectionChart) selectionChart.update(options); else selectionChart = createChart(document.querySelector('#selection-chart')!, options); } ``` Create the grid with `modules: [RangeSelectionModule]` and `rangeSelection: true` for these methods to exist. [Grid integration](https://docs.birchui.com/charts/grid-integration.md#from-a-grid-pro-range-selection) covers utility columns and live updates. ## How it works - `getAllDisplayRows()` returns the rows after filtering and sorting, across all pages, so the charts match what the grid would show. `getRows()` would return every source row, ignoring filters. - Group and total rows have `kind` other than `'data'` and no row object of their own; filtering on `kind === 'data'` skips them. - `setData()` replaces a chart's data and keeps its series, axes and theme, so the charts are created once. ## Pitfalls - **Aggregate before charting.** Passing thousands of raw rows to a column chart draws thousands of bars. Group them first, as above. - **Formatted values.** Read raw values from the row objects, not `getFormattedValue()`, so numbers reach the chart as numbers. - **Grouped grids.** With row grouping, the rows of a collapsed group are not display rows. Read the top-level group rows' `group.leaves` instead, which hold every row in the group. - **Clean up.** Call `destroy()` on every chart and the grid when the dashboard is removed. ## Related - [Grid integration](https://docs.birchui.com/charts/grid-integration.md). - [Grid events](https://docs.birchui.com/grid/events.md#modelupdated). - [Series](https://docs.birchui.com/charts/series.md). --- Source: https://docs.birchui.com/recipes/diagram-save-load-layout/ # Save, load and auto-arrange diagrams > Persist diagrams as DiagramDocument JSON, restore them with fromJSON, lay out graphs that arrive without coordinates, and keep layout results out of your change log. A workflow editor needs three things from storage: open a saved diagram exactly as the user left it, open a graph that came from another system and has no coordinates, and save edits without flooding the server. This recipe covers all three with `toJSON()`, `fromJSON()` and `layout()`. ## Steps 1. Load the saved `DiagramDocument` with `fromJSON()`. If there is none, build nodes and edges from your data and run `layout()`. 2. Save the whole document with `toJSON()`, debounced, after `nodesChange` and `edgesChange`. 3. Offer an **Arrange** button that runs `layout()` again, as one undoable step. ## Open a diagram ```ts title="workflow-editor.ts" import { createDiagram, type DiagramDocument, type DiagramEdge, type DiagramNode } from '@birchui/diagram'; interface WorkflowStep { id: string; name: string; kind: 'start' | 'task' | 'decision' | 'end'; } interface Transition { from: string; to: string; label?: string; } const diagram = createDiagram(document.querySelector('#workflow')!, { ariaLabel: 'Work order approval workflow', }); const SHAPES = { start: 'ellipse', task: 'rectangle', decision: 'diamond', end: 'ellipse' } as const; function nodesFrom(steps: WorkflowStep[]): DiagramNode[] { return steps.map((step) => ({ id: step.id, label: step.name, type: SHAPES[step.kind], x: 0, y: 0, width: step.kind === 'decision' ? 120 : 168, height: step.kind === 'decision' ? 80 : 56, data: { kind: step.kind }, })); } function edgesFrom(transitions: Transition[]): DiagramEdge[] { return transitions.map((t) => ({ id: `${t.from}->${t.to}`, source: { node: t.from }, target: { node: t.to }, label: t.label, })); } export async function openWorkflow(workflowId: string) { const response = await fetch(`/api/workflows/${workflowId}/diagram`); if (response.ok) { diagram.fromJSON((await response.json()) as DiagramDocument); return; } const { steps, transitions } = (await fetch(`/api/workflows/${workflowId}`).then((r) => r.json())) as { steps: WorkflowStep[]; transitions: Transition[]; }; diagram.update({ nodes: nodesFrom(steps), edges: edgesFrom(transitions) }); await diagram.layout({ type: 'layered', direction: 'LR', spacing: { node: 36, layer: 72 } }); diagram.zoomToFit(); } ``` `fromJSON()` restores nodes, edges and the saved viewport. It accepts the object or its JSON string, drops invalid entries with a warning, and leaves the current diagram untouched when the input is not a valid document. ## Save edits ```ts title="workflow-autosave.ts" let saveTimer: ReturnType | undefined; function scheduleSave(workflowId: string) { clearTimeout(saveTimer); saveTimer = setTimeout(async () => { const response = await fetch(`/api/workflows/${workflowId}/diagram`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(diagram.toJSON()), }); statusLine.textContent = response.ok ? 'All changes saved' : 'Changes could not be saved'; }, 800); } diagram.on('nodesChange', () => scheduleSave(workflowId)); diagram.on('edgesChange', () => scheduleSave(workflowId)); ``` The document is small and versioned: ```json { "format": "birchui-diagram", "version": 1, "nodes": [{ "id": "submitted", "x": 0, "y": 40, "type": "ellipse", "label": "Work order submitted", "data": { "kind": "start" } }], "edges": [{ "id": "submitted->review", "source": { "node": "submitted" }, "target": { "node": "review" } }], "viewport": { "x": 120, "y": 80, "zoom": 1 } } ``` ## Arrange on demand ```ts title="arrange-button.ts" arrangeButton.addEventListener('click', async () => { arrangeButton.disabled = true; await diagram.layout({ type: 'layered', direction: 'LR', animate: true }); arrangeButton.disabled = false; }); diagram.on('nodesChange', ({ source }) => { if (source === 'layout') auditLog.push('Diagram rearranged'); }); ``` A layout is one history entry labelled "Auto layout", so Ctrl + Z puts every node back. It emits `nodesChange` with `source: 'layout'`, which the autosave above saves like any other change. ## Lay out on the server When workflows are created by another system, compute positions once on the server with the pure layout functions and store a complete document, so every client opens it instantly: ```ts title="server/arrange-workflow.ts" import { runLayout, type DiagramDocument } from '@birchui/diagram'; export function workflowDocument(steps: WorkflowStep[], transitions: Transition[]): DiagramDocument { const sizes = steps.map((step) => ({ id: step.id, width: step.kind === 'decision' ? 120 : 168, height: step.kind === 'decision' ? 80 : 56, })); const positions = runLayout( sizes, transitions.map((t) => ({ source: t.from, target: t.to })), { type: 'layered', direction: 'LR' }, ); return { format: 'birchui-diagram', version: 1, nodes: sizes.map((size) => { const step = steps.find((s) => s.id === size.id)!; return { ...size, ...positions.get(size.id)!, label: step.name, data: { kind: step.kind } }; }), edges: transitions.map((t) => ({ id: `${t.from}->${t.to}`, source: { node: t.from }, target: { node: t.to }, label: t.label })), }; } ``` ## Pitfalls - **`fromJSON()` clears the undo history**, like `setNodes`, `setEdges` and `update({ nodes, edges })`. Load once when the editor opens, not after every save. - **Keep `data` serializable.** Functions, class instances and `Date` objects do not survive `JSON.stringify`. Store dates as ISO strings. - **Framework props.** Do not feed every change back into a component's `nodes` and `edges` props: each new array reloads the document. See [Loading and framework state](https://docs.birchui.com/diagram/serialization.md#loading-and-framework-state). - **Sizes for layout.** The layout engines place nodes by `width` and `height`. Give nodes their real sizes before laying out, or they will overlap. ## Related - [Serialization and export](https://docs.birchui.com/diagram/serialization.md). - [Layout](https://docs.birchui.com/diagram/layout.md), including [standalone layout functions](https://docs.birchui.com/diagram/layout.md#standalone-layout-functions). - [Nodes and edges](https://docs.birchui.com/diagram/nodes-and-edges.md). --- Source: https://docs.birchui.com/recipes/excel-report-workbook/ # Build a multi-sheet Excel report > Write a styled monthly report with a summary sheet, a detail sheet and per-depot outlines using writeXlsx, with cross-sheet formulas and cached values. Finance wants the monthly field service report as an Excel file: a summary on the first sheet, every work order on the second, and a per-depot breakdown that folds open. This recipe builds that workbook as plain data and writes it with `writeXlsx()`, in the browser, a worker or Node. ## Steps 1. Define shared styles once: header, currency, dates, totals. 2. Build the detail sheet first, because the summary's formulas refer to its rows. 3. Build the summary with `SUMIFS` formulas that point at the detail sheet, and supply cached values. 4. Build the breakdown with outline levels. 5. Write the workbook with `writeXlsx()` or download it with `downloadXlsx()`. ## Styles ```ts title="report-styles.ts" import type { XlsxCellStyle } from '@birchui/excel'; export const styles = { title: { bold: true, font: { size: 16, color: '#1F3A5F' } }, header: { bold: true, color: '#FFFFFF', fill: '#1F3A5F', valign: 'center', border: { bottom: { style: 'thin', color: '#0F1F33' } }, }, gbp: { numFmt: '"£"#,##0.00' }, hours: { numFmt: '0.0' }, date: { numFmt: 'dd mmm yyyy' }, percent: { numFmt: '0%' }, total: { bold: true, border: { top: { style: 'thin' }, bottom: { style: 'double' } } }, } satisfies Record; ``` ## The report ```ts title="monthly-report.ts" import { cellRef, writeXlsx, type XlsxSheet, type XlsxWorkbook } from '@birchui/excel'; import { styles } from './report-styles'; export interface WorkOrder { orderNo: string; depot: string; technician: string; completed: Date; hours: number; labour: number; parts: number; firstTimeFix: boolean; } const header = (labels: string[]) => labels.map((value) => ({ value, style: styles.header })); export async function monthlyReport(month: string, orders: WorkOrder[]): Promise { const lastRow = orders.length + 1; const detail: XlsxSheet = { name: 'Work orders', freeze: { rows: 1 }, autoFilter: true, columns: [ { width: 12 }, { width: 14 }, { width: 20 }, { width: 13, style: styles.date }, { width: 8, style: styles.hours }, { width: 12, style: styles.gbp }, { width: 12, style: styles.gbp }, { width: 13, style: styles.gbp }, { width: 10 }, ], rows: [ { cells: header(['Work order', 'Depot', 'Technician', 'Completed', 'Hours', 'Labour', 'Parts', 'Total', 'First fix']), height: 22 }, ...orders.map((order, index) => { const row = index + 2; return [ order.orderNo, order.depot, order.technician, order.completed, order.hours, order.labour, order.parts, { formula: `F${row}+G${row}`, value: order.labour + order.parts }, order.firstTimeFix, ]; }), ], }; const depots = [...new Set(orders.map((order) => order.depot))].sort(); const totalFor = (depot: string) => orders.filter((o) => o.depot === depot).reduce((sum, o) => sum + o.labour + o.parts, 0); const grandTotal = orders.reduce((sum, o) => sum + o.labour + o.parts, 0); const firstFixRate = orders.filter((o) => o.firstTimeFix).length / Math.max(orders.length, 1); const summary: XlsxSheet = { name: 'Summary', tabColor: '#1F3A5F', columns: [{ width: 26 }, { width: 14, style: styles.gbp }, { width: 12 }], merges: ['A1:C1'], rows: [ [{ value: `Field service report, ${month}`, style: styles.title }], [], header(['Depot', 'Revenue', 'Work orders']), ...depots.map((depot, index) => [ depot, { formula: `SUMIFS('Work orders'!H2:H${lastRow},'Work orders'!B2:B${lastRow},A${index + 4})`, value: totalFor(depot) }, { formula: `COUNTIFS('Work orders'!B2:B${lastRow},A${index + 4})`, value: orders.filter((o) => o.depot === depot).length, }, ]), [ { value: 'Total', style: styles.total }, { value: { formula: `SUM(${cellRef(3, 1)}:${cellRef(depots.length + 2, 1)})`, value: grandTotal }, style: { ...styles.gbp, ...styles.total }, }, { value: { formula: `SUM(C4:C${depots.length + 3})`, value: orders.length }, style: styles.total }, ], [], [ 'First-time fix rate', { value: { formula: `COUNTIF('Work orders'!I2:I${lastRow},TRUE)/COUNTA('Work orders'!A2:A${lastRow})`, value: firstFixRate }, style: styles.percent, }, ], ], }; const breakdown: XlsxSheet = { name: 'By depot', outlineSummaryBelow: false, freeze: { rows: 1 }, columns: [{ width: 30 }, { width: 10, style: styles.hours }, { width: 14, style: styles.gbp }], rows: [ { cells: header(['Depot / technician', 'Hours', 'Revenue']) }, ...depots.flatMap((depot) => { const inDepot = orders.filter((o) => o.depot === depot); const technicians = [...new Set(inDepot.map((o) => o.technician))].sort(); return [ { cells: [depot, inDepot.reduce((s, o) => s + o.hours, 0), totalFor(depot)], style: { bold: true, fill: '#E8EEF7' }, }, ...technicians.map((technician) => { const own = inDepot.filter((o) => o.technician === technician); return { cells: [ { value: technician, style: { indent: 1 } }, own.reduce((s, o) => s + o.hours, 0), own.reduce((s, o) => s + o.labour + o.parts, 0), ], outlineLevel: 1, }; }), ]; }), ], }; const workbook: XlsxWorkbook = { title: `Field service report ${month}`, creator: 'Fleetwise Operations', created: new Date(), sheets: [summary, detail, breakdown], }; return writeXlsx(workbook); } ``` The summary comes first in `sheets`, so Excel opens on it, but it is built after the detail sheet because its formulas depend on the detail's row count. ## Deliver the file **Browser** (`download-report.ts`) ```ts const bytes = await monthlyReport('November 2026', orders); const url = URL.createObjectURL( new Blob([bytes], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), ); const link = Object.assign(document.createElement('a'), { href: url, download: 'field-service-2026-11.xlsx' }); link.click(); URL.revokeObjectURL(url); ``` **Node** (`scripts/monthly-report.ts`) ```ts import { writeFile } from 'node:fs/promises'; import { setLicenseKey } from '@birchui/license'; setLicenseKey(process.env.BIRCHUI_LICENSE_KEY!); const orders = await db.workOrders.completedIn('2026-11'); await writeFile('reports/field-service-2026-11.xlsx', await monthlyReport('November 2026', orders)); ``` If you build the workbook object without calling `writeXlsx()` yourself, `downloadXlsx(workbook, 'field-service-2026-11')` writes and downloads it in one call. ## How it works - Column styles apply to every cell in the column, so number formats are set once per column rather than per cell. A cell's own style is merged over the column and row styles. - Formulas are written in Excel's English syntax without the leading `=`. The engine does not calculate them; Excel recalculates on open. The cached `value` is what previews and other apps show before that. - Sheet names with spaces are quoted in formulas: `'Work orders'!H2:H40`. - `outlineLevel: 1` on the technician rows groups them under their depot row, and `outlineSummaryBelow: false` puts the fold button on the depot row above them. ## Pitfalls - **Dates are written in UTC.** Build `completed` with `Date.UTC()` or from ISO date strings, or a late-evening job can land on the next day. See [Cells](https://docs.birchui.com/excel/writing.md#cells). - **Overlapping merges** are skipped with a warning, because Excel refuses to open such files. - **Sheet name rules.** Names longer than 31 characters or containing `[ ] : * ? / \` are changed, which breaks formulas that refer to the original name. Keep names short and plain. - **Large reports.** For tens of thousands of rows, build the workbook in a [worker](https://docs.birchui.com/excel/workers.md) so the page stays responsive. ## Related - [Writing workbooks](https://docs.birchui.com/excel/writing.md). - [Styles](https://docs.birchui.com/excel/styles.md) and [number formats](https://docs.birchui.com/excel/styles.md#number-formats). - [Freeze panes, outlines and merges](https://docs.birchui.com/excel/layout.md). - [Build a critical path report](https://docs.birchui.com/recipes/gantt-critical-path-report.md). --- Source: https://docs.birchui.com/support/errors/ # Error and warning codes > Every console warning and error Birch UI products print, with its stable LQ code, the cause and the fix. Birch UI products never throw at runtime for bad options or failing callbacks. They log one console message and fall back to safe behaviour. Each message has a stable code, listed here by product. Quote the code when you contact support. Callback errors (`error` level) always log the original exception as the second console argument. Expand it in the browser console to see the stack trace in your own code. To see more detail while you investigate, turn on debug logging with `debug: true` in the grid options or `window.__BIRCHUI_DEBUG__ = true` before the grid is created. It logs pipeline stage timings and render counts with `console.info`. A machine-readable version of this list, with a regular expression per message, is kept in the repository at `docs/support/error-codes.json`. ## License Package: `@birchui/license` ### LQ-LIC-001 `warn` · `[Birch UI] No license key is set for . All features keep working; a watermark is shown on non-local hosts until a valid license key is set. Purchase a license at https://birchui.com/pricing` **Cause.** No license key reached the product. Usually `setLicenseKey()` runs after the widget is created, runs in a different bundle copy of `@birchui/license`, or the environment variable holding the key is not exposed to the client build (for example a missing `VITE_` or `NEXT_PUBLIC_` prefix). **Fix.** Call `setLicenseKey(key)` once, before creating any widget, or pass `licenseKey` in the widget options. Check that the build exposes the variable to browser code. `npx birchui-doctor` shows whether a key is configured and which products it covers. ### LQ-LIC-002 `warn` · `[Birch UI] The license key for is not a valid Birch UI key. All features keep working; a watermark is shown on non-local hosts until a valid license key is set. Purchase a license at https://birchui.com/pricing` **Cause.** The key is not in the `LQ1..` format. Common causes: the key was truncated or wrapped when pasted, quotes or a trailing newline were included, or an order number was used instead of the key. **Fix.** Copy the full key again from the purchase email or customer portal. `npx birchui-doctor` decodes the key offline and reports whether its structure is valid. ### LQ-LIC-003 `warn` · `[Birch UI] The license key for has an invalid signature; it was altered or not issued by Birch UI. All features keep working; a watermark is shown on non-local hosts until a valid license key is set. Purchase a license at https://birchui.com/pricing` **Cause.** The key decodes but its signature does not match. The key was edited by hand, two keys were concatenated, or it was issued by a test signing key. **Fix.** Use the original key unchanged. If it still fails, ask support to reissue the key; support verifies it with the admin API. ### LQ-LIC-004 `warn` · `[Birch UI] The license for does not include . All features keep working; a watermark is shown on non-local hosts until a valid license key is set. Purchase a license at https://birchui.com/pricing` **Cause.** The key is valid but its product list does not include the product that is running. For example a Grid Pro key used with Scheduler. **Fix.** Check the products shown by `npx birchui-doctor`. Buy the missing product or upgrade to a bundle; support can reissue a combined key. ### LQ-LIC-005 `warn` · `[Birch UI] The trial for expired on . All features keep working; a watermark is shown on non-local hosts until a valid license key is set. Purchase a license at https://birchui.com/pricing` **Cause.** A trial key passed its expiry date. Paid keys never expire. **Fix.** Buy a license and replace the trial key. Features keep working meanwhile; only the watermark and this warning appear. ## Birch UI Grid Package: `@birchui/core` ### LQ-GRID-001 `warn` · `Birch UI Grid: column groups need unique groupId values; renamed duplicates of ` **Cause.** Two or more items in the data or options use the same id. The widget kept one and ignored the other, as the message states. **Fix.** Make ids unique. If data comes from several sources, prefix ids by source. ### LQ-GRID-002 `warn` · `Birch UI Grid: setColumnGroupOpen() found no column group with groupId ""` **Cause.** The value refers to an id, field or sheet that does not exist. Names are case-sensitive. **Fix.** Check the spelling and that the referenced item is loaded before it is referenced. ### LQ-GRID-003 `error` · `Birch UI Grid: column stage "" failed` **Cause.** Code supplied by the application (column stage "") threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-004 `error` · `Birch UI Grid: valueGetter for column "" failed` **Cause.** Code supplied by the application (valueGetter for column "") threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-005 `error` · `Birch UI Grid: format for column "" failed` **Cause.** Code supplied by the application (format for column "") threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-006 `error` · `Birch UI Grid: comparator for column "" failed` **Cause.** Code supplied by the application (comparator for column "") threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-007 `error` · `Birch UI Grid: valueSetter for column "" failed` **Cause.** Code supplied by the application (valueSetter for column "") threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-008 `error` · `Birch UI Grid: editable callback for column "" failed` **Cause.** Code supplied by the application (editable callback for column "") threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-009 `error` · `Birch UI Grid: editor destroy failed` **Cause.** Code supplied by the application (editor destroy) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-010 `error` · `Birch UI Grid: key handler failed` **Cause.** Code supplied by the application (key handler) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-011 `error` · `Birch UI Grid: module "" failed to install` **Cause.** A grid module threw while installing. This is often a version mismatch between `@birchui/core` and the package that provides the module. **Fix.** Run `npx birchui-doctor` in the project and look for duplicate or mismatched `@birchui/*` packages. Align all `@birchui/*` versions, then check the logged stack trace. ### LQ-GRID-012 `error` · `Birch UI: a "" listener threw` **Cause.** An event listener registered with `on(event, fn)` threw. The grid caught the error so other listeners still ran. **Fix.** Expand the logged error and fix the listener for the event named in the message. ### LQ-GRID-013 `warn` · `Birch UI Grid: undoRedo.limit must be a positive whole number, got . Using .` **Cause.** An option or data value is invalid. The widget did not throw; it used the fallback stated in the message. **Fix.** Correct the value as the message describes. Check the option against the API reference for the installed version. ### LQ-GRID-014 `warn` · `Birch UI Grid: cannot expose "", the name is already part of the grid API` **Cause.** An option or data value is invalid. The widget did not throw; it used the fallback stated in the message. **Fix.** Correct the value as the message describes. Check the option against the API reference for the installed version. ### LQ-GRID-015 `warn` · `Birch UI Grid: needs from @birchui/grid-pro. ` **Cause.** An option that belongs to a Grid Pro feature (grouping, aggregation, tree data, pivoting, range selection, fill handle, master/detail, status bar) is set, but the matching module was not passed to `createGrid`. **Fix.** Install `@birchui/grid-pro`, import the named module from the message and pass it in `modules: [...]`. Check that `@birchui/core` and `@birchui/grid-pro` are on the same version. ### LQ-GRID-016 `error` · `Birch UI Grid: full-width row cleanup failed` **Cause.** Code supplied by the application (full-width row cleanup) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-017 `error` · `Birch UI Grid: rowClass callback failed` **Cause.** Code supplied by the application (rowClass callback) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-018 `error` · `Birch UI Grid: full-width renderer for "" rows failed` **Cause.** Code supplied by the application (full-width renderer for "" rows) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-019 `error` · `Birch UI Grid: cellClass for column "" failed` **Cause.** Code supplied by the application (cellClass for column "") threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-020 `error` · `Birch UI Grid: cell decorator failed` **Cause.** Code supplied by the application (cell decorator) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-021 `error` · `Birch UI Grid: cell renderer for column "" failed` **Cause.** Code supplied by the application (cell renderer for column "") threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-022 `warn` · `Birch UI Grid: the contextMenu option must return an array of menu items. Showing the default menu.` **Cause.** An option or data value is invalid. The widget did not throw; it used the fallback stated in the message. **Fix.** Correct the value as the message describes. Check the option against the API reference for the installed version. ### LQ-GRID-023 `error` · `Birch UI Grid: the contextMenu callback failed` **Cause.** Code supplied by the application (the contextMenu callback) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-024 `error` · `Birch UI Grid: context menu provider failed` **Cause.** Code supplied by the application (context menu provider) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-025 `warn` · `Birch UI Grid: the browser blocked copying to the clipboard.` **Cause.** The browser refused clipboard write access. This happens on non-secure origins (plain HTTP), inside iframes without the `clipboard-write` permission, or when the action did not come from a user gesture. **Fix.** Serve the page over HTTPS or localhost, and add `allow="clipboard-write"` to embedding iframes. ### LQ-GRID-026 `error` · `Birch UI Grid: header decorator failed` **Cause.** Code supplied by the application (header decorator) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-027 `error` · `Birch UI Grid: column menu provider failed` **Cause.** Code supplied by the application (column menu provider) threw an exception, or an operation it depends on failed. The widget caught it, logged the original error as the second console argument, and continued with a safe fallback. **Fix.** Expand the logged error to find the stack frame in your code. Guard the callback against unexpected input such as `undefined` values, group or total rows, and rows that are still loading. ### LQ-GRID-028 `error` · `Birch UI Grid: menu action "