Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.2 kB
2
Indexable
Never
import * as React from 'react';
import IconButton from '@mui/material/IconButton';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import styled from '@emotion/styled';
import { ListItemIcon } from '@mui/material';
import { Language } from '@/@types/common';

const ITEM_HEIGHT = 48;

const ImageButton = styled(IconButton)`
  padding: 0px;
  margin: 0px;
`

const ImageIcon = styled.img`
  height: 40px;
  width: 40px;
  border-radius: 50%;
`

const MenuImageIcon = styled.img`
  height: 28px;
  width: 28px;
  border-radius: 50%;
`

type Props = {
  selectedLanguage: Partial<Language> | undefined,
  languages: Language[],
  onSelect: (language: Language) => void
}

export default function LongMenu({ languages, onSelect, selectedLanguage }: Props) {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <div>
      <ImageButton
        aria-label="language"
        id="long-button"
        aria-controls={open ? 'long-menu' : undefined}
        aria-expanded={open ? 'true' : undefined}
        aria-haspopup="true"
        onClick={handleClick}
      >
        <ImageIcon src={selectedLanguage?.image} />
      </ImageButton>
      <Menu
        id="long-menu"
        MenuListProps={{
          'aria-labelledby': 'long-button',
        }}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        disableScrollLock={true}
        PaperProps={{
          style: {
            maxHeight: ITEM_HEIGHT * languages.length,
          },
        }}
      >
        {languages.map((language) => (
          <MenuItem
            key={language.code}
            selected={language.code === selectedLanguage?.code}
            onClick={() => {
              onSelect(language)
              handleClose()
            }}
          >
            <ListItemIcon>
              <MenuImageIcon src={language?.image} />
            </ListItemIcon>
            {language.name}
          </MenuItem>
        ))}
      </Menu>
    </div>
  );
}