From 0a6a3e566f679d20a2e0d35bcca7d3698ef4c85c Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 15 May 2021 10:19:08 +0200 Subject: [PATCH 01/87] Tranpose works with any type --- src/interpreter/SimpleRangeValue.ts | 1 + src/interpreter/plugin/MatrixPlugin.ts | 11 ++++------- test/interpreter/matrix-plugin.spec.ts | 19 ++++++++++++++++++- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/interpreter/SimpleRangeValue.ts b/src/interpreter/SimpleRangeValue.ts index d880786bd2..a75bf0bae5 100644 --- a/src/interpreter/SimpleRangeValue.ts +++ b/src/interpreter/SimpleRangeValue.ts @@ -134,6 +134,7 @@ export class SimpleRangeValue { } public rawData(): InternalScalarValue[][] { + this.ensureThatComputed() return this._data ?? [] } diff --git a/src/interpreter/plugin/MatrixPlugin.ts b/src/interpreter/plugin/MatrixPlugin.ts index d0cae3595b..dd9a787bd0 100644 --- a/src/interpreter/plugin/MatrixPlugin.ts +++ b/src/interpreter/plugin/MatrixPlugin.ts @@ -9,7 +9,7 @@ import {MatrixSize, matrixSizeForMultiplication, matrixSizeForPoolFunction} from import {ProcedureAst} from '../../parser' import {Interpreter} from '../Interpreter' import {InterpreterState} from '../InterpreterState' -import {InterpreterValue} from '../InterpreterValue' +import {InternalScalarValue, InterpreterValue} from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' @@ -188,12 +188,9 @@ export class MatrixPlugin extends FunctionPlugin implements FunctionPluginTypech public transpose(ast: ProcedureAst, state: InterpreterState): InterpreterValue { return this.runFunction(ast.args, state, this.metadata('TRANSPOSE'), (matrix: SimpleRangeValue) => { - if (!matrix.hasOnlyNumbers()) { - return new CellError(ErrorType.VALUE, ErrorMessage.NumberRange) - } - const input = matrix.rawNumbers() + const input = matrix.rawData() const inputSize = matrix.size - const result: number[][] = [] + const result: InternalScalarValue[][] = [] for (let i = 0; i < inputSize.width; ++i) { result[i] = [] for (let j = 0; j < inputSize.height; ++j) { @@ -201,7 +198,7 @@ export class MatrixPlugin extends FunctionPlugin implements FunctionPluginTypech } } - return SimpleRangeValue.onlyNumbers(result) + return SimpleRangeValue.onlyValues(result) }) } diff --git a/test/interpreter/matrix-plugin.spec.ts b/test/interpreter/matrix-plugin.spec.ts index 7f5141c716..073fca17a3 100644 --- a/test/interpreter/matrix-plugin.spec.ts +++ b/test/interpreter/matrix-plugin.spec.ts @@ -3,7 +3,7 @@ import {ErrorType, HyperFormula} from '../../src' import {ConfigParams} from '../../src/Config' import {ErrorMessage} from '../../src/error-message' import {MatrixPlugin} from '../../src/interpreter/plugin/MatrixPlugin' -import {adr, detailedError} from '../testUtils' +import {adr, detailedError, detailedErrorWithOrigin} from '../testUtils' describe('Matrix plugin', () => { beforeAll(() => { @@ -256,6 +256,7 @@ describe('Function TRANSPOSE', () => { expect(engine.getCellValue(adr('A1'))).toEqualError(detailedError(ErrorType.NA, ErrorMessage.WrongArgNumber)) expect(engine.getCellValue(adr('B1'))).toEqualError(detailedError(ErrorType.NA, ErrorMessage.WrongArgNumber)) }) + it('transpose returns VALUE when wrong type', () => { const engine = HyperFormula.buildFromArray([ ['=TRANSPOSE("fdsa")'], @@ -276,4 +277,20 @@ describe('Function TRANSPOSE', () => { expect(engine.getCellValue(adr('A5'))).toBe(2) expect(engine.getCellValue(adr('B4'))).toBe(3) }) + + it('transpose any values', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['foo', 'bar'], + ['=1/0', '=TRUE()'], + ['=TRANSPOSE(A1:B3)'], + ]) + + expect(engine.getCellValue(adr('A4'))).toBeCloseTo(1) + expect(engine.getCellValue(adr('B4'))).toEqual('foo') + expect(engine.getCellValue(adr('C4'))).toEqual(detailedErrorWithOrigin(ErrorType.DIV_BY_ZERO, 'Sheet1!A3')) + expect(engine.getCellValue(adr('A5'))).toBeCloseTo(2) + expect(engine.getCellValue(adr('B5'))).toEqual('bar') + expect(engine.getCellValue(adr('C5'))).toEqual(true) + }) }) From 4cdf2e5f2f15c45357fcdde723564f2d5261c071 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 15 May 2021 10:33:17 +0200 Subject: [PATCH 02/87] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e7044ecbf8..03e7e7f293 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Breaking change**: Changed API of many sheet-related methods to take sheetId instead of sheetName as an argument. (#645) - **Breaking change**: Removed support for matrix formulas (`{=FORMULA}`) notation. Engine now supports formulas returning array of values (instead of only scalars). (#652) - **Breaking change**: Removed numeric matrix detection along with matrixDetection and matrixDetectionThreshold config options. (#669) +- **Breaking change**: Removed numeric matrix detection along with matrixDetection and matrixDetectionThreshold config options. (#669) - Changed SWITCH function so it takes array as its first argument. +- Changed TRANSPOSE function, so it works with data of any type. (#670) ### Added - Added support for array arithmetic. (#628) From c9cf90f6c3547eaecfbc3824b55c8e5672cbb222 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 15 May 2021 10:42:46 +0200 Subject: [PATCH 03/87] Remove obsolete test --- test/interpreter/matrix-plugin.spec.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/test/interpreter/matrix-plugin.spec.ts b/test/interpreter/matrix-plugin.spec.ts index 073fca17a3..bb97a8424a 100644 --- a/test/interpreter/matrix-plugin.spec.ts +++ b/test/interpreter/matrix-plugin.spec.ts @@ -257,14 +257,6 @@ describe('Function TRANSPOSE', () => { expect(engine.getCellValue(adr('B1'))).toEqualError(detailedError(ErrorType.NA, ErrorMessage.WrongArgNumber)) }) - it('transpose returns VALUE when wrong type', () => { - const engine = HyperFormula.buildFromArray([ - ['=TRANSPOSE("fdsa")'], - ]) - - expect(engine.getCellValue(adr('A1'))).toEqualError(detailedError(ErrorType.VALUE, ErrorMessage.NumberRange)) - }) - it('transpose without braces', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], From 0b30d65a66b60ec4d5f7be107f5f08aa40c9c9b4 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 8 May 2021 08:14:40 +0200 Subject: [PATCH 04/87] Allow to move cells in address mapping --- .../AddressMapping/AddressMapping.ts | 20 ++++++++++- test/address-mapping.spec.ts | 33 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/DependencyGraph/AddressMapping/AddressMapping.ts b/src/DependencyGraph/AddressMapping/AddressMapping.ts index 02d4044e81..d89729d269 100644 --- a/src/DependencyGraph/AddressMapping/AddressMapping.ts +++ b/src/DependencyGraph/AddressMapping/AddressMapping.ts @@ -7,7 +7,6 @@ import {SimpleCellAddress} from '../../Cell' import {RawCellContent} from '../../CellContentParser' import {NoSheetWithIdError} from '../../errors' import {EmptyValue, InterpreterValue} from '../../interpreter/InterpreterValue' -import {Sheet, SheetBoundaries} from '../../Sheet' import {ColumnsSpan, RowsSpan} from '../../Span' import {MatrixVertex, ValueCellVertex} from '../index' import {CellVertex} from '../Vertex' @@ -98,6 +97,25 @@ export class AddressMapping { sheetMapping.setCell(address, newVertex) } + public moveCell(source: SimpleCellAddress, destination: SimpleCellAddress) { + const sheetMapping = this.mapping.get(source.sheet) + if (!sheetMapping) { + throw Error('Sheet not initialized') + } + if (source.sheet !== destination.sheet) { + throw Error('Cannot move cells between sheets') + } + if (sheetMapping.has(destination)) { + throw new Error('Cannot move cell. Destination already occupied.') + } + const vertex = sheetMapping.getCell(source) + if (vertex === undefined) { + throw new Error('Cannot move cell. No cell with such address.') + } + this.setCell(destination, vertex) + this.removeCell(source) + } + public removeCell(address: SimpleCellAddress) { const sheetMapping = this.mapping.get(address.sheet) if (!sheetMapping) { diff --git a/test/address-mapping.spec.ts b/test/address-mapping.spec.ts index 617fa56f70..413fd7a673 100644 --- a/test/address-mapping.spec.ts +++ b/test/address-mapping.spec.ts @@ -315,12 +315,44 @@ const sharedExamples = (builder: (width: number, height: number) => AddressMappi mapping.setCell(adr('A3'), new EmptyCellVertex({sheet: 0, row: 0, col: 0})) expect(mapping.getHeight(0)).toBe(3) }) + + it('should move cell from source to destination', () => { + const mapping = builder(1, 2) + mapping.setCell(adr('A1'), new ValueCellVertex(42, 42)) + + mapping.moveCell(adr('A1'), adr('A2')) + + expect(mapping.has(adr('A1'))).toEqual(false) + expect(mapping.has(adr('A2'))).toEqual(true) + }) + + it('should throw error when trying to move not existing vertex', () => { + const mapping = builder(1, 2) + + expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrow(Error('Cannot move cell. No cell with such address.')) + }) + + it('should throw error when trying to move vertex onto occupied place', () => { + const mapping = builder(1, 2) + mapping.setCell(adr('A1'), new ValueCellVertex(42, 42)) + mapping.setCell(adr('A2'), new ValueCellVertex(42, 42)) + + expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrow(Error('Cannot move cell. Destination already occupied.')) + }) + + it('should throw error when trying to move vertices between sheets', () => { + const mapping = builder(1, 2) + mapping.setCell(adr('A1', 0), new ValueCellVertex(42, 42)) + + expect(() => mapping.moveCell(adr('A1', 0), adr('A2', 1))).toThrow('Cannot move cells between sheets.') + }) } describe('SparseStrategy', () => { sharedExamples((maxCol: number, maxRow: number) => { const mapping = new AddressMapping(new AlwaysSparse()) mapping.addSheet(0, new SparseStrategy(maxCol, maxRow)) + mapping.addSheet(1, new SparseStrategy(maxCol, maxRow)) return mapping }) @@ -339,6 +371,7 @@ describe('DenseStrategy', () => { sharedExamples((maxCol, maxRow) => { const mapping = new AddressMapping(new AlwaysDense()) mapping.addSheet(0, new DenseStrategy(maxCol, maxRow)) + mapping.addSheet(1, new DenseStrategy(maxCol, maxRow)) return mapping }) From 4df502c110625a4f695b4e852447bbbae5f533a3 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 8 May 2021 09:22:40 +0200 Subject: [PATCH 05/87] Compare matrices in graph comparator --- test/graphComparator.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/graphComparator.ts b/test/graphComparator.ts index f9c22010fe..4d700bbe12 100644 --- a/test/graphComparator.ts +++ b/test/graphComparator.ts @@ -54,7 +54,10 @@ export class EngineComparator { const actualVertex = this.actual.addressMapping.getCell(address) if (expectedVertex === null && actualVertex === null) { continue - } else if (expectedVertex instanceof FormulaCellVertex && actualVertex instanceof FormulaCellVertex) { + } else if ( + (expectedVertex instanceof FormulaCellVertex && actualVertex instanceof FormulaCellVertex) || + (expectedVertex instanceof MatrixVertex && actualVertex instanceof MatrixVertex) + ) { const actualVertexAddress = actualVertex.getAddress(this.actual.dependencyGraph.lazilyTransformingAstService) const expectedVertexAddress = expectedVertex.getAddress(this.expected.dependencyGraph.lazilyTransformingAstService) deepStrictEqual(actualVertexAddress, expectedVertexAddress, `Different addresses in formulas. expected: ${actualVertexAddress}, actual: ${expectedVertexAddress}`) @@ -64,8 +67,6 @@ export class EngineComparator { deepStrictEqual(actualVertex.getCellValue(), expectedVertex.getCellValue(), `Different values. expected: ${expectedVertex.getCellValue().toString()}, actual: ${actualVertex.getCellValue().toString()}`) } else if (expectedVertex instanceof EmptyCellVertex && actualVertex instanceof EmptyCellVertex) { continue - } else if (expectedVertex instanceof MatrixVertex && actualVertex instanceof MatrixVertex) { - throw Error('Not implemented yet.') } else { throw Error('Different vertex types') } From 73eda4724a39718c50e5d3d044404ac34292e6b2 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 8 May 2021 09:23:38 +0200 Subject: [PATCH 06/87] Adjust matrices address mapping after adding row --- src/CrudOperations.ts | 7 --- .../AddressMapping/AddressMapping.ts | 2 +- src/DependencyGraph/DependencyGraph.ts | 20 ++++++++ src/DependencyGraph/MatrixMapping.ts | 8 +++ test/cruds/adding-row.spec.ts | 51 ++++++++++++++----- 5 files changed, 68 insertions(+), 20 deletions(-) diff --git a/src/CrudOperations.ts b/src/CrudOperations.ts index ea6413f2c7..46fe71a87e 100644 --- a/src/CrudOperations.ts +++ b/src/CrudOperations.ts @@ -455,13 +455,6 @@ export class CrudOperations { if (!isNonnegativeInteger(row) || !isPositiveInteger(numberOfRowsToAdd)) { throw new InvalidArgumentsError('row number to be nonnegative and number of rows to add to be positive.') } - - if (isPositiveInteger(row) - && this.dependencyGraph.matrixMapping.isFormulaMatrixInRow(sheet, row - 1) - && this.dependencyGraph.matrixMapping.isFormulaMatrixInRow(sheet, row) - ) { - throw new TargetLocationHasMatrixError() - } } } diff --git a/src/DependencyGraph/AddressMapping/AddressMapping.ts b/src/DependencyGraph/AddressMapping/AddressMapping.ts index d89729d269..9c0352c436 100644 --- a/src/DependencyGraph/AddressMapping/AddressMapping.ts +++ b/src/DependencyGraph/AddressMapping/AddressMapping.ts @@ -103,7 +103,7 @@ export class AddressMapping { throw Error('Sheet not initialized') } if (source.sheet !== destination.sheet) { - throw Error('Cannot move cells between sheets') + throw Error('Cannot move cells between sheets.') } if (sheetMapping.has(destination)) { throw new Error('Cannot move cell. Destination already occupied.') diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 5d94cd29aa..161b390e55 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -378,6 +378,10 @@ export class DependencyGraph { this.addressMapping.addRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) }) + this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { + this.fixMatricesAfterAddingRow(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) + }) + this.stats.measure(StatType.ADJUSTING_RANGES, () => { this.rangeMapping.moveAllRangesInSheetAfterRowByRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) this.fixRangesWhenAddingRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) @@ -844,6 +848,22 @@ export class DependencyGraph { } } + private fixMatricesAfterAddingRow(sheet: number, rowStart: number, numberOfRows: number) { + if (rowStart <= 0) { + return + } + for (const [, matrix] of this.matrixMapping.matricesInRows(RowsSpan.fromRowStartAndEnd(sheet, rowStart-1, rowStart-1))) { + const matrixRange = matrix.getRange() + for (let col = matrixRange.start.col; col <= matrixRange.end.col; ++col) { + for (let row = rowStart; row <= matrixRange.end.row; ++row) { + const destination = simpleCellAddress(sheet, col, row) + const source = simpleCellAddress(sheet, col, row + numberOfRows) + this.addressMapping.moveCell(source, destination) + } + } + } + } + private removeVertex(vertex: Vertex) { this.removeVertexAndCleanupDependencies(vertex) if (vertex instanceof RangeVertex) { diff --git a/src/DependencyGraph/MatrixMapping.ts b/src/DependencyGraph/MatrixMapping.ts index 52e4c3272d..c49da24cfa 100644 --- a/src/DependencyGraph/MatrixMapping.ts +++ b/src/DependencyGraph/MatrixMapping.ts @@ -28,6 +28,14 @@ export class MatrixMapping { return this.matrixMapping.size } + public* matricesInRows(rowsSpan: RowsSpan): IterableIterator<[string, MatrixVertex]> { + for (const [mtxKey, mtx] of this.matrixMapping.entries()) { + if (mtx.spansThroughSheetRows(rowsSpan.sheet, rowsSpan.rowStart, rowsSpan.rowEnd)) { + yield [mtxKey, mtx] + } + } + } + public isFormulaMatrixInRow(sheet: number, row: number): boolean { for (const mtx of this.matrixMapping.values()) { if (mtx.spansThroughSheetRows(sheet, row)) { diff --git a/test/cruds/adding-row.spec.ts b/test/cruds/adding-row.spec.ts index 63c036db98..d43e1e2b63 100644 --- a/test/cruds/adding-row.spec.ts +++ b/test/cruds/adding-row.spec.ts @@ -4,7 +4,8 @@ import {simpleCellAddress} from '../../src/Cell' import {Config} from '../../src/Config' import {FormulaCellVertex, MatrixVertex} from '../../src/DependencyGraph' import {ColumnIndex} from '../../src/Lookup/ColumnIndex' -import {adr, expectArrayWithSameContent, extractMatrixRange} from '../testUtils' +import {adr, expectArrayWithSameContent, expectEngineToBeTheSameAs, extractMatrixRange} from '../testUtils' +import {AlwaysDense} from '../../src/DependencyGraph/AddressMapping/ChooseAddressMappingPolicy' describe('Adding row - checking if its possible', () => { it('no if starting row is negative', () => { @@ -89,19 +90,45 @@ describe('Adding row - checking if its possible', () => { }) }) -describe('Adding row - matrix check', () => { - it('raise error if trying to add a row in a row with matrix', () => { +describe('Adding row - matrix', () => { + it('should be possible to add row crossing matrix', () => { const engine = HyperFormula.buildFromArray([ - ['1', '2'], - ['3', '4'], - ['=TRANSPOSE(A1:B2)'], - [], - ['13'], - ]) + ['1', '2', '3'], + ['4', '5', '6'], + ['foo', '=TRANSPOSE(A1:C2)'], + ['bar'], + ], {chooseAddressMappingPolicy: new AlwaysDense()}) + + engine.addRows(0, [3, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['1', '2', '3'], + ['4', '5', '6'], + ['foo', '=TRANSPOSE(A1:C2)'], + [null], + ['bar'], + ])) + }) - expect(() => { - engine.addRows(0, [3, 1]) - }).toThrowError('Cannot perform this operation, target location has a matrix inside.') + it('should adjust matrix address mapping when adding multiple rows', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2', '3'], + ['4', '5', '6'], + ['foo', '=TRANSPOSE(A1:C2)'], + ['bar'], + ], {chooseAddressMappingPolicy: new AlwaysDense()}) + + engine.addRows(0, [3, 3]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['1', '2', '3'], + ['4', '5', '6'], + ['foo', '=TRANSPOSE(A1:C2)'], + [null], + [null], + [null], + ['bar'], + ])) }) it('should be possible to add row right above matrix', () => { From 688bcf6fadbfb4ea66c4f233ee89ec9f97b0ac94 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 8 May 2021 10:08:37 +0200 Subject: [PATCH 07/87] TODO --- test/cruds/adding-columns.spec.ts | 3 ++- test/cruds/adding-row.spec.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/test/cruds/adding-columns.spec.ts b/test/cruds/adding-columns.spec.ts index 92ed943bb2..30ae26b137 100644 --- a/test/cruds/adding-columns.spec.ts +++ b/test/cruds/adding-columns.spec.ts @@ -203,7 +203,8 @@ describe('Adding column - FormulaCellVertex#address update', () => { }) }) -describe('Adding column - MatrixVertex', () => { +/* TODO size of matrix can be dependent on structural changes */ +describe.skip('Adding column - MatrixVertex', () => { it('MatrixVertex#formula should be updated', () => { const engine = HyperFormula.buildFromArray([ ['1', '2', '=TRANSPOSE(A1:B2)'], diff --git a/test/cruds/adding-row.spec.ts b/test/cruds/adding-row.spec.ts index d43e1e2b63..b21eb4e877 100644 --- a/test/cruds/adding-row.spec.ts +++ b/test/cruds/adding-row.spec.ts @@ -224,7 +224,8 @@ describe('Adding row - reevaluation', () => { }) }) -describe('Adding row - MatrixVertex', () => { +/* TODO size of matrix can be dependent on structural changes */ +describe.skip('Adding row - MatrixVertex', () => { it('MatrixVertex#formula should be updated', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], From ae20930041c8bc0b6a04eca0992acec6c304af13 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 8 May 2021 10:10:17 +0200 Subject: [PATCH 08/87] Obsolete test --- test/cruds/adding-row.spec.ts | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/test/cruds/adding-row.spec.ts b/test/cruds/adding-row.spec.ts index b21eb4e877..4a4afbf5d2 100644 --- a/test/cruds/adding-row.spec.ts +++ b/test/cruds/adding-row.spec.ts @@ -59,21 +59,6 @@ describe('Adding row - checking if its possible', () => { expect(engine.isItPossibleToAddRows(-Infinity, [0, 1])).toEqual(false) }) - it('no if theres a formula matrix in place where we add', () => { - const engine = HyperFormula.buildFromArray([ - ['1', '2'], - ['3', '4'], - ['=TRANSPOSE(A1:B2)'], - [], - ['13'], - ]) - - expect(engine.isItPossibleToAddRows(0, [1, 1])).toEqual(true) - expect(engine.isItPossibleToAddRows(0, [2, 1])).toEqual(true) - expect(engine.isItPossibleToAddRows(0, [3, 1])).toEqual(false) - expect(engine.isItPossibleToAddRows(0, [4, 1])).toEqual(true) - }) - it('no if adding row would exceed sheet size limit', () => { const engine = HyperFormula.buildFromArray( Array(Config.defaultConfig.maxRows - 1).fill(['']) From 03cb6cecfe9c8530a3e717048ff02118959fe4c4 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 15 May 2021 09:17:47 +0200 Subject: [PATCH 09/87] Fix cherry-pick --- src/DependencyGraph/AddressMapping/AddressMapping.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/DependencyGraph/AddressMapping/AddressMapping.ts b/src/DependencyGraph/AddressMapping/AddressMapping.ts index 9c0352c436..a6854375a8 100644 --- a/src/DependencyGraph/AddressMapping/AddressMapping.ts +++ b/src/DependencyGraph/AddressMapping/AddressMapping.ts @@ -12,6 +12,7 @@ import {MatrixVertex, ValueCellVertex} from '../index' import {CellVertex} from '../Vertex' import {ChooseAddressMapping} from './ChooseAddressMappingPolicy' import {IAddressMappingStrategy} from './IAddressMappingStrategy' +import {Sheet, SheetBoundaries} from '../../Sheet' export class AddressMapping { private mapping: Map = new Map() From ce743d5d0e2d9bea81875b31028d5cf80ca7fe4e Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 21 May 2021 08:49:32 +0200 Subject: [PATCH 10/87] Compare matrix mappings in graph comparator --- test/graphComparator.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/graphComparator.ts b/test/graphComparator.ts index 4d700bbe12..d48c3d0478 100644 --- a/test/graphComparator.ts +++ b/test/graphComparator.ts @@ -47,6 +47,8 @@ export class EngineComparator { const actualWidth = this.actual.addressMapping.getWidth(sheet) const actualHeight = this.actual.addressMapping.getHeight(sheet) + deepStrictEqual(this.actual.matrixMapping, this.expected.matrixMapping) + for (let x = 0; x < Math.max(expectedWidth, actualWidth); ++x) { for (let y = 0; y < Math.max(expectedHeight, actualHeight); ++y) { const address = simpleCellAddress(sheet, x, y) From 55663ecfccf3df921d250e1c10cd7e3b54577bf6 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 21 May 2021 08:49:56 +0200 Subject: [PATCH 11/87] Remove unused code --- src/DependencyGraph/FormulaCellVertex.ts | 27 ------------------------ src/Matrix.ts | 8 ------- 2 files changed, 35 deletions(-) diff --git a/src/DependencyGraph/FormulaCellVertex.ts b/src/DependencyGraph/FormulaCellVertex.ts index 27576f1417..4f3c2a8354 100644 --- a/src/DependencyGraph/FormulaCellVertex.ts +++ b/src/DependencyGraph/FormulaCellVertex.ts @@ -175,33 +175,6 @@ export class MatrixVertex extends FormulaVertex { (col < this.cellAddress.col + this.width) } - /* TODO cruds should ensure is recent data */ - addRows(sheet: number, row: number, numberOfRows: number): void { - if (this.matrix instanceof Matrix) { - this.matrix.addRows(row - this.cellAddress.row, numberOfRows) - } - } - - addColumns(sheet: number, column: number, numberOfColumns: number): void { - if (this.matrix instanceof Matrix) { - this.matrix.addColumns(column - this.cellAddress.col, numberOfColumns) - } - } - - removeRows(removedRows: RowsSpan): void { - if (this.matrix instanceof Matrix) { - const removedRowsFromMatrix = this.rowsFromMatrix().intersect(removedRows)! - this.matrix.removeRows(removedRowsFromMatrix.rowStart - this.cellAddress.row, removedRowsFromMatrix.rowEnd - this.cellAddress.row) - } - } - - removeColumns(removedColumns: ColumnsSpan): void { - if (this.matrix instanceof Matrix) { - const removedColumnsFromMatrix = this.columnsFromMatrix().intersect(removedColumns)! - this.matrix.removeColumns(removedColumnsFromMatrix.columnStart - this.cellAddress.col, removedColumnsFromMatrix.columnEnd - this.cellAddress.col) - } - } - isComputed() { return (!(this.matrix instanceof NotComputedMatrix)) } diff --git a/src/Matrix.ts b/src/Matrix.ts index 6bdc5ac216..9ff9b88f1b 100644 --- a/src/Matrix.ts +++ b/src/Matrix.ts @@ -129,14 +129,6 @@ export class Matrix implements IMatrix { return this.matrix } - public* generateValues(leftCorner: SimpleCellAddress): IterableIterator<[InternalScalarValue, SimpleCellAddress]> { - for (let row = 0; row < this.size.height; ++row) { - for (let col = 0; col < this.size.width; ++col) { - yield [this.matrix[row][col], simpleCellAddress(leftCorner.sheet, leftCorner.col + col, leftCorner.row + row)] - } - } - } - public resize(newSize: MatrixSize) { if(this.height() < newSize.height) { this.addRows(this.height(), newSize.height-this.height()) From fbd7ae6b9f99c2913e3ad053e4234db007dadf2a Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 21 May 2021 08:50:11 +0200 Subject: [PATCH 12/87] Add simple tests --- test/cruds/matrix-cruds.spec.ts | 61 +++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 test/cruds/matrix-cruds.spec.ts diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts new file mode 100644 index 0000000000..85dc307051 --- /dev/null +++ b/test/cruds/matrix-cruds.spec.ts @@ -0,0 +1,61 @@ +import {HyperFormula} from '../../src' +import {adr, expectEngineToBeTheSameAs} from '../testUtils' +import {AbsoluteCellRange} from '../../src/AbsoluteCellRange' + +describe('Add rows', () => { + it('should be possible to add row above matrix', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D3'], + [], + [], + ['foo'] + ], {useArrayArithmetic: true}) + + engine.addRows(0, [0, 1]) + + const expected = HyperFormula.buildFromArray([ + [], + ['=-C2:D4'], + [], + [], + ['foo'] + ], {useArrayArithmetic: true}) + + expectEngineToBeTheSameAs(engine, expected) + }) + + it('adding row across array should not change array', () => { + const engine = HyperFormula.buildFromArray([ + [], [], [], + ['=-A1:B3'], + [], [], + ['foo'] + ], { useArrayArithmetic: true }) + + engine.addRows(0, [4, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [], [], [], + ['=-A1:B3'], + [], [], [], + ['foo'] + ], { useArrayArithmetic: true })) + }) + + it('Adding row should expand dependent array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ['=TRANSPOSE(A1:B2)'] + ], { useArrayArithmetic: true }) + + engine.addRows(0, [1, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [], + [3, 4], + ['=TRANSPOSE(A1:B3)'] + ], { useArrayArithmetic: true })) + }) +}) From 8028fa800a5e6e7ebb4ce95ec1556ef39519a47e Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 21 May 2021 09:29:35 +0200 Subject: [PATCH 13/87] Move MatrixMapping entries when adding rows --- src/DependencyGraph/DependencyGraph.ts | 9 ++-- src/DependencyGraph/MatrixMapping.ts | 26 +++++++++++ test/cruds/matrix-cruds.spec.ts | 3 +- test/matrix-mapping.spec.ts | 60 ++++++++++++++++++++++++++ 4 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 test/matrix-mapping.spec.ts diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 161b390e55..077fa979f2 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -378,15 +378,15 @@ export class DependencyGraph { this.addressMapping.addRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) }) - this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { - this.fixMatricesAfterAddingRow(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) - }) - this.stats.measure(StatType.ADJUSTING_RANGES, () => { this.rangeMapping.moveAllRangesInSheetAfterRowByRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) this.fixRangesWhenAddingRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) }) + this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { + this.fixMatricesAfterAddingRow(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) + }) + for (const vertex of this.addressMapping.verticesFromRowsSpan(addedRows)) { this.graph.markNodeAsSpecialRecentlyChanged(vertex) } @@ -849,6 +849,7 @@ export class DependencyGraph { } private fixMatricesAfterAddingRow(sheet: number, rowStart: number, numberOfRows: number) { + this.matrixMapping.moveMatrixVerticesAfterRowByRows(sheet, rowStart, numberOfRows) if (rowStart <= 0) { return } diff --git a/src/DependencyGraph/MatrixMapping.ts b/src/DependencyGraph/MatrixMapping.ts index c49da24cfa..d36c0e43b8 100644 --- a/src/DependencyGraph/MatrixMapping.ts +++ b/src/DependencyGraph/MatrixMapping.ts @@ -93,4 +93,30 @@ export class MatrixMapping { public destroy(): void { this.matrixMapping.clear() } + + public moveMatrixVerticesAfterRowByRows(sheet: number, row: number, numberOfRows: number) { + this.updateMatrixVerticesInSheet(sheet, (key: string, vertex: MatrixVertex) => { + const range = vertex.getRange() + return row <= range.start.row ? [range.shifted(0, numberOfRows).toString(), vertex] : undefined + }) + } + + private updateMatrixVerticesInSheet(sheet: number, fn: (key: string, vertex: MatrixVertex) => Maybe<[string, MatrixVertex]>) { + const updated = Array<[string, MatrixVertex]>() + + for (const [key, vertex] of this.matrixMapping.entries()) { + if (vertex.sheet !== sheet) { + continue + } + const result = fn(key, vertex) + if (result !== undefined) { + this.removeMatrix(key) + updated.push(result) + } + } + + updated.forEach(([key, matrix]) => { + this.matrixMapping.set(key, matrix) + }) + } } diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts index 85dc307051..9f6296a23d 100644 --- a/test/cruds/matrix-cruds.spec.ts +++ b/test/cruds/matrix-cruds.spec.ts @@ -1,6 +1,5 @@ import {HyperFormula} from '../../src' -import {adr, expectEngineToBeTheSameAs} from '../testUtils' -import {AbsoluteCellRange} from '../../src/AbsoluteCellRange' +import {expectEngineToBeTheSameAs} from '../testUtils' describe('Add rows', () => { it('should be possible to add row above matrix', () => { diff --git a/test/matrix-mapping.spec.ts b/test/matrix-mapping.spec.ts new file mode 100644 index 0000000000..87eb4771be --- /dev/null +++ b/test/matrix-mapping.spec.ts @@ -0,0 +1,60 @@ +import {MatrixMapping, MatrixVertex} from '../src/DependencyGraph' +import {adr} from './testUtils' +import {AbsoluteCellRange} from '../src/AbsoluteCellRange' +import {buildNumberAst} from '../src/parser/Ast' +import {MatrixSize} from '../src/MatrixSize' + +describe('MatrixMapping', () => { + it('should be empty', () => { + const matrixMapping = new MatrixMapping() + + expect(matrixMapping.count()).toEqual(0) + }) + it('should set matrix', () => { + const matrixMapping = new MatrixMapping() + + const vertex = new MatrixVertex(buildNumberAst(1), adr('A1'), new MatrixSize(2, 2)) + const range = AbsoluteCellRange.spanFrom(adr('A1'), 2, 2) + matrixMapping.setMatrix(range, vertex) + + expect(matrixMapping.count()).toEqual(1) + expect(matrixMapping.getMatrix(range)).toEqual(vertex) + }) + + it('should answer some questions', () => { + const matrixMapping = new MatrixMapping() + const vertex = new MatrixVertex(buildNumberAst(1), adr('B2'), new MatrixSize(2, 2)) + const range = AbsoluteCellRange.spanFrom(adr('B2'), 2, 2) + matrixMapping.setMatrix(range, vertex) + + expect(matrixMapping.isFormulaMatrixInRow(0, 0)).toBe(false) + expect(matrixMapping.isFormulaMatrixInRow(0, 1)).toBe(true) + expect(matrixMapping.isFormulaMatrixAtAddress(adr('A1'))).toBe(false) + expect(matrixMapping.isFormulaMatrixAtAddress(adr('B2'))).toBe(true) + expect(matrixMapping.isFormulaMatrixInRange(AbsoluteCellRange.spanFrom(adr('A1'), 1, 1))).toEqual(false) + expect(matrixMapping.isFormulaMatrixInRange(AbsoluteCellRange.spanFrom(adr('B1'), 1, 2))).toEqual(true) + expect(matrixMapping.isFormulaMatrixInRange(AbsoluteCellRange.spanFrom(adr('A2'), 2, 1))).toEqual(true) + expect(matrixMapping.isFormulaMatrixInColumn(0, 0)).toEqual(false) + expect(matrixMapping.isFormulaMatrixInColumn(0, 1)).toEqual(true) + expect(matrixMapping.isFormulaMatrixInRow(0, 0)).toEqual(false) + expect(matrixMapping.isFormulaMatrixInRow(0, 1)).toEqual(true) + }) + + + it('should move matrices below row', () => { + const matrixMapping = new MatrixMapping() + const vertex1 = new MatrixVertex(buildNumberAst(1), adr('B1'), new MatrixSize(2, 2)) + const range1 = AbsoluteCellRange.spanFrom(adr('B1'), 2, 2) + const vertex2 = new MatrixVertex(buildNumberAst(1), adr('D2'), new MatrixSize(2, 2)) + const range2 = AbsoluteCellRange.spanFrom(adr('D2'), 2, 2) + matrixMapping.setMatrix(range1, vertex1) + matrixMapping.setMatrix(range2, vertex2) + + matrixMapping.moveMatrixVerticesAfterRowByRows(0, 0, 2) + + expect(matrixMapping.getMatrix(range1)).toBeUndefined() + expect(matrixMapping.getMatrix(range2)).toBeUndefined() + expect(matrixMapping.getMatrix(AbsoluteCellRange.spanFrom(adr('B3'), 2, 2))).toEqual(vertex1) + expect(matrixMapping.getMatrix(AbsoluteCellRange.spanFrom(adr('D4'), 2, 2))).toEqual(vertex2) + }) +}) From 37bd290456987ad29eaa906cc4ffa63302ee3e71 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 21 May 2021 13:13:33 +0200 Subject: [PATCH 14/87] Spike --- src/DependencyGraph/DependencyGraph.ts | 23 +++++++--- src/DependencyGraph/RangeMapping.ts | 8 ++-- src/LazilyTransformingAstService.ts | 2 +- src/Operations.ts | 52 +++++++++++++++++------ src/dependencyTransformers/Transformer.ts | 2 +- src/parser/ParserWithCaching.ts | 4 +- 6 files changed, 65 insertions(+), 26 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 077fa979f2..acebc4f4f2 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -44,6 +44,7 @@ import {MatrixMapping} from './MatrixMapping' import {RangeMapping} from './RangeMapping' import {SheetMapping} from './SheetMapping' import {RawAndParsedValue} from './ValueCellVertex' +import {Matrix} from '../Matrix' export class DependencyGraph { /* @@ -373,16 +374,18 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() } - public addRows(addedRows: RowsSpan) { + public addRows(addedRows: RowsSpan): Set { this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.addRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) }) - this.stats.measure(StatType.ADJUSTING_RANGES, () => { - this.rangeMapping.moveAllRangesInSheetAfterRowByRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) + const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { + const result = this.rangeMapping.moveAllRangesInSheetAfterRowByRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) this.fixRangesWhenAddingRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) + return this.getRangeRelatedMatrixVertices(result) }) + this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { this.fixMatricesAfterAddingRow(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) }) @@ -392,6 +395,8 @@ export class DependencyGraph { } this.addStructuralNodesToChangeSet() + + return affectedMatrices } public addColumns(addedColumns: ColumnsSpan) { @@ -614,6 +619,12 @@ export class DependencyGraph { this.matrixMapping.destroy() } + public getRangeRelatedMatrixVertices(ranges: RangeVertex[]): Set { + const reduced = ranges + .map(range => Array.from(this.graph.adjacentNodes(range)).filter(node => node instanceof MatrixVertex)) as MatrixVertex[][] + return new Set(...reduced) + } + public* verticesFromRange(range: AbsoluteCellRange): IterableIterator { for (const address of range.addresses(this)) { const vertex = this.getCell(address) @@ -809,9 +820,9 @@ export class DependencyGraph { private exchangeOrAddFormulaVertex(vertex: FormulaVertex): void { const range = AbsoluteCellRange.spanFrom(vertex.getAddress(this.lazilyTransformingAstService), vertex.width, vertex.height) - for (const vertex of this.verticesFromRange(range)) { - this.ensureThatVertexIsNonMatrixCellVertex(vertex) - } + // for (const vertex of this.verticesFromRange(range)) { + // this.ensureThatVertexIsNonMatrixCellVertex(vertex) + // } if (vertex instanceof MatrixVertex) { this.setMatrix(range, vertex) diff --git a/src/DependencyGraph/RangeMapping.ts b/src/DependencyGraph/RangeMapping.ts index 520fb2b81a..f7492d08c4 100644 --- a/src/DependencyGraph/RangeMapping.ts +++ b/src/DependencyGraph/RangeMapping.ts @@ -109,8 +109,8 @@ export class RangeMapping { } } - public moveAllRangesInSheetAfterRowByRows(sheet: number, row: number, numberOfRows: number) { - this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex): Maybe => { + public moveAllRangesInSheetAfterRowByRows(sheet: number, row: number, numberOfRows: number): RangeVertex[] { + return this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex): Maybe => { if (row <= vertex.start.row) { vertex.range.shiftByRows(numberOfRows) return vertex @@ -219,7 +219,7 @@ export class RangeMapping { return this.rangeMapping.get(sheet)?.get(key) } - private updateVerticesFromSheet(sheet: number, fn: (key: string, vertex: RangeVertex) => Maybe) { + private updateVerticesFromSheet(sheet: number, fn: (key: string, vertex: RangeVertex) => Maybe): RangeVertex[] { const updated = Array() for (const [key, vertex] of this.entriesFromSheet(sheet)) { @@ -233,6 +233,8 @@ export class RangeMapping { updated.forEach((range) => { this.setRange(range) }) + + return updated } } diff --git a/src/LazilyTransformingAstService.ts b/src/LazilyTransformingAstService.ts index 54b3629f94..7d4ec40e5c 100644 --- a/src/LazilyTransformingAstService.ts +++ b/src/LazilyTransformingAstService.ts @@ -64,7 +64,7 @@ export class LazilyTransformingAstService { ast = newAst address = newAddress } - const cachedAst = this.parser!.rememberNewAst(ast) + const [hash, cachedAst] = this.parser!.rememberNewAst(ast) this.stats.end(StatType.TRANSFORM_ASTS_POSTPONED) return [cachedAst, address, this.transformations.length] diff --git a/src/Operations.ts b/src/Operations.ts index d263412c44..5a6111d55e 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -18,7 +18,7 @@ import { EmptyCellVertex, FormulaCellVertex, MatrixVertex, - ParsingErrorVertex, + ParsingErrorVertex, RangeVertex, SheetMapping, SparseStrategy, ValueCellVertex @@ -318,8 +318,8 @@ export class Operations { public setRowOrder(sheetId: number, rowMapping: [number, number][]): [SimpleCellAddress, ClipboardCell][] { const buffer: [SimpleCellAddress, ClipboardCell][][] = [] let oldContent: [SimpleCellAddress, ClipboardCell][] = [] - for(const [source, target] of rowMapping ) { - if(source!==target) { + for (const [source, target] of rowMapping) { + if (source !== target) { const rowRange = AbsoluteCellRange.spanFrom({sheet: sheetId, col: 0, row: source}, Infinity, 1) const row = this.getRangeClipboardCells(rowRange) oldContent = oldContent.concat(row) @@ -336,11 +336,11 @@ export class Operations { return oldContent } - public setColumnOrder(sheetId: number, columnMapping: [number, number][]): [SimpleCellAddress, ClipboardCell][] { + public setColumnOrder(sheetId: number, columnMapping: [number, number][]): [SimpleCellAddress, ClipboardCell][] { const buffer: [SimpleCellAddress, ClipboardCell][][] = [] let oldContent: [SimpleCellAddress, ClipboardCell][] = [] - for(const [source, target] of columnMapping ) { - if(source!==target) { + for (const [source, target] of columnMapping) { + if (source !== target) { const rowRange = AbsoluteCellRange.spanFrom({sheet: sheetId, col: source, row: 0}, 1, Infinity) const column = this.getRangeClipboardCells(rowRange) oldContent = oldContent.concat(column) @@ -540,13 +540,27 @@ export class Operations { return } - this.dependencyGraph.addRows(addedRows) + const affectedMatrices = this.dependencyGraph.addRows(addedRows) + for (const affectedMatrix of affectedMatrices) { + this.dependencyGraph.setMatrixEmpty(affectedMatrix) + } this.stats.measure(StatType.TRANSFORM_ASTS, () => { const transformation = new AddRowsTransformer(addedRows) transformation.performEagerTransformations(this.dependencyGraph, this.parser) this.lazilyTransformingAstService.addTransformation(transformation) }) + + this.rewriteAffectedMatrices(affectedMatrices) + } + + private rewriteAffectedMatrices(affectedMatrices: Set) { + for (const matrixVertex of affectedMatrices.values()) { + const ast = matrixVertex.getFormula(this.lazilyTransformingAstService) + const address = matrixVertex.getAddress(this.lazilyTransformingAstService) + const hash = this.parser.computeHashFromAst(ast) + this.setFormulaToCellFromCache(hash, address) + } } /** @@ -581,7 +595,7 @@ export class Operations { return {type: ClipboardCellType.VALUE, ...vertex.getValues()} } else if (vertex instanceof MatrixVertex) { const val = vertex.getMatrixCellValue(address) - if(val === EmptyValue) { + if (val === EmptyValue) { return {type: ClipboardCellType.EMPTY} } return {type: ClipboardCellType.VALUE, parsedValue: val, rawValue: vertex.getMatrixCellRawValue(address)} @@ -628,7 +642,13 @@ export class Operations { if (!(vertex instanceof MatrixVertex)) { if (parsedCellContent instanceof CellContent.Formula) { - const {ast, errors, hasVolatileFunction, hasStructuralChangeFunction, dependencies} = this.parser.parse(parsedCellContent.formula, address) + const { + ast, + errors, + hasVolatileFunction, + hasStructuralChangeFunction, + dependencies + } = this.parser.parse(parsedCellContent.formula, address) if (errors.length > 0) { this.dependencyGraph.setParsingErrorToCell(address, new ParsingErrorVertex(errors, parsedCellContent.formula)) } else { @@ -670,12 +690,18 @@ export class Operations { } public setFormulaToCellFromCache(formulaHash: string, address: SimpleCellAddress) { - const {ast, hasVolatileFunction, hasStructuralChangeFunction, dependencies} = this.parser.fetchCachedResult(formulaHash) + const { + ast, + hasVolatileFunction, + hasStructuralChangeFunction, + dependencies + } = this.parser.fetchCachedResult(formulaHash) const absoluteDependencies = absolutizeDependencies(dependencies, address) const [cleanedAst] = new CleanOutOfScopeDependenciesTransformer(address.sheet).transformSingleAst(ast, address) this.parser.rememberNewAst(cleanedAst) const cleanedDependencies = filterDependenciesOutOfScope(absoluteDependencies) - this.dependencyGraph.setFormulaToCell(address, cleanedAst, cleanedDependencies, MatrixSize.scalar(), hasVolatileFunction, hasStructuralChangeFunction) + const size = this.matrixSizePredictor.checkMatrixSize(ast, address) + this.dependencyGraph.setFormulaToCell(address, cleanedAst, cleanedDependencies, size, hasVolatileFunction, hasStructuralChangeFunction) } public setParsingErrorToCell(rawInput: string, errors: ParsingError[], address: SimpleCellAddress) { @@ -838,7 +864,7 @@ export function normalizeRemovedIndexes(indexes: ColumnRowIndex[]): ColumnRowInd return indexes } - const sorted = [...indexes].sort(([a], [b]) => a-b) + const sorted = [...indexes].sort(([a], [b]) => a - b) /* merge overlapping and adjacent indexes */ const merged = sorted.reduce((acc: ColumnRowIndex[], [startIndex, amount]: ColumnRowIndex) => { @@ -869,7 +895,7 @@ export function normalizeAddedIndexes(indexes: ColumnRowIndex[]): ColumnRowIndex return indexes } - const sorted = [...indexes].sort(([a], [b]) => a-b) + const sorted = [...indexes].sort(([a], [b]) => a - b) /* merge indexes with same start */ const merged = sorted.reduce((acc: ColumnRowIndex[], [startIndex, amount]: ColumnRowIndex) => { diff --git a/src/dependencyTransformers/Transformer.ts b/src/dependencyTransformers/Transformer.ts index 9309690b5e..1846e3d2ef 100644 --- a/src/dependencyTransformers/Transformer.ts +++ b/src/dependencyTransformers/Transformer.ts @@ -31,7 +31,7 @@ export abstract class Transformer implements FormulaTransformer { public performEagerTransformations(graph: DependencyGraph, parser: ParserWithCaching): void { for (const node of graph.matrixFormulaNodes()) { const [newAst, newAddress] = this.transformSingleAst(node.getFormula(graph.lazilyTransformingAstService), node.getAddress(graph.lazilyTransformingAstService)) - const cachedAst = parser.rememberNewAst(newAst) + const [hash, cachedAst] = parser.rememberNewAst(newAst) node.setFormula(cachedAst) node.setAddress(newAddress) } diff --git a/src/parser/ParserWithCaching.ts b/src/parser/ParserWithCaching.ts index 3c1d2e3167..a5dabd6821 100644 --- a/src/parser/ParserWithCaching.ts +++ b/src/parser/ParserWithCaching.ts @@ -154,9 +154,9 @@ export class ParserWithCaching { return hash } - public rememberNewAst(ast: Ast): Ast { + public rememberNewAst(ast: Ast): [string, Ast] { const hash = this.computeHashFromAst(ast) - return this.cache.maybeSetAndThenGet(hash, ast) + return [hash, this.cache.maybeSetAndThenGet(hash, ast)] } public computeHashFromAst(ast: Ast): string { From 747caec691bbd1f6cfb79f024bd159292ae85e8e Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 21 May 2021 15:12:18 +0200 Subject: [PATCH 15/87] Exchanging matrix vertex works --- src/AbsoluteCellRange.ts | 14 +++++++++-- src/Cell.ts | 4 +++ src/DependencyGraph/DependencyGraph.ts | 9 +++---- src/DependencyGraph/MatrixMapping.ts | 35 ++++++++++++++++++++------ src/DependencyGraph/RangeMapping.ts | 24 +++++++++--------- src/Operations.ts | 3 --- test/graphComparator.ts | 16 +++++++++++- test/matrix-mapping.spec.ts | 8 +++--- 8 files changed, 77 insertions(+), 36 deletions(-) diff --git a/src/AbsoluteCellRange.ts b/src/AbsoluteCellRange.ts index 0092d18874..bd8e119913 100644 --- a/src/AbsoluteCellRange.ts +++ b/src/AbsoluteCellRange.ts @@ -3,7 +3,14 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellRange, simpleCellAddress, SimpleCellAddress, SimpleColumnAddress, SimpleRowAddress} from './Cell' +import { + CellRange, + equalSimpleCellAddress, + simpleCellAddress, + SimpleCellAddress, + SimpleColumnAddress, + SimpleRowAddress +} from './Cell' import {DependencyGraph} from './DependencyGraph' import {Maybe} from './Maybe' import {AstNodeType, CellAddress, CellRangeAst} from './parser' @@ -274,6 +281,10 @@ export class AbsoluteCellRange { return this.width() === other.width() && this.height() === other.height() } + public sameAs(other: AbsoluteCellRange) { + return equalSimpleCellAddress(this.start, other.start) && equalSimpleCellAddress(this.end, other.end) + } + public addressesArrayMap(dependencyGraph: DependencyGraph, op: (arg: SimpleCellAddress) => T): T[][] { const ret = [] let currentRow = this.start.row @@ -391,7 +402,6 @@ export class AbsoluteColumnRange extends AbsoluteCellRange { return this.width() <= 0 } - public shiftByRows(_numberOfRows: number) { return } diff --git a/src/Cell.ts b/src/Cell.ts index 14a10a2661..b7c38a01f5 100644 --- a/src/Cell.ts +++ b/src/Cell.ts @@ -181,6 +181,7 @@ export interface SimpleCellAddress { sheet: number, } + export const simpleCellAddress = (sheet: number, col: number, row: number): SimpleCellAddress => ({sheet, col, row}) export const invalidSimpleCellAddress = (address: SimpleCellAddress): boolean => (address.col < 0 || address.row < 0) export const movedSimpleCellAddress = (address: SimpleCellAddress, toSheet: number, toRight: number, toBottom: number): SimpleCellAddress => { @@ -190,6 +191,9 @@ export const movedSimpleCellAddress = (address: SimpleCellAddress, toSheet: numb export const absoluteSheetReference = (address: AddressWithSheet, baseAddress: SimpleCellAddress): number => { return address.sheet === null ? baseAddress.sheet : address.sheet } +export const equalSimpleCellAddress = (left: SimpleCellAddress, right: SimpleCellAddress) => { + return left.sheet === right.sheet && left.col === right.col && left.row === right.row +} export interface SheetCellAddress { col: number, diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index acebc4f4f2..4405870e64 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -820,16 +820,13 @@ export class DependencyGraph { private exchangeOrAddFormulaVertex(vertex: FormulaVertex): void { const range = AbsoluteCellRange.spanFrom(vertex.getAddress(this.lazilyTransformingAstService), vertex.width, vertex.height) - // for (const vertex of this.verticesFromRange(range)) { - // this.ensureThatVertexIsNonMatrixCellVertex(vertex) - // } - + const oldNode = this.getCell(range.start) if (vertex instanceof MatrixVertex) { this.setMatrix(range, vertex) } + this.exchangeOrAddGraphNode(oldNode, vertex) - for (const [address, cellVertex] of this.entriesFromRange(range)) { - this.exchangeOrAddGraphNode(cellVertex, vertex) + for (const address of range.addresses(this)) { this.addressMapping.setCell(address, vertex) } } diff --git a/src/DependencyGraph/MatrixMapping.ts b/src/DependencyGraph/MatrixMapping.ts index d36c0e43b8..b5085bc770 100644 --- a/src/DependencyGraph/MatrixMapping.ts +++ b/src/DependencyGraph/MatrixMapping.ts @@ -8,20 +8,39 @@ import {SimpleCellAddress} from '../Cell' import {Maybe} from '../Maybe' import {ColumnsSpan, RowsSpan} from '../Span' import {MatrixVertex} from './' +import {simpleCellAddressToString} from '../parser' + +const mappingKey = (address: SimpleCellAddress) => `${address.sheet},${address.row},${address.col}` export class MatrixMapping { public readonly matrixMapping: Map = new Map() public getMatrix(range: AbsoluteCellRange): Maybe { - return this.matrixMapping.get(range.toString()) + const matrix = this.getMatrixByCorner(range.start) + if (matrix?.getRange().sameAs(range)) { + return matrix + } + return + } + + public getMatrixByCorner(address: SimpleCellAddress): Maybe { + return this.matrixMapping.get(mappingKey(address)) } public setMatrix(range: AbsoluteCellRange, vertex: MatrixVertex) { - this.matrixMapping.set(range.toString(), vertex) + this.matrixMapping.set(mappingKey(range.start), vertex) + } + + public setMatrixByCorner(address: SimpleCellAddress, vertex: MatrixVertex) { + this.matrixMapping.set(mappingKey(address), vertex) } public removeMatrix(range: string | AbsoluteCellRange) { - this.matrixMapping.delete(range.toString()) + if (typeof range === 'string') { + this.matrixMapping.delete(range) + } else { + this.matrixMapping.delete(mappingKey(range.start)) + } } public count(): number { @@ -97,12 +116,12 @@ export class MatrixMapping { public moveMatrixVerticesAfterRowByRows(sheet: number, row: number, numberOfRows: number) { this.updateMatrixVerticesInSheet(sheet, (key: string, vertex: MatrixVertex) => { const range = vertex.getRange() - return row <= range.start.row ? [range.shifted(0, numberOfRows).toString(), vertex] : undefined + return row <= range.start.row ? [range.shifted(0, numberOfRows), vertex] : undefined }) } - private updateMatrixVerticesInSheet(sheet: number, fn: (key: string, vertex: MatrixVertex) => Maybe<[string, MatrixVertex]>) { - const updated = Array<[string, MatrixVertex]>() + private updateMatrixVerticesInSheet(sheet: number, fn: (key: string, vertex: MatrixVertex) => Maybe<[AbsoluteCellRange, MatrixVertex]>) { + const updated = Array<[AbsoluteCellRange, MatrixVertex]>() for (const [key, vertex] of this.matrixMapping.entries()) { if (vertex.sheet !== sheet) { @@ -115,8 +134,8 @@ export class MatrixMapping { } } - updated.forEach(([key, matrix]) => { - this.matrixMapping.set(key, matrix) + updated.forEach(([range, matrix]) => { + this.setMatrix(range, matrix) }) } } diff --git a/src/DependencyGraph/RangeMapping.ts b/src/DependencyGraph/RangeMapping.ts index f7492d08c4..01f4ea20d4 100644 --- a/src/DependencyGraph/RangeMapping.ts +++ b/src/DependencyGraph/RangeMapping.ts @@ -110,13 +110,13 @@ export class RangeMapping { } public moveAllRangesInSheetAfterRowByRows(sheet: number, row: number, numberOfRows: number): RangeVertex[] { - return this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex): Maybe => { + return this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex): Maybe<[boolean, RangeVertex]> => { if (row <= vertex.start.row) { vertex.range.shiftByRows(numberOfRows) - return vertex + return [false, vertex] } else if (row > vertex.start.row && row <= vertex.end.row) { vertex.range.expandByRows(numberOfRows) - return vertex + return [true, vertex] } else { return undefined } @@ -124,13 +124,13 @@ export class RangeMapping { } public moveAllRangesInSheetAfterColumnByColumns(sheet: number, column: number, numberOfColumns: number) { - this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex): Maybe => { + this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex): Maybe<[boolean, RangeVertex]> => { if (column <= vertex.start.col) { vertex.range.shiftByColumns(numberOfColumns) - return vertex + return [false, vertex] } else if (column > vertex.start.col && column <= vertex.end.col) { vertex.range.expandByColumns(numberOfColumns) - return vertex + return [true, vertex] } else { return undefined } @@ -138,12 +138,12 @@ export class RangeMapping { } public moveRangesInsideSourceRange(sourceRange: AbsoluteCellRange, toRight: number, toBottom: number, toSheet: number) { - this.updateVerticesFromSheet(sourceRange.sheet, (key: string, vertex: RangeVertex): Maybe => { + this.updateVerticesFromSheet(sourceRange.sheet, (key: string, vertex: RangeVertex): Maybe<[boolean, RangeVertex]> => { if (sourceRange.containsRange(vertex.range)) { vertex.range.shiftByColumns(toRight) vertex.range.shiftByRows(toBottom) vertex.range.moveToSheet(toSheet) - return vertex + return [false, vertex] } else { return undefined } @@ -219,8 +219,8 @@ export class RangeMapping { return this.rangeMapping.get(sheet)?.get(key) } - private updateVerticesFromSheet(sheet: number, fn: (key: string, vertex: RangeVertex) => Maybe): RangeVertex[] { - const updated = Array() + private updateVerticesFromSheet(sheet: number, fn: (key: string, vertex: RangeVertex) => Maybe<[boolean, RangeVertex]>): RangeVertex[] { + const updated = Array<[boolean, RangeVertex]>() for (const [key, vertex] of this.entriesFromSheet(sheet)) { const result = fn(key, vertex) @@ -230,11 +230,11 @@ export class RangeMapping { } } - updated.forEach((range) => { + updated.forEach(([_, range]) => { this.setRange(range) }) - return updated + return updated.filter(entry => entry[0]).map(entry => entry[1]) } } diff --git a/src/Operations.ts b/src/Operations.ts index 5a6111d55e..bcb812731b 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -541,9 +541,6 @@ export class Operations { } const affectedMatrices = this.dependencyGraph.addRows(addedRows) - for (const affectedMatrix of affectedMatrices) { - this.dependencyGraph.setMatrixEmpty(affectedMatrix) - } this.stats.measure(StatType.TRANSFORM_ASTS, () => { const transformation = new AddRowsTransformer(addedRows) diff --git a/test/graphComparator.ts b/test/graphComparator.ts index d48c3d0478..e83ffa9aa7 100644 --- a/test/graphComparator.ts +++ b/test/graphComparator.ts @@ -47,7 +47,7 @@ export class EngineComparator { const actualWidth = this.actual.addressMapping.getWidth(sheet) const actualHeight = this.actual.addressMapping.getHeight(sheet) - deepStrictEqual(this.actual.matrixMapping, this.expected.matrixMapping) + this.compareMatrixMappings() for (let x = 0; x < Math.max(expectedWidth, actualWidth); ++x) { for (let y = 0; y < Math.max(expectedHeight, actualHeight); ++y) { @@ -88,6 +88,20 @@ export class EngineComparator { } } + private compareMatrixMappings() { + const actual = this.actual.matrixMapping.matrixMapping + const expected = this.expected.matrixMapping.matrixMapping + + expect(actual.size).toEqual(expected.size) + + for (const [key, value] of expected.entries()) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const actualEntry = actual.get(key)! + expect(actualEntry).toBeDefined() + expect(value.getRange().sameAs(actualEntry.getRange())).toBe(true) + } + } + private getAddressOfVertex(engine: HyperFormula, vertex: Vertex): SimpleCellAddress | AbsoluteCellRange { if (vertex instanceof RangeVertex) { return vertex.range diff --git a/test/matrix-mapping.spec.ts b/test/matrix-mapping.spec.ts index 87eb4771be..c56f5bd43b 100644 --- a/test/matrix-mapping.spec.ts +++ b/test/matrix-mapping.spec.ts @@ -52,9 +52,9 @@ describe('MatrixMapping', () => { matrixMapping.moveMatrixVerticesAfterRowByRows(0, 0, 2) - expect(matrixMapping.getMatrix(range1)).toBeUndefined() - expect(matrixMapping.getMatrix(range2)).toBeUndefined() - expect(matrixMapping.getMatrix(AbsoluteCellRange.spanFrom(adr('B3'), 2, 2))).toEqual(vertex1) - expect(matrixMapping.getMatrix(AbsoluteCellRange.spanFrom(adr('D4'), 2, 2))).toEqual(vertex2) + expect(matrixMapping.getMatrixByCorner(range1.start)).toBeUndefined() + expect(matrixMapping.getMatrixByCorner(range2.start)).toBeUndefined() + expect(matrixMapping.getMatrixByCorner(adr('B3'))).toEqual(vertex1) + expect(matrixMapping.getMatrixByCorner(adr('D4'))).toEqual(vertex2) }) }) From 555983f634dbfcfa026e353bbe58608bd00f28c8 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 22 May 2021 10:27:10 +0200 Subject: [PATCH 16/87] Fix addres mapping for simple case of removing row --- src/CrudOperations.ts | 5 -- src/DependencyGraph/DependencyGraph.ts | 33 ++++++--- src/Operations.ts | 5 +- test/cruds/matrix-cruds.spec.ts | 94 +++++++++++++++++++++++++- 4 files changed, 122 insertions(+), 15 deletions(-) diff --git a/src/CrudOperations.ts b/src/CrudOperations.ts index 46fe71a87e..7e0844b0d6 100644 --- a/src/CrudOperations.ts +++ b/src/CrudOperations.ts @@ -467,15 +467,10 @@ export class CrudOperations { if (rowEnd < rowStart) { throw new InvalidArgumentsError('starting row to be smaller than the ending row.') } - const rowsToRemove = RowsSpan.fromRowStartAndEnd(sheet, rowStart, rowEnd) if (!this.sheetMapping.hasSheetWithId(sheet)) { throw new NoSheetWithIdError(sheet) } - - if (this.dependencyGraph.matrixMapping.isFormulaMatrixInRows(rowsToRemove)) { - throw new SourceLocationHasMatrixError() - } } } diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 4405870e64..9fa848b5b0 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -263,11 +263,7 @@ export class DependencyGraph { return vertex } - public removeRows(removedRows: RowsSpan) { - if (this.matrixMapping.isFormulaMatrixInRows(removedRows)) { - throw Error('It is not possible to remove row with matrix') - } - + public removeRows(removedRows: RowsSpan): Set { this.stats.measure(StatType.ADJUSTING_GRAPH, () => { for (const vertex of this.addressMapping.verticesFromRowsSpan(removedRows)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { @@ -284,11 +280,18 @@ export class DependencyGraph { this.addressMapping.removeRows(removedRows) }) - this.stats.measure(StatType.ADJUSTING_RANGES, () => { - this.truncateRanges(removedRows, address => address.row) + const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { + const affectedRanges = this.truncateRanges(removedRows, address => address.row) + return this.getRangeRelatedMatrixVertices(affectedRanges) + }) + + this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { + this.fixMatricesAfterRemovingRows(removedRows.sheet, removedRows.rowStart, removedRows.numberOfRows) }) this.addStructuralNodesToChangeSet() + + return affectedMatrices } public removeSheet(removedSheetId: number) { @@ -846,7 +849,7 @@ export class DependencyGraph { } } - private truncateRanges(span: Span, coordinate: (address: SimpleCellAddress) => number) { + private truncateRanges(span: Span, coordinate: (address: SimpleCellAddress) => number): RangeVertex[] { const {verticesToRemove, verticesToMerge} = this.rangeMapping.truncateRanges(span, coordinate) for (const [existingVertex, mergedVertex] of verticesToMerge) { this.mergeRangeVertices(existingVertex, mergedVertex) @@ -854,6 +857,7 @@ export class DependencyGraph { for (const rangeVertex of verticesToRemove) { this.removeVertexAndCleanupDependencies(rangeVertex) } + return [...verticesToRemove, ...verticesToMerge.map(v => v[1])] } private fixMatricesAfterAddingRow(sheet: number, rowStart: number, numberOfRows: number) { @@ -873,6 +877,19 @@ export class DependencyGraph { } } + private fixMatricesAfterRemovingRows(sheet: number, rowStart: number, numberOfRows: number) { + this.matrixMapping.moveMatrixVerticesAfterRowByRows(sheet, rowStart, -numberOfRows) + if (rowStart <= 0) { + return + } + for (const [, matrix] of this.matrixMapping.matricesInRows(RowsSpan.fromRowStartAndEnd(sheet, rowStart-1, rowStart-1))) { + const matrixRange = matrix.getRange() + for (const address of matrixRange.addresses(this)) { + this.addressMapping.setCell(address, matrix) + } + } + } + private removeVertex(vertex: Vertex) { this.removeVertexAndCleanupDependencies(vertex) if (vertex instanceof RangeVertex) { diff --git a/src/Operations.ts b/src/Operations.ts index bcb812731b..041dd0bfa0 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -481,7 +481,7 @@ export class Operations { removedCells.push({address, cellType: this.getClipboardCell(address)}) } - this.dependencyGraph.removeRows(rowsToRemove) + const affectedMatrices = this.dependencyGraph.removeRows(rowsToRemove) let version: number this.stats.measure(StatType.TRANSFORM_ASTS, () => { @@ -489,6 +489,9 @@ export class Operations { transformation.performEagerTransformations(this.dependencyGraph, this.parser) version = this.lazilyTransformingAstService.addTransformation(transformation) }) + + this.rewriteAffectedMatrices(affectedMatrices) + return {version: version!, removedCells, rowFrom: rowsToRemove.rowStart, rowCount: rowsToRemove.numberOfRows} } diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts index 9f6296a23d..eeefca8ee3 100644 --- a/test/cruds/matrix-cruds.spec.ts +++ b/test/cruds/matrix-cruds.spec.ts @@ -41,7 +41,7 @@ describe('Add rows', () => { ], { useArrayArithmetic: true })) }) - it('Adding row should expand dependent array', () => { + it('adding row should expand dependent array', () => { const engine = HyperFormula.buildFromArray([ [1, 2], [3, 4], @@ -57,4 +57,96 @@ describe('Add rows', () => { ['=TRANSPOSE(A1:B3)'] ], { useArrayArithmetic: true })) }) + + it('undo add row with dependent array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ['=TRANSPOSE(A1:B2)'] + ], { useArrayArithmetic: true }) + + engine.addRows(0, [1, 1]) + engine.undo() + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ['=TRANSPOSE(A1:B2)'] + ], { useArrayArithmetic: true })) + }) +}) + +describe('Remove rows', () => { + it('should be possible to remove row above matrix', () => { + const engine = HyperFormula.buildFromArray([ + [], + ['=-C2:D4'], + [], + [], + ['foo'] + ], {useArrayArithmetic: true}) + + engine.removeRows(0, [0, 1]) + + const expected = HyperFormula.buildFromArray([ + ['=-C1:D3'], + [], + [], + ['foo'] + ], {useArrayArithmetic: true}) + + expectEngineToBeTheSameAs(engine, expected) + }) + + it('removing row across array should not change array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], [3, 4], [5, 6], + ['=-A1:B3'], + [], [], [], + ['foo'] + ], { useArrayArithmetic: true }) + + engine.removeRows(0, [4, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], [3, 4], [5, 6], + ['=-A1:B3'], + [], [], + ['foo'] + ], { useArrayArithmetic: true })) + }) + + it('adding row should shrink dependent array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], + [], + [3, 4], + ['=TRANSPOSE(A1:B3)'] + ], { useArrayArithmetic: true }) + + engine.removeRows(0, [1, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ['=TRANSPOSE(A1:B2)'] + ], { useArrayArithmetic: true })) + }) + + it('it should be REF if no space after removing row', () => { + const engine = HyperFormula.buildFromArray([ + ['=-A3:A4'], + [], + [1], + [2], + ], { useArrayArithmetic: true }) + + engine.removeRows(0, [1, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['=#REF!'], + [1], + [2] + ], { useArrayArithmetic: true })) + }) }) From e68288ba0339c1c6fb78c4f13843f1911de2c8d6 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 22 May 2021 10:55:16 +0200 Subject: [PATCH 17/87] Make matrix REF if no space after removing row --- .../AddressMapping/AddressMapping.ts | 8 +++++- src/DependencyGraph/DependencyGraph.ts | 28 +++++++++++++++++-- src/DependencyGraph/FormulaCellVertex.ts | 5 ++++ src/error-message.ts | 1 + test/cruds/matrix-cruds.spec.ts | 10 +++++-- 5 files changed, 45 insertions(+), 7 deletions(-) diff --git a/src/DependencyGraph/AddressMapping/AddressMapping.ts b/src/DependencyGraph/AddressMapping/AddressMapping.ts index a6854375a8..b9a251b289 100644 --- a/src/DependencyGraph/AddressMapping/AddressMapping.ts +++ b/src/DependencyGraph/AddressMapping/AddressMapping.ts @@ -8,7 +8,7 @@ import {RawCellContent} from '../../CellContentParser' import {NoSheetWithIdError} from '../../errors' import {EmptyValue, InterpreterValue} from '../../interpreter/InterpreterValue' import {ColumnsSpan, RowsSpan} from '../../Span' -import {MatrixVertex, ValueCellVertex} from '../index' +import {MatrixVertex, ValueCellVertex, Vertex} from '../index' import {CellVertex} from '../Vertex' import {ChooseAddressMapping} from './ChooseAddressMappingPolicy' import {IAddressMappingStrategy} from './IAddressMappingStrategy' @@ -125,6 +125,12 @@ export class AddressMapping { sheetMapping.removeCell(address) } + public removeCellIfEqual(address: SimpleCellAddress, vertex: CellVertex) { + if (this.getCell(address) === vertex) { + this.removeCell(address) + } + } + /** @inheritDoc */ public has(address: SimpleCellAddress): boolean { const sheetMapping = this.mapping.get(address.sheet) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 9fa848b5b0..4e5304b688 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -425,6 +425,16 @@ export class DependencyGraph { } } + public isThereSpaceForMatrix(matrixVertex: MatrixVertex): boolean { + for (const address of matrixVertex.getRange().addresses(this)) { + const vertexUnderAddress = this.addressMapping.getCell(address) + if (vertexUnderAddress !== null && vertexUnderAddress !== matrixVertex) { + return false + } + } + return true + } + public moveCells(sourceRange: AbsoluteCellRange, toRight: number, toBottom: number, toSheet: number) { for (const sourceAddress of sourceRange.addressesWithDirection(toRight, toBottom, this)) { const targetAddress = simpleCellAddress(toSheet, sourceAddress.col + toRight, sourceAddress.row + toBottom) @@ -883,13 +893,25 @@ export class DependencyGraph { return } for (const [, matrix] of this.matrixMapping.matricesInRows(RowsSpan.fromRowStartAndEnd(sheet, rowStart-1, rowStart-1))) { - const matrixRange = matrix.getRange() - for (const address of matrixRange.addresses(this)) { - this.addressMapping.setCell(address, matrix) + if (this.isThereSpaceForMatrix(matrix)) { + for (const address of matrix.getRange().addresses(this)) { + this.addressMapping.setCell(address, matrix) + } + } else { + this.shrinkMatrixToCorner(matrix) } } } + private shrinkMatrixToCorner(matrixVertex: MatrixVertex) { + const matrixRange = matrixVertex.getRange() + for (const address of matrixRange.addresses(this)) { + this.addressMapping.removeCellIfEqual(address, matrixVertex) + } + this.addressMapping.setCell(matrixRange.start, matrixVertex) + matrixVertex.setNoSpace() + } + private removeVertex(vertex: Vertex) { this.removeVertexAndCleanupDependencies(vertex) if (vertex instanceof RangeVertex) { diff --git a/src/DependencyGraph/FormulaCellVertex.ts b/src/DependencyGraph/FormulaCellVertex.ts index 4f3c2a8354..9444e10eeb 100644 --- a/src/DependencyGraph/FormulaCellVertex.ts +++ b/src/DependencyGraph/FormulaCellVertex.ts @@ -13,6 +13,7 @@ import {MatrixSize} from '../MatrixSize' import {Maybe} from '../Maybe' import {Ast} from '../parser' import {ColumnsSpan, RowsSpan} from '../Span' +import {ErrorMessage} from '../error-message' export abstract class FormulaVertex { static fromAst(formula: Ast, address: SimpleCellAddress, size: MatrixSize, version: number) { @@ -151,6 +152,10 @@ export class MatrixVertex extends FormulaVertex { } } + setNoSpace() { + this.matrix = new ErroredMatrix(new CellError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult), MatrixSize.error()) + } + getRange(): AbsoluteCellRange { return AbsoluteCellRange.spanFrom(this.cellAddress, this.width, this.height) } diff --git a/src/error-message.ts b/src/error-message.ts index 87226b45b4..4a73946645 100644 --- a/src/error-message.ts +++ b/src/error-message.ts @@ -12,6 +12,7 @@ export class ErrorMessage { public static EmptyArg = 'Empty function argument.' public static EmptyArray = 'Empty array not allowed.' public static MatrixDimensions = 'Matrix dimensions are not compatible.' + public static NoSpaceForArrayResult = 'No space for array result.' public static ValueSmall = 'Value too small.' public static ValueLarge = 'Value too large.' public static BadCriterion = 'Incorrect criterion.' diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts index eeefca8ee3..497950f973 100644 --- a/test/cruds/matrix-cruds.spec.ts +++ b/test/cruds/matrix-cruds.spec.ts @@ -1,5 +1,6 @@ -import {HyperFormula} from '../../src' -import {expectEngineToBeTheSameAs} from '../testUtils' +import {ErrorType, HyperFormula} from '../../src' +import {adr, detailedError, expectEngineToBeTheSameAs} from '../testUtils' +import {ErrorMessage} from '../../src/error-message' describe('Add rows', () => { it('should be possible to add row above matrix', () => { @@ -143,8 +144,11 @@ describe('Remove rows', () => { engine.removeRows(0, [1, 1]) + expect(engine.getCellValue(adr('A1'))).toEqual(detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult)) + expect(engine.getCellValue(adr('A2'))).toEqual(1) + expect(engine.getCellValue(adr('A3'))).toEqual(2) expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - ['=#REF!'], + ['=-A2:A3'], [1], [2] ], { useArrayArithmetic: true })) From ea1690e1dc939b4bd5e0ba1dcb9f8233e5062050 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 22 May 2021 12:16:20 +0200 Subject: [PATCH 18/87] Tidy up --- src/DependencyGraph/DependencyGraph.ts | 3 +- src/DependencyGraph/RangeMapping.ts | 70 +++++++++++++++++++------- test/cruds/matrix-cruds.spec.ts | 2 +- 3 files changed, 54 insertions(+), 21 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 4e5304b688..8d980b14bf 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -385,10 +385,9 @@ export class DependencyGraph { const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { const result = this.rangeMapping.moveAllRangesInSheetAfterRowByRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) this.fixRangesWhenAddingRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) - return this.getRangeRelatedMatrixVertices(result) + return this.getRangeRelatedMatrixVertices(result.verticesWithChangedSize) }) - this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { this.fixMatricesAfterAddingRow(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) }) diff --git a/src/DependencyGraph/RangeMapping.ts b/src/DependencyGraph/RangeMapping.ts index 01f4ea20d4..323332c683 100644 --- a/src/DependencyGraph/RangeMapping.ts +++ b/src/DependencyGraph/RangeMapping.ts @@ -9,6 +9,16 @@ import {Maybe} from '../Maybe' import {Span} from '../Span' import {RangeVertex} from './' +export interface AdjustRangesResult { + verticesWithChangedSize: RangeVertex[], +} + +export interface TruncateRangesResult extends AdjustRangesResult { + verticesToRemove: RangeVertex[], + verticesToMerge: [RangeVertex, RangeVertex][], + verticesWithChangedSize: RangeVertex[], +} + /** * Mapping from address ranges to range vertices */ @@ -71,6 +81,7 @@ export class RangeMapping { public truncateRanges(span: Span, coordinate: (address: SimpleCellAddress) => number): TruncateRangesResult { const verticesToRemove = Array() const updated = Array<[string, RangeVertex]>() + const verticesWithChangedSize = Array() const sheet = span.sheet for (const [key, vertex] of this.entriesFromSheet(span.sheet)) { @@ -83,6 +94,7 @@ export class RangeMapping { } else { updated.push([key, vertex]) } + verticesWithChangedSize.push(vertex) } } @@ -105,18 +117,25 @@ export class RangeMapping { return { verticesToRemove, - verticesToMerge + verticesToMerge, + verticesWithChangedSize } } - public moveAllRangesInSheetAfterRowByRows(sheet: number, row: number, numberOfRows: number): RangeVertex[] { - return this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex): Maybe<[boolean, RangeVertex]> => { + public moveAllRangesInSheetAfterRowByRows(sheet: number, row: number, numberOfRows: number): AdjustRangesResult { + return this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex) => { if (row <= vertex.start.row) { vertex.range.shiftByRows(numberOfRows) - return [false, vertex] + return { + changedSize: false, + vertex: vertex + } } else if (row > vertex.start.row && row <= vertex.end.row) { vertex.range.expandByRows(numberOfRows) - return [true, vertex] + return { + changedSize: true, + vertex: vertex + } } else { return undefined } @@ -124,13 +143,19 @@ export class RangeMapping { } public moveAllRangesInSheetAfterColumnByColumns(sheet: number, column: number, numberOfColumns: number) { - this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex): Maybe<[boolean, RangeVertex]> => { + this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex) => { if (column <= vertex.start.col) { vertex.range.shiftByColumns(numberOfColumns) - return [false, vertex] + return { + changedSize: false, + vertex: vertex + } } else if (column > vertex.start.col && column <= vertex.end.col) { vertex.range.expandByColumns(numberOfColumns) - return [true, vertex] + return { + changedSize: true, + vertex: vertex + } } else { return undefined } @@ -138,12 +163,15 @@ export class RangeMapping { } public moveRangesInsideSourceRange(sourceRange: AbsoluteCellRange, toRight: number, toBottom: number, toSheet: number) { - this.updateVerticesFromSheet(sourceRange.sheet, (key: string, vertex: RangeVertex): Maybe<[boolean, RangeVertex]> => { + this.updateVerticesFromSheet(sourceRange.sheet, (key: string, vertex: RangeVertex) => { if (sourceRange.containsRange(vertex.range)) { vertex.range.shiftByColumns(toRight) vertex.range.shiftByRows(toBottom) vertex.range.moveToSheet(toSheet) - return [false, vertex] + return { + changedSize: false, + vertex: vertex + } } else { return undefined } @@ -219,8 +247,8 @@ export class RangeMapping { return this.rangeMapping.get(sheet)?.get(key) } - private updateVerticesFromSheet(sheet: number, fn: (key: string, vertex: RangeVertex) => Maybe<[boolean, RangeVertex]>): RangeVertex[] { - const updated = Array<[boolean, RangeVertex]>() + private updateVerticesFromSheet(sheet: number, fn: AdjustVerticesOperation): AdjustRangesResult { + const updated = Array() for (const [key, vertex] of this.entriesFromSheet(sheet)) { const result = fn(key, vertex) @@ -230,19 +258,25 @@ export class RangeMapping { } } - updated.forEach(([_, range]) => { - this.setRange(range) + updated.forEach(entry => { + this.setRange(entry.vertex) }) - return updated.filter(entry => entry[0]).map(entry => entry[1]) + return { + verticesWithChangedSize: updated + .filter(entry => entry.changedSize) + .map(entry => entry.vertex) + } } } -export interface TruncateRangesResult { - verticesToRemove: RangeVertex[], - verticesToMerge: [RangeVertex, RangeVertex][], +type AdjustVeticesOperationResult = { + changedSize: boolean, + vertex: RangeVertex, } +type AdjustVerticesOperation = (key: string, vertex: RangeVertex) => Maybe + function keyFromAddresses(start: SimpleCellAddress, end: SimpleCellAddress): string { return `${start.col},${start.row},${end.col},${end.row}` } diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts index 497950f973..8471a10dba 100644 --- a/test/cruds/matrix-cruds.spec.ts +++ b/test/cruds/matrix-cruds.spec.ts @@ -117,7 +117,7 @@ describe('Remove rows', () => { ], { useArrayArithmetic: true })) }) - it('adding row should shrink dependent array', () => { + it('removing row should shrink dependent array', () => { const engine = HyperFormula.buildFromArray([ [1, 2], [], From c541d737519509d887cc9de677b71e7ce053edd5 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 22 May 2021 12:32:16 +0200 Subject: [PATCH 19/87] Shrink matrix before swap --- src/DependencyGraph/DependencyGraph.ts | 9 ++++++--- src/Operations.ts | 1 + 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 8d980b14bf..c73d7d43ba 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -836,6 +836,9 @@ export class DependencyGraph { if (vertex instanceof MatrixVertex) { this.setMatrix(range, vertex) } + if (oldNode instanceof MatrixVertex) { + this.shrinkMatrixToCorner(oldNode) + } this.exchangeOrAddGraphNode(oldNode, vertex) for (const address of range.addresses(this)) { @@ -859,14 +862,14 @@ export class DependencyGraph { } private truncateRanges(span: Span, coordinate: (address: SimpleCellAddress) => number): RangeVertex[] { - const {verticesToRemove, verticesToMerge} = this.rangeMapping.truncateRanges(span, coordinate) + const {verticesToRemove, verticesToMerge, verticesWithChangedSize} = this.rangeMapping.truncateRanges(span, coordinate) for (const [existingVertex, mergedVertex] of verticesToMerge) { this.mergeRangeVertices(existingVertex, mergedVertex) } for (const rangeVertex of verticesToRemove) { this.removeVertexAndCleanupDependencies(rangeVertex) } - return [...verticesToRemove, ...verticesToMerge.map(v => v[1])] + return verticesWithChangedSize } private fixMatricesAfterAddingRow(sheet: number, rowStart: number, numberOfRows: number) { @@ -898,6 +901,7 @@ export class DependencyGraph { } } else { this.shrinkMatrixToCorner(matrix) + matrix.setNoSpace() } } } @@ -908,7 +912,6 @@ export class DependencyGraph { this.addressMapping.removeCellIfEqual(address, matrixVertex) } this.addressMapping.setCell(matrixRange.start, matrixVertex) - matrixVertex.setNoSpace() } private removeVertex(vertex: Vertex) { diff --git a/src/Operations.ts b/src/Operations.ts index 041dd0bfa0..1e31f25dda 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -522,6 +522,7 @@ export class Operations { transformation.performEagerTransformations(this.dependencyGraph, this.parser) version = this.lazilyTransformingAstService.addTransformation(transformation) }) + return { version: version!, removedCells, From b5a5445adc1e202f6597cc5bc768f1cc67499004 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 22 May 2021 12:48:59 +0200 Subject: [PATCH 20/87] Fix gathering matrices related to ranges --- src/DependencyGraph/DependencyGraph.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index c73d7d43ba..fa92df5218 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -282,7 +282,7 @@ export class DependencyGraph { const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { const affectedRanges = this.truncateRanges(removedRows, address => address.row) - return this.getRangeRelatedMatrixVertices(affectedRanges) + return this.getMatrixVerticesRelatedToRanges(affectedRanges) }) this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { @@ -385,7 +385,7 @@ export class DependencyGraph { const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { const result = this.rangeMapping.moveAllRangesInSheetAfterRowByRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) this.fixRangesWhenAddingRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) - return this.getRangeRelatedMatrixVertices(result.verticesWithChangedSize) + return this.getMatrixVerticesRelatedToRanges(result.verticesWithChangedSize) }) this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { @@ -631,10 +631,15 @@ export class DependencyGraph { this.matrixMapping.destroy() } - public getRangeRelatedMatrixVertices(ranges: RangeVertex[]): Set { - const reduced = ranges - .map(range => Array.from(this.graph.adjacentNodes(range)).filter(node => node instanceof MatrixVertex)) as MatrixVertex[][] - return new Set(...reduced) + public getMatrixVerticesRelatedToRanges(ranges: RangeVertex[]): Set { + const matrixVertices = ranges.map(range => { + if (this.graph.hasNode(range)) { + return Array.from(this.graph.adjacentNodes(range)).filter(node => node instanceof MatrixVertex) + } else { + return [] + } + }) as MatrixVertex[][] + return new Set(...matrixVertices) } public* verticesFromRange(range: AbsoluteCellRange): IterableIterator { From a3b480dd68765d122414075e8954992ea349e75c Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 23 May 2021 10:36:06 +0200 Subject: [PATCH 21/87] Basic tests for removing rows works --- src/DependencyGraph/DependencyGraph.ts | 1 + src/DependencyGraph/FormulaCellVertex.ts | 9 +++++++-- src/Evaluator.ts | 16 +++++++++++++--- src/MatrixSize.ts | 4 ++-- src/Operations.ts | 3 +++ test/cruds/matrix-cruds.spec.ts | 22 +++++++++++++--------- 6 files changed, 39 insertions(+), 16 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index fa92df5218..0a22309eec 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -844,6 +844,7 @@ export class DependencyGraph { if (oldNode instanceof MatrixVertex) { this.shrinkMatrixToCorner(oldNode) } + this.exchangeOrAddGraphNode(oldNode, vertex) for (const address of range.addresses(this)) { diff --git a/src/DependencyGraph/FormulaCellVertex.ts b/src/DependencyGraph/FormulaCellVertex.ts index 9444e10eeb..e6d2135fc4 100644 --- a/src/DependencyGraph/FormulaCellVertex.ts +++ b/src/DependencyGraph/FormulaCellVertex.ts @@ -84,7 +84,11 @@ export class MatrixVertex extends FormulaVertex { constructor(formula: Ast, cellAddress: SimpleCellAddress, size: MatrixSize, version: number = 0) { super(formula, cellAddress, version) - this.matrix = new NotComputedMatrix(size) + if (size.isRef) { + this.matrix = new ErroredMatrix(new CellError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult), MatrixSize.error()) + } else { + this.matrix = new NotComputedMatrix(size) + } } get width(): number { @@ -152,8 +156,9 @@ export class MatrixVertex extends FormulaVertex { } } - setNoSpace() { + setNoSpace(): InterpreterValue { this.matrix = new ErroredMatrix(new CellError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult), MatrixSize.error()) + return this.getCellValue() } getRange(): AbsoluteCellRange { diff --git a/src/Evaluator.ts b/src/Evaluator.ts index 0777fa408b..38fa9a297b 100644 --- a/src/Evaluator.ts +++ b/src/Evaluator.ts @@ -9,7 +9,7 @@ import {CellError, ErrorType, SimpleCellAddress} from './Cell' import {Config} from './Config' import {ContentChanges} from './ContentChanges' import {DateTimeHelper} from './DateTimeHelper' -import {DependencyGraph, RangeVertex, Vertex} from './DependencyGraph' +import {DependencyGraph, MatrixVertex, RangeVertex, Vertex} from './DependencyGraph' import {FormulaVertex} from './DependencyGraph/FormulaCellVertex' import {FunctionRegistry} from './interpreter/FunctionRegistry' import {Interpreter} from './interpreter/Interpreter' @@ -64,7 +64,12 @@ export class Evaluator { const formula = vertex.getFormula(this.dependencyGraph.lazilyTransformingAstService) const currentValue = vertex.isComputed() ? vertex.getCellValue() : null const newCellValue = this.evaluateAstToCellValue(formula, new InterpreterState(address, this.config.useArrayArithmetic)) - const setValue = vertex.setCellValue(newCellValue) + let setValue + if (vertex instanceof MatrixVertex && !this.dependencyGraph.isThereSpaceForMatrix(vertex)) { + setValue = vertex.setNoSpace() + } else { + setValue = vertex.setCellValue(newCellValue) + } if (newCellValue !== currentValue) { changes.addChange(newCellValue, address) this.columnSearch.change(getRawValue(currentValue), getRawValue(setValue), address) @@ -133,7 +138,12 @@ export class Evaluator { const address = vertex.getAddress(this.lazilyTransformingAstService) const formula = vertex.getFormula(this.lazilyTransformingAstService) const newCellValue = this.evaluateAstToCellValue(formula, new InterpreterState(address, this.config.useArrayArithmetic)) - const setValue = vertex.setCellValue(newCellValue) + let setValue + if (vertex instanceof MatrixVertex && !this.dependencyGraph.isThereSpaceForMatrix(vertex)) { + setValue = vertex.setNoSpace() + } else { + setValue = vertex.setCellValue(newCellValue) + } this.columnSearch.add(getRawValue(setValue), address) } else if (vertex instanceof RangeVertex) { vertex.clearCache() diff --git a/src/MatrixSize.ts b/src/MatrixSize.ts index cde19ea675..de92d13bbe 100644 --- a/src/MatrixSize.ts +++ b/src/MatrixSize.ts @@ -29,14 +29,14 @@ export class MatrixSize { constructor( public width: number, public height: number, - public isRef?: boolean, + public isRef: boolean = false, ) { if (width <= 0 || height <= 0) { throw Error('Incorrect matrix size') } } - isScalar() { + isScalar(): boolean { return (this.width<=1 && this.height<=1) || this.isRef } } diff --git a/src/Operations.ts b/src/Operations.ts index 1e31f25dda..c611552db8 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -557,6 +557,9 @@ export class Operations { private rewriteAffectedMatrices(affectedMatrices: Set) { for (const matrixVertex of affectedMatrices.values()) { + if (matrixVertex.matrix.size.isRef) { + continue + } const ast = matrixVertex.getFormula(this.lazilyTransformingAstService) const address = matrixVertex.getAddress(this.lazilyTransformingAstService) const hash = this.parser.computeHashFromAst(ast) diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts index 8471a10dba..f9f098eb9b 100644 --- a/test/cruds/matrix-cruds.spec.ts +++ b/test/cruds/matrix-cruds.spec.ts @@ -136,21 +136,25 @@ describe('Remove rows', () => { it('it should be REF if no space after removing row', () => { const engine = HyperFormula.buildFromArray([ - ['=-A3:A4'], + ['=-B3:B4'], [], - [1], - [2], + [1, 1], + [null, 2], ], { useArrayArithmetic: true }) engine.removeRows(0, [1, 1]) expect(engine.getCellValue(adr('A1'))).toEqual(detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult)) expect(engine.getCellValue(adr('A2'))).toEqual(1) - expect(engine.getCellValue(adr('A3'))).toEqual(2) - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - ['=-A2:A3'], - [1], - [2] - ], { useArrayArithmetic: true })) + expect(engine.getCellValue(adr('B2'))).toEqual(1) + expect(engine.getCellValue(adr('B3'))).toEqual(2) + + const expected = HyperFormula.buildFromArray([ + ['=-B2:B3'], + [1, 1], + [null, 2] + ], { useArrayArithmetic: true }) + expectEngineToBeTheSameAs(engine, expected) }) }) + From 35212d9130ddbc712ec05ff7e4347a1556b8fa1c Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 23 May 2021 22:46:10 +0200 Subject: [PATCH 22/87] Test with potential CYCLE --- test/cruds/matrix-cruds.spec.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts index f9f098eb9b..6be9ad65be 100644 --- a/test/cruds/matrix-cruds.spec.ts +++ b/test/cruds/matrix-cruds.spec.ts @@ -156,5 +156,27 @@ describe('Remove rows', () => { ], { useArrayArithmetic: true }) expectEngineToBeTheSameAs(engine, expected) }) + + it('it should be REF, not CYCLE, after removing rows', () => { + const engine = HyperFormula.buildFromArray([ + ['=-A3:A4'], + [], + [1], + [2] + ], { useArrayArithmetic: true }) + + engine.removeRows(0, [1, 1]) + + expect(engine.getCellValue(adr('A1'))).toEqual(detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult)) + expect(engine.getCellValue(adr('A2'))).toEqual(1) + expect(engine.getCellValue(adr('A3'))).toEqual(2) + + const expected = HyperFormula.buildFromArray([ + ['=-A2:A3'], + [1], + [2] + ], { useArrayArithmetic: true }) + expectEngineToBeTheSameAs(engine, expected) + }) }) From 0a4455b1be3bc3bfdc03beac654700aa639f87f3 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 23 May 2021 22:55:09 +0200 Subject: [PATCH 23/87] Simplify condition by making use of MatrixSize function --- src/GraphBuilder.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GraphBuilder.ts b/src/GraphBuilder.ts index 4661c8df66..6785d54da1 100644 --- a/src/GraphBuilder.ts +++ b/src/GraphBuilder.ts @@ -97,7 +97,7 @@ export class SimpleStrategy implements GraphBuilderStrategy { this.dependencyGraph.addVertex(address, vertex) } else { const size = this.matrixSizePredictor.checkMatrixSize(parseResult.ast, address) - if(size === undefined || (size.width<=1 && size.height<=1) || size.isRef) { + if (size.isScalar()) { const vertex = new FormulaCellVertex(parseResult.ast, address, 0) dependencies.set(vertex, absolutizeDependencies(parseResult.dependencies, address)) this.dependencyGraph.addVertex(address, vertex) From cdad5c2d3920a377d9627418c3a8864a7bf9b483 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 23 May 2021 23:09:58 +0200 Subject: [PATCH 24/87] Reuse and simplify --- src/Evaluator.ts | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/src/Evaluator.ts b/src/Evaluator.ts index 38fa9a297b..bf4a94fa5e 100644 --- a/src/Evaluator.ts +++ b/src/Evaluator.ts @@ -23,6 +23,7 @@ import {NumberLiteralHelper} from './NumberLiteralHelper' import {Ast, RelativeDependency} from './parser' import {Serialization} from './Serialization' import {Statistics, StatType} from './statistics' +import {CellContent} from './CellContentParser' export class Evaluator { private interpreter: Interpreter @@ -60,19 +61,12 @@ export class Evaluator { this.dependencyGraph.graph.getTopSortedWithSccSubgraphFrom(vertices, (vertex: Vertex) => { if (vertex instanceof FormulaVertex) { - const address = vertex.getAddress(this.dependencyGraph.lazilyTransformingAstService) - const formula = vertex.getFormula(this.dependencyGraph.lazilyTransformingAstService) const currentValue = vertex.isComputed() ? vertex.getCellValue() : null - const newCellValue = this.evaluateAstToCellValue(formula, new InterpreterState(address, this.config.useArrayArithmetic)) - let setValue - if (vertex instanceof MatrixVertex && !this.dependencyGraph.isThereSpaceForMatrix(vertex)) { - setValue = vertex.setNoSpace() - } else { - setValue = vertex.setCellValue(newCellValue) - } + const newCellValue = this.recomputeFormulaVertexValue(vertex) if (newCellValue !== currentValue) { + const address = vertex.getAddress(this.lazilyTransformingAstService) changes.addChange(newCellValue, address) - this.columnSearch.change(getRawValue(currentValue), getRawValue(setValue), address) + this.columnSearch.change(getRawValue(currentValue), getRawValue(newCellValue), address) return true } return false @@ -87,7 +81,7 @@ export class Evaluator { if (vertex instanceof RangeVertex) { vertex.clearCache() } else if (vertex instanceof FormulaVertex) { - const address = vertex.getAddress(this.dependencyGraph.lazilyTransformingAstService) + const address = vertex.getAddress(this.lazilyTransformingAstService) this.columnSearch.remove(getRawValue(vertex.valueOrNull()), address) const error = new CellError(ErrorType.CYCLE, undefined, address) vertex.setCellValue(error) @@ -135,22 +129,26 @@ export class Evaluator { }) sorted.forEach((vertex: Vertex) => { if (vertex instanceof FormulaVertex) { + const newCellValue = this.recomputeFormulaVertexValue(vertex) const address = vertex.getAddress(this.lazilyTransformingAstService) - const formula = vertex.getFormula(this.lazilyTransformingAstService) - const newCellValue = this.evaluateAstToCellValue(formula, new InterpreterState(address, this.config.useArrayArithmetic)) - let setValue - if (vertex instanceof MatrixVertex && !this.dependencyGraph.isThereSpaceForMatrix(vertex)) { - setValue = vertex.setNoSpace() - } else { - setValue = vertex.setCellValue(newCellValue) - } - this.columnSearch.add(getRawValue(setValue), address) + this.columnSearch.add(getRawValue(newCellValue), address) } else if (vertex instanceof RangeVertex) { vertex.clearCache() } }) } + private recomputeFormulaVertexValue(vertex: FormulaVertex): InterpreterValue { + if (vertex instanceof MatrixVertex && !this.dependencyGraph.isThereSpaceForMatrix(vertex)) { + return vertex.setNoSpace() + } else { + const address = vertex.getAddress(this.lazilyTransformingAstService) + const formula = vertex.getFormula(this.lazilyTransformingAstService) + const newCellValue = this.evaluateAstToCellValue(formula, new InterpreterState(address, this.config.useArrayArithmetic)) + return vertex.setCellValue(newCellValue) + } + } + private evaluateAstToCellValue(ast: Ast, state: InterpreterState): InterpreterValue { const interpreterValue = this.interpreter.evaluateAst(ast, state) if (interpreterValue instanceof SimpleRangeValue) { From 48a88cae7e6c3dd3eb840744c2eb2bed3e7d1ff0 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 23 May 2021 23:50:07 +0200 Subject: [PATCH 25/87] Basic cases for setCellContent --- src/DependencyGraph/DependencyGraph.ts | 15 ++++++++----- src/Evaluator.ts | 2 +- test/cruds/matrix-cruds.spec.ts | 31 ++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 0a22309eec..ffbba2e9c1 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -835,20 +835,25 @@ export class DependencyGraph { } private exchangeOrAddFormulaVertex(vertex: FormulaVertex): void { - const range = AbsoluteCellRange.spanFrom(vertex.getAddress(this.lazilyTransformingAstService), vertex.width, vertex.height) + const address = vertex.getAddress(this.lazilyTransformingAstService) + const range = AbsoluteCellRange.spanFrom(address, vertex.width, vertex.height) + const oldNode = this.getCell(address) - const oldNode = this.getCell(range.start) if (vertex instanceof MatrixVertex) { this.setMatrix(range, vertex) } if (oldNode instanceof MatrixVertex) { this.shrinkMatrixToCorner(oldNode) } - this.exchangeOrAddGraphNode(oldNode, vertex) + this.addressMapping.setCell(address, vertex) - for (const address of range.addresses(this)) { - this.addressMapping.setCell(address, vertex) + if (vertex instanceof MatrixVertex && !this.isThereSpaceForMatrix(vertex)) { + return + } + + for (const cellAddress of range.addresses(this)) { + this.addressMapping.setCell(cellAddress, vertex) } } diff --git a/src/Evaluator.ts b/src/Evaluator.ts index bf4a94fa5e..0c3c12f680 100644 --- a/src/Evaluator.ts +++ b/src/Evaluator.ts @@ -139,10 +139,10 @@ export class Evaluator { } private recomputeFormulaVertexValue(vertex: FormulaVertex): InterpreterValue { + const address = vertex.getAddress(this.lazilyTransformingAstService) if (vertex instanceof MatrixVertex && !this.dependencyGraph.isThereSpaceForMatrix(vertex)) { return vertex.setNoSpace() } else { - const address = vertex.getAddress(this.lazilyTransformingAstService) const formula = vertex.getFormula(this.lazilyTransformingAstService) const newCellValue = this.evaluateAstToCellValue(formula, new InterpreterState(address, this.config.useArrayArithmetic)) return vertex.setCellValue(newCellValue) diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts index 6be9ad65be..e3e4605f79 100644 --- a/test/cruds/matrix-cruds.spec.ts +++ b/test/cruds/matrix-cruds.spec.ts @@ -180,3 +180,34 @@ describe('Remove rows', () => { }) }) +describe('Set cell content', () => { + it('should be REF matrix if no space for result', () => { + const engine = HyperFormula.buildFromArray([ + [], + [1], + ], { useArrayArithmetic: true }) + + engine.setCellContents(adr('A1'), [['=-B2:B3']]) + + expect(engine.getCellValue(adr('A1'))).toEqual(detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult)) + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['=-B2:B3'], + [1], + ], { useArrayArithmetic: true })) + }) + + it('should be REF matrix if no space and potential cycle', () => { + const engine = HyperFormula.buildFromArray([ + [], + [1], + ], { useArrayArithmetic: true }) + + engine.setCellContents(adr('A1'), [['=-A2:A3']]) + + expect(engine.getCellValue(adr('A1'))).toEqual(detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult)) + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['=-A2:A3'], + [1], + ], { useArrayArithmetic: true })) + }) +}) From edf3ffcd4917a524ea0b7d241c33872515e9c293 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Mon, 24 May 2021 10:53:51 +0200 Subject: [PATCH 26/87] Set no space if writing over matrix --- src/DependencyGraph/DependencyGraph.ts | 30 +++++++++++++---------- src/Operations.ts | 34 ++++++++++++-------------- test/cruds/matrix-cruds.spec.ts | 33 ++++++++++++++++++++++++- 3 files changed, 64 insertions(+), 33 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index ffbba2e9c1..2ff7bb48ec 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -101,7 +101,7 @@ export class DependencyGraph { public setParsingErrorToCell(address: SimpleCellAddress, errorVertex: ParsingErrorVertex) { const vertex = this.addressMapping.getCell(address) - this.ensureThatVertexIsNonMatrixCellVertex(vertex) + this.setNoSpaceIfMatrix(vertex) this.exchangeOrAddGraphNode(vertex, errorVertex) this.addressMapping.setCell(address, errorVertex) this.graph.markNodeAsSpecialRecentlyChanged(errorVertex) @@ -110,7 +110,7 @@ export class DependencyGraph { public setValueToCell(address: SimpleCellAddress, value: RawAndParsedValue) { const vertex = this.addressMapping.getCell(address) - this.ensureThatVertexIsNonMatrixCellVertex(vertex) + this.setNoSpaceIfMatrix(vertex) if (vertex instanceof ValueCellVertex) { const oldValue = vertex.getValues() @@ -130,10 +130,10 @@ export class DependencyGraph { public setCellEmpty(address: SimpleCellAddress) { const vertex = this.addressMapping.getCell(address) + this.setNoSpaceIfMatrix(vertex) if (vertex === null) { return } - this.ensureThatVertexIsNonMatrixCellVertex(vertex) if (this.graph.adjacentNodes(vertex).size > 0) { const emptyVertex = new EmptyCellVertex(address) @@ -842,9 +842,7 @@ export class DependencyGraph { if (vertex instanceof MatrixVertex) { this.setMatrix(range, vertex) } - if (oldNode instanceof MatrixVertex) { - this.shrinkMatrixToCorner(oldNode) - } + this.setNoSpaceIfMatrix(oldNode) this.exchangeOrAddGraphNode(oldNode, vertex) this.addressMapping.setCell(address, vertex) @@ -911,18 +909,24 @@ export class DependencyGraph { this.addressMapping.setCell(address, matrix) } } else { - this.shrinkMatrixToCorner(matrix) - matrix.setNoSpace() + this.setNoSpaceIfMatrix(matrix) } } } - private shrinkMatrixToCorner(matrixVertex: MatrixVertex) { - const matrixRange = matrixVertex.getRange() - for (const address of matrixRange.addresses(this)) { - this.addressMapping.removeCellIfEqual(address, matrixVertex) + private setNoSpaceIfMatrix(vertex: Vertex | null) { + if (vertex instanceof MatrixVertex) { + this.shrinkMatrixToCorner(vertex) + vertex.setNoSpace() } - this.addressMapping.setCell(matrixRange.start, matrixVertex) + } + + private shrinkMatrixToCorner(vertex: MatrixVertex) { + const matrixRange = vertex.getRange() + for (const address of matrixRange.addresses(this)) { + this.addressMapping.removeCellIfEqual(address, vertex) + } + this.addressMapping.setCell(matrixRange.start, vertex) } private removeVertex(vertex: Vertex) { diff --git a/src/Operations.ts b/src/Operations.ts index c611552db8..79bb7fbd33 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -644,28 +644,24 @@ export class Operations { const vertex = this.dependencyGraph.getCell(address) - if (!(vertex instanceof MatrixVertex)) { - if (parsedCellContent instanceof CellContent.Formula) { - const { - ast, - errors, - hasVolatileFunction, - hasStructuralChangeFunction, - dependencies - } = this.parser.parse(parsedCellContent.formula, address) - if (errors.length > 0) { - this.dependencyGraph.setParsingErrorToCell(address, new ParsingErrorVertex(errors, parsedCellContent.formula)) - } else { - const size = this.matrixSizePredictor.checkMatrixSize(ast, address) - this.dependencyGraph.setFormulaToCell(address, ast, absolutizeDependencies(dependencies, address), size, hasVolatileFunction, hasStructuralChangeFunction) - } - } else if (parsedCellContent instanceof CellContent.Empty) { - this.setCellEmpty(address) + if (parsedCellContent instanceof CellContent.Formula) { + const { + ast, + errors, + hasVolatileFunction, + hasStructuralChangeFunction, + dependencies + } = this.parser.parse(parsedCellContent.formula, address) + if (errors.length > 0) { + this.dependencyGraph.setParsingErrorToCell(address, new ParsingErrorVertex(errors, parsedCellContent.formula)) } else { - this.setValueToCell({parsedValue: parsedCellContent.value, rawValue: newCellContent}, address) + const size = this.matrixSizePredictor.checkMatrixSize(ast, address) + this.dependencyGraph.setFormulaToCell(address, ast, absolutizeDependencies(dependencies, address), size, hasVolatileFunction, hasStructuralChangeFunction) } + } else if (parsedCellContent instanceof CellContent.Empty) { + this.setCellEmpty(address) } else { - throw new Error('Illegal operation') + this.setValueToCell({parsedValue: parsedCellContent.value, rawValue: newCellContent}, address) } } diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts index e3e4605f79..3e02d18807 100644 --- a/test/cruds/matrix-cruds.spec.ts +++ b/test/cruds/matrix-cruds.spec.ts @@ -1,6 +1,8 @@ import {ErrorType, HyperFormula} from '../../src' import {adr, detailedError, expectEngineToBeTheSameAs} from '../testUtils' import {ErrorMessage} from '../../src/error-message' +import {MatrixVertex, ValueCellVertex} from '../../src/DependencyGraph' +import {MatrixSize} from '../../src/MatrixSize' describe('Add rows', () => { it('should be possible to add row above matrix', () => { @@ -23,7 +25,7 @@ describe('Add rows', () => { expectEngineToBeTheSameAs(engine, expected) }) - + it('adding row across array should not change array', () => { const engine = HyperFormula.buildFromArray([ [], [], [], @@ -181,6 +183,20 @@ describe('Remove rows', () => { }) describe('Set cell content', () => { + it('should set matrix to cell', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ], { useArrayArithmetic: true}) + + engine.setCellContents(adr('C1'), [['=-A1:B2']]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2, '=-A1:B2'], + [3, 4], + ], { useArrayArithmetic: true})) + }) + it('should be REF matrix if no space for result', () => { const engine = HyperFormula.buildFromArray([ [], @@ -210,4 +226,19 @@ describe('Set cell content', () => { [1], ], { useArrayArithmetic: true })) }) + + it('should shrink to one vertex if there is more content colliding with matrix', () => { + const engine = HyperFormula.buildFromArray([], { useArrayArithmetic: true}) + + engine.setCellContents(adr('A1'), [ + ['=-C1:D2', null], + [1, null] + ]) + + expect(engine.matrixMapping.getMatrixByCorner(adr('A1'))?.matrix.size).toEqual(MatrixSize.error()) + expect(engine.addressMapping.getCell(adr('A1'))).toBeInstanceOf(MatrixVertex) + expect(engine.addressMapping.getCell(adr('B1'))).toBe(null) + expect(engine.addressMapping.getCell(adr('A2'))).toBeInstanceOf(ValueCellVertex) + expect(engine.addressMapping.getCell(adr('B2'))).toBe(null) + }) }) From 6c164a54d11fbae62fe2182e495999ac019e9282 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 28 May 2021 09:59:31 +0200 Subject: [PATCH 27/87] Shrink matrix during building graph if needed --- src/DependencyGraph/DependencyGraph.ts | 22 ++- src/GraphBuilder.ts | 14 +- test/cruds/matrix-cruds.spec.ts | 230 +++++++++++++++++++++---- test/interpreter/matrix-plugin.spec.ts | 4 +- test/testUtils.ts | 23 ++- 5 files changed, 242 insertions(+), 51 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 2ff7bb48ec..6b69d48748 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -518,7 +518,7 @@ export class DependencyGraph { this.addressMapping.setCell(address, vertex) } - public addMatrixVertex(address: SimpleCellAddress, vertex: CellVertex): void { + public addMatrixVertex(address: SimpleCellAddress, vertex: MatrixVertex): void { this.graph.addNode(vertex) this.setAddressMappingForMatrixVertex(vertex, address) } @@ -738,6 +738,14 @@ export class DependencyGraph { return values } + public shrinkMatrixToCorner(vertex: MatrixVertex) { + const matrixRange = vertex.getRange() + for (const address of matrixRange.addresses(this)) { + this.addressMapping.removeCellIfEqual(address, vertex) + } + this.addressMapping.setCell(matrixRange.start, vertex) + } + private rangeDependencyQuery = (vertex: RangeVertex) => { const allDeps: [(SimpleCellAddress | AbsoluteCellRange), Vertex][] = [] const {smallerRangeVertex, restRange} = this.rangeMapping.findSmallerRange(vertex.range) //checking whether this range was splitted by bruteForce or not @@ -865,6 +873,10 @@ export class DependencyGraph { const range = AbsoluteCellRange.spanFrom(formulaAddress, vertex.width, vertex.height) this.setMatrix(range, vertex) + if (!this.isThereSpaceForMatrix(vertex)) { + return + } + for (const address of range.addresses(this)) { this.addressMapping.setCell(address, vertex) } @@ -921,14 +933,6 @@ export class DependencyGraph { } } - private shrinkMatrixToCorner(vertex: MatrixVertex) { - const matrixRange = vertex.getRange() - for (const address of matrixRange.addresses(this)) { - this.addressMapping.removeCellIfEqual(address, vertex) - } - this.addressMapping.setCell(matrixRange.start, vertex) - } - private removeVertex(vertex: Vertex) { this.removeVertexAndCleanupDependencies(vertex) if (vertex instanceof RangeVertex) { diff --git a/src/GraphBuilder.ts b/src/GraphBuilder.ts index 6785d54da1..8ba1e9f8dd 100644 --- a/src/GraphBuilder.ts +++ b/src/GraphBuilder.ts @@ -4,7 +4,7 @@ */ import {absolutizeDependencies} from './absolutizeDependencies' -import {simpleCellAddress} from './Cell' +import {SimpleCellAddress, simpleCellAddress} from './Cell' import {CellContent, CellContentParser} from './CellContentParser' import {CellDependency} from './CellDependency' import {Config} from './Config' @@ -22,6 +22,8 @@ import {MatrixSize, MatrixSizePredictor} from './MatrixSize' import {ParserWithCaching} from './parser' import {Sheets} from './Sheet' import {Statistics, StatType} from './statistics' +import {Matrix} from './Matrix' +import {AbsoluteCellRange} from './AbsoluteCellRange' export type Dependencies = Map @@ -93,9 +95,11 @@ export class SimpleStrategy implements GraphBuilderStrategy { if (parsedCellContent instanceof CellContent.Formula) { const parseResult = this.stats.measure(StatType.PARSER, () => this.parser.parse(parsedCellContent.formula, address)) if (parseResult.errors.length > 0) { + this.shrinkMatrixIfNeeded(address) const vertex = new ParsingErrorVertex(parseResult.errors, parsedCellContent.formula) this.dependencyGraph.addVertex(address, vertex) } else { + this.shrinkMatrixIfNeeded(address) const size = this.matrixSizePredictor.checkMatrixSize(parseResult.ast, address) if (size.isScalar()) { const vertex = new FormulaCellVertex(parseResult.ast, address, 0) @@ -116,6 +120,7 @@ export class SimpleStrategy implements GraphBuilderStrategy { } else if (parsedCellContent instanceof CellContent.Empty) { /* we don't care about empty cells here */ } else { + this.shrinkMatrixIfNeeded(address) const vertex = new ValueCellVertex(parsedCellContent.value, cellContent) this.columnIndex.add(getRawValue(parsedCellContent.value), address) this.dependencyGraph.addVertex(address, vertex) @@ -126,4 +131,11 @@ export class SimpleStrategy implements GraphBuilderStrategy { return dependencies } + + private shrinkMatrixIfNeeded(address: SimpleCellAddress) { + const vertex = this.dependencyGraph.getCell(address) + if (vertex instanceof MatrixVertex) { + this.dependencyGraph.shrinkMatrixToCorner(vertex) + } + } } diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts index 3e02d18807..e1ee4d2bc8 100644 --- a/test/cruds/matrix-cruds.spec.ts +++ b/test/cruds/matrix-cruds.spec.ts @@ -1,9 +1,117 @@ -import {ErrorType, HyperFormula} from '../../src' -import {adr, detailedError, expectEngineToBeTheSameAs} from '../testUtils' -import {ErrorMessage} from '../../src/error-message' +import {HyperFormula} from '../../src' +import {adr, expectEngineToBeTheSameAs, expectVerticesOfTypes, noSpace} from '../testUtils' import {MatrixVertex, ValueCellVertex} from '../../src/DependencyGraph' import {MatrixSize} from '../../src/MatrixSize' +describe('Create engine', () => { + it('should create engine with array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=-A1:B2'], + [3, 4], + ], {useArrayArithmetic: true}) + + expect(engine.getSheetValues(0)).toEqual([ + [1, 2, -1, -2], + [3, 4, -3, -4], + ]) + }) + + it('should be enough to specify only corner of an array', () => { + const engine = HyperFormula.buildFromArray([ + ['=TRANSPOSE(D1:E2)'], + ], {useArrayArithmetic: true}) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex], + [MatrixVertex, MatrixVertex], + ]) + }) + + it('should be separate arrays', () => { + const engine = HyperFormula.buildFromArray([ + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ], {useArrayArithmetic: true}) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex, null], + [MatrixVertex, MatrixVertex, MatrixVertex], + [null, MatrixVertex, MatrixVertex], + ]) + expect(engine.matrixMapping.matrixMapping.size).toEqual(4) + expect(engine.getSheetValues(0)) + }) + + it('should REF last matrix', () => { + const engine = HyperFormula.buildFromArray([ + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)', null, 1, 2], + ['=TRANSPOSE(D1:E2)', null, null, 1, 2], + ], {useArrayArithmetic: true}) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex, MatrixVertex], + [MatrixVertex, MatrixVertex, MatrixVertex], + [null, null], + ]) + expect(engine.getSheetValues(0)).toEqual([ + [noSpace(), 1, 1, 1, 2], + [noSpace(), 2, 2, 1, 2], + ]) + expect(engine.matrixMapping.matrixMapping.size).toEqual(3) + expect(engine.getSheetValues(0)) + }) + + it('array should work with different types of data', () => { + const engine = HyperFormula.buildFromArray([ + [1, 'foo', '=TRANSPOSE(A1:B2)'], + [true, '=SUM(A1)'], + ], {useArrayArithmetic: true}) + + expect(engine.getSheetValues(0)).toEqual([ + [1, 'foo', 1, true], + [true, 1, 'foo', 1], + ]) + }) + + it('should make REF matrix if no space', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D2', 2], + [3, 4], + ], {useArrayArithmetic: true}) + + expect(engine.getSheetValues(0)).toEqual([ + [noSpace(), 2], + [3, 4], + ]) + }) + + it('should not shrink matrix if empty vertex', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D2', null], + [null, null] + ], {useArrayArithmetic: true}) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex], + [MatrixVertex, MatrixVertex], + ]) + + }) + + it('should shrink to one vertex if there is more content colliding with matrix', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D2', null], + [1, null] + ], {useArrayArithmetic: true}) + + expect(engine.matrixMapping.getMatrixByCorner(adr('A1'))?.matrix.size).toEqual(MatrixSize.error()) + expectVerticesOfTypes(engine, [ + [MatrixVertex, null], + [ValueCellVertex, null], + ]) + }) +}) + describe('Add rows', () => { it('should be possible to add row above matrix', () => { const engine = HyperFormula.buildFromArray([ @@ -32,7 +140,7 @@ describe('Add rows', () => { ['=-A1:B3'], [], [], ['foo'] - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) engine.addRows(0, [4, 1]) @@ -41,7 +149,7 @@ describe('Add rows', () => { ['=-A1:B3'], [], [], [], ['foo'] - ], { useArrayArithmetic: true })) + ], {useArrayArithmetic: true})) }) it('adding row should expand dependent array', () => { @@ -49,7 +157,7 @@ describe('Add rows', () => { [1, 2], [3, 4], ['=TRANSPOSE(A1:B2)'] - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) engine.addRows(0, [1, 1]) @@ -58,7 +166,7 @@ describe('Add rows', () => { [], [3, 4], ['=TRANSPOSE(A1:B3)'] - ], { useArrayArithmetic: true })) + ], {useArrayArithmetic: true})) }) it('undo add row with dependent array', () => { @@ -66,7 +174,7 @@ describe('Add rows', () => { [1, 2], [3, 4], ['=TRANSPOSE(A1:B2)'] - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) engine.addRows(0, [1, 1]) engine.undo() @@ -75,7 +183,7 @@ describe('Add rows', () => { [1, 2], [3, 4], ['=TRANSPOSE(A1:B2)'] - ], { useArrayArithmetic: true })) + ], {useArrayArithmetic: true})) }) }) @@ -107,7 +215,7 @@ describe('Remove rows', () => { ['=-A1:B3'], [], [], [], ['foo'] - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) engine.removeRows(0, [4, 1]) @@ -116,7 +224,7 @@ describe('Remove rows', () => { ['=-A1:B3'], [], [], ['foo'] - ], { useArrayArithmetic: true })) + ], {useArrayArithmetic: true})) }) it('removing row should shrink dependent array', () => { @@ -125,7 +233,7 @@ describe('Remove rows', () => { [], [3, 4], ['=TRANSPOSE(A1:B3)'] - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) engine.removeRows(0, [1, 1]) @@ -133,7 +241,7 @@ describe('Remove rows', () => { [1, 2], [3, 4], ['=TRANSPOSE(A1:B2)'] - ], { useArrayArithmetic: true })) + ], {useArrayArithmetic: true})) }) it('it should be REF if no space after removing row', () => { @@ -142,20 +250,21 @@ describe('Remove rows', () => { [], [1, 1], [null, 2], - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) engine.removeRows(0, [1, 1]) - expect(engine.getCellValue(adr('A1'))).toEqual(detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult)) - expect(engine.getCellValue(adr('A2'))).toEqual(1) - expect(engine.getCellValue(adr('B2'))).toEqual(1) - expect(engine.getCellValue(adr('B3'))).toEqual(2) + expect(engine.getSheetValues(0)).toEqual([ + [noSpace()], + [1, 1], + [null, 2], + ]) const expected = HyperFormula.buildFromArray([ ['=-B2:B3'], [1, 1], [null, 2] - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) expectEngineToBeTheSameAs(engine, expected) }) @@ -165,19 +274,21 @@ describe('Remove rows', () => { [], [1], [2] - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) engine.removeRows(0, [1, 1]) - expect(engine.getCellValue(adr('A1'))).toEqual(detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult)) - expect(engine.getCellValue(adr('A2'))).toEqual(1) - expect(engine.getCellValue(adr('A3'))).toEqual(2) + expect(engine.getSheetValues(0)).toEqual([ + [noSpace()], + [1], + [2] + ]) const expected = HyperFormula.buildFromArray([ ['=-A2:A3'], [1], [2] - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) expectEngineToBeTheSameAs(engine, expected) }) }) @@ -187,48 +298,48 @@ describe('Set cell content', () => { const engine = HyperFormula.buildFromArray([ [1, 2], [3, 4], - ], { useArrayArithmetic: true}) + ], {useArrayArithmetic: true}) engine.setCellContents(adr('C1'), [['=-A1:B2']]) expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ [1, 2, '=-A1:B2'], [3, 4], - ], { useArrayArithmetic: true})) + ], {useArrayArithmetic: true})) }) it('should be REF matrix if no space for result', () => { const engine = HyperFormula.buildFromArray([ [], [1], - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) engine.setCellContents(adr('A1'), [['=-B2:B3']]) - expect(engine.getCellValue(adr('A1'))).toEqual(detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult)) + expect(engine.getCellValue(adr('A1'))).toEqual(noSpace()) expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ ['=-B2:B3'], [1], - ], { useArrayArithmetic: true })) + ], {useArrayArithmetic: true})) }) it('should be REF matrix if no space and potential cycle', () => { const engine = HyperFormula.buildFromArray([ [], [1], - ], { useArrayArithmetic: true }) + ], {useArrayArithmetic: true}) engine.setCellContents(adr('A1'), [['=-A2:A3']]) - expect(engine.getCellValue(adr('A1'))).toEqual(detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult)) + expect(engine.getCellValue(adr('A1'))).toEqual(noSpace()) expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ ['=-A2:A3'], [1], - ], { useArrayArithmetic: true })) + ], {useArrayArithmetic: true})) }) it('should shrink to one vertex if there is more content colliding with matrix', () => { - const engine = HyperFormula.buildFromArray([], { useArrayArithmetic: true}) + const engine = HyperFormula.buildFromArray([], {useArrayArithmetic: true}) engine.setCellContents(adr('A1'), [ ['=-C1:D2', null], @@ -236,9 +347,54 @@ describe('Set cell content', () => { ]) expect(engine.matrixMapping.getMatrixByCorner(adr('A1'))?.matrix.size).toEqual(MatrixSize.error()) - expect(engine.addressMapping.getCell(adr('A1'))).toBeInstanceOf(MatrixVertex) - expect(engine.addressMapping.getCell(adr('B1'))).toBe(null) - expect(engine.addressMapping.getCell(adr('A2'))).toBeInstanceOf(ValueCellVertex) - expect(engine.addressMapping.getCell(adr('B2'))).toBe(null) + expectVerticesOfTypes(engine, [ + [MatrixVertex, null], + [ValueCellVertex, null], + ]) + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['=-C1:D2', null], + [1, null] + ], {useArrayArithmetic: true})) + }) + + it('should be separate arrays', () => { + const engine = HyperFormula.buildFromArray([], {useArrayArithmetic: true}) + + engine.setCellContents(adr('A1'), [ + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ]) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex, null], + [MatrixVertex, MatrixVertex, MatrixVertex], + [null, MatrixVertex, MatrixVertex], + ]) + expect(engine.matrixMapping.matrixMapping.size).toEqual(4) + expect(engine.getSheetValues(0)) + }) + + it('should REF last matrix', () => { + const engine = HyperFormula.buildFromArray([ + [null, null, null, 1, 2], + [null, null, null, 1, 2], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('A1'), [ + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ['=TRANSPOSE(D1:E2)'], + ]) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex, MatrixVertex], + [MatrixVertex, MatrixVertex, MatrixVertex], + [null, null], + ]) + expect(engine.getSheetValues(0)).toEqual([ + [noSpace(), 1, 1, 1, 2], + [noSpace(), 2, 2, 1, 2], + ]) + expect(engine.matrixMapping.matrixMapping.size).toEqual(3) + expect(engine.getSheetValues(0)) }) }) diff --git a/test/interpreter/matrix-plugin.spec.ts b/test/interpreter/matrix-plugin.spec.ts index bb97a8424a..83597af2ea 100644 --- a/test/interpreter/matrix-plugin.spec.ts +++ b/test/interpreter/matrix-plugin.spec.ts @@ -78,8 +78,8 @@ describe('Matrix plugin', () => { it('mmult of other mmult', () => { const engine = HyperFormula.buildFromArray([ - ['1', '2', '=MMULT(A1:B2, A1:B2)', '=MMULT(A1:B2, A1:B2)'], - ['3', '4', '=MMULT(A1:B2, A1:B2)', '=MMULT(A1:B2, A1:B2)'], + ['1', '2', '=MMULT(A1:B2, A1:B2)'], + ['3', '4'], ['=MMULT(A1:B2, C1:D2)'], ], config) diff --git a/test/testUtils.ts b/test/testUtils.ts index 6506f11d5e..264ee10096 100644 --- a/test/testUtils.ts +++ b/test/testUtils.ts @@ -1,6 +1,6 @@ -import {CellValue, DetailedCellError, HyperFormula} from '../src' +import {CellValue, DetailedCellError, ErrorType, HyperFormula} from '../src' import {AbsoluteCellRange, AbsoluteColumnRange, AbsoluteRowRange} from '../src/AbsoluteCellRange' -import {CellError, ErrorType, SimpleCellAddress, simpleCellAddress} from '../src/Cell' +import {CellError, SimpleCellAddress, simpleCellAddress} from '../src/Cell' import {Config} from '../src/Config' import {DateTimeHelper} from '../src/DateTimeHelper' import {FormulaCellVertex, MatrixVertex, RangeVertex} from '../src/DependencyGraph' @@ -17,6 +17,7 @@ import { } from '../src/parser' import {ColumnRangeAst, RowRangeAst} from '../src/parser/Ast' import {EngineComparator} from './graphComparator' +import {ErrorMessage} from '../src/error-message' export const extractReference = (engine: HyperFormula, address: SimpleCellAddress): CellAddress => { return ((engine.addressMapping.fetchCell(address) as FormulaCellVertex).getFormula(engine.lazilyTransformingAstService) as CellReferenceAst).reference @@ -152,6 +153,10 @@ export function detailedError(errorType: ErrorType, message?: string, config?: C return new DetailedCellError(error, config.translationPackage.getErrorTranslation(errorType)) } +export function noSpace(): DetailedCellError { + return detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult) +} + export function detailedErrorWithOrigin(errorType: ErrorType, address: string, message?: string, config?: Config): DetailedCellError { config = new Config(config) const error = new CellError(errorType, message) @@ -186,3 +191,17 @@ export function unregisterAllLanguages() { HyperFormula.unregisterLanguage(langCode) } } + +export function expectVerticesOfTypes(engine: HyperFormula, types: any[][], sheet: number = 0) { + for (let row=0; row Date: Fri, 28 May 2021 13:31:46 +0200 Subject: [PATCH 28/87] Tests cleanup --- test/arrays.spec.ts | 113 ++++++- test/cruds/adding-row.spec.ts | 160 +++++++--- test/cruds/change-cell-content.spec.ts | 163 ++++++++-- test/cruds/matrix-cruds.spec.ts | 400 ------------------------- test/cruds/removing-rows.spec.ts | 108 ++++++- 5 files changed, 469 insertions(+), 475 deletions(-) delete mode 100644 test/cruds/matrix-cruds.spec.ts diff --git a/test/arrays.spec.ts b/test/arrays.spec.ts index 0d2928631f..f6761840af 100644 --- a/test/arrays.spec.ts +++ b/test/arrays.spec.ts @@ -1,6 +1,8 @@ import {ErrorType, HyperFormula} from '../src' import {ErrorMessage} from '../src/error-message' -import {adr, detailedError, detailedErrorWithOrigin} from './testUtils' +import {adr, detailedError, detailedErrorWithOrigin, expectVerticesOfTypes, noSpace} from './testUtils' +import {MatrixVertex, ValueCellVertex} from '../src/DependencyGraph' +import {MatrixSize} from '../src/MatrixSize' describe('without arrayformula, with useArrayArithmetic flag', () => { it('unary op, scalar ret', () => { @@ -321,3 +323,112 @@ describe('vectorization', () => { expect(engine.getSheetValues(0)).toEqual([[2, 5, 4]]) }) }) + +describe('build from array', () => { + it('should create engine with array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=-A1:B2'], + [3, 4], + ], {useArrayArithmetic: true}) + + expect(engine.getSheetValues(0)).toEqual([ + [1, 2, -1, -2], + [3, 4, -3, -4], + ]) + }) + + it('should be enough to specify only corner of an array', () => { + const engine = HyperFormula.buildFromArray([ + ['=TRANSPOSE(D1:E2)'], + ], {useArrayArithmetic: true}) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex], + [MatrixVertex, MatrixVertex], + ]) + }) + + it('should be separate arrays', () => { + const engine = HyperFormula.buildFromArray([ + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ], {useArrayArithmetic: true}) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex, null], + [MatrixVertex, MatrixVertex, MatrixVertex], + [null, MatrixVertex, MatrixVertex], + ]) + expect(engine.matrixMapping.matrixMapping.size).toEqual(4) + expect(engine.getSheetValues(0)) + }) + + it('should REF last array', () => { + const engine = HyperFormula.buildFromArray([ + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)', null, 1, 2], + ['=TRANSPOSE(D1:E2)', null, null, 1, 2], + ], {useArrayArithmetic: true}) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex, MatrixVertex], + [MatrixVertex, MatrixVertex, MatrixVertex], + [null, null], + ]) + expect(engine.getSheetValues(0)).toEqual([ + [noSpace(), 1, 1, 1, 2], + [noSpace(), 2, 2, 1, 2], + ]) + expect(engine.matrixMapping.matrixMapping.size).toEqual(3) + expect(engine.getSheetValues(0)) + }) + + it('array should work with different types of data', () => { + const engine = HyperFormula.buildFromArray([ + [1, 'foo', '=TRANSPOSE(A1:B2)'], + [true, '=SUM(A1)'], + ], {useArrayArithmetic: true}) + + expect(engine.getSheetValues(0)).toEqual([ + [1, 'foo', 1, true], + [true, 1, 'foo', 1], + ]) + }) + + it('should make REF array if no space', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D2', 2], + [3, 4], + ], {useArrayArithmetic: true}) + + expect(engine.getSheetValues(0)).toEqual([ + [noSpace(), 2], + [3, 4], + ]) + }) + + it('should not shrink array if empty vertex', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D2', null], + [null, null] + ], {useArrayArithmetic: true}) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex], + [MatrixVertex, MatrixVertex], + ]) + + }) + + it('should shrink to one vertex if there is more content colliding with array', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D2', null], + [1, null] + ], {useArrayArithmetic: true}) + + expect(engine.matrixMapping.getMatrixByCorner(adr('A1'))?.matrix.size).toEqual(MatrixSize.error()) + expectVerticesOfTypes(engine, [ + [MatrixVertex, null], + [ValueCellVertex, null], + ]) + }) +}) diff --git a/test/cruds/adding-row.spec.ts b/test/cruds/adding-row.spec.ts index 4a4afbf5d2..a21072c5ff 100644 --- a/test/cruds/adding-row.spec.ts +++ b/test/cruds/adding-row.spec.ts @@ -209,50 +209,6 @@ describe('Adding row - reevaluation', () => { }) }) -/* TODO size of matrix can be dependent on structural changes */ -describe.skip('Adding row - MatrixVertex', () => { - it('MatrixVertex#formula should be updated', () => { - const engine = HyperFormula.buildFromArray([ - ['1', '2'], - ['3', '4'], - ['=TRANSPOSE(A1:B2)'], - ]) - - engine.addRows(0, [1, 1]) - - expect(extractMatrixRange(engine, adr('A4'))).toEqual(new AbsoluteCellRange(adr('A1'), adr('B3'))) - }) - - it('MatrixVertex#formula should be updated when different sheets', () => { - const engine = HyperFormula.buildFromSheets({ - Sheet1: [ - ['1', '2'], - ['3', '4'], - ], - Sheet2: [ - ['=TRANSPOSE(Sheet1!A1:B2)'], - ], - }) - - engine.addRows(0, [1, 1]) - - expect(extractMatrixRange(engine, adr('A1', 1))).toEqual(new AbsoluteCellRange(adr('A1'), adr('B3'))) - }) - - it('MatrixVertex#address should be updated', () => { - const engine = HyperFormula.buildFromArray([ - ['1', '2'], - ['3', '4'], - ['=TRANSPOSE(A1:B2)'], - ]) - - engine.addRows(0, [1, 1]) - - const matrixVertex = engine.addressMapping.fetchCell(adr('A4')) as MatrixVertex - expect(matrixVertex.getAddress(engine.lazilyTransformingAstService)).toEqual(adr('A4')) - }) -}) - describe('Adding row - FormulaCellVertex#address update', () => { it('insert row, formula vertex address shifted', () => { const engine = HyperFormula.buildFromArray([ @@ -351,3 +307,119 @@ describe('Adding row - column index', () => { expectArrayWithSameContent([2], index.getValueIndex(0, 0, 2).index) }) }) + +describe('Adding row - arrays', () => { + it('should be possible to add row above array', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D3'], + [], + [], + ['foo'] + ], {useArrayArithmetic: true}) + + engine.addRows(0, [0, 1]) + + const expected = HyperFormula.buildFromArray([ + [], + ['=-C2:D4'], + [], + [], + ['foo'] + ], {useArrayArithmetic: true}) + + expectEngineToBeTheSameAs(engine, expected) + }) + + it('adding row across array should not change array', () => { + const engine = HyperFormula.buildFromArray([ + [], [], [], + ['=-A1:B3'], + [], [], + ['foo'] + ], {useArrayArithmetic: true}) + + engine.addRows(0, [4, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [], [], [], + ['=-A1:B3'], + [], [], [], + ['foo'] + ], {useArrayArithmetic: true})) + }) + + it('adding row should expand dependent array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ['=TRANSPOSE(A1:B2)'] + ], {useArrayArithmetic: true}) + + engine.addRows(0, [1, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [], + [3, 4], + ['=TRANSPOSE(A1:B3)'] + ], {useArrayArithmetic: true})) + }) + + it('undo add row with dependent array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ['=TRANSPOSE(A1:B2)'] + ], {useArrayArithmetic: true}) + + engine.addRows(0, [1, 1]) + engine.undo() + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ['=TRANSPOSE(A1:B2)'] + ], {useArrayArithmetic: true})) + }) + + it('MatrixVertex#formula should be updated', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4'], + ['=TRANSPOSE(A1:B2)'], + ]) + + engine.addRows(0, [1, 1]) + + expect(extractMatrixRange(engine, adr('A4'))).toEqual(new AbsoluteCellRange(adr('A1'), adr('B3'))) + }) + + it('MatrixVertex#formula should be updated when different sheets', () => { + const engine = HyperFormula.buildFromSheets({ + Sheet1: [ + ['1', '2'], + ['3', '4'], + ], + Sheet2: [ + ['=TRANSPOSE(Sheet1!A1:B2)'], + ], + }) + + engine.addRows(0, [1, 1]) + + expect(extractMatrixRange(engine, adr('A1', 1))).toEqual(new AbsoluteCellRange(adr('A1'), adr('B3'))) + }) + + it('MatrixVertex#address should be updated', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4'], + ['=TRANSPOSE(A1:B2)'], + ]) + + engine.addRows(0, [1, 1]) + + const matrixVertex = engine.addressMapping.fetchCell(adr('A4')) as MatrixVertex + expect(matrixVertex.getAddress(engine.lazilyTransformingAstService)).toEqual(adr('A4')) + }) +}) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index da6e6b5f3f..7e286aff08 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -1,11 +1,21 @@ import {ExportedCellChange, HyperFormula, InvalidAddressError, NoSheetWithIdError} from '../../src' import {ErrorType, simpleCellAddress} from '../../src/Cell' import {Config} from '../../src/Config' -import {EmptyCellVertex, MatrixVertex} from '../../src/DependencyGraph' +import {EmptyCellVertex, MatrixVertex, ValueCellVertex} from '../../src/DependencyGraph' import {ErrorMessage} from '../../src/error-message' import {SheetSizeLimitExceededError} from '../../src/errors' import {ColumnIndex} from '../../src/Lookup/ColumnIndex' -import {adr, colEnd, colStart, detailedError, expectArrayWithSameContent, rowEnd, rowStart} from '../testUtils' +import { + adr, + colEnd, + colStart, + detailedError, + expectArrayWithSameContent, + expectEngineToBeTheSameAs, expectVerticesOfTypes, noSpace, + rowEnd, + rowStart +} from '../testUtils' +import {MatrixSize} from '../../src/MatrixSize' describe('Changing cell content - checking if its possible', () => { it('address should have valid coordinates', () => { @@ -221,21 +231,6 @@ describe('changing cell content', () => { expect(engine.getCellFormula(adr('A1'))).toEqual('=SUM(') }) - it('rewrite part of sheet with matrix', () => { - const sheet = [ - ['1', '2'], - ['3', '4'], - ['=A1', null], - ['1', 'foo'], - ] - const engine = HyperFormula.buildFromArray(sheet) - - engine.setCellContents(adr('A3'), '=MMULT(A1:B2,A1:B2)') - expect(engine.addressMapping.fetchCell(adr('A3'))).toBeInstanceOf(MatrixVertex) - expect(engine.addressMapping.fetchCell(adr('B4'))).toBeInstanceOf(MatrixVertex) - expect(engine.getCellValue(adr('A3'))).toBe(7) - }) - it('changing value inside range', () => { const engine = HyperFormula.buildFromArray([ ['1', '0'], @@ -397,17 +392,6 @@ describe('changing cell content', () => { expect(b2setCellValueSpy).not.toHaveBeenCalled() }) - it('should not be possible to edit part of a Matrix', () => { - const engine = HyperFormula.buildFromArray([ - ['1', '2'], - [null, '=TRANSPOSE(A1:B1)'], - ]) - - expect(() => { - engine.setCellContents(adr('A2'), '=TRANSPOSE(C1:C2)') - }).toThrowError('Illegal operation') - }) - it('is not possible to set cell content in sheet which does not exist', () => { const sheet = [ ['1', '2'], @@ -772,3 +756,126 @@ describe('row ranges', () => { expect(engine.getCellValue(adr('A1'))).toEqual(3) }) }) + +describe('arrays', () => { + it('should set matrix to cell', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('C1'), [['=-A1:B2']]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2, '=-A1:B2'], + [3, 4], + ], {useArrayArithmetic: true})) + }) + + it('should be REF matrix if no space for result', () => { + const engine = HyperFormula.buildFromArray([ + [], + [1], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('A1'), [['=-B2:B3']]) + + expect(engine.getCellValue(adr('A1'))).toEqual(noSpace()) + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['=-B2:B3'], + [1], + ], {useArrayArithmetic: true})) + }) + + it('should be REF matrix if no space and potential cycle', () => { + const engine = HyperFormula.buildFromArray([ + [], + [1], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('A1'), [['=-A2:A3']]) + + expect(engine.getCellValue(adr('A1'))).toEqual(noSpace()) + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['=-A2:A3'], + [1], + ], {useArrayArithmetic: true})) + }) + + it('should shrink to one vertex if there is more content colliding with matrix', () => { + const engine = HyperFormula.buildFromArray([], {useArrayArithmetic: true}) + + engine.setCellContents(adr('A1'), [ + ['=-C1:D2', null], + [1, null] + ]) + + expect(engine.matrixMapping.getMatrixByCorner(adr('A1'))?.matrix.size).toEqual(MatrixSize.error()) + expectVerticesOfTypes(engine, [ + [MatrixVertex, null], + [ValueCellVertex, null], + ]) + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['=-C1:D2', null], + [1, null] + ], {useArrayArithmetic: true})) + }) + + it('should be separate arrays', () => { + const engine = HyperFormula.buildFromArray([], {useArrayArithmetic: true}) + + engine.setCellContents(adr('A1'), [ + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ]) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex, null], + [MatrixVertex, MatrixVertex, MatrixVertex], + [null, MatrixVertex, MatrixVertex], + ]) + expect(engine.matrixMapping.matrixMapping.size).toEqual(4) + expect(engine.getSheetValues(0)) + }) + + it('should REF last matrix', () => { + const engine = HyperFormula.buildFromArray([ + [null, null, null, 1, 2], + [null, null, null, 1, 2], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('A1'), [ + ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], + ['=TRANSPOSE(D1:E2)'], + ]) + + expectVerticesOfTypes(engine, [ + [MatrixVertex, MatrixVertex, MatrixVertex], + [MatrixVertex, MatrixVertex, MatrixVertex], + [null, null], + ]) + expect(engine.getSheetValues(0)).toEqual([ + [noSpace(), 1, 1, 1, 2], + [noSpace(), 2, 2, 1, 2], + ]) + expect(engine.matrixMapping.matrixMapping.size).toEqual(3) + expect(engine.getSheetValues(0)) + }) + + it('should make existing matrix REF and change cell content', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4'], + ['=-A1:B2'], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('B4'), [['foo']]) + + expect(engine.getSheetValues(0)).toEqual([ + [1, 2], + [1, 2], + [noSpace(), null], + [null, 'foo'] + ]) + }) +}) diff --git a/test/cruds/matrix-cruds.spec.ts b/test/cruds/matrix-cruds.spec.ts deleted file mode 100644 index e1ee4d2bc8..0000000000 --- a/test/cruds/matrix-cruds.spec.ts +++ /dev/null @@ -1,400 +0,0 @@ -import {HyperFormula} from '../../src' -import {adr, expectEngineToBeTheSameAs, expectVerticesOfTypes, noSpace} from '../testUtils' -import {MatrixVertex, ValueCellVertex} from '../../src/DependencyGraph' -import {MatrixSize} from '../../src/MatrixSize' - -describe('Create engine', () => { - it('should create engine with array', () => { - const engine = HyperFormula.buildFromArray([ - [1, 2, '=-A1:B2'], - [3, 4], - ], {useArrayArithmetic: true}) - - expect(engine.getSheetValues(0)).toEqual([ - [1, 2, -1, -2], - [3, 4, -3, -4], - ]) - }) - - it('should be enough to specify only corner of an array', () => { - const engine = HyperFormula.buildFromArray([ - ['=TRANSPOSE(D1:E2)'], - ], {useArrayArithmetic: true}) - - expectVerticesOfTypes(engine, [ - [MatrixVertex, MatrixVertex], - [MatrixVertex, MatrixVertex], - ]) - }) - - it('should be separate arrays', () => { - const engine = HyperFormula.buildFromArray([ - ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], - ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], - ], {useArrayArithmetic: true}) - - expectVerticesOfTypes(engine, [ - [MatrixVertex, MatrixVertex, null], - [MatrixVertex, MatrixVertex, MatrixVertex], - [null, MatrixVertex, MatrixVertex], - ]) - expect(engine.matrixMapping.matrixMapping.size).toEqual(4) - expect(engine.getSheetValues(0)) - }) - - it('should REF last matrix', () => { - const engine = HyperFormula.buildFromArray([ - ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)', null, 1, 2], - ['=TRANSPOSE(D1:E2)', null, null, 1, 2], - ], {useArrayArithmetic: true}) - - expectVerticesOfTypes(engine, [ - [MatrixVertex, MatrixVertex, MatrixVertex], - [MatrixVertex, MatrixVertex, MatrixVertex], - [null, null], - ]) - expect(engine.getSheetValues(0)).toEqual([ - [noSpace(), 1, 1, 1, 2], - [noSpace(), 2, 2, 1, 2], - ]) - expect(engine.matrixMapping.matrixMapping.size).toEqual(3) - expect(engine.getSheetValues(0)) - }) - - it('array should work with different types of data', () => { - const engine = HyperFormula.buildFromArray([ - [1, 'foo', '=TRANSPOSE(A1:B2)'], - [true, '=SUM(A1)'], - ], {useArrayArithmetic: true}) - - expect(engine.getSheetValues(0)).toEqual([ - [1, 'foo', 1, true], - [true, 1, 'foo', 1], - ]) - }) - - it('should make REF matrix if no space', () => { - const engine = HyperFormula.buildFromArray([ - ['=-C1:D2', 2], - [3, 4], - ], {useArrayArithmetic: true}) - - expect(engine.getSheetValues(0)).toEqual([ - [noSpace(), 2], - [3, 4], - ]) - }) - - it('should not shrink matrix if empty vertex', () => { - const engine = HyperFormula.buildFromArray([ - ['=-C1:D2', null], - [null, null] - ], {useArrayArithmetic: true}) - - expectVerticesOfTypes(engine, [ - [MatrixVertex, MatrixVertex], - [MatrixVertex, MatrixVertex], - ]) - - }) - - it('should shrink to one vertex if there is more content colliding with matrix', () => { - const engine = HyperFormula.buildFromArray([ - ['=-C1:D2', null], - [1, null] - ], {useArrayArithmetic: true}) - - expect(engine.matrixMapping.getMatrixByCorner(adr('A1'))?.matrix.size).toEqual(MatrixSize.error()) - expectVerticesOfTypes(engine, [ - [MatrixVertex, null], - [ValueCellVertex, null], - ]) - }) -}) - -describe('Add rows', () => { - it('should be possible to add row above matrix', () => { - const engine = HyperFormula.buildFromArray([ - ['=-C1:D3'], - [], - [], - ['foo'] - ], {useArrayArithmetic: true}) - - engine.addRows(0, [0, 1]) - - const expected = HyperFormula.buildFromArray([ - [], - ['=-C2:D4'], - [], - [], - ['foo'] - ], {useArrayArithmetic: true}) - - expectEngineToBeTheSameAs(engine, expected) - }) - - it('adding row across array should not change array', () => { - const engine = HyperFormula.buildFromArray([ - [], [], [], - ['=-A1:B3'], - [], [], - ['foo'] - ], {useArrayArithmetic: true}) - - engine.addRows(0, [4, 1]) - - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - [], [], [], - ['=-A1:B3'], - [], [], [], - ['foo'] - ], {useArrayArithmetic: true})) - }) - - it('adding row should expand dependent array', () => { - const engine = HyperFormula.buildFromArray([ - [1, 2], - [3, 4], - ['=TRANSPOSE(A1:B2)'] - ], {useArrayArithmetic: true}) - - engine.addRows(0, [1, 1]) - - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - [1, 2], - [], - [3, 4], - ['=TRANSPOSE(A1:B3)'] - ], {useArrayArithmetic: true})) - }) - - it('undo add row with dependent array', () => { - const engine = HyperFormula.buildFromArray([ - [1, 2], - [3, 4], - ['=TRANSPOSE(A1:B2)'] - ], {useArrayArithmetic: true}) - - engine.addRows(0, [1, 1]) - engine.undo() - - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - [1, 2], - [3, 4], - ['=TRANSPOSE(A1:B2)'] - ], {useArrayArithmetic: true})) - }) -}) - -describe('Remove rows', () => { - it('should be possible to remove row above matrix', () => { - const engine = HyperFormula.buildFromArray([ - [], - ['=-C2:D4'], - [], - [], - ['foo'] - ], {useArrayArithmetic: true}) - - engine.removeRows(0, [0, 1]) - - const expected = HyperFormula.buildFromArray([ - ['=-C1:D3'], - [], - [], - ['foo'] - ], {useArrayArithmetic: true}) - - expectEngineToBeTheSameAs(engine, expected) - }) - - it('removing row across array should not change array', () => { - const engine = HyperFormula.buildFromArray([ - [1, 2], [3, 4], [5, 6], - ['=-A1:B3'], - [], [], [], - ['foo'] - ], {useArrayArithmetic: true}) - - engine.removeRows(0, [4, 1]) - - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - [1, 2], [3, 4], [5, 6], - ['=-A1:B3'], - [], [], - ['foo'] - ], {useArrayArithmetic: true})) - }) - - it('removing row should shrink dependent array', () => { - const engine = HyperFormula.buildFromArray([ - [1, 2], - [], - [3, 4], - ['=TRANSPOSE(A1:B3)'] - ], {useArrayArithmetic: true}) - - engine.removeRows(0, [1, 1]) - - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - [1, 2], - [3, 4], - ['=TRANSPOSE(A1:B2)'] - ], {useArrayArithmetic: true})) - }) - - it('it should be REF if no space after removing row', () => { - const engine = HyperFormula.buildFromArray([ - ['=-B3:B4'], - [], - [1, 1], - [null, 2], - ], {useArrayArithmetic: true}) - - engine.removeRows(0, [1, 1]) - - expect(engine.getSheetValues(0)).toEqual([ - [noSpace()], - [1, 1], - [null, 2], - ]) - - const expected = HyperFormula.buildFromArray([ - ['=-B2:B3'], - [1, 1], - [null, 2] - ], {useArrayArithmetic: true}) - expectEngineToBeTheSameAs(engine, expected) - }) - - it('it should be REF, not CYCLE, after removing rows', () => { - const engine = HyperFormula.buildFromArray([ - ['=-A3:A4'], - [], - [1], - [2] - ], {useArrayArithmetic: true}) - - engine.removeRows(0, [1, 1]) - - expect(engine.getSheetValues(0)).toEqual([ - [noSpace()], - [1], - [2] - ]) - - const expected = HyperFormula.buildFromArray([ - ['=-A2:A3'], - [1], - [2] - ], {useArrayArithmetic: true}) - expectEngineToBeTheSameAs(engine, expected) - }) -}) - -describe('Set cell content', () => { - it('should set matrix to cell', () => { - const engine = HyperFormula.buildFromArray([ - [1, 2], - [3, 4], - ], {useArrayArithmetic: true}) - - engine.setCellContents(adr('C1'), [['=-A1:B2']]) - - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - [1, 2, '=-A1:B2'], - [3, 4], - ], {useArrayArithmetic: true})) - }) - - it('should be REF matrix if no space for result', () => { - const engine = HyperFormula.buildFromArray([ - [], - [1], - ], {useArrayArithmetic: true}) - - engine.setCellContents(adr('A1'), [['=-B2:B3']]) - - expect(engine.getCellValue(adr('A1'))).toEqual(noSpace()) - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - ['=-B2:B3'], - [1], - ], {useArrayArithmetic: true})) - }) - - it('should be REF matrix if no space and potential cycle', () => { - const engine = HyperFormula.buildFromArray([ - [], - [1], - ], {useArrayArithmetic: true}) - - engine.setCellContents(adr('A1'), [['=-A2:A3']]) - - expect(engine.getCellValue(adr('A1'))).toEqual(noSpace()) - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - ['=-A2:A3'], - [1], - ], {useArrayArithmetic: true})) - }) - - it('should shrink to one vertex if there is more content colliding with matrix', () => { - const engine = HyperFormula.buildFromArray([], {useArrayArithmetic: true}) - - engine.setCellContents(adr('A1'), [ - ['=-C1:D2', null], - [1, null] - ]) - - expect(engine.matrixMapping.getMatrixByCorner(adr('A1'))?.matrix.size).toEqual(MatrixSize.error()) - expectVerticesOfTypes(engine, [ - [MatrixVertex, null], - [ValueCellVertex, null], - ]) - expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ - ['=-C1:D2', null], - [1, null] - ], {useArrayArithmetic: true})) - }) - - it('should be separate arrays', () => { - const engine = HyperFormula.buildFromArray([], {useArrayArithmetic: true}) - - engine.setCellContents(adr('A1'), [ - ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], - ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], - ]) - - expectVerticesOfTypes(engine, [ - [MatrixVertex, MatrixVertex, null], - [MatrixVertex, MatrixVertex, MatrixVertex], - [null, MatrixVertex, MatrixVertex], - ]) - expect(engine.matrixMapping.matrixMapping.size).toEqual(4) - expect(engine.getSheetValues(0)) - }) - - it('should REF last matrix', () => { - const engine = HyperFormula.buildFromArray([ - [null, null, null, 1, 2], - [null, null, null, 1, 2], - ], {useArrayArithmetic: true}) - - engine.setCellContents(adr('A1'), [ - ['=TRANSPOSE(D1:E2)', '=TRANSPOSE(D1:E2)'], - ['=TRANSPOSE(D1:E2)'], - ]) - - expectVerticesOfTypes(engine, [ - [MatrixVertex, MatrixVertex, MatrixVertex], - [MatrixVertex, MatrixVertex, MatrixVertex], - [null, null], - ]) - expect(engine.getSheetValues(0)).toEqual([ - [noSpace(), 1, 1, 1, 2], - [noSpace(), 2, 2, 1, 2], - ]) - expect(engine.matrixMapping.matrixMapping.size).toEqual(3) - expect(engine.getSheetValues(0)) - }) -}) diff --git a/test/cruds/removing-rows.spec.ts b/test/cruds/removing-rows.spec.ts index 2f9c8871b7..93362e00d1 100644 --- a/test/cruds/removing-rows.spec.ts +++ b/test/cruds/removing-rows.spec.ts @@ -12,7 +12,7 @@ import { expectReferenceToHaveRefError, extractMatrixRange, extractRange, - extractReference, + extractReference, noSpace, verifyRangesInSheet, verifyValues, } from '../testUtils' @@ -548,7 +548,7 @@ describe('Removing rows - reevaluation', () => { }) }) -describe('Removing rows - matrices', () => { +describe('Removing rows - arrays', () => { it('should not remove row with formula matrix', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], @@ -602,6 +602,110 @@ describe('Removing rows - matrices', () => { expect(extractMatrixRange(engine, adr('A1', 1))).toEqual(new AbsoluteCellRange(adr('A1'), adr('B2'))) }) + + it('should be possible to remove row above array', () => { + const engine = HyperFormula.buildFromArray([ + [], + ['=-C2:D4'], + [], + [], + ['foo'] + ], {useArrayArithmetic: true}) + + engine.removeRows(0, [0, 1]) + + const expected = HyperFormula.buildFromArray([ + ['=-C1:D3'], + [], + [], + ['foo'] + ], {useArrayArithmetic: true}) + + expectEngineToBeTheSameAs(engine, expected) + }) + + it('removing row across array should not change array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], [3, 4], [5, 6], + ['=-A1:B3'], + [], [], [], + ['foo'] + ], {useArrayArithmetic: true}) + + engine.removeRows(0, [4, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], [3, 4], [5, 6], + ['=-A1:B3'], + [], [], + ['foo'] + ], {useArrayArithmetic: true})) + }) + + it('removing row should shrink dependent array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2], + [], + [3, 4], + ['=TRANSPOSE(A1:B3)'] + ], {useArrayArithmetic: true}) + + engine.removeRows(0, [1, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4], + ['=TRANSPOSE(A1:B2)'] + ], {useArrayArithmetic: true})) + }) + + it('it should be REF if no space after removing row', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B3:B4'], + [], + [1, 1], + [null, 2], + ], {useArrayArithmetic: true}) + + engine.removeRows(0, [1, 1]) + + expect(engine.getSheetValues(0)).toEqual([ + [noSpace()], + [1, 1], + [null, 2], + ]) + + const expected = HyperFormula.buildFromArray([ + ['=-B2:B3'], + [1, 1], + [null, 2] + ], {useArrayArithmetic: true}) + expectEngineToBeTheSameAs(engine, expected) + }) + + it('it should be REF, not CYCLE, after removing rows', () => { + const engine = HyperFormula.buildFromArray([ + ['=-A3:A4'], + [], + [1], + [2] + ], {useArrayArithmetic: true}) + + engine.removeRows(0, [1, 1]) + + expect(engine.getSheetValues(0)).toEqual([ + [noSpace()], + [1], + [2] + ]) + + const expected = HyperFormula.buildFromArray([ + ['=-A2:A3'], + [1], + [2] + ], {useArrayArithmetic: true}) + expectEngineToBeTheSameAs(engine, expected) + }) }) describe('Removing rows - graph', function() { From e345ce22de3d771bdfac79beeb48963a8fad0d02 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 28 May 2021 13:35:18 +0200 Subject: [PATCH 29/87] Allow to setCellContent onto matrix --- src/CrudOperations.ts | 4 ---- test/cruds/change-cell-content.spec.ts | 8 ++++---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/CrudOperations.ts b/src/CrudOperations.ts index 7e0844b0d6..7a725b7402 100644 --- a/src/CrudOperations.ts +++ b/src/CrudOperations.ts @@ -593,10 +593,6 @@ export class CrudOperations { if (!this.sheetMapping.hasSheetWithId(address.sheet)) { throw new NoSheetWithIdError(address.sheet) } - - if (this.dependencyGraph.matrixMapping.isFormulaMatrixAtAddress(address)) { - throw new SourceLocationHasMatrixError() - } } public ensureItIsPossibleToChangeCellContents(inputAddress: SimpleCellAddress, content: RawCellContent[][]) { diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 7e286aff08..f4b48f7660 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -695,7 +695,7 @@ describe('column ranges', () => { expect(engine.getCellValue(adr('C1'))).toEqual(6) }) - it('works when adding matrix', () => { + it.skip('works when adding matrix', () => { const engine = HyperFormula.buildFromArray([ ['=SUM(B:C)'], ['1'], @@ -741,7 +741,7 @@ describe('row ranges', () => { expect(engine.getCellValue(adr('A3'))).toEqual(6) }) - it('works when adding matrix', () => { + it.skip('works when adding matrix', () => { const engine = HyperFormula.buildFromArray([ ['=SUM(2:3)', '1', '2'], ]) @@ -873,8 +873,8 @@ describe('arrays', () => { expect(engine.getSheetValues(0)).toEqual([ [1, 2], - [1, 2], - [noSpace(), null], + [3, 4], + [noSpace()], [null, 'foo'] ]) }) From 07bc372b350718e62e5012aebd16246750b2b458 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 28 May 2021 13:40:48 +0200 Subject: [PATCH 30/87] Replacing matrix should work --- test/cruds/change-cell-content.spec.ts | 46 ++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index f4b48f7660..d816d9d0f4 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -758,7 +758,7 @@ describe('row ranges', () => { }) describe('arrays', () => { - it('should set matrix to cell', () => { + it('should set array to cell', () => { const engine = HyperFormula.buildFromArray([ [1, 2], [3, 4], @@ -772,7 +772,7 @@ describe('arrays', () => { ], {useArrayArithmetic: true})) }) - it('should be REF matrix if no space for result', () => { + it('should be REF array if no space for result', () => { const engine = HyperFormula.buildFromArray([ [], [1], @@ -787,7 +787,7 @@ describe('arrays', () => { ], {useArrayArithmetic: true})) }) - it('should be REF matrix if no space and potential cycle', () => { + it('should be REF array if no space and potential cycle', () => { const engine = HyperFormula.buildFromArray([ [], [1], @@ -802,7 +802,7 @@ describe('arrays', () => { ], {useArrayArithmetic: true})) }) - it('should shrink to one vertex if there is more content colliding with matrix', () => { + it('should shrink to one vertex if there is more content colliding with array', () => { const engine = HyperFormula.buildFromArray([], {useArrayArithmetic: true}) engine.setCellContents(adr('A1'), [ @@ -838,7 +838,7 @@ describe('arrays', () => { expect(engine.getSheetValues(0)) }) - it('should REF last matrix', () => { + it('should REF last array', () => { const engine = HyperFormula.buildFromArray([ [null, null, null, 1, 2], [null, null, null, 1, 2], @@ -862,7 +862,7 @@ describe('arrays', () => { expect(engine.getSheetValues(0)) }) - it('should make existing matrix REF and change cell content', () => { + it('should make existing array REF and change cell content', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], ['3', '4'], @@ -878,4 +878,38 @@ describe('arrays', () => { [null, 'foo'] ]) }) + + it('should make existing matrix REF and set new array', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4'], + ['=-A1:B2'], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('B3'), [['=+A1:B2']]) + + expect(engine.getSheetValues(0)).toEqual([ + [1, 2], + [3, 4], + [noSpace(), 1, 2], + [null, 3, 4] + ]) + }) + + it('should replace one array with another', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4'], + ['=-A1:B2'], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('A3'), [['=2*A1:B2']]) + + expect(engine.getSheetValues(0)).toEqual([ + [1, 2], + [3, 4], + [2, 4], + [6, 8], + ]) + }) }) From 47325c6982c9a6f1e0e4af92a799550475afd5f5 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 28 May 2021 13:47:13 +0200 Subject: [PATCH 31/87] We do not forbid to change cell content any more when there is array --- test/cruds/change-cell-content.spec.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index d816d9d0f4..f39d9b8d4e 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -30,7 +30,7 @@ describe('Changing cell content - checking if its possible', () => { expect(engine.isItPossibleToSetCellContents(adr('A1', 1))).toEqual(false) }) - it('no if in formula matrix', () => { + it('yes if there is an array', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], ['3', '4'], @@ -39,10 +39,10 @@ describe('Changing cell content - checking if its possible', () => { ['13'], ]) - expect(engine.isItPossibleToSetCellContents(adr('A3'))).toBe(false) - expect(engine.isItPossibleToSetCellContents(adr('A3'), 1, 1)).toBe(false) + expect(engine.isItPossibleToSetCellContents(adr('A3'))).toBe(true) + expect(engine.isItPossibleToSetCellContents(adr('A3'), 1, 1)).toBe(true) expect(engine.isItPossibleToSetCellContents(adr('A1'), 2, 2)).toBe(true) - expect(engine.isItPossibleToSetCellContents(adr('A2'), 2, 2)).toBe(false) + expect(engine.isItPossibleToSetCellContents(adr('A2'), 2, 2)).toBe(true) }) it('no if content exceeds sheet size limits', () => { From cf6dde9935e540238889b707ca66d7d701227f33 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 28 May 2021 15:12:43 +0200 Subject: [PATCH 32/87] Remove matrix when removing row with corner --- src/Cell.ts | 4 ++ src/DependencyGraph/DependencyGraph.ts | 21 +++++--- src/DependencyGraph/FormulaCellVertex.ts | 6 ++- .../RemoveRowsTransformer.ts | 2 +- test/cruds/removing-rows.spec.ts | 48 +++++++++++++------ 5 files changed, 59 insertions(+), 22 deletions(-) diff --git a/src/Cell.ts b/src/Cell.ts index b7c38a01f5..419038dc55 100644 --- a/src/Cell.ts +++ b/src/Cell.ts @@ -187,6 +187,10 @@ export const invalidSimpleCellAddress = (address: SimpleCellAddress): boolean => export const movedSimpleCellAddress = (address: SimpleCellAddress, toSheet: number, toRight: number, toBottom: number): SimpleCellAddress => { return simpleCellAddress(toSheet, address.col + toRight, address.row + toBottom) } +export const addressesEqual = (left: SimpleCellAddress, right: SimpleCellAddress) => { + return left.sheet === right.sheet && left.row === right.row && left.col === right.col +} + export const absoluteSheetReference = (address: AddressWithSheet, baseAddress: SimpleCellAddress): number => { return address.sheet === null ? baseAddress.sheet : address.sheet diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 6b69d48748..3b7f99e66d 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -265,12 +265,17 @@ export class DependencyGraph { public removeRows(removedRows: RowsSpan): Set { this.stats.measure(StatType.ADJUSTING_GRAPH, () => { - for (const vertex of this.addressMapping.verticesFromRowsSpan(removedRows)) { + for (const [address, vertex] of this.addressMapping.entriesFromRowsSpan(removedRows)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { this.graph.markNodeAsSpecialRecentlyChanged(adjacentNode) } if (vertex instanceof MatrixVertex) { - continue + if (vertex.isLeftCorner(address)) { + this.shrinkMatrixToCorner(vertex) + this.matrixMapping.removeMatrix(vertex.getRange()) + } else { + continue + } } this.removeVertex(vertex) } @@ -874,7 +879,7 @@ export class DependencyGraph { this.setMatrix(range, vertex) if (!this.isThereSpaceForMatrix(vertex)) { - return + return } for (const address of range.addresses(this)) { @@ -883,7 +888,11 @@ export class DependencyGraph { } private truncateRanges(span: Span, coordinate: (address: SimpleCellAddress) => number): RangeVertex[] { - const {verticesToRemove, verticesToMerge, verticesWithChangedSize} = this.rangeMapping.truncateRanges(span, coordinate) + const { + verticesToRemove, + verticesToMerge, + verticesWithChangedSize + } = this.rangeMapping.truncateRanges(span, coordinate) for (const [existingVertex, mergedVertex] of verticesToMerge) { this.mergeRangeVertices(existingVertex, mergedVertex) } @@ -898,7 +907,7 @@ export class DependencyGraph { if (rowStart <= 0) { return } - for (const [, matrix] of this.matrixMapping.matricesInRows(RowsSpan.fromRowStartAndEnd(sheet, rowStart-1, rowStart-1))) { + for (const [, matrix] of this.matrixMapping.matricesInRows(RowsSpan.fromRowStartAndEnd(sheet, rowStart - 1, rowStart - 1))) { const matrixRange = matrix.getRange() for (let col = matrixRange.start.col; col <= matrixRange.end.col; ++col) { for (let row = rowStart; row <= matrixRange.end.row; ++row) { @@ -915,7 +924,7 @@ export class DependencyGraph { if (rowStart <= 0) { return } - for (const [, matrix] of this.matrixMapping.matricesInRows(RowsSpan.fromRowStartAndEnd(sheet, rowStart-1, rowStart-1))) { + for (const [, matrix] of this.matrixMapping.matricesInRows(RowsSpan.fromRowStartAndEnd(sheet, rowStart - 1, rowStart - 1))) { if (this.isThereSpaceForMatrix(matrix)) { for (const address of matrix.getRange().addresses(this)) { this.addressMapping.setCell(address, matrix) diff --git a/src/DependencyGraph/FormulaCellVertex.ts b/src/DependencyGraph/FormulaCellVertex.ts index e6d2135fc4..4d01b4c8d2 100644 --- a/src/DependencyGraph/FormulaCellVertex.ts +++ b/src/DependencyGraph/FormulaCellVertex.ts @@ -4,7 +4,7 @@ */ import {AbsoluteCellRange} from '../AbsoluteCellRange' -import {CellError, ErrorType, SimpleCellAddress} from '../Cell' +import {addressesEqual, CellError, ErrorType, SimpleCellAddress} from '../Cell' import {RawCellContent} from '../CellContentParser' import {EmptyValue, getRawValue, InternalScalarValue, InterpreterValue} from '../interpreter/InterpreterValue' import {LazilyTransformingAstService} from '../LazilyTransformingAstService' @@ -202,6 +202,10 @@ export class MatrixVertex extends FormulaVertex { * */ ensureRecentData(updatingService: LazilyTransformingAstService) {} + isLeftCorner(address: SimpleCellAddress): boolean { + return addressesEqual(this.cellAddress, address) + } + private setErrorValue(error: CellError) { this.matrix = new ErroredMatrix(error, this.matrix.size) } diff --git a/src/dependencyTransformers/RemoveRowsTransformer.ts b/src/dependencyTransformers/RemoveRowsTransformer.ts index c3842f67b2..a034b8b2bc 100644 --- a/src/dependencyTransformers/RemoveRowsTransformer.ts +++ b/src/dependencyTransformers/RemoveRowsTransformer.ts @@ -142,7 +142,7 @@ export class RemoveRowsTransformer extends Transformer { if (newStart === false && newEnd === false) { return [actualStart, actualEnd] } else if (newStart === ErrorType.REF || newEnd === ErrorType.REF) { - throw Error('Cannot happen') + return ErrorType.REF } else { return [newStart || actualStart, newEnd || actualEnd] } diff --git a/test/cruds/removing-rows.spec.ts b/test/cruds/removing-rows.spec.ts index 93362e00d1..624bdc3af0 100644 --- a/test/cruds/removing-rows.spec.ts +++ b/test/cruds/removing-rows.spec.ts @@ -59,7 +59,7 @@ describe('Removing rows - checking if its possible', () => { expect(engine.isItPossibleToRemoveRows(-Infinity, [0, 1])).toEqual(false) }) - it('no if theres a formula matrix in place where we remove', () => { + it('yes if theres an array in place where we remove', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], ['3', '4'], @@ -68,9 +68,9 @@ describe('Removing rows - checking if its possible', () => { ]) expect(engine.isItPossibleToRemoveRows(0, [1, 1])).toEqual(true) - expect(engine.isItPossibleToRemoveRows(0, [1, 2])).toEqual(false) - expect(engine.isItPossibleToRemoveRows(0, [2, 1])).toEqual(false) - expect(engine.isItPossibleToRemoveRows(0, [3, 1])).toEqual(false) + expect(engine.isItPossibleToRemoveRows(0, [1, 2])).toEqual(true) + expect(engine.isItPossibleToRemoveRows(0, [2, 1])).toEqual(true) + expect(engine.isItPossibleToRemoveRows(0, [3, 1])).toEqual(true) expect(engine.isItPossibleToRemoveRows(0, [4, 1])).toEqual(true) }) @@ -549,16 +549,6 @@ describe('Removing rows - reevaluation', () => { }) describe('Removing rows - arrays', () => { - it('should not remove row with formula matrix', () => { - const engine = HyperFormula.buildFromArray([ - ['1', '2'], - ['3', '4'], - ['=MMULT(A1:B2, A1:B2)'], - ]) - - expect(() => engine.removeRows(0, [2, 1])).toThrowError('Cannot perform this operation, source location has a matrix inside.') - }) - it('MatrixVertex#formula should be updated', () => { const engine = HyperFormula.buildFromArray([ ['1', '4'], @@ -706,6 +696,36 @@ describe('Removing rows - arrays', () => { ], {useArrayArithmetic: true}) expectEngineToBeTheSameAs(engine, expected) }) + + it('it should remove array when removing row with left corner', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4'], + ['=MMULT(A1:B2, A1:B2)'], + ]) + + engine.removeRows(0, [2, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4] + ])) + }) + + it('it should remove array when removing rows with whole matrix', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4'], + ['=MMULT(A1:B2, A1:B2)'], + ]) + + engine.removeRows(0, [2, 2]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4] + ])) + }) }) describe('Removing rows - graph', function() { From 8fccdbdfda364350e6040276777710246924c8ae Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 28 May 2021 16:28:29 +0200 Subject: [PATCH 33/87] Do not change size of a REFed matrix --- src/DependencyGraph/DependencyGraph.ts | 24 ++++++++++++++++-------- src/DependencyGraph/FormulaCellVertex.ts | 5 +++++ src/Operations.ts | 2 -- test/cruds/change-cell-content.spec.ts | 4 ++-- 4 files changed, 23 insertions(+), 12 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 3b7f99e66d..c1ae71c3d7 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -100,8 +100,7 @@ export class DependencyGraph { } public setParsingErrorToCell(address: SimpleCellAddress, errorVertex: ParsingErrorVertex) { - const vertex = this.addressMapping.getCell(address) - this.setNoSpaceIfMatrix(vertex) + const vertex = this.shrinkPossibleMatrixAndGetCell(address) this.exchangeOrAddGraphNode(vertex, errorVertex) this.addressMapping.setCell(address, errorVertex) this.graph.markNodeAsSpecialRecentlyChanged(errorVertex) @@ -109,8 +108,7 @@ export class DependencyGraph { } public setValueToCell(address: SimpleCellAddress, value: RawAndParsedValue) { - const vertex = this.addressMapping.getCell(address) - this.setNoSpaceIfMatrix(vertex) + const vertex = this.shrinkPossibleMatrixAndGetCell(address) if (vertex instanceof ValueCellVertex) { const oldValue = vertex.getValues() @@ -129,12 +127,10 @@ export class DependencyGraph { } public setCellEmpty(address: SimpleCellAddress) { - const vertex = this.addressMapping.getCell(address) - this.setNoSpaceIfMatrix(vertex) + const vertex = this.shrinkPossibleMatrixAndGetCell(address) if (vertex === null) { return } - if (this.graph.adjacentNodes(vertex).size > 0) { const emptyVertex = new EmptyCellVertex(address) this.exchangeGraphNode(vertex, emptyVertex) @@ -935,10 +931,22 @@ export class DependencyGraph { } } + private shrinkPossibleMatrixAndGetCell(address: SimpleCellAddress): CellVertex | null { + const vertex = this.getCell(address) + if (!(vertex instanceof MatrixVertex)) { + return vertex + } + this.setNoSpaceIfMatrix(vertex) + if (vertex.isLeftCorner(address)) { + return vertex + } + return null + } + private setNoSpaceIfMatrix(vertex: Vertex | null) { if (vertex instanceof MatrixVertex) { this.shrinkMatrixToCorner(vertex) - vertex.setNoSpace() + vertex.setNoSpaceButPreserveSize() } } diff --git a/src/DependencyGraph/FormulaCellVertex.ts b/src/DependencyGraph/FormulaCellVertex.ts index 4d01b4c8d2..bf4ab03a2d 100644 --- a/src/DependencyGraph/FormulaCellVertex.ts +++ b/src/DependencyGraph/FormulaCellVertex.ts @@ -161,6 +161,11 @@ export class MatrixVertex extends FormulaVertex { return this.getCellValue() } + setNoSpaceButPreserveSize(): InterpreterValue { + this.matrix = new ErroredMatrix(new CellError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult), this.matrix.size) + return this.getCellValue() + } + getRange(): AbsoluteCellRange { return AbsoluteCellRange.spanFrom(this.cellAddress, this.width, this.height) } diff --git a/src/Operations.ts b/src/Operations.ts index 79bb7fbd33..c1edea0bf3 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -642,8 +642,6 @@ export class Operations { public setCellContent(address: SimpleCellAddress, newCellContent: RawCellContent): void { const parsedCellContent = this.cellContentParser.parse(newCellContent) - const vertex = this.dependencyGraph.getCell(address) - if (parsedCellContent instanceof CellContent.Formula) { const { ast, diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index f39d9b8d4e..b7f11f28b5 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -806,8 +806,8 @@ describe('arrays', () => { const engine = HyperFormula.buildFromArray([], {useArrayArithmetic: true}) engine.setCellContents(adr('A1'), [ - ['=-C1:D2', null], - [1, null] + ['=-C1:D2'], + [1] ]) expect(engine.matrixMapping.getMatrixByCorner(adr('A1'))?.matrix.size).toEqual(MatrixSize.error()) From 6ab5d195eaf8e76cba1fc94f060078b52ba22758 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 28 May 2021 17:31:09 +0200 Subject: [PATCH 34/87] Test for references --- test/cruds/change-cell-content.spec.ts | 49 +++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index b7f11f28b5..1afbc846b6 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -862,10 +862,10 @@ describe('arrays', () => { expect(engine.getSheetValues(0)) }) - it('should make existing array REF and change cell content', () => { + it('should make existing array REF and change cell content to simple value', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], - ['3', '4'], + ['3', '4', '=B4'], ['=-A1:B2'], ], {useArrayArithmetic: true}) @@ -873,16 +873,55 @@ describe('arrays', () => { expect(engine.getSheetValues(0)).toEqual([ [1, 2], - [3, 4], + [3, 4, 'foo'], [noSpace()], [null, 'foo'] ]) }) + it('should make existing array REF and change cell content empty', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4', '=B4'], + ['=-A1:B2'], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('B4'), [[null]]) + + expect(engine.getSheetValues(0)).toEqual([ + [1, 2], + [3, 4], + [noSpace()], + ]) + }) + + it('should make existing array REF and change cell content to formula', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4', '=B4'], + ['=-A1:B2'], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('B4'), [['=SUM(A1:B2)']]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4, 10], + ['=-A1:B2'], + [null, 10] + ], {useArrayArithmetic: true})) + expect(engine.getSheetValues(0)).toEqual([ + [1, 2], + [3, 4, 10], + [noSpace()], + [null, 10] + ]) + }) + it('should make existing matrix REF and set new array', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], - ['3', '4'], + ['3', '4', '=B4'], ['=-A1:B2'], ], {useArrayArithmetic: true}) @@ -890,7 +929,7 @@ describe('arrays', () => { expect(engine.getSheetValues(0)).toEqual([ [1, 2], - [3, 4], + [3, 4, 3], [noSpace(), 1, 2], [null, 3, 4] ]) From 07f401a27d7fbbca0512796e251d6d17335f6f8c Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 28 May 2021 17:59:04 +0200 Subject: [PATCH 35/87] Add test specially for dep correction --- test/cruds/change-cell-content.spec.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 1afbc846b6..52713be2c2 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -951,4 +951,18 @@ describe('arrays', () => { [6, 8], ]) }) + + it('should handle dependent vertices after shrinking array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, 3, '=-A1:C1'], + ['=C1', '=D1', '=SUM(E1:E1)'], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('E1'), [[null]]) + engine.setCellContents(adr('D1'), [[4, 5, 6]]) + + expect(engine.getCellValue(adr('A2'))).toEqual(4) + expect(engine.getCellValue(adr('B2'))).toEqual(5) + expect(engine.getCellValue(adr('C2'))).toEqual(6) + }) }) From 50677ca09cf7801d119dfeae501568b6672657e2 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 29 May 2021 12:06:26 +0200 Subject: [PATCH 36/87] Compare only ref flag --- test/graphComparator.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/graphComparator.ts b/test/graphComparator.ts index e83ffa9aa7..216e0f397a 100644 --- a/test/graphComparator.ts +++ b/test/graphComparator.ts @@ -98,7 +98,7 @@ export class EngineComparator { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const actualEntry = actual.get(key)! expect(actualEntry).toBeDefined() - expect(value.getRange().sameAs(actualEntry.getRange())).toBe(true) + expect(actualEntry.matrix.size.isRef).toBe(value.matrix.size.isRef) } } From 7f55fec191840f2ce3a41a31bc449400e88e7a96 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Mon, 31 May 2021 08:32:27 +0200 Subject: [PATCH 37/87] Fix adjusting edges --- src/AbsoluteCellRange.ts | 14 ++- src/DependencyGraph/DependencyGraph.ts | 114 +++++++++++++++++++---- src/DependencyGraph/FormulaCellVertex.ts | 6 +- test/cruds/change-cell-content.spec.ts | 19 +++- 4 files changed, 123 insertions(+), 30 deletions(-) diff --git a/src/AbsoluteCellRange.ts b/src/AbsoluteCellRange.ts index bd8e119913..5ccc16d673 100644 --- a/src/AbsoluteCellRange.ts +++ b/src/AbsoluteCellRange.ts @@ -75,8 +75,8 @@ export class AbsoluteCellRange { } public static singleRangeFromCellAddress(cellAddress: CellAddress, baseAddress: SimpleCellAddress): AbsoluteCellRange { - const simpleCellAddress = cellAddress.toSimpleCellAddress(baseAddress) - return new AbsoluteCellRange(simpleCellAddress, simpleCellAddress) + const absoluteAddress = cellAddress.toSimpleCellAddress(baseAddress) + return new AbsoluteCellRange(absoluteAddress, absoluteAddress) } constructor( @@ -112,12 +112,10 @@ export class AbsoluteCellRange { return false } - if (this.start.row <= address.row && this.end.row >= address.row - && this.start.col <= address.col && this.end.col >= address.col) { - return true - } - - return false + return this.start.row <= address.row + && this.end.row >= address.row + && this.start.col <= address.col + && this.end.col >= address.col } public columnInRange(address: SimpleColumnAddress): boolean { diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index c1ae71c3d7..2ba9519e56 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -5,7 +5,7 @@ import {AbsoluteCellRange} from '../AbsoluteCellRange' import {absolutizeDependencies} from '../absolutizeDependencies' -import {CellError, ErrorType, simpleCellAddress, SimpleCellAddress} from '../Cell' +import {CellError, equalSimpleCellAddress, ErrorType, simpleCellAddress, SimpleCellAddress} from '../Cell' import {RawCellContent} from '../CellContentParser' import {CellDependency} from '../CellDependency' import {Config} from '../Config' @@ -85,9 +85,6 @@ export class DependencyGraph { public setFormulaToCell(address: SimpleCellAddress, ast: Ast, dependencies: CellDependency[], size: MatrixSize, hasVolatileFunction: boolean, hasStructuralChangeFunction: boolean) { const newVertex = FormulaVertex.fromAst(ast, address, size, this.lazilyTransformingAstService.version()) this.exchangeOrAddFormulaVertex(newVertex) - - this.addressMapping.setCell(address, newVertex) - this.processCellDependencies(dependencies, newVertex) this.graph.markNodeAsSpecialRecentlyChanged(newVertex) if (hasVolatileFunction) { @@ -110,6 +107,9 @@ export class DependencyGraph { public setValueToCell(address: SimpleCellAddress, value: RawAndParsedValue) { const vertex = this.shrinkPossibleMatrixAndGetCell(address) + if (vertex instanceof MatrixVertex) { + this.matrixMapping.removeMatrix(vertex.getRange()) + } if (vertex instanceof ValueCellVertex) { const oldValue = vertex.getValues() if (oldValue.rawValue !== value.rawValue) { @@ -428,7 +428,7 @@ export class DependencyGraph { public isThereSpaceForMatrix(matrixVertex: MatrixVertex): boolean { for (const address of matrixVertex.getRange().addresses(this)) { const vertexUnderAddress = this.addressMapping.getCell(address) - if (vertexUnderAddress !== null && vertexUnderAddress !== matrixVertex) { + if (vertexUnderAddress !== null && !(vertexUnderAddress instanceof EmptyCellVertex) && vertexUnderAddress !== matrixVertex) { return false } } @@ -739,12 +739,88 @@ export class DependencyGraph { return values } - public shrinkMatrixToCorner(vertex: MatrixVertex) { + public shrinkMatrixToCorner(matrix: MatrixVertex) { + this.cleanAddressMappingUnderMatrix(matrix) + for (const adjacentVertex of this.adjacentFormulas(matrix)) { + let relevantDependencies + if (adjacentVertex instanceof FormulaVertex) { + relevantDependencies = this.formulaDependenciesToMatrix(adjacentVertex, matrix) + } else { + relevantDependencies = this.rangeDependenciesToMatrix(adjacentVertex, matrix) + } + let dependentToCorner = false + for (const [address, vertex] of relevantDependencies) { + if (matrix.isLeftCorner(address)) { + dependentToCorner = true + } + this.graph.addEdge(vertex, adjacentVertex) + this.graph.markNodeAsSpecialRecentlyChanged(vertex) + } + if (!dependentToCorner) { + this.graph.removeEdge(matrix, adjacentVertex) + } + } + } + + private cleanAddressMappingUnderMatrix(vertex: MatrixVertex) { const matrixRange = vertex.getRange() for (const address of matrixRange.addresses(this)) { - this.addressMapping.removeCellIfEqual(address, vertex) + if (!vertex.isLeftCorner(address)) { + this.addressMapping.removeCellIfEqual(address, vertex) + } + } + } + + private* rangeDependenciesToMatrix(range: RangeVertex, matrix: MatrixVertex): IterableIterator<[SimpleCellAddress, CellVertex]> { + for (const [address, vertex] of this.rangeDependencyQuery2(range)) { + if (matrix.getRange().addressInRange(address)) { + yield [address, vertex] + } + } + } + + private* formulaDependenciesToMatrix(vertex: FormulaVertex, matrix: MatrixVertex): IterableIterator<[SimpleCellAddress, CellVertex]> { + const [, formulaDependencies] = this.formulaDependencyQuery(vertex) ?? [] + if (formulaDependencies === undefined) { + return + } + for (const dependency of formulaDependencies) { + if (dependency instanceof NamedExpressionDependency || dependency instanceof AbsoluteCellRange) { + continue + } + if (matrix.getRange().addressInRange(dependency)) { + const vertex = this.fetchCellOrCreateEmpty(dependency) + yield [dependency, vertex] + } + } + } + + private* adjacentFormulas(vertex: Vertex): IterableIterator { + const adjacentNodes = this.graph.adjacentNodes(vertex) + for (const item of adjacentNodes) { + if (item instanceof FormulaVertex || item instanceof RangeVertex) { + yield item + } } - this.addressMapping.setCell(matrixRange.start, vertex) + } + + private rangeDependencyQuery2 = (vertex: RangeVertex) => { + const allDeps: [SimpleCellAddress, CellVertex][] = [] + const {smallerRangeVertex, restRange} = this.rangeMapping.findSmallerRange(vertex.range) //checking whether this range was splitted by bruteForce or not + let range + if (smallerRangeVertex !== null && this.graph.adjacentNodes(smallerRangeVertex).has(vertex)) { + range = restRange + } else { //did we ever need to use full range + range = vertex.range + } + for (const address of range.addresses(this)) { + const cell = this.fetchCellOrCreateEmpty(address) + if (cell instanceof EmptyCellVertex) { + cell.address = address + } + allDeps.push([address, cell]) + } + return allDeps } private rangeDependencyQuery = (vertex: RangeVertex) => { @@ -846,17 +922,24 @@ export class DependencyGraph { private exchangeOrAddFormulaVertex(vertex: FormulaVertex): void { const address = vertex.getAddress(this.lazilyTransformingAstService) const range = AbsoluteCellRange.spanFrom(address, vertex.width, vertex.height) - const oldNode = this.getCell(address) - + const oldNode = this.shrinkPossibleMatrixAndGetCell(address) if (vertex instanceof MatrixVertex) { this.setMatrix(range, vertex) } - this.setNoSpaceIfMatrix(oldNode) this.exchangeOrAddGraphNode(oldNode, vertex) this.addressMapping.setCell(address, vertex) - if (vertex instanceof MatrixVertex && !this.isThereSpaceForMatrix(vertex)) { - return + if (vertex instanceof MatrixVertex) { + if (!this.isThereSpaceForMatrix(vertex)) { + return + } + for (const cellAddress of range.addresses(this)) { + if (vertex.isLeftCorner(cellAddress)) { + continue + } + const old = this.getCell(cellAddress) + this.exchangeOrAddGraphNode(old, vertex) + } } for (const cellAddress of range.addresses(this)) { @@ -937,10 +1020,7 @@ export class DependencyGraph { return vertex } this.setNoSpaceIfMatrix(vertex) - if (vertex.isLeftCorner(address)) { - return vertex - } - return null + return this.getCell(address) } private setNoSpaceIfMatrix(vertex: Vertex | null) { diff --git a/src/DependencyGraph/FormulaCellVertex.ts b/src/DependencyGraph/FormulaCellVertex.ts index bf4ab03a2d..c5556f3a09 100644 --- a/src/DependencyGraph/FormulaCellVertex.ts +++ b/src/DependencyGraph/FormulaCellVertex.ts @@ -103,6 +103,10 @@ export class MatrixVertex extends FormulaVertex { return this.cellAddress.sheet } + get leftCorner(): SimpleCellAddress { + return this.cellAddress + } + setCellValue(value: InterpreterValue): InterpreterValue { if (value instanceof CellError) { this.setErrorValue(value) @@ -162,7 +166,7 @@ export class MatrixVertex extends FormulaVertex { } setNoSpaceButPreserveSize(): InterpreterValue { - this.matrix = new ErroredMatrix(new CellError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult), this.matrix.size) + this.matrix = new ErroredMatrix(new CellError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult), new MatrixSize(this.width, this.height, true)) return this.getCellValue() } diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 52713be2c2..d36d82da82 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -906,9 +906,9 @@ describe('arrays', () => { expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ [1, 2], - [3, 4, 10], + [3, 4, '=B4'], ['=-A1:B2'], - [null, 10] + [null, '=SUM(A1:B2)'] ], {useArrayArithmetic: true})) expect(engine.getSheetValues(0)).toEqual([ [1, 2], @@ -954,15 +954,26 @@ describe('arrays', () => { it('should handle dependent vertices after shrinking array', () => { const engine = HyperFormula.buildFromArray([ - [1, 2, 3, '=-A1:C1'], - ['=C1', '=D1', '=SUM(E1:E1)'], + [1, 2, 3, '=-A1:C1', null, null, 4], + ['=D1', '=E1', '=SUM(F1:F1)', '=SUM(F1:G1)'], ], {useArrayArithmetic: true}) + expect(engine.getCellValue(adr('A2'))).toEqual(-1) + expect(engine.getCellValue(adr('B2'))).toEqual(-2) + expect(engine.getCellValue(adr('C2'))).toEqual(-3) + expect(engine.getCellValue(adr('D2'))).toEqual(1) + engine.setCellContents(adr('E1'), [[null]]) engine.setCellContents(adr('D1'), [[4, 5, 6]]) + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2, 3, 4, 5, 6, 4], + ['=D1', '=E1', '=SUM(F1:F1)', '=SUM(F1:G1)'] + ], {useArrayArithmetic: true})) + expect(engine.getCellValue(adr('A2'))).toEqual(4) expect(engine.getCellValue(adr('B2'))).toEqual(5) expect(engine.getCellValue(adr('C2'))).toEqual(6) + expect(engine.getCellValue(adr('D2'))).toEqual(10) }) }) From 51894a974e811ff2e6c43682e17e2ea820d05416 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 4 Jun 2021 09:52:29 +0200 Subject: [PATCH 38/87] Skipped test for later --- test/cruds/change-cell-content.spec.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index d36d82da82..0b2d955d9e 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -976,4 +976,17 @@ describe('arrays', () => { expect(engine.getCellValue(adr('C2'))).toEqual(6) expect(engine.getCellValue(adr('D2'))).toEqual(10) }) + + it.skip('should recalculate matrix if space is available', () => { + const engine = HyperFormula.buildFromArray([ + ['=+C1:D1', 'foo', 1, 2] + ], {useArrayArithmetic: true}) + expect(engine.getCellValue(adr('A1'))).toEqual(noSpace()) + + engine.setCellContents(adr('B1'), null) + + expect(engine.getSheetValues(0)).toEqual([ + [1, 2, 1, 2] + ]) + }) }) From 62990504255c9d65a4e7c1b27a9f6d8695eb34c6 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 4 Jun 2021 09:52:41 +0200 Subject: [PATCH 39/87] just setNoSpace() --- src/DependencyGraph/DependencyGraph.ts | 2 +- src/DependencyGraph/FormulaCellVertex.ts | 5 ----- src/Evaluator.ts | 2 +- 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 2ba9519e56..cbc7b097d5 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -1026,7 +1026,7 @@ export class DependencyGraph { private setNoSpaceIfMatrix(vertex: Vertex | null) { if (vertex instanceof MatrixVertex) { this.shrinkMatrixToCorner(vertex) - vertex.setNoSpaceButPreserveSize() + vertex.setNoSpace() } } diff --git a/src/DependencyGraph/FormulaCellVertex.ts b/src/DependencyGraph/FormulaCellVertex.ts index c5556f3a09..7cbbf3ca8f 100644 --- a/src/DependencyGraph/FormulaCellVertex.ts +++ b/src/DependencyGraph/FormulaCellVertex.ts @@ -165,11 +165,6 @@ export class MatrixVertex extends FormulaVertex { return this.getCellValue() } - setNoSpaceButPreserveSize(): InterpreterValue { - this.matrix = new ErroredMatrix(new CellError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult), new MatrixSize(this.width, this.height, true)) - return this.getCellValue() - } - getRange(): AbsoluteCellRange { return AbsoluteCellRange.spanFrom(this.cellAddress, this.width, this.height) } diff --git a/src/Evaluator.ts b/src/Evaluator.ts index 0c3c12f680..6ce83cca25 100644 --- a/src/Evaluator.ts +++ b/src/Evaluator.ts @@ -140,7 +140,7 @@ export class Evaluator { private recomputeFormulaVertexValue(vertex: FormulaVertex): InterpreterValue { const address = vertex.getAddress(this.lazilyTransformingAstService) - if (vertex instanceof MatrixVertex && !this.dependencyGraph.isThereSpaceForMatrix(vertex)) { + if (vertex instanceof MatrixVertex && (vertex.matrix.size.isRef || !this.dependencyGraph.isThereSpaceForMatrix(vertex))) { return vertex.setNoSpace() } else { const formula = vertex.getFormula(this.lazilyTransformingAstService) From b3c8f8ed4568974f60cedb26d6fdccd4ae9c65a9 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 4 Jun 2021 14:00:13 +0200 Subject: [PATCH 40/87] Test for undo redo and changes --- test/cruds/change-cell-content.spec.ts | 42 ++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 0b2d955d9e..5f576b0871 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -1,5 +1,5 @@ -import {ExportedCellChange, HyperFormula, InvalidAddressError, NoSheetWithIdError} from '../../src' -import {ErrorType, simpleCellAddress} from '../../src/Cell' +import {ErrorType, ExportedCellChange, HyperFormula, InvalidAddressError, NoSheetWithIdError} from '../../src' +import {simpleCellAddress} from '../../src/Cell' import {Config} from '../../src/Config' import {EmptyCellVertex, MatrixVertex, ValueCellVertex} from '../../src/DependencyGraph' import {ErrorMessage} from '../../src/error-message' @@ -11,7 +11,9 @@ import { colStart, detailedError, expectArrayWithSameContent, - expectEngineToBeTheSameAs, expectVerticesOfTypes, noSpace, + expectEngineToBeTheSameAs, + expectVerticesOfTypes, + noSpace, rowEnd, rowStart } from '../testUtils' @@ -977,6 +979,40 @@ describe('arrays', () => { expect(engine.getCellValue(adr('D2'))).toEqual(10) }) + it('should return REF in changes', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, 3, '=-A1:C1'], + ], {useArrayArithmetic: true}) + + const changes = engine.setCellContents(adr('E1'), [[null]]) + + expect(changes).toContainEqual(new ExportedCellChange(adr('D1'), noSpace())) + expect(changes).toContainEqual(new ExportedCellChange(adr('E1'), null)) + expect(changes).toContainEqual(new ExportedCellChange(adr('F1'), null)) + }) + + it('should undo REF', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, 3, '=-A1:C1', null, null, 4], + ['=D1', '=E1', '=SUM(F1:F1)', '=SUM(F1:G1)'], + ], {useArrayArithmetic: true}) + engine.setCellContents(adr('E1'), [[null]]) + engine.setCellContents(adr('D1'), [[4, 5, 6]]) + + engine.undo() + engine.undo() + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2, 3, '=-A1:C1', null, null, 4], + ['=D1', '=E1', '=SUM(F1:F1)', '=SUM(F1:G1)'], + ], {useArrayArithmetic: true})) + + expect(engine.getCellValue(adr('A2'))).toEqual(-1) + expect(engine.getCellValue(adr('B2'))).toEqual(-2) + expect(engine.getCellValue(adr('C2'))).toEqual(-3) + expect(engine.getCellValue(adr('D2'))).toEqual(1) + }) + it.skip('should recalculate matrix if space is available', () => { const engine = HyperFormula.buildFromArray([ ['=+C1:D1', 'foo', 1, 2] From b70c2d743f808541e3eb88b9fc1e3462c072825a Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 4 Jun 2021 18:20:10 +0200 Subject: [PATCH 41/87] Keep changes with old content in map --- src/ContentChanges.ts | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/ContentChanges.ts b/src/ContentChanges.ts index d97a5b7e3c..6a30ae77a0 100644 --- a/src/ContentChanges.ts +++ b/src/ContentChanges.ts @@ -3,14 +3,16 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from './Cell' +import {simpleCellAddress, SimpleCellAddress} from './Cell' import {InterpreterValue} from './interpreter/InterpreterValue' +import {ClipboardCell} from './ClipboardOperations' export interface CellValueChange { sheet: number, row: number, col: number, value: InterpreterValue, + oldValue?: ClipboardCell, } export interface ChangeExporter { @@ -25,19 +27,27 @@ export class ContentChanges { return new ContentChanges() } - private changes: ChangeList = [] + private changes: Map = new Map() public addAll(other: ContentChanges): ContentChanges { - this.changes.push(...other.changes) + for (const [key, value] of other.changes.entries()) { + this.changes.set(key, value) + } return this } + public addChangeWithOldValue(newValue: InterpreterValue, oldValue: ClipboardCell, address: SimpleCellAddress): void { + this.addSingleCellValue(newValue, address, oldValue) + } + public addChange(newValue: InterpreterValue, address: SimpleCellAddress): void { this.addSingleCellValue(newValue, address) } - public add(...change: ChangeList) { - this.changes.push(...change) + public add(...changes: ChangeList) { + for (const change of changes) { + this.changes.set(simpleCellAddress(change.sheet, change.col, change.row), change) + } } public exportChanges(exporter: ChangeExporter): T[] { @@ -54,19 +64,20 @@ export class ContentChanges { } public getChanges(): ChangeList { - return this.changes + return Array.from(this.changes.values()) } public isEmpty(): boolean { - return this.changes.length === 0 + return this.changes.size === 0 } - private addSingleCellValue(value: InterpreterValue, address: SimpleCellAddress) { + private addSingleCellValue(value: InterpreterValue, address: SimpleCellAddress, oldValue?: ClipboardCell) { this.add({ sheet: address.sheet, col: address.col, row: address.row, value, + oldValue }) } } From 5091a07b4ea4fd96f723b1ed63600abd33a0a1aa Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 10:07:10 +0200 Subject: [PATCH 42/87] Ensure range content changes are properly exported --- src/ContentChanges.ts | 2 +- test/cruds/change-cell-content.spec.ts | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/ContentChanges.ts b/src/ContentChanges.ts index 6a30ae77a0..379eec0a06 100644 --- a/src/ContentChanges.ts +++ b/src/ContentChanges.ts @@ -44,7 +44,7 @@ export class ContentChanges { this.addSingleCellValue(newValue, address) } - public add(...changes: ChangeList) { + private add(...changes: ChangeList) { for (const change of changes) { this.changes.set(simpleCellAddress(change.sheet, change.col, change.row), change) } diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 5f576b0871..43a6acad78 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -979,6 +979,16 @@ describe('arrays', () => { expect(engine.getCellValue(adr('D2'))).toEqual(10) }) + it('should return values of a range in changes', () => { + const engine = HyperFormula.buildFromArray([[1, 2]], { useArrayArithmetic: true}) + + const changes = engine.setCellContents(adr('A2'), [['=-A1:B1']]) + + expect(changes.length).toEqual(2) + expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), -1)) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), -2)) + }) + it('should return REF in changes', () => { const engine = HyperFormula.buildFromArray([ [1, 2, 3, '=-A1:C1'], From 86f9e31268e5efdf753e9fc9b86d401c51d656a9 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 10:27:26 +0200 Subject: [PATCH 43/87] More specs --- test/cruds/change-cell-content.spec.ts | 82 ++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 43a6acad78..90a83e5973 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -989,6 +989,88 @@ describe('arrays', () => { expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), -2)) }) + it('should return changed content when replacing array left corner', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['=-A1:B1'], + ], { useArrayArithmetic: true}) + + const changes = engine.setCellContents(adr('A2'), [['foo']]) + + expect(changes.length).toEqual(2) + expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), 'foo')) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), null)) + }) + + it('should return changed content when replacing any array cell', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2', '3'], + ['=-A1:C1'], + ], { useArrayArithmetic: true}) + + const changes = engine.setCellContents(adr('B2'), [['foo']]) + + console.log(engine.getSheetValues(0)) + + expect(changes.length).toEqual(3) + expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), noSpace())) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), 'foo')) + expect(changes).toContainEqual(new ExportedCellChange(adr('C2'), null)) + }) + + it('should return changed content when clearing array left corner', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['=-A1:B1'], + ], { useArrayArithmetic: true}) + + const changes = engine.setCellContents(adr('A2'), [[null]]) + + expect(changes.length).toEqual(2) + expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), null)) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), null)) + }) + + it('should return changed content when clearing any array cell', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['=-A1:B1'], + ], { useArrayArithmetic: true}) + + const changes = engine.setCellContents(adr('B2'), [[null]]) + + expect(changes.length).toEqual(2) + expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), null)) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), null)) + }) + + it('should return changed content when replacing array to smaller one', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2', '3'], + ['=-A1:C1'], + ], { useArrayArithmetic: true}) + + const changes = engine.setCellContents(adr('A2'), [['=-A1:B1']]) + + expect(changes.length).toEqual(1) + expect(changes).toContainEqual(new ExportedCellChange(adr('C2'), null)) + }) + + it('should return changed content when replacing array to another smaller one', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2', '3'], + ['=-A1:C1'], + ], { useArrayArithmetic: true}) + + const changes = engine.setCellContents(adr('A2'), [['=+A1:B1']]) + + expect(changes.length).toEqual(3) + expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), 1)) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), 2)) + expect(changes).toContainEqual(new ExportedCellChange(adr('C2'), null)) + }) + + it('should return REF in changes', () => { const engine = HyperFormula.buildFromArray([ [1, 2, 3, '=-A1:C1'], From c5b456f26de3fbd91de93dbcfb6fbc73a2af1f6a Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 11:24:38 +0200 Subject: [PATCH 44/87] Use string key in ContentChanges --- src/ContentChanges.ts | 5 ++--- test/content-changes.spec.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/ContentChanges.ts b/src/ContentChanges.ts index 379eec0a06..0fd2af02f2 100644 --- a/src/ContentChanges.ts +++ b/src/ContentChanges.ts @@ -22,12 +22,11 @@ export interface ChangeExporter { export type ChangeList = CellValueChange[] export class ContentChanges { - public static empty() { return new ContentChanges() } - private changes: Map = new Map() + private changes: Map = new Map() public addAll(other: ContentChanges): ContentChanges { for (const [key, value] of other.changes.entries()) { @@ -46,7 +45,7 @@ export class ContentChanges { private add(...changes: ChangeList) { for (const change of changes) { - this.changes.set(simpleCellAddress(change.sheet, change.col, change.row), change) + this.changes.set(`${change.sheet},${change.col},${change.row}`, change) } } diff --git a/test/content-changes.spec.ts b/test/content-changes.spec.ts index a242d265f8..7b07fa680d 100644 --- a/test/content-changes.spec.ts +++ b/test/content-changes.spec.ts @@ -32,6 +32,17 @@ describe('ContentChanges', () => { expect(contentChanges.isEmpty()).toEqual(true) }) + it('should replace simple value change', () => { + const contentChanges = ContentChanges.empty() + + contentChanges.addChange(1, adr('A1')) + contentChanges.addChange(2, adr('A1')) + + const exportedChanges = contentChanges.exportChanges(identityChangeExporter) + expect(exportedChanges.length).toEqual(1) + expect(exportedChanges).toContainEqual({ sheet: 0, col: 0, row: 0, value: 2}) + }) + it('should export simple value change', () => { const contentChanges = ContentChanges.empty() From 1d2527d218d648fc2c4c82cacd7f46a0abf5714a Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 11:28:21 +0200 Subject: [PATCH 45/87] Gather changes from dependency graph --- .../AddressMapping/AddressMapping.ts | 6 ----- src/DependencyGraph/DependencyGraph.ts | 22 +++++++++++++++---- src/Operations.ts | 3 ++- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/DependencyGraph/AddressMapping/AddressMapping.ts b/src/DependencyGraph/AddressMapping/AddressMapping.ts index b9a251b289..e22c574cb6 100644 --- a/src/DependencyGraph/AddressMapping/AddressMapping.ts +++ b/src/DependencyGraph/AddressMapping/AddressMapping.ts @@ -125,12 +125,6 @@ export class AddressMapping { sheetMapping.removeCell(address) } - public removeCellIfEqual(address: SimpleCellAddress, vertex: CellVertex) { - if (this.getCell(address) === vertex) { - this.removeCell(address) - } - } - /** @inheritDoc */ public has(address: SimpleCellAddress): boolean { const sheetMapping = this.mapping.get(address.sheet) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index cbc7b097d5..6fddabe85a 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -5,7 +5,7 @@ import {AbsoluteCellRange} from '../AbsoluteCellRange' import {absolutizeDependencies} from '../absolutizeDependencies' -import {CellError, equalSimpleCellAddress, ErrorType, simpleCellAddress, SimpleCellAddress} from '../Cell' +import {CellError, ErrorType, simpleCellAddress, SimpleCellAddress} from '../Cell' import {RawCellContent} from '../CellContentParser' import {CellDependency} from '../CellDependency' import {Config} from '../Config' @@ -44,7 +44,7 @@ import {MatrixMapping} from './MatrixMapping' import {RangeMapping} from './RangeMapping' import {SheetMapping} from './SheetMapping' import {RawAndParsedValue} from './ValueCellVertex' -import {Matrix} from '../Matrix' +import {ContentChanges} from '../ContentChanges' export class DependencyGraph { /* @@ -67,6 +67,8 @@ export class DependencyGraph { ) } + private changes: ContentChanges = ContentChanges.empty() + public readonly graph: Graph constructor( @@ -104,7 +106,7 @@ export class DependencyGraph { this.correctInfiniteRangesDependency(address) } - public setValueToCell(address: SimpleCellAddress, value: RawAndParsedValue) { + public setValueToCell(address: SimpleCellAddress, value: RawAndParsedValue): ContentChanges { const vertex = this.shrinkPossibleMatrixAndGetCell(address) if (vertex instanceof MatrixVertex) { @@ -124,6 +126,8 @@ export class DependencyGraph { } this.correctInfiniteRangesDependency(address) + + return this.getAndClearContentChanges() } public setCellEmpty(address: SimpleCellAddress) { @@ -760,13 +764,17 @@ export class DependencyGraph { this.graph.removeEdge(matrix, adjacentVertex) } } + this.graph.markNodeAsSpecialRecentlyChanged(matrix) } private cleanAddressMappingUnderMatrix(vertex: MatrixVertex) { const matrixRange = vertex.getRange() for (const address of matrixRange.addresses(this)) { if (!vertex.isLeftCorner(address)) { - this.addressMapping.removeCellIfEqual(address, vertex) + if (this.getCell(address) === vertex) { + this.addressMapping.removeCell(address) + this.changes.addChange(EmptyValue, address) + } } } } @@ -1067,6 +1075,12 @@ export class DependencyGraph { } } + public getAndClearContentChanges(): ContentChanges { + const changes = this.changes + this.changes = ContentChanges.empty() + return changes + } + public getAdjacentNodesAddresses(inputVertex: Vertex): (AbsoluteCellRange | SimpleCellAddress)[] { const deps = this.graph.adjacentNodes(inputVertex) const ret: (AbsoluteCellRange | SimpleCellAddress)[] = [] diff --git a/src/Operations.ts b/src/Operations.ts index c1edea0bf3..7176a19833 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -675,8 +675,9 @@ export class Operations { public setValueToCell(value: RawAndParsedValue, address: SimpleCellAddress) { const oldValue = this.dependencyGraph.getCellValue(address) - this.dependencyGraph.setValueToCell(address, value) + const arrayChanges = this.dependencyGraph.setValueToCell(address, value) this.columnSearch.change(getRawValue(oldValue), getRawValue(value.parsedValue), address) + this.changes.addAll(arrayChanges) this.changes.addChange(value.parsedValue, address) } From 3ab89206e7f48b60beb96fd0312bbb7a778453ff Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 11:55:46 +0200 Subject: [PATCH 46/87] Do nothing when trying to set internal array cell empty --- src/DependencyGraph/DependencyGraph.ts | 11 +++++++++-- src/Operations.ts | 6 +++++- test/cruds/change-cell-content.spec.ts | 13 ++++++------- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 6fddabe85a..6fb572c3e2 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -130,10 +130,10 @@ export class DependencyGraph { return this.getAndClearContentChanges() } - public setCellEmpty(address: SimpleCellAddress) { + public setCellEmpty(address: SimpleCellAddress): ContentChanges { const vertex = this.shrinkPossibleMatrixAndGetCell(address) if (vertex === null) { - return + return ContentChanges.empty() } if (this.graph.adjacentNodes(vertex).size > 0) { const emptyVertex = new EmptyCellVertex(address) @@ -149,6 +149,8 @@ export class DependencyGraph { this.removeVertex(vertex) this.addressMapping.removeCell(address) } + + return this.getAndClearContentChanges() } public ensureThatVertexIsNonMatrixCellVertex(vertex: CellVertex | null) { @@ -767,6 +769,11 @@ export class DependencyGraph { this.graph.markNodeAsSpecialRecentlyChanged(matrix) } + public isArrayInternalCell(address: SimpleCellAddress): boolean { + const vertex = this.getCell(address) + return vertex instanceof MatrixVertex && !vertex.isLeftCorner(address) + } + private cleanAddressMappingUnderMatrix(vertex: MatrixVertex) { const matrixRange = vertex.getRange() for (const address of matrixRange.addresses(this)) { diff --git a/src/Operations.ts b/src/Operations.ts index 7176a19833..a71bc278f4 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -682,10 +682,14 @@ export class Operations { } public setCellEmpty(address: SimpleCellAddress) { + if (this.dependencyGraph.isArrayInternalCell(address)) { + return + } const oldValue = this.dependencyGraph.getCellValue(address) + const arrayChanges = this.dependencyGraph.setCellEmpty(address) this.columnSearch.remove(getRawValue(oldValue), address) + this.changes.addAll(arrayChanges) this.changes.addChange(EmptyValue, address) - this.dependencyGraph.setCellEmpty(address) } public setFormulaToCellFromCache(formulaHash: string, address: SimpleCellAddress) { diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 90a83e5973..d716afe57e 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -881,7 +881,7 @@ describe('arrays', () => { ]) }) - it('should make existing array REF and change cell content empty', () => { + it('should not change cell to empty if part of an array', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], ['3', '4', '=B4'], @@ -892,8 +892,9 @@ describe('arrays', () => { expect(engine.getSheetValues(0)).toEqual([ [1, 2], - [3, 4], - [noSpace()], + [3, 4, -4], + [-1, -2], + [-3, -4], ]) }) @@ -1031,7 +1032,7 @@ describe('arrays', () => { expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), null)) }) - it('should return changed content when clearing any array cell', () => { + it('should return on changes when trying to clear array cell', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], ['=-A1:B1'], @@ -1039,9 +1040,7 @@ describe('arrays', () => { const changes = engine.setCellContents(adr('B2'), [[null]]) - expect(changes.length).toEqual(2) - expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), null)) - expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), null)) + expect(changes.length).toEqual(0) }) it('should return changed content when replacing array to smaller one', () => { From 55ab673900baa0767662fb6ce1ce8316db9f5d04 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 13:37:20 +0200 Subject: [PATCH 47/87] Track SimpleRangeValue changes --- src/ContentChanges.ts | 41 ++++++++++++++------------ src/DependencyGraph/DependencyGraph.ts | 3 +- src/Evaluator.ts | 2 +- src/Exporter.ts | 6 ++-- src/Operations.ts | 17 ++++++----- src/interpreter/SimpleRangeValue.ts | 9 ++++++ test/content-changes.spec.ts | 23 ++++++++------- test/cruds/change-cell-content.spec.ts | 21 ++++++------- 8 files changed, 69 insertions(+), 53 deletions(-) diff --git a/src/ContentChanges.ts b/src/ContentChanges.ts index 0fd2af02f2..68ffbfafbc 100644 --- a/src/ContentChanges.ts +++ b/src/ContentChanges.ts @@ -3,14 +3,13 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {simpleCellAddress, SimpleCellAddress} from './Cell' +import {SimpleCellAddress} from './Cell' import {InterpreterValue} from './interpreter/InterpreterValue' import {ClipboardCell} from './ClipboardOperations' +import {SimpleRangeValue} from './interpreter/SimpleRangeValue' export interface CellValueChange { - sheet: number, - row: number, - col: number, + address: SimpleCellAddress, value: InterpreterValue, oldValue?: ClipboardCell, } @@ -26,27 +25,23 @@ export class ContentChanges { return new ContentChanges() } + private constructor() {} + private changes: Map = new Map() public addAll(other: ContentChanges): ContentChanges { - for (const [key, value] of other.changes.entries()) { - this.changes.set(key, value) + for (const change of other.changes.values()) { + this.add(change.address, change) } return this } public addChangeWithOldValue(newValue: InterpreterValue, oldValue: ClipboardCell, address: SimpleCellAddress): void { - this.addSingleCellValue(newValue, address, oldValue) + this.addInterpreterValue(newValue, address, oldValue) } public addChange(newValue: InterpreterValue, address: SimpleCellAddress): void { - this.addSingleCellValue(newValue, address) - } - - private add(...changes: ChangeList) { - for (const change of changes) { - this.changes.set(`${change.sheet},${change.col},${change.row}`, change) - } + this.addInterpreterValue(newValue, address) } public exportChanges(exporter: ChangeExporter): T[] { @@ -70,11 +65,19 @@ export class ContentChanges { return this.changes.size === 0 } - private addSingleCellValue(value: InterpreterValue, address: SimpleCellAddress, oldValue?: ClipboardCell) { - this.add({ - sheet: address.sheet, - col: address.col, - row: address.row, + private add(address: SimpleCellAddress, change: CellValueChange) { + const value = change.value + if (value instanceof SimpleRangeValue) { + for (const cellAddress of value.effectiveAddressesFromData(address)) { + this.changes.delete(`${cellAddress.sheet},${cellAddress.col},${cellAddress.row}`) + } + } + this.changes.set(`${address.sheet},${address.col},${address.row}`, change) + } + + private addInterpreterValue(value: InterpreterValue, address: SimpleCellAddress, oldValue?: ClipboardCell) { + this.add(address, { + address, value, oldValue }) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 6fb572c3e2..4c1c2801e4 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -84,7 +84,7 @@ export class DependencyGraph { this.graph = new Graph(this.dependencyQueryVertices) } - public setFormulaToCell(address: SimpleCellAddress, ast: Ast, dependencies: CellDependency[], size: MatrixSize, hasVolatileFunction: boolean, hasStructuralChangeFunction: boolean) { + public setFormulaToCell(address: SimpleCellAddress, ast: Ast, dependencies: CellDependency[], size: MatrixSize, hasVolatileFunction: boolean, hasStructuralChangeFunction: boolean): ContentChanges { const newVertex = FormulaVertex.fromAst(ast, address, size, this.lazilyTransformingAstService.version()) this.exchangeOrAddFormulaVertex(newVertex) this.processCellDependencies(dependencies, newVertex) @@ -96,6 +96,7 @@ export class DependencyGraph { this.markAsDependentOnStructureChange(newVertex) } this.correctInfiniteRangesDependency(address) + return this.getAndClearContentChanges() } public setParsingErrorToCell(address: SimpleCellAddress, errorVertex: ParsingErrorVertex) { diff --git a/src/Evaluator.ts b/src/Evaluator.ts index 6ce83cca25..4e9aec54ae 100644 --- a/src/Evaluator.ts +++ b/src/Evaluator.ts @@ -55,7 +55,7 @@ export class Evaluator { } public partialRun(vertices: Vertex[]): ContentChanges { - const changes = new ContentChanges() + const changes = ContentChanges.empty() this.stats.measure(StatType.EVALUATION, () => { this.dependencyGraph.graph.getTopSortedWithSccSubgraphFrom(vertices, diff --git a/src/Exporter.ts b/src/Exporter.ts index ef72dfea88..10e713d805 100644 --- a/src/Exporter.ts +++ b/src/Exporter.ts @@ -61,10 +61,10 @@ export class Exporter implements ChangeExporter { public exportChange(change: CellValueChange): ExportedChange | ExportedChange[] { const value = change.value - const address = simpleCellAddress(change.sheet, change.col, change.row) + const address = change.address - if (change.sheet === NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS) { - const namedExpression = this.namedExpressions.namedExpressionInAddress(change.row) + if (address.sheet === NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS) { + const namedExpression = this.namedExpressions.namedExpressionInAddress(address.row) if (!namedExpression) { throw new Error('Missing named expression') } diff --git a/src/Operations.ts b/src/Operations.ts index a71bc278f4..a448149276 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -54,6 +54,7 @@ import {ParsingError} from './parser/Ast' import {findBoundaries, Sheet} from './Sheet' import {ColumnsSpan, RowsSpan} from './Span' import {Statistics, StatType} from './statistics' +import {ParsingResult} from './parser/ParserWithCaching' export class RemoveRowsCommand { constructor( @@ -643,18 +644,13 @@ export class Operations { const parsedCellContent = this.cellContentParser.parse(newCellContent) if (parsedCellContent instanceof CellContent.Formula) { - const { - ast, - errors, - hasVolatileFunction, - hasStructuralChangeFunction, - dependencies - } = this.parser.parse(parsedCellContent.formula, address) + const parserResult = this.parser.parse(parsedCellContent.formula, address) + const {ast, errors} = parserResult if (errors.length > 0) { this.dependencyGraph.setParsingErrorToCell(address, new ParsingErrorVertex(errors, parsedCellContent.formula)) } else { const size = this.matrixSizePredictor.checkMatrixSize(ast, address) - this.dependencyGraph.setFormulaToCell(address, ast, absolutizeDependencies(dependencies, address), size, hasVolatileFunction, hasStructuralChangeFunction) + this.setFormulaToCell(address, size, parserResult) } } else if (parsedCellContent instanceof CellContent.Empty) { this.setCellEmpty(address) @@ -673,6 +669,11 @@ export class Operations { } } + public setFormulaToCell(address: SimpleCellAddress, size: MatrixSize, { ast, hasVolatileFunction, hasStructuralChangeFunction, dependencies}: ParsingResult) { + const arrayChanges = this.dependencyGraph.setFormulaToCell(address, ast, absolutizeDependencies(dependencies, address), size, hasVolatileFunction, hasStructuralChangeFunction) + this.changes.addAll(arrayChanges) + } + public setValueToCell(value: RawAndParsedValue, address: SimpleCellAddress) { const oldValue = this.dependencyGraph.getCellValue(address) const arrayChanges = this.dependencyGraph.setValueToCell(address, value) diff --git a/src/interpreter/SimpleRangeValue.ts b/src/interpreter/SimpleRangeValue.ts index a75bf0bae5..d9a7347acb 100644 --- a/src/interpreter/SimpleRangeValue.ts +++ b/src/interpreter/SimpleRangeValue.ts @@ -96,6 +96,15 @@ export class SimpleRangeValue { return ret } + public* effectiveAddressesFromData(leftCorner: SimpleCellAddress): IterableIterator { + for (let row = 0; row < this.data.length; ++row) { + const rowData = this.data[row] + for (let col = 0; col < rowData.length; ++col) { + yield simpleCellAddress(leftCorner.sheet, leftCorner.col + col, leftCorner.row + row) + } + } + } + public* entriesFromTopLeftCorner(leftCorner: SimpleCellAddress): IterableIterator<[InternalScalarValue, SimpleCellAddress]> { this.ensureThatComputed() for (let row = 0; row < this.size.height; ++row) { diff --git a/test/content-changes.spec.ts b/test/content-changes.spec.ts index 7b07fa680d..2decce3eed 100644 --- a/test/content-changes.spec.ts +++ b/test/content-changes.spec.ts @@ -2,6 +2,7 @@ import {simpleCellAddress} from '../src/Cell' import {CellValueChange, ChangeExporter, ContentChanges} from '../src/ContentChanges' import {SimpleRangeValue} from '../src/interpreter/SimpleRangeValue' import {adr} from './testUtils' +import {HyperFormula} from '../src' class IdentityChangeExporter implements ChangeExporter{ exportChange(change: CellValueChange): CellValueChange { @@ -12,10 +13,10 @@ class IdentityChangeExporter implements ChangeExporter{ class SpreadRangeExporter implements ChangeExporter{ exportChange(change: CellValueChange): CellValueChange | CellValueChange[] { const value = change.value - const address = simpleCellAddress(change.sheet, change.col, change.row) + const address = change.address if (value instanceof SimpleRangeValue) { return Array.from(value.entriesFromTopLeftCorner(address)).map(([v, a]) => { - return { sheet: a.sheet, col: a.col, row: a.row, value: v } + return { address: a, value: v } }) } else { return change @@ -40,7 +41,7 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(identityChangeExporter) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({ sheet: 0, col: 0, row: 0, value: 2}) + expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 2}) }) it('should export simple value change', () => { @@ -52,7 +53,7 @@ describe('ContentChanges', () => { expect(contentChanges.isEmpty()).toEqual(false) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({ sheet: 0, col: 0, row: 0, value: 1}) + expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 1}) }) it('should export SimpleRangeValue change', () => { @@ -63,7 +64,7 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(identityChangeExporter) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({ sheet: 0, col: 0, row: 0, value: SimpleRangeValue.onlyValues([['foo', 'bar']])}) + expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: SimpleRangeValue.onlyValues([['foo', 'bar']])}) }) it('should add all changes', () => { @@ -76,8 +77,8 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(identityChangeExporter) expect(exportedChanges.length).toEqual(2) - expect(exportedChanges).toContainEqual({ sheet: 0, col: 0, row: 0, value: 1}) - expect(exportedChanges).toContainEqual({ sheet: 0, col: 0, row: 1, value: 2}) + expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 1}) + expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 1}, value: 2}) }) it('should handle array change', () => { @@ -87,9 +88,9 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(new SpreadRangeExporter()) expect(exportedChanges.length).toEqual(4) - expect(exportedChanges).toContainEqual({ sheet: 0, col: 0, row: 0, value: 1}) - expect(exportedChanges).toContainEqual({ sheet: 0, col: 1, row: 0, value: 2}) - expect(exportedChanges).toContainEqual({ sheet: 0, col: 0, row: 1, value: 'foo'}) - expect(exportedChanges).toContainEqual({ sheet: 0, col: 1, row: 1, value: 'bar'}) + expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 1}) + expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 1, row: 0}, value: 2}) + expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 1}, value: 'foo'}) + expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 1, row: 1}, value: 'bar'}) }) }) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index d716afe57e..6aeeda1bf0 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -1043,42 +1043,43 @@ describe('arrays', () => { expect(changes.length).toEqual(0) }) - it('should return changed content when replacing array to smaller one', () => { + it('should return changed content when replacing array to another smaller one', () => { const engine = HyperFormula.buildFromArray([ ['1', '2', '3'], ['=-A1:C1'], ], { useArrayArithmetic: true}) - const changes = engine.setCellContents(adr('A2'), [['=-A1:B1']]) + const changes = engine.setCellContents(adr('A2'), [['=+A1:B1']]) - expect(changes.length).toEqual(1) + expect(changes.length).toEqual(3) + expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), 1)) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), 2)) expect(changes).toContainEqual(new ExportedCellChange(adr('C2'), null)) }) - it('should return changed content when replacing array to another smaller one', () => { + it('should return changed content when replacing array to smaller one even if values are same', () => { const engine = HyperFormula.buildFromArray([ ['1', '2', '3'], ['=-A1:C1'], ], { useArrayArithmetic: true}) - const changes = engine.setCellContents(adr('A2'), [['=+A1:B1']]) + const changes = engine.setCellContents(adr('A2'), [['=-A1:B1']]) expect(changes.length).toEqual(3) - expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), 1)) - expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), 2)) + expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), -1)) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), -2)) expect(changes).toContainEqual(new ExportedCellChange(adr('C2'), null)) }) - it('should return REF in changes', () => { const engine = HyperFormula.buildFromArray([ [1, 2, 3, '=-A1:C1'], ], {useArrayArithmetic: true}) - const changes = engine.setCellContents(adr('E1'), [[null]]) + const changes = engine.setCellContents(adr('E1'), [['foo']]) expect(changes).toContainEqual(new ExportedCellChange(adr('D1'), noSpace())) - expect(changes).toContainEqual(new ExportedCellChange(adr('E1'), null)) + expect(changes).toContainEqual(new ExportedCellChange(adr('E1'), 'foo')) expect(changes).toContainEqual(new ExportedCellChange(adr('F1'), null)) }) From f4d0a01d48b8c3b07d54ff325cc9e161ebd1844b Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 14:20:22 +0200 Subject: [PATCH 48/87] Compare raw input of parsing errors --- test/graphComparator.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/graphComparator.ts b/test/graphComparator.ts index 216e0f397a..052c48b495 100644 --- a/test/graphComparator.ts +++ b/test/graphComparator.ts @@ -5,7 +5,7 @@ import {SimpleCellAddress, simpleCellAddress} from '../src/Cell' import { EmptyCellVertex, FormulaCellVertex, - MatrixVertex, + MatrixVertex, ParsingErrorVertex, RangeVertex, ValueCellVertex, Vertex, @@ -69,6 +69,8 @@ export class EngineComparator { deepStrictEqual(actualVertex.getCellValue(), expectedVertex.getCellValue(), `Different values. expected: ${expectedVertex.getCellValue().toString()}, actual: ${actualVertex.getCellValue().toString()}`) } else if (expectedVertex instanceof EmptyCellVertex && actualVertex instanceof EmptyCellVertex) { continue + } else if (expectedVertex instanceof ParsingErrorVertex && actualVertex instanceof ParsingErrorVertex) { + deepStrictEqual(expectedVertex.rawInput, actualVertex.rawInput, `Different raw input. expected: ${expectedVertex.rawInput}, actual: ${actualVertex.rawInput}`) } else { throw Error('Different vertex types') } From 036ab8f57ea2bf5fa7df14a09c608681ff42dd10 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 14:29:39 +0200 Subject: [PATCH 49/87] Handle ParsingError case --- src/DependencyGraph/DependencyGraph.ts | 3 ++- src/Operations.ts | 11 +++++--- test/cruds/change-cell-content.spec.ts | 35 ++++++++++++++++++++++++-- 3 files changed, 42 insertions(+), 7 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 4c1c2801e4..0a164f983f 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -99,12 +99,13 @@ export class DependencyGraph { return this.getAndClearContentChanges() } - public setParsingErrorToCell(address: SimpleCellAddress, errorVertex: ParsingErrorVertex) { + public setParsingErrorToCell(address: SimpleCellAddress, errorVertex: ParsingErrorVertex): ContentChanges { const vertex = this.shrinkPossibleMatrixAndGetCell(address) this.exchangeOrAddGraphNode(vertex, errorVertex) this.addressMapping.setCell(address, errorVertex) this.graph.markNodeAsSpecialRecentlyChanged(errorVertex) this.correctInfiniteRangesDependency(address) + return this.getAndClearContentChanges() } public setValueToCell(address: SimpleCellAddress, value: RawAndParsedValue): ContentChanges { diff --git a/src/Operations.ts b/src/Operations.ts index a448149276..f4f6d983a6 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -5,7 +5,7 @@ import {AbsoluteCellRange} from './AbsoluteCellRange' import {absolutizeDependencies, filterDependenciesOutOfScope} from './absolutizeDependencies' -import {invalidSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from './Cell' +import {CellError, ErrorType, invalidSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from './Cell' import {CellContent, CellContentParser, RawCellContent} from './CellContentParser' import {ClipboardCell, ClipboardCellType} from './ClipboardOperations' import {Config} from './Config' @@ -18,7 +18,7 @@ import { EmptyCellVertex, FormulaCellVertex, MatrixVertex, - ParsingErrorVertex, RangeVertex, + ParsingErrorVertex, SheetMapping, SparseStrategy, ValueCellVertex @@ -647,7 +647,7 @@ export class Operations { const parserResult = this.parser.parse(parsedCellContent.formula, address) const {ast, errors} = parserResult if (errors.length > 0) { - this.dependencyGraph.setParsingErrorToCell(address, new ParsingErrorVertex(errors, parsedCellContent.formula)) + this.setParsingErrorToCell(parsedCellContent.formula, errors, address) } else { const size = this.matrixSizePredictor.checkMatrixSize(ast, address) this.setFormulaToCell(address, size, parserResult) @@ -709,7 +709,10 @@ export class Operations { } public setParsingErrorToCell(rawInput: string, errors: ParsingError[], address: SimpleCellAddress) { - this.dependencyGraph.setParsingErrorToCell(address, new ParsingErrorVertex(errors, rawInput)) + const vertex = new ParsingErrorVertex(errors, rawInput) + const arrayChanges = this.dependencyGraph.setParsingErrorToCell(address, vertex) + this.changes.addAll(arrayChanges) + this.changes.addChange(vertex.getCellValue(), address) } /** diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 6aeeda1bf0..87ac86c0a7 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -921,6 +921,23 @@ describe('arrays', () => { ]) }) + it('should make existing array REF and change cell content to parsing error', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ['3', '4', '=B4'], + ['=-A1:B2'], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('B4'), [['=SUM(']]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4, '=B4'], + ['=-A1:B2'], + [null, '=SUM('] + ], {useArrayArithmetic: true})) + }) + it('should make existing matrix REF and set new array', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], @@ -1003,7 +1020,7 @@ describe('arrays', () => { expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), null)) }) - it('should return changed content when replacing any array cell', () => { + it('should return changed content when replacing any array cell with simple value', () => { const engine = HyperFormula.buildFromArray([ ['1', '2', '3'], ['=-A1:C1'], @@ -1011,11 +1028,25 @@ describe('arrays', () => { const changes = engine.setCellContents(adr('B2'), [['foo']]) + expect(changes.length).toEqual(3) + expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), noSpace())) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), 'foo')) + expect(changes).toContainEqual(new ExportedCellChange(adr('C2'), null)) + }) + + it('should return changed content when replacing any array cell with parsing error', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2', '3'], + ['=-A1:C1'], + ], { useArrayArithmetic: true}) + + const changes = engine.setCellContents(adr('B2'), [['=SUM(']]) + console.log(engine.getSheetValues(0)) expect(changes.length).toEqual(3) expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), noSpace())) - expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), 'foo')) + expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), detailedError(ErrorType.ERROR, ErrorMessage.ParseError))) expect(changes).toContainEqual(new ExportedCellChange(adr('C2'), null)) }) From 2dfe38868b469e344021f6b65fff50846a506761 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 16:09:37 +0200 Subject: [PATCH 50/87] Cleanup --- src/Cell.ts | 3 +-- src/ContentChanges.ts | 15 ++++----------- src/DependencyGraph/MatrixMapping.ts | 13 +++++-------- 3 files changed, 10 insertions(+), 21 deletions(-) diff --git a/src/Cell.ts b/src/Cell.ts index 419038dc55..66194c037e 100644 --- a/src/Cell.ts +++ b/src/Cell.ts @@ -181,7 +181,6 @@ export interface SimpleCellAddress { sheet: number, } - export const simpleCellAddress = (sheet: number, col: number, row: number): SimpleCellAddress => ({sheet, col, row}) export const invalidSimpleCellAddress = (address: SimpleCellAddress): boolean => (address.col < 0 || address.row < 0) export const movedSimpleCellAddress = (address: SimpleCellAddress, toSheet: number, toRight: number, toBottom: number): SimpleCellAddress => { @@ -190,7 +189,7 @@ export const movedSimpleCellAddress = (address: SimpleCellAddress, toSheet: numb export const addressesEqual = (left: SimpleCellAddress, right: SimpleCellAddress) => { return left.sheet === right.sheet && left.row === right.row && left.col === right.col } - +export const addressKey = (address: SimpleCellAddress) => `${address.sheet},${address.row},${address.col}` export const absoluteSheetReference = (address: AddressWithSheet, baseAddress: SimpleCellAddress): number => { return address.sheet === null ? baseAddress.sheet : address.sheet diff --git a/src/ContentChanges.ts b/src/ContentChanges.ts index 68ffbfafbc..e5f0bc55ba 100644 --- a/src/ContentChanges.ts +++ b/src/ContentChanges.ts @@ -3,15 +3,13 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from './Cell' +import {addressKey, SimpleCellAddress} from './Cell' import {InterpreterValue} from './interpreter/InterpreterValue' -import {ClipboardCell} from './ClipboardOperations' import {SimpleRangeValue} from './interpreter/SimpleRangeValue' export interface CellValueChange { address: SimpleCellAddress, value: InterpreterValue, - oldValue?: ClipboardCell, } export interface ChangeExporter { @@ -36,10 +34,6 @@ export class ContentChanges { return this } - public addChangeWithOldValue(newValue: InterpreterValue, oldValue: ClipboardCell, address: SimpleCellAddress): void { - this.addInterpreterValue(newValue, address, oldValue) - } - public addChange(newValue: InterpreterValue, address: SimpleCellAddress): void { this.addInterpreterValue(newValue, address) } @@ -72,14 +66,13 @@ export class ContentChanges { this.changes.delete(`${cellAddress.sheet},${cellAddress.col},${cellAddress.row}`) } } - this.changes.set(`${address.sheet},${address.col},${address.row}`, change) + this.changes.set(addressKey((address)), change) } - private addInterpreterValue(value: InterpreterValue, address: SimpleCellAddress, oldValue?: ClipboardCell) { + private addInterpreterValue(value: InterpreterValue, address: SimpleCellAddress) { this.add(address, { address, - value, - oldValue + value }) } } diff --git a/src/DependencyGraph/MatrixMapping.ts b/src/DependencyGraph/MatrixMapping.ts index b5085bc770..5f8a18119c 100644 --- a/src/DependencyGraph/MatrixMapping.ts +++ b/src/DependencyGraph/MatrixMapping.ts @@ -4,13 +4,10 @@ */ import {AbsoluteCellRange} from '../AbsoluteCellRange' -import {SimpleCellAddress} from '../Cell' +import {addressKey, SimpleCellAddress} from '../Cell' import {Maybe} from '../Maybe' import {ColumnsSpan, RowsSpan} from '../Span' import {MatrixVertex} from './' -import {simpleCellAddressToString} from '../parser' - -const mappingKey = (address: SimpleCellAddress) => `${address.sheet},${address.row},${address.col}` export class MatrixMapping { public readonly matrixMapping: Map = new Map() @@ -24,22 +21,22 @@ export class MatrixMapping { } public getMatrixByCorner(address: SimpleCellAddress): Maybe { - return this.matrixMapping.get(mappingKey(address)) + return this.matrixMapping.get(addressKey(address)) } public setMatrix(range: AbsoluteCellRange, vertex: MatrixVertex) { - this.matrixMapping.set(mappingKey(range.start), vertex) + this.matrixMapping.set(addressKey(range.start), vertex) } public setMatrixByCorner(address: SimpleCellAddress, vertex: MatrixVertex) { - this.matrixMapping.set(mappingKey(address), vertex) + this.matrixMapping.set(addressKey(address), vertex) } public removeMatrix(range: string | AbsoluteCellRange) { if (typeof range === 'string') { this.matrixMapping.delete(range) } else { - this.matrixMapping.delete(mappingKey(range.start)) + this.matrixMapping.delete(addressKey(range.start)) } } From 48252d80be665f4c4923b5fcf6ab1659cb1270c3 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 11 Jun 2021 16:37:38 +0200 Subject: [PATCH 51/87] Working undo/redo --- src/CrudOperations.ts | 15 +++++++++------ src/Operations.ts | 25 ++++++++++++++++++++++++- src/UndoRedo.ts | 17 ++++++++++++----- test/cruds/change-cell-content.spec.ts | 20 ++++++++++++++++++-- 4 files changed, 63 insertions(+), 14 deletions(-) diff --git a/src/CrudOperations.ts b/src/CrudOperations.ts index 7a725b7402..6d396232c5 100644 --- a/src/CrudOperations.ts +++ b/src/CrudOperations.ts @@ -39,7 +39,7 @@ import { import {AddColumnsCommand, AddRowsCommand, Operations, RemoveColumnsCommand, RemoveRowsCommand} from './Operations' import {ParserWithCaching} from './parser' import {findBoundaries, validateAsSheet} from './Sheet' -import {ColumnsSpan, RowsSpan} from './Span' +import {ColumnsSpan} from './Span' import {Statistics} from './statistics' import { AddColumnsUndoEntry, @@ -257,7 +257,9 @@ export class CrudOperations { this.ensureItIsPossibleToChangeCellContents(topLeftCornerAddress, cellContents) this.undoRedo.clearRedoStack() - const modifiedCellContents: { address: SimpleCellAddress, newContent: RawCellContent, oldContent: ClipboardCell }[] = [] + + const oldContents: { address: SimpleCellAddress, newContent: RawCellContent, oldContent: [SimpleCellAddress, ClipboardCell] }[] = [] + for (let i = 0; i < cellContents.length; i++) { for (let j = 0; j < cellContents[i].length; j++) { const address = { @@ -265,13 +267,14 @@ export class CrudOperations { row: topLeftCornerAddress.row + i, col: topLeftCornerAddress.col + j, } + const newContent = cellContents[i][j] this.clipboardOperations.abortCut() - const oldContent = this.operations.getClipboardCell(address) - this.operations.setCellContent(address, cellContents[i][j]) - modifiedCellContents.push({address, newContent: cellContents[i][j], oldContent}) + const oldContent = this.operations.setCellContent(address, newContent) + oldContents.push({address, newContent, oldContent}) } } - this.undoRedo.saveOperation(new SetCellContentsUndoEntry(modifiedCellContents)) + + this.undoRedo.saveOperation(new SetCellContentsUndoEntry(oldContents)) } public setSheetContent(sheetId: number, values: RawCellContent[][]): void { diff --git a/src/Operations.ts b/src/Operations.ts index f4f6d983a6..c1144d846b 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -55,6 +55,7 @@ import {findBoundaries, Sheet} from './Sheet' import {ColumnsSpan, RowsSpan} from './Span' import {Statistics, StatType} from './statistics' import {ParsingResult} from './parser/ParserWithCaching' +import {FormulaVertex} from './DependencyGraph/FormulaCellVertex' export class RemoveRowsCommand { constructor( @@ -591,6 +592,25 @@ export class Operations { }) } + public getOldContent(address: SimpleCellAddress): [SimpleCellAddress, ClipboardCell] { + const vertex = this.dependencyGraph.getCell(address) + + if (vertex === null || vertex instanceof EmptyCellVertex) { + return [address, {type: ClipboardCellType.EMPTY}] + } else if (vertex instanceof ValueCellVertex) { + return [address, {type: ClipboardCellType.VALUE, ...vertex.getValues()}] + } else if (vertex instanceof FormulaVertex) { + return [vertex.getAddress(this.lazilyTransformingAstService), { + type: ClipboardCellType.FORMULA, + hash: this.parser.computeHashFromAst(vertex.getFormula(this.lazilyTransformingAstService)) + }] + } else if (vertex instanceof ParsingErrorVertex) { + return [address, {type: ClipboardCellType.PARSING_ERROR, rawInput: vertex.rawInput, errors: vertex.errors}] + } + + throw Error('Trying to copy unsupported type') + } + public getClipboardCell(address: SimpleCellAddress): ClipboardCell { const vertex = this.dependencyGraph.getCell(address) @@ -640,8 +660,9 @@ export class Operations { return result } - public setCellContent(address: SimpleCellAddress, newCellContent: RawCellContent): void { + public setCellContent(address: SimpleCellAddress, newCellContent: RawCellContent): [SimpleCellAddress, ClipboardCell] { const parsedCellContent = this.cellContentParser.parse(newCellContent) + const oldContent = this.getOldContent(address) if (parsedCellContent instanceof CellContent.Formula) { const parserResult = this.parser.parse(parsedCellContent.formula, address) @@ -657,6 +678,8 @@ export class Operations { } else { this.setValueToCell({parsedValue: parsedCellContent.value, rawValue: newCellContent}, address) } + + return oldContent } public setSheetContent(sheetId: number, newSheetContent: RawCellContent[][]) { diff --git a/src/UndoRedo.ts b/src/UndoRedo.ts index b61c259219..b4e1a6634f 100644 --- a/src/UndoRedo.ts +++ b/src/UndoRedo.ts @@ -3,9 +3,9 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {simpleCellAddress, SimpleCellAddress} from './Cell' +import {equalSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from './Cell' import {RawCellContent} from './CellContentParser' -import {ClipboardCell} from './ClipboardOperations' +import {ClipboardCell, ClipboardCellType} from './ClipboardOperations' import {Config} from './Config' import {InternalNamedExpression, NamedExpressionOptions} from './NamedExpressions' import { @@ -20,11 +20,13 @@ import { export interface UndoEntry { doUndo(undoRedo: UndoRedo): void, + doRedo(undoRedo: UndoRedo): void, } export abstract class BaseUndoEntry implements UndoEntry { abstract doUndo(undoRedo: UndoRedo): void + abstract doRedo(undoRedo: UndoRedo): void } @@ -296,7 +298,7 @@ export class SetCellContentsUndoEntry extends BaseUndoEntry { public readonly cellContents: { address: SimpleCellAddress, newContent: RawCellContent, - oldContent: ClipboardCell, + oldContent: [SimpleCellAddress, ClipboardCell], }[], ) { super() @@ -544,7 +546,12 @@ export class UndoRedo { public undoSetCellContents(operation: SetCellContentsUndoEntry) { for (const cellContentData of operation.cellContents) { - this.operations.restoreCell(cellContentData.address, cellContentData.oldContent) + const address = cellContentData.address + const [oldContentAddress, oldContent] = cellContentData.oldContent + if (!equalSimpleCellAddress(address, oldContentAddress)) { + this.operations.setCellEmpty(address) + } + this.operations.restoreCell(oldContentAddress, oldContent) } } @@ -597,7 +604,7 @@ export class UndoRedo { } } - for(const [namedexpression, content] of operation.scopedNamedExpressions) { + for (const [namedexpression, content] of operation.scopedNamedExpressions) { this.operations.restoreNamedExpression(namedexpression, content, sheetId) } diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 87ac86c0a7..b14ab04f38 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -1119,9 +1119,9 @@ describe('arrays', () => { [1, 2, 3, '=-A1:C1', null, null, 4], ['=D1', '=E1', '=SUM(F1:F1)', '=SUM(F1:G1)'], ], {useArrayArithmetic: true}) - engine.setCellContents(adr('E1'), [[null]]) - engine.setCellContents(adr('D1'), [[4, 5, 6]]) + engine.setCellContents(adr('E1'), [['foo']]) + engine.setCellContents(adr('D1'), [[4, 5, 6]]) engine.undo() engine.undo() @@ -1136,6 +1136,22 @@ describe('arrays', () => { expect(engine.getCellValue(adr('D2'))).toEqual(1) }) + it('should redo REF', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, 3, '=-A1:C1', null, null, 4], + ['=D1', '=E1', '=SUM(F1:F1)', '=SUM(F1:G1)'], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('E1'), [['foo']]) + engine.undo() + engine.redo() + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2, 3, '=-A1:C1', 'foo', null, 4], + ['=D1', '=E1', '=SUM(F1:F1)', '=SUM(F1:G1)'], + ], {useArrayArithmetic: true})) + }) + it.skip('should recalculate matrix if space is available', () => { const engine = HyperFormula.buildFromArray([ ['=+C1:D1', 'foo', 1, 2] From d1cde5ea7d4812a5d2070c289c2839ce9d0b4a2d Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 12 Jun 2021 10:51:39 +0200 Subject: [PATCH 52/87] Do not allow to move rows inside array --- src/CrudOperations.ts | 43 ++++++++++++++++------------ src/DependencyGraph/MatrixMapping.ts | 9 +++--- 2 files changed, 30 insertions(+), 22 deletions(-) diff --git a/src/CrudOperations.ts b/src/CrudOperations.ts index 6d396232c5..df59bb5980 100644 --- a/src/CrudOperations.ts +++ b/src/CrudOperations.ts @@ -39,7 +39,7 @@ import { import {AddColumnsCommand, AddRowsCommand, Operations, RemoveColumnsCommand, RemoveRowsCommand} from './Operations' import {ParserWithCaching} from './parser' import {findBoundaries, validateAsSheet} from './Sheet' -import {ColumnsSpan} from './Span' +import {ColumnsSpan, RowsSpan} from './Span' import {Statistics} from './statistics' import { AddColumnsUndoEntry, @@ -135,7 +135,11 @@ export class CrudOperations { public moveCells(sourceLeftCorner: SimpleCellAddress, width: number, height: number, destinationLeftCorner: SimpleCellAddress): void { this.undoRedo.clearRedoStack() this.clipboardOperations.abortCut() - const {version, overwrittenCellsData, addedGlobalNamedExpressions} = this.operations.moveCells(sourceLeftCorner, width, height, destinationLeftCorner) + const { + version, + overwrittenCellsData, + addedGlobalNamedExpressions + } = this.operations.moveCells(sourceLeftCorner, width, height, destinationLeftCorner) this.undoRedo.saveOperation(new MoveCellsUndoEntry(sourceLeftCorner, width, height, destinationLeftCorner, overwrittenCellsData, addedGlobalNamedExpressions, version)) } @@ -306,8 +310,8 @@ export class CrudOperations { } public testColumnOrderForMatrices(sheetId: number, columnMapping: [number, number][]): void { - for(const [source, target] of columnMapping ) { - if(source!==target) { + 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() @@ -334,8 +338,8 @@ export class CrudOperations { } public testRowOrderForMatrices(sheetId: number, rowMapping: [number, number][]): void { - for(const [source, target] of rowMapping ) { - if(source!==target) { + 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() @@ -350,12 +354,12 @@ export class CrudOperations { 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'}.`) + 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) + const sources = rowMapping.map(([a, _]) => a).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'}.`) + for (let i = 0; i < sources.length; i++) { + if (!isNonnegativeInteger(sources[i]) || sources[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]) { + if (sources[i] === sources[i + 1]) { throw new InvalidArgumentsError(`source ${rowOrColumn} numbers to be unique.`) } - if(sources[i]!==targets[i]) { + if (sources[i] !== targets[i]) { throw new InvalidArgumentsError(`target ${rowOrColumn} numbers to be permutation of source ${rowOrColumn} numbers.`) } } @@ -546,6 +550,9 @@ export class CrudOperations { if (this.dependencyGraph.matrixMapping.isFormulaMatrixInRange(sourceRange)) { throw new SourceLocationHasMatrixError() } + if (targetRow > 0 && this.dependencyGraph.matrixMapping.isFormulaMatrixInAllRows(RowsSpan.fromNumberOfRows(sheet, targetRow - 1, 2))) { + throw new TargetLocationHasMatrixError() + } } public ensureItIsPossibleToMoveColumns(sheet: number, startColumn: number, numberOfColumns: number, targetColumn: number): void { @@ -632,7 +639,7 @@ export class CrudOperations { } public ensureScopeIdIsValid(scopeId?: number): void { - if(scopeId !== undefined && !this.sheetMapping.hasSheetWithId(scopeId)) { + if (scopeId !== undefined && !this.sheetMapping.hasSheetWithId(scopeId)) { throw new NoSheetWithIdError(scopeId) } } diff --git a/src/DependencyGraph/MatrixMapping.ts b/src/DependencyGraph/MatrixMapping.ts index 5f8a18119c..612ac695ed 100644 --- a/src/DependencyGraph/MatrixMapping.ts +++ b/src/DependencyGraph/MatrixMapping.ts @@ -61,13 +61,14 @@ export class MatrixMapping { return false } - public isFormulaMatrixInRows(span: RowsSpan) { + public isFormulaMatrixInAllRows(span: RowsSpan) { + let result = true for (const row of span.rows()) { - if (this.isFormulaMatrixInRow(span.sheet, row)) { - return true + if (!this.isFormulaMatrixInRow(span.sheet, row)) { + result = false } } - return false + return result } public isFormulaMatrixInColumn(sheet: number, column: number): boolean { From 5ab2606491e899fde370d40f74a0bf0777bb5bc6 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 12 Jun 2021 11:01:35 +0200 Subject: [PATCH 53/87] Update js docs --- src/HyperFormula.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 0fa11f0f0d..5d15b6f648 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -1135,7 +1135,6 @@ export class HyperFormula implements TypedEmitter { * * @throws [[InvalidArgumentsError]] when the value is not an array of arrays or a raw cell value * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding - * @throws an error when it is an attempt to set cells content inside matrices during batch operation * * @example * ```js @@ -1503,7 +1502,6 @@ export class HyperFormula implements TypedEmitter { * 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. * If returns `true`, doing [[addRows]] operation won't throw any errors. - * Returns `false` if the operation might be disrupted and causes side-effects by the fact that there is a matrix inside the selected rows. * * @param {number} sheetId - sheet ID in which rows will be added * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format [row, amount], where row is a row number above which the rows will be added @@ -1547,7 +1545,6 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding - * @throws [[TargetLocationHasMatrixError]] when the selected position has matrix inside * * @example * ```js @@ -1573,7 +1570,6 @@ export class HyperFormula implements TypedEmitter { * Returns information whether it is possible to remove rows from a specified position in a given sheet. * Checks against particular rules to ascertain that removeRows can be called. * If returns `true`, doing [[removeRows]] operation won't throw any errors. - * Returns `false` if the operation might be disrupted and causes side-effects by the fact that there is a matrix inside the selected rows. * * @param {number} sheetId - sheet ID from which rows will be removed * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [row, amount] @@ -1618,7 +1614,6 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist - * @throws [[SourceLocationHasMatrixError]] when the selected position has matrix inside * * @example * ```js From 6190ceff2bacba48a6fab899ffc64e671dd6046b Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 12 Jun 2021 11:15:57 +0200 Subject: [PATCH 54/87] Fix rebase --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 03e7e7f293..f3876b69a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Breaking change**: Changed API of many sheet-related methods to take sheetId instead of sheetName as an argument. (#645) - **Breaking change**: Removed support for matrix formulas (`{=FORMULA}`) notation. Engine now supports formulas returning array of values (instead of only scalars). (#652) - **Breaking change**: Removed numeric matrix detection along with matrixDetection and matrixDetectionThreshold config options. (#669) -- **Breaking change**: Removed numeric matrix detection along with matrixDetection and matrixDetectionThreshold config options. (#669) - Changed SWITCH function so it takes array as its first argument. - Changed TRANSPOSE function, so it works with data of any type. (#670) From ec581aba656e29c579add4ac1d7feb2d8c90639a Mon Sep 17 00:00:00 2001 From: izulin Date: Thu, 17 Jun 2021 15:35:24 +0200 Subject: [PATCH 55/87] imports --- src/DependencyGraph/AddressMapping/AddressMapping.ts | 2 +- src/DependencyGraph/DependencyGraph.ts | 2 +- src/DependencyGraph/FormulaCellVertex.ts | 2 +- src/Evaluator.ts | 1 - src/Exporter.ts | 2 +- src/GraphBuilder.ts | 2 -- src/HyperFormula.ts | 3 ++- src/Matrix.ts | 2 +- src/Operations.ts | 6 +++--- src/UndoRedo.ts | 2 +- test/arrays.spec.ts | 4 ++-- test/content-changes.spec.ts | 2 -- test/cruds/adding-row.spec.ts | 2 +- test/cruds/change-cell-content.spec.ts | 2 +- test/cruds/removing-rows.spec.ts | 3 ++- test/graphComparator.ts | 3 ++- test/matrix-mapping.spec.ts | 6 +++--- test/testUtils.ts | 2 +- 18 files changed, 23 insertions(+), 25 deletions(-) diff --git a/src/DependencyGraph/AddressMapping/AddressMapping.ts b/src/DependencyGraph/AddressMapping/AddressMapping.ts index cead04905a..c59c126c81 100644 --- a/src/DependencyGraph/AddressMapping/AddressMapping.ts +++ b/src/DependencyGraph/AddressMapping/AddressMapping.ts @@ -8,12 +8,12 @@ import {RawCellContent} from '../../CellContentParser' import {NoSheetWithIdError} from '../../errors' import {EmptyValue, InterpreterValue} from '../../interpreter/InterpreterValue' import {Maybe} from '../../Maybe' +import {Sheet, SheetBoundaries} from '../../Sheet' import {ColumnsSpan, RowsSpan} from '../../Span' import {MatrixVertex, ValueCellVertex} from '../index' import {CellVertex} from '../Vertex' import {ChooseAddressMapping} from './ChooseAddressMappingPolicy' import {IAddressMappingStrategy} from './IAddressMappingStrategy' -import {Sheet, SheetBoundaries} from '../../Sheet' export class AddressMapping { private mapping: Map = new Map() diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 8de03c7c99..ed352831f4 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -9,6 +9,7 @@ import {CellError, ErrorType, isSimpleCellAddress, simpleCellAddress, SimpleCell import {RawCellContent} from '../CellContentParser' import {CellDependency} from '../CellDependency' import {Config} from '../Config' +import {ContentChanges} from '../ContentChanges' import {ErrorMessage} from '../error-message' import {FunctionRegistry} from '../interpreter/FunctionRegistry' import { @@ -44,7 +45,6 @@ import {MatrixMapping} from './MatrixMapping' import {RangeMapping} from './RangeMapping' import {SheetMapping} from './SheetMapping' import {RawAndParsedValue} from './ValueCellVertex' -import {ContentChanges} from '../ContentChanges' export class DependencyGraph { /** diff --git a/src/DependencyGraph/FormulaCellVertex.ts b/src/DependencyGraph/FormulaCellVertex.ts index 4f14f54f77..382d329141 100644 --- a/src/DependencyGraph/FormulaCellVertex.ts +++ b/src/DependencyGraph/FormulaCellVertex.ts @@ -6,6 +6,7 @@ import {AbsoluteCellRange} from '../AbsoluteCellRange' import {addressesEqual, CellError, ErrorType, SimpleCellAddress} from '../Cell' import {RawCellContent} from '../CellContentParser' +import {ErrorMessage} from '../error-message' import {EmptyValue, getRawValue, InternalScalarValue, InterpreterValue} from '../interpreter/InterpreterValue' import {LazilyTransformingAstService} from '../LazilyTransformingAstService' import {ErroredMatrix, IMatrix, Matrix, NotComputedMatrix} from '../Matrix' @@ -13,7 +14,6 @@ import {MatrixSize} from '../MatrixSize' import {Maybe} from '../Maybe' import {Ast} from '../parser' import {ColumnsSpan, RowsSpan} from '../Span' -import {ErrorMessage} from '../error-message' export abstract class FormulaVertex { static fromAst(formula: Ast, address: SimpleCellAddress, size: MatrixSize, version: number) { diff --git a/src/Evaluator.ts b/src/Evaluator.ts index c8270b8773..fac575f02c 100644 --- a/src/Evaluator.ts +++ b/src/Evaluator.ts @@ -23,7 +23,6 @@ import {NumberLiteralHelper} from './NumberLiteralHelper' import {Ast, RelativeDependency} from './parser' import {Serialization} from './Serialization' import {Statistics, StatType} from './statistics' -import {CellContent} from './CellContentParser' export class Evaluator { private interpreter: Interpreter diff --git a/src/Exporter.ts b/src/Exporter.ts index 12f60e7f0d..518b9489e7 100644 --- a/src/Exporter.ts +++ b/src/Exporter.ts @@ -3,7 +3,7 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress, simpleCellAddress} from './Cell' +import {CellError, ErrorType, SimpleCellAddress} from './Cell' import {CellValue, DetailedCellError} from './CellValue' import {Config} from './Config' import {CellValueChange, ChangeExporter} from './ContentChanges' diff --git a/src/GraphBuilder.ts b/src/GraphBuilder.ts index 8ba1e9f8dd..d0769a360a 100644 --- a/src/GraphBuilder.ts +++ b/src/GraphBuilder.ts @@ -22,8 +22,6 @@ import {MatrixSize, MatrixSizePredictor} from './MatrixSize' import {ParserWithCaching} from './parser' import {Sheets} from './Sheet' import {Statistics, StatType} from './statistics' -import {Matrix} from './Matrix' -import {AbsoluteCellRange} from './AbsoluteCellRange' export type Dependencies = Map diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 9edfca02d9..a5a6e52778 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -33,7 +33,8 @@ import { } from './DependencyGraph' import {Emitter, Events, Listeners, TypedEmitter} from './Emitter' import { - EvaluationSuspendedError, ExpectedValueOfTypeError, + EvaluationSuspendedError, + ExpectedValueOfTypeError, LanguageAlreadyRegisteredError, LanguageNotRegisteredError, NotAFormulaError, diff --git a/src/Matrix.ts b/src/Matrix.ts index 9ff9b88f1b..f14399ba90 100644 --- a/src/Matrix.ts +++ b/src/Matrix.ts @@ -3,7 +3,7 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, SimpleCellAddress, simpleCellAddress} from './Cell' +import {CellError} from './Cell' import {EmptyValue, InternalScalarValue, InterpreterValue} from './interpreter/InterpreterValue' import {SimpleRangeValue} from './interpreter/SimpleRangeValue' import {MatrixSize} from './MatrixSize' diff --git a/src/Operations.ts b/src/Operations.ts index e9f73a6481..7f9cad2de7 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -5,7 +5,7 @@ import {AbsoluteCellRange} from './AbsoluteCellRange' import {absolutizeDependencies, filterDependenciesOutOfScope} from './absolutizeDependencies' -import {CellError, ErrorType, invalidSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from './Cell' +import {invalidSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from './Cell' import {CellContent, CellContentParser, RawCellContent} from './CellContentParser' import {ClipboardCell, ClipboardCellType} from './ClipboardOperations' import {Config} from './Config' @@ -23,6 +23,7 @@ import { SparseStrategy, ValueCellVertex } from './DependencyGraph' +import {FormulaVertex} from './DependencyGraph/FormulaCellVertex' import {RawAndParsedValue} from './DependencyGraph/ValueCellVertex' import {AddColumnsTransformer} from './dependencyTransformers/AddColumnsTransformer' import {AddRowsTransformer} from './dependencyTransformers/AddRowsTransformer' @@ -51,11 +52,10 @@ import { } from './NamedExpressions' import {NamedExpressionDependency, ParserWithCaching, RelativeDependency} from './parser' import {ParsingError} from './parser/Ast' +import {ParsingResult} from './parser/ParserWithCaching' import {findBoundaries, Sheet} from './Sheet' import {ColumnsSpan, RowsSpan} from './Span' import {Statistics, StatType} from './statistics' -import {ParsingResult} from './parser/ParserWithCaching' -import {FormulaVertex} from './DependencyGraph/FormulaCellVertex' export class RemoveRowsCommand { constructor( diff --git a/src/UndoRedo.ts b/src/UndoRedo.ts index b4e1a6634f..bad176503b 100644 --- a/src/UndoRedo.ts +++ b/src/UndoRedo.ts @@ -5,7 +5,7 @@ import {equalSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from './Cell' import {RawCellContent} from './CellContentParser' -import {ClipboardCell, ClipboardCellType} from './ClipboardOperations' +import {ClipboardCell} from './ClipboardOperations' import {Config} from './Config' import {InternalNamedExpression, NamedExpressionOptions} from './NamedExpressions' import { diff --git a/test/arrays.spec.ts b/test/arrays.spec.ts index aa7e9fad0f..1821a266ea 100644 --- a/test/arrays.spec.ts +++ b/test/arrays.spec.ts @@ -1,8 +1,8 @@ import {ErrorType, HyperFormula} from '../src' -import {ErrorMessage} from '../src/error-message' -import {adr, detailedError, detailedErrorWithOrigin, expectVerticesOfTypes, noSpace} from './testUtils' import {MatrixVertex, ValueCellVertex} from '../src/DependencyGraph' +import {ErrorMessage} from '../src/error-message' import {MatrixSize} from '../src/MatrixSize' +import {adr, detailedError, detailedErrorWithOrigin, expectVerticesOfTypes, noSpace} from './testUtils' describe('without arrayformula, with useArrayArithmetic flag', () => { it('unary op, scalar ret', () => { diff --git a/test/content-changes.spec.ts b/test/content-changes.spec.ts index 2decce3eed..79595f1b70 100644 --- a/test/content-changes.spec.ts +++ b/test/content-changes.spec.ts @@ -1,8 +1,6 @@ -import {simpleCellAddress} from '../src/Cell' import {CellValueChange, ChangeExporter, ContentChanges} from '../src/ContentChanges' import {SimpleRangeValue} from '../src/interpreter/SimpleRangeValue' import {adr} from './testUtils' -import {HyperFormula} from '../src' class IdentityChangeExporter implements ChangeExporter{ exportChange(change: CellValueChange): CellValueChange { diff --git a/test/cruds/adding-row.spec.ts b/test/cruds/adding-row.spec.ts index 56508633e8..be0b8b12bc 100644 --- a/test/cruds/adding-row.spec.ts +++ b/test/cruds/adding-row.spec.ts @@ -2,9 +2,9 @@ import {ExportedCellChange, HyperFormula, SheetSizeLimitExceededError} from '../ import {AbsoluteCellRange} from '../../src/AbsoluteCellRange' import {Config} from '../../src/Config' import {FormulaCellVertex, MatrixVertex} from '../../src/DependencyGraph' +import {AlwaysDense} from '../../src/DependencyGraph/AddressMapping/ChooseAddressMappingPolicy' import {ColumnIndex} from '../../src/Lookup/ColumnIndex' import {adr, expectArrayWithSameContent, expectEngineToBeTheSameAs, extractMatrixRange} from '../testUtils' -import {AlwaysDense} from '../../src/DependencyGraph/AddressMapping/ChooseAddressMappingPolicy' describe('Adding row - checking if its possible', () => { it('no if starting row is negative', () => { diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index d1f27acd2c..8691bff8e2 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -6,6 +6,7 @@ import {EmptyCellVertex, MatrixVertex, ValueCellVertex} from '../../src/Dependen import {ErrorMessage} from '../../src/error-message' import {SheetSizeLimitExceededError} from '../../src/errors' import {ColumnIndex} from '../../src/Lookup/ColumnIndex' +import {MatrixSize} from '../../src/MatrixSize' import { adr, colEnd, @@ -18,7 +19,6 @@ import { rowEnd, rowStart } from '../testUtils' -import {MatrixSize} from '../../src/MatrixSize' describe('Changing cell content - checking if its possible', () => { it('address should have valid coordinates', () => { diff --git a/test/cruds/removing-rows.spec.ts b/test/cruds/removing-rows.spec.ts index cdf5520ccc..5564eaff4f 100644 --- a/test/cruds/removing-rows.spec.ts +++ b/test/cruds/removing-rows.spec.ts @@ -11,7 +11,8 @@ import { expectReferenceToHaveRefError, extractMatrixRange, extractRange, - extractReference, noSpace, + extractReference, + noSpace, verifyRangesInSheet, verifyValues, } from '../testUtils' diff --git a/test/graphComparator.ts b/test/graphComparator.ts index e2692a0b68..353b3431f3 100644 --- a/test/graphComparator.ts +++ b/test/graphComparator.ts @@ -5,7 +5,8 @@ import {SimpleCellAddress, simpleCellAddress} from '../src/Cell' import { EmptyCellVertex, FormulaCellVertex, - MatrixVertex, ParsingErrorVertex, + MatrixVertex, + ParsingErrorVertex, RangeVertex, ValueCellVertex, Vertex, diff --git a/test/matrix-mapping.spec.ts b/test/matrix-mapping.spec.ts index c56f5bd43b..17720c1479 100644 --- a/test/matrix-mapping.spec.ts +++ b/test/matrix-mapping.spec.ts @@ -1,8 +1,8 @@ -import {MatrixMapping, MatrixVertex} from '../src/DependencyGraph' -import {adr} from './testUtils' import {AbsoluteCellRange} from '../src/AbsoluteCellRange' -import {buildNumberAst} from '../src/parser/Ast' +import {MatrixMapping, MatrixVertex} from '../src/DependencyGraph' import {MatrixSize} from '../src/MatrixSize' +import {buildNumberAst} from '../src/parser/Ast' +import {adr} from './testUtils' describe('MatrixMapping', () => { it('should be empty', () => { diff --git a/test/testUtils.ts b/test/testUtils.ts index 78bfd091a7..ec3734abc3 100644 --- a/test/testUtils.ts +++ b/test/testUtils.ts @@ -4,6 +4,7 @@ import {CellError, SimpleCellAddress, simpleCellAddress} from '../src/Cell' import {Config} from '../src/Config' import {DateTimeHelper} from '../src/DateTimeHelper' import {FormulaCellVertex, MatrixVertex, RangeVertex} from '../src/DependencyGraph' +import {ErrorMessage} from '../src/error-message' import {defaultStringifyDateTime} from '../src/format/format' import {complex} from '../src/interpreter/ArithmeticHelper' import { @@ -17,7 +18,6 @@ import { } from '../src/parser' import {ColumnRangeAst, RowRangeAst} from '../src/parser/Ast' import {EngineComparator} from './graphComparator' -import {ErrorMessage} from '../src/error-message' export const extractReference = (engine: HyperFormula, address: SimpleCellAddress): CellAddress => { return ((engine.addressMapping.fetchCell(address) as FormulaCellVertex).getFormula(engine.lazilyTransformingAstService) as CellReferenceAst).reference From 7d26afca3c319bf273f262aa28e2291ea7b7493c Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 18 Jun 2021 14:38:50 +0200 Subject: [PATCH 56/87] Enable tests --- test/cruds/change-cell-content.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 8691bff8e2..f7b3d39c1d 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -698,7 +698,7 @@ describe('column ranges', () => { expect(engine.getCellValue(adr('C1'))).toEqual(6) }) - it.skip('works when adding matrix', () => { + it('works when adding matrix', () => { const engine = HyperFormula.buildFromArray([ ['=SUM(B:C)'], ['1'], @@ -744,7 +744,7 @@ describe('row ranges', () => { expect(engine.getCellValue(adr('A3'))).toEqual(6) }) - it.skip('works when adding matrix', () => { + it('works when adding matrix', () => { const engine = HyperFormula.buildFromArray([ ['=SUM(2:3)', '1', '2'], ]) From 3152155bb4e826185f745247224603ce0a2c64dc Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 20 Jun 2021 11:46:04 +0200 Subject: [PATCH 57/87] ColumnIndex specs for arrays --- test/column-index.spec.ts | 167 +++++++++++++++++++++++++++++++++++++- test/testUtils.ts | 42 +++++++++- 2 files changed, 206 insertions(+), 3 deletions(-) diff --git a/test/column-index.spec.ts b/test/column-index.spec.ts index 82f686a001..8a6422cf5b 100644 --- a/test/column-index.spec.ts +++ b/test/column-index.spec.ts @@ -12,7 +12,8 @@ import {ColumnIndex} from '../src/Lookup/ColumnIndex' import {NamedExpressions} from '../src/NamedExpressions' import {ColumnsSpan, RowsSpan} from '../src/Span' import {Statistics} from '../src/statistics' -import {adr} from './testUtils' +import {adr, columnIndexToSheet, expectArrayWithSameContent, expectColumnIndexToMatchSheet} from './testUtils' +import {HyperFormula, Sheet} from '../src' function buildEmptyIndex(transformingService: LazilyTransformingAstService, config: Config, statistics: Statistics): ColumnIndex { const functionRegistry = new FunctionRegistry(config) @@ -554,3 +555,167 @@ describe('ColumnIndex - lazy cruds', () => { expect(index.getValueIndex(0, 0, 2).index).toEqual([2]) }) }) + +describe('Arrays', () => { + it('should update column index with array values', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=-A1:B1'], + ], {useArrayArithmetic: true, useColumnIndex: true }) + + expectColumnIndexToMatchSheet([ + [1, 2, -1, -2] + ], engine) + }) + + it('should remove values from index when REF', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=-A1:B1'], + ], {useArrayArithmetic: true, useColumnIndex: true }) + + engine.setCellContents(adr('D1'), [['foo']]) + + expectColumnIndexToMatchSheet([ + [1, 2, null, 'foo'] + ], engine) + }) + + it('should remove values from index when replacing array with scalar', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=-A1:B1'], + ], {useArrayArithmetic: true, useColumnIndex: true }) + + engine.setCellContents(adr('C1'), [['foo']]) + + expectColumnIndexToMatchSheet([ + [1, 2, 'foo'] + ], engine) + }) + + it('should remove values when replacing array with smaller one', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=-A1:B1'], + ], {useArrayArithmetic: true, useColumnIndex: true }) + + engine.setCellContents(adr('C1'), [['=2*A1:A1']]) + + expectColumnIndexToMatchSheet([ + [1, 2, 2] + ], engine) + }) + + it('should update index when replacing array with another one', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=-A1:B1'], + ], {useArrayArithmetic: true, useColumnIndex: true }) + + engine.setCellContents(adr('C1'), [['=2*A1:B1']]) + + expectColumnIndexToMatchSheet([ + [1, 2, 2, 4] + ], engine) + }) + + it('should move array values when adding rows above array', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B3:B4'], + [null, 'foo'], + [null, 1], + [null, 2], + ], {useArrayArithmetic: true, useColumnIndex: true }) + + engine.addRows(0, [0, 1]) + + expectColumnIndexToMatchSheet([ + [null], + [-1], + [-2, 'foo'], + [null, 1], + [null, 2], + ], engine) + }) + + it('should not move array values when adding rows', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B3:B4'], + [null, 'foo'], + [-2, 1], + [-1, 2], + ], {useArrayArithmetic: true, useColumnIndex: true }) + + engine.addRows(0, [1, 1]) + + expectColumnIndexToMatchSheet([ + [-1], + [-2], + [null, 'foo'], + [-2, 1], + [-1, 2], + ], engine) + }) + + it('should move array values when removing rows above array', () => { + const engine = HyperFormula.buildFromArray([ + [], + ['=-B3:B4'], + [null, 1], + [null, 2], + ], {useArrayArithmetic: true, useColumnIndex: true }) + + engine.removeRows(0, [0, 1]) + + expectColumnIndexToMatchSheet([ + [-1], + [-2, 1], + [null, 2] + ], engine) + }) + + it('should not move array values when removing rows', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B4:B5'], + [null], + [null, 'foo'], + [-2, 1], + [-1, 2], + ], {useArrayArithmetic: true, useColumnIndex: true }) + + engine.removeRows(0, [1, 1]) + + expectColumnIndexToMatchSheet([ + [-1], + [-2, 'foo'], + [-2, 1], + [-1, 2], + ], engine) + }) + + it('should remove array values from index when removing row with left corner', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B2:B3'], + [null, 1], + [null, 2], + ], {useArrayArithmetic: true, useColumnIndex: true}) + + engine.removeRows(0, [0, 1]) + + expectColumnIndexToMatchSheet([ + [null, 1], + [null, 2] + ], engine) + }) + + it('should remove array values from index when REF after removing rows', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B2:B3'], + [null, 1], + [3, 2], + ], {useArrayArithmetic: true, useColumnIndex: true}) + + engine.removeRows(0, [1, 1]) + + expectColumnIndexToMatchSheet([ + [], + [3, 2] + ], engine) + }) +}) diff --git a/test/testUtils.ts b/test/testUtils.ts index ec3734abc3..1a997d9300 100644 --- a/test/testUtils.ts +++ b/test/testUtils.ts @@ -1,10 +1,9 @@ -import {CellValue, DetailedCellError, ErrorType, HyperFormula} from '../src' +import {CellValue, DetailedCellError, ErrorType, HyperFormula, Sheet, SheetDimensions} from '../src' import {AbsoluteCellRange, AbsoluteColumnRange, AbsoluteRowRange} from '../src/AbsoluteCellRange' import {CellError, SimpleCellAddress, simpleCellAddress} from '../src/Cell' import {Config} from '../src/Config' import {DateTimeHelper} from '../src/DateTimeHelper' import {FormulaCellVertex, MatrixVertex, RangeVertex} from '../src/DependencyGraph' -import {ErrorMessage} from '../src/error-message' import {defaultStringifyDateTime} from '../src/format/format' import {complex} from '../src/interpreter/ArithmeticHelper' import { @@ -18,6 +17,8 @@ import { } from '../src/parser' import {ColumnRangeAst, RowRangeAst} from '../src/parser/Ast' import {EngineComparator} from './graphComparator' +import {ErrorMessage} from '../src/error-message' +import {ColumnIndex} from '../src/Lookup/ColumnIndex' export const extractReference = (engine: HyperFormula, address: SimpleCellAddress): CellAddress => { return ((engine.addressMapping.fetchCell(address) as FormulaCellVertex).getFormula(engine.lazilyTransformingAstService) as CellReferenceAst).reference @@ -205,3 +206,40 @@ export function expectVerticesOfTypes(engine: HyperFormula, types: any[][], shee } } } + +export function columnIndexToSheet(columnIndex: ColumnIndex, width: number, height: number, sheet: number = 0): any[][] { + const result: any[][] = [] + for (let col=0; col { + if (row) { + row.length = dimensions.width + return Array.from(row, v => v || null) + } + return Array(dimensions.width).fill(null) + }) +} + +export function expectColumnIndexToMatchSheet(expected: Sheet, engine: HyperFormula, sheetId: number = 0) { + const columnIndex = engine.columnSearch as ColumnIndex + expect(columnIndex).toBeInstanceOf(ColumnIndex) + const exportedColumnIndex = columnIndexToSheet(columnIndex, engine.getSheetDimensions(sheetId).width, sheetId) + const dimensions = engine.getSheetDimensions(0) + expectArrayWithSameContent(normalizeSheet(expected, dimensions), normalizeSheet(exportedColumnIndex, dimensions)) +} + From 73b69501d68d96b66cb99e78e9fcdd0c5fa75f6f Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Wed, 23 Jun 2021 15:58:35 +0200 Subject: [PATCH 58/87] Fix test --- test/cruds/removing-rows.spec.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/test/cruds/removing-rows.spec.ts b/test/cruds/removing-rows.spec.ts index 5564eaff4f..a2139b76e1 100644 --- a/test/cruds/removing-rows.spec.ts +++ b/test/cruds/removing-rows.spec.ts @@ -64,7 +64,6 @@ describe('Removing rows - checking if its possible', () => { ['1', '2'], ['3', '4'], ['=TRANSPOSE(A1:B2)'], - ['13'], ]) expect(engine.isItPossibleToRemoveRows(0, [1, 1])).toEqual(true) From 7d1df27069f0222a419e725426a5046d769509fc Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Wed, 23 Jun 2021 16:07:13 +0200 Subject: [PATCH 59/87] Ensure DependencyGraph changes are cleared after building graph --- src/GraphBuilder.ts | 1 + test/arrays.spec.ts | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/src/GraphBuilder.ts b/src/GraphBuilder.ts index d0769a360a..7f37f746c1 100644 --- a/src/GraphBuilder.ts +++ b/src/GraphBuilder.ts @@ -51,6 +51,7 @@ export class GraphBuilder { */ public buildGraph(sheets: Sheets) { const dependencies = this.buildStrategy.run(sheets) + this.dependencyGraph.getAndClearContentChanges() this.processDependencies(dependencies) } diff --git a/test/arrays.spec.ts b/test/arrays.spec.ts index 1821a266ea..05bc79b2d8 100644 --- a/test/arrays.spec.ts +++ b/test/arrays.spec.ts @@ -431,4 +431,13 @@ describe('build from array', () => { [ValueCellVertex, undefined], ]) }) + + it('DependencyGraph changes should be empty after building fresh engine', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D2', null], + [1, null] + ], {useArrayArithmetic: true}) + + expect(engine.dependencyGraph.getAndClearContentChanges().isEmpty()).toEqual(true) + }) }) From d9bf8310a6a55b442bd5a67678b7adb0e342172f Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 25 Jun 2021 10:27:37 +0200 Subject: [PATCH 60/87] Ignore EmptyValue in columnIndex --- src/Lookup/ColumnIndex.ts | 14 ++++++++--- test/column-index.spec.ts | 50 ++++++++++++++++++++++++++------------- 2 files changed, 44 insertions(+), 20 deletions(-) diff --git a/src/Lookup/ColumnIndex.ts b/src/Lookup/ColumnIndex.ts index d5c37baa6a..46b9b985ad 100644 --- a/src/Lookup/ColumnIndex.ts +++ b/src/Lookup/ColumnIndex.ts @@ -10,7 +10,13 @@ import {AddRowsTransformer} from '../dependencyTransformers/AddRowsTransformer' import {RemoveRowsTransformer} from '../dependencyTransformers/RemoveRowsTransformer' import {FormulaTransformer} from '../dependencyTransformers/Transformer' import {forceNormalizeString} from '../interpreter/ArithmeticHelper' -import {getRawValue, RawInterpreterValue, RawNoErrorScalarValue, RawScalarValue} from '../interpreter/InterpreterValue' +import { + EmptyValue, + getRawValue, + RawInterpreterValue, + RawNoErrorScalarValue, + RawScalarValue +} from '../interpreter/InterpreterValue' import {SimpleRangeValue} from '../interpreter/SimpleRangeValue' import {LazilyTransformingAstService} from '../LazilyTransformingAstService' import {ColumnsSpan, RowsSpan} from '../Span' @@ -43,11 +49,13 @@ export class ColumnIndex implements ColumnSearchStrategy { } public add(value: RawInterpreterValue, address: SimpleCellAddress) { - if (value instanceof SimpleRangeValue) { + if (value === EmptyValue || value instanceof CellError) { + return + } else if (value instanceof SimpleRangeValue) { for (const [matrixValue, cellAddress] of value.entriesFromTopLeftCorner(address)) { this.addSingleCellValue(getRawValue(matrixValue), cellAddress) } - } else if (!(value instanceof CellError)) { + } else { this.addSingleCellValue(value, address) } } diff --git a/test/column-index.spec.ts b/test/column-index.spec.ts index 8a6422cf5b..953d8578e8 100644 --- a/test/column-index.spec.ts +++ b/test/column-index.spec.ts @@ -12,8 +12,9 @@ import {ColumnIndex} from '../src/Lookup/ColumnIndex' import {NamedExpressions} from '../src/NamedExpressions' import {ColumnsSpan, RowsSpan} from '../src/Span' import {Statistics} from '../src/statistics' -import {adr, columnIndexToSheet, expectArrayWithSameContent, expectColumnIndexToMatchSheet} from './testUtils' -import {HyperFormula, Sheet} from '../src' +import {adr, expectColumnIndexToMatchSheet} from './testUtils' +import {HyperFormula} from '../src' +import {EmptyValue} from '../src/interpreter/InterpreterValue' function buildEmptyIndex(transformingService: LazilyTransformingAstService, config: Config, statistics: Statistics): ColumnIndex { const functionRegistry = new FunctionRegistry(config) @@ -114,6 +115,12 @@ describe('ColumnIndex#add', () => { expect(columnMap.get('ŧ')!.index.length).toBe(1) // eslint-enable @typescript-eslint/no-non-null-assertion }) + + it('should ignore EmptyValue', () => { + const index = buildEmptyIndex(transformingService, new Config(), statistics) + index.add(EmptyValue, adr('A1')) + expect(index.getColumnMap(0, 0).size).toBe(0) + }) }) describe('ColumnIndex change/remove', () => { @@ -217,6 +224,15 @@ describe('ColumnIndex change/remove', () => { expect(index.getColumnMap(0, 0).keys()).not.toContain(1) expect(index.getColumnMap(0, 0).keys()).not.toContain(error) }) + + it('should ignore EmptyValue', () => { + const index = buildEmptyIndex(transformingService, new Config(), statistics) + index.add(1, adr('A1')) + + index.change(1, EmptyValue, adr('A1')) + + expect(index.getColumnMap(0, 0).size).toBe(0) + }) }) describe('ColumnIndex#addColumns', () => { @@ -311,7 +327,7 @@ describe('ColumnIndex#find', () => { const stats = new Statistics() const transformService = new LazilyTransformingAstService(stats) - it('should find row number', function() { + it('should find row number', function () { const index = buildEmptyIndex(transformService, new Config(), stats) index.add(1, adr('A2')) @@ -320,7 +336,7 @@ describe('ColumnIndex#find', () => { expect(row).toBe(1) }) - it('should find smallest row number for value', function() { + it('should find smallest row number for value', function () { const index = buildEmptyIndex(transformService, new Config(), stats) index.add(1, adr('A4')) @@ -515,7 +531,7 @@ describe('ColumnIndex#removeRows', () => { }) describe('ColumnIndex - lazy cruds', () => { - it('should add rows only in specific column after find', function() { + it('should add rows only in specific column after find', function () { const stats = new Statistics() const transformService = new LazilyTransformingAstService(stats) const index = buildEmptyIndex(transformService, new Config(), stats) @@ -535,7 +551,7 @@ describe('ColumnIndex - lazy cruds', () => { expect(index.getValueIndex(0, 1, 1).index).toEqual([1]) }) - it('should add rows only for specific value after find', function() { + it('should add rows only for specific value after find', function () { const stats = new Statistics() const transformService = new LazilyTransformingAstService(stats) const index = buildEmptyIndex(transformService, new Config(), stats) @@ -560,7 +576,7 @@ describe('Arrays', () => { it('should update column index with array values', () => { const engine = HyperFormula.buildFromArray([ [1, 2, '=-A1:B1'], - ], {useArrayArithmetic: true, useColumnIndex: true }) + ], {useArrayArithmetic: true, useColumnIndex: true}) expectColumnIndexToMatchSheet([ [1, 2, -1, -2] @@ -570,7 +586,7 @@ describe('Arrays', () => { it('should remove values from index when REF', () => { const engine = HyperFormula.buildFromArray([ [1, 2, '=-A1:B1'], - ], {useArrayArithmetic: true, useColumnIndex: true }) + ], {useArrayArithmetic: true, useColumnIndex: true}) engine.setCellContents(adr('D1'), [['foo']]) @@ -582,7 +598,7 @@ describe('Arrays', () => { it('should remove values from index when replacing array with scalar', () => { const engine = HyperFormula.buildFromArray([ [1, 2, '=-A1:B1'], - ], {useArrayArithmetic: true, useColumnIndex: true }) + ], {useArrayArithmetic: true, useColumnIndex: true}) engine.setCellContents(adr('C1'), [['foo']]) @@ -594,7 +610,7 @@ describe('Arrays', () => { it('should remove values when replacing array with smaller one', () => { const engine = HyperFormula.buildFromArray([ [1, 2, '=-A1:B1'], - ], {useArrayArithmetic: true, useColumnIndex: true }) + ], {useArrayArithmetic: true, useColumnIndex: true}) engine.setCellContents(adr('C1'), [['=2*A1:A1']]) @@ -606,7 +622,7 @@ describe('Arrays', () => { it('should update index when replacing array with another one', () => { const engine = HyperFormula.buildFromArray([ [1, 2, '=-A1:B1'], - ], {useArrayArithmetic: true, useColumnIndex: true }) + ], {useArrayArithmetic: true, useColumnIndex: true}) engine.setCellContents(adr('C1'), [['=2*A1:B1']]) @@ -621,7 +637,7 @@ describe('Arrays', () => { [null, 'foo'], [null, 1], [null, 2], - ], {useArrayArithmetic: true, useColumnIndex: true }) + ], {useArrayArithmetic: true, useColumnIndex: true}) engine.addRows(0, [0, 1]) @@ -640,7 +656,7 @@ describe('Arrays', () => { [null, 'foo'], [-2, 1], [-1, 2], - ], {useArrayArithmetic: true, useColumnIndex: true }) + ], {useArrayArithmetic: true, useColumnIndex: true}) engine.addRows(0, [1, 1]) @@ -652,14 +668,14 @@ describe('Arrays', () => { [-1, 2], ], engine) }) - - it('should move array values when removing rows above array', () => { + + it('should move array values when removing rows above array', () => { const engine = HyperFormula.buildFromArray([ [], ['=-B3:B4'], [null, 1], [null, 2], - ], {useArrayArithmetic: true, useColumnIndex: true }) + ], {useArrayArithmetic: true, useColumnIndex: true}) engine.removeRows(0, [0, 1]) @@ -677,7 +693,7 @@ describe('Arrays', () => { [null, 'foo'], [-2, 1], [-1, 2], - ], {useArrayArithmetic: true, useColumnIndex: true }) + ], {useArrayArithmetic: true, useColumnIndex: true}) engine.removeRows(0, [1, 1]) From b28ed81b47666da3b4c640e261ea395115ebbd9e Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 25 Jun 2021 11:34:31 +0200 Subject: [PATCH 61/87] Apply array changes in all cases --- src/ContentChanges.ts | 10 ++++++-- src/DependencyGraph/DependencyGraph.ts | 13 ++++++---- src/Lookup/ColumnBinarySearch.ts | 3 +++ src/Lookup/ColumnIndex.ts | 9 +++++++ src/Lookup/SearchStrategy.ts | 3 +++ src/Operations.ts | 33 ++++++++++++++++-------- test/column-index.spec.ts | 12 +++++++++ test/cruds/change-cell-content.spec.ts | 35 ++++++++++++++++++++++++-- 8 files changed, 99 insertions(+), 19 deletions(-) diff --git a/src/ContentChanges.ts b/src/ContentChanges.ts index e5f0bc55ba..38abf64dd3 100644 --- a/src/ContentChanges.ts +++ b/src/ContentChanges.ts @@ -10,6 +10,7 @@ import {SimpleRangeValue} from './interpreter/SimpleRangeValue' export interface CellValueChange { address: SimpleCellAddress, value: InterpreterValue, + oldValue?: InterpreterValue, } export interface ChangeExporter { @@ -38,6 +39,10 @@ export class ContentChanges { this.addInterpreterValue(newValue, address) } + public addChangeWithOldValue(newValue: InterpreterValue, address: SimpleCellAddress, oldValue: InterpreterValue): void { + this.addInterpreterValue(newValue, address, oldValue) + } + public exportChanges(exporter: ChangeExporter): T[] { let ret: T[] = [] this.changes.forEach((e) => { @@ -69,10 +74,11 @@ export class ContentChanges { this.changes.set(addressKey((address)), change) } - private addInterpreterValue(value: InterpreterValue, address: SimpleCellAddress) { + private addInterpreterValue(value: InterpreterValue, address: SimpleCellAddress, oldValue?: InterpreterValue) { this.add(address, { address, - value + value, + oldValue }) } } diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index ed352831f4..bf786f2b7e 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -115,8 +115,8 @@ export class DependencyGraph { this.matrixMapping.removeMatrix(vertex.getRange()) } if (vertex instanceof ValueCellVertex) { - const oldValue = vertex.getValues() - if (oldValue.rawValue !== value.rawValue) { + const oldValues = vertex.getValues() + if (oldValues.rawValue !== value.rawValue) { vertex.setValues(value) this.graph.markNodeAsSpecialRecentlyChanged(vertex) } @@ -780,10 +780,13 @@ export class DependencyGraph { private cleanAddressMappingUnderMatrix(vertex: MatrixVertex) { const matrixRange = vertex.getRange() for (const address of matrixRange.addresses(this)) { - if (!vertex.isLeftCorner(address)) { - if (this.getCell(address) === vertex) { + if (this.getCell(address) === vertex) { + const oldValue = vertex.getMatrixCellValue(address) + if (vertex.isLeftCorner(address)) { + this.changes.addChangeWithOldValue(new CellError(ErrorType.REF), address, oldValue) + } else { this.addressMapping.removeCell(address) - this.changes.addChange(EmptyValue, address) + this.changes.addChangeWithOldValue(EmptyValue, address, oldValue) } } } diff --git a/src/Lookup/ColumnBinarySearch.ts b/src/Lookup/ColumnBinarySearch.ts index 4ed9c60453..38bb6ef075 100644 --- a/src/Lookup/ColumnBinarySearch.ts +++ b/src/Lookup/ColumnBinarySearch.ts @@ -13,6 +13,7 @@ import {SimpleRangeValue} from '../interpreter/SimpleRangeValue' import {ColumnsSpan} from '../Span' import {AdvancedFind} from './AdvancedFind' import {ColumnSearchStrategy} from './SearchStrategy' +import {CellValueChange} from '../ContentChanges' export class ColumnBinarySearch extends AdvancedFind implements ColumnSearchStrategy { constructor( @@ -29,6 +30,8 @@ export class ColumnBinarySearch extends AdvancedFind implements ColumnSearchStra // eslint-disable-next-line @typescript-eslint/no-unused-vars public change(oldValue: RawScalarValue | undefined, newValue: RawScalarValue, address: SimpleCellAddress): void {} // eslint-disable-next-line @typescript-eslint/no-unused-vars + public applyChanges(contentChanges: CellValueChange[]): void {} + // eslint-disable-next-line @typescript-eslint/no-unused-vars public addColumns(columnsSpan: ColumnsSpan): void {} // eslint-disable-next-line @typescript-eslint/no-unused-vars public removeColumns(columnsSpan: ColumnsSpan): void {} diff --git a/src/Lookup/ColumnIndex.ts b/src/Lookup/ColumnIndex.ts index 46b9b985ad..6f452f9564 100644 --- a/src/Lookup/ColumnIndex.ts +++ b/src/Lookup/ColumnIndex.ts @@ -23,6 +23,7 @@ import {ColumnsSpan, RowsSpan} from '../Span' import {Statistics, StatType} from '../statistics' import {ColumnBinarySearch} from './ColumnBinarySearch' import {ColumnSearchStrategy} from './SearchStrategy' +import {CellValueChange} from '../ContentChanges' type ColumnMap = Map @@ -82,6 +83,14 @@ export class ColumnIndex implements ColumnSearchStrategy { this.add(newValue, address) } + public applyChanges(contentChanges: CellValueChange[]) { + for (const change of contentChanges) { + if (change.oldValue !== undefined) { + this.change(getRawValue(change.oldValue), getRawValue(change.value), change.address) + } + } + } + public moveValues(sourceRange: IterableIterator<[RawScalarValue, SimpleCellAddress]>, toRight: number, toBottom: number, toSheet: number) { for (const [value, address] of sourceRange) { const targetAddress = movedSimpleCellAddress(address, toSheet, toRight, toBottom) diff --git a/src/Lookup/SearchStrategy.ts b/src/Lookup/SearchStrategy.ts index b4e39d5f7c..5b216d4f17 100644 --- a/src/Lookup/SearchStrategy.ts +++ b/src/Lookup/SearchStrategy.ts @@ -12,6 +12,7 @@ import {ColumnsSpan} from '../Span' import {Statistics} from '../statistics/Statistics' import {ColumnBinarySearch} from './ColumnBinarySearch' import {ColumnIndex} from './ColumnIndex' +import {CellValueChange} from '../ContentChanges' export interface SearchStrategy { find(key: RawNoErrorScalarValue, range: SimpleRangeValue, sorted: boolean): number, @@ -26,6 +27,8 @@ export interface ColumnSearchStrategy extends SearchStrategy { change(oldValue: RawInterpreterValue | undefined, newValue: RawInterpreterValue, address: SimpleCellAddress): void, + applyChanges(contentChanges: CellValueChange[]): void, + addColumns(columnsSpan: ColumnsSpan): void, removeColumns(columnsSpan: ColumnsSpan): void, diff --git a/src/Operations.ts b/src/Operations.ts index 7f9cad2de7..50f07901d1 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -5,7 +5,7 @@ import {AbsoluteCellRange} from './AbsoluteCellRange' import {absolutizeDependencies, filterDependenciesOutOfScope} from './absolutizeDependencies' -import {invalidSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from './Cell' +import {equalSimpleCellAddress, invalidSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from './Cell' import {CellContent, CellContentParser, RawCellContent} from './CellContentParser' import {ClipboardCell, ClipboardCellType} from './ClipboardOperations' import {Config} from './Config' @@ -23,7 +23,6 @@ import { SparseStrategy, ValueCellVertex } from './DependencyGraph' -import {FormulaVertex} from './DependencyGraph/FormulaCellVertex' import {RawAndParsedValue} from './DependencyGraph/ValueCellVertex' import {AddColumnsTransformer} from './dependencyTransformers/AddColumnsTransformer' import {AddRowsTransformer} from './dependencyTransformers/AddRowsTransformer' @@ -56,6 +55,7 @@ import {ParsingResult} from './parser/ParserWithCaching' import {findBoundaries, Sheet} from './Sheet' import {ColumnsSpan, RowsSpan} from './Span' import {Statistics, StatType} from './statistics' +import {FormulaVertex} from './DependencyGraph/FormulaCellVertex' export class RemoveRowsCommand { constructor( @@ -692,8 +692,26 @@ export class Operations { } } - public setFormulaToCell(address: SimpleCellAddress, size: MatrixSize, { ast, hasVolatileFunction, hasStructuralChangeFunction, dependencies}: ParsingResult) { + public setParsingErrorToCell(rawInput: string, errors: ParsingError[], address: SimpleCellAddress) { + const oldValue = this.dependencyGraph.getCellValue(address) + const vertex = new ParsingErrorVertex(errors, rawInput) + const arrayChanges = this.dependencyGraph.setParsingErrorToCell(address, vertex) + this.columnSearch.remove(getRawValue(oldValue), address) + this.columnSearch.applyChanges(arrayChanges.getChanges()) + this.changes.addAll(arrayChanges) + this.changes.addChange(vertex.getCellValue(), address) + } + + public setFormulaToCell(address: SimpleCellAddress, size: MatrixSize, { + ast, + hasVolatileFunction, + hasStructuralChangeFunction, + dependencies + }: ParsingResult) { + const oldValue = this.dependencyGraph.getCellValue(address) const arrayChanges = this.dependencyGraph.setFormulaToCell(address, ast, absolutizeDependencies(dependencies, address), size, hasVolatileFunction, hasStructuralChangeFunction) + this.columnSearch.remove(getRawValue(oldValue), address) + this.columnSearch.applyChanges(arrayChanges.getChanges()) this.changes.addAll(arrayChanges) } @@ -701,6 +719,7 @@ export class Operations { const oldValue = this.dependencyGraph.getCellValue(address) const arrayChanges = this.dependencyGraph.setValueToCell(address, value) this.columnSearch.change(getRawValue(oldValue), getRawValue(value.parsedValue), address) + this.columnSearch.applyChanges(arrayChanges.getChanges().filter(change => !equalSimpleCellAddress(change.address, address))) this.changes.addAll(arrayChanges) this.changes.addChange(value.parsedValue, address) } @@ -712,6 +731,7 @@ export class Operations { const oldValue = this.dependencyGraph.getCellValue(address) const arrayChanges = this.dependencyGraph.setCellEmpty(address) this.columnSearch.remove(getRawValue(oldValue), address) + this.columnSearch.applyChanges(arrayChanges.getChanges()) this.changes.addAll(arrayChanges) this.changes.addChange(EmptyValue, address) } @@ -731,13 +751,6 @@ export class Operations { this.dependencyGraph.setFormulaToCell(address, cleanedAst, cleanedDependencies, size, hasVolatileFunction, hasStructuralChangeFunction) } - public setParsingErrorToCell(rawInput: string, errors: ParsingError[], address: SimpleCellAddress) { - const vertex = new ParsingErrorVertex(errors, rawInput) - const arrayChanges = this.dependencyGraph.setParsingErrorToCell(address, vertex) - this.changes.addAll(arrayChanges) - this.changes.addChange(vertex.getCellValue(), address) - } - /** * Returns true if row number is outside of given sheet. * diff --git a/test/column-index.spec.ts b/test/column-index.spec.ts index 953d8578e8..0a1ed98c07 100644 --- a/test/column-index.spec.ts +++ b/test/column-index.spec.ts @@ -619,6 +619,18 @@ describe('Arrays', () => { ], engine) }) + it('shoud remove values when replacing array with parsing error', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=-A1:B1'], + ], {useArrayArithmetic: true, useColumnIndex: true}) + + engine.setCellContents(adr('C1'), [['=SUM(']]) + + expectColumnIndexToMatchSheet([ + [1, 2] + ], engine) + }) + it('should update index when replacing array with another one', () => { const engine = HyperFormula.buildFromArray([ [1, 2, '=-A1:B1'], diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index f7b3d39c1d..f94a042208 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -669,9 +669,40 @@ describe('updating column index', () => { engine.setCellContents(adr('B2'), '8') - expectArrayWithSameContent((engine.columnSearch as ColumnIndex).getValueIndex(0, 1, 4).index, []) + expectArrayWithSameContent((engine.columnSearch as ColumnIndex).getValueIndex(0, 1, 15).index, []) expectArrayWithSameContent((engine.columnSearch as ColumnIndex).getValueIndex(0, 1, 8).index, [1]) }) + + it('should update column index when clearing cell content', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ], {binarySearchThreshold: 1, useColumnIndex: true}) + + engine.setCellContents(adr('B1'), null) + + expectArrayWithSameContent((engine.columnSearch as ColumnIndex).getValueIndex(0, 1, 2).index, []) + }) + + it('should update column index when changing to ParsingError', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ], {binarySearchThreshold: 1, useColumnIndex: true}) + + engine.setCellContents(adr('B1'), '=SUM(') + + expectArrayWithSameContent((engine.columnSearch as ColumnIndex).getValueIndex(0, 1, 2).index, []) + }) + + it('should update column index when changing to formula', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2'], + ], {binarySearchThreshold: 1, useColumnIndex: true}) + + engine.setCellContents(adr('B1'), '=SUM(A1)') + + expectArrayWithSameContent((engine.columnSearch as ColumnIndex).getValueIndex(0, 1, 2).index, []) + expectArrayWithSameContent((engine.columnSearch as ColumnIndex).getValueIndex(0, 1, 1).index, [0]) + }) }) describe('column ranges', () => { @@ -1064,7 +1095,7 @@ describe('arrays', () => { expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), null)) }) - it('should return on changes when trying to clear array cell', () => { + it('should return no changes when trying to clear array cell', () => { const engine = HyperFormula.buildFromArray([ ['1', '2'], ['=-A1:B1'], From 7070b5e9d27183bed6eb3173087f54468386b4bf Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 25 Jun 2021 15:14:32 +0200 Subject: [PATCH 62/87] Gather changes when removing rows --- src/ContentChanges.ts | 6 +----- src/DependencyGraph/DependencyGraph.ts | 12 +++++++----- src/Operations.ts | 4 +++- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/ContentChanges.ts b/src/ContentChanges.ts index 38abf64dd3..72e8e51abd 100644 --- a/src/ContentChanges.ts +++ b/src/ContentChanges.ts @@ -35,11 +35,7 @@ export class ContentChanges { return this } - public addChange(newValue: InterpreterValue, address: SimpleCellAddress): void { - this.addInterpreterValue(newValue, address) - } - - public addChangeWithOldValue(newValue: InterpreterValue, address: SimpleCellAddress, oldValue: InterpreterValue): void { + public addChange(newValue: InterpreterValue, address: SimpleCellAddress, oldValue?: InterpreterValue): void { this.addInterpreterValue(newValue, address, oldValue) } diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index bf786f2b7e..ce577d40ba 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -267,7 +267,7 @@ export class DependencyGraph { return vertex } - public removeRows(removedRows: RowsSpan): Set { + public removeRows(removedRows: RowsSpan): [Set, ContentChanges]{ this.stats.measure(StatType.ADJUSTING_GRAPH, () => { for (const [address, vertex] of this.addressMapping.entriesFromRowsSpan(removedRows)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { @@ -300,7 +300,7 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() - return affectedMatrices + return [affectedMatrices, this.getAndClearContentChanges()] } public removeSheet(removedSheetId: number) { @@ -780,14 +780,16 @@ export class DependencyGraph { private cleanAddressMappingUnderMatrix(vertex: MatrixVertex) { const matrixRange = vertex.getRange() for (const address of matrixRange.addresses(this)) { + const oldValue = vertex.getMatrixCellValue(address) if (this.getCell(address) === vertex) { - const oldValue = vertex.getMatrixCellValue(address) if (vertex.isLeftCorner(address)) { - this.changes.addChangeWithOldValue(new CellError(ErrorType.REF), address, oldValue) + this.changes.addChange(new CellError(ErrorType.REF), address, oldValue) } else { this.addressMapping.removeCell(address) - this.changes.addChangeWithOldValue(EmptyValue, address, oldValue) + this.changes.addChange(EmptyValue, address, oldValue) } + } else { + this.changes.addChange(EmptyValue, address, oldValue) } } } diff --git a/src/Operations.ts b/src/Operations.ts index 50f07901d1..f04b57b04e 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -483,7 +483,9 @@ export class Operations { removedCells.push({address, cellType: this.getClipboardCell(address)}) } - const affectedMatrices = this.dependencyGraph.removeRows(rowsToRemove) + const [affectedMatrices, changes] = this.dependencyGraph.removeRows(rowsToRemove) + + this.columnSearch.applyChanges(changes.getChanges()) let version: number this.stats.measure(StatType.TRANSFORM_ASTS, () => { From 346e5d4c9e533395afbd44262142792d5d867f32 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 25 Jun 2021 16:20:43 +0200 Subject: [PATCH 63/87] Make sure range edges are adjusted properly --- src/Cell.ts | 14 ++-- src/DependencyGraph/DependencyGraph.ts | 47 ++++--------- src/HyperFormula.ts | 94 +++++++++++++------------- test/cruds/change-cell-content.spec.ts | 50 ++++++++++---- 4 files changed, 104 insertions(+), 101 deletions(-) diff --git a/src/Cell.ts b/src/Cell.ts index 45a1cdb317..c596805cc5 100644 --- a/src/Cell.ts +++ b/src/Cell.ts @@ -109,11 +109,11 @@ export const getCellValueType = (cellValue: InterpreterValue): CellValueType => return CellValueType.ERROR } - if(typeof cellValue === 'string') { + if (typeof cellValue === 'string') { return CellValueType.STRING - } else if(isExtendedNumber(cellValue)) { + } else if (isExtendedNumber(cellValue)) { return CellValueType.NUMBER - } else if(typeof cellValue === 'boolean') { + } else if (typeof cellValue === 'boolean') { return CellValueType.BOOLEAN } @@ -121,7 +121,7 @@ export const getCellValueType = (cellValue: InterpreterValue): CellValueType => } export const getCellValueDetailedType = (cellValue: InterpreterValue): CellValueDetailedType => { - if(isExtendedNumber(cellValue)) { + if (isExtendedNumber(cellValue)) { return getTypeOfExtendedNumber(cellValue) } else { return getCellValueType(cellValue) as CellValueDetailedType @@ -129,7 +129,7 @@ export const getCellValueDetailedType = (cellValue: InterpreterValue): CellValue } export const getCellValueFormat = (cellValue: InterpreterValue): string | undefined => { - if(isExtendedNumber(cellValue)) { + if (isExtendedNumber(cellValue)) { return getFormatOfExtendedNumber(cellValue) } else { return undefined @@ -145,7 +145,7 @@ export class CellError { } public attachAddress(address: SimpleCellAddress): CellError { - if(this.address === undefined) { + if (this.address === undefined) { return new CellError(this.type, this.message, address) } else { return this @@ -192,7 +192,7 @@ export const addressesEqual = (left: SimpleCellAddress, right: SimpleCellAddress export const addressKey = (address: SimpleCellAddress) => `${address.sheet},${address.row},${address.col}` export function isSimpleCellAddress(obj: any): obj is SimpleCellAddress { - if( obj && (typeof obj === 'object' || typeof obj === 'function')) { + if (obj && (typeof obj === 'object' || typeof obj === 'function')) { return 'col' in obj && typeof obj.col === 'number' && 'row' in obj && typeof obj.row === 'number' && 'sheet' in obj && typeof obj.sheet === 'number' } else { return false diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index ce577d40ba..c94e4038a6 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -750,12 +750,12 @@ export class DependencyGraph { public shrinkMatrixToCorner(matrix: MatrixVertex) { this.cleanAddressMappingUnderMatrix(matrix) - for (const adjacentVertex of this.adjacentFormulas(matrix)) { + for (const adjacentVertex of this.adjacentMatrixVertices(matrix)) { let relevantDependencies if (adjacentVertex instanceof FormulaVertex) { - relevantDependencies = this.formulaDependenciesToMatrix(adjacentVertex, matrix) + relevantDependencies = this.formulaDirectDependenciesToMatrix(adjacentVertex, matrix) } else { - relevantDependencies = this.rangeDependenciesToMatrix(adjacentVertex, matrix) + relevantDependencies = this.rangeDirectDependenciesToMatrix(adjacentVertex, matrix) } let dependentToCorner = false for (const [address, vertex] of relevantDependencies) { @@ -794,15 +794,7 @@ export class DependencyGraph { } } - private* rangeDependenciesToMatrix(range: RangeVertex, matrix: MatrixVertex): IterableIterator<[SimpleCellAddress, CellVertex]> { - for (const [address, vertex] of this.rangeDependencyQuery2(range)) { - if (matrix.getRange().addressInRange(address)) { - yield [address, vertex] - } - } - } - - private* formulaDependenciesToMatrix(vertex: FormulaVertex, matrix: MatrixVertex): IterableIterator<[SimpleCellAddress, CellVertex]> { + private* formulaDirectDependenciesToMatrix(vertex: FormulaVertex, matrix: MatrixVertex): IterableIterator<[SimpleCellAddress, CellVertex]> { const [, formulaDependencies] = this.formulaDependencyQuery(vertex) ?? [] if (formulaDependencies === undefined) { return @@ -818,32 +810,23 @@ export class DependencyGraph { } } - private* adjacentFormulas(vertex: Vertex): IterableIterator { - const adjacentNodes = this.graph.adjacentNodes(vertex) - for (const item of adjacentNodes) { - if (item instanceof FormulaVertex || item instanceof RangeVertex) { - yield item + private* rangeDirectDependenciesToMatrix(vertex: RangeVertex, matrix: MatrixVertex): IterableIterator<[SimpleCellAddress, CellVertex]> { + const { restRange: range } = this.rangeMapping.findSmallerRange(vertex.range) + for (const address of range.addresses(this)) { + if (matrix.getRange().addressInRange(address)) { + const cell = this.fetchCellOrCreateEmpty(address) + yield [address, cell] } } } - private rangeDependencyQuery2 = (vertex: RangeVertex) => { - const allDeps: [SimpleCellAddress, CellVertex][] = [] - const {smallerRangeVertex, restRange} = this.rangeMapping.findSmallerRange(vertex.range) //checking whether this range was splitted by bruteForce or not - let range - if (smallerRangeVertex !== undefined && this.graph.adjacentNodes(smallerRangeVertex).has(vertex)) { - range = restRange - } else { //did we ever need to use full range - range = vertex.range - } - for (const address of range.addresses(this)) { - const cell = this.fetchCellOrCreateEmpty(address) - if (cell instanceof EmptyCellVertex) { - cell.address = address + private* adjacentMatrixVertices(vertex: MatrixVertex): IterableIterator { + const adjacentNodes = this.graph.adjacentNodes(vertex) + for (const item of adjacentNodes) { + if (item instanceof FormulaVertex || item instanceof RangeVertex) { + yield item } - allDeps.push([address, cell]) } - return allDeps } private rangeDependencyQuery = (vertex: RangeVertex) => { diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index a5a6e52778..47f69abd31 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -617,7 +617,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public getCellValue(cellAddress: SimpleCellAddress): CellValue { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } this.ensureEvaluationIsNotSuspended() @@ -653,7 +653,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public getCellFormula(cellAddress: SimpleCellAddress): string | undefined { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } return this._serialization.getCellFormula(cellAddress) @@ -683,7 +683,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public getCellSerialized(cellAddress: SimpleCellAddress): RawCellContent { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } this.ensureEvaluationIsNotSuspended() @@ -1128,7 +1128,7 @@ export class HyperFormula implements TypedEmitter { */ public isItPossibleToSetCellContents(address: SimpleCellAddress | SimpleCellRange): boolean { let range - if(isSimpleCellAddress(address)) { + if (isSimpleCellAddress(address)) { range = new AbsoluteCellRange(address, address) } else if (isSimpleCellRange(address)) { range = new AbsoluteCellRange(address.start, address.end) @@ -1137,7 +1137,7 @@ export class HyperFormula implements TypedEmitter { } try { this._crudOperations.ensureRangeInSizeLimits(range) - for(const it of range.addresses(this._dependencyGraph)) { + for (const it of range.addresses(this._dependencyGraph)) { this._crudOperations.ensureItIsPossibleToChangeContent(it) } } catch (e) { @@ -1836,10 +1836,10 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public isItPossibleToMoveCells(source: SimpleCellRange, destinationLeftCorner: SimpleCellAddress): boolean { - if(!isSimpleCellAddress(destinationLeftCorner)) { + if (!isSimpleCellAddress(destinationLeftCorner)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'destinationLeftCorner') } - if(!isSimpleCellRange(source)) { + if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } try { @@ -1890,10 +1890,10 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public moveCells(source: SimpleCellRange, destinationLeftCorner: SimpleCellAddress): ExportedChange[] { - if(!isSimpleCellAddress(destinationLeftCorner)) { + if (!isSimpleCellAddress(destinationLeftCorner)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'destinationLeftCorner') } - if(!isSimpleCellRange(source)) { + if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } const range = new AbsoluteCellRange(source.start, source.end) @@ -2087,7 +2087,7 @@ export class HyperFormula implements TypedEmitter { * @category Clipboard */ public copy(source: SimpleCellRange): CellValue[][] { - if(!isSimpleCellRange(source)) { + if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } const range = new AbsoluteCellRange(source.start, source.end) @@ -2119,7 +2119,7 @@ export class HyperFormula implements TypedEmitter { * @category Clipboard */ public cut(source: SimpleCellRange): CellValue[][] { - if(!isSimpleCellRange(source)) { + if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } const range = new AbsoluteCellRange(source.start, source.end) @@ -2161,7 +2161,7 @@ export class HyperFormula implements TypedEmitter { * @category Clipboard */ public paste(targetLeftCorner: SimpleCellAddress): ExportedChange[] { - if(!isSimpleCellAddress(targetLeftCorner)) { + if (!isSimpleCellAddress(targetLeftCorner)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'targetLeftCorner') } this.ensureEvaluationIsNotSuspended() @@ -2283,7 +2283,7 @@ export class HyperFormula implements TypedEmitter { * @category Ranges */ public getRangeValues(source: SimpleCellRange): CellValue[][] { - if(!isSimpleCellRange(source)) { + if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } const cellRange = new AbsoluteCellRange(source.start, source.end) @@ -2318,7 +2318,7 @@ export class HyperFormula implements TypedEmitter { * @category Ranges */ public getRangeFormulas(source: SimpleCellRange): (string | undefined)[][] { - if(!isSimpleCellRange(source)) { + if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } const cellRange = new AbsoluteCellRange(source.start, source.end) @@ -2353,7 +2353,7 @@ export class HyperFormula implements TypedEmitter { * @category Ranges */ public getRangeSerialized(source: SimpleCellRange): RawCellContent[][] { - if(!isSimpleCellRange(source)) { + if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } const cellRange = new AbsoluteCellRange(source.start, source.end) @@ -2388,15 +2388,15 @@ export class HyperFormula implements TypedEmitter { */ public getFillRangeData(source: SimpleCellRange, target: SimpleCellRange): RawCellContent[][] { - if(!isSimpleCellRange(source)) { + if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } - if(!isSimpleCellRange(target)) { + if (!isSimpleCellRange(target)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'target') } const sourceRange = new AbsoluteCellRange(source.start, source.end) const targetRange = new AbsoluteCellRange(target.start, target.end) - if(sourceRange.sheet !== targetRange.sheet) { + if (sourceRange.sheet !== targetRange.sheet) { throw new SheetsNotEqual(sourceRange.sheet, targetRange.sheet) } this.ensureEvaluationIsNotSuspended() @@ -2471,7 +2471,7 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public addSheet(sheetName?: string): string { - if(sheetName !== undefined) { + if (sheetName !== undefined) { validateArgToType(sheetName, 'string', 'sheetName') } const addedSheetName = this._crudOperations.addSheet(sheetName) @@ -2729,7 +2729,7 @@ export class HyperFormula implements TypedEmitter { * @category Helpers */ public simpleCellAddressToString(simpleCellAddress: SimpleCellAddress, sheetId: number): string | undefined { - if(!isSimpleCellAddress(simpleCellAddress)) { + if (!isSimpleCellAddress(simpleCellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'simpleCellAddress') } validateArgToType(sheetId, 'number', 'sheetId') @@ -2756,14 +2756,14 @@ export class HyperFormula implements TypedEmitter { */ public getCellDependents(address: SimpleCellAddress | SimpleCellRange): (SimpleCellRange | SimpleCellAddress)[] { let vertex - if(isSimpleCellAddress(address)) { + if (isSimpleCellAddress(address)) { vertex = this._dependencyGraph.addressMapping.getCell(address) - } else if(isSimpleCellRange(address)){ + } else if (isSimpleCellRange(address)) { vertex = this._dependencyGraph.rangeMapping.getRange(address.start, address.end) } else { throw new ExpectedValueOfTypeError('SimpleCellAddress | SimpleCellRange', address) } - if(vertex===undefined) { + if (vertex === undefined) { return [] } return this._dependencyGraph.getAdjacentNodesAddresses(vertex) @@ -2788,14 +2788,14 @@ export class HyperFormula implements TypedEmitter { */ public getCellPrecedents(address: SimpleCellAddress | SimpleCellRange): (SimpleCellRange | SimpleCellAddress)[] { let vertex - if(isSimpleCellAddress(address)) { + if (isSimpleCellAddress(address)) { vertex = this._dependencyGraph.addressMapping.getCell(address) - } else if(isSimpleCellRange(address)){ + } else if (isSimpleCellRange(address)) { vertex = this._dependencyGraph.rangeMapping.getRange(address.start, address.end) } else { throw new ExpectedValueOfTypeError('SimpleCellAddress | SimpleCellRange', address) } - if(vertex===undefined) { + if (vertex === undefined) { return [] } return this._dependencyGraph.dependencyQueryAddresses(vertex) @@ -2922,7 +2922,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public getCellType(cellAddress: SimpleCellAddress): CellType { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } const vertex = this.dependencyGraph.getCell(cellAddress) @@ -2953,7 +2953,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public doesCellHaveSimpleValue(cellAddress: SimpleCellAddress): boolean { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } return this.getCellType(cellAddress) === CellType.VALUE @@ -2983,7 +2983,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public doesCellHaveFormula(cellAddress: SimpleCellAddress): boolean { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } return this.getCellType(cellAddress) === CellType.FORMULA @@ -3013,7 +3013,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public isCellEmpty(cellAddress: SimpleCellAddress): boolean { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } return this.getCellType(cellAddress) === CellType.EMPTY @@ -3040,7 +3040,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public isCellPartOfMatrix(cellAddress: SimpleCellAddress): boolean { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } return this.getCellType(cellAddress) === CellType.MATRIX @@ -3071,7 +3071,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public getCellValueType(cellAddress: SimpleCellAddress): CellValueType { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } this.ensureEvaluationIsNotSuspended() @@ -3104,7 +3104,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public getCellValueDetailedType(cellAddress: SimpleCellAddress): CellValueDetailedType { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } this.ensureEvaluationIsNotSuspended() @@ -3137,7 +3137,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public getCellValueFormat(cellAddress: SimpleCellAddress): FormatInfo { - if(!isSimpleCellAddress(cellAddress)) { + if (!isSimpleCellAddress(cellAddress)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress') } this.ensureEvaluationIsNotSuspended() @@ -3402,7 +3402,7 @@ export class HyperFormula implements TypedEmitter { */ public isItPossibleToAddNamedExpression(expressionName: string, expression: RawCellContent, scope?: number): boolean { validateArgToType(expressionName, 'string', 'expressionName') - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } try { @@ -3452,7 +3452,7 @@ export class HyperFormula implements TypedEmitter { */ public addNamedExpression(expressionName: string, expression: RawCellContent, scope?: number, options?: NamedExpressionOptions): ExportedChange[] { validateArgToType(expressionName, 'string', 'expressionName') - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } this._crudOperations.addNamedExpression(expressionName, expression, scope, options) @@ -3488,7 +3488,7 @@ export class HyperFormula implements TypedEmitter { */ public getNamedExpressionValue(expressionName: string, scope?: number): CellValue | undefined { validateArgToType(expressionName, 'string', 'expressionName') - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } this.ensureEvaluationIsNotSuspended() @@ -3528,7 +3528,7 @@ export class HyperFormula implements TypedEmitter { */ public getNamedExpressionFormula(expressionName: string, scope?: number): string | undefined { validateArgToType(expressionName, 'string', 'expressionName') - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } this._crudOperations.ensureScopeIdIsValid(scope) @@ -3562,7 +3562,7 @@ export class HyperFormula implements TypedEmitter { * // for this example, returns: * // {name: 'prettyName', expression: '=Sheet1!$A$1+100', options: undefined, scope: 0} * const myFormula = hfInstance.getNamedExpression('prettyName', 0); - * + * * // for a named expression that doesn't exist, returns 'undefined': * const myFormulaTwo = hfInstance.getNamedExpression('uglyName', 0); * ``` @@ -3571,7 +3571,7 @@ export class HyperFormula implements TypedEmitter { */ public getNamedExpression(expressionName: string, scope?: number): NamedExpression | undefined { validateArgToType(expressionName, 'string', 'expressionName') - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } const namedExpression = this._namedExpressions.namedExpressionForScope(expressionName, scope) @@ -3622,7 +3622,7 @@ export class HyperFormula implements TypedEmitter { */ public isItPossibleToChangeNamedExpression(expressionName: string, newExpression: RawCellContent, scope?: number): boolean { validateArgToType(expressionName, 'string', 'expressionName') - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } try { @@ -3668,7 +3668,7 @@ export class HyperFormula implements TypedEmitter { */ public changeNamedExpression(expressionName: string, newExpression: RawCellContent, scope?: number, options?: NamedExpressionOptions): ExportedChange[] { validateArgToType(expressionName, 'string', 'expressionName') - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } this._crudOperations.changeNamedExpressionExpression(expressionName, scope, newExpression, options) @@ -3706,7 +3706,7 @@ export class HyperFormula implements TypedEmitter { */ public isItPossibleToRemoveNamedExpression(expressionName: string, scope?: number): boolean { validateArgToType(expressionName, 'string', 'expressionName') - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } try { @@ -3749,7 +3749,7 @@ export class HyperFormula implements TypedEmitter { */ public removeNamedExpression(expressionName: string, scope?: number): ExportedChange[] { validateArgToType(expressionName, 'string', 'expressionName') - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } const removedNamedExpression = this._crudOperations.removeNamedExpression(expressionName, scope) @@ -3794,7 +3794,7 @@ export class HyperFormula implements TypedEmitter { * @category Named Expressions */ public listNamedExpressions(scope?: number): string[] { - if(scope !== undefined) { + if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') } this._crudOperations.ensureScopeIdIsValid(scope) @@ -4057,7 +4057,7 @@ export class HyperFormula implements TypedEmitter { return numberToSimpleTime(inputNumber) } - private extractTemporaryFormula(formulaString: string, sheetId: number = 1): {ast?: Ast, address: SimpleCellAddress, dependencies: RelativeDependency[]} { + private extractTemporaryFormula(formulaString: string, sheetId: number = 1): { ast?: Ast, address: SimpleCellAddress, dependencies: RelativeDependency[] } { const parsedCellContent = this._cellContentParser.parse(formulaString) const address = {sheet: sheetId, col: 0, row: 0} if (!(parsedCellContent instanceof CellContent.Formula)) { @@ -4076,7 +4076,7 @@ export class HyperFormula implements TypedEmitter { /** * Subscribes to an event. * For the list of all available events, see [[Listeners]]. - * + * * @param {Event} event the name of the event to subscribe to * @param {Listener} listener to be called when event is emitted * diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index f94a042208..1577a8354d 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -1004,29 +1004,49 @@ describe('arrays', () => { ]) }) - it('should handle dependent vertices after shrinking array', () => { + it('should adjust dependent formulas after shrinking array', () => { const engine = HyperFormula.buildFromArray([ [1, 2, 3, '=-A1:C1', null, null, 4], - ['=D1', '=E1', '=SUM(F1:F1)', '=SUM(F1:G1)'], + ['=D1', '=E1', '=SUM(E1, F1:G1)'], ], {useArrayArithmetic: true}) - expect(engine.getCellValue(adr('A2'))).toEqual(-1) - expect(engine.getCellValue(adr('B2'))).toEqual(-2) - expect(engine.getCellValue(adr('C2'))).toEqual(-3) - expect(engine.getCellValue(adr('D2'))).toEqual(1) - - engine.setCellContents(adr('E1'), [[null]]) + engine.setCellContents(adr('E1'), [['foo']]) engine.setCellContents(adr('D1'), [[4, 5, 6]]) expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ [1, 2, 3, 4, 5, 6, 4], - ['=D1', '=E1', '=SUM(F1:F1)', '=SUM(F1:G1)'] + ['=D1', '=E1', '=SUM(E1, F1:G1)'] ], {useArrayArithmetic: true})) + }) - expect(engine.getCellValue(adr('A2'))).toEqual(4) - expect(engine.getCellValue(adr('B2'))).toEqual(5) - expect(engine.getCellValue(adr('C2'))).toEqual(6) - expect(engine.getCellValue(adr('D2'))).toEqual(10) + it('should adjust dependent ranges after shrinking array taking smaller vertices into account', () => { + const engine = HyperFormula.buildFromArray([ + [1, '=-A1:A3', '=SUM(B1:B2)', '=SUM(B1:B3)'], + [2], + [3], + ], {useArrayArithmetic: true}) + + engine.setCellContents(adr('B1'), 'foo') + engine.setCellContents(adr('B1'), [[4], [5], [6]]) + + const b1 = engine.dependencyGraph.getCell(adr('b1'))! + const b2 = engine.dependencyGraph.getCell(adr('b2'))! + const b3 = engine.dependencyGraph.getCell(adr('b3'))! + const b1b2 = engine.rangeMapping.getRange(adr('b1'), adr('b2'))! + const b1b3 = engine.rangeMapping.getRange(adr('b1'), adr('b3'))! + + expect(engine.graph.existsEdge(b1, b1b2)).toBe(true) + expect(engine.graph.existsEdge(b2, b1b2)).toBe(true) + expect(engine.graph.existsEdge(b1b2, b1b3)).toBe(true) + expect(engine.graph.existsEdge(b1, b1b3)).toBe(false) + expect(engine.graph.existsEdge(b2, b1b3)).toBe(false) + expect(engine.graph.existsEdge(b3, b1b3)).toBe(true) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 4, '=SUM(B1:B2)', '=SUM(B1:B3)'], + [2, 5], + [3, 6], + ], {useArrayArithmetic: true})) }) it('should return values of a range in changes', () => { @@ -1088,7 +1108,7 @@ describe('arrays', () => { ['=-A1:B1'], ], { useArrayArithmetic: true}) - const changes = engine.setCellContents(adr('A2'), [[null]]) + const changes = engine.setCellContents(adr('A2'), null) expect(changes.length).toEqual(2) expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), null)) @@ -1101,7 +1121,7 @@ describe('arrays', () => { ['=-A1:B1'], ], { useArrayArithmetic: true}) - const changes = engine.setCellContents(adr('B2'), [[null]]) + const changes = engine.setCellContents(adr('B2'), null) expect(changes.length).toEqual(0) }) From dc153102bc6e97605a6742d25c751ac23aa907c5 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 26 Jun 2021 10:36:00 +0200 Subject: [PATCH 64/87] Linter --- test/column-index.spec.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/column-index.spec.ts b/test/column-index.spec.ts index 0a1ed98c07..a8d53c1bb9 100644 --- a/test/column-index.spec.ts +++ b/test/column-index.spec.ts @@ -327,7 +327,7 @@ describe('ColumnIndex#find', () => { const stats = new Statistics() const transformService = new LazilyTransformingAstService(stats) - it('should find row number', function () { + it('should find row number', () => { const index = buildEmptyIndex(transformService, new Config(), stats) index.add(1, adr('A2')) @@ -336,7 +336,7 @@ describe('ColumnIndex#find', () => { expect(row).toBe(1) }) - it('should find smallest row number for value', function () { + it('should find smallest row number for value', () => { const index = buildEmptyIndex(transformService, new Config(), stats) index.add(1, adr('A4')) @@ -531,7 +531,7 @@ describe('ColumnIndex#removeRows', () => { }) describe('ColumnIndex - lazy cruds', () => { - it('should add rows only in specific column after find', function () { + it('should add rows only in specific column after find', () => { const stats = new Statistics() const transformService = new LazilyTransformingAstService(stats) const index = buildEmptyIndex(transformService, new Config(), stats) @@ -551,7 +551,7 @@ describe('ColumnIndex - lazy cruds', () => { expect(index.getValueIndex(0, 1, 1).index).toEqual([1]) }) - it('should add rows only for specific value after find', function () { + it('should add rows only for specific value after find', () => { const stats = new Statistics() const transformService = new LazilyTransformingAstService(stats) const index = buildEmptyIndex(transformService, new Config(), stats) From aad74cd092b3d5e7870e60c5ed8d40f476fe3894 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 26 Jun 2021 12:56:58 +0200 Subject: [PATCH 65/87] Remove console.log --- test/cruds/change-cell-content.spec.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 1577a8354d..375ebda182 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -1094,8 +1094,6 @@ describe('arrays', () => { const changes = engine.setCellContents(adr('B2'), [['=SUM(']]) - console.log(engine.getSheetValues(0)) - expect(changes.length).toEqual(3) expect(changes).toContainEqual(new ExportedCellChange(adr('A2'), noSpace())) expect(changes).toContainEqual(new ExportedCellChange(adr('B2'), detailedError(ErrorType.ERROR, ErrorMessage.ParseError))) From 5a3ec5c010178acd9ee03ee4ff6f260ac4637f5d Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 27 Jun 2021 09:19:10 +0200 Subject: [PATCH 66/87] Cleanup --- src/AbsoluteCellRange.ts | 5 - .../AddressMapping/AddressMapping.ts | 2 +- src/DependencyGraph/DependencyGraph.ts | 101 +++++++++--------- src/DependencyGraph/MatrixMapping.ts | 4 - src/Operations.ts | 10 +- test/address-mapping.spec.ts | 7 ++ 6 files changed, 63 insertions(+), 66 deletions(-) diff --git a/src/AbsoluteCellRange.ts b/src/AbsoluteCellRange.ts index 269a158415..3d3ab306bf 100644 --- a/src/AbsoluteCellRange.ts +++ b/src/AbsoluteCellRange.ts @@ -96,11 +96,6 @@ export class AbsoluteCellRange implements SimpleCellRange { return new AbsoluteCellRange(simpleCellAddress(sheet, x1, y1), simpleCellAddress(sheet, x2, y2)) } - public static singleRangeFromCellAddress(cellAddress: CellAddress, baseAddress: SimpleCellAddress): AbsoluteCellRange { - const absoluteAddress = cellAddress.toSimpleCellAddress(baseAddress) - return new AbsoluteCellRange(absoluteAddress, absoluteAddress) - } - constructor( start: SimpleCellAddress, end: SimpleCellAddress, diff --git a/src/DependencyGraph/AddressMapping/AddressMapping.ts b/src/DependencyGraph/AddressMapping/AddressMapping.ts index c59c126c81..1191c7c0ce 100644 --- a/src/DependencyGraph/AddressMapping/AddressMapping.ts +++ b/src/DependencyGraph/AddressMapping/AddressMapping.ts @@ -102,7 +102,7 @@ export class AddressMapping { public moveCell(source: SimpleCellAddress, destination: SimpleCellAddress) { const sheetMapping = this.mapping.get(source.sheet) if (!sheetMapping) { - throw Error('Sheet not initialized') + throw Error('Sheet not initialized.') } if (source.sheet !== destination.sheet) { throw Error('Cannot move cells between sheets.') diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index c94e4038a6..b9ac001f8d 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -233,19 +233,6 @@ export class DependencyGraph { this.exchangeGraphNode(vertexFrom, vertexTo) } - private correctInfiniteRangesDependenciesByRangeVertex(vertex: RangeVertex) { - for (const range of this.graph.infiniteRanges) { - const infiniteRangeVertex = (range as RangeVertex) - const intersection = vertex.range.intersectionWith(infiniteRangeVertex.range) - if (intersection === undefined) { - continue - } - for (const address of intersection.addresses(this)) { - this.graph.addEdge(this.fetchCellOrCreateEmpty(address), range) - } - } - } - public correctInfiniteRangesDependency(address: SimpleCellAddress) { let vertex: Maybe = undefined for (const range of this.graph.infiniteRanges) { @@ -267,7 +254,7 @@ export class DependencyGraph { return vertex } - public removeRows(removedRows: RowsSpan): [Set, ContentChanges]{ + public removeRows(removedRows: RowsSpan): RemoveRowsResult { this.stats.measure(StatType.ADJUSTING_GRAPH, () => { for (const [address, vertex] of this.addressMapping.entriesFromRowsSpan(removedRows)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { @@ -289,7 +276,7 @@ export class DependencyGraph { this.addressMapping.removeRows(removedRows) }) - const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { + const affectedArrays = this.stats.measure(StatType.ADJUSTING_RANGES, () => { const affectedRanges = this.truncateRanges(removedRows, address => address.row) return this.getMatrixVerticesRelatedToRanges(affectedRanges) }) @@ -300,7 +287,10 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() - return [affectedMatrices, this.getAndClearContentChanges()] + return { + affectedArrays, + contentChanges: this.getAndClearContentChanges() + } } public removeSheet(removedSheetId: number) { @@ -386,12 +376,12 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() } - public addRows(addedRows: RowsSpan): Set { + public addRows(addedRows: RowsSpan): AddRowsResult { this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.addRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) }) - const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { + const affectedArrays = this.stats.measure(StatType.ADJUSTING_RANGES, () => { const result = this.rangeMapping.moveAllRangesInSheetAfterRowByRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) this.fixRangesWhenAddingRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) return this.getMatrixVerticesRelatedToRanges(result.verticesWithChangedSize) @@ -407,7 +397,7 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() - return affectedMatrices + return { affectedArrays } } public addColumns(addedColumns: ColumnsSpan) { @@ -584,10 +574,6 @@ export class DependencyGraph { return this.sheetMapping.fetch(sheetName) } - public getSheetName(sheetId: number): string { - return this.sheetMapping.fetchDisplayName(sheetId) - } - public getSheetHeight(sheet: number): number { return this.addressMapping.getHeight(sheet) } @@ -651,15 +637,6 @@ export class DependencyGraph { return new Set(...matrixVertices) } - public* verticesFromRange(range: AbsoluteCellRange): IterableIterator { - for (const address of range.addresses(this)) { - const vertex = this.getCell(address) - if (vertex) { - yield vertex - } - } - } - public* rawValuesFromRange(range: AbsoluteCellRange): IterableIterator<[RawScalarValue, SimpleCellAddress]> { for (const address of range.addresses(this)) { const value = this.getScalarValue(address) @@ -777,6 +754,39 @@ export class DependencyGraph { return vertex instanceof MatrixVertex && !vertex.isLeftCorner(address) } + public getAndClearContentChanges(): ContentChanges { + const changes = this.changes + this.changes = ContentChanges.empty() + return changes + } + + public getAdjacentNodesAddresses(inputVertex: Vertex): (SimpleCellRange | SimpleCellAddress)[] { + const deps = this.graph.adjacentNodes(inputVertex) + const ret: (SimpleCellRange | SimpleCellAddress)[] = [] + deps.forEach((vertex: Vertex) => { + const castVertex = vertex as RangeVertex | FormulaCellVertex | MatrixVertex + if (castVertex instanceof RangeVertex) { + ret.push(simpleCellRange(castVertex.start, castVertex.end)) + } else { + ret.push(castVertex.getAddress(this.lazilyTransformingAstService)) + } + }) + return ret + } + + private correctInfiniteRangesDependenciesByRangeVertex(vertex: RangeVertex) { + for (const range of this.graph.infiniteRanges) { + const infiniteRangeVertex = (range as RangeVertex) + const intersection = vertex.range.intersectionWith(infiniteRangeVertex.range) + if (intersection === undefined) { + continue + } + for (const address of intersection.addresses(this)) { + this.graph.addEdge(this.fetchCellOrCreateEmpty(address), range) + } + } + } + private cleanAddressMappingUnderMatrix(vertex: MatrixVertex) { const matrixRange = vertex.getRange() for (const address of matrixRange.addresses(this)) { @@ -811,7 +821,7 @@ export class DependencyGraph { } private* rangeDirectDependenciesToMatrix(vertex: RangeVertex, matrix: MatrixVertex): IterableIterator<[SimpleCellAddress, CellVertex]> { - const { restRange: range } = this.rangeMapping.findSmallerRange(vertex.range) + const {restRange: range} = this.rangeMapping.findSmallerRange(vertex.range) for (const address of range.addresses(this)) { if (matrix.getRange().addressInRange(address)) { const cell = this.fetchCellOrCreateEmpty(address) @@ -1072,24 +1082,13 @@ export class DependencyGraph { } } } +} - public getAndClearContentChanges(): ContentChanges { - const changes = this.changes - this.changes = ContentChanges.empty() - return changes - } +export interface AddRowsResult { + affectedArrays: Set, +} - public getAdjacentNodesAddresses(inputVertex: Vertex): (SimpleCellRange | SimpleCellAddress)[] { - const deps = this.graph.adjacentNodes(inputVertex) - const ret: (SimpleCellRange | SimpleCellAddress)[] = [] - deps.forEach((vertex: Vertex) => { - const castVertex = vertex as RangeVertex | FormulaCellVertex | MatrixVertex - if (castVertex instanceof RangeVertex) { - ret.push(simpleCellRange(castVertex.start, castVertex.end)) - } else { - ret.push(castVertex.getAddress(this.lazilyTransformingAstService)) - } - }) - return ret - } +export interface RemoveRowsResult { + affectedArrays: Set, + contentChanges: ContentChanges, } diff --git a/src/DependencyGraph/MatrixMapping.ts b/src/DependencyGraph/MatrixMapping.ts index 612ac695ed..44436088a6 100644 --- a/src/DependencyGraph/MatrixMapping.ts +++ b/src/DependencyGraph/MatrixMapping.ts @@ -28,10 +28,6 @@ export class MatrixMapping { this.matrixMapping.set(addressKey(range.start), vertex) } - public setMatrixByCorner(address: SimpleCellAddress, vertex: MatrixVertex) { - this.matrixMapping.set(addressKey(address), vertex) - } - public removeMatrix(range: string | AbsoluteCellRange) { if (typeof range === 'string') { this.matrixMapping.delete(range) diff --git a/src/Operations.ts b/src/Operations.ts index f04b57b04e..5e6bf35de1 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -483,9 +483,9 @@ export class Operations { removedCells.push({address, cellType: this.getClipboardCell(address)}) } - const [affectedMatrices, changes] = this.dependencyGraph.removeRows(rowsToRemove) + const { affectedArrays, contentChanges } = this.dependencyGraph.removeRows(rowsToRemove) - this.columnSearch.applyChanges(changes.getChanges()) + this.columnSearch.applyChanges(contentChanges.getChanges()) let version: number this.stats.measure(StatType.TRANSFORM_ASTS, () => { @@ -494,7 +494,7 @@ export class Operations { version = this.lazilyTransformingAstService.addTransformation(transformation) }) - this.rewriteAffectedMatrices(affectedMatrices) + this.rewriteAffectedMatrices(affectedArrays) return {version: version!, removedCells, rowFrom: rowsToRemove.rowStart, rowCount: rowsToRemove.numberOfRows} } @@ -548,7 +548,7 @@ export class Operations { return } - const affectedMatrices = this.dependencyGraph.addRows(addedRows) + const { affectedArrays } = this.dependencyGraph.addRows(addedRows) this.stats.measure(StatType.TRANSFORM_ASTS, () => { const transformation = new AddRowsTransformer(addedRows) @@ -556,7 +556,7 @@ export class Operations { this.lazilyTransformingAstService.addTransformation(transformation) }) - this.rewriteAffectedMatrices(affectedMatrices) + this.rewriteAffectedMatrices(affectedArrays) } private rewriteAffectedMatrices(affectedMatrices: Set) { diff --git a/test/address-mapping.spec.ts b/test/address-mapping.spec.ts index 0f61232f13..d163bc0753 100644 --- a/test/address-mapping.spec.ts +++ b/test/address-mapping.spec.ts @@ -346,6 +346,13 @@ const sharedExamples = (builder: (width: number, height: number) => AddressMappi expect(() => mapping.moveCell(adr('A1', 0), adr('A2', 1))).toThrow('Cannot move cells between sheets.') }) + + it('should throw error when trying to move vertices in non-existing sheet', () => { + const mapping = builder(1, 2) + mapping.setCell(adr('A1', 0), new ValueCellVertex(42, 42)) + + expect(() => mapping.moveCell(adr('A1', 3), adr('A2', 3))).toThrow('Sheet not initialized.') + }) } describe('SparseStrategy', () => { From 20ddf9f0ca551509572ac8d08baf3da5febf276a Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 27 Jun 2021 10:34:17 +0200 Subject: [PATCH 67/87] Fix lgtm complaints --- src/LazilyTransformingAstService.ts | 2 +- src/Operations.ts | 4 ++-- src/dependencyTransformers/Transformer.ts | 2 +- src/parser/ParserWithCaching.ts | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/LazilyTransformingAstService.ts b/src/LazilyTransformingAstService.ts index 7d4ec40e5c..54b3629f94 100644 --- a/src/LazilyTransformingAstService.ts +++ b/src/LazilyTransformingAstService.ts @@ -64,7 +64,7 @@ export class LazilyTransformingAstService { ast = newAst address = newAddress } - const [hash, cachedAst] = this.parser!.rememberNewAst(ast) + const cachedAst = this.parser!.rememberNewAst(ast) this.stats.end(StatType.TRANSFORM_ASTS_POSTPONED) return [cachedAst, address, this.transformations.length] diff --git a/src/Operations.ts b/src/Operations.ts index 5e6bf35de1..4a872f0dc2 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -483,7 +483,7 @@ export class Operations { removedCells.push({address, cellType: this.getClipboardCell(address)}) } - const { affectedArrays, contentChanges } = this.dependencyGraph.removeRows(rowsToRemove) + const {affectedArrays, contentChanges} = this.dependencyGraph.removeRows(rowsToRemove) this.columnSearch.applyChanges(contentChanges.getChanges()) @@ -548,7 +548,7 @@ export class Operations { return } - const { affectedArrays } = this.dependencyGraph.addRows(addedRows) + const {affectedArrays} = this.dependencyGraph.addRows(addedRows) this.stats.measure(StatType.TRANSFORM_ASTS, () => { const transformation = new AddRowsTransformer(addedRows) diff --git a/src/dependencyTransformers/Transformer.ts b/src/dependencyTransformers/Transformer.ts index 1846e3d2ef..9309690b5e 100644 --- a/src/dependencyTransformers/Transformer.ts +++ b/src/dependencyTransformers/Transformer.ts @@ -31,7 +31,7 @@ export abstract class Transformer implements FormulaTransformer { public performEagerTransformations(graph: DependencyGraph, parser: ParserWithCaching): void { for (const node of graph.matrixFormulaNodes()) { const [newAst, newAddress] = this.transformSingleAst(node.getFormula(graph.lazilyTransformingAstService), node.getAddress(graph.lazilyTransformingAstService)) - const [hash, cachedAst] = parser.rememberNewAst(newAst) + const cachedAst = parser.rememberNewAst(newAst) node.setFormula(cachedAst) node.setAddress(newAddress) } diff --git a/src/parser/ParserWithCaching.ts b/src/parser/ParserWithCaching.ts index a5dabd6821..3c1d2e3167 100644 --- a/src/parser/ParserWithCaching.ts +++ b/src/parser/ParserWithCaching.ts @@ -154,9 +154,9 @@ export class ParserWithCaching { return hash } - public rememberNewAst(ast: Ast): [string, Ast] { + public rememberNewAst(ast: Ast): Ast { const hash = this.computeHashFromAst(ast) - return [hash, this.cache.maybeSetAndThenGet(hash, ast)] + return this.cache.maybeSetAndThenGet(hash, ast) } public computeHashFromAst(ast: Ast): string { From 0a44540849a26d0baa4213b052eb7ef64299a0de Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 26 Jun 2021 11:50:57 +0200 Subject: [PATCH 68/87] Adjust adding columns by analogy --- src/CrudOperations.ts | 7 - src/DependencyGraph/DependencyGraph.ts | 31 +++- src/DependencyGraph/MatrixMapping.ts | 15 ++ src/DependencyGraph/RangeMapping.ts | 4 +- src/Operations.ts | 4 +- test/cruds/adding-columns.spec.ts | 200 ++++++++++++++++--------- 6 files changed, 181 insertions(+), 80 deletions(-) diff --git a/src/CrudOperations.ts b/src/CrudOperations.ts index a5beaeccd0..ce605f35f7 100644 --- a/src/CrudOperations.ts +++ b/src/CrudOperations.ts @@ -496,13 +496,6 @@ export class CrudOperations { if (!isNonnegativeInteger(column) || !isPositiveInteger(numberOfColumnsToAdd)) { throw new InvalidArgumentsError('column number to be nonnegative and number of columns to add to be positive.') } - - if (isPositiveInteger(column) - && this.dependencyGraph.matrixMapping.isFormulaMatrixInColumn(sheet, column - 1) - && this.dependencyGraph.matrixMapping.isFormulaMatrixInColumn(sheet, column) - ) { - throw new TargetLocationHasMatrixError() - } } } diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index b9ac001f8d..743c4c100c 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -400,14 +400,19 @@ export class DependencyGraph { return { affectedArrays } } - public addColumns(addedColumns: ColumnsSpan) { + public addColumns(addedColumns: ColumnsSpan): Set { this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.addColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) }) - this.stats.measure(StatType.ADJUSTING_RANGES, () => { - this.rangeMapping.moveAllRangesInSheetAfterColumnByColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) + const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { + const result = this.rangeMapping.moveAllRangesInSheetAfterColumnByColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) this.fixRangesWhenAddingColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) + return this.getMatrixVerticesRelatedToRanges(result.verticesWithChangedSize) + }) + + this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { + this.fixMatricesAfterAddingColumn(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) }) for (const vertex of this.addressMapping.verticesFromColumnsSpan(addedColumns)) { @@ -415,6 +420,8 @@ export class DependencyGraph { } this.addStructuralNodesToChangeSet() + + return affectedMatrices } public ensureNoMatrixInRange(range: AbsoluteCellRange) { @@ -1030,6 +1037,24 @@ export class DependencyGraph { } } + + private fixMatricesAfterAddingColumn(sheet: number, columnStart: number, numberOfColumns: number) { + this.matrixMapping.moveMatrixVerticesAfterColumnByColumns(sheet, columnStart, numberOfColumns) + if (columnStart <= 0) { + return + } + for (const [, matrix] of this.matrixMapping.matricesInCols(ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) { + const matrixRange = matrix.getRange() + for (let row = matrixRange.start.row; row <= matrixRange.end.row; ++row) { + for (let col = columnStart; col <= matrixRange.end.col; ++col) { + const destination = simpleCellAddress(sheet, col, row) + const source = simpleCellAddress(sheet, col + numberOfColumns, row) + this.addressMapping.moveCell(source, destination) + } + } + } + } + private shrinkPossibleMatrixAndGetCell(address: SimpleCellAddress): Maybe { const vertex = this.getCell(address) if (!(vertex instanceof MatrixVertex)) { diff --git a/src/DependencyGraph/MatrixMapping.ts b/src/DependencyGraph/MatrixMapping.ts index 44436088a6..71e0ee98d5 100644 --- a/src/DependencyGraph/MatrixMapping.ts +++ b/src/DependencyGraph/MatrixMapping.ts @@ -48,6 +48,14 @@ export class MatrixMapping { } } + public* matricesInCols(col: ColumnsSpan): IterableIterator<[string, MatrixVertex]> { + for (const [mtxKey, mtx] of this.matrixMapping.entries()) { + if (mtx.spansThroughSheetColumn(col.sheet, col.columnStart, col.columnEnd)) { + yield [mtxKey, mtx] + } + } + } + public isFormulaMatrixInRow(sheet: number, row: number): boolean { for (const mtx of this.matrixMapping.values()) { if (mtx.spansThroughSheetRows(sheet, row)) { @@ -114,6 +122,13 @@ export class MatrixMapping { }) } + public moveMatrixVerticesAfterColumnByColumns(sheet: number, column: number, numberOfColumns: number) { + this.updateMatrixVerticesInSheet(sheet, (key: string, vertex: MatrixVertex) => { + const range = vertex.getRange() + return column <= range.start.col ? [range.shifted(numberOfColumns, 0), vertex] : undefined + }) + } + private updateMatrixVerticesInSheet(sheet: number, fn: (key: string, vertex: MatrixVertex) => Maybe<[AbsoluteCellRange, MatrixVertex]>) { const updated = Array<[AbsoluteCellRange, MatrixVertex]>() diff --git a/src/DependencyGraph/RangeMapping.ts b/src/DependencyGraph/RangeMapping.ts index c510bfa259..ade49d04b9 100644 --- a/src/DependencyGraph/RangeMapping.ts +++ b/src/DependencyGraph/RangeMapping.ts @@ -142,8 +142,8 @@ export class RangeMapping { }) } - public moveAllRangesInSheetAfterColumnByColumns(sheet: number, column: number, numberOfColumns: number) { - this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex) => { + public moveAllRangesInSheetAfterColumnByColumns(sheet: number, column: number, numberOfColumns: number): AdjustRangesResult { + return this.updateVerticesFromSheet(sheet, (key: string, vertex: RangeVertex) => { if (column <= vertex.start.col) { vertex.range.shiftByColumns(numberOfColumns) return { diff --git a/src/Operations.ts b/src/Operations.ts index 4a872f0dc2..a2c086fd7e 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -584,7 +584,7 @@ export class Operations { return } - this.dependencyGraph.addColumns(addedColumns) + const affectedMatrices = this.dependencyGraph.addColumns(addedColumns) this.columnSearch.addColumns(addedColumns) this.stats.measure(StatType.TRANSFORM_ASTS, () => { @@ -592,6 +592,8 @@ export class Operations { transformation.performEagerTransformations(this.dependencyGraph, this.parser) this.lazilyTransformingAstService.addTransformation(transformation) }) + + this.rewriteAffectedMatrices(affectedMatrices) } public getOldContent(address: SimpleCellAddress): [SimpleCellAddress, ClipboardCell] { diff --git a/test/cruds/adding-columns.spec.ts b/test/cruds/adding-columns.spec.ts index ad841cf2d9..751a9f0c9e 100644 --- a/test/cruds/adding-columns.spec.ts +++ b/test/cruds/adding-columns.spec.ts @@ -1,11 +1,17 @@ import {ExportedCellChange, HyperFormula} from '../../src' import {AbsoluteCellRange} from '../../src/AbsoluteCellRange' -import {simpleCellAddress} from '../../src/Cell' import {Config} from '../../src/Config' import {FormulaCellVertex, MatrixVertex} from '../../src/DependencyGraph' import {SheetSizeLimitExceededError} from '../../src/errors' import {ColumnIndex} from '../../src/Lookup/ColumnIndex' -import {adr, expectArrayWithSameContent, extractMatrixRange, extractRange} from '../testUtils' +import { + adr, + expectArrayWithSameContent, + expectEngineToBeTheSameAs, + extractMatrixRange, + extractRange +} from '../testUtils' +import {AlwaysDense} from '../../src/DependencyGraph/AddressMapping/ChooseAddressMappingPolicy' describe('Adding column - checking if its possible', () => { it('no if starting column is negative', () => { @@ -59,18 +65,6 @@ describe('Adding column - checking if its possible', () => { expect(engine.isItPossibleToAddColumns(-Infinity, [0, 1])).toEqual(false) }) - it('no if theres a formula matrix in place where we add', () => { - const engine = HyperFormula.buildFromArray([ - ['1', '2', '=TRANSPOSE(A1:B2)', undefined, '13'], - ['3', '4'], - ]) - - expect(engine.isItPossibleToAddColumns(0, [1, 1])).toEqual(true) - expect(engine.isItPossibleToAddColumns(0, [2, 1])).toEqual(true) - expect(engine.isItPossibleToAddColumns(0, [3, 1])).toEqual(false) - expect(engine.isItPossibleToAddColumns(0, [4, 1])).toEqual(true) - }) - it('no if adding column would exceed sheet size limit', () => { const engine = HyperFormula.buildFromArray([ Array(Config.defaultConfig.maxColumns - 1).fill('') @@ -88,18 +82,36 @@ describe('Adding column - checking if its possible', () => { }) describe('Adding column - matrix check', () => { - it('raise error if trying to add a row in a row with matrix', () => { + it('should be possible to add a row crossing matrix', () => { const engine = HyperFormula.buildFromArray([ - ['1', '2'], - ['3', '4'], - ['=TRANSPOSE(A1:B2)'], - [], - ['13'], - ]) + ['1', '2', 'foo', 'bar'], + ['3', '4', '=TRANSPOSE(A1:B3)'], + ['5', '6'], + ], {chooseAddressMappingPolicy: new AlwaysDense()}) + + engine.addColumns(0, [3, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['1', '2', 'foo', null, 'bar'], + ['3', '4', '=TRANSPOSE(A1:B3)'], + ['5', '6'] + ])) + }) - expect(() => { - engine.addColumns(0, [1, 1]) - }).toThrowError('Cannot perform this operation, target location has a matrix inside.') + it('should adjust matrix address mapping when adding multiple columns', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2', 'foo', 'bar'], + ['3', '4', '=TRANSPOSE(A1:B3)'], + ['5', '6'], + ], {chooseAddressMappingPolicy: new AlwaysDense()}) + + engine.addColumns(0, [3, 3]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + ['1', '2', 'foo', null, null, null, 'bar'], + ['3', '4', '=TRANSPOSE(A1:B3)'], + ['5', '6'] + ])) }) it('should be possible to add row right before matrix', () => { @@ -185,7 +197,7 @@ describe('Adding column - reevaluation', () => { const changes = engine.addColumns(0, [1, 1]) expect(changes.length).toBe(1) - expect(changes).toContainEqual(new ExportedCellChange(simpleCellAddress(0, 3, 0), 3)) + expect(changes).toContainEqual(new ExportedCellChange(adr('D1'), 3)) }) }) @@ -203,48 +215,6 @@ describe('Adding column - FormulaCellVertex#address update', () => { }) }) -/* TODO size of matrix can be dependent on structural changes */ -describe.skip('Adding column - MatrixVertex', () => { - it('MatrixVertex#formula should be updated', () => { - const engine = HyperFormula.buildFromArray([ - ['1', '2', '=TRANSPOSE(A1:B2)'], - ['3', '4'], - ]) - - engine.addColumns(0, [1, 1]) - - expect(extractMatrixRange(engine, adr('D1'))).toEqual(new AbsoluteCellRange(adr('A1'), adr('C2'))) - }) - - it('MatrixVertex#address should be updated', () => { - const engine = HyperFormula.buildFromArray([ - ['1', '2', '=TRANSPOSE(A1:B2)'], - ['3', '4'], - ]) - - engine.addColumns(0, [1, 1]) - - const matrixVertex = engine.addressMapping.fetchCell(adr('D1')) as MatrixVertex - expect(matrixVertex.getAddress(engine.lazilyTransformingAstService)).toEqual(adr('D1')) - }) - - it('MatrixVertex#formula should be updated when different sheets', () => { - const engine = HyperFormula.buildFromSheets({ - Sheet1: [ - ['1', '2'], - ['3', '4'], - ], - Sheet2: [ - ['=TRANSPOSE(Sheet1!A1:B2)'], - ], - }) - - engine.addColumns(0, [1, 1]) - - expect(extractMatrixRange(engine, adr('A1', 1))).toEqual(new AbsoluteCellRange(adr('A1'), adr('C2'))) - }) -}) - describe('Adding column - address mapping', () => { it('verify sheet dimensions', () => { const engine = HyperFormula.buildFromArray([ @@ -329,3 +299,99 @@ describe('Adding column - column index', () => { expectArrayWithSameContent([0], index.getValueIndex(0, 1, 1).index) }) }) + +describe('Adding column - arrays', () => { + it('should be possible to add column before array', () => { + const engine = HyperFormula.buildFromArray([ + ['=-A3:C4', null, null, 'foo'], + ], {useArrayArithmetic: true}) + + engine.addColumns(0, [0, 1]) + + const expected = HyperFormula.buildFromArray([ + [null, '=-B3:D4', null, null, 'foo'], + ], {useArrayArithmetic: true}) + + expectEngineToBeTheSameAs(engine, expected) + }) + + it('adding column across array should not change array', () => { + const engine = HyperFormula.buildFromArray([ + [null, null, null, '=-A1:C1', null, null, 'foo'] + ], {useArrayArithmetic: true}) + + engine.addColumns(0, [4, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [null, null, null, '=-A1:C1', null, null, null, 'foo'] + ], {useArrayArithmetic: true})) + }) + + it('adding column should expand dependent array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=TRANSPOSE(A1:B2)'], + [3, 4], + ], {useArrayArithmetic: true}) + + engine.addColumns(0, [1, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, null, 2, '=TRANSPOSE(A1:C2)'], + [3, null, 4], + ], {useArrayArithmetic: true})) + }) + + it('undo add column with dependent array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=TRANSPOSE(A1:B2)'], + [3, 4], + ], {useArrayArithmetic: true}) + + engine.addColumns(0, [1, 1]) + engine.undo() + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2, '=TRANSPOSE(A1:B2)'], + [3, 4], + ], {useArrayArithmetic: true})) + }) + + it('MatrixVertex#formula should be updated', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=TRANSPOSE(A1:B2)'], + [3, 4], + ]) + + engine.addColumns(0, [1, 1]) + + expect(extractMatrixRange(engine, adr('D1'))).toEqual(new AbsoluteCellRange(adr('A1'), adr('C2'))) + }) + + it('MatrixVertex#formula should be updated when different sheets', () => { + const engine = HyperFormula.buildFromSheets({ + Sheet1: [ + ['1', '2'], + ['3', '4'], + ], + Sheet2: [ + ['=TRANSPOSE(Sheet1!A1:B2)'], + ], + }) + + engine.addColumns(0, [1, 1]) + + expect(extractMatrixRange(engine, adr('A1', 1))).toEqual(new AbsoluteCellRange(adr('A1'), adr('C2'))) + }) + + it('MatrixVertex#address should be updated', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, '=TRANSPOSE(A1:B2)'], + [3, 4], + ]) + + engine.addColumns(0, [1, 1]) + + const matrixVertex = engine.addressMapping.fetchCell(adr('D1')) as MatrixVertex + expect(matrixVertex.getAddress(engine.lazilyTransformingAstService)).toEqual(adr('D1')) + }) +}) From 604b283837a599442e19c059f7127f8244e9a15b Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 26 Jun 2021 12:10:10 +0200 Subject: [PATCH 69/87] ColumnIndex needs to be adjusted --- src/DependencyGraph/DependencyGraph.ts | 17 +++++++++------ src/Operations.ts | 5 ++++- test/column-index.spec.ts | 30 +++++++++++++++++++++++++- 3 files changed, 44 insertions(+), 8 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 743c4c100c..c998027a83 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -45,6 +45,7 @@ import {MatrixMapping} from './MatrixMapping' import {RangeMapping} from './RangeMapping' import {SheetMapping} from './SheetMapping' import {RawAndParsedValue} from './ValueCellVertex' +import internal from 'stream' export class DependencyGraph { /** @@ -400,7 +401,7 @@ export class DependencyGraph { return { affectedArrays } } - public addColumns(addedColumns: ColumnsSpan): Set { + public addColumns(addedColumns: ColumnsSpan): [Set, [SimpleCellAddress, InterpreterValue][]] { this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.addColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) }) @@ -411,8 +412,8 @@ export class DependencyGraph { return this.getMatrixVerticesRelatedToRanges(result.verticesWithChangedSize) }) - this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { - this.fixMatricesAfterAddingColumn(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) + const valuesToRemoveFromIndex = this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { + return this.fixMatricesAfterAddingColumn(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) }) for (const vertex of this.addressMapping.verticesFromColumnsSpan(addedColumns)) { @@ -421,7 +422,7 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() - return affectedMatrices + return [affectedMatrices, valuesToRemoveFromIndex] } public ensureNoMatrixInRange(range: AbsoluteCellRange) { @@ -1038,10 +1039,11 @@ export class DependencyGraph { } - private fixMatricesAfterAddingColumn(sheet: number, columnStart: number, numberOfColumns: number) { + private fixMatricesAfterAddingColumn(sheet: number, columnStart: number, numberOfColumns: number): [SimpleCellAddress, InterpreterValue][] { + const valuesToRemoveFromIndex: [SimpleCellAddress, InterpreterValue][] = [] this.matrixMapping.moveMatrixVerticesAfterColumnByColumns(sheet, columnStart, numberOfColumns) if (columnStart <= 0) { - return + return [] } for (const [, matrix] of this.matrixMapping.matricesInCols(ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) { const matrixRange = matrix.getRange() @@ -1049,10 +1051,13 @@ export class DependencyGraph { for (let col = columnStart; col <= matrixRange.end.col; ++col) { const destination = simpleCellAddress(sheet, col, row) const source = simpleCellAddress(sheet, col + numberOfColumns, row) + const value = matrix.getMatrixCellValue(destination) this.addressMapping.moveCell(source, destination) + valuesToRemoveFromIndex.push([source, value]) } } } + return valuesToRemoveFromIndex } private shrinkPossibleMatrixAndGetCell(address: SimpleCellAddress): Maybe { diff --git a/src/Operations.ts b/src/Operations.ts index a2c086fd7e..a29794a1d9 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -584,8 +584,11 @@ export class Operations { return } - const affectedMatrices = this.dependencyGraph.addColumns(addedColumns) + const [affectedMatrices, valuesToRemoveFromIndex] = this.dependencyGraph.addColumns(addedColumns) this.columnSearch.addColumns(addedColumns) + for (const [address, value] of valuesToRemoveFromIndex) { + this.columnSearch.remove(getRawValue(value), address) + } this.stats.measure(StatType.TRANSFORM_ASTS, () => { const transformation = new AddColumnsTransformer(addedColumns) diff --git a/test/column-index.spec.ts b/test/column-index.spec.ts index a8d53c1bb9..cf2a837efb 100644 --- a/test/column-index.spec.ts +++ b/test/column-index.spec.ts @@ -12,7 +12,7 @@ import {ColumnIndex} from '../src/Lookup/ColumnIndex' import {NamedExpressions} from '../src/NamedExpressions' import {ColumnsSpan, RowsSpan} from '../src/Span' import {Statistics} from '../src/statistics' -import {adr, expectColumnIndexToMatchSheet} from './testUtils' +import {adr, columnIndexToSheet, expectColumnIndexToMatchSheet} from './testUtils' import {HyperFormula} from '../src' import {EmptyValue} from '../src/interpreter/InterpreterValue' @@ -717,6 +717,34 @@ describe('Arrays', () => { ], engine) }) + it('should move array values when adding columns before array', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C2:D2'], + [null, 'foo', 1, 2] + ], {useArrayArithmetic: true, useColumnIndex: true}) + + engine.addColumns(0, [0, 1]) + + expectColumnIndexToMatchSheet([ + [null, -1, -2], + [null, null, 'foo', 1, 2] + ], engine) + }) + + it('should not move array values when adding columns', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C2:E2', null, null, -3, -2, -1], + [null, 'foo', 1, 2, 3] + ], {useArrayArithmetic: true, useColumnIndex: true}) + + engine.addColumns(0, [1, 1]) + + expectColumnIndexToMatchSheet([ + [-1, -2, -3, null, -3, -2, -1], + [null, null, 'foo', 1, 2, 3] + ], engine) + }) + it('should remove array values from index when removing row with left corner', () => { const engine = HyperFormula.buildFromArray([ ['=-B2:B3'], From ebf8f9e508aa8b8648789ed32e7ba18c58d005ed Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 26 Jun 2021 13:02:04 +0200 Subject: [PATCH 70/87] Adjust removing columns by analogy --- src/CrudOperations.ts | 7 -- src/DependencyGraph/DependencyGraph.ts | 46 +++++++-- src/Operations.ts | 5 +- test/cruds/removing-columns.spec.ts | 133 +++++++++++++++++++++---- 4 files changed, 155 insertions(+), 36 deletions(-) diff --git a/src/CrudOperations.ts b/src/CrudOperations.ts index ce605f35f7..7a552c0b02 100644 --- a/src/CrudOperations.ts +++ b/src/CrudOperations.ts @@ -474,7 +474,6 @@ export class CrudOperations { if (rowEnd < rowStart) { throw new InvalidArgumentsError('starting row to be smaller than the ending row.') } - if (!this.sheetMapping.hasSheetWithId(sheet)) { throw new NoSheetWithIdError(sheet) } @@ -509,15 +508,9 @@ export class CrudOperations { if (columnEnd < columnStart) { throw new InvalidArgumentsError('starting column to be smaller than the ending column.') } - const columnsToRemove = ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart, columnEnd) - if (!this.sheetMapping.hasSheetWithId(sheet)) { throw new NoSheetWithIdError(sheet) } - - if (this.dependencyGraph.matrixMapping.isFormulaMatrixInColumns(columnsToRemove)) { - throw new SourceLocationHasMatrixError() - } } } diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index c998027a83..7337d4e17e 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -349,18 +349,19 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() } - public removeColumns(removedColumns: ColumnsSpan) { - if (this.matrixMapping.isFormulaMatrixInColumns(removedColumns)) { - throw Error('It is not possible to remove column within matrix') - } - + public removeColumns(removedColumns: ColumnsSpan): [Set, ContentChanges] { this.stats.measure(StatType.ADJUSTING_GRAPH, () => { - for (const vertex of this.addressMapping.verticesFromColumnsSpan(removedColumns)) { + for (const [address, vertex] of this.addressMapping.entriesFromColumnsSpan(removedColumns)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { this.graph.markNodeAsSpecialRecentlyChanged(adjacentNode) } if (vertex instanceof MatrixVertex) { - continue + if (vertex.isLeftCorner(address)) { + this.shrinkMatrixToCorner(vertex) + this.matrixMapping.removeMatrix(vertex.getRange()) + } else { + continue + } } this.removeVertex(vertex) } @@ -370,11 +371,18 @@ export class DependencyGraph { this.addressMapping.removeColumns(removedColumns) }) - this.stats.measure(StatType.ADJUSTING_RANGES, () => { - this.truncateRanges(removedColumns, address => address.col) + const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { + const affectedRanges = this.truncateRanges(removedColumns, address => address.col) + return this.getMatrixVerticesRelatedToRanges(affectedRanges) + }) + + this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { + this.fixMatricesAfterRemovingColumns(removedColumns.sheet, removedColumns.columnStart, removedColumns.numberOfColumns) }) this.addStructuralNodesToChangeSet() + + return [affectedMatrices, this.getAndClearContentChanges()] } public addRows(addedRows: RowsSpan): AddRowsResult { @@ -398,10 +406,10 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() - return { affectedArrays } + return {affectedArrays} } - public addColumns(addedColumns: ColumnsSpan): [Set, [SimpleCellAddress, InterpreterValue][]] { + public addColumns(addedColumns: ColumnsSpan): [Set, [SimpleCellAddress, InterpreterValue][]] { this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.addColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) }) @@ -1060,6 +1068,22 @@ export class DependencyGraph { return valuesToRemoveFromIndex } + private fixMatricesAfterRemovingColumns(sheet: number, columnStart: number, numberOfColumns: number) { + this.matrixMapping.moveMatrixVerticesAfterColumnByColumns(sheet, columnStart, -numberOfColumns) + if (columnStart <= 0) { + return + } + for (const [, matrix] of this.matrixMapping.matricesInCols(ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) { + if (this.isThereSpaceForMatrix(matrix)) { + for (const address of matrix.getRange().addresses(this)) { + this.addressMapping.setCell(address, matrix) + } + } else { + this.setNoSpaceIfMatrix(matrix) + } + } + } + private shrinkPossibleMatrixAndGetCell(address: SimpleCellAddress): Maybe { const vertex = this.getCell(address) if (!(vertex instanceof MatrixVertex)) { diff --git a/src/Operations.ts b/src/Operations.ts index a29794a1d9..1cd8fa2cf2 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -517,8 +517,9 @@ export class Operations { removedCells.push({address, cellType: this.getClipboardCell(address)}) } - this.dependencyGraph.removeColumns(columnsToRemove) + const [affectedMatrices, changes] = this.dependencyGraph.removeColumns(columnsToRemove) this.columnSearch.removeColumns(columnsToRemove) + this.columnSearch.applyChanges(changes.getChanges()) let version: number this.stats.measure(StatType.TRANSFORM_ASTS, () => { @@ -527,6 +528,8 @@ export class Operations { version = this.lazilyTransformingAstService.addTransformation(transformation) }) + this.rewriteAffectedMatrices(affectedMatrices) + return { version: version!, removedCells, diff --git a/test/cruds/removing-columns.spec.ts b/test/cruds/removing-columns.spec.ts index 136ec51da6..2ff25db9ed 100644 --- a/test/cruds/removing-columns.spec.ts +++ b/test/cruds/removing-columns.spec.ts @@ -11,7 +11,7 @@ import { expectReferenceToHaveRefError, extractMatrixRange, extractRange, - extractReference, + extractReference, noSpace, verifyRangesInSheet, verifyValues, } from '../testUtils' @@ -58,16 +58,16 @@ describe('Removing columns - checking if its possible', () => { expect(engine.isItPossibleToRemoveColumns(-Infinity, [0, 1])).toEqual(false) }) - it('no if theres a formula matrix in place where we remove', () => { + it('yes if theres an array in place where we remove', () => { const engine = HyperFormula.buildFromArray([ - ['1', '2', '=TRANSPOSE(A1:B2)', undefined, '13'], + ['1', '2', '=TRANSPOSE(A1:B2)'], ['3', '4'], ]) expect(engine.isItPossibleToRemoveColumns(0, [1, 1])).toEqual(true) - expect(engine.isItPossibleToRemoveColumns(0, [1, 2])).toEqual(false) - expect(engine.isItPossibleToRemoveColumns(0, [2, 1])).toEqual(false) - expect(engine.isItPossibleToRemoveColumns(0, [3, 1])).toEqual(false) + expect(engine.isItPossibleToRemoveColumns(0, [1, 2])).toEqual(true) + expect(engine.isItPossibleToRemoveColumns(0, [2, 1])).toEqual(true) + expect(engine.isItPossibleToRemoveColumns(0, [3, 1])).toEqual(true) expect(engine.isItPossibleToRemoveColumns(0, [4, 1])).toEqual(true) }) @@ -490,16 +490,7 @@ describe('Removing columns - reevaluation', () => { }) }) -describe('Removing columns - matrices', () => { - it('should not remove column within formula matrix', () => { - const engine = HyperFormula.buildFromArray([ - ['1', '2', '=MMULT(A1:B2, A1:B2)'], - ['3', '4'], - ]) - - expect(() => engine.removeColumns(0, [2, 1])).toThrowError('Cannot perform this operation, source location has a matrix inside.') - }) - +describe('Removing rows - arrays', () => { it('MatrixVertex#formula should be updated', () => { const engine = HyperFormula.buildFromArray([ ['1', '2', '3', '=TRANSPOSE(A1:C2)'], @@ -538,6 +529,114 @@ describe('Removing columns - matrices', () => { expect(extractMatrixRange(engine, adr('A1', 1))).toEqual(new AbsoluteCellRange(adr('A1'), adr('B2'))) }) + + it('should be possible to remove column before array', () => { + const engine = HyperFormula.buildFromArray([ + [null, '=-B3:D4', null, null, 'foo'], + ], {useArrayArithmetic: true}) + + engine.removeColumns(0, [0, 1]) + + const expected = HyperFormula.buildFromArray([ + ['=-A3:C4', null, null, 'foo'], + ], {useArrayArithmetic: true}) + + expectEngineToBeTheSameAs(engine, expected) + }) + + it('removing column across array should not change array', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, 3, '=-A1:C2', null, null, null, 'foo'], + [4, 5, 6] + ], {useArrayArithmetic: true}) + + engine.removeColumns(0, [4, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2, 3, '=-A1:C2', null, null, 'foo'], + [4, 5, 6] + ], {useArrayArithmetic: true})) + }) + + it('removing column should shrink dependent array', () => { + const engine = HyperFormula.buildFromArray([ + [1, null, 3, '=TRANSPOSE(A1:C2)'], + [2, null, 4], + ], {useArrayArithmetic: true}) + + engine.removeColumns(0, [1, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 3, '=TRANSPOSE(A1:B2)'], + [2, 4], + ], {useArrayArithmetic: true})) + }) + + it('it should be REF if no space after removing column', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C2:D2', null, 1], + [null, null, 1, 2] + ], {useArrayArithmetic: true}) + + engine.removeColumns(0, [1, 1]) + + expect(engine.getSheetValues(0)).toEqual([ + [noSpace(), 1], + [null, 1, 2], + ]) + + const expected = HyperFormula.buildFromArray([ + ['=-B2:C2', 1], + [null, 1, 2] + ], {useArrayArithmetic: true}) + + expectEngineToBeTheSameAs(engine, expected) + }) + + it('it should be REF, not CYCLE, after removing columns', () => { + const engine = HyperFormula.buildFromArray([ + ['=-C1:D1', null, 1, 2] + ], {useArrayArithmetic: true}) + + engine.removeColumns(0, [1, 1]) + + expect(engine.getSheetValues(0)).toEqual([ + [noSpace(), 1, 2], + ]) + + const expected = HyperFormula.buildFromArray([ + ['=-B1:C1', 1, 2], + ], {useArrayArithmetic: true}) + expectEngineToBeTheSameAs(engine, expected) + }) + + it('it should remove array when removing column with left corner', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2', '=MMULT(A1:B2, A1:B2)'], + ['3', '4'], + ]) + + engine.removeColumns(0, [2, 1]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4] + ])) + }) + + it('it should remove array when removing columns with whole matrix', () => { + const engine = HyperFormula.buildFromArray([ + ['1', '2', '=MMULT(A1:B2, A1:B2)'], + ['3', '4'], + ]) + + engine.removeColumns(0, [2, 2]) + + expectEngineToBeTheSameAs(engine, HyperFormula.buildFromArray([ + [1, 2], + [3, 4] + ])) + }) }) describe('Removing columns - graph', function() { @@ -679,7 +778,7 @@ describe('Removing columns - sheet dimensions', () => { }) describe('Removing columns - column index', () => { - it('should update column index when adding row', () => { + it('should update column index when adding column', () => { const engine = HyperFormula.buildFromArray([ ['', '1', '=VLOOKUP(2, A1:A10, 1, TRUE())'], ], { useColumnIndex: true }) From 33726394c5e7447a154b8c1f7a42b1c73a2f32ad Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sat, 26 Jun 2021 13:51:27 +0200 Subject: [PATCH 71/87] ColumnIndex needs to be adjusted --- src/DependencyGraph/DependencyGraph.ts | 17 +++--- src/Operations.ts | 7 ++- test/column-index.spec.ts | 82 ++++++++++++++++++++++---- 3 files changed, 84 insertions(+), 22 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 7337d4e17e..56a3a2ec35 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -45,7 +45,6 @@ import {MatrixMapping} from './MatrixMapping' import {RangeMapping} from './RangeMapping' import {SheetMapping} from './SheetMapping' import {RawAndParsedValue} from './ValueCellVertex' -import internal from 'stream' export class DependencyGraph { /** @@ -349,7 +348,7 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() } - public removeColumns(removedColumns: ColumnsSpan): [Set, ContentChanges] { + public removeColumns(removedColumns: ColumnsSpan): [Set, ContentChanges, [SimpleCellAddress, InterpreterValue][]] { this.stats.measure(StatType.ADJUSTING_GRAPH, () => { for (const [address, vertex] of this.addressMapping.entriesFromColumnsSpan(removedColumns)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { @@ -376,13 +375,13 @@ export class DependencyGraph { return this.getMatrixVerticesRelatedToRanges(affectedRanges) }) - this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { - this.fixMatricesAfterRemovingColumns(removedColumns.sheet, removedColumns.columnStart, removedColumns.numberOfColumns) + const valuesToUdpateInIndex = this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { + return this.fixMatricesAfterRemovingColumns(removedColumns.sheet, removedColumns.columnStart, removedColumns.numberOfColumns) }) this.addStructuralNodesToChangeSet() - return [affectedMatrices, this.getAndClearContentChanges()] + return [affectedMatrices, this.getAndClearContentChanges(), valuesToUdpateInIndex] } public addRows(addedRows: RowsSpan): AddRowsResult { @@ -1068,20 +1067,24 @@ export class DependencyGraph { return valuesToRemoveFromIndex } - private fixMatricesAfterRemovingColumns(sheet: number, columnStart: number, numberOfColumns: number) { + private fixMatricesAfterRemovingColumns(sheet: number, columnStart: number, numberOfColumns: number): [SimpleCellAddress, InterpreterValue][] { + const valuesToUpdateInIndex: [SimpleCellAddress, InterpreterValue][] = [] this.matrixMapping.moveMatrixVerticesAfterColumnByColumns(sheet, columnStart, -numberOfColumns) if (columnStart <= 0) { - return + return [] } for (const [, matrix] of this.matrixMapping.matricesInCols(ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) { if (this.isThereSpaceForMatrix(matrix)) { for (const address of matrix.getRange().addresses(this)) { + const value = matrix.getMatrixCellValue(address) + valuesToUpdateInIndex.push([address, value]) this.addressMapping.setCell(address, matrix) } } else { this.setNoSpaceIfMatrix(matrix) } } + return valuesToUpdateInIndex } private shrinkPossibleMatrixAndGetCell(address: SimpleCellAddress): Maybe { diff --git a/src/Operations.ts b/src/Operations.ts index 1cd8fa2cf2..ec7535226a 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -517,9 +517,12 @@ export class Operations { removedCells.push({address, cellType: this.getClipboardCell(address)}) } - const [affectedMatrices, changes] = this.dependencyGraph.removeColumns(columnsToRemove) - this.columnSearch.removeColumns(columnsToRemove) + const [affectedMatrices, changes, valuesToUpdateInIndex] = this.dependencyGraph.removeColumns(columnsToRemove) this.columnSearch.applyChanges(changes.getChanges()) + this.columnSearch.removeColumns(columnsToRemove) + for (const [address, value] of valuesToUpdateInIndex) { + this.columnSearch.add(getRawValue(value), address) + } let version: number this.stats.measure(StatType.TRANSFORM_ASTS, () => { diff --git a/test/column-index.spec.ts b/test/column-index.spec.ts index cf2a837efb..ba4e45711d 100644 --- a/test/column-index.spec.ts +++ b/test/column-index.spec.ts @@ -717,6 +717,36 @@ describe('Arrays', () => { ], engine) }) + it('should remove array values from index when removing row with left corner', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B2:B3'], + [null, 1], + [null, 2], + ], {useArrayArithmetic: true, useColumnIndex: true}) + + engine.removeRows(0, [0, 1]) + + expectColumnIndexToMatchSheet([ + [null, 1], + [null, 2] + ], engine) + }) + + it('should remove array values from index when REF after removing rows', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B2:B3'], + [null, 1], + [3, 2], + ], {useArrayArithmetic: true, useColumnIndex: true}) + + engine.removeRows(0, [1, 1]) + + expectColumnIndexToMatchSheet([ + [], + [3, 2] + ], engine) + }) + it('should move array values when adding columns before array', () => { const engine = HyperFormula.buildFromArray([ ['=-C2:D2'], @@ -745,33 +775,59 @@ describe('Arrays', () => { ], engine) }) - it('should remove array values from index when removing row with left corner', () => { + it('should move array values when removing columns before array', () => { const engine = HyperFormula.buildFromArray([ - ['=-B2:B3'], - [null, 1], - [null, 2], + [null, '=-C2:D2'], + [null, null, 1, 2] ], {useArrayArithmetic: true, useColumnIndex: true}) - engine.removeRows(0, [0, 1]) + engine.removeColumns(0, [0, 1]) expectColumnIndexToMatchSheet([ - [null, 1], - [null, 2] + [-1, -2], + [null, 1, 2] ], engine) }) - it('should remove array values from index when REF after removing rows', () => { + it('should not move array values when removing columns', () => { const engine = HyperFormula.buildFromArray([ - ['=-B2:B3'], - [null, 1], - [3, 2], + ['=-D2:E2', null, null, -2, -1], + [-2, 'foo', null, 1, 2] ], {useArrayArithmetic: true, useColumnIndex: true}) - engine.removeRows(0, [1, 1]) + engine.removeColumns(0, [1, 1]) + + expectColumnIndexToMatchSheet([ + [-1, -2, -2, -1], + [-2, null, 1, 2] + ], engine) + }) + + it('should remove array values from index when removing column with left corner', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B2:C2'], + [null, 1, 2], + ], {useArrayArithmetic: true, useColumnIndex: true}) + + engine.removeColumns(0, [0, 1]) expectColumnIndexToMatchSheet([ [], - [3, 2] + [1, 2], + ], engine) + }) + + it('should remove array values from index when REF after removing columns', () => { + const engine = HyperFormula.buildFromArray([ + ['=-B2:C2', null, 1], + [2, null, 3] + ], {useArrayArithmetic: true, useColumnIndex: true}) + + engine.removeColumns(0, [1, 1]) + + expectColumnIndexToMatchSheet([ + [null, 1], + [2, 3] ], engine) }) }) From 8d6b95ea2df0f7fca98448c84d17f6e39eddeb46 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 27 Jun 2021 08:53:59 +0200 Subject: [PATCH 72/87] Do not allow to move columns inside array --- src/CrudOperations.ts | 3 +++ src/DependencyGraph/MatrixMapping.ts | 11 ++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/CrudOperations.ts b/src/CrudOperations.ts index 7a552c0b02..7d25a99fb2 100644 --- a/src/CrudOperations.ts +++ b/src/CrudOperations.ts @@ -563,6 +563,9 @@ export class CrudOperations { if (this.dependencyGraph.matrixMapping.isFormulaMatrixInRange(sourceRange)) { throw new SourceLocationHasMatrixError() } + if (targetColumn > 0 && this.dependencyGraph.matrixMapping.isFormulaMatrixInAllColumns(ColumnsSpan.fromNumberOfColumns(sheet, targetColumn - 1, 2))) { + throw new TargetLocationHasMatrixError() + } } public ensureItIsPossibleToAddSheet(name: string): void { diff --git a/src/DependencyGraph/MatrixMapping.ts b/src/DependencyGraph/MatrixMapping.ts index 71e0ee98d5..14c107e733 100644 --- a/src/DependencyGraph/MatrixMapping.ts +++ b/src/DependencyGraph/MatrixMapping.ts @@ -65,7 +65,7 @@ export class MatrixMapping { return false } - public isFormulaMatrixInAllRows(span: RowsSpan) { + public isFormulaMatrixInAllRows(span: RowsSpan): boolean { let result = true for (const row of span.rows()) { if (!this.isFormulaMatrixInRow(span.sheet, row)) { @@ -84,13 +84,14 @@ export class MatrixMapping { return false } - public isFormulaMatrixInColumns(span: ColumnsSpan) { + public isFormulaMatrixInAllColumns(span: ColumnsSpan): boolean { + let result = true for (const col of span.columns()) { - if (this.isFormulaMatrixInColumn(span.sheet, col)) { - return true + if (!this.isFormulaMatrixInColumn(span.sheet, col)) { + result = false } } - return false + return result } public isFormulaMatrixInRange(range: AbsoluteCellRange) { From c29f3accc2931a42d6ca33fdd5e8319c9ab10a66 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 27 Jun 2021 10:00:49 +0200 Subject: [PATCH 73/87] Cleanup --- src/DependencyGraph/DependencyGraph.ts | 46 ++++++++++++-------------- src/Operations.ts | 17 ++++------ 2 files changed, 28 insertions(+), 35 deletions(-) diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 56a3a2ec35..ca3ba35cd7 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -254,7 +254,7 @@ export class DependencyGraph { return vertex } - public removeRows(removedRows: RowsSpan): RemoveRowsResult { + public removeRows(removedRows: RowsSpan): EagerChangesGraphChangeResult { this.stats.measure(StatType.ADJUSTING_GRAPH, () => { for (const [address, vertex] of this.addressMapping.entriesFromRowsSpan(removedRows)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { @@ -348,7 +348,7 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() } - public removeColumns(removedColumns: ColumnsSpan): [Set, ContentChanges, [SimpleCellAddress, InterpreterValue][]] { + public removeColumns(removedColumns: ColumnsSpan): EagerChangesGraphChangeResult { this.stats.measure(StatType.ADJUSTING_GRAPH, () => { for (const [address, vertex] of this.addressMapping.entriesFromColumnsSpan(removedColumns)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { @@ -370,21 +370,24 @@ export class DependencyGraph { this.addressMapping.removeColumns(removedColumns) }) - const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { + const affectedArrays = this.stats.measure(StatType.ADJUSTING_RANGES, () => { const affectedRanges = this.truncateRanges(removedColumns, address => address.col) return this.getMatrixVerticesRelatedToRanges(affectedRanges) }) - const valuesToUdpateInIndex = this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { + this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { return this.fixMatricesAfterRemovingColumns(removedColumns.sheet, removedColumns.columnStart, removedColumns.numberOfColumns) }) this.addStructuralNodesToChangeSet() - return [affectedMatrices, this.getAndClearContentChanges(), valuesToUdpateInIndex] + return { + affectedArrays, + contentChanges: this.getAndClearContentChanges(), + } } - public addRows(addedRows: RowsSpan): AddRowsResult { + public addRows(addedRows: RowsSpan): ArrayAffectingGraphChangeResult { this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.addRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows) }) @@ -408,18 +411,18 @@ export class DependencyGraph { return {affectedArrays} } - public addColumns(addedColumns: ColumnsSpan): [Set, [SimpleCellAddress, InterpreterValue][]] { + public addColumns(addedColumns: ColumnsSpan): EagerChangesGraphChangeResult { this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.addColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) }) - const affectedMatrices = this.stats.measure(StatType.ADJUSTING_RANGES, () => { + const affectedArrays = this.stats.measure(StatType.ADJUSTING_RANGES, () => { const result = this.rangeMapping.moveAllRangesInSheetAfterColumnByColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) this.fixRangesWhenAddingColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) return this.getMatrixVerticesRelatedToRanges(result.verticesWithChangedSize) }) - const valuesToRemoveFromIndex = this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { + this.stats.measure(StatType.ADJUSTING_MATRIX_MAPPING, () => { return this.fixMatricesAfterAddingColumn(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns) }) @@ -429,7 +432,7 @@ export class DependencyGraph { this.addStructuralNodesToChangeSet() - return [affectedMatrices, valuesToRemoveFromIndex] + return {affectedArrays, contentChanges: this.getAndClearContentChanges()} } public ensureNoMatrixInRange(range: AbsoluteCellRange) { @@ -1023,7 +1026,9 @@ export class DependencyGraph { for (let row = rowStart; row <= matrixRange.end.row; ++row) { const destination = simpleCellAddress(sheet, col, row) const source = simpleCellAddress(sheet, col, row + numberOfRows) + const value = matrix.getMatrixCellValue(destination) this.addressMapping.moveCell(source, destination) + this.changes.addChange(EmptyValue, source, value) } } } @@ -1046,11 +1051,10 @@ export class DependencyGraph { } - private fixMatricesAfterAddingColumn(sheet: number, columnStart: number, numberOfColumns: number): [SimpleCellAddress, InterpreterValue][] { - const valuesToRemoveFromIndex: [SimpleCellAddress, InterpreterValue][] = [] + private fixMatricesAfterAddingColumn(sheet: number, columnStart: number, numberOfColumns: number) { this.matrixMapping.moveMatrixVerticesAfterColumnByColumns(sheet, columnStart, numberOfColumns) if (columnStart <= 0) { - return [] + return } for (const [, matrix] of this.matrixMapping.matricesInCols(ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) { const matrixRange = matrix.getRange() @@ -1060,31 +1064,26 @@ export class DependencyGraph { const source = simpleCellAddress(sheet, col + numberOfColumns, row) const value = matrix.getMatrixCellValue(destination) this.addressMapping.moveCell(source, destination) - valuesToRemoveFromIndex.push([source, value]) + this.changes.addChange(EmptyValue, source, value) } } } - return valuesToRemoveFromIndex } - private fixMatricesAfterRemovingColumns(sheet: number, columnStart: number, numberOfColumns: number): [SimpleCellAddress, InterpreterValue][] { - const valuesToUpdateInIndex: [SimpleCellAddress, InterpreterValue][] = [] + private fixMatricesAfterRemovingColumns(sheet: number, columnStart: number, numberOfColumns: number) { this.matrixMapping.moveMatrixVerticesAfterColumnByColumns(sheet, columnStart, -numberOfColumns) if (columnStart <= 0) { - return [] + return } for (const [, matrix] of this.matrixMapping.matricesInCols(ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) { if (this.isThereSpaceForMatrix(matrix)) { for (const address of matrix.getRange().addresses(this)) { - const value = matrix.getMatrixCellValue(address) - valuesToUpdateInIndex.push([address, value]) this.addressMapping.setCell(address, matrix) } } else { this.setNoSpaceIfMatrix(matrix) } } - return valuesToUpdateInIndex } private shrinkPossibleMatrixAndGetCell(address: SimpleCellAddress): Maybe { @@ -1141,11 +1140,10 @@ export class DependencyGraph { } } -export interface AddRowsResult { +export interface ArrayAffectingGraphChangeResult { affectedArrays: Set, } -export interface RemoveRowsResult { - affectedArrays: Set, +export interface EagerChangesGraphChangeResult extends ArrayAffectingGraphChangeResult { contentChanges: ContentChanges, } diff --git a/src/Operations.ts b/src/Operations.ts index ec7535226a..da6e9c0a45 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -517,12 +517,9 @@ export class Operations { removedCells.push({address, cellType: this.getClipboardCell(address)}) } - const [affectedMatrices, changes, valuesToUpdateInIndex] = this.dependencyGraph.removeColumns(columnsToRemove) - this.columnSearch.applyChanges(changes.getChanges()) + const {affectedArrays, contentChanges} = this.dependencyGraph.removeColumns(columnsToRemove) + this.columnSearch.applyChanges(contentChanges.getChanges()) this.columnSearch.removeColumns(columnsToRemove) - for (const [address, value] of valuesToUpdateInIndex) { - this.columnSearch.add(getRawValue(value), address) - } let version: number this.stats.measure(StatType.TRANSFORM_ASTS, () => { @@ -531,7 +528,7 @@ export class Operations { version = this.lazilyTransformingAstService.addTransformation(transformation) }) - this.rewriteAffectedMatrices(affectedMatrices) + this.rewriteAffectedMatrices(affectedArrays) return { version: version!, @@ -590,11 +587,9 @@ export class Operations { return } - const [affectedMatrices, valuesToRemoveFromIndex] = this.dependencyGraph.addColumns(addedColumns) + const {affectedArrays, contentChanges} = this.dependencyGraph.addColumns(addedColumns) this.columnSearch.addColumns(addedColumns) - for (const [address, value] of valuesToRemoveFromIndex) { - this.columnSearch.remove(getRawValue(value), address) - } + this.columnSearch.applyChanges(contentChanges.getChanges()) this.stats.measure(StatType.TRANSFORM_ASTS, () => { const transformation = new AddColumnsTransformer(addedColumns) @@ -602,7 +597,7 @@ export class Operations { this.lazilyTransformingAstService.addTransformation(transformation) }) - this.rewriteAffectedMatrices(affectedMatrices) + this.rewriteAffectedMatrices(affectedArrays) } public getOldContent(address: SimpleCellAddress): [SimpleCellAddress, ClipboardCell] { From a4ba74dea8f3e29d7780e9906dcb50272a86caa6 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 27 Jun 2021 10:55:37 +0200 Subject: [PATCH 74/87] Fix browser tests --- test/address-mapping.spec.ts | 8 +++--- test/content-changes.spec.ts | 38 +++++++++++++------------- test/cruds/change-cell-content.spec.ts | 2 +- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/test/address-mapping.spec.ts b/test/address-mapping.spec.ts index d163bc0753..6660b3c415 100644 --- a/test/address-mapping.spec.ts +++ b/test/address-mapping.spec.ts @@ -329,7 +329,7 @@ const sharedExamples = (builder: (width: number, height: number) => AddressMappi it('should throw error when trying to move not existing vertex', () => { const mapping = builder(1, 2) - expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrow(Error('Cannot move cell. No cell with such address.')) + expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrowError('Cannot move cell. No cell with such address.') }) it('should throw error when trying to move vertex onto occupied place', () => { @@ -337,21 +337,21 @@ const sharedExamples = (builder: (width: number, height: number) => AddressMappi mapping.setCell(adr('A1'), new ValueCellVertex(42, 42)) mapping.setCell(adr('A2'), new ValueCellVertex(42, 42)) - expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrow(Error('Cannot move cell. Destination already occupied.')) + expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrowError('Cannot move cell. Destination already occupied.') }) it('should throw error when trying to move vertices between sheets', () => { const mapping = builder(1, 2) mapping.setCell(adr('A1', 0), new ValueCellVertex(42, 42)) - expect(() => mapping.moveCell(adr('A1', 0), adr('A2', 1))).toThrow('Cannot move cells between sheets.') + expect(() => mapping.moveCell(adr('A1', 0), adr('A2', 1))).toThrowError('Cannot move cells between sheets.') }) it('should throw error when trying to move vertices in non-existing sheet', () => { const mapping = builder(1, 2) mapping.setCell(adr('A1', 0), new ValueCellVertex(42, 42)) - expect(() => mapping.moveCell(adr('A1', 3), adr('A2', 3))).toThrow('Sheet not initialized.') + expect(() => mapping.moveCell(adr('A1', 3), adr('A2', 3))).toThrowError('Sheet not initialized.') }) } diff --git a/test/content-changes.spec.ts b/test/content-changes.spec.ts index 79595f1b70..9801ce83d4 100644 --- a/test/content-changes.spec.ts +++ b/test/content-changes.spec.ts @@ -2,28 +2,28 @@ import {CellValueChange, ChangeExporter, ContentChanges} from '../src/ContentCha import {SimpleRangeValue} from '../src/interpreter/SimpleRangeValue' import {adr} from './testUtils' -class IdentityChangeExporter implements ChangeExporter{ +class SimpleChangeExporter implements ChangeExporter { exportChange(change: CellValueChange): CellValueChange { - return change + return {address: change.address, value: change.value} } } -class SpreadRangeExporter implements ChangeExporter{ +class SpreadRangeExporter implements ChangeExporter { exportChange(change: CellValueChange): CellValueChange | CellValueChange[] { const value = change.value const address = change.address if (value instanceof SimpleRangeValue) { return Array.from(value.entriesFromTopLeftCorner(address)).map(([v, a]) => { - return { address: a, value: v } + return {address: a, value: v} }) } else { - return change + return {address: address, value: value} } } } describe('ContentChanges', () => { - const identityChangeExporter = new IdentityChangeExporter() + const simpleChangeExporter = new SimpleChangeExporter() it('should be empty', () => { const contentChanges = ContentChanges.empty() @@ -37,9 +37,9 @@ describe('ContentChanges', () => { contentChanges.addChange(1, adr('A1')) contentChanges.addChange(2, adr('A1')) - const exportedChanges = contentChanges.exportChanges(identityChangeExporter) + const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 2}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 2}) }) it('should export simple value change', () => { @@ -47,11 +47,11 @@ describe('ContentChanges', () => { contentChanges.addChange(1, adr('A1')) - const exportedChanges = contentChanges.exportChanges(identityChangeExporter) + const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(contentChanges.isEmpty()).toEqual(false) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 1}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 1}) }) it('should export SimpleRangeValue change', () => { @@ -59,10 +59,10 @@ describe('ContentChanges', () => { contentChanges.addChange(SimpleRangeValue.onlyValues([['foo', 'bar']]), adr('A1')) - const exportedChanges = contentChanges.exportChanges(identityChangeExporter) + const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: SimpleRangeValue.onlyValues([['foo', 'bar']])}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: SimpleRangeValue.onlyValues([['foo', 'bar']])}) }) it('should add all changes', () => { @@ -73,10 +73,10 @@ describe('ContentChanges', () => { otherChanges.addChange(2, adr('A2')) contentChanges.addAll(otherChanges) - const exportedChanges = contentChanges.exportChanges(identityChangeExporter) + const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(exportedChanges.length).toEqual(2) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 1}) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 1}, value: 2}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 1}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 1}, value: 2}) }) it('should handle array change', () => { @@ -86,9 +86,9 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(new SpreadRangeExporter()) expect(exportedChanges.length).toEqual(4) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 1}) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 1, row: 0}, value: 2}) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 1}, value: 'foo'}) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 1, row: 1}, value: 'bar'}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 1}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 1, row: 0}, value: 2}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 1}, value: 'foo'}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 1, row: 1}, value: 'bar'}) }) }) diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 375ebda182..e0099f06a2 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -1202,7 +1202,7 @@ describe('arrays', () => { ], {useArrayArithmetic: true})) }) - it.skip('should recalculate matrix if space is available', () => { + xit('should recalculate matrix if space is available', () => { const engine = HyperFormula.buildFromArray([ ['=+C1:D1', 'foo', 1, 2] ], {useArrayArithmetic: true}) From ff6f3a158691e9209c5d88e9dd21c70b2003cf1a Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Sun, 27 Jun 2021 10:55:37 +0200 Subject: [PATCH 75/87] Fix browser tests --- test/address-mapping.spec.ts | 8 +++--- test/content-changes.spec.ts | 38 +++++++++++++------------- test/cruds/adding-columns.spec.ts | 2 +- test/cruds/change-cell-content.spec.ts | 2 +- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/test/address-mapping.spec.ts b/test/address-mapping.spec.ts index d163bc0753..6660b3c415 100644 --- a/test/address-mapping.spec.ts +++ b/test/address-mapping.spec.ts @@ -329,7 +329,7 @@ const sharedExamples = (builder: (width: number, height: number) => AddressMappi it('should throw error when trying to move not existing vertex', () => { const mapping = builder(1, 2) - expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrow(Error('Cannot move cell. No cell with such address.')) + expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrowError('Cannot move cell. No cell with such address.') }) it('should throw error when trying to move vertex onto occupied place', () => { @@ -337,21 +337,21 @@ const sharedExamples = (builder: (width: number, height: number) => AddressMappi mapping.setCell(adr('A1'), new ValueCellVertex(42, 42)) mapping.setCell(adr('A2'), new ValueCellVertex(42, 42)) - expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrow(Error('Cannot move cell. Destination already occupied.')) + expect(() => mapping.moveCell(adr('A1'), adr('A2'))).toThrowError('Cannot move cell. Destination already occupied.') }) it('should throw error when trying to move vertices between sheets', () => { const mapping = builder(1, 2) mapping.setCell(adr('A1', 0), new ValueCellVertex(42, 42)) - expect(() => mapping.moveCell(adr('A1', 0), adr('A2', 1))).toThrow('Cannot move cells between sheets.') + expect(() => mapping.moveCell(adr('A1', 0), adr('A2', 1))).toThrowError('Cannot move cells between sheets.') }) it('should throw error when trying to move vertices in non-existing sheet', () => { const mapping = builder(1, 2) mapping.setCell(adr('A1', 0), new ValueCellVertex(42, 42)) - expect(() => mapping.moveCell(adr('A1', 3), adr('A2', 3))).toThrow('Sheet not initialized.') + expect(() => mapping.moveCell(adr('A1', 3), adr('A2', 3))).toThrowError('Sheet not initialized.') }) } diff --git a/test/content-changes.spec.ts b/test/content-changes.spec.ts index 79595f1b70..9801ce83d4 100644 --- a/test/content-changes.spec.ts +++ b/test/content-changes.spec.ts @@ -2,28 +2,28 @@ import {CellValueChange, ChangeExporter, ContentChanges} from '../src/ContentCha import {SimpleRangeValue} from '../src/interpreter/SimpleRangeValue' import {adr} from './testUtils' -class IdentityChangeExporter implements ChangeExporter{ +class SimpleChangeExporter implements ChangeExporter { exportChange(change: CellValueChange): CellValueChange { - return change + return {address: change.address, value: change.value} } } -class SpreadRangeExporter implements ChangeExporter{ +class SpreadRangeExporter implements ChangeExporter { exportChange(change: CellValueChange): CellValueChange | CellValueChange[] { const value = change.value const address = change.address if (value instanceof SimpleRangeValue) { return Array.from(value.entriesFromTopLeftCorner(address)).map(([v, a]) => { - return { address: a, value: v } + return {address: a, value: v} }) } else { - return change + return {address: address, value: value} } } } describe('ContentChanges', () => { - const identityChangeExporter = new IdentityChangeExporter() + const simpleChangeExporter = new SimpleChangeExporter() it('should be empty', () => { const contentChanges = ContentChanges.empty() @@ -37,9 +37,9 @@ describe('ContentChanges', () => { contentChanges.addChange(1, adr('A1')) contentChanges.addChange(2, adr('A1')) - const exportedChanges = contentChanges.exportChanges(identityChangeExporter) + const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 2}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 2}) }) it('should export simple value change', () => { @@ -47,11 +47,11 @@ describe('ContentChanges', () => { contentChanges.addChange(1, adr('A1')) - const exportedChanges = contentChanges.exportChanges(identityChangeExporter) + const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(contentChanges.isEmpty()).toEqual(false) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 1}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 1}) }) it('should export SimpleRangeValue change', () => { @@ -59,10 +59,10 @@ describe('ContentChanges', () => { contentChanges.addChange(SimpleRangeValue.onlyValues([['foo', 'bar']]), adr('A1')) - const exportedChanges = contentChanges.exportChanges(identityChangeExporter) + const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: SimpleRangeValue.onlyValues([['foo', 'bar']])}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: SimpleRangeValue.onlyValues([['foo', 'bar']])}) }) it('should add all changes', () => { @@ -73,10 +73,10 @@ describe('ContentChanges', () => { otherChanges.addChange(2, adr('A2')) contentChanges.addAll(otherChanges) - const exportedChanges = contentChanges.exportChanges(identityChangeExporter) + const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(exportedChanges.length).toEqual(2) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 1}) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 1}, value: 2}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 1}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 1}, value: 2}) }) it('should handle array change', () => { @@ -86,9 +86,9 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(new SpreadRangeExporter()) expect(exportedChanges.length).toEqual(4) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 0}, value: 1}) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 1, row: 0}, value: 2}) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 0, row: 1}, value: 'foo'}) - expect(exportedChanges).toContainEqual({ address: {sheet: 0, col: 1, row: 1}, value: 'bar'}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 1}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 1, row: 0}, value: 2}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 1}, value: 'foo'}) + expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 1, row: 1}, value: 'bar'}) }) }) diff --git a/test/cruds/adding-columns.spec.ts b/test/cruds/adding-columns.spec.ts index ad841cf2d9..be19b56510 100644 --- a/test/cruds/adding-columns.spec.ts +++ b/test/cruds/adding-columns.spec.ts @@ -204,7 +204,7 @@ describe('Adding column - FormulaCellVertex#address update', () => { }) /* TODO size of matrix can be dependent on structural changes */ -describe.skip('Adding column - MatrixVertex', () => { +xdescribe('Adding column - MatrixVertex', () => { it('MatrixVertex#formula should be updated', () => { const engine = HyperFormula.buildFromArray([ ['1', '2', '=TRANSPOSE(A1:B2)'], diff --git a/test/cruds/change-cell-content.spec.ts b/test/cruds/change-cell-content.spec.ts index 375ebda182..e0099f06a2 100644 --- a/test/cruds/change-cell-content.spec.ts +++ b/test/cruds/change-cell-content.spec.ts @@ -1202,7 +1202,7 @@ describe('arrays', () => { ], {useArrayArithmetic: true})) }) - it.skip('should recalculate matrix if space is available', () => { + xit('should recalculate matrix if space is available', () => { const engine = HyperFormula.buildFromArray([ ['=+C1:D1', 'foo', 1, 2] ], {useArrayArithmetic: true}) From 9c409649318ab3f403a607d64feb0877eafa7bb0 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 2 Jul 2021 10:19:33 +0200 Subject: [PATCH 76/87] Adjust tsdoc --- src/HyperFormula.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 47f69abd31..ca64ff982c 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -1526,6 +1526,7 @@ export class HyperFormula implements TypedEmitter { * 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. * If returns `true`, doing [[addRows]] operation won't throw any errors. + * Returns `false` if adding rows would exceed the sheet size limit or given arguments are invalid. * * @param {number} sheetId - sheet ID in which rows will be added * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format [row, amount], where row is a row number above which the rows will be added @@ -1594,6 +1595,7 @@ export class HyperFormula implements TypedEmitter { * Returns information whether it is possible to remove rows from a specified position in a given sheet. * Checks against particular rules to ascertain that removeRows can be called. * If returns `true`, doing [[removeRows]] operation won't throw any errors. + * Returns `false` if given arguments are invalid. * * @param {number} sheetId - sheet ID from which rows will be removed * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [row, amount] From 861737a0aa244a5a330fece2ed2c18bfc3a28c63 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 2 Jul 2021 10:45:11 +0200 Subject: [PATCH 77/87] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use adr helper function insted of raw objects. Co-authored-by: Przemysław Uznański <40573492+izulin@users.noreply.github.com> --- test/content-changes.spec.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/test/content-changes.spec.ts b/test/content-changes.spec.ts index 9801ce83d4..e1c0c39b7f 100644 --- a/test/content-changes.spec.ts +++ b/test/content-changes.spec.ts @@ -39,7 +39,7 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 2}) + expect(exportedChanges).toContainEqual({address: adr('A1'), value: 2}) }) it('should export simple value change', () => { @@ -51,7 +51,7 @@ describe('ContentChanges', () => { expect(contentChanges.isEmpty()).toEqual(false) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 1}) + expect(exportedChanges).toContainEqual({address: adr('A1'), value: 1}) }) it('should export SimpleRangeValue change', () => { @@ -62,7 +62,7 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(exportedChanges.length).toEqual(1) - expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: SimpleRangeValue.onlyValues([['foo', 'bar']])}) + expect(exportedChanges).toContainEqual({address: adr('A1'), value: SimpleRangeValue.onlyValues([['foo', 'bar']])}) }) it('should add all changes', () => { @@ -75,8 +75,8 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(simpleChangeExporter) expect(exportedChanges.length).toEqual(2) - expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 1}) - expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 1}, value: 2}) + expect(exportedChanges).toContainEqual({address: adr('A1'), value: 1}) + expect(exportedChanges).toContainEqual({address: adr('A2'), value: 2}) }) it('should handle array change', () => { @@ -86,9 +86,9 @@ describe('ContentChanges', () => { const exportedChanges = contentChanges.exportChanges(new SpreadRangeExporter()) expect(exportedChanges.length).toEqual(4) - expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 0}, value: 1}) - expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 1, row: 0}, value: 2}) - expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 0, row: 1}, value: 'foo'}) - expect(exportedChanges).toContainEqual({address: {sheet: 0, col: 1, row: 1}, value: 'bar'}) + expect(exportedChanges).toContainEqual({address: adr('A1'), value: 1}) + expect(exportedChanges).toContainEqual({address: adr('B1'), value: 2}) + expect(exportedChanges).toContainEqual({address: adr('A2'), value: 'foo'}) + expect(exportedChanges).toContainEqual({address: adr('B2'), value: 'bar'}) }) }) From 57834fe9e4db91a9323a67b90596df23df206286 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 2 Jul 2021 10:54:30 +0200 Subject: [PATCH 78/87] Adjust tsdocs --- src/HyperFormula.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 47f69abd31..92f330662d 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -1662,7 +1662,7 @@ export class HyperFormula implements TypedEmitter { * Returns information whether it is possible to add columns into a specified position in a given sheet. * Checks against particular rules to ascertain that addColumns can be called. * If returns `true`, doing [[addColumns]] operation won't throw any errors. - * Returns `false` if the operation might be disrupted and causes side-effects by the fact that there is a matrix inside the selected columns. + * Returns `false` if adding columns would exceed the sheet size limit or given arguments are invalid. * * @param {number} sheetId - sheet ID in which columns will be added * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [column, amount], where column is a column number from which new columns will be added @@ -1736,7 +1736,7 @@ export class HyperFormula implements TypedEmitter { * Returns information whether it is possible to remove columns from a specified position in a given sheet. * Checks against particular rules to ascertain that removeColumns can be called. * If returns `true`, doing [[removeColumns]] operation won't throw any errors. - * Returns `false` if the operation might be disrupted and causes side-effects by the fact that there is a matrix inside the selected columns. + * Returns `false` if given arguments are invalid. * * @param {number} sheetId - sheet ID from which columns will be removed * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format [column, amount] From c027918c3f59679054784e84f2ef115b4b3b591d Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 2 Jul 2021 11:11:18 +0200 Subject: [PATCH 79/87] Update CHANGELOG --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f68a9dd44..3a19cafef5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Breaking change**: Changed API of the following methods to take `SimpleCellRange` type argument: `copy`, `cut`, `getCellDependents`, `getCellPrecedents`, `getFillRangeData`, `getRangeFormulas`, `getRangeSerialized`, `getRangeValues`, `isItPossibleToMoveCells`, `isItPossibleToSetCellContents`, `moveCells`. (#687) - **Breaking change**: Changed the AGPLv3 license to GPLv3. - **Breaking change**: Removed the free non-commercial license. -- Changed SWITCH function so it takes array as its first argument. +- **Breaking change**: Changed behaviour of `setCellContents` so that it is possible to override space occupied by spilled array. (#708) +- **Breaking change**: Changed behaviour of `addRows/removeRows` so that it is possible to add/remove rows across spilled array without changing array size. (#708) +- Changed SWITCH function, so it takes array as its first argument. - Changed TRANSPOSE function, so it works with data of any type. (#670) ### Added From a895bf52668d4ac6a872cb172f57e6554c8cd784 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 2 Jul 2021 14:01:42 +0200 Subject: [PATCH 80/87] Adjust tsdocs --- src/HyperFormula.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 66ac26e836..127a9363ae 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -1725,7 +1725,6 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding - * @throws [[TargetLocationHasMatrixError]] when the selected position has matrix inside * * @example * ```js @@ -1799,7 +1798,6 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when the given arguments are invalid - * @throws [[SourceLocationHasMatrixError]] when the selected position has matrix inside * * @example * ```js From 8fca66389cb3611206d2d0b2c4a7e1ab2b016f03 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 2 Jul 2021 14:01:52 +0200 Subject: [PATCH 81/87] Update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a19cafef5..941f044b17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Breaking change**: Removed the free non-commercial license. - **Breaking change**: Changed behaviour of `setCellContents` so that it is possible to override space occupied by spilled array. (#708) - **Breaking change**: Changed behaviour of `addRows/removeRows` so that it is possible to add/remove rows across spilled array without changing array size. (#708) +- **Breaking change**: Changed behaviour of `addColumns/removeColumns` so that it is possible to add/remove columns across spilled array without changing array size. (#732) - Changed SWITCH function, so it takes array as its first argument. - Changed TRANSPOSE function, so it works with data of any type. (#670) From 92a04a2d56fea2e0d0960f67a18f573b82a4801f Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Fri, 2 Jul 2021 14:05:06 +0200 Subject: [PATCH 82/87] Adjust tsdocs --- src/HyperFormula.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index e7e8db91e8..43b9827953 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -1109,7 +1109,7 @@ export class HyperFormula implements TypedEmitter { /** * Returns information whether it is possible to change the content in a rectangular area bounded by the box. * If returns `true`, doing [[setCellContents]] operation won't throw any errors. - * Returns `false` if the operation might be disrupted and causes side-effects by the fact that there is a matrix inside selected cells, the address is invalid or the sheet does not exist. + * Returns `false` if the address is invalid or the sheet does not exist. * * @param {SimpleCellAddress | SimpleCellRange} address - single cell or block of cells to check * From b355e1de7329ef6705b0c28c8cf991974d082e36 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Mon, 5 Jul 2021 09:13:17 +0200 Subject: [PATCH 83/87] SPILL array error --- src/Cell.ts | 3 +++ src/i18n/languages/csCZ.ts | 1 + src/i18n/languages/daDK.ts | 1 + src/i18n/languages/deDE.ts | 1 + src/i18n/languages/enGB.ts | 1 + src/i18n/languages/esES.ts | 1 + src/i18n/languages/fiFI.ts | 1 + src/i18n/languages/frFR.ts | 1 + src/i18n/languages/huHU.ts | 1 + src/i18n/languages/itIT.ts | 1 + src/i18n/languages/nbNO.ts | 1 + src/i18n/languages/nlNL.ts | 1 + src/i18n/languages/plPL.ts | 1 + src/i18n/languages/ptPT.ts | 1 + src/i18n/languages/ruRU.ts | 1 + src/i18n/languages/svSE.ts | 1 + src/i18n/languages/trTR.ts | 1 + 17 files changed, 19 insertions(+) diff --git a/src/Cell.ts b/src/Cell.ts index c596805cc5..ca9a07306f 100644 --- a/src/Cell.ts +++ b/src/Cell.ts @@ -36,6 +36,9 @@ export enum ErrorType { /** Wrong address reference. */ REF = 'REF', + /** Array spill error. */ + SPILL = 'SPILL', + /** Invalid/missing licence error. */ LIC = 'LIC', diff --git a/src/i18n/languages/csCZ.ts b/src/i18n/languages/csCZ.ts index de95e2b3c5..bf4ba20165 100644 --- a/src/i18n/languages/csCZ.ts +++ b/src/i18n/languages/csCZ.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NÁZEV?', NUM: '#ČÍSLO!', REF: '#ODKAZ!', + SPILL: '#PRESAH!', VALUE: '#HODNOTA!', }, functions: { diff --git a/src/i18n/languages/daDK.ts b/src/i18n/languages/daDK.ts index 1c16365cce..27a5e2ebca 100644 --- a/src/i18n/languages/daDK.ts +++ b/src/i18n/languages/daDK.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NAVN?', NUM: '#NUMMER!', REF: '#REFERENCE!', + SPILL: '#OVERLØB!', VALUE: '#VÆRDI!', }, functions: { diff --git a/src/i18n/languages/deDE.ts b/src/i18n/languages/deDE.ts index 94120b58d6..9deea7c9fc 100644 --- a/src/i18n/languages/deDE.ts +++ b/src/i18n/languages/deDE.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NAME?', NUM: '#ZAHL!', REF: '#BEZUG!', + SPILL: '#ÜBERLAUF!', VALUE: '#WERT!', }, functions: { diff --git a/src/i18n/languages/enGB.ts b/src/i18n/languages/enGB.ts index 79beb76b83..9641af66e2 100644 --- a/src/i18n/languages/enGB.ts +++ b/src/i18n/languages/enGB.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NAME?', NUM: '#NUM!', REF: '#REF!', + SPILL: '#SPILL!', VALUE: '#VALUE!', }, functions: { diff --git a/src/i18n/languages/esES.ts b/src/i18n/languages/esES.ts index e97874cb85..98a422ea3c 100644 --- a/src/i18n/languages/esES.ts +++ b/src/i18n/languages/esES.ts @@ -15,6 +15,7 @@ export const dictionary: RawTranslationPackage = { NAME: '#¿NOMBRE?', NUM: '#¡NUM!', REF: '#¡REF!', + SPILL: '#¡DESBORDAMIENTO!', VALUE: '#¡VALOR!', }, functions: { diff --git a/src/i18n/languages/fiFI.ts b/src/i18n/languages/fiFI.ts index 286f1f0807..6202a4f941 100644 --- a/src/i18n/languages/fiFI.ts +++ b/src/i18n/languages/fiFI.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NIMI?', NUM: '#LUKU!', REF: '#VIITTAUS!', + SPILL: '#LEVITTYMINEN!', VALUE: '#ARVO!', }, functions: { diff --git a/src/i18n/languages/frFR.ts b/src/i18n/languages/frFR.ts index 6db4d175d2..c7ec8aa190 100644 --- a/src/i18n/languages/frFR.ts +++ b/src/i18n/languages/frFR.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NOM?', NUM: '#NOMBRE!', REF: '#REF!', + SPILL: '#EPARS!', VALUE: '#VALEUR!', }, functions: { diff --git a/src/i18n/languages/huHU.ts b/src/i18n/languages/huHU.ts index 9057caaa2c..0844592a0c 100644 --- a/src/i18n/languages/huHU.ts +++ b/src/i18n/languages/huHU.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NÉV?', NUM: '#SZÁM!', REF: '#HIV!', + SPILL: '#KIBONTÁS!', VALUE: '#ÉRTÉK!', }, functions: { diff --git a/src/i18n/languages/itIT.ts b/src/i18n/languages/itIT.ts index a8ca660aa2..aa24e82299 100644 --- a/src/i18n/languages/itIT.ts +++ b/src/i18n/languages/itIT.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NOME?', NUM: '#NUM!', REF: '#RIF!', + SPILL: '#ESPANSIONE!', VALUE: '#VALORE!', }, functions: { diff --git a/src/i18n/languages/nbNO.ts b/src/i18n/languages/nbNO.ts index 601d44cca0..afb45a15d1 100644 --- a/src/i18n/languages/nbNO.ts +++ b/src/i18n/languages/nbNO.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NAVN?', NUM: '#NUM!', REF: '#REF!', + SPILL: '#OVERFLYT!', VALUE: '#VERDI!', }, functions: { diff --git a/src/i18n/languages/nlNL.ts b/src/i18n/languages/nlNL.ts index 8f3d57c6b7..2920ed1ee8 100644 --- a/src/i18n/languages/nlNL.ts +++ b/src/i18n/languages/nlNL.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NAAM?', NUM: '#GETAL!', REF: '#VERW!', + SPILL: '#OVERLOOP!', VALUE: '#WAARDE!', }, functions: { diff --git a/src/i18n/languages/plPL.ts b/src/i18n/languages/plPL.ts index f1115b6380..83145ae569 100644 --- a/src/i18n/languages/plPL.ts +++ b/src/i18n/languages/plPL.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NAZWA?', NUM: '#LICZBA!', REF: '#ADR!', + SPILL: '#ROZLANIE!', VALUE: '#ARG!', }, functions: { diff --git a/src/i18n/languages/ptPT.ts b/src/i18n/languages/ptPT.ts index 340fa89e19..93decffcdc 100644 --- a/src/i18n/languages/ptPT.ts +++ b/src/i18n/languages/ptPT.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NOME?', NUM: '#NÚM!', REF: '#REF!', + SPILL: '#TRANSPOSIÇÃO!', VALUE: '#VALOR!', }, functions: { diff --git a/src/i18n/languages/ruRU.ts b/src/i18n/languages/ruRU.ts index f6c75de334..e2ea4539e9 100644 --- a/src/i18n/languages/ruRU.ts +++ b/src/i18n/languages/ruRU.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#ИМЯ?', NUM: '#ЧИСЛО!', REF: '#ССЫЛКА!', + SPILL: '#ПЕРЕНОС!', VALUE: '#ЗНАЧ!', }, functions: { diff --git a/src/i18n/languages/svSE.ts b/src/i18n/languages/svSE.ts index 9e467df3a1..0a7769f526 100644 --- a/src/i18n/languages/svSE.ts +++ b/src/i18n/languages/svSE.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#NAMN?', NUM: '#OGILTIGT!', REF: '#REFERENS!', + SPILL: '#SPILL!', VALUE: '#VÄRDEFEL!', }, functions: { diff --git a/src/i18n/languages/trTR.ts b/src/i18n/languages/trTR.ts index 4c33134d09..12c9091579 100644 --- a/src/i18n/languages/trTR.ts +++ b/src/i18n/languages/trTR.ts @@ -15,6 +15,7 @@ const dictionary: RawTranslationPackage = { NAME: '#AD?', NUM: '#SAYI!', REF: '#BAŞV!', + SPILL: '#TAŞMA!', VALUE: '#DEĞER!', }, functions: { From c3cf3c2e4439f225474aa7247958a84a703db73e Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Mon, 5 Jul 2021 09:13:55 +0200 Subject: [PATCH 84/87] SPILL instead of REF --- src/DependencyGraph/FormulaCellVertex.ts | 2 +- test/testUtils.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/DependencyGraph/FormulaCellVertex.ts b/src/DependencyGraph/FormulaCellVertex.ts index 382d329141..49a4feaeeb 100644 --- a/src/DependencyGraph/FormulaCellVertex.ts +++ b/src/DependencyGraph/FormulaCellVertex.ts @@ -161,7 +161,7 @@ export class MatrixVertex extends FormulaVertex { } setNoSpace(): InterpreterValue { - this.matrix = new ErroredMatrix(new CellError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult), MatrixSize.error()) + this.matrix = new ErroredMatrix(new CellError(ErrorType.SPILL, ErrorMessage.NoSpaceForArrayResult), MatrixSize.error()) return this.getCellValue() } diff --git a/test/testUtils.ts b/test/testUtils.ts index 1a997d9300..186a0d9ede 100644 --- a/test/testUtils.ts +++ b/test/testUtils.ts @@ -155,7 +155,7 @@ export function detailedError(errorType: ErrorType, message?: string, config?: C } export function noSpace(): DetailedCellError { - return detailedError(ErrorType.REF, ErrorMessage.NoSpaceForArrayResult) + return detailedError(ErrorType.SPILL, ErrorMessage.NoSpaceForArrayResult) } export function detailedErrorWithOrigin(errorType: ErrorType, address: string, message?: string, config?: Config): DetailedCellError { From 519622d84c8a1155d4f841654a0a072efe96ff7f Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Mon, 5 Jul 2021 09:15:27 +0200 Subject: [PATCH 85/87] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a19cafef5..94264960e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added pretty print for detailedCellError. (#712) - Added `simpleCellRangeFromString` and `simpleCellRangeToString` helpers. (#720) - Added `CellError` to exports. (#736) +- Added `#SPILL!` error type. (#708) ### Fixed - Fixed an issue with arrays and cruds. (#651) From 9af813efe95432631a3a08824919cfbfe240bf9d Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Mon, 5 Jul 2021 09:29:17 +0200 Subject: [PATCH 86/87] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94264960e2..5f60b80517 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Breaking change**: Changed behaviour of `setCellContents` so that it is possible to override space occupied by spilled array. (#708) - **Breaking change**: Changed behaviour of `addRows/removeRows` so that it is possible to add/remove rows across spilled array without changing array size. (#708) - Changed SWITCH function, so it takes array as its first argument. -- Changed TRANSPOSE function, so it works with data of any type. (#670) +- Changed TRANSPOSE function, so it works with data of any type. (#708) ### Added - Added support for array arithmetic. (#628) From 2012c315835aa58833ae7a7169b9b7c98d4299d6 Mon Sep 17 00:00:00 2001 From: Jakub Kowalski Date: Mon, 5 Jul 2021 10:26:04 +0200 Subject: [PATCH 87/87] Unused import --- src/AbsoluteCellRange.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AbsoluteCellRange.ts b/src/AbsoluteCellRange.ts index 3d3ab306bf..29743dee4c 100644 --- a/src/AbsoluteCellRange.ts +++ b/src/AbsoluteCellRange.ts @@ -15,7 +15,7 @@ import { import {DependencyGraph} from './DependencyGraph' import {SheetsNotEqual} from './errors' import {Maybe} from './Maybe' -import {AstNodeType, CellAddress, CellRangeAst} from './parser' +import {AstNodeType, CellRangeAst} from './parser' import {ColumnRangeAst, RowRangeAst} from './parser/Ast' import {RowsSpan, Span} from './Span'