Skip to content

Build your personal knowledge base with Trilium Notes

feat(snippets): preview snippet content as the fallback description

Elian Doran89c1af1fc91c
diff --git a/apps/client/src/widgets/type_widgets/text/snippets.spec.ts b/apps/client/src/widgets/type_widgets/text/snippets.spec.ts
index 15b425c03b..6e102761de 100644
--- a/apps/client/src/widgets/type_widgets/text/snippets.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/snippets.spec.ts
@@ -7,7 +7,7 @@ vi.mock("../../../services/search.js", () => ({
}));
import search from "../../../services/search.js";
-import getTemplates from "./snippets.js";
+import getTemplates, { buildContentPreview } from "./snippets.js";
const logErrorMock = vi.fn();
@@ -90,6 +90,24 @@ describe("getTemplates (text snippets)", () => {
}
});
+ it("falls back to a content preview when the note has no description label", async () => {
+ vi.mocked(search.searchForNotes).mockResolvedValue([
+ makeTextNote({ noteId: "plain", getContent: async () => "<p>Dear <b>Sir or Madam</b>,</p><p>I am writing to…</p>" }),
+ makeTextNote({
+ noteId: "labelled",
+ getLabelValue: (name) => (name === "snippetDescription" ? "own description" : null),
+ getContent: async () => "<p>content the label overrides</p>"
+ }),
+ makeTextNote({ noteId: "empty", getContent: async () => "<p> </p>" })
+ ]);
+
+ const definitions = await getTemplates();
+
+ // The user's own description always wins; empty content yields no description at all.
+ expect(definitions.map((definition) => definition.description))
+ .toEqual(["Dear Sir or Madam, I am writing to…", "own description", undefined]);
+ });
+
it("returns an empty list and logs when loading fails", async () => {
vi.mocked(search.searchForNotes).mockRejectedValue(new Error("boom"));
@@ -97,3 +115,30 @@ describe("getTemplates (text snippets)", () => {
expect(logErrorMock).toHaveBeenCalled();
});
});
+
+describe("buildContentPreview", () => {
+ it("strips markup, decodes entities and collapses whitespace", () => {
+ expect(buildContentPreview("<p>Dear <b>Sir&nbsp;or Madam</b>,</p>\n<p>hello</p>")).toBe("Dear Sir or Madam, hello");
+ });
+
+ it("returns undefined for missing, empty or markup-only content", () => {
+ expect(buildContentPreview(undefined)).toBeUndefined();
+ expect(buildContentPreview("")).toBeUndefined();
+ expect(buildContentPreview("<p> </p><br/>")).toBeUndefined();
+ });
+
+ it("truncates long content at a word boundary with an ellipsis", () => {
+ const preview = buildContentPreview(`<p>${"word ".repeat(40)}</p>`);
+
+ expect(preview?.endsWith("…")).toBe(true);
+ expect(preview?.length).toBeLessThanOrEqual(81);
+ // No mid-word cut: everything before the ellipsis is whole words.
+ expect(preview?.slice(0, -1).split(" ").every((part) => part === "word")).toBe(true);
+ });
+
+ it("hard-cuts a single giant word rather than returning nothing", () => {
+ const preview = buildContentPreview(`<p>${"a".repeat(200)}</p>`);
+
+ expect(preview).toBe(`${"a".repeat(80)}…`);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/snippets.ts b/apps/client/src/widgets/type_widgets/text/snippets.ts
index c7f3526239..c3c66b36ae 100644
--- a/apps/client/src/widgets/type_widgets/text/snippets.ts
+++ b/apps/client/src/widgets/type_widgets/text/snippets.ts
@@ -51,10 +51,13 @@ async function invalidateCacheFor(snippet: FNote) {
// Prefer the unified `snippetDescription`, falling back to the legacy `textSnippetDescription`
// so existing text snippets keep showing their description without any migration.
const description = snippet.getLabelValue("snippetDescription") ?? snippet.getLabelValue("textSnippetDescription");
+ const content = await snippet.getContent();
const data: TemplateData = {
title: snippet.title,
- description: description ?? undefined,
- content: await snippet.getContent()
+ // The user's own description always wins; without one, preview the snippet's content so
+ // the entry still reads as "this inserts that text" in the palette and the dropdown.
+ description: description ?? buildContentPreview(content),
+ content
};
templateCache.set(snippet.noteId, data);
return data;
@@ -76,13 +79,16 @@ async function handleContentUpdate(affectedNoteIds: string[], setTemplates: (val
continue;
}
- const newTitle = template.title;
- if (templateCache.get(affectedTemplateNoteId)?.title !== newTitle) {
+ const previous = templateCache.get(affectedTemplateNoteId);
+ const updated = await invalidateCacheFor(template);
+
+ // A changed title or description is baked into the definition list (unlike content,
+ // which stays live through the `data` getter), so the list must be rebuilt. Content
+ // edits land here too: without a user description they shift the derived preview.
+ if (previous?.title !== updated.title || previous?.description !== updated.description) {
fullReloadNeeded = true;
break;
}
-
- await invalidateCacheFor(template);
} catch (e) {
// If a note was not found while updating the cache, it means we need to do a full reload.
fullReloadNeeded = true;
@@ -94,13 +100,49 @@ async function handleContentUpdate(affectedNoteIds: string[], setTemplates: (val
}
}
+/** Longest content-derived description shown under a snippet's title. */
+const PREVIEW_MAX_LENGTH = 80;
+
+/**
+ * Derives a plain-text preview from a snippet's HTML content, used as the description when the
+ * note carries no `#snippetDescription` of its own. Returns `undefined` for empty content, so
+ * such snippets keep rendering without a description element.
+ */
+export function buildContentPreview(html: string | undefined): string | undefined {
+ if (!html) {
+ return undefined;
+ }
+
+ // Block boundaries carry an implicit line break that `textContent` drops, gluing paragraphs
+ // together ("<p>a</p><p>b</p>" → "ab"); turn them into spaces before parsing.
+ const withBreaks = html.replace(/<(?:br\b|\/(?:p|div|li|h[1-6]|blockquote|figcaption|pre|td|th|tr)\b)[^>]*>/gi, " ");
+ const text = (new DOMParser().parseFromString(withBreaks, "text/html").body.textContent ?? "")
+ .replace(/\s+/g, " ")
+ .trim();
+
+ if (!text) {
+ return undefined;
+ }
+
+ if (text.length <= PREVIEW_MAX_LENGTH) {
+ return text;
+ }
+
+ // Cut at the last word boundary that fits, unless the text is one giant word.
+ const cut = text.lastIndexOf(" ", PREVIEW_MAX_LENGTH);
+ return `${text.slice(0, cut > 0 ? cut : PREVIEW_MAX_LENGTH)}…`;
+}
+
export async function updateTemplateCache(loadResults: LoadResults, setTemplates: (value: SnippetDefinition[]) => void) {
const affectedNoteIds = loadResults.getNoteIds();
// React to creation or deletion of text snippets.
if (loadResults.getAttributeRows().find((attr) => {
if (attr.type === "label") {
- return (attr.name === "textSnippet" || attr.name === "textSnippetDescription");
+ // Both the unified `#snippet(Description)` labels and their legacy `#textSnippet`
+ // forms mark a note as a snippet, so all four must trigger a rebuild.
+ return (attr.name === "snippet" || attr.name === "snippetDescription"
+ || attr.name === "textSnippet" || attr.name === "textSnippetDescription");
} else if (attr.type === "relation") {
return (attr.value === "_template_text_snippet");
}