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(note_type_chooser): keep parent-path focus when types load late
Jakob Schlanstedt518312ba66f2
diff --git a/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx b/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsxindex 805123c15c..8063ef5439 100644--- a/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx+++ b/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx@@ -1,7 +1,3 @@-/**- * 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";@@ -19,12 +15,33 @@ vi.mock("../../services/i18n", () => ({t: (key: string) => key}));+const noteTypeItems = vi.hoisted(() => {+ const items = [+ { title: "Text", type: "text", uiIcon: "bx bx-note" },+ { title: "Code", type: "code", uiIcon: "bx bx-code" }+ ];+ let resolveItems: (value: typeof items) => void = () => {};+ let promise = Promise.resolve(items);++ return {+ resetDeferred() {+ promise = new Promise((resolve) => {+ resolveItems = resolve;+ });+ },+ resolve() {+ resolveItems(items);+ return promise;+ },+ get() {+ return promise;+ }+ };+});+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" }- ])+ getNoteTypeItems: () => noteTypeItems.get()}}));@@ -70,6 +87,7 @@ describe("NoteTypeChooserDialog", () => {let host: Component;beforeEach(() => {+ noteTypeItems.resetDeferred();container = document.createElement("div");document.body.appendChild(container);host = new Component();@@ -92,19 +110,18 @@ describe("NoteTypeChooserDialog", () => {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();- });+ await openChooser(callback);+ await resolveNoteTypes();- const textItem = container.querySelector<HTMLElement>('.dropdown-item[data-value="text,"]');- expect(textItem).not.toBeNull();- expect(document.activeElement).toBe(textItem);+ const item = textItem();+ expect(item).not.toBeNull();+ expect(document.activeElement).toBe(item);- const event = new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true });- textItem?.dispatchEvent(event);+ item?.dispatchEvent(new KeyboardEvent("keydown", {+ key: "Enter",+ bubbles: true,+ cancelable: true+ }));expect(callback).toHaveBeenCalledExactlyOnceWith({success: true,@@ -113,4 +130,43 @@ describe("NoteTypeChooserDialog", () => {notePath: undefined});});++ it("does not steal focus from the parent-path field when types arrive late", async () => {+ await openChooser();++ const input = parentPathInput();+ input.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));+ input.focus();+ expect(document.activeElement).toBe(input);++ await resolveNoteTypes();++ expect(textItem()).not.toBeNull();+ expect(document.activeElement).toBe(input);+ });++ async function openChooser(callback = vi.fn()) {+ await act(async () => {+ await host.handleEventInChildren("chooseNoteType", { callback });+ });+ return callback;+ }++ async function resolveNoteTypes() {+ await act(async () => {+ await noteTypeItems.resolve();+ });+ }++ function textItem() {+ return container.querySelector<HTMLElement>('.dropdown-item[data-value="text,"]');+ }++ function parentPathInput() {+ const input = container.querySelector<HTMLInputElement>(".note-autocomplete");+ if (!input) {+ throw new Error("The parent-path field was missing.");+ }+ return input;+ }});diff --git a/apps/client/src/widgets/dialogs/note_type_chooser.tsx b/apps/client/src/widgets/dialogs/note_type_chooser.tsxindex e8587b66ae..1f269299a3 100644--- a/apps/client/src/widgets/dialogs/note_type_chooser.tsx+++ b/apps/client/src/widgets/dialogs/note_type_chooser.tsx@@ -33,8 +33,10 @@ export default function NoteTypeChooserDialogComponent() {const [ parentNote, setParentNote ] = useState<Suggestion | null>();const [ noteTypes, setNoteTypes ] = useState<MenuItem<TreeCommandNames>[]>([]);const modalRef = useRef<HTMLDivElement>(null);+ const userMovedFocus = useRef(false);useTriliumEvent("chooseNoteType", ({ callback }) => {+ userMovedFocus.current = false;setCallback(() => callback);setShown(true);});@@ -57,14 +59,42 @@ 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(() => {+ const modal = modalRef.current;+ if (!shown || !modal) {+ return;+ }++ const onUserGesture = (e: Event) => {+ const target = e.target as HTMLElement | null;+ if (target?.closest(".dropdown-item")) {+ return;+ }+ userMovedFocus.current = true;+ };++ modal.addEventListener("pointerdown", onUserGesture);+ modal.addEventListener("keydown", onUserGesture);+ return () => {+ modal.removeEventListener("pointerdown", onUserGesture);+ modal.removeEventListener("keydown", onUserGesture);+ };+ }, [ shown ]);++ // Opening focuses the first type so Enter creates it, unless the user is already on the+ // parent-path field.useEffect(() => {if (shown && noteTypes.length > 0) {- focusFirstNoteType(modalRef.current);+ tryFocusFirstNoteType();}}, [ shown, noteTypes.length ]);+ function tryFocusFirstNoteType() {+ if (!userMovedFocus.current) {+ focusFirstNoteType(modalRef.current);+ }+ }+function onNoteTypeSelected(value: string) {const [ noteType, templateNoteId ] = value.split(",");@@ -85,7 +115,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={() => focusFirstNoteType(modalRef.current)}+ onShown={tryFocusFirstNoteType}onHidden={() => {callback?.({ success: false });setShown(false);