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(ui): popup enhance direction (#2281)
Wenzhao Hue9c27b70c660
diff --git a/packages/design/src/components/popup/RectPopup.tsx b/packages/design/src/components/popup/RectPopup.tsxindex 032552c7f0..aec11b8485 100644--- a/packages/design/src/components/popup/RectPopup.tsx+++ b/packages/design/src/components/popup/RectPopup.tsx@@ -35,46 +35,58 @@ export interface IRectPopupProps {*/anchorRect: IAbsolutePosition;- direction?: 'horizontal' | 'vertical';+ direction?: 'vertical' | 'horizontal' | 'left' | 'top' | 'left' | 'bottom';++ // #region closing behaviorcloseOnSelfTarget?: boolean;onClickOutside?: (e: MouseEvent) => void;-excludeOutside?: HTMLElement[];++ // #endregion}-export interface IPopupLayoutInfo {+export interface IPopupLayoutInfo extends Pick<IRectPopupProps, 'direction'> {position: IAbsolutePosition;width: number;height: number;containerWidth: number;containerHeight: number;- direction?: 'horizontal' | 'vertical';}-const calcPopupPosition = (layout: IPopupLayoutInfo) => {- const { position, width, height, containerHeight, containerWidth, direction = 'vertical' } = layout;- if (direction === 'vertical') {- const { left: startX, top: startY, right: endX, bottom: endY } = position;+/** The popup should have a minimum edge to the boundary. */+const PUSHING_MINIMUM_GAP = 4;- const verticalStyle = (endY + height) > containerHeight ? { top: startY - height } : { top: endY };- const horizontalStyle = (startX + width) > containerWidth ? { left: endX - width } : { left: startX };+function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: number } {+ const { position, width, height, containerHeight, containerWidth, direction = 'vertical' } = layout;- return {- ...verticalStyle,- ...horizontalStyle,- };- } else {+ // In y-axis+ if (direction === 'vertical' || direction === 'top' || direction === 'bottom') {const { left: startX, top: startY, right: endX, bottom: endY } = position;+ const verticalStyle = ((endY + height) > containerHeight || direction === 'top')+ ? { top: startY - height }+ : { top: endY };- const verticalStyle = ((startY + height) > containerHeight) ? { top: endY - height } : { top: startY };- const horizontalStyle = ((endX + width) > containerWidth) ? { left: startX - width } : { left: endX };+ // If the popup element exceed the visible area. We should "push" it back.+ const horizontalStyle = (startX + width) > containerWidth+ ? { left: Math.max(endX - width, PUSHING_MINIMUM_GAP) } // on left+ : { left: Math.min(startX, containerWidth - width - PUSHING_MINIMUM_GAP) }; // on right- return {- ...verticalStyle,- ...horizontalStyle,- };+ return { ...verticalStyle, ...horizontalStyle };}++ // In x-axis+ const { left: startX, top: startY, right: endX, bottom: endY } = position;+ const horizontalStyle = ((endX + width) > containerWidth || direction === 'left')+ ? { left: startX - width }+ : { left: endX };++ // If the popup element exceed the visible area. We should "push" it back.+ const verticalStyle = ((startY + height) > containerHeight)+ ? { top: Math.max(endY - height, PUSHING_MINIMUM_GAP) } // on top+ : { top: Math.min(startX, containerHeight - height - PUSHING_MINIMUM_GAP) }; // on bottom++ return { ...verticalStyle, ...horizontalStyle };};function RectPopup(props: IRectPopupProps) {@@ -87,21 +99,19 @@ function RectPopup(props: IRectPopupProps) {left: -9999,});+ // TODO@weird94: push the content into the visible area.+useEffect(() => {const { clientWidth, clientHeight } = nodeRef.current!;const { innerWidth, innerHeight } = window;- setPosition(- calcPopupPosition(- {- position: anchorRect,- width: clientWidth,- height: clientHeight,- containerWidth: innerWidth,- containerHeight: innerHeight,- direction,- }- )- );+ setPosition(calcPopupPosition({+ position: anchorRect,+ width: clientWidth,+ height: clientHeight,+ containerWidth: innerWidth,+ containerHeight: innerHeight,+ direction,+ }));},// eslint-disable-next-line react-hooks/exhaustive-deps[diff --git a/packages/sheets-filter-ui/src/controllers/sheets-filter-ui.controller.ts b/packages/sheets-filter-ui/src/controllers/sheets-filter-ui.controller.tsindex 4021ab69e4..35c5066548 100644--- a/packages/sheets-filter-ui/src/controllers/sheets-filter-ui.controller.ts+++ b/packages/sheets-filter-ui/src/controllers/sheets-filter-ui.controller.ts@@ -132,6 +132,7 @@ export class SheetsFilterUIController extends RxDisposable {direction: 'horizontal',closeOnSelfTarget: true,onClickOutside: () => this._commandService.syncExecuteCommand(CloseFilterPanelOperation.id),+ offset: [5, 0],});}diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.tsindex b4e698e956..ef5e67e1d3 100644--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts@@ -18,6 +18,7 @@ import type { IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';import { Disposable, DisposableCollection, ICommandService, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import type { BaseObject, IBoundRectNoAngle, IRender, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';+import type { IPopup } from '@univerjs/ui';import { ICanvasPopupService } from '@univerjs/ui';import type { IDisposable } from '@wendellhu/redi';import { Inject } from '@wendellhu/redi';@@ -29,15 +30,10 @@ import { SetScrollOperation } from '../commands/operations/scroll.operation';import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';-export interface ICanvasPopup {- componentKey: string;+export interface ICanvasPopup extends Pick<IPopup,+ 'direction' | 'excludeOutside' | 'closeOnSelfTarget' | 'componentKey' | 'offset' | 'onClickOutside'+> {mask?: boolean;- onClickOutside?: (e: MouseEvent) => void;- direction?: 'vertical' | 'horizontal';- offset?: [number, number];- excludeOutside?: HTMLElement[];- /** Close the popup even if the outside element clicked is its target. */- closeOnSelfTarget?: boolean;extraProps?: Record<string, any>;}@@ -53,84 +49,7 @@ export class SheetCanvasPopManagerService extends Disposable {super();}- private _calcCellPosition(- row: number,- col: number,- currentRender: IRender,- skeleton: SpreadsheetSkeleton,- activeViewport: Viewport- ) {- const { scene, engine } = currentRender;-- const primaryWithCoord = skeleton.getCellByIndex(row, col);- const cellInfo = primaryWithCoord.isMergedMainCell ? primaryWithCoord.mergeInfo : primaryWithCoord;-- const { scaleX, scaleY } = scene.getAncestorScale();-- const scrollXY = {- x: activeViewport.actualScrollX,- y: activeViewport.actualScrollY,- };-- const bounding = engine.getCanvasElement().getBoundingClientRect();-- const position: IBoundRectNoAngle = {- left: ((cellInfo.startX - scrollXY.x) * scaleX) + bounding.left,- right: (cellInfo.endX - scrollXY.x) * scaleX + bounding.left,- top: ((cellInfo.startY - scrollXY.y) * scaleY) + bounding.top,- bottom: ((cellInfo.endY - scrollXY.y) * scaleY) + bounding.top,- };-- return position;- }-- private _createCellPositionObserver(- initialRow: number,- initialCol: number,- currentRender: IRender,- skeleton: SpreadsheetSkeleton,- activeViewport: Viewport- ) {- let row = initialRow;- let col = initialCol;-- const position = this._calcCellPosition(row, col, currentRender, skeleton, activeViewport);- const position$ = new BehaviorSubject(position);- const updatePosition = () => position$.next(this._calcCellPosition(row, col, currentRender, skeleton, activeViewport));-- const disposable = new DisposableCollection();- disposable.add(this._commandService.onCommandExecuted((commandInfo) => {- if (commandInfo.id === SetWorksheetRowAutoHeightMutation.id) {- const params = commandInfo.params as ISetWorksheetRowAutoHeightMutationParams;- if (params.rowsAutoHeightInfo.findIndex((item) => item.row === row) > -1) {- updatePosition();- return;- }- }-- if (- COMMAND_LISTENER_SKELETON_CHANGE.indexOf(commandInfo.id) > -1 ||- commandInfo.id === SetScrollOperation.id ||- commandInfo.id === SetZoomRatioOperation.id- ) {- updatePosition();- }- }));-- const updateRowCol = (newRow: number, newCol: number) => {- row = newRow;- col = newCol;-- updatePosition();- };-- return {- position$,- disposable,- position,- updateRowCol,- };- }+ // #region attach to objectprivate _createObjectPositionObserver(targetObject: BaseObject,@@ -221,6 +140,10 @@ export class SheetCanvasPopManagerService extends Disposable {};}+ // #endregion++ // #region attach to cell+/*** attach a popup to given cell* @param row cell row index@@ -249,7 +172,7 @@ export class SheetCanvasPopManagerService extends Disposable {return null;}- const { position, position$, disposable, updateRowCol } = this._createCellPositionObserver(row, col, currentRender, skeleton, activeViewport);+ const { position, position$, disposable: positionObserverDisposable, updateRowCol } = this._createCellPositionObserver(row, col, currentRender, skeleton, activeViewport);const id = this._globalPopupManagerService.addPopup({...popup,unitId,@@ -259,12 +182,13 @@ export class SheetCanvasPopManagerService extends Disposable {});const disposableCollection = new DisposableCollection();- disposableCollection.add(disposable);+ disposableCollection.add(positionObserverDisposable);disposableCollection.add(toDisposable(() => {this._globalPopupManagerService.removePopup(id);position$.complete();}));+ // If the range changes, the popup should change with it. And if the range vanished, the popup should be removed.const watchedRange: IRange = { startRow: row, endRow: row, startColumn: col, endColumn: col };disposableCollection.add(this._refRangeService.watchRange(unitId, subUnitId, watchedRange, (_, after) => {if (!after) {@@ -276,4 +200,81 @@ export class SheetCanvasPopManagerService extends Disposable {return disposableCollection;}++ private _createCellPositionObserver(+ initialRow: number,+ initialCol: number,+ currentRender: IRender,+ skeleton: SpreadsheetSkeleton,+ activeViewport: Viewport+ ) {+ let row = initialRow;+ let col = initialCol;++ const position = this._calcCellPositionByCell(row, col, currentRender, skeleton, activeViewport);+ const position$ = new BehaviorSubject(position);+ const updatePosition = () => position$.next(this._calcCellPositionByCell(row, col, currentRender, skeleton, activeViewport));++ const disposable = new DisposableCollection();+ disposable.add(this._commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetWorksheetRowAutoHeightMutation.id) {+ const params = commandInfo.params as ISetWorksheetRowAutoHeightMutationParams;+ if (params.rowsAutoHeightInfo.findIndex((item) => item.row === row) > -1) {+ updatePosition();+ return;+ }+ }++ if (+ COMMAND_LISTENER_SKELETON_CHANGE.indexOf(commandInfo.id) > -1 ||+ commandInfo.id === SetScrollOperation.id ||+ commandInfo.id === SetZoomRatioOperation.id+ ) {+ updatePosition();+ }+ }));++ const updateRowCol = (newRow: number, newCol: number) => {+ row = newRow;+ col = newCol;++ updatePosition();+ };++ return {+ position$,+ disposable,+ position,+ updateRowCol,+ };+ }++ private _calcCellPositionByCell(+ row: number,+ col: number,+ currentRender: IRender,+ skeleton: SpreadsheetSkeleton,+ activeViewport: Viewport+ ): IBoundRectNoAngle {+ const { scene, engine } = currentRender;++ const primaryWithCoord = skeleton.getCellByIndex(row, col);+ const cellInfo = primaryWithCoord.isMergedMainCell ? primaryWithCoord.mergeInfo : primaryWithCoord;++ const { scaleX, scaleY } = scene.getAncestorScale();+ const scrollXY = {+ x: activeViewport.actualScrollX,+ y: activeViewport.actualScrollY,+ };++ const bounding = engine.getCanvasElement().getBoundingClientRect();+ return {+ left: ((cellInfo.startX - scrollXY.x) * scaleX) + bounding.left,+ right: (cellInfo.endX - scrollXY.x) * scaleX + bounding.left,+ top: ((cellInfo.startY - scrollXY.y) * scaleY) + bounding.top,+ bottom: ((cellInfo.endY - scrollXY.y) * scaleY) + bounding.top,+ };+ }++ // #endregion}diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 6b523240fb..1a56fd9afc 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -85,6 +85,6 @@ export { SetEditorResizeOperation } from './commands/operations/editor/set-editoexport { RangeSelector } from './components/range-selector/RangeSelector';export { IRangeSelectorService } from './services/range-selector/range-selector.service';export { DesktopLocalStorageService } from './services/local-storage/local-storage.service';-export { CanvasPopupService, ICanvasPopupService } from './services/popup/canvas-popup.service';+export { CanvasPopupService, ICanvasPopupService, type IPopup } from './services/popup/canvas-popup.service';export { ProgressBar } from './components/progress-bar/ProgressBar';export { IProgressService } from './services/progress/progress.service';diff --git a/packages/ui/src/services/popup/canvas-popup.service.ts b/packages/ui/src/services/popup/canvas-popup.service.tsindex 22362c5ab0..18fe197e5f 100644--- a/packages/ui/src/services/popup/canvas-popup.service.ts+++ b/packages/ui/src/services/popup/canvas-popup.service.ts@@ -14,22 +14,21 @@* limitations under the License.*/-import { Tools } from '@univerjs/core';+import { Disposable, Tools } from '@univerjs/core';+import type { IRectPopupProps } from '@univerjs/design';import type { IBoundRectNoAngle } from '@univerjs/engine-render';import { createIdentifier } from '@wendellhu/redi';import type { Observable } from 'rxjs';import { BehaviorSubject } from 'rxjs';-export interface IPopup {+export interface IPopup extends Pick<IRectPopupProps, 'closeOnSelfTarget' | 'direction' | 'excludeOutside' | 'onClickOutside' > {anchorRect: IBoundRectNoAngle;anchorRect$: Observable<IBoundRectNoAngle>;componentKey: string;- onClickOutside?: (e: MouseEvent) => void;- closeOnSelfTarget?: boolean;- excludeOutside?: HTMLElement[];+unitId: string;subUnitId: string;- direction?: 'vertical' | 'horizontal';+offset?: [number, number];}@@ -42,37 +41,41 @@ export interface ICanvasPopupService {get popups(): [string, IPopup][];}-export const ICanvasPopupService = createIdentifier<ICanvasPopupService>('univer.popup.service');+export const ICanvasPopupService = createIdentifier<ICanvasPopupService>('ui.popup.service');-export class CanvasPopupService implements ICanvasPopupService {- private _popupMap = new Map<string, IPopup>();- private _popups$ = new BehaviorSubject<[string, IPopup][]>([]);+export class CanvasPopupService extends Disposable implements ICanvasPopupService {+ private readonly _popupMap = new Map<string, IPopup>();+ private readonly _popups$ = new BehaviorSubject<[string, IPopup][]>([]);+ readonly popups$ = this._popups$.asObservable();+ get popups() { return Array.from(this._popupMap.entries()); }- popups$ = this._popups$.asObservable();-- get popups() {- return Array.from(this._popupMap.entries());+ private _update() {+ this._popups$.next(Array.from(this._popupMap.entries()));}- private _notice() {- this._popups$.next(Array.from(this._popupMap.entries()));+ override dispose(): void {+ super.dispose();++ this._popups$.next([]);+ this._popups$.complete();+ this._popupMap.clear();}addPopup(item: IPopup): string {const id = Tools.generateRandomId();this._popupMap.set(id, item);- this._notice();+ this._update();return id;}removePopup(id: string): void {if (this._popupMap.delete(id)) {- this._notice();+ this._update();}}removeAll(): void {this._popupMap.clear();- this._notice();+ this._update();}}diff --git a/packages/ui/src/views/components/popup/CanvasPopup.tsx b/packages/ui/src/views/components/popup/CanvasPopup.tsxindex 722173d561..dbbf89c876 100644--- a/packages/ui/src/views/components/popup/CanvasPopup.tsx+++ b/packages/ui/src/views/components/popup/CanvasPopup.tsx@@ -25,19 +25,23 @@ import type { IPopup } from '../../../services/popup/canvas-popup.service';const SingleCanvasPopup = ({ popup, children }: { popup: IPopup; children?: React.ReactNode }) => {const anchorRect = useObservable(popup.anchorRect$, popup.anchorRect);- const rect: IBoundRectNoAngle = useMemo(() => {- const [x = 0, y = 0] = popup.offset ?? [];+ const { bottom, left, right, top } = anchorRect;+ const { offset } = popup;++ // We add an offset to the anchor rect to make the popup offset with the anchor.+ const rectWithOffset: IBoundRectNoAngle = useMemo(() => {+ const [x = 0, y = 0] = offset ?? [];return {- left: anchorRect.left - x,- right: anchorRect.right + x,- top: anchorRect.top - y,- bottom: anchorRect.bottom + y,+ left: left - x,+ right: right + x,+ top: top - y,+ bottom: bottom + y,};- }, [anchorRect.bottom, anchorRect.left, anchorRect.right, anchorRect.top, popup.offset]);+ }, [bottom, left, right, top, offset]);return (<RectPopup- anchorRect={rect}+ anchorRect={rectWithOffset}direction={popup.direction}onClickOutside={popup.onClickOutside}excludeOutside={popup.excludeOutside}