import { Store } from '@/lib/store'; import { reduce } from 'lodash'; import { LayoutOperator } from '@/lib/operator/LayoutOperator'; /** * 管理整个表格数据的编辑、计算 主要操作 data2D */ export class TreeOperator { private store: Store; private layoutOperator: LayoutOperator; constructor(store: Store, layoutOperator: LayoutOperator) { this.store = store; this.layoutOperator = layoutOperator; } public narrowTreeRow(rowId: string) { const viewRowRecord = this.store.state.view.rowRecord; const rowHeight = this.store.state.config.rowHeight; let indexCount = 0; let topCount = 0; const rowIndex2Id = []; const newRows = Object.keys(viewRowRecord).reduce((result, currentRowId) => { const currentRow = viewRowRecord[currentRowId]; if (currentRow.parentId !== rowId) { result[currentRowId] = { ...currentRow, expand: currentRow.id === rowId ? false : currentRow.expand, top: topCount, index: indexCount, }; rowIndex2Id.push(currentRowId); indexCount = indexCount + 1; topCount = topCount + rowHeight; } return result; }, {}); this.store.mutation.setViewRow(newRows, rowIndex2Id); this.layoutOperator.flushBodyView(); } public expandTreeRow(rowId: string) { const indexRowRecord = this.store.state.index.rowRecord; const viewRowRecord = this.store.state.view.rowRecord; const rowHeight = this.store.state.config.rowHeight; // 累计值 let indexCount = 0; let topCount = 0; const rowIndex2Id = []; // 获取所有的子节点 const subRows = reduce( indexRowRecord, (acc, row) => { if (row.parentId === rowId) { acc.push(row); } return acc; }, [], ); const markAddRow = (rowId) => { indexCount = indexCount + 1; topCount = topCount + rowHeight; rowIndex2Id.push(rowId); }; // 添加子节点到视图,并且重制索引与top const newRows = reduce( viewRowRecord, (acc, row) => { // 命中添加子节点 if (rowId === row.id) { // 添加自己 acc[row.id] = { ...row, index: indexCount, top: topCount, expand: true, }; markAddRow(row.id); // 添加子 subRows.forEach((subRow) => { acc[subRow.id] = { ...subRow, index: indexCount, top: topCount, }; markAddRow(subRow.id); }); } else { acc[row.id] = { ...row, index: indexCount, top: topCount, }; markAddRow(row.id); } return acc; }, {}, ); this.store.mutation.setViewRow(newRows, rowIndex2Id); this.layoutOperator.flushBodyView(); } }