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-ui): link & checklist can't work on header-footer (#3107)
zhangw106e7c4989bc
diff --git a/packages-experimental/uni-formula-ui/src/controllers/doc-formula-input.controller.ts b/packages-experimental/uni-formula-ui/src/controllers/doc-formula-input.controller.tsindex f7872b182b..456fb6a434 100644--- a/packages-experimental/uni-formula-ui/src/controllers/doc-formula-input.controller.ts+++ b/packages-experimental/uni-formula-ui/src/controllers/doc-formula-input.controller.ts@@ -18,7 +18,7 @@ import { CustomRangeType, Disposable, ICommandService, ILogService, Inject, IUniimport type { IInsertCommandParams } from '@univerjs/docs';import { DeleteLeftCommand, InsertCommand, MoveCursorOperation, TextSelectionManagerService } from '@univerjs/docs';import { IEditorService } from '@univerjs/ui';-import { DocHoverManagerService } from '@univerjs/docs-ui';+import { DocEventManagerService } from '@univerjs/docs-ui';import { AddDocUniFormulaCommand, RemoveDocUniFormulaCommand, UpdateDocUniFormulaCommand } from '../commands/commands/doc.command';import type { IShowFormulaPopupOperationParams } from '../commands/operations/operation';@@ -35,7 +35,7 @@ export class DocUniFormulaInputController extends Disposable {@IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,@IEditorService private readonly _editorService: IEditorService,@ILogService private readonly _logService: ILogService,- @Inject(DocHoverManagerService) private readonly _docHoverManagerSrv: DocHoverManagerService,+ @Inject(DocEventManagerService) private readonly _docEventManagerService: DocEventManagerService,@Inject(UniFormulaPopupService) private readonly _formulaPopupSrv: UniFormulaPopupService,@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService) {@@ -91,7 +91,7 @@ export class DocUniFormulaInputController extends Disposable {}private _initHoverListener(): void {- this.disposeWithMe(this._docHoverManagerSrv.activeCustomRanges$.subscribe((customRanges) => {+ this.disposeWithMe(this._docEventManagerService.hoverCustomRanges$.subscribe((customRanges) => {const focusedUnit = this._instanceSrv.getFocusedUnit();if (@@ -102,7 +102,7 @@ export class DocUniFormulaInputController extends Disposable {return;}- const formulaCustomRange = customRanges.find((range) => range.rangeType === CustomRangeType.UNI_FORMULA);+ const formulaCustomRange = customRanges.find((range) => range.range.rangeType === CustomRangeType.UNI_FORMULA)?.range;if (formulaCustomRange) {const { startIndex, rangeId } = formulaCustomRange;this._logService.debug('[DocUniFormulaController]: activeCustomRanges', customRanges);diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.tsindex a82f1e642b..4d73dea313 100644--- a/packages/core/src/docs/data-model/document-data-model.ts+++ b/packages/core/src/docs/data-model/document-data-model.ts@@ -329,6 +329,7 @@ export class DocumentDataModel extends DocumentDataModelSimple {for (const headerId in headers) {const header = headers[headerId];this.headerModelMap.set(headerId, new DocumentDataModel(header));+ this.headerModelMap.get(headerId)!.updateDocumentId(this.getUnitId());}}@@ -336,6 +337,7 @@ export class DocumentDataModel extends DocumentDataModelSimple {for (const footerId in footers) {const footer = footers[footerId];this.footerModelMap.set(footerId, new DocumentDataModel(footer));+ this.footerModelMap.get(footerId)!.updateDocumentId(this.getUnitId());}}}diff --git a/packages/docs-hyper-link-ui/src/commands/commands/delete-link.command.ts b/packages/docs-hyper-link-ui/src/commands/commands/delete-link.command.tsindex e114ce02be..e3659ab8f0 100644--- a/packages/docs-hyper-link-ui/src/commands/commands/delete-link.command.ts+++ b/packages/docs-hyper-link-ui/src/commands/commands/delete-link.command.ts@@ -22,6 +22,7 @@ import { DocHyperLinkModel } from '@univerjs/docs-hyper-link';export interface IDeleteDocHyperLinkMutationParams {unitId: string;linkId: string;+ segmentId?: string;}export const DeleteDocHyperLinkCommand: ICommand<IDeleteDocHyperLinkMutationParams> = {@@ -31,7 +32,7 @@ export const DeleteDocHyperLinkCommand: ICommand<IDeleteDocHyperLinkMutationParaif (!params) {return false;}- const { unitId, linkId } = params;+ const { unitId, linkId, segmentId } = params;const commandService = accessor.get(ICommandService);const hyperLinkModel = accessor.get(DocHyperLinkModel);const link = hyperLinkModel.getLink(unitId, linkId);@@ -39,7 +40,7 @@ export const DeleteDocHyperLinkCommand: ICommand<IDeleteDocHyperLinkMutationParareturn false;}- const doMutation = deleteCustomRangeFactory(accessor, { unitId, rangeId: linkId });+ const doMutation = deleteCustomRangeFactory(accessor, { unitId, rangeId: linkId, segmentId });if (!doMutation) {return false;}diff --git a/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.tsindex b75ce0c9b5..9957f1d44c 100644--- a/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts+++ b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts@@ -14,13 +14,17 @@* limitations under the License.*/-import { CommandType, type ICommand, ICommandService } from '@univerjs/core';-import { UpdateDocHyperLinkMutation } from '@univerjs/docs-hyper-link';+import { CommandType, CustomRangeType, DataStreamTreeTokenType, generateRandomId, type ICommand, ICommandService, sequenceExecute } from '@univerjs/core';+import { replaceSelectionFactory, TextSelectionManagerService } from '@univerjs/docs';+import type { IAddDocHyperLinkMutationParams } from '@univerjs/docs-hyper-link';+import { AddDocHyperLinkMutation } from '@univerjs/docs-hyper-link';export interface IUpdateDocHyperLinkCommandParams {unitId: string;linkId: string;payload: string;+ label: string;+ segmentId: string;}export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParams> = {@@ -30,8 +34,54 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParamif (!params) {return false;}-+ const { unitId, payload, segmentId } = params;const commandService = accessor.get(ICommandService);- return commandService.syncExecuteCommand(UpdateDocHyperLinkMutation.id, params);+ const selectionService = accessor.get(TextSelectionManagerService);+ const currentSelection = selectionService.getActiveTextRange();+ if (!currentSelection) {+ return false;+ }++ const newId = generateRandomId();+ const replaceSelection = replaceSelectionFactory(accessor, {+ unitId: params.unitId,+ body: {+ dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${params.label}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`,+ customRanges: [{+ rangeId: newId,+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: params.label.length + 1,+ }],+ },+ selection: {+ startOffset: currentSelection.startOffset!,+ endOffset: currentSelection.endOffset!,+ collapsed: false,+ segmentId,+ },+ });++ if (!replaceSelection) {+ return false;+ }++ // doc don't support undo now+ // so use an new id to replace the old link+ // in case of undo or redo+ const addLinkMutation = {+ id: AddDocHyperLinkMutation.id,+ params: {+ unitId,+ link: {+ id: newId,+ payload,+ },+ } as IAddDocHyperLinkMutationParams,+ };++ const result = sequenceExecute([addLinkMutation, replaceSelection], commandService);++ return result.result;},};diff --git a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.tsindex 068cf35638..6839b61006 100644--- a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts+++ b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts@@ -14,24 +14,17 @@* limitations under the License.*/-import type { DocumentDataModel, IAccessor, ICommand } from '@univerjs/core';-import { CommandType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';-import { DocSkeletonManagerService, serializeDocRange, TextSelectionManagerService } from '@univerjs/docs';-import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';+import type { DocumentDataModel, IAccessor, ICommand, ITextRange } from '@univerjs/core';+import { CommandType, CustomRangeType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { getCustomRangesInterestsWithRange, TextSelectionManagerService } from '@univerjs/docs';+import { DocHyperLinkModel } from '@univerjs/docs-hyper-link';import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';export const shouldDisableAddLink = (accessor: IAccessor) => {const textSelectionService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);- const textRanges = textSelectionService.getCurrentTextRanges()?.map(serializeDocRange);- const renderManagerService = accessor.get(IRenderManagerService);- const render = renderManagerService.getCurrent();- const skeleton = render?.with(DocSkeletonManagerService).getSkeleton();- const editArea = skeleton?.getViewModel().getEditArea();- if (editArea === DocumentEditArea.FOOTER || editArea === DocumentEditArea.HEADER) {- return true;- }- if (!textRanges || textRanges.length > 1) {+ const textRanges = textSelectionService.getDocRanges();+ if (!textRanges.length || textRanges.length > 1) {return true;}@@ -41,14 +34,15 @@ export const shouldDisableAddLink = (accessor: IAccessor) => {return true;}- const paragraphs = doc.getBody()?.paragraphs;+ const body = doc.getSelfOrHeaderFooterModel(activeRange.segmentId).getBody();+ const paragraphs = body?.paragraphs;if (!paragraphs) {return true;}for (let i = 0, len = paragraphs.length; i < len; i++) {const p = paragraphs[i];- if (activeRange.startOffset <= p.startIndex && activeRange.endOffset > p.startIndex) {+ if (activeRange.startOffset! <= p.startIndex && activeRange.endOffset! > p.startIndex) {return true;}@@ -57,20 +51,23 @@ export const shouldDisableAddLink = (accessor: IAccessor) => {}}- return false;+ const insertCustomRanges = getCustomRangesInterestsWithRange(activeRange as ITextRange, body.customRanges ?? []);+ // can't insert hyperlink in range contains other custom ranges+ return !insertCustomRanges.every((range) => range.rangeType === CustomRangeType.HYPERLINK);};export interface IShowDocHyperLinkEditPopupOperationParams {link?: {unitId: string;linkId: string;- rangeIndex: number;+ segmentId?: string;+ segmentPage?: number;};}export const ShowDocHyperLinkEditPopupOperation: ICommand<IShowDocHyperLinkEditPopupOperationParams> = {type: CommandType.OPERATION,- id: 'docs.operation.show-hyper-link-edit-popup',+ id: 'doc.operation.show-hyper-link-edit-popup',handler(accessor, params) {const linkInfo = params?.link;if (shouldDisableAddLink(accessor) && !linkInfo) {@@ -81,3 +78,43 @@ export const ShowDocHyperLinkEditPopupOperation: ICommand<IShowDocHyperLinkEditPreturn true;},};++export interface IShowDocHyperLinkInfoPopupOperationParams {+ linkId: string;+ segmentId?: string;+ unitId: string;+ segmentPage?: number;+}++export const ToggleDocHyperLinkInfoPopupOperation: ICommand<IShowDocHyperLinkInfoPopupOperationParams> = {+ type: CommandType.OPERATION,+ id: 'doc.operation.toggle-hyper-link-info-popup',+ handler(accessor, params) {+ const hyperLinkService = accessor.get(DocHyperLinkPopupService);+ if (!params) {+ hyperLinkService.hideInfoPopup();+ return true;+ }++ hyperLinkService.showInfoPopup(params);+ return true;+ },+};++export const ClickDocHyperLinkOperation: ICommand<{ unitId: string; linkId: string }> = {+ type: CommandType.OPERATION,+ id: 'doc.operation.click-hyper-link',+ handler(accessor, params) {+ if (!params) {+ return false;+ }+ const { unitId, linkId } = params;+ const docLinkModel = accessor.get(DocHyperLinkModel);+ const link = docLinkModel.getLink(unitId, linkId);+ if (!link) {+ return false;+ }+ window.open(link.payload, '_blank', 'noopener noreferrer');+ return true;+ },+};diff --git a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.tsindex 680ea1999a..db3f6fdb69 100644--- a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts+++ b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts@@ -17,8 +17,8 @@import type { DocumentDataModel } from '@univerjs/core';import { Disposable, ICommandService, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';import type { ISetTextSelectionsOperationParams } from '@univerjs/docs';-import { DocSkeletonManagerService, SetTextSelectionsOperation } from '@univerjs/docs';-import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';+import { SetTextSelectionsOperation } from '@univerjs/docs';+import { IRenderManagerService } from '@univerjs/engine-render';import { DocHyperLinkPopupService } from '../services/hyper-link-popup.service';@OnLifecycle(LifecycleStages.Ready, DocHyperLinkSelectionController)@@ -39,30 +39,25 @@ export class DocHyperLinkSelectionController extends Disposable {this._commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === SetTextSelectionsOperation.id) {const params = commandInfo.params as ISetTextSelectionsOperationParams;- const { unitId, ranges } = params;- const render = this._renderMangerService.getRenderById(unitId);- const skeleton = render?.with(DocSkeletonManagerService).getSkeleton();- const editArea = skeleton?.getViewModel().getEditArea();- if (editArea !== DocumentEditArea.BODY) {- this._docHyperLinkService.hideInfoPopup();- this._docHyperLinkService.hideEditPopup();- return;- }+ const { unitId, ranges, segmentId } = params;const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);const primary = ranges[0];if (primary && doc) {- const { startOffset, endOffset, collapsed } = primary;- const customRanges = doc.getBody()?.customRanges;- if (collapsed) { // cursor+ const { startOffset, endOffset, collapsed, segmentPage } = primary;+ const customRanges = doc.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customRanges;+ if (collapsed) {+ // cursorconst index = customRanges?.findIndex((value) => (value.startIndex) < startOffset && value.endIndex > endOffset - 1) ?? -1;if (index > -1) {const customRange = customRanges![index];- this._docHyperLinkService.showInfoPopup({ unitId, linkId: customRange.rangeId, rangeIndex: index });+ this._docHyperLinkService.showInfoPopup({ unitId, linkId: customRange.rangeId, segmentId, segmentPage });return;}- } else { // range- if (customRanges?.find((value) => value.startIndex <= startOffset && value.endIndex >= (endOffset - 1))) {+ } else {+ // range+ const range = customRanges?.find((value) => value.startIndex <= startOffset && value.endIndex >= (endOffset - 1));+ if (range) {return;}}diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.tsnew file mode 100644index 0000000000..38383ca402--- /dev/null+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts@@ -0,0 +1,95 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { DocumentDataModel } from '@univerjs/core';+import { CustomRangeType, Disposable, ICommandService, Inject } from '@univerjs/core';+import { DocEventManagerService } from '@univerjs/docs-ui';+import { DocumentEditArea, type IRenderContext, type IRenderModule } from '@univerjs/engine-render';+import { DocSkeletonManagerService } from '@univerjs/docs';+import { ClickDocHyperLinkOperation, ToggleDocHyperLinkInfoPopupOperation } from '../../commands/operations/popup.operation';+import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';++export class DocHyperLinkEventRenderController extends Disposable implements IRenderModule {+ get _skeleton() {+ return this._docSkeletonManagerService.getSkeleton();+ }++ constructor(+ private readonly _context: IRenderContext<DocumentDataModel>,+ @Inject(DocEventManagerService) private readonly _docEventManagerService: DocEventManagerService,+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(DocHyperLinkPopupService) private readonly _hyperLinkPopupService: DocHyperLinkPopupService,+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService+ ) {+ super();++ this._initHover();+ this._initClick();+ }++ private _hideInfoPopup() {+ if (this._hyperLinkPopupService.showing) {+ this._commandService.executeCommand(+ ToggleDocHyperLinkInfoPopupOperation.id+ );+ }+ }++ private _initHover() {+ this.disposeWithMe(+ this._docEventManagerService.hoverCustomRanges$.subscribe((ranges) => {+ const link = ranges.find((range) => range.range.rangeType === CustomRangeType.HYPERLINK);+ const editArea = this._skeleton.getViewModel().getEditArea();+ if ((link?.segmentId && editArea === DocumentEditArea.BODY) || (!link?.segmentId && editArea !== DocumentEditArea.BODY)) {+ this._hideInfoPopup();+ return;+ }++ if (link) {+ this._commandService.executeCommand(+ ToggleDocHyperLinkInfoPopupOperation.id,+ {+ unitId: this._context.unitId,+ linkId: link.range.rangeId,+ segmentId: link.segmentId,+ segmentPage: link.segmentPageIndex,+ rangeId: link.range.rangeId,+ }+ );+ } else {+ this._hideInfoPopup();+ }+ })+ );+ }++ private _initClick() {+ this.disposeWithMe(+ this._docEventManagerService.clickCustomRanges$.subscribe((range) => {+ const link = range.range;+ if (link) {+ this._commandService.executeCommand(+ ClickDocHyperLinkOperation.id,+ {+ unitId: this._context.unitId,+ linkId: link.rangeId,+ }+ );+ }+ })+ );+ }+}diff --git a/packages/docs-hyper-link-ui/src/controllers/ui.controller.ts b/packages/docs-hyper-link-ui/src/controllers/ui.controller.tsindex b8558560dd..7c0972f4f3 100644--- a/packages/docs-hyper-link-ui/src/controllers/ui.controller.ts+++ b/packages/docs-hyper-link-ui/src/controllers/ui.controller.ts@@ -22,7 +22,7 @@ import { DocHyperLinkEdit } from '../views/hyper-link-edit';import { AddDocHyperLinkCommand } from '../commands/commands/add-link.command';import { UpdateDocHyperLinkCommand } from '../commands/commands/update-link.command';import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';-import { ShowDocHyperLinkEditPopupOperation } from '../commands/operations/popup.operation';+import { ClickDocHyperLinkOperation, ShowDocHyperLinkEditPopupOperation, ToggleDocHyperLinkInfoPopupOperation } from '../commands/operations/popup.operation';import { DocLinkPopup } from '../views/hyper-link-popup';import { AddHyperLinkMenuItemFactory, addLinkShortcut, DOC_LINK_ICON } from './menu';@@ -64,6 +64,8 @@ export class DocHyperLinkUIController extends Disposable {UpdateDocHyperLinkCommand,DeleteDocHyperLinkCommand,ShowDocHyperLinkEditPopupOperation,+ ToggleDocHyperLinkInfoPopupOperation,+ ClickDocHyperLinkOperation,].forEach((command) => {this._commandService.registerCommand(command);});diff --git a/packages/docs-hyper-link-ui/src/locale/en-US.ts b/packages/docs-hyper-link-ui/src/locale/en-US.tsindex 4ce664e6e4..c0e484b907 100644--- a/packages/docs-hyper-link-ui/src/locale/en-US.ts+++ b/packages/docs-hyper-link-ui/src/locale/en-US.ts@@ -22,9 +22,11 @@ const enUS: typeof zhCN = {confirm: 'Confirm',cancel: 'Cancel',title: 'Link',- address: 'Link address',+ address: 'Link',placeholder: 'Please input a link url',addressError: 'Url is illegal!',+ label: 'Label',+ LabelError: 'Please input label of link',},info: {copy: 'Copy',diff --git a/packages/docs-hyper-link-ui/src/locale/ru-RU.ts b/packages/docs-hyper-link-ui/src/locale/ru-RU.tsindex 02858dc350..ea26fd77f9 100644--- a/packages/docs-hyper-link-ui/src/locale/ru-RU.ts+++ b/packages/docs-hyper-link-ui/src/locale/ru-RU.ts@@ -22,7 +22,9 @@ const ruRU: typeof zhCN = {confirm: 'Подтвердить',cancel: 'Отменить',title: 'Ссылка',- address: 'Адрес ссылки',+ address: 'Cсылки',+ label: 'Текст',+ LabelError: 'Введите текст ссылки',placeholder: 'Пожалуйста, введите URL ссылки',addressError: 'URL некорректен!',},diff --git a/packages/docs-hyper-link-ui/src/locale/vi-VN.ts b/packages/docs-hyper-link-ui/src/locale/vi-VN.tsindex 95e5d72dc1..03a5e7ca86 100644--- a/packages/docs-hyper-link-ui/src/locale/vi-VN.ts+++ b/packages/docs-hyper-link-ui/src/locale/vi-VN.ts@@ -22,7 +22,9 @@ const locale: typeof zhCN = {confirm: 'Xác nhận',cancel: 'Hủy',title: 'Liên kết',- address: 'Địa chỉ liên kết',+ address: 'Liên kết',+ label: 'Nhãn',+ LabelError: 'Vui lòng nhập nhãn liên kết',placeholder: 'Vui lòng nhập liên kết hợp lệ',addressError: 'Vui lòng nhập liên kết hợp lệ',},diff --git a/packages/docs-hyper-link-ui/src/locale/zh-CN.ts b/packages/docs-hyper-link-ui/src/locale/zh-CN.tsindex 8c3742c7f2..c71262ed97 100644--- a/packages/docs-hyper-link-ui/src/locale/zh-CN.ts+++ b/packages/docs-hyper-link-ui/src/locale/zh-CN.ts@@ -20,9 +20,12 @@ const zhCN = {confirm: '确认',cancel: '取消',title: '链接',- address: '链接地址',+ address: '链接',+ label: '文本',+ LabelError: '请输入链接文本',placeholder: '请输入合法的链接',addressError: '请输入合法的链接',+},info: {copy: '复制',diff --git a/packages/docs-hyper-link-ui/src/locale/zh-TW.ts b/packages/docs-hyper-link-ui/src/locale/zh-TW.tsindex 85d825943e..30599512ce 100644--- a/packages/docs-hyper-link-ui/src/locale/zh-TW.ts+++ b/packages/docs-hyper-link-ui/src/locale/zh-TW.ts@@ -22,7 +22,9 @@ const locale: typeof zhCN = {confirm: '確認',cancel: '取消',title: '連結',- address: '連結地址',+ address: '連結',+ label: '文本',+ LabelError: '请输入链接文本',placeholder: '請輸入合法的連結',addressError: '請輸入合法的連結',},diff --git a/packages/docs-hyper-link-ui/src/plugin.ts b/packages/docs-hyper-link-ui/src/plugin.tsindex 1be51ae646..bc67ec721a 100644--- a/packages/docs-hyper-link-ui/src/plugin.ts+++ b/packages/docs-hyper-link-ui/src/plugin.ts@@ -26,6 +26,7 @@ import { DocHyperLinkSelectionController } from './controllers/doc-hyper-link-seimport { DocHyperLinkRenderController } from './controllers/render-controllers/render.controller';import { DocHyperLinkClipboardController } from './controllers/doc-hyper-link-clipboard.controller';import { DocHyperLinkCustomRangeController } from './controllers/doc-hyper-link-custom-range.controller';+import { DocHyperLinkEventRenderController } from './controllers/render-controllers/hyper-link-event.render-controller';@DependentOn(UniverDocsHyperLinkPlugin)export class UniverDocsHyperLinkUIPlugin extends Plugin {@@ -63,8 +64,11 @@ export class UniverDocsHyperLinkUIPlugin extends Plugin {}private _initRenderModule() {- [DocHyperLinkRenderController].forEach((dep) => {- this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, dep as unknown as Dependency);+ ([+ [DocHyperLinkRenderController],+ [DocHyperLinkEventRenderController],+ ] as Dependency[]).forEach((dep) => {+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, dep);});}}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 9c044d512d..8545ce1718 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@@ -14,8 +14,8 @@* limitations under the License.*/-import type { DocumentDataModel, IDisposable, ITextRange, Nullable } from '@univerjs/core';-import { Disposable, ICommandService, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import type { DocumentDataModel, IDisposable, ITextRangeParam, Nullable } from '@univerjs/core';+import { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { TextSelectionManagerService } from '@univerjs/docs';import { DocCanvasPopManagerService } from '@univerjs/docs-ui';import { BehaviorSubject } from 'rxjs';@@ -26,10 +26,13 @@ import { DocLinkPopup } from '../views/hyper-link-popup';/*** A link will have a placeholder, and when it is a link at the beginning, the placeholder does not have a width or height, causing an evaluation error*/-const SKIT_PLACEHOLDER = 2;+const SKIT_PLACEHOLDER = 0;export interface ILinkInfo {- unitId: string; linkId: string; rangeIndex: number;+ unitId: string;+ linkId: string;+ segmentId?: string;+ segmentPage?: number;}export class DocHyperLinkPopupService extends Disposable {@@ -45,8 +48,7 @@ export class DocHyperLinkPopupService extends Disposable {@Inject(DocCanvasPopManagerService) private readonly _docCanvasPopupManagerService: DocCanvasPopManagerService,@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,@Inject(DocHyperLinkModel) private readonly _docHyperLinkModel: DocHyperLinkModel,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @ICommandService private readonly _commandService: ICommandService+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService) {super();@@ -69,26 +71,27 @@ export class DocHyperLinkPopupService extends Disposable {this._editPopup.dispose();}this._editingLink$.next(linkInfo);- let activeRange: Nullable<ITextRange> = this._textSelectionManagerService.getActiveTextRangeWithStyle();+ let activeRange: Nullable<ITextRangeParam> = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (linkInfo) {- const { unitId, rangeIndex } = linkInfo;+ const { unitId, linkId, segmentId, segmentPage } = linkInfo;const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);- const range = doc?.getBody()?.customRanges?.[rangeIndex];+ const range = doc?.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customRanges?.find((i) => i.rangeId === linkId);if (range) {activeRange = {collapsed: false,- startOffset: range.startIndex,+ startOffset: range.startIndex + SKIT_PLACEHOLDER,endOffset: range.endIndex + 1,+ segmentId,+ segmentPage,};+this._textSelectionManagerService.replaceTextRanges([{startOffset: range.startIndex,endOffset: range.endIndex + 1,}]);}}-if (activeRange) {- activeRange.startOffset += SKIT_PLACEHOLDER;this._editPopup = this._docCanvasPopupManagerService.attachPopupToRange(activeRange,{@@ -108,11 +111,12 @@ export class DocHyperLinkPopupService extends Disposable {}showInfoPopup(info: ILinkInfo): Nullable<IDisposable> {- const { linkId, unitId, rangeIndex } = info;+ const { linkId, unitId, segmentId, segmentPage } = info;if (this.showing?.linkId === linkId &&this.showing?.unitId === unitId &&- this.showing.rangeIndex === rangeIndex+ this.showing?.segmentId === segmentId &&+ this.showing?.segmentPage === segmentPage) {return;}@@ -125,8 +129,8 @@ export class DocHyperLinkPopupService extends Disposable {if (!doc || !link) {return;}- const range = doc.getBody()?.customRanges?.[rangeIndex];- this._showingLink$.next({ unitId, linkId, rangeIndex });+ const range = doc.getSelfOrHeaderFooterModel(info.segmentId).getBody()?.customRanges?.find((i) => i.rangeId === linkId);+ this._showingLink$.next({ unitId, linkId, segmentId, segmentPage });if (!range) {return;}@@ -136,6 +140,8 @@ export class DocHyperLinkPopupService extends Disposable {collapsed: false,startOffset: range.startIndex + SKIT_PLACEHOLDER,endOffset: range.endIndex + 1,+ segmentId: info.segmentId,+ segmentPage: info.segmentPage,},{componentKey: DocLinkPopup.componentKey,diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.module.less b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.module.lessindex 73a7218600..80a32d65ff 100644--- a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.module.less+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.module.less@@ -5,6 +5,7 @@box-shadow: var(--box-shadow-base);padding: 20px 24px;width: 328px;+ box-sizing: border-box;&-title {display: flex;diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsxindex 47b55acbc6..79f6f38adf 100644--- a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx@@ -16,12 +16,12 @@import { Button, FormLayout, Input } from '@univerjs/design';import React, { useEffect, useState } from 'react';-import { CloseSingle } from '@univerjs/icons';-import { ICommandService, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency, useObservable } from '@univerjs/core';+import { getBodySlice, ICommandService, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency, useObservable } from '@univerjs/core';import { DocHyperLinkModel } from '@univerjs/docs-hyper-link';import type { DocumentDataModel } from '@univerjs/core';import { ITextSelectionRenderManager } from '@univerjs/engine-render';-import { TextSelectionManagerService } from '@univerjs/docs';+import { getPlainTextFormBody, TextSelectionManagerService } from '@univerjs/docs';+import { KeyCode } from '@univerjs/ui';import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';import { AddDocHyperLinkCommand } from '../../commands/commands/add-link.command';import { UpdateDocHyperLinkCommand } from '../../commands/commands/update-link.command';@@ -45,35 +45,42 @@ export const DocHyperLinkEdit = () => {const hyperLinkService = useDependency(DocHyperLinkPopupService);const localeService = useDependency(LocaleService);const hyperLinkModel = useDependency(DocHyperLinkModel);- const editingId = useObservable(hyperLinkService.editingLink$);+ const editing = useObservable(hyperLinkService.editingLink$);const commandService = useDependency(ICommandService);const univerInstanceService = useDependency(IUniverInstanceService);const textSelectionRenderManager = useDependency(ITextSelectionRenderManager);const textSelectionManagerService = useDependency(TextSelectionManagerService);const [link, setLink] = useState('');+ const [label, setLabel] = useState('');const [showError, setShowError] = useState(false);const isLegal = Tools.isLegalUrl(link);- const doc = editingId- ? univerInstanceService.getUnit<DocumentDataModel>(editingId.unitId, UniverInstanceType.UNIVER_DOC) :+ const doc = editing+ ? univerInstanceService.getUnit<DocumentDataModel>(editing.unitId, UniverInstanceType.UNIVER_DOC) :univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);useEffect(() => {- if (editingId) {- const linkDetail = editingId ? hyperLinkModel.getLink(editingId.unitId, editingId.linkId) : null;- setLink(linkDetail?.payload ?? '');- return;- }const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (!activeRange) {return;}- const doc = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- const matchedRange = doc?.getBody()?.customRanges?.find((i) => Math.max(activeRange.startOffset, i.startIndex) <= Math.min(activeRange.endOffset - 1, i.endIndex));++ if (editing) {+ const linkDetail = editing ? hyperLinkModel.getLink(editing.unitId, editing.linkId) : null;+ setLink(linkDetail?.payload ?? '');+ const body = doc?.getSelfOrHeaderFooterModel(editing.segmentId)?.getBody();+ const matchedRange = body?.customRanges?.find((i) => linkDetail?.id === i.rangeId);+ if (doc && matchedRange) {+ setLabel(getPlainTextFormBody(getBodySlice(body!, matchedRange.startIndex, matchedRange.endIndex)));+ }+ return;+ }++ const matchedRange = doc?.getSelfOrHeaderFooterModel(activeRange.segmentId)?.getBody()?.customRanges?.find((i) => Math.max(activeRange.startOffset, i.startIndex) <= Math.min(activeRange.endOffset - 1, i.endIndex));if (doc && matchedRange) {const linkDetail = hyperLinkModel.getLink(doc.getUnitId(), matchedRange.rangeId);setLink(linkDetail?.payload ?? '');}- }, [editingId, hyperLinkModel, textSelectionManagerService, univerInstanceService]);+ }, [doc, editing, hyperLinkModel, textSelectionManagerService, univerInstanceService]);useEffect(() => {textSelectionRenderManager.blurEditor();@@ -92,16 +99,22 @@ export const DocHyperLinkEdit = () => {}const linkFinal = transformUrl(link);- if (!editingId) {+ if (!editing) {commandService.executeCommand(AddDocHyperLinkCommand.id, {unitId: doc.getUnitId(),payload: linkFinal,});} else {+ if (!label) {+ return;+ }+commandService.executeCommand(UpdateDocHyperLinkCommand.id, {unitId: doc.getUnitId(),payload: linkFinal,- linkId: editingId.linkId,+ linkId: editing.linkId,+ label,+ segmentId: editing.segmentId,});}hyperLinkService.hideEditPopup();@@ -113,16 +126,40 @@ export const DocHyperLinkEdit = () => {return (<div className={styles.docsLinkEdit}>- <div className={styles.docsLinkEditTitle}>- <span>{localeService.t('docLink.edit.title')}</span>- <CloseSingle className={styles.docsLinkEditClose} onClick={handleCancel} />- </div><div>+ {editing+ ? (+ <FormLayout+ label={localeService.t('docLink.edit.label')}+ error={showError && !isLegal ? localeService.t('docLink.edit.labelError') : ''}+ >+ <Input+ value={label}+ onChange={setLabel}+ autoFocus+ onKeyDown={(evt) => {+ if (evt.keyCode === KeyCode.ENTER) {+ handleConfirm();+ }+ }}+ />+ </FormLayout>+ )+ : null}<FormLayoutlabel={localeService.t('docLink.edit.address')}error={showError && !isLegal ? localeService.t('docLink.edit.addressError') : ''}>- <Input value={link} onChange={setLink} autoFocus />+ <Input+ value={link}+ onChange={setLink}+ autoFocus+ onKeyDown={(evt) => {+ if (evt.keyCode === KeyCode.ENTER) {+ handleConfirm();+ }+ }}+ /></FormLayout></div><div className={styles.docsLinkEditButtons}>diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.module.less b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.module.lessindex eeda3405e5..9bb9f1857f 100644--- a/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.module.less+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.module.less@@ -9,6 +9,7 @@border: 1px solid rgb(var(--grey-200));background: rgb(var(--color-white));max-width: 328px;+ box-sizing: border-box;overflow: hidden;}diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsxindex 9e5cd22ce2..406a57251b 100644--- a/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-popup/index.tsx@@ -37,7 +37,7 @@ export const DocLinkPopup = () => {return null;}- const { unitId, linkId } = currentPopup;+ const { unitId, linkId, segmentId } = currentPopup;const link = hyperLinkModel.getLink(unitId, linkId);if (!link) {return null;@@ -92,6 +92,7 @@ export const DocLinkPopup = () => {commandService.executeCommand(DeleteDocHyperLinkCommand.id, {unitId,linkId: link.id,+ segmentId,});}}>diff --git a/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.tsindex 0ca501b294..ac9cb2bfdc 100644--- a/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts+++ b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts@@ -36,7 +36,7 @@ export const ShowCommentPanelOperation: ICommand<IShowCommentPanelOperationParamconst panelService = accessor.get(ThreadCommentPanelService);const sidebarService = accessor.get(ISidebarService);- if (!panelService.panelVisible) {+ if (!panelService.panelVisible || sidebarService.options.children?.label !== DocThreadCommentPanel.componentKey) {sidebarService.open({header: { title: 'threadCommentUI.panel.title' },children: { label: DocThreadCommentPanel.componentKey },@@ -45,6 +45,7 @@ export const ShowCommentPanelOperation: ICommand<IShowCommentPanelOperationParam});panelService.setPanelVisible(true);}+if (params) {panelService.setActiveComment(params?.activeComment);}@@ -90,7 +91,6 @@ export const StartAddCommentOperation: ICommand = {const docCommentService = accessor.get(DocThreadCommentService);const commandService = accessor.get(ICommandService);const sidebarService = accessor.get(ISidebarService);-const textRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (!doc || !textRange) {return false;@@ -106,10 +106,7 @@ export const StartAddCommentOperation: ICommand = {return true;}- if (!panelService.panelVisible) {- commandService.executeCommand(ShowCommentPanelOperation.id);- }-+ commandService.executeCommand(ShowCommentPanelOperation.id);const unitId = doc.getUnitId();const text = getSelectionText(doc.getBody()?.dataStream ?? '', textRange.startOffset, textRange.endOffset);const subUnitId = DEFAULT_DOC_SUBUNIT_ID;diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-checklist.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-checklist.render-controller.tsindex e3cdc20af2..0a1f29d024 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-checklist.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-checklist.render-controller.ts@@ -15,18 +15,19 @@*/import type { Documents, IRenderContext, IRenderModule, Viewport } from '@univerjs/engine-render';-import { CURSOR_TYPE, getParagraphByGlyph, GlyphType, PageLayoutType, Vector2 } from '@univerjs/engine-render';+import { CURSOR_TYPE, Vector2 } from '@univerjs/engine-render';import type { DocumentDataModel } from '@univerjs/core';-import { Disposable, ICommandService, Inject, PresetListType } from '@univerjs/core';-import { DocSkeletonManagerService, ToggleCheckListCommand, VIEWPORT_KEY } from '@univerjs/docs';-import { DocHoverManagerService } from '../../services/doc-hover-manager.service';+import { Disposable, ICommandService, Inject } from '@univerjs/core';+import { DocSkeletonManagerService, TextSelectionManagerService, ToggleCheckListCommand } from '@univerjs/docs';+import { DocEventManagerService } from '../../services/doc-event-manager.service';export class DocChecklistRenderController extends Disposable implements IRenderModule {constructor(private _context: IRenderContext<DocumentDataModel>,@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,@ICommandService private readonly _commandService: ICommandService,- @Inject(DocHoverManagerService) private readonly _docHoverManagerService: DocHoverManagerService+ @Inject(DocEventManagerService) private readonly _docEventManagerService: DocEventManagerService,+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService) {super();@@ -35,49 +36,17 @@ export class DocChecklistRenderController extends Disposable implements IRenderM}private _initPointerDownObserver() {- this.disposeWithMe(- this._context.mainComponent!.onPointerDown$.subscribeEvent((evt) => {- const { offsetX, offsetY } = evt;-- const documentComponent = this._context.mainComponent as Documents;- const coord = this._getTransformCoordForDocumentOffset(- documentComponent,- this._context.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)!,- offsetX,- offsetY- );- if (!coord) {- return;- }- const { pageLayoutType = PageLayoutType.VERTICAL, pageMarginLeft, pageMarginTop } = documentComponent.getOffsetConfig();- const skeleton = this._docSkeletonManagerService.getSkeleton();- const node = skeleton.findNodeByCoord(- coord,- pageLayoutType,- pageMarginLeft,- pageMarginTop- );- if (!node) {- return;- }- const paragraph = getParagraphByGlyph(node.node, this._context.unit.getBody());- if (paragraph && paragraph.bullet && node.node.glyphType === GlyphType.LIST) {- if (- paragraph.bullet.listType === PresetListType.CHECK_LIST ||- paragraph.bullet.listType === PresetListType.CHECK_LIST_CHECKED- ) {- this._commandService.executeCommand(ToggleCheckListCommand.id, {- index: paragraph.startIndex,- });- }- }- })- );+ this._docEventManagerService.clickBullets$.subscribe((paragraph) => {+ this._commandService.executeCommand(ToggleCheckListCommand.id, {+ index: paragraph.paragraph.startIndex,+ segmentId: paragraph.segmentId,+ });+ });}private _initHoverCursor() {this.disposeWithMe(- this._docHoverManagerService.bullet$.subscribe((paragraph) => {+ this._docEventManagerService.hoverBullet$.subscribe((paragraph) => {if (paragraph) {this._context.mainComponent!.setCursor(CURSOR_TYPE.POINTER);} else {diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-hover.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-hover.render-controller.tsdeleted file mode 100644index 40e753f2cd..0000000000--- a/packages/docs-ui/src/controllers/render-controllers/doc-hover.render-controller.ts+++ /dev/null@@ -1,56 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * 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 { Disposable, fromEventSubject, Inject } from '@univerjs/core';-import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';-import { VIEWPORT_KEY } from '@univerjs/docs';-import { debounceTime } from 'rxjs';-import { DocHoverManagerService } from '../../services/doc-hover-manager.service';--export class DocHoverRenderController extends Disposable implements IRenderModule {- constructor(- private _context: IRenderContext,- @Inject(DocHoverManagerService) private readonly _docHoverManagerService: DocHoverManagerService- ) {- super();-- this._initPointerDown();- this._initScroll();- }-- private _initPointerDown() {- this.disposeWithMe(- fromEventSubject(this._context.scene.onPointerMove$)- .pipe(debounceTime(100))- .subscribe((evt) => {- this._docHoverManagerService.onMouseMove(evt);- })- );- }-- private _initScroll() {- const viewMain = this._context.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);- if (viewMain) {- this.disposeWithMe(fromEventSubject(viewMain.onScrollAfter$).pipe(debounceTime(60)).subscribe(() => {- this._docHoverManagerService.endScroll();- }));-- this.disposeWithMe(viewMain.onScrollBefore$.subscribeEvent(() => {- this._docHoverManagerService.startScroll();- }));- }- }-}diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-resize.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-resize.render-controller.tsindex 97d8fb7eb2..ea684b1dc5 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-resize.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-resize.render-controller.ts@@ -17,7 +17,7 @@import { Disposable, DOCS_ZEN_EDITOR_UNIT_ID_KEY, fromEventSubject, Inject, isInternalEditorID } from '@univerjs/core';import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';-import { filter, throttleTime } from 'rxjs';+import { animationFrameScheduler, filter, throttleTime } from 'rxjs';import { TextSelectionManagerService } from '@univerjs/docs';import { DocPageLayoutService } from '../../services/doc-page-layout.service';@@ -39,7 +39,7 @@ export class DocResizeRenderController extends Disposable implements IRenderModuthis.disposeWithMe(fromEventSubject(this._context.engine.onTransformChange$).pipe(filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.resize),- throttleTime(16)+ throttleTime(0, animationFrameScheduler)).subscribe(() => {this._docPageLayoutService.calculatePagePosition();this._textSelectionManagerService.refreshSelection();diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.tsindex 35666fed25..56133b84b2 100644--- a/packages/docs-ui/src/docs-ui-plugin.ts+++ b/packages/docs-ui/src/docs-ui-plugin.ts@@ -58,8 +58,7 @@ import { DocHeaderFooterController } from './controllers/doc-header-footer.contrimport { DocContextMenuRenderController } from './controllers/render-controllers/contextmenu.render-controller';import { DocPageLayoutService } from './services/doc-page-layout.service';import { DocResizeRenderController } from './controllers/render-controllers/doc-resize.render-controller';-import { DocHoverManagerService } from './services/doc-hover-manager.service';-import { DocHoverRenderController } from './controllers/render-controllers/doc-hover.render-controller';+import { DocEventManagerService } from './services/doc-event-manager.service';import { DocAutoFormatController } from './controllers/doc-auto-format.controller';import { ShiftTabShortCut } from './shortcuts/format.shortcut';import { DocChecklistRenderController } from './controllers/render-controllers/doc-checklist.render-controller';@@ -138,7 +137,6 @@ export class UniverDocsUIPlugin extends Plugin {[AppUIController, { useFactory: () => this._injector.createInstance(AppUIController, this._config) }],[IDocClipboardService, { useClass: DocClipboardService }],[DocCanvasPopManagerService],- [DocHoverManagerService],[DocParagraphSettingController],];@@ -181,11 +179,11 @@ export class UniverDocsUIPlugin extends Plugin {private _initRenderModules(): void {([+ [DocEventManagerService],[DocBackScrollRenderController],[DocTextSelectionRenderController],[DocHeaderFooterController],[DocResizeRenderController],- [DocHoverRenderController],[DocContextMenuRenderController],[DocChecklistRenderController],] as Dependency[]).forEach((m) => {diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex eb4ce53739..a44dace3c9 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -24,7 +24,7 @@ export * from './services';export { DocsRenderService } from './services/docs-render.service';export { DocCanvasPopManagerService } from './services/doc-popup-manager.service';export { docDrawingPositionToTransform, transformToDocDrawingPosition } from './basics/transform-position';-export { DocHoverManagerService } from './services/doc-hover-manager.service';+export { DocEventManagerService } from './services/doc-event-manager.service';export { DocUIController } from './controllers/doc-ui.controller';// #region - all commandsdiff --git a/packages/docs-ui/src/services/doc-event-manager.service.ts b/packages/docs-ui/src/services/doc-event-manager.service.tsnew file mode 100644index 0000000000..f57de41bdb--- /dev/null+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts@@ -0,0 +1,358 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { DocumentDataModel, ICustomRange, IParagraph, ITextRangeParam, Nullable } from '@univerjs/core';+import { Disposable, fromEventSubject, Inject } from '@univerjs/core';+import { DocSkeletonManagerService } from '@univerjs/docs';+import type { Documents, DocumentSkeleton, IBoundRectNoAngle, IDocumentSkeletonGlyph, IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';+import { CURSOR_TYPE, getLineBounding, NodePositionConvertToCursor, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';+import { animationFrameScheduler, distinctUntilChanged, filter, map, mergeMap, Subject, take, throttleTime } from 'rxjs';+import { transformOffset2Bound } from './doc-popup-manager.service';++interface ICustomRangeBound {+ customRange: ICustomRange;+ rects: IBoundRectNoAngle[];+ segmentId?: string;+ segmentPageIndex: number;+}++interface IBulletBound {+ rect: IBoundRectNoAngle;+ segmentId?: string;+ segmentPageIndex: number;+ paragraph: IParagraph;+}++const calcDocRangePositions = (range: ITextRangeParam, documents: Documents, skeleton: DocumentSkeleton, pageIndex: number): IBoundRectNoAngle[] | undefined => {+ const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, false, range.segmentId, pageIndex);+ const skeletonData = skeleton.getSkeletonData();+ let end = range.endOffset;+ if (range.segmentId) {+ const root = Array.from(skeletonData?.skeFooters.get(range.segmentId)?.values() ?? [])[0] ?? Array.from(skeletonData?.skeHeaders.get(range.segmentId)?.values() ?? [])[0];+ if (root) {+ end = Math.min(root.ed, end);+ }+ }+ const endPosition = skeleton.findNodePositionByCharIndex(end, false, range.segmentId, pageIndex);+ if (!endPosition || !startPosition) {+ return;+ }++ const documentOffsetConfig = documents.getOffsetConfig();+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);+ const { borderBoxPointGroup } = convertor.getRangePointData(startPosition, endPosition);+ const bounds = getLineBounding(borderBoxPointGroup);++ return bounds.map((rect) => ({+ top: rect.top + documentOffsetConfig.docsTop,+ bottom: rect.bottom + documentOffsetConfig.docsTop,+ left: rect.left + documentOffsetConfig.docsLeft,+ right: rect.right + documentOffsetConfig.docsLeft,+ }));+};+export const calcDocGlyphPosition = (glyph: IDocumentSkeletonGlyph, documents: Documents, skeleton: DocumentSkeleton, pageIndex = -1): IBoundRectNoAngle | undefined => {+ const start = skeleton.findPositionByGlyph(glyph, pageIndex);+ if (!start) {+ return;+ }++ const documentOffsetConfig = documents.getOffsetConfig();+ const startPosition = { ...start, isBack: true };+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);+ const { borderBoxPointGroup } = convertor.getRangePointData(startPosition, startPosition);+ const bounds = getLineBounding(borderBoxPointGroup);+ const rect = bounds[0];++ return {+ top: rect.top + documentOffsetConfig.docsTop,+ bottom: rect.bottom + documentOffsetConfig.docsTop,+ left: rect.left + documentOffsetConfig.docsLeft,+ right: rect.left + documentOffsetConfig.docsLeft + glyph.width,+ };+};++interface ICustomRangeActive {+ range: ICustomRange; segmentId?: string; segmentPageIndex: number;+}++interface IBulletActive {+ paragraph: IParagraph; segmentId?: string; segmentPageIndex: number;+}++export class DocEventManagerService extends Disposable implements IRenderModule {+ private readonly _hoverCustomRanges$ = new Subject<ICustomRangeActive[]>();+ readonly hoverCustomRanges$ = this._hoverCustomRanges$.pipe(distinctUntilChanged((pre, aft) => pre.length === aft.length && pre.every((item, i) => aft[i].range.rangeId === item.range.rangeId && aft[i].segmentId === item.segmentId && aft[i].segmentPageIndex === item.segmentPageIndex)));++ private readonly _clickCustomRanges$ = new Subject<ICustomRangeActive>();+ readonly clickCustomRanges$ = this._clickCustomRanges$.asObservable();++ private readonly _hoverBullet$ = new Subject<Nullable<IBulletActive>>();+ readonly hoverBullet$ = this._hoverBullet$.pipe(distinctUntilChanged((pre, aft) => pre?.paragraph.startIndex === aft?.paragraph.startIndex && pre?.segmentId === aft?.segmentId && pre?.segmentPageIndex === aft?.segmentPageIndex));++ private readonly _clickBullet$ = new Subject<IBulletActive>();+ readonly clickBullets$ = this._clickBullet$.asObservable();++ private _customRangeDirty = true;+ private _bulletDirty = true;++ /**+ * cache the bounding of custom ranges,+ * it will be updated when the doc-skeleton is recalculated+ */+ private _customRangeBounds: ICustomRangeBound[] = [];+ /**+ * cache the bounding of bullets,+ * it will be updated when the doc-skeleton is recalculated+ */+ private _bulletBounds: IBulletBound[] = [];++ private get _skeleton() {+ return this._docSkeletonManagerService.getSkeleton();+ }++ private get _documents() {+ return this._context.mainComponent as Documents;+ }++ constructor(+ private _context: IRenderContext<DocumentDataModel>,+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService+ ) {+ super();++ this._initResetDirty();+ this._initEvents();+ this._initPointer();+ }++ override dispose() {+ this._hoverCustomRanges$.complete();+ this._clickCustomRanges$.complete();+ super.dispose();+ }++ private _initPointer() {+ let preCursor = CURSOR_TYPE.TEXT;+ this.disposeWithMe(this.hoverCustomRanges$.subscribe((ranges) => {+ if (ranges.length) {+ preCursor = this._context.scene.getCursor();+ this._context.scene.setCursor(CURSOR_TYPE.POINTER);+ } else {+ this._context.scene.setCursor(preCursor);+ }+ }));+ }++ private _initResetDirty() {+ this.disposeWithMe(this._skeleton.dirty$.subscribe(() => {+ this._customRangeDirty = true;+ this._bulletDirty = true;+ }));++ this.disposeWithMe(+ fromEventSubject(this._context.engine.onTransformChange$).pipe(+ filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.resize)+ ).subscribe(() => {+ this._customRangeDirty = true;+ this._bulletDirty = true;+ })+ );+ }++ private _initEvents() {+ this.disposeWithMe(fromEventSubject(this._context.scene.onPointerMove$).pipe(throttleTime(0, animationFrameScheduler)).subscribe((evt) => {+ this._hoverCustomRanges$.next(+ this._calcActiveRanges(evt)+ );+ this._hoverBullet$.next(+ this._calcActiveBullet(evt)+ );+ }));++ const onPointerDown$ = fromEventSubject(this._context.mainComponent!.onPointerDown$);+ const onPointerUp$ = fromEventSubject(this._context.scene!.onPointerUp$);+ this.disposeWithMe(onPointerDown$.pipe(+ mergeMap((down) => onPointerUp$.pipe(take(1), map((up) => ({ down, up })))),+ filter(({ down, up }) => down.target === up.target && up.timeStamp - down.timeStamp < 300)+ // filter(({ down, up }) => down.offsetX === up.offsetX && down.offsetY === up.offsetY)+ ).subscribe(({ down }) => {+ if (down.button === 2) {+ return;+ }+ const ranges = this._calcActiveRanges(down);+ if (ranges.length) {+ this._clickCustomRanges$.next(ranges.pop()!);+ }++ const bullet = this._calcActiveBullet(down);+ if (bullet) {+ this._clickBullet$.next(bullet);+ }+ }));+ }++ private _buildCustomRangeBoundsBySegment(segmentId?: string, segmentPage = -1) {+ const customRanges = this._context.unit.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customRanges ?? [];+ const layouts: ICustomRangeBound[] = [];++ customRanges.forEach((range) => {+ const textRange: ITextRangeParam = {+ startOffset: range.startIndex,+ endOffset: range.endIndex,+ collapsed: false,+ segmentId,+ };++ const rects = calcDocRangePositions(textRange, this._documents, this._skeleton, segmentPage);+ if (!rects) {+ return null;+ }++ layouts.push({+ customRange: range,+ rects,+ segmentId,+ segmentPageIndex: segmentPage,+ });+ });++ return layouts;+ }++ private _buildCustomRangeBounds() {+ if (!this._customRangeDirty) {+ return;+ }+ this._customRangeDirty = false;+ const customRangeBounds: ICustomRangeBound[] = [];++ customRangeBounds.push(...this._buildCustomRangeBoundsBySegment());+ this._skeleton.getSkeletonData()?.pages.forEach((page, pageIndex) => {+ if (page.headerId) {+ customRangeBounds.push(...this._buildCustomRangeBoundsBySegment(page.headerId, pageIndex));+ }++ if (page.footerId) {+ customRangeBounds.push(...this._buildCustomRangeBoundsBySegment(page.footerId, pageIndex));+ }+ });++ this._customRangeBounds = customRangeBounds;+ }++ private _calcActiveRanges(evt: IPointerEvent | IMouseEvent) {+ this._buildCustomRangeBounds();++ const { offsetX, offsetY } = evt;+ const { x, y } = transformOffset2Bound(offsetX, offsetY, this._context.scene);+ const matchedRanges = this._customRangeBounds.filter((layout) => {+ return layout.rects.some((rect) => {+ const { left, right, top, bottom } = rect;+ if (x >= left && x <= right && y >= top && y <= bottom) {+ return true;+ }+ return false;+ });+ });++ return matchedRanges.map(+ (range) => ({+ segmentId: range.segmentId,+ range: range.customRange,+ segmentPageIndex: range.segmentPageIndex,+ })+ );+ }++ private _buildBulletBoundsBySegment(segmentId?: string, segmentPage = -1) {+ const body = this._context.unit.getSelfOrHeaderFooterModel(segmentId)?.getBody();+ const paragraphs = body?.paragraphs ?? [];+ const bounds: IBulletBound[] = [];++ paragraphs.forEach((paragraph) => {+ if (paragraph.bullet && paragraph.bullet.listType.indexOf('CHECK_LIST') === 0) {+ const calcRect = (pageIndex: number) => {+ const node = this._skeleton.findNodeByCharIndex(paragraph.startIndex, segmentId, pageIndex);+ const divide = node?.parent;+ const line = divide?.parent;+ const column = line?.parent;+ const targetLine = column?.lines.find((l) => l.paragraphStart && l.paragraphIndex === paragraph.startIndex);+ const bulletNode = targetLine?.divides?.[0]?.glyphGroup?.[0];++ if (!bulletNode) {+ return;+ }++ if (!bulletNode) {+ return;+ }++ const rect = calcDocGlyphPosition(bulletNode, this._documents, this._skeleton, pageIndex);++ if (!rect) {+ return;+ }++ bounds.push({+ rect,+ segmentId,+ segmentPageIndex: pageIndex,+ paragraph,+ });+ };++ calcRect(segmentPage);+ }+ });++ return bounds;+ }++ private _buildBulletBounds() {+ if (!this._bulletDirty) {+ return;+ }+ this._bulletDirty = false;++ this._bulletBounds = [];+ this._bulletBounds.push(...this._buildBulletBoundsBySegment());++ this._skeleton.getSkeletonData()?.pages.forEach((page, pageIndex) => {+ if (page.headerId) {+ this._bulletBounds.push(...this._buildBulletBoundsBySegment(page.headerId, pageIndex));+ }++ if (page.footerId) {+ this._bulletBounds.push(...this._buildBulletBoundsBySegment(page.footerId, pageIndex));+ }+ });+ }++ private _calcActiveBullet(evt: IPointerEvent | IMouseEvent) {+ this._buildBulletBounds();++ const { offsetX, offsetY } = evt;+ const { x, y } = transformOffset2Bound(offsetX, offsetY, this._context.scene);+ const bullet = this._bulletBounds.find((layout) => {+ const { left, right, top, bottom } = layout.rect;+ if (x >= left && x <= right && y >= top && y <= bottom) {+ return true;+ }+ return false;+ });+ return bullet;+ }+}diff --git a/packages/docs-ui/src/services/doc-hover-manager.service.ts b/packages/docs-ui/src/services/doc-hover-manager.service.tsdeleted file mode 100644index 09f9c3f55d..0000000000--- a/packages/docs-ui/src/services/doc-hover-manager.service.ts+++ /dev/null@@ -1,138 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * 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 { DocumentDataModel, ICustomRange, IParagraph, Nullable } from '@univerjs/core';-import { Disposable, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';-import { DocSkeletonManagerService, VIEWPORT_KEY } from '@univerjs/docs';-import type { Documents, IMouseEvent, IPointerEvent, Viewport } from '@univerjs/engine-render';-import { getParagraphByGlyph, IRenderManagerService, PageLayoutType, Vector2 } from '@univerjs/engine-render';-import { Subject } from 'rxjs';--// TODO: this service need to be remove, calc cost to much time-export class DocHoverManagerService extends Disposable {- private readonly _activeCustomRanges$ = new Subject<ICustomRange[]>();- readonly activeCustomRanges$ = this._activeCustomRanges$.asObservable();-- private readonly _activeIndex$ = new Subject<Nullable<number>>();- readonly activeIndex$ = this._activeIndex$.asObservable();-- private readonly _bullet$ = new Subject<Nullable<IParagraph>>();- readonly bullet$ = this._bullet$.asObservable();-- private _scrolling = false;-- constructor(- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService- ) {- super();-- this.disposeWithMe(() => {- this._activeCustomRanges$.complete();- this._activeIndex$.complete();- });- }-- private _getTransformCoordForDocumentOffset(document: Documents, viewport: Viewport, evtOffsetX: number, evtOffsetY: number) {- const { documentTransform } = document.getOffsetConfig();- const originCoord = viewport.transformVector2SceneCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));-- if (!originCoord) {- return;- }-- return documentTransform.clone().invert().applyPoint(originCoord);- }-- private _calcActiveCustomRanges(offsetX: number, offsetY: number) {- const document = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- if (!document) {- this._activeCustomRanges$.next([]);- return;- }-- const currentRender = this._renderManagerService.getRenderById(document.getUnitId());-- if (!currentRender) {- return null;- }- const documentComponent = currentRender.mainComponent as Documents;- const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();- const { pageLayoutType = PageLayoutType.VERTICAL, pageMarginLeft, pageMarginTop, docsLeft, docsTop } = documentComponent.getOffsetConfig();- const coord = this._getTransformCoordForDocumentOffset(- documentComponent,- currentRender.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)!,- offsetX,- offsetY- );- if (!coord) {- return;- }- const node = skeleton.findNodeByCoord(- coord,- pageLayoutType,- pageMarginLeft,- pageMarginTop- );- if (node && node.node) {- const left = node.node.left + pageMarginLeft;- const right = node.node.left + node.node.width + pageMarginLeft;- let index = node.node.parent!.st! + node.node.parent!.glyphGroup.indexOf(node.node)!;- const paragraph = getParagraphByGlyph(node.node, document.getBody());- if (paragraph && paragraph.bullet && index === paragraph.paragraphStart) {- this._bullet$.next(paragraph);- this._activeIndex$.next(null);- this._activeCustomRanges$.next([]);- return;- }-- if (coord.x < left || coord.x > right) {- this._activeIndex$.next(null);- this._activeCustomRanges$.next([]);- this._bullet$.next(null);- return;- }-- if (paragraph && paragraph.bullet) {- index = index - 1;- }-- this._bullet$.next(null);- this._activeIndex$.next(index);- const ranges = document.getCustomRanges()?.filter((range) => range.startIndex <= index && range.endIndex >= index) ?? [];- this._activeCustomRanges$.next(ranges);- }- }-- onMouseMove(evt: IPointerEvent | IMouseEvent) {- if (this._scrolling) {- return;- }- const { offsetX, offsetY } = evt;- this._calcActiveCustomRanges(offsetX, offsetY);- }-- startScroll() {- if (this._scrolling) {- return;- }- this._scrolling = true;- }-- endScroll() {- this._scrolling = false;- }-}diff --git a/packages/docs-ui/src/services/doc-popup-manager.service.ts b/packages/docs-ui/src/services/doc-popup-manager.service.tsindex ef5b41bf47..da7849ebd9 100644--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IDisposable, ITextRange } from '@univerjs/core';+import type { IDisposable, ITextRangeParam } from '@univerjs/core';import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { getLineBounding, IRenderManagerService, NodePositionConvertToCursor, pxToNum } from '@univerjs/engine-render';import type { BaseObject, Documents, IBoundRectNoAngle, IRender, Scene } from '@univerjs/engine-render';@@ -57,11 +57,66 @@ export function transformPosition2Offset(x: number, y: number, scene: Scene) {};}+export function transformOffset2Bound(offsetX: number, offsetY: number, scene: Scene) {+ const { scaleX, scaleY } = scene.getAncestorScale();+ const viewMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);+ if (!viewMain) {+ return {+ x: offsetX,+ y: offsetY,+ };+ }++ const { viewportScrollX: actualScrollX, viewportScrollY: actualScrollY } = viewMain;++ const x = offsetX / scaleX + actualScrollX;++ const y = offsetY / scaleY + actualScrollY;++ return {+ x,+ y,+ };+}+export interface IDocCanvasPopup extends Pick<IPopup, 'direction' | 'excludeOutside' | 'closeOnSelfTarget' | 'componentKey' | 'offset' | 'onClickOutside' | 'hideOnInvisible'> {mask?: boolean;extraProps?: Record<string, any>;}+export const calcDocRangePositions = (range: ITextRangeParam, currentRender: IRender): IBoundRectNoAngle[] | undefined => {+ const { scene, mainComponent, engine } = currentRender;+ const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();+ const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, false, range.segmentId, range.segmentPage);+ const endPosition = skeleton.findNodePositionByCharIndex(range.endOffset, false, range.segmentId, range.segmentPage);+ const document = mainComponent as Documents;++ if (!endPosition || !startPosition) {+ return;+ }++ const documentOffsetConfig = document.getOffsetConfig();+ const { docsLeft, docsTop } = documentOffsetConfig;+ const canvasElement = engine.getCanvasElement();+ const canvasClientRect = canvasElement.getBoundingClientRect();+ const widthOfCanvas = pxToNum(canvasElement.style.width); // declared width+ const { top, left, width } = canvasClientRect; // real width affected by scale+ const scaleAdjust = width / widthOfCanvas;++ const { scaleX, scaleY } = scene.getAncestorScale();+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);+ const { borderBoxPointGroup } = convertor.getRangePointData(startPosition, endPosition);+ const bounds = getLineBounding(borderBoxPointGroup);+ const res = bounds.map((bound) => transformBound2OffsetBound(bound, scene)).map((i) => ({+ left: (i.left + docsLeft * scaleX) * scaleAdjust + left,+ right: (i.right + docsLeft * scaleX) * scaleAdjust + left,+ top: (i.top + docsTop * scaleY) * scaleAdjust + top,+ bottom: (i.bottom + docsTop * scaleY) * scaleAdjust + top,+ }));++ return res;+};+export class DocCanvasPopManagerService extends Disposable {constructor(@Inject(ICanvasPopupService) private readonly _globalPopupManagerService: ICanvasPopupService,@@ -129,47 +184,14 @@ export class DocCanvasPopManagerService extends Disposable {};}- private _createRangePositionObserver(range: ITextRange, currentRender: IRender) {- const calc = (): IBoundRectNoAngle[] | undefined => {- const { scene, mainComponent, engine } = currentRender;- const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();- const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset);- const endPosition = skeleton.findNodePositionByCharIndex(range.endOffset);- const document = mainComponent as Documents;-- if (!endPosition || !startPosition) {- return;- }-- const documentOffsetConfig = document.getOffsetConfig();- const { docsLeft, docsTop } = documentOffsetConfig;- const canvasElement = engine.getCanvasElement();- const canvasClientRect = canvasElement.getBoundingClientRect();- const widthOfCanvas = pxToNum(canvasElement.style.width); // declared width- const { top, left, width } = canvasClientRect; // real width affected by scale- const scaleAdjust = width / widthOfCanvas;-- const { scaleX, scaleY } = scene.getAncestorScale();- const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);- const { contentBoxPointGroup } = convertor.getRangePointData(startPosition, endPosition);- const bounds = getLineBounding(contentBoxPointGroup);- const res = bounds.map((bound) => transformBound2OffsetBound(bound, scene)).map((i) => ({- left: (i.left + docsLeft * scaleX) * scaleAdjust + left,- right: (i.right + docsLeft * scaleX) * scaleAdjust + left,- top: (i.top + docsTop * scaleY) * scaleAdjust + top,- bottom: (i.bottom + docsTop * scaleY) * scaleAdjust + top,- }));-- return res;- };-- const positions = calc() ?? [];+ private _createRangePositionObserver(range: ITextRangeParam, currentRender: IRender) {+ const positions = calcDocRangePositions(range, currentRender) ?? [];const positions$ = new BehaviorSubject(positions);const disposable = new DisposableCollection();disposable.add(this._commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === SetDocZoomRatioOperation.id) {- const position = calc();+ const position = calcDocRangePositions(range, currentRender);if (position) {positions$.next(position);}@@ -179,7 +201,7 @@ export class DocCanvasPopManagerService extends Disposable {const viewMain = currentRender.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);if (viewMain) {disposable.add(viewMain.onScrollAfter$.subscribeEvent(() => {- const position = calc();+ const position = calcDocRangePositions(range, currentRender);if (position) {positions$.next(position);}@@ -233,11 +255,10 @@ export class DocCanvasPopManagerService extends Disposable {};}- attachPopupToRange(range: ITextRange, popup: IDocCanvasPopup): IDisposable {+ attachPopupToRange(range: ITextRangeParam, popup: IDocCanvasPopup): IDisposable {const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_DOC)!;const unitId = workbook.getUnitId();const { direction = 'top' } = popup;-const currentRender = this._renderManagerService.getRenderById(unitId);if (!currentRender) {return {diff --git a/packages/docs/src/basics/custom-range-factory.ts b/packages/docs/src/basics/custom-range-factory.tsindex 568c294c0c..673c8e58f4 100644--- a/packages/docs/src/basics/custom-range-factory.ts+++ b/packages/docs/src/basics/custom-range-factory.ts@@ -19,6 +19,7 @@ import { DataStreamTreeTokenType, IUniverInstanceService, JSONX, TextX, TextXActimport type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';import { RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';import { TextSelectionManagerService } from '../services/text-selection-manager.service';+import { getRichTextEditPath } from '../commands/util';import { getSelectionForAddCustomRange, normalizeSelection } from './selection';interface IAddCustomRangeParam {@@ -105,7 +106,6 @@ export function addCustomRangeFactory(param: IAddCustomRangeParam, body: IDocume}interface IAddCustomRangeFactoryParam {- segmentId?: string;rangeId: string;rangeType: CustomRangeType;wholeEntity?: boolean;@@ -113,11 +113,12 @@ interface IAddCustomRangeFactoryParam {// eslint-disable-next-line max-lines-per-functionexport function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAddCustomRangeFactoryParam) {- const { segmentId, rangeId, rangeType, wholeEntity } = param;+ const { rangeId, rangeType, wholeEntity } = param;const textSelectionManagerService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);const selection = textSelectionManagerService.getActiveTextRangeWithStyle();+ const segmentId = selection?.segmentId;if (!selection) {return false;}@@ -126,7 +127,7 @@ export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAdif (!documentDataModel) {return false;}- const body = documentDataModel.getBody();+ const body = documentDataModel.getSelfOrHeaderFooterModel(selection.segmentId).getBody();const unitId = documentDataModel.getUnitId();if (!body) {return false;@@ -232,7 +233,8 @@ export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAdtextRanges: undefined,},};- doMutation.params.actions = jsonX.editOp(textX.serialize());+ const path = getRichTextEditPath(documentDataModel, segmentId);+ doMutation.params.actions = jsonX.editOp(textX.serialize(), path);return doMutation;}@@ -251,7 +253,7 @@ function deleteCustomRangeTextX(accessor: IAccessor, params: IDeleteCustomRangePreturn false;}- const range = documentDataModel.getBody()?.customRanges?.find((r) => r.rangeId === rangeId);+ const range = documentDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.customRanges?.find((r) => r.rangeId === rangeId);if (!range) {return false;}@@ -295,12 +297,20 @@ function deleteCustomRangeTextX(accessor: IAccessor, params: IDeleteCustomRangeP}export function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCustomRangeParam) {+ const { unitId, segmentId } = params;+ const univerInstanceService = accessor.get(IUniverInstanceService);++ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);+ if (!documentDataModel) {+ return false;+ }const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {id: RichTextEditingMutation.id,params: {unitId: params.unitId,actions: [],textRanges: undefined,+ segmentId,},};@@ -310,6 +320,7 @@ export function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCusreturn false;}- doMutation.params.actions = jsonX.editOp(textX.serialize());+ const path = getRichTextEditPath(documentDataModel, segmentId);+ doMutation.params.actions = jsonX.editOp(textX.serialize(), path);return doMutation;}diff --git a/packages/docs/src/basics/custom-range.ts b/packages/docs/src/basics/custom-range.tsindex 4d62c24ce9..74d2932988 100644--- a/packages/docs/src/basics/custom-range.ts+++ b/packages/docs/src/basics/custom-range.ts@@ -54,7 +54,7 @@ export function shouldDeleteCustomRange(deleteStart: number, deleteLen: number,return true;}-export function getCustomRangesIntesetsWithRange(range: ITextRange, customRanges: ICustomRange[]) {+export function getCustomRangesInterestsWithRange(range: ITextRange, customRanges: ICustomRange[]) {const result: ICustomRange[] = [];for (let i = 0, len = customRanges.length; i < len; i++) {const customRange = customRanges[i];diff --git a/packages/docs/src/basics/plain-text.ts b/packages/docs/src/basics/plain-text.tsindex 3ff40f9b14..aa17263d73 100644--- a/packages/docs/src/basics/plain-text.ts+++ b/packages/docs/src/basics/plain-text.ts@@ -14,7 +14,20 @@* limitations under the License.*/-import { DataStreamTreeTokenType, type IDocumentData } from '@univerjs/core';+import type { IDocumentBody, IDocumentData } from '@univerjs/core';+import { DataStreamTreeTokenType } from '@univerjs/core';++/**+ * get plain text from rich-text+ */+export const getPlainTextFormBody = (body: IDocumentBody) => {+ let str = body.dataStream;+ if (body.dataStream.endsWith('\r\n')) {+ str = body.dataStream.slice(0, -2);+ }++ return str.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');+};/*** get plain text from rich-text@@ -23,6 +36,5 @@ export const getPlainTextFormDocument = (data: IDocumentData) => {if (!data.body) {return '';}- const str = data.body.dataStream.slice(0, -2);- return str.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, '');+ return getPlainTextFormBody(data.body);};diff --git a/packages/docs/src/basics/replace.ts b/packages/docs/src/basics/replace.tsindex e130c68ad0..2f60fc5eaa 100644--- a/packages/docs/src/basics/replace.ts+++ b/packages/docs/src/basics/replace.ts@@ -14,12 +14,13 @@* limitations under the License.*/-import type { DocumentDataModel, IAccessor, IDeleteAction, IDocumentBody, IMutationInfo, IRetainAction, ITextRange } from '@univerjs/core';+import type { DocumentDataModel, IAccessor, IDeleteAction, IDocumentBody, IMutationInfo, IRetainAction, ITextRange, ITextRangeParam } from '@univerjs/core';import { IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';import type { ITextRangeWithStyle } from '@univerjs/engine-render';import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';import { RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';import { TextSelectionManagerService } from '../services/text-selection-manager.service';+import { getRichTextEditPath } from '../commands/util';import { isIntersecting, shouldDeleteCustomRange } from './custom-range';import { getDeleteSelection } from './selection';@@ -48,7 +49,6 @@ export function getRetainAndDeleteAndExcludeLineBreak(const relativeCustomRanges = body.customRanges?.filter((customRange) => isIntersecting(customRange.startIndex, customRange.endIndex, startOffset, endOffset));const toDeleteRanges = new Set(relativeCustomRanges?.filter((customRange) => shouldDeleteCustomRange(startOffset, endOffset - startOffset, customRange, dataStream)));const retainPoints = new Set<number>();-relativeCustomRanges?.forEach((range) => {if (toDeleteRanges.has(range)) {return;@@ -115,7 +115,7 @@ export function getRetainAndDeleteAndExcludeLineBreak(export interface IReplaceSelectionFactoryParams {unitId: string;- selection?: ITextRange;+ selection?: ITextRangeParam;originBody?: IDocumentBody;@@ -128,11 +128,15 @@ export interface IReplaceSelectionFactoryParams {export function replaceSelectionFactory(accessor: IAccessor, params: IReplaceSelectionFactoryParams) {const { unitId, originBody, body: insertBody } = params;const univerInstanceService = accessor.get(IUniverInstanceService);+ const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);+ if (!docDataModel) {+ return false;+ }+ const segmentId = params.selection?.segmentId;let body: IDocumentBody | undefined;if (!params.originBody) {- const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);- body = docDataModel?.getBody();+ body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();} else {body = originBody;}@@ -148,6 +152,7 @@ export function replaceSelectionFactory(accessor: IAccessor, params: IReplaceSelstartOffset: selection.startOffset + insertBody.dataStream.length,endOffset: selection.startOffset + insertBody.dataStream.length,collapsed: true,+ segmentId,}];const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {@@ -157,20 +162,23 @@ export function replaceSelectionFactory(accessor: IAccessor, params: IReplaceSelactions: [],textRanges,debounce: true,+ segmentId,},};const textX = new TextX();const jsonX = JSONX.getInstance();// delete- textX.push(...getRetainAndDeleteAndExcludeLineBreak(selection, body));+ textX.push(...getRetainAndDeleteAndExcludeLineBreak(selection, body, segmentId));// inserttextX.push({t: TextXActionType.INSERT,body: insertBody,len: insertBody.dataStream.length,line: 0,+ segmentId,});- doMutation.params.actions = jsonX.editOp(textX.serialize());+ const path = getRichTextEditPath(docDataModel, segmentId);+ doMutation.params.actions = jsonX.editOp(textX.serialize(), path);return doMutation;}diff --git a/packages/docs/src/basics/selection.ts b/packages/docs/src/basics/selection.tsindex 818f9bcd72..71081f1ef4 100644--- a/packages/docs/src/basics/selection.ts+++ b/packages/docs/src/basics/selection.ts@@ -123,7 +123,7 @@ export function getDeleteSelection<T extends ITextRange>(selection: T, body: IDo};}-export function getInsertSelection(selection: ITextRange, body: IDocumentBody): ITextRange {+export function getInsertSelection<T extends ITextRange>(selection: T, body: IDocumentBody): T {let { startOffset, endOffset, collapsed } = normalizeSelection(selection);if (collapsed) {@@ -138,12 +138,14 @@ export function getInsertSelection(selection: ITextRange, body: IDocumentBody):}return {+ ...selection,startOffset,endOffset,collapsed,};} else {return {+ ...selection,...getSelectionWithSymbolMax(selection, body),collapsed: false,};diff --git a/packages/docs/src/commands/commands/clipboard.inner.command.ts b/packages/docs/src/commands/commands/clipboard.inner.command.tsindex 4b7f873034..0079523cb5 100644--- a/packages/docs/src/commands/commands/clipboard.inner.command.ts+++ b/packages/docs/src/commands/commands/clipboard.inner.command.ts@@ -88,6 +88,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {unitId,actions: [],textRanges,+ segmentId,},};diff --git a/packages/docs/src/commands/commands/ime-input.command.ts b/packages/docs/src/commands/commands/ime-input.command.tsindex 7316e502db..c1a0f5cf16 100644--- a/packages/docs/src/commands/commands/ime-input.command.ts+++ b/packages/docs/src/commands/commands/ime-input.command.ts@@ -54,7 +54,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {if (!previousActiveRange) {return false;}- const { startOffset, style, segmentId } = previousActiveRange;+ const { style, segmentId } = previousActiveRange;const body = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();if (body == null) {@@ -63,6 +63,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {const insertRange = getInsertSelection(previousActiveRange, body);Object.assign(previousActiveRange, insertRange);+ const { startOffset } = previousActiveRange;const len = newText.length;diff --git a/packages/docs/src/commands/commands/list.command.ts b/packages/docs/src/commands/commands/list.command.tsindex 4c8719e533..b9e5c1ee31 100644--- a/packages/docs/src/commands/commands/list.command.ts+++ b/packages/docs/src/commands/commands/list.command.ts@@ -512,6 +512,7 @@ export const CheckListCommand: ICommand<IBulletListCommandParams> = {export interface IToggleCheckListCommandParams {index: number;+ segmentId?: string;}export const ToggleCheckListCommand: ICommand<IToggleCheckListCommandParams> = {@@ -524,14 +525,14 @@ export const ToggleCheckListCommand: ICommand<IToggleCheckListCommandParams> = {}const univerInstanceService = accessor.get(IUniverInstanceService);const commandService = accessor.get(ICommandService);- const { index } = params;+ const { index, segmentId } = params;const docDataModel = univerInstanceService.getCurrentUniverDocInstance();if (docDataModel == null) {return false;}- const paragraphs = docDataModel.getBody()?.paragraphs;+ const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;if (paragraphs == null) {return false;}@@ -547,6 +548,7 @@ export const ToggleCheckListCommand: ICommand<IToggleCheckListCommandParams> = {unitId,actions: [],textRanges: [],+ segmentId,},};@@ -573,6 +575,7 @@ export const ToggleCheckListCommand: ICommand<IToggleCheckListCommandParams> = {textX.push({t: TextXActionType.RETAIN,len: startIndex - memoryCursor.cursor,+ segmentId,});textX.push({@@ -599,11 +602,12 @@ export const ToggleCheckListCommand: ICommand<IToggleCheckListCommandParams> = {],},coverType: UpdateDocsAttributeType.REPLACE,+ segmentId,});memoryCursor.moveCursorTo(startIndex + 1);- const path = getRichTextEditPath(docDataModel);+ const path = getRichTextEditPath(docDataModel, segmentId);doMutation.params.actions = jsonX.editOp(textX.serialize(), path);const result = commandService.syncExecuteCommand<IRichTextEditingMutationParams,diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.tsindex 80a7f3bbc9..b73a42976a 100644--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts@@ -96,7 +96,6 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,// Step 1: Update Doc Data Model.const undoActions = JSONX.invertWithDoc(actions, documentDataModel.getSnapshot());documentDataModel.apply(actions);-// Step 2: Update Doc View Model.documentViewModel.reset(documentDataModel);// Step 3: Update cursor & selection.diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex 21eadcefca..f70bf09150 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -14,6 +14,7 @@* limitations under the License.*/+export { getCustomRangesInterestsWithRange } from './basics/custom-range';export { getParagraphsInRange, getParagraphsInRanges } from './commands/commands/list.command';export { replaceSelectionFactory } from './basics/replace';export { makeSelection, getSelectionText, getDeleteSelection, getInsertSelection, isSegmentIntersects } from './basics/selection';@@ -94,7 +95,7 @@ export {export { getRetainAndDeleteFromReplace } from './basics/retain-delete-params';export { getRichTextEditPath } from './commands/util';-export { getPlainTextFormDocument } from './basics/plain-text';+export { getPlainTextFormDocument, getPlainTextFormBody } from './basics/plain-text';export { addCustomRangeFactory, addCustomRangeBySelectionFactory, deleteCustomRangeFactory } from './basics/custom-range-factory';export { addCustomDecorationBySelectionFactory, addCustomDecorationFactory, deleteCustomDecorationFactory } from './basics/custom-decoration-factory';export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';diff --git a/packages/docs/src/services/doc-auto-format.service.ts b/packages/docs/src/services/doc-auto-format.service.tsindex 51368cc9a4..b71aec492a 100644--- a/packages/docs/src/services/doc-auto-format.service.ts+++ b/packages/docs/src/services/doc-auto-format.service.ts@@ -16,7 +16,7 @@import type { DocumentDataModel, ICommandInfo, ICustomRange, IDisposable, IParagraph, IParagraphRange, ITextRange, Nullable } from '@univerjs/core';import { Disposable, Inject, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';-import { getCustomRangesIntesetsWithRange } from '../basics/custom-range';+import { getCustomRangesInterestsWithRange } from '../basics/custom-range';import type { ITextActiveRange } from './text-selection-manager.service';import { TextSelectionManagerService } from './text-selection-manager.service';@@ -122,7 +122,7 @@ export class DocAutoFormatService extends Disposable {selection,isBody: !selection.segmentId,paragraphs: getParagraphsInRange(selection, doc.getBody()?.paragraphs ?? []),- customRanges: getCustomRangesIntesetsWithRange(selection, doc.getBody()?.customRanges ?? []),+ customRanges: getCustomRangesInterestsWithRange(selection, doc.getBody()?.customRanges ?? []),commandId: id,commandParams: params,};diff --git a/packages/docs/src/services/doc-interceptor/doc-interceptor.service.ts b/packages/docs/src/services/doc-interceptor/doc-interceptor.service.tsindex 724f049263..fb75289e3d 100644--- a/packages/docs/src/services/doc-interceptor/doc-interceptor.service.ts+++ b/packages/docs/src/services/doc-interceptor/doc-interceptor.service.ts@@ -30,16 +30,14 @@ export class DocInterceptorService extends Disposable implements IRenderModule {) {super();- this.disposeWithMe(this._docSkeletonManagerService.currentViewModel$.subscribe((viewModel) => {- if (viewModel) {- const unitId = viewModel.getDataModel().getUnitId();- if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY || unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {- return;- }+ const viewModel = this._docSkeletonManagerService.getViewModel();- this.interceptDocumentViewModel(viewModel);- }- }));+ const unitId = viewModel.getDataModel().getUnitId();+ if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY || unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {+ return;+ }++ this.disposeWithMe(this.interceptDocumentViewModel(viewModel));this.disposeWithMe(this.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_RANGE, {priority: -1,@@ -47,6 +45,17 @@ export class DocInterceptorService extends Disposable implements IRenderModule {return next(data);},}));++ let disposableCollection = new DisposableCollection();+ viewModel.segmentViewModels$.subscribe((segmentViewModels) => {+ disposableCollection.dispose();+ disposableCollection = new DisposableCollection();+ segmentViewModels.forEach((segmentViewModel) => {+ disposableCollection.add(this.interceptDocumentViewModel(segmentViewModel));+ });+ });++ this.disposeWithMe(disposableCollection);}intercept<T extends IInterceptor<any, any>>(name: T, interceptor: T) {diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.tsindex b51600c0eb..60e90f4720 100644--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts@@ -16,6 +16,7 @@import type { ColumnSeparatorType, ISectionColumnProperties, LocaleService, Nullable } from '@univerjs/core';import { PRESET_LIST_TYPE, SectionType } from '@univerjs/core';+import { Subject } from 'rxjs';import type {IDocumentSkeletonCached,IDocumentSkeletonGlyph,@@ -112,6 +113,9 @@ function getPagePath(page: IDocumentSkeletonPage) {}export class DocumentSkeleton extends Skeleton {+ private _dirty$ = new Subject<boolean>();+ readonly dirty$ = this._dirty$.asObservable();+private _skeletonData: Nullable<IDocumentSkeletonCached>;private _findLiquid: Liquid = new Liquid();@@ -156,6 +160,7 @@ export class DocumentSkeleton extends Skeleton {// const start = +new Date();this._skeletonData = this._createSkeleton(ctx, bounds);// console.log('skeleton calculate cost', +new Date() - start);+ this._dirty$.next(true);}getSkeletonData() {diff --git a/packages/engine-render/src/components/docs/view-model/document-view-model.ts b/packages/engine-render/src/components/docs/view-model/document-view-model.tsindex bb2b4a4e91..b16d6c2ed9 100644--- a/packages/engine-render/src/components/docs/view-model/document-view-model.ts+++ b/packages/engine-render/src/components/docs/view-model/document-view-model.ts@@ -175,6 +175,9 @@ export class DocumentViewModel implements IDisposable {headerTreeMap: Map<string, DocumentViewModel> = new Map();footerTreeMap: Map<string, DocumentViewModel> = new Map();+ private readonly _segmentViewModels$ = new BehaviorSubject<DocumentViewModel[]>([]);+ readonly segmentViewModels$ = this._segmentViewModels$.asObservable();+constructor(private _documentDataModel: DocumentDataModel) {if (_documentDataModel.getBody() == null) {return;@@ -607,14 +610,18 @@ export class DocumentViewModel implements IDisposable {private _buildHeaderFooterViewModel() {const { headerModelMap, footerModelMap } = this._documentDataModel;-+ const viewModels = [];for (const [headerId, headerModel] of headerModelMap) {this.headerTreeMap.set(headerId, new DocumentViewModel(headerModel));+ viewModels.push(this.headerTreeMap.get(headerId)!);}for (const [footerId, footerModel] of footerModelMap) {this.footerTreeMap.set(footerId, new DocumentViewModel(footerModel));+ viewModels.push(this.footerTreeMap.get(footerId)!);}++ this._segmentViewModels$.next(viewModels);}private _getParagraphByIndex(nodes: DataStreamTreeNode[], insertIndex: number): Nullable<DataStreamTreeNode> {diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx b/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsxindex 2336e97b6c..f08747827a 100644--- a/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx@@ -22,6 +22,7 @@ import { ICommandService, LocaleService, useDependency } from '@univerjs/core';import type { IDocumentBody } from '@univerjs/core';import { ITextSelectionRenderManager } from '@univerjs/engine-render';import { TextSelectionManagerService } from '@univerjs/docs';+import { KeyCode } from '@univerjs/ui';import { IThreadCommentMentionDataService } from '../../services/thread-comment-mention-data.service';import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';import styles from './index.module.less';@@ -75,6 +76,18 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThr},}));+ const handleSave = () => {+ if (localComment.text) {+ onSave?.({+ ...localComment,+ text: localComment.text,+ });+ setEditing(false);+ setLocalComment({ text: undefined });+ (inputRef.current as any)?.inputElement.blur();+ }+ };+return (<div className={styles.threadCommentEditor} onClick={(e) => e.preventDefault()}><Mentions@@ -98,6 +111,11 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThrtextSelectionRenderManager.blur();setEditing(true);}}+ onKeyDown={(e) => {+ if (e.keyCode === KeyCode.ENTER) {+ handleSave();+ }+ }}><Mentionkey={mentionDataService.trigger}@@ -106,6 +124,7 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThr.then((res) => res.map(transformMention)).then(callback) as any}displayTransform={(id, label) => `@${label} `}renderSuggestion={mentionDataService.renderSuggestion ?? defaultRenderSuggestion}+/></Mentions>{editing@@ -125,16 +144,7 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThr<Buttontype="primary"disabled={!localComment.text}- onClick={() => {- if (localComment.text) {- onSave?.({- ...localComment,- text: localComment.text,- });- setEditing(false);- setLocalComment({ text: undefined });- }- }}+ onClick={handleSave}>{localeService.t(id ? 'threadCommentUI.editor.save' : 'threadCommentUI.editor.reply')}</Button>diff --git a/packages/ui/src/services/popup/canvas-popup.service.ts b/packages/ui/src/services/popup/canvas-popup.service.tsindex 943a6d6167..b794f2888b 100644--- a/packages/ui/src/services/popup/canvas-popup.service.ts+++ b/packages/ui/src/services/popup/canvas-popup.service.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';import { createIdentifier, Disposable, Tools } from '@univerjs/core';import type { IRectPopupProps } from '@univerjs/design';import type { IBoundRectNoAngle } from '@univerjs/engine-render';@@ -21,7 +22,7 @@ import type { Observable } from 'rxjs';import { BehaviorSubject } from 'rxjs';export interface IPopup extends Pick<IRectPopupProps, 'closeOnSelfTarget' | 'direction' | 'excludeOutside' | 'onClickOutside' > {- anchorRect: IBoundRectNoAngle;+ anchorRect: Nullable<IBoundRectNoAngle>;anchorRect$: Observable<IBoundRectNoAngle>;excludeRects?: IBoundRectNoAngle[];excludeRects$?: Observable<IBoundRectNoAngle[]>;diff --git a/packages/ui/src/views/components/popup/CanvasPopup.tsx b/packages/ui/src/views/components/popup/CanvasPopup.tsxindex 3d5b90ec70..fdcee4991d 100644--- a/packages/ui/src/views/components/popup/CanvasPopup.tsx+++ b/packages/ui/src/views/components/popup/CanvasPopup.tsx@@ -17,8 +17,7 @@import { useDependency } from '@univerjs/core';import React, { useEffect, useMemo, useState } from 'react';import { RectPopup } from '@univerjs/design';-import type { IBoundRectNoAngle } from '@univerjs/engine-render';-import { throttleTime } from 'rxjs';+import { animationFrameScheduler, throttleTime } from 'rxjs';import { ICanvasPopupService } from '../../../services/popup/canvas-popup.service';import { useObservable } from '../../../components/hooks/observable';import { ComponentManager } from '../../../common';@@ -31,15 +30,19 @@ interface ISingleCanvasPopupProps {const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps) => {const [hidden, setHidden] = useState(false);- const anchorRect$ = useMemo(() => popup.anchorRect$.pipe(throttleTime(16)), [popup.anchorRect$]);- const excludeRects$ = useMemo(() => popup.excludeRects$?.pipe(throttleTime(16)), [popup.excludeRects$]);+ const anchorRect$ = useMemo(() => popup.anchorRect$.pipe(throttleTime(0, animationFrameScheduler)), [popup.anchorRect$]);+ const excludeRects$ = useMemo(() => popup.excludeRects$?.pipe(throttleTime(0, animationFrameScheduler)), [popup.excludeRects$]);const anchorRect = useObservable(anchorRect$, popup.anchorRect);const excludeRects = useObservable(excludeRects$, popup.excludeRects);- const { bottom, left, right, top } = anchorRect;const { offset, canvasElement, hideOnInvisible = true } = popup;// We add an offset to the anchor rect to make the popup offset with the anchor.- const rectWithOffset: IBoundRectNoAngle = useMemo(() => {+ const rectWithOffset = useMemo(() => {+ if (!anchorRect) {+ return null;+ }++ const { bottom, left, right, top } = anchorRect;const [x = 0, y = 0] = offset ?? [];return {left: left - x,@@ -47,10 +50,10 @@ const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps) => {top: top - y,bottom: bottom + y,};- }, [bottom, left, right, top, offset]);+ }, [anchorRect, offset]);useEffect(() => {- if (!hideOnInvisible) {+ if (!hideOnInvisible || !rectWithOffset) {return;}const rect = canvasElement.getBoundingClientRect();@@ -62,7 +65,7 @@ const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps) => {}}, [rectWithOffset, canvasElement, hideOnInvisible]);- if (hidden) {+ if (hidden || !rectWithOffset) {return null;}