Skip to content

Build your personal knowledge base with Trilium Notes

client/options: add search support

Adorian Doran7d2b7eddf277
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index db7070b69d..17243d009a 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1062,7 +1062,12 @@
},
"options": {
"title": "Options",
- "back": "Back to all options"
+ "back": "Back to all options",
+ "search_placeholder": "Search settings",
+ "search_clear": "Clear the search",
+ "search_title": "Options search",
+ "search_hint": "Type a keyword to search across every settings page.",
+ "search_no_results": "No setting matches what you are looking for."
},
"global_menu": {
"menu": "Menu",
diff --git a/apps/client/src/widgets/dialogs/OptionsDialog.css b/apps/client/src/widgets/dialogs/OptionsDialog.css
index 5ed10c0614..957f2bc7b8 100644
--- a/apps/client/src/widgets/dialogs/OptionsDialog.css
+++ b/apps/client/src/widgets/dialogs/OptionsDialog.css
@@ -23,15 +23,21 @@ body.desktop .modal.options-dialog > .modal-dialog {
height: 75vh;
}
+/* Stated on the column itself rather than left to whichever child turns out to be the widest, so
+ that the search field takes the width it is given instead of setting it. */
.modal.options-dialog > .modal-dialog > .modal-content > .modal-sidebar {
+ width: 240px;
background-color: var(--card-background-color);
}
+.modal.options-dialog > .modal-dialog > .modal-content > .modal-sidebar .settings-search {
+ margin: 8px 8px 0;
+}
+
.modal.options-dialog > .modal-dialog > .modal-content > .modal-sidebar .settings-navigation {
flex: 1 1 0;
min-height: 0;
overflow: auto;
- width: 240px;
padding: 8px;
}
diff --git a/apps/client/src/widgets/dialogs/OptionsDialog.tsx b/apps/client/src/widgets/dialogs/OptionsDialog.tsx
index 586fc5c608..78501d7630 100644
--- a/apps/client/src/widgets/dialogs/OptionsDialog.tsx
+++ b/apps/client/src/widgets/dialogs/OptionsDialog.tsx
@@ -15,6 +15,8 @@ import { DetailPane, MasterDetailHeader, MasterPane, useMobileMasterDetail } fro
import Modal from "../react/Modal";
import { NoteContextContext, ParentComponent } from "../react/react_utils";
import SettingsNavigation from "../type_widgets/options/components/SettingsNavigation";
+import SettingsSearch from "../type_widgets/options/components/SettingsSearch";
+import OptionsSearchPage from "../type_widgets/options/search_page";
/** The settings page shown when no specific section was requested and none was viewed yet this session. */
const DEFAULT_SECTION = "_optionsAppearance";
@@ -34,6 +36,11 @@ export default function OptionsDialog() {
// Remembers the page last viewed this session so reopening the dialog lands there instead of
// always on Appearance. Kept in component state (resets on reload), not persisted.
const [ lastSection, setLastSection ] = useState<string | null>(null);
+ // What is being looked for across the pages, and whether the search is what the dialog is
+ // showing. The two are apart because focusing the field opens the search before anything is
+ // typed, and picking a page closes it again without emptying the field.
+ const [ searchQuery, setSearchQuery ] = useState("");
+ const [ searching, setSearching ] = useState(false);
const modalRef = useRef<HTMLDivElement>(null);
const isMobile = utils.isMobile();
const { isMasterDetail, mobileView, switchMobileView, resetMobileView } = useMobileMasterDetail(modalRef);
@@ -41,6 +48,8 @@ export default function OptionsDialog() {
useTriliumEvent("showOptions", async ({ section }) => {
const noteContext = new NoteContext("_options-dialog");
await noteContext.setNote(section ?? lastSection ?? DEFAULT_SECTION, { keepActiveDialog: true });
+ setSearchQuery("");
+ setSearching(false);
// Events triggered at note context level (e.g. the save indicator) would not work since the note context has no parent component. Propagate events to parent component so that they can be handled properly.
noteContext.triggerEvent = (name, data) => parentComponent?.handleEventInChildren(name, data);
@@ -55,6 +64,7 @@ export default function OptionsDialog() {
useContainedLinkNavigation(modalRef, useCallback((notePath, viewScope) => {
if (notePath.split("/").at(-1)?.startsWith("_options")) {
void noteContext.setNote(notePath, { viewScope, keepActiveDialog: true });
+ setSearching(false);
switchMobileView("page");
} else {
void appContext.triggerCommand("openInPopup", { noteIdOrPath: notePath });
@@ -76,7 +86,14 @@ export default function OptionsDialog() {
listIcon="bx bx-cog"
/>
)}
- sidebar={isMasterDetail ? undefined : <SettingsSidebar />}
+ sidebar={isMasterDetail ? undefined : (
+ <SettingsSidebar
+ searchQuery={searchQuery}
+ searching={searching}
+ onSearchChange={setSearchQuery}
+ onSearchFocus={() => setSearching(true)}
+ />
+ )}
isFullPageOnMobile
customTitleBarButtons={!isMobile ? [{
iconClassName: "bx-expand-alt",
@@ -107,11 +124,13 @@ export default function OptionsDialog() {
}} />
</MasterPane>
)}
- <SettingsScrollReset modalRef={modalRef} />
+ <SettingsScrollReset modalRef={modalRef} searching={searching} />
{/* The settings page is the detail half of the flow, and is wrapped as a pane only where
there is a flow for it to be half of: the sidebar layout expects it as the body's own
child. */}
- {isMasterDetail ? <DetailPane><NoteDetail /></DetailPane> : <NoteDetail />}
+ {isMasterDetail
+ ? <DetailPane><NoteDetail /></DetailPane>
+ : (searching ? <OptionsSearchPage query={searchQuery} /> : <NoteDetail />)}
</Modal>
</NoteContextContext.Provider>
);
@@ -178,27 +197,41 @@ export function isOptionPageVisibleOnPlatform(page: FNote) {
* resets both scroll containers in use: the `.modal-body` on the desktop sidebar layout and the
* `.note-detail` pane in the mobile master-detail flow.
*/
-function SettingsScrollReset({ modalRef }: { modalRef: RefObject<HTMLDivElement> }) {
+function SettingsScrollReset({ modalRef, searching }: { modalRef: RefObject<HTMLDivElement>, searching: boolean }) {
const { noteId } = useNoteContext();
useLayoutEffect(() => {
const modal = modalRef.current;
if (!modal) return;
modal.querySelector<HTMLElement>(".modal-body")?.scrollTo({ top: 0 });
modal.querySelector<HTMLElement>(".note-detail")?.scrollTo({ top: 0 });
- }, [ modalRef, noteId ]);
+ }, [ modalRef, noteId, searching ]);
return null;
}
+interface SettingsSidebarProps {
+ searchQuery: string;
+ /** Whether the search is what the dialog is showing, in which case no page is the active one. */
+ searching: boolean;
+ onSearchChange(query: string): void;
+ onSearchFocus(): void;
+}
+
/**
- * The settings page selector shown in the dialog's sidebar. It derives the active page from
- * `useNoteContext()` (resolved against the dialog's own context via the surrounding provider) so the
- * highlighted entry tracks navigation. The link clicks themselves are handled by the dialog's
- * {@link useContainedLinkNavigation} interceptor.
+ * The dialog's sidebar: the field looking through every page, above the selector for one of them.
+ *
+ * The selector derives the active page from `useNoteContext()` (resolved against the dialog's own
+ * context via the surrounding provider) so the highlighted entry tracks navigation. The link clicks
+ * themselves are handled by the dialog's {@link useContainedLinkNavigation} interceptor.
*/
-function SettingsSidebar() {
+function SettingsSidebar({ searchQuery, searching, onSearchChange, onSearchFocus }: SettingsSidebarProps) {
const { noteId } = useNoteContext();
- if (!noteId) return null;
- return <SettingsNavigation activeNoteId={noteId} />;
+
+ return (
+ <>
+ <SettingsSearch query={searchQuery} onChange={onSearchChange} onFocus={onSearchFocus} />
+ {noteId && <SettingsNavigation activeNoteId={searching ? "" : noteId} />}
+ </>
+ );
}
/**
diff --git a/apps/client/src/widgets/type_widgets/ContentWidget.tsx b/apps/client/src/widgets/type_widgets/ContentWidget.tsx
index af9cffad73..70d4fc0e41 100644
--- a/apps/client/src/widgets/type_widgets/ContentWidget.tsx
+++ b/apps/client/src/widgets/type_widgets/ContentWidget.tsx
@@ -24,7 +24,8 @@ import BackendLog from "./code/BackendLog";
export type OptionPages = "_optionsAppearance" | "_optionsShortcuts" | "_optionsTextNotes" | "_optionsCodeNotes" | "_optionsContentManager" | "_optionsMedia" | "_optionsSpellcheck" | "_optionsPassword" | "_optionsEtapi" | "_optionsBackup" | "_optionsDatabase" | "_optionsSync" | "_optionsDesktop" | "_optionsOther" | "_optionsLocalization" | "_optionsSecurity" | "_optionsAdvanced" | "_optionsLlm";
-const CONTENT_WIDGETS: Record<OptionPages | "_backendLog", (props: TypeWidgetProps) => JSX.Element> = {
+/** The page behind each of these notes. Exported for the options search, which renders them all. */
+export const CONTENT_WIDGETS: Record<OptionPages | "_backendLog", (props: TypeWidgetProps) => JSX.Element> = {
_optionsAppearance: AppearanceSettings,
_optionsShortcuts: ShortcutSettings,
_optionsTextNotes: TextNoteSettings,
diff --git a/apps/client/src/widgets/type_widgets/options/components/OptionsPageHeader.tsx b/apps/client/src/widgets/type_widgets/options/components/OptionsPageHeader.tsx
index 51c0e8f5cd..ea10317300 100644
--- a/apps/client/src/widgets/type_widgets/options/components/OptionsPageHeader.tsx
+++ b/apps/client/src/widgets/type_widgets/options/components/OptionsPageHeader.tsx
@@ -22,6 +22,10 @@ interface OptionsPageHeaderProps {
* where the help is page-level rather than scoped to one card.
*/
helpUrl?: string;
+ /** Title of a page that is not a note of its own, such as the options search. */
+ title?: string;
+ /** Icon to go with {@link OptionsPageHeaderProps.title}, in `bx bx-…` form. */
+ icon?: string;
}
/**
@@ -34,23 +38,25 @@ interface OptionsPageHeaderProps {
* for options pages. The sticky-bar styling differs per context (see the CSS), but each page owns its
* header the same way in all of them.
*/
-export default function OptionsPageHeader({ actions, below, helpUrl }: OptionsPageHeaderProps) {
+export default function OptionsPageHeader({ actions, below, helpUrl, title, icon }: OptionsPageHeaderProps) {
const { note } = useNoteContext();
+ const shownTitle = title ?? note?.title;
+ const shownIcon = icon ?? note?.getIcon();
// Nothing to render: the note isn't available yet and the page provided no content.
- if (!note && !actions && !below) return null;
+ if (!shownTitle && !actions && !below) return null;
return (
// A header carrying nothing but the page's name is marked as such: on a phone the name is
// shown beside the way back instead, leaving this with no band of its own to draw (see CSS).
<div className={clsx("options-page-header", !actions && !below && "options-page-header-title-only")}>
<div className="options-page-header-inner">
- {(note || actions) && (
+ {(shownTitle || actions) && (
<div className="options-page-header-main">
- {note && (
+ {shownTitle && (
<div className="options-page-header-titles">
- <span className={`options-page-header-icon ${note.getIcon()}`} aria-hidden="true" />
- <h2 className="options-page-header-title">{note.title}</h2>
+ <span className={`options-page-header-icon ${shownIcon}`} aria-hidden="true" />
+ <h2 className="options-page-header-title">{shownTitle}</h2>
{/* Classed so it can be told from the name it stands beside: on a
phone the name moves into the dialog's header and this stays. */}
{helpUrl && <HelpButton className="options-page-header-help" helpPage={helpUrl} />}
diff --git a/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.css b/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.css
new file mode 100644
index 0000000000..5dc7625931
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.css
@@ -0,0 +1,28 @@
+/* Layout-neutral, like the navigation it sits above: where it goes is the container's business. */
+.settings-search {
+ position: relative;
+
+ .settings-search-icon,
+ .settings-search-clear {
+ position: absolute;
+ top: 50%;
+ transform: translateY(-50%);
+ }
+
+ .settings-search-icon {
+ inset-inline-start: 8px;
+ color: var(--muted-text-color);
+ pointer-events: none;
+ }
+
+ /* Room kept for the icon and the button standing over the two ends of the field. */
+ .settings-search-input {
+ padding-inline: 30px 36px;
+ }
+
+ .settings-search-clear {
+ --icon-button-size: 24px;
+
+ inset-inline-end: 8px;
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.spec.tsx b/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.spec.tsx
new file mode 100644
index 0000000000..d2535f0bb1
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.spec.tsx
@@ -0,0 +1,43 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../react/hooks")>()),
+ useStaticTooltip: vi.fn()
+}));
+
+import { renderInto } from "../../../../test/render";
+import SettingsSearch from "./SettingsSearch";
+
+describe("SettingsSearch", () => {
+ it("carries what is being looked for, and offers to clear it only once there is something to clear", () => {
+ const onChange = vi.fn();
+
+ const empty = renderInto(<SettingsSearch query="" onChange={onChange} onFocus={vi.fn()} />);
+ expect(empty.querySelector("input")?.value).toBe("");
+ expect(empty.querySelector(".settings-search-clear")).toBeNull();
+
+ const filled = renderInto(<SettingsSearch query="backup" onChange={onChange} onFocus={vi.fn()} />);
+ expect(filled.querySelector("input")?.value).toBe("backup");
+
+ filled.querySelector<HTMLButtonElement>(".settings-search-clear")?.click();
+ expect(onChange).toHaveBeenCalledWith("");
+ });
+
+ it("reports what is typed, and the focus that opens the search", () => {
+ const onChange = vi.fn();
+ const onFocus = vi.fn();
+ const input = renderInto(
+ <SettingsSearch query="" onChange={onChange} onFocus={onFocus} />
+ ).querySelector("input");
+
+ // preact/compat delegates focus to focusin, the same way it does blur to focusout.
+ input?.dispatchEvent(new Event("focusin", { bubbles: true }));
+ expect(onFocus).toHaveBeenCalledTimes(1);
+
+ if (input) input.value = "theme";
+ input?.dispatchEvent(new Event("input", { bubbles: true }));
+ expect(onChange).toHaveBeenCalledWith("theme", expect.anything());
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.tsx b/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.tsx
new file mode 100644
index 0000000000..9e34d38c2a
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.tsx
@@ -0,0 +1,51 @@
+import "./SettingsSearch.css";
+
+import { useRef } from "preact/hooks";
+
+import { t } from "../../../../services/i18n";
+import ActionButton from "../../../react/ActionButton";
+import FormTextBox from "../../../react/FormTextBox";
+
+interface SettingsSearchProps {
+ query: string;
+ onChange(query: string): void;
+ /** Called when the field takes focus, which is what opens the search results. */
+ onFocus(): void;
+}
+
+/**
+ * The field at the top of the settings sidebar, which looks through every page at once rather than
+ * through the one on show. Focusing it is enough to open the results, so that what is typed lands
+ * somewhere it can be read straight away.
+ */
+export default function SettingsSearch({ query, onChange, onFocus }: SettingsSearchProps) {
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ return (
+ <div className="settings-search">
+ <span className="settings-search-icon bx bx-search" aria-hidden="true" />
+
+ <FormTextBox
+ inputRef={inputRef}
+ className="settings-search-input"
+ placeholder={t("options.search_placeholder")}
+ aria-label={t("options.search_placeholder")}
+ currentValue={query}
+ onChange={onChange}
+ onFocus={onFocus}
+ />
+
+ {query && (
+ <ActionButton
+ className="settings-search-clear"
+ icon="bx bx-x"
+ text={t("options.search_clear")}
+ onClick={() => {
+ onChange("");
+ inputRef.current?.focus();
+ }}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/options/search_page.css b/apps/client/src/widgets/type_widgets/options/search_page.css
new file mode 100644
index 0000000000..3ee6abc71f
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/search_page.css
@@ -0,0 +1,45 @@
+.options-search {
+ .options-search-loading,
+ .options-search-hint {
+ margin-top: 2em;
+ color: var(--muted-text-color);
+ font-size: 1.2em;
+ text-align: center;
+ }
+
+ .options-search-results,
+ .options-search-page {
+ display: flex;
+ flex-direction: column;
+ gap: 26px;
+ }
+
+ /* The layout above out-weighs the browser's own rule for the attribute, so it is said again. */
+ .options-search-results[hidden] {
+ display: none;
+ }
+
+ .options-search-page-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0;
+ color: var(--muted-text-color);
+ font-size: 1.5rem;
+ font-weight: 400;
+ }
+}
+
+/*
+ * A page brings its whole self along, of which the search wants only the cards: its header names the
+ * page it thinks it is showing, and its tables and listings are not settings anyone can search for.
+ *
+ * What counts as something to show is therefore a card that matched by name, or any single setting
+ * that matched — the same test decides whether a page is worth naming and whether the search found
+ * anything at all.
+ */
+.options-search-page > :not(.tn-card, .options-search-page-title),
+.options-search-page:not(:has(.tn-card:not(.tn-card-filter-unmatched), .tn-card-option)),
+.options-search-results:has(.tn-card:not(.tn-card-filter-unmatched), .tn-card-option) .options-search-empty {
+ display: none;
+}
diff --git a/apps/client/src/widgets/type_widgets/options/search_page.spec.tsx b/apps/client/src/widgets/type_widgets/options/search_page.spec.tsx
new file mode 100644
index 0000000000..92416fe02c
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/search_page.spec.tsx
@@ -0,0 +1,124 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type FNote from "../../../entities/fnote";
+
+const mocks = vi.hoisted(() => ({
+ pages: [] as FNote[]
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../dialogs/OptionsDialog", () => ({
+ useOptionPages: () => mocks.pages
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useNoteContext: () => ({})
+}));
+
+vi.mock("../ContentWidget", async () => {
+ const { Card, OptionCardSection } = await import("../../react/Card");
+
+ return {
+ CONTENT_WIDGETS: {
+ _optionsAppearance: () => (
+ <Card heading="Appearance">
+ <OptionCardSection className="theme" label="Theme" />
+ <OptionCardSection className="zoom" label="Zoom level" />
+ </Card>
+ ),
+ _optionsBackup: () => (
+ <Card heading="Backup">
+ <OptionCardSection className="interval" label="Backup interval" />
+ </Card>
+ ),
+ _optionsContentManager: () => <Card heading="Content manager"><div /></Card>
+ }
+ };
+});
+
+import { renderInto } from "../../../test/render";
+import OptionsSearchPage, { MIN_QUERY_LENGTH } from "./search_page";
+
+function fakePage(noteId: string, title: string) {
+ return { noteId, title, getIcon: () => "bx bx-cog" } as unknown as FNote;
+}
+
+/** Renders the page and lets it get past the spinner, which it holds for a tick on purpose. */
+async function renderSearch(query: string) {
+ const container = renderInto(null);
+ await act(() => render(<OptionsSearchPage query={query} />, container));
+ await act(() => { vi.advanceTimersByTime(500); });
+
+ return container;
+}
+
+function shownSettings(container: HTMLElement) {
+ return [ ...container.querySelectorAll(".tn-card-option") ].map((el) => el.textContent);
+}
+
+describe("OptionsSearchPage", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ mocks.pages = [
+ fakePage("_optionsAppearance", "Appearance"),
+ fakePage("_optionsBackup", "Backup"),
+ fakePage("_optionsContentManager", "Content manager")
+ ];
+ });
+
+ afterEach(() => vi.useRealTimers());
+
+ it("stands the pages up behind a spinner, rather than freezing on an empty page", async () => {
+ const container = renderInto(null);
+
+ await act(() => render(<OptionsSearchPage query="" />, container));
+ expect(container.querySelector(".options-search-loading")).not.toBeNull();
+ expect(container.querySelector(".options-search-results")).toBeNull();
+
+ await act(() => { vi.advanceTimersByTime(500); });
+ expect(container.querySelector(".options-search-loading")).toBeNull();
+ expect(container.querySelector(".options-search-results")).not.toBeNull();
+ });
+
+ it("holds the results back until enough has been typed to look for", async () => {
+ const short = await renderSearch("th".slice(0, MIN_QUERY_LENGTH - 1));
+ expect(short.querySelector(".options-search-results")?.hasAttribute("hidden")).toBe(true);
+ expect(short.querySelector(".options-search-hint")).not.toBeNull();
+ // Mounted all the same, so that the first search is as quick as every one after it.
+ expect(shownSettings(short).length).toBeGreaterThan(0);
+
+ const long = await renderSearch("theme");
+ expect(long.querySelector(".options-search-results")?.hasAttribute("hidden")).toBe(false);
+ expect(long.querySelector(".options-search-hint")).toBeNull();
+ });
+
+ it("keeps only the settings that match, from whichever page they belong to", async () => {
+ expect(shownSettings(await renderSearch("theme"))).toEqual([ "Theme" ]);
+ expect(shownSettings(await renderSearch("backup"))).toEqual([ "Backup interval" ]);
+ expect(shownSettings(await renderSearch("nothing at all"))).toEqual([]);
+ });
+
+ it("shows the whole of a page's card when the card itself is what matched", async () => {
+ const container = await renderSearch("appearance");
+
+ expect(shownSettings(container)).toEqual([ "Theme", "Zoom level" ]);
+ });
+
+ it("names the page each result belongs to", async () => {
+ const container = await renderSearch("theme");
+ const titles = [ ...container.querySelectorAll(".options-search-page-title") ].map((el) => el.textContent);
+
+ expect(titles).toContain("Appearance");
+ });
+
+ it("leaves out the pages that do work on show instead of holding settings", async () => {
+ const container = await renderSearch("content");
+
+ expect(container.querySelectorAll(".options-search-page")).toHaveLength(2);
+ expect(container.textContent).not.toContain("Content manager");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/search_page.tsx b/apps/client/src/widgets/type_widgets/options/search_page.tsx
new file mode 100644
index 0000000000..8d297d401a
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/search_page.tsx
@@ -0,0 +1,120 @@
+import "./search_page.css";
+
+import type { ComponentChildren } from "preact";
+import { useEffect, useState } from "preact/hooks";
+
+import type FNote from "../../../entities/fnote";
+import { t } from "../../../services/i18n";
+import { useOptionPages } from "../../dialogs/OptionsDialog";
+import { FilterProvider } from "../../react/filter";
+import { useDebouncedValue, useNoteContext } from "../../react/hooks";
+import LoadingSpinner from "../../react/LoadingSpinner";
+import NoItems from "../../react/NoItems";
+import { CONTENT_WIDGETS } from "../ContentWidget";
+import type { TypeWidgetProps } from "../type_widget";
+import OptionsPageHeader from "./components/OptionsPageHeader";
+
+/** How much has to be typed before there is enough of a word to look for. */
+export const MIN_QUERY_LENGTH = 3;
+
+const DEBOUNCE_MS = 250;
+
+/**
+ * Pages the search leaves out. The Content Manager is a tool rather than a set of settings, and
+ * showing it costs a scan of the database that nobody asked for by typing in a search box.
+ */
+const PAGES_LEFT_OUT = new Set([ "_optionsContentManager" ]);
+
+/**
+ * The settings search: every options page at once, cut down to the settings matching what is being
+ * looked for. Reached by focusing the field in the sidebar rather than from the list of pages, since
+ * it is a way of finding a setting rather than a page of its own.
+ *
+ * The pages are mounted as they are, and each takes care of hiding what does not match through
+ * {@link FilterProvider}. Mounting them costs a moment, which is what the spinner covers; from then
+ * on the results follow the typing, since nothing is mounted or torn down as the query changes.
+ */
+export default function OptionsSearchPage({ query }: { query: string }) {
+ const settled = useDebouncedValue(query.trim(), DEBOUNCE_MS);
+ const filter = settled.length >= MIN_QUERY_LENGTH ? settled : "";
+ const ready = useDeferredMount();
+
+ if (!ready) {
+ return (
+ <SearchPageFrame>
+ <div className="options-search-loading"><LoadingSpinner /></div>
+ </SearchPageFrame>
+ );
+ }
+
+ return (
+ <SearchPageFrame>
+ {!filter && (
+ <p className="options-search-hint">{t("options.search_hint")}</p>
+ )}
+
+ {/* Kept mounted while there is nothing to look for, so that the first search is as quick
+ as every one after it. */}
+ <FilterProvider query={filter}>
+ <div className="options-search-results" hidden={!filter}>
+ <SearchedPages />
+
+ <NoItems
+ className="options-search-empty"
+ icon="bx bx-search"
+ text={t("options.search_no_results")}
+ />
+ </div>
+ </FilterProvider>
+ </SearchPageFrame>
+ );
+}
+
+function SearchPageFrame({ children }: { children: ComponentChildren }) {
+ return (
+ <div className="note-detail-content-widget-content options options-search">
+ <OptionsPageHeader title={t("options.search_title")} icon="bx bx-search" />
+ {children}
+ </div>
+ );
+}
+
+function SearchedPages() {
+ const pages = useOptionPages().filter((page) => !PAGES_LEFT_OUT.has(page.noteId));
+ const { noteContext, parentComponent, ntxId, viewScope } = useNoteContext();
+ const pageProps = { noteContext, parentComponent, ntxId, viewScope, isVisible: true };
+
+ return <>{pages.map((page) => <SearchedPage key={page.noteId} page={page} {...pageProps} />)}</>;
+}
+
+/** One page's cards, under the name of the page they belong to, so a result says where it lives. */
+function SearchedPage({ page, ...pageProps }: { page: FNote } & Omit<TypeWidgetProps, "note">) {
+ const Page = CONTENT_WIDGETS[page.noteId];
+ if (!Page) return null;
+
+ return (
+ <section className="options-search-page">
+ <h3 className="options-search-page-title">
+ <span className={page.getIcon()} aria-hidden="true" />
+ {page.title}
+ </h3>
+
+ <Page note={page} {...pageProps} />
+ </section>
+ );
+}
+
+/**
+ * False for the first render and true from the next one, which gives the spinner a chance to be seen
+ * before the pages are built and the browser is busy with them.
+ */
+function useDeferredMount() {
+ const [ ready, setReady ] = useState(false);
+
+ useEffect(() => {
+ const timer = setTimeout(() => setReady(true));
+ return () => clearTimeout(timer);
+ }, []);
+
+ return ready;
+}