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
feat(pivot): support pivot table in interceptor & formula (#2923)
ybzkycf8f4922fbbc
diff --git a/packages/design/src/components/checkbox/Checkbox.tsx b/packages/design/src/components/checkbox/Checkbox.tsxindex 770968d9bb..36a11f6936 100644--- a/packages/design/src/components/checkbox/Checkbox.tsx+++ b/packages/design/src/components/checkbox/Checkbox.tsx@@ -60,13 +60,15 @@ export interface ICheckboxProps {* Set the handler to handle `click` event*/onChange?: (value: string | number | boolean) => void;++ contentClassName?: string;}/*** Checkbox Component*/export function Checkbox(props: ICheckboxProps) {- const { children, className, style, checked = false, indeterminate = false, value, disabled = false, onChange } = props;+ const { children, className, style, checked = false, indeterminate = false, value, disabled = false, onChange, contentClassName } = props;const inputRef = useRef<HTMLInputElement>(null);@@ -102,7 +104,7 @@ export function Checkbox(props: ICheckboxProps) {<span className={styles.checkboxTargetInner} /></span>- <span>{children}</span>+ <span className={contentClassName}>{children}</span></label>);}diff --git a/packages/design/src/components/dialog/Dialog.tsx b/packages/design/src/components/dialog/Dialog.tsxindex a2e894c4f1..8dcab84345 100644--- a/packages/design/src/components/dialog/Dialog.tsx+++ b/packages/design/src/components/dialog/Dialog.tsx@@ -20,6 +20,7 @@ import React, { useContext, useRef, useState } from 'react';import type { DraggableData, DraggableEvent, DraggableEventHandler } from 'react-draggable';import Draggable from 'react-draggable';+import type { ModalStyles } from 'rc-dialog/lib/IDialogPropTypes';import { ConfigContext } from '../config-provider/ConfigProvider';import styles from './index.module.less';@@ -92,6 +93,16 @@ export interface IDialogProps {*/mask?: boolean;className?: string;++ /**+ * The style of the customize.+ */+ dialogStyles?: ModalStyles;++ /**+ *+ */+ closable?: boolean;}export function Dialog(props: IDialogProps) {@@ -110,6 +121,8 @@ export function Dialog(props: IDialogProps) {footer,onClose,mask,+ dialogStyles,+ closable,} = props;const [dragDisabled, setDragDisabled] = useState(false);const [positionOffset, setPositionOffset] = useState<{ x: number; y: number } | null>(null);@@ -123,6 +136,7 @@ export function Dialog(props: IDialogProps) {style={{width: '100%',cursor: 'pointer',+ ...dialogStyles?.header,}}onMouseOver={() => {if (dragDisabled) {@@ -207,6 +221,8 @@ export function Dialog(props: IDialogProps) {mask={needMask}style={style}onClose={onClose}+ styles={dialogStyles}+ closable={closable}>{children}</RcDialog>diff --git a/packages/design/src/components/input-number/index.module.less b/packages/design/src/components/input-number/index.module.lessindex 30fab85060..7f5118a3c0 100644--- a/packages/design/src/components/input-number/index.module.less+++ b/packages/design/src/components/input-number/index.module.less@@ -40,7 +40,7 @@display: flex;align-items: center;justify-content: center;-+ flex: 1;text-align: center;}diff --git a/packages/engine-formula/src/engine/dependency/dependency-tree.ts b/packages/engine-formula/src/engine/dependency/dependency-tree.tsindex 86d17fc4dc..805e3d0b57 100644--- a/packages/engine-formula/src/engine/dependency/dependency-tree.ts+++ b/packages/engine-formula/src/engine/dependency/dependency-tree.ts@@ -72,7 +72,7 @@ export class FormulaDependencyTree extends Disposable {isPassive: boolean = true;getDirtyData: Nullable<- (tree: FormulaDependencyTree, dirtyData: IFormulaDirtyData, runtimeData: IAllRuntimeData) => {+ (dirtyData: IFormulaDirtyData, runtimeData: IAllRuntimeData) => {runtimeCellData: IRuntimeUnitDataType;dirtyRanges: IFeatureDirtyRangeType;}diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.tsindex fd897eb822..e8905107ff 100644--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts@@ -18,13 +18,16 @@ import type { IRange, Nullable } from '@univerjs/core';import { Disposable, Inject, LifecycleStages, ObjectMatrix, OnLifecycle } from '@univerjs/core';import { FormulaAstLRU } from '../../basics/cache-lru';-import type { IDirtyUnitSheetNameMap, IFormulaData, IOtherFormulaData, IUnitData } from '../../basics/common';+import type { IDirtyUnitSheetNameMap, IFeatureDirtyRangeType, IFormulaData, IOtherFormulaData, IUnitData } from '../../basics/common';import type { ErrorType } from '../../basics/error-type';import { ERROR_TYPE_SET } from '../../basics/error-type';import { prefixToken, suffixToken } from '../../basics/token';+import type { IFormulaDirtyData } from '../../services/current-data.service';import { IFormulaCurrentConfigService } from '../../services/current-data.service';+import type { IFeatureCalculationManagerParam } from '../../services/feature-calculation-manager.service';import { IFeatureCalculationManagerService } from '../../services/feature-calculation-manager.service';import { IOtherFormulaManagerService } from '../../services/other-formula-manager.service';+import type { IAllRuntimeData } from '../../services/runtime.service';import { IFormulaRuntimeService } from '../../services/runtime.service';import { Lexer } from '../analysis/lexer';import type { LexerNode } from '../analysis/lexer-node';@@ -43,6 +46,12 @@ import { FormulaDependencyTree, FormulaDependencyTreeCache } from './dependency-const FORMULA_CACHE_LRU_COUNT = 100000;+interface IFeatureFormulaParam {+ unitId: string;+ subUnitId: string;+ featureId: string;+}+@OnLifecycle(LifecycleStages.Rendered, FormulaDependencyGenerator)export class FormulaDependencyGenerator extends Disposable {private _updateRangeFlattenCache = new Map<string, Map<string, IRange[]>>();@@ -86,14 +95,23 @@ export class FormulaDependencyGenerator extends Disposable {const updateTreeList = this._getUpdateTreeListAndMakeDependency(treeList, dependencyTreeCache);- const isCycleDependency = this._checkIsCycleDependency(updateTreeList);+ let finalTreeList = this._calculateRunList(updateTreeList);++ const hasFeatureCalculation = this._dependencyFeatureCalculation(finalTreeList);++ if (hasFeatureCalculation) {+ finalTreeList.forEach((tree) => {+ tree.resetState();+ });+ finalTreeList = this._calculateRunList(finalTreeList);+ }++ const isCycleDependency = this._checkIsCycleDependency(finalTreeList);if (isCycleDependency) {this._runtimeService.enableCycleDependency();}- const finalTreeList = this._calculateRunList(updateTreeList);-return Promise.resolve(finalTreeList);}@@ -203,67 +221,38 @@ export class FormulaDependencyGenerator extends Disposable {* which can determine the execution timing of the external application* registration Executor based on the dependency relationship.*/-const featureMap = this._featureCalculationManagerService.getReferenceExecutorMap();featureMap.forEach((subUnitMap, _) => {subUnitMap.forEach((featureMap, _) => {featureMap.forEach((params, featureId) => {- const { unitId, subUnitId, dependencyRanges, getDirtyData } = params;-- if (this._dependencyManagerService.hasFeatureFormulaDependency(unitId, subUnitId, featureId)) {- this._makePassiveDirtyForFeatureFormulas(this._dependencyManagerService.getFeatureFormulaDependency(unitId, subUnitId, featureId)!);- return true;- }-- const FDtree = new FormulaDependencyTree();-- FDtree.unitId = unitId;- FDtree.subUnitId = subUnitId;-- FDtree.getDirtyData = getDirtyData;-- FDtree.featureId = featureId;-- FDtree.rangeList = dependencyRanges.map((range) => {- return {- gridRange: range,- token: serializeRangeToRefString({ ...range, sheetName: this._currentConfigService.getSheetName(range.unitId, range.sheetId) }),- };- });-- this._dependencyManagerService.addFeatureFormulaDependency(unitId, subUnitId, featureId, FDtree);-- this._makePassiveDirtyForFeatureFormulas(FDtree);-- treeList.push(FDtree);+ treeList.push(this._getFeatureFormulaTree(featureId, params));});});});}- private _makePassiveDirtyForFeatureFormulas(tree: FormulaDependencyTree) {- const featureId = tree.featureId;+ private _getFeatureFormulaTree(featureId: string, params: IFeatureCalculationManagerParam) {+ const { unitId, subUnitId, dependencyRanges, getDirtyData } = params;- if (featureId == null) {- tree.isPassive = true;- return;- }+ const FDtree = new FormulaDependencyTree();- const featureMap = this._currentConfigService.getDirtyUnitFeatureMap();+ FDtree.unitId = unitId;+ FDtree.subUnitId = subUnitId;- if (featureMap == null) {- tree.isPassive = true;- return;- }+ FDtree.getDirtyData = getDirtyData;- const featureState = featureMap[tree.unitId]?.[tree.subUnitId]?.[featureId];+ FDtree.featureId = featureId;- if (featureState == null) {- tree.isPassive = true;- return;- }+ FDtree.rangeList = dependencyRanges.map((range) => {+ return {+ gridRange: range,+ token: serializeRangeToRefString({ ...range, sheetName: this._currentConfigService.getSheetName(range.unitId, range.sheetId) }),+ };+ });++ this._dependencyManagerService.addFeatureFormulaDependency(unitId, subUnitId, featureId, FDtree);- tree.isPassive = false;+ return FDtree;}private _registerOtherFormulas(otherFormulaData: IOtherFormulaData, otherFormulaDataKeys: string[], treeList: FormulaDependencyTree[]) {@@ -627,6 +616,114 @@ export class FormulaDependencyGenerator extends Disposable {return newTreeList;}+ private _dependencyFeatureCalculation(newTreeList: FormulaDependencyTree[]) {+ /**+ * Clear the dependency relationships of all featureCalculation nodes in the tree.+ * Because each execution requires rebuilding the reverse dependencies,+ * the previous dependencies may become outdated due to data changes in applications such as pivot tables,+ * which can result in an outdated dirty mark range.+ */+ this._clearFeatureCalculationNode(newTreeList);++ let hasFeatureCalculation = false;++ const featureMap = this._featureCalculationManagerService.getReferenceExecutorMap();+ featureMap.forEach((subUnitMap, _) => {+ subUnitMap.forEach((featureMap, _) => {+ featureMap.forEach((params, featureId) => {+ const { unitId, subUnitId, getDirtyData } = params;+ const allDependency = getDirtyData(this._currentConfigService.getDirtyData() as IFormulaDirtyData, this._runtimeService.getAllRuntimeData() as IAllRuntimeData);+ const dirtyRanges = allDependency.dirtyRanges;+ const dirtyRangesToMap = this._convertDirtyRangesToMap(dirtyRanges);+ const intersectTrees = this._intersectFeatureCalculation(dirtyRangesToMap, newTreeList, { unitId, subUnitId, featureId });+ if (intersectTrees.length > 0) {+ let featureTree = this._getExistTreeList({ unitId, subUnitId, featureId }, newTreeList);+ if (featureTree == null) {+ featureTree = this._getFeatureFormulaTree(featureId, params);+ newTreeList.push(featureTree);+ }+ featureTree.parents = [];+ intersectTrees.forEach((tree) => {+ if (tree.children.includes(featureTree!)) {+ return;+ }+ tree.pushChildren(featureTree!);+ });++ hasFeatureCalculation = true;+ }+ });+ });+ });++ return hasFeatureCalculation;+ }++ private _clearFeatureCalculationNode(newTreeList: FormulaDependencyTree[]) {+ const featureMap = this._featureCalculationManagerService.getReferenceExecutorMap();++ newTreeList.forEach((tree) => {+ tree.children = tree.children.filter((child) => {+ if (!child.featureId) {+ return true;+ }+ if (featureMap.get(tree.unitId)?.get(tree.subUnitId)?.has(child.featureId)) {+ return false;+ }+ return true;+ });++ tree.parents = tree.parents.filter((parent) => {+ if (!parent.featureId) {+ return true;+ }+ if (featureMap.get(tree.unitId)?.get(tree.subUnitId)?.has(parent.featureId)) {+ return false;+ }+ return true;+ });+ });+ }++ private _getExistTreeList(param: IFeatureFormulaParam, treeList: FormulaDependencyTree[]) {+ const { unitId, subUnitId, featureId } = param;+ for (let i = 0, len = treeList.length; i < len; i++) {+ const tree = treeList[i];+ if (tree.unitId === unitId && tree.subUnitId === subUnitId && tree.featureId === featureId) {+ return tree;+ }+ }+ }++ private _convertDirtyRangesToMap(dirtyRanges: IFeatureDirtyRangeType) {+ const map = new Map<string, Map<string, IRange[]>>();+ for (const unitId in dirtyRanges) {+ const unitMap = dirtyRanges[unitId];+ const unitRangeMap = new Map<string, IRange[]>();+ for (const subUnitId in unitMap) {+ const ranges = unitMap[subUnitId];+ unitRangeMap.set(subUnitId, ranges);+ }+ map.set(unitId, unitRangeMap);+ }+ return map;+ }++ private _intersectFeatureCalculation(dirtyRangesToMap: Map<string, Map<string, IRange[]>>, newTreeList: FormulaDependencyTree[], param: IFeatureFormulaParam) {+ const dependencyTree = [];+ for (let i = 0, len = newTreeList.length; i < len; i++) {+ const tree = newTreeList[i];+ if (tree.unitId === param.unitId && tree.subUnitId === param.subUnitId && tree.featureId === param.featureId) {+ continue;+ }+ const isAdded = tree.dependencyRange(dirtyRangesToMap, {});+ if (isAdded) {+ dependencyTree.push(tree);+ }+ }+ return dependencyTree;+ }+private _includeTreeFeature(tree: FormulaDependencyTree) {const unitId = tree.unitId;const subUnitId = tree.subUnitId;diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex bdd3d8b9cf..23fb2ffcd2 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -145,5 +145,4 @@ export {export { SetFormulaDataMutation, type ISetFormulaDataMutationParams } from './commands/mutations/set-formula-data.mutation';export { SetOtherFormulaMutation, RemoveOtherFormulaMutation, type ISetOtherFormulaMutationParams, type IRemoveOtherFormulaMutationParams } from './commands/mutations/set-other-formula.mutation';export { SetSuperTableMutation, RemoveSuperTableMutation, SetSuperTableOptionMutation } from './commands/mutations/set-super-table.mutation';-// #endregiondiff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.tsindex 7a2f31ad06..274ec30cfe 100644--- a/packages/engine-formula/src/services/calculate-formula.service.ts+++ b/packages/engine-formula/src/services/calculate-formula.service.ts@@ -286,7 +286,7 @@ export class CalculateFormulaService extends Disposable {* and return the dirty area marked by the feature,* so as to allow the formulas depending on the dirty area to continue the calculation.*/- const { runtimeCellData, dirtyRanges } = getDirtyData(tree, this._currentConfigService.getDirtyData(), this._runtimeService.getAllRuntimeData());+ const { runtimeCellData, dirtyRanges } = getDirtyData(this._currentConfigService.getDirtyData(), this._runtimeService.getAllRuntimeData());this._runtimeService.setRuntimeFeatureCellData(tree.featureId, runtimeCellData);diff --git a/packages/engine-formula/src/services/feature-calculation-manager.service.ts b/packages/engine-formula/src/services/feature-calculation-manager.service.tsindex aa23a322a8..36ac9cbb2d 100644--- a/packages/engine-formula/src/services/feature-calculation-manager.service.ts+++ b/packages/engine-formula/src/services/feature-calculation-manager.service.ts@@ -21,7 +21,6 @@ import type { Observable } from 'rxjs';import { Subject } from 'rxjs';import type { IFeatureDirtyRangeType, IRuntimeUnitDataType } from '../basics/common';import type { IRemoveFeatureCalculationMutationParam } from '../commands/mutations/set-feature-calculation.mutation';-import type { FormulaDependencyTree } from '../engine/dependency/dependency-tree';import type { IAllRuntimeData } from './runtime.service';import type { IFormulaDirtyData } from './current-data.service';@@ -29,7 +28,7 @@ export interface IFeatureCalculationManagerParam {unitId: string;subUnitId: string;dependencyRanges: IUnitRange[];- getDirtyData: (tree: FormulaDependencyTree, dirtyData: IFormulaDirtyData, runtimeData: IAllRuntimeData) => {+ getDirtyData: (dirtyData: IFormulaDirtyData, runtimeData: IAllRuntimeData) => {runtimeCellData: IRuntimeUnitDataType;dirtyRanges: IFeatureDirtyRangeType;};diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.tsindex 4b35d7604a..050bfa32b6 100644--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts@@ -14,11 +14,11 @@* limitations under the License.*/-import type { IMutationInfo, Workbook } from '@univerjs/core';import { Disposable, Inject, Injector, IUniverInstanceService, LifecycleStages, OnLifecycle, Rectangle, UniverInstanceType } from '@univerjs/core';+import type { IMutationInfo, IRange, Workbook } from '@univerjs/core';import { ClearSelectionAllCommand, ClearSelectionFormatCommand, RangeMergeUtil, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';import { ConditionalFormattingRuleModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory } from '@univerjs/sheets-conditional-formatting';-import type { IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';+import type { IConditionalFormattingRuleConfig, IConditionFormattingRule, IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';@OnLifecycle(LifecycleStages.Rendered, ConditionalFormattingClearController)export class ConditionalFormattingClearController extends Disposable {@@ -51,45 +51,76 @@ export class ConditionalFormattingClearController extends Disposable {if (!worksheet) {return defaultV;}+ const unitId = workbook.getUnitId();+ const subUnitId = worksheet.getSheetId();- const allRules = this._conditionalFormattingRuleModel.getSubunitRules(workbook.getUnitId(), worksheet.getSheetId());+ const allRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);if (!allRules || !allRules.length) {return defaultV;}- allRules.filter((rule) => {- return ranges.some((range) => rule.ranges.some((ruleRange) => Rectangle.getIntersects(ruleRange, range)));- }).forEach((rule) => {- const mergeUtil = new RangeMergeUtil();- const mergeRanges = mergeUtil.add(...rule.ranges).subtract(...ranges).merge();- if (mergeRanges.length) {- const redo: IMutationInfo<ISetConditionalRuleMutationParams> = {- id: SetConditionalRuleMutation.id,- params: {- unitId: workbook.getUnitId(),- subUnitId: worksheet.getSheetId(),- rule: { ...rule, ranges: mergeRanges },- },- };- const undo = setConditionalRuleMutationUndoFactory(this._injector, redo.params);- redos.push(redo);- undos.push(...undo);- } else {- const redo: IMutationInfo<IDeleteConditionalRuleMutationParams> = {- id: DeleteConditionalRuleMutation.id,- params: {- unitId: workbook.getUnitId(),- subUnitId: worksheet.getSheetId(),- cfId: rule.cfId,- },- };- const undo = DeleteConditionalRuleMutationUndoFactory(this._injector, redo.params);- redos.push(redo);- undos.push(...undo);- }- });+ const { redos: interceptRedos, undos: interceptUndos } = generateClearCfMutations(this._injector, allRules, ranges, unitId, subUnitId);+ redos.push(...interceptRedos);+ undos.push(...interceptUndos);}return defaultV;},}));++ this.disposeWithMe(this._sheetInterceptorService.interceptRanges({+ getMutations: ({ unitId, subUnitId, ranges }) => {+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];+ const emptyInterceptorArr = { redos, undos };+ if (!ranges || !ranges.length) {+ return emptyInterceptorArr;+ }+ const allRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);+ if (!allRules || !allRules.length) {+ return emptyInterceptorArr;+ }+ const { redos: interceptRedos, undos: interceptUndos } = generateClearCfMutations(this._injector, allRules, ranges, unitId, subUnitId);+ redos.push(...interceptRedos);+ undos.push(...interceptUndos);++ return emptyInterceptorArr;+ },+ }));}}++export function generateClearCfMutations(injector: Injector, allRules: IConditionFormattingRule<IConditionalFormattingRuleConfig>[], ranges: IRange[], unitId: string, subUnitId: string) {+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];+ allRules.filter((rule) => {+ return ranges.some((range) => rule.ranges.some((ruleRange) => Rectangle.getIntersects(ruleRange, range)));+ }).forEach((rule) => {+ const mergeUtil = new RangeMergeUtil();+ const mergeRanges = mergeUtil.add(...rule.ranges).subtract(...ranges).merge();+ if (mergeRanges.length) {+ const redo: IMutationInfo<ISetConditionalRuleMutationParams> = {+ id: SetConditionalRuleMutation.id,+ params: {+ unitId,+ subUnitId,+ rule: { ...rule, ranges: mergeRanges },+ },+ };+ const undo = setConditionalRuleMutationUndoFactory(injector, redo.params);+ redos.push(redo);+ undos.push(...undo);+ } else {+ const redo: IMutationInfo<IDeleteConditionalRuleMutationParams> = {+ id: DeleteConditionalRuleMutation.id,+ params: {+ unitId,+ subUnitId,+ cfId: rule.cfId,+ },+ };+ const undo = DeleteConditionalRuleMutationUndoFactory(injector, redo.params);+ redos.push(redo);+ undos.push(...undo);+ }+ });+ return { redos, undos };+}diff --git a/packages/sheets-numfmt/src/controllers/numfmt.cell-content.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.cell-content.controller.tsindex f49e8b6102..7f9f930668 100644--- a/packages/sheets-numfmt/src/controllers/numfmt.cell-content.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt.cell-content.controller.ts@@ -59,7 +59,16 @@ export class SheetsNumfmtCellContentController extends Disposable {handler: (cell, location, next) => {const unitId = location.unitId;const sheetId = location.subUnitId;- const numfmtValue = this._numfmtService.getValue(unitId, sheetId, location.row, location.col);+ let numfmtValue;+ if (cell?.s) {+ const style = location.workbook.getStyles().get(cell.s);+ if (style?.n) {+ numfmtValue = style.n;+ }+ }+ if (!numfmtValue) {+ numfmtValue = this._numfmtService.getValue(unitId, sheetId, location.row, location.col);+ }if (!numfmtValue) {return next(cell);}@@ -75,7 +84,7 @@ export class SheetsNumfmtCellContentController extends Disposable {let numfmtRes: string = '';const cache = renderCache.getValue(location.row, location.col);- if (cache && cache.parameters === originCellValue.v) {+ if (cache && cache.parameters === `${originCellValue.v}_${numfmtValue.pattern}`) {return next({ ...cell, ...cache.result });}@@ -96,7 +105,7 @@ export class SheetsNumfmtCellContentController extends Disposable {renderCache.setValue(location.row, location.col, {result: res,- parameters: originCellValue.v as number,+ parameters: `${originCellValue.v}_${numfmtValue.pattern}`,});return next({ ...cell, ...res });diff --git a/packages/sheets-numfmt/src/menu/menu.ts b/packages/sheets-numfmt/src/menu/menu.tsindex 27540302c4..bfe52d53ba 100644--- a/packages/sheets-numfmt/src/menu/menu.ts+++ b/packages/sheets-numfmt/src/menu/menu.ts@@ -124,7 +124,7 @@ export const FactoryOtherMenuItem = (accessor: IAccessor): IMenuSelectorItem =>const row = range.startRow;const col = range.startColumn;- const numfmtValue = numfmtService.getValue(workbook.getUnitId(), worksheet.getSheetId(), row, col);+ const numfmtValue = workbook.getStyles().get(worksheet.getCell(row, col)?.s)?.n;const pattern = numfmtValue?.pattern;let value: string = localeService.t('sheet.numfmt.general');diff --git a/packages/sheets-ui/src/controllers/utils/selections-tools.ts b/packages/sheets-ui/src/controllers/utils/selections-tools.tsindex 09b119a20d..06033a81b9 100644--- a/packages/sheets-ui/src/controllers/utils/selections-tools.ts+++ b/packages/sheets-ui/src/controllers/utils/selections-tools.ts@@ -17,7 +17,7 @@import type { IAccessor, Workbook } from '@univerjs/core';import { IUniverInstanceService, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';import type { ISelectionWithStyle } from '@univerjs/sheets';-import { RangeProtectionRuleModel, SheetsSelectionsService } from '@univerjs/sheets';+import { MERGE_CELL_INTERCEPTOR_CHECK, MergeCellController, RangeProtectionRuleModel, SheetsSelectionsService } from '@univerjs/sheets';import { combineLatest, map } from 'rxjs';export function getSheetSelectionsDisabled$(accessor: IAccessor) {@@ -27,6 +27,8 @@ export function getSheetSelectionsDisabled$(accessor: IAccessor) {const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const unitId = workbook.getUnitId();+ const mergeCellController = accessor.get(MergeCellController);+return combineLatest([selectionManagerService.selectionMoveEnd$,workbook.activeSheet$,@@ -35,6 +37,14 @@ export function getSheetSelectionsDisabled$(accessor: IAccessor) {if (!sheet) return false;if (!selection || selection.length === 0) return false;const subUnitId = sheet.getSheetId();++ const selectionRanges = selection.map((sel) => sel.range);+ const withPivot = mergeCellController.interceptor.fetchThroughInterceptors(MERGE_CELL_INTERCEPTOR_CHECK)(false, selectionRanges);++ if (withPivot) {+ return true;+ }+const subUnitRuleRange = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).map((rule) => rule.ranges).flat();diff --git a/packages/sheets/src/commands/commands/insert-row-col.command.ts b/packages/sheets/src/commands/commands/insert-row-col.command.tsindex 47bca83c0a..2f424182bf 100644--- a/packages/sheets/src/commands/commands/insert-row-col.command.ts+++ b/packages/sheets/src/commands/commands/insert-row-col.command.ts@@ -101,6 +101,15 @@ export const InsertRowCommand: ICommand = {insertRowParams);+ const canPerform = await sheetInterceptorService.beforeCommandExecute({+ id: InsertRowCommand.id,+ params: insertRowParams,+ });++ if (!canPerform) {+ return false;+ }+const redos: IMutationInfo[] = [{ id: InsertRowMutation.id, params: insertRowParams }];const undos: IMutationInfo[] = [{ id: RemoveRowMutation.id, params: undoRowInsertionParams }];@@ -284,10 +293,19 @@ export const InsertColCommand: ICommand<IInsertColCommandParams> = {hd: BooleanNumber.FALSE,})),};+const undoColInsertionParams: IRemoveColMutationParams = InsertColMutationUndoFactory(accessor,insertColParams);+ const canPerform = await sheetInterceptorService.beforeCommandExecute({+ id: InsertColCommand.id,+ params: insertColParams,+ });++ if (!canPerform) {+ return false;+ }const redos: IMutationInfo[] = [{ id: InsertColMutation.id, params: insertColParams }];const undos: IMutationInfo[] = [{ id: RemoveColMutation.id, params: undoColInsertionParams }];diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.tsindex a0c3831bf2..0a501ffa3d 100644--- a/packages/sheets/src/commands/commands/move-range.command.ts+++ b/packages/sheets/src/commands/commands/move-range.command.ts@@ -45,16 +45,23 @@ export const MoveRangeCommandId = 'sheet.command.move-range';export const MoveRangeCommand: ICommand = {type: CommandType.COMMAND,id: MoveRangeCommandId,- handler: (accessor: IAccessor, params: IMoveRangeCommandParams) => {+ handler: async (accessor: IAccessor, params: IMoveRangeCommandParams) => {const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);const univerInstanceService = accessor.get(IUniverInstanceService);const errorService = accessor.get(ErrorService);const localeService = accessor.get(LocaleService);+ const sheetInterceptorService = accessor.get(SheetInterceptorService);const target = getSheetCommandTarget(univerInstanceService);if (!target) return false;+ const perform = await sheetInterceptorService.beforeCommandExecute({ id: MoveRangeCommand.id, params });++ if (!perform) {+ return false;+ }+const { worksheet, subUnitId, unitId } = target;const moveRangeMutations = getMoveRangeUndoRedoMutations(accessor,@@ -66,7 +73,6 @@ export const MoveRangeCommand: ICommand = {return false;}- const sheetInterceptorService = accessor.get(SheetInterceptorService);const interceptorCommands = sheetInterceptorService.onCommandExecute({id: MoveRangeCommand.id,params: { ...params },diff --git a/packages/sheets/src/commands/commands/remove-row-col.command.ts b/packages/sheets/src/commands/commands/remove-row-col.command.tsindex 744f013e67..ce00bb504e 100644--- a/packages/sheets/src/commands/commands/remove-row-col.command.ts+++ b/packages/sheets/src/commands/commands/remove-row-col.command.ts@@ -100,6 +100,15 @@ export const RemoveRowCommand: ICommand<IRemoveRowColCommandParams> = {ranges.push(totalRange);}+ const canPerform = await sheetInterceptorService.beforeCommandExecute({+ id: RemoveRowCommand.id,+ params: { range: totalRange } as IRemoveRowColCommandParams,+ });++ if (!canPerform) {+ return false;+ }+const redos: IMutationInfo[] = [];const undos: IMutationInfo[] = [];@@ -204,6 +213,16 @@ export const RemoveColCommand: ICommand = {subUnitId,cellValue: removedCols.getMatrix(),};++ const canPerform = await sheetInterceptorService.beforeCommandExecute({+ id: RemoveColCommand.id,+ params: { range } as IRemoveRowColCommandParams,+ });++ if (!canPerform) {+ return false;+ }+const intercepted = sheetInterceptorService.onCommandExecute({id: RemoveColCommand.id,params: { range } as IRemoveRowColCommandParams,diff --git a/packages/sheets/src/controllers/merge-cell.controller.ts b/packages/sheets/src/controllers/merge-cell.controller.tsindex 33eb5c14a8..efcc1f384e 100644--- a/packages/sheets/src/controllers/merge-cell.controller.ts+++ b/packages/sheets/src/controllers/merge-cell.controller.ts@@ -16,12 +16,14 @@import type { ICommandInfo, IMutationInfo, IRange, Workbook } from '@univerjs/core';import {+ createInterceptorKey,Dimension,Disposable,DisposableCollection,ICommandService,Inject,Injector,+ InterceptorManager,IUniverInstanceService,LifecycleStages,OnLifecycle,@@ -73,6 +75,7 @@ import { MoveColsMutation, MoveRowsMutation } from '../commands/mutations/move-rimport { InsertColMutation, InsertRowMutation } from '../commands/mutations/insert-row-col.mutation';import { RemoveColMutation, RemoveRowMutation } from '../commands/mutations/remove-row-col.mutation';import type { IMoveColsCommandParams, IMoveRowsCommandParams } from '../commands/commands/move-rows-cols.command';+import { getSheetCommandTarget } from '../commands/commands/utils/target-util';const mutationIdByRowCol = [InsertColMutation.id, InsertRowMutation.id, RemoveColMutation.id, RemoveRowMutation.id];const mutationIdArrByMove = [MoveRowsMutation.id, MoveColsMutation.id];@@ -118,9 +121,14 @@ export function getAddMergeMutationRangeByType(selection: IRange[], type?: Dimenreturn ranges;}+export const MERGE_CELL_INTERCEPTOR_CHECK = createInterceptorKey<boolean, IRange[]>('mergeCellPermissionCheck');+@OnLifecycle(LifecycleStages.Steady, MergeCellController)export class MergeCellController extends Disposable {disposableCollection = new DisposableCollection();++ public readonly interceptor = new InterceptorManager({ MERGE_CELL_INTERCEPTOR_CHECK });+constructor(@Inject(ICommandService) private readonly _commandService: ICommandService,@Inject(RefRangeService) private readonly _refRangeService: RefRangeService,@@ -180,6 +188,45 @@ export class MergeCellController extends Disposable {return { redos: [], undos: [] };},});++ this._sheetInterceptorService.interceptRanges({+ getMutations: ({ unitId, subUnitId, ranges }) => {+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];+ const emptyInterceptorArr = { redos, undos };+ if (!ranges || !ranges.length) {+ return emptyInterceptorArr;+ }+ const target = getSheetCommandTarget(this._univerInstanceService, { unitId, subUnitId });+ if (!target) {+ return emptyInterceptorArr;+ }+ const { worksheet } = target;+ const mergeData = worksheet.getMergeData();+ const overlapRanges = mergeData.filter((item) => ranges.some((range) => Rectangle.intersects(item, range)));+ if (overlapRanges.length) {+ redos.push({+ id: RemoveWorksheetMergeMutation.id,+ params: {+ unitId,+ subUnitId,+ ranges: overlapRanges,+ },+ });+ undos.push({+ id: AddWorksheetMergeMutation.id,+ params: {+ unitId,+ subUnitId,+ ranges: overlapRanges,+ },+ });+ return { undos, redos };+ }++ return emptyInterceptorArr;+ },+ });}refRangeHandle(config: EffectRefRangeParams, unitId: string, subUnitId: string) {diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex 2320989458..33b18c7442 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -97,7 +97,7 @@ export {export { INTERCEPTOR_POINT } from './services/sheet-interceptor/interceptor-const';export { SheetInterceptorService } from './services/sheet-interceptor/sheet-interceptor.service';export type { ISheetLocation, ISheetLocationBase, ISheetRowLocation } from './services/sheet-interceptor/utils/interceptor';-export { MergeCellController } from './controllers/merge-cell.controller';+export { MergeCellController, MERGE_CELL_INTERCEPTOR_CHECK } from './controllers/merge-cell.controller';export { AddMergeRedoSelectionsOperationFactory, AddMergeUndoSelectionsOperationFactory } from './commands/utils/handle-merge-operation';export type { FormatType } from './services/numfmt/type';@@ -165,7 +165,7 @@ export {export { RangeProtectionPermissionEditPoint } from './services/permission/permission-point/range/edit';export { RangeProtectionPermissionViewPoint } from './services/permission/permission-point/range/view';-export { generateNullCellValue } from './basics/utils';+export { generateNullCellValue, generateNullCell } from './basics/utils';// #region - all commandsdiff --git a/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts b/packages/sheets/src/services/__tests__/ref-range.setvice.spec.tsindex 42e93ff11b..4e3c8705f6 100644--- a/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts+++ b/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts@@ -71,20 +71,20 @@ describe('Test ref-range.service', () => {univer.dispose();});- it('test registerRefRange', () => {+ it('test registerRefRange', async () => {const mockFn = vi.fn(() => ({ redos: [], undos: [] }));refRangeService.registerRefRange(originRange, mockFn);const params: IMoveRangeCommandParams = {fromRange: { ...originRange },toRange: { startRow: 4, endRow: 4, startColumn: 4, endColumn: 4 },};- commandService.executeCommand(MoveRangeCommand.id, params);+ await commandService.executeCommand(MoveRangeCommand.id, params);expect(mockFn.mock.calls.length).toBe(1);const callParams = (mockFn.mock.calls as any)[0][0];expect(callParams?.id).toBe('sheet.command.move-range');});- it('test registerRefRange 3', () => {+ it('test registerRefRange 3', async () => {const redoMutationId = 'test-redo-mutation';const undoMutationId = 'test-undo-mutation';@@ -114,7 +114,7 @@ describe('Test ref-range.service', () => {fromRange: { startRow: 2, endRow: 4, startColumn: 2, endColumn: 2 },toRange: { startRow: 3, endRow: 5, startColumn: 2, endColumn: 2 },};- commandService.executeCommand(MoveRangeCommand.id, params);+ await commandService.executeCommand(MoveRangeCommand.id, params);expect(mockFn1.mock.calls.length).toBe(1);expect(mockFn2.mock.calls.length).toBe(1);@@ -124,7 +124,7 @@ describe('Test ref-range.service', () => {expect(result.redos.length).toBe(3);});- it('test merge mutation', () => {+ it('test merge mutation', async () => {const redoMutationId = 'test-redo-mutation';const undoMutationId = 'test-undo-mutation';@@ -178,7 +178,7 @@ describe('Test ref-range.service', () => {fromRange: { startRow: 2, endRow: 4, startColumn: 2, endColumn: 2 },toRange: { startRow: 3, endRow: 5, startColumn: 2, endColumn: 2 },};- commandService.executeCommand(MoveRangeCommand.id, params);+ await commandService.executeCommand(MoveRangeCommand.id, params);const result = sheetInterceptorService.onCommandExecute({ id: MoveRangeCommand.id, params });expect((result as any).redos.length).toBe(1);expect((result as any).redos[0].params.values.length).toBe(9);diff --git a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.tsindex 806ef16cef..3c1f346c03 100644--- a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts+++ b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts@@ -19,6 +19,7 @@ import type {ICommandInfo,IDisposable,IInterceptor,+ IRange,IUndoRedoCommandInfosByInterceptor,Nullable,Workbook,@@ -38,11 +39,27 @@ import {import { INTERCEPTOR_POINT } from './interceptor-const';+export interface IBeforeCommandInterceptor {+ priority?: number;+ performCheck(info: ICommandInfo): Promise<boolean>;+}+export interface ICommandInterceptor {priority?: number;getMutations(command: ICommandInfo): IUndoRedoCommandInfosByInterceptor;}+export interface IRangesInfo {+ unitId: string;+ subUnitId: string;+ ranges: IRange[];+}++export interface IRangeInterceptors {+ priority?: number;+ getMutations(rangesInfo: IRangesInfo): IUndoRedoCommandInfosByInterceptor;+}+/*** This class expose methods for sheet features to inject code to sheet underlying logic.*@@ -52,6 +69,9 @@ export interface ICommandInterceptor {export class SheetInterceptorService extends Disposable {private _interceptorsByName: Map<string, Array<IInterceptor<unknown, unknown>>> = new Map();private _commandInterceptors: ICommandInterceptor[] = [];+ private _rangeInterceptors: IRangeInterceptors[] = [];++ private _beforeCommandInterceptor: IBeforeCommandInterceptor[] = [];private readonly _workbookDisposables = new Map<string, IDisposable>();private readonly _worksheetDisposables = new Map<string, IDisposable>();@@ -102,13 +122,63 @@ export class SheetInterceptorService extends Disposable {return this.disposeWithMe(toDisposable(() => remove(this._commandInterceptors, interceptor)));}+ // Add a listener function to the command, which will be run before the command is run to get whether it can be executed the command+ interceptBeforeCommand(interceptor: IBeforeCommandInterceptor): IDisposable {+ if (this._beforeCommandInterceptor.includes(interceptor)) {+ throw new Error('[SheetInterceptorService]: Interceptor already exists!');+ }++ this._beforeCommandInterceptor.push(interceptor);+ this._beforeCommandInterceptor.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));++ return this.disposeWithMe(toDisposable(() => remove(this._beforeCommandInterceptor, interceptor)));+ }++ /**+ * before command execute, call this method to get the flag of whether it can be executed the command,+ * @param info ICommandInfo+ * @returns Promise<boolean>+ */+ async beforeCommandExecute(info: ICommandInfo): Promise<boolean> {+ const allPerformCheckRes = await Promise.all(this._beforeCommandInterceptor.map((i) => i.performCheck(info)));+ return allPerformCheckRes.every((perform) => perform);+ }++ /**+ * By adding callbacks to some Ranges can get some additional mutations, such as clearing all plugin data in a certain area.+ * @param interceptor IRangeInterceptors+ * @returns IDisposable+ */+ interceptRanges(interceptor: IRangeInterceptors): IDisposable {+ if (this._rangeInterceptors.includes(interceptor)) {+ throw new Error('[SheetInterceptorService]: Interceptor already exists!');+ }++ this._rangeInterceptors.push(interceptor);+ this._rangeInterceptors.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));++ return this.disposeWithMe(toDisposable(() => remove(this._rangeInterceptors, interceptor)));+ }+/*** When command is executing, call this method to gether undo redo mutations from upper features.* @param command* @returns*/- onCommandExecute(command: ICommandInfo): IUndoRedoCommandInfosByInterceptor {- const infos = this._commandInterceptors.map((i) => i.getMutations(command));++ onCommandExecute(info: ICommandInfo): IUndoRedoCommandInfosByInterceptor {+ const infos = this._commandInterceptors.map((i) => i.getMutations(info));++ return {+ preUndos: infos.map((i) => i.preUndos ?? []).flat(),+ undos: infos.map((i) => i.undos).flat(),+ preRedos: infos.map((i) => i.preRedos ?? []).flat(),+ redos: infos.map((i) => i.redos).flat(),+ };+ }++ generateMutationsByRanges(info: IRangesInfo): IUndoRedoCommandInfosByInterceptor {+ const infos = this._rangeInterceptors.map((i) => i.getMutations(info));return {preUndos: infos.map((i) => i.preUndos ?? []).flat(),diff --git a/packages/ui/src/services/sidebar/desktop-sidebar.service.ts b/packages/ui/src/services/sidebar/desktop-sidebar.service.tsindex 57e7e7e6b8..258d0a574e 100644--- a/packages/ui/src/services/sidebar/desktop-sidebar.service.ts+++ b/packages/ui/src/services/sidebar/desktop-sidebar.service.ts@@ -30,6 +30,7 @@ export class DesktopSidebarService implements ISidebarService {open(params: ISidebarMethodOptions): IDisposable {this._sidebarOptions = {...params,+ id: params.id,visible: true,};@@ -40,12 +41,14 @@ export class DesktopSidebarService implements ISidebarService {});}- close() {+ close(id?: string) {+ if (id && this._sidebarOptions.id !== id) {+ return;+ }this._sidebarOptions = {...this._sidebarOptions,visible: false,};-this.sidebarOptions$.next(this._sidebarOptions);this._sidebarOptions.onClose && this._sidebarOptions.onClose();}diff --git a/packages/ui/src/services/sidebar/sidebar.service.ts b/packages/ui/src/services/sidebar/sidebar.service.tsindex 1aaa8dc786..976d7741bd 100644--- a/packages/ui/src/services/sidebar/sidebar.service.ts+++ b/packages/ui/src/services/sidebar/sidebar.service.ts@@ -27,5 +27,5 @@ export interface ISidebarService {readonly scrollEvent$: Subject<Event>;open(params: ISidebarMethodOptions): IDisposable;- close(): void;+ close(id?: string): void;}diff --git a/packages/ui/src/views/components/sidebar/interface.ts b/packages/ui/src/views/components/sidebar/interface.tsindex 603a5a53a2..9410ba290b 100644--- a/packages/ui/src/views/components/sidebar/interface.ts+++ b/packages/ui/src/views/components/sidebar/interface.ts@@ -17,6 +17,7 @@import type { ICustomLabelProps } from '../../../components/custom-label/CustomLabel';export interface ISidebarMethodOptions {+ id?: string;header?: ICustomLabelProps;children?: ICustomLabelProps;footer?: ICustomLabelProps;