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.

feat: support chart element float menu (#7192)

siam5f15f7421808
diff --git a/packages/design/src/components/accordion/Accordion.tsx b/packages/design/src/components/accordion/Accordion.tsx
index 02fcf1a7a9..7ceeabb93c 100644
--- a/packages/design/src/components/accordion/Accordion.tsx
+++ b/packages/design/src/components/accordion/Accordion.tsx
@@ -20,6 +20,7 @@ import { useState } from 'react';
import { clsx } from '../../helper/clsx';
interface IAccordionItem {
+ id?: string;
label: ReactNode;
children: ReactNode;
}
@@ -27,14 +28,22 @@ interface IAccordionItem {
export interface IAccordionProps {
className?: string;
items: IAccordionItem[];
+ defaultOpenIndex?: number | null;
+ openIndex?: number | null;
+ onOpenIndexChange?: (openIndex: number | null) => void;
}
export function Accordion(props: IAccordionProps) {
- const { className, items } = props;
- const [openIndex, setOpenIndex] = useState<number | null>(null);
+ const { className, defaultOpenIndex = null, items, onOpenIndexChange } = props;
+ const [innerOpenIndex, setInnerOpenIndex] = useState<number | null>(defaultOpenIndex);
+ const openIndex = props.openIndex ?? innerOpenIndex;
const toggleItem = (index: number) => {
- setOpenIndex(openIndex === index ? null : index);
+ const nextOpenIndex = openIndex === index ? null : index;
+ if (props.openIndex === undefined) {
+ setInnerOpenIndex(nextOpenIndex);
+ }
+ onOpenIndexChange?.(nextOpenIndex);
};
return (
@@ -46,7 +55,7 @@ export function Accordion(props: IAccordionProps) {
`, className)}
>
{items.map((item, index) => (
- <div key={index}>
+ <div key={item.id ?? index}>
<button
className={`
univer-box-border univer-flex univer-w-full univer-cursor-pointer univer-items-center
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/drawing-context-menu.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/drawing-context-menu.controller.spec.ts
index 227b2baaa1..a34b0dd332 100644
--- a/packages/sheets-drawing-ui/src/controllers/__tests__/drawing-context-menu.controller.spec.ts
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/drawing-context-menu.controller.spec.ts
@@ -14,15 +14,18 @@
* limitations under the License.
*/
+import { DrawingTypeEnum } from '@univerjs/core';
import { ContextMenuPosition } from '@univerjs/ui';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
+import { DrawingContextMenuService } from '../../services/drawing-context-menu.service';
import { DrawingContextMenuController } from '../drawing-context-menu.controller';
function createController(options?: {
selectedObjects?: Map<string, { oKey: string }>;
drawingLookup?: (oKey: string) => unknown;
scene?: any;
+ drawingContextMenuService?: DrawingContextMenuService;
}) {
const changeEnd$ = new Subject<any>();
const transformer = {
@@ -35,14 +38,16 @@ function createController(options?: {
const contextMenuService = {
triggerContextMenu: vi.fn(),
};
+ const drawingContextMenuService = options?.drawingContextMenuService ?? new DrawingContextMenuService();
const controller = new DrawingContextMenuController(
{ getDrawingOKey: vi.fn(options?.drawingLookup ?? (() => ({ unitId: 'u1' }))) } as any,
contextMenuService as any,
{ getRenderById: vi.fn(() => ({ scene })) } as any,
- { getAllUnitsForType: vi.fn(() => [{ getUnitId: () => 'unit-1' }]) } as any
+ { getAllUnitsForType: vi.fn(() => [{ getUnitId: () => 'unit-1' }]) } as any,
+ drawingContextMenuService
);
- return { controller, changeEnd$, contextMenuService, transformer };
+ return { controller, changeEnd$, contextMenuService, drawingContextMenuService, transformer };
}
describe('DrawingContextMenuController', () => {
@@ -56,6 +61,109 @@ describe('DrawingContextMenuController', () => {
controller.dispose();
});
+ it('uses a drawing-type provider for a single selected drawing', () => {
+ const drawingContextMenuService = new DrawingContextMenuService();
+ const provider = {
+ getContextMenuPosition: vi.fn(() => 'chart-context-menu'),
+ };
+ drawingContextMenuService.registerProvider(DrawingTypeEnum.DRAWING_CHART, provider);
+ const drawing = {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'chart-1',
+ drawingType: DrawingTypeEnum.DRAWING_CHART,
+ };
+ const { controller, changeEnd$, contextMenuService } = createController({
+ drawingLookup: () => drawing,
+ drawingContextMenuService,
+ });
+ const event = { button: 2 };
+
+ changeEnd$.next({ event });
+
+ expect(provider.getContextMenuPosition).toHaveBeenCalledWith({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'chart-1',
+ drawingType: DrawingTypeEnum.DRAWING_CHART,
+ drawing,
+ });
+ expect(contextMenuService.triggerContextMenu).toHaveBeenCalledWith(event, 'chart-context-menu');
+ controller.dispose();
+ });
+
+ it('falls back to the drawing menu when there is no provider', () => {
+ const { controller, changeEnd$, contextMenuService } = createController({
+ drawingLookup: () => ({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'shape-1',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ }),
+ });
+ const event = { button: 2 };
+
+ changeEnd$.next({ event });
+
+ expect(contextMenuService.triggerContextMenu).toHaveBeenCalledWith(event, ContextMenuPosition.DRAWING);
+ controller.dispose();
+ });
+
+ it('keeps the drawing menu for multiple selected drawings', () => {
+ const drawingContextMenuService = new DrawingContextMenuService();
+ const provider = {
+ getContextMenuPosition: vi.fn(() => 'chart-context-menu'),
+ };
+ drawingContextMenuService.registerProvider(DrawingTypeEnum.DRAWING_CHART, provider);
+ const { controller, changeEnd$, contextMenuService } = createController({
+ selectedObjects: new Map([
+ ['chart-1', { oKey: 'chart-1' }],
+ ['chart-2', { oKey: 'chart-2' }],
+ ]),
+ drawingLookup: (oKey) => ({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: oKey,
+ drawingType: DrawingTypeEnum.DRAWING_CHART,
+ }),
+ drawingContextMenuService,
+ });
+ const event = { button: 2 };
+
+ changeEnd$.next({ event });
+
+ expect(provider.getContextMenuPosition).not.toHaveBeenCalled();
+ expect(contextMenuService.triggerContextMenu).toHaveBeenCalledWith(event, ContextMenuPosition.DRAWING);
+ controller.dispose();
+ });
+
+ it('keeps newer providers when an older provider is disposed', () => {
+ const drawingContextMenuService = new DrawingContextMenuService();
+ const firstProvider = {
+ getContextMenuPosition: vi.fn(() => 'first-menu'),
+ };
+ const secondProvider = {
+ getContextMenuPosition: vi.fn(() => 'second-menu'),
+ };
+ const firstDisposable = drawingContextMenuService.registerProvider(DrawingTypeEnum.DRAWING_CHART, firstProvider);
+ drawingContextMenuService.registerProvider(DrawingTypeEnum.DRAWING_CHART, secondProvider);
+
+ firstDisposable.dispose();
+
+ expect(drawingContextMenuService.getContextMenuPosition({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'chart-1',
+ drawingType: DrawingTypeEnum.DRAWING_CHART,
+ drawing: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'chart-1',
+ drawingType: DrawingTypeEnum.DRAWING_CHART,
+ },
+ })).toBe('second-menu');
+ });
+
it('ignores non-right-clicks, empty selections and non-drawing selected objects', () => {
const { controller, changeEnd$, contextMenuService, transformer } = createController({
selectedObjects: new Map(),
diff --git a/packages/sheets-drawing-ui/src/controllers/drawing-context-menu.controller.ts b/packages/sheets-drawing-ui/src/controllers/drawing-context-menu.controller.ts
index 00ac13e46c..4771460527 100644
--- a/packages/sheets-drawing-ui/src/controllers/drawing-context-menu.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/drawing-context-menu.controller.ts
@@ -14,18 +14,20 @@
* limitations under the License.
*/
-import type { Nullable, Workbook } from '@univerjs/core';
+import type { DrawingTypeEnum, IDrawingParam, Nullable, Workbook } from '@univerjs/core';
import { IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';
import { IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
import { ContextMenuPosition, IContextMenuService } from '@univerjs/ui';
+import { IDrawingContextMenuService } from '../services/drawing-context-menu.service';
export class DrawingContextMenuController extends RxDisposable {
constructor(
@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IDrawingContextMenuService private readonly _drawingContextMenuService: IDrawingContextMenuService
) {
super();
@@ -58,14 +60,33 @@ export class DrawingContextMenuController extends RxDisposable {
const selectedObjects = transformer.getSelectedObjectMap();
if (selectedObjects.size === 0) return;
+ const drawings: IDrawingParam[] = [];
for (const object of selectedObjects.values()) {
const oKey = object.oKey;
const drawingParam = this._drawingManagerService.getDrawingOKey(oKey);
if (!drawingParam) return;
+
+ drawings.push(drawingParam);
}
- this._contextMenuService.triggerContextMenu(event, ContextMenuPosition.DRAWING);
+ this._contextMenuService.triggerContextMenu(event, this._getContextMenuPosition(drawings));
}));
}
+
+ private _getContextMenuPosition(drawings: IDrawingParam[]): string {
+ if (drawings.length !== 1) {
+ return ContextMenuPosition.DRAWING;
+ }
+
+ const [drawing] = drawings;
+
+ return this._drawingContextMenuService.getContextMenuPosition({
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ drawingType: drawing.drawingType as DrawingTypeEnum,
+ drawing,
+ }) ?? ContextMenuPosition.DRAWING;
+ }
}
diff --git a/packages/sheets-drawing-ui/src/index.ts b/packages/sheets-drawing-ui/src/index.ts
index c4d05448c6..36031036ed 100644
--- a/packages/sheets-drawing-ui/src/index.ts
+++ b/packages/sheets-drawing-ui/src/index.ts
@@ -38,4 +38,8 @@ export {
SheetCanvasFloatDomManagerService,
} from './services/canvas-float-dom-manager.service';
export type { ICanvasFloatDom, ICanvasFloatDomInfo, IDOMAnchor } from './services/canvas-float-dom-manager.service';
+export { DrawingContextMenuService, IDrawingContextMenuService } from './services/drawing-context-menu.service';
+export type { IDrawingContextMenuProvider, IDrawingContextMenuProviderContext } from './services/drawing-context-menu.service';
+export { SheetDrawingHitTestService } from './services/sheet-drawing-hit-test.service';
+export type { ISheetDrawingDoubleClickEvent, ISheetDrawingHitTestResult } from './services/sheet-drawing-hit-test.service';
export { SheetDrawingAnchor } from './views/sheet-image-panel/SheetDrawingAnchor';
diff --git a/packages/sheets-drawing-ui/src/plugin.ts b/packages/sheets-drawing-ui/src/plugin.ts
index ca574f36d8..f3e713d822 100644
--- a/packages/sheets-drawing-ui/src/plugin.ts
+++ b/packages/sheets-drawing-ui/src/plugin.ts
@@ -51,6 +51,8 @@ import { SheetDrawingUIController } from './controllers/ui.controller';
import { DrawingPopupMenuController } from './menu/drawing-popup-menu.controller';
import { BatchSaveImagesService, IBatchSaveImagesService } from './services/batch-save-images.service';
import { SheetCanvasFloatDomManagerService } from './services/canvas-float-dom-manager.service';
+import { DrawingContextMenuService, IDrawingContextMenuService } from './services/drawing-context-menu.service';
+import { SheetDrawingHitTestService } from './services/sheet-drawing-hit-test.service';
@DependentOn(UniverDrawingPlugin, UniverDocsDrawingPlugin, UniverDrawingUIPlugin, UniverSheetsDrawingPlugin)
export class UniverSheetsDrawingUIPlugin extends Plugin {
@@ -83,6 +85,7 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {
registerDependencies(this._injector, [
[ComponentsController],
[SheetCanvasFloatDomManagerService],
+ [SheetDrawingHitTestService],
[SheetDrawingUIController],
[DrawingPopupMenuController],
[SheetDrawingPrintingController],
@@ -93,6 +96,7 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {
[SheetCellImageAutofillController],
[SheetCellImageCopyPasteController],
[IBatchSaveImagesService, { useClass: BatchSaveImagesService }],
+ [IDrawingContextMenuService, { useClass: DrawingContextMenuService }],
[DrawingContextMenuController],
]);
diff --git a/packages/sheets-drawing-ui/src/services/__tests__/sheet-drawing-hit-test.service.spec.ts b/packages/sheets-drawing-ui/src/services/__tests__/sheet-drawing-hit-test.service.spec.ts
new file mode 100644
index 0000000000..eb8fa8e93d
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/services/__tests__/sheet-drawing-hit-test.service.spec.ts
@@ -0,0 +1,153 @@
+/**
+ * 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 { IDrawingParam } from '@univerjs/core';
+import { DrawingTypeEnum, UniverInstanceType } from '@univerjs/core';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetDrawingHitTestService } from '../sheet-drawing-hit-test.service';
+
+function createDrawing(drawingId: string, subUnitId = 'sheet-1'): IDrawingParam {
+ return {
+ unitId: 'unit-1',
+ subUnitId,
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_CHART,
+ };
+}
+
+function createScene(oKey = 'unit-1#-#sheet-1#-#chart-1') {
+ const handlers = new Set<(event: { offsetX: number; offsetY: number }) => void>();
+ const unsubscribers: Array<ReturnType<typeof vi.fn>> = [];
+ const scene = {
+ pick: vi.fn(() => ({ oKey })),
+ onDblclick$: {
+ subscribeEvent: vi.fn((handler: (event: { offsetX: number; offsetY: number }) => void) => {
+ handlers.add(handler);
+ const unsubscribe = vi.fn(() => handlers.delete(handler));
+ unsubscribers.push(unsubscribe);
+ return { unsubscribe };
+ }),
+ },
+ emitDoubleClick(event: { offsetX: number; offsetY: number }) {
+ Array.from(handlers).forEach((handler) => handler(event));
+ },
+ unsubscribers,
+ };
+
+ return scene;
+}
+
+function createServiceHarness(options: { drawing?: IDrawingParam | null } = {}) {
+ const currentSheet$ = new Subject<unknown>();
+ const renderCreated$ = new Subject<unknown>();
+ const renderDisposed$ = new Subject<string>();
+ const scene = createScene();
+ let currentRender = { unitId: 'unit-1', scene };
+ const drawing = options.drawing === undefined ? createDrawing('chart-1') : options.drawing;
+ const drawingManagerService = {
+ getDrawingOKey: vi.fn(() => drawing),
+ };
+ const workbook = {
+ getUnitId: vi.fn(() => 'unit-1'),
+ getActiveSheet: vi.fn(() => ({ getSheetId: vi.fn(() => 'sheet-1') })),
+ };
+ const renderManagerService = {
+ getRenderById: vi.fn((unitId: string) => unitId === 'unit-1' ? currentRender : null),
+ created$: renderCreated$.asObservable(),
+ disposed$: renderDisposed$.asObservable(),
+ };
+ const service = new SheetDrawingHitTestService(
+ drawingManagerService as never,
+ {
+ getCurrentTypeOfUnit$: vi.fn(() => currentSheet$.asObservable()),
+ getCurrentUnitOfType: vi.fn((type: UniverInstanceType) => type === UniverInstanceType.UNIVER_SHEET ? workbook : null),
+ } as never,
+ renderManagerService as never
+ );
+ const doubleClickEvents: unknown[] = [];
+ const subscription = service.onDoubleClick$.subscribe((event) => doubleClickEvents.push(event));
+
+ return {
+ currentSheet$,
+ doubleClickEvents,
+ drawing,
+ drawingManagerService,
+ renderCreated$,
+ renderDisposed$,
+ renderManagerService,
+ scene,
+ service,
+ setRender(nextRender: typeof currentRender) {
+ currentRender = nextRender;
+ },
+ subscription,
+ };
+}
+
+describe('SheetDrawingHitTestService', () => {
+ it('emits the current sheet drawing on scene double-click', () => {
+ const { doubleClickEvents, drawing, drawingManagerService, scene, service, subscription } = createServiceHarness();
+
+ scene.emitDoubleClick({ offsetX: 140, offsetY: 90 });
+
+ expect(scene.pick).toHaveBeenCalled();
+ expect(drawingManagerService.getDrawingOKey).toHaveBeenCalledWith('unit-1#-#sheet-1#-#chart-1');
+ expect(doubleClickEvents[0]).toMatchObject({
+ drawing,
+ oKey: 'unit-1#-#sheet-1#-#chart-1',
+ offsetX: 140,
+ offsetY: 90,
+ });
+
+ subscription.unsubscribe();
+ service.dispose();
+ });
+
+ it('ignores drawings outside the active sheet', () => {
+ const { doubleClickEvents, scene, service, subscription } = createServiceHarness({
+ drawing: createDrawing('chart-1', 'sheet-2'),
+ });
+
+ scene.emitDoubleClick({ offsetX: 140, offsetY: 90 });
+
+ expect(doubleClickEvents).toHaveLength(0);
+
+ subscription.unsubscribe();
+ service.dispose();
+ });
+
+ it('rebinds when the active workbook render is recreated', () => {
+ const { doubleClickEvents, renderCreated$, scene, service, setRender, subscription } = createServiceHarness();
+ const nextScene = createScene();
+ const nextRender = { unitId: 'unit-1', scene: nextScene };
+
+ setRender(nextRender);
+ renderCreated$.next(nextRender);
+ scene.emitDoubleClick({ offsetX: 140, offsetY: 90 });
+ nextScene.emitDoubleClick({ offsetX: 150, offsetY: 100 });
+
+ expect(scene.unsubscribers[0]).toHaveBeenCalled();
+ expect(doubleClickEvents).toHaveLength(1);
+ expect(doubleClickEvents[0]).toMatchObject({
+ offsetX: 150,
+ offsetY: 100,
+ });
+
+ subscription.unsubscribe();
+ service.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/services/drawing-context-menu.service.ts b/packages/sheets-drawing-ui/src/services/drawing-context-menu.service.ts
new file mode 100644
index 0000000000..28c70be900
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/services/drawing-context-menu.service.ts
@@ -0,0 +1,55 @@
+/**
+ * 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 { DrawingTypeEnum, IDisposable, IDrawingParam } from '@univerjs/core';
+import { createIdentifier, Disposable, toDisposable } from '@univerjs/core';
+
+export interface IDrawingContextMenuProviderContext {
+ unitId: string;
+ subUnitId: string;
+ drawingId: string;
+ drawingType: DrawingTypeEnum;
+ drawing: IDrawingParam;
+}
+
+export interface IDrawingContextMenuProvider {
+ getContextMenuPosition(context: IDrawingContextMenuProviderContext): string | undefined;
+}
+
+export interface IDrawingContextMenuService {
+ registerProvider(drawingType: DrawingTypeEnum, provider: IDrawingContextMenuProvider): IDisposable;
+ getContextMenuPosition(context: IDrawingContextMenuProviderContext): string | undefined;
+}
+
+export const IDrawingContextMenuService = createIdentifier<IDrawingContextMenuService>('sheets-drawing-ui.drawing-context-menu.service');
+
+export class DrawingContextMenuService extends Disposable implements IDrawingContextMenuService {
+ private readonly _providers = new Map<DrawingTypeEnum, IDrawingContextMenuProvider>();
+
+ registerProvider(drawingType: DrawingTypeEnum, provider: IDrawingContextMenuProvider): IDisposable {
+ this._providers.set(drawingType, provider);
+
+ return toDisposable(() => {
+ if (this._providers.get(drawingType) === provider) {
+ this._providers.delete(drawingType);
+ }
+ });
+ }
+
+ getContextMenuPosition(context: IDrawingContextMenuProviderContext): string | undefined {
+ return this._providers.get(context.drawingType)?.getContextMenuPosition(context);
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/services/sheet-drawing-hit-test.service.ts b/packages/sheets-drawing-ui/src/services/sheet-drawing-hit-test.service.ts
new file mode 100644
index 0000000000..7a824e77c3
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/services/sheet-drawing-hit-test.service.ts
@@ -0,0 +1,192 @@
+/**
+ * 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 { IDisposable, IDrawingParam, Workbook } from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRender, Scene } from '@univerjs/engine-render';
+import type { Observable } from 'rxjs';
+import { Disposable, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { IRenderManagerService, Vector2 } from '@univerjs/engine-render';
+import { Subject } from 'rxjs';
+
+export interface ISheetDrawingHitTestResult {
+ drawing: IDrawingParam;
+ oKey: string;
+ offsetX: number;
+ offsetY: number;
+}
+
+export interface ISheetDrawingDoubleClickEvent extends ISheetDrawingHitTestResult {
+ nativeEvent: IPointerEvent | IMouseEvent;
+}
+
+/**
+ * Resolves sheet canvas pointer coordinates to drawing objects.
+ *
+ * Callers consume drawing-level events and should not depend on renderer object
+ * keys, scene picking, or active sheet filtering.
+ */
+export class SheetDrawingHitTestService extends Disposable {
+ private readonly _onDoubleClick$ = new Subject<ISheetDrawingDoubleClickEvent>();
+ readonly onDoubleClick$: Observable<ISheetDrawingDoubleClickEvent> = this._onDoubleClick$.asObservable();
+
+ private _doubleClickDisposable: IDisposable | null = null;
+ private _boundRender: IRender | null = null;
+ private _boundScene: Scene | null = null;
+
+ constructor(
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ override dispose(): void {
+ this._disposeDoubleClickListener();
+ this._onDoubleClick$.complete();
+ super.dispose();
+ }
+
+ hitTestCurrentSheet(offsetX: number, offsetY: number): ISheetDrawingHitTestResult | null {
+ const context = this._getActiveSheetContext();
+ if (!context) {
+ return null;
+ }
+
+ return this.hitTest(context.unitId, context.subUnitId, offsetX, offsetY);
+ }
+
+ hitTest(unitId: string, subUnitId: string, offsetX: number, offsetY: number): ISheetDrawingHitTestResult | null {
+ const scene = this._renderManagerService.getRenderById(unitId)?.scene;
+ if (!scene) {
+ return null;
+ }
+
+ return this._hitTestScene(scene, unitId, subUnitId, offsetX, offsetY);
+ }
+
+ private _init(): void {
+ this.disposeWithMe(toDisposable(
+ this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).subscribe(() => {
+ this._bindDoubleClickListener();
+ })
+ ));
+
+ this.disposeWithMe(toDisposable(
+ this._renderManagerService.created$.subscribe((render) => {
+ const context = this._getActiveSheetContext();
+ if (render.unitId === context?.unitId) {
+ this._bindDoubleClickListener();
+ }
+ })
+ ));
+
+ this.disposeWithMe(toDisposable(
+ this._renderManagerService.disposed$.subscribe((unitId) => {
+ if (unitId === this._boundRender?.unitId) {
+ this._disposeDoubleClickListener();
+ }
+ })
+ ));
+
+ this._bindDoubleClickListener();
+ }
+
+ private _bindDoubleClickListener(): void {
+ const context = this._getActiveSheetContext();
+ if (!context) {
+ this._disposeDoubleClickListener();
+ return;
+ }
+
+ const render = this._renderManagerService.getRenderById(context.unitId);
+ const scene = render?.scene;
+ if (!render || !scene) {
+ this._disposeDoubleClickListener();
+ return;
+ }
+
+ if (this._boundRender === render && this._boundScene === scene && this._doubleClickDisposable) {
+ return;
+ }
+
+ this._disposeDoubleClickListener();
+
+ const subscription = scene.onDblclick$.subscribeEvent((event: IPointerEvent | IMouseEvent) => {
+ const activeContext = this._getActiveSheetContext();
+ if (!activeContext || activeContext.unitId !== context.unitId) {
+ return;
+ }
+
+ const hit = this._hitTestScene(scene, activeContext.unitId, activeContext.subUnitId, event.offsetX, event.offsetY);
+ if (!hit) {
+ return;
+ }
+
+ this._onDoubleClick$.next({
+ ...hit,
+ nativeEvent: event,
+ });
+ });
+
+ this._doubleClickDisposable = { dispose: () => subscription.unsubscribe() };
+ this._boundRender = render;
+ this._boundScene = scene;
+ }
+
+ private _disposeDoubleClickListener(): void {
+ this._doubleClickDisposable?.dispose();
+ this._doubleClickDisposable = null;
+ this._boundRender = null;
+ this._boundScene = null;
+ }
+
+ private _hitTestScene(scene: Scene, unitId: string, subUnitId: string, offsetX: number, offsetY: number): ISheetDrawingHitTestResult | null {
+ const pickedObject = scene.pick(Vector2.FromArray([offsetX, offsetY])) as {
+ oKey?: string;
+ } | null | undefined;
+ const oKey = typeof pickedObject?.oKey === 'string' ? pickedObject.oKey : null;
+ if (!oKey) {
+ return null;
+ }
+
+ const drawing = this._drawingManagerService.getDrawingOKey(oKey);
+ if (!drawing || drawing.unitId !== unitId || drawing.subUnitId !== subUnitId) {
+ return null;
+ }
+
+ return {
+ drawing,
+ oKey,
+ offsetX,
+ offsetY,
+ };
+ }
+
+ private _getActiveSheetContext(): { unitId: string; subUnitId: string } | null {
+ const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const unitId = workbook?.getUnitId();
+ const subUnitId = workbook?.getActiveSheet()?.getSheetId();
+ if (!unitId || !subUnitId) {
+ return null;
+ }
+
+ return { unitId, subUnitId };
+ }
+}
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.ts
index 8e3e020768..b455b8a30e 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
@@ -349,6 +349,36 @@ describe('SheetCanvasPopManagerService', () => {
expect(popupService.removedIds).toEqual(['popup-1']);
});
+ it('keeps dynamic absolute-position popups subscribed to caller-provided anchors', () => {
+ const { service, popupService } = createSheetHarness();
+ const bound = { top: 10, left: 20, right: 30, bottom: 40 };
+ const anchorRect$ = new BehaviorSubject(bound);
+
+ const disposable = service.attachPopupToDynamicAbsolutePosition(
+ bound,
+ anchorRect$,
+ { componentKey: 'dynamic-tooltip' } as never,
+ 'unit-1',
+ 'sheet-1'
+ );
+ const popup = popupService.lastPopup()!;
+ const positions: unknown[] = [];
+ popup.anchorRect$.subscribe((position) => positions.push(position));
+
+ anchorRect$.next({ top: 12, left: 24, right: 34, bottom: 46 });
+
+ expect(popup).toMatchObject({
+ componentKey: 'dynamic-tooltip',
+ anchorRect: bound,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ });
+ expect(positions).toContainEqual({ top: 12, left: 24, right: 34, bottom: 46 });
+
+ disposable?.dispose();
+ expect(popupService.removedIds).toEqual(['popup-1']);
+ });
+
it('anchors a popup to a sheet position and refreshes its hidden freeze area on viewport changes', () => {
const { service, popupService, commandService, transformChange$ } = createSheetHarness();
diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
index a8fe43957b..0af52b7220 100644
--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
@@ -18,6 +18,7 @@ import type { DrawingTypeEnum, ICommandInfo, INeedCheckDisposable, IRange, Nulla
import type { BaseObject, IBoundRectNoAngle, IRender, IShapeProps, Shape, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
import type { ISetWorksheetRowAutoHeightMutationParams, ISheetLocationBase } from '@univerjs/sheets';
import type { IPopup } from '@univerjs/ui';
+import type { Observable } from 'rxjs';
import { Disposable, DisposableCollection, fromEventSubject, ICommandService, Inject, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService, RENDER_CLASS_TYPE } from '@univerjs/engine-render';
import { COMMAND_LISTENER_SKELETON_CHANGE, IRefSelectionsService, RefRangeService, SetFrozenMutation, SetSelectionsOperation, SetWorksheetRowAutoHeightMutation, SheetsSelectionsService } from '@univerjs/sheets';
@@ -387,6 +388,34 @@ export class SheetCanvasPopManagerService extends Disposable {
// #region attach to absolute position
attachPopupToAbsolutePosition(bound: IBoundRectNoAngle, popup: ICanvasPopup, _unitId?: string, _subUnitId?: string) {
+ const position$ = new BehaviorSubject(bound);
+ const disposable = this._attachAbsolutePopup(
+ bound,
+ position$.asObservable(),
+ popup,
+ _unitId,
+ _subUnitId,
+ () => position$.complete()
+ );
+ if (!disposable) {
+ position$.complete();
+ }
+
+ return disposable;
+ }
+
+ attachPopupToDynamicAbsolutePosition(bound: IBoundRectNoAngle, anchorRect$: Observable<IBoundRectNoAngle>, popup: ICanvasPopup, _unitId?: string, _subUnitId?: string) {
+ return this._attachAbsolutePopup(bound, anchorRect$, popup, _unitId, _subUnitId);
+ }
+
+ private _attachAbsolutePopup(
+ bound: IBoundRectNoAngle,
+ anchorRect$: Observable<IBoundRectNoAngle>,
+ popup: ICanvasPopup,
+ _unitId?: string,
+ _subUnitId?: string,
+ onDispose?: () => void
+ ) {
const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
if (!worksheet) {
@@ -410,20 +439,19 @@ export class SheetCanvasPopManagerService extends Disposable {
return;
}
- const position$ = new BehaviorSubject(bound);
const id = this._globalPopupManagerService.addPopup({
...popup,
unitId,
subUnitId,
anchorRect: bound,
- anchorRect$: position$.asObservable(),
+ anchorRect$,
canvasElement: currentRender.engine.getCanvasElement(),
});
return {
dispose: () => {
this._globalPopupManagerService.removePopup(id);
- position$.complete();
+ onDispose?.();
},
canDispose: () => this._globalPopupManagerService.activePopupId !== id,
};
diff --git a/packages/ui/src/services/menu/__tests__/menu-manager.service.spec.ts b/packages/ui/src/services/menu/__tests__/menu-manager.service.spec.ts
index e065c98481..e269b1516a 100644
--- a/packages/ui/src/services/menu/__tests__/menu-manager.service.spec.ts
+++ b/packages/ui/src/services/menu/__tests__/menu-manager.service.spec.ts
@@ -55,6 +55,13 @@ describe('MenuManagerService', () => {
sub.unsubscribe();
});
+ it('returns an empty array for missing menu positions', () => {
+ const service = createService();
+
+ expect(service.getMenuByPositionKey('missing-position')).toEqual([]);
+ expect(service.getFlatMenuByPositionKey('missing-position')).toEqual([]);
+ });
+
it('identifies selector menu item variants used by menu renderers', () => {
expect(isMenuSelectorItem({ id: 'font-family', type: MenuItemType.SELECTOR })).toBe(true);
expect(isMenuSelectorItem({ id: 'more-actions', type: MenuItemType.SUBITEMS })).toBe(true);
diff --git a/packages/ui/src/services/menu/menu-manager.service.ts b/packages/ui/src/services/menu/menu-manager.service.ts
index 91e2986436..700fcea39c 100644
--- a/packages/ui/src/services/menu/menu-manager.service.ts
+++ b/packages/ui/src/services/menu/menu-manager.service.ts
@@ -368,7 +368,7 @@ export class MenuManagerService extends Disposable implements IMenuManagerServic
}
};
- return findKey(this._menu);
+ return findKey(this._menu) ?? [];
}
/**