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
fix(quick_search): open the results under the search box
Elian Dorandda1f02bdb06
diff --git a/apps/client/src/widgets/quick_search.css b/apps/client/src/widgets/quick_search.cssindex 32aee75d9c..32b0e0bab2 100644--- a/apps/client/src/widgets/quick_search.css+++ b/apps/client/src/widgets/quick_search.css@@ -1,8 +1,6 @@/* Colors come from the theme's `--quick-search-*` variables; the fallbacks cover the themes thatdefine none of them. */.quick-search {- /* The room between the widget's edge and the box drawn inside it. */- --quick-search-inset: 8px;--quick-search-button-active-background:var(--left-pane-item-action-button-background, var(--hover-item-background-color));--quick-search-button-hover-background:@@ -10,45 +8,38 @@--quick-search-button-active-color:var(--left-pane-item-action-button-color, var(--main-text-color));- position: relative;display: flex;- flex-direction: row-reverse;- align-items: center;- padding: var(--quick-search-inset);+ /* Around the box, and still part of the widget. */+ padding: 8px;/* `.component`, which `BasicWidget` adds, sets `contain: size` and would collapse the box. */&.component {contain: unset;}- /* The box. Drawn inside the padding, which stays part of the widget. */- &::before {- content: "";- position: absolute;- inset: var(--quick-search-inset);- z-index: 0;+ .quick-search-box {+ display: flex;+ flex: 1 1 auto;+ flex-direction: row-reverse;+ align-items: center;+ min-width: 0;border: 2px solid transparent;border-radius: 6px;background: var(--quick-search-background, var(--accented-background-color));transition: background-color 200ms ease-in;}- &:hover::before {+ &:hover .quick-search-box {background: var(--quick-search-hover-background, var(--accented-background-color));transition: background-color 75ms ease-out;}- &:focus-within::before {+ &:focus-within .quick-search-box {border-color: var(--quick-search-focus-border, var(--main-border-color));background: var(--quick-search-focus-background, var(--main-background-color));transition: background-color 100ms ease-out;}- /* Over the box. */- & > * {- position: relative;- }-.search-string {display: flex;flex: 1 1 auto;diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsxindex 2fd6e5e4a7..97cd718205 100644--- a/apps/client/src/widgets/quick_search.spec.tsx+++ b/apps/client/src/widgets/quick_search.spec.tsx@@ -128,6 +128,27 @@ describe("QuickSearch", () => {await act(async () => first.click());await vi.waitFor(() => expect(menu()).toBeNull());});++ it("stands the results under the search box, which a press does not close them from", async () => {+ vi.spyOn(server, "get").mockResolvedValue(response(3, []));+ // happy-dom lays nothing out, so the viewport is given a size to place the popup in.+ vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1000);+ vi.spyOn(document.documentElement, "clientHeight", "get").mockReturnValue(800);+ const { container, editor } = await mount();+ const box = container.querySelector<HTMLElement>(".quick-search-box");+ if (!box) throw new Error("The search box did not render.");+ vi.spyOn(box, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect({ x: 20, y: 40, width: 300, height: 30 }));++ typeQuery(editor, "hello");+ pressEnter(editor);+ await waitForResults(3);+ await vi.waitFor(() => expect(menu()?.style.left).toBe("20px"));++ await act(async () => {+ editor.contentDOM.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));+ });+ expect(menu()).not.toBeNull();+ });});/** Renders the component and waits for the CodeMirror modules it imports on demand. */diff --git a/apps/client/src/widgets/quick_search.tsx b/apps/client/src/widgets/quick_search.tsxindex 0ad16b6163..0812b23206 100644--- a/apps/client/src/widgets/quick_search.tsx+++ b/apps/client/src/widgets/quick_search.tsx@@ -25,6 +25,7 @@ export default function QuickSearch() {const [ searchState, setSearchState ] = useState<SearchState>();const editorRef = useRef<FieldEditor>();const dropdownRef = useRef<DropdownHandle | null>(null);+ const boxRef = useRef<HTMLDivElement>(null);const isOpenRef = useRef(false);// Each search takes a number, so a slower earlier response cannot overwrite a later one.const requestIdRef = useRef(0);@@ -55,53 +56,56 @@ export default function QuickSearch() {return (<div className={clsx("quick-search", searchString && "has-query")}>- <DropdownPanel- className="quick-search-toggle"- buttonClassName="search-button"- dropdownContainerClassName="quick-search-menu"- text={<Icon icon="bx bx-search" />}- hideToggleArrow- noSelectButtonStyle- placement="bottom-start"- 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>-- <SearchStringEditor- className="search-string"- currentValue={searchString}- placeholder={t("quick-search.placeholder")}- singleLine- editorRef={editorRef}- onChange={setSearchString}- onEnter={() => {- // Opening the results runs the search; open results are refreshed.- if (isOpenRef.current) {+ <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();- } else {- dropdownRef.current?.show();- }- editorRef.current?.focus();- }}- onEscape={() => {- if (!isOpenRef.current) return false;- dropdownRef.current?.hide();- return true;- }}- />+ }}+ onHidden={() => {+ isOpenRef.current = false;+ }}+ >+ <div className="quick-search-results">+ <QuickSearchResults+ searchState={searchState}+ onOpenResult={() => dropdownRef.current?.hide()}+ />+ </div>+ </DropdownPanel>++ <SearchStringEditor+ className="search-string"+ currentValue={searchString}+ placeholder={t("quick-search.placeholder")}+ singleLine+ editorRef={editorRef}+ onChange={setSearchString}+ 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;+ }}+ />+ </div></div>);}diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsxindex de8d83bc7a..f60d69d62a 100644--- a/apps/client/src/widgets/react/Dropdown.spec.tsx+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx@@ -104,6 +104,24 @@ 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 e6fcd312d5..ad71edf502 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 } from "preact";+import { ComponentChildren, HTMLAttributes, type RefObject } from "preact";import { CSSProperties, HTMLProps } from "preact/compat";import { MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";@@ -35,6 +35,11 @@ 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@@ -152,7 +157,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, 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, anchorRef, 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;@@ -306,7 +311,7 @@ function DropdownToggle({ id, className, buttonClassName, title, text, dropdownC{shown && triggerRef.current && popup({popupProps: {- anchor: triggerRef.current,+ anchor: anchorRef?.current ?? triggerRef.current,placement,offset: TOGGLE_GAP,// In a wrapper with the dropdown's classes, so CSS scoped under them still