THIS IS ARCHIVED DOCUMENTATION

(Deprecated) CategoryFacet

The CategoryFacet headless controller offers a high-level interface for designing a facet UI controller that renders values in a hierarchical fashion.

Methods

deselectAll

Deselects all facet values.

isSortedBy

Checks whether the facet values are sorted according to the specified criterion.

Parameters

  • criterion: 'alphanumeric' | 'occurrences'

    The criterion to compare.

Returns boolean: Whether the facet values are sorted according to the specified criterion.

showLessValues

Sets the number of values displayed in the facet to the originally configured value.

showMoreValues

Increases the number of values displayed in the facet to the next multiple of the originally configured value.

sortBy

Sorts the facet values according to the specified criterion.

Parameters

  • criterion: 'alphanumeric' | 'occurrences'

    The criterion to use for sorting values.

toggleSelect

Toggles the specified facet value.

Parameters

subscribe

Adds a callback that will be called on state change.

Parameters

  • listener: () ⇒ void

    A callback to be invoked on state change.

Returns Unsubscribe: An unsubscribe function to remove the listener.

Attributes

facetSearch

Provides methods to search the facet’s values.

Performs a facet search.

select

Selects a facet search result.

Parameters

showMoreResults

Shows more facet search results.

updateText

Updates the facet search query.

Parameters

  • text: string

    The query to search.

state

The state of the Facet controller.

Properties

  • canShowLessValues: boolean

    true if fewer values can be displayed and false otherwise.

  • canShowMoreValues: boolean

    true if there are more values to display and false otherwise.

  • facetId: string

    The facet ID.

  • facetSearch: CategoryFacetSearchState

    The state of the facet’s searchbox.

  • hasActiveValues: boolean

    true if there’s at least one non-idle value and false otherwise.

  • isLoading: boolean

    true if a search is in progress and false otherwise.

  • parents: CategoryFacetValue[]

    The parent values of the facet.

  • sortCriteria: 'alphanumeric' | 'occurrences'

    The active sortCriterion of the facet.

  • values: CategoryFacetValue[]

    The values of the facet.

Initialize

buildCategoryFacet

Creates a CategoryFacet controller instance.

Parameters

  • engine: Engine<CategoryFacetSection & SearchSection & ConfigurationSection & CategoryFacetSearchSection>

    The headless engine.

  • props: CategoryFacetProps

    The configurable CategoryFacet properties.

Returns CategoryFacet

CategoryFacetProps

The configurable CategoryFacet properties.

Properties

CategoryFacetOptions

The options for the CategoryFacet controller.

Properties

  • field: string

    The field whose values you want to display in the facet.

  • basePath?: string[]

    The base path shared by all values for the facet.

    Default: []

  • delimitingCharacter?: string

    The character that specifies the hierarchical dependency.

    Default: ;

  • facetId?: string

    A unique identifier for the controller. By default, a random unique identifier is generated.

  • facetSearch?: CategoryFacetSearchOptions

    Facet search options.

  • filterByBasePath?: boolean

    Whether to use basePath as a filter for the results.

    Default: true

  • filterFacetCount?: boolean

    Whether to exclude the parents of folded results when estimating the result count for each facet value.

    Default: true

  • injectionDepth?: number

    The maximum number of results to scan in the index to ensure that the facet lists all potential facet values.

    Note: A high injectionDepth may negatively impact the facet request performance.

    Minimum: 0

    Default: 1000

  • numberOfValues?: number

    The number of values to request for this facet. Also determines the number of additional values to request each time this facet is expanded, and the number of values to display when this facet is collapsed.

    Minimum: 1

    Default: 5

  • sortCriteria?: 'alphanumeric' | 'occurrences'

    The criterion to use for sorting returned facet values.

    Default: occurences

CategoryFacetSearchOptions

Properties

  • captions?: Record<string, string>

    A dictionary that maps index field values to facet value display names.

  • numberOfValues?: number

    The maximum number of values to fetch.

    Default: 10

  • query?: string

    The string to match.

CategoryFacetSearchResult

Properties

  • count: number

    An estimate of the number of result items matching both the current query and the filter expression that would get generated if the facet value were selected.

  • displayValue: string

    The custom facet value display name, as specified in the captions argument of the facet request.

  • path: string[]

    The hierarchical path to the facet value.

  • rawValue: string

    The original facet value, as retrieved from the field in the index.

CategoryFacetSearchState

Properties

  • isLoading: boolean

    true if the facet search is in progress and false otherwise.

  • moreValuesAvailable: boolean

    Whether more values are available.

  • values: CategoryFacetSearchResult[]

    The facet search results.

CategoryFacetValue

Properties

  • children: CategoryFacetValue[]

    The children of this facet value.

  • moreValuesAvailable: boolean

    Whether more values are available.

  • numberOfResults: number

    The number of results having the facet value.

  • path: string[]

    The hierarchical path to the facet value.

  • state: 'idle' | 'selected'

    Whether a facet value is filtering results (selected) or not (idle).

  • value: string

    The facet value.

Unsubscribe

Call signatures

  • (): void

Example Implementation

category-facet.fn.tsx

import {useEffect, useState, FunctionComponent} from 'react';
import {
  CategoryFacet as HeadlessCategoryFacet,
  CategoryFacetValue,
} from '@coveo/headless';
import {CategoryFacetSearch} from './category-facet-search';
 
interface CategoryFacetProps {
  controller: HeadlessCategoryFacet;
}
 
export const CategoryFacet: FunctionComponent<CategoryFacetProps> = (props) => {
  const {controller} = props;
  const [state, setState] = useState(controller.state);
 
  useEffect(() => controller.subscribe(() => setState(controller.state)), []);
 
  function getUniqueKeyForValue(value: CategoryFacetValue) {
    return value.path.join('>');
  }
 
  function renderSearch() {
    return (
      <CategoryFacetSearch
        controller={controller.facetSearch}
        searchState={state.facetSearch}
      />
    );
  }
 
  function renderClearButton() {
    return (
      <button onClick={() => controller.deselectAll()}>All categories</button>
    );
  }
 
  function renderParents() {
    return (
      state.hasActiveValues && (
        <div>
          Filtering by: {renderClearButton()}
          {state.parents.map((parentValue, i) => {
            const isSelectedValue = i === state.parents.length - 1;
 
            return (
              <span key={getUniqueKeyForValue(parentValue)}>
                &rarr;
                {!isSelectedValue ? (
                  <button onClick={() => controller.toggleSelect(parentValue)}>
                    {parentValue.value}
                  </button>
                ) : (
                  <span>{parentValue.value}</span>
                )}
              </span>
            );
          })}
        </div>
      )
    );
  }
 
  function renderActiveValues() {
    return (
      <ul>
        {state.values.map((value) => (
          <li key={getUniqueKeyForValue(value)}>
            <button onClick={() => controller.toggleSelect(value)}>
              {value.value} ({value.numberOfResults}{' '}
              {value.numberOfResults === 1 ? 'result' : 'results'})
            </button>
          </li>
        ))}
      </ul>
    );
  }
 
  function renderCanShowMoreLess() {
    return (
      <div>
        {state.canShowLessValues && (
          <button onClick={() => controller.showLessValues()}>Show less</button>
        )}
        {state.canShowMoreValues && (
          <button onClick={() => controller.showMoreValues()}>Show more</button>
        )}
      </div>
    );
  }
 
  if (!state.hasActiveValues && state.values.length === 0) {
    return <div>No facet values</div>;
  }
 
  return (
    <ul>
      <li>{renderSearch()}</li>
      <li>
        {renderParents()}
        {renderActiveValues()}
        {renderCanShowMoreLess()}
      </li>
    </ul>
  );
};
 
// usage
 
/**
 * ```tsx
 * const options: CategoryFacetOptions = {field: 'geographicalhierarchy'};
 * const controller = buildCategoryFacet(engine, {options});
 *
 * <CategoryFacet controller={controller} />;
 * ```
 */

category-facet-search.tsx

import {
  CategoryFacetSearch as HeadlessCategoryFacetSearch,
  CategoryFacetSearchState,
} from '@coveo/headless';
import {FunctionComponent} from 'react';
 
export interface CategoryFacetSearchProps {
  controller: HeadlessCategoryFacetSearch;
  searchState: CategoryFacetSearchState;
}
 
export const CategoryFacetSearch: FunctionComponent<CategoryFacetSearchProps> = (
  props
) => {
  const onInput = (text: string) => {
    props.controller.updateText(text);
    props.controller.search();
  };
 
  return (
    <div>
      <input onInput={(e) => onInput(e.currentTarget.value)} />
      <ul>
        {props.searchState.values.map((value) => (
          <li key={[...value.path, value.rawValue].join('>')}>
            <button onClick={() => props.controller.select(value)}>
              {value.displayValue} ({value.count} results)
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
};