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(docs): clean up stale range popups (#7618)
wpxp123456e53f36b60137
diff --git a/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.tsindex fd4d3ba5e7..661bfb7dc2 100644--- a/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts+++ b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts@@ -18,6 +18,7 @@ import type { IDocumentData } from '@univerjs/core';import { CustomRangeType, ICommandService, toDisposable, Univer, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { DocHyperLinkPopupService } from '../../../services/hyper-link-popup.service';import {@@ -73,6 +74,7 @@ describe('doc hyperlink popup operations', () => {const injector = univer.__getInjector();injector.add([DocSelectionManagerService]);injector.add([DocCanvasPopManagerService, { useClass: TestDocCanvasPopManagerService as never }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);injector.add([DocHyperLinkPopupService]);univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData());diff --git a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.tsindex 9d3044a4db..4f0ac1c05c 100644--- a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts+++ b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts@@ -15,23 +15,13 @@*/import {- CommandService,- ConfigService,- ContextService,- DesktopLogService,- DocumentDataModel,- ICommandService,- IConfigService,- IContextService,- ILogService,- Injector,IPermissionService,- IUniverInstanceService,- PermissionService,- UniverInstanceService,+ Univer,+ UniverInstanceType,} from '@univerjs/core';import { DocSelectionManagerService, setDocumentPermissionValue } from '@univerjs/docs';import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import { UnitAction } from '@univerjs/protocol';import { describe, expect, it } from 'vitest';import { DocHyperLinkPopupService } from '../hyper-link-popup.service';@@ -50,33 +40,74 @@ class CapturingDocCanvasPopManagerService {const CapturingDocCanvasPopManagerServiceCtor = CapturingDocCanvasPopManagerService as unknown as typeof DocCanvasPopManagerService;function createService() {- const injector = new Injector();- injector.add([ILogService, { useClass: DesktopLogService }]);- injector.add([IConfigService, { useClass: ConfigService }]);- injector.add([IContextService, { useClass: ContextService }]);- injector.add([ICommandService, { useClass: CommandService }]);- injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);- injector.add([IPermissionService, { useClass: PermissionService }]);+ const univer = new Univer();+ const injector = univer.__getInjector();injector.add([DocCanvasPopManagerService, { useClass: CapturingDocCanvasPopManagerServiceCtor }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);injector.add([DocSelectionManagerService]);injector.add([DocHyperLinkPopupService]);- const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;- univerInstanceService.__addUnit(new DocumentDataModel({ id: 'doc-1' }));+ univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'doc-1' });const selectionManager = injector.get(DocSelectionManagerService);selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });const popupManager = injector.get(DocCanvasPopManagerService) as unknown as CapturingDocCanvasPopManagerService;const permissionService = injector.get(IPermissionService);+ const renderManagerService = injector.get(IRenderManagerService);return {service: injector.get(DocHyperLinkPopupService),selectionManager,attached: popupManager.attached,disposed: popupManager.disposed,+ disposeRender: (unitId: string) => {+ renderManagerService.addRender(unitId, {+ unitId,+ type: UniverInstanceType.UNIVER_DOC,+ components: new Map(),+ engine: { dispose: () => {} },+ scene: { dispose: () => {} },+ dispose: () => {},+ } as never);+ renderManagerService.removeRender(unitId);+ },permissionService,};}describe('DocHyperLinkPopupService', () => {+ it('closes link popups only when their owning Render is disposed', () => {+ const { service, disposed, disposeRender } = createService();+ const link = {+ unitId: 'doc-1',+ linkId: 'link-1',+ startIndex: 4,+ endIndex: 8,+ };++ service.showEditPopup('doc-1', link);+ service.showInfoPopup(link);+ disposeRender('doc-2');+ expect(disposed).toEqual([]);++ disposeRender('doc-1');+ expect(disposed).toEqual([1, 2]);+ });++ it('releases owned link popups when the service is disposed', () => {+ const { service, disposed } = createService();+ const link = {+ unitId: 'doc-1',+ linkId: 'link-1',+ startIndex: 4,+ endIndex: 8,+ };++ service.showEditPopup('doc-1', link);+ service.showInfoPopup(link);+ service.dispose();++ expect(disposed).toEqual([1, 2]);+ });+it('opens edit and info popups around the selected document link and disposes previous popups', () => {const { service, selectionManager, attached, disposed } = createService();const refreshes: unknown[] = [];diff --git a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.tsindex 21f5f43792..88b30d95dd 100644--- a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts+++ b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts@@ -17,6 +17,7 @@import { Disposable, DocumentDataModel, Inject, IPermissionService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { canEditDocumentTargets, DocSelectionManagerService, getDocumentEntityParentPermissionObjectIds, getDocumentEntityPermissionObjectId } from '@univerjs/docs';import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import { IRenderManagerService } from '@univerjs/engine-render';import { BehaviorSubject } from 'rxjs';import { DocHyperLinkEdit } from '../views/DocHyperLinkEdit';import { DocLinkPopup } from '../views/DocLinkPopup';@@ -39,6 +40,7 @@ export class DocHyperLinkPopupService extends Disposable {readonly showingLink$ = this._showingLink$.asObservable();private _editPopup: LinkPopupDisposable | null = null;+ private _editPopupUnitId: string | null = null;private _infoPopup: LinkPopupDisposable | null = null;private _infoPopupSuppressed = false;private _infoPopupSuppressionTimer: ReturnType<typeof setTimeout> | null = null;@@ -47,7 +49,8 @@ export class DocHyperLinkPopupService extends Disposable {@Inject(DocCanvasPopManagerService) private readonly _docCanvasPopupManagerService: DocCanvasPopManagerService,@Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @IPermissionService private readonly _permissionService: IPermissionService+ @IPermissionService private readonly _permissionService: IPermissionService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();@@ -69,6 +72,20 @@ export class DocHyperLinkPopupService extends Disposable {this._showingLink$.next({ ...showing });}}));+ this.disposeWithMe(this._renderManagerService.disposed$.subscribe((unitId) => {+ if (this._editPopupUnitId === unitId) {+ this.hideEditPopup();+ }+ if (this.showing?.unitId === unitId) {+ this.hideInfoPopup();+ }+ }));+ }++ override dispose(): void {+ this.hideEditPopup();+ this.hideInfoPopup();+ super.dispose();}get editing() {@@ -85,6 +102,8 @@ export class DocHyperLinkPopupService extends Disposable {}if (this._editPopup) {this._editPopup.dispose();+ this._editPopup = null;+ this._editPopupUnitId = null;}this._editingLink$.next(linkInfo);const textRanges = this._textSelectionManagerService.getTextRanges({ unitId, subUnitId: unitId });@@ -116,6 +135,7 @@ export class DocHyperLinkPopupService extends Disposable {},unitId);+ this._editPopupUnitId = unitId;return this._editPopup;}@@ -125,6 +145,8 @@ export class DocHyperLinkPopupService extends Disposable {hideEditPopup() {this._editingLink$.next(null);this._editPopup?.dispose();+ this._editPopup = null;+ this._editPopupUnitId = null;}showInfoPopup(info: ILinkInfo): LinkPopupDisposable | null | undefined {@@ -146,6 +168,7 @@ export class DocHyperLinkPopupService extends Disposable {if (this._infoPopup) {this._infoPopup.dispose();+ this._infoPopup = null;}const doc = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);if (!(doc instanceof DocumentDataModel)) {@@ -178,6 +201,7 @@ export class DocHyperLinkPopupService extends Disposable {hideInfoPopup() {this._showingLink$.next(null);this._infoPopup?.dispose();+ this._infoPopup = null;}hideInfoPopupOnPointerDown() {diff --git a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.tsindex 35e25bcf1e..532cb30f19 100644--- a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts@@ -55,6 +55,7 @@ class TestCanvasPopupService {class TestRenderManagerService {scale = 1;hasViewport = true;+ throwOnGetOffsetConfig = false;viewportScrollX = 0;viewportScrollY = 0;isMainScene: boolean | undefined = true;@@ -89,10 +90,16 @@ class TestRenderManagerService {},getInjector: this.getInjector,mainComponent: {- getOffsetConfig: () => ({- docsLeft: 0,- docsTop: 0,- }),+ getOffsetConfig: () => {+ if (this.throwOnGetOffsetConfig) {+ throw new TypeError("Cannot read properties of null (reading 'clone')");+ }++ return {+ docsLeft: 0,+ docsTop: 0,+ };+ },},scene: this.getScene(),with: (token: unknown) => {@@ -423,4 +430,31 @@ describe('DocCanvasPopManagerService', () => {rangeSpy.mockRestore();expect(popupService.removedIds).toContain('popup-1');});++ it('keeps the last range popup anchor when its render is stale during refresh', () => {+ const { service, popupService, renderManagerService, commandService } = createService();+ const rangeSpy = vi.spyOn(NodePositionConvertToCursor.prototype, 'getRangePointData').mockImplementation(() => ({+ borderBoxPointGroup: [+ [{ x: 10, y: 10 }, { x: 40, y: 10 }, { x: 40, y: 20 }, { x: 10, y: 20 }],+ ],+ }) as never);++ const disposable = service.attachPopupToRange(+ { startOffset: 0, endOffset: 4, collapsed: false },+ { componentKey: 'stale-range' },+ 'doc-1'+ );+ const popup = popupService.popups.get('popup-1');+ const emittedAnchors: unknown[] = [];+ const anchorSubscription = popup?.anchorRect$?.subscribe((anchor) => emittedAnchors.push(anchor));++ renderManagerService.throwOnGetOffsetConfig = true;++ expect(() => commandService.emit(RichTextEditingMutation.id, { unitId: 'doc-1' })).not.toThrow();+ expect(emittedAnchors.at(-1)).toEqual({ left: 20, right: 50, top: 30, bottom: 40 });++ anchorSubscription?.unsubscribe();+ disposable.dispose();+ rangeSpy.mockRestore();+ });});diff --git a/packages/docs-ui/src/services/doc-popup-manager.service.ts b/packages/docs-ui/src/services/doc-popup-manager.service.tsindex 23c90f220a..9512e8e890 100644--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts@@ -181,7 +181,7 @@ export class DocCanvasPopManagerService extends Disposable {return false;}- const params = commandInfo.params as { unitId?: string } | undefined;+ const params = commandInfo.params as IRichTextEditingMutationParams | undefined;return params?.unitId == null || params.unitId === unitId;}@@ -275,34 +275,33 @@ export class DocCanvasPopManagerService extends Disposable {const positions = calcDocRangePositions(range, currentRender) ?? [];const positions$ = new BehaviorSubject(positions);const disposable = new DisposableCollection();+ const updatePositions = () => {+ try {+ const position = calcDocRangePositions(range, currentRender);+ if (position) {+ positions$.next(position);+ }+ } catch {+ // The popup may outlive an embedded render while its host switches tabs.+ // Keep the last anchor until the popup is disposed.+ }+ };disposable.add(this._commandService.onCommandExecuted((commandInfo) => {- if (commandInfo.id === SetDocZoomRatioOperation.id || commandInfo.id === RichTextEditingMutation.id) {- const params = commandInfo.params as IRichTextEditingMutationParams;- if (params.unitId === currentRender.unitId) {- const position = calcDocRangePositions(range, currentRender);- if (position) {- positions$.next(position);- }- }+ if (this._shouldUpdateForCommand(commandInfo, currentRender.unitId)) {+ updatePositions();}}));const viewMain = currentRender.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);if (viewMain) {disposable.add(viewMain.onScrollAfter$.subscribeEvent(() => {- const position = calcDocRangePositions(range, currentRender);- if (position) {- positions$.next(position);- }+ updatePositions();}));}disposable.add(currentRender.scene.onTransformChange$.subscribeEvent(() => {- const position = calcDocRangePositions(range, currentRender);- if (position) {- positions$.next(position);- }+ updatePositions();}));return {