-
-
Notifications
You must be signed in to change notification settings - Fork 229
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
wip: feat(search): match geographic entities within search
- Loading branch information
1 parent
3e70ab9
commit ab1d6c2
Showing
3 changed files
with
110 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { HitAttributeHighlightResult } from "instantsearch.js/es/types/results.js" | ||
import { IChartHit } from "./searchTypes.js" | ||
import { EntityName } from "@ourworldindata/types" | ||
|
||
const removeHighlightTags = (text: string) => | ||
text.replace(/<\/?(mark|strong)>/g, "") | ||
|
||
export function pickEntitiesForChartHit(hit: IChartHit): EntityName[] { | ||
const availableEntitiesHighlighted = hit._highlightResult | ||
?.availableEntities as HitAttributeHighlightResult[] | undefined | ||
|
||
const pickedEntities = availableEntitiesHighlighted | ||
?.filter((highlightEntry) => { | ||
// Keep the highlight if it is fully highlighted | ||
if (highlightEntry.fullyHighlighted) return true | ||
if (highlightEntry.matchLevel === "none") return false | ||
|
||
// Remove any trailing parentheses, e.g. "Africa (UN)" -> "Africa" | ||
const withoutTrailingParens = removeHighlightTags( | ||
highlightEntry.value | ||
).replace(/\s?\(.*\)$/, "") | ||
|
||
const matchedWordsLowerCase = highlightEntry.matchedWords.map( | ||
(mw) => mw.toLowerCase() | ||
) | ||
|
||
// Keep the highlight if every word (except for trailing parens) is fully highlighted | ||
// This will also highlight "Central African Republic" when searching for "african central republic", | ||
// but that's probably okay | ||
return withoutTrailingParens | ||
.toLowerCase() | ||
.split(" ") | ||
.every((w) => matchedWordsLowerCase.includes(w)) | ||
}) | ||
.map((highlightEntry) => removeHighlightTags(highlightEntry.value)) | ||
|
||
return pickedEntities ?? [] | ||
} |