Skip to content

Build your personal knowledge base with Trilium Notes

fix(quick_search): step from the field into the results with ArrowDown

Elian Doran7cd273bcc3f7
diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsx
index 343618335d..c041a97013 100644
--- a/apps/client/src/widgets/quick_search.spec.tsx
+++ b/apps/client/src/widgets/quick_search.spec.tsx
@@ -169,6 +169,47 @@ describe("QuickSearch", () => {
expect(editor.hasFocus).toBe(true);
});
+ it("steps from the field into the first result on ArrowDown, and back on ArrowUp", async () => {
+ vi.spyOn(server, "get").mockResolvedValue(response(3, []));
+ const { editor } = await mount();
+
+ typeQuery(editor, "hello");
+ pressEnter(editor);
+ const [ first ] = await waitForResults(3);
+ editor.focus();
+
+ // A modifier leaves the key to the field.
+ pressArrowDown(editor, { ctrlKey: true });
+ pressArrowDown(editor, { shiftKey: true });
+ expect(editor.hasFocus).toBe(true);
+
+ pressArrowDown(editor);
+ expect(document.activeElement).toBe(first);
+
+ act(() => {
+ first.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true, cancelable: true }));
+ });
+ expect(editor.hasFocus).toBe(true);
+ expect(menu()).not.toBeNull();
+ });
+
+ 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();
+
+ typeQuery(editor, "nothing");
+ editor.focus();
+ pressArrowDown(editor);
+ expect(editor.hasFocus).toBe(true);
+ expect(menu()).toBeNull();
+
+ pressEnter(editor);
+ await vi.waitFor(() => expect(get).toHaveBeenCalled());
+ await vi.waitFor(() => expect(placeholderItems()[0]?.querySelector(".bx-loader")).toBeNull());
+ pressArrowDown(editor);
+ 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();
@@ -258,6 +299,14 @@ function pressEnter(editor: EditorView) {
});
}
+function pressArrowDown(editor: EditorView, modifiers: KeyboardEventInit = {}) {
+ act(() => {
+ editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", {
+ key: "ArrowDown", code: "ArrowDown", bubbles: true, cancelable: true, ...modifiers
+ }));
+ });
+}
+
/** 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 6481b472b1..9ffe1ac1fc 100644
--- a/apps/client/src/widgets/quick_search.tsx
+++ b/apps/client/src/widgets/quick_search.tsx
@@ -36,7 +36,7 @@ export default function QuickSearch() {
const requestIdRef = useRef(0);
useTriliumEvent("quickSearch", () => editorRef.current?.focus());
- useResultNavigation(popupRef, open);
+ useResultNavigation(popupRef, open, () => editorRef.current?.focus());
/** Opens the results with a search for the query, or refreshes the open results. */
async function search() {
@@ -90,6 +90,12 @@ export default function QuickSearch() {
setHasQuery(value.length > 0);
}}
onEnter={() => void search()}
+ onArrowDown={() => {
+ const popup = popupRef.current;
+ if (!popup || !firstResult(popup)) return false;
+ focusListItem(popup, "first");
+ return true;
+ }}
/>
</div>
@@ -113,25 +119,43 @@ export default function QuickSearch() {
}
/**
- * 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.
+ * Moves focus between the results with Up and Down, and from the first result up to the field.
+ * 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) {
+function useResultNavigation(
+ popupRef: RefObject<HTMLElement>,
+ open: boolean,
+ focusField: () => void
+) {
+ const focusFieldRef = useRef(focusField);
+ focusFieldRef.current = focusField;
+
useEffect(() => {
if (!open) return;
const onKeyDown = (e: KeyboardEvent) => {
const popup = popupRef.current;
+ const target = e.target as Element;
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
- if (!popup?.contains(e.target as Node)) return;
+ if (!popup?.contains(target)) return;
e.preventDefault();
e.stopPropagation();
- focusListItem(popup, e.key === "ArrowDown" ? "next" : "previous", e.target as Element);
+ if (e.key === "ArrowUp" && target.closest(".dropdown-item") === firstResult(popup)) {
+ focusFieldRef.current();
+ } else {
+ focusListItem(popup, e.key === "ArrowDown" ? "next" : "previous", target);
+ }
};
window.addEventListener("keydown", onKeyDown, true);
return () => window.removeEventListener("keydown", onKeyDown, true);
}, [ open ]);
}
+/** The first result focus can move to; the searching and no-results rows are disabled. */
+function firstResult(popup: HTMLElement) {
+ return popup.querySelector(".dropdown-item:not(.disabled)");
+}
+
function QuickSearchResults({ searchState, onOpenResult }: {
searchState: SearchState | undefined;
onOpenResult(): void;
diff --git a/apps/client/src/widgets/quick_search_old.spec.ts b/apps/client/src/widgets/quick_search_old.spec.ts
index 749c648c35..41813763eb 100644
--- a/apps/client/src/widgets/quick_search_old.spec.ts
+++ b/apps/client/src/widgets/quick_search_old.spec.ts
@@ -13,29 +13,6 @@ describe("QuickSearchWidget", () => {
document.body.innerHTML = "";
});
- it("moves focus to the first result on ArrowDown, only while the popup is open", async () => {
- const widget = await renderAndSearch();
- const $firstItem = widget.$widget.find(".dropdown-menu .dropdown-item").first();
-
- widget.$widget.find(".dropdown-menu").removeClass("show");
- expect(widget.focusFirstResult()).toBe(false);
- expect(document.activeElement).not.toBe($firstItem[0]);
-
- widget.$widget.find(".dropdown-menu").addClass("show");
- expect(widget.focusFirstResult()).toBe(true);
- expect(document.activeElement).toBe($firstItem[0]);
- });
-
- it("leaves ArrowDown alone when the popup holds no result to focus", async () => {
- const widget = await renderAndSearch(0);
-
- const $disabled = widget.$widget.find(".dropdown-menu .dropdown-item.disabled");
- expect($disabled.length).toBe(1);
-
- expect(widget.focusFirstResult()).toBe(false);
- expect(document.activeElement).not.toBe($disabled[0]);
- });
-
it("searches for the query and hands it to the full search", async () => {
const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockResolvedValue(undefined);
const widget = renderWidget();
@@ -108,33 +85,6 @@ describe("QuickSearchWidget", () => {
});
});
-async function renderAndSearch(resultCount = 3) {
- const searchResults = Array.from({ length: resultCount }, (_, index) => ({
- notePath: `note${index}`,
- noteTitle: `Note ${index}`,
- notePathTitle: `Note ${index}`,
- highlightedNotePathTitle: `Note ${index}`,
- icon: "bx bx-note"
- }));
-
- vi.spyOn(server, "get").mockResolvedValue({
- searchResultNoteIds: searchResults.map((result) => result.notePath),
- searchResults,
- highlightedTokens: [],
- error: ""
- } as never);
-
- const widget = new QuickSearchWidget();
- widget.render();
- // Focus only moves within the document, and `show` is the class Bootstrap opens the menu with.
- widget.$widget.appendTo(document.body);
- widget.searchString = "hello";
- await widget.search();
- widget.$widget.find(".dropdown-menu").addClass("show");
-
- return widget;
-}
-
function renderWidget() {
const widget = new QuickSearchWidget();
widget.render();
diff --git a/apps/client/src/widgets/quick_search_old.ts b/apps/client/src/widgets/quick_search_old.ts
index 36b8c1f7c5..43023ec882 100644
--- a/apps/client/src/widgets/quick_search_old.ts
+++ b/apps/client/src/widgets/quick_search_old.ts
@@ -71,25 +71,6 @@ export default class QuickSearchWidget extends BasicWidget {
return this.$widget;
}
- /**
- * Steps from the field into the results on ArrowDown, which Bootstrap does not do on its own.
- * Searching and no-results leave only a disabled item, and the caret keeps the key.
- */
- focusFirstResult() {
- if (!this.isDropdownOpen()) {
- return false;
- }
-
- const $firstResult = this.$searchResults.find(".dropdown-item:not(.disabled)").first();
-
- if (!$firstResult.length) {
- return false;
- }
-
- $firstResult.focus();
- return true;
- }
-
async search() {
const searchString = this.searchString.trim();
@@ -217,11 +198,6 @@ export default class QuickSearchWidget extends BasicWidget {
}
}
- /** Whether the results popup is open, which is what makes ArrowDown move focus into it. */
- private isDropdownOpen() {
- return this.$dropdownMenu.hasClass("show");
- }
-
async showInFullSearch() {
this.dropdown.hide();
diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
index 2d01f29e8a..90173fc54c 100644
--- a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
@@ -28,6 +28,11 @@ interface SearchStringEditorProps {
onChange(newValue: string): void;
/** Runs when Enter is pressed, which the editor treats as "run this search". */
onEnter(): void;
+ /**
+ * Runs on ArrowDown while no completion is open, for a field with results listed below it.
+ * Returns whether the field took it; `false` moves the caret.
+ */
+ onArrowDown?(): boolean;
/**
* Runs on Escape, once the completion popup has passed the key on. Returns whether the field
* took it; `false` leaves it to whatever the field sits in.
@@ -66,13 +71,13 @@ const SINGLE_LINE_HINTS: ShortcutHintDefinition = [
*
* Written to edit the `#searchString` of a saved search, and used for a collection filter too.
*/
-export default function SearchStringEditor({ currentValue, noteId, placeholder, ariaLabel, className, autoFocus, singleLine, editorRef: exposedRef, onChange, onEnter, onEscape }: SearchStringEditorProps) {
+export default function SearchStringEditor({ currentValue, noteId, placeholder, ariaLabel, className, autoFocus, singleLine, editorRef: exposedRef, onChange, onEnter, onArrowDown, onEscape }: SearchStringEditorProps) {
const parentRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<FieldEditor>();
// The editor is built once, so it reaches the current props through a ref rather than
// through the closure of the render that created it.
- const propsRef = useRef({ currentValue, onChange, onEnter, onEscape });
- propsRef.current = { currentValue, onChange, onEnter, onEscape };
+ const propsRef = useRef({ currentValue, onChange, onEnter, onArrowDown, onEscape });
+ propsRef.current = { currentValue, onChange, onEnter, onArrowDown, onEscape };
// Set while the effect below writes `currentValue` into the document, so `onChange` does not
// report it as an edit the user made.
const isAdopting = useRef(false);
@@ -96,6 +101,7 @@ export default function SearchStringEditor({ currentValue, noteId, placeholder,
}
},
onEnter: () => propsRef.current.onEnter(),
+ onArrowDown: () => propsRef.current.onArrowDown?.() ?? false,
onEscape: () => propsRef.current.onEscape?.() ?? false
});
editorRef.current = editor;