All files / client/src/components MultiSelectDropdown.tsx

87.71% Statements 50/57
60.86% Branches 14/23
100% Functions 23/23
87.5% Lines 49/56

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                                      356x                   2363x 2363x 2363x 2363x 2363x 2363x   2363x 10284x     2363x 616x 547x   69x 72x 72x                   69x 63x 63x     69x 69x 69x 63x 63x                     548x               3x                           69x       69x                             1374x           70x                   1x       1x             2361x     2361x     1x       548x     548x 548x       1x           548x       1x               2361x 2361x         1x           1x         1x                       241x   241x 241x     1x      
import { ReactElement, useEffect, useId, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Checkbox } from "client/components/Checkbox";
import { Option } from "client/components/Dropdown";
import { TertiaryButton } from "client/components/TertiaryButton";
 
interface Props {
  id?: string;
  options: Option[];
  selectedValues: readonly string[];
  onToggle: (value: string) => void;
  onClear: () => void;
  placeholder: string;
  testId?: string;
  className?: string;
}
 
export const MultiSelectDropdown = ({
  id,
  options,
  selectedValues,
  onToggle,
  onClear,
  placeholder,
  testId,
  className,
}: Props): ReactElement => {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const skipNextToggle = useRef(false);
  const generatedId = useId();
  const panelId = `${id ?? generatedId}-panel`;
 
  const selectedOptions = options.filter((option) =>
    selectedValues.includes(option.value),
  );
 
  useEffect(() => {
    if (!open) {
      return;
    }
    const handlePointerDown = (event: MouseEvent): void => {
      Eif (containerRef.current?.contains(event.target as Node)) {
        return;
      }
      setOpen(false);
      // Clicking the control's own label forwards a click to the toggle
      // button, which would reopen the panel this handler just closed
      const label = (event.target as Element).closest("label");
      if (label && id && label.htmlFor === id) {
        skipNextToggle.current = true;
      }
    };
    const handleKeyDown = (event: KeyboardEvent): void => {
      Eif (event.key === "Escape") {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handlePointerDown);
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("mousedown", handlePointerDown);
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [open, id]);
 
  return (
    <Container ref={containerRef} className={className}>
      {/* Pills hold their own remove buttons, so the dropdown toggle is a
          sibling button instead of wrapping the whole control (nested buttons
          are invalid HTML) */}
      <Control data-testid={testId}>
        {selectedOptions.map((option) => (
          <TagPill key={option.value}>
            {option.title}
            <RemoveButton
              type="button"
              aria-label={t("iconAltText.removeSelection", {
                SELECTION: option.title,
              })}
              onClick={() => {
                onToggle(option.value);
              }}
            >
              <FontAwesomeIcon icon="xmark" />
            </RemoveButton>
          </TagPill>
        ))}
        <ToggleButton
          type="button"
          id={id}
          aria-haspopup="listbox"
          aria-expanded={open}
          aria-controls={panelId}
          onClick={() => {
            Iif (skipNextToggle.current) {
              skipNextToggle.current = false;
              return;
            }
            setOpen((prev) => !prev);
          }}
        >
          {selectedOptions.length === 0 && (
            <Placeholder>{placeholder}</Placeholder>
          )}
          <CaretIcon icon={open ? "chevron-up" : "chevron-down"} />
        </ToggleButton>
      </Control>
      {open && (
        <Panel id={panelId} role="group">
          {selectedValues.length > 0 && (
            <ClearButton onClick={onClear}>{t("clearSelection")}</ClearButton>
          )}
          {options.map((option) => (
            <Checkbox
              key={option.value}
              id={`${panelId}-${option.value}`}
              label={option.title}
              checked={selectedValues.includes(option.value)}
              onChange={() => {
                onToggle(option.value);
              }}
            />
          ))}
        </Panel>
      )}
    </Container>
  );
};
 
const Container = styled.div`
  position: relative;
`;
 
const Control = styled.div`
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
  box-sizing: border-box;
  min-height: 38px;
  border: 1px solid ${(props) => props.theme.borderInactive};
  border-radius: 6px;
  padding: 2px 6px;
  background-color: ${(props) => props.theme.backgroundMain};
`;
 
const TagPill = styled.span`
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background-color: ${(props) => props.theme.backgroundTag};
  border-radius: 100px;
  padding: 4px 8px;
  font-size: ${(props) => props.theme.fontSizeSmaller};
  color: ${(props) => props.theme.textTag};
  white-space: nowrap;
`;
 
const RemoveButton = styled.button`
  display: inline-flex;
  align-items: center;
  padding: 0;
  border: none;
  background: none;
  color: ${(props) => props.theme.textTag};
  cursor: pointer;
`;
 
const ToggleButton = styled.button`
  display: flex;
  flex: 1;
  align-items: center;
  align-self: stretch;
  padding: 0;
  border: none;
  background: none;
  font-size: ${(props) => props.theme.fontSizeNormal};
  color: ${(props) => props.theme.textMain};
  cursor: pointer;
  text-align: left;
`;
 
const Placeholder = styled.span`
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
`;
 
const CaretIcon = styled(FontAwesomeIcon)`
  margin: 0 0 0 auto;
  font-size: 12px;
`;
 
const Panel = styled.div`
  position: absolute;
 
  /* Above the program list's sticky timeslot headers (z-index: 2) */
  z-index: 3;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  border: 1px solid ${(props) => props.theme.borderInactive};
  border-radius: 6px;
  background-color: ${(props) => props.theme.backgroundMain};
  box-shadow: ${(props) => props.theme.shadowLower};
`;
 
const ClearButton = styled(TertiaryButton)`
  align-self: flex-start;
`;