diff --git a/src/Smartable/Row.tsx b/src/Smartable/Row.tsx index 323788d..7310e1c 100644 --- a/src/Smartable/Row.tsx +++ b/src/Smartable/Row.tsx @@ -1,5 +1,5 @@ import React, {useContext, useMemo} from "react"; -import {AutoColumnContextProvider, ColumnKey} from "./Column"; +import {ColumnContext, ColumnKey} from "./Column"; import {CellDefinition, CellInstance} from "./Cell"; import {Smartable, useTable} from "./Smartable"; import {Async, Promisable} from "@kernelui/core"; @@ -69,15 +69,18 @@ export function RowCells() // Get row data. const row = useRow(); + // Get table data. + const {columns} = useTable(); + return ( - Object.entries(row.cells).map(([columnKey, cellData]) => ( - - promise={cellData}> + Object.entries(columns).map(([columnKey, column]) => ( + + promise={row.cells?.[columnKey] ?? { data: undefined }}> {(cellDefinition) => ( )} - + )) ); } diff --git a/src/Smartable/Smartable.tsx b/src/Smartable/Smartable.tsx index 9403c40..2b8a49a 100644 --- a/src/Smartable/Smartable.tsx +++ b/src/Smartable/Smartable.tsx @@ -19,6 +19,11 @@ export interface SmartableProperties */ data: SmartableData; + /** + * When defined, only show the columns in the array. + */ + shownColumns?: CK[]; + /** * Default row element. */ @@ -50,14 +55,40 @@ export function createSmartable({columns}: { columns: Columns; }): Smartable { + /** + * Filter columns, given an array of shown columns. + * @param columns Full columns definition. + * @param shownColumns Shown columns list. + */ + const filterColumns = (columns: Columns, shownColumns: CK[]) => { + // Initialize the filtered columns object. + const filteredColumns = {...columns}; + + // Build an associative object of shown columns. + const shownColumnsMap = Object.fromEntries(shownColumns.map((shownColumn) => [shownColumn, true])) as Record; + + for (const key of Object.keys(columns) as CK[]) + { // For each key, if it is not present in the shown columns + if (!shownColumnsMap?.[key]) + // Delete all columns not present in the shown columns map. + delete filteredColumns[key]; + } + + // Return filtered columns. + return filteredColumns; + }; + return { Table: (props: SmartableProperties) => { + // Filter columns from the given property. + const filteredColumns = props.shownColumns ? filterColumns(columns, props.shownColumns) : columns; + return ( - + ); }, @@ -87,5 +118,5 @@ const TableContext = React.createContext>(undefined) */ export function useTable(smartable?: Smartable): TableContextData { - return useContext(TableContext); + return useContext(TableContext) as TableContextData; }