@humanspeak/svelte-headless-table
Version:
A powerful, headless table library for Svelte that provides complete control over table UI while handling complex data operations like sorting, filtering, pagination, grouping, and row expansion. Build custom, accessible data tables with zero styling opin
54 lines (53 loc) • 1.59 kB
JavaScript
import { derived } from 'svelte/store';
import { DataBodyRow, getSubRows } from '../bodyRows.js';
/**
* Recursively adds sub-rows to a row based on the children accessor.
* @internal
*/
const withSubRows = (row, getChildren) => {
const subItems = getChildren(row.original);
if (subItems === undefined) {
return row;
}
const subRows = getSubRows(subItems, row);
row.subRows = subRows.map((row) => withSubRows(row, getChildren));
return row;
};
/**
* Creates a sub-rows plugin that enables hierarchical data display.
* Extracts child items from each row using the specified children accessor.
*
* @template Item - The type of data items in the table.
* @param config - Configuration with the children accessor.
* @returns A TablePlugin that creates hierarchical row structure.
* @example
* ```typescript
* interface Employee {
* name: string
* directReports?: Employee[]
* }
*
* const table = createTable(data, {
* subRows: addSubRows({
* children: 'directReports' // or: (item) => item.directReports
* })
* })
* ```
*/
export const addSubRows = ({ children }) => () => {
const getChildren = children instanceof Function ? children : (item) => item[children];
const deriveRows = (rows) => {
return derived(rows, ($rows) => {
return $rows.map((row) => {
if (row.isData()) {
return withSubRows(row, getChildren);
}
return row;
});
});
};
return {
pluginState: {},
deriveRows
};
};