import { ICommand } from 'valor-unistore-undo'; import { IStoreState, ID } from '../index.data'; import { getCurrentRowIndex, restoreSelection, getCurrentRowIndexes } from './helper'; import * as R from 'rambda'; import { moveTreeRow } from '../store/actions/row'; import { isTreeRow } from '../store/selectors'; import { moveRow } from '../store/actions/flattenRow'; import { SpreadSheetRuntime } from '../RuntimeContext'; export interface MoveRowCommandParams { type: 'up' | 'down'; } class MoveRowCommand extends ICommand { isTreeRow?: boolean; rowIndexes?: number[]; // 第一行的第1个单元格, 如果为null. 表示该行被完全合并 cellId: ID | null = null; execute = () => { const { type } = this.params; const state = this.store.getState(); const rowIndexes = R.is(Array, this.rowIndexes) ? this.rowIndexes! : getCurrentRowIndexes(state); if (rowIndexes.length <= 0) return false; const firstRow = state.rows[rowIndexes[0]]; if (firstRow.sealed) return false; const lastRow = state.rows[R.last(rowIndexes)!]; const rowId = firstRow.id; this.cellId = firstRow.cellIds![0]; if (isTreeRow(firstRow) && isTreeRow(lastRow)) { this.isTreeRow = true; const newState = moveTreeRow(state, type, rowIndexes[0]); if (!newState) return false; // 无法移动 this.store.setState(Object.assign(newState, { readyDimensions: true })); this.rowIndexes = [newState.rows.findIndex(r => r.id === rowId)]; } else if (!isTreeRow(firstRow) && !isTreeRow(lastRow)) { this.isTreeRow = false; const newState = moveRow(state, type, rowIndexes); if (!newState) return false; this.store.setState(Object.assign(newState, { readyDimensions: true })); this.rowIndexes = type === 'up' ? rowIndexes.map(it => it - 1) : rowIndexes.map(it => it + 1); } // 收尾 setTimeout(() => { this.runtime!.setSheetDimensions(); }); // 收尾 return true; }; undo = () => { const state = this.store.getState(); const undoType = this.params.type === 'up' ? 'down' : 'up'; if (this.isTreeRow) { const rowId = state.rows[this.rowIndexes![0]].id; const newState = moveTreeRow(state, undoType, this.rowIndexes![0])!; this.store.setState(Object.assign(newState, { readyDimensions: true })); this.rowIndexes = [newState.rows.findIndex(r => r.id === rowId)]; } else { const newState = moveRow(state, undoType, this.rowIndexes!)!; this.store.setState(Object.assign(newState, { readyDimensions: true })); this.rowIndexes = undoType === 'up' ? this.rowIndexes!.map(it => it - 1) : this.rowIndexes!.map(it => it + 1); } setTimeout(() => { this.runtime!.setSheetDimensions(); // 如果该行是一个合并行, 那么有可能无法选择第一个单元格 this.cellId && restoreSelection(this.store, this.cellId!, this.runtime!); }); }; } export default MoveRowCommand;