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: improve undo redo history handling (#7416)
Univer9f0cad68f82e
diff --git a/packages/core/src/__tests__/univer-skeleton.spec.ts b/packages/core/src/__tests__/univer-skeleton.spec.tsindex 9c8cd93505..4a05f9ffaf 100644--- a/packages/core/src/__tests__/univer-skeleton.spec.ts+++ b/packages/core/src/__tests__/univer-skeleton.spec.ts@@ -18,11 +18,14 @@ import type { ILocales } from '../shared/locale';import { defaultTheme } from '@univerjs/themes';import { describe, expect, it, vi } from 'vitest';import { Injector } from '../common/di';+import { UniverInstanceType } from '../common/unit';import { COMMAND_LOG_EXECUTION_CONFIG_KEY } from '../services/command/command.service';import { IConfigService } from '../services/config/config.service';+import { IUniverInstanceService } from '../services/instance/instance.service';import { LocaleService } from '../services/locale/locale.service';import { LogLevel } from '../services/log/log.service';import { RegionService } from '../services/region/region.service';+import { IUndoRedoService, UNDO_REDO_HISTORY_LIMIT_CONFIG_KEY } from '../services/undoredo/undoredo.service';import { Skeleton } from '../skeleton';import { LocaleType } from '../types/enum/locale-type';import { Univer } from '../univer';@@ -61,6 +64,7 @@ describe('Univer', () => {direction: 'rtl',logLevel: LogLevel.VERBOSE,logCommandExecution: true,+ undoRedoHistoryLimit: 12,});const injector = univer.__getInjector();@@ -72,6 +76,7 @@ describe('Univer', () => {expect(localeService.getDirection()).toBe('rtl');expect(localeService.t('test.greeting', 'Univer')).toBe('Hello Univer');expect(injector.get(IConfigService).getConfig(COMMAND_LOG_EXECUTION_CONFIG_KEY)).toBe(true);+ expect(injector.get(IConfigService).getConfig(UNDO_REDO_HISTORY_LIMIT_CONFIG_KEY)).toBe(12);univer.setLocale(LocaleType.ZH_CN);expect(localeService.getCurrentLocale()).toBe(LocaleType.ZH_CN);@@ -84,6 +89,33 @@ describe('Univer', () => {univer.dispose();});+ it('should apply the configured undo redo history limit', () => {+ const unitId = 'undo-redo-limit-doc';+ const univer = new Univer({ undoRedoHistoryLimit: 2 });+ univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: unitId });++ const injector = univer.__getInjector();+ injector.get(IUniverInstanceService).focusUnit(unitId);+ const undoRedoService = injector.get(IUndoRedoService);++ for (let i = 0; i < 3; i++) {+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ undoMutations: [],+ redoMutations: [],+ id: `item-${i}`,+ });+ }++ expect(undoRedoService.pitchTopUndoElement()?.id).toBe('item-2');+ undoRedoService.popUndoToRedo();+ expect(undoRedoService.pitchTopUndoElement()?.id).toBe('item-1');+ undoRedoService.popUndoToRedo();+ expect(undoRedoService.pitchTopUndoElement()).toBeNull();++ univer.dispose();+ });+it('should support add/remove dispose callbacks', () => {const univer = new Univer();const removedCallback = vi.fn();diff --git a/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.tsindex a7315761b4..0970f020e9 100644--- a/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts+++ b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts@@ -25,7 +25,13 @@ import { EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHEET } from '../../import { ContextService, IContextService } from '../../context/context.service';import { IUniverInstanceService } from '../../instance/instance.service';import { DesktopLogService, ILogService, LogLevel } from '../../log/log.service';-import { IUndoRedoService, LocalUndoRedoService, RedoCommandId, UndoCommandId } from '../undoredo.service';+import {+ DEFAULT_UNDO_REDO_HISTORY_LIMIT,+ IUndoRedoService,+ LocalUndoRedoService,+ RedoCommandId,+ UndoCommandId,+} from '../undoredo.service';const MUTATION_ID = 'test.mutation';@@ -120,6 +126,105 @@ describe('LocalUndoRedoService', () => {expect(statuses.at(-1)).toEqual({ undos: 1, redos: 0 });});+ it('should retain 50 undo items by default', () => {+ expect(DEFAULT_UNDO_REDO_HISTORY_LIMIT).toBe(50);++ for (let i = 0; i <= DEFAULT_UNDO_REDO_HISTORY_LIMIT; i++) {+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [],+ redoMutations: [],+ id: `item-${i}`,+ });+ }++ const itemIds: string[] = [];+ for (let i = 0; i < DEFAULT_UNDO_REDO_HISTORY_LIMIT; i++) {+ const item = undoRedoService.pitchTopUndoElement();+ if (item?.id) {+ itemIds.push(item.id);+ }+ undoRedoService.popUndoToRedo();+ }++ expect(itemIds).toHaveLength(DEFAULT_UNDO_REDO_HISTORY_LIMIT);+ expect(itemIds.at(-1)).toBe('item-1');+ expect(undoRedoService.pitchTopUndoElement()).toBeNull();+ });++ it('should group consecutive scopes without exposing the group on history items', () => {+ const replaceGroup = undoRedoService.beginUndoRedoGroup('unit-1', 'property');+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-first' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-first' } }],+ });+ replaceGroup.dispose();++ const nextReplaceGroup = undoRedoService.beginUndoRedoGroup('unit-1', 'property');+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-latest' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-latest' } }],+ });+ nextReplaceGroup.dispose();++ expect(undoRedoService.pitchTopUndoElement()).toEqual(expect.objectContaining({+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-first' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-latest' } }],+ }));++ const appendGroup = undoRedoService.beginUndoRedoGroup('unit-1', 'compound', 'append');+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-text' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-text' } }],+ });+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-size' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-size' } }],+ });+ appendGroup.dispose();++ expect(undoRedoService.pitchTopUndoElement()).toEqual(expect.objectContaining({+ undoMutations: [+ { id: MUTATION_ID, params: { label: 'undo-size' } },+ { id: MUTATION_ID, params: { label: 'undo-text' } },+ ],+ redoMutations: [+ { id: MUTATION_ID, params: { label: 'redo-text' } },+ { id: MUTATION_ID, params: { label: 'redo-size' } },+ ],+ }));+ });++ it('should start a new group after undo and redo', () => {+ const group = undoRedoService.beginUndoRedoGroup('unit-1', 'property');+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-first' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-first' } }],+ });+ group.dispose();++ undoRedoService.popUndoToRedo();+ undoRedoService.popRedoToUndo();++ const nextGroup = undoRedoService.beginUndoRedoGroup('unit-1', 'property');+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-second' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-second' } }],+ });+ nextGroup.dispose();++ undoRedoService.popUndoToRedo();+ expect(undoRedoService.pitchTopUndoElement()?.redoMutations).toEqual([+ { id: MUTATION_ID, params: { label: 'redo-first' } },+ ]);+ });+it('should execute undo and redo commands against registered mutations', () => {undoRedoService.pushUndoRedo({unitID: 'unit-1',diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.tsindex 3e81ee43fc..92fbc9ea50 100644--- a/packages/core/src/services/undoredo/undoredo.service.ts+++ b/packages/core/src/services/undoredo/undoredo.service.ts@@ -23,6 +23,7 @@ import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } fimport { createIdentifier } from '../../common/di';import { Disposable, toDisposable } from '../../shared/lifecycle';import { CommandType, ICommandService, sequenceExecute } from '../command/command.service';+import { IConfigService } from '../config/config.service';import { EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHEET } from '../context/context';import { IContextService } from '../context/context.service';import { IUniverInstanceService } from '../instance/instance.service';@@ -45,6 +46,13 @@ export interface IUndoRedoService {pushUndoRedo(item: IUndoRedoItem): void;+ /**+ * Group undo redo items pushed while the returned scope is active.+ * Reusing the same group id joins consecutive scopes without exposing the+ * group to commands or undo redo items.+ */+ beginUndoRedoGroup(unitId: string, groupId: string, mode?: 'replace' | 'append'): IDisposable;+/** Pitch the top redo element of the currently focused Univer document instance. */pitchTopUndoElement(): Nullable<IUndoRedoItem>;/** Pitch the top undo element of the currently focused Univer document instance. */@@ -97,7 +105,8 @@ export interface IUndoRedoStatus {redos: number;}-const STACK_CAPACITY = 20;+export const DEFAULT_UNDO_REDO_HISTORY_LIMIT = 50;+export const UNDO_REDO_HISTORY_LIMIT_CONFIG_KEY = 'undoRedo.historyLimit';abstract class MultiImplementationCommand implements IDisposable {dispose(): void {@@ -173,14 +182,20 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoServiceprotected readonly _redoStacks = new Map<string, IUndoRedoItem[]>();private _batchingStatus = new Map<string, BatchingStatus>();+ private readonly _activeGroups = new Map<string, { id: string; mode: 'replace' | 'append' }>();+ private readonly _itemGroups = new WeakMap<IUndoRedoItem, string>();++ private readonly _historyLimit: number;constructor(@IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService,@ICommandService protected readonly _commandService: ICommandService,- @IContextService private readonly _contextService: IContextService+ @IContextService private readonly _contextService: IContextService,+ @IConfigService configService: IConfigService) {super();+ this._historyLimit = configService.getConfig<number>(UNDO_REDO_HISTORY_LIMIT_CONFIG_KEY) ?? DEFAULT_UNDO_REDO_HISTORY_LIMIT;this.undoRedoStatus$ = this._undoRedoStatus$.asObservable();this.disposeWithMe(this._commandService.registerCommand(UndoCommand));@@ -195,14 +210,27 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoServiceconst redoStack = this._getRedoStack(unitID, true);const undoStack = this._getUndoStack(unitID, true);+ const historyLimit = this._historyLimit;// redo stack should be cleared when pushing an undoredoStack.length = 0;- // should try to append first and then- if (this._batchingStatus.has(item.unitID)) {+ const activeGroup = this._activeGroups.get(unitID);+ const lastItem = this._pitchUndoElement(unitID);+ if (activeGroup) {+ if (lastItem && this._itemGroups.get(lastItem) === activeGroup.id) {+ if (activeGroup.mode === 'replace') {+ lastItem.redoMutations = item.redoMutations;+ } else {+ lastItem.redoMutations.push(...item.redoMutations);+ lastItem.undoMutations.unshift(...item.undoMutations);+ }+ } else {+ appendNewItem(item);+ this._itemGroups.set(item, activeGroup.id);+ }+ } else if (this._batchingStatus.has(item.unitID)) {const batchingStatus = this._batchingStatus.get(item.unitID)!;- const lastItem = this._pitchUndoElement(item.unitID);if (batchingStatus === BatchingStatus.WAITING || !lastItem) {appendNewItem(item);this._batchingStatus.set(item.unitID, BatchingStatus.CREATED);@@ -215,7 +243,7 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoServicefunction appendNewItem(item: IUndoRedoItem) {undoStack.push(item);- if (undoStack.length > STACK_CAPACITY) {+ if (undoStack.length > historyLimit) {undoStack.splice(0, 1);}}@@ -223,6 +251,20 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoServicethis._updateStatus();}+ beginUndoRedoGroup(unitId: string, groupId: string, mode: 'replace' | 'append' = 'replace'): IDisposable {+ if (this._activeGroups.has(unitId) || this._batchingStatus.has(unitId)) {+ throw new Error('[LocalUndoRedoService]: cannot group undo redo twice at the same time!');+ }++ const group = { id: groupId, mode };+ this._activeGroups.set(unitId, group);+ return toDisposable(() => {+ if (this._activeGroups.get(unitId) === group) {+ this._activeGroups.delete(unitId);+ }+ });+ }+clearUndoRedo(unitID: string): void {const redoStack = this._getRedoStack(unitID);if (redoStack) {@@ -261,6 +303,7 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoServiceconst undoStack = this._getUndoStackForFocused();const element = undoStack.pop();if (element) {+ this._itemGroups.delete(element);// Only push to redo stack if redoMutations is not emptyif (element.redoMutations.length > 0) {const redoStack = this._getRedoStackForFocused();@@ -274,6 +317,7 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoServiceconst redoStack = this._getRedoStackForFocused();const element = redoStack.pop();if (element) {+ this._itemGroups.delete(element);const undoStack = this._getUndoStackForFocused();undoStack.push(element);this._updateStatus();@@ -287,12 +331,13 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService// if the last item is the one we want to rollbackif (item && item.id === id) {stack.pop();+ this._itemGroups.delete(item);sequenceExecute(item.undoMutations, this._commandService);}}__tempBatchingUndoRedo(unitId: string): IDisposable {- if (this._batchingStatus.has(unitId)) {+ if (this._batchingStatus.has(unitId) || this._activeGroups.has(unitId)) {throw new Error('[LocalUndoRedoService]: cannot batching undo redo twice at the same time!');}diff --git a/packages/core/src/univer.ts b/packages/core/src/univer.tsindex a7426b98f2..391aa997f0 100644--- a/packages/core/src/univer.ts+++ b/packages/core/src/univer.ts@@ -48,7 +48,12 @@ import { IResourceLoaderService } from './services/resource-loader/type';import { ResourceManagerService } from './services/resource-manager/resource-manager.service';import { IResourceManagerService } from './services/resource-manager/type';import { ThemeService } from './services/theme/theme.service';-import { IUndoRedoService, LocalUndoRedoService } from './services/undoredo/undoredo.service';+import {+ DEFAULT_UNDO_REDO_HISTORY_LIMIT,+ IUndoRedoService,+ LocalUndoRedoService,+ UNDO_REDO_HISTORY_LIMIT_CONFIG_KEY,+} from './services/undoredo/undoredo.service';import { UserManagerService } from './services/user-manager/user-manager.service';import { DisposableCollection, toDisposable } from './shared';import { Workbook } from './sheets/workbook';@@ -98,6 +103,13 @@ export interface IUniverConfig {*/logCommandExecution?: boolean;+ /**+ * The maximum number of undoable command groups retained for each unit.+ * Set to `0` to disable undo history.+ * @default 50+ */+ undoRedoHistoryLimit?: number;+/*** The override dependencies of the Univer instance.*/@@ -129,7 +141,8 @@ export class Univer implements IDisposable {constructor(config: Partial<IUniverConfig> = {}, parentInjector?: Injector) {const injector = this._injector = createUniverInjector(parentInjector, config?.override);- const { theme, darkMode, locale, region, locales, direction, logLevel, logCommandExecution } = config;+ const { theme, darkMode, locale, region, locales, direction, logLevel, logCommandExecution, undoRedoHistoryLimit } = config;+ const configService = this._injector.get(IConfigService);if (theme) this._injector.get(ThemeService).setTheme(theme);if (darkMode) this._injector.get(ThemeService).setDarkMode(darkMode);if (locales) this._injector.get(LocaleService).load(locales);@@ -138,8 +151,12 @@ export class Univer implements IDisposable {if (direction) this._injector.get(LocaleService).setDirection(direction);if (logLevel) this._injector.get(ILogService).setLogLevel(logLevel);if (logCommandExecution !== undefined) {- this._injector.get(IConfigService).setConfig(COMMAND_LOG_EXECUTION_CONFIG_KEY, logCommandExecution);+ configService.setConfig(COMMAND_LOG_EXECUTION_CONFIG_KEY, logCommandExecution);}+ configService.setConfig(+ UNDO_REDO_HISTORY_LIMIT_CONFIG_KEY,+ undoRedoHistoryLimit ?? DEFAULT_UNDO_REDO_HISTORY_LIMIT+ );this._init(injector);}diff --git a/packages/sheets-drawing-ui/src/__tests__/create-sheets-drawing-ui-test-bed.ts b/packages/sheets-drawing-ui/src/__tests__/create-sheets-drawing-ui-test-bed.tsindex 445480ac3d..bced5749b5 100644--- a/packages/sheets-drawing-ui/src/__tests__/create-sheets-drawing-ui-test-bed.ts+++ b/packages/sheets-drawing-ui/src/__tests__/create-sheets-drawing-ui-test-bed.ts@@ -37,7 +37,7 @@ import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-reimport { UniverSheetsPlugin } from '@univerjs/sheets';import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing';import enUS from '@univerjs/sheets/locale/en-US';-import { ISidebarService } from '@univerjs/ui';+import { ISidebarService, UndoRedoGroupService } from '@univerjs/ui';import { BehaviorSubject, Subject } from 'rxjs';const TEST_WORKBOOK_DATA: IWorkbookData = {@@ -153,6 +153,7 @@ export function createSheetsDrawingUiTestBed(workbookData?: IWorkbookData, depenthis._injector.add([IRenderManagerService, { useClass: RenderManagerService }]);}this._injector.add([ISidebarService, { useClass: TestSidebarService as never }]);+ this._injector.add([UndoRedoGroupService]);dependencies?.forEach((dependency) => this._injector.add(dependency));}}diff --git a/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts b/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.tsindex 73a3c8c07e..48d482a99e 100644--- a/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts+++ b/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts@@ -19,6 +19,7 @@ import type { ISetDrawingCommandParams, ISheetDrawing } from '@univerjs/sheets-dimport { CommandType, Direction, ICommandService } from '@univerjs/core';import { SheetSkeletonService } from '@univerjs/sheets';import { ClearSheetDrawingTransformerOperation, ISheetDrawingService, SetSheetDrawingCommand, transformToAxisAlignPosition, transformToDrawingPosition } from '@univerjs/sheets-drawing';+import { UndoRedoGroupService } from '@univerjs/ui';export interface IMoveDrawingsCommandParams {direction: Direction;@@ -31,6 +32,7 @@ export const MoveDrawingsCommand: ICommand = {const commandService = accessor.get(ICommandService);const drawingManagerService = accessor.get(ISheetDrawingService);const sheetSkeletonService = accessor.get(SheetSkeletonService);+ const undoRedoGroupService = accessor.get(UndoRedoGroupService);const { direction } = params;@@ -70,10 +72,14 @@ export const MoveDrawingsCommand: ICommand = {} as ISheetDrawing;}).filter((drawing) => drawing != null) as ISheetDrawing[];- const result = commandService.syncExecuteCommand<ISetDrawingCommandParams>(SetSheetDrawingCommand.id, {+ const result = undoRedoGroupService.runTimed(unitId,- drawings: newDrawings,- });+ `sheet-drawing:nudge:${drawings[0].subUnitId}:${drawings.map((drawing) => drawing.drawingId).sort().join(',')}`,+ () => commandService.syncExecuteCommand<ISetDrawingCommandParams>(SetSheetDrawingCommand.id, {+ unitId,+ drawings: newDrawings,+ })+ );if (result) {commandService.syncExecuteCommand(ClearSheetDrawingTransformerOperation.id, [unitId]);diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 5d15c01e79..ffcd730645 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -145,6 +145,7 @@ export { DesktopSidebarService } from './services/sidebar/desktop-sidebar.servicexport { useSidebarClick } from './services/sidebar/hooks/use-sidebar-click';export { ILeftSidebarService, ISidebarService } from './services/sidebar/sidebar.service';export { ThemeSwitcherService } from './services/theme-switcher/theme-switcher.service';+export { UndoRedoGroupService } from './services/undo-redo/undo-redo-group.service';export { IWorkbenchService, WorkbenchService } from './services/workbench/workbench.service';export * from './utils';export { COLOR_PICKER_COMPONENT } from './views/color-picker/interface';diff --git a/packages/ui/src/plugin.ts b/packages/ui/src/plugin.tsindex 2c99c19693..3c5912b74f 100644--- a/packages/ui/src/plugin.ts+++ b/packages/ui/src/plugin.ts@@ -78,6 +78,7 @@ import { IShortcutService, ShortcutService } from './services/shortcut/shortcut.import { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';import { ISidebarService } from './services/sidebar/sidebar.service';import { ThemeSwitcherService } from './services/theme-switcher/theme-switcher.service';+import { UndoRedoGroupService } from './services/undo-redo/undo-redo-group.service';import { IWorkbenchService, WorkbenchService } from './services/workbench/workbench.service';export const DISABLE_AUTO_FOCUS_KEY = 'DISABLE_AUTO_FOCUS';@@ -123,6 +124,7 @@ export class UniverUIPlugin extends Plugin {[IconManager],[ComponentsController],[ThemeSwitcherService],+ [UndoRedoGroupService],[ZIndexManager],[ShortcutPanelService],[IUIPartsService, { useClass: UIPartsService }],diff --git a/packages/ui/src/services/undo-redo/__tests__/undo-redo-group.service.spec.ts b/packages/ui/src/services/undo-redo/__tests__/undo-redo-group.service.spec.tsnew file mode 100644index 0000000000..c8810c6b1d--- /dev/null+++ b/packages/ui/src/services/undo-redo/__tests__/undo-redo-group.service.spec.ts@@ -0,0 +1,48 @@+/**+ * 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 { describe, expect, it, vi } from 'vitest';+import { UndoRedoGroupService } from '../undo-redo-group.service';++describe('UndoRedoGroupService', () => {+ it('reuses only active timed groups and always closes the core scope', () => {+ const dispose = vi.fn();+ const beginUndoRedoGroup = vi.fn((_unitId: string, _groupId: string) => ({ dispose }));+ const service = new UndoRedoGroupService({ beginUndoRedoGroup });++ vi.spyOn(Date, 'now').mockReturnValueOnce(1_000).mockReturnValueOnce(1_900).mockReturnValueOnce(2_901);+ service.runTimed('unit-1', 'drawing:nudge', () => true);+ service.runTimed('unit-1', 'drawing:nudge', () => true);+ service.runTimed('unit-1', 'drawing:nudge', () => true);++ expect(beginUndoRedoGroup.mock.calls[1][1]).toBe(beginUndoRedoGroup.mock.calls[0][1]);+ expect(beginUndoRedoGroup.mock.calls[2][1]).not.toBe(beginUndoRedoGroup.mock.calls[0][1]);+ expect(dispose).toHaveBeenCalledTimes(3);+ });++ it('creates a runner that can group separated command executions', () => {+ const dispose = vi.fn();+ const beginUndoRedoGroup = vi.fn((_unitId: string, _groupId: string) => ({ dispose }));+ const service = new UndoRedoGroupService({ beginUndoRedoGroup });+ const run = service.createRunner('unit-1');++ run(() => true);+ run(() => true);++ expect(beginUndoRedoGroup.mock.calls[1][1]).toBe(beginUndoRedoGroup.mock.calls[0][1]);+ expect(dispose).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/ui/src/services/undo-redo/undo-redo-group.service.ts b/packages/ui/src/services/undo-redo/undo-redo-group.service.tsnew file mode 100644index 0000000000..9849bbe959--- /dev/null+++ b/packages/ui/src/services/undo-redo/undo-redo-group.service.ts@@ -0,0 +1,63 @@+/**+ * 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 { generateRandomId, IUndoRedoService } from '@univerjs/core';++const HISTORY_GROUP_WINDOW = 1_000;++export class UndoRedoGroupService {+ private readonly _sessions = new Map<string, { expiresAt: number; id: string }>();++ constructor(+ @IUndoRedoService private readonly _undoRedoService: Pick<IUndoRedoService, 'beginUndoRedoGroup'>+ ) {}++ run<T>(unitId: string, action: () => T, mode: 'replace' | 'append' = 'append'): T {+ return this._run(unitId, generateRandomId(8), mode, action);+ }++ createRunner(unitId: string, mode: 'replace' | 'append' = 'append') {+ const groupId = generateRandomId(8);+ return <T>(action: () => T): T => this._run(unitId, groupId, mode, action);+ }++ runTimed<T>(unitId: string, scope: string, action: () => T, mode: 'replace' | 'append' = 'replace'): T {+ const now = Date.now();+ const sessionKey = `${unitId}:${scope}`;+ const current = this._sessions.get(sessionKey);+ const groupId = current && current.expiresAt >= now ? current.id : generateRandomId(8);++ this._sessions.set(sessionKey, { id: groupId, expiresAt: now + HISTORY_GROUP_WINDOW });+ if (this._sessions.size > 100) {+ this._sessions.forEach((session, key) => {+ if (session.expiresAt < now) {+ this._sessions.delete(key);+ }+ });+ }++ return this._run(unitId, groupId, mode, action);+ }++ private _run<T>(unitId: string, groupId: string, mode: 'replace' | 'append', action: () => T): T {+ const group = this._undoRedoService.beginUndoRedoGroup(unitId, groupId, mode);+ try {+ return action();+ } finally {+ group.dispose();+ }+ }+}