Search: improve layer search code

This commit is contained in:
Pieter Vander Vennet 2024-09-24 17:23:44 +02:00
parent 2db7ef872c
commit d1fed39fcb
2 changed files with 30 additions and 13 deletions

View file

@ -8,21 +8,27 @@ import { Utils } from "../../Utils"
export default class LayerSearch {
private readonly _layout: LayoutConfig
private readonly _layerWhitelist : Set<string>
private readonly _layerWhitelist: Set<string>
constructor(layout: LayoutConfig) {
this._layout = layout
this._layerWhitelist = new Set(layout.layers.map(l => l.id).filter(id => Constants.added_by_default.indexOf(<any> id) < 0))
this._layerWhitelist = new Set(layout.layers.map(l => l.id).filter(id => Constants.added_by_default.indexOf(<any>id) < 0))
}
static scoreLayers(query: string, layerWhitelist?: Set<string>): Record<string, number> {
static scoreLayers(query: string, options: {
whitelist?: Set<string>, blacklist?: Set<string>
}): Record<string, number> {
const result: Record<string, number> = {}
const queryParts = query.trim().split(" ").map(q => Utils.simplifyStringForSearch(q))
for (const id in ThemeSearch.officialThemes.layers) {
if(layerWhitelist !== undefined && !layerWhitelist.has(id)){
if (options?.whitelist && !options?.whitelist.has(id)) {
continue
}
if (options?.blacklist?.has(id)) {
continue
}
const keywords = ThemeSearch.officialThemes.layers[id]
const distance = Math.min(... queryParts.map(q => SearchUtils.scoreKeywords(q, keywords)))
const distance = Math.min(...queryParts.map(q => SearchUtils.scoreKeywords(q, keywords)))
result[id] = distance
}
return result
@ -34,11 +40,11 @@ export default class LayerSearch {
return []
}
const scores = LayerSearch.scoreLayers(query, this._layerWhitelist)
const asList:({layer: LayerConfig, score:number})[] = []
const asList: ({ layer: LayerConfig, score: number })[] = []
for (const layer in scores) {
asList.push({
layer: this._layout.getLayer(layer),
score: scores[layer]
score: scores[layer],
})
}
asList.sort((a, b) => a.score - b.score)