Skip to content

Build your personal knowledge base with Trilium Notes

client/content manager: implement filtering by user input

Adorian Doranfac6c9eb4bb4
diff --git a/apps/client/src/services/content_manager.spec.ts b/apps/client/src/services/content_manager.spec.ts
index 537e9132bd..9eb9b56d0e 100644
--- a/apps/client/src/services/content_manager.spec.ts
+++ b/apps/client/src/services/content_manager.spec.ts
@@ -42,6 +42,27 @@ describe("buildCategoryQuery", () => {
}
});
+ it("appends a title match, keeping the cheap attribute lookup first", () => {
+ // `AndExp` narrows its operands left to right, so the indexed attribute group has to lead;
+ // the bare "#" is what ends the fulltext portion so the following "(" is not swallowed.
+ expect(buildCategoryQuery("#appCss OR #disabled:appCss", "title", "dark")).toBe(
+ `# (#appCss OR #disabled:appCss) AND note.title *=* "dark" orderBy note.title, note.noteId`
+ );
+ });
+
+ it("leaves the query untouched when the filter is empty or only whitespace", () => {
+ const plain = "#appCss orderBy note.title, note.noteId";
+
+ expect(buildCategoryQuery("#appCss", "title")).toBe(plain);
+ expect(buildCategoryQuery("#appCss", "title", " ")).toBe(plain);
+ });
+
+ it("quotes the filter so spaces and quotes cannot break out of the term", () => {
+ expect(buildCategoryQuery("#appCss", "title", "my theme")).toContain(`note.title *=* "my theme"`);
+ expect(buildCategoryQuery("#appCss", "title", `a" OR #run`)).toContain(`note.title *=* "a\\" OR #run"`);
+ expect(buildCategoryQuery("#appCss", "title", "back\\slash")).toContain(`note.title *=* "back\\\\slash"`);
+ });
+
it("keeps the ordering clause at the top level of an OR chain", () => {
// `orderBy` is rejected by the parser unless it sits on the top expression level, so the
// filters must not be wrapped in parentheses.
diff --git a/apps/client/src/services/content_manager.ts b/apps/client/src/services/content_manager.ts
index fb77da4cd8..4ea0e5b7e8 100644
--- a/apps/client/src/services/content_manager.ts
+++ b/apps/client/src/services/content_manager.ts
@@ -217,8 +217,8 @@ export const CONTENT_CATEGORIES: ContentCategory[] = [
];
/** Runs one category's query and returns the user-made notes it matches, already sorted. */
-export async function findCategoryNotes(category: ContentCategory, sortOrder: ContentSortOrder) {
- const notes = await search.searchForNotes(buildCategoryQuery(category.filter, sortOrder));
+export async function findCategoryNotes(category: ContentCategory, sortOrder: ContentSortOrder, titleFilter = "") {
+ const notes = await search.searchForNotes(buildCategoryQuery(category.filter, sortOrder, titleFilter));
return notes.filter((note) => isUserContent(note) && ownsCategoryTrigger(note, category));
}
@@ -229,13 +229,25 @@ export async function findCategoryNotes(category: ContentCategory, sortOrder: Co
* Note IDs break ties. Notes routinely share a title, and the sort would otherwise be unstable —
* equally named rows could swap places on every refresh, which reads as the list jumping about.
*/
-export function buildCategoryQuery(filter: string, sortOrder: ContentSortOrder) {
+export function buildCategoryQuery(filter: string, sortOrder: ContentSortOrder, titleFilter = "") {
// Newest first reads better for dates, while titles are most useful alphabetically.
const orderBy = sortOrder === "dateCreated"
? "note.dateCreated desc, note.noteId"
: "note.title, note.noteId";
+ const wanted = titleFilter.trim();
- return `${filter} orderBy ${orderBy}`;
+ // The attribute group comes first on purpose: `AndExp` threads the narrowing note set through
+ // its operands in order, so the index-backed attribute lookup shrinks the set before the title
+ // comparison has to walk it. The leading bare "#" is what ends the fulltext portion — without
+ // it the opening paren is swallowed into that portion and the expression parses unbalanced.
+ const expression = wanted ? `# (${filter}) AND note.title *=* ${quoteSearchValue(wanted)}` : filter;
+
+ return `${expression} orderBy ${orderBy}`;
+}
+
+/** Quotes a user-typed value so spaces keep it one token and quotes in it can't end it early. */
+function quoteSearchValue(value: string) {
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
}
/**
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 22c15f744f..ca4da85e7b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2614,6 +2614,8 @@
"category_endpoints": "Custom Endpoints",
"category_sharing": "Sharing",
"loading": "Retrieving content...",
+ "filter_placeholder": "Type text to filter by title...",
+ "no_matches": "No active content matches the filter.",
"toggle_enable": "Enable",
"toggle_disable": "Disable",
"property_trigger": "Trigger",
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager.css b/apps/client/src/widgets/type_widgets/options/content_manager.css
index 20dcced723..a7891b953a 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager.css
+++ b/apps/client/src/widgets/type_widgets/options/content_manager.css
@@ -1,6 +1,5 @@
.content-manager-toolbar {
display: flex;
- justify-content: flex-end;
align-items: center;
gap: 0.75em;
margin-bottom: 1em;
@@ -11,7 +10,14 @@
margin-bottom: 2em;
}
+.content-manager-filter {
+ flex-grow: 1;
+ max-width: 25em;
+}
+
.content-manager-toolbar-label {
+ /* Pushes the sort control to the trailing edge, leaving the filter box on the leading one. */
+ margin-inline-start: auto;
white-space: nowrap;
}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager.tsx b/apps/client/src/widgets/type_widgets/options/content_manager.tsx
index 0a2559d500..496ebc9aa5 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager.tsx
@@ -2,7 +2,7 @@ import "./content_manager.css";
import clsx from "clsx";
import type { TargetedMouseEvent } from "preact";
-import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
import appContext from "../../../components/app_context";
import type FNote from "../../../entities/fnote";
@@ -18,10 +18,12 @@ import {
resolveProperties,
setCategoryEnabled
} from "../../../services/content_manager";
+import debounce from "../../../services/debounce";
import { t } from "../../../services/i18n";
import { ListView, type ListViewOptions } from "../../collections/legacy/ListOrGridView";
import ActionButton from "../../react/ActionButton";
import Button, { ButtonGroup } from "../../react/Button";
+import FormTextBox from "../../react/FormTextBox";
import FormToggle from "../../react/FormToggle";
import { useTriliumEvent, useTriliumOption } from "../../react/hooks";
import NoItems from "../../react/NoItems";
@@ -30,6 +32,9 @@ import OptionsPageHeader from "./components/OptionsPageHeader";
const NOOP = () => {};
+/** Long enough that a burst of typing issues one round of searches, short enough to feel immediate. */
+const FILTER_DEBOUNCE_MS = 300;
+
/**
* The item's "..." menu. The collection menu is replaced here because most of its entries act on a
* note in the context of its parent, which this list is not: these notes live all over the tree.
@@ -135,25 +140,44 @@ const LIST_OPTIONS: ListViewOptions = {
export default function ContentManagerSettings({ note }: TypeWidgetProps) {
const [ sortOrder, setSortOrder ] = useTriliumOption("contentManagerSortOrder");
- const categories = useCategoryNotes(sortOrder as ContentSortOrder);
+ const [ typedFilter, setTypedFilter ] = useState("");
+ const [ appliedFilter, setAppliedFilter ] = useState("");
+ const categories = useCategoryNotes(sortOrder as ContentSortOrder, appliedFilter);
+
+ // Typing stays instant while the searches only re-run once the user pauses.
+ const applyFilter = useMemo(() => debounce(setAppliedFilter, FILTER_DEBOUNCE_MS), []);
+ useEffect(() => () => applyFilter.clear(), [ applyFilter ]);
return (
<>
<OptionsPageHeader />
<div className="content-manager-toolbar">
+ <FormTextBox
+ className="content-manager-filter"
+ placeholder={t("content_manager.filter_placeholder")}
+ currentValue={typedFilter}
+ onChange={(newValue) => {
+ setTypedFilter(newValue);
+ applyFilter(newValue);
+ }}
+ />
<span className="content-manager-toolbar-label">{t("content_manager.sort_order")}</span>
<SortOrderSelect currentValue={sortOrder} onChange={(newValue) => void setSortOrder(newValue)} />
</div>
<div className="content-manager-list">
- <CategoryList pageNote={note} categories={categories} />
+ <CategoryList pageNote={note} categories={categories} isFiltered={!!appliedFilter.trim()} />
</div>
</>
);
}
-function CategoryList({ pageNote, categories }: { pageNote: FNote, categories: CategoryNotes[] | null }) {
+function CategoryList({ pageNote, categories, isFiltered }: {
+ pageNote: FNote,
+ categories: CategoryNotes[] | null,
+ isFiltered: boolean
+}) {
if (!categories) {
return <p className="content-manager-loading">{t("content_manager.loading")}</p>;
}
@@ -161,11 +185,15 @@ function CategoryList({ pageNote, categories }: { pageNote: FNote, categories: C
const populated = categories.filter(({ notes }) => notes.length > 0);
if (!populated.length) {
- return (
- <NoItems icon="bx bx-package" text={t("content_manager.no_items")}>
- <small>{t("content_manager.no_items_hint")}</small>
- </NoItems>
- );
+ // An empty result means something different while filtering: content may well exist, just
+ // none of it matching, so the "nothing here yet" hint would be misleading.
+ return isFiltered
+ ? <NoItems icon="bx bx-search" text={t("content_manager.no_matches")} />
+ : (
+ <NoItems icon="bx bx-package" text={t("content_manager.no_items")}>
+ <small>{t("content_manager.no_items_hint")}</small>
+ </NoItems>
+ );
}
return (
@@ -231,7 +259,7 @@ interface CategoryNotes {
* each category's definition self-contained and the counts stay far too small for the difference to
* be noticeable.
*/
-function useCategoryNotes(sortOrder: ContentSortOrder) {
+function useCategoryNotes(sortOrder: ContentSortOrder, titleFilter: string) {
// `null` until the first search resolves, so the page can tell "still loading" apart from
// "genuinely nothing to show" instead of flashing the empty state on every open.
const [ categories, setCategories ] = useState<CategoryNotes[] | null>(null);
@@ -241,7 +269,7 @@ function useCategoryNotes(sortOrder: ContentSortOrder) {
const requestId = ++latestRequest.current;
const refreshed = await Promise.all(CONTENT_CATEGORIES.map(async (category) => ({
category,
- notes: await findCategoryNotes(category, sortOrder)
+ notes: await findCategoryNotes(category, sortOrder, titleFilter)
})));
// Both the sort order and `entitiesReloaded` trigger a refresh, so two can be in flight at
@@ -249,7 +277,7 @@ function useCategoryNotes(sortOrder: ContentSortOrder) {
if (requestId === latestRequest.current) {
setCategories(refreshed);
}
- }, [ sortOrder ]);
+ }, [ sortOrder, titleFilter ]);
useEffect(() => { void refresh(); }, [ refresh ]);
diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.ts
index 5fd52b8a72..bb34c5786e 100644
--- a/packages/trilium-core/src/services/search/services/search.spec.ts
+++ b/packages/trilium-core/src/services/search/services/search.spec.ts
@@ -682,6 +682,40 @@ describe("Search", () => {
expect(searchResults.map((sr) => sr.noteId)).toEqual([ "nB", "nA", "nZ" ]);
});
+ it("test attribute group AND-ed with a note property, then ordered", () => {
+ // The shape the Content Manager builds when its filter box is used: an OR chain of attribute
+ // filters grouped in parens, AND-ed with a title match, with `orderBy` still at top level.
+ // The title condition leads deliberately — a query *starting* with "(" is mis-lexed, since
+ // the paren is swallowed into the fulltext portion before any token ends it.
+ const alpha = note("Alpha script").label("run", "hourly");
+ const beta = note("Beta script").label("run", "daily");
+ const gamma = note("Gamma other").label("disabled:run", "hourly");
+
+ rootNote.child(note("Scripts").child(alpha).child(beta).child(gamma));
+
+ const searchContext = new SearchContext();
+
+ // The attribute group leads so the cheap index-backed lookup narrows the set before the
+ // title comparison walks it. A bare "#" ends the fulltext portion, which a leading "(" alone
+ // would not do.
+ let searchResults = searchService.findResultsWithQuery(
+ `# (#run OR #disabled:run) AND note.title *=* script orderBy note.title`, searchContext);
+ expect(searchResults.map((sr) => becca.notes[sr.noteId].title)).toEqual([ "Alpha script", "Beta script" ]);
+
+ // Same results with the operands the other way round, confirming the ordering is purely an
+ // optimisation rather than a semantic difference.
+ searchResults = searchService.findResultsWithQuery(
+ `note.title *=* script AND (#run OR #disabled:run) orderBy note.title`, searchContext);
+ expect(searchResults.map((sr) => becca.notes[sr.noteId].title)).toEqual([ "Alpha script", "Beta script" ]);
+
+ // A quoted value keeps a multi-word filter in one token.
+ searchResults = searchService.findResultsWithQuery(
+ `# (#run OR #disabled:run) AND note.title *=* "gamma other" orderBy note.title`, searchContext);
+ expect(searchResults.map((sr) => becca.notes[sr.noteId].title)).toEqual([ "Gamma other" ]);
+
+ expect(searchContext.getError()).toBeFalsy();
+ });
+
it("test not(...)", () => {
const italy = note("Italy").label("capital", "Rome");
const slovakia = note("Slovakia").label("capital", "Bratislava");