Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): update the share search some more to make ci happy

perfectra1n15e87ad58dbe
diff --git a/apps/server/src/share/routes.ts b/apps/server/src/share/routes.ts
index 5a6fab1550..be08f7530b 100644
--- a/apps/server/src/share/routes.ts
+++ b/apps/server/src/share/routes.ts
@@ -329,12 +329,15 @@ function register(router: Router) {
// Results beyond the cap are still returned, just without a snippet.
const SNIPPET_LIMIT = 20;
const snippetTargets = searchResults.slice(0, SNIPPET_LIMIT);
+ const { highlightedTokens } = searchContext;
for (const result of snippetTargets) {
- result.contentSnippet = searchService.extractContentSnippet(result.noteId, searchContext.highlightedTokens);
+ result.contentSnippet = searchService.extractContentSnippet(
+ result.noteId, highlightedTokens
+ );
}
// highlightSearchResults wraps matched tokens in <b>...</b> on highlightedContentSnippet.
// We pass ignoreInternalAttributes=true to match the share UX (no internal attrs).
- searchService.highlightSearchResults(snippetTargets, searchContext.highlightedTokens, true);
+ searchService.highlightSearchResults(snippetTargets, highlightedTokens, true);
const filteredResults = searchResults.map((sr) => {
const fullNote = shaca.notes[sr.noteId];
@@ -346,7 +349,7 @@ function register(router: Router) {
title: fullNote.title,
score: sr.score,
path: pathTitle,
- // Plain-text fallback and the <b>-highlighted variant produced by the search service.
+ // Plain-text fallback and the <b>-highlighted variant from the search service.
snippet: sr.contentSnippet,
highlightedSnippet: sr.highlightedContentSnippet
};
diff --git a/apps/website/.svelte-kit/tsconfig.json b/apps/website/.svelte-kit/tsconfig.json
new file mode 100644
index 0000000000..64aad0734b
--- /dev/null
+++ b/apps/website/.svelte-kit/tsconfig.json
@@ -0,0 +1,52 @@
+{
+ "compilerOptions": {
+ "paths": {
+ "$lib": [
+ "../src/lib"
+ ],
+ "$lib/*": [
+ "../src/lib/*"
+ ],
+ "$app/types": [
+ "./types/index.d.ts"
+ ]
+ },
+ "rootDirs": [
+ "..",
+ "./types"
+ ],
+ "verbatimModuleSyntax": true,
+ "isolatedModules": true,
+ "lib": [
+ "esnext",
+ "DOM",
+ "DOM.Iterable"
+ ],
+ "moduleResolution": "bundler",
+ "module": "esnext",
+ "noEmit": true,
+ "target": "esnext"
+ },
+ "include": [
+ "ambient.d.ts",
+ "non-ambient.d.ts",
+ "./types/**/$types.d.ts",
+ "../vite.config.js",
+ "../vite.config.ts",
+ "../src/**/*.js",
+ "../src/**/*.ts",
+ "../src/**/*.svelte",
+ "../tests/**/*.js",
+ "../tests/**/*.ts",
+ "../tests/**/*.svelte"
+ ],
+ "exclude": [
+ "../node_modules/**",
+ "../src/service-worker.js",
+ "../src/service-worker/**/*.js",
+ "../src/service-worker.ts",
+ "../src/service-worker/**/*.ts",
+ "../src/service-worker.d.ts",
+ "../src/service-worker/**/*.d.ts"
+ ]
+}
\ No newline at end of file
diff --git a/apps/website/.svelte-kit/types/route_meta_data.json b/apps/website/.svelte-kit/types/route_meta_data.json
new file mode 100644
index 0000000000..241b66a8b4
--- /dev/null
+++ b/apps/website/.svelte-kit/types/route_meta_data.json
@@ -0,0 +1,6 @@
+{
+ "/": [],
+ "/demo": [],
+ "/demo/paraglide": [],
+ "/download": []
+}
\ No newline at end of file
diff --git a/packages/share-theme/package.json b/packages/share-theme/package.json
index 1873f9138d..42297dcbb2 100644
--- a/packages/share-theme/package.json
+++ b/packages/share-theme/package.json
@@ -10,7 +10,7 @@
"build-scripts": "esrun scripts/build.ts -- --module=scripts",
"build-styles": "esrun scripts/build.ts -- --module=styles",
"dist": "esrun scripts/build.ts -- --minify",
- "test": "esrun src/scripts/test.ts"
+ "test": "vitest run"
},
"exports": {
"./templates/*": "./src/templates/*",
@@ -37,6 +37,7 @@
"esbuild": "0.28.0",
"eslint": "10.4.0",
"highlight.js": "11.11.1",
- "typescript": "6.0.3"
+ "typescript": "6.0.3",
+ "vitest": "4.1.7"
}
}
diff --git a/packages/share-theme/src/scripts/modules/search.spec.ts b/packages/share-theme/src/scripts/modules/search.spec.ts
new file mode 100644
index 0000000000..20faa546d6
--- /dev/null
+++ b/packages/share-theme/src/scripts/modules/search.spec.ts
@@ -0,0 +1,114 @@
+import type { FuseResultMatch } from "fuse.js";
+import { describe, expect, it } from "vitest";
+
+import { buildStaticSnippet, escapeHtml } from "./search.js";
+
+describe("escapeHtml", () => {
+ it("escapes the five HTML special characters", () => {
+ expect(escapeHtml("&")).toBe("&amp;");
+ expect(escapeHtml("<")).toBe("&lt;");
+ expect(escapeHtml(">")).toBe("&gt;");
+ expect(escapeHtml("\"")).toBe("&quot;");
+ expect(escapeHtml("'")).toBe("&#39;");
+ });
+
+ it("escapes every occurrence in a mixed string", () => {
+ expect(escapeHtml(`<script>alert("x & 'y'")</script>`))
+ .toBe("&lt;script&gt;alert(&quot;x &amp; &#39;y&#39;&quot;)&lt;/script&gt;");
+ });
+
+ it("returns the input unchanged when nothing needs escaping", () => {
+ expect(escapeHtml("just plain text 123")).toBe("just plain text 123");
+ expect(escapeHtml("")).toBe("");
+ });
+});
+
+describe("buildStaticSnippet", () => {
+ const contentMatch = (...indices: [number, number][]): FuseResultMatch => ({
+ key: "content",
+ indices
+ });
+
+ it("returns undefined for empty/missing content", () => {
+ expect(buildStaticSnippet(undefined, undefined)).toBeUndefined();
+ expect(buildStaticSnippet("", undefined)).toBeUndefined();
+ });
+
+ it("falls back to head-of-content preview when only title matched", () => {
+ const titleOnly: FuseResultMatch = { key: "title", indices: [ [ 0, 4 ] ] };
+ const result = buildStaticSnippet("hello world goodbye", [ titleOnly ]);
+ expect(result).toBe("hello world goodbye");
+ });
+
+ it("truncates the head preview with an ellipsis when content exceeds maxLength", () => {
+ const long = "a".repeat(200);
+ const result = buildStaticSnippet(long, undefined, 20);
+ // Trim then ellipsis suffix.
+ expect(result).toBe(`${"a".repeat(20)}…`);
+ });
+
+ it("returns undefined when the head preview would be all whitespace", () => {
+ expect(buildStaticSnippet(" \n\t ", undefined)).toBeUndefined();
+ });
+
+ it("wraps a single content match in <b>...</b>", () => {
+ // "magnesium" lives at indices [11, 19] in "Patient on magnesium drip, stable."
+ // (Fuse indices are inclusive on both ends.)
+ const content = "Patient on magnesium drip, stable.";
+ const result = buildStaticSnippet(content, [ contentMatch([ 11, 19 ]) ]);
+ expect(result).toBe("Patient on <b>magnesium</b> drip, stable.");
+ });
+
+ it("escapes HTML in both matched and surrounding text", () => {
+ // The '&' character sits at index 12 in this string; everything else must be escaped.
+ const content = "<em>hi</em> & 'world'";
+ const result = buildStaticSnippet(content, [ contentMatch([ 12, 12 ]) ]);
+ expect(result).toBe("&lt;em&gt;hi&lt;/em&gt; <b>&amp;</b> &#39;world&#39;");
+ });
+
+ it("wraps multiple match ranges and leaves the text between them untouched", () => {
+ // Match "foo" [0, 2] and "baz" [8, 10].
+ const result = buildStaticSnippet(
+ "foo bar baz",
+ [ contentMatch([ 0, 2 ], [ 8, 10 ]) ]
+ );
+ expect(result).toBe("<b>foo</b> bar <b>baz</b>");
+ });
+
+ it("prepends an ellipsis when the window is cut from the left of content", () => {
+ // 200 chars, match at position 180. With maxLength=40, window anchors to the right.
+ const before = "x".repeat(180);
+ const content = `${before}MATCH and tail`;
+ const result = buildStaticSnippet(content, [ contentMatch([ 180, 184 ]) ], 40);
+ expect(result).toMatch(/^…/);
+ expect(result).toContain("<b>MATCH</b>");
+ // Window ends at content.length, so no trailing ellipsis.
+ expect(result?.endsWith("…")).toBe(false);
+ });
+
+ it("appends an ellipsis when the window is cut from the right of content", () => {
+ // Match near the start of a long content.
+ const content = `FOO ${"y".repeat(200)}`;
+ const result = buildStaticSnippet(content, [ contentMatch([ 0, 2 ]) ], 40);
+ expect(result).toMatch(/^<b>FOO<\/b>/);
+ expect(result?.endsWith("…")).toBe(true);
+ });
+
+ it("clips a match range that straddles the window boundary", () => {
+ // maxLength=20 so window won't fit the whole match. Match at [0, 30] in a longer string.
+ const content = `${"A".repeat(31)} tail tail tail tail tail`;
+ const result = buildStaticSnippet(content, [ contentMatch([ 0, 30 ]) ], 20);
+ // The bolded portion is clipped to the window (20 A's), then ellipsis on the right.
+ expect(result).toMatch(/^<b>A+<\/b>…$/);
+ // Should not include all 31 A's — only the windowed slice.
+ const bolded = result!.match(/<b>(A+)<\/b>/)![1];
+ expect(bolded.length).toBeLessThanOrEqual(20);
+ });
+
+ it("ignores content matches with no indices", () => {
+ const emptyMatch: FuseResultMatch = { key: "content", indices: [] };
+ const result = buildStaticSnippet("abc def ghi", [ emptyMatch ]);
+ // No content match found, so falls through to head preview.
+ expect(result).toBe("abc def ghi");
+ });
+});
diff --git a/packages/share-theme/src/scripts/modules/search.ts b/packages/share-theme/src/scripts/modules/search.ts
index 83198ca4ea..f6336ee264 100644
--- a/packages/share-theme/src/scripts/modules/search.ts
+++ b/packages/share-theme/src/scripts/modules/search.ts
@@ -1,7 +1,7 @@
import debounce from "../common/debounce.js";
import parents from "../common/parents.js";
import parseHTML from "../common/parsehtml.js";
-import type { default as Fuse } from "fuse.js";
+import type { default as Fuse, FuseResultMatch } from "fuse.js";
let fuseInstance: Fuse<SearchResult> | null = null;
@@ -20,22 +20,25 @@ interface SearchResult {
highlightedSnippet?: string;
}
+const HTML_ESCAPE_MAP: Record<string, string> = {
+ "&": "&amp;",
+ "<": "&lt;",
+ ">": "&gt;",
+ "\"": "&quot;",
+ "'": "&#39;"
+};
+
/** Escape user-supplied/match text before injecting into innerHTML. */
-function escapeHtml(s: string): string {
- return s.replace(/[&<>"']/g, (c) => (
- c === "&" ? "&amp;" :
- c === "<" ? "&lt;" :
- c === ">" ? "&gt;" :
- c === "\"" ? "&quot;" :
- "&#39;"
- ));
+export function escapeHtml(s: string): string {
+ return s.replace(/[&<>"']/g, (c) => HTML_ESCAPE_MAP[c]);
}
function buildResultItem(result: SearchResult) {
// Prefer the server-rendered highlighted snippet (it only contains <b>/<br> tags that
// the search service inserts). For static (Fuse) mode we build a plain snippet below
// and the highlight pass wraps matched substrings in <b>.
- const snippetHtml = result.highlightedSnippet ?? (result.snippet ? escapeHtml(result.snippet) : "");
+ const snippetHtml = result.highlightedSnippet
+ ?? (result.snippet ? escapeHtml(result.snippet) : "");
const snippetBlock = snippetHtml
? `<div class="search-result-snippet">${snippetHtml}</div>`
: "";
@@ -50,39 +53,45 @@ function buildResultItem(result: SearchResult) {
* Build a content snippet around the first Fuse match for the static-export search index.
* Returns an HTML string with the matched ranges wrapped in <b>...</b>.
*/
-function buildStaticSnippet(content: string | undefined, matches: ReadonlyArray<{ key?: string; indices: ReadonlyArray<[number, number]>; }> | undefined, maxLength = 160): string | undefined {
+export function buildStaticSnippet(
+ content: string | undefined,
+ matches: ReadonlyArray<FuseResultMatch> | undefined,
+ maxLength = 160
+): string | undefined {
if (!content) return undefined;
- const contentMatch = matches?.find((m) => m.key === "content" && m.indices && m.indices.length > 0);
+ const contentMatch = matches?.find(
+ (m) => m.key === "content" && m.indices && m.indices.length > 0
+ );
if (!contentMatch) {
// No content match (e.g. matched only on title) — return a small head-of-content preview.
const head = content.slice(0, maxLength).trim();
- return head ? escapeHtml(head) + (content.length > maxLength ? "\u2026" : "") : undefined;
+ if (!head) return undefined;
+ return `${escapeHtml(head)}${content.length > maxLength ? "…" : ""}`;
}
// Centre the window on the first match and wrap every match-range that falls inside it.
- const [firstStart] = contentMatch.indices[0];
+ const [ firstStart ] = contentMatch.indices[0];
const half = Math.floor(maxLength / 2);
- let from = Math.max(0, firstStart - half);
- let to = Math.min(content.length, from + maxLength);
- // Re-extend left if we hit the right end early.
- from = Math.max(0, to - maxLength);
+ const to = Math.min(content.length, Math.max(0, firstStart - half) + maxLength);
+ // Anchor the window to the right edge when we hit the end of content.
+ const from = Math.max(0, to - maxLength);
// Build the snippet by walking the window and inserting <b>...</b> around any
// match-range that intersects it. Indices are inclusive on both ends per Fuse.
let out = "";
let cursor = from;
const ranges = contentMatch.indices
- .map(([s, e]) => [Math.max(s, from), Math.min(e + 1, to)] as [number, number])
- .filter(([s, e]) => e > s)
+ .map(([ s, e ]) => [ Math.max(s, from), Math.min(e + 1, to) ] as [number, number])
+ .filter(([ s, e ]) => e > s)
.sort((a, b) => a[0] - b[0]);
- for (const [s, e] of ranges) {
+ for (const [ s, e ] of ranges) {
if (s > cursor) out += escapeHtml(content.slice(cursor, s));
out += `<b>${escapeHtml(content.slice(s, e))}</b>`;
cursor = e;
}
if (cursor < to) out += escapeHtml(content.slice(cursor, to));
- return (from > 0 ? "\u2026" : "") + out + (to < content.length ? "\u2026" : "");
+ return `${from > 0 ? "…" : ""}${out}${to < content.length ? "…" : ""}`;
}
@@ -153,7 +162,8 @@ async function fetchResults(query: string): Promise<SearchResults> {
const results = fuseInstance.search(query, { limit: 5 });
console.debug("Search results:", results);
const processedResults = results.map(({ item, score, matches }) => {
- const highlightedSnippet = buildStaticSnippet((item as SearchResult & { content?: string }).content, matches as any);
+ const itemWithContent = item as SearchResult & { content?: string };
+ const highlightedSnippet = buildStaticSnippet(itemWithContent.content, matches);
return {
...item,
id: rootUrl + "/" + item.id,
diff --git a/packages/share-theme/vitest.config.ts b/packages/share-theme/vitest.config.ts
new file mode 100644
index 0000000000..3a5b305bc5
--- /dev/null
+++ b/packages/share-theme/vitest.config.ts
@@ -0,0 +1,7 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: [ "src/**/*.spec.ts" ]
+ }
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ded5a3ae86..48770e2fb3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1625,6 +1625,9 @@ importers:
typescript:
specifier: 6.0.3
version: 6.0.3
+ vitest:
+ specifier: 4.1.7
packages/splitjs:
devDependencies:
@@ -2503,7 +2506,7 @@ packages:
engines: {node: '>=14'}
'@electron/node-gyp@https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2':
- resolution: {gitHosted: true, integrity: sha512-MXgzlTDEEndJB3TBbvd5uFQO/8gaINo1Hfen8vef5rq/VHVPeB63uuv/uO5+8GFsAJ/rauu6XB79S6K4+aXc+w==, tarball: https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2}
+ resolution: {gitHosted: true, tarball: https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2}
version: 10.2.0-electron.1
engines: {node: '>=12.13.0'}
hasBin: true