@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
87 lines (86 loc) • 2.55 kB
JavaScript
import { derived } from 'svelte/store';
/**
* Creates a grid layout plugin that renders the table using CSS Grid.
* This allows for more flexible layouts and better handling of complex headers.
*
* @template Item - The type of data items in the table.
* @returns A TablePlugin that applies CSS Grid layout to the table.
* @example
* ```typescript
* const table = createTable(data, {
* grid: addGridLayout()
* })
* ```
*/
export const addGridLayout = () => ({ tableState }) => {
const pluginState = {};
const deriveTableAttrs = (attrs) => {
return derived([attrs, tableState.visibleColumns], ([$attrs, $visibleColumns]) => {
return {
...$attrs,
style: {
display: 'grid',
'grid-template-columns': `repeat(${$visibleColumns.length}, auto)`
}
};
});
};
const deriveTableHeadAttrs = (attrs) => {
return derived(attrs, ($attrs) => {
return {
...$attrs,
style: {
display: 'contents'
}
};
});
};
const deriveTableBodyAttrs = (attrs) => {
return derived(attrs, ($attrs) => {
return {
...$attrs,
style: {
display: 'contents'
}
};
});
};
return {
pluginState,
deriveTableAttrs,
deriveTableHeadAttrs,
deriveTableBodyAttrs,
hooks: {
'thead.tr': () => {
const attrs = derived([], () => {
return {
style: {
display: 'contents'
}
};
});
return { attrs };
},
'thead.tr.th': (cell) => {
const attrs = derived([], () => {
return {
style: {
'grid-column': `${cell.colstart + 1} / span ${cell.colspan}`
}
};
});
return { attrs };
},
'tbody.tr': () => {
const attrs = derived([], () => {
return {
style: {
display: 'contents'
}
};
});
return { attrs };
}
}
};
};