UNPKG

@yext/search-headless

Version:

A library for powering UI components for Yext Search integrations

75 lines 2.83 kB
import { createSlice } from '@reduxjs/toolkit'; import isEqual from 'lodash/isEqual'; import { areStaticFiltersEqual } from '../utils/filter-utils'; export const initialState = {}; const reducers = { setStatic: (state, action) => { state.static = action.payload; }, setFacets: (state, action) => { state.facets = action.payload; }, resetFacets: (state) => { var _a; (_a = state.facets) === null || _a === void 0 ? void 0 : _a.forEach(facet => { facet.options.forEach(o => o.selected = false); }); }, setFacetOption: (state, { payload }) => { if (!state.facets) { console.warn('Trying to select a facet option when no facets exist.'); return; } const { fieldId, facetOption: optionToSelect, shouldSelect } = payload; const facetsWithFieldId = state.facets.filter(f => f.fieldId === fieldId); if (facetsWithFieldId.length === 0) { console.warn(`Could not select a facet option for fieldId "${fieldId}": the fieldId was not found.`); return; } facetsWithFieldId.forEach(facet => { // Mutating is OK because redux-toolkit uses the immer package facet.options = facet.options.map(o => { if (o.matcher !== optionToSelect.matcher || !isEqual(o.value, optionToSelect.value)) { return o; } return Object.assign(Object.assign({}, o), { selected: shouldSelect }); }); }); }, /** * Sets whether a static filter currently in the state is selected or unselected. * If the specified static filter should be selected, but is not in state, it will * be added to the state. */ setFilterOption: (state, { payload }) => { if (!state.static) { state.static = []; } const { selected, displayName: _, filter } = payload; const matchingFilter = state.static.find(storedFilter => { return areStaticFiltersEqual(storedFilter.filter, filter); }); if (matchingFilter) { matchingFilter.selected = selected; } else if (selected) { state.static.push(payload); } else { console.warn('Could not unselect a non-existing filter option in state ' + `with the following fields:\n${JSON.stringify(filter)}.`); } } }; /** * Registers with Redux the slice of {@link State} pertaining to filters. There are * reducers for setting the static filters and facet options. */ export default function createFiltersSlice(prefix) { return createSlice({ name: prefix + 'filters', initialState, reducers }); } //# sourceMappingURL=filters.js.map