All files / app/features/communities/CommunityPage SubCommunitiesDropdown.tsx

100% Statements 37/37
87.5% Branches 7/8
100% Functions 10/10
100% Lines 36/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154                7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x               39x       7x   5x         29x 29x 29x 29x 29x 29x   29x 37x     29x     29x 2x 2x     29x 1x 1x     29x 19x 18x                           4x                                                     18x                               19x   1x                                                            
import { ExpandLess, ExpandMore, SearchOutlined } from "@mui/icons-material";
import {
  Button,
  InputAdornment,
  Menu,
  MenuItem,
  styled,
  Typography,
} from "@mui/material";
import StyledLink from "components/StyledLink";
import TextField from "components/TextField";
import useAccountInfo from "features/auth/useAccountInfo";
import { Trans, useTranslation } from "i18n";
import { COMMUNITIES } from "i18n/namespaces";
import { useRouter } from "next/router";
import { Community, NodeType } from "proto/communities_pb";
import { KeyboardEvent, useState } from "react";
import { communityCreationFormURL, routeToCommunity } from "routes";
 
const NODE_TYPE_LABEL_KEYS: Partial<Record<NodeType, string>> = {
  [NodeType.NODE_TYPE_MACROREGION]: "communities:select_macroregion",
  [NodeType.NODE_TYPE_REGION]: "communities:select_region",
  [NodeType.NODE_TYPE_SUBREGION]: "communities:select_subregion",
  [NodeType.NODE_TYPE_LOCALITY]: "communities:select_locality",
  [NodeType.NODE_TYPE_SUBLOCALITY]: "communities:select_sublocality",
};
 
const StyledSearchBox = styled("li")(({ theme }) => ({
  padding: theme.spacing(1, 2),
}));
 
const menuId = "sub-communities-menu";
 
export default function SubCommunitiesDropdown({
  subCommunities,
}: {
  subCommunities: Community.AsObject[];
}) {
  const { t } = useTranslation(COMMUNITIES);
  const router = useRouter();
  const { data: accountInfo } = useAccountInfo();
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const [query, setQuery] = useState("");
  const open = !!anchorEl;
 
  const filteredOptions = subCommunities.filter((option) =>
    option.name.toLowerCase().includes(query.toLowerCase()),
  );
  const labelKey =
    NODE_TYPE_LABEL_KEYS[subCommunities[0].nodeType] ??
    "communities:select_sub_community";
 
  const handleClose = () => {
    setAnchorEl(null);
    setQuery("");
  };
 
  const handleSelect = (option: Community.AsObject) => {
    router.push(routeToCommunity(option.communityId, option.slug));
    handleClose();
  };
 
  const handleSearchKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    if (event.key !== "Escape") {
      event.stopPropagation();
    }
  };
 
  return (
    <>
      <Button
        variant="text"
        color="primary"
        endIcon={open ? <ExpandLess /> : <ExpandMore />}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-controls={open ? menuId : undefined}
        aria-label={t("communities:sub_community_dropdown_a11y")}
        onClick={(event) => setAnchorEl(event.currentTarget)}
        sx={{
          minWidth: { xs: 0, sm: 64 },
          pl: { xs: 0, sm: 1 },
        }}
      >
        {t(labelKey)}
      </Button>
      <Menu
        id={menuId}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        disableAutoFocusItem
        anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
        transformOrigin={{ vertical: "top", horizontal: "left" }}
        slotProps={{
          paper: { sx: { width: 300, maxWidth: "90vw", maxHeight: 288 } },
        }}
      >
        <StyledSearchBox>
          <TextField
            autoFocus
            variant="outlined"
            size="small"
            fullWidth
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            onKeyDown={handleSearchKeyDown}
            placeholder={t("communities:sub_community_search_placeholder")}
            slotProps={{
              input: {
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchOutlined color="action" />
                  </InputAdornment>
                ),
              },
            }}
          />
        </StyledSearchBox>
        {filteredOptions.length > 0 ? (
          filteredOptions.map((option) => (
            <MenuItem
              key={option.communityId}
              onClick={() => handleSelect(option)}
            >
              {option.name}
            </MenuItem>
          ))
        ) : (
          <StyledSearchBox>
            <Typography
              variant="body2"
              color="var(--mui-palette-text-secondary)"
            >
              <Trans
                t={t}
                i18nKey="communities:no_results_found_with_link"
                components={[
                  <StyledLink
                    href={communityCreationFormURL(accountInfo?.username)}
                    target="_blank"
                    rel="noreferrer noopener"
                    key="request-link"
                  />,
                ]}
              />
            </Typography>
          </StyledSearchBox>
        )}
      </Menu>
    </>
  );
}