Skip to content

Build your personal knowledge base with Trilium Notes

feat(note_type_chooser): focus first note type by default in note type chooser

Jakob Schlanstedtaf5c1cd9eaad
diff --git a/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx b/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx
new file mode 100644
index 0000000000..805123c15c
--- /dev/null
+++ b/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx
@@ -0,0 +1,116 @@
+/**
+ * Opening the chooser used to focus the parent-path search, so Enter did nothing useful.
+ * Focus belongs on the first type (Text) so a second Enter creates a text note.
+ */
+import { render } from "preact";
+import { useEffect, useRef } from "preact/hooks";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import Component from "../../components/component";
+import { ParentComponent } from "../react/react_utils";
+
+vi.mock("bootstrap", () => ({
+ Dropdown: { getOrCreateInstance: () => ({ dispose() {} }) },
+ Tooltip: class { static getInstance() { return null; } }
+}));
+
+vi.mock("../../services/i18n", () => ({
+ t: (key: string) => key
+}));
+
+vi.mock("../../services/note_types", () => ({
+ default: {
+ getNoteTypeItems: () => Promise.resolve([
+ { title: "Text", type: "text", uiIcon: "bx bx-note" },
+ { title: "Code", type: "code", uiIcon: "bx bx-code" }
+ ])
+ }
+}));
+
+vi.mock("../react/NoteAutocomplete", () => ({
+ default: function NoteAutocompleteStub() {
+ return <input className="note-autocomplete" />;
+ }
+}));
+
+vi.mock("../react/Modal", () => ({
+ default: function ModalStub({
+ show, children, onShown, modalRef, className
+ }: {
+ show: boolean;
+ children: preact.ComponentChildren;
+ onShown?: () => void;
+ modalRef?: { current: HTMLDivElement | null };
+ className: string;
+ }) {
+ const ref = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (modalRef) {
+ modalRef.current = ref.current;
+ }
+ if (show) {
+ onShown?.();
+ }
+ });
+
+ if (!show) {
+ return null;
+ }
+
+ return <div className={className} ref={ref}>{children}</div>;
+ }
+}));
+
+import NoteTypeChooserDialogComponent from "./note_type_chooser";
+
+describe("NoteTypeChooserDialog", () => {
+ let container: HTMLElement;
+ let host: Component;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ host = new Component();
+
+ act(() => {
+ render(
+ <ParentComponent.Provider value={host}>
+ <NoteTypeChooserDialogComponent />
+ </ParentComponent.Provider>,
+ container
+ );
+ });
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ it("focuses Text on open so Enter creates a text note", async () => {
+ const callback = vi.fn();
+
+ await act(async () => {
+ await host.handleEventInChildren("chooseNoteType", { callback });
+ });
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ const textItem = container.querySelector<HTMLElement>('.dropdown-item[data-value="text,"]');
+ expect(textItem).not.toBeNull();
+ expect(document.activeElement).toBe(textItem);
+
+ const event = new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true });
+ textItem?.dispatchEvent(event);
+
+ expect(callback).toHaveBeenCalledExactlyOnceWith({
+ success: true,
+ noteType: "text",
+ templateNoteId: "",
+ notePath: undefined
+ });
+ });
+});
diff --git a/apps/client/src/widgets/dialogs/note_type_chooser.tsx b/apps/client/src/widgets/dialogs/note_type_chooser.tsx
index df150e4948..e8587b66ae 100644
--- a/apps/client/src/widgets/dialogs/note_type_chooser.tsx
+++ b/apps/client/src/widgets/dialogs/note_type_chooser.tsx
@@ -10,7 +10,6 @@ import { TreeCommandNames } from "../../menus/tree_context_menu";
import { Suggestion } from "../../services/note_autocomplete";
import SimpleBadge from "../react/Badge";
import { useTriliumEvent } from "../react/hooks";
-import { refToJQuerySelector } from "../react/react_utils";
export interface ChooseNoteTypeResponse {
success: boolean;
@@ -34,7 +33,6 @@ export default function NoteTypeChooserDialogComponent() {
const [ parentNote, setParentNote ] = useState<Suggestion | null>();
const [ noteTypes, setNoteTypes ] = useState<MenuItem<TreeCommandNames>[]>([]);
const modalRef = useRef<HTMLDivElement>(null);
- const autocompleteRef = useRef<HTMLInputElement>(null);
useTriliumEvent("chooseNoteType", ({ callback }) => {
setCallback(() => callback);
@@ -59,6 +57,14 @@ export default function NoteTypeChooserDialogComponent() {
});
}, []);
+ // The types load asynchronously; Bootstrap then focuses the first field, so `onShown` repeats
+ // this after the dialog is up. Enter then creates a text note (the first type).
+ useEffect(() => {
+ if (shown && noteTypes.length > 0) {
+ focusFirstNoteType(modalRef.current);
+ }
+ }, [ shown, noteTypes.length ]);
+
function onNoteTypeSelected(value: string) {
const [ noteType, templateNoteId ] = value.split(",");
@@ -79,11 +85,7 @@ export default function NoteTypeChooserDialogComponent() {
size="md"
zIndex={1100} // note type chooser needs to be higher than other dialogs from which it is triggered, e.g. "add link"
scrollable
- onShown={() => {
- refToJQuerySelector(autocompleteRef)
- .trigger("focus")
- .trigger("select");
- }}
+ onShown={() => focusFirstNoteType(modalRef.current)}
onHidden={() => {
callback?.({ success: false });
setShown(false);
@@ -93,7 +95,6 @@ export default function NoteTypeChooserDialogComponent() {
>
<FormGroup name="parent-note" label={t("note_type_chooser.change_path_prompt")}>
<NoteAutocomplete
- inputRef={autocompleteRef}
onChange={setParentNote}
placeholder={t("note_type_chooser.search_placeholder")}
opts={{
@@ -129,3 +130,7 @@ export default function NoteTypeChooserDialogComponent() {
</Modal>
);
}
+
+function focusFirstNoteType(modal: HTMLDivElement | null) {
+ modal?.querySelector<HTMLElement>(".dropdownWrapper .dropdown-item:not(.disabled)")?.focus();
+}