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
fix(sheets-ui): refresh range menu state on sheet switch (#7736)
wpxp123456aa149b38d53b
diff --git a/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.ts b/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.tsindex 5a992ddf85..acb2b868bc 100644--- a/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.ts+++ b/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.ts@@ -46,6 +46,7 @@ import { Engine } from '../../../engine';import { MAIN_VIEW_PORT_KEY, Scene } from '../../../scene';import { Viewport } from '../../../viewport';import { Font } from '../extensions/font';+import { SHEET_EXTENSION_TYPE } from '../extensions/sheet-extension';import { SHEET_VIEWPORT_KEY } from '../interfaces';import {convertTransformToOffsetX,@@ -759,6 +760,38 @@ describe('spreadsheet integration', () => {expect(extensionDraw.mock.calls.at(-1)?.[4].hasMergeData).toBe(false);});+ it('repaints background extensions after clearing merged cell gridlines', () => {+ const { spreadsheet, skeleton, scene, cacheCanvas, mainCanvas } = fixture;+ const context = mainCanvas.getContext();+ const backgroundDraw = vi.fn();+ const gridDraw = vi.fn();+ const clearRectSpy = vi.spyOn(context, 'clearRectByPrecision');+ const mergedRange = { startRow: 2, endRow: 3, startColumn: 2, endColumn: 3, rangeType: RANGE_TYPE.NORMAL };+ vi.spyOn(skeleton, 'getCurrentRowColumnSegmentMergeData').mockReturnValue([mergedRange]);+ vi.spyOn(skeleton.overflowCache, 'toNativeArray').mockReturnValue([]);+ vi.spyOn(spreadsheet as unknown as { getExtensionsByOrder: () => unknown[] }, 'getExtensionsByOrder').mockReturnValue([+ {+ type: SHEET_EXTENSION_TYPE.BACKGROUND,+ uKey: 'MockBackgroundExtension',+ draw: backgroundDraw,+ },+ {+ type: SHEET_EXTENSION_TYPE.GRID,+ uKey: 'MockGridExtension',+ draw: gridDraw,+ },+ ]);++ const viewportInfo = createViewportInfo(scene, cacheCanvas);+ skeleton.setStylesCache(viewportInfo);+ spreadsheet.draw(context, viewportInfo);++ expect(backgroundDraw).toHaveBeenCalledTimes(2);+ expect(backgroundDraw.mock.calls[1][3]).toEqual(expect.arrayContaining([mergedRange]));+ expect(clearRectSpy.mock.invocationCallOrder[0]).toBeLessThan(backgroundDraw.mock.invocationCallOrder[1]);+ expect(backgroundDraw.mock.invocationCallOrder[1]).toBeLessThan(gridDraw.mock.invocationCallOrder[0]);+ });+it('skips sparse extensions outside merge repair bounds on sheets with merged cells', () => {const { spreadsheet, skeleton, scene, cacheCanvas, mainCanvas } = fixture;const context = mainCanvas.getContext() as any;diff --git a/packages/engine-render/src/components/sheets/spreadsheet.ts b/packages/engine-render/src/components/sheets/spreadsheet.tsindex 8cfd420866..da1a1cf413 100644--- a/packages/engine-render/src/components/sheets/spreadsheet.ts+++ b/packages/engine-render/src/components/sheets/spreadsheet.ts@@ -370,22 +370,27 @@ export class Spreadsheet extends SheetComponent {// At this moment, ctx.transform is at topLeft of sheet content, cell(0, 0)const scene = this.getScene();- for (const extension of backgroundExtensions) {- const timeKey = `${SHEET_EXTENSION_PREFIX}${extension.uKey}`;- const st = Tools.now();- extension.draw(ctx, parentScale, spreadsheetSkeleton, diffRanges, {- viewRanges,- checkOutOfViewBound: true,- hasMergeData,- viewportKey: viewportInfo.viewportKey,- viewBound: viewportInfo.cacheBound,- diffBounds: viewportInfo.diffBounds,- } as IDrawInfo);- const cost = Tools.now() - st;- this.addRenderFrameTimeMetricToScene(timeKey, cost, scene);- }+ const drawBackgroundExtensions = (backgroundDiffRanges: IRange[], backgroundViewRanges: IRange[]) => {+ for (const extension of backgroundExtensions) {+ const timeKey = `${SHEET_EXTENSION_PREFIX}${extension.uKey}`;+ const st = Tools.now();+ extension.draw(ctx, parentScale, spreadsheetSkeleton, backgroundDiffRanges, {+ viewRanges: backgroundViewRanges,+ checkOutOfViewBound: true,+ hasMergeData,+ viewportKey: viewportInfo.viewportKey,+ viewBound: viewportInfo.cacheBound,+ diffBounds: viewportInfo.diffBounds,+ } as IDrawInfo);+ const cost = Tools.now() - st;+ this.addRenderFrameTimeMetricToScene(timeKey, cost, scene);+ }+ };- this._drawAuxiliary(ctx, hasMergeData);+ drawBackgroundExtensions(diffRanges, viewRanges);+ this._drawAuxiliary(ctx, hasMergeData, (clearedRanges) => {+ drawBackgroundExtensions(clearedRanges, clearedRanges);+ });for (const extension of gridExtensions) {if (shouldSkipSparseExtension(extension.uKey, sparseExtensionFeatures)) {@@ -922,7 +927,11 @@ export class Spreadsheet extends SheetComponent {* @param ctx*/// eslint-disable-next-line max-lines-per-function, complexity- private _drawAuxiliary(ctx: UniverRenderingContext2D, hasMergeData = true) {+ private _drawAuxiliary(+ ctx: UniverRenderingContext2D,+ hasMergeData = true,+ redrawBackgrounds?: (ranges: IRange[]) => void+ ) {const spreadsheetSkeleton = this.getSkeleton();if (spreadsheetSkeleton == null) {return;@@ -1043,10 +1052,16 @@ export class Spreadsheet extends SheetComponent {mergeCellRanges.push(...mergeRangeInVisible);}}- this._clearRectangle(ctx, rowHeightAccumulation, columnWidthAccumulation, mergeCellRanges);+ this._clearRectangle(ctx, rowHeightAccumulation, columnWidthAccumulation, mergeCellRanges, redrawBackgrounds);// clear line of overflow cell- this._clearRectangle(ctx, rowHeightAccumulation, columnWidthAccumulation, overflowCache.toNativeArray());+ this._clearRectangle(+ ctx,+ rowHeightAccumulation,+ columnWidthAccumulation,+ overflowCache.toNativeArray(),+ redrawBackgrounds+ );// Draw gap areas AFTER merge/overflow clearing so gap visuals are always on topthis._drawGapAreas(ctx, spreadsheetSkeleton, rowStart, rowEnd, columnStart, columnEnd, startX, endX, startY, endY);@@ -1061,11 +1076,13 @@ export class Spreadsheet extends SheetComponent {ctx: UniverRenderingContext2D,rowHeightAccumulation: number[],columnWidthAccumulation: number[],- cellRanges?: IRange[]+ cellRanges?: IRange[],+ redrawBackgrounds?: (ranges: IRange[]) => void) {- if (cellRanges == null) {+ if (!cellRanges?.length) {return;}+ const bounds: IBoundRectNoAngle[] = [];for (const range of cellRanges) {const { startRow, endRow, startColumn, endColumn } = range;@@ -1077,14 +1094,19 @@ export class Spreadsheet extends SheetComponent {columnWidthAccumulation[endColumn] ?? columnWidthAccumulation[columnWidthAccumulation.length - 1];ctx.clearRectByPrecision(startX, startY, endX - startX, endY - startY);+ bounds.push({ left: startX, top: startY, right: endX, bottom: endY });+ }++ redrawBackgrounds?.(cellRanges);+ for (const { left, top, right, bottom } of bounds) {// After ClearRect, the lines will become thinner, and the lines will be repaired below.ctx.beginPath();- ctx.moveToByPrecision(startX, startY);- ctx.lineToByPrecision(endX, startY);- ctx.lineToByPrecision(endX, endY);- ctx.lineToByPrecision(startX, endY);- ctx.lineToByPrecision(startX, startY);+ ctx.moveToByPrecision(left, top);+ ctx.lineToByPrecision(right, top);+ ctx.lineToByPrecision(right, bottom);+ ctx.lineToByPrecision(left, bottom);+ ctx.lineToByPrecision(left, top);ctx.stroke();ctx.closePath();}diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-auto-fill.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-auto-fill.controller.spec.tsindex b3751b5afc..f6abe98af7 100644--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-auto-fill.controller.spec.ts+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-auto-fill.controller.spec.ts@@ -33,6 +33,7 @@ import {IAutoFillService,RangeProtectionRenderModel,RangeProtectionService,+ RefRangeService,RemoveWorksheetMergeMutation,SetRangeValuesMutation,SetSelectionsOperation,@@ -42,10 +43,11 @@ import { FormulaAutoFillController } from '@univerjs/sheets-formula';import {AutoFillUIController,ISheetSelectionRenderService,+ SheetCanvasPopManagerService,SheetSelectionRenderService,SheetsRenderService,} from '@univerjs/sheets-ui';-import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';+import { CanvasPopupService, ICanvasPopupService, IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { createCommandTestBed } from './create-command-test-bed';@@ -73,6 +75,9 @@ describe('Test auto fill with formula', () => {[IShortcutService, { useClass: ShortcutService }],[IPlatformService, { useClass: PlatformService }],[SheetsRenderService, { useClass: mockSheetsRenderService }],+ [RefRangeService],+ [ICanvasPopupService, { useClass: CanvasPopupService }],+ [SheetCanvasPopManagerService],[AutoFillController],[AutoFillUIController],[FormulaAutoFillController],diff --git a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.tsindex 8dfb003d08..45c8669323 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts@@ -38,17 +38,19 @@ import {AutoFillService,IAutoFillService,RefillCommand,+ RefRangeService,RemoveWorksheetMergeMutation,SetRangeValuesMutation,SetSelectionsOperation,SheetSkeletonService,SheetsSelectionsService,} from '@univerjs/sheets';-import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';+import { CanvasPopupService, ICanvasPopupService, IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';import { Subject } from 'rxjs';import { beforeEach, describe, expect, it, vi } from 'vitest';import { AutoFillRenderController, AutoFillUIController, detectAutoFillRange } from '../../../controllers/auto-fill-ui.controller';import { createRenderTestBed } from '../../../controllers/render-controllers/__tests__/render-test-bed';+import { SheetCanvasPopManagerService } from '../../../services/canvas-pop-manager.service';import { EditorBridgeService, IEditorBridgeService } from '../../../services/editor-bridge.service';import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';import { SheetSelectionRenderService } from '../../../services/selection/selection-render.service';@@ -356,7 +358,10 @@ describe('Test auto fill rules in controller', () => {[IEditorService, { useClass: EditorService }],[IRenderManagerService, { useClass: RenderManagerService }],[SheetsRenderService, { useClass: mockSheetsRenderService }],+ [RefRangeService],+ [ICanvasPopupService, { useClass: CanvasPopupService }],[SheetSkeletonManagerService],+ [SheetCanvasPopManagerService],[AutoFillController],[AutoFillUIController],]);diff --git a/packages/sheets-ui/src/controllers/__tests__/auto-fill-ui.controller.spec.ts b/packages/sheets-ui/src/controllers/__tests__/auto-fill-ui.controller.spec.tsnew file mode 100644index 0000000000..93999496c2--- /dev/null+++ b/packages/sheets-ui/src/controllers/__tests__/auto-fill-ui.controller.spec.ts@@ -0,0 +1,104 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommandInfo, IDisposable } from '@univerjs/core';+import { ICommandService, Injector, IUniverInstanceService, RANGE_TYPE } from '@univerjs/core';+import { AutoFillController, IAutoFillService, RefRangeService } from '@univerjs/sheets';+import { CanvasPopupService, ICanvasPopupService } from '@univerjs/ui';+import { BehaviorSubject, Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SetScrollOperation } from '../../commands/operations/scroll.operation';+import { SheetCanvasPopManagerService } from '../../services/canvas-pop-manager.service';+import { SheetsRenderService } from '../../services/sheets-render.service';+import { AUTO_FILL_POPUP_MENU_COMPONENT } from '../../views/auto-fill-popup-menu/component-name';+import { AutoFillUIController } from '../auto-fill-ui.controller';++describe('AutoFillUIController', () => {+ it('attaches the menu to the filled range and owns its lifecycle', () => {+ let commandExecuted: ((command: ICommandInfo) => void) | undefined;+ const showMenu$ = new BehaviorSubject(false);+ const firstPopupDisposable = { dispose: vi.fn() };+ const secondPopupDisposable = { dispose: vi.fn() };+ const thirdPopupDisposable = { dispose: vi.fn() };+ const attachRangePopup = vi.fn()+ .mockReturnValueOnce(firstPopupDisposable)+ .mockReturnValueOnce(secondPopupDisposable)+ .mockReturnValueOnce(thirdPopupDisposable);+ const quit = vi.fn();+ const autoFillService = {+ addHook: () => ({ dispose: () => undefined }),+ autoFillLocation: {+ source: { rows: [1, 2], cols: [3, 4] },+ target: { rows: [3, 4], cols: [3, 4] },+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ },+ setShowMenu: (show: boolean) => showMenu$.next(show),+ showMenu$,+ };+ const injector = new Injector([+ [ICommandService, {+ useValue: {+ onCommandExecuted: (callback: (command: ICommandInfo) => void): IDisposable => {+ commandExecuted = callback;+ return { dispose: () => undefined };+ },+ },+ }],+ [IUniverInstanceService, { useValue: { unitDisposed$: new Subject() } }],+ [IAutoFillService, { useValue: autoFillService }],+ [AutoFillController, { useValue: { quit } }],+ [SheetsRenderService, {+ useValue: {+ registerSkeletonChangingMutations: () => ({ dispose: () => undefined }),+ },+ }],+ [RefRangeService],+ [ICanvasPopupService, { useClass: CanvasPopupService }],+ [SheetCanvasPopManagerService, { useValue: { attachRangePopup } }],+ [AutoFillUIController],+ ]);+ const controller = injector.get(AutoFillUIController);++ autoFillService.setShowMenu(true);++ expect(attachRangePopup).toHaveBeenLastCalledWith(+ { startRow: 1, endRow: 4, startColumn: 3, endColumn: 4, rangeType: RANGE_TYPE.NORMAL },+ {+ componentKey: AUTO_FILL_POPUP_MENU_COMPONENT,+ constrainToCanvas: true,+ direction: 'bottom-right',+ offset: [2, 2],+ },+ 'unit-1',+ 'sheet-1'+ );++ commandExecuted?.({ id: SetScrollOperation.id, type: SetScrollOperation.type, params: {} });+ expect(firstPopupDisposable.dispose).not.toHaveBeenCalled();+ expect(quit).not.toHaveBeenCalled();++ autoFillService.setShowMenu(true);+ expect(firstPopupDisposable.dispose).toHaveBeenCalledTimes(1);++ autoFillService.setShowMenu(false);+ expect(secondPopupDisposable.dispose).toHaveBeenCalledTimes(1);++ autoFillService.setShowMenu(true);+ controller.dispose();+ expect(thirdPopupDisposable.dispose).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/sheets-ui/src/controllers/auto-fill-ui.controller.ts b/packages/sheets-ui/src/controllers/auto-fill-ui.controller.tsindex 5d8ce99bd4..50af64d3d4 100644--- a/packages/sheets-ui/src/controllers/auto-fill-ui.controller.ts+++ b/packages/sheets-ui/src/controllers/auto-fill-ui.controller.ts@@ -14,7 +14,17 @@* limitations under the License.*/-import type { ICommandInfo, IExecutionOptions, IMutationCommonParams, IRange, Nullable, UnitModel, Workbook, Worksheet } from '@univerjs/core';+import type {+ ICommandInfo,+ IDisposable,+ IExecutionOptions,+ IMutationCommonParams,+ IRange,+ Nullable,+ UnitModel,+ Workbook,+ Worksheet,+} from '@univerjs/core';import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import type { IAutoFillLocation, IRemoveSheetMutationParams } from '@univerjs/sheets';import {@@ -23,6 +33,7 @@ import {ICommandService,Inject,IUniverInstanceService,+ Rectangle,} from '@univerjs/core';import { DeviceInputEventType } from '@univerjs/engine-render';import {@@ -30,6 +41,7 @@ import {AutoClearContentCommand,AutoFillCommand,AutoFillController,+ discreteRangeToRange,IAutoFillService,InsertColMutation,InsertRowMutation,@@ -49,19 +61,23 @@ import {} from '@univerjs/sheets';import { SetCellEditVisibleOperation } from '../commands/operations/cell-edit.operation';import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';+import { SheetCanvasPopManagerService } from '../services/canvas-pop-manager.service';import { IEditorBridgeService } from '../services/editor-bridge.service';import { ISheetSelectionRenderService } from '../services/selection/base-selection-render.service';import { SheetsRenderService } from '../services/sheets-render.service';+import { AUTO_FILL_POPUP_MENU_COMPONENT } from '../views/auto-fill-popup-menu/component-name';export class AutoFillUIController extends Disposable {private _currentLocation: Nullable<IAutoFillLocation> = null;+ private _popupDisposable: Nullable<IDisposable> = null;constructor(@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@ICommandService private readonly _commandService: ICommandService,@IAutoFillService private readonly _autoFillService: IAutoFillService,@Inject(AutoFillController) private _autoFillController: AutoFillController,- @Inject(SheetsRenderService) private _sheetsRenderService: SheetsRenderService+ @Inject(SheetsRenderService) private _sheetsRenderService: SheetsRenderService,+ @Inject(SheetCanvasPopManagerService) private readonly _sheetCanvasPopManagerService: SheetCanvasPopManagerService) {super();@@ -70,10 +86,41 @@ export class AutoFillUIController extends Disposable {private _init() {this._initDefaultHook();+ this._initPopup();this._initQuitListener();this._initSkeletonChange();}+ private _initPopup(): void {+ this.disposeWithMe(this._autoFillService.showMenu$.subscribe((show) => {+ this._disposePopup();+ if (!show) {+ return;+ }++ const location = this._autoFillService.autoFillLocation;+ if (!location) {+ return;+ }++ const range = Rectangle.union(+ discreteRangeToRange(location.source),+ discreteRangeToRange(location.target)+ );+ this._popupDisposable = this._sheetCanvasPopManagerService.attachRangePopup(range, {+ componentKey: AUTO_FILL_POPUP_MENU_COMPONENT,+ constrainToCanvas: true,+ direction: 'bottom-right',+ offset: [2, 2],+ }, location.unitId, location.subUnitId);+ }));+ }++ private _disposePopup(): void {+ this._popupDisposable?.dispose();+ this._popupDisposable = null;+ }+private _initSkeletonChange() {this.disposeWithMe(this._sheetsRenderService.registerSkeletonChangingMutations(AutoFillCommand.id));}@@ -137,10 +184,16 @@ export class AutoFillUIController extends Disposable {}private _quit() {+ this._disposePopup();this._currentLocation = null;this._autoFillController.quit();this._autoFillService.setShowMenu(false);}++ override dispose(): void {+ this._disposePopup();+ super.dispose();+ }}export class AutoFillRenderController extends Disposable implements IRenderModule {diff --git a/packages/sheets-ui/src/controllers/components.controller.ts b/packages/sheets-ui/src/controllers/components.controller.tsindex 89a168dc12..2b232b60b3 100644--- a/packages/sheets-ui/src/controllers/components.controller.ts+++ b/packages/sheets-ui/src/controllers/components.controller.ts@@ -24,6 +24,8 @@ import {UNIVER_SHEET_PERMISSION_USER_DIALOG,UNIVER_SHEET_PERMISSION_USER_PART,} from '../consts/permission';+import { AutoFillPopupMenu } from '../views/auto-fill-popup-menu/AutoFillPopupMenu';+import { AUTO_FILL_POPUP_MENU_COMPONENT } from '../views/auto-fill-popup-menu/component-name';import { BorderPanel } from '../views/border-panel/BorderPanel';import { BORDER_PANEL_COMPONENT } from '../views/border-panel/interface';import { CELL_ALERT_KEY } from '../views/cell-alert';@@ -94,6 +96,7 @@ export class ComponentsController extends Disposable {this.disposeWithMe(componentManager.register(BORDER_PANEL_COMPONENT, BorderPanel));this.disposeWithMe(componentManager.register(DEFINED_NAME_CONTAINER, DefinedNameContainer));this.disposeWithMe(componentManager.register(CELL_POPUP_COMPONENT_KEY, CellPopup));+ this.disposeWithMe(componentManager.register(AUTO_FILL_POPUP_MENU_COMPONENT, AutoFillPopupMenu));Object.values(dropdownMap).forEach((component) => {this.disposeWithMe(componentManager.register(component.componentKey, component));});diff --git a/packages/sheets-ui/src/menu/__tests__/menu-util.spec.ts b/packages/sheets-ui/src/menu/__tests__/menu-util.spec.tsnew file mode 100644index 0000000000..9d01bacfbf--- /dev/null+++ b/packages/sheets-ui/src/menu/__tests__/menu-util.spec.ts@@ -0,0 +1,93 @@+/**+ * 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.+ */++/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { 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';++describe('getCurrentExclusiveRangeInterest$', () => {+ it('uses the current sheet selections when the active sheet changes', () => {+ const worksheets = {+ regular: { getSheetId: () => 'regular-sheet' },+ exclusive: { getSheetId: () => 'exclusive-sheet' },+ };+ const activeSheet$ = new BehaviorSubject(worksheets.exclusive);+ const workbook = { activeSheet$ };+ const workbook$ = new BehaviorSubject(workbook);+ const selectionsBySheet: Record<string, ISelectionWithStyle[]> = {+ 'regular-sheet': [createSelection('regular-sheet')],+ 'exclusive-sheet': [createSelection('exclusive-sheet')],+ };+ const selectionMoveEnd$ = new BehaviorSubject(selectionsBySheet['exclusive-sheet']);+ const services = new Map<unknown, unknown>([+ [IUniverInstanceService, {+ getCurrentTypeOfUnit$: () => workbook$,+ }],+ [SheetsSelectionsService, {+ selectionMoveEnd$,+ getCurrentSelections: () => selectionsBySheet[activeSheet$.value.getSheetId()],+ }],+ [IExclusiveRangeService, {+ getInterestGroupId: (selections: ISelectionWithStyle[]) => selections[0].range.sheetId === 'exclusive-sheet'+ ? ['pivot-table']+ : [],+ }],+ ]);+ const accessor = { get: (token: unknown) => services.get(token) } as never;+ const states: boolean[] = [];+ const subscription = getCurrentExclusiveRangeInterest$(accessor).subscribe((state) => states.push(state));++ expect(states[states.length - 1]).toBe(true);++ activeSheet$.next(worksheets.regular);++ expect(states[states.length - 1]).toBe(false);+ subscription.unsubscribe();+ });+});++function createSelection(sheetId: string): ISelectionWithStyle {+ return {+ range: {+ unitId: 'unit-1',+ sheetId,+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ },+ primary: null,+ };+}diff --git a/packages/sheets-ui/src/menu/menu-util.ts b/packages/sheets-ui/src/menu/menu-util.tsindex 303f5168b3..25419c6145 100644--- a/packages/sheets-ui/src/menu/menu-util.ts+++ b/packages/sheets-ui/src/menu/menu-util.ts@@ -89,23 +89,29 @@ export function getCurrentExclusiveRangeInterest$(accessor: IAccessor, disableGrif (!workbook) {return of(false);}- return combineLatest([selectionManagerService.selectionMoveEnd$, workbook.activeSheet$]).pipe(- switchMap(([selections, worksheet]) => {+ return workbook.activeSheet$.pipe(+ switchMap((worksheet) => {if (!worksheet) {return of(false);}- if (selections.length === 0) {- return of(false);- }- const interestGroupIds = exclusiveRangeService.getInterestGroupId(selections);- // if disableGroupSet is provided, check if the interestGroupIds contains any of the disableGroupSet- if (disableGroupSet) {- const disableGroup = interestGroupIds.filter((groupId) => disableGroupSet.has(groupId));- return of(disableGroup.length > 0);- } else {- return of(interestGroupIds.length > 0);- }+ return selectionManagerService.selectionMoveEnd$.pipe(+ map(() => selectionManagerService.getCurrentSelections()),+ startWith(selectionManagerService.getCurrentSelections()),+ map((selections) => {+ if (selections.length === 0) {+ return false;+ }++ const interestGroupIds = exclusiveRangeService.getInterestGroupId([...selections]);+ // if disableGroupSet is provided, check if the interestGroupIds contains any of the disableGroupSet+ if (disableGroupSet) {+ return interestGroupIds.some((groupId) => disableGroupSet.has(groupId));+ }++ return interestGroupIds.length > 0;+ })+ );}));})diff --git a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.tsindex 24e8f48591..708b50d9ae 100644--- a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts+++ b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts@@ -530,7 +530,16 @@ describe('SheetCanvasPopManagerService', () => {});it('updates cell and range anchors when sheet geometry changes', () => {- const { service, popupService, commandService, clientRect$, transformChange$, refRangeService, viewport } = createSheetHarness();+ const {+ service,+ popupService,+ commandService,+ clientRect$,+ transformChange$,+ refRangeService,+ viewport,+ viewMainScrollAfter$,+ } = createSheetHarness();service.attachPopupToCell(1, 1, { componentKey: 'cell-action' } as never, 'unit-1', 'sheet-1', viewport as never);const cellPopup = popupService.lastPopup()!;@@ -553,16 +562,21 @@ describe('SheetCanvasPopManagerService', () => {const rangePositions: unknown[] = [];rangePopup.anchorRect$!.subscribe((position) => rangePositions.push(position));+ viewport.viewportScrollX = 5;+ viewport.viewportScrollY = 4;+ viewMainScrollAfter$.emit({});+ expect(rangePositions[rangePositions.length - 1]).toEqual({ left: 0, right: 120, top: 12, bottom: 92 });+commandService.emit(SetScrollOperation.id);commandService.emit(SetFrozenMutation.id);- expect(rangePositions[rangePositions.length - 1]).toEqual({ left: 10, right: 130, top: 20, bottom: 100 });+ expect(rangePositions[rangePositions.length - 1]).toEqual({ left: 0, right: 120, top: 12, bottom: 92 });const rangeWatch = refRangeService.watchedRanges[1];rangeWatch.callback({ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 });- expect(rangePositions[rangePositions.length - 1]).toEqual({ left: 70, right: 190, top: 60, bottom: 140 });+ expect(rangePositions[rangePositions.length - 1]).toEqual({ left: 60, right: 180, top: 52, bottom: 132 });rangeWatch.callback({ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.tsindex 138269150e..c7d689e097 100644--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts@@ -538,7 +538,7 @@ export class SheetCanvasPopManagerService extends Disposable {* @param _unitId* @param _subUnitId* @param viewport- * @returns+ * @returns A disposable that detaches the popup, or `null` if it cannot be attached.*/attachPopupToCell(row: number, col: number, popup: ICanvasPopup, _unitId?: string, _subUnitId?: string, viewport?: Viewport): Nullable<INeedCheckDisposable> {let workbook = _unitId@@ -847,8 +847,7 @@ export class SheetCanvasPopManagerService extends Disposable {/*** Unlike _createCellPositionObserver, this accept a range not a single cell.- * @param initialRow- * @param initialCol+ * @param range* @param currentRender* @param skeleton* @param activeViewport@@ -893,6 +892,8 @@ export class SheetCanvasPopManagerService extends Disposable {}}));+ disposable.add(activeViewport.onScrollAfter$.subscribeEvent(() => updatePosition()));+const updateRange = (newRange: IRange) => {startRow = newRange.startRow;startColumn = newRange.startColumn;diff --git a/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx b/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsxindex 8fb3efa15a..3ddf13a960 100644--- a/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx+++ b/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx@@ -14,25 +14,13 @@* limitations under the License.*/-import type { ICommandInfo } from '@univerjs/core';-import { ICommandService, IUniverInstanceService, LocaleService, toDisposable } from '@univerjs/core';+import { ICommandService, LocaleService } from '@univerjs/core';import { borderClassName, clsx, DropdownMenu } from '@univerjs/design';-import { convertTransformToOffsetX, convertTransformToOffsetY, IRenderManagerService } from '@univerjs/engine-render';import { AutofillDoubleIcon, MoreDownIcon } from '@univerjs/icons';import { AUTO_FILL_APPLY_TYPE, IAutoFillService, RefillCommand } from '@univerjs/sheets';import { ILayoutService, useDependency, useObservable } from '@univerjs/ui';-import { useEffect, useMemo, useReducer, useState } from 'react';+import { useEffect, useState } from 'react';import { map } from 'rxjs';-import { SetScrollOperation } from '../../commands/operations/scroll.operation';-import { getViewportByCell } from '../../common/utils';-import { getSheetObject } from '../../controllers/utils/component-tools';-import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';-import { useActiveWorkbook } from '../hook';--export interface IAnchorPoint {- row: number;- col: number;-}export interface IAutoFillPopupMenuItem {label: string;@@ -47,8 +35,6 @@ export interface IAutoFillPopupMenuProps {export function AutoFillPopupMenu({ DropdownMenuComponent = DropdownMenu }: IAutoFillPopupMenuProps = {}) {const commandService = useDependency(ICommandService);- const univerInstanceService = useDependency(IUniverInstanceService);- const renderManagerService = useDependency(IRenderManagerService);const autoFillService = useDependency(IAutoFillService);const layoutService = useDependency(ILayoutService);const localeService = useDependency(LocaleService);@@ -62,34 +48,8 @@ export function AutoFillPopupMenu({ DropdownMenuComponent = DropdownMenu }: IAut[autoFillService]);const [visible, setVisible] = useState(false);- const anchor = useObservable(- () => autoFillService.showMenu$.pipe(map((show) => {- const { source, target } = autoFillService.autoFillLocation || { source: null, target: null };- if (!show || !source || !target) {- return { row: -1, col: -1 };- }-- return {- row: Math.max(source.rows[source.rows.length - 1], target.rows[target.rows.length - 1]),- col: Math.max(source.cols[source.cols.length - 1], target.cols[target.cols.length - 1]),- };- })),- { row: -1, col: -1 },- false,- [autoFillService]- );const selected = useObservable(autoFillService.applyType$, AUTO_FILL_APPLY_TYPE.SERIES);const [isHovered, setIsHovered] = useState(false);- const [, forceUpdate] = useReducer((version: number) => version + 1, 0);- const workbook = useActiveWorkbook();- const sheetSkeletonManagerService = useMemo(() => {- if (workbook) {- const ru = renderManagerService.getRenderUnitById(workbook.getUnitId());- return ru?.with(SheetSkeletonManagerService);- }-- return null;- }, [workbook, renderManagerService]);const handleMouseEnter = () => {setIsHovered(true);@@ -99,26 +59,6 @@ export function AutoFillPopupMenu({ DropdownMenuComponent = DropdownMenu }: IAutsetIsHovered(false);};- useEffect(() => {- const disposable = commandService.onCommandExecuted((command: ICommandInfo) => {- if (command.id === SetScrollOperation.id) {- forceUpdate();- }- });- return disposable.dispose;- }, [forceUpdate, commandService]);-- useEffect(() => {- const disposable = sheetSkeletonManagerService && toDisposable(- sheetSkeletonManagerService.currentSkeleton$.subscribe((skeleton) => {- if (skeleton) {- forceUpdate();- }- })- );- return disposable?.dispose;- }, [sheetSkeletonManagerService, forceUpdate]);-useEffect(() => {function handleClose() {setVisible(false);@@ -129,29 +69,8 @@ export function AutoFillPopupMenu({ DropdownMenuComponent = DropdownMenu }: IAutreturn () => {document.removeEventListener('wheel', handleClose);};- }, [visible]);-- if (anchor.col < 0 || anchor.row < 0) {- return null;- }-- const sheetObject = getSheetObject(univerInstanceService, renderManagerService);- if (!sheetObject || !workbook) return null;-- const { scene } = sheetObject;- const skeleton = sheetSkeletonManagerService?.getCurrentSkeleton();- const viewport = getViewportByCell(anchor.row, anchor.col, scene, workbook.getActiveSheet());- if (!viewport) return null;- const scaleX = scene?.scaleX;- const scaleY = scene?.scaleY;- const scrollXY = scene?.getViewportScrollXY(viewport);- if (!scaleX || !scene || !scaleX || !scaleY || !scrollXY) return null;- const x = skeleton?.getNoMergeCellWithCoordByIndex(anchor.row, anchor.col).endX || 0;- const y = skeleton?.getNoMergeCellWithCoordByIndex(anchor.row, anchor.col).endY || 0;- const relativeX = convertTransformToOffsetX(x, scaleX, scrollXY);- const relativeY = convertTransformToOffsetY(y, scaleY, scrollXY);+ }, []);- if (relativeX == null || relativeY == null) return null;const onVisibleChange = (visible: boolean) => {setVisible(visible);};@@ -165,13 +84,8 @@ export function AutoFillPopupMenu({ DropdownMenuComponent = DropdownMenu }: IAutconst availableMenu = menu.filter((item) => !item.disable);return (- <div className="univer-absolute univer-z-10 univer-size-0" style={{ left: 0, top: 0 }}>- <div- className="univer-absolute"- style={{ left: `${relativeX + 2}px`, top: `${relativeY + 2}px` }}- onMouseEnter={handleMouseEnter}- onMouseLeave={handleMouseLeave}- >+ <div className="univer-relative univer-size-0">+ <div className="univer-absolute univer-left-0 univer-top-0"><DropdownMenuComponentalign="start"onCloseAutoFocus={(event) => {@@ -188,6 +102,8 @@ export function AutoFillPopupMenu({ DropdownMenuComponent = DropdownMenu }: IAutonOpenChange={onVisibleChange}><div+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}className={clsx(`univer-flex univer-items-center univer-gap-2 univer-rounded univer-p-1hover:univer-bg-gray-100diff --git a/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsx b/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsxindex 9b8cb2b370..15ce9374c9 100644--- a/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsx+++ b/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsx@@ -25,14 +25,12 @@ import {Univer,UniverInstanceType,} from '@univerjs/core';-import { IRenderManagerService } from '@univerjs/engine-render';import { AUTO_FILL_APPLY_TYPE, IAutoFillService, RefillCommand } from '@univerjs/sheets';import { ILayoutService, RediContext } from '@univerjs/ui';import { act } from 'react';import { createRoot } from 'react-dom/client';import { BehaviorSubject } from 'rxjs';import { afterEach, describe, expect, it } from 'vitest';-import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';import { AutoFillPopupMenu } from '../AutoFillPopupMenu';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -48,25 +46,11 @@ class TestAutoFillService {readonly menu$ = this._menu$.asObservable();- private readonly _showMenu$ = new BehaviorSubject(false);- readonly showMenu$ = this._showMenu$.asObservable();-private readonly _applyType$ = new BehaviorSubject(AUTO_FILL_APPLY_TYPE.SERIES);readonly applyType$ = this._applyType$.asObservable();- autoFillLocation = {- source: { rows: [0], cols: [0] },- target: { rows: [0, 1], cols: [0, 1] },- unitId: UNIT_ID,- subUnitId: SHEET_ID,- };-readonly refillTypes: AUTO_FILL_APPLY_TYPE[] = [];- setShowMenu(show: boolean): void {- this._showMenu$.next(show);- }-fillData(type: AUTO_FILL_APPLY_TYPE): boolean {this.refillTypes.push(type);this._applyType$.next(type);@@ -74,51 +58,6 @@ class TestAutoFillService {}}-class TestSheetSkeletonManagerService {- readonly currentSkeleton$ = new BehaviorSubject({});-- getCurrentSkeleton() {- return {- getNoMergeCellWithCoordByIndex: () => ({ endX: 80, endY: 40 }),- };- }-}--class TestRenderUnit {- readonly components = new Map();- readonly mainComponent = {};- readonly engine = {};- readonly sheetSkeletonManagerService = new TestSheetSkeletonManagerService();- readonly scene = {- scaleX: 1,- scaleY: 1,- getViewport: () => ({}),- getViewportScrollXY: () => ({ x: 0, y: 0 }),- getEngine: () => ({- getCanvas: () => ({- getWidth: () => 400,- getHeight: () => 300,- }),- }),- };-- with(token: unknown): unknown {- if (token === SheetSkeletonManagerService) {- return this.sheetSkeletonManagerService;- }-- return null;- }-}--class TestRenderManagerService {- readonly renderUnit = new TestRenderUnit();-- getRenderUnitById(): TestRenderUnit {- return this.renderUnit;- }-}-class TestLayoutService {focusCount = 0;menuOpenWhenFocused = false;@@ -151,7 +90,6 @@ function createAutoFillPopupTestBed() {const univer = new Univer();const injector = univer.__getInjector();- injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);injector.add([IAutoFillService, { useClass: TestAutoFillService as never }]);injector.add([ILayoutService, { useClass: TestLayoutService as never }]);@@ -228,10 +166,6 @@ describe('AutoFillPopupMenu', () => {root = rendered.root;container = rendered.container;- act(() => {- autoFillService.setShowMenu(true);- });-const trigger = rendered.container.querySelector('[data-slot="dropdown-menu-trigger"]');if (!(trigger instanceof HTMLElement)) {throw new TypeError('Auto fill menu trigger not found');@@ -245,16 +179,11 @@ describe('AutoFillPopupMenu', () => {it('restores focus after selecting an auto fill option', async () => {currentBed = createAutoFillPopupTestBed();- const autoFillService = currentBed.injector.get(IAutoFillService) as unknown as TestAutoFillService;const layoutService = currentBed.injector.get(ILayoutService) as unknown as TestLayoutService;const rendered = renderWithDependencies(<AutoFillPopupMenu />, currentBed.injector);root = rendered.root;container = rendered.container;- act(() => {- autoFillService.setShowMenu(true);- });-const trigger = rendered.container.querySelector('[data-slot="dropdown-menu-trigger"]');if (!(trigger instanceof HTMLElement)) {throw new TypeError('Auto fill menu trigger not found');@@ -266,30 +195,4 @@ describe('AutoFillPopupMenu', () => {await expect.poll(() => layoutService.focusCount).toBe(1);expect(layoutService.menuOpenWhenFocused).toBe(false);});-- it('keeps the overlay origin on the physical left edge in rtl', () => {- currentBed = createAutoFillPopupTestBed();- currentBed.injector.get(LocaleService).setDirection('rtl');- const autoFillService = currentBed.injector.get(IAutoFillService) as unknown as TestAutoFillService;- const rendered = renderWithDependencies(<AutoFillPopupMenu />, currentBed.injector);- root = rendered.root;- container = rendered.container;-- act(() => {- autoFillService.setShowMenu(true);- });-- const trigger = rendered.container.querySelector('[data-slot="dropdown-menu-trigger"]');- if (!(trigger instanceof HTMLElement)) {- throw new TypeError('Auto fill menu trigger not found');- }-- const overlay = trigger.parentElement?.parentElement;- if (!(overlay instanceof HTMLElement)) {- throw new TypeError('Auto fill menu overlay not found');- }-- expect(overlay.style.left).toBe('0px');- expect(overlay.style.right).toBe('');- });});diff --git a/packages/sheets-ui/src/views/auto-fill-popup-menu/component-name.ts b/packages/sheets-ui/src/views/auto-fill-popup-menu/component-name.tsnew file mode 100644index 0000000000..1e2141a429--- /dev/null+++ b/packages/sheets-ui/src/views/auto-fill-popup-menu/component-name.ts@@ -0,0 +1,17 @@+/**+ * 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.+ */++export const AUTO_FILL_POPUP_MENU_COMPONENT = 'sheets.component.auto-fill-popup-menu';diff --git a/packages/sheets-ui/src/views/mobile/sheet-container/MobileRenderSheetContent.tsx b/packages/sheets-ui/src/views/mobile/sheet-container/MobileRenderSheetContent.tsxindex a980e1fba5..bc143e454c 100644--- a/packages/sheets-ui/src/views/mobile/sheet-container/MobileRenderSheetContent.tsx+++ b/packages/sheets-ui/src/views/mobile/sheet-container/MobileRenderSheetContent.tsx@@ -17,5 +17,5 @@import { RenderSheetContent } from '../../sheet-container/SheetContainer';export function MobileRenderSheetContent() {- return <RenderSheetContent AutoFillPopupMenuComponent={null} />;+ return <RenderSheetContent />;}diff --git a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsxindex 39023af1d4..3847435ee6 100644--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx@@ -30,7 +30,6 @@ import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';import { getEmbedSheetsTabCustomData } from '../../embed-tab-anchor';import { ISheetEmbedRuntimeFocusCoordinator } from '../../services/sheet-embed-integration.service';import { ISheetEmbedRuntimeService } from '../../services/sheet-embed-runtime.service';-import { AutoFillPopupMenu } from '../auto-fill-popup-menu/AutoFillPopupMenu';import { EditorContainer } from '../editor-container/EditorContainer';import { FormulaBar } from '../formula-bar/FormulaBar';import { useActiveWorkbook, useActiveWorksheet } from '../hook';@@ -113,14 +112,7 @@ export function RenderSheetHeader() {return null;}-/**- * We should not write into this component anymore.- */-export interface IRenderSheetContentProps {- AutoFillPopupMenuComponent?: typeof AutoFillPopupMenu | null;-}--export function RenderSheetContent({ AutoFillPopupMenuComponent = AutoFillPopupMenu }: IRenderSheetContentProps = {}) {+export function RenderSheetContent() {const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);const componentManager = useDependency(ComponentManager);const activeWorkbook = useActiveWorkbook();@@ -183,7 +175,6 @@ export function RenderSheetContent({ AutoFillPopupMenuComponent = AutoFillPopupM<>{ShapeTextEditorContainer && <ShapeTextEditorContainer />}{!config?.disableEdit && <CellEditorContainer />}- {AutoFillPopupMenuComponent && <AutoFillPopupMenuComponent />}</>);}