import { ICommand } from 'valor-unistore-undo'; import * as R from 'rambda'; import { IStoreState, IRow } from '../index.data'; import { IRowWithCell } from '../SpreadSheetProvider/index.data'; import { getCurrentRowIndex } from './helper'; import { isTreeRow, getRowi } from '../store/selectors'; import { insertRow, deleteRow, ensureSelectionWhenDelete } from '../store/actions/flattenRow'; import { SpreadSheetRuntime } from '../RuntimeContext'; export interface InsertRowCommandParams { rows: IRowWithCell[]; helpers: { normalizeRow: (rows: IRow[], row: IRowWithCell) => IRowWithCell; }; } interface IUndoContext {} class InsertRowCommand extends ICommand< IStoreState, InsertRowCommandParams, IUndoContext, SpreadSheetRuntime > { // 当前选中的行, rowsToInsert要插入到该行之下 baseI?: number; execute = () => { const { rows: oldRows } = this.params; const rowsToInsert = oldRows.map(row => Object.assign({}, row, { area: 'flatten' })); const state = this.store.getState(); const baseI = R.is(Number, this.baseI) ? this.baseI! : getCurrentRowIndex(state); this.baseI = baseI; if (baseI < 0) return false; const baseRow = state.rows[baseI]; if (isTreeRow(baseRow) || baseI >= state.rows.length - 1 || rowsToInsert.length <= 0) { return false; } const newState = insertRow(state, baseI, rowsToInsert, this.runtime!); this.store.setState(Object.assign(newState, { readyDimensions: true })); // 保存undo环境 // 可以使用params.rowsToInsert.ids, 不用保存 this.undoContext = {}; // 收尾 setTimeout(() => { this.runtime!.setSheetDimensions(); this.runtime!.fsmService.send({ type: 'SELECT.ROW', selectedRow: rowsToInsert[0].id }); }); return true; // 记录历史 }; undo = () => { const deleteIds = this.params.rows.map(it => it.id); ensureSelectionWhenDelete(this.store, deleteIds, this.runtime!, () => { const state = this.store.getState(); const fromIndex = getRowi(state, this.params.rows[0].id); const toIndex = getRowi(state, R.last(this.params.rows)!.id); const newState = deleteRow(this.store.getState(), fromIndex, toIndex, this.runtime!); this.store.setState(Object.assign(newState, { readyDimensions: true })); }); }; } export default InsertRowCommand;