@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
67 lines (66 loc) • 2.12 kB
JavaScript
import { derived, writable } from 'svelte/store';
/**
* Recursively extracts rows at a specific depth from the hierarchy.
*
* @template Item - The type of data items.
* @template Row - The row type.
* @param rows - The rows to flatten.
* @param depth - The depth to extract (0 returns current level).
* @returns The flattened rows array.
*/
export const getFlattenedRows = (rows, depth) => {
if (depth === 0)
return rows;
const flattenedRows = [];
for (const row of rows) {
if (row.subRows === undefined)
continue;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
flattenedRows.push(...getFlattenedRows(row.subRows, depth - 1));
}
return flattenedRows;
};
/**
* Creates a flatten plugin that enables displaying rows at a specific depth level.
* Useful for showing only leaf nodes or a specific level of hierarchical data.
*
* @template Item - The type of data items in the table.
* @param config - Configuration options.
* @returns A TablePlugin that provides flattening functionality.
* @example
* ```typescript
* const table = createTable(data, {
* flatten: addFlatten({
* initialDepth: 0 // Start with no flattening
* })
* })
*
* // Flatten to show only first-level children
* table.pluginStates.flatten.depth.set(1)
* ```
*/
export const addFlatten = ({ initialDepth = 0 } = {}) => () => {
const depth = writable(initialDepth);
const pluginState = { depth };
const deriveRows = (rows) => {
return derived([rows, depth], ([$rows, $depth]) => {
return getFlattenedRows($rows, $depth);
});
};
return {
pluginState,
deriveRows,
hooks: {
'tbody.tr.td': () => {
const props = derived([], () => {
const flatten = ($depth) => {
depth.set($depth);
};
const unflatten = () => flatten(0);
return { flatten, unflatten };
});
return { props };
}
}
};
};