diff --git a/CHANGELOG.md b/CHANGELOG.md index 4311e9c8a9..1c3efbb71a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- Added support for row and column reordering. (#343) + +### Fixed +- Fixed a bug with serialization of some addresses after CRUDs. (#587) + ## [0.4.0] - 2020-12-17 ### Changed diff --git a/src/Cell.ts b/src/Cell.ts index 51d2ed936a..1d428629ca 100644 --- a/src/Cell.ts +++ b/src/Cell.ts @@ -136,6 +136,8 @@ export interface SimpleRowAddress { export const simpleRowAddress = (sheet: number, row: number): SimpleRowAddress => ({sheet, row}) +export const invalidSimpleRowAddress = (address: SimpleRowAddress): boolean => (address.row < 0) + export interface SimpleColumnAddress { col: number, sheet: number, @@ -143,6 +145,8 @@ export interface SimpleColumnAddress { export const simpleColumnAddress = (sheet: number, col: number): SimpleColumnAddress => ({sheet, col}) +export const invalidSimpleColumnAddress = (address: SimpleColumnAddress): boolean => (address.col < 0) + export interface SimpleCellAddress { col: number, row: number, diff --git a/src/CrudOperations.ts b/src/CrudOperations.ts index 04410f9d90..31f08e2c5f 100644 --- a/src/CrudOperations.ts +++ b/src/CrudOperations.ts @@ -56,7 +56,7 @@ import { RemoveRowsUndoEntry, RemoveSheetUndoEntry, RenameSheetUndoEntry, - SetCellContentsUndoEntry, + SetCellContentsUndoEntry, SetColumnOrderUndoEntry, SetRowOrderUndoEntry, SetSheetContentUndoEntry, UndoRedo } from './UndoRedo' @@ -293,6 +293,97 @@ export class CrudOperations { this.undoRedo.saveOperation(new SetSheetContentUndoEntry(sheetId, oldSheetContent, values)) } + public setRowOrder(sheetId: number, rowMapping: [number, number][]): void { + this.validateSwapRowIndexes(sheetId, rowMapping) + this.testRowOrderForMatrices(sheetId, rowMapping) + this.undoRedo.clearRedoStack() + this.clipboardOperations.abortCut() + this.operations.setRowOrder(sheetId, rowMapping) + this.undoRedo.saveOperation(new SetRowOrderUndoEntry(sheetId, rowMapping)) + } + + public validateSwapRowIndexes(sheetId: number, rowMapping: [number, number][]): void { + if (!this.sheetMapping.hasSheetWithId(sheetId)) { + throw new NoSheetWithIdError(sheetId) + } + this.validateRowOrColumnMapping(sheetId, rowMapping, 'row') + } + + public testColumnOrderForMatrices(sheetId: number, columnMapping: [number, number][]): void { + for(const [source, target] of columnMapping ) { + if(source!==target) { + const rowRange = AbsoluteCellRange.spanFrom({sheet: sheetId, col: source, row: 0}, 1, Infinity) + if (this.dependencyGraph.matrixMapping.isFormulaMatrixInRange(rowRange)) { + throw new SourceLocationHasMatrixError() + } + } + } + } + + + public setColumnOrder(sheetId: number, columnMapping: [number, number][]): void { + this.validateSwapColumnIndexes(sheetId, columnMapping) + this.testColumnOrderForMatrices(sheetId, columnMapping) + this.undoRedo.clearRedoStack() + this.clipboardOperations.abortCut() + this.operations.setColumnOrder(sheetId, columnMapping) + this.undoRedo.saveOperation(new SetColumnOrderUndoEntry(sheetId, columnMapping)) + } + + public validateSwapColumnIndexes(sheetId: number, columnMapping: [number, number][]): void { + if (!this.sheetMapping.hasSheetWithId(sheetId)) { + throw new NoSheetWithIdError(sheetId) + } + this.validateRowOrColumnMapping(sheetId, columnMapping, 'column') + } + + public testRowOrderForMatrices(sheetId: number, rowMapping: [number, number][]): void { + for(const [source, target] of rowMapping ) { + if(source!==target) { + const rowRange = AbsoluteCellRange.spanFrom({sheet: sheetId, col: 0, row: source}, Infinity, 1) + if (this.dependencyGraph.matrixMapping.isFormulaMatrixInRange(rowRange)) { + throw new SourceLocationHasMatrixError() + } + } + } + } + + + public mappingFromOrder(sheetId: number, newOrder: number[], rowOrColumn: 'row' | 'column'): [number, number][] { + if (!this.sheetMapping.hasSheetWithId(sheetId)) { + throw new NoSheetWithIdError(sheetId) + } + const limit = rowOrColumn === 'row' ? this.dependencyGraph.getSheetHeight(sheetId) : this.dependencyGraph.getSheetWidth(sheetId) + if(newOrder.length !== limit) { + throw new InvalidArgumentsError(`number of ${rowOrColumn}s provided to be sheet ${rowOrColumn==='row'?'height':'width'}.`) + } + const ret: [number, number][] = [] + for(let i=0;ia).sort((a, b) => a-b) + const targets = rowMapping.map(([_, b])=>b).sort((a, b) => a-b) + + for(let i=0;i= limit) { + throw new InvalidArgumentsError(`${rowOrColumn} numbers to be nonnegative integers and less than sheet ${rowOrColumn==='row'?'height':'width'}.`) + } + if(sources[i]===sources[i+1]) { + throw new InvalidArgumentsError(`source ${rowOrColumn} numbers to be unique.`) + } + if(sources[i]!==targets[i]) { + throw new InvalidArgumentsError(`target ${rowOrColumn} numbers to be permutation of source ${rowOrColumn} numbers.`) + } + } + } + public undo() { if (this.undoRedo.isUndoStackEmpty()) { throw new NoOperationToUndoError() diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 2eb72e0562..d1d794199d 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -1126,6 +1126,331 @@ export class HyperFormula implements TypedEmitter { return this.recomputeIfDependencyGraphNeedsIt() } + /** + * Reorders rows of a sheet according to a source-target mapping. + * + * Note that this method may trigger dependency graph recalculation. + * + * @param {number} sheetId - ID of a sheet to operate on + * @param {[number, number][]} rowMapping - array mapping original positions to final positions of rows + * + * @fires [[valuesUpdated]] if recalculation was triggered by this change + * + * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist + * @throws [[InvalidArgumentsError]] when rowMapping does not define correct row permutation for some subset of rows of the given sheet + * @throws [[SourceLocationHasMatrixError]] when the selected position has matrix inside + * + * @example + * ```js + * const hfInstance = HyperFormula.buildFromArray([ + * [1], + * [2], + * [4, 5], + * ]); + * + * // should set swap rows 0 and 2 in place, returns: + * // [{ + * // address: { sheet: 0, col: 0, row: 2 }, + * // newValue: 1, + * // }, + * // { + * // address: { sheet: 0, col: 1, row: 2 }, + * // newValue: null, + * // }, + * // { + * // address: { sheet: 0, col: 0, row: 0 }, + * // newValue: 4, + * // }, + * // { + * // address: { sheet: 0, col: 1, row: 0 }, + * // newValue: 5, + * // }] + * const changes = hfInstance.swapRowIndexes(0, [[0,2],[2,0]]); + * ``` + * + * @category Rows + */ + public swapRowIndexes(sheetId: number, rowMapping: [number, number][]): ExportedChange[] { + this._crudOperations.setRowOrder(sheetId, rowMapping) + return this.recomputeIfDependencyGraphNeedsIt() + } + + /** + * Checks if it is possible to reorder rows of a sheet according to a source-target mapping. + * + * @param {number} sheetId - ID of a sheet to operate on + * @param {[number, number][]} rowMapping - array mapping original positions to final positions of rows + * + * @example + * ```js + * const hfInstance = HyperFormula.buildFromArray([ + * [1], + * [2], + * [4, 5], + * ]); + * + * // returns true + * const isSwappable = hfInstance.isItPossibleToSwapRowIndexes(0, [[0,2],[2,0]]); + * + * // returns false + * const isSwappable = hfInstance.isItPossibleToSwapRowIndexes(0, [[0,1]]); + * ``` + * + * @category Rows + */ + public isItPossibleToSwapRowIndexes(sheetId: number, rowMapping: [number, number][]): boolean { + try { + this._crudOperations.validateSwapRowIndexes(sheetId, rowMapping) + this._crudOperations.testRowOrderForMatrices(sheetId, rowMapping) + return true + } catch (e) { + return false + } + } + + /** + * Reorders rows of a sheet according to a permutation. + * + * Note that this method may trigger dependency graph recalculation. + * + * @param {number} sheetId - ID of a sheet to operate on + * @param {number[]} newRowOrder - permutation of rows + * + * @fires [[valuesUpdated]] if recalculation was triggered by this change + * + * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist + * @throws [[InvalidArgumentsError]] when rowMapping does not define correct row permutation for some subset of rows of the given sheet + * @throws [[SourceLocationHasMatrixError]] when the selected position has matrix inside + * + * @example + * ```js + * const hfInstance = HyperFormula.buildFromArray([ + * [1], + * [2], + * [4, 5], + * ]); + * + * // should set swap rows 0 and 2 in place, returns: + * // [{ + * // address: { sheet: 0, col: 0, row: 2 }, + * // newValue: 1, + * // }, + * // { + * // address: { sheet: 0, col: 1, row: 2 }, + * // newValue: null, + * // }, + * // { + * // address: { sheet: 0, col: 0, row: 0 }, + * // newValue: 4, + * // }, + * // { + * // address: { sheet: 0, col: 1, row: 0 }, + * // newValue: 5, + * // }] + * const changes = hfInstance.setRowOrder(0, [2, 1, 0]); + * ``` + * + * @category Rows + */ + public setRowOrder(sheetId: number, newRowOrder: number[]): ExportedChange[] { + const mapping = this._crudOperations.mappingFromOrder(sheetId, newRowOrder, 'row') + return this.swapRowIndexes(sheetId, mapping) + } + + /** + * Checks if it is possible to reorder rows of a sheet according to a permutation. + * + * @param {number} sheetId - ID of a sheet to operate on + * @param {number[]} newRowOrder - permutation of rows + * + * @example + * ```js + * const hfInstance = HyperFormula.buildFromArray([ + * [1], + * [2], + * [4, 5], + * ]); + * + * // returns true + * hfInstance.isItPossibleToSetRowOrder(0, [2, 1, 0]); + * + * // returns false + * hfInstance.isItPossibleToSetRowOrder(0, [2]); + * ``` + * + * @category Rows + */ + public isItPossibleToSetRowOrder(sheetId: number, newRowOrder: number[]): boolean { + try { + const rowMapping = this._crudOperations.mappingFromOrder(sheetId, newRowOrder, 'row') + this._crudOperations.validateSwapRowIndexes(sheetId, rowMapping) + this._crudOperations.testRowOrderForMatrices(sheetId, rowMapping) + return true + } catch (e) { + return false + } + } + + /** + * Reorders columns of a sheet according to a source-target mapping. + * + * Note that this method may trigger dependency graph recalculation. + * + * @param {number} sheetId - ID of a sheet to operate on + * @param {[number, number][]} columnMapping - array mapping original positions to final positions of columns + * + * @fires [[valuesUpdated]] if recalculation was triggered by this change + * + * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist + * @throws [[InvalidArgumentsError]] when columnMapping does not define correct column permutation for some subset of columns of the given sheet + * @throws [[SourceLocationHasMatrixError]] when the selected position has matrix inside + * + * @example + * ```js + * const hfInstance = HyperFormula.buildFromArray([ + * [1, 2, 4], + * [5] + * ]); + * + * // should set swap columns 0 and 2 in place, returns: + * // [{ + * // address: { sheet: 0, col: 2, row: 0 }, + * // newValue: 1, + * // }, + * // { + * // address: { sheet: 0, col: 2, row: 1 }, + * // newValue: 5, + * // }, + * // { + * // address: { sheet: 0, col: 0, row: 0 }, + * // newValue: 4, + * // }, + * // { + * // address: { sheet: 0, col: 0, row: 1 }, + * // newValue: null, + * // }] + * const changes = hfInstance.swapColumnIndexes(0, [[0,2],[2,0]]); + * ``` + * + * @category Columns + */ + public swapColumnIndexes(sheetId: number, columnMapping: [number, number][]): ExportedChange[] { + this._crudOperations.setColumnOrder(sheetId, columnMapping) + return this.recomputeIfDependencyGraphNeedsIt() + } + + /** + * Checks if it is possible to reorder columns of a sheet according to a source-target mapping. + * + * @fires [[valuesUpdated]] if recalculation was triggered by this change + * + * @example + * ```js + * const hfInstance = HyperFormula.buildFromArray([ + * [1, 2, 4], + * [5] + * ]); + * + * // returns true + * hfInstance.isItPossibleToSwapColumnIndexes(0, [[0,2],[2,0]]); + * + * // returns false + * hfInstance.isItPossibleToSwapColumnIndexes(0, [[0,1]]); + * ``` + * + * @category Columns + */ + public isItPossibleToSwapColumnIndexes(sheetId: number, columnMapping: [number, number][]): boolean { + try { + this._crudOperations.validateSwapColumnIndexes(sheetId, columnMapping) + this._crudOperations.testColumnOrderForMatrices(sheetId, columnMapping) + return true + } catch (e) { + return false + } + } + + /** + * Reorders columns of a sheet according to a permutation. + * + * Note that this method may trigger dependency graph recalculation. + * + * @param {number} sheetId - ID of a sheet to operate on + * @param {number[]} newColumnOrder - permutation of columns + * + * @fires [[valuesUpdated]] if recalculation was triggered by this change + * + * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist + * @throws [[InvalidArgumentsError]] when columnMapping does not define correct column permutation for some subset of columns of the given sheet + * @throws [[SourceLocationHasMatrixError]] when the selected position has matrix inside + * + * @example + * ```js + * const hfInstance = HyperFormula.buildFromArray([ + * [1, 2, 4], + * [5] + * ]); + * + * // should set swap columns 0 and 2 in place, returns: + * // [{ + * // address: { sheet: 0, col: 2, row: 0 }, + * // newValue: 1, + * // }, + * // { + * // address: { sheet: 0, col: 2, row: 1 }, + * // newValue: 5, + * // }, + * // { + * // address: { sheet: 0, col: 0, row: 0 }, + * // newValue: 4, + * // }, + * // { + * // address: { sheet: 0, col: 0, row: 1 }, + * // newValue: null, + * // }] + * const changes = hfInstance.setColumnOrder(0, [2, 1, 0]]); + * ``` + * + * @category Columns + */ + public setColumnOrder(sheetId: number, newColumnOrder: number[]): ExportedChange[] { + const mapping = this._crudOperations.mappingFromOrder(sheetId, newColumnOrder, 'column') + return this.swapColumnIndexes(sheetId, mapping) + } + + /** + * Checks if it possible to reorder columns of a sheet according to a permutation. + * + * @param {number} sheetId - ID of a sheet to operate on + * @param {number[]} newColumnOrder - permutation of columns + * + * @example + * ```js + * const hfInstance = HyperFormula.buildFromArray([ + * [1, 2, 4], + * [5] + * ]); + * + * // returns true + * hfInstance.isItPossibleToSetColumnOrder(0, [2, 1, 0]]); + * + * // returns false + * hfInstance.isItPossibleToSetColumnOrder(0, [1]]); + * ``` + * + * @category Columns + */ + public isItPossibleToSetColumnOrder(sheetId: number, newRowOrder: number[]): boolean { + try { + const columnMapping = this._crudOperations.mappingFromOrder(sheetId, newRowOrder, 'column') + this._crudOperations.validateSwapColumnIndexes(sheetId, columnMapping) + this._crudOperations.testColumnOrderForMatrices(sheetId, columnMapping) + return true + } catch (e) { + return false + } + } + /** * Returns information whether it is possible to add rows into a specified position in a given sheet. * Checks against particular rules to ascertain that addRows can be called. diff --git a/src/Operations.ts b/src/Operations.ts index 7e70087050..522e6908a0 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -3,16 +3,14 @@ * Copyright (c) 2020 Handsoncode. All rights reserved. */ -import {Statistics, StatType} from './statistics' -import {ClipboardCell, ClipboardCellType} from './ClipboardOperations' +import {AbsoluteCellRange} from './AbsoluteCellRange' +import {absolutizeDependencies} from './absolutizeDependencies' import {EmptyValue, invalidSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from './Cell' import {CellContent, CellContentParser, RawCellContent} from './CellContentParser' -import {ColumnsSpan, RowsSpan} from './Span' +import {ClipboardCell, ClipboardCellType} from './ClipboardOperations' +import {Config} from './Config' import {ContentChanges} from './ContentChanges' -import {ColumnSearchStrategy} from './Lookup/SearchStrategy' -import {absolutizeDependencies} from './absolutizeDependencies' -import {LazilyTransformingAstService} from './LazilyTransformingAstService' -import {buildMatrixVertex} from './GraphBuilder' +import {ColumnRowIndex} from './CrudOperations' import { AddressMapping, CellVertex, @@ -26,6 +24,12 @@ import { ValueCellVertex } from './DependencyGraph' import {ValueCellVertexValue} from './DependencyGraph/ValueCellVertex' +import {AddColumnsTransformer} from './dependencyTransformers/AddColumnsTransformer' +import {AddRowsTransformer} from './dependencyTransformers/AddRowsTransformer' +import {MoveCellsTransformer} from './dependencyTransformers/MoveCellsTransformer' +import {RemoveColumnsTransformer} from './dependencyTransformers/RemoveColumnsTransformer' +import {RemoveRowsTransformer} from './dependencyTransformers/RemoveRowsTransformer' +import {RemoveSheetTransformer} from './dependencyTransformers/RemoveSheetTransformer' import { InvalidArgumentsError, NamedExpressionDoesNotExistError, @@ -34,24 +38,20 @@ import { SourceLocationHasMatrixError, TargetLocationHasMatrixError } from './errors' -import {NamedExpressionDependency, ParserWithCaching, ProcedureAst, RelativeDependency} from './parser' -import {ParsingError} from './parser/Ast' -import {AddRowsTransformer} from './dependencyTransformers/AddRowsTransformer' -import {RemoveRowsTransformer} from './dependencyTransformers/RemoveRowsTransformer' -import {AddColumnsTransformer} from './dependencyTransformers/AddColumnsTransformer' -import {MoveCellsTransformer} from './dependencyTransformers/MoveCellsTransformer' -import {RemoveSheetTransformer} from './dependencyTransformers/RemoveSheetTransformer' -import {RemoveColumnsTransformer} from './dependencyTransformers/RemoveColumnsTransformer' -import {AbsoluteCellRange} from './AbsoluteCellRange' -import {findBoundaries, Sheet} from './Sheet' -import {Config} from './Config' +import {buildMatrixVertex} from './GraphBuilder' +import {LazilyTransformingAstService} from './LazilyTransformingAstService' +import {ColumnSearchStrategy} from './Lookup/SearchStrategy' import { doesContainRelativeReferences, InternalNamedExpression, NamedExpressionOptions, NamedExpressions } from './NamedExpressions' -import {ColumnRowIndex} from './CrudOperations' +import {NamedExpressionDependency, ParserWithCaching, ProcedureAst, RelativeDependency} from './parser' +import {ParsingError} from './parser/Ast' +import {findBoundaries, Sheet} from './Sheet' +import {ColumnsSpan, RowsSpan} from './Span' +import {Statistics, StatType} from './statistics' export class RemoveRowsCommand { constructor( @@ -309,6 +309,44 @@ export class Operations { } } + public setRowOrder(sheetId: number, rowMapping: [number, number][]): void { + const buffer: [SimpleCellAddress, ClipboardCell][][] = [] + for(const [source, target] of rowMapping ) { + if(source!==target) { + const rowRange = AbsoluteCellRange.spanFrom({sheet: sheetId, col: 0, row: source}, Infinity, 1) + this.dependencyGraph.breakNumericMatricesInRange(rowRange) + const row = this.getRangeClipboardCells(rowRange) + buffer.push( + row.map( + ([{sheet, col, row}, cell]) => [{sheet, col, row: target}, cell] + ) + ) + } + } + buffer.forEach( + row => this.restoreClipboardCells(sheetId, row.values()) + ) + } + + public setColumnOrder(sheetId: number, columnMapping: [number, number][]): void { + const buffer: [SimpleCellAddress, ClipboardCell][][] = [] + for(const [source, target] of columnMapping ) { + if(source!==target) { + const rowRange = AbsoluteCellRange.spanFrom({sheet: sheetId, col: source, row: 0}, 1, Infinity) + this.dependencyGraph.breakNumericMatricesInRange(rowRange) + const column = this.getRangeClipboardCells(rowRange) + buffer.push( + column.map( + ([{sheet, col, row}, cell]) => [{sheet, col: target, row}, cell] + ) + ) + } + } + buffer.forEach( + column => this.restoreClipboardCells(sheetId, column.values()) + ) + } + public addNamedExpression(expressionName: string, expression: RawCellContent, sheetId?: number, options?: NamedExpressionOptions) { this.storeNamedExpressionInCell(this.namedExpressions.lookupNextAddress(expressionName, sheetId), expression) const namedExpression = this.namedExpressions.addNamedExpression(expressionName, sheetId, options) @@ -646,7 +684,8 @@ export class Operations { public setFormulaToCellFromCache(formulaHash: string, address: SimpleCellAddress) { const {ast, hasVolatileFunction, hasStructuralChangeFunction, dependencies} = this.parser.fetchCachedResult(formulaHash) - this.dependencyGraph.setFormulaToCell(address, ast, absolutizeDependencies(dependencies, address), hasVolatileFunction, hasStructuralChangeFunction) + const absoluteDependencies = absolutizeDependencies(dependencies, address) + this.dependencyGraph.setFormulaToCell(address, ast, absoluteDependencies, hasVolatileFunction, hasStructuralChangeFunction) } public setParsingErrorToCell(rawInput: string, errors: ParsingError[], address: SimpleCellAddress) { diff --git a/src/UndoRedo.ts b/src/UndoRedo.ts index 8c49d3beda..8fca476e88 100644 --- a/src/UndoRedo.ts +++ b/src/UndoRedo.ts @@ -46,6 +46,22 @@ export class AddRowsUndoEntry { } } +export class SetRowOrderUndoEntry { + constructor( + public readonly sheetId: number, + public readonly rowMapping: [number, number][] + ) { + } +} + +export class SetColumnOrderUndoEntry { + constructor( + public readonly sheetId: number, + public readonly columnMapping: [number, number][] + ) { + } +} + export class SetSheetContentUndoEntry { constructor( public readonly sheetId: number, @@ -220,6 +236,8 @@ type UndoStackEntry | AddNamedExpressionUndoEntry | RemoveNamedExpressionUndoEntry | ChangeNamedExpressionUndoEntry + | SetRowOrderUndoEntry + | SetColumnOrderUndoEntry export class UndoRedo { private undoStack: UndoStackEntry[] = [] @@ -333,6 +351,10 @@ export class UndoRedo { this.undoRemoveNamedExpression(operation) } else if (operation instanceof ChangeNamedExpressionUndoEntry) { this.undoChangeNamedExpression(operation) + } else if (operation instanceof SetRowOrderUndoEntry) { + this.undoSetRowOrder(operation) + } else if (operation instanceof SetColumnOrderUndoEntry) { + this.undoSetColumnOrder(operation) } else { throw 'Unknown element' } @@ -495,6 +517,16 @@ export class UndoRedo { this.operations.restoreNamedExpression(operation.namedExpression, operation.oldContent, operation.scope) } + private undoSetRowOrder(operation: SetRowOrderUndoEntry) { + const reverseMap = operation.rowMapping.map(([source, target]) => [target, source] as [number, number]) + this.operations.setRowOrder(operation.sheetId, reverseMap) + } + + private undoSetColumnOrder(operation: SetColumnOrderUndoEntry) { + const reverseMap = operation.columnMapping.map(([source, target]) => [target, source] as [number, number]) + this.operations.setColumnOrder(operation.sheetId, reverseMap) + } + public redo() { const operation = this.redoStack.pop() @@ -544,6 +576,10 @@ export class UndoRedo { this.redoRemoveNamedExpression(operation) } else if (operation instanceof ChangeNamedExpressionUndoEntry) { this.redoChangeNamedExpression(operation) + } else if (operation instanceof SetRowOrderUndoEntry) { + this.redoSetRowOrder(operation) + } else if (operation instanceof SetColumnOrderUndoEntry) { + this.redoSetColumnOrder(operation) } else { throw 'Unknown element' } @@ -634,6 +670,14 @@ export class UndoRedo { this.operations.changeNamedExpressionExpression(operation.namedExpression.displayName, operation.newContent, operation.scope, operation.options) } + private redoSetRowOrder(operation: SetRowOrderUndoEntry) { + this.operations.setRowOrder(operation.sheetId, operation.rowMapping) + } + + private redoSetColumnOrder(operation: SetColumnOrderUndoEntry) { + this.operations.setColumnOrder(operation.sheetId, operation.columnMapping) + } + private restoreOldDataFromVersion(version: number) { const oldDataToRestore = this.oldData.get(version) || [] for (const entryToRestore of oldDataToRestore) { diff --git a/src/parser/CellAddress.ts b/src/parser/CellAddress.ts index c6d2d44968..9a7953b6cb 100644 --- a/src/parser/CellAddress.ts +++ b/src/parser/CellAddress.ts @@ -5,6 +5,7 @@ import { absoluteSheetReference, + invalidSimpleCellAddress, simpleCellAddress, SimpleCellAddress, simpleColumnAddress, @@ -12,8 +13,9 @@ import { simpleRowAddress, SimpleRowAddress, } from '../Cell' -import {columnIndexToLabel} from './addressRepresentationConverters' +import {Maybe} from '../Maybe' import {AddressWithColumn, AddressWithRow} from './Address' +import {columnIndexToLabel} from './addressRepresentationConverters' /** Possible kinds of cell references */ export enum CellReferenceType { @@ -158,8 +160,11 @@ export class CellAddress implements AddressWithColumn, AddressWithRow { } } - public unparse(baseAddress: SimpleCellAddress): string { + public unparse(baseAddress: SimpleCellAddress): Maybe { const simpleAddress = this.toSimpleCellAddress(baseAddress) + if(invalidSimpleCellAddress(simpleAddress)) { + return undefined + } const column = columnIndexToLabel(simpleAddress.col) const rowDollar = this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW ? '$' : '' const colDollar = this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL ? '$' : '' diff --git a/src/parser/ColumnAddress.ts b/src/parser/ColumnAddress.ts index 26b77dc185..4389c4a6e6 100644 --- a/src/parser/ColumnAddress.ts +++ b/src/parser/ColumnAddress.ts @@ -3,9 +3,16 @@ * Copyright (c) 2020 Handsoncode. All rights reserved. */ -import {absoluteSheetReference, SimpleCellAddress, simpleColumnAddress, SimpleColumnAddress} from '../Cell' -import {columnIndexToLabel} from './addressRepresentationConverters' +import { + absoluteSheetReference, + invalidSimpleColumnAddress, + SimpleCellAddress, + simpleColumnAddress, + SimpleColumnAddress +} from '../Cell' +import {Maybe} from '../Maybe' import {AddressWithColumn} from './Address' +import {columnIndexToLabel} from './addressRepresentationConverters' export enum ReferenceType { RELATIVE = 'RELATIVE', @@ -83,8 +90,11 @@ export class ColumnAddress implements AddressWithColumn { } } - public unparse(baseAddress: SimpleCellAddress): string { + public unparse(baseAddress: SimpleCellAddress): Maybe { const simpleAddress = this.toSimpleColumnAddress(baseAddress) + if(invalidSimpleColumnAddress(simpleAddress)) { + return undefined + } const column = columnIndexToLabel(simpleAddress.col) const dollar = this.type === ReferenceType.ABSOLUTE ? '$' : '' return `${dollar}${column}` diff --git a/src/parser/RowAddress.ts b/src/parser/RowAddress.ts index bccf724de9..2736b17441 100644 --- a/src/parser/RowAddress.ts +++ b/src/parser/RowAddress.ts @@ -3,9 +3,16 @@ * Copyright (c) 2020 Handsoncode. All rights reserved. */ -import {absoluteSheetReference, SimpleCellAddress, simpleRowAddress, SimpleRowAddress} from '../Cell' -import {ReferenceType} from './ColumnAddress' +import { + absoluteSheetReference, + invalidSimpleRowAddress, + SimpleCellAddress, + simpleRowAddress, + SimpleRowAddress +} from '../Cell' +import {Maybe} from '../Maybe' import {AddressWithRow} from './Address' +import {ReferenceType} from './ColumnAddress' export class RowAddress implements AddressWithRow { private constructor( @@ -78,8 +85,11 @@ export class RowAddress implements AddressWithRow { } } - public unparse(baseAddress: SimpleCellAddress): string { + public unparse(baseAddress: SimpleCellAddress): Maybe { const simpleAddress = this.toSimpleRowAddress(baseAddress) + if(invalidSimpleRowAddress(simpleAddress)) { + return undefined + } const dollar = this.type === ReferenceType.ABSOLUTE ? '$' : '' return `${dollar}${simpleAddress.row + 1}` } diff --git a/src/parser/Unparser.ts b/src/parser/Unparser.ts index 3869529304..e7bb7e04db 100644 --- a/src/parser/Unparser.ts +++ b/src/parser/Unparser.ts @@ -4,6 +4,9 @@ */ import {ErrorType, SimpleCellAddress} from '../Cell' +import {NoSheetWithIdError} from '../index' +import {NamedExpressions} from '../NamedExpressions' +import {SheetIndexMappingFn, sheetIndexToString} from './addressRepresentationConverters' import { Ast, AstNodeType, @@ -16,9 +19,6 @@ import { import {binaryOpTokenMap} from './binaryOpTokenMap' import {ILexerConfig} from './LexerConfig' import {ParserConfig} from './ParserConfig' -import {NamedExpressions} from '../NamedExpressions' -import {SheetIndexMappingFn, sheetIndexToString} from './addressRepresentationConverters' -import {NoSheetWithIdError} from '../index' export class Unparser { constructor( @@ -60,10 +60,11 @@ export class Unparser { case AstNodeType.CELL_REFERENCE: { let image if (ast.reference.sheet !== null) { - image = this.unparseSheetName(ast.reference.sheet) + '!' + ast.reference.unparse(address) + image = this.unparseSheetName(ast.reference.sheet) + '!' } else { - image = ast.reference.unparse(address) + image = '' } + image += ast.reference.unparse(address) ?? this.config.translationPackage.getErrorTranslation(ErrorType.REF) return imageWithWhitespace(image, ast.leadingWhitespace) } case AstNodeType.COLUMN_RANGE: @@ -124,7 +125,12 @@ export class Unparser { endSheet = this.unparseSheetName(ast.end.sheet) + '!' } - return `${startSheeet}${ast.start.unparse(baseAddress)}:${endSheet}${ast.end.unparse(baseAddress)}` + const unparsedStart = ast.start.unparse(baseAddress) + const unparsedEnd = ast.end.unparse(baseAddress) + if(unparsedStart === undefined || unparsedEnd === undefined) { + return this.config.translationPackage.getErrorTranslation(ErrorType.REF) + } + return `${startSheeet}${unparsedStart}:${endSheet}${unparsedEnd}` } } diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 7626c1ad82..fc3e273906 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -660,7 +660,7 @@ describe('change multiple cells contents', () => { expect(engine.getCellValue(adr('A1'))).toBe(1) }) - it('returns changes of mutliple values', () => { + it('returns changes of multiple values', () => { const sheet = [ ['1', '2'], ['3', '4'], @@ -674,7 +674,7 @@ describe('change multiple cells contents', () => { expectArrayWithSameContent(changes.map((change) => change.newValue), [7, 8, 9, 10]) }) - it('returns changes of mutliple values dependent formulas', () => { + it('returns changes of multiple values dependent formulas', () => { const sheet = [ ['1', '2'], ['3', '4'], diff --git a/test/cruds/copy-paste.spec.ts b/test/cruds/copy-paste.spec.ts index bd2c583cc3..dfe1788c5c 100644 --- a/test/cruds/copy-paste.spec.ts +++ b/test/cruds/copy-paste.spec.ts @@ -183,13 +183,50 @@ describe('Copy - paste integration', () => { it('should return ref when pasted reference is out of scope', () => { const engine = HyperFormula.buildFromArray([ [null, null], - [null, '=B1'], + [null, '=A1'], ]) engine.copy(adr('B2'), 1, 1) engine.paste(adr('A1')) expect(engine.getCellValue(adr('A1'))).toEqualError(detailedError(ErrorType.REF, ErrorMessage.BadRef)) + expect(engine.getCellSerialized(adr('A1'))).toEqual('=#REF!') + }) + + it('should return ref when pasted range is out of scope', () => { + const engine = HyperFormula.buildFromArray([ + [null, null], + [null, '=A1:B2'], + ]) + + engine.copy(adr('B2'), 1, 1) + engine.paste(adr('A1')) + + expect(engine.getCellSerialized(adr('A1'))).toEqual('=#REF!') + }) + + it('should return ref when pasted column range is out of scope', () => { + const engine = HyperFormula.buildFromArray([ + [null, null], + [null, '=A:B'], + ]) + + engine.copy(adr('B2'), 1, 1) + engine.paste(adr('A1')) + + expect(engine.getCellSerialized(adr('A1'))).toEqual('=#REF!') + }) + + it('should return ref when pasted row range is out of scope', () => { + const engine = HyperFormula.buildFromArray([ + [null, null], + [null, '=1:2'], + ]) + + engine.copy(adr('B2'), 1, 1) + engine.paste(adr('A1')) + + expect(engine.getCellSerialized(adr('A1'))).toEqual('=#REF!') }) it('should create new range vertex - cell range', () => { diff --git a/test/cruds/cut-paste.spec.ts b/test/cruds/cut-paste.spec.ts index 5b1cf64fce..ce1450179d 100644 --- a/test/cruds/cut-paste.spec.ts +++ b/test/cruds/cut-paste.spec.ts @@ -1034,4 +1034,32 @@ describe('aborting cut paste', () => { expect(engine.isClipboardEmpty()).toBe(true) }) + + it('should be aborted when swapping rows', () => { + const engine = HyperFormula.buildFromArray([['1']]) + engine.cut(adr('A1'), 1, 1) + engine.swapRowIndexes(0, [[0, 0]]) + expect(engine.isClipboardEmpty()).toBe(true) + }) + + it('should be aborted when swapping columns', () => { + const engine = HyperFormula.buildFromArray([['1']]) + engine.cut(adr('A1'), 1, 1) + engine.swapColumnIndexes(0, [[0, 0]]) + expect(engine.isClipboardEmpty()).toBe(true) + }) + + it('should be aborted when setting row order', () => { + const engine = HyperFormula.buildFromArray([['1']]) + engine.cut(adr('A1'), 1, 1) + engine.setRowOrder(0, [0]) + expect(engine.isClipboardEmpty()).toBe(true) + }) + + it('should be aborted when setting column order', () => { + const engine = HyperFormula.buildFromArray([['1']]) + engine.cut(adr('A1'), 1, 1) + engine.setColumnOrder(0, [0]) + expect(engine.isClipboardEmpty()).toBe(true) + }) }) diff --git a/test/cruds/set-column-order.spec.ts b/test/cruds/set-column-order.spec.ts new file mode 100644 index 0000000000..ec8075187c --- /dev/null +++ b/test/cruds/set-column-order.spec.ts @@ -0,0 +1,341 @@ +import {HyperFormula} from '../../src' +import {AlwaysSparse} from '../../src/DependencyGraph/AddressMapping/ChooseAddressMappingPolicy' +import {adr} from '../testUtils' + +describe('swapping columns - checking if it is possible', () => { + it('should validate numbers for negative columns', () => { + const engine = HyperFormula.buildFromArray([[]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[-1, 0]])).toEqual(false) + expect(() => + engine.swapColumnIndexes(0, [[-1, 0]]) + ).toThrowError('Invalid arguments, expected column numbers to be nonnegative integers and less than sheet width.') + }) + + it('should validate sources for noninteger values', () => { + const engine = HyperFormula.buildFromArray([[]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[1, 1], [0.5, 0]])).toEqual(false) + expect(() => + engine.swapColumnIndexes(0, [[1, 1], [0.5, 0]]) + ).toThrowError('Invalid arguments, expected column numbers to be nonnegative integers and less than sheet width.') + }) + + it('should validate sources for values exceeding sheet width', () => { + const engine = HyperFormula.buildFromArray([[0, 0, 0]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[1, 1], [3, 0]])).toEqual(false) + expect(() => + engine.swapColumnIndexes(0, [[3, 0]]) + ).toThrowError('Invalid arguments, expected column numbers to be nonnegative integers and less than sheet width.') + }) + + it('should validate sources to be unique', () => { + const engine = HyperFormula.buildFromArray([[0, 0, 0]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 0], [1, 1], [1, 2]])).toEqual(false) + expect(() => + engine.swapColumnIndexes(0, [[0, 0], [1, 1], [1, 2]]) + ).toThrowError('Invalid arguments, expected source column numbers to be unique.') + }) + + it('should validate sources to be permutation of targets', () => { + const engine = HyperFormula.buildFromArray([[0, 0, 0]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 0], [1, 1], [2, 1]])).toEqual(false) + expect(() => + engine.swapColumnIndexes(0, [[0, 0], [1, 1], [2, 1]]) + ).toThrowError('Invalid arguments, expected target column numbers to be permutation of source column numbers.') + }) + + it('should check for matrices', () => { + const engine = HyperFormula.buildFromArray([[0, 0, '{=1}']]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 2], [1, 1], [2, 0]])).toEqual(false) + expect(() => + engine.swapColumnIndexes(0, [[0, 2], [1, 1], [2, 0]]) + ).toThrowError('Cannot perform this operation, source location has a matrix inside.') + }) + + it('should check for matrices only in moved rows', () => { + const engine = HyperFormula.buildFromArray([[0, '{=1}', 0]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 2], [1, 1], [2, 0]])).toEqual(true) + expect(() => + engine.swapColumnIndexes(0, [[0, 2], [1, 1], [2, 0]]) + ).not.toThrowError() + }) +}) + +describe('swapping rows should correctly work', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 'abcd'], [3, 3], [5, true]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 1], [1, 0]])).toEqual(true) + engine.swapColumnIndexes(0, [[0, 1], [1, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([['abcd', 1], [3, 3], [true, 5]]) + }) + + it('should return number of changed cells', () => { + const engine = HyperFormula.buildFromArray([[1, 2], [3, 4], [5, 6]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 1], [1, 0]])).toEqual(true) + const ret = engine.swapColumnIndexes(0, [[0, 1], [1, 0]]) + expect(ret.length).toEqual(6) + }) + + it('should work on static engine with uneven column', () => { + const engine = HyperFormula.buildFromArray([[1, 2], [3, 4], [5]], {chooseAddressMappingPolicy: new AlwaysSparse()}) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 1], [1, 0]])).toEqual(true) + engine.swapColumnIndexes(0, [[0, 1], [1, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([[2, 1], [4, 3], [null, 5]]) + }) + + it('should work with more complicated permutations', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.swapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([[3, 1, 2], [6, 4, 5], [9, 7, 8]]) + }) + + it('should not move values unnecessarily', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 0], [1, 1]])).toEqual(true) + const ret = engine.swapColumnIndexes(0, [[0, 0], [1, 1]]) + expect(ret.length).toEqual(0) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3, '=A1', '=SUM(A2:A3)'], [4, 5, 6], [7, 8, 9]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.swapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([[3, 1, 2, '=A1', '=SUM(A2:A3)'], [6, 4, 5], [9, 7, 8]]) + expect(engine.getSheetValues(0)).toEqual([[3, 1, 2, 3, 15], [6, 4, 5], [9, 7, 8]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], [1, '=SUM(B10:B15)', '=A10'], ['=SUM(D1:D10)', 8, 9]]) + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.swapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([[3, '=B2', '=SUM(C2:C3)'], ['=#REF!', 1, '=SUM(C10:C15)'], [9, '=SUM(E1:E10)', 8]]) + }) +}) + +describe('swapping rows working with undo', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + engine.swapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3, '=A1', '=SUM(A2:A3)'], [4, 5, 6], [7, 8, 9]]) + engine.swapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([[1, 2, 3, '=A1', '=SUM(A2:A3)'], [4, 5, 6], [7, 8, 9]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], [1, '=SUM(B10:B15)', '=A10'], ['=SUM(D1:D10)', 8, 9]]) + engine.swapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([['=A2', '=SUM(B2:B3)', 3], [1, '=SUM(B10:B15)', '=A10'], ['=SUM(D1:D10)', 8, 9]]) + }) +}) + +describe('swapping rows working with redo', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + engine.swapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[3, 1, 2], [6, 4, 5], [9, 7, 8]]) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3, '=A1', '=SUM(A2:A3)'], [4, 5, 6], [7, 8, 9]]) + engine.swapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[3, 1, 2, '=A1', '=SUM(A2:A3)'], [6, 4, 5], [9, 7, 8]]) + expect(engine.getSheetValues(0)).toEqual([[3, 1, 2, 3, 15], [6, 4, 5], [9, 7, 8]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], [1, '=SUM(B10:B15)', '=A10'], ['=SUM(D1:D10)', 8, 9]]) + engine.swapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.isItPossibleToSwapColumnIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[3, '=B2', '=SUM(C2:C3)'], ['=#REF!', 1, '=SUM(C10:C15)'], [9, '=SUM(E1:E10)', 8]]) + }) + + it('clears redo stack', () => { + const engine = HyperFormula.buildFromArray([[1]]) + engine.setCellContents(adr('A1'), 42) + engine.undo() + + engine.swapColumnIndexes(0, [[0, 0]]) + + expect(engine.isThereSomethingToRedo()).toBe(false) + }) +}) + +describe('setting column order - checking if it is possible', () => { + it('should check for length', () => { + const engine = HyperFormula.buildFromArray([[]]) + expect(engine.isItPossibleToSetColumnOrder(0, [0])).toEqual(false) + expect(() => + engine.setColumnOrder(0, [0]) + ).toThrowError('Invalid arguments, expected number of columns provided to be sheet width.') + }) + + it('should validate sources for noninteger values', () => { + const engine = HyperFormula.buildFromArray([[]]) + expect(engine.isItPossibleToSetColumnOrder(0, [0, 0.5])).toEqual(false) + expect(() => + engine.setColumnOrder(0, [0, 0.5]) + ).toThrowError('Invalid arguments, expected number of columns provided to be sheet width.') + }) + + it('should validate for repeated values', () => { + const engine = HyperFormula.buildFromArray([[0, 0, 0]]) + expect(engine.isItPossibleToSetColumnOrder(0, [0, 1, 1])).toEqual(false) + expect(() => + engine.setColumnOrder(0, [0, 1, 1]) + ).toThrowError('Invalid arguments, expected target column numbers to be permutation of source column numbers.') + }) + + it('should validate sources to be permutation of targets', () => { + const engine = HyperFormula.buildFromArray([[0, 0, 0]]) + expect(engine.isItPossibleToSetColumnOrder(0, [1, 2, 3])).toEqual(false) + expect(() => + engine.setColumnOrder(0, [1, 2, 3]) + ).toThrowError('Invalid arguments, expected target column numbers to be permutation of source column numbers.') + }) + + it('should check for matrices', () => { + const engine = HyperFormula.buildFromArray([[0, 0, '{=1}']]) + expect(engine.isItPossibleToSetColumnOrder(0, [2, 1, 0])).toEqual(false) + expect(() => + engine.setColumnOrder(0, [2, 1, 0]) + ).toThrowError('Cannot perform this operation, source location has a matrix inside.') + }) + + it('should check for matrices only in moved columns', () => { + const engine = HyperFormula.buildFromArray([[0, '{=1}', 0]]) + expect(engine.isItPossibleToSetColumnOrder(0, [2, 1, 0])).toEqual(true) + expect(() => + engine.setColumnOrder(0, [2, 1, 0]) + ).not.toThrowError() + }) +}) + +describe('reorder base case', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 'abcd'], [3, 3], [5, true]]) + expect(engine.isItPossibleToSetColumnOrder(0, [1, 0])).toEqual(true) + engine.setColumnOrder(0, [1, 0]) + expect(engine.getSheetSerialized(0)).toEqual([['abcd', 1], [3, 3], [true, 5]]) + }) + + it('should return number of changed cells', () => { + const engine = HyperFormula.buildFromArray([[1, 2], [3, 4], [5, 6]]) + expect(engine.isItPossibleToSetColumnOrder(0, [1, 0])).toEqual(true) + const ret = engine.setColumnOrder(0, [1, 0]) + expect(ret.length).toEqual(6) + }) + + it('should work on static engine with uneven column', () => { + const engine = HyperFormula.buildFromArray([[1, 2], [3, 4], [5]], {chooseAddressMappingPolicy: new AlwaysSparse()}) + expect(engine.isItPossibleToSetColumnOrder(0, [1, 0])).toEqual(true) + engine.setColumnOrder(0, [1, 0]) + expect(engine.getSheetSerialized(0)).toEqual([[2, 1], [4, 3], [null, 5]]) + }) + + it('should work with more complicated permutations', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + expect(engine.isItPossibleToSetColumnOrder(0, [1, 2, 0])).toEqual(true) + engine.setColumnOrder(0, [1, 2, 0]) + expect(engine.getSheetSerialized(0)).toEqual([[3, 1, 2], [6, 4, 5], [9, 7, 8]]) + }) + + it('should not move values unnecessarily', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6]]) + expect(engine.isItPossibleToSetColumnOrder(0, [0, 1, 2])).toEqual(true) + const ret = engine.setColumnOrder(0, [0, 1, 2]) + expect(ret.length).toEqual(0) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3, '=A1', '=SUM(A2:A3)'], [4, 5, 6], [7, 8, 9]]) + expect(engine.isItPossibleToSetColumnOrder(0, [1, 2, 0, 3, 4])).toEqual(true) + engine.setColumnOrder(0, [1, 2, 0, 3, 4]) + expect(engine.getSheetSerialized(0)).toEqual([[3, 1, 2, '=A1', '=SUM(A2:A3)'], [6, 4, 5], [9, 7, 8]]) + expect(engine.getSheetValues(0)).toEqual([[3, 1, 2, 3, 15], [6, 4, 5], [9, 7, 8]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], [1, '=SUM(B10:B15)', '=A10'], ['=SUM(D1:D10)', 8, 9]]) + expect(engine.isItPossibleToSetColumnOrder(0, [1, 2, 0, 3])).toEqual(true) + engine.setColumnOrder(0, [1, 2, 0, 3]) + expect(engine.getSheetSerialized(0)).toEqual([[3, '=B2', '=SUM(C2:C3)'], ['=#REF!', 1, '=SUM(C10:C15)'], [9, '=SUM(E1:E10)', 8]]) + }) +}) + +describe('reorder working with undo', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + engine.setColumnOrder(0, [1, 2, 0]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3, '=A1', '=SUM(A2:A3)'], [4, 5, 6], [7, 8, 9]]) + engine.setColumnOrder(0, [1, 2, 0, 3, 4]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([[1, 2, 3, '=A1', '=SUM(A2:A3)'], [4, 5, 6], [7, 8, 9]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], [1, '=SUM(B10:B15)', '=A10'], ['=SUM(D1:D10)', 8, 9]]) + engine.setColumnOrder(0, [1, 2, 0, 3]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([['=A2', '=SUM(B2:B3)', 3], [1, '=SUM(B10:B15)', '=A10'], ['=SUM(D1:D10)', 8, 9]]) + }) +}) + +describe('reorder working with redo', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + engine.setColumnOrder(0, [1, 2, 0]) + engine.undo() + expect(engine.isItPossibleToSetColumnOrder(0, [1, 2, 0])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[3, 1, 2], [6, 4, 5], [9, 7, 8]]) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3, '=A1', '=SUM(A2:A3)'], [4, 5, 6], [7, 8, 9]]) + engine.setColumnOrder(0, [1, 2, 0, 3, 4]) + engine.undo() + expect(engine.isItPossibleToSetColumnOrder(0, [1, 2, 0, 3, 4])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[3, 1, 2, '=A1', '=SUM(A2:A3)'], [6, 4, 5], [9, 7, 8]]) + expect(engine.getSheetValues(0)).toEqual([[3, 1, 2, 3, 15], [6, 4, 5], [9, 7, 8]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], [1, '=SUM(B10:B15)', '=A10'], ['=SUM(D1:D10)', 8, 9]]) + engine.setColumnOrder(0, [1, 2, 0, 3]) + engine.undo() + expect(engine.isItPossibleToSetColumnOrder(0, [1, 2, 0, 3, 4])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[3, '=B2', '=SUM(C2:C3)'], ['=#REF!', 1, '=SUM(C10:C15)'], [9, '=SUM(E1:E10)', 8]]) + }) + + it('clears redo stack', () => { + const engine = HyperFormula.buildFromArray([[1]]) + engine.setCellContents(adr('A1'), 42) + engine.undo() + + engine.setColumnOrder(0, [0]) + + expect(engine.isThereSomethingToRedo()).toBe(false) + }) +}) diff --git a/test/cruds/set-row-order.spec.ts b/test/cruds/set-row-order.spec.ts new file mode 100644 index 0000000000..b8f5c7b070 --- /dev/null +++ b/test/cruds/set-row-order.spec.ts @@ -0,0 +1,347 @@ +import {HyperFormula} from '../../src' +import {AlwaysSparse} from '../../src/DependencyGraph/AddressMapping/ChooseAddressMappingPolicy' +import {adr} from '../testUtils' + +describe('swapping rows - checking if it is possible', () => { + it('should validate numbers for negative rows', () => { + const engine = HyperFormula.buildFromArray([[]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[-1, 0]])).toEqual(false) + expect(() => + engine.swapRowIndexes(0, [[-1, 0]]) + ).toThrowError('Invalid arguments, expected row numbers to be nonnegative integers and less than sheet height.') + }) + + it('should validate sources for noninteger values', () => { + const engine = HyperFormula.buildFromArray([[]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[1, 1], [0.5, 0]])).toEqual(false) + expect(() => + engine.swapRowIndexes(0, [[1, 1], [0.5, 0]]) + ).toThrowError('Invalid arguments, expected row numbers to be nonnegative integers and less than sheet height.') + }) + + it('should validate sources for values exceeding sheet height', () => { + const engine = HyperFormula.buildFromArray([[0], [0], [0]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[1, 1], [3, 0]])).toEqual(false) + expect(() => + engine.swapRowIndexes(0, [[3, 0]]) + ).toThrowError('Invalid arguments, expected row numbers to be nonnegative integers and less than sheet height.') + }) + + it('should validate sources to be unique', () => { + const engine = HyperFormula.buildFromArray([[0], [0], [0]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 0], [1, 1], [1, 2]])).toEqual(false) + expect(() => + engine.swapRowIndexes(0, [[0, 0], [1, 1], [1, 2]]) + ).toThrowError('Invalid arguments, expected source row numbers to be unique.') + }) + + it('should validate sources to be permutation of targets', () => { + const engine = HyperFormula.buildFromArray([[0], [0], [0]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 0], [1, 1], [2, 1]])).toEqual(false) + expect(() => + engine.swapRowIndexes(0, [[0, 0], [1, 1], [2, 1]]) + ).toThrowError('Invalid arguments, expected target row numbers to be permutation of source row numbers.') + }) + + it('should check for matrices', () => { + const engine = HyperFormula.buildFromArray([[0], [0], ['{=1}']]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 2], [1, 1], [2, 0]])).toEqual(false) + expect(() => + engine.swapRowIndexes(0, [[0, 2], [1, 1], [2, 0]]) + ).toThrowError('Cannot perform this operation, source location has a matrix inside.') + }) + + it('should check for matrices only in moved rows', () => { + const engine = HyperFormula.buildFromArray([[0], ['{=1}'], [0]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 2], [1, 1], [2, 0]])).toEqual(true) + expect(() => + engine.swapRowIndexes(0, [[0, 2], [1, 1], [2, 0]]) + ).not.toThrowError() + }) +}) + +describe('swapping rows should correctly work', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 'abcd', 3], [3, 5, true]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 1], [1, 0]])).toEqual(true) + engine.swapRowIndexes(0, [[0, 1], [1, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([[3, 5, true], [1, 'abcd', 3]]) + }) + + it('should return number of changed cells', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 1], [1, 0]])).toEqual(true) + const ret = engine.swapRowIndexes(0, [[0, 1], [1, 0]]) + expect(ret.length).toEqual(6) + }) + + it('should work on static engine with uneven rows', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6, 7, 8]], {chooseAddressMappingPolicy: new AlwaysSparse()}) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 1], [1, 0]])).toEqual(true) + engine.swapRowIndexes(0, [[0, 1], [1, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([[4, 5, 6, 7, 8], [1, 2, 3]]) + }) + + it('should work with more complicated permutations', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.swapRowIndexes(0, [[0, 1], [1, 2], [2, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6]]) + }) + + it('should not move values unnecessarily', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 0], [1, 1]])).toEqual(true) + const ret = engine.swapRowIndexes(0, [[0, 0], [1, 1]]) + expect(ret.length).toEqual(0) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9], ['=A1', '=SUM(A2:A3)']]) + engine.swapRowIndexes(0, [[0, 1], [1, 2], [2, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6], ['=A1', '=SUM(A2:A3)']]) + expect(engine.getSheetValues(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 5]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], ['=A10', '=SUM(B10:B15)', 6], ['=SUM(C1:C10)', 8, 9]]) + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.swapRowIndexes(0, [[0, 1], [1, 2], [2, 0]]) + expect(engine.getSheetSerialized(0)).toEqual([['=SUM(#REF!)', 8, 9], ['=A3', '=SUM(B3:B4)', 3], ['=A11', '=SUM(B11:B16)', 6]]) + }) +}) + +describe('swapping rows working with undo', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + engine.swapRowIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9], ['=A1', '=SUM(A2:A3)']]) + engine.swapRowIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([[1, 2, 3], [4, 5, 6], [7, 8, 9], ['=A1', '=SUM(A2:A3)']]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], ['=A10', '=SUM(B10:B15)', 6], ['=SUM(C1:C10)', 8, 9]]) + engine.swapRowIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([['=A2', '=SUM(B2:B3)', 3], ['=A10', '=SUM(B10:B15)', 6], ['=SUM(C1:C10)', 8, 9]]) + }) +}) + +describe('swapping rows working with redo', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + engine.swapRowIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6]]) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9], ['=A1', '=SUM(A2:A3)']]) + engine.swapRowIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6], ['=A1', '=SUM(A2:A3)']]) + expect(engine.getSheetValues(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 5]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], ['=A10', '=SUM(B10:B15)', 6], ['=SUM(C1:C10)', 8, 9]]) + engine.swapRowIndexes(0, [[0, 1], [1, 2], [2, 0]]) + engine.undo() + expect(engine.isItPossibleToSwapRowIndexes(0, [[0, 1], [1, 2], [2, 0]])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([['=SUM(#REF!)', 8, 9], ['=A3', '=SUM(B3:B4)', 3], ['=A11', '=SUM(B11:B16)', 6]]) + }) + + it('clears redo stack', () => { + const engine = HyperFormula.buildFromArray([[1]]) + engine.setCellContents(adr('A1'), 42) + engine.undo() + + engine.swapRowIndexes(0, [[0, 0]]) + + expect(engine.isThereSomethingToRedo()).toBe(false) + }) +}) + +function fillValues(order: number[], fill: number): number[] { + while(order.length < fill) { + const x = order.length + order[x] = x + } + return order +} + +describe('setting row order - checking if it is possible', () => { + it('should check for length', () => { + const engine = HyperFormula.buildFromArray([[]]) + expect(engine.isItPossibleToSetRowOrder(0, [0])).toEqual(false) + expect(() => + engine.setRowOrder(0, [0]) + ).toThrowError('Invalid arguments, expected number of rows provided to be sheet height.') + }) + + it('should validate sources for noninteger values', () => { + const engine = HyperFormula.buildFromArray([[0], [0]]) + expect(engine.isItPossibleToSetRowOrder(0, [0, 0.5])).toEqual(false) + expect(() => + engine.setRowOrder(0, [0, 0.5]) + ).toThrowError('Invalid arguments, expected target row numbers to be permutation of source row numbers.') + }) + + it('should validate for repeated values', () => { + const engine = HyperFormula.buildFromArray([[0], [0], [0]]) + expect(engine.isItPossibleToSetRowOrder(0, [0, 1, 1])).toEqual(false) + expect(() => + engine.setRowOrder(0, [0, 1, 1]) + ).toThrowError('Invalid arguments, expected target row numbers to be permutation of source row numbers.') + }) + + it('should validate sources to be permutation of targets', () => { + const engine = HyperFormula.buildFromArray([[0], [0], [0]]) + expect(engine.isItPossibleToSetRowOrder(0, [1, 2, 3])).toEqual(false) + expect(() => + engine.setRowOrder(0, [1, 2, 3]) + ).toThrowError('Invalid arguments, expected target row numbers to be permutation of source row numbers.') + }) + + it('should check for matrices', () => { + const engine = HyperFormula.buildFromArray([[0], [0], ['{=1}']]) + expect(engine.isItPossibleToSetRowOrder(0, [2, 1, 0])).toEqual(false) + expect(() => + engine.setRowOrder(0, [2, 1, 0]) + ).toThrowError('Cannot perform this operation, source location has a matrix inside.') + }) + + it('should check for matrices only in moved rows', () => { + const engine = HyperFormula.buildFromArray([[0], ['{=1}'], [0]]) + expect(engine.isItPossibleToSetRowOrder(0, [2, 1, 0])).toEqual(true) + expect(() => + engine.setRowOrder(0, [2, 1, 0]) + ).not.toThrowError() + }) +}) + +describe('reorder base case', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 'abcd', 3], [3, 5, true]]) + expect(engine.isItPossibleToSetRowOrder(0, [1, 0])).toEqual(true) + engine.setRowOrder(0, [1, 0]) + expect(engine.getSheetSerialized(0)).toEqual([[3, 5, true], [1, 'abcd', 3]]) + }) + + it('should return number of changed cells', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6]]) + expect(engine.isItPossibleToSetRowOrder(0, [1, 0])).toEqual(true) + const ret = engine.setRowOrder(0, [1, 0]) + expect(ret.length).toEqual(6) + }) + + it('should work on static engine with uneven rows', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6, 7, 8]], {chooseAddressMappingPolicy: new AlwaysSparse()}) + expect(engine.isItPossibleToSetRowOrder(0, [1, 0])).toEqual(true) + engine.setRowOrder(0, [1, 0]) + expect(engine.getSheetSerialized(0)).toEqual([[4, 5, 6, 7, 8], [1, 2, 3]]) + }) + + it('should work with more complicated permutations', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + expect(engine.isItPossibleToSetRowOrder(0, [1, 2, 0])).toEqual(true) + engine.setRowOrder(0, [1, 2, 0]) + expect(engine.getSheetSerialized(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6]]) + }) + + it('should not move values unnecessarily', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6]]) + expect(engine.isItPossibleToSetRowOrder(0, [0, 1])).toEqual(true) + const ret = engine.setRowOrder(0, [0, 1]) + expect(ret.length).toEqual(0) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9], ['=A1', '=SUM(A2:A3)']]) + engine.setRowOrder(0, [1, 2, 0, 3]) + expect(engine.getSheetSerialized(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6], ['=A1', '=SUM(A2:A3)']]) + expect(engine.getSheetValues(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 5]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], ['=A10', '=SUM(B10:B15)', 6], ['=SUM(C1:C10)', 8, 9]]) + expect(engine.isItPossibleToSetRowOrder(0, fillValues([1, 2, 0], 15))).toEqual(true) + engine.setRowOrder(0, fillValues([1, 2, 0], 15)) + expect(engine.getSheetSerialized(0)).toEqual([['=SUM(#REF!)', 8, 9], ['=A3', '=SUM(B3:B4)', 3], ['=A11', '=SUM(B11:B16)', 6]]) + }) +}) + +describe('reorder working with undo', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + engine.setRowOrder(0, [1, 2, 0]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9], ['=A1', '=SUM(A2:A3)']]) + engine.setRowOrder(0, [1, 2, 0, 3]) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([[1, 2, 3], [4, 5, 6], [7, 8, 9], ['=A1', '=SUM(A2:A3)']]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], ['=A10', '=SUM(B10:B15)', 6], ['=SUM(C1:C10)', 8, 9]]) + engine.setRowOrder(0, fillValues([1, 2, 0], 15)) + engine.undo() + expect(engine.getSheetSerialized(0)).toEqual([['=A2', '=SUM(B2:B3)', 3], ['=A10', '=SUM(B10:B15)', 6], ['=SUM(C1:C10)', 8, 9]]) + }) +}) + +describe('reorder working with redo', () => { + it('should work on static engine', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + engine.setRowOrder(0, [1, 2, 0]) + engine.undo() + expect(engine.isItPossibleToSetRowOrder(0, [1, 2, 0])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6]]) + }) + + it('should work with external references', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9], ['=A1', '=SUM(A2:A3)']]) + engine.setRowOrder(0, [1, 2, 0, 3]) + engine.undo() + expect(engine.isItPossibleToSetRowOrder(0, [1, 2, 0, 3])).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6], ['=A1', '=SUM(A2:A3)']]) + expect(engine.getSheetValues(0)).toEqual([[7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 5]]) + }) + + it('should work with internal references', () => { + const engine = HyperFormula.buildFromArray([['=A2', '=SUM(B2:B3)', 3], ['=A10', '=SUM(B10:B15)', 6], ['=SUM(C1:C10)', 8, 9]]) + engine.setRowOrder(0, fillValues([1, 2, 0], 15)) + engine.undo() + expect(engine.isItPossibleToSetRowOrder(0, fillValues( [1, 2, 0], 16))).toEqual(true) + engine.redo() + expect(engine.getSheetSerialized(0)).toEqual([['=SUM(#REF!)', 8, 9], ['=A3', '=SUM(B3:B4)', 3], ['=A11', '=SUM(B11:B16)', 6]]) + }) + + it('clears redo stack', () => { + const engine = HyperFormula.buildFromArray([[1]]) + engine.setCellContents(adr('A1'), 42) + engine.undo() + + engine.setRowOrder(0, [0]) + + expect(engine.isThereSomethingToRedo()).toBe(false) + }) +})