Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(ui): change floating position (#2698)

Wenzhao Huf2fbd3bdf1f2
diff --git a/packages/design/src/components/popup/RectPopup.tsx b/packages/design/src/components/popup/RectPopup.tsx
index 1ff0edc410..8daf804da7 100644
--- a/packages/design/src/components/popup/RectPopup.tsx
+++ b/packages/design/src/components/popup/RectPopup.tsx
@@ -64,7 +64,7 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbe
if (direction === 'vertical' || direction === 'top' || direction === 'bottom') {
const { left: startX, top: startY, right: endX, bottom: endY } = position;
const verticalStyle = direction === 'top'
- // const verticalStyle = ((endY + height) > containerHeight || direction === 'top')
+ // const verticalStyle = ((endY + height) > containerHeight || direction === 'top')
? { top: Math.max(startY - height, PUSHING_MINIMUM_GAP) }
: { top: Math.min(endY, containerHeight - height - PUSHING_MINIMUM_GAP) };
@@ -108,10 +108,9 @@ function RectPopup(props: IRectPopupProps) {
if (!nodeRef.current) return;
const { clientWidth, clientHeight } = nodeRef.current;
- const parent = nodeRef.current.parentElement;
- if (!parent) return;
+ const innerWidth = window.innerWidth;
+ const innerHeight = window.innerHeight;
- const { clientWidth: innerWidth, clientHeight: innerHeight } = parent;
setPosition(calcPopupPosition(
{
position: anchorRect,
@@ -157,11 +156,8 @@ function RectPopup(props: IRectPopupProps) {
clickOtherFn(e);
};
- window.addEventListener('click', handleClickOther);
-
- return () => {
- window.removeEventListener('click', handleClickOther);
- };
+ window.addEventListener('pointerdown', handleClickOther);
+ return () => window.removeEventListener('pointerdown', handleClickOther);
}, [anchorRect, anchorRect.bottom, anchorRect.left, anchorRect.right, anchorRect.top, clickOtherFn, excludeOutside]);
return (
@@ -169,9 +165,7 @@ function RectPopup(props: IRectPopupProps) {
ref={nodeRef}
style={style}
className={styles.popupAbsolute}
- onClick={(e) => {
- e.stopPropagation();
- }}
+ onPointerDown={(e) => e.stopPropagation()}
>
<RectPopupContext.Provider value={anchorRect}>
{children}
diff --git a/packages/engine-render/package.json b/packages/engine-render/package.json
index 4811b51dda..3aba8e6fe3 100644
--- a/packages/engine-render/package.json
+++ b/packages/engine-render/package.json
@@ -65,6 +65,8 @@
"rxjs": ">=7.0.0"
},
"dependencies": {
+ "@floating-ui/dom": "^1.6.7",
+ "@floating-ui/utils": "^0.2.4",
"cjk-regex": "^3.1.0",
"franc-min": "^6.2.0",
"opentype.js": "^1.3.4"
diff --git a/packages/engine-render/src/engine.ts b/packages/engine-render/src/engine.ts
index a49e23e0ca..b33d4f950c 100644
--- a/packages/engine-render/src/engine.ts
+++ b/packages/engine-render/src/engine.ts
@@ -17,7 +17,7 @@
import type { Nullable } from '@univerjs/core';
import { toDisposable } from '@univerjs/core';
-import { Subject } from 'rxjs';
+import { Observable, shareReplay, Subject } from 'rxjs';
import type { CURSOR_TYPE } from './basics/const';
import type { IKeyboardEvent, IPointerEvent } from './basics/i-events';
import { DeviceType, PointerInput } from './basics/i-events';
@@ -27,15 +27,33 @@ import { getPointerPrefix, getSizeForDom, IsSafari, requestNewFrame } from './ba
import { Canvas, CanvasRenderMode } from './canvas';
import type { Scene } from './scene';
import { ThinEngine } from './thin-engine';
+import { observeClientRect } from './floating/util';
export class Engine extends ThinEngine<Scene> {
renderEvenInBackground = true;
private readonly _beginFrame$ = new Subject<void>();
readonly beginFrame$ = this._beginFrame$.asObservable();
+
private readonly _endFrame$ = new Subject<void>();
readonly endFrame$ = this._endFrame$.asObservable();
+ private _rect$: Nullable<Observable<void>> = null;
+ public get clientRect$(): Observable<void> {
+ return this._rect$ || (this._rect$ = new Observable((subscriber) => {
+ if (!this._container) {
+ throw new Error('[Engine]: cannot subscribe to rect changes when container is not set!');
+ }
+
+ const sub = observeClientRect(this._container).subscribe(() => subscriber.next());
+
+ return () => {
+ sub.unsubscribe();
+ this._rect$ = null;
+ };
+ })).pipe(shareReplay(1));
+ }
+
private _container: Nullable<HTMLElement>;
private _canvas: Nullable<Canvas>;
diff --git a/packages/engine-render/src/floating/util.ts b/packages/engine-render/src/floating/util.ts
new file mode 100644
index 0000000000..089f8948c2
--- /dev/null
+++ b/packages/engine-render/src/floating/util.ts
@@ -0,0 +1,187 @@
+/**
+ * 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 { getOverflowAncestors } from '@floating-ui/dom';
+import { floor, max, min } from '@floating-ui/utils';
+import { getDocumentElement } from '@floating-ui/utils/dom';
+import { Observable } from 'rxjs';
+
+export function observeClientRect(containerElement: HTMLElement): Observable<void> {
+ return new Observable<void>((observer) => {
+ const disposable = autoClientRect(containerElement, () => observer.next());
+ return () => disposable();
+ });
+}
+
+/// The following methods are copied from floating-ui's `autoUpdate` function. Though it does not have the floating
+/// element but only reports that client rect of the reference element changes.
+
+// https://samthor.au/2021/observing-dom/
+function observeMove(element: Element, onMove: () => void) {
+ let io: IntersectionObserver | null = null;
+ let timeoutId: NodeJS.Timeout;
+
+ const root = getDocumentElement(element);
+
+ function cleanup() {
+ clearTimeout(timeoutId);
+ io?.disconnect();
+ io = null;
+ }
+
+ function refresh(skip = false, threshold = 1) {
+ cleanup();
+
+ const { left, top, width, height } = element.getBoundingClientRect();
+
+ if (!skip) {
+ onMove();
+ }
+
+ if (!width || !height) {
+ return;
+ }
+
+ const insetTop = floor(top);
+ const insetRight = floor(root.clientWidth - (left + width));
+ const insetBottom = floor(root.clientHeight - (top + height));
+ const insetLeft = floor(left);
+ const rootMargin = `${-insetTop}px ${-insetRight}px ${-insetBottom}px ${-insetLeft}px`;
+
+ const options = {
+ rootMargin,
+ threshold: max(0, min(1, threshold)) || 1,
+ };
+
+ let isFirstUpdate = true;
+
+ function handleObserve(entries: IntersectionObserverEntry[]) {
+ const ratio = entries[0].intersectionRatio;
+
+ if (ratio !== threshold) {
+ if (!isFirstUpdate) {
+ return refresh();
+ }
+
+ if (!ratio) {
+ // If the reference is clipped, the ratio is 0. Throttle the refresh
+ // to prevent an infinite loop of updates.
+ timeoutId = setTimeout(() => {
+ refresh(false, 1e-7);
+ }, 1000);
+ } else {
+ refresh(false, ratio);
+ }
+ }
+
+ isFirstUpdate = false;
+ }
+
+ // Older browsers don't support a `document` as the root and will throw an
+ // error.
+ try {
+ io = new IntersectionObserver(handleObserve, {
+ ...options,
+ // Handle <iframe>s
+ root: root.ownerDocument,
+ });
+ } catch (e) {
+ io = new IntersectionObserver(handleObserve, options);
+ }
+
+ io.observe(element);
+ }
+
+ refresh(true);
+
+ return cleanup;
+}
+
+// This implementation is very simple compared to the original implementation in floating-ui.
+// Maybe some bugs.
+function getBoundingClientRect(reference: Element) {
+ return reference.getBoundingClientRect();
+}
+
+function autoClientRect(
+ reference: Element,
+ update: () => void
+) {
+ const ancestorScroll = true;
+ const ancestorResize = true;
+ const layoutShift = true;
+ const animationFrame = false;
+
+ const referenceEl = reference;
+
+ const ancestors =
+ ancestorScroll || ancestorResize
+ ? [
+ ...(referenceEl ? getOverflowAncestors(referenceEl) : []),
+ ]
+ : [];
+
+ ancestors.forEach((ancestor) => {
+ ancestorScroll &&
+ ancestor.addEventListener('scroll', update, { passive: true });
+ ancestorResize && ancestor.addEventListener('resize', update);
+ });
+
+ const cleanupIo =
+ referenceEl && layoutShift ? observeMove(referenceEl, update) : null;
+
+ let resizeObserver: ResizeObserver | null = null;
+
+ let frameId: number;
+ let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
+
+ if (animationFrame) {
+ frameLoop();
+ }
+
+ function frameLoop() {
+ const nextRefRect = getBoundingClientRect(reference);
+
+ if (prevRefRect &&
+ (nextRefRect.x !== prevRefRect.x ||
+ nextRefRect.y !== prevRefRect.y ||
+ nextRefRect.width !== prevRefRect.width ||
+ nextRefRect.height !== prevRefRect.height)
+ ) {
+ update();
+ }
+
+ prevRefRect = nextRefRect;
+ frameId = requestAnimationFrame(frameLoop);
+ }
+
+ update();
+
+ return () => {
+ ancestors.forEach((ancestor) => {
+ ancestorScroll && ancestor.removeEventListener('scroll', update);
+ ancestorResize && ancestor.removeEventListener('resize', update);
+ });
+
+ cleanupIo?.();
+ resizeObserver?.disconnect();
+ resizeObserver = null;
+
+ if (animationFrame) {
+ cancelAnimationFrame(frameId);
+ }
+ };
+}
diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
index 2f08d0c59b..9545243dd3 100644
--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
@@ -225,6 +225,7 @@ export class SheetCanvasPopManagerService extends Disposable {
const updatePosition = () => position$.next(this._calcCellPositionByCell(row, col, currentRender, skeleton, activeViewport));
const disposable = new DisposableCollection();
+ disposable.add(currentRender.engine.clientRect$.subscribe(() => updatePosition()));
disposable.add(this._commandService.onCommandExecuted((commandInfo) => {
if (commandInfo.id === SetWorksheetRowAutoHeightMutation.id) {
const params = commandInfo.params as ISetWorksheetRowAutoHeightMutationParams;
@@ -265,7 +266,7 @@ export class SheetCanvasPopManagerService extends Disposable {
skeleton: SpreadsheetSkeleton,
activeViewport: Viewport
): IBoundRectNoAngle {
- const { scene } = currentRender;
+ const { scene, engine } = currentRender;
const primaryWithCoord = skeleton.getCellByIndex(row, col);
const cellInfo = primaryWithCoord.isMergedMainCell ? primaryWithCoord.mergeInfo : primaryWithCoord;
@@ -276,11 +277,14 @@ export class SheetCanvasPopManagerService extends Disposable {
y: activeViewport.viewportScrollY,
};
+ const canvasClientRect = engine.getCanvasElement().getBoundingClientRect();
+ const { top, left } = canvasClientRect;
+
return {
- left: ((cellInfo.startX - scrollXY.x) * scaleX),
- right: (cellInfo.endX - scrollXY.x) * scaleX,
- top: ((cellInfo.startY - scrollXY.y) * scaleY),
- bottom: ((cellInfo.endY - scrollXY.y) * scaleY),
+ left: ((cellInfo.startX - scrollXY.x) * scaleX) + left,
+ right: (cellInfo.endX - scrollXY.x) * scaleX + left,
+ top: ((cellInfo.startY - scrollXY.y) * scaleY) + top,
+ bottom: ((cellInfo.endY - scrollXY.y) * scaleY) + top,
};
}
diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
index 6d631f9f28..246687f3eb 100644
--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
@@ -87,7 +87,7 @@ export class DesktopUIController extends Disposable {
}
private _initBuiltinComponents() {
- this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(CanvasPopup, this._injector)));
+ this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.FLOATING, () => connectInjector(CanvasPopup, this._injector)));
this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(FloatDom, this._injector)));
}
}
diff --git a/packages/ui/src/services/parts/parts.service.ts b/packages/ui/src/services/parts/parts.service.ts
index 53875d311f..e1d1f2473a 100644
--- a/packages/ui/src/services/parts/parts.service.ts
+++ b/packages/ui/src/services/parts/parts.service.ts
@@ -31,6 +31,7 @@ export enum BuiltInUIPart {
CONTENT = 'content',
FOOTER = 'footer',
LEFT_SIDEBAR = 'left-sidebar',
+ FLOATING = 'floating',
}
export interface IUIPartsService {
diff --git a/packages/ui/src/views/DesktopApp.tsx b/packages/ui/src/views/DesktopApp.tsx
index b73701568d..124b158b2a 100644
--- a/packages/ui/src/views/DesktopApp.tsx
+++ b/packages/ui/src/views/DesktopApp.tsx
@@ -16,9 +16,11 @@
import { LocaleService, ThemeService } from '@univerjs/core';
import type { ILocale } from '@univerjs/design';
-import { ConfigProvider, defaultTheme, themeInstance } from '@univerjs/design';
+import { ConfigContext, ConfigProvider, defaultTheme, themeInstance } from '@univerjs/design';
import { useDependency } from '@wendellhu/redi/react-bindings';
-import React, { useEffect, useMemo, useRef, useState } from 'react';
+import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+
import type { IWorkbenchOptions } from '../controllers/ui/ui.controller';
import { IMessageService } from '../services/message/message.service';
import { BuiltInUIPart } from '../services/parts/parts.service';
@@ -154,6 +156,14 @@ export function DesktopApp(props: IUniverAppProps) {
<ComponentContainer key="global" components={globalComponents} />
<ComponentContainer key="built-in-global" components={builtInGlobalComponents} />
{contextMenu && <DesktopContextMenu />}
+ <FloatingContainer />
</ConfigProvider>
);
}
+
+function FloatingContainer() {
+ const { mountContainer } = useContext(ConfigContext);
+ const floatingComponents = useComponentsOfPart(BuiltInUIPart.FLOATING);
+
+ return createPortal(<ComponentContainer key="floating" components={floatingComponents} />, mountContainer!);
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 40e47650fa..07bc61640a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1057,6 +1057,12 @@ importers:
packages/engine-render:
dependencies:
+ '@floating-ui/dom':
+ specifier: ^1.6.7
+ version: 1.6.7
+ '@floating-ui/utils':
+ specifier: ^0.2.4
+ version: 0.2.4
cjk-regex:
specifier: ^3.1.0
version: 3.1.0
@@ -4004,6 +4010,15 @@ packages:
'@fal-works/[email protected]':
resolution: {integrity: sha512-cEee/Z+I12mZcFJshKcCqC8tuX5hG3s+d+9nZ3LabqKF1vKdF41B92pJVCBggjAGORAeOzyyDDKrZwIkLffeOQ==}
+ '@floating-ui/[email protected]':
+ resolution: {integrity: sha512-a4IowK4QkXl4SCWTGUR0INAfEOX3wtsYw3rKK5InQEHMGObkR8Xk44qYQD9P4r6HHw0iIfK6GUKECmY8sTkqRA==}
+
+ '@floating-ui/[email protected]':
+ resolution: {integrity: sha512-wmVfPG5o2xnKDU4jx/m4w5qva9FWHcnZ8BvzEe90D/RpwsJaTAVYPEPdQ8sbr/N8zZTAHlZUTQdqg8ZUbzHmng==}
+
+ '@floating-ui/[email protected]':
+ resolution: {integrity: sha512-dWO2pw8hhi+WrXq1YJy2yCuWoL20PddgGaqTgVe4cOS9Q6qklXCiA1tJEqX6BEwRNSCP84/afac9hd4MS+zEUA==}
+
resolution: {integrity: sha512-5tcgUctCG0qoNyfChZifz2tJqbRbXVO9J7X6duFcOjY3HUNCxg5D0ZCK7EP9vIcZ0zRpLU9bWkyCqVCLZ46IbQ==}
engines: {node: '>=12.10.0'}
@@ -12321,6 +12336,17 @@ snapshots:
'@fal-works/[email protected]': {}
+ '@floating-ui/[email protected]':
+ dependencies:
+ '@floating-ui/utils': 0.2.4
+
+ '@floating-ui/[email protected]':
+ dependencies:
+ '@floating-ui/core': 1.6.4
+ '@floating-ui/utils': 0.2.4
+
+ '@floating-ui/[email protected]': {}
+
dependencies:
'@grpc/proto-loader': 0.7.13