All files / src/views/Search KeywordsFilter.tsx

0% Statements 0/18
0% Branches 0/4
0% Functions 0/10
0% Lines 0/17

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                                                                                                             
import { FunctionComponent, useMemo } from "react";
import { CheckboxFilter } from "./CheckboxFilter";
import testIds from "./testIds";
import { useKeywords } from "./useSearchParam";
import { useUpdateSearchParam } from "./useUpdateSearchParam";
import { useSearchContext } from "../../contexts/Search";
 
export const KeywordsFilter: FunctionComponent = () => {
  const keywords = useKeywords();
  const keywordMap = useSearchContext()!.keywords;
  const updateSearch = useUpdateSearchParam();
 
  const onKeywordChange = (keyword: string) => {
    updateSearch({
      keywords: keywords.includes(keyword)
        ? keywords.filter((k) => k !== keyword)
        : [...keywords, keyword],
    });
  };
 
  const keywordOptions = useMemo(() => {
    const baseOptions = [...keywordMap.entries()]
      .sort(([, count1], [, count2]) => {
        return count1 < count2 ? 1 : -1;
      })
      .filter(([keyword]) => !keywords.includes(keyword))
      .map(([keyword]) => ({
        display: keyword,
        value: keyword,
      }))
      .slice(0, 25);
 
    const keywordsNotInOptions = keywords.filter(
      (k) => !baseOptions.some((opt) => opt.value === k)
    );
 
    return [
      ...keywordsNotInOptions.map((k) => ({ display: k, value: k })),
      ...baseOptions,
    ];
  }, [keywordMap, keywords]);
 
  return (
    <CheckboxFilter
      data-testid={testIds.languagesFilter}
      hint="Focus the results by choosing one or more keywords reflecting the kind of construct you're looking for. Keywords are provided by construct authors."
      initialItemCount={5}
      name="Keywords"
      onValueChange={onKeywordChange}
      options={keywordOptions}
      values={keywords}
    />
  );
};