UNPKG

@gouvfr/dsfr-roller

Version:

Le module `dsfr-roller` permet de publier le site de documentation du Système de Design de l’État - DSFR

54 lines (44 loc) 1.61 kB
import MiniSearch from 'minisearch'; import { normalizeTerm } from '@gouvfr/dsfr-kit'; const ROOT_REGEX = /^(?<root>\/(?<version>v\d+\.\d+|[\w-]+)\/(?<locale>[a-zA-Z-]+))/; class FilterEngine { async init (type) { const response = await fetch(this.getFilterIndex(type)); this._documentJSON = await response.json(); this._document = JSON.stringify(this._documentJSON); this._miniSearch = MiniSearch.loadJSON(this._document, {fields: this.getFields(), storeFields: this.getFields()}); } getFilterIndex = (type) => { const { groups: { root, version, locale } } = window.location.pathname.match(ROOT_REGEX); return `${root}/${type}.json`; } getFields = () => { const fields = Object.keys(this._documentJSON.fieldIds || {}); return fields; } getOptions = (filter = null) => { const options = { prefix: true, fuzzy: 0.1, processTerm: (term) => normalizeTerm(term.toLowerCase()), tokenize: (string) => string.split(/\s+/) }; if (filter) { options.filter = (result) => { return Object.entries(filter).every(([key, value]) => result[key] === value); }; } return options; } search (query, filter) { if (query === '' || query == null || query.trim().length === 0) { return Object.values(this._documentJSON.storedFields).filter(result => { return Object.entries(filter).every(([key, value]) => result[key] === value); }); } else { const results = this._miniSearch.search(query, this.getOptions(filter)); return results; } } } export { FilterEngine };