import { ReactNode, PropsWithChildren, HTMLAttributes, Fragment, isValidElement, Children, forwardRef, useContext, useState, useRef, useImperativeHandle, } from 'react' import { cx, isNil, isUndefined, safeInvoke, toggleSelectedList, codeWarning, pick, } from '@befe/brick-utils' import {getThemeConfigSingleton} from '@befe/brick-core' import { MenuItemId, MenuSize, SUBMENU_POPPER_TRIGGER_TYPE_DEFAULT, SUBMENU_TYPE_DEFAULT, resolveMenuLevel, } from './common' import {MenuContext, MenuContextValue} from './menu-context' import {MenuItem} from './menu-item' import {Submenu} from './menu-submenu' type PropsFromMenuContextValue = Pick type PropsFromHTMLUListElement = Pick, 'onMouseDown'> export interface MenuProps extends PropsFromMenuContextValue, PropsFromHTMLUListElement { /** * 自定义 class */ className?: string /** * 点选 item 的回调 */ onSelect?: (id: MenuItemId, selectedIds: MenuItemId[], currentSelectedIds: MenuItemId[]) => void /** * 反选 item 的回调 */ onDeselect?: (id: MenuItemId, selectedIds: MenuItemId[], currentSelectedIds: MenuItemId[]) => void /** * selectIds 变化时的回调 * select / deselect 均会调用 */ onChangeSelectedIds?: (selectedIds: MenuItemId[]) => void /** * 子菜单展开时的回调 */ onExpand?: (id: MenuItemId, expandedIds: MenuItemId[], currentExpandedIds: MenuItemId[]) => void /** * 子菜单折叠时的回调 */ onCollapse?: (id: MenuItemId, expandedIds: MenuItemId[], currentExpandedIds: MenuItemId[]) => void /** * expandedIds 变化时的回调 * expand / collapse 均会调用 */ onChangeExpandedIds?: (expandedIds: MenuItemId[]) => void /** * (暂定)使用反色,适用于深色背景色上 */ reverseColor?: boolean } export interface MenuState { cursorId: MenuItemId | null selectedIds: MenuItemId[] expandedIds: MenuItemId[] } /** * Menu 的对外实例句柄(经 ref 调用),由 select / cascade 等消费方同步读写 */ export interface MenuHandle { moveCursor(id: MenuItemId | null): void toggleSelected(id?: MenuItemId | null): void setSelectIds(ids: MenuItemId[]): void setExpandedIds(ids: MenuItemId[]): void readonly state: MenuState } const {config: themeConfig} = getThemeConfigSingleton() function getChildrenArray(children: ReactNode): ReactNode[] { if (isValidElement(children) && children.type === Fragment) { return getChildrenArray((children.props as {children?: ReactNode}).children) } return Children.toArray(children) } function resolveMenuSize(propSize: MenuSize | undefined, contextSize: MenuSize | undefined): MenuSize { const size = propSize || contextSize const isValid = !isUndefined(size) && ['md', 'lg'].includes(size) if (isValid) { return size as MenuSize } codeWarning( isValid, `[Menu] size 只能是 'md' | 'lg', 空或其他值则被置为 '${themeConfig.baseSize}'` ) return themeConfig.baseSize as MenuSize } export const Menu = forwardRef>(function Menu(props, ref) { const context = useContext(MenuContext) const { size: sizeProp = 'md', layout = 'vertical', multiple = false, multipleItemType = 'normal', reverseColor = false, folderToggleSpot = 'auto', submenuType = SUBMENU_TYPE_DEFAULT, submenuPopperTriggerType = SUBMENU_POPPER_TRIGGER_TYPE_DEFAULT, } = props const [cursorId, setCursorId] = useState(null) const [selectedIdsState, setSelectedIdsState] = useState([]) const [expandedIdsState, setExpandedIdsState] = useState([]) // 等价原 getDerivedStateFromProps:受控 prop 优先,未控制取内部 state const effectiveSelectedIds = isUndefined(props.selectedIds) ? selectedIdsState : props.selectedIds const effectiveExpandedIds = isUndefined(props.expandedIds) ? expandedIdsState : props.expandedIds const size = resolveMenuSize(sizeProp, context.size) const type = !isUndefined(props.type) ? props.type : (context.layout ? 'common' : 'nav') // 只在第一层处理 icon 缩进 const withPrefixIcon = context.layout ? false : getChildrenArray(props.children).some(child => { return isValidElement(child) && (child.type === MenuItem || child.type === Submenu) && !!(child.props as {icon?: unknown}).icon }) // 层级:仅 vertical + nav 的内联树参与缩进(根 Menu 从 1 起算),否则整棵树为 0(不缩进); // popper 分支会在其 Provider 把 level 置 0,0 粘滞下传,使浮层维持 CSS 现状 const level = resolveMenuLevel(context.level, type === 'nav' && layout === 'vertical') const moveCursor = (nextCursorId: MenuItemId | null) => { setCursorId(nextCursorId) } const setSelectIds = (nextSelectedIds: MenuItemId[]) => { setSelectedIdsState(nextSelectedIds) } const setExpandedIds = (nextExpandedIds: MenuItemId[]) => { setExpandedIdsState(nextExpandedIds) } const toggleSelected = (id: MenuItemId | null = cursorId) => { // if (!id) { // bad, because `id` could be `''`, `0` if (isNil(id)) { return } const selectedIds = toggleSelectedList(id, effectiveSelectedIds, { multiple, onSelect: props.onSelect, onDeselect: props.onDeselect, } ) safeInvoke(props.onChangeSelectedIds, selectedIds) if (isUndefined(props.selectedIds)) { setSelectIds(selectedIds) } } const toggleExpanded = (id: MenuItemId) => { const expandedIds = toggleSelectedList( id, effectiveExpandedIds, { onSelect: props.onExpand, onDeselect: props.onCollapse, } ) safeInvoke(props.onChangeExpandedIds, expandedIds) if (isUndefined(props.expandedIds)) { setExpandedIds(expandedIds) } } const handleItemClick = (id: MenuItemId) => { if (multiple || !effectiveSelectedIds.includes(id)) { toggleSelected(id) } } const handleClickSubmenuToggle = (id: MenuItemId) => { toggleExpanded(id) } // 以「生效态」镜像供 handle 的 get state() 同步读取(消费方在键盘处理里同步读 state.cursorId) const stateRef = useRef({ cursorId, selectedIds: effectiveSelectedIds, expandedIds: effectiveExpandedIds, }) stateRef.current = { cursorId, selectedIds: effectiveSelectedIds, expandedIds: effectiveExpandedIds, } // latest-ref 包装:useImperativeHandle 以 [] 稳定,但始终调用当前 render 的闭包(读最新 props/state) const moveCursorRef = useRef(moveCursor) moveCursorRef.current = moveCursor const toggleSelectedRef = useRef(toggleSelected) toggleSelectedRef.current = toggleSelected const setSelectIdsRef = useRef(setSelectIds) setSelectIdsRef.current = setSelectIds const setExpandedIdsRef = useRef(setExpandedIds) setExpandedIdsRef.current = setExpandedIds useImperativeHandle(ref, () => ({ moveCursor: (id: MenuItemId | null) => moveCursorRef.current(id), toggleSelected: (id?: MenuItemId | null) => toggleSelectedRef.current(id as MenuItemId | null), setSelectIds: (ids: MenuItemId[]) => setSelectIdsRef.current(ids), setExpandedIds: (ids: MenuItemId[]) => setExpandedIdsRef.current(ids), get state() { return stateRef.current }, }), []) const contextValue: MenuContextValue = { toggleSelected: handleItemClick, toggleExpanded: handleClickSubmenuToggle, moveCursor, cursorId, expandedIds: effectiveExpandedIds, selectedIds: effectiveSelectedIds, multiple, multipleItemType, submenuType, submenuPopperTriggerType, folderToggleSpot, cursorType: type === 'nav' ? 'nav' : 'common', // withPrefixIcon 只在根 Menu 真实计算,放在 ...context 之前,使其从根透传到各层(子 Menu 自算恒为 false,会被继承值覆盖) withPrefixIcon, // 上面由顶层持有(this.context 只有有值,就取 this.context 中的值) ...context, // 以下就近取 size, type, layout, level, refMenuPopper: props.refMenuPopper, } const {multiple: ctxMultiple, multipleItemType: ctxMultipleItemType, cursorType} = contextValue const className = cx( 'brick-menu', `brick-menu-size-${size}`, `brick-menu-layout-${layout}`, `brick-menu-type-${type}`, `brick-menu-cursor-type-${cursorType || 'common'}`, { 'brick-menu-multiple': ctxMultiple, [`brick-menu-multiple-item-type-${ctxMultipleItemType!}`]: ctxMultiple && ctxMultipleItemType, 'brick-menu-reverse-color': reverseColor, 'brick-menu-with-prefix-icon': withPrefixIcon, }, props.className ) const ulProps = pick(props, [ 'onMouseDown', ]) return (
    {props.children}
) }) Menu.displayName = 'Menu'