Skip to content

Commit

Permalink
fix(core): expose matched indices on array fields in search hit stories
Browse files Browse the repository at this point in the history
  • Loading branch information
robinpyon committed Jun 20, 2023
1 parent c7f78db commit ffd36c1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/@sanity/base/src/search/weighted/applyWeights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ export function applyWeights(
const typeSpec = specByType[hit._type]
const stories = typeSpec.paths.map((pathSpec, idx) => {
const pathHit = hit[`w${idx}`]
const indices = Array.isArray(pathHit) ? findMatchingIndices(terms, pathHit) : null
// Only stringify non-falsy values so null values don't pollute search
const value = pathHit ? stringify(pathHit) : null
if (!value) {
return {path: pathSpec.path, score: 0, why: 'No match'}
}
const [score, why] = calculateScore(terms, value)
return {
indices,
path: pathSpec.path,
score: score * pathSpec.weight,
why: `${why} (*${pathSpec.weight})`,
Expand Down Expand Up @@ -149,6 +151,26 @@ export function partitionAndSanitizeSearchTerms(
}
}

export function findMatchingIndices(uniqueSearchTerms: string[], values: unknown[]): number[] {
// Separate search terms by phrases (wrapped with quotes) and words.
const {phrases: uniqueSearchPhrases, words: uniqueSearchWords} = partitionAndSanitizeSearchTerms(
uniqueSearchTerms
)

return values.reduce<number[]>((acc, val, index) => {
if (val) {
const contains = [...uniqueSearchPhrases, ...uniqueSearchWords].some((term) => {
const stringifiedValue = stringify(val).toLowerCase().trim()
return stringifiedValue.includes(term)
})
if (contains) {
acc.push(index)
}
}
return acc
}, [])
}

function stripWrappingQuotes(str: string) {
return str.replace(/^"(.*)"$/, '$1')
}
1 change: 1 addition & 0 deletions packages/@sanity/base/src/search/weighted/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export interface SearchHit {
* @internal
*/
export interface SearchStory {
indices?: number[]
path: string
score: number
why: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ export function DebugOverlay({data}: DebugScoreProps) {
<Code size={0} weight="semibold">
{story.path}
</Code>
{!!story.indices?.length && (
<Code size={0}>{JSON.stringify(story.indices)}</Code>
)}
<Code size={0}>{story.why}</Code>
</Inline>
))}
Expand Down

0 comments on commit ffd36c1

Please sign in to comment.