Skip to content

Commit

Permalink
working with string array (OR)
Browse files Browse the repository at this point in the history
  • Loading branch information
mollykreis committed Mar 15, 2024
1 parent aeaa29b commit 7f55eed
Show file tree
Hide file tree
Showing 5 changed files with 161 additions and 12 deletions.
2 changes: 2 additions & 0 deletions packages/nimble-components/src/table-column/base/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ export abstract class TableColumn<
this.setAttribute('slot', this.columnInternals.uniqueId);
}

public getText?(cellRecord: unknown): string;

protected abstract getColumnInternalsOptions(): ColumnInternalsOptions;

protected sortDirectionChanged(): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ export class TableColumnDateTextCellView extends TableColumnTextCellViewBase<
TableColumnDateTextCellRecord,
TableColumnDateTextColumnConfig
> {
public static getText(cellRecord: TableColumnDateTextCellRecord | undefined, columnConfig: TableColumnDateTextColumnConfig | undefined): string {
if (columnConfig) {
return formatNumericDate(
columnConfig.formatter,
cellRecord?.value
);
}
return '';
}

private columnConfigChanged(): void {
this.updateText();
}
Expand All @@ -30,14 +40,7 @@ TableColumnDateTextColumnConfig
}

private updateText(): void {
if (this.columnConfig) {
this.text = formatNumericDate(
this.columnConfig.formatter,
this.cellRecord?.value
);
} else {
this.text = '';
}
this.text = TableColumnDateTextCellView.getText(this.cellRecord, this.columnConfig);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { TableNumberField } from '../../table/types';
import { TableColumnTextBase } from '../text-base';
import { TableColumnSortOperation, TableColumnValidity } from '../base/types';
import { tableColumnDateTextGroupHeaderViewTag } from './group-header-view';
import { tableColumnDateTextCellViewTag } from './cell-view';
import { TableColumnDateTextCellView, tableColumnDateTextCellViewTag } from './cell-view';
import type { ColumnInternalsOptions } from '../base/models/column-internals';
import {
DateTextFormat,
Expand Down Expand Up @@ -135,6 +135,10 @@ export class TableColumnDateText extends TableColumnTextBase {
return this.validator.getValidity();
}

public override getText(cellRecord: TableColumnDateTextCellRecord): string {
return TableColumnDateTextCellView.getText(cellRecord, this.columnInternals.columnConfig as TableColumnDateTextColumnConfig);
}

protected override getColumnInternalsOptions(): ColumnInternalsOptions {
return {
cellRecordFieldNames: ['value'],
Expand Down
138 changes: 135 additions & 3 deletions packages/nimble-components/src/table/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ import {
getSortedRowModel as tanStackGetSortedRowModel,
getGroupedRowModel as tanStackGetGroupedRowModel,
getExpandedRowModel as tanStackGetExpandedRowModel,
getFilteredRowModel as tanStackGetFilteredRowModel,
TableOptionsResolved as TanStackTableOptionsResolved,
SortingState as TanStackSortingState,
RowSelectionState as TanStackRowSelectionState,
GroupingState as TanStackGroupingState,
ExpandedState as TanStackExpandedState,
OnChangeFn as TanStackOnChangeFn
OnChangeFn as TanStackOnChangeFn,
FilterFn as TanStackFilterFn
} from '@tanstack/table-core';
import { keyShift } from '@microsoft/fast-web-utilities';
import { TableColumn } from '../table-column/base';
Expand All @@ -46,7 +48,9 @@ import {
TableRowSelectionToggleEventDetail,
TableRowState,
TableValidity,
TableSetRecordHierarchyOptions
TableSetRecordHierarchyOptions,
TableFilter,
TableFieldName
} from './types';
import { Virtualizer } from './models/virtualizer';
import { getTanStackSortingFunction } from './models/sort-operations';
Expand All @@ -58,6 +62,7 @@ import { InteractiveSelectionManager } from './models/interactive-selection-mana
import { DataHierarchyManager } from './models/data-hierarchy-manager';
import { ExpansionManager } from './models/expansion-manager';
import { waitUntilCustomElementsDefinedAsync } from '../utilities/wait-until-custom-elements-defined-async';
import { diacriticInsensitiveStringNormalizer } from '../utilities/models/string-normalizers';

declare global {
interface HTMLElementTagNameMap {
Expand Down Expand Up @@ -237,6 +242,8 @@ export class Table<

public constructor() {
super();

const that = this;
this.options = {
data: [],
onStateChange: (_: TanStackUpdater<TanStackTableState>) => {},
Expand All @@ -246,22 +253,69 @@ export class Table<
getSortedRowModel: tanStackGetSortedRowModel(),
getGroupedRowModel: tanStackGetGroupedRowModel(),
getExpandedRowModel: tanStackGetExpandedRowModel(),
getFilteredRowModel: tanStackGetFilteredRowModel(),
getRowCanExpand: this.getRowCanExpand,
getIsRowExpanded: this.getIsRowExpanded,
getSubRows: r => r.subRows,
columns: [],
state: {
rowSelection: {},
grouping: [],
columnFilters: [],
expanded: true // Workaround until we can apply a fix to TanStack regarding leveraging our getIsRowExpanded implementation
},
enableRowSelection: row => !row.getIsGrouped(),
enableMultiRowSelection: false,
enableSubRowSelection: false,
enableSorting: true,
enableGrouping: true,
filterFromLeafRows: true,
renderFallbackValue: null,
autoResetAll: false
autoResetAll: false,
// filterFns: {
// foo: this.getGlobalFilterFn
// }
// globalFilterFn: this.getGlobalFilterFn
globalFilterFn: (row: TanStackRow<TableNode<TData>>, columnId: string, filterValue: string[]): boolean => {
let cellText: string | undefined = '';
const record = row.original.clientRecord;
const column = that.columns.find(x => x.columnInternals.uniqueId === columnId);
if (!column) {
return false;
}
if (column.getText) {
const fieldNames = column.columnInternals.dataRecordFieldNames;
if (that.hasValidFieldNames(fieldNames) && record) {
const cellDataValues = fieldNames.map(
field => record[field]
);
const cellRecord = Object.fromEntries(
column.columnInternals.cellRecordFieldNames.map((k, j) => [
k,
cellDataValues[j]
])
);
cellText = column.getText(cellRecord);
} else {
return false;
}
} else {
const fieldName = column.columnInternals.operandDataRecordFieldName;
if (typeof fieldName !== 'string') {
cellText = undefined;
} else {
const cellValue = record[fieldName];
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
cellText = cellValue === undefined || cellValue === null ? undefined : `${cellValue}`;
}
}

if (typeof cellText !== 'string') {
return false;
}
const normalizedCellText = diacriticInsensitiveStringNormalizer(cellText);
return filterValue.some(x => normalizedCellText.includes(diacriticInsensitiveStringNormalizer(x.toString())));
}
};
this.table = tanStackCreateTable(this.options);
this.virtualizer = new Virtualizer(this, this.table);
Expand All @@ -281,6 +335,24 @@ export class Table<
this.updateTableOptions(tanstackUpdates);
}

public async filterData(/*filter: TableFilter[]*/filter: string[]): Promise<void> {
await this.processPendingUpdates();
// this.updateTableOptions({
// filterFns: this.calculateTanStackFilter(filter)
// });
// this.table.setGlobalFilter()
this.updateTableOptions({
state: {
globalFilter: filter
}
});
}

public async clearFilter(): Promise<void> {
await this.processPendingUpdates();
this.table.resetGlobalFilter();
}

public async getSelectedRecordIds(): Promise<string[]> {
await this.processPendingUpdates();
return this.selectionManager.getCurrentSelectedRecordIds();
Expand Down Expand Up @@ -1067,6 +1139,46 @@ export class Table<
});
};

// private readonly getGlobalFilterFn: TanStackFilterFn<TableNode<TData>> = (row: TanStackRow<TableNode<TData>>, columnId: string, filterValue: string): boolean => {
// let cellText: string | undefined = '';
// const record = row.original.clientRecord;
// const column = this.columns.find(x => x.id === columnId);
// if (!column) {
// return false;
// }
// if (column.getText) {
// const fieldNames = column.columnInternals.dataRecordFieldNames;
// if (this.hasValidFieldNames(fieldNames) && record) {
// const cellDataValues = fieldNames.map(
// field => record[field]
// );
// const cellRecord = Object.fromEntries(
// column.columnInternals.cellRecordFieldNames.map((k, j) => [
// k,
// cellDataValues[j]
// ])
// );
// cellText = column.getText(cellRecord);
// } else {
// return false;
// }
// } else {
// const fieldName = column.columnInternals.operandDataRecordFieldName;
// if (typeof fieldName !== 'string') {
// cellText = undefined;
// } else {
// const cellValue = record[fieldName];
// // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
// cellText = cellValue === undefined || cellValue === null ? undefined : `${cellValue}`;
// }
// }

// if (typeof cellText !== 'string') {
// return false;
// }
// return diacriticInsensitiveStringNormalizer(filterValue).includes(diacriticInsensitiveStringNormalizer(filterValue.toString()));
// };

private readonly handleExpandedChange: TanStackOnChangeFn<TanStackExpandedState> = (updaterOrValue: TanStackUpdater<TanStackExpandedState>): void => {
const expandedState = updaterOrValue instanceof Function
? updaterOrValue(this.table.getState().expanded)
Expand All @@ -1085,6 +1197,20 @@ export class Table<
this.expansionManager.toggleRowExpansion(row);
}

// private calculateTanStackFilter(filters: TableFilter[]): { [name: string]: TanStackFilterFn<TableNode<TData>> } {
// const retValue = {};
// filters.forEach((filter: TableFilter, index: number) => {
// retValue[`filter${index}`] = (row: TanStackRow<TData>, columnId: string, filterValue: any) => {
// const cellValue = row.getValue(columnId);
// return cellValue === filterValue;
// };
// });
// return retValue;

// this.table.setGlobalFilter();
// this.table.resetGlobalFilter();
// }

private calculateTanStackSortState(): TanStackSortingState {
const sortedColumns = this.getColumnsParticipatingInSorting().sort(
(x, y) => x.columnInternals.currentSortIndex!
Expand Down Expand Up @@ -1143,6 +1269,12 @@ export class Table<
});
}

private hasValidFieldNames(
keys: readonly (TableFieldName | undefined)[]
): keys is TableFieldName[] {
return keys.every(key => key !== undefined);
}

private calculateTanStackSelectionState(
recordIdsToSelect: readonly string[]
): TanStackRowSelectionState {
Expand Down
8 changes: 8 additions & 0 deletions packages/nimble-components/src/table/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,14 @@ export interface TableColumnConfiguration {
pixelWidth?: number;
}

export interface TableFilter {
matchString: string; // Does this need to support different types?
// matchMode: 'recordValue' | 'renderedValue' | 'custom'
// hierachyMode: 'includeChildren' | 'includeParent' | 'includeMatchesOnly' | 'includeFulHierarchy' -- look at Tanstack's `filterFromLeafRows`. I think our options here may be limited
// columns: 'all' | 'visible-only' | 'custom'
// customColumns: []
}

/**
* @internal
*
Expand Down

0 comments on commit 7f55eed

Please sign in to comment.