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: improve Docs table menus and comment interactions (#7871)

Univer37238bf58a9f
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-paragraph-placeholder.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-paragraph-placeholder.render-controller.spec.ts
index 0a4267e806..45bd914508 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-paragraph-placeholder.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-paragraph-placeholder.render-controller.spec.ts
@@ -15,9 +15,14 @@
*/
import type { IDocumentBody, IParagraph } from '@univerjs/core';
-import type { IDocumentSkeletonLine, IDocumentSkeletonPage } from '@univerjs/engine-render';
+import type { IDocumentSkeletonLine, IDocumentSkeletonPage, UniverRenderingContext } from '@univerjs/engine-render';
import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DocumentFlavor, NamedStyleType } from '@univerjs/core';
-import { DocumentSkeletonPageType, GlyphType, LineType, setDocsTableRenderViewportProvider } from '@univerjs/engine-render';
+import {
+ DocumentSkeletonPageType,
+ GlyphType,
+ LineType,
+ setDocsTableRenderViewportProvider,
+} from '@univerjs/engine-render';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
drawParagraphPlaceholders,
@@ -359,12 +364,46 @@ describe('doc paragraph placeholder render controller', () => {
}]);
});
+ it('paints hints at half the inherited opacity without fading subsequent document content', () => {
+ const alphaStack: number[] = [];
+ const paintedAlphas: number[] = [];
+ const context = {
+ globalAlpha: 0.8,
+ save() {
+ alphaStack.push(this.globalAlpha);
+ },
+ restore() {
+ this.globalAlpha = alphaStack.pop()!;
+ },
+ beginPath: vi.fn(),
+ clip: vi.fn(),
+ closePath: vi.fn(),
+ rectByPrecision: vi.fn(),
+ fillText() {
+ paintedAlphas.push(this.globalAlpha);
+ },
+ };
+ drawParagraphPlaceholders(context as unknown as UniverRenderingContext, [{
+ fontFamily: 'Arial',
+ fontSize: 16,
+ fontWeight: 'normal',
+ maxWidth: 200,
+ text: 'Hint',
+ x: 20,
+ y: 40,
+ }]);
+ expect(paintedAlphas).toEqual([0.4]);
+ expect(context.globalAlpha).toBe(0.8);
+ expect(alphaStack).toEqual([]);
+ });
+
it('clips long placeholder text instead of scaling its glyphs to maxWidth', () => {
const ctx = {
beginPath: vi.fn(),
clip: vi.fn(),
closePath: vi.fn(),
fillText: vi.fn(),
+ globalAlpha: 1,
rectByPrecision: vi.fn(),
restore: vi.fn(),
save: vi.fn(),
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-paragraph-placeholder.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-paragraph-placeholder.render-controller.ts
index 5505cefa1e..b7448a2e8c 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-paragraph-placeholder.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-paragraph-placeholder.render-controller.ts
@@ -422,6 +422,7 @@ export function drawParagraphPlaceholders(
): void {
ctx.save();
ctx.fillStyle = color;
+ ctx.globalAlpha *= 0.5;
ctx.textBaseline = 'alphabetic';
for (const placeholder of placeholders) {
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index 6d64fed043..40480103ca 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -175,6 +175,7 @@ export { scrollDocsTableLikeCustomBlockLive } from './embed-docs-custom-block-sc
export type { IDocsTableLikeCustomBlockScrollOptions } from './embed-docs-custom-block-scroll';
export { resolveDocsCustomBlockRenderViewport } from './embed-host-anchor';
export type { IDocsCustomBlockLayoutViewport, IDocsCustomBlockRenderViewportParams } from './embed-host-anchor';
+export { ParagraphSettingMenuFactory } from './menu/context-menu';
export {
AlignMenuItemFactory,
BackgroundColorSelectorMenuItemFactory,
diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
index 4e148cc5ec..09db077eed 100644
--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
+import type { RenderUnit } from '@univerjs/engine-render';
import type { IMutiPageParagraphBound, ITableBound } from '../doc-event-manager.service';
import {
BlockType,
@@ -21,24 +23,181 @@ import {
DOC_RANGE_TYPE,
DocumentBlockRangeType,
DocumentBlockType,
+ DocumentFlavor,
+ IPermissionService,
+ LocaleService,
+ LocaleType,
PresetListType,
+ Univer,
+ UniverInstanceType,
} from '@univerjs/core';
-import { createDocumentPermissionPoint, getDocumentParagraphPermissionObjectId } from '@univerjs/docs';
-import { DocumentEditArea } from '@univerjs/engine-render';
+import {
+ createDocumentPermissionPoint,
+ DocSkeletonManagerService,
+ getDocumentParagraphPermissionObjectId,
+ setDocumentPermissionValue,
+ UniverDocsPlugin,
+} from '@univerjs/docs';
+import {
+ CanvasColorService,
+ DocumentEditArea,
+ Documents,
+ ICanvasColorService,
+ IRenderManagerService,
+ RenderManagerService,
+ Viewport,
+} from '@univerjs/engine-render';
import { UnitAction } from '@univerjs/protocol';
+import {
+ CanvasPopupService,
+ ContextMenuService,
+ DesktopLayoutService,
+ ICanvasPopupService,
+ IContextMenuService,
+ ILayoutService,
+} from '@univerjs/ui';
import { BehaviorSubject, Subject } from 'rxjs';
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it, onTestFinished, vi } from 'vitest';
+import { buildMoveDocBlockActions } from '../../commands/commands/doc-block-move.command';
+import { genTableSource } from '../../commands/commands/table/table';
+import enUS from '../../locale/en-US';
import {
DOC_PARAGRAPH_MENU_COMPONENT_KEY,
DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,
} from '../../views/paragraph-menu/component-keys';
import {
+ DocEventManagerService,
getPreferredParagraphBoundsInRange,
getTableBlockMenuHoverRect,
getTableHorizontalViewportGeometry,
} from '../doc-event-manager.service';
import { DocLayoutInteractionService } from '../doc-layout-interaction.service';
import { DocParagraphMenuService } from '../doc-paragraph-menu.service';
+import { DocCanvasPopManagerService } from '../doc-popup-manager.service';
+import { DocFloatMenuService } from '../float-menu.service';
+import { DocSelectionRenderService } from '../selection/doc-selection-render.service';
+
+describe('focused table menus with real render services', () => {
+ function createFocusedMenuTestBed() {
+ const context = new Proxy({
+ font: '',
+ measureText: (text: string) => ({ width: text.length * 8, actualBoundingBoxAscent: 8, actualBoundingBoxDescent: 2 }),
+ }, { get: (target, key) => key in target ? Reflect.get(target, key) : () => {} });
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as never);
+ const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });
+ onTestFinished(() => {
+ univer.dispose();
+ vi.restoreAllMocks();
+ });
+ univer.registerPlugin(UniverDocsPlugin);
+ const injector = univer.__getInjector();
+ injector.get(LocaleService).setDirection('ltr');
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([IContextMenuService, { useClass: ContextMenuService }]);
+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
+ injector.add([DocCanvasPopManagerService]);
+ const table = genTableSource(1, 1, 200);
+ const tableStream = `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}Cell\r\n${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}`;
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'focused-table-doc',
+ body: {
+ dataStream: `${tableStream}\rBody\r\n`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell' },
+ { startIndex: tableStream.length, paragraphId: 'after-table' },
+ { startIndex: tableStream.length + 5, paragraphId: 'body' },
+ ],
+ tables: [{ tableId: table.tableId, startIndex: 0, endIndex: tableStream.length }],
+ },
+ tableSource: { [table.tableId]: table },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 300, height: 400 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const render = injector.get(IRenderManagerService).createRender(model.getUnitId()) as RenderUnit;
+ render.deactivate();
+ render.engine.resizeBySize(300, 400);
+ const canvas = render.engine.getCanvasElement();
+ canvas.style.width = '300px';
+ vi.spyOn(canvas, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 300, 400));
+ const viewport = new Viewport('viewMain', render.scene, { left: 0, top: 0, width: 300, height: 400 });
+ onTestFinished(() => viewport.dispose());
+ render.addRenderDependencies([[DocSkeletonManagerService], [DocLayoutInteractionService]]);
+ const skeleton = render.with(DocSkeletonManagerService).getSkeleton();
+ const documents = new Documents('focused-table-documents', skeleton);
+ render.mainComponent = documents;
+ render.scene.addObject(documents);
+ render.addRenderDependencies([
+ [DocSelectionRenderService],
+ [DocEventManagerService],
+ [DocFloatMenuService],
+ [DocParagraphMenuService],
+ ]);
+ const service = render.with(DocParagraphMenuService);
+ const bound = render.with(DocEventManagerService).tableBounds.get(table.tableId)!;
+ return { injector, service, bound, render, model };
+ }
+
+ it('keeps a focused table trigger independent of paragraph hover and closes each popup independently', () => {
+ const { injector, service, bound, render, model } = createFocusedMenuTestBed();
+ const popups = injector.get(ICanvasPopupService);
+ service.showTableMenu(bound, true);
+ expect(service.focusedTableTarget?.table?.tableId).toBe(bound.tableId);
+ expect(service.focusedTableTarget?.moveRange.endOffset)
+ .toBe(service.focusedTableTarget!.table!.endIndex + 1);
+ const sourceRange = service.focusedTableTarget!.moveRange;
+ const snapshot = model.getSnapshot();
+ const moved = buildMoveDocBlockActions({
+ documentData: snapshot,
+ sourceRange,
+ targetOffset: snapshot.body!.dataStream.length - 1,
+ });
+ expect(moved.nextDocumentData.body!.dataStream.endsWith('\r\n')).toBe(true);
+ const restored = buildMoveDocBlockActions({
+ documentData: moved.nextDocumentData,
+ sourceRange: moved.movedRange,
+ targetOffset: sourceRange.startOffset,
+ });
+ expect(restored.nextDocumentData.body).toEqual(snapshot.body);
+ service.showParagraphMenu(createParagraphBound({ paragraphStart: 3, paragraphEnd: 7, startIndex: 7 }));
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
+ expect(popups.popups).toHaveLength(2);
+ service.setParagraphMenuActive(true, true);
+ service.hideParagraphMenu(true);
+ expect(popups.popups).toHaveLength(1);
+ expect(render.with(DocLayoutInteractionService).isActive).toBe(true);
+ const dismiss = vi.fn();
+ const subscription = service.focusedTableMenuDismiss$.subscribe(dismiss);
+ onTestFinished(() => subscription.unsubscribe());
+ popups.popups[0][1].onClickOutside?.(new PointerEvent('pointerdown'));
+ expect(dismiss).toHaveBeenCalledOnce();
+ expect(service.focusedTableTarget?.table?.tableId).toBe(bound.tableId);
+ service.hideFocusedTableMenu();
+ expect(popups.popups).toHaveLength(0);
+ expect(render.with(DocLayoutInteractionService).isActive).toBe(false);
+ });
+
+ it('releases focused popups on permission loss and service disposal', () => {
+ const { injector, service, bound } = createFocusedMenuTestBed();
+ const popups = injector.get(ICanvasPopupService);
+ service.showTableMenu(bound, true);
+ setDocumentPermissionValue(injector.get(IPermissionService), 'focused-table-doc', 'focused-table-doc', UnitAction.Edit, false);
+ expect(service.focusedTableTarget).toBeNull();
+ expect(popups.popups).toHaveLength(0);
+ setDocumentPermissionValue(injector.get(IPermissionService), 'focused-table-doc', 'focused-table-doc', UnitAction.Edit, true);
+ service.showTableMenu(bound, true);
+ expect(popups.popups).toHaveLength(1);
+ service.dispose();
+ expect(popups.popups).toHaveLength(0);
+ });
+});
describe('DocParagraphMenuService', () => {
it('shows the paragraph menu for empty paragraphs', () => {
diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
index c2986d10fd..0173b20747 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -46,7 +46,7 @@ import {
getDocumentEditTargetObjectIds,
} from '@univerjs/docs';
import { DocumentEditArea } from '@univerjs/engine-render';
-import { BehaviorSubject, combineLatest, first, throttleTime } from 'rxjs';
+import { BehaviorSubject, combineLatest, first, Subject, throttleTime } from 'rxjs';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
import { isHorizontalLineParagraph } from '../utils/horizontal-line';
import {
@@ -149,6 +149,17 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
private readonly _activeTarget$ = new BehaviorSubject<IDocBlockMenuTarget | null>(null);
readonly activeTarget$ = this._activeTarget$.asObservable();
+ private _focusedTableMenu: {
+ target: IDocBlockMenuTarget;
+ bound: ITableBound;
+ disposable: INeedCheckDisposable;
+ active: boolean;
+ } | null = null;
+
+ private readonly _focusedTableTarget$ = new BehaviorSubject<IDocBlockMenuTarget | null>(null);
+ readonly focusedTableTarget$ = this._focusedTableTarget$.asObservable();
+ private readonly _focusedTableMenuDismiss$ = new Subject<void>();
+ readonly focusedTableMenuDismiss$ = this._focusedTableMenuDismiss$.asObservable();
private readonly _slashMenuRequest$ = new BehaviorSubject<IDocSlashMenuRequest | null>(null);
readonly slashMenuRequest$ = this._slashMenuRequest$.asObservable();
private _isBlockMenuDragging = false;
@@ -165,6 +176,10 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
return this._paragraphMenu?.target ?? null;
}
+ get focusedTableTarget() {
+ return this._focusedTableMenu?.target ?? null;
+ }
+
setBlockMenuDragging(isDragging: boolean) {
this._isBlockMenuDragging = isDragging;
if (isDragging) {
@@ -204,6 +219,9 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
this._isBlockMenuDragging = false;
this.hideParagraphMenu(true);
}
+ if (this._focusedTableMenu && !this._canEditDocument(this._focusedTableMenu.target.menuRange)) {
+ this.hideFocusedTableMenu();
+ }
}));
}
@@ -267,11 +285,12 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
return this._hasExpandedSelectionRanges(this._docSelectionManagerService.getDocRanges());
}
- setParagraphMenuActive(active: boolean) {
- if (this._paragraphMenu) {
- this._paragraphMenu.active = active;
+ setParagraphMenuActive(active: boolean, focusedTable = false) {
+ const menu = focusedTable ? this._focusedTableMenu : this._paragraphMenu;
+ if (menu) {
+ menu.active = active;
}
- if (active && this._paragraphMenu) {
+ if (this._paragraphMenu?.active || this._focusedTableMenu?.active) {
this._menuInteraction ??= this._docLayoutInteractionService.beginInteraction();
} else {
this._menuInteraction?.dispose();
@@ -284,6 +303,9 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
if (this._isBlockMenuDragging) {
return;
}
+ if (this._focusedTableMenu?.active) {
+ return;
+ }
if (this._docSelectionRenderService.isOnPointerEvent) {
this.hideParagraphMenu(true);
@@ -366,6 +388,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
lastScrollY = e.scrollY;
+ this._focusedTableMenuDismiss$.next();
if (this._paragraphMenu?.blockRange) {
return;
}
@@ -391,6 +414,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
return;
}
+ this._focusedTableMenuDismiss$.next();
this.hideParagraphMenu(true);
}));
@@ -589,8 +613,11 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
this._activeTarget$.next(target);
}
- showTableMenu(tableBound: ITableBound) {
- if (this._hasExpandedTextSelection()) {
+ showTableMenu(tableBound: ITableBound, focused = false) {
+ if (!focused && this._focusedTableMenu?.target.table?.tableId === tableBound.tableId) {
+ return;
+ }
+ if (!focused && this._hasExpandedTextSelection()) {
this.hideParagraphMenu(true);
return;
}
@@ -598,6 +625,9 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
const body = this._context.unit.getBody();
const table = body?.tables?.find((item) => item.tableId === tableBound.tableId);
if (!table) {
+ if (focused) {
+ this.hideFocusedTableMenu();
+ }
return;
}
@@ -613,21 +643,26 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
},
moveRange: {
startOffset: table.startIndex,
- endOffset: table.endIndex,
+ // Move the trailing empty paragraph with the table to retain the body terminator at the document end.
+ endOffset: table.endIndex + (body?.dataStream[table.endIndex] === '\r' ? 1 : 0),
},
emptyMode: false,
draggable: true,
};
if (!this._canEditDocument(target.menuRange)) {
+ if (focused) {
+ this.hideFocusedTableMenu();
+ return;
+ }
this.hideParagraphMenu(true);
return;
}
- if (this._shouldKeepCurrentCellMenuForTable(table)) {
+ if (!focused && this._shouldKeepCurrentCellMenuForTable(table)) {
return;
}
- if (this._paragraphMenu?.target.key === target.key) {
+ if (!focused && this._paragraphMenu?.target.key === target.key) {
return;
}
@@ -642,8 +677,22 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
firstLine: anchorRect,
};
+ if (focused) {
+ target.paragraph = paragraph;
+ this._showFocusedTableMenu(tableBound, target);
+ return;
+ }
+
+ this._showHoverTableMenu(tableBound, target, paragraph);
+ }
+
+ private _showHoverTableMenu(
+ tableBound: ITableBound,
+ target: IDocBlockMenuTarget,
+ paragraph: IMutiPageParagraphBound
+ ): void {
this.hideParagraphMenu(true);
- const getFirstLine = () => getTableAnchorRect(this._docEventManagerService.tableBounds.get(table.tableId) ?? tableBound);
+ const getFirstLine = () => getTableAnchorRect(this._docEventManagerService.tableBounds.get(tableBound.tableId) ?? tableBound);
const disposable = this._docPopupManagerService.attachPopupToRect(
getFirstLine,
{
@@ -668,6 +717,34 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
this._activeTarget$.next(target);
}
+ private _showFocusedTableMenu(tableBound: ITableBound, target: IDocBlockMenuTarget): void {
+ if (this._focusedTableMenu?.target.key === target.key) {
+ this._focusedTableMenu.target = target;
+ this._focusedTableMenu.bound = tableBound;
+ this._focusedTableTarget$.next(target);
+ return;
+ }
+
+ this.hideFocusedTableMenu();
+ if (this._paragraphMenu?.target.key === target.key) {
+ this.hideParagraphMenu(true);
+ }
+ const getFocusedAnchor = () => getTableAnchorRect(
+ this._docEventManagerService.tableBounds.get(tableBound.tableId) ?? this._focusedTableMenu?.bound ?? tableBound
+ );
+ const disposable = this._docPopupManagerService.attachPopupToRect(getFocusedAnchor, {
+ componentKey: DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,
+ extraProps: { focusedTableMenu: true },
+ constrainToCanvas: true,
+ requiresStableLayout: false,
+ direction: 'top-right',
+ onClickOutside: () => this._focusedTableMenuDismiss$.next(),
+ zIndex: 102,
+ }, this._context.unitId);
+ this._focusedTableMenu = { target, bound: tableBound, disposable, active: false };
+ this._focusedTableTarget$.next(target);
+ }
+
private _shouldKeepCurrentCellMenuForTable(table: ICustomTable): boolean {
const target = this._paragraphMenu?.target;
if (!target || target.kind === DocumentBlockType.TABLE || !target.cellRange) {
@@ -732,14 +809,20 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
if (this._paragraphMenu && ((this._paragraphMenu.disposable.canDispose() || force))) {
this._paragraphMenu.disposable.dispose();
this._paragraphMenu = null;
- this._menuInteraction?.dispose();
- this._menuInteraction = null;
+ this.setParagraphMenuActive(false);
this._isSlashMenuActive = false;
this._slashMenuRequest$.next(null);
this._activeTarget$.next(null);
}
}
+ hideFocusedTableMenu() {
+ this._focusedTableMenu?.disposable.dispose();
+ this._focusedTableMenu = null;
+ this._focusedTableTarget$.next(null);
+ this.setParagraphMenuActive(false, true);
+ }
+
private _canEditDocument(
range?: { startOffset: number; endOffset: number },
segmentId = ''
@@ -752,6 +835,11 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
override dispose(): void {
+ this._isBlockMenuDragging = false;
+ this.hideFocusedTableMenu();
+ this.hideParagraphMenu(true);
+ this._focusedTableTarget$.complete();
+ this._focusedTableMenuDismiss$.complete();
this._menuInteraction?.dispose();
this._menuInteraction = null;
this._dragInteraction?.dispose();
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index d079bcb1c8..3ad4bcab0e 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -33,6 +33,7 @@ import {
DataStreamTreeTokenType,
DocumentBlockRangeType,
ICommandService,
+ ILogService,
IUniverInstanceService,
JSONX,
LocaleService,
@@ -876,10 +877,12 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const targetRangeRef = useRef<ITextRangeWithStyle | null>(null);
const dragTargetOffsetRef = useRef<number | null>(null);
const dragRangeRef = useRef<{ startOffset: number; endOffset: number } | null>(null);
+ const dragCleanupRef = useRef<(() => void) | null>(null);
const isDraggingRef = useRef(false);
const openMenuRef = useRef<() => void>(() => undefined);
const hoverOpenSchedulerRef = useRef(createParagraphMenuHoverOpenScheduler(() => openMenuRef.current()));
const commandService = useDependency(ICommandService);
+ const logService = useDependency(ILogService);
const localeService = useDependency(LocaleService);
const themeService = useDependency(ThemeService);
const docSelectionManagerService = useDependency(DocSelectionManagerService);
@@ -900,14 +903,24 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const doc = univerInstanceService.getUnit<DocumentDataModel>(popup.unitId, UniverInstanceType.UNIVER_DOC);
const docParagraphMenuService = renderUnit?.with(DocParagraphMenuService);
const docEventManagerService = renderUnit?.with(DocEventManagerService);
- const activeTarget = useObservable(docParagraphMenuService?.activeTarget$);
+ const isFocusedTableMenu = popup.extraProps?.focusedTableMenu === true;
+ const activeTarget = useObservable(isFocusedTableMenu
+ ? docParagraphMenuService?.focusedTableTarget$
+ : docParagraphMenuService?.activeTarget$);
const slashMenuRequest = useObservable(docParagraphMenuService?.slashMenuRequest$);
const paragraph = useObservable(docEventManagerService?.hoverParagraph$);
const paragraphLeft = useObservable(docEventManagerService?.hoverParagraphLeft$);
- const rawActiveTarget = activeTarget ?? docParagraphMenuService?.activeTarget;
- const currentActiveTarget = tableBlockOnly
- ? rawActiveTarget?.kind === 'table' ? rawActiveTarget : null
- : rawActiveTarget?.kind === 'table' ? null : rawActiveTarget;
+ const getActiveTarget = () => {
+ if (isFocusedTableMenu) {
+ return docParagraphMenuService?.focusedTableTarget ?? activeTarget;
+ }
+ return docParagraphMenuService?.activeTarget ?? activeTarget;
+ };
+ const setMenuInteractionActive = (active: boolean) => {
+ docParagraphMenuService?.setParagraphMenuActive(active, isFocusedTableMenu);
+ };
+ const rawActiveTarget = getActiveTarget();
+ const currentActiveTarget = (rawActiveTarget?.kind === 'table') === tableBlockOnly ? rawActiveTarget : null;
const activeParagraphBound = currentActiveTarget?.paragraph ?? docParagraphMenuService?.activeParagraph ?? paragraph ?? paragraphLeft;
const startIndex = activeParagraphBound?.startIndex;
const dataStream = doc?.getBody()?.dataStream ?? '';
@@ -974,13 +987,36 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
// Service-driven dismissal (for example scrolling) can unmount the entire popup.
useLayoutEffect(() => restoreMenuFocus, [restoreMenuFocus]);
- const handleHideMenu = () => {
+ const handleHideMenu = useCallback(() => {
+ hoverOpenSchedulerRef.current.cancel();
restoreMenuFocus();
setVisible(false);
setOpenMode('pointer');
targetRangeRef.current = null;
- setParagraphMenuInteractionActive(docParagraphMenuService, false);
- };
+ docParagraphMenuService?.setParagraphMenuActive(false, isFocusedTableMenu);
+ }, [docParagraphMenuService, isFocusedTableMenu, restoreMenuFocus]);
+
+ useEffect(() => {
+ if (!isFocusedTableMenu || !docParagraphMenuService) {
+ return;
+ }
+ const subscription = docParagraphMenuService.focusedTableMenuDismiss$.subscribe(handleHideMenu);
+ const ownerDocument = popup.canvasElement.ownerDocument;
+ const handleKeydown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ event.stopPropagation();
+ handleHideMenu();
+ }
+ };
+ if (visible) {
+ ownerDocument.addEventListener('keydown', handleKeydown, true);
+ }
+ return () => {
+ subscription.unsubscribe();
+ ownerDocument.removeEventListener('keydown', handleKeydown, true);
+ };
+ }, [docParagraphMenuService, isFocusedTableMenu, handleHideMenu, popup.canvasElement, visible]);
const clearHideTimer = () => {
if (hideTimerRef.current != null) {
@@ -1010,8 +1046,8 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
return;
}
- const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;
- setParagraphMenuInteractionActive(docParagraphMenuService, true);
+ const latestTarget = getActiveTarget();
+ setMenuInteractionActive(true);
const targetRange = latestTarget
? {
...latestTarget.menuRange,
@@ -1078,7 +1114,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
};
const unwrapActiveBlockRange = async () => {
- const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;
+ const latestTarget = getActiveTarget();
if (!latestTarget || latestTarget.kind !== 'blockRange' || !latestTarget.blockRange || !doc?.getBody()) {
return null;
}
@@ -1111,7 +1147,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
};
const executeParagraphMenuOption = async (option: IValueOption) => {
- const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;
+ const latestTarget = getActiveTarget();
const targetRange = getTargetSelectionRange(latestTarget, activeParagraphBound ?? undefined);
const blockRange = getBlockSelectionRange(latestTarget, activeParagraphBound ?? undefined);
const formattingRange = getParagraphFormattingRange(latestTarget, activeParagraphBound ?? undefined);
@@ -1273,16 +1309,17 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const resolvedParagraphMenuType = openMode === 'slash' ? DOC_PARAGRAPH_T_INSERT_MENU_ID : paragraphMenuType;
useEffect(() => () => {
+ dragCleanupRef.current?.();
if (hideTimerRef.current != null) {
window.clearTimeout(hideTimerRef.current);
hideTimerRef.current = null;
}
hoverOpenSchedulerRef.current.cancel();
- setParagraphMenuInteractionActive(docParagraphMenuService, false);
- }, []);
+ docParagraphMenuService?.setParagraphMenuActive(false, isFocusedTableMenu);
+ }, [docParagraphMenuService, isFocusedTableMenu]);
useEffect(() => {
- if (!slashMenuRequest || handledSlashRequestNonceRef.current >= slashMenuRequest.nonce) {
+ if (tableBlockOnly || !slashMenuRequest || handledSlashRequestNonceRef.current >= slashMenuRequest.nonce) {
return;
}
@@ -1291,7 +1328,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
clearHideTimer();
isMouseOver.current = false;
handleOpenSlashMenu(slashMenuRequest);
- }, [slashMenuRequest]);
+ }, [slashMenuRequest, tableBlockOnly]);
if (!currentActiveTarget) {
return null;
@@ -1301,20 +1338,22 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
<>
<div
data-u-comp="paragraph-menu"
+ data-u-table-menu={tableBlockOnly ? 'true' : undefined}
+ data-u-focused-table-menu={isFocusedTableMenu ? 'true' : undefined}
ref={anchorRef}
className={clsx(`
univer-mr-1 univer-inline-flex univer-h-7 univer-cursor-pointer univer-items-center univer-gap-1
- univer-rounded-md univer-border univer-border-gray-200 univer-bg-gray-0 univer-px-2 univer-py-0
- univer-shadow-sm univer-transition-colors
+ univer-rounded-md univer-border univer-border-solid univer-border-gray-200 univer-bg-gray-0
+ univer-px-2 univer-py-0 univer-shadow-sm univer-transition-colors
hover:univer-bg-gray-50 hover:univer-shadow-md
- dark:!univer-border-gray-700 dark:!univer-bg-gray-900
+ dark:!univer-border-gray-600 dark:!univer-bg-gray-900
dark:hover:!univer-bg-gray-800
`, {
'univer-bg-gray-100 univer-shadow-md dark:!univer-bg-gray-800': visible,
})}
onMouseEnter={(e) => {
popup.onPointerEnter?.(e);
- setParagraphMenuInteractionActive(docParagraphMenuService, true);
+ setMenuInteractionActive(true);
isMouseOver.current = true;
scheduleOpenMenu();
}}
@@ -1350,7 +1389,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
aria-label={localeService.t<LocaleKey>('docs-ui.doc.blockMenu.dragBlock')}
title={localeService.t<LocaleKey>('docs-ui.doc.blockMenu.dragBlock')}
onPointerDown={(event) => {
- const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;
+ const latestTarget = getActiveTarget();
const moveRange = latestTarget?.moveRange;
if (!moveRange || !latestTarget?.draggable) {
return;
@@ -1388,6 +1427,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
window.removeEventListener('pointerup', handlePointerUp);
window.removeEventListener('pointercancel', handlePointerCancel);
window.removeEventListener('blur', handleWindowBlur);
+ dragCleanupRef.current = null;
const range = dragRangeRef.current;
const targetOffset = dragTargetOffsetRef.current;
dragRangeRef.current = null;
@@ -1405,7 +1445,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
unitId: popup.unitId,
sourceRange: range,
targetOffset,
- });
+ }).catch((error) => logService.error(error));
}
};
const handlePointerUp = (upEvent: PointerEvent) => {
@@ -1427,6 +1467,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
finishDrag(false);
};
+ dragCleanupRef.current = () => finishDrag(false);
window.addEventListener('pointermove', handlePointerMove);
window.addEventListener('pointerup', handlePointerUp);
window.addEventListener('pointercancel', handlePointerCancel);
@@ -1445,7 +1486,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
// Keep hover continuity when the pointer crosses the tiny dead zone between trigger and popup.
onMouseEnter={(e) => {
popup.onPointerEnter?.(e);
- setParagraphMenuInteractionActive(docParagraphMenuService, true);
+ setMenuInteractionActive(true);
isMouseOver.current = true;
clearHideTimer();
}}
@@ -1470,7 +1511,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}}
onMouseEnter={(e) => {
popup.onPointerEnter?.(e);
- setParagraphMenuInteractionActive(docParagraphMenuService, true);
+ setMenuInteractionActive(true);
isMouseOver.current = true;
clearHideTimer();
}}
@@ -1489,7 +1530,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
autoFocusTarget={openMode === 'slash' ? 'container' : undefined}
suppressHoverUntilPointerMove={openMode === 'slash'}
onMenuPointerEnter={() => {
- setParagraphMenuInteractionActive(docParagraphMenuService, true);
+ setMenuInteractionActive(true);
isMouseOver.current = true;
clearHideTimer();
}}
@@ -1503,7 +1544,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
onOptionSelect={async (params) => {
const targetRange = targetRangeRef.current ?? getParagraphMenuTargetRange(activeParagraphBound);
const { commandId, params: commandParams } = getParagraphMenuCommand(params, targetRange);
- const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;
+ const latestTarget = getActiveTarget();
if (latestTarget?.kind === 'table' && commandId && targetRange) {
univerInstanceService.focusUnit(popup.unitId);
diff --git a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
index 9dfd741347..6062014773 100644
--- a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
+++ b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
@@ -23,6 +23,7 @@ import {
dateKit,
generateRandomId,
ICommandService,
+ isSafeUrl,
LOCALE_META,
LocaleService,
RegionService,
@@ -331,8 +332,9 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
)
: (
<div
+ tabIndex={-1}
className={`
- univer-text-sm univer-text-gray-900
+ univer-select-text univer-text-sm univer-text-gray-900
dark:!univer-text-gray-0
`}
>
@@ -351,11 +353,29 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
switch (node.type) {
case 'mention':
return (
- <a className="univer-text-primary-600" key={key}>
+ <span className="univer-text-primary-600" key={key}>
{node.content.label}
{' '}
+ </span>
+ );
+ case 'hyperlink': {
+ const url = node.range.properties?.url;
+ if (!isSafeUrl(url)) {
+ return node.content;
+ }
+ return (
+ <a
+ key={key}
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="univer-text-primary-600 univer-underline"
+ onClick={(event) => event.stopPropagation()}
+ >
+ {node.content}
</a>
);
+ }
default:
return node.content;
}
@@ -516,7 +536,14 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {
'univer-shadow': !resolved && (showHighlight || isHover || location === ThreadCommentTreeLocation.CELL),
})}
style={style}
- onClick={onClick}
+ onClick={(event) => {
+ const selection = event.currentTarget.ownerDocument.getSelection();
+ if (selection && !selection.isCollapsed && selection.anchorNode && selection.focusNode &&
+ event.currentTarget.contains(selection.anchorNode) && event.currentTarget.contains(selection.focusNode)) {
+ return;
+ }
+ onClick?.();
+ }}
onMouseEnter={() => {
onMouseEnter?.();
setIsHover(true);
diff --git a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx
index ce8eac5765..bd0b5df975 100644
--- a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx
+++ b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx
@@ -25,6 +25,7 @@ import {
ConfigService,
ContextService,
createIdentifier,
+ CustomRangeType,
dateKit,
DesktopLogService,
ICommandService,
@@ -63,8 +64,9 @@ import { IShortcutService, ISidebarService, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { BehaviorSubject, Subject } from 'rxjs';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';
+import enUS from '../../locale/en-US';
import { ThreadCommentPanelService } from '../../services/thread-comment-panel.service';
import { transformTextNodes2Document } from '../thread-comment-editor/util';
import { ThreadCommentTree, ThreadCommentTreeLocation } from '../ThreadCommentTree';
@@ -376,14 +378,14 @@ function createComment(overrides: Partial<IThreadComment>): IThreadComment {
};
}
-function createTreeTestBed() {
+function createTreeTestBed(localeDependency: Dependency = [LocaleService, { useClass: TestLocaleService as never }]) {
const injector = new Injector();
const dependencies: Dependency[] = [
[ICommandService, { useClass: CommandService }],
[ILogService, { useClass: DesktopLogService }],
[IContextService, { useClass: ContextService }],
[IConfigService, { useClass: ConfigService }],
- [LocaleService, { useClass: TestLocaleService as never }],
+ localeDependency,
[RegionService],
[IEditorService, { useClass: TestEditorService as never }],
[IRenderManagerService, { useClass: TestRenderManagerService as never }],
@@ -665,6 +667,106 @@ describe('ThreadCommentTree', () => {
expect(container.querySelector('script')).toBeNull();
});
+ it.each([
+ ['https://univer.ai', true],
+ ['mailto:[email protected]', true],
+ ['javascript:alert(1)', false],
+ ['data:text/html,test', false],
+ ['', false],
+ ])('renders the comment URL %s as a navigable link only when safe', (url, navigable) => {
+ const testBed = createTreeTestBed([LocaleService]);
+ const localeService = testBed.injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS });
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ const text = 'Open website';
+ addRootComment(testBed.threadCommentModel, createComment({
+ id: 'link-thread',
+ text: {
+ dataStream: `${text}\r\n`,
+ paragraphs: [{ startIndex: text.length, paragraphId: 'para_comment_link' }],
+ customRanges: [{
+ rangeId: 'comment-link',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 0,
+ endIndex: text.length - 1,
+ properties: { url },
+ }],
+ },
+ }));
+ const onActivate = vi.fn();
+ const rendered = renderTree(
+ testBed.injector,
+ <ThreadCommentTree
+ id="link-thread"
+ unitId={UNIT_ID}
+ subUnitId={SHEET_ID}
+ type={UniverInstanceType.UNIVER_SHEET}
+ getSubUnitName={() => ''}
+ location={ThreadCommentTreeLocation.PANEL}
+ showEdit={false}
+ onClick={onActivate}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ const link = container.querySelector('a');
+ if (!navigable) {
+ expect(link).toBeNull();
+ expect(container.textContent).toContain(text);
+ return;
+ }
+ expect(link?.getAttribute('href')).toBe(url);
+ expect(link?.target).toBe('_blank');
+ expect(link?.rel).toContain('noopener');
+ link!.addEventListener('click', (event) => event.preventDefault());
+ act(() => link!.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
+ expect(onActivate).not.toHaveBeenCalled();
+ });
+
+ it('keeps selected comment text focused without activating its document anchor', () => {
+ const testBed = createTreeTestBed([LocaleService]);
+ const localeService = testBed.injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS });
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ addRootComment(testBed.threadCommentModel, createComment({ id: 'selection-thread' }));
+ const onActivate = vi.fn();
+ const rendered = renderTree(
+ testBed.injector,
+ <ThreadCommentTree
+ id="selection-thread"
+ unitId={UNIT_ID}
+ subUnitId={SHEET_ID}
+ type={UniverInstanceType.UNIVER_SHEET}
+ getSubUnitName={() => ''}
+ location={ThreadCommentTreeLocation.PANEL}
+ showEdit={false}
+ onClick={onActivate}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+ const paragraph = container.querySelector('.univer-break-words')!;
+ const content = paragraph.parentElement!;
+ const selection = document.getSelection()!;
+ content.focus();
+ expect(document.activeElement).toBe(content);
+ const range = document.createRange();
+ range.selectNodeContents(paragraph);
+ selection.removeAllRanges();
+ selection.addRange(range);
+
+ act(() => paragraph.dispatchEvent(new MouseEvent('click', { bubbles: true })));
+ expect(onActivate).not.toHaveBeenCalled();
+ expect(selection.toString()).toBe('selection-thread');
+
+ selection.removeAllRanges();
+ act(() => paragraph.dispatchEvent(new MouseEvent('click', { bubbles: true })));
+ expect(onActivate).toHaveBeenCalledOnce();
+ });
+
it('exposes icon-only thread actions as labeled keyboard controls', () => {
const testBed = createTreeTestBed();
addRootComment(testBed.threadCommentModel, createComment({ id: 'accessible-thread' }));
diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts
index fff411c3d2..b49dca7044 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts
+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts
@@ -14,8 +14,10 @@
* limitations under the License.
*/
+import type { IDocumentBody } from '@univerjs/core';
+import { CustomRangeType } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
-import { focusThreadCommentEditor } from '../util';
+import { focusThreadCommentEditor, transformDocument2TextNodes, transformTextNodes2Document } from '../util';
class TestEditorService {
focusedEditorId = '';
@@ -45,3 +47,69 @@ describe('focusThreadCommentEditor', () => {
expect(editor.focused).toBe(true);
});
});
+
+describe('comment text conversion', () => {
+ it('preserves mixed text, mentions and hyperlink metadata through a round trip', () => {
+ const text = 'Hello @Ada see website.';
+ const body: IDocumentBody = {
+ dataStream: `${text}\r\n`,
+ paragraphs: [{ startIndex: text.length, paragraphId: 'para_comment_round_trip' }],
+ customRanges: [
+ {
+ rangeId: 'person-1',
+ rangeType: CustomRangeType.MENTION,
+ startIndex: 6,
+ endIndex: 9,
+ wholeEntity: true,
+ properties: {},
+ },
+ {
+ rangeId: 'link-1',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 15,
+ endIndex: 21,
+ wholeEntity: false,
+ properties: { url: 'https://univer.ai', textStyleMode: 'text' },
+ },
+ ],
+ };
+
+ const [nodes] = transformDocument2TextNodes(body);
+ expect(nodes.map((node) => node.type)).toEqual(['text', 'mention', 'text', 'hyperlink', 'text']);
+ const restored = transformTextNodes2Document(nodes);
+ expect(restored.dataStream).toBe(body.dataStream);
+ expect(restored.customRanges).toEqual(body.customRanges);
+ });
+
+ it('keeps paragraph boundaries and paragraph-relative hyperlink offsets', () => {
+ const nodes = transformDocument2TextNodes({
+ dataStream: 'Intro\rRead site\r\n',
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'para_comment_intro' },
+ { startIndex: 15, paragraphId: 'para_comment_link' },
+ ],
+ customRanges: [{
+ rangeId: 'link-1',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 11,
+ endIndex: 14,
+ properties: { url: 'https://univer.ai' },
+ }],
+ });
+
+ expect(nodes[0]).toEqual([{ type: 'text', content: 'Intro' }]);
+ expect(nodes[1]).toContainEqual(expect.objectContaining({ type: 'hyperlink', content: 'site' }));
+ expect(transformTextNodes2Document(nodes[1]).customRanges?.[0]).toMatchObject({ startIndex: 5, endIndex: 8 });
+ });
+
+ it('renders unsupported custom range kinds as plain text', () => {
+ const nodes = transformDocument2TextNodes({
+ dataStream: 'field\r\n',
+ paragraphs: [{ startIndex: 5, paragraphId: 'para_comment_unknown_range' }],
+ customRanges: [{ rangeId: 'unknown', rangeType: 999, startIndex: 0, endIndex: 4 }],
+ });
+
+ expect(nodes[0].every((node) => node.type === 'text')).toBe(true);
+ expect(nodes[0].map((node) => node.content).join('')).toBe('field');
+ });
+});
diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts b/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
index b0ed5cebf6..1c26bfbebd 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDocumentBody } from '@univerjs/core';
+import type { ICustomRange, IDocumentBody } from '@univerjs/core';
import type { IThreadCommentMention } from '@univerjs/thread-comment';
import { createParagraphId, createSectionId, CustomRangeType, getBodySlice } from '@univerjs/core';
@@ -32,6 +32,10 @@ export type TextNode = {
} | {
type: 'mention';
content: IThreadCommentMention;
+} | {
+ type: 'hyperlink';
+ content: string;
+ range: ICustomRange;
};
const transformDocument2TextNodesInParagraph = (doc: IDocumentBody) => {
@@ -48,13 +52,14 @@ const transformDocument2TextNodesInParagraph = (doc: IDocumentBody) => {
content: dataStream.slice(lastIndex, range.startIndex),
});
}
- textNodes.push({
- type: 'mention',
- content: {
- label: dataStream.slice(range.startIndex, range.endIndex + 1),
- id: range.rangeId,
- },
- });
+ const content = dataStream.slice(range.startIndex, range.endIndex + 1);
+ if (range.rangeType === CustomRangeType.MENTION) {
+ textNodes.push({ type: 'mention', content: { label: content, id: range.rangeId } });
+ } else if (range.rangeType === CustomRangeType.HYPERLINK) {
+ textNodes.push({ type: 'hyperlink', content, range });
+ } else {
+ textNodes.push({ type: 'text', content });
+ }
lastIndex = range.endIndex + 1;
});
@@ -101,6 +106,12 @@ export const transformTextNodes2Document = (nodes: TextNode[]): IDocumentBody =>
});
break;
}
+ case 'hyperlink': {
+ const startIndex = str.length;
+ str += node.content;
+ customRanges.push({ ...node.range, startIndex, endIndex: str.length - 1 });
+ break;
+ }
default:
break;