| 1 | // This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt |
| 2 | |
| 3 | import { MouseEvent, createElement as h, Fragment, useCallback, useId, useState } from 'react' |
| 4 | import { Menu, MenuItem } from '@mui/material' |
| 5 | import { Btn, BtnProps } from './mui' |
| 6 | |
| 7 | export default function MenuButton({ items, ...rest }: BtnProps & { items: any[] }) { |
| 8 | const [anchorEl, setAnchorEl] = useState<HTMLElement>() |
| 9 | const open = Boolean(anchorEl) |
| 10 | const onClose = useCallback(() => setAnchorEl(undefined), []) |
| 11 | const id = useId() |
| 12 | const menuId = useId() |
| 13 | return h(Fragment, {}, |
| 14 | h(Btn, { |
| 15 | id, |
| 16 | 'aria-controls': open ? menuId : undefined, |
| 17 | 'aria-haspopup': true, |
| 18 | 'aria-expanded': open ? true : undefined, |
| 19 | onClick(event: MouseEvent<HTMLButtonElement>) { |
| 20 | setAnchorEl(event.currentTarget) |
| 21 | }, |
| 22 | ...rest, |
| 23 | }), |
| 24 | h(Menu, { |
| 25 | id: menuId, |
| 26 | anchorEl, |
| 27 | open, |
| 28 | onClose, |
| 29 | slotProps: { list: { 'aria-labelledby': id } }, |
| 30 | children: items.map((it,idx) => |
| 31 | h(MenuItem, { |
| 32 | key: idx, |
| 33 | ...it, |
| 34 | onClick() { |
| 35 | onClose() |
| 36 | it.onClick?.apply(this, arguments) |
| 37 | } |
| 38 | }) ) |
| 39 | }) |
| 40 | ) |
| 41 | } |