Skip to content

Build your personal knowledge base with Trilium Notes

feat(text): list at most ten notes after @, as the server stops at them

Elian Doran8bc55e4374e4
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.ts
index eac4bc86d4..c8b58322eb 100644
--- a/apps/client/src/services/note_autocomplete.spec.ts
+++ b/apps/client/src/services/note_autocomplete.spec.ts
@@ -73,6 +73,9 @@ describe("getNoteSuggestions", () => {
await getNoteSuggestions("a", { fastSearch: false });
expect(server.get).toHaveBeenLastCalledWith(expect.stringContaining("fastSearch=false"));
+ // A limit is passed on for the server to stop at; left out, none is sent.
+ await getNoteSuggestions("a", { limit: 10 });
+ expect(server.get).toHaveBeenLastCalledWith("autocomplete?query=a&activeNoteId=activeNote&fastSearch=true&limit=10");
expect(getInboxTarget).not.toHaveBeenCalled();
});
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index 5318d648c7..e1e732bc15 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -50,20 +50,22 @@ export interface NoteSuggestionOptions {
allowExternalLinks?: boolean;
/** Searches the titles only, as autocompletion does, or the content as well. */
fastSearch?: boolean;
+ /** Lists at most this many notes, which the server then stops at. The action rows come on top. */
+ limit?: number;
}
/**
* Returns the notes matching `term`, or the recently visited notes when `term` is blank, with the
* action rows the options ask for.
*/
-export async function getNoteSuggestions(term: string, { allowCreatingNotes, allowJumpToSearchNotes, allowExternalLinks, fastSearch = true }: NoteSuggestionOptions = {}): Promise<Suggestion[]> {
+export async function getNoteSuggestions(term: string, { allowCreatingNotes, allowJumpToSearchNotes, allowExternalLinks, fastSearch = true, limit }: NoteSuggestionOptions = {}): Promise<Suggestion[]> {
const activeNoteId = appContext.tabManager.getActiveContextNoteId();
const hasTerm = term.trim().length >= 1;
// Runs concurrently with the search, so naming the destination costs a request but no wait.
const pendingInboxTarget = hasTerm && allowCreatingNotes ? getInboxTarget() : null;
- const results: Suggestion[] = await server.get<AutocompleteResult[]>(`autocomplete?query=${encodeURIComponent(term)}&activeNoteId=${activeNoteId}&fastSearch=${fastSearch}`);
+ const results: Suggestion[] = await server.get<AutocompleteResult[]>(`autocomplete?query=${encodeURIComponent(term)}&activeNoteId=${activeNoteId}&fastSearch=${fastSearch}${limit ? `&limit=${limit}` : ""}`);
const before: Suggestion[] = [];
const after: Suggestion[] = [];
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index d32b67a265..225619de8f 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -1155,12 +1155,13 @@ describe("NoteMentionList", () => {
it("lists the notes for the query as the field does, and again as the query changes", async () => {
const { draw, unmount } = await show("al", { allowCreatingNotes: true });
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { allowCreatingNotes: true });
+ // At most ten notes, which the server stops at.
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { allowCreatingNotes: true, limit: 10 });
expect(rows().map((row) => row.querySelector(".search-result-title")?.innerHTML)).toEqual([ "<b>Al</b>pha", "Beta" ]);
expect(rows()[0].querySelector(".tn-icon")?.className).toContain("bx-file");
await draw("alp");
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("alp", { allowCreatingNotes: true });
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("alp", { allowCreatingNotes: true, limit: 10 });
expect(rows()).toHaveLength(2);
await unmount();
});
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 87339bf2e2..6fa6840533 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -29,6 +29,8 @@ import { renderShortcutKbds } from "./shortcut_kbd";
const DROPDOWN_MIN_WIDTH = 500;
/** Keyboard hints are left out on mobile, as `Button` leaves out its shortcut. */
const cachedIsMobile = isMobile();
+/** How many notes {@link NoteMentionList} shows; typing more of the title narrows them down. */
+const MENTION_NOTE_LIMIT = 10;
export interface NoteAutocompleteProps {
id?: string;
@@ -454,7 +456,8 @@ export function NoteMentionList({ query, anchor, allowCreatingNotes, preselect =
}) {
// The focus stays where the query is typed, so there is no field to return it to.
const inputRef = useRef<HTMLInputElement>(null);
- const source = useCallback((term: string) => getNoteSuggestions(term, { allowCreatingNotes }), [ allowCreatingNotes ]);
+ const source = useCallback((term: string) =>
+ getNoteSuggestions(term, { allowCreatingNotes, limit: MENTION_NOTE_LIMIT }), [ allowCreatingNotes ]);
const schedule = useMemo(() => createSearchScheduler(), []);
const autocomplete = useAutocomplete({
diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx
index 5e4c587b41..a72688ca4b 100644
--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx
@@ -158,7 +158,7 @@ describe("createNoteMentionList", () => {
it("lists the notes for the query, and mentions the one picked by its path", async () => {
const { list, commit } = await open();
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { allowCreatingNotes: true });
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { allowCreatingNotes: true, limit: 10 });
expect(list.element?.textContent).toContain("Alpha");
expect(list.handleKeyDown(new KeyboardEvent("keydown", { key: "Enter", cancelable: true }))).toBe(true);
expect(commit).toHaveBeenCalledExactlyOnceWith({ id: "@root/a", notePath: "root/a" });
diff --git a/packages/trilium-core/src/routes/api/autocomplete.spec.ts b/packages/trilium-core/src/routes/api/autocomplete.spec.ts
index 4000b9b096..06fd762afd 100644
--- a/packages/trilium-core/src/routes/api/autocomplete.spec.ts
+++ b/packages/trilium-core/src/routes/api/autocomplete.spec.ts
@@ -137,6 +137,26 @@ describe("Autocomplete API (core)", () => {
expect(res.body.length).toBe(25);
});
+ it("stops at the limit a caller gives, which lowers the caps and never raises them", async () => {
+ const marker = `limitmarker${Date.now()}`;
+ for (let i = 0; i < 30; i++) {
+ const { noteId } = await createTextNote(api, { title: `${marker} note ${i}` });
+ await api.post("/api/recent-notes", { body: { noteId, notePath: `root/${noteId}` } });
+ }
+ const count = async (query: string, limit: string) =>
+ (await api.get<AutocompleteResult[]>("/api/autocomplete", { query: { query, limit } })).body.length;
+
+ expect(await count(marker, "10")).toBe(10);
+ expect(await count(marker, "100")).toBe(25);
+ // The recent notes, for an empty query.
+ expect(await count("", "10")).toBe(10);
+ });
+
+ it.each([ "0", "-1", "2.5", "ten" ])("400s for a limit of %s", async (limit) => {
+ const res = await api.get("/api/autocomplete", { query: { query: "root", limit } });
+ expect(res.status).toBe(400);
+ });
+
it("400s when the query param is missing", async () => {
const res = await api.get("/api/autocomplete");
expect(res.status).toBe(400);
diff --git a/packages/trilium-core/src/routes/api/autocomplete.ts b/packages/trilium-core/src/routes/api/autocomplete.ts
index 0a65cccbfc..90fe351cfb 100644
--- a/packages/trilium-core/src/routes/api/autocomplete.ts
+++ b/packages/trilium-core/src/routes/api/autocomplete.ts
@@ -10,12 +10,16 @@ import { escapeHtml } from "../../services/utils/index.js";
import { ValidationError } from "../../errors.js";
import becca_service from "../../becca/becca_service.js";
+/** The most recent notes an empty query lists. */
+const RECENT_NOTES_LIMIT = 200;
+
function getAutocomplete(req: Request): AutocompleteResult[] {
if (typeof req.query.query !== "string") {
throw new ValidationError("Invalid query data type.");
}
const query = (req.query.query || "").trim();
const fastSearch = String(req.query.fastSearch).toLowerCase() !== "false";
+ const limit = parseLimit(req.query.limit);
const activeNoteId = req.query.activeNoteId || "none";
@@ -24,9 +28,9 @@ function getAutocomplete(req: Request): AutocompleteResult[] {
const timestampStarted = Date.now();
if (query.length === 0 && typeof activeNoteId === "string") {
- results = getRecentNotes(activeNoteId);
+ results = getRecentNotes(activeNoteId, limit);
} else {
- results = searchService.searchNotesForAutocomplete(query, fastSearch);
+ results = searchService.searchNotesForAutocomplete(query, fastSearch, limit);
}
const msTaken = Date.now() - timestampStarted;
@@ -38,7 +42,7 @@ function getAutocomplete(req: Request): AutocompleteResult[] {
return results;
}
-function getRecentNotes(activeNoteId: string): AutocompleteResult[] {
+function getRecentNotes(activeNoteId: string, limit = RECENT_NOTES_LIMIT): AutocompleteResult[] {
let extraCondition = "";
const params = [activeNoteId];
@@ -61,7 +65,7 @@ function getRecentNotes(activeNoteId: string): AutocompleteResult[] {
${extraCondition}
ORDER BY
utcDateCreated DESC
- LIMIT 200`,
+ LIMIT ${Math.min(limit, RECENT_NOTES_LIMIT)}`,
params
);
@@ -85,6 +89,23 @@ function getRecentNotes(activeNoteId: string): AutocompleteResult[] {
});
}
+/**
+ * The `limit` query parameter: how many notes a caller shows, which the server then stops at
+ * rather than building rows that are thrown away. Left out, the server's own caps apply; it can
+ * lower them, never raise them.
+ */
+function parseLimit(limit: unknown): number | undefined {
+ if (limit === undefined) {
+ return undefined;
+ }
+
+ const parsed = typeof limit === "string" ? Number(limit) : NaN;
+ if (!Number.isInteger(parsed) || parsed < 1) {
+ throw new ValidationError("Invalid limit.");
+ }
+ return parsed;
+}
+
export default {
getAutocomplete
};
diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.ts
index d93b90a79a..ffcfd5fa62 100644
--- a/packages/trilium-core/src/services/search/services/search.ts
+++ b/packages/trilium-core/src/services/search/services/search.ts
@@ -820,7 +820,8 @@ function extractAttributeSnippet(noteId: string, searchTokens: HighlightedTokenI
// response, so the limit follows what a dropdown shows rather than what the query matched.
const AUTOCOMPLETE_RESULT_LIMIT = 25;
-function searchNotesForAutocomplete(query: string, fastSearch: boolean = true) {
+/** Searches for the notes a dropdown lists, the first `limit` of them, at most {@link AUTOCOMPLETE_RESULT_LIMIT}. */
+function searchNotesForAutocomplete(query: string, fastSearch: boolean = true, limit = AUTOCOMPLETE_RESULT_LIMIT) {
const searchContext = new SearchContext({
fastSearch,
includeArchivedNotes: false,
@@ -836,7 +837,7 @@ function searchNotesForAutocomplete(query: string, fastSearch: boolean = true) {
rankInTwoPasses: true
});
- const trimmed = findResultsWithQuery(query, searchContext).slice(0, AUTOCOMPLETE_RESULT_LIMIT);
+ const trimmed = findResultsWithQuery(query, searchContext).slice(0, Math.min(limit, AUTOCOMPLETE_RESULT_LIMIT));
return buildSearchResultDetails(trimmed, searchContext);
}