@empathyco/x-components
Version:
Empathy X Components
92 lines (89 loc) • 2.97 kB
JavaScript
import { isHierarchicalFilter } from '@empathyco/x-types';
import { addFacetIfNotPresent } from './add-facet-if-not-present.js';
/**
* Allows selecting and deselecting a filter of {@link @empathyco/x-types#HierarchicalFilter
* | HierarchicalFilter}.
*
* @internal
*/
class HierarchicalFilterEntity {
constructor(store) {
this.store = store;
}
/**
* Deselects the hierarchical filter and all of its descendants.
*
* @param filterParam - The filter to deselect.
*/
deselect(filterParam) {
const filter = filterParam;
this.saveFilter(filter, { selected: false });
this.deselectDescendants(filter);
addFacetIfNotPresent(this.store, filter.facetId, 'HierarchicalFacet');
}
/**
* Selects the hierarchical filter and its ancestors.
*
* @param filterParam - The filter to select.
*/
select(filterParam) {
const filter = filterParam;
this.saveFilter(filter, { selected: true });
this.selectAncestors(filter);
addFacetIfNotPresent(this.store, filter.facetId, 'HierarchicalFacet');
}
/**
* Deselects all the descendants of the given filter, saving them to the store.
*
* @remarks The descendants hierarchy is retrieved from the store.
* @param filter - The filter to deselect its descendants.
* @internal
*/
deselectDescendants(filter) {
if (filter.children) {
filter.children.forEach(child => {
this.saveFilter(child, { selected: false });
this.deselectDescendants(child);
});
}
}
/**
* Selects all the ancestors of the given filter, saving them to the store.
*
* @remarks The ancestors hierarchy is retrieved from the store.
* @param filter - The filter to select its ancestors.
* @internal
*/
selectAncestors(filter) {
if (filter.parentId) {
const parent = this.getFilterById(filter.parentId);
if (parent) {
this.saveFilter(parent, { selected: true });
this.selectAncestors(parent);
}
}
}
/**
* Retrieves a hierarchical filter from the store by its id.
*
* @param id - The id of the filter to retrieve.
* @returns The hierarchical filter retrieved from the store.
* @internal
*/
getFilterById(id) {
return this.store.state.x.facets.filters[id];
}
/**
* Saves the given filter to the store.
*
* @param filter - The filter to save to the store.
* @param newFilterState - The new partial state of the filter.
* @internal
*/
saveFilter(filter, newFilterState = {}) {
this.store.commit('x/facets/mutateFilter', { filter, newFilterState });
}
}
HierarchicalFilterEntity.accepts = isHierarchicalFilter;
export { HierarchicalFilterEntity };
//# sourceMappingURL=hierarchical-filter.entity.js.map