Skip to content

Commit

Permalink
Improve search
Browse files Browse the repository at this point in the history
Searches like "display.scroll" will now return the relevant API section in the results.
  • Loading branch information
microbit-robert committed Mar 27, 2024
1 parent a6346c4 commit 384bf06
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
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 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

0 comments on commit 384bf06

Please sign in to comment.