FacetManager (Search Engine)
FacetManager (Search Engine)
This is for:
DeveloperExample 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
-
facets:
FacetManagerPayload<T>[]
An array of facet payloads to sort.
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
Related Types
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;