Compare commits

...
4 Commits
Author SHA1 Message Date
Ken 4700da665c refactor: Simplify validation and types 2026-11-23 18:39:25 +01:00
Ken 0de6bc83bc feat: Harden DataGrid plugin handling
feat: Added tests and storybook
2026-11-22 10:12:38 +01:00
Ken 8c73a23939 feat: Baseline plugin 2026-11-21 17:11:03 +01:00
Ken 6d608cda93 feat: plugins boilerplate 2026-11-20 21:35:30 +01:00
3 changed files with 561 additions and 0 deletions

No files matched your search

@@ -0,0 +1,200 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import React, { useMemo, useState } from "react";
import { DataGrid } from "..";
import { Pagination } from "../../pagination";
import { HStack, VStack } from "../../primitives/stack";
import { Detail } from "../../typography";
import {
type DataGridPlugin,
type DataGridPlugins,
applyTableContext,
useDataGridPlugins,
} from "./useDataGridPlugins";
type InvoiceRow = {
id: string;
invoiceNumber: string;
category: string;
status: string;
amount: string;
};
const DEMO_ROWS: InvoiceRow[] = [
{
id: "1",
invoiceNumber: "INV-2026-001",
category: "Cloud Hosting",
status: "Paid",
amount: "12 400 kr",
},
{
id: "2",
invoiceNumber: "INV-2026-002",
category: "Software License",
status: "Pending",
amount: "4 850 kr",
},
{
id: "3",
invoiceNumber: "INV-2026-003",
category: "Office Supplies",
status: "Paid",
amount: "1 290 kr",
},
{
id: "4",
invoiceNumber: "INV-2026-004",
category: "Security Audit",
status: "Overdue",
amount: "28 000 kr",
},
{
id: "5",
invoiceNumber: "INV-2026-005",
category: "Hardware",
status: "Paid",
amount: "19 990 kr",
},
{
id: "6",
invoiceNumber: "INV-2026-006",
category: "Training",
status: "Pending",
amount: "7 500 kr",
},
{
id: "7",
invoiceNumber: "INV-2026-007",
category: "Domain Renewal",
status: "Paid",
amount: "640 kr",
},
{
id: "8",
invoiceNumber: "INV-2026-008",
category: "Monitoring",
status: "Pending",
amount: "3 200 kr",
},
];
const DEMO_COLUMNS: DataGrid.Columns<InvoiceRow> = [
{
id: "invoiceNumber",
header: "Invoice",
isRowHeader: true,
bodyCell: (row) => row.invoiceNumber,
},
{ id: "category", header: "Category", bodyCell: (row) => row.category },
{ id: "status", header: "Status", bodyCell: (row) => row.status },
{ id: "amount", header: "Amount", bodyCell: (row) => row.amount },
];
/**
* Preview of how `DataGrid` will integrate the plugin API.
* Only two lines are added around `DataGrid`'s children:
* 1. `useDataGridPlugins(userPlugins)` to order and stabilize plugins
* 2. `applyTableContext(plugins, children)` to wrap the grid output
*/
function PluginAwareDataGrid<RowT>({
plugins: userPlugins,
children,
...dataGridProps
}: DataGrid.Props<RowT> & { plugins?: DataGridPlugins }) {
const plugins = useDataGridPlugins(userPlugins);
return (
<DataGrid {...dataGridProps}>
{applyTableContext(plugins, children)}
</DataGrid>
);
}
/**
* Example first-party plugin hook.
* The consumer owns pagination state; the hook returns a memoized `DataGridPlugin`
* that wraps the table with Aksel's `<Pagination />`.
*/
function useDummyPaginationPlugin({
page,
pageSize,
totalItems,
onPageChange,
}: {
page: number;
pageSize: number;
totalItems: number;
onPageChange: (nextPage: number) => void;
}): DataGridPlugin {
return useMemo(() => {
const pageCount = Math.max(1, Math.ceil(totalItems / pageSize));
const start = (page - 1) * pageSize + 1;
const end = Math.min(page * pageSize, totalItems);
return {
transformTableContext: (children) => (
<VStack gap="space-12" data-plugin="pagination">
{children}
<HStack align="center" justify="space-between" gap="space-16" wrap>
<Detail>
Showing {start}–{end} of {totalItems}
</Detail>
<Pagination
page={page}
count={pageCount}
onPageChange={onPageChange}
size="small"
/>
</HStack>
</VStack>
),
};
}, [page, pageSize, totalItems, onPageChange]);
}
const meta: Meta = {
title: "ds-react/DataGrid/Plugins",
parameters: {
chromatic: { disable: true },
layout: "padded",
},
};
export default meta;
type Story = StoryObj;
/**
* Shows the intended consumer API for a first-party plugin hook:
* state stays in consumer code, the hook returns a memoized `DataGridPlugin`,
* and `DataGrid` renders it through `plugins={{ pagination }}`.
*/
export const PaginationPlugin: Story = {
render: function PaginationPluginDemo() {
const [page, setPage] = useState(1);
const pageSize = 3;
const paginationPlugin = useDummyPaginationPlugin({
page,
pageSize,
totalItems: DEMO_ROWS.length,
onPageChange: setPage,
});
const pageRows = useMemo(
() => DEMO_ROWS.slice((page - 1) * pageSize, page * pageSize),
[page],
);
return (
<PluginAwareDataGrid
columns={DEMO_COLUMNS}
data={pageRows}
getRowId={(row) => row.id}
plugins={{ pagination: paginationPlugin }}
>
<DataGrid.Table />
</PluginAwareDataGrid>
);
},
};
@@ -0,0 +1,160 @@
import { renderHook } from "@testing-library/react";
import { afterEach, describe, expect, test, vi } from "vitest";
import * as consoleWarningModule from "../../utils/helpers/consoleWarning";
import {
type DataGridPlugin,
type DataGridPlugins,
applyTableContext,
useDataGridPlugins,
} from "./useDataGridPlugins";
const createContextPlugin = (label: string): DataGridPlugin => ({
transformTableContext: (children) => `${label}(${children})`,
});
describe("useDataGridPlugins", () => {
test("returns a stable empty array when plugins are undefined or empty", () => {
const { result, rerender } = renderHook<
readonly DataGridPlugin[],
{ plugins?: DataGridPlugins }
>(({ plugins }) => useDataGridPlugins(plugins), {
initialProps: { plugins: undefined },
});
const initialResult = result.current;
expect(initialResult).toEqual([]);
rerender({ plugins: {} });
expect(result.current).toBe(initialResult);
});
test("orders known plugins before unknown plugins, ignores prototype keys, and skips non-object entries", () => {
const customFirst = createContextPlugin("first");
const customSecond = createContextPlugin("second");
const pagination = createContextPlugin("pagination");
const { result } = renderHook(() =>
useDataGridPlugins({
zCustom: customFirst,
aCustom: customSecond,
pagination,
}),
);
expect(result.current).toEqual([pagination, customFirst, customSecond]);
const inherited = Object.create({ pagination }) as DataGridPlugins;
inherited.custom = customFirst;
const { result: inheritedResult } = renderHook(() =>
useDataGridPlugins(inherited),
);
expect(inheritedResult.current).toEqual([customFirst]);
// Runtime guard: nullish or primitive entries on known or custom keys are skipped instead of crashing WeakMap
const { result: invalidEntriesResult } = renderHook(() =>
useDataGridPlugins({
pagination: undefined,
customUndefined: undefined,
customNull: null,
customPrimitive: "not-an-object",
valid: customFirst,
} as unknown as DataGridPlugins),
);
expect(invalidEntriesResult.current).toEqual([customFirst]);
});
test("interns array reference by plugin identity and order across inline objects", () => {
const pagination = createContextPlugin("pagination");
const customA = createContextPlugin("a");
const customB = createContextPlugin("b");
const { result, rerender } = renderHook<
readonly DataGridPlugin[],
{ plugins?: DataGridPlugins }
>(({ plugins }) => useDataGridPlugins(plugins), {
initialProps: { plugins: { customA, pagination } },
});
const first = result.current;
expect(Object.isFrozen(first)).toBe(true);
// New inline object with same plugin instances (even in different key order)
rerender({ plugins: { pagination, customA } });
expect(result.current).toBe(first);
// Removing a plugin returns a new array; restoring it returns the interned array
rerender({ plugins: { pagination } });
expect(result.current).not.toBe(first);
expect(result.current).toEqual([pagination]);
rerender({ plugins: { pagination, customA } });
expect(result.current).toBe(first);
// Changing plugin order or replacing an instance produces a new array
rerender({ plugins: { customA, customB } });
const ab = result.current;
rerender({ plugins: { customB, customA } });
expect(result.current).not.toBe(ab);
expect(result.current).toEqual([customB, customA]);
});
});
describe("applyTableContext", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("wraps children in reverse plugin order and skips plugins without a valid transform", () => {
const pagination = createContextPlugin("pagination");
const custom = createContextPlugin("custom");
const noopPlugin = {} as DataGridPlugin;
const invalidPlugin = {
transformTableContext: "not-a-function",
} as unknown as DataGridPlugin;
expect(applyTableContext([], "table")).toBe("table");
expect(
applyTableContext(
[pagination, noopPlugin, invalidPlugin, custom],
"table",
),
).toBe("pagination(custom(table))");
});
test("preserves previous content and warns when transformTableContext returns undefined", () => {
const warnSpy = vi
.spyOn(consoleWarningModule, "consoleWarning")
.mockImplementation(() => {});
const outer = createContextPlugin("outer");
const returnsUndefined: DataGridPlugin = {
transformTableContext: () => undefined,
};
const inner = createContextPlugin("inner");
expect(applyTableContext([outer, returnsUndefined, inner], "table")).toBe(
"outer(inner(table))",
);
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("transformTableContext returned undefined"),
);
});
test("catches plugin errors, logs them, and continues applying remaining plugins", () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const boom = new Error("plugin failure");
const outer = createContextPlugin("outer");
const broken: DataGridPlugin = {
transformTableContext: () => {
throw boom;
},
};
const inner = createContextPlugin("inner");
expect(applyTableContext([outer, broken, inner], "table")).toBe(
"outer(inner(table))",
);
expect(errorSpy).toHaveBeenCalledWith(
"[Aksel] DataGrid: Plugin threw in transformTableContext:",
boom,
);
});
});
@@ -0,0 +1,201 @@
import type { ReactNode } from "react";
import { consoleWarning } from "../../utils/helpers/consoleWarning";
/**
* Plugin that extends DataGrid rendering (e.g. wrapping the table in providers
* or extra UI). Remember to memoize the plugin object (with `useMemo`) so
* DataGrid can skip unnecessary re-renders.
*/
interface DataGridPlugin {
/**
* Wraps the table output in context providers or surrounding UI (e.g. pagination).
* Runs as a plain function during render. Do not call React hooks directly
* inside this function; render a component or provider that calls hooks instead.
*/
transformTableContext: (children: ReactNode) => ReactNode;
}
/**
* Fixed order for built-in plugins so behavior doesn't depend on key order
* in `plugins={{ ... }}`. Custom plugins are placed after these, in their
* original order.
*/
const PLUGIN_ORDER = ["pagination"] as const;
const KNOWN_PLUGINS = new Set<string>(PLUGIN_ORDER);
type BuiltInDataGridPluginKey = (typeof PLUGIN_ORDER)[number];
/**
* Named plugins passed to DataGrid.
*
* Keep plugins always present rather than toggling entries conditionally:
* adding or removing a plugin that wraps children changes React's tree depth and remounts the grid.
* Control active/visible state inside the plugin instead.
*/
type DataGridPlugins = Partial<
Record<BuiltInDataGridPluginKey, DataGridPlugin>
> &
Record<string, DataGridPlugin>;
/**
* We freeze in dev-mode to enforce immutability of the empty plugin array.
* Based on React best practices: https://react.dev/reference/react/createElement#caveats
*/
const EMPTY_PLUGINS: readonly never[] =
process.env.NODE_ENV !== "production" ? Object.freeze([]) : [];
/**
* Turns a `plugins={{ ... }}` object into an ordered, stable plugin array.
*
* - Orders built-in plugins consistently (`orderPlugins`).
* - Keeps the same array reference even when the consumer passes an inline
* `plugins={{ pagination }}` object on every render (`internByIdentity`).
*/
function useDataGridPlugins(
userPlugins?: DataGridPlugins,
): readonly DataGridPlugin[] {
return internByIdentity(orderPlugins(userPlugins));
}
// WeakMap keys must be objects; guard against nullish/primitive entries at runtime.
function isPluginObject(value: unknown): value is DataGridPlugin {
return typeof value === "object" && value !== null;
}
/**
* Places known plugins first (in `PLUGIN_ORDER`), then unknown plugins in
* insertion order.
*/
function orderPlugins(
userPlugins?: DataGridPlugins,
): readonly DataGridPlugin[] {
if (!userPlugins) {
return EMPTY_PLUGINS;
}
const keys = Object.keys(userPlugins);
if (keys.length === 0) {
return EMPTY_PLUGINS;
}
const ordered: DataGridPlugin[] = [];
for (const name of PLUGIN_ORDER) {
/* TS target does not support Object.hasOwn */
if (Object.prototype.hasOwnProperty.call(userPlugins, name)) {
const plugin = userPlugins[name];
if (isPluginObject(plugin)) {
ordered.push(plugin);
}
}
}
for (const name of keys) {
if (!KNOWN_PLUGINS.has(name)) {
const plugin = userPlugins[name];
if (isPluginObject(plugin)) {
ordered.push(plugin);
}
}
}
return ordered;
}
interface InternNode {
readonly next: WeakMap<object, InternNode>;
array?: readonly object[];
}
/**
* Tree of WeakMaps where each path represents a sequence of plugin objects.
* WeakMap lets unused paths be garbage-collected when plugins go away.
*/
const internRoot: InternNode = { next: new WeakMap() };
/**
* Returns the same array instance whenever given the same objects in the same order
* using a WeakMap trie (prefix tree keyed by object identity).
*
* Solves inline `plugins={{ pagination }}` props: `useMemo` on the outer object
* would miss every render, and mutating a `useRef` during render is unsafe in
* StrictMode / concurrent React.
*
* Each item walks one step down `internRoot`:
* ```text
* internRoot
* └─ [pluginA] ──▶ nodeA (array: [pluginA])
* └─ [pluginB] ──▶ nodeAB (array: [pluginA, pluginB])
* └─ [pluginB] ──▶ nodeB
* └─ [pluginA] ──▶ nodeBA (array: [pluginB, pluginA])
* ```
*
* 1. Walk `internRoot` using each item as a `WeakMap` key, creating nodes as needed.
* 2. Cache a copy at the terminal node so future calls with the same sequence return the exact same (`===`) array.
* 3. Unused branches are garbage-collected automatically once any plugin object in the path is no longer referenced.
*/
function internByIdentity<T extends object>(items: readonly T[]): readonly T[] {
if (items.length === 0) {
return EMPTY_PLUGINS;
}
let node = internRoot;
for (const item of items) {
let child = node.next.get(item);
if (child === undefined) {
child = { next: new WeakMap() };
node.next.set(item, child);
}
node = child;
}
if (node.array === undefined) {
const copy = items.slice();
/* Freeze in dev so accidental mutation fails fast instead of corrupting the shared cache. */
node.array =
process.env.NODE_ENV !== "production" ? Object.freeze(copy) : copy;
}
return node.array as readonly T[];
}
/**
* Wraps `children` with each plugin's `transformTableContext`.
* Runs in reverse so the first plugin wraps outermost.
* Synchronous errors are caught and logged, and an `undefined` return preserves
* the previous content so one broken plugin doesn't blank or crash the grid.
*/
function applyTableContext(
plugins: readonly DataGridPlugin[],
children: ReactNode,
): ReactNode {
let content = children;
for (let i = plugins.length - 1; i >= 0; i--) {
const transform = plugins[i].transformTableContext;
if (typeof transform !== "function") {
continue;
}
try {
const next = transform(content);
if (next === undefined) {
consoleWarning(
"DataGrid: Plugin transformTableContext returned undefined. Preserving previous content.",
);
continue;
}
content = next;
} catch (error) {
console.error(
"[Aksel] DataGrid: Plugin threw in transformTableContext:",
error,
);
}
}
return content;
}
export { applyTableContext, useDataGridPlugins };
export type { DataGridPlugin, DataGridPlugins };