All files / app/features/profile ProfileTagInput.tsx

54.83% Statements 34/62
18.18% Branches 2/11
25.92% Functions 7/27
58.82% Lines 30/51

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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301                    1x     1x 1x 1x 1x 1x   1x                                     93x                                         93x         155x                                 155x           1x                     1x                                           1x         1x       1x         1x                       93x                 93x           93x 155x       93x 93x 93x   93x         93x                     93x             93x                             155x 155x                                                                                                                                                                                      
import {
  alpha,
  ButtonBase,
  Checkbox,
  IconButton,
  InputBase,
  Paper,
  Popper,
  styled,
  Typography,
} from "@mui/material";
import Autocomplete, {
  AutocompleteCloseReason,
} from "@mui/material/Autocomplete";
import { CloseIcon, ExpandMoreIcon } from "components/Icons";
import { useTranslation } from "i18n";
import { PROFILE } from "i18n/namespaces";
import React, { useRef, useState } from "react";
import { ControllerRenderProps } from "react-hook-form";
import { theme } from "theme";
 
interface ProfileTagOption {
  key: string;
  label: string;
}
 
interface ProfileTagInputProps {
  onChange: (_: unknown, value: string[]) => void;
  value: string[];
  // Possible options keys and their labels
  options: Record<string, string>;
  label: string;
  id: string;
  className?: string;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  inputFieldProps?: ControllerRenderProps<any, string>;
}
 
const StyledButtonBase = styled(ButtonBase)(() => ({
  "&:focus": {
    boxShadow: `0 0 0 2px var(--mui-palette-primary-main)`,
  },
  "&:hover": {
    borderColor: "var(--mui-palette-primary-main)",
    backgroundColor: "var(--mui-palette-grey-50)",
  },
  borderRadius: theme.spacing(1.5),
  border: `1px solid var(--mui-palette-grey-300)`,
  backgroundColor: "var(--mui-palette-background-paper)",
  fontFamily: "inherit",
  fontSize: "1rem",
  justifyContent: "space-between",
  margin: theme.spacing(1, 0),
  padding: theme.spacing(1.5, 2),
  width: "inherit",
  transition: "all 0.2s ease-in-out",
  boxShadow: "0 1px 3px rgba(0, 0, 0, 0.05)",
}));
 
const StyledTagsContainer = styled("div")(() => ({
  display: "grid",
  gridTemplateColumns: "repeat(auto-fit, minmax(auto, 250px))",
}));
 
const StyledTagWrapper = styled("div")(() => ({
  alignItems: "center",
  display: "flex",
  fontSize: theme.typography.fontSize,
  margin: theme.spacing(0.5, 0.5, 0.5, 0),
  padding: theme.spacing(0.75, 1.5),
  backgroundColor: "var(--mui-palette-primary-main)",
  border: `1px solid var(--mui-palette-primary-dark)`,
  borderRadius: theme.spacing(2),
  boxShadow: "0 1px 3px rgba(0, 0, 0, 0.08)",
  transition: "all 0.2s ease-in-out",
  "&:hover": {
    boxShadow: "0 2px 6px rgba(0, 0, 0, 0.12)",
    transform: "translateY(-1px)",
  },
}));
 
const StyledTagLabel = styled("span")(() => ({
  marginLeft: theme.spacing(0.75),
  fontWeight: 500,
  color: "var(--mui-palette-common-white)",
}));
 
const StyledPopper = styled(Popper)(() => ({
  backgroundColor: "var(--mui-palette-background-paper)",
  borderColor: "var(--mui-palette-grey-200)",
  borderRadius: theme.spacing(1.5),
  borderStyle: "solid",
  borderWidth: 1,
  boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
  marginTop: theme.spacing(1),
  zIndex: 101,
}));
 
const StyledInputBase = styled(InputBase)(({ theme }) => ({
  "& input": {
    "&:focus": {
      borderColor: "var(--mui-palette-primary-main)",
      boxShadow: `${alpha(theme.palette.primary.main, 0.15)} 0 0 0 2px`,
    },
    backgroundColor: "var(--mui-palette-background-paper)",
    borderColor: "var(--mui-palette-divider)",
    borderRadius: theme.spacing(1),
    borderStyle: "solid",
    borderWidth: 1,
    padding: theme.spacing(1, 1.5),
    transition: theme.transitions.create(["border-color", "box-shadow"]),
    fontSize: "0.875rem",
  },
  borderBottomColor: "var(--mui-palette-divider)",
  borderBottomStyle: "solid",
  borderBottomWidth: 1,
  padding: theme.spacing(2),
  width: "100%",
}));
 
const StyledCheckbox = styled(Checkbox)(({ theme }) => ({
  marginRight: theme.spacing(1),
  padding: 0,
}));
 
const StyledAutocompletePopper = styled(Popper)(() => ({
  position: "relative",
}));
 
const StyledAutocompletePaper = styled(Paper)(() => ({
  boxShadow: "none",
  margin: 0,
}));
 
const StyledAutocompleteOption = styled("li")(() => ({
  '&[aria-selected="true"]': {
    backgroundColor: "transparent",
  },
  "&.MuiAutocomplete-option.Mui-focused": {
    backgroundColor: "var(--mui-palette-action-hover)",
  },
  alignItems: "flex-start",
  minHeight: "auto",
  padding: theme.spacing(1),
}));
 
export default function ProfileTagInput({
  onChange,
  value = [],
  options,
  label,
  id,
  className,
  inputFieldProps,
}: ProfileTagInputProps) {
  const { t, i18n } = useTranslation(PROFILE);
 
  // In case some value doesn't map to an option, add a fake option for it.
  // For example if value is [en, xx] and options is { en: "English", fr: "French" },
  // then we extend to { en: "English", fr: "French", xx: "xx" },
  // so the all values can be displayed.
  const effectiveOptions: Record<string, string> = {
    ...Object.fromEntries(value.map((k) => [k, k])),
    ...options,
  };
 
  const [open, setOpen] = useState<boolean>(false);
  const anchorEl = useRef<null | HTMLButtonElement>(null);
  const [pendingValue, setPendingValue] = useState<string[]>([]);
 
  const handleClick = () => {
    setPendingValue(value);
    setOpen(true);
  };
 
  const handleClose = (
    _: React.ChangeEvent<unknown>,
    reason: AutocompleteCloseReason,
  ) => {
    if (reason === "toggleInput") {
      return;
    }
    onChange(null, pendingValue);
    setOpen(false);
  };
 
  const handleRemove = (key: string) => {
    onChange(
      null,
      value.filter((v) => v !== key),
    );
  };
 
  const popperId = open ? id : undefined;
 
  return (
    <>
      <StyledButtonBase
        aria-describedby={popperId}
        onClick={handleClick}
        ref={anchorEl}
        className={className}
      >
        <Typography variant="body1">{label}</Typography>
        <ExpandMoreIcon />
      </StyledButtonBase>
      <StyledTagsContainer>
        {value.map((key) => {
          const label = effectiveOptions[key];
          return (
            <StyledTagWrapper key={key}>
              <IconButton
                aria-label={t("profile_tag_input.remove_button_a11y_text", {
                  tag: label,
                })}
                edge="start"
                onClick={() => handleRemove(key)}
                size="small"
                sx={{
                  color: "var(--mui-palette-common-white)",
                  padding: 0.5,
                  "&:hover": {
                    backgroundColor: "var(--mui-palette-primary-dark)",
                    color: "var(--mui-palette-common-white)",
                  },
                }}
              >
                <CloseIcon fontSize="small" />
              </IconButton>
              <StyledTagLabel>{label}</StyledTagLabel>
            </StyledTagWrapper>
          );
        })}
      </StyledTagsContainer>
      {open && anchorEl.current && (
        <StyledPopper
          id={popperId}
          open={open}
          anchorEl={anchorEl.current}
          placement="bottom-start"
        >
          <Autocomplete<ProfileTagOption, true>
            {...inputFieldProps}
            open
            onClose={handleClose}
            multiple
            onChange={(_, newValue) => {
              if (Array.isArray(newValue) && newValue.length) {
                // For some reason I came across situations when there were undefined values in this array.
                newValue = newValue.filter((element) => element !== undefined);
                setPendingValue(
                  Array.from(new Set(newValue.map((o) => o.key))),
                );
              } else {
                setPendingValue([]);
              }
            }}
            value={pendingValue.map((key) => ({
              key,
              label: effectiveOptions[key],
            }))}
            isOptionEqualToValue={(option, val) => option.key === val.key}
            getOptionLabel={(option) => option.label}
            renderInput={(params) => (
              <StyledInputBase
                ref={params.InputProps.ref}
                inputProps={params.inputProps}
                autoFocus
              />
            )}
            disableCloseOnSelect
            disablePortal
            options={Object.entries(effectiveOptions)
              .map(([key, label]) => ({ key, label }))
              .sort((a, b) => a.label.localeCompare(b.label, i18n.language))}
            renderOption={(props, option, { selected }) => {
              const { key, ...rest } = props;
 
              return (
                <StyledAutocompleteOption key={key} {...rest}>
                  <StyledCheckbox
                    color="primary"
                    size="small"
                    checked={selected}
                  />
 
                  {option.label}
                </StyledAutocompleteOption>
              );
            }}
            slots={{
              paper: StyledAutocompletePaper,
              popper: StyledAutocompletePopper,
            }}
          />
        </StyledPopper>
      )}
    </>
  );
}