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: replace .map().filter() chains with explicit for-loops (#6934)
白熱60b3ec0c9227
diff --git a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.tsindex 82463c22b8..5307ced72a 100644--- a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts@@ -32,7 +32,19 @@ import type { IAddConditionalRuleMutationParams } from '../commands/mutations/adimport type { IDeleteConditionalRuleMutationParams } from '../commands/mutations/delete-conditional-rule.mutation';import type { IConditionFormattingRule, IHighlightCell, IRuleModelJson } from '../models/type';import type { IDataBarCellData, IDataBarRenderParams, IIconSetCellData, IIconSetRenderParams } from '../render/type';-import { Disposable, ICommandService, Inject, Injector, IResourceManagerService, isInternalEditorID, IUniverInstanceService, merge, ObjectMatrix, Rectangle, UniverInstanceType } from '@univerjs/core';+import {+ Disposable,+ ICommandService,+ Inject,+ Injector,+ IResourceManagerService,+ isInternalEditorID,+ IUniverInstanceService,+ merge,+ ObjectMatrix,+ Rectangle,+ UniverInstanceType,+} from '@univerjs/core';import {CopySheetCommand,getSheetCommandTarget,@@ -301,7 +313,14 @@ export class ConditionalFormattingService extends Disposable {const ruleItem = this._conditionalFormattingViewModelV2.getCellCfs(unitId, subUnitId, row, col);ruleItem?.forEach((item) => ruleIds.add(item.cfId));});- return [...ruleIds].map((cfId) => this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cfId) as IConditionFormattingRule).filter((rule) => !!rule);+ const rules: IConditionFormattingRule[] = [];+ for (const cfId of ruleIds) {+ const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cfId);+ if (rule) {+ rules.push(rule);+ }+ }+ return rules;};switch (commandInfo.id) {diff --git a/packages/sheets-data-validation/src/index.ts b/packages/sheets-data-validation/src/index.tsindex 08ea4b10f9..6be7727938 100644--- a/packages/sheets-data-validation/src/index.ts+++ b/packages/sheets-data-validation/src/index.ts@@ -40,7 +40,7 @@ export { DataValidationCacheService } from './services/dv-cache.service';export { DataValidationCustomFormulaService } from './services/dv-custom-formula.service';export { DataValidationFormulaService } from './services/dv-formula.service';export { DataValidationListCacheService, type IListCacheItem } from './services/dv-list-cache.service';-export { SheetsDataValidationValidatorService } from './services/dv-validator-service';+export { SheetsDataValidationValidatorService } from './services/dv-validator.service';export { createDefaultNewRule } from './utils/create';export { getFormulaCellData, getFormulaResult } from './utils/formula';export { isLegalFormulaResult } from './utils/formula';diff --git a/packages/sheets-data-validation/src/plugin.ts b/packages/sheets-data-validation/src/plugin.tsindex 13e1e26cdf..a797702227 100644--- a/packages/sheets-data-validation/src/plugin.ts+++ b/packages/sheets-data-validation/src/plugin.ts@@ -50,7 +50,7 @@ import { DataValidationCacheService } from './services/dv-cache.service';import { DataValidationCustomFormulaService } from './services/dv-custom-formula.service';import { DataValidationFormulaService } from './services/dv-formula.service';import { DataValidationListCacheService } from './services/dv-list-cache.service';-import { SheetsDataValidationValidatorService } from './services/dv-validator-service';+import { SheetsDataValidationValidatorService } from './services/dv-validator.service';@DependentOn(UniverSheetsFormulaPlugin, UniverDataValidationPlugin)export class UniverSheetsDataValidationPlugin extends Plugin {diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-validator-service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.tssimilarity index 99%rename from packages/sheets-data-validation/src/services/__tests__/dv-validator-service.spec.tsrename to packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.tsindex da881a7325..48b9d90bc1 100644--- a/packages/sheets-data-validation/src/services/__tests__/dv-validator-service.spec.ts+++ b/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts@@ -21,7 +21,7 @@ import type { DataValidationCacheService } from '../dv-cache.service';import { ObjectMatrix as CoreObjectMatrix, DataValidationStatus, LifecycleStages } from '@univerjs/core';import { BehaviorSubject, Subject } from 'rxjs';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { SheetsDataValidationValidatorService } from '../dv-validator-service';+import { SheetsDataValidationValidatorService } from '../dv-validator.service';function createRule(uid: string, ranges: IRange[]): IDataValidationRule {return { uid, ranges } as IDataValidationRule;diff --git a/packages/sheets-data-validation/src/services/dv-cache.service.ts b/packages/sheets-data-validation/src/services/dv-cache.service.tsindex 69651dcf0f..e37d13fe8b 100644--- a/packages/sheets-data-validation/src/services/dv-cache.service.ts+++ b/packages/sheets-data-validation/src/services/dv-cache.service.ts@@ -16,7 +16,16 @@import type { DataValidationStatus, IRange, ISheetDataValidationRule, Nullable } from '@univerjs/core';import type { IRemoveSheetMutationParams, ISetRangeValuesMutationParams } from '@univerjs/sheets';-import { Disposable, getIntersectRange, ICommandService, Inject, IUniverInstanceService, ObjectMatrix, Range, UniverInstanceType } from '@univerjs/core';+import {+ Disposable,+ getIntersectRange,+ ICommandService,+ Inject,+ IUniverInstanceService,+ ObjectMatrix,+ Range,+ UniverInstanceType,+} from '@univerjs/core';import { DataValidationModel } from '@univerjs/data-validation';import { RemoveSheetMutation, SetRangeValuesMutation } from '@univerjs/sheets';import { Subject } from 'rxjs';@@ -45,8 +54,18 @@ export class DataValidationCacheService extends Disposable {const range = new ObjectMatrix(cellValue).getDataRange();if (range.endRow === -1) return;const rules = this._sheetDataValidationModel.getRules(unitId, subUnitId);- const ranges = rules.map((rule) => rule.ranges).flat();- const intersectsRanges = ranges.map((ruleRange) => getIntersectRange(ruleRange, range)).filter(Boolean) as IRange[];+ const ranges: IRange[] = [];+ for (const rule of rules) {+ ranges.push(...rule.ranges);+ }++ const intersectsRanges: IRange[] = [];+ for (const ruleRange of ranges) {+ const intersect = getIntersectRange(ruleRange, range);+ if (intersect) {+ intersectsRanges.push(intersect);+ }+ }if (intersectsRanges.length) {this.markRangeDirty(unitId, subUnitId, intersectsRanges, true);}diff --git a/packages/sheets-data-validation/src/services/dv-validator-service.ts b/packages/sheets-data-validation/src/services/dv-validator-service.tsindex 85afc52a15..61280d2811 100644--- a/packages/sheets-data-validation/src/services/dv-validator-service.ts+++ b/packages/sheets-data-validation/src/services/dv-validator-service.ts@@ -15,7 +15,19 @@*/import type { IDataValidationRule, IRange, Nullable, ObjectMatrix, Workbook, Worksheet } from '@univerjs/core';-import { bufferDebounceTime, DataValidationStatus, Disposable, getIntersectRange, Inject, IUniverInstanceService, LifecycleService, LifecycleStages, Range, Tools, UniverInstanceType } from '@univerjs/core';+import {+ bufferDebounceTime,+ DataValidationStatus,+ Disposable,+ getIntersectRange,+ Inject,+ IUniverInstanceService,+ LifecycleService,+ LifecycleStages,+ Range,+ Tools,+ UniverInstanceType,+} from '@univerjs/core';import { bufferWhen, filter, skip } from 'rxjs';import { SheetDataValidationModel } from '../models/sheet-data-validation-model';import { DataValidationCacheService } from './dv-cache.service';@@ -70,8 +82,20 @@ export class SheetsDataValidationValidatorService extends Disposable {});};- this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(bufferWhen(() => this._lifecycleService.lifecycle$.pipe(skip(1), filter((stage) => stage === LifecycleStages.Rendered)))).subscribe(handleDirtyRanges));- this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(filter(() => this._lifecycleService.stage >= LifecycleStages.Rendered), bufferDebounceTime(20)).subscribe(handleDirtyRanges));+ this.disposeWithMe(+ this._dataValidationCacheService.dirtyRanges$.pipe(+ bufferWhen(() => this._lifecycleService.lifecycle$.pipe(+ skip(1),+ filter((stage) => stage === LifecycleStages.Rendered)+ ))+ ).subscribe(handleDirtyRanges)+ );+ this.disposeWithMe(+ this._dataValidationCacheService.dirtyRanges$.pipe(+ filter(() => this._lifecycleService.stage >= LifecycleStages.Rendered),+ bufferDebounceTime(20)+ ).subscribe(handleDirtyRanges)+ );}private async _validatorByCell(workbook: Workbook, worksheet: Worksheet, row: number, col: number) {@@ -96,7 +120,14 @@ export class SheetsDataValidationValidatorService extends Disposable {}return new Promise<DataValidationStatus>((resolve) => {- this._sheetDataValidationModel.validator(rule, { unitId, subUnitId, row: _row, col: _col, worksheet, workbook }, (status) => {+ this._sheetDataValidationModel.validator(rule, {+ unitId,+ subUnitId,+ row: _row,+ col: _col,+ worksheet,+ workbook,+ }, (status) => {resolve(status);});});@@ -132,8 +163,20 @@ export class SheetsDataValidationValidatorService extends Disposable {}const allRules = this._sheetDataValidationModel.getRules(unitId, subUnitId);- const ruleRanges = allRules.map((i) => i.ranges).flat();- const intersectRanges = ranges.map((range) => ruleRanges.map((ruleRange) => getIntersectRange(range, ruleRange))).flat().filter(Boolean) as IRange[];+ const ruleRanges: IRange[] = [];+ for (const rule of allRules) {+ ruleRanges.push(...rule.ranges);+ }++ const intersectRanges: IRange[] = [];+ for (const range of ranges) {+ for (const ruleRange of ruleRanges) {+ const intersect = getIntersectRange(range, ruleRange);+ if (intersect) {+ intersectRanges.push(intersect);+ }+ }+ }const mergeCells: Array<{resultRowIndex: number;@@ -171,7 +214,12 @@ export class SheetsDataValidationValidatorService extends Disposable {if (mergeCells.length) {mergeCells.forEach(({ resultRowIndex, resultColIndex, row, col }) => {if (result[resultRowIndex][resultColIndex] === DataValidationStatus.VALIDATING) {- result[resultRowIndex][resultColIndex] = this._dataValidationCacheService.getValue(unitId, subUnitId, row, col) ?? DataValidationStatus.VALID;+ result[resultRowIndex][resultColIndex] = this._dataValidationCacheService.getValue(+ unitId,+ subUnitId,+ row,+ col+ ) ?? DataValidationStatus.VALID;}});}@@ -232,7 +280,13 @@ export class SheetsDataValidationValidatorService extends Disposable {});});- const rules = Array.from(ruleIdSet).map((id) => this._sheetDataValidationModel.getRuleById(unitId, subUnitId, id)).filter(Boolean) as IDataValidationRule[];+ const rules: IDataValidationRule[] = [];+ for (const id of ruleIdSet) {+ const rule = this._sheetDataValidationModel.getRuleById(unitId, subUnitId, id);+ if (rule) {+ rules.push(rule);+ }+ }return rules;}diff --git a/packages/sheets-data-validation/src/services/dv-validator.service.ts b/packages/sheets-data-validation/src/services/dv-validator.service.tsnew file mode 100644index 0000000000..b1ea9102a0--- /dev/null+++ b/packages/sheets-data-validation/src/services/dv-validator.service.ts@@ -0,0 +1,260 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { IDataValidationRule, IRange, Nullable, ObjectMatrix, Workbook, Worksheet } from '@univerjs/core';+import { bufferDebounceTime, DataValidationStatus, Disposable, getIntersectRange, Inject, IUniverInstanceService, LifecycleService, LifecycleStages, Range, Tools, UniverInstanceType } from '@univerjs/core';+import { bufferWhen, filter, skip } from 'rxjs';+import { SheetDataValidationModel } from '../models/sheet-data-validation-model';+import { DataValidationCacheService } from './dv-cache.service';++export class SheetsDataValidationValidatorService extends Disposable {+ constructor(+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(SheetDataValidationModel) private readonly _sheetDataValidationModel: SheetDataValidationModel,+ @Inject(DataValidationCacheService) private readonly _dataValidationCacheService: DataValidationCacheService,+ @Inject(LifecycleService) private readonly _lifecycleService: LifecycleService+ ) {+ super();+ this._initRecalculate();+ }++ private _initRecalculate() {+ const handleDirtyRanges = (ranges: { unitId: string; subUnitId: string; ranges: IRange[] }[]) => {+ if (ranges.length === 0) {+ return;+ }++ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getActiveSheet();++ const map: Record<string, Record<string, IRange[]>> = {};++ ranges.flat().forEach((range) => {+ if (!map[range.unitId]) {+ map[range.unitId] = {};+ }+ if (!map[range.unitId][range.subUnitId]) {+ map[range.unitId][range.subUnitId] = [];+ }+ const workbook = this._univerInstanceService.getUnit<Workbook>(range.unitId, UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getSheetBySheetId(range.subUnitId);+ if (!worksheet) {+ return;+ }+ map[range.unitId][range.subUnitId].push(...range.ranges.map((range) => Range.transformRange(range, worksheet)));+ });++ Object.entries(map).forEach(([unitId, subUnitMap]) => {+ Object.entries(subUnitMap).forEach(([subUnitId, ranges]) => {+ if (workbook?.getUnitId() === unitId && worksheet?.getSheetId() === subUnitId) {+ this.validatorRanges(unitId, subUnitId, ranges);+ } else {+ requestIdleCallback(() => {+ this.validatorRanges(unitId, subUnitId, ranges);+ });+ }+ });+ });+ };++ this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(bufferWhen(() => this._lifecycleService.lifecycle$.pipe(skip(1), filter((stage) => stage === LifecycleStages.Rendered)))).subscribe(handleDirtyRanges));+ this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(filter(() => this._lifecycleService.stage >= LifecycleStages.Rendered), bufferDebounceTime(20)).subscribe(handleDirtyRanges));+ }++ private async _validatorByCell(workbook: Workbook, worksheet: Worksheet, row: number, col: number) {+ const unitId = workbook.getUnitId();+ const subUnitId = worksheet.getSheetId();+ if (!Tools.isDefine(row) || !Tools.isDefine(col)) {+ throw new Error(`row or col is not defined, row: ${row}, col: ${col}`);+ }++ let _row = row;+ let _col = col;++ const mergedCell = worksheet.getMergedCell(row, col);+ if (mergedCell) {+ _row = mergedCell.startRow;+ _col = mergedCell.startColumn;+ }++ const rule = this._sheetDataValidationModel.getRuleByLocation(unitId, subUnitId, _row, _col);+ if (!rule) {+ return DataValidationStatus.VALID;+ }++ return new Promise<DataValidationStatus>((resolve) => {+ this._sheetDataValidationModel.validator(rule, { unitId, subUnitId, row: _row, col: _col, worksheet, workbook }, (status) => {+ resolve(status);+ });+ });+ }++ async validatorCell(unitId: string, subUnitId: string, row: number, col: number) {+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ throw new Error(`cannot find current workbook, unitId: ${unitId}`);+ }++ const worksheet = workbook.getSheetBySheetId(subUnitId);+ if (!worksheet) {+ throw new Error(`cannot find current worksheet, sheetId: ${subUnitId}`);+ }++ return this._validatorByCell(workbook, worksheet, row, col);+ }++ async validatorRanges(unitId: string, subUnitId: string, ranges: IRange[]) {+ if (!ranges.length) {+ return Promise.resolve([]);+ }++ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ throw new Error(`cannot find current workbook, unitId: ${unitId}`);+ }++ const worksheet = workbook.getSheetBySheetId(subUnitId);+ if (!worksheet) {+ throw new Error(`cannot find current worksheet, sheetId: ${subUnitId}`);+ }++ const allRules = this._sheetDataValidationModel.getRules(unitId, subUnitId);+ const ruleRanges: IRange[] = [];+ for (const rule of allRules) {+ ruleRanges.push(...rule.ranges);+ }++ const intersectRanges: IRange[] = [];+ for (const range of ranges) {+ for (const ruleRange of ruleRanges) {+ const intersect = getIntersectRange(range, ruleRange);+ if (intersect) {+ intersectRanges.push(intersect);+ }+ }+ }++ const mergeCells: Array<{+ resultRowIndex: number;+ resultColIndex: number;+ row: number;+ col: number;+ }> = [];++ const result = await Promise.all(+ intersectRanges.map((range, resultRowIndex) => {+ const promises: Promise<DataValidationStatus>[] = [];+ for (let row = range.startRow; row <= range.endRow; row++) {+ for (let col = range.startColumn; col <= range.endColumn; col++) {+ promises.push(this._validatorByCell(workbook, worksheet, row, col));++ const mergedCell = worksheet.getMergedCell(row, col);+ if (mergedCell) {+ mergeCells.push({+ resultRowIndex,+ resultColIndex: promises.length - 1,+ row: mergedCell.startRow,+ col: mergedCell.startColumn,+ });+ }+ }+ }+ return Promise.all(promises);+ })+ );++ /**+ * If this range has merged cells, the validation status of merged cells should be the same as the main cell, so we need to update the status of merged cells here after all validations are done.+ * Because during the validation process, merged cells are all marked as VALIDATING status in cache.+ */+ if (mergeCells.length) {+ mergeCells.forEach(({ resultRowIndex, resultColIndex, row, col }) => {+ if (result[resultRowIndex][resultColIndex] === DataValidationStatus.VALIDATING) {+ result[resultRowIndex][resultColIndex] = this._dataValidationCacheService.getValue(unitId, subUnitId, row, col) ?? DataValidationStatus.VALID;+ }+ });+ }++ return result;+ }++ async validatorWorksheet(unitId: string, subUnitId: string) {+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ throw new Error(`cannot find current workbook, unitId: ${unitId}`);+ }++ const worksheet = workbook.getSheetBySheetId(subUnitId);+ if (!worksheet) {+ throw new Error(`cannot find current worksheet, sheetId: ${subUnitId}`);+ }+ const rules = this._sheetDataValidationModel.getRules(unitId, subUnitId);+ await Promise.all(+ rules.map((rule) => {+ return Promise.all(+ rule.ranges.map((range) => {+ const promises: Promise<DataValidationStatus>[] = [];+ Range.foreach(range, (row, col) => {+ promises.push(this._validatorByCell(workbook, worksheet, row, col));+ });+ return Promise.all(promises);+ })+ );+ })+ );++ return this._dataValidationCacheService.ensureCache(unitId, subUnitId);+ }++ async validatorWorkbook(unitId: string) {+ const sheetIds = this._sheetDataValidationModel.getSubUnitIds(unitId);+ const results = await Promise.all(sheetIds.map((id) => this.validatorWorksheet(unitId, id)));++ const map: Record<string, ObjectMatrix<Nullable<DataValidationStatus>>> = {};++ results.forEach((result, i) => {+ map[sheetIds[i]] = result;+ });++ return map;+ }++ getDataValidations(unitId: string, subUnitId: string, ranges: IRange[]): IDataValidationRule[] {+ const ruleMatrix = this._sheetDataValidationModel.getRuleObjectMatrix(unitId, subUnitId);+ const ruleIdSet = new Set<string>();+ ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ const ruleId = ruleMatrix.getValue(row, col);+ if (ruleId) {+ ruleIdSet.add(ruleId);+ }+ });+ });++ const rules: IDataValidationRule[] = [];+ for (const id of ruleIdSet) {+ const rule = this._sheetDataValidationModel.getRuleById(unitId, subUnitId, id);+ if (rule) {+ rules.push(rule);+ }+ }+ return rules;+ }++ getDataValidation(unitId: string, subUnitId: string, ranges: IRange[]): Nullable<IDataValidationRule> {+ return this.getDataValidations(unitId, subUnitId, ranges)[0];+ }+}diff --git a/packages/sheets-formula/src/services/formula-ref-range.service.ts b/packages/sheets-formula/src/services/formula-ref-range.service.tsindex 882dcbc48b..569ad9aac9 100644--- a/packages/sheets-formula/src/services/formula-ref-range.service.ts+++ b/packages/sheets-formula/src/services/formula-ref-range.service.ts@@ -275,7 +275,13 @@ export class FormulaRefRangeService extends Disposable {const offsetColumn = currentStartColumn - originStartColumn;for (const range of effectedRanges.ranges) {- const intersectedRange = ranges.map((r) => getIntersectRange(range, r)).filter(Boolean) as IRange[];+ const intersectedRange: IRange[] = [];+ for (const r of ranges) {+ const intersect = getIntersectRange(range, r);+ if (intersect) {+ intersectedRange.push(intersect);+ }+ }if (intersectedRange.length > 0) {intersectedRanges.push(...intersectedRange);}diff --git a/packages/sheets-thread-comment/src/models/sheets-thread-comment.model.ts b/packages/sheets-thread-comment/src/models/sheets-thread-comment.model.tsindex f7b02d14a8..359e46c8b2 100644--- a/packages/sheets-thread-comment/src/models/sheets-thread-comment.model.ts+++ b/packages/sheets-thread-comment/src/models/sheets-thread-comment.model.ts@@ -240,7 +240,14 @@ export class SheetsThreadCommentModel extends Disposable {return [];}- return Array.from(current).map((id) => this.getComment(unitId, subUnitId, id)).filter(Boolean) as IThreadComment[];+ const comments: IThreadComment[] = [];+ for (const id of current) {+ const comment = this.getComment(unitId, subUnitId, id);+ if (comment) {+ comments.push(comment);+ }+ }+ return comments;}getComment(unitId: string, subUnitId: string, commentId: string) {