Documentation
Concepts

Features

A small core and the features your app installs on a grid (keys, sorting, filters, selections, editing, column and row features), each typed and opt-in.

The grid's core renders, scrolls and virtualizes. What an app may not need is a feature: a plain object, made by a factory from its own entry point, that the app installs on a grid when it creates it.

featureentryneedsgives
navigation()/navigationthe keys, the active cell, one tab stop, the grid's roles (Keyboard)
sorting()/sortingcolumns that sort (Sorting)
rowSelection()/row-selectionselected rows and their keys (Row selection)
cellRange()/rangenavigation()a range of cells (Cell selection)
clipboard()/clipboardcellRange()copying and pasting the range
fillHandle()/fillcellRange()the fill handle (Fill handle)
editing()/editingnavigation()cells edited in place (Editing cells)
columnResize()/column-resizeresizable columns, their handles and fits (Column resizing)
columnReorder()/column-reordercolumns and groups moved by a drag or the keys (Column reordering)
columnPinning()/column-pinningcolumns pinned at the start or the end (Pinned columns)
columnGroupCollapse()/column-group-collapsecollapsible column groups (Collapsible groups)
rowExpansion()/row-expansionrows that expand into a detail, RowDetail (Master-detail)
rowGrouping()/row-groupinggroup rows and a tree's parents that expand, the group toggle, the treegrid role (Row grouping)
rowReorder()/row-reorderrows moved by their drag handles or the keys (Row reordering)
cellSpans()/spansa column's colSpan in the body (Column spanning)
summaryRows()/summary-rowsrows of figures under the header and at the bottom, Summary (Summary rows)
filtering()/filteringthe column filters as grid state, data-filtered on a filtered column's header cell (Rows in memory)
search()/searchthe search text as grid state (Rows in memory)
pagination()/paginationthe page, its size and the page count as grid state (Rows in memory)

Every optional behaviour is one of these nineteen: a grid installs only what it uses.

A feature another one needs is installed with it: a grid missing one throws when it is created, naming it (feature "cellRange" requires feature "navigation": install it too). Their order in the list is free.

Installing a feature

Give the root a list of features. Make it once, outside the component (or in a field), so it is the same list on every render.

people-grid.tsx
import { DataGrid } from "@fragiola/data-grid-react";
import { navigation } from "@fragiola/data-grid-react/navigation";
import { sorting } from "@fragiola/data-grid-react/sorting";

const features = [navigation(), sorting()];

export function PeopleGrid({ people }: { people: Person[] }) {
    return (
        <DataGrid.Root features={features} columns={columns} rows={people}>
            {/* … */}
        </DataGrid.Root>
    );
}

The root then takes the features' props: activePosition, sortColumns, defaultSortColumns, onSortColumnsChange, …

Each package re-exports the core's features from an entry of the same name (@fragiola/data-grid-react/sorting, @fragiola/data-grid-vue/sorting, @fragiola/data-grid-angular/sorting), so an app installs one package. The core's own is @fragiola/data-grid/sorting. A feature's hooks are in its entry too: useSelectAll in /row-selection, useFillHandle in /fill, useCellEdit in /editing, useColumnResizer in /column-resize, RowDetail and useRowDetail in /row-expansion, useGroupToggle in /row-grouping, useRowDragHandle in /row-reorder, Summary, SummaryRows, SummaryRow, SummaryCells, SummaryCell and their hooks in /summary-rows (Angular: injectSelectAll, injectFillHandle and *dataGridFillHandle, injectCellEdit and *dataGridCellEdit, injectColumnResizer and *dataGridColumnResizer, the row detail's, the group toggle's, the drag handle's and the summary's directives and inject functions in their entries, SUMMARY_ROWS the summary's). A primitive of a feature is never in the DataGrid namespace, which holds the core's parts only. The core's SummaryRowsProps (the feature's root props) is SummaryRowsFeatureProps in the adapters, whose SummaryRowsProps is the component's; Vue's /summary-rows has typedSummaryRows<TRow>() for typed summary cells.

Fixed when the grid is created

A grid installs its features once, when it is created. A different list given later is ignored, and the console says so once. For other features, mount a new grid (a new key).

The bare grid

With no features, a grid still renders, scrolls and virtualizes, on both axes, as a plain table: the APG table pattern.

  • it is role="table", its rows row, its header cells columnheader, its cells cell;
  • neither the grid nor its cells are tab stops (no tabIndex), no cell is ever active, and the controls inside cells keep their own tab order;
  • the arrows and the other grid keys are the page's;
  • nothing is selectable, nothing copies or pastes, nothing fills, and their props do not compile.

It never sorts either. A column keeps sortable and compare, but without sorting():

  • a sortable: true column does not sort;
  • its header cell carries no aria-sort, data-sortable, data-sort or data-sort-priority, and the header cell's state has no sortable, sortDirection or sortPriority;
  • a click, Enter or Space on a header cell is not the grid's;
  • the sort props do not compile (in Angular, [sortColumns] is not a known input without DataGridSorting).

Nor does it resize, move, pin or collapse a column. The column model stays: columns and groups as declared (their header rows, spans and sticky labels), their width, flex and autoSize. But a column's resizable, reorderable and pinned, and a group's collapsible, do nothing:

  • a resize handle has no behaviour and fit-columns fits nothing; a header cell's drag is a plain press, Ctrl/⌘+Shift+←/→ moves nothing;
  • every column scrolls (pinned is ignored: no sticky cell, no data-pinned);
  • a collapsible group shows its expanded children, and stays so;
  • their props and commands do not compile.

Nor do its rows expand, group, span, move or sum up. The row model stays: the rows as given (a row's kind too, getRowMeta: a group row renders as a row, at its depth), their sizes and measured heights, the windows. But:

  • no row expands and no detail renders (the details' heights are rowExpansion()'s props);
  • no group expands: a group toggle and the keys do nothing, the grid is a grid (never a treegrid) and its rows carry no aria-level, aria-expanded, aria-setsize or aria-posinset;
  • a column's colSpan is never asked: every body cell is one column (a header's spans stay);
  • the grid has no summary rows;
  • a row's drag handle drags nothing and Ctrl/⌘+Shift+↑/↓ moves nothing;
  • their props, commands and primitives do not compile, nor import from the main entry.

Nor does it keep a filter, a search or a page: without filtering(), search() and pagination(), no header cell carries data-filtered, and columnFilters, searchText, pageIndex, pageSize and totalRowCount do not compile. The grid never filters, searches or pages the rows either way: your app does, or /local in memory.

Rows in memory run the stages of the features you give them (useLocalRows, injectLocalRows: features, the root's list) and hand the root their state ([dataGridLocalRows] in Angular): install sorting(), filtering(), search(), pagination() for what they apply, and rowGrouping() when they group (their props then carry the expanded groups). A stage whose feature is not installed is skipped.

Typed by the features

The model's keys are the core's and the installed features': model.run("sort-columns.toggle", …) is a type error on a grid without sorting. The hooks and the refs take the features as a type argument, after the row:

toolbar.tsx
const features = [sorting()];

function ClearSort() {
    const { model } = useDataGrid<Person, typeof features>();
    return (
        <button type="button" onClick={() => model.run("sort-columns.set", { sortColumns: [] })}>
            Clear the sort
        </button>
    );
}

// outside the root: useDataGridRef<Person, typeof features>(), or createDataGridRef<…>()

Without the type argument, they are typed by the core alone. A plain DataGridModel<Person> is a grid of any features: a model with features is one, so code that serves every grid takes it.

At runtime, a command of a feature that is not installed (an untyped call, say) never throws: it returns { ok: false, error: { code: "not_found" } }, as any command the grid does not know. A get of a key no feature has is undefined, an is is false.

Not in your bundle

A feature lives in its own entry point, and the packages' main entries never import one: a feature your app does not import is not in its bundle. pnpm build checks it, failing when a package's main entry holds a feature's code, or when a /local entry does (the pipeline reads the features' state from the props it hands the root, and never imports one).

Your own feature

defineFeature makes one, from @fragiola/data-grid (re-exported by every package). Its types extend FeatureTypes: its slice of the state, the model's options, its commands, get and is keys, and a root's props; this["row"] is the grid's row type, at a member's level. Every part is optional.

flags.ts
import { type DataGridFeature, defineFeature, done, type FeatureTypes } from "@fragiola/data-grid";

interface FlagsTypes extends FeatureTypes {
    readonly state: { readonly flagged: readonly number[] };
    readonly commands: {
        "flags.toggle": { payload: { readonly rowIndex: number }; result: readonly number[] };
    };
    readonly questions: { "row-flagged": { readonly rowIndex: number } };
}

const FLAGS = defineFeature<FlagsTypes>({
    name: "flags",
    initial: () => ({ flagged: [] }),
    commands: {
        "flags.toggle": (state, { rowIndex }) => {
            const flagged = state.flagged.includes(rowIndex)
                ? state.flagged.filter((index) => index !== rowIndex)
                : [...state.flagged, rowIndex];
            return done({ ...state, flagged }, flagged);
        },
    },
    questions: {
        "row-flagged": (state, { rowIndex }) => state.flagged.includes(rowIndex),
    },
});

export function flags(): DataGridFeature<FlagsTypes> {
    return FLAGS;
}

Installed (features: [flags(), sorting()]), its keys are the grid's: model.run("flags.toggle", { rowIndex: 3 }) goes through the same middleware and returns the same results. Its handlers return done(state, value), or fail(code, message). What else a feature can contribute, every part optional:

partwhat it does
requiresthe features it needs, by name
sourceChanged(after, before)keeps its state to new rows or columns
stateChanged(after, before)after every command (and once at creation): keeps its state to the grid's rules
viewthe state keys a view carries, so a change renders
row(view, rowIndex, meta, share), cell(view, cell, span, share)fills a row's or a cell's share (its state and attributes): one object reused, nothing allocated per row or cell
headerCell(view, cell), grid(view)a header cell's state and attributes, the grid's attributes (aria-multiselectable)
navigablethe grid's roles and tab stop are the APG grid's (navigation() has it)
engine(context)its keys, presses, clicks, focus, copies and pastes, drags and engine actions, in the engine
editCell(view, cell, draft, engine)an edited cell's editor props, what its column's renderEditCell gets (editing() has it)
columnLayoutits say in the columns' layout: arrangement(state) gives each sibling list an order (arrange) and the collapsed groups (collapsed), and changed(after, before) tells a state that lays them out otherwise (the columns laid out again, the active cell following its column: columnReorder(), columnGroupCollapse())
columnWidths(state)the widths it gives columns over their declared sizing (columnResize()'s)
pinnedColumns(columns, axis, viewportWidth)the columns pinned in effect and the strips' widths (columnPinning()'s): without it, none
rowDetails(state)the rows showing a detail, ascending (rowExpansion()'s): the core lays their details out on the rows' axis, sizes and measures them; without it, none, and the axis is the rows' own
cellSpansthe body cells' column spans, a reader the core keeps on its state at creation (state.cellSpans, asked through spansOf): the navigation, the ranges and the clipboard ask the same (cellSpans()'s)
treeits rows form a tree: with navigation, a grid whose rows have kinds is a treegrid (rowGrouping()'s)
rootthe props a root takes for it, controlled or not (defineControlled), and plain props it follows (follow: pagination's totalRowCount, the details' heights)

In an engine, a feature's keys run at a place of their own in the grid's: beforeKeydown before any (never taking one), guardKeydown for the elements it holds (an edit's editor), keydown before the grid's own cell keys (a header's sort), startKeydown among them (an edit's start), laterKeydown after them (the selections'), lastKeydown last (the arrows); a column's move (Ctrl/⌘+Shift+←/→) is reordering's keydown. interactionKeydown takes a key on a control of the cell in interaction, after the grid's Escape and Tab there (a resize handle's arrows, Home, End, Enter). Each place runs the features in the list's order; the first to take a key ends it. Its engine context lends it the grid's own means (engine: which cell an event is in, scrolling to a cell, focus following a move, events, drags on the grid's own drag machinery, the columns' layout: columnAxis, viewportWidth, pinned, scrollLeft, viewX, columnOffsetAt, columnEdgeStep, edgeScroll, committed, measureColumns, autoWidths(overrides?)), so its keys and presses act as the grid's do. A drag (FeatureDrag) may follow one axis (axis), ignore a scroll (fixed, a resize) and take the click that ends it (click, a handle's double click). A feature's engine also hears the columns laid out again before the view is built for it (columnsFollowed: a drag follows its column), says when a new layout of the same columns keeps the view on its first column by key (columnAnchored: a collapse), and is told when the engine is destroyed (destroy). A feature may keep a body row rendered out of the rendered rows (heldRow: a row's drag, its handle holding the pointer). The rows' means are lent too (rowAxis, viewY, rowOffsetAt, rowEdgeStep, rowsOrdered): a row's drag is a FeatureDrag along y, as a column's is along x, and a row's move (Ctrl/⌘+Shift+↑/↓) and a row group's keys are keydowns on body cells. Its engine.get keys and engine.run actions are its own: column-resize, column-reorder and fit-columns are the column features', row-reorder row reorder's.

A root's controlled piece (defineControlled) may be a layout input (first: "layout": a column's widths, order or collapsed groups): it settles first of all, then the active position, so a position a layout moved settles in the same pass. The others settle after it, in the features' order (the expanded rows and row groups among them).

Features read each other only through keys (model.get("cell-selection")), never each other's code. Two features of one name, a feature it requires missing, or a key another one already has throws when the grid is created.