iter(g324): table-core 补 setColumns,换列后失效排序与筛选剔除
This commit is contained in:
@@ -14,7 +14,8 @@ export function createTable<T>(
|
||||
options: TableOptions<T>,
|
||||
): TableInstance<T> & Record<string, unknown> {
|
||||
let data = options.data; // 可变:setRows 整体换数据源(筛选结果、轮询刷新),派生管线照旧跑
|
||||
const { columns, plugins = [], onStateChange } = options;
|
||||
let cols = options.columns; // 可变:setColumns 动态换列(按角色 / 视图切换列集),失效的排序 / 筛选按 key 剔除
|
||||
const { plugins = [], onStateChange } = options;
|
||||
|
||||
const rowKey = options.rowKey ?? ('id' as keyof T & string); // 默认行标识
|
||||
const getKey: (row: T) => RowKey =
|
||||
@@ -64,7 +65,7 @@ export function createTable<T>(
|
||||
|
||||
/*** 取单元格值:优先列 accessor,缺省取 row[key] ***/
|
||||
function getCellValue(row: T, key: string): unknown {
|
||||
const col = columns.find((c) => c.key === key);
|
||||
const col = cols.find((c) => c.key === key);
|
||||
if (col?.accessor) return col.accessor(row);
|
||||
return (row as Record<string, unknown>)[key];
|
||||
}
|
||||
@@ -115,14 +116,29 @@ export function createTable<T>(
|
||||
for (const fn of listeners) fn();
|
||||
}
|
||||
|
||||
/*** 整体替换列定义:引用未变则不动;换列后指向不存在列的排序 / 筛选剔除(列都没了,规则失去语义),分页 / 选择与列集无关、保持不动。 ***/
|
||||
function setColumns(next: typeof cols): void {
|
||||
if (next === cols) return;
|
||||
cols = next;
|
||||
const keys = new Set(next.map((c) => c.key));
|
||||
const sorting = state.sorting.filter((s) => keys.has(s.key));
|
||||
const filters = state.filters.filter((f) => keys.has(f.key));
|
||||
if (sorting.length !== state.sorting.length || filters.length !== state.filters.length) {
|
||||
state = { ...state, sorting, filters }; // 只动失效规则:页码 / 选择保持
|
||||
}
|
||||
onStateChange?.(state);
|
||||
for (const fn of listeners) fn();
|
||||
}
|
||||
|
||||
const instance: TableInstance<T> = {
|
||||
getState: () => state,
|
||||
dispatch,
|
||||
subscribe,
|
||||
setRows,
|
||||
setColumns,
|
||||
getVisibleRows,
|
||||
getAllRows: () => getVisibleRows(false), // 筛选 + 排序后、未分页的全量行(导出等场景)
|
||||
getColumns: () => columns,
|
||||
getColumns: () => cols,
|
||||
getCellValue,
|
||||
isRowSelected: (key) => state.selection.includes(key),
|
||||
};
|
||||
|
||||
@@ -91,6 +91,7 @@ export interface TableInstance<T = unknown> {
|
||||
dispatch(action: Action): void; // 派发动作,唯一变更入口
|
||||
subscribe(fn: () => void): () => void; // 订阅变更,返回取消函数
|
||||
setRows(rows: T[]): void; // 整体换数据源(筛选结果 / 轮询刷新),选择状态按 rowKey 剔除失效行
|
||||
setColumns(columns: ColumnDef<T>[]): void; // 整体换列定义(按角色 / 视图切换列集),失效的排序 / 筛选按 key 剔除
|
||||
getVisibleRows(): RowModel<T>; // 可见行模型(过完整管线)
|
||||
getAllRows(): RowModel<T>; // 筛选 + 排序后、未分页的全量行(导出用)
|
||||
getColumns(): ColumnDef<T>[]; // 列定义
|
||||
|
||||
Reference in New Issue
Block a user