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
refactor(form-list): move between a list's items without a Bootstrap dropdown
Elian Doranc80ac4702c6a
diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsxindex 2803918bef..f28380fa34 100644--- a/apps/client/src/widgets/react/Dropdown.tsx+++ b/apps/client/src/widgets/react/Dropdown.tsx@@ -6,6 +6,7 @@ import { CSSProperties, HTMLProps } from "preact/compat";import { MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";import { isMobile } from "../../services/utils";+import { focusListItem } from "./FormList";import { useTooltip, useUniqueName } from "./hooks";import { suspendModalFocusTraps } from "./modal_focustrap";import Menu from "./Menu";@@ -116,7 +117,7 @@ export function DropdownPanel({ scrollable, ...props }: DropdownPanelProps) {<DropdownToggle{...props}hasPopup="true"- onToggleArrow={(popup, edge) => focusItem(popup, edge)}+ onToggleArrow={(popup, edge) => focusListItem(popup, edge)}popup={({ popupProps, className, bottomSheet, startAt, dismiss }) => (<PanelPopup{...popupProps}@@ -348,7 +349,7 @@ function PanelPopup({ startAt, elementRef, ...props }: PopupProps & { startAt: "if (!popup?.contains(target) || /input|textarea/i.test(target.tagName)) return;e.preventDefault();e.stopPropagation();- focusItem(popup, e.key === "ArrowDown" ? "next" : "previous", target);+ focusListItem(popup, e.key === "ArrowDown" ? "next" : "previous", target);};window.addEventListener("keydown", onKeyDown, true);return () => window.removeEventListener("keydown", onKeyDown, true);@@ -365,26 +366,8 @@ function PanelPopup({ startAt, elementRef, ...props }: PopupProps & { startAt: "{...props}elementRef={setElement}onPlaced={() => {- if (startAt && popupRef.current) focusItem(popupRef.current, startAt);+ if (startAt && popupRef.current) focusListItem(popupRef.current, startAt);}}/>);}--/**- * Focuses an enabled item of `popup`'s own, not one in a submenu nested in it: the first or the- * last, or the one after or before `from`, going round at either end, as Bootstrap's did.- */-function focusItem(popup: HTMLElement, where: "first" | "last" | "next" | "previous", from?: Element) {- const items = [ ...popup.querySelectorAll<HTMLElement>(".dropdown-item:not(.disabled):not(:disabled)") ]- .filter((item) => item.parentElement?.closest(".dropdown-menu") === popup);- if (!items.length) return;-- const current = from?.closest<HTMLElement>(".dropdown-item");- const index = current ? items.indexOf(current) : -1;- let target: HTMLElement | undefined;- if (where === "first" || (where === "next" && index < 0)) target = items[0];- else if (where === "last" || (where === "previous" && index < 0)) target = items.at(-1);- else target = items[(index + (where === "next" ? 1 : -1) + items.length) % items.length];- target?.focus();-}diff --git a/apps/client/src/widgets/react/FormList.spec.tsx b/apps/client/src/widgets/react/FormList.spec.tsxindex cd8a50fa87..72f82426d0 100644--- a/apps/client/src/widgets/react/FormList.spec.tsx+++ b/apps/client/src/widgets/react/FormList.spec.tsx@@ -1,10 +1,8 @@import { type ComponentChildren, render } from "preact";import { describe, expect, it, vi } from "vitest";-// FormList instantiates a real Bootstrap dropdown in an effect; stub it so the-// component mounts without pulling in Bootstrap's layout-dependent machinery.+// Rows with a tooltip reach Bootstrap's; stub it so they mount without its layout machinery.vi.mock("bootstrap", () => ({- Dropdown: { getOrCreateInstance: () => ({ dispose() {} }) },Tooltip: class { static getInstance() { return null; } }}));@@ -196,6 +194,46 @@ describe("FormList keyboard activation", () => {expect(onSelect).not.toHaveBeenCalled();expect(event.defaultPrevented).toBe(false);});++ it("moves focus over the enabled items with Up and Down, keeping the keys from the document", () => {+ const container = mount(+ <FormList>+ <input className="embedded-search" />+ <FormListItem value="text">Text</FormListItem>+ <FormListItem value="code" disabled>Code</FormListItem>+ <FormListItem value="book">Book</FormListItem>+ </FormList>+ );+ // Bootstrap's dropdown handler listens there, and throws for a list with no toggle.+ const documentHeard = vi.fn();+ document.addEventListener("keydown", documentHeard, true);+ expect(container.querySelector("[data-bs-toggle]")).toBeNull();++ press(getItem(container, "text"), "ArrowDown");+ expect(document.activeElement).toBe(getItem(container, "book"));+ // Round from the last item to the first.+ press(getItem(container, "book"), "ArrowDown");+ expect(document.activeElement).toBe(getItem(container, "text"));+ press(getItem(container, "text"), "ArrowUp");+ expect(document.activeElement).toBe(getItem(container, "book"));+ expect(documentHeard).not.toHaveBeenCalled();++ // A field keeps its own.+ const input = container.querySelector<HTMLInputElement>(".embedded-search");+ expect(input).not.toBeNull();+ const event = press(input as HTMLInputElement, "ArrowDown");+ expect(event.defaultPrevented).toBe(false);+ document.removeEventListener("keydown", documentHeard, true);+ });++ it("keeps Escape from Bootstrap's handler, and from a dialog around it as that handler did", () => {+ const container = mount(<FormList><FormListItem value="text">Text</FormListItem></FormList>);+ const dialogHeard = vi.fn();+ container.addEventListener("keydown", dialogHeard);++ expect(() => press(getItem(container, "text"), "Escape")).not.toThrow();+ expect(dialogHeard).not.toHaveBeenCalled();+ });});function renderList() {diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsxindex f8f0aed568..d20344ee2f 100644--- a/apps/client/src/widgets/react/FormList.tsx+++ b/apps/client/src/widgets/react/FormList.tsx@@ -2,10 +2,10 @@ import "./FormList.css";import { autoUpdate } from "@floating-ui/dom";import type { KeyboardActionNames } from "@triliumnext/commons";-import { Dropdown as BootstrapDropdown, Tooltip } from "bootstrap";+import type { Tooltip } from "bootstrap";import clsx from "clsx";import { ComponentChildren, RefObject } from "preact";-import { createPortal, type CSSProperties, useContext, useEffect, useLayoutEffect, useMemo, useRef } from "preact/compat";+import { createPortal, type CSSProperties, useContext, useLayoutEffect, useMemo, useRef } from "preact/compat";import { getActionSync } from "../../services/keyboard_actions";import { handleRightToLeftPlacement, isMobile, openInAppHelpFromUrl } from "../../services/utils";@@ -27,23 +27,27 @@ interface FormListOpts {}export default function FormList({ children, onSelect, style, fullHeight, wrapperClassName }: FormListOpts) {- const wrapperRef = useRef<HTMLDivElement | null>(null);- const triggerRef = useRef<HTMLButtonElement | null>(null);+ const listRef = useRef<HTMLDivElement | null>(null);- useEffect(() => {- if (!triggerRef.current || !wrapperRef.current) {- return;- }-- const $wrapperRef = $(wrapperRef.current);- const dropdown = BootstrapDropdown.getOrCreateInstance(triggerRef.current);- $wrapperRef.on("hide.bs.dropdown", (e) => e.preventDefault());-- return () => {- $wrapperRef.off("hide.bs.dropdown");- dropdown.dispose();+ // Captured at the window: Bootstrap captures Escape, Up and Down at the document for any+ // `.dropdown-menu`, and throws for one with no toggle beside it. Escape goes no further, as+ // Bootstrap kept it from a dialog around the list too.+ useLayoutEffect(() => {+ const onKeyDown = (e: KeyboardEvent) => {+ const list = listRef.current;+ const target = e.target as Element;+ if (!list?.contains(target)) return;+ if (e.key === "Escape") {+ e.stopPropagation();+ } else if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !/input|textarea/i.test(target.tagName)) {+ e.preventDefault();+ e.stopPropagation();+ focusListItem(list, e.key === "ArrowDown" ? "next" : "previous", target);+ }};- }, [ triggerRef, wrapperRef ]);+ window.addEventListener("keydown", onKeyDown, true);+ return () => window.removeEventListener("keydown", onKeyDown, true);+ }, []);const builtinStyles = useMemo(() => {const style: CSSProperties = {};@@ -55,14 +59,9 @@ export default function FormList({ children, onSelect, style, fullHeight, wrappe}, [ fullHeight ]);return (- <div className={clsx("dropdownWrapper", wrapperClassName)} ref={wrapperRef} style={builtinStyles}>+ <div className={clsx("dropdownWrapper", wrapperClassName)} style={builtinStyles}><div className="dropdown" style={builtinStyles}>- <button- ref={triggerRef}- type="button" style="display: none;"- data-bs-toggle="dropdown" data-bs-display="static" />-- <div class="dropdown-menu static show" style={{+ <div ref={listRef} class="dropdown-menu static show" style={{...style ?? {},...builtinStyles,position: "relative",@@ -108,6 +107,24 @@ function onDropdownMenuKeyDown(e: KeyboardEvent) {dropdownItem.click();}+/**+ * Focuses an enabled item of `list`'s own, not one in a submenu nested in it: the first or the+ * last, or the one after or before `from`, going round at either end.+ */+export function focusListItem(list: HTMLElement, where: "first" | "last" | "next" | "previous", from?: Element) {+ const items = [ ...list.querySelectorAll<HTMLElement>(".dropdown-item:not(.disabled):not(:disabled)") ]+ .filter((item) => item.parentElement?.closest(".dropdown-menu") === list);+ if (!items.length) return;++ const current = from?.closest<HTMLElement>(".dropdown-item");+ const index = current ? items.indexOf(current) : -1;+ let target: HTMLElement | undefined;+ if (where === "first" || (where === "next" && index < 0)) target = items[0];+ else if (where === "last" || (where === "previous" && index < 0)) target = items.at(-1);+ else target = items[(index + (where === "next" ? 1 : -1) + items.length) % items.length];+ target?.focus();+}+export interface FormListBadge {className?: string;text: string;