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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
refactor(sheet): object array remove (#792)
Univerd5c17f6fc52f
diff --git a/packages/core/src/shared/__test__/object-matrix.spec.ts b/packages/core/src/shared/__test__/object-matrix.spec.tsindex e30971d6bd..85cd9ee4a8 100644--- a/packages/core/src/shared/__test__/object-matrix.spec.ts+++ b/packages/core/src/shared/__test__/object-matrix.spec.ts@@ -30,8 +30,8 @@ describe('test ObjectMatrix', () => {expect(matrix.getSizeOf()).toBe(2);matrix.realDeleteValue(1, 2);matrix.realDeleteValue(1, 3);- expect(matrix.getValue(1, 2)).toBe(null);- expect(matrix.getValue(1, 3)).toBe(null);+ expect(matrix.getValue(1, 2)).toBe(undefined);+ expect(matrix.getValue(1, 3)).toBe(undefined);expect(matrix.getRow(1)).toBe(undefined);expect(matrix.getSizeOf()).toBe(1);});diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.tsindex b5926defec..a32330e7f4 100644--- a/packages/core/src/shared/index.ts+++ b/packages/core/src/shared/index.ts@@ -28,7 +28,6 @@ export * from './hash-algorithm';export * from './lifecycle';export * from './locale';export * from './lru/index';-export * from './object-array';export * from './object-matrix';export * from './permission';export * from './rectangle';diff --git a/packages/core/src/shared/object-array.ts b/packages/core/src/shared/object-array.tsdeleted file mode 100644index c7903c4318..0000000000--- a/packages/core/src/shared/object-array.ts+++ /dev/null@@ -1,635 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { IKeyValue, Nullable } from './types';--/**- * Predicate Function type- */-export type PredicateFunction<T> = (index: number, value: T) => Nullable<boolean>;--/**- * Function type- */-export type Function<T, S> = (value: Nullable<T>) => S;--/**- * Unary Operator Function type- */-export type UnaryOperatorFunction<T> = (value: T) => T;--/**- * Object Array Primitive Type- */-export interface ObjectArrayPrimitiveType<T> {- [key: number]: T;- length?: number;-}--/**- * Object Array Type- * @deprecated- */-export type ObjectArrayType<T> = ObjectArray<T> | ObjectArrayPrimitiveType<T>;--const define = <T>(value?: T): value is T => value !== undefined && value !== null;--const likeArr = (value: object): number => {- const keys: string[] = Object.keys(value);- const regexp = /^\d+$/;- let maxKey = 0;- for (let i = 0; i < keys.length; i++) {- const key = keys[i];- if (!regexp.test(key)) {- return -1;- }- const seq = parseInt(key) + 1;- if (seq > maxKey) {- maxKey = seq;- }- }- return maxKey;-};--/**- * Arrays in object form and provide an array-like API- * @beta- */-export class ObjectArray<T> {- private _objectArray!: ObjectArrayPrimitiveType<T>;-- private _length: number = 0;-- // FIXME: fix constructor function overload- constructor();-- constructor(array: ObjectArrayPrimitiveType<T>);-- constructor(size: number);-- constructor(array: ObjectArrayPrimitiveType<T>, size: number);-- constructor(...argument: any) {- switch (argument.length) {- case 0: {- this._objectArray = {};- this._length = 0;- return;- }- case 1: {- if (typeof argument[0] === 'number') {- this._objectArray = {};- this._length = argument[0];- return;- }- const length = likeArr(argument[0]);- if (length > -1) {- this._objectArray = argument[0];- this._length = length;- return;- }- throw new Error(`create object array error ${argument[0]}`);- }- case 2: {- if (likeArr(argument[0]) > -1) {- this._objectArray = argument[0];- this._length = argument[1];- return;- }- throw new Error(`create object array error ${JSON.stringify(argument[0])}`);- }- }- }-- static objectKeys<T>(array: Nullable<ObjectArrayPrimitiveType<T>>) {- if (array) {- const keys = Object.keys(array);- const index = keys.indexOf('length');- if (index > -1) {- keys.splice(index, 1);- }- return keys;- }- return [];- }-- static getMaxLength<T>(array: Nullable<ObjectArrayPrimitiveType<T>>) {- if (array) {- if (array.length) {- return array.length;- }- const keys: unknown[] = ObjectArray.objectKeys(array);- if (keys.length) {- return Math.max(...(keys as number[])) + 1;- }- }- return 0;- }-- obtain(index: number, defaultValue: T): T {- return this._objectArray[index] ?? defaultValue;- }-- getKeys(): string[] {- return ObjectArray.objectKeys(this._objectArray);- }-- get(index: number): Nullable<T> {- return this._objectArray[index];- }-- set(index: number, value: T): void {- if (index < 0) {- throw new Error(`[ObjectArray]: index ${index} is invalid!`);- }- // Accept NULL, for cell clear all- // if (define(value)) {- const length = this._length;- this._objectArray[index] = value;-- if (index >= length) {- this._length = index + 1;- }- // }- }-- pop(): Nullable<T> {- const length = this._length;- const array = this._objectArray;- if (length > 0) {- const lastIndex = length - 1;- const lastValue = array[lastIndex];- if (lastIndex > 0) {- delete array[lastIndex];- this._length--;- }- return lastValue;- }- return null;- }-- push(value: T): void {- if (define(value)) {- let length = this._length;- const array = this._objectArray;- array[length++] = value;- this._length = length;- }- }-- first(): Nullable<T> {- return this._objectArray[0];- }-- last(): Nullable<T> {- const length = this._length - 1;- return this._objectArray[length];- }-- shift(): Nullable<T> {- const length = this._length;- if (length > 0) {- const first = this._objectArray[0];- const sizeOf = length - 1;- let next: T;- for (let i = 0; i < sizeOf; i++) {- next = this._objectArray[i + 1];- if (define(next)) {- this._objectArray[i] = next;- }- }- this._length--;- delete this._objectArray[sizeOf];- return first;- }- return null;- }-- unshift(topValue: T): void {- if (define(topValue)) {- const length = this._length;- const array = this._objectArray;- const sizeOf = length + 1;- let last = array[0];- for (let i = 1; i < sizeOf; i++) {- const temp = this._objectArray[i];- if (define(last)) {- array[i] = last;- }- last = temp;- }- array[0] = topValue;- this._length = sizeOf;- }- }-- clear(): void {- this._objectArray = {};- this._length = 0;- }-- getLength(): number {- return this._length;- }-- getSizeOf(): number {- const array = this._objectArray;- const keys = Object.keys(array);- return keys.length;- }-- toJSON(): ObjectArrayPrimitiveType<T> {- return this._objectArray;- }-- toArray(): T[] {- const native = new Array<T>();- const array = this._objectArray;- const keys = Object.keys(array);- const length = keys.length;- for (let i = 0; i < length; i++) {- const key = +keys[i];- native[key] = array[key];- }- return native;- }-- forEach(callback: PredicateFunction<T>): ObjectArray<T> {- const array = this._objectArray;- const keys = Object.keys(array);- const length = keys.length;- for (let i = 0; i < length; i++) {- const key = +keys[i];- const result = callback(key, array[key]);- if (result === false) {- return this;- }- }- return this;- }-- clone(callback: Nullable<UnaryOperatorFunction<T>>): ObjectArray<T> {- const instance = new ObjectArray<T>();- if (callback) {- this.forEach((idx, val) => {- instance.set(idx, callback(val));- });- } else {- this.forEach((idx, val) => {- instance.set(idx, val);- });- }- return instance;- }-- isEmpty(): boolean {- const array = this._objectArray;- const keys = Object.keys(array);- return keys.length === 0;- }-- /**- * @deprecated use `realDelete` or `splice`- * @param index- */- delete(index: number): void {- this.splice(index, 1);- }-- realDelete(index: number): void {- const length = this._length;- if (length > 0) {- const end = index + 1;- const array = this._objectArray;- let effective = 0;- const splice: ObjectArrayPrimitiveType<T> = {};- for (let i = index; i < end; i++) {- const item = array[i];- if (define(item)) {- delete array[i];- splice[effective] = item;- effective++;- }- }- }- }-- includes(target: T): boolean {- const array = this._objectArray;- const keys = Object.keys(array);- const length = keys.length;- for (let i = 0; i < length; i++) {- const key = +keys[i];- const value = array[key];- if (value === target) {- return true;- }- }- return false;- }-- slice(start: number, end: number): ObjectArray<T> {- const array = this._objectArray;- const length = this._length;- if (length > 0) {- const fragment: IKeyValue = {};- let effective = 0;- for (let i = start; i < end; i++) {- const item = array[i];- if (define(item)) {- fragment[effective] = array[i];- effective++;- }- }- return new ObjectArray(fragment, effective);- }- return new ObjectArray<T>();- }-- concat(target: ObjectArray<T>): ObjectArray<T> {- const srcArray = this._objectArray;- const srcKeys = Object.keys(srcArray) as unknown as number[];- const srcLength = srcKeys.length;-- const targetArray = target._objectArray;- const targetKeys = Object.keys(targetArray) as unknown as number[];- const targetLength = targetKeys.length;-- const container = new ObjectArray<T>(srcLength + targetLength);- const containerArray = container._objectArray;- let master = 0;-- for (let i = 0; i < srcLength; i++, master++) {- const key = srcKeys[i];- containerArray[master] = srcArray[key];- }- for (let i = 0; i < targetLength; i++, master++) {- const key = targetKeys[i];- containerArray[master] = targetArray[key];- }-- return container;- }-- find(callback: PredicateFunction<T>): Nullable<T> {- const array = this._objectArray;- const keys = Object.keys(array);- const length = keys.length;- for (let i = 0; i < length; i++) {- const key = +keys[i];- const value = array[key];- const result = callback(key, value);- if (result === true) {- return value;- }- }- return null;- }-- splice(start: number, count: number): ObjectArray<T> {- const length = this._length;- if (length > 0) {- const end = start + count;- const array = this._objectArray;- let effective = 0;- const splice: ObjectArrayPrimitiveType<T> = {};- for (let i = start; i < end; i++) {- const item = array[i];- if (define(item)) {- delete array[i];- splice[effective] = item;- effective++;- }- }-- const diff = end - start;- const last = length;- this._length -= diff;-- if (this._length <= 0) {- this._objectArray = {};- this._length = 0;- } else {- for (let i = end; i < last; i++) {- const item = array[i];- if (define(item)) {- array[i - diff] = array[i];- delete array[i];- }- }- }- return new ObjectArray(splice, effective);- }- return new ObjectArray<T>();- }-- findIndex(callback: PredicateFunction<T>): number {- const array = this._objectArray;- const keys = Object.keys(array);- const length = keys.length;- for (let i = 0; i < length; i++) {- const key = +keys[i];- const result = callback(key, array[key]);- if (result === true) {- return i;- }- }- return -1;- }-- map<S>(callback: Function<T, S>): ObjectArray<S> {- const array = this._objectArray;- const keys = Object.keys(array);- const length = keys.length;- const result: ObjectArrayPrimitiveType<S> = {};- for (let i = 0; i < length; i++) {- const key = +keys[i];- const value = array[key];- result[i] = callback(value);- }- return new ObjectArray<S>(result);- }-- filter(callback: PredicateFunction<T>): ObjectArray<T> {- const array = this._objectArray;- const keys = Object.keys(array);- const length = keys.length;- const filter: ObjectArrayPrimitiveType<T> = {};- let master = 0;- for (let i = 0; i < length; i++) {- const key = +keys[i];- const value = array[key];- if (callback(key, value)) {- filter[master] = value;- master++;- }- }- return new ObjectArray(filter, master);- }-- // TODO: insert should support adding multi items at the same time for it- // could improve performance- insert(index: number, value: T): this {- const length = this._length;- const array = this._objectArray;-- // move all items after index in backward order- for (let i = length - 1; i >= index; i--) {- array[i + 1] = array[i];- }-- array[index] = value;- this._length = length + 1;- return this;- }-- /**- * Move some items some to another position- * @param fromIndex index to move from, fromIndex is not necessary lesser than toIndex- * @param count numbers of items to move- * @param toIndex index moving to- * @returns this- */- move(fromIndex: number, count: number, toIndex: number): this {- const moveBackward = fromIndex > toIndex;- if (!moveBackward && fromIndex + count > toIndex) {- throw new Error('Invalid move operation');- }-- if (moveBackward) {- this._moveBackward(fromIndex, count, toIndex);- } else {- this._moveForward(fromIndex, count, toIndex);- }-- return this;- }-- private _moveBackward(fromIndex: number, count: number, toIndex: number): void {- const array = this._objectArray;-- // cache item should be removed- const toMove: T[] = [];- for (let i = fromIndex; i < fromIndex + count; i++) {- toMove.push(array[i]);- }-- // move all items after toIndex in backward order- for (let i = fromIndex - 1; i >= toIndex; i--) {- const item = array[i];- array[i + count] = item;-- // Prevent undefined, otherwise the forValue loop will report an error- if (item == null) {- delete array[i + count];- }- }-- // insert cached items to toIndex- toMove.forEach((item, index) => {- array[toIndex + index] = item;- });- }-- private _moveForward(fromIndex: number, count: number, toIndex: number): void {- const array = this._objectArray;-- // cache item should be removed- const toMove: T[] = [];- for (let i = fromIndex; i < fromIndex + count; i++) {- toMove.push(array[i]);- }-- // move all items after toIndex in forward order- for (let i = fromIndex + count; i < toIndex; i++) {- const item = array[i];- array[i - count] = item;-- // Prevent undefined, otherwise the forValue loop will report an error- if (item == null) {- delete array[i - count];- }- }-- // insert cached items to toIndex- toMove.forEach((item, index) => {- array[toIndex + index - count] = item;- });- }-- inserts(index: number, target: ObjectArray<T>): ObjectArray<T> {- const targetArray = target._objectArray;- const targetLength = target._length;-- const srcArray = this._objectArray;- const srcLength = this._length;-- const lastIndex = srcLength - 1;- for (let i = lastIndex; i >= index; i--) {- const item = srcArray[i];- if (define(item)) {- delete srcArray[i];- srcArray[i + targetLength] = item;- }- }- for (let i = 0; i < targetLength; i++) {- const item = targetArray[i];- if (define(item)) {- srcArray[i + index] = targetArray[i];- }- }- this._length += targetLength;- return this;- }-- [Symbol.iterator](): IterableIterator<T> {- return new ObjectArrayIterableIterator<T>(this);- }-}--/**- * Iterator with ObjectArray- */-export class ObjectArrayIterableIterator<T> implements IterableIterator<T> {- private _array: ObjectArray<T>;-- private _keys: string[];-- private _cursor: number;-- constructor(objectArray: ObjectArray<T>) {- this._array = objectArray;- this._keys = objectArray.getKeys();- this._cursor = 0;- }-- next(): IteratorResult<T, null> {- const array = this._array;- const keys = this._keys;- const cursor = this._cursor;- if (cursor < keys.length) {- const key = keys[cursor];- const value = array.get(+key);- this._cursor++;- return { value: value as T, done: false };- }- return { value: null, done: true };- }-- [Symbol.iterator](): IterableIterator<T> {- return new ObjectArrayIterableIterator(this._array);- }-}diff --git a/packages/core/src/shared/object-matrix.ts b/packages/core/src/shared/object-matrix.tsindex 0c36cd6db8..a94678ec15 100644--- a/packages/core/src/shared/object-matrix.ts+++ b/packages/core/src/shared/object-matrix.ts@@ -15,8 +15,6 @@*/import type { IRange } from '../types/interfaces/i-range';-import type { ObjectArrayPrimitiveType, PredicateFunction } from './object-array';-import { ObjectArray } from './object-array';import { Tools } from './tools';import type { Nullable } from './types';@@ -24,7 +22,166 @@ import type { Nullable } from './types';* Object Matrix Primitive Type*/export interface IObjectMatrixPrimitiveType<T> {- [key: number]: { [key: number]: T };+ [key: number]: IObjectArrayPrimitiveType<T>;+}++export interface IObjectArrayPrimitiveType<T> {+ [key: number]: T;+}++export function getArrayLength<T>(o: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T>) {+ let maxIndex = 0;+ const keys = Object.keys(o);+ for (const key of keys) {+ const rowIndex = Number(key);+ maxIndex = Math.max(maxIndex, rowIndex);+ }+ return maxIndex + 1;+}++export function insertMatrixArray<T>(+ index: number,+ value: T,+ o: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T>+) {+ const length = getArrayLength(o);+ const array = o;++ // move all items after index in backward order+ for (let i = length - 1; i >= index; i--) {+ array[i + 1] = array[i];+ }++ array[index] = value;+}++export function concatMatrixArray<T>(+ source: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T>,+ target: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T>+) {+ const srcArray = source;+ const srcKeys = Object.keys(srcArray) as unknown as number[];+ const srcLength = srcKeys.length;++ const targetArray = target;+ const targetKeys = Object.keys(targetArray) as unknown as number[];+ const targetLength = targetKeys.length;++ const containerArray: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T> = {};+ let master = 0;++ for (let i = 0; i < srcLength; i++, master++) {+ const key = srcKeys[i];+ containerArray[master] = srcArray[key];+ }+ for (let i = 0; i < targetLength; i++, master++) {+ const key = targetKeys[i];+ containerArray[master] = targetArray[key];+ }++ return containerArray;+}++export function sliceMatrixArray<T>(+ start: number,+ end: number,+ matrixArray: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T>+): IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T> {+ const array = matrixArray;+ const length = getArrayLength(matrixArray);+ if (length > 0) {+ const fragment: IObjectArrayPrimitiveType<T> = {};+ let effective = 0;+ for (let i = start; i < end; i++) {+ const item = array[i];+ if (item) {+ fragment[effective] = array[i] as T;+ effective++;+ }+ }+ return fragment;+ }+ return {};+}++export function moveMatrixArray<T>(+ fromIndex: number,+ count: number,+ toIndex: number,+ o: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T>+) {+ const moveBackward = fromIndex > toIndex;+ if (!moveBackward && fromIndex + count > toIndex) {+ throw new Error('Invalid move operation');+ }++ if (moveBackward) {+ _moveBackward(fromIndex, count, toIndex, o);+ } else {+ _moveForward(fromIndex, count, toIndex, o);+ }+}++function _moveBackward<T>(+ fromIndex: number,+ count: number,+ toIndex: number,+ o: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T>+): void {+ const array = o;++ // cache item should be removed+ const toMove: Array<T | IObjectArrayPrimitiveType<T>> = [];+ for (let i = fromIndex; i < fromIndex + count; i++) {+ toMove.push(array[i]);+ }++ // move all items after toIndex in backward order+ for (let i = fromIndex - 1; i >= toIndex; i--) {+ const item = array[i];+ array[i + count] = item;++ // Prevent undefined, otherwise the forValue loop will report an error+ if (item == null) {+ delete array[i + count];+ }+ }++ // insert cached items to toIndex+ toMove.forEach((item, index) => {+ array[toIndex + index] = item;+ });+}++function _moveForward<T>(+ fromIndex: number,+ count: number,+ toIndex: number,+ o: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T>+): void {+ const array = o;++ // cache item should be removed+ const toMove: Array<T | IObjectArrayPrimitiveType<T>> = [];+ for (let i = fromIndex; i < fromIndex + count; i++) {+ toMove.push(array[i]);+ }++ // move all items after toIndex in forward order+ for (let i = fromIndex + count; i < toIndex; i++) {+ const item = array[i];+ array[i - count] = item;++ // Prevent undefined, otherwise the forValue loop will report an error+ if (item == null) {+ delete array[i - count];+ }+ }++ // insert cached items to toIndex+ toMove.forEach((item, index) => {+ array[toIndex + index - count] = item;+ });}// TODO: this is not a good name@@ -35,8 +192,6 @@ export interface IObjectMatrixPrimitiveType<T> {* @beta*/export class ObjectMatrix<T> {- private _option!: ObjectArray<ObjectArrayPrimitiveType<T>>;-private _matrix!: IObjectMatrixPrimitiveType<T>;constructor(matrix: IObjectMatrixPrimitiveType<T> = {}) {@@ -53,74 +208,81 @@ export class ObjectMatrix<T> {return this._matrix;}- forEach(callback: PredicateFunction<ObjectArray<T>>): ObjectMatrix<T> {- const keys = this._option.getKeys();- for (let i = 0; i < keys.length; i++) {- const key = +keys[i];- const value = this.getRow(key) as ObjectArray<T>;- const result = callback(key, value);+ forEach(callback: (row: number, objectArray: IObjectArrayPrimitiveType<T>) => Nullable<boolean>): ObjectMatrix<T> {+ const matrix = this._matrix;+ const matrixRow = Object.keys(matrix);+ for (const row of matrixRow) {+ const rowNumber = Number(row);+ const columns = matrix[rowNumber];+ const result = callback(rowNumber, columns);if (result === false) {return this;}}+return this;}- forRow(callback: (row: number, cols: number[]) => Nullable<boolean>): void {- const keys = this._option.getKeys();- for (let i = 0; i < keys.length; i++) {- const key = +keys[i];- const value = this.getRow(key) as ObjectArray<T>;+ forRow(callback: (row: number, cols: number[]) => Nullable<boolean>): ObjectMatrix<T> {+ const matrix = this._matrix;+ const matrixRow = Object.keys(matrix);+ for (const row of matrixRow) {+ const rowNumber = Number(row);+ const columns = matrix[rowNumber];const result = callback(- key,- value.getKeys().map((item) => +item)+ rowNumber,+ Object.keys(columns).map((col) => {+ return Number(col);+ }));if (result === false) {- return;+ return this;}}+ return this;}forValue(callback: (row: number, col: number, value: T) => Nullable<boolean>): ObjectMatrix<T> {- const keys = this._option.getKeys();- for (let i = 0; i < keys.length; i++) {- const rowNumber = +keys[i];- const colArray = this.getRow(rowNumber) as ObjectArray<T>;- const colKeys = colArray.getKeys();- const colLength = colKeys.length;- for (let j = 0; j < colLength; j++) {- const colNumber = +colKeys[j];- const value = colArray.get(colNumber) as T;+ const matrix = this._matrix;+ const matrixRow = Object.keys(matrix);+ for (const row of matrixRow) {+ const rowNumber = Number(row);+ const columns = matrix[rowNumber];+ const columnKeys = Object.keys(columns);+ for (const column of columnKeys) {+ const colNumber = Number(column);+ const value = columns[Number(column)];+const result = callback(rowNumber, colNumber, value);if (result === false) {return this;}}}+return this;}swapRow(src: number, target: number): void {- const srcRow = this._option.get(src);- const targetRow = this._option.get(target);- this._option.set(target, srcRow as ObjectArrayPrimitiveType<T>);- this._option.set(src, targetRow as ObjectArrayPrimitiveType<T>);+ const srcRow = this._matrix[src];+ const targetRow = this._matrix[target];++ this._matrix[src] = targetRow;++ this._matrix[target] = srcRow;}- getRow(rowIndex: number): Nullable<ObjectArray<T>> {- const element = this._option.get(rowIndex);- if (element) {- return new ObjectArray(element);- }+ getRow(rowIndex: number): Nullable<IObjectArrayPrimitiveType<T>> {+ return this._matrix[rowIndex];}- getRowOrCreate(rowIndex: number): ObjectArray<T> {- const row = this.getRow(rowIndex);+ getRowOrCreate(rowIndex: number): IObjectArrayPrimitiveType<T> {+ let row = this.getRow(rowIndex);if (row == null) {- const row = {};- this._option.set(rowIndex, row as ObjectArrayPrimitiveType<T>);- return new ObjectArray(row);+ row = {};+ this._matrix[rowIndex] = row;}+return row;}@@ -129,26 +291,30 @@ export class ObjectMatrix<T> {}hasValue() {- const matrix = this._option;- for (const row of matrix) {- if (!new ObjectArray(row).isEmpty()) {+ const matrix = this._matrix;+ const matrixRow = Object.keys(matrix);+ if (matrixRow.length === 0) {+ return false;+ }+ for (const row of matrixRow) {+ const rowNumber = Number(row);+ const columns = matrix[rowNumber];+ const columnKeys = Object.keys(columns);+ if (columnKeys.length > 0) {return true;}}+return false;}- getValue(row: number, column: number): Nullable<T> {- const objectArray = this.getRow(row);- if (objectArray) {- return objectArray.get(column);- }- return null;+ getValue(row: number, column: number): T {+ return this._matrix?.[row]?.[column];}- setValue(row: number, column: number, value: Nullable<T>): void {+ setValue(row: number, column: number, value: T): void {const objectArray = this.getRowOrCreate(row);- objectArray.set(column, value as T);+ objectArray[column] = value;}/**@@ -157,106 +323,36 @@ export class ObjectMatrix<T> {* @deprecated use `realDelete` or `splice`*/deleteValue(row: number, column: number): void {- const objectArray = this.getRow(row);- if (objectArray) {- objectArray.delete(column);- }+ delete this._matrix?.[row]?.[column];}realDeleteValue(row: number, column: number): void {- const objectArray = this.getRow(row);- if (objectArray) {- objectArray.realDelete(column);- const size = objectArray.getSizeOf();- if (!size) {- this._option.realDelete(row);+ delete this._matrix?.[row]?.[column];++ if (this.getRow(row)) {+ const objectArray = this.getRow(row);+ if (objectArray == null) {+ return;+ }+ const keys = Object.keys(objectArray);+ if (keys.length === 0) {+ delete this._matrix?.[row];}}}- spliceRows(start: number, count: number): ObjectMatrix<T> {- const splice = this._option.splice(start, count);- return new ObjectMatrix(splice.toJSON() as IObjectMatrixPrimitiveType<T>);- }-- sliceRows(start: number, count: number): ObjectMatrix<T> {- const slice = this._option.slice(start, count);- return new ObjectMatrix(slice.toJSON() as IObjectMatrixPrimitiveType<T>);- }-- pushRow(row: ObjectArray<T>): void {- this._option.push(row.toJSON() as ObjectArrayPrimitiveType<T>);+ setRow(rowNumber: number, row: IObjectArrayPrimitiveType<T>): void {+ this._matrix[rowNumber] = row;}moveRows(start: number, count: number, target: number): void {- this._option.move(start, count, target);+ moveMatrixArray(start, count, target, this._matrix);}moveColumns(start: number, count: number, target: number): void {// loop all rows and move column one by one, because our matrix is row-first- this._option.forEach((row, value) => {- const array = new ObjectArray(value);- array.move(start, count, target);- });- }-- insertRow(rowIndex: number, row: ObjectArray<T>): void {- this._option.insert(rowIndex, row.toJSON() as ObjectArrayPrimitiveType<T>);- }-- insertRowCount(rowIndex: number, rowCount: number): void {- this._option.inserts(rowIndex, new ObjectArray(rowCount));- }-- insertRows(rowIndex: number, matrix: ObjectMatrix<T>) {- this._option.inserts(rowIndex, matrix._option);- console.dir(this._option);- }-- spliceColumns(start: number, count: number): ObjectMatrix<T> {- const columnData = new ObjectMatrix<T>();- this._option.forEach((index, value) => {- for (let i = start; i < start + count; i++) {- columnData.setValue(index, i - start, this.getValue(index, i));- }- const row = this._option.get(index);- if (row) {- new ObjectArray(row).splice(start, count);- }- });- return columnData;- }-- sliceColumns(start: number, count: number): ObjectMatrix<T> {- const columnData = new ObjectMatrix<T>();- this._option.forEach((index, value) => {- for (let i = start; i < start + count; i++) {- columnData.setValue(index, i - start, this.getValue(index, i));- }- });- return columnData;- }-- insertColumns(columnIndex: number, columnData: ObjectMatrix<T>) {- let count = 0;- columnData.forEach((key) => {- const data = columnData.getRow(key);- if (data) {- count = data.getLength();- return false;- }- });- this.forEach((index, value) => {- for (let i = columnIndex; i < columnIndex + count; i++) {- const data = columnData.getRow(index)?.get(i - columnIndex);- value.insert(i, columnData.getRow(index)?.get(i - columnIndex) as T);- }- });- }-- insertColumnCount(columnIndex: number, columnCount: number) {- this.forEach((index, value) => {- value.inserts(columnIndex, new ObjectArray<T>(columnCount));+ this.forEach((row, value) => {+ moveMatrixArray(start, count, target, value);});}@@ -272,13 +368,17 @@ export class ObjectMatrix<T> {*/getFragment(startRow: number, endRow: number, startColumn: number, endColumn: number): ObjectMatrix<T> {const objectMatrix = new ObjectMatrix<T>();+ let insertRow = 0;for (let r = startRow; r <= endRow; r++) {- const row = new ObjectArray<T>();+ const row: IObjectArrayPrimitiveType<T> = {};+ let insertColumn = 0;for (let c = startColumn; c <= endColumn; c++) {const value = this.getValue(r, c) as T;- row.push(value);+ row[insertColumn] = value;+ insertColumn++;}- objectMatrix.pushRow(row);+ objectMatrix.setRow(insertRow, row);+ insertRow++;}return objectMatrix;}@@ -308,11 +408,21 @@ export class ObjectMatrix<T> {}getSizeOf(): number {- return this._option.getSizeOf();+ const keys = Object.keys(this._matrix);+ return keys.length;+ // return this._option.getSizeOf();}getLength(): number {- return this._option.getLength();+ return getArrayLength(this._matrix);+ // let maxIndex = 0;+ // const keys = Object.keys(this._matrix);+ // for (const key of keys) {+ // const rowIndex = Number(key);+ // maxIndex = Math.max(maxIndex, rowIndex);+ // }+ // return maxIndex + 1;+ // return this._option.getLength();}getRange(): IRange {@@ -325,7 +435,7 @@ export class ObjectMatrix<T> {for (let i = 0; i < length; i++) {const row = this.getRow(i);if (row) {- const columnLength = row.getLength() - 1;+ const columnLength = getArrayLength(row) - 1;endColumn = columnLength > endColumn ? columnLength : endColumn;}}@@ -346,15 +456,36 @@ export class ObjectMatrix<T> {}toArray(): T[][] {- return this._option.toArray().map((item) => new ObjectArray(item).toArray()) as T[][];+ const array: T[][] = [];+ this.forRow((row, cols) => {+ if (array[row] == null) {+ array[row] = [];+ }++ cols.forEach((column) => {+ array[row][column] = this.getValue(row, column);+ });+ });+ return array;}+ /**+ * @deprecated Use getMatrix as a substitute.+ */toJSON(): IObjectMatrixPrimitiveType<T> {return this._matrix;}+ clone(): IObjectMatrixPrimitiveType<T> {+ const json = JSON.stringify(this._matrix);+ return JSON.parse(json);+ }++ /**+ * @deprecated Use clone as a substitute.+ */getData(): IObjectMatrixPrimitiveType<T> {- const json = JSON.stringify(this);+ const json = JSON.stringify(this._matrix);return JSON.parse(json);}@@ -365,12 +496,13 @@ export class ObjectMatrix<T> {let initRow = false;let initColumn = false;const objectMatrix = new ObjectMatrix<T>();- this.forEach((rowIndex, row) => {+ this.forEach((rowIndex, rowObject) => {if (!initRow) {initRow = true;startRow = rowIndex;}- row.forEach((columnIndex, column) => {+ Object.keys(rowObject).forEach((column) => {+ const columnIndex = Number(column);if (!initColumn) {initColumn = true;startColumn = columnIndex;@@ -399,11 +531,13 @@ export class ObjectMatrix<T> {startRow = rowIndex;}- const rowSize = row.getLength() - 1;+ const rowSize = getArrayLength(row) - 1;if (rowSize > endColumn) {endColumn = rowSize;}- row.forEach((columnIndex, column) => {++ Object.keys(row).forEach((column) => {+ const columnIndex = Number(column);if (!initColumn) {initColumn = true;startColumn = columnIndex;@@ -428,7 +562,8 @@ export class ObjectMatrix<T> {// Traverse row by rowthis.forEach((r, row) => {// Traverse column by column- row.forEach((c, cell) => {+ Object.keys(row).forEach((col) => {+ const c = Number(col);let merged = false;// Check if it can be merged with any of the existing rangesfor (const range of ranges) {@@ -472,6 +607,5 @@ export class ObjectMatrix<T> {private _setOriginValue(matrix: IObjectMatrixPrimitiveType<T> = {}) {this._matrix = matrix;- this._option = new ObjectArray<ObjectArrayPrimitiveType<T>>(matrix);}}diff --git a/packages/core/src/shared/tools.ts b/packages/core/src/shared/tools.tsindex cace85fc92..fd0818b89e 100644--- a/packages/core/src/shared/tools.ts+++ b/packages/core/src/shared/tools.ts@@ -16,8 +16,6 @@import { nanoid } from 'nanoid';-import type { ObjectArrayPrimitiveType } from './object-array';-import { ObjectArray } from './object-array';import type { Class, IKeyValue } from './types';const rmsPrefix = /^-ms-/;@@ -643,13 +641,6 @@ export class Tools {return obj;}- static createObjectArray<T>(array: ObjectArrayPrimitiveType<T> | ObjectArray<T>): ObjectArray<T> {- if (array instanceof ObjectArray) {- return new ObjectArray<T>(array.toJSON());- }- return new ObjectArray<T>(array);- }-static hasIntersectionBetweenTwoRanges(range1Start: number,range1End: number,diff --git a/packages/core/src/sheets/__tests__/styles.spec.ts b/packages/core/src/sheets/__tests__/styles.spec.tsindex 0558f99bdd..da758be9c4 100644--- a/packages/core/src/sheets/__tests__/styles.spec.ts+++ b/packages/core/src/sheets/__tests__/styles.spec.ts@@ -20,13 +20,10 @@ import { Styles } from '../styles';describe('Test Styles', () => {it('Init styles, set style', () => {- const styles = new Styles(- {- '1': { fs: 12 },- '2': { fs: 14 },- },- 2- );+ const styles = new Styles({+ '1': { fs: 12 },+ '2': { fs: 14 },+ });// get style by idlet style = styles.get('1');@@ -43,7 +40,7 @@ describe('Test Styles', () => {const styleId = styles.setValue({ fs: 16 });// search style not in cache- const searchId = styles.search({ fs: 12 });+ const searchId = styles.search({ fs: 12 }, JSON.stringify({ fs: 12 }));expect(searchId).toBe('1');// Add duplicate style, search style in cachediff --git a/packages/core/src/sheets/column-manager.ts b/packages/core/src/sheets/column-manager.tsindex 0bbd09e615..75e9a3d99b 100644--- a/packages/core/src/sheets/column-manager.ts+++ b/packages/core/src/sheets/column-manager.ts@@ -14,10 +14,9 @@* limitations under the License.*/-import type { Nullable } from '../shared';-import { Tools } from '../shared';-import type { ObjectArrayType } from '../shared/object-array';-import { ObjectArray } from '../shared/object-array';+import type { Nullable } from '../common/type-utils';+import type { IObjectArrayPrimitiveType } from '../shared/object-matrix';+import { getArrayLength } from '../shared/object-matrix';import { BooleanNumber } from '../types/enum';import type { IColumnData, IRange, IWorksheetData } from '../types/interfaces';import { RANGE_TYPE } from '../types/interfaces';@@ -26,33 +25,33 @@ import { RANGE_TYPE } from '../types/interfaces';* Manage configuration information of all columns, get column width, column length, set column width, etc.*/export class ColumnManager {- private _columnData: ObjectArray<IColumnData>;+ private _columnData: IObjectArrayPrimitiveType<Partial<IColumnData>> = {};constructor(private readonly _config: IWorksheetData,- data: ObjectArrayType<Partial<IColumnData>>+ data: IObjectArrayPrimitiveType<Partial<IColumnData>>) {- this._columnData = Tools.createObjectArray(data) as ObjectArray<IColumnData>;+ this._columnData = data;}/*** Get width and hidden status of columns in the sheet* @returns*/- getColumnData(): ObjectArray<IColumnData> {+ getColumnData(): IObjectArrayPrimitiveType<Partial<IColumnData>> {return this._columnData;}getColVisible(colPos: number): boolean {const { _columnData } = this;- const col = _columnData.get(colPos);+ const col = _columnData[colPos];if (!col) {return true;}return col.hd !== BooleanNumber.TRUE;}- getHiddenCols(start: number = 0, end: number = this._columnData.getLength() - 1): IRange[] {+ getHiddenCols(start: number = 0, end: number = getArrayLength(this._columnData) - 1): IRange[] {const hiddenCols: IRange[] = [];let inHiddenRange = false;@@ -88,11 +87,13 @@ export class ColumnManager {return hiddenCols;}- getColumnDatas(columnPos: number, numColumns: number): ObjectArray<IColumnData> {- const columnData = new ObjectArray<IColumnData>();+ getColumnDatas(columnPos: number, numColumns: number): IObjectArrayPrimitiveType<Partial<IColumnData>> {+ const columnData: IObjectArrayPrimitiveType<Partial<IColumnData>> = {};+ let index = 0;for (let i = columnPos; i < columnPos + numColumns; i++) {const data = this.getColumnOrCreate(i);- columnData.push(data);+ columnData[index] = data;+ index++;}return columnData;}@@ -102,7 +103,7 @@ export class ColumnManager {* @returns*/getSize(): number {- return this._columnData.getLength();+ return getArrayLength(this._columnData);}/**@@ -115,10 +116,10 @@ export class ColumnManager {const config = this._config;let width: number = 0;- const column = _columnData.obtain(columnPos, {+ const column = _columnData[columnPos] || {hd: BooleanNumber.FALSE,w: config.defaultColumnWidth,- });+ };width = column.w || config.defaultColumnWidth;return width;@@ -129,8 +130,8 @@ export class ColumnManager {* @param columnPos column index* @returns*/- getColumn(columnPos: number): Nullable<IColumnData> {- const column = this._columnData.get(columnPos);+ getColumn(columnPos: number): Nullable<Partial<IColumnData>> {+ const column = this._columnData[columnPos];if (column) {return column;}@@ -141,10 +142,10 @@ export class ColumnManager {* @param columnPos column index* @returns*/- getColumnOrCreate(columnPos: number): IColumnData {+ getColumnOrCreate(columnPos: number): Partial<IColumnData> {const { _columnData } = this;const config = this._config;- const column = _columnData.get(columnPos);+ const column = _columnData[columnPos];if (column) {return column;}@@ -152,7 +153,7 @@ export class ColumnManager {w: config.defaultColumnWidth,hd: BooleanNumber.FALSE,};- this._columnData.set(columnPos, create);+ this._columnData[columnPos] = create;return create;}}diff --git a/packages/core/src/sheets/range.ts b/packages/core/src/sheets/range.tsindex 2fef270df0..18ca391a65 100644--- a/packages/core/src/sheets/range.ts+++ b/packages/core/src/sheets/range.ts@@ -165,11 +165,11 @@ export class Range {** @returns range matrix*/- getMatrix(): ObjectMatrix<ICellData> {+ getMatrix(): ObjectMatrix<Nullable<ICellData>> {const { startRow, endRow, startColumn, endColumn } = this._range;const sheetMatrix = this._worksheet.getCellMatrix();- const rangeMatrix = new ObjectMatrix<ICellData>();+ const rangeMatrix = new ObjectMatrix<Nullable<ICellData>>();for (let r = startRow; r <= endRow; r++) {for (let c = startColumn; c <= endColumn; c++) {@@ -276,7 +276,7 @@ export class Range {/*** Returns the data of the object structure, and can set whether to bring styles*/- getObjectValue(options: IValueOptionsType = {}): ICellData {+ getObjectValue(options: IValueOptionsType = {}): Nullable<ICellData> {return this.getObjectValues(options)[0][0];}@@ -286,7 +286,7 @@ export class Range {* @param options set whether to include style* @returns Returns a value in object format*/- getObjectValues(options: IValueOptionsType = {}): IObjectMatrixPrimitiveType<ICellData> {+ getObjectValues(options: IValueOptionsType = {}): IObjectMatrixPrimitiveType<Nullable<ICellData>> {const { startRow, endRow, startColumn, endColumn } = this._range;// get object values from sheet matrix, or use this.getMatrix() create a new matrix then this.getMatrix().getData()@@ -297,13 +297,15 @@ export class Range {for (let r = 0; r <= endRow - startRow; r++) {for (let c = 0; c <= endColumn - startColumn; c++) {// handle null- if (!values[r][c]) continue;+ if (values == null || values?.[r]?.[c] == null) {+ continue;+ }- const s = values[r][c].s;+ const s = values[r][c]!.s;// make sure value has styleif (s) {- values[r][c].s = style.get(s);+ values[r][c]!.s = style.get(s);}}}diff --git a/packages/core/src/sheets/row-manager.ts b/packages/core/src/sheets/row-manager.tsindex 5465a2d195..00dc1c4537 100644--- a/packages/core/src/sheets/row-manager.ts+++ b/packages/core/src/sheets/row-manager.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import type { Nullable, ObjectArrayType } from '../shared';-import { ObjectArray, Tools } from '../shared';+import { getArrayLength, type IObjectArrayPrimitiveType } from '../shared/object-matrix';+import type { Nullable } from '../shared/types';import { BooleanNumber } from '../types/enum';import type { IRange, IRowData, IWorksheetData } from '../types/interfaces';import { RANGE_TYPE } from '../types/interfaces';@@ -26,28 +26,30 @@ import { RANGE_TYPE } from '../types/interfaces';* @deprecated This class is not necessary. It increases the complexity of the code and does not bring any benefits.*/export class RowManager {- private _rowData: ObjectArray<IRowData>;+ private _rowData: IObjectArrayPrimitiveType<Partial<IRowData>>;constructor(private readonly _config: IWorksheetData,- data: ObjectArrayType<Partial<IRowData>>+ data: IObjectArrayPrimitiveType<Partial<IRowData>>) {- this._rowData = Tools.createObjectArray(data) as ObjectArray<IRowData>;+ this._rowData = data;}/*** Get height and hidden status of columns in the sheet* @returns*/- getRowData(): ObjectArray<IRowData> {+ getRowData(): IObjectArrayPrimitiveType<Partial<IRowData>> {return this._rowData;}- getRowDatas(rowPos: number, numRows: number): ObjectArray<IRowData> {- const rowData = new ObjectArray<IRowData>();+ getRowDatas(rowPos: number, numRows: number): IObjectArrayPrimitiveType<Partial<IRowData>> {+ const rowData: IObjectArrayPrimitiveType<Partial<IRowData>> = {};+ let index = 0;for (let i = rowPos; i < rowPos + numRows; i++) {const data = this.getRowOrCreate(i);- rowData.push(data);+ rowData[index] = data;+ index++;}return rowData;}@@ -60,10 +62,10 @@ export class RowManager {let height: number = 0;for (let i = 0; i < count; i++) {- const row = _rowData.obtain(i + rowPos, {+ const row = _rowData[i + rowPos] || {hd: BooleanNumber.FALSE,h: config.defaultRowHeight,- });+ };const { isAutoHeight, ah, h = config.defaultRowHeight } = row;height += (isAutoHeight == null || !!isAutoHeight) && typeof ah === 'number' ? ah : h;@@ -77,9 +79,8 @@ export class RowManager {* @param rowPos row index* @returns*/- getRow(rowPos: number): Nullable<IRowData> {- const { _rowData } = this;- return _rowData.get(rowPos);+ getRow(rowPos: number): Nullable<Partial<IRowData>> {+ return this._rowData[rowPos];}/**@@ -87,20 +88,20 @@ export class RowManager {* @param rowPos row index* @returns*/- getRowOrCreate(rowPos: number): IRowData {+ getRowOrCreate(rowPos: number): Partial<IRowData> {const { _rowData } = this;- const row = _rowData.get(rowPos);+ const row = _rowData[rowPos];if (row) {return row;}const config = this._config;const create = { hd: BooleanNumber.FALSE, h: config.defaultRowHeight };- _rowData.set(rowPos, create);+ _rowData[rowPos] = create;return create;}- getHiddenRows(start: number = 0, end: number = this._rowData.getLength() - 1): IRange[] {+ getHiddenRows(start: number = 0, end: number = getArrayLength(this._rowData) - 1): IRange[] {const hiddenRows: IRange[] = [];let inHiddenRange = false;@@ -144,6 +145,6 @@ export class RowManager {* @returns*/getSize(): number {- return this._rowData.getLength();+ return getArrayLength(this._rowData);}}diff --git a/packages/core/src/sheets/styles.ts b/packages/core/src/sheets/styles.tsindex 2bd9deaf44..89467ad932 100644--- a/packages/core/src/sheets/styles.ts+++ b/packages/core/src/sheets/styles.ts@@ -15,24 +15,21 @@*/import type { IKeyType, Nullable } from '../shared';-import { Tools } from '../shared';+import { LRUMap, Tools } from '../shared';import type { ICellDataForSheetInterceptor, IStyleData } from '../types/interfaces';/*** Styles in a workbook, cells locate styles based on style IDs*- * TODO@Dushusir: Cachemap needs to follow style to clear cleared following styles*/export class Styles {private _styles: IKeyType<Nullable<IStyleData>>;- private _cacheMap = new Map<string, string>();+ private _cacheMap = new LRUMap<string, string>(100000);- private _maxCacheSize: number;-- constructor(styles: IKeyType<Nullable<IStyleData>> = {}, maxCacheSize = 100) {+ constructor(styles: IKeyType<Nullable<IStyleData>> = {}) {this._styles = styles;- this._maxCacheSize = maxCacheSize;+this._generateCacheMap();}@@ -47,20 +44,15 @@ export class Styles {return this;}- search(data: IStyleData): string {+ search(data: IStyleData, styleObject: string): string {// Take from cache- const styleObject = JSON.stringify(data);- if (this._cacheMap.has(styleObject)) {- const id = this._cacheMap.get(styleObject) as string;- // Move the accessed entry to the end of the Map to represent its recent usage- this._cacheMap.delete(styleObject);- this._cacheMap.set(styleObject, id);- return id;+ if (this._cacheMap.has(styleObject)) {+ return this._cacheMap.get(styleObject) as string;}// Check if the data exists in _styles and not in _cacheMap- const existingId = this.getExistingStyleId(data);+ const existingId = this._getExistingStyleId(data);if (existingId) {return existingId;}@@ -74,30 +66,24 @@ export class Styles {return this._styles[id];}- add(data: IStyleData): string {+ add(data: IStyleData, styleObject: string): string {const id = Tools.generateRandomId(6);this._styles[id] = data;// update cache- const styleObject = JSON.stringify(data);- this._cacheMap.set(styleObject, id);- // Check if cache size exceeds the maximum limit- if (this._cacheMap.size > this._maxCacheSize) {- // Remove the least recently used entry (the first entry in the Map)- const firstEntry = this._cacheMap.entries().next().value;- this._cacheMap.delete(firstEntry[0]);- }+ this._cacheMap.set(styleObject, id);return id;}setValue(data: Nullable<IStyleData>): Nullable<string> {if (data == null) return;- const result = this.search(data);+ const styleObject = JSON.stringify(data);+ const result = this.search(data, styleObject);if (result !== '-1') {return result;}- return this.add(data);+ return this.add(data, styleObject);}toJSON(): IKeyType<Nullable<IStyleData>> {@@ -126,18 +112,13 @@ export class Styles {private _generateCacheMap(): void {const { _styles, _cacheMap } = this;- let count = 0;for (const id in _styles) {const styleObject = JSON.stringify(_styles[id]);_cacheMap.set(styleObject, id);- count++;- if (count >= this._maxCacheSize) {- break;- }}}- private getExistingStyleId(data: IStyleData): Nullable<string> {+ private _getExistingStyleId(data: IStyleData): Nullable<string> {const { _styles } = this;for (const id in _styles) {if (Tools.diffValue(_styles[id], data)) {diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.tsindex 4852f02a73..3378999758 100644--- a/packages/core/src/sheets/worksheet.ts+++ b/packages/core/src/sheets/worksheet.ts@@ -98,7 +98,7 @@ export class Worksheet {* Returns WorkSheet Cell Data Matrix* @returns*/- getCellMatrix(): ObjectMatrix<ICellData> {+ getCellMatrix(): ObjectMatrix<Nullable<ICellData>> {return this._cellData;}diff --git a/packages/core/src/types/interfaces/i-worksheet-data.ts b/packages/core/src/types/interfaces/i-worksheet-data.tsindex 64825ebe9f..c92c10890d 100644--- a/packages/core/src/types/interfaces/i-worksheet-data.ts+++ b/packages/core/src/types/interfaces/i-worksheet-data.ts@@ -14,8 +14,7 @@* limitations under the License.*/-import type { ObjectArrayType } from '../../shared/object-array';-import type { IObjectMatrixPrimitiveType } from '../../shared/object-matrix';+import type { IObjectArrayPrimitiveType, IObjectMatrixPrimitiveType } from '../../shared/object-matrix';import type { IKeyValue } from '../../shared/types';import type { BooleanNumber, SheetTypes } from '../enum';import type { ICellData } from './i-cell-data';@@ -75,8 +74,8 @@ export interface IWorksheetData {*/status: BooleanNumber;cellData: IObjectMatrixPrimitiveType<ICellData>;- rowData: ObjectArrayType<Partial<IRowData>>; // TODO:配置文件不能为ObjectArray实例,应该是纯json配置 @jerry- columnData: ObjectArrayType<Partial<IColumnData>>;+ rowData: IObjectArrayPrimitiveType<Partial<IRowData>>; // TODO:配置文件不能为ObjectArray实例,应该是纯json配置 @jerry+ columnData: IObjectArrayPrimitiveType<Partial<IColumnData>>;showGridlines: BooleanNumber;rowHeader: {width: number;diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.tsindex 68f1364212..4e67d4f2dc 100644--- a/packages/engine-formula/src/basics/common.ts+++ b/packages/engine-formula/src/basics/common.ts@@ -61,7 +61,7 @@ export interface IUnitData {}export interface IRuntimeUnitDataType {- [unitId: string]: { [sheetId: string]: ObjectMatrix<ICellData> };+ [unitId: string]: { [sheetId: string]: ObjectMatrix<Nullable<ICellData>> };}export interface IRuntimeOtherUnitDataType {@@ -89,7 +89,7 @@ export interface IFeatureDirtyRangeType {}export interface IArrayFormulaUnitCellType {- [unitId: string]: { [sheetId: string]: IObjectMatrixPrimitiveType<ICellData> };+ [unitId: string]: { [sheetId: string]: IObjectMatrixPrimitiveType<Nullable<ICellData>> };}export interface IFormulaData {diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex bead9d7591..78d0f6cd4f 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -60,10 +60,10 @@ export class FormulaDataModel extends Disposable {return true;}- let arrayFormulaCellMatrixData = new ObjectMatrix<ICellData>(); // Original array formula cell data.+ let arrayFormulaCellMatrixData = new ObjectMatrix<Nullable<ICellData>>(); // Original array formula cell data.if (this._arrayFormulaCellData[unitId][sheetId] != null) {- arrayFormulaCellMatrixData = new ObjectMatrix<ICellData>(+ arrayFormulaCellMatrixData = new ObjectMatrix<Nullable<ICellData>>(this._arrayFormulaCellData[unitId][sheetId]);}@@ -102,14 +102,14 @@ export class FormulaDataModel extends Disposable {let arrayFormulaRangeMatrix = new ObjectMatrix<IRange>(); // Original array formula range.- let arrayFormulaCellMatrixData = new ObjectMatrix<ICellData>(); // Original array formula cell data.+ let arrayFormulaCellMatrixData = new ObjectMatrix<Nullable<ICellData>>(); // Original array formula cell data.if (this._arrayFormulaRange[unitId][sheetId] != null) {arrayFormulaRangeMatrix = new ObjectMatrix<IRange>(this._arrayFormulaRange[unitId][sheetId]);}if (this._arrayFormulaCellData[unitId][sheetId] != null) {- arrayFormulaCellMatrixData = new ObjectMatrix<ICellData>(+ arrayFormulaCellMatrixData = new ObjectMatrix<Nullable<ICellData>>(this._arrayFormulaCellData[unitId][sheetId]);}@@ -259,7 +259,7 @@ export class FormulaDataModel extends Disposable {};}- updateFormulaData(unitId: string, sheetId: string, cellValue: IObjectMatrixPrimitiveType<ICellData | null>) {+ updateFormulaData(unitId: string, sheetId: string, cellValue: IObjectMatrixPrimitiveType<Nullable<ICellData>>) {const cellMatrix = new ObjectMatrix(cellValue);const formulaIdMap = this.getFormulaIdMap(unitId, sheetId); // Connect the formula and ID@@ -300,8 +300,8 @@ export class FormulaDataModel extends Disposable {f: '',si: formulaId,});- } else if (!checkFormulaString && !checkFormulaId && sheetFormulaDataMatrix.getRow(r)?.get(c)) {- const currentFormulaInfo = sheetFormulaDataMatrix.getRow(r)?.get(c);+ } else if (!checkFormulaString && !checkFormulaId && sheetFormulaDataMatrix.getValue(r, c)) {+ const currentFormulaInfo = sheetFormulaDataMatrix.getValue(r, c);const f = currentFormulaInfo?.f || '';const si = currentFormulaInfo?.si || '';@@ -418,7 +418,7 @@ export function initSheetFormulaData(formulaData: IFormulaData,unitId: string,sheetId: string,- cellMatrix: ObjectMatrix<ICellData>+ cellMatrix: ObjectMatrix<Nullable<ICellData>>) {const formulaIdMap = new Map<string, { f: string; r: number; c: number }>(); // Connect the formula and IDconst sheetFormulaDataMatrix = new ObjectMatrix<IFormulaDataItem>();diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.tsindex 66934135fd..9565285f12 100644--- a/packages/engine-formula/src/services/runtime.service.ts+++ b/packages/engine-formula/src/services/runtime.service.ts@@ -377,7 +377,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeconst unitData = this._runtimeData[unitId];if (unitData[sheetId] == null) {- unitData[sheetId] = new ObjectMatrix<ICellData>();+ unitData[sheetId] = new ObjectMatrix<Nullable<ICellData>>();}if (this._unitArrayFormulaRange[unitId] == null) {@@ -399,7 +399,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeconst arrayFormulaCellData = this._runtimeArrayFormulaCellData[unitId];if (arrayFormulaCellData[sheetId] == null) {- arrayFormulaCellData[sheetId] = new ObjectMatrix<ICellData>();+ arrayFormulaCellData[sheetId] = new ObjectMatrix<Nullable<ICellData>>();}if (this._runtimeClearArrayFormulaCellData[unitId] === undefined) {@@ -409,7 +409,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeconst clearArrayFormulaCellData = this._runtimeClearArrayFormulaCellData[unitId];if (clearArrayFormulaCellData[sheetId] == null) {- clearArrayFormulaCellData[sheetId] = new ObjectMatrix<ICellData>();+ clearArrayFormulaCellData[sheetId] = new ObjectMatrix<Nullable<ICellData>>();}const sheetData = unitData[sheetId];diff --git a/packages/engine-render/src/components/docs/extensions/line.ts b/packages/engine-render/src/components/docs/extensions/line.tsindex 419a6e9b65..00bd8cb1c9 100644--- a/packages/engine-render/src/components/docs/extensions/line.ts+++ b/packages/engine-render/src/components/docs/extensions/line.ts@@ -19,10 +19,10 @@import type { IScale, ITextDecoration } from '@univerjs/core';import { BooleanNumber, getColorStyle, TextDecoration } from '@univerjs/core';-import { COLOR_BLACK_RGB, DEFAULT_OFFSET_SPACING } from '../../../basics/const';+import { COLOR_BLACK_RGB, DEFAULT_OFFSET_SPACING, FIX_ONE_PIXEL_BLUR_OFFSET } from '../../../basics/const';import { calculateRectRotate } from '../../../basics/draw';import type { IDocumentSkeletonSpan } from '../../../basics/i-document-skeleton-cached';-import { degToRad, getScale } from '../../../basics/tools';+import { degToRad, fixLineWidthByScale, getScale } from '../../../basics/tools';import { Vector2 } from '../../../basics/vector2';import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';import { docExtension } from '../doc-extension';@@ -61,19 +61,19 @@ export class Line extends docExtension {if (underline) {const startY = contentHeight + DEFAULT_OFFSET_SPACING - DELTA;- this._drawLine(ctx, span, underline, startY);+ this._drawLine(ctx, span, underline, startY, scale);}if (strikethrough) {const startY = strikeoutPosition - DELTA;- this._drawLine(ctx, span, strikethrough, startY);+ this._drawLine(ctx, span, strikethrough, startY, scale);}if (overline) {const startY = -DEFAULT_OFFSET_SPACING - DELTA;- this._drawLine(ctx, span, overline, startY);+ this._drawLine(ctx, span, overline, startY, scale);}}@@ -85,7 +85,8 @@ export class Line extends docExtension {ctx: CanvasRenderingContext2D,span: IDocumentSkeletonSpan,line: ITextDecoration,- startY: number+ startY: number,+ scale: number) {const { s: show, cl: colorStyle, t: lineType } = line;@@ -105,6 +106,8 @@ export class Line extends docExtension {ctx.save();+ ctx.translate(FIX_ONE_PIXEL_BLUR_OFFSET / scale, FIX_ONE_PIXEL_BLUR_OFFSET / scale);+ctx.beginPath();const color = getColorStyle(colorStyle) || COLOR_BLACK_RGB;ctx.strokeStyle = color;@@ -125,8 +128,8 @@ export class Line extends docExtension {alignOffset);- ctx.moveTo(start.x, start.y);- ctx.lineTo(end.x, end.y);+ ctx.moveTo(fixLineWidthByScale(start.x, scale), fixLineWidthByScale(start.y, scale));+ ctx.lineTo(fixLineWidthByScale(end.x, scale), fixLineWidthByScale(end.y, scale));ctx.stroke();ctx.restore();diff --git a/packages/engine-render/src/components/sheets/extensions/background.ts b/packages/engine-render/src/components/sheets/extensions/background.tsindex 178ee10014..00b9b7c3f9 100644--- a/packages/engine-render/src/components/sheets/extensions/background.ts+++ b/packages/engine-render/src/components/sheets/extensions/background.ts@@ -63,45 +63,43 @@ export class Background extends SheetExtension {// eslint-disable-next-line no-magic-numbersctx.fillStyle = rgb || getColor([255, 255, 255])!;ctx.beginPath();- backgroundCache.forEach((rowIndex, backgroundRow) => {- backgroundRow.forEach((columnIndex) => {- const cellInfo = backgroundPositions?.getValue(rowIndex, columnIndex);-- if (cellInfo == null) {- return true;- }- let { startY, endY, startX, endX } = cellInfo;- const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;- if (isMerged) {- return true;- }-- if (- !this.isRenderDiffRangesByRow(mergeInfo.startRow, diffRanges) &&- !this.isRenderDiffRangesByRow(mergeInfo.endRow, diffRanges)- ) {- return true;- }-- if (- !this.isRenderDiffRangesByColumn(mergeInfo.startColumn, diffRanges) &&- !this.isRenderDiffRangesByColumn(mergeInfo.endColumn, diffRanges)- ) {- return true;- }-- if (isMergedMainCell) {- startY = mergeInfo.startY;- endY = mergeInfo.endY;- startX = mergeInfo.startX;- endX = mergeInfo.endX;- }-- ctx.moveTo(startX, startY);- ctx.lineTo(startX, endY);- ctx.lineTo(endX, endY);- ctx.lineTo(endX, startY);- });+ backgroundCache.forValue((rowIndex, columnIndex) => {+ const cellInfo = backgroundPositions?.getValue(rowIndex, columnIndex);++ if (cellInfo == null) {+ return true;+ }+ let { startY, endY, startX, endX } = cellInfo;+ const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;+ if (isMerged) {+ return true;+ }++ if (+ !this.isRenderDiffRangesByRow(mergeInfo.startRow, diffRanges) &&+ !this.isRenderDiffRangesByRow(mergeInfo.endRow, diffRanges)+ ) {+ return true;+ }++ if (+ !this.isRenderDiffRangesByColumn(mergeInfo.startColumn, diffRanges) &&+ !this.isRenderDiffRangesByColumn(mergeInfo.endColumn, diffRanges)+ ) {+ return true;+ }++ if (isMergedMainCell) {+ startY = mergeInfo.startY;+ endY = mergeInfo.endY;+ startX = mergeInfo.startX;+ endX = mergeInfo.endX;+ }++ ctx.moveTo(startX, startY);+ ctx.lineTo(startX, endY);+ ctx.lineTo(endX, endY);+ ctx.lineTo(endX, startY);});ctx.closePath();ctx.fill();diff --git a/packages/engine-render/src/components/sheets/extensions/border-auxiliary.ts b/packages/engine-render/src/components/sheets/extensions/border-auxiliary.tsdeleted file mode 100644index b680d560e1..0000000000--- a/packages/engine-render/src/components/sheets/extensions/border-auxiliary.ts+++ /dev/null@@ -1,304 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { IRange, IScale, ISelectionCellWithCoord, ObjectMatrix } from '@univerjs/core';-import { BooleanNumber } from '@univerjs/core';--import { clearLineByBorderType, getLineWith } from '../../../basics/draw';-import { getColor } from '../../../basics/tools';-import type { BorderCacheItem } from '../interfaces';-import type { SpreadsheetSkeleton } from '../sheet-skeleton';-import { SheetExtension } from './sheet-extension';--const UNIQUE_KEY = 'DefaultBorderAuxiliaryExtension';--const BORDER_AUXILIARY_Z_INDEX = 10;-export class BorderAuxiliary extends SheetExtension {- override uKey = UNIQUE_KEY;-- override zIndex = BORDER_AUXILIARY_Z_INDEX;-- override draw(- ctx: CanvasRenderingContext2D,- parentScale: IScale,- spreadsheetSkeleton: SpreadsheetSkeleton,- diffRanges?: IRange[]- ) {- const { rowColumnSegment, dataMergeCache, overflowCache, stylesCache, showGridlines } = spreadsheetSkeleton;- const { border, backgroundPositions } = stylesCache;- const { startRow, endRow, startColumn, endColumn } = rowColumnSegment;- if (!spreadsheetSkeleton || showGridlines === BooleanNumber.FALSE) {- return;- }-- const { rowHeightAccumulation, columnTotalWidth, columnWidthAccumulation, rowTotalHeight } =- spreadsheetSkeleton;-- if (- !rowHeightAccumulation ||- !columnWidthAccumulation ||- columnTotalWidth === undefined ||- rowTotalHeight === undefined- ) {- return;- }-- ctx.save();- const scale = this._getScale(parentScale);- ctx.beginPath();- ctx.lineWidth = getLineWith(1) / scale;- // eslint-disable-next-line no-magic-numbers- ctx.strokeStyle = getColor([212, 212, 212]);-- const width = columnTotalWidth;-- let height = rowTotalHeight;-- const columnWidthAccumulationLength = columnWidthAccumulation.length;- const rowHeightAccumulationLength = rowHeightAccumulation.length;-- let rowStart = startRow;-- let rowEnd = endRow - 1;-- let columnDrawTopStart = 0;-- if (diffRanges && diffRanges.length > 0) {- const diffRange = diffRanges[0];-- const { startRow: diffRangeStartRow, endRow: diffRangeEndRow } = diffRange;-- rowStart = diffRangeStartRow;-- rowEnd = diffRangeEndRow - 1;-- columnDrawTopStart = rowHeightAccumulation[rowStart - 1] || 0;-- height = rowHeightAccumulation[rowEnd] || rowHeightAccumulation[rowHeightAccumulationLength - 1];- }-- for (let r = rowStart; r <= rowEnd; r++) {- if (r < 0 || r > rowHeightAccumulationLength - 1) {- continue;- }- const rowEndPosition = rowHeightAccumulation[r];- ctx.moveTo(0, rowEndPosition);- ctx.lineTo(width, rowEndPosition);- }-- for (let c = startColumn; c <= endColumn; c++) {- if (c < 0 || c > columnWidthAccumulationLength - 1) {- continue;- }- const columnEndPosition = columnWidthAccumulation[c];- ctx.moveTo(columnEndPosition, columnDrawTopStart);- ctx.lineTo(columnEndPosition, height);- }- // console.log('xx2', scaleX, scaleY, columnTotalWidth, rowTotalHeight, rowHeightAccumulation, columnWidthAccumulation);- ctx.stroke();- ctx.closePath();- // ctx.restore();- // return;-- const { scaleX = 1, scaleY = 1 } = parentScale;- // Clearing the dashed line issue caused by overlaid auxiliary lines and strokes- border?.forValue((rowIndex, columnIndex, borderCaches) => {- if (!borderCaches) {- return true;- }-- const cellInfo = this.getCellIndex(- rowIndex,- columnIndex,- rowHeightAccumulation,- columnWidthAccumulation,- dataMergeCache- );-- let { startY, endY, startX, endX } = cellInfo;- const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;-- if (isMerged) {- return true;- }-- if (isMergedMainCell) {- startY = mergeInfo.startY;- endY = mergeInfo.endY;- startX = mergeInfo.startX;- endX = mergeInfo.endX;- }-- if (!(mergeInfo.startRow >= rowStart && mergeInfo.endRow <= rowEnd)) {- return true;- }-- for (const key in borderCaches) {- const { type } = borderCaches[key] as BorderCacheItem;-- clearLineByBorderType(ctx, type, { startX, startY, endX, endY }, scaleX, scaleY);- }- });- ctx.closePath();- // merge cell- this._clearRectangle(ctx, scale, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache, diffRanges);-- // overflow cell- this._clearOverflow(- ctx,- scale,- rowHeightAccumulation,- columnWidthAccumulation,- startRow,- endRow,- overflowCache,- diffRanges- );-- this._clearBackground(ctx, scale, backgroundPositions, diffRanges);-- ctx.restore();- }-- /**- * Clear the guide lines within a range in the table, to make room for merged cells and overflow.- */- private _clearRectangle(- ctx: CanvasRenderingContext2D,- scale: number,- rowHeightAccumulation: number[],- columnWidthAccumulation: number[],- dataMergeCache?: IRange[],- diffRanges?: IRange[]- ) {- if (dataMergeCache == null) {- return;- }- for (const dataCache of dataMergeCache) {- const { startRow, endRow, startColumn, endColumn } = dataCache;-- const startY = rowHeightAccumulation[startRow - 1] || 0;- const endY = rowHeightAccumulation[endRow] || rowHeightAccumulation[rowHeightAccumulation.length - 1];-- const startX = columnWidthAccumulation[startColumn - 1] || 0;- const endX =- columnWidthAccumulation[endColumn] || columnWidthAccumulation[columnWidthAccumulation.length - 1];-- if (- !this.isRenderDiffRangesByRow(startRow, diffRanges) &&- !this.isRenderDiffRangesByRow(endRow, diffRanges)- ) {- continue;- }-- ctx.clearRect(startX, startY, endX - startX, endY - startY);-- // After ClearRect, the lines will become thinner, and the lines will be repaired below.- ctx.beginPath();- ctx.moveTo(startX, startY);- ctx.lineTo(endX, startY);- ctx.lineTo(endX, endY);- ctx.lineTo(startX, endY);- ctx.lineTo(startX, startY);- ctx.stroke();- ctx.closePath();- }- }-- private _clearOverflow(- ctx: CanvasRenderingContext2D,- scale: number,- rowHeightAccumulation: number[],- columnWidthAccumulation: number[],- currentStartRow: number,- currentEndRow: number,- overflowCache?: ObjectMatrix<IRange>,- diffRanges?: IRange[]- ) {- if (overflowCache == null) {- return;- }-- overflowCache.forEach((row, columnRange) => {- if (!(row >= currentStartRow && row <= currentEndRow)) {- return true;- }-- columnRange.forEach((column, dataCache) => {- const { startRow, endRow, startColumn, endColumn } = dataCache;-- const startY = rowHeightAccumulation[startRow - 1] || 0;- const endY = rowHeightAccumulation[endRow] || rowHeightAccumulation[rowHeightAccumulation.length - 1];-- const startX = columnWidthAccumulation[startColumn - 1] || 0;- const endX =- columnWidthAccumulation[endColumn] || columnWidthAccumulation[columnWidthAccumulation.length - 1];-- if (- !this.isRenderDiffRangesByRow(startRow, diffRanges) &&- !this.isRenderDiffRangesByRow(endRow, diffRanges)- ) {- return true;- }-- ctx.clearRect(startX, startY, endX - startX, endY - startY);-- // After ClearRect, the lines will become thinner, and the lines will be repaired below.- ctx.beginPath();- ctx.moveTo(startX, startY);- ctx.lineTo(endX, startY);- ctx.lineTo(endX, endY);- ctx.lineTo(startX, endY);- ctx.lineTo(startX, startY);- ctx.stroke();- ctx.closePath();- });- });- }-- private _clearBackground(- ctx: CanvasRenderingContext2D,- scale: number,- backgroundPositions?: ObjectMatrix<ISelectionCellWithCoord>,- diffRanges?: IRange[]- ) {- backgroundPositions?.forValue((row, column, cellInfo) => {- let { startY, endY, startX, endX } = cellInfo;- const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;- if (isMerged) {- return true;- }-- if (- !this.isRenderDiffRangesByRow(mergeInfo.startRow, diffRanges) &&- !this.isRenderDiffRangesByRow(mergeInfo.endRow, diffRanges)- ) {- return true;- }-- if (isMergedMainCell) {- startY = mergeInfo.startY;- endY = mergeInfo.endY;- startX = mergeInfo.startX;- endX = mergeInfo.endX;- }-- ctx.clearRect(startX, startY, endX - startX, endY - startY);- });- }-}--// SpreadsheetExtensionRegistry.add(new BorderAuxiliary());diff --git a/packages/engine-render/src/components/sheets/extensions/border.ts b/packages/engine-render/src/components/sheets/extensions/border.tsindex 65a3504f7d..fb7346ac11 100644--- a/packages/engine-render/src/components/sheets/extensions/border.ts+++ b/packages/engine-render/src/components/sheets/extensions/border.ts@@ -66,100 +66,72 @@ export class Border extends SheetExtension {ctx.translate(FIX_ONE_PIXEL_BLUR_OFFSET / scale, FIX_ONE_PIXEL_BLUR_OFFSET / scale);- border?.forEach((rowIndex, borderColumns) => {- borderColumns?.forEach((columnIndex: number, borderCaches) => {- if (!borderCaches) {- return true;- }+ border?.forValue((rowIndex, columnIndex, borderCaches) => {+ if (!borderCaches) {+ return true;+ }- const cellInfo = this.getCellIndex(- rowIndex,- columnIndex,- rowHeightAccumulation,- columnWidthAccumulation,- dataMergeCache- );+ const cellInfo = this.getCellIndex(+ rowIndex,+ columnIndex,+ rowHeightAccumulation,+ columnWidthAccumulation,+ dataMergeCache+ );- let { startY, endY, startX, endX } = cellInfo;- const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;+ let { startY, endY, startX, endX } = cellInfo;+ const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;- if (isMerged) {- return true;- }+ if (isMerged) {+ return true;+ }- if (isMergedMainCell) {- startY = mergeInfo.startY;- endY = mergeInfo.endY;- startX = mergeInfo.startX;- endX = mergeInfo.endX;- }+ if (isMergedMainCell) {+ startY = mergeInfo.startY;+ endY = mergeInfo.endY;+ startX = mergeInfo.startX;+ endX = mergeInfo.endX;+ }++ if (+ !this.isRenderDiffRangesByRow(mergeInfo.startRow - 1, diffRanges) &&+ !this.isRenderDiffRangesByRow(mergeInfo.endRow + 1, diffRanges)+ ) {+ return true;+ }++ if (+ !this.isRenderDiffRangesByColumn(mergeInfo.startColumn - 1, diffRanges) &&+ !this.isRenderDiffRangesByColumn(mergeInfo.endColumn + 1, diffRanges)+ ) {+ return true;+ }- if (- !this.isRenderDiffRangesByRow(mergeInfo.startRow - 1, diffRanges) &&- !this.isRenderDiffRangesByRow(mergeInfo.endRow + 1, diffRanges)- ) {- return true;+ for (const key in borderCaches) {+ const { type, style, color } = borderCaches[key] as BorderCacheItem;++ if (this._getOverflowExclusion(overflowCache, type, rowIndex, columnIndex)) {+ continue;}- if (- !this.isRenderDiffRangesByColumn(mergeInfo.startColumn - 1, diffRanges) &&- !this.isRenderDiffRangesByColumn(mergeInfo.endColumn + 1, diffRanges)- ) {- return true;+ if (style !== preStyle) {+ setLineType(ctx, style);+ ctx.lineWidth = getLineWidth(style) / scale;+ preStyle = style;}- for (const key in borderCaches) {- const { type, style, color } = borderCaches[key] as BorderCacheItem;-- if (this._getOverflowExclusion(overflowCache, type, rowIndex, columnIndex)) {- continue;- }-- if (style !== preStyle) {- setLineType(ctx, style);- ctx.lineWidth = getLineWidth(style) / scale;- preStyle = style;- }-- if (color !== preColor) {- ctx.strokeStyle = color || COLOR_BLACK_RGB;- preColor = color;- }-- // make sure border would not overlap- switch (type) {- case BORDER_TYPE.LEFT: {- const lastCell = border.getValue(rowIndex, columnIndex - 1);- if (lastCell && lastCell[BORDER_TYPE.RIGHT]) {- // skip draw border- continue;- }- break;- }- case BORDER_TYPE.RIGHT:- // draw- break;- case BORDER_TYPE.TOP: {- const lastCell = border.getValue(rowIndex - 1, columnIndex);- if (lastCell && lastCell[BORDER_TYPE.BOTTOM]) {- // skip draw border- continue;- }- break;- }- case BORDER_TYPE.BOTTOM:- // draw- break;- }-- drawLineByBorderType(ctx, type, {- startX: fixLineWidthByScale(startX, scale),- startY: fixLineWidthByScale(startY, scale),- endX: fixLineWidthByScale(endX, scale),- endY: fixLineWidthByScale(endY, scale),- });+ if (color !== preColor) {+ ctx.strokeStyle = color || COLOR_BLACK_RGB;+ preColor = color;}- });++ drawLineByBorderType(ctx, type, {+ startX: fixLineWidthByScale(startX, scale),+ startY: fixLineWidthByScale(startY, scale),+ endX: fixLineWidthByScale(endX, scale),+ endY: fixLineWidthByScale(endY, scale),+ });+ }});ctx.closePath();@@ -177,11 +149,12 @@ export class Border extends SheetExtension {return isDraw;}- overflowCache?.forEach((row, rowArray) => {+ overflowCache?.forRow((row, rowArray) => {if (row !== borderRow) {return true;}- rowArray.forEach((column, rectangle) => {+ rowArray.forEach((column) => {+ const rectangle = overflowCache.getValue(row, column);const { startColumn, endColumn } = rectangle;if (type === BORDER_TYPE.LEFT && borderColumn > startColumn && borderColumn <= endColumn) {isDraw = true;diff --git a/packages/engine-render/src/components/sheets/extensions/font.ts b/packages/engine-render/src/components/sheets/extensions/font.tsindex afa7ab4b5f..59db1d45f3 100644--- a/packages/engine-render/src/components/sheets/extensions/font.ts+++ b/packages/engine-render/src/components/sheets/extensions/font.ts@@ -74,106 +74,105 @@ export class Font extends SheetExtension {fontList &&Object.keys(fontList).forEach((fontFormat: string) => {const fontObjectArray = fontList[fontFormat];- fontObjectArray.forEach((rowIndex, fontArray) => {- fontArray.forEach((columnIndex, docsConfig) => {- const cellInfo = this.getCellIndex(- rowIndex,- columnIndex,- rowHeightAccumulation,- columnWidthAccumulation,- dataMergeCache- );- let { startY, endY, startX, endX } = cellInfo;- const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;-- if (isMerged) {- return true;- }-- if (isMergedMainCell) {- startY = mergeInfo.startY;- endY = mergeInfo.endY;- startX = mergeInfo.startX;- endX = mergeInfo.endX;- }- if (- !this.isRenderDiffRangesByRow(mergeInfo.startRow, diffRanges) &&- !this.isRenderDiffRangesByRow(mergeInfo.endRow, diffRanges)- ) {- return true;- }-- /**- * Overflow can cause text truncation, so columns are not rendered incrementally.- */- // if (- // !this.isRenderDiffRangesByColumn(mergeInfo.startColumn, diffRanges) &&- // !this.isRenderDiffRangesByColumn(mergeInfo.endColumn, diffRanges)- // ) {- // return true;- // }-- const cellWidth = endX - startX;- const cellHeight = endY - startY;-- const overflowRectangle = overflowCache.getValue(rowIndex, columnIndex);- const { horizontalAlign } = docsConfig;-- ctx.save();- ctx.beginPath();- if (overflowRectangle) {- const { startColumn, startRow, endColumn, endRow } = overflowRectangle;- if (startColumn === endColumn && startColumn === columnIndex) {- ctx.rect(startX, startY, cellWidth, cellHeight);- ctx.clearRect(startX + 1, startY + 1, cellWidth - 2, cellHeight - 2);- } else {- if (horizontalAlign === HorizontalAlign.CENTER) {- this._clipRectangle(- ctx,- startRow,- endRow,- startColumn,- endColumn,- scale,- rowHeightAccumulation,- columnWidthAccumulation- );- } else if (horizontalAlign === HorizontalAlign.RIGHT) {- // console.log('horizontalAlign === HorizontalAlign.RIGHT', { rowIndex, startColumn, columnIndex, endColumn });- this._clipRectangle(- ctx,- startRow,- rowIndex,- startColumn,- columnIndex,- scale,- rowHeightAccumulation,- columnWidthAccumulation- );- } else {- this._clipRectangle(- ctx,- rowIndex,- endRow,- columnIndex,- endColumn,- scale,- rowHeightAccumulation,- columnWidthAccumulation- );- }- }- } else {+ fontObjectArray.forValue((rowIndex, columnIndex, docsConfig) => {+ const cellInfo = this.getCellIndex(+ rowIndex,+ columnIndex,+ rowHeightAccumulation,+ columnWidthAccumulation,+ dataMergeCache+ );+ let { startY, endY, startX, endX } = cellInfo;+ const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;++ if (isMerged) {+ return true;+ }++ if (isMergedMainCell) {+ startY = mergeInfo.startY;+ endY = mergeInfo.endY;+ startX = mergeInfo.startX;+ endX = mergeInfo.endX;+ }++ if (+ !this.isRenderDiffRangesByRow(mergeInfo.startRow, diffRanges) &&+ !this.isRenderDiffRangesByRow(mergeInfo.endRow, diffRanges)+ ) {+ return true;+ }++ /**+ * Overflow can cause text truncation, so columns are not rendered incrementally.+ */+ // if (+ // !this.isRenderDiffRangesByColumn(mergeInfo.startColumn, diffRanges) &&+ // !this.isRenderDiffRangesByColumn(mergeInfo.endColumn, diffRanges)+ // ) {+ // return true;+ // }++ const cellWidth = endX - startX;+ const cellHeight = endY - startY;++ const overflowRectangle = overflowCache.getValue(rowIndex, columnIndex);+ const { horizontalAlign } = docsConfig;++ ctx.save();+ ctx.beginPath();+ if (overflowRectangle) {+ const { startColumn, startRow, endColumn, endRow } = overflowRectangle;+ if (startColumn === endColumn && startColumn === columnIndex) {ctx.rect(startX, startY, cellWidth, cellHeight);ctx.clearRect(startX + 1, startY + 1, cellWidth - 2, cellHeight - 2);+ } else {+ if (horizontalAlign === HorizontalAlign.CENTER) {+ this._clipRectangle(+ ctx,+ startRow,+ endRow,+ startColumn,+ endColumn,+ scale,+ rowHeightAccumulation,+ columnWidthAccumulation+ );+ } else if (horizontalAlign === HorizontalAlign.RIGHT) {+ // console.log('horizontalAlign === HorizontalAlign.RIGHT', { rowIndex, startColumn, columnIndex, endColumn });+ this._clipRectangle(+ ctx,+ startRow,+ rowIndex,+ startColumn,+ columnIndex,+ scale,+ rowHeightAccumulation,+ columnWidthAccumulation+ );+ } else {+ this._clipRectangle(+ ctx,+ rowIndex,+ endRow,+ columnIndex,+ endColumn,+ scale,+ rowHeightAccumulation,+ columnWidthAccumulation+ );+ }}- ctx.clip();-- ctx.translate(startX, startY);- this._renderDocuments(ctx, docsConfig, startX, startY, endX, endY, rowIndex, columnIndex);- ctx.restore();- });+ } else {+ ctx.rect(startX, startY, cellWidth, cellHeight);+ ctx.clearRect(startX + 1, startY + 1, cellWidth - 2, cellHeight - 2);+ }+ ctx.clip();++ ctx.translate(startX, startY);+ this._renderDocuments(ctx, docsConfig, startX, startY, endX, endY, rowIndex, columnIndex);+ ctx.restore();});});ctx.restore();diff --git a/packages/engine-render/src/components/sheets/extensions/index.ts b/packages/engine-render/src/components/sheets/extensions/index.tsindex e3ec3361fa..5d2e37df90 100644--- a/packages/engine-render/src/components/sheets/extensions/index.ts+++ b/packages/engine-render/src/components/sheets/extensions/index.ts@@ -16,7 +16,6 @@export * from './background';export * from './border';-export * from './border-auxiliary';export * from './column-header-layout';export * from './font';export * from './row-header-layout';diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.tsindex 9deb913053..254a4e278b 100644--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts@@ -20,6 +20,7 @@ import type {IColumnData,IDocumentData,IDocumentRenderConfig,+ IObjectArrayPrimitiveType,IPaddingData,IRange,IRowData,@@ -31,7 +32,6 @@ import type {IWorksheetData,LocaleService,Nullable,- ObjectArrayType,Styles,TextDirection,Worksheet,@@ -43,6 +43,7 @@ import {getColorStyle,HorizontalAlign,isEmptyCell,+ isNullCell,ObjectMatrix,searchArray,Tools,@@ -226,7 +227,7 @@ export class SpreadsheetSkeleton extends Skeleton {constructor(private _worksheet: Worksheet | undefined,private _config: IWorksheetData,- private _cellData: ObjectMatrix<ICellData>,+ private _cellData: ObjectMatrix<Nullable<ICellData>>,private _styles: Styles,_localeService: LocaleService) {@@ -307,7 +308,7 @@ export class SpreadsheetSkeleton extends Skeleton {static create(worksheet: Worksheet | undefined,config: IWorksheetData,- cellData: ObjectMatrix<ICellData>,+ cellData: ObjectMatrix<Nullable<ICellData>>,styles: Styles,LocaleService: LocaleService) {@@ -397,7 +398,7 @@ export class SpreadsheetSkeleton extends Skeleton {const results: IRowAutoHeightInfo[] = [];const { mergeData, rowData } = this._config;- const rowObjectArray = Tools.createObjectArray(rowData);+ const rowObjectArray = rowData;for (const range of ranges) {const { startRow, endRow, startColumn, endColumn } = range;@@ -409,7 +410,7 @@ export class SpreadsheetSkeleton extends Skeleton {}// The row sets isAutoHeight to false, and there is no need to calculate the automatic row height for the row.- if (rowObjectArray.get(rowIndex)?.isAutoHeight === false) {+ if (rowObjectArray[rowIndex]?.isAutoHeight === false) {continue;}@@ -431,7 +432,7 @@ export class SpreadsheetSkeleton extends Skeleton {private _calculateRowAutoHeight(rowNum: number): number {const { columnCount, columnData, mergeData, defaultRowHeight } = this._config;- const data = Tools.createObjectArray(columnData);+ const data = columnData;let height = defaultRowHeight;const worksheet = this._worksheet;@@ -467,7 +468,7 @@ export class SpreadsheetSkeleton extends Skeleton {angle = VERTICAL_ROTATE_ANGLE;}- const colWidth = data.get(i)?.w;+ const colWidth = data[i]?.w;if (typeof colWidth === 'number' && wrapStrategy === WrapStrategy.WRAP) {documentModel.updateDocumentDataPageSize(colWidth);}@@ -1229,17 +1230,17 @@ export class SpreadsheetSkeleton extends Skeleton {private _generateRowMatrixCache(rowCount: number,- rowData: ObjectArrayType<Partial<IRowData>>,+ rowData: IObjectArrayPrimitiveType<Partial<IRowData>>,defaultRowHeight: number) {let rowTotalHeight = 0;const rowHeightAccumulation: number[] = [];- const data = Tools.createObjectArray(rowData);+ const data = rowData;for (let r = 0; r < rowCount; r++) {let rowHeight = defaultRowHeight;- if (data.get(r) != null) {- const rowDataItem = data.get(r);+ if (data[r] != null) {+ const rowDataItem = data[r];if (!rowDataItem) {continue;@@ -1269,19 +1270,19 @@ export class SpreadsheetSkeleton extends Skeleton {private _generateColumnMatrixCache(colCount: number,- columnData: ObjectArrayType<Partial<IColumnData>>,+ columnData: IObjectArrayPrimitiveType<Partial<IColumnData>>,defaultColumnWidth: number) {let columnTotalWidth = 0;const columnWidthAccumulation: number[] = [];- const data = Tools.createObjectArray(columnData);+ const data = columnData;for (let c = 0; c < colCount; c++) {let columnWidth = defaultColumnWidth;- if (data.get(c) != null) {- const columnDataItem = data.get(c);+ if (data[c] != null) {+ const columnDataItem = data[c];if (!columnDataItem) {continue;@@ -1442,21 +1443,6 @@ export class SpreadsheetSkeleton extends Skeleton {for (const data of dataMergeCache) {this._setCellCache(data.startRow, data.startColumn, false);}-- // dataMergeCache &&- // dataMergeCache.forEach((rowIndex: number, row: ObjectArray<IRange>) => {- // row.forEach((columnIndex: number, mainCell: IRange) => {- // if (!mainCell) {- // return true;- // }-- // this._setCellCache(- // rowIndex,- // columnIndex,- // false,- // );- // });- // });}private _resetCache() {@@ -1521,6 +1507,10 @@ export class SpreadsheetSkeleton extends Skeleton {this._setBorderProps(r, c, BORDER_TYPE.RIGHT, style, cache);}+ if (isNullCell(cell)) {+ return;+ }+const modelObject = cell && this._getCellDocumentModel(cell);if (modelObject == null) {diff --git a/packages/engine-render/src/components/sheets/spreadsheet.ts b/packages/engine-render/src/components/sheets/spreadsheet.tsindex cff7d710d9..a04d3934fc 100644--- a/packages/engine-render/src/components/sheets/spreadsheet.ts+++ b/packages/engine-render/src/components/sheets/spreadsheet.ts@@ -233,6 +233,8 @@ export class Spreadsheet extends SheetComponent {return this;}+ const { top, left, bottom, right } = bounds!.viewBound;+const spreadsheetSkeleton = this.getSkeleton();if (!spreadsheetSkeleton) {@@ -267,6 +269,11 @@ export class Spreadsheet extends SheetComponent {if (bounds && this._allowCache === true) {const { viewBound, diffBounds, diffX, diffY, viewPortPosition, viewPortKey } = bounds;+ if (viewPortKey === 'viewColumnRight' || viewPortKey === 'viewRowBottom' || viewPortKey === 'viewLeftTop') {+ // console.warn('ignore object', this);+ return;+ }+if (viewPortKey === 'viewMain') {const ctx = this._cacheCanvas.getContext();ctx.save();@@ -474,12 +481,13 @@ export class Spreadsheet extends SheetComponent {Object.keys(fontList).forEach((fontFormat: string) => {const fontObjectArray = fontList[fontFormat];- fontObjectArray.forEach((row, fontCache) => {+ fontObjectArray.forRow((row, columns) => {if (this._overflowCacheRuntime[row] != null) {return;}- fontCache.forEach((column, docsConfig) => {+ columns.forEach((column) => {+ const docsConfig = fontObjectArray.getValue(row, column);// wrap and angle handlerconst { documentSkeleton, angle = 0, horizontalAlign, wrapStrategy } = docsConfig;diff --git a/packages/sheets-find/src/domain/text-find.ts b/packages/sheets-find/src/domain/text-find.tsindex cc2e937b97..299329458d 100644--- a/packages/sheets-find/src/domain/text-find.ts+++ b/packages/sheets-find/src/domain/text-find.ts@@ -274,7 +274,7 @@ export class TextFinder {.getSheetBySheetId(this._rangeData[i].sheetId);if (!sheet) return [];- let matrix: ObjectMatrix<ICellData> = new ObjectMatrix<ICellData>();+ let matrix: ObjectMatrix<Nullable<ICellData>> = new ObjectMatrix<Nullable<ICellData>>();if (this._matchFormula) {// matrix = this._rangeData[i].getValue().f;} else {@@ -283,7 +283,7 @@ export class TextFinder {if (this._matchEntire) {matrix.forValue((row, col, value) => {- if (!value.v) return;+ if (value == null || !value.v) return;if ((this._matchCase && value.v === this._text) ||(this._text as string).toLowerCase() === `${value.v}`.toLowerCase()@@ -316,7 +316,7 @@ export class TextFinder {const reg = new RegExp(getRegExpStr(this._text as string), this._matchCase ? 'g' : 'ig');matrix.forValue((row, col, value) => {- if (!value.v) return;+ if (value == null || !value.v) return;if (reg.test(`${value.v}`)) {reg.lastIndex = 0;range.push({diff --git a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts b/packages/sheets-formula/src/commands/operations/insert-function.operation.tsindex b6d703fe12..26aedbcb17 100644--- a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts+++ b/packages/sheets-formula/src/commands/operations/insert-function.operation.ts@@ -149,7 +149,7 @@ export const InsertFunctionOperation: ICommand = {* 1. Starting from the first position on the left or top and ending with a continuous number (the first non-blank cell is allowed to be text)* 2. Match the upper part first, then the left part. If not, insert a function with empty parameters.*/-function findRefRange(cellMatrix: ObjectMatrix<ICellData>, row: number, column: number): Nullable<IRange> {+function findRefRange(cellMatrix: ObjectMatrix<Nullable<ICellData>>, row: number, column: number): Nullable<IRange> {const startRow = findStartRow(cellMatrix, row, column);if (startRow !== row) {return {@@ -172,7 +172,7 @@ function findRefRange(cellMatrix: ObjectMatrix<ICellData>, row: number, column:return null;}-function findStartRow(cellMatrix: ObjectMatrix<ICellData>, row: number, column: number) {+function findStartRow(cellMatrix: ObjectMatrix<Nullable<ICellData>>, row: number, column: number) {let isFirstNumber = false;if (row === 0) return row;@@ -193,7 +193,7 @@ function findStartRow(cellMatrix: ObjectMatrix<ICellData>, row: number, column:return row;}-function findStartColumn(cellMatrix: ObjectMatrix<ICellData>, row: number, column: number) {+function findStartColumn(cellMatrix: ObjectMatrix<Nullable<ICellData>>, row: number, column: number) {let isFirstNumber = false;if (column === 0) return column;diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.tsindex 09ee283b03..91d6d0fad3 100644--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts@@ -259,10 +259,10 @@ export class ActiveDirtyController extends Disposable {const lastEndColumn = worksheet?.getLastColumnWithContent() || 0;- const matrix = new ObjectMatrix<ICellData | null>();+ const matrix = new ObjectMatrix<Nullable<ICellData>>();for (const range of ranges) {- let newMatrix: Nullable<ObjectMatrix<ICellData | null>> = null;+ let newMatrix: Nullable<ObjectMatrix<Nullable<ICellData>>> = null;const { startRow, startColumn, endRow, endColumn } = range;if (shiftDimension === Dimension.ROWS) {newMatrix = this._rangeToMatrix({@@ -307,10 +307,10 @@ export class ActiveDirtyController extends Disposable {const columnCount = worksheet?.getColumnCount() || 0;- const matrix = new ObjectMatrix<ICellData | null>();+ const matrix = new ObjectMatrix<Nullable<ICellData>>();for (const range of ranges) {- let newMatrix: Nullable<ObjectMatrix<ICellData | null>> = null;+ let newMatrix: Nullable<ObjectMatrix<Nullable<ICellData>>> = null;const { startRow, endRow, startColumn, endColumn } = range;if (isRow === true) {@@ -372,7 +372,7 @@ export class ActiveDirtyController extends Disposable {}private _rangeToMatrix(range: IRange) {- const matrix = new ObjectMatrix<ICellData | null>();+ const matrix = new ObjectMatrix<Nullable<ICellData>>();const { startRow, startColumn, endRow, endColumn } = range;@@ -388,7 +388,7 @@ export class ActiveDirtyController extends Disposable {private _getDirtyRangesByCellValue(unitId: string,sheetId: string,- cellValue?: IObjectMatrixPrimitiveType<ICellData | null>+ cellValue?: IObjectMatrixPrimitiveType<Nullable<ICellData>>) {const dirtyRanges: IUnitRange[] = [];@@ -414,7 +414,7 @@ export class ActiveDirtyController extends Disposable {private _getDirtyRangesForArrayFormula(unitId: string,sheetId: string,- cellValue: IObjectMatrixPrimitiveType<ICellData | null>+ cellValue: IObjectMatrixPrimitiveType<Nullable<ICellData>>) {const dirtyRanges: IUnitRange[] = [];diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex 44719f04cc..9850d2ccf8 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -573,7 +573,7 @@ export class UpdateFormulaController extends Disposable {formulaMatrix.forValue((r, c, formulaItem) => {const formulaString = formulaItem?.f || '';- const oldFormulaString = oldFormulaMatrix.getRow(r)?.get(c)?.f || '';+ const oldFormulaString = oldFormulaMatrix.getValue(r, c)?.f || '';if (isFormulaString(formulaString)) {// formula with formula iddiff --git a/packages/sheets-formula/src/controllers/utils.ts b/packages/sheets-formula/src/controllers/utils.tsindex 62d80a0517..b4f7b00405 100644--- a/packages/sheets-formula/src/controllers/utils.ts+++ b/packages/sheets-formula/src/controllers/utils.ts@@ -122,7 +122,7 @@ function handleMoveRange<T>(formulaMatrix: ObjectMatrix<T>, command: ICommandInfconst cacheValue = formulaMatrix.getValue(r, c);cacheMatrix.setValue(r - fromStartRow, c - fromStartColumn, cacheValue);- formulaMatrix.setValue(r, c, null);+ formulaMatrix.setValue(r, c, null as T);}}diff --git a/packages/sheets-import-xlsx/src/services/upload.service.ts b/packages/sheets-import-xlsx/src/services/upload.service.tsindex 08fcc23f92..3ff83b9daf 100644--- a/packages/sheets-import-xlsx/src/services/upload.service.ts+++ b/packages/sheets-import-xlsx/src/services/upload.service.ts@@ -19,13 +19,13 @@ import type {ICellData,IColumnData,IKeyValue,+ IObjectArrayPrimitiveType,IRowData,IStyleData,ITextRun,ITextStyle,IWorkbookData,IWorksheetData,- ObjectArrayPrimitiveType,} from '@univerjs/core';import { HorizontalAlign, IUniverInstanceService, Tools, VerticalAlign, WrapStrategy } from '@univerjs/core';@@ -148,7 +148,7 @@ export function migrate(config: any): Partial<IWorkbookData> {// 隐藏行if (sheet.config.rowhidden) {if (!newSheet.rowData) newSheet.rowData = {};- const rowData = newSheet.rowData as ObjectArrayPrimitiveType<Partial<IRowData>>;+ const rowData = newSheet.rowData as IObjectArrayPrimitiveType<Partial<IRowData>>;for (const [rowIndex, isHidden] of Object.entries(sheet.config.rowhidden)) {if (!rowData[Number(rowIndex)]) {rowData[Number(rowIndex)] = {};@@ -160,7 +160,7 @@ export function migrate(config: any): Partial<IWorkbookData> {// 隐藏列if (sheet.config.colhidden) {if (!newSheet.columnData) newSheet.columnData = {};- const columnData = newSheet.columnData as ObjectArrayPrimitiveType<Partial<IColumnData>>;+ const columnData = newSheet.columnData as IObjectArrayPrimitiveType<Partial<IColumnData>>;for (const [colIndex, isHidden] of Object.entries(sheet.config.colhidden)) {if (!columnData[Number(colIndex)]) {columnData[Number(colIndex)] = {};diff --git a/packages/sheets-ui/src/common/utils.ts b/packages/sheets-ui/src/common/utils.tsindex 06f1d2b840..12f5f7ab73 100644--- a/packages/sheets-ui/src/common/utils.ts+++ b/packages/sheets-ui/src/common/utils.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, IMutationInfo, IRange, Worksheet } from '@univerjs/core';+import type { ICellData, IMutationInfo, IRange, Nullable, Worksheet } from '@univerjs/core';import { ObjectMatrix } from '@univerjs/core';import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '@univerjs/sheets';@@ -77,10 +77,13 @@ export function getClearContentMutationParamsForRanges(};}-export function getClearContentMutationParamForRange(worksheet: Worksheet, range: IRange): ObjectMatrix<ICellData> {+export function getClearContentMutationParamForRange(+ worksheet: Worksheet,+ range: IRange+): ObjectMatrix<Nullable<ICellData>> {const { startRow, startColumn, endColumn, endRow } = range;const cellMatrix = worksheet.getMatrixWithMergedCells(startRow, startColumn, endRow, endColumn);- const redoMatrix = new ObjectMatrix<ICellData>();+ const redoMatrix = new ObjectMatrix<Nullable<ICellData>>();cellMatrix.forValue((row, col, cellData) => {if (cellData && (row !== startRow || col !== startColumn)) {redoMatrix.setValue(row, col, null);diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.tsindex b29d8afbcb..5bc0214162 100644--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts@@ -14,7 +14,16 @@* limitations under the License.*/-import type { ICellData, IMutationInfo, IObjectMatrixPrimitiveType, IRange, IRowData, Worksheet } from '@univerjs/core';+import type {+ ICellData,+ IMutationInfo,+ IObjectArrayPrimitiveType,+ IObjectMatrixPrimitiveType,+ IRange,+ IRowData,+ Nullable,+ Worksheet,+} from '@univerjs/core';import {BooleanNumber,DEFAULT_WORKSHEET_COLUMN_WIDTH,@@ -26,7 +35,6 @@ import {IUniverInstanceService,LifecycleStages,LocaleService,- ObjectArray,ObjectMatrix,OnLifecycle,} from '@univerjs/core';@@ -241,7 +249,7 @@ export class SheetClipboardController extends Disposable {const addingRowsCount = range.endRow - maxRow;const existingRowsCount = rowProperties.length - addingRowsCount;if (addingRowsCount > 0) {- const rowInfo = new ObjectArray<IRowData>();+ const rowInfo: IObjectArrayPrimitiveType<IRowData> = {};rowProperties.slice(existingRowsCount).forEach((property, index) => {const style = property?.style;if (!style) {@@ -261,10 +269,10 @@ export class SheetClipboardController extends Disposable {return false;});- rowInfo.set(index, {+ rowInfo[index] = {h: height,hd: BooleanNumber.FALSE,- });+ };});const addRowMutation: IInsertRowMutationParams = {@@ -281,7 +289,7 @@ export class SheetClipboardController extends Disposable {// get row height of existing rows// TODO When Excel pasted, there was no width height, Do we still need to set the height?- const rowHeight = new ObjectArray<number>();+ const rowHeight: IObjectArrayPrimitiveType<number> = {};rowProperties.slice(0, existingRowsCount).forEach((property, index) => {const style = property.style;if (!style) {@@ -301,7 +309,7 @@ export class SheetClipboardController extends Disposable {return false;});- rowHeight.set(index, height);+ rowHeight[index] = height;});// apply row properties to the existing rows@@ -338,12 +346,10 @@ export class SheetClipboardController extends Disposable {unitId: unitId!,subUnitId: subUnitId!,ranges: [{ ...range, startColumn: maxColumn }],- colInfo: new ObjectArray(- colProperties.slice(existingColsCount).map((property) => ({- w: property.width ? +property.width : DEFAULT_WORKSHEET_COLUMN_WIDTH,- hd: BooleanNumber.FALSE,- }))- ),+ colInfo: colProperties.slice(existingColsCount).map((property) => ({+ w: property.width ? +property.width : DEFAULT_WORKSHEET_COLUMN_WIDTH,+ hd: BooleanNumber.FALSE,+ })),};redoMutations.push({id: InsertColMutation.id,@@ -355,11 +361,9 @@ export class SheetClipboardController extends Disposable {unitId: unitId!,subUnitId: subUnitId!,ranges: [{ ...range, endRow: Math.min(range.endColumn, maxColumn) }],- colWidth: new ObjectArray(- colProperties- .slice(0, existingColsCount)- .map((property) => (property.width ? +property.width : DEFAULT_WORKSHEET_COLUMN_WIDTH))- ),+ colWidth: colProperties+ .slice(0, existingColsCount)+ .map((property) => (property.width ? +property.width : DEFAULT_WORKSHEET_COLUMN_WIDTH)),};redoMutations.push({id: SetWorksheetColWidthMutation.id,@@ -502,11 +506,9 @@ export class SheetClipboardController extends Disposable {unitId: unitId!,subUnitId: subUnitId!,ranges: [{ ...range, endRow: Math.min(range.endColumn, maxColumn) }],- colWidth: new ObjectArray(- colProperties- .slice(0, existingColsCount)- .map((property) => (property.width ? +property.width : DEFAULT_WORKSHEET_COLUMN_WIDTH))- ),+ colWidth: colProperties+ .slice(0, existingColsCount)+ .map((property) => (property.width ? +property.width : DEFAULT_WORKSHEET_COLUMN_WIDTH)),};redoMutations.push({id: SetWorksheetColWidthMutation.id,@@ -603,8 +605,8 @@ export class SheetClipboardController extends Disposable {}// Generate cellValue from range and set null-function generateNullCellValue(range: IRange[]): IObjectMatrixPrimitiveType<ICellData> {- const cellValue = new ObjectMatrix<ICellData>();+function generateNullCellValue(range: IRange[]): IObjectMatrixPrimitiveType<Nullable<ICellData>> {+ const cellValue = new ObjectMatrix<Nullable<ICellData>>();range.forEach((range: IRange) => {const { startRow, startColumn, endRow, endColumn } = range;for (let i = startRow; i <= endRow; i++) {diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.tsindex 7850907c1b..265ce83099 100644--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, IMutationInfo, IRange } from '@univerjs/core';+import type { ICellData, IMutationInfo, IRange, Nullable } from '@univerjs/core';import { IUniverInstanceService, ObjectMatrix, Rectangle } from '@univerjs/core';import type {IAddWorksheetMergeMutationParams,@@ -135,20 +135,20 @@ export function getMoveRangeMutations(res.setValue(copyRange.startRow + rowIndex, copyRange.startColumn + colIndex, null);});return res;- }, new ObjectMatrix<ICellData | null>());+ }, new ObjectMatrix<Nullable<ICellData>>());const currentFromCellValues = fromValues.reduce((res, row, rowIndex) => {row.forEach((colItem, colIndex) => {res.setValue(copyRange.startRow + rowIndex, copyRange.startColumn + colIndex, colItem);});return res;- }, new ObjectMatrix<ICellData | null>());+ }, new ObjectMatrix<Nullable<ICellData>>());const newToCellValues = fromValues.reduce((res, row, rowIndex) => {row.forEach((colItem, colIndex) => {res.setValue(pastedRange.startRow + rowIndex, pastedRange.startColumn + colIndex, colItem);});return res;- }, new ObjectMatrix<ICellData | null>());+ }, new ObjectMatrix<Nullable<ICellData>>());const currentToCellValues = worksheet.getRange(pastedRange).getValues()@@ -157,7 +157,7 @@ export function getMoveRangeMutations(res.setValue(pastedRange.startRow + rowIndex, pastedRange.startColumn + colIndex, colItem);});return res;- }, new ObjectMatrix<ICellData | null>());+ }, new ObjectMatrix<Nullable<ICellData>>());const doMoveRangeMutation: IMoveRangeMutationParams = {from: newFromCellValues.getMatrix(),diff --git a/packages/sheets/src/basics/interfaces/mutation-interface.ts b/packages/sheets/src/basics/interfaces/mutation-interface.tsindex b3a8896e18..c3caf0c511 100644--- a/packages/sheets/src/basics/interfaces/mutation-interface.ts+++ b/packages/sheets/src/basics/interfaces/mutation-interface.ts@@ -18,11 +18,11 @@ import type {Dimension,ICellData,IColumnData,+ IObjectArrayPrimitiveType,IObjectMatrixPrimitiveType,IRange,IRowData,IWorksheetData,- ObjectArray,} from '@univerjs/core';/** Params of `RemoveSheetMutation` */@@ -43,7 +43,7 @@ export interface IInsertRowMutationParams {unitId: string;subUnitId: string;ranges: IRange[];- rowInfo?: ObjectArray<IRowData>;+ rowInfo?: IObjectArrayPrimitiveType<IRowData>;}/** Params of InsertColMutation */@@ -51,7 +51,7 @@ export interface IInsertColMutationParams {unitId: string;subUnitId: string;ranges: IRange[];- colInfo?: ObjectArray<IColumnData>;+ colInfo?: IObjectArrayPrimitiveType<IColumnData>;}/** Params of InsertRowMutation */diff --git a/packages/sheets/src/commands/commands/__tests__/set-border.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-border.command.spec.tsindex 76284a1fe8..1bb1eae87a 100644--- a/packages/sheets/src/commands/commands/__tests__/set-border.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/set-border.command.spec.ts@@ -180,7 +180,7 @@ describe('Test style commands', () => {expect(await commandService.executeCommand(SetBorderStyleCommand.id, { value: BorderStyleTypes.MEDIUM })).toBeTruthy();- expect(getBorder({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 })?.b).toBeUndefined();+ expect(getBorder({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 })?.b).toBeNull();expect(await commandService.executeCommand(SetBorderPositionCommand.id, { value: BorderType.OUTSIDE })@@ -225,7 +225,7 @@ describe('Test style commands', () => {value: BorderStyleTypes.MEDIUM_DASH_DOT_DOT,})).toBeTruthy();- expect(getBorder({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 })?.b).toBeUndefined();+ expect(getBorder({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 })?.b).toBeNull();expect(await commandService.executeCommand(SetBorderPositionCommand.id, { value: BorderType.ALL })diff --git a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.tsindex 4c2d869bc8..f9a587eb90 100644--- a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts@@ -261,9 +261,12 @@ describe('Test set range values commands', () => {).toBeTruthy();expect(getStyle()).toStrictEqual((allStyle.value as ICellData).s);+ /**+ * todo: @Dushusir null attribute+ */// undoexpect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();- expect(getStyle()).toStrictEqual(getParamsStyleBaseObject());+ expect(Tools.removeNull(getStyle())).toStrictEqual(getParamsStyleBaseObject());// redoexpect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();diff --git a/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts b/packages/sheets/src/commands/commands/add-worksheet-merge.command.tsindex c6d0552836..031cebf128 100644--- a/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts+++ b/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, ICommand, IMutationInfo, IRange, Worksheet } from '@univerjs/core';+import type { ICellData, ICommand, IMutationInfo, IRange, Nullable, Worksheet } from '@univerjs/core';import {CommandType,Dimension,@@ -104,10 +104,10 @@ function getClearContentMutationParamsForRanges(};}-function getClearContentMutationParamForRange(worksheet: Worksheet, range: IRange): ObjectMatrix<ICellData> {+function getClearContentMutationParamForRange(worksheet: Worksheet, range: IRange): ObjectMatrix<Nullable<ICellData>> {const { startRow, startColumn, endColumn, endRow } = range;const cellMatrix = worksheet.getMatrixWithMergedCells(startRow, startColumn, endRow, endColumn);- const redoMatrix = new ObjectMatrix<ICellData>();+ const redoMatrix = new ObjectMatrix<Nullable<ICellData>>();cellMatrix.forValue((row, col, cellData) => {if (cellData && (row !== startRow || col !== startColumn)) {redoMatrix.setValue(row, col, null);diff --git a/packages/sheets/src/commands/commands/clear-selection-all.command.ts b/packages/sheets/src/commands/commands/clear-selection-all.command.tsindex 677bf03c43..d1a10776f5 100644--- a/packages/sheets/src/commands/commands/clear-selection-all.command.ts+++ b/packages/sheets/src/commands/commands/clear-selection-all.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, ICommand, IMutationInfo, IObjectMatrixPrimitiveType, IRange } from '@univerjs/core';+import type { ICellData, ICommand, IMutationInfo, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';import {CommandType,ICommandService,@@ -98,8 +98,8 @@ export const ClearSelectionAllCommand: ICommand = {};// Generate cellValue from range and set null-function generateNullCellValue(range: IRange[]): IObjectMatrixPrimitiveType<ICellData> {- const cellValue = new ObjectMatrix<ICellData>();+function generateNullCellValue(range: IRange[]): IObjectMatrixPrimitiveType<Nullable<ICellData>> {+ const cellValue = new ObjectMatrix<Nullable<ICellData>>();range.forEach((range: IRange) => {const { startRow, startColumn, endRow, endColumn } = range;for (let i = startRow; i <= endRow; i++) {diff --git a/packages/sheets/src/commands/commands/insert-range-move-down.command.ts b/packages/sheets/src/commands/commands/insert-range-move-down.command.tsindex a1be018e4f..9e6911ef2f 100644--- a/packages/sheets/src/commands/commands/insert-range-move-down.command.ts+++ b/packages/sheets/src/commands/commands/insert-range-move-down.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, ICommand, IMutationInfo, IRange, IRowData } from '@univerjs/core';+import type { ICellData, ICommand, IMutationInfo, IRange } from '@univerjs/core';import {BooleanNumber,CommandType,@@ -23,7 +23,6 @@ import {ILogService,IUndoRedoService,IUniverInstanceService,- ObjectArray,ObjectMatrix,sequenceExecute,} from '@univerjs/core';@@ -152,12 +151,10 @@ export const InsertRangeMoveDownCommand: ICommand = {unitId,subUnitId,ranges: [lastRowRange],- rowInfo: new ObjectArray<IRowData>(- new Array(rowsCount).fill(undefined).map(() => ({- h: lastRowHeight,- hd: BooleanNumber.FALSE,- }))- ),+ rowInfo: new Array(rowsCount).fill(undefined).map(() => ({+ h: lastRowHeight,+ hd: BooleanNumber.FALSE,+ })),};redoMutations.push({diff --git a/packages/sheets/src/commands/commands/insert-range-move-right.command.ts b/packages/sheets/src/commands/commands/insert-range-move-right.command.tsindex ec50c55fd5..1d36d99a8e 100644--- a/packages/sheets/src/commands/commands/insert-range-move-right.command.ts+++ b/packages/sheets/src/commands/commands/insert-range-move-right.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, IColumnData, ICommand, IMutationInfo, IRange } from '@univerjs/core';+import type { ICellData, ICommand, IMutationInfo, IRange } from '@univerjs/core';import {BooleanNumber,CommandType,@@ -23,7 +23,6 @@ import {ILogService,IUndoRedoService,IUniverInstanceService,- ObjectArray,ObjectMatrix,sequenceExecute,} from '@univerjs/core';@@ -148,12 +147,10 @@ export const InsertRangeMoveRightCommand: ICommand = {unitId,subUnitId,ranges: [lastColumnRange],- colInfo: new ObjectArray<IColumnData>(- new Array(columnsCount).fill(undefined).map(() => ({- w: lastColumnWidth,- hd: BooleanNumber.FALSE,- }))- ),+ colInfo: new Array(columnsCount).fill(undefined).map(() => ({+ w: lastColumnWidth,+ hd: BooleanNumber.FALSE,+ })),};redoMutations.push({diff --git a/packages/sheets/src/commands/commands/insert-row-col.command.ts b/packages/sheets/src/commands/commands/insert-row-col.command.tsindex 9ca8f052d8..ddf20cb535 100644--- a/packages/sheets/src/commands/commands/insert-row-col.command.ts+++ b/packages/sheets/src/commands/commands/insert-row-col.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, IColumnData, ICommand, IRange, IRowData, IStyleData, Nullable } from '@univerjs/core';+import type { ICellData, ICommand, IRange, IStyleData, Nullable } from '@univerjs/core';import {BooleanNumber,CommandType,@@ -23,7 +23,6 @@ import {ICommandService,IUndoRedoService,IUniverInstanceService,- ObjectArray,ObjectMatrix,sequenceExecute,} from '@univerjs/core';@@ -91,13 +90,10 @@ export const InsertRowCommand: ICommand = {unitId,subUnitId,ranges: [range],- rowInfo: new ObjectArray<IRowData>(- // row height should inherit from the anchor row- new Array(endRow - startRow + 1).fill(undefined).map(() => ({- h: height,- hd: BooleanNumber.FALSE,- }))- ),+ rowInfo: new Array(endRow - startRow + 1).fill(undefined).map(() => ({+ h: height,+ hd: BooleanNumber.FALSE,+ })), // row height should inherit from the anchor row};const undoRowInsertionParams: IRemoveRowsMutationParams = InsertRowMutationUndoFactory(accessor,@@ -285,12 +281,10 @@ export const InsertColCommand: ICommand<IInsertColCommandParams> = {unitId,subUnitId,ranges: [range],- colInfo: new ObjectArray<IColumnData>(- new Array(endColumn - startColumn + 1).fill(undefined).map(() => ({- w: width,- hd: BooleanNumber.FALSE,- }))- ),+ colInfo: new Array(endColumn - startColumn + 1).fill(undefined).map(() => ({+ w: width,+ hd: BooleanNumber.FALSE,+ })),};const undoColInsertionParams: IRemoveColMutationParams = InsertColMutationUndoFactory(accessor,diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.tsindex b7fcd2a43b..c46082d11f 100644--- a/packages/sheets/src/commands/commands/move-range.command.ts+++ b/packages/sheets/src/commands/commands/move-range.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellData, ICommand, IRange } from '@univerjs/core';+import type { ICellData, ICommand, IRange, Nullable } from '@univerjs/core';import {CommandType,ICommandService,@@ -55,20 +55,20 @@ export const MoveRangeCommand: ICommand = {res.setValue(params.fromRange.startRow + rowIndex, params.fromRange.startColumn + colIndex, null);});return res;- }, new ObjectMatrix<ICellData | null>());+ }, new ObjectMatrix<Nullable<ICellData>>());const currentFromCellValues = fromValues.reduce((res, row, rowIndex) => {row.forEach((colItem, colIndex) => {res.setValue(params.fromRange.startRow + rowIndex, params.fromRange.startColumn + colIndex, colItem);});return res;- }, new ObjectMatrix<ICellData | null>());+ }, new ObjectMatrix<Nullable<ICellData>>());const newToCellValues = fromValues.reduce((res, row, rowIndex) => {row.forEach((colItem, colIndex) => {res.setValue(params.toRange.startRow + rowIndex, params.toRange.startColumn + colIndex, colItem);});return res;- }, new ObjectMatrix<ICellData | null>());+ }, new ObjectMatrix<Nullable<ICellData>>());const currentToCellValues = worksheet.getRange(params.toRange).getValues()@@ -77,7 +77,7 @@ export const MoveRangeCommand: ICommand = {res.setValue(params.toRange.startRow + rowIndex, params.toRange.startColumn + colIndex, colItem);});return res;- }, new ObjectMatrix<ICellData | null>());+ }, new ObjectMatrix<Nullable<ICellData>>());const doMoveRangeMutation: IMoveRangeMutationParams = {from: newFromCellValues.getMatrix(),diff --git a/packages/sheets/src/commands/mutations/insert-row-col.mutation.ts b/packages/sheets/src/commands/mutations/insert-row-col.mutation.tsindex 2856269c38..2aeb8ec370 100644--- a/packages/sheets/src/commands/mutations/insert-row-col.mutation.ts+++ b/packages/sheets/src/commands/mutations/insert-row-col.mutation.ts@@ -15,7 +15,7 @@*/import type { IMutation } from '@univerjs/core';-import { CommandType, IUniverInstanceService, ObjectArray, Rectangle } from '@univerjs/core';+import { CommandType, insertMatrixArray, IUniverInstanceService, Rectangle } from '@univerjs/core';import type { IAccessor } from '@wendellhu/redi';import type {@@ -75,9 +75,9 @@ export const InsertRowMutation: IMutation<IInsertRowMutationParams> = {for (let j = rowIndex; j < rowIndex + rowCount; j++) {if (rowInfo) {- rowWrapper.insert(j, rowInfo.get(j - range.startRow) ?? defaultRowInfo);+ insertMatrixArray(j, rowInfo[j - range.startRow] ?? defaultRowInfo, rowWrapper);} else {- rowWrapper.insert(j, defaultRowInfo);+ insertMatrixArray(j, defaultRowInfo, rowWrapper);}}}@@ -123,8 +123,8 @@ export const InsertColMutation: IMutation<IInsertColMutationParams> = {if (!worksheet) return false;const manager = worksheet.getColumnManager();const { ranges, colInfo } = params;- const columnPrimitive = manager.getColumnData().toJSON();- const columnWrapper = new ObjectArray(columnPrimitive);+ const columnPrimitive = manager.getColumnData();+ const columnWrapper = columnPrimitive;for (let i = 0; i < ranges.length; i++) {const range = ranges[i];@@ -138,9 +138,9 @@ export const InsertColMutation: IMutation<IInsertColMutationParams> = {hd: 0,};if (colInfo) {- columnWrapper.insert(j, colInfo.get(j - range.startColumn) ?? defaultColInfo);+ insertMatrixArray(j, colInfo[j - range.startColumn] ?? defaultColInfo, columnWrapper);} else {- columnWrapper.insert(j, defaultColInfo);+ insertMatrixArray(j, defaultColInfo, columnWrapper);}}}diff --git a/packages/sheets/src/commands/mutations/move-range.mutation.ts b/packages/sheets/src/commands/mutations/move-range.mutation.tsindex e4df0c069f..17a6dd88c3 100644--- a/packages/sheets/src/commands/mutations/move-range.mutation.ts+++ b/packages/sheets/src/commands/mutations/move-range.mutation.ts@@ -14,14 +14,14 @@* limitations under the License.*/-import type { ICellData, IMutation, IObjectMatrixPrimitiveType } from '@univerjs/core';+import type { ICellData, IMutation, IObjectMatrixPrimitiveType, Nullable } from '@univerjs/core';import { CommandType, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';export interface IMoveRangeMutationParams {unitId: string;subUnitId: string;- from: IObjectMatrixPrimitiveType<ICellData | null>;- to: IObjectMatrixPrimitiveType<ICellData | null>;+ from: IObjectMatrixPrimitiveType<Nullable<ICellData>>;+ to: IObjectMatrixPrimitiveType<Nullable<ICellData>>;}export const MoveRangeMutation: IMutation<IMoveRangeMutationParams, boolean> = {@@ -47,11 +47,11 @@ export const MoveRangeMutation: IMutation<IMoveRangeMutationParams, boolean> = {const cellMatrix = worksheet.getCellMatrix();- new ObjectMatrix<ICellData | null>(from).forValue((row, col, newVal) => {+ new ObjectMatrix<Nullable<ICellData>>(from).forValue((row, col, newVal) => {cellMatrix.setValue(row, col, newVal);});- new ObjectMatrix<ICellData | null>(to).forValue((row, col, newVal) => {+ new ObjectMatrix<Nullable<ICellData>>(to).forValue((row, col, newVal) => {cellMatrix.setValue(row, col, newVal);});diff --git a/packages/sheets/src/commands/mutations/move-rows-cols.mutation.ts b/packages/sheets/src/commands/mutations/move-rows-cols.mutation.tsindex 391f413dd2..409ea3d801 100644--- a/packages/sheets/src/commands/mutations/move-rows-cols.mutation.ts+++ b/packages/sheets/src/commands/mutations/move-rows-cols.mutation.ts@@ -15,7 +15,7 @@*/import type { IMutation, IRange } from '@univerjs/core';-import { CommandType, IUniverInstanceService, Rectangle } from '@univerjs/core';+import { CommandType, IUniverInstanceService, moveMatrixArray, Rectangle } from '@univerjs/core';import type { IAccessor } from '@wendellhu/redi';// TODO@wzhudev: maybe we should do some error handling in these mutators@@ -85,7 +85,7 @@ export const MoveRowsMutation: IMutation<IMoveRowsMutationParams> = {// move row properties by directing mutatingconst rowWrapper = worksheet.getRowManager().getRowData();- rowWrapper.move(fromRow, count, toRow);+ moveMatrixArray(fromRow, count, toRow, rowWrapper);// move cells contents by directly mutating worksheetCellMatrixconst cellMatrix = worksheet.getCellMatrix();@@ -159,7 +159,7 @@ export const MoveColsMutation: IMutation<IMoveColumnsMutationParams> = {// move column properties by directing mutatingconst columnWrapper = worksheet.getColumnManager().getColumnData();- columnWrapper.move(fromCol, count, toCol);+ moveMatrixArray(fromCol, count, toCol, columnWrapper);// move cells contents by directly mutating worksheetCellMatrixconst cellMatrix = worksheet.getCellMatrix();diff --git a/packages/sheets/src/commands/mutations/remove-row-col.mutation.ts b/packages/sheets/src/commands/mutations/remove-row-col.mutation.tsindex a7ce5eb2de..bf81f8bf59 100644--- a/packages/sheets/src/commands/mutations/remove-row-col.mutation.ts+++ b/packages/sheets/src/commands/mutations/remove-row-col.mutation.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import type { IColumnData, IMutation, IRowData, Worksheet } from '@univerjs/core';-import { CommandType, IUniverInstanceService, ObjectArray } from '@univerjs/core';+import type { IColumnData, IMutation, IObjectArrayPrimitiveType, IRowData, Worksheet } from '@univerjs/core';+import { CommandType, concatMatrixArray, IUniverInstanceService, sliceMatrixArray } from '@univerjs/core';import type { IAccessor } from '@wendellhu/redi';import type {@@ -30,14 +30,14 @@ export const RemoveRowsUndoMutationFactory = (worksheet: Worksheet): IInsertRowMutationParams => {const manager = worksheet.getRowManager();- const rowPrimitive = manager.getRowData().toJSON();- const rowWrapper = new ObjectArray(rowPrimitive);- const rowInfo = new ObjectArray<IRowData>();+ const rowPrimitive = manager.getRowData();+ const rowWrapper = rowPrimitive;+ const rowInfo: IObjectArrayPrimitiveType<IRowData> = {};for (let i = 0; i < params.ranges.length; i++) {const range = params.ranges[i];- const slice = rowWrapper.slice(range.startRow, range.endRow);- rowInfo.concat(slice);+ const slice = sliceMatrixArray(range.startRow, range.endRow, rowWrapper);+ concatMatrixArray(rowInfo, slice);}return {@@ -63,8 +63,8 @@ export const RemoveRowMutation: IMutation<IRemoveRowsMutationParams> = {if (!worksheet) return false;const manager = worksheet.getRowManager();- const rowPrimitive = manager.getRowData().toJSON();- const rowWrapper = new ObjectArray(rowPrimitive);+ const rowPrimitive = manager.getRowData();+ let rowWrapper = rowPrimitive;for (let i = 0; i < params.ranges.length; i++) {const range = params.ranges[i];@@ -72,7 +72,7 @@ export const RemoveRowMutation: IMutation<IRemoveRowsMutationParams> = {const end = range.endRow;for (let j = start; j <= end; j++) {- rowWrapper.splice(j, 1);+ rowWrapper = sliceMatrixArray(j, 1, rowWrapper);}}@@ -102,15 +102,16 @@ export const RemoveColMutationFactory = (}const manager = worksheet.getColumnManager();- const columnPrimitive = manager.getColumnData().toJSON();- const columnWrapper = new ObjectArray(columnPrimitive);- const colInfo = new ObjectArray<IColumnData>();+ const columnPrimitive = manager.getColumnData();+ const columnWrapper = columnPrimitive;+ const colInfo: IObjectArrayPrimitiveType<IColumnData> = {};for (let i = 0; i < params.ranges.length; i++) {const range = params.ranges[i];- const slice = columnWrapper.slice(range.startColumn, range.endColumn);- colInfo.concat(slice);+ const slice = sliceMatrixArray(range.startColumn, range.endColumn, columnWrapper);++ concatMatrixArray(colInfo, slice);}return {@@ -136,8 +137,8 @@ export const RemoveColMutation: IMutation<IRemoveColMutationParams> = {if (!worksheet) return false;const manager = worksheet.getColumnManager();- const columnPrimitive = manager.getColumnData().toJSON();- const columnWrapper = new ObjectArray(columnPrimitive);+ const columnPrimitive = manager.getColumnData();+ let columnWrapper = columnPrimitive;for (let i = 0; i < params.ranges.length; i++) {const range = params.ranges[i];@@ -145,7 +146,7 @@ export const RemoveColMutation: IMutation<IRemoveColMutationParams> = {const end = range.endColumn;for (let j = start; j <= end; j++) {- columnWrapper.splice(j, 1);+ columnWrapper = sliceMatrixArray(j, i, columnWrapper);}}diff --git a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/sheets/src/commands/mutations/set-range-values.mutation.tsindex c8793a3b0c..89598ece63 100644--- a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts+++ b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts@@ -40,7 +40,7 @@ export interface ISetRangeValuesMutationParams extends IMutationCommonParams {/*** null for clear all*/- cellValue?: IObjectMatrixPrimitiveType<ICellData | null>;+ cellValue?: IObjectMatrixPrimitiveType<Nullable<ICellData>>;/*** @deprecated not a good design@@ -83,7 +83,7 @@ export const SetRangeValuesUndoMutationFactory = (const cellMatrix = worksheet.getCellMatrix();const styles = workbook.getStyles();- const undoData = new ObjectMatrix<ICellData>();+ const undoData = new ObjectMatrix<Nullable<ICellData>>();const newValues = new ObjectMatrix(cellValue);@@ -98,9 +98,9 @@ export const SetRangeValuesUndoMutationFactory = (});return {- ...Tools.deepClone(params),+ ...params,options: {},- cellValue: undoData.getData(),+ cellValue: undoData.getMatrix(),} as ISetRangeValuesMutationParams;};@@ -271,7 +271,7 @@ export function transformNormalKey(if (!newStyle || !Object.keys(newStyle).length) {return oldStyle;}- const backupStyle: { [key: string]: any } = Tools.deepClone(oldStyle) || {};+ const backupStyle: { [key: string]: any } = oldStyle || {};for (const k in newStyle) {if (k === 'bd') {diff --git a/packages/sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts b/packages/sheets/src/commands/mutations/set-worksheet-col-width.mutation.tsindex 16e4ff3a49..56de8bafcd 100644--- a/packages/sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts+++ b/packages/sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts@@ -14,15 +14,15 @@* limitations under the License.*/-import type { IMutation, IRange } from '@univerjs/core';-import { CommandType, IUniverInstanceService, ObjectArray } from '@univerjs/core';+import type { IMutation, IObjectArrayPrimitiveType, IRange, Nullable } from '@univerjs/core';+import { CommandType, IUniverInstanceService } from '@univerjs/core';import type { IAccessor } from '@wendellhu/redi';export interface ISetWorksheetColWidthMutationParams {unitId: string;subUnitId: string;ranges: IRange[];- colWidth: number | ObjectArray<number>;+ colWidth: number | IObjectArrayPrimitiveType<Nullable<number>>;}export const SetWorksheetColWidthMutationFactory = (@@ -40,14 +40,14 @@ export const SetWorksheetColWidthMutationFactory = (if (worksheet == null) {throw new Error('universheet is null error!');}- const colWidth = new ObjectArray<number>();+ const colWidth: IObjectArrayPrimitiveType<Nullable<number>> = {};const manager = worksheet.getColumnManager();const ranges = params.ranges;for (let i = 0; i < ranges.length; i++) {const range = ranges[i];for (let j = range.startColumn; j < range.endColumn + 1; j++) {const column = manager.getColumnOrCreate(j);- colWidth.set(j, column.w);+ colWidth[j] = column.w;}}@@ -86,7 +86,7 @@ export const SetWorksheetColWidthMutation: IMutation<ISetWorksheetColWidthMutatiif (typeof params.colWidth === 'number') {column.w = params.colWidth;} else {- column.w = params.colWidth.get(j - range.startColumn) ?? defaultColumnWidth;+ column.w = params.colWidth[j - range.startColumn] ?? defaultColumnWidth;}}}diff --git a/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts b/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.tsindex 2b907383ac..e6fee52610 100644--- a/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts+++ b/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import type { IMutation, IRange, Nullable, ObjectArrayPrimitiveType } from '@univerjs/core';-import { CommandType, IUniverInstanceService, ObjectArray } from '@univerjs/core';+import type { IMutation, IObjectArrayPrimitiveType, IRange, Nullable } from '@univerjs/core';+import { CommandType, IUniverInstanceService } from '@univerjs/core';import type { IRowAutoHeightInfo } from '@univerjs/engine-render';import type { IAccessor } from '@wendellhu/redi';@@ -25,14 +25,14 @@ export interface ISetWorksheetRowHeightMutationParams {unitId: string;subUnitId: string;ranges: IRange[];- rowHeight: number | ObjectArray<number>;+ rowHeight: number | IObjectArrayPrimitiveType<Nullable<number>>;}export interface ISetWorksheetRowIsAutoHeightMutationParams {unitId: string;subUnitId: string;ranges: IRange[];- autoHeightInfo: boolean | ObjectArrayPrimitiveType<Nullable<boolean>>;+ autoHeightInfo: boolean | IObjectArrayPrimitiveType<Nullable<boolean>>;}export interface ISetWorksheetRowAutoHeightMutationParams {@@ -54,13 +54,13 @@ export const SetWorksheetRowHeightMutationFactory = (throw new Error('worksheet is null error!');}- const rowHeight = new ObjectArray<number>();+ const rowHeight: IObjectArrayPrimitiveType<Nullable<number>> = {};const manager = worksheet.getRowManager();for (const { startRow, endRow } of ranges) {for (let rowIndex = startRow; rowIndex < endRow + 1; rowIndex++) {const row = manager.getRowOrCreate(rowIndex);- rowHeight.set(rowIndex, row.h);+ rowHeight[rowIndex] = row.h;}}@@ -82,14 +82,14 @@ export const SetWorksheetRowIsAutoHeightMutationFactory = (const workbook = univerInstanceService.getUniverSheetInstance(unitId)!;const worksheet = workbook.getSheetBySheetId(subUnitId)!;- const autoHeightHash = new ObjectArray<Nullable<boolean>>();+ const autoHeightHash: IObjectArrayPrimitiveType<Nullable<boolean>> = {};const manager = worksheet.getRowManager();for (const { startRow, endRow } of ranges) {for (let rowIndex = startRow; rowIndex <= endRow; rowIndex++) {const row = manager.getRowOrCreate(rowIndex);- autoHeightHash.set(rowIndex, row.isAutoHeight);+ autoHeightHash[rowIndex] = row.isAutoHeight;}}@@ -97,7 +97,7 @@ export const SetWorksheetRowIsAutoHeightMutationFactory = (unitId,subUnitId,ranges,- autoHeightInfo: autoHeightHash.toJSON(),+ autoHeightInfo: autoHeightHash,};};@@ -153,7 +153,7 @@ export const SetWorksheetRowHeightMutation: IMutation<ISetWorksheetRowHeightMutaif (typeof rowHeight === 'number') {row.h = rowHeight;} else {- row.h = rowHeight.get(rowIndex) ?? defaultRowHeight;+ row.h = rowHeight[rowIndex] ?? defaultRowHeight;}row.h = Math.min(MAXIMUM_ROW_HEIGHT, row.h);@@ -187,8 +187,7 @@ export const SetWorksheetRowIsAutoHeightMutation: IMutation<ISetWorksheetRowIsAuif (typeof autoHeightInfo === 'boolean') {row.isAutoHeight = autoHeightInfo;} else {- row.isAutoHeight =- new ObjectArray(autoHeightInfo).get(rowIndex - startRow) ?? defaultRowIsAutoHeight;+ row.isAutoHeight = autoHeightInfo[rowIndex - startRow] ?? defaultRowIsAutoHeight;}}}