FacetManager (Search Engine)

This is for:

Developer

Example Implementation

facet-manager.fn.tsx

import {
  FacetManager as HeadlessFacetManager,
  Facet as HeadlessFacet,
  FacetManagerPayload,
} from '@coveo/headless';
import {
  useEffect,
  useState,
  FunctionComponent,
  ReactElement,
  Children,
} from 'react';
 
type FacetManagerChild = ReactElement<{controller: HeadlessFacet}>;
 
interface FacetManagerProps {
  controller: HeadlessFacetManager;
  children: FacetManagerChild | FacetManagerChild[];
}
 
export const FacetManager: FunctionComponent<FacetManagerProps> = (props) => {
  const {controller} = props;
  const [, setState] = useState(controller.state);
 
  useEffect(() => controller.subscribe(() => setState(controller.state)), []);
 
  function createPayload(
    facets: FacetManagerChild[]
  ): FacetManagerPayload<FacetManagerChild>[] {
    return facets.map((facet) => ({
      facetId: facet.props.controller.state.facetId,
      payload: facet,
    }));
  }
 
  const childFacets = Children.toArray(props.children) as FacetManagerChild[];
  const payload = createPayload(childFacets);
  const sortedFacets = controller.sort(payload).map((p) => p.payload);
 
  return <div>{sortedFacets}</div>;
};
 
// usage
 
/**
 * ```tsx
 * const facetManager = buildFacetManager(engine);
 * const facetA = buildFacet(engine, {options: {field: 'abc'}});
 * const facetB = buildFacet(engine, {options: {field: 'def'}});
 *
 * <FacetManager controller={facetManager}>
 *   <Facet controller={facetA} />
 *   <Facet controller={facetB} />
 * </FacetManager>
 * ```
 */

The FacetManager controller helps reorder facets to match the most recent search response.

Methods

sort

Sorts the facets to match the order in the most recent search response.

Parameters

Returns FacetManagerPayload<T>[]: A sorted array.

subscribe

Adds a callback that’s invoked on state change.

Parameters

  • listener: () => void

    A callback that’s invoked on state change.

Returns Unsubscribe: A function to remove the listener.

Attributes

state

The state of the CoreFacetManager controller.

Properties

  • facetIds: string[]

    The facet ids sorted in the same order as the latest response.

Initialize

buildFacetManager

Creates a FacetManager instance.

Parameters

  • engine: SearchEngine

    The headless engine.

Returns FacetManager

FacetManagerPayload<T>

Properties

  • facetId: string

    A unique string identifying a facet.

  • payload: T

    The payload to associate with the facetId. This can be anything e.g., a DOM element, JSX, a string.

Unsubscribe

Call signatures

  • (): void;