All files / src/components facets.tsx

86.67% Statements 39/45
54.05% Branches 20/37
90% Functions 9/10
86.36% Lines 38/44

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                                                        18x       14x 14x 14x 14x 10x   4x   5x 4x 4x 5x 5x   5x   4x 4x             18x       204x 204x   205x       204x 204x     204x 204x                                           18x             10x 10x   10x     10x         200x     200x   200x         200x   200x                           200x                                                                       18x                 1x       1x       6x                                                            
import { FC, ReactNode, HTMLAttributes, Children } from 'react';
import { Link, useLocation } from 'react-router-dom';
import cn from 'classnames';
 
import ExpandableList from './expandable-list';
 
import { formatLargeNumber } from '../utils';
 
import '../styles/components/facets.scss';
 
type FacetValue = { label?: ReactNode; value: string; count: number };
 
export type FacetObject = {
  label?: ReactNode;
  name: string;
  allowMultipleSelection?: boolean;
  values?: FacetValue[];
};
 
// To hold facets, record of sets
type CustomQueryValue = Record<string, Set<string>>;
// The modified query object, with our custom facet object
export type CustomParsedQuery = Record<string, string | CustomQueryValue>;
 
/**
 * Takes a search string and parse it, handle facets specifically, keeps them
 * as sets of values
 */
export const parse = (
  string: string,
  queryStringKey = 'facets'
): CustomParsedQuery => {
  const parsed = new URLSearchParams(string);
  const customParsed: CustomParsedQuery = Object.fromEntries(parsed);
  const queryStringFacet = parsed.get(queryStringKey);
  if (!queryStringFacet) {
    return customParsed;
  }
  const facetTokens = queryStringFacet
    .split(',')
    .map((stringTuple) => stringTuple.split(':'));
  const facets: CustomQueryValue = {};
  for (const [name, value] of facetTokens) {
    if (!facets[name]) {
      facets[name] = new Set();
    }
    facets[name].add(value);
  }
  customParsed[queryStringKey] = facets;
  return customParsed;
};
 
/**
 * Takes a parsed search object (as generated by the previous "parse" function)
 * and generate a search string
 */
export const stringify = (
  query: CustomParsedQuery,
  queryStringKey = 'facets'
): string => {
  const { [queryStringKey]: facets = {}, ...rest } = query;
  const facetString = Object.entries(facets as CustomQueryValue)
    .map(([name, values]) =>
      Array.from(values).map((value) => `${name}:${value}`)
    )
    .flat()
    .join(',');
  const sp = new URLSearchParams(rest as Record<string, string>);
  Iif (!facetString) {
    return sp.toString();
  }
  sp.set(queryStringKey, facetString);
  return sp.toString();
};
 
type FacetProps = {
  /**
   * The facet data to be displayed
   */
  data: FacetObject;
  /**
   * Extra components to be added in the "action" area
   */
  extraActions?: ReactNode;
  /**
   * Key with which to add the facets in the querystring (defaults to "facets")
   */
  queryStringKey?: string;
  /**
   * ClickHandler for specific behaviour
   */
  facetClickHandler?: (event: React.MouseEvent<HTMLElement>) => void;
};
 
export const Facet: FC<FacetProps & HTMLAttributes<HTMLDivElement>> = ({
  data,
  extraActions,
  queryStringKey = 'facets',
  facetClickHandler,
  ...props
}) => {
  const location = useLocation();
  const search = parse(location.search, queryStringKey);
 
  Iif (!data.values?.length) {
    return null;
  }
  return (
    <div {...props}>
      <div className="facet-name">{data.label || data.name}</div>
      <ExpandableList extraActions={extraActions}>
        {data.values.map(({ value, label, count }) => {
          const queryField = search[queryStringKey] as
            | CustomQueryValue
            | undefined;
          const isActive = queryField?.[data.name]?.has(value);
 
          const facetSet = new Set(
            data.allowMultipleSelection && queryField
              ? queryField[data.name]
              : null
          );
          facetSet[isActive ? 'delete' : 'add'](value);
 
          const to = {
            ...location,
            search: stringify(
              {
                ...search,
                [queryStringKey]: {
                  ...queryField,
                  [data.name]: facetSet,
                },
              },
              queryStringKey
            ),
          };
 
          return (
            <Link
              key={`${data.name}_${value}`}
              to={to}
              className={isActive ? 'facet-active' : undefined}
              onClick={facetClickHandler}
            >
              {label || value}
              {` (${formatLargeNumber(count)})`}
            </Link>
          );
        })}
      </ExpandableList>
    </div>
  );
};
 
type FacetsProps = {
  /**
   * The facet data to be displayed
   */
  data?: FacetObject[];
  /**
   * Extra components to be added in the "action" area, map of <facet name, component>
   */
  extraActionsFor?: Map<string, ReactNode>;
  /**
   * Key with which to add the facets in the querystring (defaults to "facets")
   */
  queryStringKey?: string;
  /**
   * ClickHandler for specific behaviour
   */
  facetClickHandler?: (event: React.MouseEvent<HTMLElement>) => void;
};
 
export const Facets: FC<FacetsProps & HTMLAttributes<HTMLDivElement>> = ({
  data,
  extraActionsFor,
  queryStringKey = 'facets',
  children,
  className,
  facetClickHandler,
  ...props
}) => {
  Iif (!(data?.length || Children.count(children))) {
    return null;
  }
 
  return (
    <div className={cn(className, 'facets')} {...props}>
      <ul className="no-bullet">
        {data?.map((facet) =>
          facet.values?.length ? (
            <li key={facet.name}>
              <Facet
                data={facet}
                extraActions={extraActionsFor?.get(facet.name)}
                queryStringKey={queryStringKey}
                facetClickHandler={facetClickHandler}
              />
            </li>
          ) : null
        )}
        {Children.map(children, (child, index) => {
          if (!child) {
            return null;
          }
          return (
            <li
              key={
                (typeof child === 'object' && 'key' in child && child.key) ||
                index
              }
            >
              {child}
            </li>
          );
        })}
      </ul>
    </div>
  );
};