Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(export/share): load search index once per page
Elian Doranf1f8f34ef8a2
diff --git a/packages/share-theme/package.json b/packages/share-theme/package.jsonindex 13dac7f025..9a6d36128f 100644--- a/packages/share-theme/package.json+++ b/packages/share-theme/package.json@@ -2,6 +2,7 @@"name": "@triliumnext/share-theme","version": "1.0.3","description": "Adaptation of the trilium.rocks share theme",+ "type": "module","main": "index.js","scripts": {"build": "esrun scripts/build.ts",diff --git a/packages/share-theme/src/scripts/modules/search.ts b/packages/share-theme/src/scripts/modules/search.tsindex 67bf0c22b6..a396cfaed8 100644--- a/packages/share-theme/src/scripts/modules/search.ts+++ b/packages/share-theme/src/scripts/modules/search.ts@@ -1,6 +1,9 @@import debounce from "../common/debounce";import parents from "../common/parents";import parseHTML from "../common/parsehtml";+import type { default as Fuse } from "fuse.js";++let fuseInstance: Fuse<SearchResult> | null = null;interface SearchResults {results: SearchResult[];@@ -61,25 +64,30 @@ export default function setupSearch() {}async function fetchResults(query: string): Promise<SearchResults> {+ const linkHref = document.head.querySelector("link[rel=stylesheet]")?.getAttribute("href");+ const rootUrl = linkHref?.split("/").slice(0, -2).join("/") || ".";+if ((window as any).glob.isStatic) {- const linkHref = document.head.querySelector("link[rel=stylesheet]")?.getAttribute("href");- const rootUrl = linkHref?.split("/").slice(0, -2).join("/") || ".";- const searchIndex = await (await fetch(`${rootUrl}/search-index.json`)).json();- const Fuse = (await import("fuse.js")).default;- const fuse = new Fuse(searchIndex, {- keys: [- "title",- "content"- ],- includeScore: true,- threshold: 0.65,- ignoreDiacritics: true,- ignoreLocation: true,- ignoreFieldNorm: true,- useExtendedSearch: true- });+ // Load the search index.+ if (!fuseInstance) {+ const searchIndex = await (await fetch(`${rootUrl}/search-index.json`)).json();+ const Fuse = (await import("fuse.js")).default;+ fuseInstance = new Fuse(searchIndex, {+ keys: [+ "title",+ "content"+ ],+ includeScore: true,+ threshold: 0.65,+ ignoreDiacritics: true,+ ignoreLocation: true,+ ignoreFieldNorm: true,+ useExtendedSearch: true+ });+ }- const results = fuse.search<SearchResult>(query, { limit: 5 });+ // Do the search.+ const results = fuseInstance.search(query, { limit: 5 });console.debug("Search results:", results);const processedResults = results.map(({ item, score }) => ({...item,