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): improve adaptive toolbar popups (#7422)
Univer83e48d927330
diff --git a/packages/design/src/components/select/Select.tsx b/packages/design/src/components/select/Select.tsxindex 56fbfa92f2..5388d06f43 100644--- a/packages/design/src/components/select/Select.tsx+++ b/packages/design/src/components/select/Select.tsx@@ -59,6 +59,12 @@ export interface ISelectProps {*/borderless?: boolean;+ /** Preferred side for the options popup. */+ side?: IDropdownMenuProps['side'];++ /** Whether the options popup may flip to avoid viewport collisions. */+ avoidCollisions?: IDropdownMenuProps['avoidCollisions'];+/*** The callback function that is triggered when the value is changed*/@@ -78,6 +84,8 @@ export function Select(props: ISelectProps) {disabled = false,options = [],borderless = false,+ side,+ avoidCollisions,onChange,} = props;@@ -151,6 +159,8 @@ export function Select(props: ISelectProps) {open={open}items={items}disabled={disabled}+ side={side}+ avoidCollisions={avoidCollisions}onOpenChange={handleOpenChange}><divdiff --git a/packages/ui/src/views/components/popup/RectPopup.tsx b/packages/ui/src/views/components/popup/RectPopup.tsxindex 3d83f9e1cd..b6b680b145 100644--- a/packages/ui/src/views/components/popup/RectPopup.tsx+++ b/packages/ui/src/views/components/popup/RectPopup.tsx@@ -14,15 +14,13 @@* limitations under the License.*/-import type { Nullable } from '@univerjs/core';-import type { ReactNode, RefObject } from 'react';+import type { MouseEventHandler, ReactNode, RefObject } from 'react';import type { Observable } from 'rxjs';-import type { IUniverUIConfig } from '../../../config/config';import { IConfigService, LocaleService } from '@univerjs/core';import { clsx } from '@univerjs/design';-import { createContext, useContext, useEffect, useRef } from 'react';+import { createContext, useContext, useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';-import { UI_PLUGIN_CONFIG_KEY } from '../../../config/config';+import { defaultPluginConfig, UI_PLUGIN_CONFIG_KEY } from '../../../config/config';import { useDependency, useObservable } from '../../../utils/di';import { useEvent } from '../../hooks/event';@@ -34,6 +32,7 @@ interface IAbsolutePosition {}const RectPopupContext = createContext<RefObject<IAbsolutePosition | undefined>>({ current: undefined });+const RectPopupDirectionContext = createContext<RectPopupDirection>('vertical');export type RectPopupDirection =| 'left'@@ -68,7 +67,7 @@ export interface IRectPopupProps {* the anchor element bounding rect*/anchorRect$: Observable<IAbsolutePosition>;- excludeRects?: RefObject<Nullable<IAbsolutePosition[]>>;+ excludeRects?: RefObject<IAbsolutePosition[] | null | undefined | void>;direction?: RectPopupDirection;hidden?: boolean;// #region closing behavior@@ -76,9 +75,9 @@ export interface IRectPopupProps {excludeOutside?: HTMLElement[];onContextMenu?: () => void;- onPointerEnter?: (e: React.MouseEvent<HTMLElement>) => void;- onPointerLeave?: (e: React.MouseEvent<HTMLElement>) => void;- onClick?: (e: React.MouseEvent<HTMLElement>) => void;+ onPointerEnter?: MouseEventHandler<HTMLElement>;+ onPointerLeave?: MouseEventHandler<HTMLElement>;+ onClick?: MouseEventHandler<HTMLElement>;// #endregionportal?: boolean;@@ -103,8 +102,27 @@ export interface IPopupLayoutInfo extends Pick<IRectPopupProps, 'direction'> {/** The popup should have a minimum edge to the boundary. */const PUSHING_MINIMUM_GAP = 8;+function resolvePopupDirection(layout: IPopupLayoutInfo): RectPopupDirection {+ const direction = layout.direction ?? 'vertical';+ const availableTop = layout.position.top;+ const availableBottom = layout.containerHeight - layout.position.bottom;+ const placeAbove = availableTop >= availableBottom;++ switch (direction) {+ case 'vertical-center':+ return placeAbove ? 'top-center' : 'bottom-center';+ case 'vertical-left':+ return placeAbove ? 'top-left' : 'bottom-left';+ case 'vertical-right':+ return placeAbove ? 'top-right' : 'bottom-right';+ default:+ return direction;+ }+}+function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: number } {- const { position, width, height, containerHeight, containerWidth, direction = 'vertical', noPushMinimumGap = false } = layout;+ const { position, width, height, containerHeight, containerWidth, noPushMinimumGap = false } = layout;+ const direction = resolvePopupDirection(layout);const minTop = noPushMinimumGap ? -Infinity : PUSHING_MINIMUM_GAP;const maxTop = noPushMinimumGap ? Infinity : containerHeight - height - PUSHING_MINIMUM_GAP;@@ -212,7 +230,8 @@ function RectPopup(props: IRectPopupProps) {const excludeRectsRef = excludeRects;const configService = useDependency(IConfigService);const anchorRectRef = useRef<IAbsolutePosition | undefined>(undefined);- const uiConfig = configService.getConfig(UI_PLUGIN_CONFIG_KEY) as IUniverUIConfig;+ const [resolvedDirection, setResolvedDirection] = useState<RectPopupDirection>(direction);+ const uiConfig = configService.getConfig<typeof defaultPluginConfig>(UI_PLUGIN_CONFIG_KEY) ?? defaultPluginConfig;const popupRootId = uiConfig?.popupRootId ?? 'univer-popup-portal';const updatePosition = useEvent((position: IAbsolutePosition) => {@@ -223,17 +242,19 @@ function RectPopup(props: IRectPopupProps) {const innerWidth = window.innerWidth;const innerHeight = window.innerHeight;- positionRef.current = calcPopupPosition(- {- position,- width: clientWidth,- height: clientHeight,- containerWidth: innerWidth,- containerHeight: innerHeight,- direction,- noPushMinimumGap,- }- );+ const layout = {+ position,+ width: clientWidth,+ height: clientHeight,+ containerWidth: innerWidth,+ containerHeight: innerHeight,+ direction,+ noPushMinimumGap,+ };+ const nextDirection = resolvePopupDirection(layout);++ setResolvedDirection((currentDirection) => currentDirection === nextDirection ? currentDirection : nextDirection);+ positionRef.current = calcPopupPosition({ ...layout, direction: nextDirection });nodeRef.current.style.top = `${positionRef.current.top}px`;nodeRef.current.style.left = `${positionRef.current.left}px`;@@ -340,9 +361,11 @@ function RectPopup(props: IRectPopupProps) {onPointerEnter={onPointerEnter}onPointerLeave={onPointerLeave}>- <RectPopupContext.Provider value={anchorRectRef}>- {children}- </RectPopupContext.Provider>+ <RectPopupDirectionContext.Provider value={resolvedDirection}>+ <RectPopupContext.Provider value={anchorRectRef}>+ {children}+ </RectPopupContext.Provider>+ </RectPopupDirectionContext.Provider></section></>);@@ -353,5 +376,6 @@ function RectPopup(props: IRectPopupProps) {RectPopup.calcPopupPosition = calcPopupPosition;RectPopup.useContext = () => useContext(RectPopupContext);+RectPopup.useDirection = () => useContext(RectPopupDirectionContext);export { RectPopup };diff --git a/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.ts b/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.tsnew file mode 100644index 0000000000..9e1bed1fd3--- /dev/null+++ b/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.ts@@ -0,0 +1,80 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { describe, expect, it } from 'vitest';+import { RectPopup } from '../RectPopup';++describe('RectPopup adaptive vertical placement', () => {+ it('uses the bottom side when the anchor has more space below', () => {+ expect(RectPopup.calcPopupPosition({+ position: { left: 100, right: 300, top: 100, bottom: 200 },+ width: 100,+ height: 40,+ containerWidth: 1000,+ containerHeight: 1000,+ direction: 'vertical-center',+ })).toEqual({ left: 150, top: 200 });+ });++ it('uses the top side when the anchor has more space above', () => {+ expect(RectPopup.calcPopupPosition({+ position: { left: 100, right: 300, top: 700, bottom: 800 },+ width: 100,+ height: 40,+ containerWidth: 1000,+ containerHeight: 1000,+ direction: 'vertical-center',+ })).toEqual({ left: 150, top: 660 });+ });++ it('preserves left alignment when choosing the vertical side', () => {+ expect(RectPopup.calcPopupPosition({+ position: { left: 100, right: 300, top: 100, bottom: 200 },+ width: 100,+ height: 40,+ containerWidth: 1000,+ containerHeight: 1000,+ direction: 'vertical-left',+ })).toEqual({ left: 100, top: 200 });+ expect(RectPopup.calcPopupPosition({+ position: { left: 100, right: 300, top: 700, bottom: 800 },+ width: 100,+ height: 40,+ containerWidth: 1000,+ containerHeight: 1000,+ direction: 'vertical-left',+ })).toEqual({ left: 100, top: 660 });+ });++ it('preserves right alignment when choosing the vertical side', () => {+ expect(RectPopup.calcPopupPosition({+ position: { left: 100, right: 300, top: 100, bottom: 200 },+ width: 100,+ height: 40,+ containerWidth: 1000,+ containerHeight: 1000,+ direction: 'vertical-right',+ })).toEqual({ left: 200, top: 200 });+ expect(RectPopup.calcPopupPosition({+ position: { left: 100, right: 300, top: 700, bottom: 800 },+ width: 100,+ height: 40,+ containerWidth: 1000,+ containerHeight: 1000,+ direction: 'vertical-right',+ })).toEqual({ left: 200, top: 660 });+ });+});diff --git a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx b/packages/ui/src/views/components/ribbon/ToolbarItem.tsxindex d74a4f0c9f..1748caa228 100644--- a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx+++ b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx@@ -395,10 +395,20 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((prconst buttonStyle = grid && large ? { textAlign: 'center', whiteSpace: 'normal' } as const : undefined;if (isCustomComponent) {+ const hoverable = typeof label === 'string' || label?.hoverable !== false;+return (<spandata-u-command={id}- className={toolbarButtonVariants({ noIcon: !icon, active: activated, className: buttonClassName })}+ className={toolbarButtonVariants({+ noIcon: !icon,+ active: activated,+ className: clsx(buttonClassName, !hoverable && `+ univer-cursor-default !univer-bg-transparent+ hover:!univer-bg-transparent+ dark:hover:!univer-bg-transparent+ `),+ })}style={buttonStyle}aria-disabled={disabled}>diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsxindex ea2630982f..cf4c42729f 100644--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx@@ -17,7 +17,12 @@import type { IDropdownMenuProps, IDropdownProps, ITooltipProps } from '@univerjs/design';import type { ReactNode } from 'react';import type { IMenuItem, IValueOption } from '../../../services/menu/menu';-import { clsx, Dropdown, DropdownMenu, Tooltip } from '@univerjs/design';+import {+ clsx,+ Dropdown,+ DropdownMenu,+ Tooltip,+} from '@univerjs/design';import { CheckMarkIcon } from '@univerjs/icons';import {createContext,@@ -50,6 +55,37 @@ export interface ITooltipWrapperRef {el: HTMLSpanElement | null;}+export interface IToolbarTooltipProps extends Omit<ITooltipProps, 'visible' | 'onVisibleChange'> {+ popupOpen: boolean;+}++/**+ * Keeps toolbar tooltips controlled while a related popup opens and closes.+ * The tooltip stays hidden after the popup closes until a new hover or focus interaction occurs.+ */+export function ToolbarTooltip(props: IToolbarTooltipProps) {+ const { popupOpen, ...tooltipProps } = props;+ const [tooltipVisible, setTooltipVisible] = useState(false);++ useEffect(() => {+ if (popupOpen) {+ setTooltipVisible(false);+ }+ }, [popupOpen]);++ return (+ <Tooltip+ {...tooltipProps}+ visible={!popupOpen && tooltipVisible}+ onVisibleChange={(visible) => {+ if (!popupOpen) {+ setTooltipVisible(visible);+ }+ }}+ />+ );+}+export function ToolbarDropdownProvider(props: { children: ReactNode }) {const [openDropdownKey, setOpenDropdownKey] = useState<string | null>(null);const contextValue = useMemo(() => ({@@ -69,29 +105,18 @@ export const TooltipWrapper = forwardRef<ITooltipWrapperRef, ITooltipProps & { dconst spanRef = useRef<HTMLSpanElement>(null);- const [tooltipVisible, setTooltipVisible] = useState(false);const [localDropdownVisible, setLocalDropdownVisible] = useState(false);const toolbarDropdownContext = useContext(ToolbarDropdownContext);const dropdownVisible = dropdownKey && toolbarDropdownContext? toolbarDropdownContext.openDropdownKey === dropdownKey: localDropdownVisible;- function handleChangeTooltipVisible(visible: boolean) {- if (dropdownVisible) {- setTooltipVisible(false);- } else {- setTooltipVisible(visible);- }- }-const handleChangeDropdownVisible = useCallback((visible: boolean) => {if (dropdownKey && toolbarDropdownContext) {toolbarDropdownContext.setOpenDropdownKey(visible ? dropdownKey : null);} else {setLocalDropdownVisible(visible);}-- setTooltipVisible(false);}, [dropdownKey, toolbarDropdownContext]);const contextValue = useMemo(() => ({@@ -113,13 +138,12 @@ export const TooltipWrapper = forwardRef<ITooltipWrapperRef, ITooltipProps & { dreturn tooltipProps.title? (- <Tooltip- visible={tooltipVisible}- onVisibleChange={handleChangeTooltipVisible}+ <ToolbarTooltip+ popupOpen={dropdownVisible}{...tooltipProps}>{content}- </Tooltip>+ </ToolbarTooltip>): content;});diff --git a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsxindex 2c2f8b6833..774092b552 100644--- a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx+++ b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx@@ -248,6 +248,21 @@ describe('ToolbarItem', () => {expect(container.querySelector('button button')).toBeNull();});+ it('does not apply a full-item hover background to a non-hoverable custom label', () => {+ const { container } = renderWithDependencies(+ <ToolbarItem+ id="test-custom-button"+ type={MenuItemType.BUTTON}+ label={{ name: 'TestDynamicOption', hoverable: false }}+ grid+ />+ );++ const rootClassName = container.querySelector('[data-u-command="test-custom-button"]')?.className;+ expect(rootClassName).toContain('hover:!univer-bg-transparent');+ expect(rootClassName).toContain('univer-cursor-default');+ });+it('fills a custom component in a fixed-width Grid item', () => {const { container, getByRole } = renderWithDependencies(<ToolbarItemdiff --git a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsxindex 7a897d11a8..2971624a29 100644--- a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx+++ b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx@@ -34,6 +34,7 @@ import {DropdownMenuWrapper,DropdownWrapper,ToolbarDropdownProvider,+ ToolbarTooltip,TooltipWrapper,} from '../TooltipButtonWrapper';@@ -75,6 +76,34 @@ function renderWithDependencies(afterEach(cleanup);+describe('ToolbarTooltip', () => {+ it('stays hidden after its popup closes until a new trigger interaction', () => {+ const renderTooltip = (popupOpen: boolean) => (+ <ToolbarTooltip title="Fill" popupOpen={popupOpen}>+ <button type="button">Fill trigger</button>+ </ToolbarTooltip>+ );+ const { getByRole, queryByRole, rerender } = render(renderTooltip(false));+ const trigger = getByRole('button', { name: 'Fill trigger' }).parentElement;+ if (!trigger) {+ throw new Error('Expected toolbar tooltip trigger wrapper');+ }++ fireEvent.mouseEnter(trigger);+ expect(getByRole('tooltip').textContent).toBe('Fill');++ rerender(renderTooltip(true));+ expect(queryByRole('tooltip')).toBeNull();++ rerender(renderTooltip(false));+ expect(queryByRole('tooltip')).toBeNull();++ fireEvent.mouseLeave(trigger);+ fireEvent.mouseEnter(trigger);+ expect(getByRole('tooltip').textContent).toBe('Fill');+ });+});+describe('DropdownMenuLabel', () => {it('preserves option metadata when a custom label emits a dynamic value', () => {const onOptionSelect = vi.fn();