Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve search #1161

Merged
merged 1 commit into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/documentation/search/extracts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,14 @@ describe("contextExtracts", () => {
// Previous bug was an empty match here.
]);
});
it("returns the first sentence without matches if no positions are provided", () => {
expect(contextExtracts([], "First sentence. Second sentence.")).toEqual([
{
type: "text",
extract: "First sentence.",
},
]);
});
});

describe("sortByStart", () => {
Expand Down
9 changes: 8 additions & 1 deletion src/documentation/search/extracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,14 @@ export const contextExtracts = (
text: string
): Extract[] => {
if (positions.length === 0) {
return [];
// Fallback if only text in the title (or id for Reference section) is matched.
const end = forward(text, 1);
return [
{
type: "text",
extract: text.slice(0, end + 1),
},
];
}
// Find the text around the first match.
// Highlight all positions within it.
Expand Down
11 changes: 10 additions & 1 deletion src/documentation/search/search.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ const getExtracts = (

return {
title: fullStringExtracts(allTitlePositions, content.title),
// TODO: consider a fallback if only text in the title is matched.
content: contextExtracts(allContentPositions, content.content),
};
};
Expand Down Expand Up @@ -234,6 +233,16 @@ export const buildSearchIndex = (
let customTokenizer: TokenizerFunction | undefined;
const index = lunr(function () {
this.ref("id");
this.field("id", {
boost: 10,
extractor: (doc: object) => {
// Ensure we match a search query like 'microbit.display.scroll' or 'display.scroll'
// to the correct API section.
return `${(doc as SearchableContent).id} ${(
doc as SearchableContent
).id.replaceAll("microbit.", "")}`;
},
});
this.field("title", { boost: 10 });
this.field("content");
this.use(languagePlugin);
Expand Down
Loading