All files / src/components accordion-search.tsx

93.18% Statements 41/44
68.75% Branches 22/32
86.66% Functions 13/15
95% Lines 38/40

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                    8x     33x 23x   23x 2x   21x     8x       12x 3x   9x 9x 21x 2x 19x 6x 6x 2x       9x                                                                                                             8x               13x             1x                   8x                       9x 9x 21x 9x                                 21x                                                                                                                       8x             5x 5x   5x   4x             5x   1x         5x       5x     9x                                       5x                          
import { useState, useMemo, useDeferredValue, useCallback } from 'react';
 
import SubstringHighlight from './substring-highlight';
import Accordion from './accordion';
import Loader from './loader';
import Message from './message';
import SearchInput from './search-input';
 
import '../styles/components/accordion-search.scss';
 
export const getLeafKeys = (
  item: AccordionItem[] | AccordionItem
): string[] | string => {
  if (Array.isArray(item)) {
    return item.flatMap((i) => getLeafKeys(i));
  }
  if (item.items) {
    return getLeafKeys(item.items);
  }
  return item.id;
};
 
export const filterAccordionData = (
  accordionData: AccordionItem[],
  query: string
): AccordionItem[] => {
  if (!query) {
    return accordionData;
  }
  const result = [];
  for (const item of accordionData) {
    if (item.label.toLowerCase().includes(query)) {
      result.push(item);
    } else if (item.items?.length) {
      const items = filterAccordionData(item.items, query);
      if (items.length) {
        result.push({ ...item, items });
      }
    }
  }
  return result;
};
 
export type AccordionItem = {
  label: string;
  id: string;
  items?: AccordionItem[];
  addAsterisk?: boolean;
};
 
type AccordionSearchItemProps = {
  /**
   * An array of objects which populates the list items
   */
  items: AccordionItem[];
  /**
   * String used to fill in the search input when empty
   */
  id: string;
  /**
   * Callback that is fired when an accordion's item is selected
   */
  onSelect: (id: string) => unknown;
  /**
   * Array of the selected items' IDs
   */
  selected: string[];
  /**
   * Indicates if the accordion should always be open
   */
  alwaysOpen?: boolean;
  /**
   * Indicates if the item should initially be open ie the user can
   * still collapse after intial load.
   */
  initialOpen?: boolean;
  /**
   * A boolean indicating whether the component should span multiple
   * columns: 2 columns for medium to 3 columns for large+ screens.
   */
  columns?: boolean;
  /**
   * The title, works as a trigger to open/close
   */
  label: string;
  /**
   * The user's query, passed to highlight in the item's label
   */
  query: string;
  /**
   * Appends an asterisk to selected items (in the case of xrefs this indicates full xrefs)
   */
  addAsterisk?: boolean;
};
 
const AccordionSearchCheckbox = ({
  onSelect,
  selected,
  id,
  label,
  query,
  addAsterisk,
}: Omit<AccordionSearchItemProps, 'items' | 'alwaysOpen' | 'columns'>) => (
  <li key={id} className="accordion-search__list__item">
    <label key={id} htmlFor={`checkbox-${id}`}>
      <input
        type="checkbox"
        id={`checkbox-${id}`}
        className="accordion-search__list__item-checkbox"
        onChange={() => {
          onSelect(id);
        }}
        checked={selected.includes(id)}
      />
      <SubstringHighlight substring={query}>{label}</SubstringHighlight>
      {addAsterisk && selected.includes(id) ? '*' : ''}
    </label>
  </li>
);
 
const AccordionSearchItem = ({
  label,
  alwaysOpen,
  items,
  selected,
  columns,
  onSelect,
  id,
  query,
  addAsterisk,
  initialOpen = false,
}: AccordionSearchItemProps) => {
  const itemKeys = useMemo(() => new Set(getLeafKeys(items)), [items]);
  const count = selected.filter((s) => itemKeys.has(s)).length;
  const areChildrenCheckboxes = items.every((item) => !item.items);
  return (
    <Accordion
      accordionTitle={
        <SubstringHighlight substring={query}>{label}</SubstringHighlight>
      }
      count={count}
      alwaysOpen={alwaysOpen}
      key={id}
      initialOpen={initialOpen}
    >
      {areChildrenCheckboxes ? (
        <ul
          className={`no-bullet accordion-search__list${
            columns ? ' accordion-search__list--columns' : ''
          }`}
        >
          {items.map((item) => (
            <AccordionSearchCheckbox
              label={item.label}
              selected={selected}
              onSelect={onSelect}
              id={item.id}
              key={item.id}
              query={query}
              addAsterisk={item.addAsterisk}
            />
          ))}
        </ul>
      ) : (
        <ul className="no-bullet accordion-search__list">
          {items.map(
            (item) =>
              item.items?.length && (
                <AccordionSearchItem
                  label={item.label}
                  alwaysOpen={alwaysOpen}
                  items={item.items}
                  selected={selected}
                  columns={columns}
                  onSelect={onSelect}
                  id={item.id}
                  key={item.id}
                  query={query}
                  addAsterisk={addAsterisk}
                />
              )
          )}
        </ul>
      )}
    </Accordion>
  );
};
 
type AccordionSearchProps = {
  /**
   * An array of objects each of which is used to populate an accordion.
   */
  accordionData: AccordionItem[];
  /**
   * String used to fill in the search input when empty
   */
  placeholder?: string;
  /**
   * Callback that is fired when an accordion's item is selected
   */
  onSelect: (itemId: string) => unknown;
  /**
   * Array of the selected items' IDs
   */
  selected: string[];
  /**
   * A boolean indicating whether the component should span multiple
   * columns: 2 columns for medium to 3 columns for large+ screens.
   */
  columns?: boolean;
};
 
const AccordionSearch = ({
  accordionData,
  placeholder = '',
  onSelect,
  selected,
  columns,
}: AccordionSearchProps) => {
  const [inputValue, setInputValue] = useState('');
  const deferredInputValue = useDeferredValue(inputValue);
 
  const filteredAccordionData = useMemo(
    () =>
      filterAccordionData(
        accordionData,
        deferredInputValue.trim().toLowerCase()
      ),
    [accordionData, deferredInputValue]
  );
 
  const handleSearchInputChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      setInputValue(event.target.value);
    },
    []
  );
 
  Iif (!accordionData || !accordionData.length) {
    return <Loader />;
  }
 
  const accordionGroupNode = filteredAccordionData.length ? (
    filteredAccordionData.map(
      ({ label, id, items, addAsterisk }, index) =>
        items?.length && (
          <AccordionSearchItem
            label={label}
            initialOpen={index === 0}
            alwaysOpen={Boolean(deferredInputValue)}
            items={items}
            selected={selected}
            columns={columns}
            onSelect={onSelect}
            id={id}
            key={id}
            query={deferredInputValue}
            addAsterisk={addAsterisk}
          />
        )
    )
  ) : (
    <Message level="failure">No matches found</Message>
  );
 
  return (
    <>
      <SearchInput
        value={inputValue}
        onChange={handleSearchInputChange}
        placeholder={placeholder}
      />
      {accordionGroupNode}
    </>
  );
};
 
export default AccordionSearch;