Skip to content

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

fix(sheets): keep worksheet removal consistent for formulas, skeletons and menus (#8161)

wpxp12345612f1f2cb47c2
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts
index eec1def83c..bd9429023e 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Injector, Univer } from '@univerjs/core';
+import type { Injector, Univer, Workbook } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import { ICommandService } from '@univerjs/core';
import { FormulaDataModel } from '@univerjs/engine-formula';
@@ -47,6 +47,8 @@ function createControllerTestBed(editLocation = createEditLocation()) {
let injector: Injector;
const renderContext = {
unitId: 'test',
+ // The skeleton manager follows the workbook active sheet, so the context has to reference the real workbook.
+ unit: undefined as unknown as Workbook,
scene: {
onTransformChange$: {
subscribeEvent: () => ({ dispose: vi.fn() }),
@@ -67,6 +69,7 @@ function createControllerTestBed(editLocation = createEditLocation()) {
{ useFactory: createFormulaEditorShowController },
],
]);
+ renderContext.unit = testBed.sheet;
activeUniver = testBed.univer;
injector = testBed.univer.__getInjector();
testBed.sheet.addWorksheet('sheet2', 1, { id: 'sheet2', name: 'Sheet2', cellData: {} });
diff --git a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts
index 777f882819..579f4a9813 100644
--- a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts
@@ -33,6 +33,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '../../config/config';
import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
import { UniverSheetsFormulaPlugin } from '../../plugin';
+import { UpdateDefinedNameController } from '../update-defined-name.controller';
import { UpdateFormulaController } from '../update-formula.controller';
import '@univerjs/sheets/facade';
import '../../facade/index';
@@ -373,6 +374,59 @@ describe('UpdateFormulaController', () => {
]));
});
+ it('should remove a sheet that references itself without leaving dangling formulas behind', async () => {
+ commandService.registerCommand(RemoveSheetCommand);
+ testBed.injector.add([UpdateDefinedNameController]);
+ testBed.injector.get(UpdateDefinedNameController);
+
+ const univerInstanceService = testBed.injector.get(IUniverInstanceService);
+ const sheetInterceptorService = testBed.injector.get(SheetInterceptorService);
+ const getWorkbook = () => univerInstanceService.getUnit<Workbook>('test');
+ const getDefinedNameRef = () => definedNamesService.getValueById('test', 'range-name')?.formulaOrRefString;
+ const getSheet2Formula = () => getWorkbook()?.getSheetBySheetId('sheet2')?.getRange(0, 0, 0, 0).getValue()?.f;
+
+ // A formula on the sheet that is about to be removed, qualified with that sheet's own name.
+ expect(commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: { 10: { 1: { f: '=SUM(Sheet1!A1:B2)' } } },
+ })).toBe(true);
+
+ const intercepted = sheetInterceptorService.onCommandExecute({
+ id: RemoveSheetCommand.id,
+ params: { unitId: 'test', subUnitId: 'sheet1' },
+ });
+
+ // A rewrite aimed at the removed sheet can never be applied and would abort RemoveSheetCommand halfway.
+ expect(intercepted.redos).not.toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ id: SetRangeValuesMutation.id,
+ params: expect.objectContaining({ subUnitId: 'sheet1' }),
+ }),
+ ]));
+ expect(intercepted.redos).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ id: SetRangeValuesMutation.id,
+ params: expect.objectContaining({ subUnitId: 'sheet2' }),
+ }),
+ ]));
+
+ expect(commandService.syncExecuteCommand(RemoveSheetCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ })).toBe(true);
+
+ expect(getWorkbook()?.getSheetBySheetId('sheet1')).toBeFalsy();
+ expect(getSheet2Formula()).toBe('=#REF!');
+ expect(getDefinedNameRef()).toBe('#REF!');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+
+ expect(getWorkbook()?.getSheetBySheetId('sheet1')).toBeTruthy();
+ expect(getSheet2Formula()).toBe('=Sheet1!A1:B2');
+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');
+ });
+
it('should sync defined-name formulas when a defined name is renamed, undone, and redone', async () => {
const getFormula = () => formulaDataModel.getFormulaData().test?.sheet2?.[0]?.[1]?.f;
const getCellFormula = () => testBed.injector
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index be34d4cacc..aa11f85087 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -403,6 +403,8 @@ export class UpdateFormulaController extends Disposable {
const newFormulaData: IFormulaData = Object.create(null);
const inCrossSheetCutRangeNewFormulas: ICrossSheetCutFormula[] = [];
+ const { type, unitId: affectedUnitId, sheetId: affectedSheetId } = formulaReferenceMoveParam;
+ const isRemovingSheet = type === FormulaReferenceMoveType.RemoveSheet;
for (const unitId of formulaDataKeys) {
const sheetData = formulaData[unitId];
@@ -418,6 +420,13 @@ export class UpdateFormulaController extends Disposable {
}
for (const sheetId of sheetDataKeys) {
+ // The removed sheet is deleted by the `remove-sheet` mutation that runs before these rewrites are
+ // applied, so a rewrite targeting it can never succeed. `RemoveSheetCommand` aborts its whole
+ // sequence on the first failure, leaving the remaining sheets and defined names untouched.
+ if (isRemovingSheet && unitId === affectedUnitId && sheetId === affectedSheetId) {
+ continue;
+ }
+
const matrixData = new ObjectMatrix(sheetData[sheetId] || {});
const newFormulaDataItem = new ObjectMatrix<IFormulaDataItem>();
const shouldModifySi: string[] = [];
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/sheet.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/sheet.render-controller.spec.ts
index c6bd73730c..3da88c3599 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/__tests__/sheet.render-controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/sheet.render-controller.spec.ts
@@ -20,7 +20,7 @@ import { describe, expect, it } from 'vitest';
import { SHEET_VIEW_KEY } from '../../../common/keys';
import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
import { HeaderFreezeRenderController } from '../freeze.render-controller';
-import { getLeftTopPlaceholderSize } from '../sheet.render-controller';
+import { getLeftTopPlaceholderSize, SheetRenderController } from '../sheet.render-controller';
import { SheetSkeletonRenderController } from '../skeleton.render-controller';
import { SheetsZoomRenderController } from '../zoom.render-controller';
import { createChartRenderTestBed } from './chart-render-test-bed';
@@ -37,6 +37,20 @@ describe('SheetRenderController', () => {
height: 60,
});
});
+
+ it('skips dirty bounds once the removed sheet has no skeleton param left', () => {
+ const { render, workbook, activate } = createChartRenderTestBed();
+ activate('grid');
+
+ const controller = render.with(SheetRenderController) as unknown as {
+ _rangeToBounds: (ranges: { startRow: number; endRow: number; startColumn: number; endColumn: number }[]) => unknown;
+ };
+ const range = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };
+
+ expect(controller._rangeToBounds([range])).toHaveLength(1);
+ expect(workbook.removeSheet('grid')).toBe(true);
+ expect(controller._rangeToBounds([range])).toEqual([]);
+ });
});
describe('Chart host render lifecycle', () => {
diff --git a/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts
index 7f2c080894..8927648d77 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts
@@ -630,8 +630,14 @@ export class SheetRenderController extends RxDisposable implements IRenderModule
}
private _rangeToBounds(ranges: IRange[]) {
- const skeleton = this._sheetSkeletonManagerService.getCurrentParam()!.skeleton;
- const { rowHeightAccumulation, columnWidthAccumulation, rowHeaderWidth, columnHeaderHeight } = skeleton;
+ // Backstop for a stale or disposed current skeleton: the manager now follows the active worksheet, but a
+ // mutation can still arrive while the skeleton param is in flux, and a dirty-bounds miss is harmless.
+ const param = this._sheetSkeletonManagerService.getCurrentParam();
+ if (!param) {
+ return [];
+ }
+
+ const { rowHeightAccumulation, columnWidthAccumulation, rowHeaderWidth, columnHeaderHeight } = param.skeleton;
const dirtyBounds: IViewportInfos[] = [];
for (const r of ranges) {
diff --git a/packages/sheets-ui/src/menu/__tests__/menu-util.spec.ts b/packages/sheets-ui/src/menu/__tests__/menu-util.spec.ts
index 9d01bacfbf..9446b73c37 100644
--- a/packages/sheets-ui/src/menu/__tests__/menu-util.spec.ts
+++ b/packages/sheets-ui/src/menu/__tests__/menu-util.spec.ts
@@ -31,11 +31,17 @@
*/
import type { ISelectionWithStyle } from '@univerjs/sheets';
-import { IUniverInstanceService } from '@univerjs/core';
-import { IExclusiveRangeService, SheetsSelectionsService } from '@univerjs/sheets';
-import { BehaviorSubject } from 'rxjs';
-import { describe, expect, it } from 'vitest';
-import { getCurrentExclusiveRangeInterest$ } from '../menu-util';
+import { IContextService, IPermissionService, IUniverInstanceService, UserManagerService } from '@univerjs/core';
+import {
+ IExclusiveRangeService,
+ RangeProtectionRuleModel,
+ SheetsSelectionsService,
+ WorksheetEditPermission,
+ WorksheetProtectionRuleModel,
+} from '@univerjs/sheets';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { getCurrentExclusiveRangeInterest$, getCurrentRangeDisable$ } from '../menu-util';
describe('getCurrentExclusiveRangeInterest$', () => {
it('uses the current sheet selections when the active sheet changes', () => {
@@ -78,6 +84,49 @@ describe('getCurrentExclusiveRangeInterest$', () => {
});
});
+describe('getCurrentRangeDisable$', () => {
+ it('drops a removed active worksheet instead of composing permissions for it', () => {
+ const worksheet = { getSheetId: () => 'sheet-1', getConfig: () => ({}) };
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ activeSheet$: new BehaviorSubject(worksheet),
+ sheetDisposed$: new Subject(),
+ // The worksheet is no longer part of the workbook: its permission points were deleted on disposal.
+ getSheetBySheetId: () => undefined,
+ };
+ const permissionService = {
+ permissionPointUpdate$: new Subject(),
+ composePermission$: vi.fn(() => {
+ throw new Error('composePermission$ must not run for a removed worksheet');
+ }),
+ };
+ const services = new Map<unknown, unknown>([
+ [IUniverInstanceService, { getCurrentTypeOfUnit$: () => new BehaviorSubject(workbook) }],
+ [UserManagerService, { currentUser$: new BehaviorSubject(null) }],
+ [IContextService, { subscribeContextValue$: () => new BehaviorSubject(false) }],
+ [RangeProtectionRuleModel, { getSubunitRuleList: () => [] }],
+ [WorksheetProtectionRuleModel, { getRule: () => null }],
+ [SheetsSelectionsService, {
+ selectionChanged$: new BehaviorSubject([]),
+ getWorkbookSelections: () => ({ getSelectionsOfWorksheet: () => [] }),
+ }],
+ [IPermissionService, permissionService],
+ ]);
+ const accessor = {
+ get: (token: unknown) => services.get(token),
+ has: (token: unknown) => services.has(token),
+ } as never;
+
+ const states: boolean[] = [];
+ const subscription = getCurrentRangeDisable$(accessor, { worksheetTypes: [WorksheetEditPermission] })
+ .subscribe((state) => states.push(state));
+
+ expect(states[states.length - 1]).toBe(true);
+ expect(permissionService.composePermission$).not.toHaveBeenCalled();
+ subscription.unsubscribe();
+ });
+});
+
function createSelection(sheetId: string): ISelectionWithStyle {
return {
range: {
diff --git a/packages/sheets-ui/src/menu/menu-util.ts b/packages/sheets-ui/src/menu/menu-util.ts
index 207adec351..ce0e846761 100644
--- a/packages/sheets-ui/src/menu/menu-util.ts
+++ b/packages/sheets-ui/src/menu/menu-util.ts
@@ -57,10 +57,32 @@ interface IActive {
worksheet: Worksheet;
}
+/**
+ * Emits the active worksheet only while it is still part of the workbook.
+ *
+ * `Workbook.removeSheet` clears neither the active sheet nor its permission points; the next active sheet is set by
+ * a separate operation, and `deletePermissionPoint` does not notify subscribers. Menu permission chains therefore
+ * have to observe sheet disposal themselves and drop a worksheet that has been removed instead of querying
+ * permissions for it.
+ */
+function getAliveActiveSheet$(workbook: Workbook): Observable<Nullable<Worksheet>> {
+ return merge(
+ workbook.activeSheet$,
+ workbook.sheetDisposed$.pipe(map(() => workbook.getActiveSheet(true)))
+ ).pipe(
+ map((worksheet) => {
+ if (!worksheet || !workbook.getSheetBySheetId(worksheet.getSheetId())) {
+ return null;
+ }
+ return worksheet;
+ })
+ );
+}
+
function getActiveSheet$(univerInstanceService: IUniverInstanceService): Observable<Nullable<IActive>> {
return univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).pipe(switchMap((workbook) =>
workbook
- ? workbook.activeSheet$.pipe(map((worksheet) => {
+ ? getAliveActiveSheet$(workbook).pipe(map((worksheet) => {
if (!worksheet) {
return null;
}
@@ -172,7 +194,7 @@ export function getCurrentRangeDisable$(accessor: IAccessor, permissionTypes: IP
return of(true);
}
- return workbook.activeSheet$.pipe(
+ return getAliveActiveSheet$(workbook).pipe(
switchMap((worksheet) => {
if (!worksheet || (worksheet.getConfig().type === SheetTypes.CHART &&
!(supportShapeText && focusingShapeTextEditor && editorActivated))) {
@@ -262,13 +284,12 @@ export function getBaseRangeMenuHidden$(accessor: IAccessor) {
getActiveSheet$(univerInstanceService),
merge(selectionManagerService.selectionMoveEnd$, permissionService.permissionPointUpdate$.pipe(debounceTime(100))).pipe(startWith(null)),
]).pipe(
- map(() => {
+ map(([active]) => {
const range = selectionManagerService.getCurrentLastSelection()?.range;
- if (!range) return true;
+ if (!active || !range) return true;
- const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const worksheet = workbook?.getActiveSheet();
- if (!workbook || !worksheet || worksheet.getConfig().type === SheetTypes.CHART) {
+ const { workbook, worksheet } = active;
+ if (worksheet.getConfig().type === SheetTypes.CHART) {
return true;
}
@@ -299,13 +320,12 @@ export function getInsertAfterMenuHidden$(accessor: IAccessor, type: 'row' | 'co
getActiveSheet$(univerInstanceService),
merge(selectionManagerService.selectionMoveEnd$, permissionService.permissionPointUpdate$.pipe(debounceTime(100))).pipe(startWith(null)),
]).pipe(
- map(() => {
+ map(([active]) => {
const range = selectionManagerService.getCurrentLastSelection()?.range;
- if (!range) return true;
+ if (!active || !range) return true;
- const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const worksheet = workbook?.getActiveSheet();
- if (!workbook || !worksheet || worksheet.getConfig().type === SheetTypes.CHART) {
+ const { workbook, worksheet } = active;
+ if (worksheet.getConfig().type === SheetTypes.CHART) {
return true;
}
@@ -344,13 +364,12 @@ export function getInsertBeforeMenuHidden$(accessor: IAccessor, type: 'row' | 'c
getActiveSheet$(univerInstanceService),
merge(selectionManagerService.selectionMoveEnd$, permissionService.permissionPointUpdate$.pipe(debounceTime(100))).pipe(startWith(null)),
]).pipe(
- map(() => {
+ map(([active]) => {
const range = selectionManagerService.getCurrentLastSelection()?.range;
- if (!range) return true;
+ if (!active || !range) return true;
- const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const worksheet = workbook?.getActiveSheet();
- if (!workbook || !worksheet || worksheet.getConfig().type === SheetTypes.CHART) {
+ const { workbook, worksheet } = active;
+ if (worksheet.getConfig().type === SheetTypes.CHART) {
return true;
}
@@ -390,13 +409,12 @@ export function getDeleteMenuHidden$(accessor: IAccessor, type: 'row' | 'col') {
getActiveSheet$(univerInstanceService),
merge(selectionManagerService.selectionMoveEnd$, permissionService.permissionPointUpdate$.pipe(debounceTime(100))).pipe(startWith(null)),
]).pipe(
- map(() => {
+ map(([active]) => {
const range = selectionManagerService.getCurrentLastSelection()?.range;
- if (!range) return true;
+ if (!active || !range) return true;
- const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const worksheet = workbook?.getActiveSheet();
- if (!workbook || !worksheet || worksheet.getConfig().type === SheetTypes.CHART) {
+ const { workbook, worksheet } = active;
+ if (worksheet.getConfig().type === SheetTypes.CHART) {
return true;
}
@@ -438,13 +456,12 @@ export function getCellMenuHidden$(accessor: IAccessor, type: 'row' | 'col') {
getActiveSheet$(univerInstanceService),
merge(selectionManagerService.selectionMoveEnd$, permissionService.permissionPointUpdate$.pipe(debounceTime(100))).pipe(startWith(null)),
]).pipe(
- map(() => {
+ map(([active]) => {
const range = selectionManagerService.getCurrentLastSelection()?.range;
- if (!range) return true;
+ if (!active || !range) return true;
- const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const worksheet = workbook?.getActiveSheet();
- if (!workbook || !worksheet || worksheet.getConfig().type === SheetTypes.CHART) {
+ const { workbook, worksheet } = active;
+ if (worksheet.getConfig().type === SheetTypes.CHART) {
return true;
}
diff --git a/packages/sheets-ui/src/services/__tests__/sheet-skeleton-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/sheet-skeleton-manager.service.spec.ts
index 541dc00bac..cddd3425ee 100644
--- a/packages/sheets-ui/src/services/__tests__/sheet-skeleton-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/sheet-skeleton-manager.service.spec.ts
@@ -118,6 +118,51 @@ describe('SheetSkeletonManagerService', () => {
expect(current[current.length - 1]).toBeNull();
expect(service.ensureSkeleton('chart')).toBeUndefined();
});
+ it('follows the active worksheet once the tracked skeleton has been removed', () => {
+ const injector = new Injector([
+ [IConfigService, { useClass: ConfigService }],
+ [IContextService, { useClass: ContextService }],
+ [ILogService, { useClass: DesktopLogService }],
+ [LocaleService],
+ [ThemeService],
+ [IUniverInstanceService, { useClass: UniverInstanceService }],
+ [SheetSkeletonService],
+ [ICanvasColorService, { useClass: CanvasColorService }],
+ [IRenderManagerService, { useClass: RenderManagerService }],
+ ]);
+ onTestFinished(() => injector.dispose());
+ const workbook = injector.createInstance(Workbook, {
+ id: 'delete-sheet',
+ sheetOrder: ['sheet-a', 'sheet-b'],
+ sheets: {
+ 'sheet-a': { id: 'sheet-a', rowCount: 10, columnCount: 10 },
+ 'sheet-b': { id: 'sheet-b', rowCount: 10, columnCount: 10 },
+ },
+ });
+ onTestFinished(() => workbook.dispose());
+ injector.get(SheetSkeletonService);
+ (injector.get(IUniverInstanceService) as UniverInstanceService).__addUnit(workbook);
+ const canvasContext = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(
+ { setTransform: vi.fn(), clearRect: vi.fn() } as unknown as CanvasRenderingContext2D
+ );
+ onTestFinished(() => canvasContext.mockRestore());
+ const renderManager = injector.get(IRenderManagerService);
+ renderManager.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService]);
+ const render = renderManager.createRender(workbook.getUnitId());
+ const service = render.with(SheetSkeletonManagerService);
+
+ service.setCurrent({ sheetId: 'sheet-a' });
+ expect(service.getCurrentParam()?.sheetId).toBe('sheet-a');
+
+ // Removing the tracked sheet drops its skeleton param before any skeleton-change command runs.
+ expect(workbook.removeSheet('sheet-a')).toBe(true);
+ expect(service.getCurrentParam()).toBeUndefined();
+
+ workbook.setActiveSheet(workbook.getSheetBySheetId('sheet-b')!);
+ expect(service.getCurrentParam()?.sheetId).toBe('sheet-b');
+ expect(service.getCurrentSkeleton()?.worksheet).toBe(workbook.getSheetBySheetId('sheet-b'));
+ });
+
it('sets the current worksheet skeleton and marks it dirty for recalculation', () => {
const injector = new Injector();
injector.add([IConfigService, { useClass: ConfigService }]);
@@ -170,6 +215,7 @@ describe('SheetSkeletonManagerService', () => {
const workbook = {
getSheetBySheetId: () => ({ getSheetId: () => 'sheet-1' }),
getStyles: () => ({}),
+ activeSheet$: new Subject(),
};
const service = injector.createInstance(SheetSkeletonManagerService, {
unit: workbook,
@@ -231,7 +277,7 @@ describe('SheetSkeletonManagerService', () => {
const injector = new Injector();
injector.add([SheetSkeletonService, { useClass: TestSheetSkeletonService as never }]);
const service = injector.createInstance(SheetSkeletonManagerService, {
- unit: {},
+ unit: { activeSheet$: new Subject() },
unitId: 'unit-1',
type: UniverInstanceType.UNIVER_SHEET,
scene: {},
diff --git a/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts
index 86223d0f92..c2bba87a6e 100644
--- a/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts
+++ b/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts
@@ -339,6 +339,20 @@ describe('BaseSelectionRenderService', () => {
expect(service.inRefSelectionMode()).toBe(false);
});
+ it('returns no selection data once the sheet skeleton has been disposed', () => {
+ const { service } = createSelectionRenderService();
+ const { skeleton } = service.changeRuntimeForTest();
+ service.resetSelectionsByModelData([selections[0]]);
+
+ const worksheet = skeleton.worksheet;
+ (skeleton as unknown as { worksheet: unknown }).worksheet = null;
+ try {
+ expect(service.getSelectionDataWithStyle()).toEqual([]);
+ } finally {
+ (skeleton as unknown as { worksheet: unknown }).worksheet = worksheet;
+ }
+ });
+
it.each([undefined, true, false])('keeps selection updates working with enableFillHandle=%s', (enableFillHandle) => {
const { injector, service } = createSelectionRenderService();
injector.get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, { enableFillHandle });
diff --git a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
index b3cfb8c100..0809553e60 100644
--- a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
@@ -361,7 +361,9 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
*/
getSelectionDataWithStyle(): ISelectionWithCoord[] {
const selectionControls = this._selectionControls;
- if (this._skeleton) {
+ // Removing a worksheet disposes its skeleton and clears the `worksheet` it was built from, while the
+ // render services keep the disposed instance until the skeleton manager publishes the next one.
+ if (this._skeleton?.worksheet) {
const [unitId, sheetId] = this._skeleton.getLocation();
return selectionControls.map((control) => {
const v = control.getValue();
diff --git a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
index a08e269382..00fabcd66f 100644
--- a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
+++ b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
@@ -57,6 +57,7 @@ export class SheetSkeletonManagerService extends Disposable implements IRenderMo
this._sheetSkeletonService.setScene(unitId, scene);
this._initSkeletonsRegisterGetCellHeight(unitId);
+ this._initActiveSheetSync();
}
private _initSkeletonsRegisterGetCellHeight(unitId: string) {
@@ -68,6 +69,30 @@ export class SheetSkeletonManagerService extends Disposable implements IRenderMo
);
}
+ /**
+ * Keep the tracked skeleton on the active worksheet once the tracked one is gone.
+ *
+ * Removing a worksheet disposes its skeleton and drops its param immediately, while `_sheetId` is only
+ * updated by the next skeleton-change command. That leaves the manager pointing at a dead sheet for the
+ * whole `RemoveSheetCommand` redo sequence, so consumers either read a disposed skeleton or nothing at all.
+ */
+ private _initActiveSheetSync() {
+ this.disposeWithMe(
+ this._context.unit.activeSheet$.subscribe((worksheet) => {
+ if (!worksheet || !this._sheetId || worksheet.getSheetId() === this._sheetId) {
+ return;
+ }
+
+ // The tracked worksheet still exists: a skeleton-change command owns this transition.
+ if (this._getSkeletonParam(this._sheetId)) {
+ return;
+ }
+
+ this._setCurrent(worksheet.getSheetId());
+ })
+ );
+ }
+
override dispose(): void {
super.dispose();