Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(sheets-data-validation): large data validation oom (#3492)

zhangw42ce25727293
diff --git a/packages/core/src/shared/__tests__/range.spec.ts b/packages/core/src/shared/__tests__/range.spec.ts
index f66b76d48f..ab0b040c85 100644
--- a/packages/core/src/shared/__tests__/range.spec.ts
+++ b/packages/core/src/shared/__tests__/range.spec.ts
@@ -16,8 +16,9 @@
import { describe, expect, it } from 'vitest';
-import { moveRangeByOffset } from '../range';
import { AbsoluteRefType } from '../../sheets/typedef';
+import { mergeHorizontalRanges, mergeRanges, mergeVerticalRanges, moveRangeByOffset, splitIntoGrid } from '../range';
+import type { IRange } from '../../sheets/typedef';
describe('test moveRangeByOffset', () => {
it('test normal', () => {
@@ -76,3 +77,335 @@ describe('test moveRangeByOffset', () => {
});
});
});
+
+// Test cases
+describe('splitIntoGrid', () => {
+ it('should split and align ranges into grid cells', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 1 },
+ { startColumn: 6, endColumn: 8, startRow: 1, endRow: 2 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 1 },
+ { startColumn: 6, endColumn: 8, startRow: 1, endRow: 1 },
+ { startColumn: 6, endColumn: 8, startRow: 2, endRow: 2 },
+ ];
+
+ expect(splitIntoGrid(input)).toEqual(expected);
+ });
+
+ it('should handle no ranges', () => {
+ const input: IRange[] = [];
+ const expected: IRange[] = [];
+ expect(splitIntoGrid(input)).toEqual(expected);
+ });
+
+ it('should handle single range', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 2 },
+ ];
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 2 },
+ ];
+ expect(splitIntoGrid(input)).toEqual(expected);
+ });
+
+ it('should handle simple case', () => {
+ const input = [{ startColumn: 1, endColumn: 5, startRow: 1, endRow: 1 }, { startColumn: 6, endColumn: 8, startRow: 1, endRow: 2 }];
+ const expected = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 1 },
+ { startColumn: 6, endColumn: 8, startRow: 1, endRow: 1 },
+ { startColumn: 6, endColumn: 8, startRow: 2, endRow: 2 },
+ ];
+
+ expect(splitIntoGrid(input)).toEqual(expected);
+ });
+
+ it('should handle this case', () => {
+ const input = [
+ {
+ startColumn: 0,
+ endColumn: 5,
+ startRow: 6,
+ endRow: 10,
+ },
+ {
+ startColumn: 6,
+ startRow: 8,
+ endColumn: 7,
+ endRow: 8,
+ },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 0, endColumn: 5, startRow: 6, endRow: 7 },
+ { startColumn: 0, endColumn: 5, startRow: 8, endRow: 8 },
+ { startColumn: 6, endColumn: 7, startRow: 8, endRow: 8 },
+ { startColumn: 0, endColumn: 5, startRow: 9, endRow: 10 },
+ ];
+ expect(JSON.stringify(splitIntoGrid(input))).toEqual(JSON.stringify(expected));
+ });
+});
+
+describe('mergeHorizontalRanges', () => {
+ it('should merge contiguous ranges horizontally', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 1 },
+ { startColumn: 6, endColumn: 8, startRow: 1, endRow: 1 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 8, startRow: 1, endRow: 1 },
+ ];
+
+ expect(mergeHorizontalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle ranges with gaps', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 1 },
+ { startColumn: 5, endColumn: 7, startRow: 1, endRow: 1 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 1 },
+ { startColumn: 5, endColumn: 7, startRow: 1, endRow: 1 },
+ ];
+
+ expect(mergeHorizontalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle overlapping ranges', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 1 },
+ { startColumn: 4, endColumn: 8, startRow: 1, endRow: 1 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 8, startRow: 1, endRow: 1 },
+ ];
+
+ expect(mergeHorizontalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle multiple rows independently', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 1 },
+ { startColumn: 6, endColumn: 8, startRow: 1, endRow: 1 },
+ { startColumn: 1, endColumn: 3, startRow: 2, endRow: 2 },
+ { startColumn: 4, endColumn: 7, startRow: 2, endRow: 2 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 8, startRow: 1, endRow: 1 },
+ { startColumn: 1, endColumn: 7, startRow: 2, endRow: 2 },
+ ];
+
+ expect(mergeHorizontalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle single range', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 1 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 1 },
+ ];
+
+ expect(mergeHorizontalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle no ranges', () => {
+ const input: IRange[] = [];
+ const expected: IRange[] = [];
+ expect(mergeHorizontalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle complex ranges', () => {
+ const input = [
+ { startColumn: 1, endColumn: 1, startRow: 1, endRow: 2 },
+ { startColumn: 2, endColumn: 2, startRow: 1, endRow: 2 },
+ { startColumn: 3, endColumn: 3, startRow: 1, endRow: 2 },
+ { startColumn: 4, endColumn: 4, startRow: 1, endRow: 2 },
+ { startColumn: 5, endColumn: 5, startRow: 1, endRow: 2 },
+ { startColumn: 6, endColumn: 6, startRow: 1, endRow: 2 },
+ { startColumn: 7, endColumn: 7, startRow: 1, endRow: 2 },
+ ];
+ const expected = [{ startColumn: 1, endColumn: 7, startRow: 1, endRow: 2 }];
+ expect(JSON.stringify(mergeHorizontalRanges(input))).toEqual(JSON.stringify(expected));
+ });
+});
+
+// Test cases
+describe('mergeVerticalRanges', () => {
+ it('should merge contiguous ranges vertically', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 1, startRow: 1, endRow: 5 },
+ { startColumn: 1, endColumn: 1, startRow: 6, endRow: 10 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 1, startRow: 1, endRow: 10 },
+ ];
+
+ expect(mergeVerticalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle ranges with gaps', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 1, startRow: 1, endRow: 3 },
+ { startColumn: 1, endColumn: 1, startRow: 5, endRow: 7 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 1, startRow: 1, endRow: 3 },
+ { startColumn: 1, endColumn: 1, startRow: 5, endRow: 7 },
+ ];
+
+ expect(mergeVerticalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle overlapping ranges', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 1, startRow: 1, endRow: 5 },
+ { startColumn: 1, endColumn: 1, startRow: 4, endRow: 8 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 1, startRow: 1, endRow: 8 },
+ ];
+
+ expect(mergeVerticalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle multiple columns independently', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 1, startRow: 1, endRow: 5 },
+ { startColumn: 2, endColumn: 2, startRow: 1, endRow: 5 },
+ { startColumn: 1, endColumn: 1, startRow: 6, endRow: 8 },
+ { startColumn: 2, endColumn: 2, startRow: 6, endRow: 8 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 1, startRow: 1, endRow: 8 },
+ { startColumn: 2, endColumn: 2, startRow: 1, endRow: 8 },
+ ];
+
+ expect(mergeVerticalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle single range', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 8, startRow: 1, endRow: 2 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 8, startRow: 1, endRow: 2 },
+ ];
+
+ expect(mergeVerticalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle no ranges', () => {
+ const input: IRange[] = [];
+ const expected: IRange[] = [];
+ expect(mergeVerticalRanges(input)).toEqual(expected);
+ });
+
+ it('should handle this case', () => {
+ const input: IRange[] = [
+ { startColumn: 0, endColumn: 5, startRow: 6, endRow: 7 },
+ { startColumn: 0, endColumn: 7, startRow: 8, endRow: 8 },
+ { startColumn: 0, endColumn: 5, startRow: 9, endRow: 10 },
+ ];
+
+ expect(JSON.stringify(mergeVerticalRanges(input))).toEqual(JSON.stringify(input));
+ });
+});
+
+describe('mergeRanges', () => {
+ it('should merge ranges correctly', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 2 },
+ { startColumn: 6, endColumn: 8, startRow: 1, endRow: 2 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 8, startRow: 1, endRow: 2 },
+ ];
+
+ expect(JSON.stringify(mergeRanges(input))).toEqual(JSON.stringify(expected));
+ });
+
+ it('should handle no ranges', () => {
+ const input: IRange[] = [];
+ const expected: IRange[] = [];
+ expect(mergeRanges(input)).toEqual(expected);
+ });
+
+ it('should handle single range', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 3 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 3 },
+ ];
+
+ expect(mergeRanges(input)).toEqual(expected);
+ });
+
+ it('should handle ranges with gaps', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 2 },
+ { startColumn: 5, endColumn: 7, startRow: 1, endRow: 2 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 3, startRow: 1, endRow: 2 },
+ { startColumn: 5, endColumn: 7, startRow: 1, endRow: 2 },
+ ];
+
+ expect(mergeRanges(input)).toEqual(expected);
+ });
+
+ it('should handle multiple ranges in multiple rows and columns', () => {
+ const input: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 1 },
+ { startColumn: 5, endColumn: 5, startRow: 2, endRow: 5 },
+ { startColumn: 1, endColumn: 4, startRow: 2, endRow: 5 },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 5 },
+ ];
+
+ expect(JSON.stringify(mergeRanges(input))).toEqual(JSON.stringify(expected));
+ });
+
+ it('should handle this case', () => {
+ const input = [
+ {
+ startColumn: 0,
+ endColumn: 5,
+ startRow: 6,
+ endRow: 10,
+ },
+ {
+ startColumn: 6,
+ startRow: 8,
+ endColumn: 7,
+ endRow: 8,
+ },
+ ];
+
+ const expected: IRange[] = [
+ { startColumn: 0, endColumn: 5, startRow: 6, endRow: 7 },
+ { startColumn: 0, endColumn: 7, startRow: 8, endRow: 8 },
+ { startColumn: 0, endColumn: 5, startRow: 9, endRow: 10 },
+ ];
+ expect(JSON.stringify(mergeRanges(input))).toEqual(JSON.stringify(expected));
+ });
+});
diff --git a/packages/core/src/shared/__tests__/rectangle.spec.ts b/packages/core/src/shared/__tests__/rectangle.spec.ts
index a0764f55f0..f22760531f 100644
--- a/packages/core/src/shared/__tests__/rectangle.spec.ts
+++ b/packages/core/src/shared/__tests__/rectangle.spec.ts
@@ -15,10 +15,24 @@
*/
import { describe, expect, it } from 'vitest';
-
+import { Range } from '../../sheets/range';
+import { AbsoluteRefType } from '../../sheets/typedef';
+import { ObjectMatrix } from '../object-matrix';
+import { multiSubtractMultiRanges } from '../object-matrix-query';
import { Rectangle } from '../rectangle';
import type { IRange } from '../../sheets/typedef';
-import { AbsoluteRefType } from '../../sheets/typedef';
+
+function rangesToMatrix(ranges: IRange[]) {
+ // return JSON.stringify(ranges);
+ const matrix = new ObjectMatrix<number>();
+ ranges.forEach((range) => {
+ Range.foreach(range, (row, col) => {
+ matrix.setValue(row, col, 1);
+ });
+ });
+
+ return matrix.getMatrix();
+}
const cellToRange = (row: number, col: number) => ({ startRow: row, endRow: row, startColumn: col, endColumn: col } as IRange);
describe('test "Rectangle"', () => {
@@ -111,3 +125,68 @@ describe('test "Rectangle"', () => {
expect(positionRangeWithALl).toEqual({ ...originRange, endAbsoluteRefType: AbsoluteRefType.ALL, startAbsoluteRefType: AbsoluteRefType.ALL });
});
});
+
+describe('multiSubtractMulti', () => {
+ it('should subtract a single range from another range', () => {
+ const ranges1: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 5 },
+ ];
+ const ranges2: IRange[] = [
+ { startColumn: 2, endColumn: 4, startRow: 2, endRow: 4 },
+ ];
+ const expected: IRange[] = multiSubtractMultiRanges(ranges1, ranges2);
+ expect(rangesToMatrix(Rectangle.subtractMulti(ranges1, ranges2))).toEqual(rangesToMatrix(expected));
+ });
+
+ it('should handle subtracting multiple ranges from a single range', () => {
+ const ranges1: IRange[] = [
+ { startColumn: 1, endColumn: 10, startRow: 1, endRow: 10 },
+ ];
+ const ranges2: IRange[] = [
+ { startColumn: 2, endColumn: 5, startRow: 2, endRow: 5 },
+ { startColumn: 6, endColumn: 8, startRow: 6, endRow: 8 },
+ ];
+ const expected: IRange[] = multiSubtractMultiRanges(ranges1, ranges2);
+ expect(rangesToMatrix(Rectangle.subtractMulti(ranges1, ranges2))).toEqual(rangesToMatrix(expected));
+ });
+
+ it('should handle non-overlapping subtraction ranges', () => {
+ const ranges1: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 5 },
+ ];
+ const ranges2: IRange[] = [
+ { startColumn: 6, endColumn: 8, startRow: 6, endRow: 8 },
+ ];
+ const expected: IRange[] = multiSubtractMultiRanges(ranges1, ranges2);
+ expect(rangesToMatrix(Rectangle.subtractMulti(ranges1, ranges2))).toEqual(rangesToMatrix(expected));
+ });
+
+ it('should handle subtraction ranges that completely overlap', () => {
+ const ranges1: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 5 },
+ ];
+ const ranges2: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 5 },
+ ];
+ const expected: IRange[] = multiSubtractMultiRanges(ranges1, ranges2);
+ expect(rangesToMatrix(Rectangle.subtractMulti(ranges1, ranges2))).toEqual(rangesToMatrix(expected));
+ });
+
+ it('should handle empty ranges', () => {
+ const ranges1: IRange[] = [];
+ const ranges2: IRange[] = [
+ { startColumn: 2, endColumn: 4, startRow: 2, endRow: 4 },
+ ];
+ const expected: IRange[] = multiSubtractMultiRanges(ranges1, ranges2);
+ expect(rangesToMatrix(Rectangle.subtractMulti(ranges1, ranges2))).toEqual(rangesToMatrix(expected));
+ });
+
+ it('should handle empty subtraction ranges', () => {
+ const ranges1: IRange[] = [
+ { startColumn: 1, endColumn: 5, startRow: 1, endRow: 5 },
+ ];
+ const ranges2: IRange[] = [];
+ const expected: IRange[] = multiSubtractMultiRanges(ranges1, ranges2);
+ expect(rangesToMatrix(Rectangle.subtractMulti(ranges1, ranges2))).toEqual(rangesToMatrix(expected));
+ });
+});
diff --git a/packages/core/src/shared/object-matrix-query.ts b/packages/core/src/shared/object-matrix-query.ts
index ecca56d210..9afe6ff280 100644
--- a/packages/core/src/shared/object-matrix-query.ts
+++ b/packages/core/src/shared/object-matrix-query.ts
@@ -15,8 +15,9 @@
*/
import { Range } from '../sheets/range';
+import { ObjectMatrix } from './object-matrix';
+import { Rectangle } from './rectangle';
import type { IRange } from '../sheets/typedef';
-import type { ObjectMatrix } from './object-matrix';
import type { Nullable } from './types';
function maximalRectangle<T>(matrix: T[][], match: (val: T) => boolean) {
@@ -99,3 +100,21 @@ export function queryObjectMatrix<T>(matrix: ObjectMatrix<T>, match: (value: T)
return results;
}
+
+export function multiSubtractMultiRanges(ranges1: IRange[], ranges2: IRange[]): IRange[] {
+ const matrix = new ObjectMatrix<number>();
+
+ ranges1.forEach((range) => {
+ Range.foreach(range, (row, col) => {
+ matrix.setValue(row, col, 1);
+ });
+ });
+
+ ranges2.forEach((range) => {
+ Range.foreach(range, (row, col) => {
+ matrix.setValue(row, col, 0);
+ });
+ });
+
+ return Rectangle.mergeRanges(queryObjectMatrix(matrix, (value) => value === 1));
+}
diff --git a/packages/core/src/shared/range.ts b/packages/core/src/shared/range.ts
index a8559989d5..1c5d2ec114 100644
--- a/packages/core/src/shared/range.ts
+++ b/packages/core/src/shared/range.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { IRange } from '../sheets/typedef';
import { AbsoluteRefType } from '../sheets/typedef';
import { Rectangle } from './rectangle';
+import type { IRange } from '../sheets/typedef';
export function moveRangeByOffset(range: IRange, refOffsetX: number, refOffsetY: number, ignoreAbsolute = false): IRange {
let newRange = { ...range };
@@ -50,3 +50,176 @@ export function moveRangeByOffset(range: IRange, refOffsetX: number, refOffsetY:
return newRange;
}
+
+/**
+ * Split ranges into aligned smaller ranges
+ * @param ranges no overlap ranges
+ * @returns aligned smaller ranges
+ */
+export function splitIntoGrid(ranges: IRange[]): IRange[] {
+ const columns: Set<number> = new Set();
+ const rows: Set<number> = new Set();
+
+ // Extract unique column and row boundaries
+ for (const range of ranges) {
+ columns.add(range.startColumn);
+ columns.add(range.endColumn + 1); // Include boundary right after the end
+ rows.add(range.startRow);
+ rows.add(range.endRow + 1); // Include boundary right after the end
+ }
+
+ // Convert sets to sorted arrays
+ const sortedColumns = Array.from(columns).sort((a, b) => a - b);
+ const sortedRows = Array.from(rows).sort((a, b) => a - b);
+
+ // Create grid cells based on unique boundaries
+ const gridCells: IRange[] = [];
+ for (let i = 0; i < sortedRows.length - 1; i++) {
+ for (let j = 0; j < sortedColumns.length - 1; j++) {
+ gridCells.push({
+ startColumn: sortedColumns[j],
+ endColumn: sortedColumns[j + 1] - 1,
+ startRow: sortedRows[i],
+ endRow: sortedRows[i + 1] - 1,
+ });
+ }
+ }
+
+ // Assign original ranges to the grid cells
+ const result: IRange[] = [];
+ for (const gridCell of gridCells) {
+ for (const range of ranges) {
+ if (range.startRow <= gridCell.endRow && range.endRow >= gridCell.startRow &&
+ range.startColumn <= gridCell.endColumn && range.endColumn >= gridCell.startColumn) {
+ result.push({
+ startColumn: Math.max(gridCell.startColumn, range.startColumn),
+ endColumn: Math.min(gridCell.endColumn, range.endColumn),
+ startRow: Math.max(gridCell.startRow, range.startRow),
+ endRow: Math.min(gridCell.endRow, range.endRow),
+ });
+ break; // No need to check other ranges for this grid cell
+ }
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Horizontal Merging
+ * @param ranges no overlap ranges
+ * @returns merged ranges
+ */
+export function mergeHorizontalRanges(ranges: IRange[]): IRange[] {
+ ranges.sort((a, b) => a.startRow - b.startRow || a.startColumn - b.startColumn);
+ // Step 1: Group ranges by row
+ const rowGroups: { [key: number]: IRange[] } = {};
+
+ for (const range of ranges) {
+ if (!rowGroups[range.startRow]) {
+ rowGroups[range.startRow] = [];
+ }
+ rowGroups[range.startRow].push(range);
+ }
+
+ // Step 2: Merge ranges within each row
+ const mergedRanges: IRange[] = [];
+
+ for (const row in rowGroups) {
+ const rangesInRow = rowGroups[+row];
+
+ // Sort ranges by starting column
+ rangesInRow.sort((a, b) => a.startColumn - b.startColumn);
+
+ // Merge contiguous ranges
+ let currentRange = rangesInRow[0];
+
+ for (let i = 1; i < rangesInRow.length; i++) {
+ const nextRange = rangesInRow[i];
+
+ if (nextRange.startColumn <= currentRange.endColumn + 1 && nextRange.startRow === currentRange.startRow && nextRange.endRow === currentRange.endRow) {
+ // Ranges are contiguous, merge them
+ currentRange.endColumn = Math.max(currentRange.endColumn, nextRange.endColumn);
+ } else {
+ // Ranges are not contiguous, push the current range and start a new range
+ mergedRanges.push(currentRange);
+ currentRange = nextRange;
+ }
+ }
+
+ // Push the last range
+ mergedRanges.push(currentRange);
+ }
+
+ return mergedRanges;
+}
+
+/**
+ * Vertical Merging
+ * @param ranges no overlap ranges
+ * @returns merged ranges
+ */
+export function mergeVerticalRanges(ranges: IRange[]): IRange[] {
+ // Step 1: Sort ranges by columns and then by rows
+ ranges.sort((a, b) => a.startColumn - b.startColumn || a.startRow - b.startRow);
+
+ const columnGroups: { [key: number]: IRange[] } = {};
+
+ // Group ranges by columns
+ for (const range of ranges) {
+ if (!columnGroups[range.startColumn]) {
+ columnGroups[range.startColumn] = [];
+ }
+ columnGroups[range.startColumn].push(range);
+ }
+
+ // Step 2: Merge ranges within each column
+ const mergedRanges: IRange[] = [];
+
+ for (const col in columnGroups) {
+ const rangesInCol = columnGroups[+col];
+
+ // Sort ranges by starting row
+ rangesInCol.sort((a, b) => a.startRow - b.startRow);
+
+ // Merge contiguous ranges with the same column range
+ let currentRange = rangesInCol[0];
+
+ for (let i = 1; i < rangesInCol.length; i++) {
+ const nextRange = rangesInCol[i];
+
+ if (nextRange.startRow <= currentRange.endRow + 1 && nextRange.startColumn === currentRange.startColumn && nextRange.endColumn === currentRange.endColumn) {
+ // Ranges are contiguous and have the same column range, merge them
+ currentRange.endRow = Math.max(currentRange.endRow, nextRange.endRow);
+ } else {
+ // Ranges are not contiguous or have different column ranges, push the current range and start a new range
+ mergedRanges.push(currentRange);
+ currentRange = nextRange;
+ }
+ }
+
+ // Push the last range
+ mergedRanges.push(currentRange);
+ }
+
+ return mergedRanges;
+}
+/**
+ * Merge no overlap ranges
+ * @param ranges no overlap ranges
+ * @returns ranges
+ */
+export function mergeRanges(ranges: IRange[]): IRange[] {
+ const split = splitIntoGrid(ranges);
+ const horizontalMerged = mergeHorizontalRanges(split);
+ return mergeVerticalRanges(horizontalMerged);
+ // return horizontalMerged;
+}
+
+export function multiSubtractSingleRange(ranges: IRange[], toDelete: IRange) {
+ const res: IRange[] = [];
+ ranges.forEach((range) => {
+ res.push(...Rectangle.subtract(range, toDelete));
+ });
+ return Rectangle.mergeRanges(res);
+};
diff --git a/packages/core/src/shared/rectangle.ts b/packages/core/src/shared/rectangle.ts
index 2b05d12fd9..395f2ab7cd 100644
--- a/packages/core/src/shared/rectangle.ts
+++ b/packages/core/src/shared/rectangle.ts
@@ -15,6 +15,7 @@
*/
import { AbsoluteRefType, type IRange, type IRectLTRB, RANGE_TYPE } from '../sheets/typedef';
+import { mergeRanges, multiSubtractSingleRange } from './range';
import type { Nullable } from './types';
/**
@@ -313,6 +314,28 @@ export class Rectangle {
return result;
}
+ /**
+ * Combine smaller rectangles into larger ones
+ * @param ranges
+ * @returns
+ */
+ static mergeRanges(ranges: IRange[]): IRange[] {
+ return mergeRanges(ranges);
+ }
+
+ static subtractMulti(ranges1: IRange[], ranges2: IRange[]): IRange[] {
+ if (!ranges2.length) {
+ return ranges1;
+ }
+
+ let res: IRange[] = ranges1;
+ ranges2.forEach((range) => {
+ res = multiSubtractSingleRange(res, range);
+ });
+
+ return Rectangle.mergeRanges(res);
+ }
+
static hasIntersectionBetweenTwoRect(rect1: IRectLTRB, rect2: IRectLTRB) {
if (
rect1.left > rect2.right || // rect1 在 rect2 右侧
diff --git a/packages/sheets-data-validation/src/controllers/dv-auto-fill.controller.ts b/packages/sheets-data-validation/src/controllers/dv-auto-fill.controller.ts
index 488cf9e3cc..3645c4f3d8 100644
--- a/packages/sheets-data-validation/src/controllers/dv-auto-fill.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-auto-fill.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { DataValidationType, Disposable, Inject, Injector, LifecycleStages, OnLifecycle, Range, Rectangle } from '@univerjs/core';
+import { DataValidationType, Disposable, Inject, Injector, LifecycleStages, ObjectMatrix, OnLifecycle, queryObjectMatrix, Range, Rectangle } from '@univerjs/core';
import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
import type { IAutoFillLocation, ISheetAutoFillHook } from '@univerjs/sheets-ui';
import { getDataValidationDiffMutations } from '../commands/commands/data-validation.command';
@@ -48,6 +48,8 @@ export class DataValidationAutoFillController extends Disposable {
col: vSourceRange.startColumn,
};
const repeats = getAutoFillRepeatRange(vSourceRange, vTargetRange);
+ const additionMatrix = new ObjectMatrix();
+ const additionRules = new Set<string>();
repeats.forEach((repeat) => {
const targetStartCell = repeat.repeatStartCell;
const relativeRange = repeat.relativeRange;
@@ -87,11 +89,13 @@ export class DataValidationAutoFillController extends Disposable {
);
const { row: targetRow, col: targetCol } = mapFunc(targetPositionRange.startRow, targetPositionRange.startColumn);
- ruleMatrixCopy.setValue(targetRow, targetCol, ruleId);
+ additionMatrix.setValue(targetRow, targetCol, ruleId);
+ additionRules.add(ruleId);
}
});
});
-
+ const additions = Array.from(additionRules).map((id) => ({ id, ranges: queryObjectMatrix(additionMatrix, (value) => value === id) }));
+ ruleMatrixCopy.addRangeRules(additions);
const diffs = ruleMatrixCopy.diff(this._dataValidationModel.getRules(unitId, subUnitId));
const { redoMutations, undoMutations } = getDataValidationDiffMutations(unitId, subUnitId, diffs, this._injector, 'patched', applyType === APPLY_TYPE.ONLY_FORMAT);
return {
diff --git a/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts b/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts
index a7191b0a37..fffe3337ec 100644
--- a/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-copy-paste.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { Disposable, Inject, Injector, LifecycleStages, ObjectMatrix, OnLifecycle, Rectangle } from '@univerjs/core';
+import { Disposable, Inject, Injector, LifecycleStages, ObjectMatrix, OnLifecycle, queryObjectMatrix, Rectangle } from '@univerjs/core';
import { COPY_TYPE, getRepeatRange, ISheetClipboardService, PREDEFINED_HOOK_NAME, rangeToDiscreteRange, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
import type { IRange, ISheetDataValidationRule, Nullable } from '@univerjs/core';
import type { IDiscreteRange } from '@univerjs/sheets-ui';
@@ -139,7 +139,7 @@ export class DataValidationCopyPasteController extends Disposable {
}
const { row: startRow, col: startColumn } = mapFunc(range.startRow, range.startColumn);
- ruleMatrix.setValue(startRow, startColumn, transformedRuleId);
+ // ruleMatrix.setValue(startRow, startColumn, transformedRuleId);
});
});
@@ -157,6 +157,8 @@ export class DataValidationCopyPasteController extends Disposable {
};
} else {
const ruleMatrix = this._sheetDataValidationModel.getRuleObjectMatrix(unitId, subUnitId).clone();
+ const additionMatrix = new ObjectMatrix();
+ const additionRules = new Set<string>();
const { ranges: [vCopyRange, vPastedRange], mapFunc } = virtualizeDiscreteRanges([copyInfo.copyRange, pastedRange]);
@@ -174,10 +176,13 @@ export class DataValidationCopyPasteController extends Disposable {
startRange
);
const { row: startRow, col: startColumn } = mapFunc(range.startRow, range.startColumn);
- ruleMatrix.setValue(startRow, startColumn, ruleId);
+ additionMatrix.setValue(startRow, startColumn, ruleId);
+ additionRules.add(ruleId);
});
});
+ const additions = Array.from(additionRules).map((id) => ({ id, ranges: queryObjectMatrix(additionMatrix, (value) => value === id) }));
+ ruleMatrix.addRangeRules(additions);
const { redoMutations, undoMutations } = getDataValidationDiffMutations(
unitId,
subUnitId,
diff --git a/packages/sheets-data-validation/src/models/rule-matrix.ts b/packages/sheets-data-validation/src/models/rule-matrix.ts
index 7766df6e4a..2814e76b8f 100644
--- a/packages/sheets-data-validation/src/models/rule-matrix.ts
+++ b/packages/sheets-data-validation/src/models/rule-matrix.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
+import { Range, Rectangle, Tools } from '@univerjs/core';
import type { IRange, ISheetDataValidationRule, Worksheet } from '@univerjs/core';
-import { ObjectMatrix, queryObjectMatrix, Range, Rectangle } from '@univerjs/core';
export type RangeMutation = {
type: 'update';
@@ -32,77 +32,67 @@ export type RangeMutation = {
};
export class RuleMatrix {
- readonly value: ObjectMatrix<string>;
+ private _map = new Map<string, IRange[]>();
constructor(
- value: ObjectMatrix<string>,
+ value: Map<string, IRange[]>,
private _worksheet: Worksheet
) {
- this.value = value;
+ this._map = value;
}
addRule(rule: ISheetDataValidationRule) {
const ruleId = rule.uid;
- rule.ranges.forEach((range) => {
- Range.foreach(
- Range.transformRange(range, this._worksheet),
- (row, col) => {
- this.value.setValue(row, col, ruleId);
- }
- );
+ const ranges = rule.ranges.map((range) => Range.transformRange(range, this._worksheet));
+
+ this._map.forEach((value, key) => {
+ const newRanges = Rectangle.subtractMulti(value, ranges);
+ if (newRanges.length === 0) {
+ this._map.delete(key);
+ } else {
+ this._map.set(key, newRanges);
+ }
});
+
+ this._map.set(ruleId, ranges);
}
- removeRange(ranges: IRange[]) {
- ranges.forEach((range) => {
- Range.foreach(Range.transformRange(range, this._worksheet), (row, col) => {
- this.value.realDeleteValue(row, col);
- });
+ removeRange(_ranges: IRange[]) {
+ const ranges = _ranges.map((range) => Range.transformRange(range, this._worksheet));
+ this._map.forEach((value, key) => {
+ const newRanges = Rectangle.subtractMulti(value, ranges);
+ if (newRanges.length === 0) {
+ this._map.delete(key);
+ } else {
+ this._map.set(key, newRanges);
+ }
});
}
removeRule(rule: ISheetDataValidationRule) {
- rule.ranges.forEach((range) => {
- Range.foreach(Range.transformRange(range, this._worksheet), (row, col) => {
- this.value.setValue(row, col, '');
- });
- });
+ this._map.delete(rule.uid);
}
updateRange(ruleId: string, _oldRanges: IRange[], _newRanges: IRange[]) {
- const tempRuleId = `${ruleId}$`;
- const oldRanges = _oldRanges.map((range) => Range.transformRange(range, this._worksheet));
- const newRanges = _newRanges.map((range) => Range.transformRange(range, this._worksheet));
-
- oldRanges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- if (this.value.getValue(row, col) === ruleId) {
- this.value.setValue(row, col, tempRuleId);
- }
- });
- });
-
- newRanges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- this.value.setValue(row, col, ruleId);
- });
+ this._map.delete(ruleId);
+ const ranges = _newRanges.map((range) => Range.transformRange(range, this._worksheet));
+ this._map.forEach((value, key) => {
+ const newRanges = Rectangle.subtractMulti(value, ranges);
+ if (newRanges.length === 0) {
+ this._map.delete(key);
+ } else {
+ this._map.set(key, newRanges);
+ }
});
- oldRanges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- const value = this.value.getValue(row, col);
- if (value === tempRuleId) {
- this.value.realDeleteValue(row, col);
- }
- });
- });
+ this._map.set(ruleId, _newRanges);
}
diff(rules: ISheetDataValidationRule[]) {
const mutations: RangeMutation[] = [];
let deleteIndex = 0;
rules.forEach((rule, index) => {
- const newRanges = queryObjectMatrix(this.value, (ruleId) => ruleId === rule.uid);
+ const newRanges = this._map.get(rule.uid) ?? [];
const oldRanges = rule.ranges;
if (newRanges.length !== oldRanges.length || newRanges.some((range, i) => !Rectangle.equals(range, oldRanges[i]))) {
@@ -131,7 +121,7 @@ export class RuleMatrix {
const mutations: RangeMutation[] = [];
let deleteIndex = 0;
rules.forEach((rule, index) => {
- const newRanges = queryObjectMatrix(this.value, (ruleId) => ruleId === rule.uid);
+ const newRanges = this._map.get(rule.uid) ?? [];
const oldRanges = rule.ranges;
if (newRanges.length !== oldRanges.length || newRanges.some((range, i) => !Rectangle.equals(range, oldRanges[i]))) {
@@ -154,7 +144,7 @@ export class RuleMatrix {
});
Array.from(additionRules).forEach((rule) => {
- const newRanges = queryObjectMatrix(this.value, (ruleId) => ruleId === rule.uid);
+ const newRanges = this._map.get(rule.uid) ?? [];
mutations.push({
type: 'add',
rule: {
@@ -168,14 +158,45 @@ export class RuleMatrix {
}
clone() {
- return new RuleMatrix(new ObjectMatrix(this.value.clone()), this._worksheet);
+ return new RuleMatrix(new Map(Tools.deepClone(Array.from(this._map.entries()))), this._worksheet);
}
getValue(row: number, col: number) {
- return this.value.getValue(row, col);
+ const keys = Array.from(this._map.keys());
+ for (const id of keys) {
+ const ranges = this._map.get(id) ?? [];
+ if (ranges.find((range) => range.startRow <= row && range.endRow >= row && range.startColumn <= col && range.endColumn >= col)) {
+ return id;
+ }
+ }
}
- setValue(row: number, col: number, value: string) {
- return this.value.setValue(row, col, value);
+ addRangeRules(rules: { id: string;ranges: IRange[] }[]) {
+ rules.forEach(({ id: ruleId, ranges }) => {
+ if (!ranges.length) {
+ return;
+ }
+
+ let current = this._map.get(ruleId);
+ if (!current) {
+ current = ranges;
+ this._map.set(ruleId, current);
+ } else {
+ this._map.set(ruleId, Rectangle.mergeRanges([...current, ...ranges]));
+ current = this._map.get(ruleId)!;
+ }
+
+ this._map.forEach((value, key) => {
+ if (key === ruleId) {
+ return;
+ }
+ const newRanges = Rectangle.subtractMulti(value, ranges);
+ if (newRanges.length === 0) {
+ this._map.delete(key);
+ } else {
+ this._map.set(key, newRanges);
+ }
+ });
+ });
}
}
diff --git a/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts b/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts
index 203712991d..a046096b53 100644
--- a/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts
+++ b/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { DataValidationStatus, DataValidationType, Disposable, Inject, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, UniverInstanceType } from '@univerjs/core';
+import { DataValidationStatus, DataValidationType, Disposable, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';
import { DataValidationModel, DataValidatorRegistryService, UpdateRuleType } from '@univerjs/data-validation';
import { isReferenceString } from '@univerjs/engine-formula';
import { Subject } from 'rxjs';
@@ -104,7 +104,7 @@ export class SheetDataValidationModel extends Disposable {
}
let matrix = unitMap.get(subUnitId);
if (!matrix) {
- matrix = new RuleMatrix(new ObjectMatrix(), worksheet);
+ matrix = new RuleMatrix(new Map(), worksheet);
unitMap.set(subUnitId, matrix);
}