|
| 1 | +import * as React from 'react'; |
| 2 | +import {ToolbarMenu} from 'nice-ui/lib/4-card/Toolbar/ToolbarMenu'; |
| 3 | +import {ContextMenu, type ContextMenuProps} from 'nice-ui/lib/4-card/ContextMenu'; |
| 4 | +import {PositionAtPoint} from 'nice-ui/lib/utils/popup/PositionAtPoint'; |
| 5 | +import {context as popupContext} from 'nice-ui/lib/4-card/Popup/context'; |
| 6 | +import {ClickAway} from 'nice-ui/lib/utils/ClickAway'; |
| 7 | +import {ToolbarMenuProvider} from 'nice-ui/lib/4-card/Toolbar/ToolbarMenu/ToolbarMenuProvider'; |
| 8 | +import {MoveToViewport} from 'nice-ui/lib/utils/popup/MoveToViewport'; |
| 9 | +import type {ToolbarMenuProps} from 'nice-ui/lib/4-card/Toolbar/ToolbarMenu/types'; |
| 10 | +import type {AnchorPoint} from 'nice-ui/lib/utils/popup'; |
| 11 | + |
| 12 | +export type InlineMenuView = 'toolbar' | 'context'; |
| 13 | + |
| 14 | +export interface ExpandableToolbarProps extends ToolbarMenuProps { |
| 15 | + expandPoint?: AnchorPoint | (() => AnchorPoint); |
| 16 | + disabled?: boolean; |
| 17 | + more?: Omit<ToolbarMenuProps['more'], 'onClick'>; |
| 18 | + context?: ContextMenuProps; |
| 19 | +} |
| 20 | + |
| 21 | +export const ExpandableToolbar: React.FC<ExpandableToolbarProps> = (props) => { |
| 22 | + const {expandPoint, more, context, ...rest} = props; |
| 23 | + const [view, setView] = React.useState<InlineMenuView>('toolbar'); |
| 24 | + const popupContextValue = React.useMemo( |
| 25 | + () => ({ |
| 26 | + close: () => { |
| 27 | + setView('toolbar'); |
| 28 | + }, |
| 29 | + }), |
| 30 | + [], |
| 31 | + ); |
| 32 | + const handleContextMenuClickAway = React.useCallback(() => { |
| 33 | + setView('toolbar'); |
| 34 | + }, []); |
| 35 | + |
| 36 | + if (view === 'context') { |
| 37 | + if (!expandPoint) return null; |
| 38 | + return ( |
| 39 | + <PositionAtPoint point={typeof expandPoint === 'function' ? expandPoint() : expandPoint}> |
| 40 | + <ClickAway onClickAway={handleContextMenuClickAway}> |
| 41 | + <popupContext.Provider value={popupContextValue}> |
| 42 | + <ToolbarMenuProvider {...rest}> |
| 43 | + <MoveToViewport> |
| 44 | + <ContextMenu inset showSearch {...context} menu={rest.menu} onEsc={() => setView('toolbar')} /> |
| 45 | + </MoveToViewport> |
| 46 | + </ToolbarMenuProvider> |
| 47 | + </popupContext.Provider> |
| 48 | + </ClickAway> |
| 49 | + </PositionAtPoint> |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + return ( |
| 54 | + <ToolbarMenu |
| 55 | + {...rest} |
| 56 | + more={{ |
| 57 | + ...more, |
| 58 | + onClick: expandPoint |
| 59 | + ? () => { |
| 60 | + setView('context'); |
| 61 | + } |
| 62 | + : undefined, |
| 63 | + }} |
| 64 | + /> |
| 65 | + ); |
| 66 | +}; |
0 commit comments