Skip to content

Commit

Permalink
Fixed search link when update to Docusaurus 3.4.0 (#410)
Browse files Browse the repository at this point in the history
fix: handle hash link with url path, closes #408

---------

Co-authored-by: AnonID <[email protected]>
Co-authored-by: weareoutman <[email protected]>
  • Loading branch information
3 people authored Jun 4, 2024
1 parent c5b1c29 commit 408e08f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
25 changes: 25 additions & 0 deletions docusaurus-search-local/src/server/utils/scanDocuments.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,16 @@ describe("scanDocuments", () => {
hash: "",
content: "",
},
{
title: "Second heading",
hash: "/2#second-heading",
content: "Second content.",
},
{
title: "Third heading",
hash: "/3#third-heading",
content: "Third content.",
},
],
breadcrumb: [],
};
Expand Down Expand Up @@ -106,6 +116,13 @@ describe("scanDocuments", () => {
"t": "First heading",
"u": "/1",
},
Object {
"h": "#second-heading",
"i": 6,
"p": 5,
"t": "Second heading",
"u": "/2",
},
],
Array [
Object {
Expand Down Expand Up @@ -142,6 +159,14 @@ describe("scanDocuments", () => {
"t": "First content.",
"u": "/1",
},
Object {
"h": "#second-heading",
"i": 7,
"p": 5,
"s": "Second heading",
"t": "Second content.",
"u": "/2",
},
],
]
`);
Expand Down
29 changes: 27 additions & 2 deletions docusaurus-search-local/src/server/utils/scanDocuments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,23 +81,33 @@ export async function scanDocuments(
}

for (const section of sections) {
const trimmedHash = getTrimmedHash(section.hash, url);

if (section.title !== pageTitle) {
if (trimmedHash === false) {
continue;
}

headingDocuments.push({
i: getNextDocId(),
t: section.title,
u: url,
h: section.hash,
h: trimmedHash,
p: titleId,
});
}

if (section.content) {
if (trimmedHash === false) {
continue;
}

contentDocuments.push({
i: getNextDocId(),
t: section.content,
s: section.title || pageTitle,
u: url,
h: section.hash,
h: trimmedHash,
p: titleId,
});
}
Expand All @@ -106,3 +116,18 @@ export async function scanDocuments(
);
return allDocuments;
}

function getTrimmedHash(hash: string, url: string) {
if (hash && !hash.startsWith("#") && hash.includes("#")) {
// The hash link may contains URL path, we need to remove it.
if (hash.startsWith(url) && hash[url.length] === "#") {
return hash.slice(url.length);
}

// If the hash doesn't start with the URL, it's likely an external link.
// Don't know this will happen or not, but just in case.
return false;
}

return hash;
}

0 comments on commit 408e08f

Please sign in to comment.