# Data Grid

> A spreadsheet-like grid for editing records, with typed columns, sorting and grouping.

Page: https://uicontext.com/docs/components/data-grid

Group: Records.

## When to use

A spreadsheet-like grid for editing records, with typed columns, sorting and grouping. Use [Table](https://uicontext.com/docs/components/table.md) instead when the table is read-only.

## Usage

```ts
import type { Outcome } from "./ui/uicontext/components/domain/Outcome.ts"
import { type Item, type Property, View } from "./ui/uicontext/components/domain/Record.ts"
import { Table } from "./ui/uicontext/components/Table.ts"
import { Value } from "./ui/uicontext/components/Property.ts"

const Message = UiSchema.TaggedEnum({
	RequestedEditTask: { request: Schema.String, item: Schema.String, key: Schema.String, value: Value },
	ChangedTaskView: { view: View },
})

interface Model {
	readonly tasks: ReadonlyArray<Item>
	readonly fields: ReadonlyArray<Property>
	readonly view: View
	readonly outcomes: ReadonlyArray<Outcome>
}

export const Tasks = (h: Html.H<typeof Message.Type>, { tasks, fields, view, outcomes }: Model) =>
	Table(h, {
		props: { label: "Tasks", records: tasks, fields, view, title: { label: "Task", editable: true }, outcomes },
		onEmit: {
			// save the edit, then answer with { _tag: "Accepted" | "Refused", request } in `outcomes`
			RequestedEdit: (edit) => Message.RequestedEditTask(edit),
			// sorting, resizing and hiding columns come back as the next view
			RequestedView: ({ view }) => Message.ChangedTaskView({ view }),
			RequestedOpen: () => undefined,
			RequestedCreate: () => undefined,
			RequestedAction: () => undefined,
			RequestedReorder: () => undefined,
			RequestedCellAction: () => undefined,
			RequestedAddColumn: () => undefined,
			RequestedColumnAction: () => undefined,
			Selected: () => undefined,
		},
	})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### Issues

The example the page opens with: Data Grid in “Issues”.

```ts title="src/demo.ts" source="www/src/examples/data-grid/demo.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { Outcome } from "./ui/uicontext/components/domain/Outcome.ts"
import { View, viewOf } from "./ui/uicontext/components/domain/Record.ts"
import { Item, Value } from "./ui/uicontext/components/Property.ts"
import { Table } from "./ui/uicontext/components/Table.ts"
import { collectionKeymap, gridKeymap, KeymapLegend } from "./ui/uicontext/components/RecordKeys.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { applyEdit, issueFields, issues, issueShortcuts } from "./issues.ts"

const styles = stylex.create({
	stack: { display: "grid", gridTemplateColumns: "minmax(0, 1fr)", gap: 20 },
	frame: { blockSize: 400, inlineSize: "100%" },
})

const Message = UiSchema.TaggedEnum({
	RequestedEditIssue: { request: Schema.String, item: Schema.String, key: Schema.String, value: Value },
	RequestedIssueView: { view: View },
})

export const IssueGrid = Html.component({
	name: "IssueGrid",
	model: Schema.Struct({ records: Schema.Array(Item), outcomes: Schema.Array(Outcome), view: View }),
	message: Message,
}).make({
	init: () => ({ records: issues, outcomes: [], view: viewOf({ hidden: ["customer"] }, "table") }),
	update: {
		RequestedEditIssue: ($, { request, item, key, value }) => {
			// the app's rules decide; this one refuses a negative estimate
			if (key === "estimate" && typeof value === "number" && value < 0) {
				return $.evolve({ outcomes: (o) => [...o.slice(-10), { _tag: "Refused", request, reason: "An estimate can't be negative." }] })
			}
			return $.evolve({
				records: (records) => records.map((r) => (r.id === item ? applyEdit(r, key, value) : r)),
				outcomes: (o) => [...o.slice(-10), { _tag: "Accepted", request }],
			})
		},
		// a header's sort and a column's new width come back as the whole next view
		RequestedIssueView: ($, { view }) => $.evolve({ view }),
	},
	view: (h, { records, outcomes, view }) =>
		h.div.attrs(sx(styles.stack)).children(
			h.div.attrs(sx(styles.frame)).children(
				Table(h, {
					props: {
						label: "Issues",
						records,
						fields: issueFields,
						view,
						title: { label: "Issue", editable: true, width: 300 },
						shortcuts: issueShortcuts,
						resizable: true,
						movable: true,
						freezable: true,
						hideable: true,
						create: "New issue",
						outcomes,
					},
					onEmit: {
						RequestedEdit: (edit) => Message.RequestedEditIssue(edit),
						RequestedView: ({ view }) => Message.RequestedIssueView({ view }),
						RequestedOpen: () => undefined,
						RequestedAction: () => undefined,
						RequestedCreate: () => undefined,
						RequestedReorder: () => undefined,
						RequestedCellAction: () => undefined,
						RequestedAddColumn: () => undefined,
						RequestedColumnAction: () => undefined,
						Selected: () => undefined,
					},
				}),
			),
			KeymapLegend(h, [...gridKeymap, ...collectionKeymap(issueShortcuts)], "Data Grid keyboard shortcuts"),
		),
})
```

### Editing

Edits are requests the app accepts or refuses. This one refuses estimates over 8 and closing an unassigned issue.

```ts title="src/editing.ts" source="www/src/examples/data-grid/editing.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { Outcome } from "./ui/uicontext/components/domain/Outcome.ts"
import { viewOf } from "./ui/uicontext/components/domain/Record.ts"
import { Item, Value } from "./ui/uicontext/components/Property.ts"
import { Table } from "./ui/uicontext/components/Table.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, font } from "./ui/uicontext/components/tokens.stylex.ts"
import { applyEdit, issueFields, issues } from "./issues.ts"

// Every edit is a request. The cell shows the new value at once; the app checks it and answers with
// an Outcome. A refusal puts the old value back, marks the cell and says why.

const styles = stylex.create({
	stack: { display: "grid", gridTemplateColumns: "minmax(0, 1fr)", gap: 12 },
	frame: { blockSize: 260, inlineSize: "100%" },
	log: { margin: 0, color: color.muted, fontSize: font.sm },
})

const Message = UiSchema.TaggedEnum({
	RequestedEditIssue: { request: Schema.String, item: Schema.String, key: Schema.String, value: Value },
})

/** The app's rules: what it refuses, and why. */
const refusal = (record: Item, key: string, value: Value): string | null => {
	if (key === "estimate" && typeof value === "number" && value > 8) return "Split anything over 8 points into smaller issues."
	if (key === "status" && value === "done" && record.values["assignee"] == null) return "Assign the issue before closing it."
	return null
}

export const EditingGrid = Html.component({
	name: "EditingGrid",
	model: Schema.Struct({ records: Schema.Array(Item), outcomes: Schema.Array(Outcome), last: Schema.String }),
	message: Message,
}).make({
	init: () => ({ records: issues.slice(3, 8), outcomes: [], last: "" }),
	update: {
		RequestedEditIssue: ($, { request, item, key, value }) => {
			const record = $.model.records.find((r) => r.id === item)
			const reason = record === undefined ? "That issue is gone." : refusal(record, key, value)
			if (reason !== null) {
				return $.evolve({ outcomes: (o) => [...o.slice(-10), { _tag: "Refused", request, reason }], last: `Refused: ${reason}` })
			}
			return $.evolve({
				records: (records) => records.map((r) => (r.id === item ? applyEdit(r, key, value) : r)),
				outcomes: (o) => [...o.slice(-10), { _tag: "Accepted", request }],
				last: `Saved ${record?.prefix ?? item}.`,
			})
		},
	},
	view: (h, { records, outcomes, last }) =>
		h.div.attrs(sx(styles.stack)).children(
			h.div.attrs(sx(styles.frame)).children(
				Table(h, {
					props: {
						label: "Issues",
						// several grids on one page each need their own id for agents
						agentId: "table:editing-example",
						records,
						fields: issueFields,
						view: viewOf({ hidden: ["labels", "due", "customer", "impact"] }),
						title: { label: "Issue", editable: true, width: 280 },
						selectable: false,
						outcomes,
					},
					onEmit: {
						RequestedEdit: (edit) => Message.RequestedEditIssue(edit),
						RequestedView: () => undefined,
						RequestedOpen: () => undefined,
						RequestedAction: () => undefined,
						RequestedCreate: () => undefined,
						RequestedReorder: () => undefined,
						RequestedCellAction: () => undefined,
						RequestedAddColumn: () => undefined,
						RequestedColumnAction: () => undefined,
						Selected: () => undefined,
					},
				}),
			),
			h.p.attrs(sx(styles.log)).children("Estimates above 8, and closing an unassigned issue, are refused in this example."),
			// what the app last decided, announced once there's something to say
			h.p.attrs({ role: "status", ...sx(styles.log) }).children(last),
		),
})
```

### Grouping

Rows grouped by priority, sorted by due date within each group. Click a group's header to fold it.

```ts title="src/grouping.ts" source="www/src/examples/data-grid/grouping.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { View, viewOf } from "./ui/uicontext/components/domain/Record.ts"
import { Table } from "./ui/uicontext/components/Table.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { issueFields, issues } from "./issues.ts"

// `view.groupBy` puts the rows under a header per value, each with a count; a header folds its
// group away. Sorting a column sorts within each group.

const styles = stylex.create({
	frame: { blockSize: 420, inlineSize: "100%" },
})

const Message = UiSchema.TaggedEnum({ ChangedView: { view: View } })

export const GroupedGrid = Html.component({
	name: "GroupedGrid",
	model: Schema.Struct({ view: View }),
	message: Message,
}).make({
	init: () => ({
		view: viewOf({ groupBy: "priority", sort: [{ key: "due", direction: "asc" }], hidden: ["priority", "customer", "impact"] }),
	}),
	update: { ChangedView: ($, { view }) => $.evolve({ view }) },
	view: (h, { view }) =>
		h.div.attrs(sx(styles.frame)).children(
			Table(h, {
				props: {
					label: "Issues by priority",
					records: issues,
					fields: issueFields,
					view,
					title: { label: "Issue", width: 300 },
					readOnly: "This example only groups and sorts.",
				},
				onEmit: {
					RequestedView: ({ view }) => Message.ChangedView({ view }),
					RequestedEdit: () => undefined,
					RequestedOpen: () => undefined,
					RequestedAction: () => undefined,
					RequestedCreate: () => undefined,
					RequestedReorder: () => undefined,
					RequestedCellAction: () => undefined,
					RequestedAddColumn: () => undefined,
					RequestedColumnAction: () => undefined,
					Selected: () => undefined,
				},
			}),
		),
})
```

### Frozen and moved columns

The title and Status stay in place while the rest scroll. Freeze from a column's menu, drag a header to move it, or drag its edge to resize it.

```ts title="src/frozen-column.ts" source="www/src/examples/data-grid/frozen-column.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { View, viewOf } from "./ui/uicontext/components/domain/Record.ts"
import { Table } from "./ui/uicontext/components/Table.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { issueFields, issues } from "./issues.ts"

// The row number, the title and the first field stay put while the other columns scroll sideways.
// "Freeze up to here" in a column's menu moves the line; dragging a header moves the column. On a
// phone only the title stays, so the frozen columns never fill the screen.

const styles = stylex.create({
	frame: { blockSize: 320, inlineSize: "min(100%, 560px)", marginInline: "auto" },
})

const Message = UiSchema.TaggedEnum({ ChangedView: { view: View } })

export const FrozenTitleGrid = Html.component({
	name: "FrozenTitleGrid",
	model: Schema.Struct({ view: View }),
	message: Message,
}).make({
	init: () => ({
		view: viewOf({ frozen: 1, widths: { status: 160, priority: 150, assignee: 180, labels: 200, estimate: 130, due: 150, customer: 220, impact: 140 } }),
	}),
	update: { ChangedView: ($, { view }) => $.evolve({ view }) },
	view: (h, { view }) =>
		h.div.attrs(sx(styles.frame)).children(
			Table(h, {
				props: {
					label: "Issues",
					// several grids on one page each need their own id for agents
					agentId: "table:frozen-example",
					records: issues,
					fields: issueFields,
					view,
					title: { label: "Issue", width: 240 },
					resizable: true,
					movable: true,
					freezable: true,
					selectable: false,
					readOnly: "This example only arranges columns.",
				},
				onEmit: {
					// a new width, a frozen column or a moved column comes back as the next view
					RequestedView: ({ view }) => Message.ChangedView({ view }),
					RequestedEdit: () => undefined,
					RequestedOpen: () => undefined,
					RequestedAction: () => undefined,
					RequestedCreate: () => undefined,
					RequestedReorder: () => undefined,
					RequestedCellAction: () => undefined,
					RequestedAddColumn: () => undefined,
					RequestedColumnAction: () => undefined,
					Selected: () => undefined,
				},
			}),
		),
})
```

### A CRM base

Companies with typed columns: links, currency, ratings and people.

```ts title="src/crm.ts" source="www/src/examples/data-grid/crm.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { Outcome } from "./ui/uicontext/components/domain/Outcome.ts"
import { View, viewOf } from "./ui/uicontext/components/domain/Record.ts"
import { Item, type Property, Value } from "./ui/uicontext/components/Property.ts"
import { Table } from "./ui/uicontext/components/Table.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { Toaster } from "./ui/uicontext/components/Toast.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"

// A CRM base of companies: money, percents, stars, links, files, a relation to contacts, a rollup
// over open deals and a formula. The pretend app refuses lowering ARR mid-contract, so the old value
// comes back and a toast says why.

const owners = [
	{ value: "maya", label: "Maya Chen", glyph: { _tag: "Person" as const, id: "maya", name: "Maya Chen", agent: false } },
	{ value: "omar", label: "Omar Haddad", glyph: { _tag: "Person" as const, id: "omar", name: "Omar Haddad", agent: false } },
	{ value: "lena", label: "Lena Fischer", glyph: { _tag: "Person" as const, id: "lena", name: "Lena Fischer", agent: false } },
]

const contacts = [
	{ value: "ct1", label: "Priya Raman" },
	{ value: "ct2", label: "Jonas Berg" },
	{ value: "ct3", label: "Sofia Alvarez" },
	{ value: "ct4", label: "Kenji Watanabe" },
	{ value: "ct5", label: "Amara Okafor" },
	{ value: "ct6", label: "Tom Hughes" },
]

export const companyFields: ReadonlyArray<Property> = [
	{
		key: "stage",
		label: "Stage",
		kind: "select",
		options: [
			{ value: "lead", label: "Lead", tone: "gray" },
			{ value: "trial", label: "Trial", tone: "blue" },
			{ value: "customer", label: "Customer", tone: "green" },
			{ value: "churned", label: "Churned", tone: "red" },
		],
	},
	{ key: "owner", label: "Owner", kind: "person", options: owners },
	{ key: "arr", label: "ARR", kind: "number", format: { style: "currency", currency: "USD", decimals: 0 } },
	{ key: "probability", label: "Win probability", kind: "number", format: { style: "percent", decimals: 0 } },
	{ key: "fit", label: "Fit", kind: "rating", max: 5 },
	{ key: "website", label: "Website", kind: "url" },
	{ key: "email", label: "Billing email", kind: "email" },
	{ key: "phone", label: "Phone", kind: "phone" },
	{ key: "files", label: "Contracts", kind: "attachment" },
	{ key: "contact", label: "Primary contact", kind: "relation", relation: { target: "Contacts", multiple: false }, options: contacts },
	{
		key: "deals",
		label: "Open deals",
		kind: "rollup",
		result: "number",
		format: { style: "integer" },
		rollup: { relation: "deals", field: "status", aggregate: "count" },
	},
	{
		key: "perSeat",
		label: "ARR per seat",
		kind: "formula",
		result: "number",
		format: { style: "currency", currency: "USD", decimals: 0 },
		formula: 'prop("ARR") / prop("Seats")',
	},
]

const company = (n: number, title: string, values: Item["values"], extra: Partial<Item> = {}): Item => ({
	id: `co-${n}`,
	title,
	values,
	...extra,
})

const companies: ReadonlyArray<Item> = [
	company(1, "Northwind Freight", { stage: "customer", owner: "maya", arr: 184000, probability: 1, fit: 5, website: "https://northwind.example", email: "ap@northwind.example", phone: "+1 415 555 0142", files: ["https://files.example/northwind-msa.pdf"], contact: ["ct1"], deals: 2, perSeat: 460 }),
	company(2, "Halcyon Health", { stage: "trial", owner: "omar", arr: 0, probability: 0.65, fit: 4, website: "https://halcyon.example", email: "billing@halcyon.example", phone: "+1 617 555 0199", files: [], contact: ["ct2"], deals: 1, perSeat: null }, {
		// one cell's own error: the formula can't divide by zero seats
		cells: { perSeat: { status: "error", note: "Seats is 0: can't divide by zero" } },
	}),
	company(3, "Bluebird Credit Union", { stage: "customer", owner: "lena", arr: 96000, probability: 1, fit: 4, website: "https://bluebird.example", email: "finance@bluebird.example", phone: "+1 312 555 0110", files: ["https://files.example/bluebird-order-form.pdf", "https://files.example/bluebird-dpa.pdf"], contact: ["ct3"], deals: 0, perSeat: 320 }),
	company(4, "Orchard Robotics", { stage: "lead", owner: "maya", arr: 0, probability: 0.2, fit: 3, website: "https://orchard.example", email: null, phone: null, files: [], contact: ["ct4"], deals: 1, perSeat: 0 }),
	company(5, "Lumen Schools", { stage: "trial", owner: "omar", arr: 42000, probability: 0.45, fit: 3, website: "https://lumen.example", email: "it@lumen.example", phone: "+44 20 7946 0321", files: [], contact: ["ct5"], deals: 3, perSeat: 140 }),
	company(6, "Kestrel Logistics", { stage: "churned", owner: "lena", arr: 0, probability: 0, fit: 2, website: "https://kestrel.example", email: "ops@kestrel.example", phone: "+1 206 555 0187", files: ["https://files.example/kestrel-msa.pdf"], contact: ["ct6"], deals: 0, perSeat: 0 }),
]

const styles = stylex.create({
	frame: { blockSize: 360, inlineSize: "100%" },
	hint: { margin: 0, marginBlockStart: space.md, color: color.muted, fontSize: font.sm },
})

const Message = UiSchema.TaggedEnum({
	RequestedEditCompany: { request: Schema.String, item: Schema.String, key: Schema.String, value: Value },
	RequestedCompanyView: { view: View },
})

export const CompanyGrid = Html.component({
	name: "CompanyGrid",
	model: Schema.Struct({ records: Schema.Array(Item), outcomes: Schema.Array(Outcome), view: View }),
	message: Message,
}).make({
	init: () => ({ records: companies, outcomes: [], view: viewOf({ widths: { website: 180 } }, "table") }),
	update: {
		RequestedEditCompany: ($, { request, item, key, value }) => {
			const before = $.model.records.find((r) => r.id === item)?.values.arr
			// the app's rule: ARR can't go down mid-contract. The grid puts the old value back and toasts.
			if (key === "arr" && typeof value === "number" && typeof before === "number" && value < before) {
				return $.evolve({
					outcomes: (o) => [...o.slice(-10), { _tag: "Refused", request, reason: "ARR can't go down mid-contract. Change it at renewal." }],
				})
			}
			return $.evolve({
				records: (records) =>
					records.map((r) =>
						r.id !== item ? r : key === "title" ? { ...r, title: String(value) } : { ...r, values: { ...r.values, [key]: value } },
					),
				outcomes: (o) => [...o.slice(-10), { _tag: "Accepted", request }],
			})
		},
		RequestedCompanyView: ($, { view }) => $.evolve({ view }),
	},
	view: (h, { records, outcomes, view }) =>
		Toaster(h, {
			children: [
				h.div.attrs(sx(styles.frame)).children(
					Table(h, {
						props: {
							label: "Companies",
							records,
							fields: companyFields,
							view,
							title: { label: "Company", editable: true, width: 220 },
							resizable: true,
							create: "Add a company",
							outcomes,
							locale: "en-US",
						},
						onEmit: {
							RequestedEdit: (edit) => Message.RequestedEditCompany(edit),
							RequestedView: ({ view }) => Message.RequestedCompanyView({ view }),
							RequestedOpen: () => undefined,
							RequestedAction: () => undefined,
							RequestedCreate: () => undefined,
							RequestedReorder: () => undefined,
							RequestedCellAction: () => undefined,
							RequestedAddColumn: () => undefined,
							RequestedColumnAction: () => undefined,
							Selected: () => undefined,
						},
					}),
				),
				h.p.attrs(sx(styles.hint)).children("Try lowering Northwind Freight's ARR: the app refuses, the old value comes back and a toast says why."),
			],
		}),
})
```

### Five thousand rows

Only the rows near the visible part are drawn, so scrolling, sorting and editing stay quick.

```ts title="src/large.ts" source="www/src/examples/data-grid/large.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { Outcome } from "./ui/uicontext/components/domain/Outcome.ts"
import { View, viewOf } from "./ui/uicontext/components/domain/Record.ts"
import { Edit, type Item, Value } from "./ui/uicontext/components/Property.ts"
import { Table } from "./ui/uicontext/components/Table.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { applyEdit, issueFields } from "./issues.ts"

// Five thousand issues. Only the rows near the visible part are drawn, so scrolling, sorting and
// moving with the keys stay quick. The records are made once; the Model keeps only the edits the
// app accepted, so the page state stays small.

const areas = ["Billing", "Sign-in", "Search", "Exports", "Notifications", "Admin console", "Mobile app", "Webhooks"]
const problems = [
	"times out for large workspaces",
	"shows the wrong currency",
	"loses the draft on reload",
	"needs an empty state",
	"ignores the saved filter",
	"is slow on the first load",
	"misses keyboard focus",
	"sends a duplicate email",
]
const statuses = ["todo", "doing", "review", "done"]
const priorities = ["urgent", "high", "medium", "low", null]
const assignees = ["ada", "grace", "alan", "scout", null]

const backlog: ReadonlyArray<Item> = Array.from({ length: 5000 }, (_, i) => {
	const n = 5000 - i
	return {
		id: `big-${n}`,
		prefix: `ENG-${n}`,
		title: `${areas[i % areas.length]} ${problems[(i * 7) % problems.length]}`,
		values: {
			status: statuses[(i * 3) % statuses.length]!,
			priority: priorities[(i * 5) % priorities.length]!,
			assignee: assignees[(i * 11) % assignees.length]!,
			labels: i % 3 === 0 ? ["bug"] : i % 3 === 1 ? ["feature"] : [],
			estimate: (i * 13) % 9 || null,
			due: `2027-0${1 + (i % 9)}-${String(1 + (i % 28)).padStart(2, "0")}`,
			customer: [],
			impact: (i % 4) || null,
		},
	}
})

const styles = stylex.create({
	frame: { blockSize: 480, inlineSize: "100%" },
})

const Message = UiSchema.TaggedEnum({
	RequestedEditBacklog: { request: Schema.String, item: Schema.String, key: Schema.String, value: Value },
	RequestedBacklogView: { view: View },
})

// the records with the accepted edits applied, made again only when the edits change
let applied: { readonly edits: ReadonlyArray<Edit>; readonly records: ReadonlyArray<Item> } = { edits: [], records: backlog }
const recordsWith = (edits: ReadonlyArray<Edit>) => {
	if (applied.edits !== edits) {
		const byId = Map.groupBy(edits, (e) => e.item)
		applied = {
			edits,
			records: backlog.map((r) => (byId.get(r.id) ?? []).reduce((record, e) => applyEdit(record, e.key, e.value), r)),
		}
	}
	return applied.records
}

export const LargeBacklog = Html.component({
	name: "LargeBacklog",
	model: Schema.Struct({ edits: Schema.Array(Edit), outcomes: Schema.Array(Outcome), view: View }),
	message: Message,
}).make({
	init: () => ({
		edits: [],
		outcomes: [],
		view: viewOf({ hidden: ["customer", "labels"], sort: [{ key: "due", direction: "asc" }] }),
	}),
	update: {
		RequestedEditBacklog: ($, edit) =>
			$.evolve({
				edits: (edits) => [...edits, edit],
				outcomes: (o) => [...o.slice(-20), { _tag: "Accepted", request: edit.request }],
			}),
		RequestedBacklogView: ($, { view }) => $.evolve({ view }),
	},
	view: (h, { edits, outcomes, view }) =>
		h.div.attrs(sx(styles.frame)).children(
			Table(h, {
				props: {
					label: "Backlog",
					agentId: "table:backlog",
					records: recordsWith(edits),
					fields: issueFields,
					view,
					title: { label: "Issue", editable: true, width: 300 },
					resizable: true,
					movable: true,
					outcomes,
				},
				onEmit: {
					RequestedEdit: (edit) => Message.RequestedEditBacklog(edit),
					RequestedView: ({ view }) => Message.RequestedBacklogView({ view }),
					RequestedOpen: () => undefined,
					RequestedAction: () => undefined,
					RequestedCreate: () => undefined,
					RequestedReorder: () => undefined,
					RequestedCellAction: () => undefined,
					RequestedAddColumn: () => undefined,
					RequestedColumnAction: () => undefined,
					Selected: () => undefined,
				},
			}),
		),
})
```

### Sample data

The examples above import these files.

```ts title="src/issues.ts" source="www/src/examples/_shared/issues.ts"
import type { Item, Property } from "./ui/uicontext/components/Property.ts"
import { color } from "./ui/uicontext/components/tokens.stylex.ts"

// One set of issues for every record view: the list, the board, the data grid, the form and the
// detail all take the same `records` and `fields` (and a `view`), so switching views is switching
// components.

export const people = [
	{ value: "ada", label: "Ada Lovelace", glyph: { _tag: "Person" as const, id: "ada", name: "Ada Lovelace", agent: false } },
	{ value: "grace", label: "Grace Hopper", glyph: { _tag: "Person" as const, id: "grace", name: "Grace Hopper", agent: false } },
	{ value: "alan", label: "Alan Turing", glyph: { _tag: "Person" as const, id: "alan", name: "Alan Turing", agent: false } },
	{ value: "scout", label: "Scout", glyph: { _tag: "Person" as const, id: "scout", name: "Scout", agent: true } },
]

// a relation's options are the records it can link to, with their titles
export const customers = [
	{ value: "northwind", label: "Northwind Freight" },
	{ value: "halcyon", label: "Halcyon Health" },
	{ value: "bluebird", label: "Bluebird Credit Union" },
]

export const issueFields: ReadonlyArray<Property> = [
	{
		key: "status",
		label: "Status",
		kind: "select",
		options: [
			{ value: "todo", label: "Todo", glyph: { _tag: "Ring", color: color.muted, progress: 0, label: "Todo" } },
			{ value: "doing", label: "In Progress", glyph: { _tag: "Ring", color: color.caution, progress: 0.5, label: "In Progress" } },
			{ value: "review", label: "In Review", glyph: { _tag: "Ring", color: color.success, progress: 0.75, label: "In Review" } },
			{ value: "done", label: "Done", glyph: { _tag: "Ring", color: color.done, progress: 1, mark: "check", label: "Done" } },
		],
	},
	{
		key: "priority",
		label: "Priority",
		kind: "select",
		empty: "No priority",
		options: [
			{ value: "urgent", label: "Urgent", glyph: { _tag: "Bars", level: 3, alert: true, label: "Urgent" } },
			{ value: "high", label: "High", glyph: { _tag: "Bars", level: 3, label: "High" } },
			{ value: "medium", label: "Medium", glyph: { _tag: "Bars", level: 2, label: "Medium" } },
			{ value: "low", label: "Low", glyph: { _tag: "Bars", level: 1, label: "Low" } },
		],
	},
	{ key: "assignee", label: "Assignee", kind: "person", empty: "No assignee", options: people },
	{
		key: "labels",
		label: "Labels",
		kind: "multiSelect",
		options: [
			{ value: "bug", label: "Bug", glyph: { _tag: "Swatch", color: color.danger } },
			{ value: "feature", label: "Feature", glyph: { _tag: "Swatch", color: color.info } },
			{ value: "design", label: "Design", glyph: { _tag: "Swatch", color: color.agent } },
		],
	},
	{ key: "estimate", label: "Estimate", kind: "number", empty: "No estimate", description: "In points" },
	{ key: "due", label: "Due", kind: "date" },
	{
		key: "customer",
		label: "Customer",
		kind: "relation",
		relation: { target: "Companies", multiple: false },
		options: customers,
		empty: "No customer",
	},
	{ key: "impact", label: "Impact", kind: "rating", max: 3, description: "How much it matters to the customer" },
]

const issue = (n: number, title: string, values: Item["values"], extra: Partial<Item> = {}): Item => ({
	id: `eng-${n}`,
	prefix: `ENG-${n}`,
	title,
	values,
	...extra,
})

export const issues: ReadonlyArray<Item> = [
	issue(142, "Sign-in link expires before the email arrives", { status: "doing", priority: "urgent", assignee: "ada", labels: ["bug"], estimate: 3, due: "2026-12-04", customer: ["northwind"], impact: 3 }),
	issue(139, "Keyboard shortcuts for triage", { status: "todo", priority: "high", assignee: "grace", labels: ["feature"], estimate: 5, due: "2026-12-11", customer: [], impact: 2 }),
	issue(137, "Export drops the last row of a filtered view", { status: "review", priority: "high", assignee: "alan", labels: ["bug"], estimate: 2, due: "2026-12-03", customer: ["halcyon"], impact: 3 }),
	issue(135, "Draft release notes for 2.4", { status: "doing", priority: "medium", assignee: "scout", labels: [], estimate: 1, due: "2026-12-06", customer: [], impact: null }, { busy: "Scout is writing" }),
	issue(131, "Empty states for saved views", { status: "todo", priority: "medium", assignee: "ada", labels: ["design"], estimate: 3, due: null, customer: [], impact: 1 }),
	issue(128, "Notifications arrive twice on mobile", { status: "todo", priority: "low", assignee: null, labels: ["bug"], estimate: null, due: null, customer: ["bluebird"], impact: 2 }),
	issue(126, "Bulk move issues between teams", { status: "review", priority: "medium", assignee: "grace", labels: ["feature"], estimate: 8, due: "2026-12-09", customer: ["northwind"], impact: 2 }),
	issue(121, "Webhook retries with backoff", { status: "done", priority: "high", assignee: "alan", labels: ["feature"], estimate: 5, due: "2026-11-27", customer: ["halcyon"], impact: 1 }),
	issue(118, "Dark mode contrast on badges", { status: "done", priority: "low", assignee: "ada", labels: ["design"], estimate: 1, due: "2026-11-24", customer: [], impact: 1 }),
	issue(144, "Invoice PDF cuts off long company names", { status: "todo", priority: "urgent", assignee: "grace", labels: ["bug"], estimate: 2, due: "2026-12-02", customer: ["bluebird"], impact: 3 }, { attention: true, note: "Reported by three customers this week" }),
	issue(140, "SAML sign-in for the admin console", { status: "doing", priority: "high", assignee: "alan", labels: ["feature"], estimate: 8, due: "2026-12-18", customer: ["halcyon"], impact: 3 }),
	issue(133, "Triage suggestions for new bug reports", { status: "review", priority: "medium", assignee: "scout", labels: ["feature"], estimate: 3, due: "2026-12-10", customer: [], impact: 2 }),
]

/** Single keys that open a field's picker on the focused (or every selected) issue. */
export const issueShortcuts = [
	{ key: "s", field: "status", label: "Status" },
	{ key: "p", field: "priority", label: "Priority" },
	{ key: "a", field: "assignee", label: "Assignee" },
]

/** Applies an accepted edit to a record: the title, or one of its values. */
export const applyEdit = (record: Item, key: string, value: Item["values"][string]): Item =>
	key === "title" ? { ...record, title: String(value) } : { ...record, values: { ...record.values, [key]: value } }
```

## API reference

**Props**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` | — | The table's accessible name: "Tasks" |
| `agentId` | `string` | `table:<label>` | This table's id for agents, unique on the page; `table:<label>` by default |
| `records` (required) | `Item[]` | — | The records to show, in the order the app gives them |
| `fields` (required) | `Property[]` | — | Every field, in its own order; the view hides and orders them |
| `view` | `ViewInput` | — | How the records show: sort, groupBy, hidden, order, widths and filter |
| `title` | `{ label, width, editable }` | — | The first, frozen column: the record's title. `editable` makes it a text cell |
| `shortcuts` | `FieldShortcut[]` | — | Single keys that open a field's picker on the focused or selected rows: `{ key: "s", field: "stage" }` |
| `selectable` | `boolean` | `true` | A checkbox per row and the action bar; true by default |
| `actions` | `ItemAction[]` | — | Actions offered on each record, such as archive or delete |
| `create` | `string` | — | An "add row" button with this label, emitting `RequestedCreate`; absent hides it (a synced table) |
| `focusRecord` | `string` | — | A record the app just added: its first cell takes focus as its row appears, ready to edit |
| `openable` | `boolean` | — | Each row gets an open button, and Enter on a read-only title opens it |
| `resizable` | `boolean` | — | Column edges can be dragged, or moved with Alt+Arrow keys on a header; each asks for a new view |
| `addColumn` | `string` | — | A "+" header after the last column, emitting `RequestedAddColumn`: its label, "Add a field" |
| `columnActions` | `ItemAction[]` | — | A menu on each header ("Edit field", "Delete field"), emitting `RequestedColumnAction` |
| `hideable` | `boolean` | — | A "Hide field" entry in each field's column menu, asking for a view with the field hidden |
| `freezable` | `boolean` | — | A "Freeze up to here" entry in each field's column menu, asking for a view with `frozen` set |
| `movable` | `boolean` | — | Field headers can be dragged to a new place, or moved with Alt+Shift+Arrow keys; each asks for a new view |
| `readOnly` | `string` | — | Why nothing here can be edited: "You can view this table, not edit it" |
| `loading` | `boolean` | — | Show placeholder rows while the records load |
| `empty` | `{ title, hint }` | — | What the grid says when there are no records: a title and a hint |
| `outcomes` | `Outcome[]` | — | How each requested change settled: pending, accepted, or refused with a reason |
| `notice` | `string \| null` | — | A sentence about the last bulk action or a table-level refusal |
| `rowHeight` | `number` | `32` | A row's height in pixels; 32 by default |
| `locale` | `string` | — | The locale numbers and dates are formatted in; the browser's by default |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedEdit` | `{ request: string; item: string; key: string; value: Value }` | A value the person changed; answer through `outcomes` with the same `request` |
| `RequestedOpen` | `{ item: string }` | Open the record's page |
| `RequestedCreate` | `{ group?: string; title?: string; values?: Record<string, Value> }` | A new record, in the group it was added from ("" for the empty group) |
| `RequestedAction` | `{ action: string; items: string[] }` | One of the view's actions, on these records |
| `RequestedReorder` | `{ item: string; before: string \| null }` | Move `item` before `before`, or last when it's null |
| `RequestedView` | `{ view: View }` | The person changed how the view shows records (its sort, grouping, widths); pass it back as `view` |
| `Selected` | `{ items: string[] }` | The selection changed |
| `RequestedCellAction` | `{ item: string; key: string; action: string }` | A cell's button: "Run agent", "Retry", a button field's press |
| `RequestedAddColumn` | `{}` | The "+" header was pressed: open a field editor to add a field |
| `RequestedColumnAction` | `{ key: string; action: string }` | One of `columnActions` on a column (title for the first) |

**Agent actions**

| Action | Description |
| --- | --- |
| `CommittedEdit` | Set one cell. key: a column key (or title when it's editable). value: an option value, a list of them, text, a number, an ISO date, true/false, or null to clear |
| `ClickedCellAction` | Press a cell's button, such as Run agent or Retry (see the cell's action in the page) |
| `RequestedSelection` | Select rows by id, replacing the selection ([] clears it) |
| `ClickedAction` | Run one of the table's actions on the selected rows; destructive ones name the selection as the target |
| `ClickedSort` | Order the rows by a column key (or title), asc or desc, replacing the view's sort; direction null drops it |
| `ActivatedRow` | Open a row |
| `ClickedCreate` | Add a row |
| `ClickedAddColumn` | Start adding a column |
| `ClickedColumnAction` | Run one of a column's actions (key: a column key, or title); destructive ones name the column |
| `ClickedHideColumn` | Hide a field's column from this view (key: a field key) |
| `ClickedPeek` | Show a row's fields in Peek, beside the grid |
| `ClosedPeek` | Close Peek |

## Wiring it to your app

The grid handles the active cell, selection and showing an edit before it saves. Handle RequestedEdit with an app command, and reply through outcomes with the request's ID.

On success, pass the saved row with an Accepted outcome. On refusal, pass a Refused outcome with the reason and leave the row unchanged. Edits from people and agents can share the same command and rules.

A complete app example, from `workflows.ts`:

```ts title="src/workflows.ts" source="verification/registry-consumer/cases/contracts/src/workflows.ts"
import { Command, UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import { Effect, Schema } from "effect"
import { Outcome, type Property, Value } from "./ui/uicontext/components/Property.ts"
import { Table } from "./ui/uicontext/components/Table.ts"

const Status = Schema.Literals(["Ready", "Paused"])
const isStatus = Schema.is(Status)
const Workflow = Schema.Struct({ id: Schema.String, name: Schema.String, status: Status })
const Edit = { request: Schema.String, item: Schema.String, key: Schema.String, value: Value }
const SaveResult = Schema.Union([
	Schema.TaggedStruct("Saved", { status: Status }),
	Schema.TaggedStruct("Refused", { reason: Schema.String }),
])

export class SaveWorkflow extends Command.Service<SaveWorkflow>()("recipe/SaveWorkflow", {
	args: Edit,
	success: SaveResult,
	mode: "queue",
	group: ["item"],
}) {
	static readonly layer = this.toLayer(({ item, key, value }) =>
		Effect.sleep("350 millis").pipe(Effect.map(() => {
			if (key !== "status" || !isStatus(value)) {
				return { _tag: "Refused", reason: "Enter Ready or Paused." }
			}
			if (item === "billing" && value === "Paused") {
				return { _tag: "Refused", reason: "Billing sync must stay ready." }
			}
			return { _tag: "Saved", status: value }
		})),
	)
}

const Message = UiSchema.TaggedEnum({
	RequestedEdit: Edit,
	SavedEdit: { request: Schema.String, item: Schema.String, result: SaveResult },
	RequestedArchive: { items: Schema.Array(Schema.String) },
})

const properties: ReadonlyArray<Property> = [{ key: "status", label: "Status", kind: "text" }]
const archive = [{ id: "archive", label: "Archive selected", consequential: true }] as const

export const Workflows = Html.component({
	name: "WorkflowStatus",
	model: Schema.Struct({
		workflows: Schema.Array(Workflow),
		pending: Schema.Array(Schema.String),
		outcomes: Schema.Array(Outcome),
		notice: Schema.String,
	}),
	message: Message,
}).make({
	init: () => ({
		workflows: [
			{ id: "digest", name: "Daily digest", status: "Ready" },
			{ id: "billing", name: "Billing sync", status: "Ready" },
		],
		pending: [],
		outcomes: [],
		notice: "Changes are kept until you reload this page.",
	}),
	update: {
		RequestedEdit: ($, { request, item, key, value }) =>
			$.evolve({ pending: (pending) => [...pending, request] })
				.run(Command.map(
					SaveWorkflow.make({ request, item, key, value }),
					(result) => Message.SavedEdit({ request, item, result }),
				)),
		SavedEdit: ($, { request, item, result }) => {
			if (!$.model.pending.includes(request)) return $.model
			const saved = result._tag === "Saved"
			return $.evolve({
				workflows: saved
					? $.model.workflows.map((workflow) => workflow.id === item ? { ...workflow, status: result.status } : workflow)
					: $.model.workflows,
				pending: (pending) => pending.filter((id) => id !== request),
				outcomes: (outcomes) => [...outcomes, saved ? { _tag: "Accepted" as const, request } : { _tag: "Refused" as const, request, reason: result.reason }],
				notice: saved ? "Status saved." : "Status left unchanged.",
			})
		},
		RequestedArchive: ($, { items }) => {
			if ($.model.pending.length !== 0) return $.model
			return $.evolve({
				workflows: (workflows) => workflows.filter(({ id }) => !items.includes(id)),
				notice: "Selection archived.",
			})
		},
	},
	view: (h, model) => {
		const items = model.workflows.map(({ id, name, status }) => ({ id, title: name, values: { status } }))
		return h.section.attr("aria-labelledby", "workflow-heading").children(
			h.header.children(
				h.h2.attr("id", "workflow-heading").children("Workflow status"),
				h.p.children("Press Enter on a status to edit it. Try pausing Billing sync to see a refused save."),
			),
			h.div.attr("class", "table").children(
				Table(h, {
					key: "workflows",
					props: {
						agentId: "workflows",
						label: "Workflows",
						title: { label: "Workflow", width: 176 },
						view: { widths: { status: 160 } },
						rowHeight: 40,
						records: items,
						fields: properties,
						outcomes: model.outcomes,
						actions: model.pending.length === 0 ? archive : [],
					},
					onEmit: {
						RequestedEdit: (edit) => Message.RequestedEdit(edit),
						RequestedAction: ({ action, items }) => action === "archive" ? Message.RequestedArchive({ items }) : undefined,
						RequestedOpen: () => undefined,
						RequestedCreate: () => undefined,
						RequestedReorder: () => undefined,
						RequestedView: () => undefined,
						RequestedCellAction: () => undefined,
						RequestedAddColumn: () => undefined,
						RequestedColumnAction: () => undefined,
						Selected: () => undefined,
					},
				}),
			),
			h.p.attrs({ class: "feedback", role: "status" }).children(
				model.pending.length > 0 ? "Saving changes…" : model.notice,
			),
		)
	},
})
```

## Keyboard and accessibility

### Keys

| Keys | Does |
| --- | --- |
| Up arrow, Down arrow, Left arrow, Right arrow | Move between cells, the header row included |
| Alt+Left arrow, Alt+Right arrow | On a header, narrow or widen the column |
| Enter, F2 | Edit the cell, or type to replace it; Escape cancels and Tab saves and moves |
| Shift+Down arrow, Shift+Right arrow | Stretch a range of cells; Shift+click or drag does too |
| Control+C, Control+V | Copy or paste cells as tab-separated text; one value pasted fills the range |
| Control+D | Fill down from the range's top row, or from the row above |
| Delete | Clear the cell or the range |
| Control+Z, Control+Shift+Z | Undo or redo your last change |
| Alt+Shift+Right arrow | Move a column, on its header |
| J, Down arrow | Next record |
| K, Up arrow | Previous record |
| Shift+J, Shift+K | Extend the selection |
| X | Select or unselect |
| Space | Peek at the record; Escape closes it |
| Enter | Open the record |
| Escape | Clear the selection |
| S, P, A | Open the picker for a field the app gives a shortcut, on the focused or selected records |

On a Mac, Control is Command and Alt is Option. Left and Right trade places in right-to-left text.

- A grid: arrow keys move between cells and headers, Enter or F2 edits, typing starts an edit, Escape cancels, Tab saves and moves on.
- Mod+C copies the selected cells, and pasting tab-separated text fills a block.
- Shift+F10 on a header opens its column actions; Alt+Left and Alt+Right resize a column.
- A refused edit puts the old value back and says why.
- A cell that can't be edited is read-only, and says why as its description and in a tip under it while it has focus, by keyboard or touch.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/data-grid
```

With npm: `npx shadcn@latest add checkfu/uicontext/data-grid`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/data-grid`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/data-grid`.

It writes these files:

- `src/ui/uicontext/components/Button.ts`
- `src/ui/uicontext/components/CollectionFocus.ts`
- `src/ui/uicontext/components/Direction.ts`
- `src/ui/uicontext/components/Filter.ts`
- `src/ui/uicontext/components/FormControls.ts`
- `src/ui/uicontext/components/Glyph.ts`
- `src/ui/uicontext/components/IconStroke.ts`
- `src/ui/uicontext/components/InlineNotice.ts`
- `src/ui/uicontext/components/Kbd.ts`
- `src/ui/uicontext/components/Menu.ts`
- `src/ui/uicontext/components/Motion.ts`
- `src/ui/uicontext/components/Peek.ts`
- `src/ui/uicontext/components/Popover.ts`
- `src/ui/uicontext/components/Property.ts`
- `src/ui/uicontext/components/RecordKeys.ts`
- `src/ui/uicontext/components/RequestNonce.ts`
- `src/ui/uicontext/components/SegmentedControl.ts`
- `src/ui/uicontext/components/Sheet.ts`
- `src/ui/uicontext/components/ShowText.ts`
- `src/ui/uicontext/components/States.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/Table.ts`
- `src/ui/uicontext/components/Toast.ts`
- `src/ui/uicontext/components/agent/Agent.ts`
- `src/ui/uicontext/components/button.stylex.ts`
- `src/ui/uicontext/components/collection.stylex.ts`
- `src/ui/uicontext/components/domain/Format.ts`
- `src/ui/uicontext/components/domain/Glyph.ts`
- `src/ui/uicontext/components/domain/Outcome.ts`
- `src/ui/uicontext/components/domain/Permission.ts`
- `src/ui/uicontext/components/domain/Record.ts`
- `src/ui/uicontext/components/safeArea.stylex.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/touch.stylex.ts`
- `src/ui/uicontext/components/variants.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/Table.ts](https://github.com/checkfu/uicontext/blob/main/src/Table.ts)

## Used in

- [SaaS dashboard](https://uicontext.com/blocks/saas-dashboard.md)
- [Company brain](https://uicontext.com/blocks/doc-workspace.md)
- [Database](https://uicontext.com/blocks/tables.md)
- [CRM](https://uicontext.com/blocks/crm.md)
- [Storefront](https://uicontext.com/blocks/storefront.md)

## Related

- [Pivot Table](https://uicontext.com/docs/components/pivot-table.md) (`pivot-table`): Records summed two ways, such as revenue by region and quarter, with totals on both edges and cells tinted by size.
- [Table](https://uicontext.com/docs/components/table.md) (`table`): A simple read-only table with a caption, row headers and an empty state.
- [Group Header](https://uicontext.com/docs/components/group-header.md) (`group-header`): The line over a group of rows with its count, sticky while they scroll, folding the group.
- [Description List](https://uicontext.com/docs/components/description-list.md) (`description-list`): A record's facts as label and value pairs, in rows or columns, with Copy for ids.
- [Fact Grid](https://uicontext.com/docs/components/fact-grid.md) (`fact-grid`): A few numbers about one thing, such as a customer's plan and seats, as small tiles.
- [Order Summary](https://uicontext.com/docs/components/order-summary.md) (`order-summary`): What an order comes to: its lines, then subtotal, discount, shipping, tax and the total.
