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
perf(client): resolve the "new" template badges in a single request
Elian Doran7f2dcf84835d
diff --git a/apps/client/src/menus/tree_context_menu.ts b/apps/client/src/menus/tree_context_menu.tsindex c4cc587b5d..c1a4914fcd 100644--- a/apps/client/src/menus/tree_context_menu.ts+++ b/apps/client/src/menus/tree_context_menu.ts@@ -127,6 +127,12 @@ export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Prconst parentNotSearch = !parentNote || parentNote.type !== "search";const insertNoteAfterEnabled = isNotRoot && !isHoisted && parentNotSearch;+ // Both submenus hit the server, so they are resolved together rather than one after the other.+ const [ insertNoteAfterItems, insertChildNoteItems ] = await Promise.all([+ insertNoteAfterEnabled ? noteTypesService.getNoteTypeItems("insertNoteAfter") : null,+ notSearch ? noteTypesService.getNoteTypeItems("insertChildNote") : null+ ]);+const items: (MenuItem<TreeCommandNames> | null)[] = [{ title: t("tree-context-menu.open-in-a-new-tab"), command: "openInTab", shortcut: "Ctrl+Click", uiIcon: "bx bx-link-external", enabled: noSelectedNotes },{ title: t("tree-context-menu.open-in-a-new-split"), command: "openNoteInSplit", uiIcon: "bx bx-dock-right", enabled: noSelectedNotes },@@ -153,7 +159,7 @@ export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Prcommand: "insertNoteAfter",keyboardShortcut: "createNoteAfter",uiIcon: "bx bx-plus",- items: insertNoteAfterEnabled ? await noteTypesService.getNoteTypeItems("insertNoteAfter") : null,+ items: insertNoteAfterItems,enabled: insertNoteAfterEnabled && noSelectedNotes && notOptionsOrHelp,columns: 2},@@ -163,7 +169,7 @@ export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Prcommand: "insertChildNote",keyboardShortcut: "createNoteInto",uiIcon: "bx bx-plus",- items: notSearch ? await noteTypesService.getNoteTypeItems("insertChildNote") : null,+ items: insertChildNoteItems,enabled: notSearch && noSelectedNotes && notOptionsOrHelp && !hasSubtreeHidden && !isSpotlighted,columns: 2},diff --git a/apps/client/src/services/note_types.spec.ts b/apps/client/src/services/note_types.spec.tsindex 4810c04ede..05bb45f045 100644--- a/apps/client/src/services/note_types.spec.ts+++ b/apps/client/src/services/note_types.spec.ts@@ -44,6 +44,16 @@ function fakeTemplate(noteId: string, labels: string[], title = noteId): FakeNot};}+/** Stubs `search-templates`, the only endpoint the service talks to. */+function withTemplates(templateNoteIds: string[] = [], newTemplateNoteIds: string[] = []) {+ const get = vi.fn(async (url: string) => {+ if (url === "search-templates") return { templateNoteIds, newTemplateNoteIds };+ return undefined;+ });+ server.get = get as unknown as typeof server.get;+ return get;+}+function withTemplatesRoot(children: FakeNote[] | null) {const realGetNote = froca.getNote.bind(froca);froca.getNote = (async (noteId: string, silent?: boolean) => {@@ -68,10 +78,7 @@ describe("getBlankNoteTypes (via getNoteTypeItems)", () => {vi.clearAllMocks();llmFlag.mockReturnValue(false);// Empty templates root and no user templates so we only see blank types.- server.get = vi.fn(async (url: string) => {- if (url === "search-templates") return [];- return undefined;- }) as typeof server.get;+ withTemplates();});it("excludes reserved types, book, and llmChat (when feature disabled), and maps icons/badges", async () => {@@ -147,17 +154,8 @@ describe("getBuiltInTemplates", () => {beforeEach(() => {vi.clearAllMocks();llmFlag.mockReturnValue(false);- server.get = vi.fn(async (url: string) => {- if (url === "search-templates") return [];- // notes/root returns an object WITHOUT dateCreated: exercises the- // `"dateCreated" in rootNoteInfo` false branch AND keeps the module-level- // rootCreationDate undefined for the following tests.- if (url === "notes/root") return { id: "root" };- // A recent built-in template ("tpl-plain") gets the "new" badge; everything- // else is old.- if (url === "notes/tpl-plain") return { dateCreated: new Date().toISOString() };- return { dateCreated: "2000-01-02 00:00:00.000Z" };- }) as typeof server.get;+ // The server reports "tpl-plain" as a new built-in template; everything else is old.+ withTemplates([], ["tpl-plain"]);});it("warns and returns nothing when the templates root is missing", async () => {@@ -230,7 +228,7 @@ describe("getBuiltInTemplates", () => {expect(plainItem.command).toBe("cmd");expect(plainItem.type).toBe("text");expect(plainItem.uiIcon).toBe("tn-icon bx-x");- // tpl-plain has a recent creation date -> gets the "new" badge.+ // tpl-plain is reported as new by the server -> gets the "new" badge.expect(plainItem.badges).toHaveLength(1);expect(plainItem.badges[0].className).toBe("new-note-type-badge");// The old collection template is not marked new.@@ -249,10 +247,7 @@ describe("getUserTemplates", () => {});it("returns nothing when there are no user template notes", async () => {- server.get = vi.fn(async (url: string) => {- if (url === "search-templates") return [];- return undefined;- }) as typeof server.get;+ withTemplates();const restore = withTemplatesRoot([]);try {const items: any[] = await noteTypesService.getNoteTypeItems();@@ -265,12 +260,8 @@ describe("getUserTemplates", () => {it("adds a header and one item per user template, mapping note fields", async () => {const userTpl = buildNote({ title: "My Template", type: "text" });- server.get = vi.fn(async (url: string) => {- if (url === "search-templates") return [userTpl.noteId];- if (url === "notes/root") throw new Error("no root");- // Old creation date -> not "new".- return { dateCreated: "2000-01-02 00:00:00.000Z" };- }) as typeof server.get;+ // The template is not among the new ones -> no badge.+ withTemplates([userTpl.noteId]);const restore = withTemplatesRoot([]);try {const items: any[] = await noteTypesService.getNoteTypeItems("cmd2" as never);@@ -289,134 +280,30 @@ describe("getUserTemplates", () => {});});-describe("isNewTemplate (via getUserTemplates)", () => {+describe("new template badges", () => {beforeEach(() => {vi.clearAllMocks();llmFlag.mockReturnValue(false);});- async function runWithTemplate(noteId: string, getImpl: (url: string) => Promise<unknown>) {- const tpl = buildNote({ id: noteId, title: noteId, type: "text" });- server.get = vi.fn(getImpl) as typeof server.get;+ it("badges exactly the templates the server reports as new", async () => {+ const isNew = buildNote({ id: "tpl-new", title: "New template", type: "text" });+ const isOld = buildNote({ id: "tpl-old", title: "Old template", type: "text" });+ const get = withTemplates([isNew.noteId, isOld.noteId], [isNew.noteId]);const restore = withTemplatesRoot([]);try {const items: any[] = await noteTypesService.getNoteTypeItems();- return items.find((i) => i.templateNoteId === tpl.noteId);- } finally {- restore();- }- }-- // NOTE on ordering: the module caches `rootCreationDate` on the FIRST successful- // `notes/root` fetch and never resets it. To keep it `undefined` for the- // age-based-branch tests, those tests make `notes/root` throw (a throw is caught,- // leaving the date unset). The single test that sets a real root date — the "30s"- // test — runs LAST so it cannot pollute the others.-- it("tolerates a failing notes/root fetch (root date stays unknown) and marks a recent template as new", async () => {- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- const recent = new Date().toISOString();- // notes/root throws -> caught, rootCreationDate stays undefined; template fetched- // with a recent date and no root date -> age check applies -> new badge.- const item = await runWithTemplate("isnew-recent-1", async (url) => {- if (url === "search-templates") return ["isnew-recent-1"];- if (url === "notes/root") throw new Error("boom");- return { dateCreated: recent };- });- expect(item.badges).toHaveLength(1);- expect(item.badges[0].className).toBe("new-note-type-badge");- expect(errorSpy).toHaveBeenCalled();- errorSpy.mockRestore();- });-- it("does not mark an old template as new (age check returns false)", async () => {- // root fetch throws -> rootCreationDate undefined -> skips 30s check, reaches age check.- const item = await runWithTemplate("isnew-old", async (url) => {- if (url === "search-templates") return ["isnew-old"];- if (url === "notes/root") throw new Error("no root");- return { dateCreated: "1999-06-01 00:00:00.000Z" };- });- expect(item.badges).toBeUndefined();- });- it("returns no badge when the note fetch fails (creation date stays unknown)", async () => {- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- // Template note fetch throws -> creationDate stays undefined -> returns false (no badge).- const item = await runWithTemplate("isnew-nodate", async (url) => {- if (url === "search-templates") return ["isnew-nodate"];- if (url === "notes/root") throw new Error("no root");- throw new Error("note fetch failed");- });- expect(item.badges).toBeUndefined();- expect(errorSpy).toHaveBeenCalled();- errorSpy.mockRestore();- });+ const newItem = items.find((i) => i.templateNoteId === isNew.noteId);+ expect(newItem.badges).toHaveLength(1);+ expect(newItem.badges[0].className).toBe("new-note-type-badge");- it("returns no badge when the note response has no dateCreated field", async () => {- // notes/<id> returns an object without dateCreated -> creationDate stays- // undefined -> returns false. Exercises the `"dateCreated" in noteInfo` false branch.- const item = await runWithTemplate("isnew-nofield", async (url) => {- if (url === "search-templates") return ["isnew-nofield"];- if (url === "notes/root") throw new Error("no root");- return { id: "isnew-nofield" };- });- expect(item.badges).toBeUndefined();- });+ const oldItem = items.find((i) => i.templateNoteId === isOld.noteId);+ expect(oldItem.badges).toBeUndefined();- it("uses the cached creation date on a second lookup (no second notes/<id> fetch)", async () => {- const recent = new Date().toISOString();- const getImpl = vi.fn(async (url: string) => {- if (url === "search-templates") return ["isnew-cached"];- if (url === "notes/root") throw new Error("no root");- return { dateCreated: recent };- });- buildNote({ id: "isnew-cached", title: "isnew-cached", type: "text" });- server.get = getImpl as unknown as typeof server.get;- const restore = withTemplatesRoot([]);- try {- await noteTypesService.getNoteTypeItems();- const callsAfterFirst = getImpl.mock.calls.filter((c) => c[0] === "notes/isnew-cached").length;- await noteTypesService.getNoteTypeItems();- const callsAfterSecond = getImpl.mock.calls.filter((c) => c[0] === "notes/isnew-cached").length;- // The per-note creation date is cached, so it is fetched at most once.- expect(callsAfterFirst).toBe(1);- expect(callsAfterSecond).toBe(1);- } finally {- restore();- }- });-- // MUST run before the "cached root date" test below: this is the only test that- // lets `notes/root` resolve, which permanently caches `rootCreationDate` in the module.- it("ignores templates created within 30s of the root note (no new badge)", async () => {- const root = new Date();- const justAfterRoot = new Date(root.getTime() + 10_000).toISOString();- const item = await runWithTemplate("isnew-near-root", async (url) => {- if (url === "search-templates") return ["isnew-near-root"];- if (url === "notes/root") return { dateCreated: root.toISOString() };- return { dateCreated: justAfterRoot };- });- expect(item.badges).toBeUndefined();- });-- // MUST be last: relies on `rootCreationDate` already being cached by the test above.- it("does not re-fetch notes/root once the root creation date is cached", async () => {- const getImpl = vi.fn(async (url: string) => {- if (url === "search-templates") return ["isnew-after-cached"];- // notes/root must NOT be requested anymore; if it were, this would throw.- if (url === "notes/root") throw new Error("root should not be fetched again");- return { dateCreated: "1999-06-01 00:00:00.000Z" };- });- buildNote({ id: "isnew-after-cached", title: "isnew-after-cached", type: "text" });- server.get = getImpl as unknown as typeof server.get;- const restore = withTemplatesRoot([]);- try {- const items: any[] = await noteTypesService.getNoteTypeItems();- const item = items.find((i) => i.templateNoteId === "isnew-after-cached");- // Old template -> not new regardless.- expect(item.badges).toBeUndefined();- // The cached root date means notes/root is never requested.- expect(getImpl.mock.calls.some((c) => c[0] === "notes/root")).toBe(false);+ // The badges cost no request of their own: `search-templates` is the only+ // endpoint hit, no matter how many templates there are.+ expect(get.mock.calls.map((c) => c[0])).toEqual(["search-templates"]);} finally {restore();}diff --git a/apps/client/src/services/note_types.ts b/apps/client/src/services/note_types.tsindex 3ba92aee1f..721a766ee9 100644--- a/apps/client/src/services/note_types.ts+++ b/apps/client/src/services/note_types.ts@@ -1,3 +1,6 @@+import type { TemplatesResponse } from "@triliumnext/commons";++import type FNote from "../entities/fnote.js";import type { NoteType } from "../entities/fnote.js";import type { MenuCommandItem, MenuItem, MenuItemBadge, MenuSeparatorItem } from "../menus/context_menu.js";import type { TreeCommandNames } from "../menus/tree_context_menu.js";@@ -59,12 +62,6 @@ export const NOTE_TYPES: NoteTypeMapping[] = [{ type: "launcher", mime: "", title: t("note_types.launcher"), reserved: true },];-/** The maximum age in days for a template to be marked with the "New" badge */-const NEW_TEMPLATE_MAX_AGE = 3;--/** The length of a day in milliseconds. */-const DAY_LENGTH = 1000 * 60 * 60 * 24;-/** The menu item badge used to mark new note types and templates */const NEW_BADGE: MenuItemBadge = {title: t("note_types.new-feature"),@@ -78,15 +75,22 @@ const BETA_BADGE = {const SEPARATOR: MenuSeparatorItem = { kind: "separator" };-const creationDateCache = new Map<string, Date>();-let rootCreationDate: Date | undefined;-async function getNoteTypeItems(command?: TreeCommandNames) {+ // A single request reports both the user templates and which templates are new, so that the+ // menu can be assembled without a round trip per template.+ const { templateNoteIds, newTemplateNoteIds } = await server.get<TemplatesResponse>("search-templates");+ const newTemplates = new Set(newTemplateNoteIds);++ const [ builtInTemplateNotes, userTemplateNotes ] = await Promise.all([+ getBuiltInTemplateNotes(),+ froca.getNotes(templateNoteIds)+ ]);+const items: MenuItem<TreeCommandNames>[] = [...getBlankNoteTypes(command),- ...await getBuiltInTemplates(null, command, false),- ...await getBuiltInTemplates(t("note_types.collections"), command, true),- ...await getUserTemplates(command)+ ...getBuiltInTemplates(null, command, builtInTemplateNotes, false, newTemplates),+ ...getBuiltInTemplates(t("note_types.collections"), command, builtInTemplateNotes, true, newTemplates),+ ...getUserTemplates(command, userTemplateNotes, newTemplates)];return items;@@ -118,9 +122,7 @@ function getBlankNoteTypes(command?: TreeCommandNames): MenuItem<TreeCommandName});}-async function getUserTemplates(command?: TreeCommandNames) {- const templateNoteIds = await server.get<string[]>("search-templates");- const templateNotes = await froca.getNotes(templateNoteIds);+function getUserTemplates(command: TreeCommandNames | undefined, templateNotes: FNote[], newTemplates: Set<string>) {if (templateNotes.length === 0) {return [];}@@ -141,7 +143,7 @@ async function getUserTemplates(command?: TreeCommandNames) {templateNoteId: templateNote.noteId};- if (await isNewTemplate(templateNote.noteId)) {+ if (newTemplates.has(templateNote.noteId)) {item.badges = [NEW_BADGE];}@@ -150,14 +152,17 @@ async function getUserTemplates(command?: TreeCommandNames) {return items;}-async function getBuiltInTemplates(title: string | null, command: TreeCommandNames | undefined, filterCollections: boolean) {+async function getBuiltInTemplateNotes() {const templatesRoot = await froca.getNote("_templates");if (!templatesRoot) {console.warn("Unable to find template root.");return [];}- const childNotes = await templatesRoot.getChildNotes();+ return await templatesRoot.getChildNotes();+}++function getBuiltInTemplates(title: string | null, command: TreeCommandNames | undefined, childNotes: FNote[], filterCollections: boolean, newTemplates: Set<string>) {if (childNotes.length === 0) {return [];}@@ -187,7 +192,7 @@ async function getBuiltInTemplates(title: string | null, command: TreeCommandNam};const badges: MenuItemBadge[] = [];- if (await isNewTemplate(templateNote.noteId)) {+ if (newTemplates.has(templateNote.noteId)) {badges.push(NEW_BADGE);}if (templateNote.hasLabel("beta")) {@@ -202,51 +207,6 @@ async function getBuiltInTemplates(title: string | null, command: TreeCommandNamreturn items;}-async function isNewTemplate(templateNoteId) {- if (rootCreationDate === undefined) {- // Retrieve the root note creation date- try {- const rootNoteInfo: any = await server.get("notes/root");- if ("dateCreated" in rootNoteInfo) {- rootCreationDate = new Date(rootNoteInfo.dateCreated);- }- } catch (ex) {- console.error(ex);- }- }-- // Try to retrieve the template's creation date from the cache- let creationDate: Date | undefined = creationDateCache.get(templateNoteId);-- if (creationDate === undefined) {- // The creation date isn't available in the cache, try to retrieve it from the server- try {- const noteInfo: any = await server.get(`notes/${templateNoteId}`);- if ("dateCreated" in noteInfo) {- creationDate = new Date(noteInfo.dateCreated);- creationDateCache.set(templateNoteId, creationDate);- }- } catch (ex) {- console.error(ex);- }- }-- if (creationDate) {- if (rootCreationDate && creationDate.getTime() - rootCreationDate.getTime() < 30000) {- // Ignore templates created within 30 seconds after the root note is created.- // This is useful to prevent predefined templates from being marked- // as 'New' after setting up a new database.- return false;- }-- // Determine the difference in days between now and the template's creation date- const age = (new Date().getTime() - creationDate.getTime()) / DAY_LENGTH;- // Return true if the template is at most NEW_TEMPLATE_MAX_AGE days old- return (age <= NEW_TEMPLATE_MAX_AGE);- }- return false;-}-export default {getNoteTypeItems};diff --git a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsxindex 9ac081b459..e5fb73ccc3 100644--- a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx+++ b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx@@ -66,7 +66,7 @@ async function flush() {describe("TemplateNoteTypes", () => {it("re-resolves user templates on frocaReloaded (fresh FNote refs after unlock)", async () => {buildNote({ id: "userTemplate1", title: "[protected]" });- const serverGetSpy = vi.spyOn(server, "get").mockResolvedValue([ "userTemplate1" ]);+ const serverGetSpy = vi.spyOn(server, "get").mockResolvedValue({ templateNoteIds: [ "userTemplate1" ], newTemplateNoteIds: [] });const host = new Component();container = document.createElement("div");diff --git a/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx b/apps/client/src/widgets/layout/NoteTypeSwitcher.tsxindex 22b0e55683..365ef9762b 100644--- a/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx+++ b/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx@@ -1,6 +1,6 @@import "./NoteTypeSwitcher.css";-import { NoteType } from "@triliumnext/commons";+import { NoteType, type TemplatesResponse } from "@triliumnext/commons";import { useEffect, useMemo, useState } from "preact/hooks";import FNote from "../../entities/fnote";@@ -104,7 +104,7 @@ export function TemplateNoteTypes({ noteId, builtinTemplates }: { noteId: stringconst [ userTemplates, setUserTemplates ] = useState<FNote[]>([]);async function refreshTemplates() {- const templateNoteIds = await server.get<string[]>("search-templates");+ const { templateNoteIds } = await server.get<TemplatesResponse>("search-templates");const templateNotes = await froca.getNotes(templateNoteIds);setUserTemplates(templateNotes);}diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 62269f7481..e39f6539c0 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -710,6 +710,17 @@ export type SimilarNoteResponse = SimilarNote[];export type SaveSearchNoteResponse = CloneResponse;+export interface TemplatesResponse {+ /** The IDs of the user-defined templates, i.e. the notes labelled with `#template`. */+ templateNoteIds: string[];+ /**+ * The IDs of the templates that were created recently enough to be marked as new in the UI.+ * Unlike {@link templateNoteIds} this also covers the built-in templates, which live in the+ * hidden subtree and are thus not part of the search results.+ */+ newTemplateNoteIds: string[];+}+export interface CloneResponse {success: boolean;message?: string;diff --git a/packages/trilium-core/src/routes/api/search.spec.ts b/packages/trilium-core/src/routes/api/search.spec.tsindex 7711a53aab..85dd5c7b18 100644--- a/packages/trilium-core/src/routes/api/search.spec.ts+++ b/packages/trilium-core/src/routes/api/search.spec.ts@@ -1,7 +1,9 @@+import { dayjs, type TemplatesResponse } from "@triliumnext/commons";import { beforeAll, describe, expect, it } from "vitest";import { createTextNote } from "../../test/api_fixtures";import { CoreApiTester } from "../../test/api_tester";+import { isNewTemplate } from "./search";let api: CoreApiTester;const UNIQUE_TOKEN = "ZzUniqueSearchTokenQwerty";@@ -36,10 +38,10 @@ describe("Search API (core)", () => {body: { type: "label", name: "template", value: "" }});- const res = await api.get<string[]>("/api/search-templates");+ const res = await api.get<TemplatesResponse>("/api/search-templates");expect(res.status).toBe(200);- expect(Array.isArray(res.body)).toBe(true);- expect(res.body).toContain(noteId);+ expect(res.body.templateNoteIds).toContain(noteId);+ expect(Array.isArray(res.body.newTemplateNoteIds)).toBe(true);});it("400s when searching from a note that is not a search note", async () => {@@ -99,3 +101,28 @@ describe("Search API (core)", () => {expect(res.status).toBe(400);});});++describe("isNewTemplate", () => {+ const ROOT_CREATED = "2026-01-01 00:00:00.000Z";+ const utc = (date: dayjs.Dayjs) => date.format("YYYY-MM-DD HH:mm:ss.SSS[Z]");++ it("marks recent templates as new and leaves older ones alone", () => {+ expect(isNewTemplate(utc(dayjs.utc().subtract(1, "day")), ROOT_CREATED)).toBe(true);+ expect(isNewTemplate(utc(dayjs.utc().subtract(4, "day")), ROOT_CREATED)).toBe(false);+ expect(isNewTemplate(null, ROOT_CREATED)).toBe(false);+ });++ it("never marks the predefined templates set up alongside the root note", () => {+ const root = dayjs.utc().subtract(1, "hour");+ // Created together with the database: within the grace period, so not new+ // despite being only an hour old.+ expect(isNewTemplate(utc(root.add(10, "second")), utc(root))).toBe(false);+ // Added later on, e.g. by an upgrade.+ expect(isNewTemplate(utc(root.add(1, "minute")), utc(root))).toBe(true);+ });++ it("falls back to the age check when the root creation date is unknown", () => {+ expect(isNewTemplate(utc(dayjs.utc()), null)).toBe(true);+ expect(isNewTemplate(utc(dayjs.utc().subtract(4, "day")), undefined)).toBe(false);+ });+});diff --git a/packages/trilium-core/src/routes/api/search.ts b/packages/trilium-core/src/routes/api/search.tsindex 01bab721ec..795f796e80 100644--- a/packages/trilium-core/src/routes/api/search.ts+++ b/packages/trilium-core/src/routes/api/search.ts@@ -1,3 +1,4 @@+import { dayjs, type TemplatesResponse } from "@triliumnext/commons";import type { Request } from "express";import becca from "../../becca/becca.js";@@ -11,6 +12,12 @@ import { ValidationError } from "../../errors.js";import becca_service from "../../becca/becca_service.js";import { getHoistedNoteId } from "../../services/context.js";+/** The maximum age in days for a template to be marked as new. */+const NEW_TEMPLATE_MAX_AGE = 3;++/** The number of seconds after the root note's creation during which templates count as predefined. */+const INITIAL_SETUP_GRACE_PERIOD = 30;+function searchFromNote(req: Request<{ noteId: string }>): SearchNoteResult {const note = becca.getNoteOrThrow(req.params.noteId);@@ -148,15 +155,47 @@ function getRelatedNotes(req: Request) {};}-function searchTemplates() {+function searchTemplates(): TemplatesResponse {const query = getHoistedNoteId() === "root" ? "#template" : "#template OR #workspaceTemplate";+ const userTemplates = searchService.searchNotes(query, {+ includeArchivedNotes: true,+ ignoreHoistedNote: false+ });++ // The built-in templates live in the hidden subtree, so the search above never returns them.+ // Their "new" flag is reported here regardless, sparing the client a request per template.+ const builtInTemplates = becca.getNote("_templates")?.getChildNotes() ?? [];+ const rootCreationDate = becca.getNote("root")?.utcDateCreated;++ return {+ templateNoteIds: userTemplates.map((note) => note.noteId),+ newTemplateNoteIds: [ ...userTemplates, ...builtInTemplates ]+ .filter((note) => isNewTemplate(note.utcDateCreated, rootCreationDate))+ .map((note) => note.noteId)+ };+}++/**+ * Determines whether a template was created recently enough to be marked as new in the UI.+ *+ * @param utcDateCreated the creation date of the template.+ * @param rootCreationDate the creation date of the root note, used to recognize the predefined+ * templates that are set up together with a new database.+ */+export function isNewTemplate(utcDateCreated: string | null, rootCreationDate: string | null | undefined) {+ if (!utcDateCreated) {+ return false;+ }++ const creationDate = dayjs.utc(utcDateCreated);++ if (rootCreationDate && creationDate.diff(dayjs.utc(rootCreationDate), "second") < INITIAL_SETUP_GRACE_PERIOD) {+ // Ignore templates created shortly after the root note. This prevents the predefined+ // templates from being marked as new after setting up a new database.+ return false;+ }- return searchService- .searchNotes(query, {- includeArchivedNotes: true,- ignoreHoistedNote: false- })- .map((note) => note.noteId);+ return dayjs.utc().diff(creationDate, "day", true) <= NEW_TEMPLATE_MAX_AGE;}export default {