From 0efb60bb6694bcec9751f24997731e3ff759494e Mon Sep 17 00:00:00 2001 From: Madeorsk Date: Sat, 20 Jul 2024 12:22:01 +0200 Subject: [PATCH] Add table shown columns filter & fix row cells render. --- src/Smartable/Row.tsx | 13 ++++++++----- src/Smartable/Smartable.tsx | 37 ++++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 8 deletions(-) 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; }