Skip to content

Build your personal knowledge base with Trilium Notes

fix(quick_search): let hover and keyboard focus mark one result at a time

Elian Doran98a28290ccc2
diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsx
index 51d42c944e..793cc82a9b 100644
--- a/apps/client/src/widgets/quick_search.spec.tsx
+++ b/apps/client/src/widgets/quick_search.spec.tsx
@@ -196,6 +196,34 @@ describe("QuickSearch", () => {
expect(menu()).not.toBeNull();
});
+ it("lets the keys and the pointer take turns marking a result", async () => {
+ vi.spyOn(server, "get").mockResolvedValue(response(3, []));
+ const { editor } = await mount();
+
+ typeQuery(editor, "hello");
+ pressEnter(editor);
+ const [ first, , third ] = await waitForResults(3);
+ editor.focus();
+
+ // With focus in the field, a pointer moving over a result leaves the focus there.
+ movePointer(third, 4);
+ expect(editor.hasFocus).toBe(true);
+
+ // The keys mark their row and silence the hover a resting pointer would add.
+ pressArrowDown(editor);
+ expect(document.activeElement).toBe(first);
+ expect(menu()?.classList.contains("tn-menu-keyboard")).toBe(true);
+
+ // A pointer that does not move, as when a row slides under it, changes nothing.
+ movePointer(third, 0);
+ expect(document.activeElement).toBe(first);
+
+ // A pointer that moves takes over: its row gets the focus, so the keys go on from there.
+ movePointer(third, 4);
+ expect(document.activeElement).toBe(third);
+ expect(menu()?.classList.contains("tn-menu-keyboard")).toBe(false);
+ });
+
it("leaves ArrowDown to the field while the results are closed or hold nothing to focus", async () => {
const get = vi.spyOn(server, "get").mockResolvedValue(response(0, []));
const { editor } = await mount();
@@ -340,6 +368,12 @@ function pressArrowDown(editor: EditorView, modifiers: KeyboardEventInit = {}) {
});
}
+function movePointer(target: HTMLElement, movement: number) {
+ act(() => {
+ target.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, movementX: movement }));
+ });
+}
+
/** The popup is portaled to `<body>`, outside the rendered container. */
function menu() {
return document.querySelector<HTMLElement>(".quick-search-menu");
diff --git a/apps/client/src/widgets/quick_search.tsx b/apps/client/src/widgets/quick_search.tsx
index be1d642449..c56b93ec46 100644
--- a/apps/client/src/widgets/quick_search.tsx
+++ b/apps/client/src/widgets/quick_search.tsx
@@ -15,6 +15,7 @@ import Button from "./react/Button";
import { focusListItem } from "./react/FormList";
import { useTriliumEvent } from "./react/hooks";
import Icon from "./react/Icon";
+import { pointerMoved } from "./react/menu_context";
import Popup from "./react/Popup";
import RawHtml, { RawHtmlBlock } from "./react/RawHtml";
import SearchStringEditor from "./ribbon/SearchStringEditor";
@@ -29,6 +30,8 @@ export default function QuickSearch() {
const [ hasQuery, setHasQuery ] = useState(false);
const [ searchState, setSearchState ] = useState<SearchState>();
const [ open, setOpen ] = useState(false);
+ // Set while the keys move through the results; see `.tn-menu-keyboard` in Menu.css.
+ const [ keyboardDriven, setKeyboardDriven ] = useState(false);
const editorRef = useRef<FieldEditor>();
const boxRef = useRef<HTMLDivElement>(null);
const popupRef = useRef<HTMLDivElement | null>(null);
@@ -36,7 +39,10 @@ export default function QuickSearch() {
const requestIdRef = useRef(0);
useTriliumEvent("quickSearch", () => editorRef.current?.focus());
- useResultNavigation(popupRef, open, () => editorRef.current?.focus());
+ useResultNavigation(popupRef, open, {
+ focusField: () => editorRef.current?.focus(),
+ onMoved: () => setKeyboardDriven(true)
+ });
/** Opens the results with a search for the query, or refreshes the open results. */
async function search() {
@@ -64,13 +70,15 @@ export default function QuickSearch() {
function showInFullSearch() {
close();
- void appContext.triggerCommand("searchNotes", { searchString: searchStringRef.current.trim() });
+ const searchString = searchStringRef.current.trim();
+ void appContext.triggerCommand("searchNotes", { searchString });
}
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);
+ setKeyboardDriven(false);
}
return (
@@ -109,6 +117,7 @@ export default function QuickSearch() {
const popup = popupRef.current;
if (!popup || !firstResult(popup)) return false;
focusListItem(popup, "first");
+ setKeyboardDriven(true);
return true;
}}
/>
@@ -120,8 +129,20 @@ export default function QuickSearch() {
placement="bottom-start"
offset={2}
capHeight={false}
- className="dropdown-menu show tn-dropdown-menu quick-search-menu"
+ className={clsx("dropdown-menu show tn-dropdown-menu quick-search-menu",
+ keyboardDriven && "tn-menu-keyboard")}
elementRef={popupRef}
+ onPointerMove={(e) => {
+ if (!pointerMoved(e)) return;
+ setKeyboardDriven(false);
+ // With focus in the results, the pointer's row takes it, so the keys go on
+ // from there; with focus in the field, the field keeps it.
+ const row = (e.target as Element).closest<HTMLElement>(".dropdown-item");
+ if (row && !row.classList.contains("disabled")
+ && popupRef.current?.contains(document.activeElement)) {
+ row.focus({ preventScroll: true });
+ }
+ }}
onDismiss={close}
>
<div className="quick-search-results">
@@ -146,13 +167,14 @@ export default function QuickSearch() {
* 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,
- focusField: () => void
-) {
- const focusFieldRef = useRef(focusField);
- focusFieldRef.current = focusField;
+function useResultNavigation(popupRef: RefObject<HTMLElement>, open: boolean, callbacks: {
+ /** Runs for ArrowUp on the first result. */
+ focusField(): void;
+ /** Runs once the keys have moved focus to another result. */
+ onMoved(): void;
+}) {
+ const callbacksRef = useRef(callbacks);
+ callbacksRef.current = callbacks;
useEffect(() => {
if (!open) return;
@@ -164,9 +186,10 @@ function useResultNavigation(
e.preventDefault();
e.stopPropagation();
if (e.key === "ArrowUp" && target.closest(".dropdown-item") === firstResult(popup)) {
- focusFieldRef.current();
+ callbacksRef.current.focusField();
} else {
focusListItem(popup, e.key === "ArrowDown" ? "next" : "previous", target);
+ callbacksRef.current.onMoved();
}
};
window.addEventListener("keydown", onKeyDown, true);
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index 2ab3210afd..6acccaa6f0 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -70,9 +70,10 @@ body.desktop .dropdown-item.dropdown-submenu.submenu-open,
* Once the keys move the active row, a pointer at rest still hovers the row it left, which would
* mark a second row until the pointer moves. The row looks unhovered meanwhile, as in the resting
* `.dropdown-item` rule. `!important` and the extra classes outrank the theme's `:hover` rule in
- * style.css, whose values these undo.
+ * style.css, whose values these undo. A popup whose rows take focus themselves, such as the quick
+ * search's results, sets the class too; its focused row is the keys' row.
*/
-.tn-menu.tn-menu-keyboard .dropdown-item:hover:not(.disabled, .active, .dropdown-container-item, .tn-menu-active, .submenu-open) {
+.tn-menu-keyboard .dropdown-item:hover:not(.disabled, .active, .dropdown-container-item, .tn-menu-active, .submenu-open, :focus) {
color: var(--menu-text-color) !important;
background-color: transparent !important;
border-color: transparent !important;