Compare commits

...
Author SHA1 Message Date
Ken 14cb7ebc44 refactor: Update types to avoid as casting 2026-11-26 14:29:29 +01:00
KenandHalvor Haugan 4d5be5b09c Apply suggestion from @HalvorHaugan
Co-authored-by: Halvor Haugan <83693529+HalvorHaugan@users.noreply.github.com>
2026-11-26 14:26:41 +01:00
Ken 49d2cd34f7 chore: Added todo 2026-11-26 14:24:46 +01:00
Ken 47f7545cdc Merge branch 'main' into datagrid-plugins 2026-11-26 09:49:43 +01:00
Ken 229c07bdec Merge branch 'main' into datagrid-plugins 2026-11-25 14:52:39 +01:00
Ken dd2c32c476 fix: Remove non-relevant test 2026-11-25 14:51:12 +01:00
Ken 903e090732 refactor: Update error-handling, testing plugin and plugin validation 2026-11-25 14:41:49 +01:00
Ken 010a2028f8 refactor: Replace DataGrid plugin hook with resolver 2026-11-24 09:11:12 +01:00
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 503 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,
resolveDataGridPlugins,
} from "./dataGridPlugins";
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. `resolveDataGridPlugins(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 = resolveDataGridPlugins(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,119 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import * as consoleWarningModule from "../../utils/helpers/consoleWarning";
import {
type DataGridPlugin,
type DataGridPlugins,
applyTableContext,
resolveDataGridPlugins,
} from "./dataGridPlugins";
const createTestPlugin = (label: string): DataGridPlugin => ({
transformTableContext: (children) => `${label}(${children})`,
});
describe("resolveDataGridPlugins", () => {
test("returns a stable empty array when plugins are undefined or empty", () => {
const initialResult = resolveDataGridPlugins(undefined);
expect(initialResult).toEqual([]);
expect(resolveDataGridPlugins({})).toBe(initialResult);
});
test("orders known plugins before unknown plugins, ignores prototype keys, and skips non-object entries", () => {
const customFirst = createTestPlugin("first");
const customSecond = createTestPlugin("second");
const pagination = createTestPlugin("pagination");
expect(
resolveDataGridPlugins({
zCustom: customFirst,
aCustom: customSecond,
pagination,
}),
).toEqual([pagination, customFirst, customSecond]);
const inherited = Object.create({ pagination }) as DataGridPlugins;
inherited.custom = customFirst;
expect(resolveDataGridPlugins(inherited)).toEqual([customFirst]);
});
test("interns array reference by plugin identity and order across inline objects", () => {
const pagination = createTestPlugin("pagination");
const customA = createTestPlugin("a");
const customB = createTestPlugin("b");
const first = resolveDataGridPlugins({ customA, pagination });
expect(Object.isFrozen(first)).toBe(true);
// New inline object with same plugin instances (even in different key order)
expect(resolveDataGridPlugins({ pagination, customA })).toBe(first);
// Removing a plugin returns a new array; restoring it returns the interned array
const paginationOnly = resolveDataGridPlugins({ pagination });
expect(paginationOnly).not.toBe(first);
expect(paginationOnly).toEqual([pagination]);
expect(resolveDataGridPlugins({ pagination, customA })).toBe(first);
// Changing plugin order or replacing an instance produces a new array
const ab = resolveDataGridPlugins({ customA, customB });
const ba = resolveDataGridPlugins({ customB, customA });
expect(ba).not.toBe(ab);
expect(ba).toEqual([customB, customA]);
});
});
describe("applyTableContext", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("wraps children in reverse plugin order and skips plugins without a valid transform", () => {
const pagination = createTestPlugin("pagination");
const custom = createTestPlugin("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 a falsy value", () => {
const warnSpy = vi
.spyOn(consoleWarningModule, "consoleWarning")
.mockImplementation(() => {});
const outer = createTestPlugin("outer");
const returnsUndefined: DataGridPlugin = {
transformTableContext: () => undefined,
};
const returnsNull: DataGridPlugin = {
transformTableContext: () => null,
};
const returnsFalse: DataGridPlugin = {
transformTableContext: () => false,
};
const inner = createTestPlugin("inner");
expect(
applyTableContext(
[outer, returnsUndefined, returnsNull, returnsFalse, inner],
"table",
),
).toBe("outer(inner(table))");
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('transformTableContext returned "undefined"'),
);
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('transformTableContext returned "null"'),
);
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('transformTableContext returned "false"'),
);
});
});
@@ -0,0 +1,184 @@
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>;
const EMPTY_PLUGINS: readonly never[] = [];
/**
* 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 resolveDataGridPlugins(
userPlugins?: DataGridPlugins,
): readonly DataGridPlugin[] {
return internByIdentity(orderPlugins(userPlugins));
}
/**
* 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];
plugin && ordered.push(plugin);
}
}
for (const name of keys) {
if (!KNOWN_PLUGINS.has(name)) {
const plugin = userPlugins[name];
plugin && ordered.push(plugin);
}
}
return ordered;
}
interface InternNode {
readonly next: WeakMap<DataGridPlugin, InternNode>;
array?: readonly DataGridPlugin[];
}
/**
* 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(
items: readonly DataGridPlugin[],
): readonly DataGridPlugin[] {
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;
}
/**
* Wraps `children` with each plugin's `transformTableContext`.
* Runs in reverse so the first plugin wraps outermost.
* A falsy return (`undefined`, `null`, `false`, etc.) preserves the previous
* content so one broken plugin doesn't accidentally blank the grid.
*
* TODO: Consier returning plugin name with plugin for better debugging and error messages.
*/
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;
}
const next = transform(content);
if (!next) {
consoleWarning(
`DataGrid: A plugin's transformTableContext returned "${String(next)}". Preserving previous content.`,
);
continue;
}
content = next;
}
return content;
}
export { applyTableContext, resolveDataGridPlugins };
export type { DataGridPlugin, DataGridPlugins };