Skip to content

Build your personal knowledge base with Trilium Notes

client/ui: implement a filtering provider for Preact components

Adorian Doran9d5c19472444
diff --git a/apps/client/src/widgets/react/filter.spec.tsx b/apps/client/src/widgets/react/filter.spec.tsx
new file mode 100644
index 0000000000..b62cca1f58
--- /dev/null
+++ b/apps/client/src/widgets/react/filter.spec.tsx
@@ -0,0 +1,216 @@
+import { type ComponentChildren, Fragment, render } from "preact";
+import { useEffect } from "preact/hooks";
+import { act } from "preact/test-utils";
+import { describe, expect, it } from "vitest";
+
+import { renderInto } from "../../test/render";
+import {
+ FilterPassthrough, FilterProvider, filterText, filterTokens, matchesFilter, useFilterMatch,
+ useFilterState, useIsFiltering
+} from "./filter";
+
+describe("filterText", () => {
+ it("reads text out of anything renderable, and nothing out of what has none", () => {
+ expect(filterText("Backups")).toBe("Backups");
+ expect(filterText(42)).toBe("42");
+ expect(filterText([ "Take", "backups" ])).toBe("Take backups");
+ expect(filterText(<b>Backups</b>)).toBe("Backups");
+ expect(filterText(<p>Take a <b>backup</b> daily</p>)).toBe("Take a backup daily");
+ expect(filterText(<Fragment>{[ "Take", <b>backups</b> ]}</Fragment>)).toBe("Take backups");
+
+ expect(filterText(null)).toBe("");
+ expect(filterText(undefined)).toBe("");
+ expect(filterText(false)).toBe("");
+ expect(filterText(<hr />)).toBe("");
+ });
+
+ it("cannot see inside a custom component, whose text is only known once it renders", () => {
+ function PageTitle() {
+ return <span>Backups</span>;
+ }
+
+ expect(filterText(<PageTitle />)).toBe("");
+ expect(filterText(<p>Backups <PageTitle /></p>)).toBe("Backups ");
+ });
+});
+
+describe("filterTokens", () => {
+ it("splits a query into terms, ignoring case, accents and spacing", () => {
+ expect(filterTokens("Take Backups")).toEqual([ "take", "backups" ]);
+ expect(filterTokens(" spaced out\tterms\n")).toEqual([ "spaced", "out", "terms" ]);
+ expect(filterTokens("Modèle Français")).toEqual([ "modele", "francais" ]);
+ });
+
+ it("finds no terms in a query holding none", () => {
+ expect(filterTokens("")).toEqual([]);
+ expect(filterTokens(" ")).toEqual([]);
+ });
+});
+
+describe("matchesFilter", () => {
+ it("passes content holding every term, in any order and as part of a word", () => {
+ expect(matchesFilter([ "back" ], "Backup interval")).toBe(true);
+ expect(matchesFilter([ "interval", "backup" ], "Backup interval")).toBe(true);
+ expect(matchesFilter([ "backup", "daily" ], "Backup interval")).toBe(false);
+ });
+
+ it("matches across everything it is given, ignoring case and accents", () => {
+ expect(matchesFilter([ "daily" ], "Backup", "Taken daily")).toBe(true);
+ expect(matchesFilter([ "modele" ], "Modèle")).toBe(true);
+ expect(matchesFilter([ "backup" ], <b>Backups</b>)).toBe(true);
+ expect(matchesFilter([ "backup" ], null, undefined)).toBe(false);
+ });
+
+ it("passes anything when there are no terms to match", () => {
+ expect(matchesFilter([], "Backup")).toBe(true);
+ expect(matchesFilter([], null)).toBe(true);
+ });
+});
+
+describe("useFilterMatch", () => {
+ it("renders everything when there is no filter, and only matches when there is one", () => {
+ const outside = renderInto(<Settings />);
+ expect(labelsIn(outside)).toEqual([ "Backup interval", "Theme", "Language" ]);
+
+ const filtered = renderInto(
+ <FilterProvider query="the"><Settings /></FilterProvider>
+ );
+ expect(labelsIn(filtered)).toEqual([ "Theme" ]);
+ });
+
+ it("matches on the description as well as the label", () => {
+ const container = renderInto(
+ <FilterProvider query="colours"><Settings /></FilterProvider>
+ );
+
+ expect(labelsIn(container)).toEqual([ "Theme" ]);
+ });
+
+ it("treats a query with no terms in it as no filter at all", () => {
+ for (const query of [ "", " ", null, undefined ]) {
+ const container = renderInto(
+ <FilterProvider query={query}><Settings /></FilterProvider>
+ );
+
+ expect(labelsIn(container)).toHaveLength(3);
+ expect(container.querySelector(".filtering")?.textContent).toBe("false");
+ }
+ });
+
+ it("reports the filter in force, with the terms ready to be matched or highlighted", () => {
+ const container = renderInto(
+ <FilterProvider query="Thème Dark"><Settings /></FilterProvider>
+ );
+
+ expect(container.querySelector(".filtering")?.textContent).toBe("true");
+ expect(container.querySelector(".tokens")?.textContent).toBe("theme,dark");
+ });
+});
+
+describe("FilterPassthrough", () => {
+ it("shows the whole of a group that matched by its own heading", () => {
+ const container = renderInto(
+ <FilterProvider query="appearance">
+ <Group heading="Appearance"><Settings /></Group>
+ </FilterProvider>
+ );
+
+ expect(container.querySelector(".group")?.getAttribute("data-matched")).toBe("true");
+ expect(labelsIn(container)).toEqual([ "Backup interval", "Theme", "Language" ]);
+ });
+
+ it("leaves the group's contents to match on their own when it did not", () => {
+ const container = renderInto(
+ <FilterProvider query="theme">
+ <Group heading="Appearance"><Settings /></Group>
+ </FilterProvider>
+ );
+
+ expect(container.querySelector(".group")?.getAttribute("data-matched")).toBe("false");
+ expect(labelsIn(container)).toEqual([ "Theme" ]);
+ });
+
+ it("lifts only its own filter, so one set up further down still applies", () => {
+ const container = renderInto(
+ <FilterProvider query="appearance">
+ <Group heading="Appearance">
+ <FilterProvider query="language"><Settings /></FilterProvider>
+ </Group>
+ </FilterProvider>
+ );
+
+ expect(labelsIn(container)).toEqual([ "Language" ]);
+ });
+
+ it("keeps the children in place as the group starts and stops matching", async () => {
+ const container = renderInto(null);
+
+ mounts = 0;
+ await act(() => render(<Tree query="theme" />, container));
+ await act(() => render(<Tree query="appearance" />, container));
+ expect(labelsIn(container)).toHaveLength(3);
+
+ await act(() => render(<Tree query="nothing here" />, container));
+ expect(labelsIn(container)).toHaveLength(0);
+
+ expect(mounts).toBe(1);
+ });
+});
+
+function Setting({ label, description }: { label: string, description?: ComponentChildren }) {
+ if (!useFilterMatch(label, description)) return null;
+
+ return <span className="setting">{label}</span>;
+}
+
+/** A handful of settings to filter, plus a readout of the filter they are being shown under. */
+function Settings() {
+ const state = useFilterState();
+
+ return (
+ <>
+ <span className="filtering">{String(useIsFiltering())}</span>
+ <span className="tokens">{state?.tokens.join(",")}</span>
+
+ <Setting label="Backup interval" description="How often a copy is taken." />
+ <Setting label="Theme" description={<>Which <b>colours</b> the app is drawn in.</>} />
+ <Setting label="Language" />
+ </>
+ );
+}
+
+function Group({ heading, children }: { heading: string, children: ComponentChildren }) {
+ const matched = useFilterMatch(heading);
+
+ return (
+ <div className="group" data-matched={String(matched)}>
+ <FilterPassthrough when={matched}>{children}</FilterPassthrough>
+ </div>
+ );
+}
+
+let mounts = 0;
+
+/** Sits inside the group without filtering itself, so its mounts tell whether the group remounted. */
+function Persistent() {
+ useEffect(() => {
+ mounts++;
+ }, []);
+
+ return null;
+}
+
+function Tree({ query }: { query: string }) {
+ return (
+ <FilterProvider query={query}>
+ <Group heading="Appearance">
+ <Persistent />
+ <Settings />
+ </Group>
+ </FilterProvider>
+ );
+}
+
+function labelsIn(container: HTMLElement) {
+ return [ ...container.querySelectorAll(".setting") ].map((el) => el.textContent);
+}
diff --git a/apps/client/src/widgets/react/filter.tsx b/apps/client/src/widgets/react/filter.tsx
new file mode 100644
index 0000000000..2617158888
--- /dev/null
+++ b/apps/client/src/widgets/react/filter.tsx
@@ -0,0 +1,171 @@
+import { type ComponentChildren, createContext, isValidElement } from "preact";
+import { useContext, useMemo } from "preact/hooks";
+
+/**
+ * What a subtree is being narrowed down to, provided by {@link FilterProvider}.
+ *
+ * Most components never read this directly: they ask {@link useFilterMatch} whether to render. Read
+ * it when the terms themselves are needed, for example to hand them to
+ * `useImperativeSearchHighlighlighting` so the matched words are marked in place.
+ */
+export interface FilterState {
+ /**
+ * The terms being filtered by, lowercased and stripped of accents. Never empty, since a query
+ * with no terms in it filters nothing and is provided as `null` instead.
+ */
+ tokens: string[];
+ /** Whether the given content holds every term. See {@link matchesFilter}. */
+ matches(...content: ComponentChildren[]): boolean;
+}
+
+/** Null wherever nothing is filtered, which is everywhere outside a {@link FilterProvider}. */
+const FilterContext = createContext<FilterState | null>(null);
+
+interface FilterProviderProps {
+ /** What the user typed. Blank or missing means nothing is filtered. */
+ query?: string | null;
+ children: ComponentChildren;
+}
+
+/**
+ * Filters everything rendered below it by `query`, without those components needing to know where
+ * the query came from or that a filter exists at all.
+ *
+ * Each participating component asks {@link useFilterMatch} whether its own text matches, and returns
+ * `null` when it does not. Components that do not ask are left alone, so a filter can be added over
+ * an existing tree and only the parts opted in respond to it.
+ *
+ * Nothing here is debounced: pass a value already settled with `useDebouncedValue` when the filter
+ * covers enough content that filtering on every keystroke would be felt.
+ *
+ * @example
+ * const [ query, setQuery ] = useState("");
+ *
+ * <FormTextBox currentValue={query} onChange={setQuery} />
+ * <FilterProvider query={useDebouncedValue(query, 200)}>
+ * <Settings />
+ * </FilterProvider>
+ */
+export function FilterProvider({ query, children }: FilterProviderProps) {
+ const state = useMemo(() => createFilterState(query ?? ""), [ query ]);
+
+ return <FilterContext.Provider value={state}>{children}</FilterContext.Provider>;
+}
+
+interface FilterPassthroughProps {
+ /**
+ * Whether to lift the filter for the children. A prop rather than a condition around this
+ * component, so that turning it on and off leaves the tree in place: wrapping and unwrapping
+ * children instead would remount them, losing focus and any state they hold.
+ */
+ when?: boolean;
+ children: ComponentChildren;
+}
+
+/**
+ * Shows the children in full, as though nothing were being filtered.
+ *
+ * This is how a container that matched by its own title passes the whole of what it holds: the user
+ * asked for this group, so the parts inside it should no longer have to match on their own. Filters
+ * further down still apply, since each provider only lifts its own.
+ *
+ * @example
+ * const matched = useFilterMatch(heading);
+ *
+ * <div className="group">
+ * <h5>{heading}</h5>
+ * <FilterPassthrough when={matched}>{children}</FilterPassthrough>
+ * </div>
+ */
+export function FilterPassthrough({ when = true, children }: FilterPassthroughProps) {
+ const state = useContext(FilterContext);
+
+ return <FilterContext.Provider value={when ? null : state}>{children}</FilterContext.Provider>;
+}
+
+/**
+ * Whether the content given survives the filter it sits under, which is always true when nothing is
+ * being filtered. Pass everything the user could reasonably search this piece of content by; plain
+ * strings and JSX are both accepted (see {@link filterText} for what is read out of JSX).
+ *
+ * @example
+ * function Setting({ label, description, children }: SettingProps) {
+ * if (!useFilterMatch(label, description)) return null;
+ * return <label>{label}<small>{description}</small>{children}</label>;
+ * }
+ */
+export function useFilterMatch(...content: ComponentChildren[]): boolean {
+ const state = useContext(FilterContext);
+
+ return !state || state.matches(...content);
+}
+
+/**
+ * The filter in force, or `null` when there is none. For components doing their own filtering, such
+ * as a list narrowing its data before rendering rows, or one highlighting the matched terms.
+ */
+export function useFilterState(): FilterState | null {
+ return useContext(FilterContext);
+}
+
+/**
+ * Whether anything is being filtered here. Useful for styling a component differently while a filter
+ * is running, for example to hide a group left empty by it through CSS rather than in code.
+ */
+export function useIsFiltering(): boolean {
+ return useContext(FilterContext) !== null;
+}
+
+/**
+ * Splits a query into the terms to match by, lowercased and stripped of accents so that typing
+ * "Modele" finds "Modèle". Returns an empty array for a query holding no terms.
+ */
+export function filterTokens(query: string): string[] {
+ return normalize(query).split(/\s+/).filter((token) => token.length > 0);
+}
+
+/**
+ * Whether every term appears somewhere in the content given, each as part of a word rather than a
+ * whole one, so "back" finds "backup". Content with no terms to match against passes.
+ *
+ * The terms must come from {@link filterTokens}, which is what makes the comparison ignore case and
+ * accents on both sides.
+ */
+export function matchesFilter(tokens: string[], ...content: ComponentChildren[]): boolean {
+ if (tokens.length === 0) return true;
+
+ const haystack = normalize(content.map((item) => filterText(item)).join(" "));
+
+ return tokens.every((token) => haystack.includes(token));
+}
+
+/**
+ * Reads the plain text out of anything renderable: strings and numbers as they are, arrays and the
+ * children of JSX elements joined together.
+ *
+ * A custom component is opaque, since what it renders is only known once it does. `<b>Backups</b>`
+ * therefore reads as "Backups" while `<PageTitle />` reads as nothing, so a label built from a
+ * component should be passed to {@link useFilterMatch} alongside its text in plain form.
+ */
+export function filterText(content: ComponentChildren): string {
+ if (typeof content === "string") return content;
+ if (typeof content === "number" || typeof content === "bigint") return String(content);
+ if (Array.isArray(content)) return content.map((child) => filterText(child)).join(" ");
+ if (isValidElement(content)) return filterText(content.props?.children);
+
+ return "";
+}
+
+function createFilterState(query: string): FilterState | null {
+ const tokens = filterTokens(query);
+ if (tokens.length === 0) return null;
+
+ return {
+ tokens,
+ matches: (...content) => matchesFilter(tokens, ...content)
+ };
+}
+
+function normalize(text: string): string {
+ return text.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase();
+}