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
feat(docs): support doc-hover-service (#2824)
zhangw28dbb786a32c
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 414ac555a5..d814101f71 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -54,7 +54,7 @@ export type { TPriority } from './docs/data-model/text-x/text-x';export { JSONX, JSON1 } from './docs/data-model/json-x/json-x';export type { JSONXActions, JSONXPath } from './docs/data-model/json-x/json-x';export { replaceInDocumentBody } from './docs/data-model/replacement';-export { type IEventObserver, EventState, EventSubject } from './observer/observable';+export { type IEventObserver, EventState, EventSubject, fromEventSubject } from './observer/observable';export { Plugin } from './services/plugin/plugin';export { PluginService, DependentOn } from './services/plugin/plugin.service';export {diff --git a/packages/core/src/observer/observable.ts b/packages/core/src/observer/observable.tsindex f1cb7cde59..866ee2b212 100644--- a/packages/core/src/observer/observable.ts+++ b/packages/core/src/observer/observable.ts@@ -15,7 +15,7 @@*/import type { Observer as RxObserver, Subscription } from 'rxjs';-import { Subject } from 'rxjs';+import { Observable, Subject } from 'rxjs';/*** A class serves as a medium between the observable and its observers@@ -131,3 +131,11 @@ export class EventSubject<T> extends Subject<[T, EventState]> {}}+export function fromEventSubject<T>(subject$: EventSubject<T>) {+ return new Observable<T>((subscriber) => {+ const ob = subject$.subscribeEvent((evt) => {+ subscriber.next(evt);+ });+ return () => ob.unsubscribe();+ });+}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.tsnew file mode 100644index 0000000000..5ea16ce2ba--- /dev/null+++ b/packages/docs-ui/src/controllers/render-controllers/doc-hover.render-controller.ts@@ -0,0 +1,56 @@+/**+ * 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, throttleTime } 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(throttleTime(16))+ .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/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.tsindex 8b3df68f8d..a2d52520bd 100644--- a/packages/docs-ui/src/docs-ui-plugin.ts+++ b/packages/docs-ui/src/docs-ui-plugin.ts@@ -54,6 +54,8 @@ import { DocBackScrollRenderController } from './controllers/render-controllers/import { DocCanvasPopManagerService } from './services/doc-popup-manager.service';import { DocsRenderService } from './services/docs-render.service';import { DocHeaderFooterController } from './controllers/doc-header-footer.controller';+import { DocHoverManagerService } from './services/doc-hover-manager.service';+import { DocHoverRenderController } from './controllers/render-controllers/doc-hover.render-controller';export class UniverDocsUIPlugin extends Plugin {static override pluginName = DOC_UI_PLUGIN_NAME;@@ -110,6 +112,7 @@ export class UniverDocsUIPlugin extends Plugin {[AppUIController, { useFactory: () => this._injector.createInstance(AppUIController, this._config) }],[IDocClipboardService, { useClass: DocClipboardService }],[DocCanvasPopManagerService],+ [DocHoverManagerService],];dependencies.forEach((d) => injector.add(d));@@ -151,6 +154,7 @@ export class UniverDocsUIPlugin extends Plugin {[DocBackScrollRenderController],[DocTextSelectionRenderController],[DocHeaderFooterController],+ [DocHoverRenderController],] as Dependency[]).forEach((m) => {this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m);});diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex 4b19d9975b..564c26084c 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -24,6 +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';// #region - all commandsdiff --git a/packages/docs-ui/src/services/doc-hover-manager.service.ts b/packages/docs-ui/src/services/doc-hover-manager.service.tsnew file mode 100644index 0000000000..09af3e283a--- /dev/null+++ b/packages/docs-ui/src/services/doc-hover-manager.service.ts@@ -0,0 +1,143 @@+/**+ * 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, 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 { IRenderManagerService, PageLayoutType, Vector2 } from '@univerjs/engine-render';+import { BehaviorSubject } from 'rxjs';++/**+ * 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.+ */+export class DocHoverManagerService extends Disposable {+ private readonly _activeCustomRanges$ = new BehaviorSubject<ICustomRange[]>([]);+ readonly activeCustomRanges$ = this._activeCustomRanges$.asObservable();++ private readonly _activeIndex$ = new BehaviorSubject<Nullable<number>>(null);+ readonly activeIndex$ = this._activeIndex$.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;+ if (coord.x < left || coord.x > right) {+ this._activeIndex$.next(null);+ this._activeCustomRanges$.next([]);+ return;+ }++ const index = node.node.parent!.st! + node.node.parent!.glyphGroup.indexOf(node.node)!;+ if (index !== this._activeIndex$.value) {+ this._activeIndex$.next(index);+ }++ const ranges = document.getCustomRanges()?.filter((range) => range.startIndex <= index && range.endIndex >= index) ?? [];+ const currentRanges = this._activeCustomRanges$.value;+ if (currentRanges.length === ranges.length && currentRanges.every((range, i) => range.rangeId === ranges[i].rangeId)) {+ return;+ }++ 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-mark-selection.service.ts b/packages/docs-ui/src/services/doc-mark-selection.service.tsdeleted file mode 100644index a80cd99e97..0000000000--- a/packages/docs-ui/src/services/doc-mark-selection.service.ts+++ /dev/null@@ -1,111 +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 } from '@univerjs/core';-import { IUniverInstanceService, Tools, UniverInstanceType } from '@univerjs/core';-import { type BaseObject, IRenderManagerService, type ITextRangeWithStyle } from '@univerjs/engine-render';--export interface IDocMarkSelectionService {- addShape(selection: ITextRangeWithStyle, zIndex?: number): string | null;- removeShape(id: string): void;- removeAllShapes(): void;- refreshShapes(): void;- getShapeMap(): Map<string, IDocMarkSelectionInfo>;-}--export interface IDocMarkSelectionInfo {- control: BaseObject[] | null;- unitId: string;- selection: ITextRangeWithStyle;- zIndex: number;-}--const DEFAULT_Z_INDEX = 10000;--export class DocMarkSelectionService implements IDocMarkSelectionService {- private _shapeMap: Map<string, IDocMarkSelectionInfo> = new Map();-- constructor(- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService- ) {}-- addShape(selection: ITextRangeWithStyle, zIndex = DEFAULT_Z_INDEX): string | null {- const doc = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- if (!doc) return null;- const id = Tools.generateRandomId();-- this._shapeMap.set(id, {- selection,- unitId: doc.getUnitId(),- zIndex,- control: null,- });-- this.refreshShapes();- return id;- }-- removeShape(id: string): void {- const shapeInfo = this._shapeMap.get(id);- if (!shapeInfo) return;- const { control } = shapeInfo;- control && control.forEach((obj) => obj.dispose());- this._shapeMap.delete(id);- }-- removeAllShapes(): void {- for (const shape of this._shapeMap.values()) {- const { control } = shape;- control && control.forEach((obj) => obj.dispose());- }- this._shapeMap.clear();- }-- refreshShapes() {- const doc = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- if (!doc) return;-- const currentUnitId = doc.getUnitId();- this._shapeMap.forEach((shape) => {- const { unitId, selection, control: oldControl, zIndex } = shape;-- oldControl && oldControl.forEach((obj) => obj.dispose());-- if (unitId !== currentUnitId) {- return;- }-- const { style } = selection;- const renderUnit = this._renderManagerService.getRenderById(unitId);- const scene = renderUnit?.scene;- // const { rangeWithCoord, primaryWithCoord } =- // this._selectionRenderService.attachSelectionWithCoord(selection);-- // const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrentSkeleton();- // if (!scene || !skeleton) return;-- // const { rowHeaderWidth, columnHeaderHeight } = skeleton;- // const control = new SelectionShape(scene, zIndex, false, this._themeService);- // control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);- // shape.control = control;- });- }-- getShapeMap(): Map<string, IDocMarkSelectionInfo> {- return this._shapeMap;- }-}diff --git a/packages/docs/src/basics/selection.ts b/packages/docs/src/basics/selection.tsindex ce512f88fc..10a2ccd7ec 100644--- a/packages/docs/src/basics/selection.ts+++ b/packages/docs/src/basics/selection.ts@@ -68,12 +68,12 @@ export function getDeleteSelection<T extends ITextRange>(selection: T, body: IDoif (collapsed) {if (direction === DeleteDirection.LEFT) {- while (body.dataStream[startOffset - 1] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {+ while (isCustomRangeSplitSymbol(body.dataStream[startOffset - 1])) {endOffset -= 1;startOffset -= 1;}} else {- while (body.dataStream[startOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {+ while (isCustomRangeSplitSymbol(body.dataStream[startOffset])) {endOffset += 1;startOffset += 1;}