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
refactor(quick_search): show the results in a plain Popup
Elian Doran9c47a813264d
diff --git a/apps/client/src/widgets/quick_search.css b/apps/client/src/widgets/quick_search.cssindex 32b0e0bab2..4f504ea4f3 100644--- a/apps/client/src/widgets/quick_search.css+++ b/apps/client/src/widgets/quick_search.css@@ -104,7 +104,7 @@}&:focus-within .search-button:hover,- .search-button.show {+ .search-button.active {background: var(--quick-search-button-hover-background) !important;color: var(--quick-search-button-active-color) !important;transition: background-color 100ms ease-out !important;diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsxindex 2c094eee4a..343618335d 100644--- a/apps/client/src/widgets/quick_search.spec.tsx+++ b/apps/client/src/widgets/quick_search.spec.tsx@@ -130,6 +130,45 @@ describe("QuickSearch", () => {await vi.waitFor(() => expect(menu()).toBeNull());});+ it("opens and closes the results from the search button", async () => {+ const get = vi.spyOn(server, "get").mockResolvedValue(response(3, []));+ const { container, editor } = await mount();+ const button = container.querySelector<HTMLButtonElement>(".search-button");+ if (!button) throw new Error("The search button did not render.");++ typeQuery(editor, "hello");+ await act(async () => button.click());+ await waitForResults(3);+ expect(get).toHaveBeenCalledWith("quick-search/hello");+ expect(button.classList.contains("active")).toBe(true);++ await act(async () => button.click());+ await vi.waitFor(() => expect(menu()).toBeNull());+ expect(button.classList.contains("active")).toBe(false);+ });++ it("moves between the results with Up and Down, and gives the field focus back on Escape", async () => {+ vi.spyOn(server, "get").mockResolvedValue(response(3, []));+ const { editor } = await mount();++ typeQuery(editor, "hello");+ pressEnter(editor);+ const [ first, second ] = await waitForResults(3);++ const press = (target: HTMLElement, key: string) => act(() => {+ target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));+ });+ first.focus();+ press(first, "ArrowDown");+ expect(document.activeElement).toBe(second);+ press(second, "ArrowUp");+ expect(document.activeElement).toBe(first);++ press(first, "Escape");+ await vi.waitFor(() => expect(menu()).toBeNull());+ expect(editor.hasFocus).toBe(true);+ });+it("leaves the open results alone while the query is typed", async () => {vi.spyOn(server, "get").mockResolvedValue(response(15, []));const { editor } = await mount();diff --git a/apps/client/src/widgets/quick_search.tsx b/apps/client/src/widgets/quick_search.tsxindex 6214f40f00..6481b472b1 100644--- a/apps/client/src/widgets/quick_search.tsx+++ b/apps/client/src/widgets/quick_search.tsx@@ -3,14 +3,17 @@ import "./quick_search.css";import type { FieldEditor } from "@triliumnext/codemirror/src/field_editor";import type { QuickSearchResponse, SearchResultDetails } from "@triliumnext/commons";import clsx from "clsx";-import { useRef, useState } from "preact/hooks";+import type { RefObject } from "preact";+import { useEffect, useRef, useState } from "preact/hooks";import { t } from "../services/i18n";import { calculateHash, type ViewScope } from "../services/link";import server from "../services/server";-import { DropdownPanel, type DropdownHandle } from "./react/Dropdown";+import ActionButton from "./react/ActionButton";+import { focusListItem } from "./react/FormList";import { useTriliumEvent } from "./react/hooks";import Icon from "./react/Icon";+import Popup from "./react/Popup";import RawHtml, { RawHtmlBlock } from "./react/RawHtml";import SearchStringEditor from "./ribbon/SearchStringEditor";@@ -25,22 +28,25 @@ export default function QuickSearch() {const searchStringRef = useRef("");const [ hasQuery, setHasQuery ] = useState(false);const [ searchState, setSearchState ] = useState<SearchState>();+ const [ open, setOpen ] = useState(false);const editorRef = useRef<FieldEditor>();- const dropdownRef = useRef<DropdownHandle | null>(null);const boxRef = useRef<HTMLDivElement>(null);- const isOpenRef = useRef(false);+ const popupRef = useRef<HTMLDivElement | null>(null);// Each search takes a number, so a slower earlier response cannot overwrite a later one.const requestIdRef = useRef(0);useTriliumEvent("quickSearch", () => editorRef.current?.focus());+ useResultNavigation(popupRef, open);+ /** Opens the results with a search for the query, or refreshes the open results. */async function search() {const query = searchStringRef.current.trim();if (!query) {- dropdownRef.current?.hide();+ close();return;}+ setOpen(true);const requestId = ++requestIdRef.current;setSearchState({ status: "searching" });const { searchResults, highlightedTokens } = await server.get<QuickSearchResponse>(@@ -56,34 +62,23 @@ export default function QuickSearch() {});}+ function close() {+ // Focus on a result goes back to the field, rather than to the page's body.+ if (popupRef.current?.contains(document.activeElement)) editorRef.current?.focus();+ setOpen(false);+ }+return (<div className={clsx("quick-search", hasQuery && "has-query")}><div ref={boxRef} className="quick-search-box">- <DropdownPanel- className="quick-search-toggle"- buttonClassName="search-button"- dropdownContainerClassName="quick-search-menu"- text={<Icon icon="bx bx-search" />}- hideToggleArrow- noSelectButtonStyle- placement="bottom-start"- anchorRef={boxRef}- dropdownRef={dropdownRef}- onShown={() => {- isOpenRef.current = true;- void search();- }}- onHidden={() => {- isOpenRef.current = false;- }}- >- <div className="quick-search-results">- <QuickSearchResults- searchState={searchState}- onOpenResult={() => dropdownRef.current?.hide()}- />- </div>- </DropdownPanel>+ <ActionButton+ className="search-button"+ icon="bx bx-search"+ text={t("quick-search.placeholder")}+ noIconActionClass+ active={open}+ onClick={() => (open ? close() : void search())}+ /><SearchStringEditorclassName="search-string"@@ -94,26 +89,49 @@ export default function QuickSearch() {searchStringRef.current = value;setHasQuery(value.length > 0);}}- onEnter={() => {- // Opening the results runs the search; open results are refreshed.- if (isOpenRef.current) {- void search();- } else {- dropdownRef.current?.show();- }- editorRef.current?.focus();- }}- onEscape={() => {- if (!isOpenRef.current) return false;- dropdownRef.current?.hide();- return true;- }}+ onEnter={() => void search()}/></div>++ {open && boxRef.current && (+ <Popup+ anchor={boxRef.current}+ placement="bottom-start"+ offset={2}+ capHeight={false}+ className="dropdown-menu show tn-dropdown-menu quick-search-menu"+ elementRef={popupRef}+ onDismiss={close}+ >+ <div className="quick-search-results">+ <QuickSearchResults searchState={searchState} onOpenResult={close} />+ </div>+ </Popup>+ )}</div>);}+/**+ * Moves focus between the results with Up and Down. Captured at the window, as Bootstrap's handler+ * for keys in a `.dropdown-menu` crashes on one with no toggle beside it.+ */+function useResultNavigation(popupRef: RefObject<HTMLElement>, open: boolean) {+ useEffect(() => {+ if (!open) return;+ const onKeyDown = (e: KeyboardEvent) => {+ const popup = popupRef.current;+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;+ if (!popup?.contains(e.target as Node)) return;+ e.preventDefault();+ e.stopPropagation();+ focusListItem(popup, e.key === "ArrowDown" ? "next" : "previous", e.target as Element);+ };+ window.addEventListener("keydown", onKeyDown, true);+ return () => window.removeEventListener("keydown", onKeyDown, true);+ }, [ open ]);+}+function QuickSearchResults({ searchState, onOpenResult }: {searchState: SearchState | undefined;onOpenResult(): void;@@ -153,6 +171,7 @@ function QuickSearchResult({ result, viewScope, onOpen }: {className="dropdown-item"tabIndex={0}href={calculateHash({ notePath: result.notePath, viewScope })}+ onClick={onOpen}onAuxClick={onOpen}><div className="quick-search-item">diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsxindex f60d69d62a..de8d83bc7a 100644--- a/apps/client/src/widgets/react/Dropdown.spec.tsx+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx@@ -104,24 +104,6 @@ describe("Dropdown", () => {expect(onHidden).toHaveBeenCalledTimes(1);});- it("stands under `anchorRef` when given, and stays open for a press on it", async () => {- const anchor = document.createElement("div");- const field = document.createElement("input");- anchor.append(field);- document.body.append(anchor);- vi.spyOn(anchor, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect({ x: 20, y: 40, width: 300, height: 30 }));- const { toggle } = renderDropdown({ panel: true, anchorRef: { current: anchor } });-- click(toggle);- await vi.waitFor(() => expect(popup()?.style.visibility).toBe("visible"));- expect([ popup()?.style.left, popup()?.style.top ]).toEqual([ "20px", "72px" ]);-- field.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));- await new Promise((resolve) => setTimeout(resolve, 0));- expect(popup()).not.toBeNull();- anchor.remove();- });-it("closes on a press outside, and on Escape, which hands focus back to the toggle", async () => {const { toggle } = renderDropdown();diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsxindex ad71edf502..e6fcd312d5 100644--- a/apps/client/src/widgets/react/Dropdown.tsx+++ b/apps/client/src/widgets/react/Dropdown.tsx@@ -1,7 +1,7 @@import type { Placement } from "@floating-ui/dom";import type { Tooltip } from "bootstrap";import clsx from "clsx";-import { ComponentChildren, HTMLAttributes, type RefObject } from "preact";+import { ComponentChildren, HTMLAttributes } from "preact";import { CSSProperties, HTMLProps } from "preact/compat";import { MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";@@ -35,11 +35,6 @@ export interface DropdownProps extends Pick<HTMLProps<HTMLDivElement>, "id" | "conHidden?: () => void;/** The side of the toggle the popup prefers; it flips to the other near the viewport's edge. */placement?: Placement;- /**- * The element the popup stands beside instead of the toggle, such as the field a search- * button belongs to. A press on it does not close the popup.- */- anchorRef?: RefObject<HTMLElement | null>;/*** What closes the popup besides Escape and the toggle: `true` a click inside and a press* outside, `"inside"` or `"outside"` that one alone, `false` neither. A row that stops its click@@ -157,7 +152,7 @@ interface PopupSlot {* The toggle both kinds of dropdown share: the button, its tooltip, the open state and its* callbacks, the handle, and the phone's cover. `popup` draws what opens under it.*/-function DropdownToggle({ id, className, buttonClassName, title, text, dropdownContainerStyle, dropdownContainerClassName, dropdownContainerRef: externalContainerRef, hideToggleArrow, iconAction, disabled, noSelectButtonStyle, onShown, onHidden, placement, anchorRef, autoClose = true, buttonProps, dropdownRef, titlePosition, titleOptions, mobileBackdrop: mobileBackdropProp, mobileBottomSheet, backdrop, hasPopup, onToggleArrow, popup }: Omit<DropdownProps, "children"> & {+function DropdownToggle({ id, className, buttonClassName, title, text, dropdownContainerStyle, dropdownContainerClassName, dropdownContainerRef: externalContainerRef, hideToggleArrow, iconAction, disabled, noSelectButtonStyle, onShown, onHidden, placement, autoClose = true, buttonProps, dropdownRef, titlePosition, titleOptions, mobileBackdrop: mobileBackdropProp, mobileBottomSheet, backdrop, hasPopup, onToggleArrow, popup }: Omit<DropdownProps, "children"> & {hasPopup: "menu" | "true";/** Called for Up or Down on the toggle while the popup is up. */onToggleArrow?(popup: HTMLElement, edge: "first" | "last"): void;@@ -311,7 +306,7 @@ function DropdownToggle({ id, className, buttonClassName, title, text, dropdownC{shown && triggerRef.current && popup({popupProps: {- anchor: anchorRef?.current ?? triggerRef.current,+ anchor: triggerRef.current,placement,offset: TOGGLE_GAP,// In a wrapper with the dropdown's classes, so CSS scoped under them still