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
feat(menu): reach the context menu's color picker from the keyboard
Elian Dorane677111e8ba9
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex fce3c2e830..c5ae52c6f8 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -1,3 +1,4 @@+import { h } from "preact";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";vi.mock("../services/note_tooltip", () => ({ default: { dismissAllTooltips: vi.fn() } }));@@ -754,6 +755,45 @@ describe("contextMenu", () => {vi.restoreAllMocks();});+ it("steps into a custom row that has something to focus, and leaves it the keys it answers", async () => {+ buildPage();+ const contextMenu = await buildContextMenu();+ const widgetHeard = vi.fn();+ await contextMenu.show({+ x: 10, y: 10, selectMenuItemHandler: () => {},+ items: [+ { title: "Cut" },+ // Nothing to focus, so the keys pass it by.+ { kind: "custom", componentFn: () => h("span", {}, "A note") },+ // Such as the color picker, whose way in is its selected cell.+ { kind: "custom", componentFn: () => h("div", { class: "widget", tabIndex: 0, onKeyDown: (e: KeyboardEvent) => widgetHeard(e.key) }) },+ { title: "Paste" }+ ]+ });+ await vi.waitFor(() => expect(document.activeElement).toBe(menuElement()));+ const widget = menuElement()?.querySelector(".widget");++ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Cut"));+ key("ArrowDown");+ await vi.waitFor(() => expect(document.activeElement).toBe(widget));++ // Its own keys reach it; the menu keeps Up, Down, Escape and Tab.+ key("ArrowRight");+ key("Enter");+ expect(widgetHeard.mock.calls.map(([ name ]) => name)).toEqual([ "ArrowRight", "Enter" ]);++ key("ArrowDown");+ await vi.waitFor(() => expect(activeRow()).toBe("Paste"));+ expect(document.activeElement).toBe(menuElement());+ key("ArrowUp");+ await vi.waitFor(() => expect(document.activeElement).toBe(widget));+ expect(widgetHeard).toHaveBeenCalledTimes(2);++ key("Escape");+ expect(contextMenu.isShown).toBe(false);+ });+it("closes a submenu the pointer opened once the keys move off its row", async () => {await openMenu();const templates = [ ...menuElement()?.querySelectorAll<HTMLElement>("li.dropdown-item") ?? [] ]diff --git a/apps/client/src/widgets/react/ColorPicker.css b/apps/client/src/widgets/react/ColorPicker.cssindex 08cfe9a341..46593c5e8c 100644--- a/apps/client/src/widgets/react/ColorPicker.css+++ b/apps/client/src/widgets/react/ColorPicker.css@@ -36,6 +36,12 @@outline-offset: 2px;}+/* The cell the keys stand on, which Enter or Space picks. */+.color-picker .color-cell:focus-visible {+ outline: 2px solid var(--input-focus-outline-color);+ outline-offset: 2px;+}+/** RESET COLOR CELL*/diff --git a/apps/client/src/widgets/react/ColorPicker.spec.tsx b/apps/client/src/widgets/react/ColorPicker.spec.tsxindex 6952c20a78..012980567c 100644--- a/apps/client/src/widgets/react/ColorPicker.spec.tsx+++ b/apps/client/src/widgets/react/ColorPicker.spec.tsx@@ -271,4 +271,72 @@ describe("ColorPicker", () => {const noneWrapper = none.querySelector(".custom-color-cell")?.parentElement;expect(noneWrapper?.getAttribute("style")).toContain("inherit");});++ describe("keyboard", () => {+ function key(name: string) {+ const event = new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true });+ (document.activeElement ?? document.body).dispatchEvent(event);+ return event;+ }++ it("is a list of options, entered at the selected one", async () => {+ const container = await renderColorPicker(<ColorPicker currentValue="#4de64d" onChange={vi.fn()} />);++ expect(container.querySelector(".color-picker")?.getAttribute("role")).toBe("listbox");+ const all = cells(container);+ expect(all.every((cell) => cell.getAttribute("role") === "option")).toBe(true);+ // One way in: the selected cell, which the listbox and a menu row focus first.+ expect(all.filter((cell) => cell.tabIndex === 0)).toEqual([ presetCells(container)[4] ]);+ expect(all.map((cell) => cell.getAttribute("aria-selected"))).toEqual(+ all.map((cell) => String(cell === presetCells(container)[4])));+ // The native input behind the custom cell is no stop of its own.+ expect(container.querySelector<HTMLInputElement>("input[type=color]")?.tabIndex).toBe(-1);++ // With nothing selected, the list is entered at its first cell.+ const indeterminate = await renderColorPicker(<ColorPicker currentValue="#4de64d" indeterminate onChange={vi.fn()} />);+ expect(cells(indeterminate).filter((cell) => cell.tabIndex === 0)).toEqual([ resetCell(indeterminate) ]);+ // A disabled picker cannot be entered at all.+ const disabled = await renderColorPicker(<ColorPicker currentValue={null} disabled onChange={vi.fn()} />);+ expect(cells(disabled).filter((cell) => cell.tabIndex === 0)).toEqual([]);+ });++ it("moves focus with the arrows and the ends without picking, and picks on Enter or Space", async () => {+ const onChange = vi.fn();+ const container = await renderColorPicker(<ColorPicker currentValue={null} onChange={onChange} />);+ const all = cells(container);+ all[0]?.focus();++ key("ArrowRight");+ expect(document.activeElement).toBe(all[1]);+ key("ArrowLeft");+ key("ArrowLeft");+ // It stops at either end.+ expect(document.activeElement).toBe(all[0]);+ key("End");+ expect(document.activeElement).toBe(customCell(container));+ key("Home");+ expect(document.activeElement).toBe(all[0]);+ // Only moved, nothing picked.+ expect(onChange).not.toHaveBeenCalled();++ key("ArrowRight");+ expect(key("Enter").defaultPrevented).toBe(true);+ expect(onChange).toHaveBeenLastCalledWith(DEFAULT_COLOR_PALETTE[0]);+ key("ArrowRight");+ key(" ");+ expect(onChange).toHaveBeenLastCalledWith(DEFAULT_COLOR_PALETTE[1]);+ });++ it("opens the native picker from the custom cell on Enter, as a click does", async () => {+ const container = await renderColorPicker(<ColorPicker currentValue={null} onChange={vi.fn()} />);+ const input = container.querySelector<HTMLInputElement>("input[type=color]");+ // Recorded rather than run: the input's click bubbles back to its cell, which a browser+ // leaves alone while that click is in progress and happy-dom does not.+ const opened = vi.spyOn(input as HTMLInputElement, "click").mockImplementation(() => {});++ customCell(container)?.focus();+ key("Enter");+ expect(opened).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/apps/client/src/widgets/react/ColorPicker.tsx b/apps/client/src/widgets/react/ColorPicker.tsxindex 4c1740d202..c13b3c3f0a 100644--- a/apps/client/src/widgets/react/ColorPicker.tsx+++ b/apps/client/src/widgets/react/ColorPicker.tsx@@ -6,7 +6,7 @@ import { ComponentChildren } from "preact";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../services/i18n";-import { isMobile } from "../../services/utils";+import { handleRightToLeftPlacement, isMobile } from "../../services/utils";import Debouncer from "../../utils/debouncer";/** Curated default preset palette, using Trilium note-color-friendly CSS colors. */@@ -48,13 +48,23 @@ export interface ColorPickerProps {export default function ColorPicker({ currentValue, onChange, presets = DEFAULT_COLOR_PALETTE, indeterminate, disabled, className, tooltips }: ColorPickerProps) {const normalizedValue = normalizeColor(currentValue);const isCustomColor = !indeterminate && normalizedValue !== null && presets.indexOf(normalizedValue) === -1;-- return <div className={clsx("color-picker", className)}>+ const isResetSelected = !indeterminate && normalizedValue === null;+ const isPresetSelected = !indeterminate && normalizedValue !== null && !isCustomColor;+ // The one cell Tab and a menu's keys enter at: the selected one, or with none the first.+ const isResetTabStop = !disabled && (isResetSelected || (!isPresetSelected && !isCustomColor));++ return <div+ className={clsx("color-picker", className)}+ role="listbox"+ aria-orientation="horizontal"+ onKeyDown={onColorPickerKeyDown}+ ><ColorCell className="color-cell-reset"tooltip={tooltips?.clear ?? t("color-picker.clear-color")}color={null}- isSelected={(!indeterminate && normalizedValue === null)}+ isSelected={isResetSelected}+ isTabStop={isResetTabStop}isDisabled={disabled}onSelect={onChange}>@@ -70,6 +80,7 @@ export default function ColorPicker({ currentValue, onChange, presets = DEFAULT_tooltip={tooltips?.set ?? t("color-picker.set-color")}color={color}isSelected={(!indeterminate && color === normalizedValue)}+ isTabStop={!disabled && !indeterminate && color === normalizedValue}isDisabled={disabled}onSelect={onChange} />))}@@ -77,17 +88,49 @@ export default function ColorPicker({ currentValue, onChange, presets = DEFAULT_<CustomColorCell tooltip={tooltips?.setCustom ?? t("color-picker.set-custom-color")}color={normalizedValue}isSelected={isCustomColor}+ isTabStop={!disabled && isCustomColor}isDisabled={disabled}onSelect={onChange} /></div>;}+/**+ * Moves focus between the cells with the arrows (towards the reading direction) and Home and End,+ * without picking: picking writes the color, so it waits for Enter or Space, which click the+ * focused cell as the pointer does.+ */+function onColorPickerKeyDown(e: KeyboardEvent) {+ const cells = [ ...(e.currentTarget as HTMLElement).querySelectorAll<HTMLElement>(".color-cell") ];+ const index = cells.indexOf(e.target as HTMLElement);+ if (index < 0) return;++ const forward = handleRightToLeftPlacement("right") === "right" ? "ArrowRight" : "ArrowLeft";+ const backward = forward === "ArrowRight" ? "ArrowLeft" : "ArrowRight";+ let target: number;+ switch (e.key) {+ case forward: target = Math.min(index + 1, cells.length - 1); break;+ case backward: target = Math.max(index - 1, 0); break;+ case "Home": target = 0; break;+ case "End": target = cells.length - 1; break;+ case "Enter":+ case " ":+ e.preventDefault();+ cells[index]?.click();+ return;+ default: return;+ }+ e.preventDefault();+ cells[target]?.focus();+}+interface ColorCellProps {children?: ComponentChildren,className?: string,tooltip?: string,color: string | null,isSelected: boolean,+ /** Whether Tab, and a menu's keys, enter the picker at this cell. */+ isTabStop?: boolean,isDisabled?: boolean,onSelect?: (color: string | null) => void}@@ -98,6 +141,10 @@ function ColorCell(props: ColorCellProps) {"selected": props.isSelected,"disabled-color-cell": props.isDisabled})}+ role="option"+ aria-selected={props.isSelected}+ aria-disabled={props.isDisabled || undefined}+ tabIndex={props.isTabStop ? 0 : -1}style={`${(props.color !== null) ? `--color: ${props.color}` : ""}`}title={props.tooltip}onClick={() => !props.isDisabled && props.onSelect?.(props.color)}>@@ -155,6 +202,8 @@ function CustomColorCell(props: ColorCellProps) {<input ref={colorInput}type="color"+ // Reached through its cell, so not a stop of its own.+ tabIndex={-1}disabled={props.isDisabled}value={pickedColor ?? props.color ?? "#40bfbf"}onChange={() => {colorInputDebouncer.current?.updateValue(colorInput.current?.value ?? null);}}diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxindex 5a84258aad..a824f70038 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -4,7 +4,7 @@ import { autoUpdate, computePosition, flip, hide, offset, type Placement, type Rimport clsx from "clsx";import { useCallback, useId, useLayoutEffect, useRef, useState } from "preact/hooks";-import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";+import type { CustomMenuItem, MenuCommandItem, MenuItem } from "../../menus/context_menu";import { getActionSync } from "../../services/keyboard_actions";import { handleRightToLeftPlacement, isMobile } from "../../services/utils";import { joinElements } from "./react_utils";@@ -46,12 +46,18 @@ interface OpenSubmenu<T> {key: number;}+/** A row the keyboard can stand on: a command, or a custom row with something to focus in it. */+type NavigableItem<T> = MenuCommandItem<T> | CustomMenuItem;+/** The row the keyboard acts on, and the level it stands at. */interface ActiveRow<T> {level: number;- item: MenuCommandItem<T>;+ item: NavigableItem<T>;}+/** The keys the menu keeps while focus is inside a custom row: those that leave it. */+const KEYS_LEAVING_CUSTOM_ROW = new Set([ "ArrowUp", "ArrowDown", "Escape", "Tab" ]);+/** How long typed letters keep adding to the text a row is looked up by. */const TYPEAHEAD_TIMEOUT = 500;@@ -67,9 +73,9 @@ interface MenuState<T> {/** The item whose submenu stands open at each level. */openItems: MenuCommandItem<T>[];active?: ActiveRow<T>;- setActive(level: number, item: MenuCommandItem<T>): void;+ setActive(level: number, item: NavigableItem<T>): void;/** Each row's element, for `aria-activedescendant` and for anchoring a submenu the keyboard opens. */- rows: Map<MenuCommandItem<T>, HTMLElement>;+ rows: Map<NavigableItem<T>, HTMLElement>;}export default function Menu<T>({ id, className, x, y, orientation, bottomSheet, items, onSelect, onClose }: MenuProps<T>) {@@ -85,12 +91,12 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,});}, []);const [ active, setActiveRow ] = useState<ActiveRow<T>>();- const rows = useRef(new Map<MenuCommandItem<T>, HTMLElement>()).current;+ const rows = useRef(new Map<NavigableItem<T>, HTMLElement>()).current;const typeahead = useRef({ text: "", timeout: 0 });/** Whether the keys moved the menu since the pointer last did. See `Menu.css`. */const [ keyboardDriven, setKeyboardDriven ] = useState(false);- const setActive = useCallback((level: number, item: MenuCommandItem<T>) => {+ const setActive = useCallback((level: number, item: NavigableItem<T>) => {setActiveRow({ level, item });rows.get(item)?.scrollIntoView?.({ block: "nearest" });}, [ rows ]);@@ -100,19 +106,34 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,// After the commit: a submenu's rows register their elements only as they mount.useLayoutEffect(() => {- const id = active && rows.get(active.item)?.id;+ const id = active && !isCustom(active.item) ? rows.get(active.item)?.id : undefined;if (id) menuRef.current?.setAttribute("aria-activedescendant", id);else menuRef.current?.removeAttribute("aria-activedescendant");}, [ active, submenus, rows ]);+ // A custom row takes focus in itself, for its own keys; any other row hands it back to the menu.+ useLayoutEffect(() => {+ const menu = menuRef.current;+ if (!menu || !active) return;+ if (isCustom(active.item)) {+ focusTarget(rows.get(active.item))?.focus({ preventScroll: true });+ } else if (document.activeElement !== menu && menu.contains(document.activeElement)) {+ menu.focus({ preventScroll: true });+ }+ }, [ active, rows ]);+const keyHandler = useRef(onKeyDown);keyHandler.current = onKeyDown;useLayoutEffect(() => {// Captured at the window: Bootstrap captures keys at the document for anything inside a- // `.dropdown-menu`, and takes them for a dropdown of its own. Only keys the menu itself- // receives, so a control inside a custom item keeps its own.+ // `.dropdown-menu`, and takes them for a dropdown of its own. Inside a custom row, only the+ // keys that leave it, so the control there keeps its own.const listener = (e: KeyboardEvent) => {- if (e.target === menuRef.current) keyHandler.current(e);+ const menu = menuRef.current;+ if (e.target === menu+ || (menu?.contains(e.target as Node) && KEYS_LEAVING_CUSTOM_ROW.has(e.key))) {+ keyHandler.current(e);+ }};window.addEventListener("keydown", listener, true);return () => window.removeEventListener("keydown", listener, true);@@ -120,11 +141,14 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,function onKeyDown(e: KeyboardEvent) {const level = active?.level ?? 0;- const levelRows = runnableRows(level === 0 ? items : submenus[level - 1]?.item.items ?? []);+ const levelRows = menuRows(level === 0 ? items : submenus[level - 1]?.item.items ?? [])+ .filter((row): row is NavigableItem<T> => isCustom(row)+ ? !!focusTarget(rows.get(row))+ : isRunnable(row));const index = active ? levelRows.indexOf(active.item) : -1;const count = levelRows.length;// A submenu goes with its row's highlight, as in a native menu, until Right opens it again.- const moveTo = (item: MenuCommandItem<T>) => {+ const moveTo = (item: NavigableItem<T>) => {if (submenus[level]?.item !== item) openSubmenu(level);setActive(level, item);};@@ -133,7 +157,7 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,if (item) moveTo(item);};const openActive = () => {- const item = active?.item;+ const item = active && !isCustom(active.item) ? active.item : undefined;const anchor = item && rows.get(item);if (!item?.items || !anchor || isMobile()) return;openSubmenu(level, item, anchor);@@ -163,7 +187,7 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,case "End": goTo(-1); break;// Into the active row's submenu, or else across to the next column.case rtl ? "ArrowLeft" : "ArrowRight":- if (active?.item.items) openActive();+ if (active && !isCustom(active.item) && active.item.items) openActive();else moveAcross(e.key === "ArrowRight" ? "right" : "left");break;// Back across a column, or else out of the submenu.@@ -172,7 +196,7 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,break;case "Enter":case " ":- if (!active) break;+ if (!active || isCustom(active.item)) break;openActive();onSelect(active.item, e);break;@@ -322,7 +346,14 @@ function MenuListRow<T>({ level, row, state }: { level: number, row: MenuItem<T>if (row.kind === "separator") return <div className="dropdown-divider" role="separator" />;if (row.kind === "header") return <h6 className="dropdown-header">{row.title}</h6>;return (- <li className="dropdown-custom-item" onClick={state.onClose}>+ <li+ className="dropdown-custom-item"+ ref={(element) => {+ if (element) state.rows.set(row, element);+ else state.rows.delete(row);+ }}+ onClick={state.onClose}+ ><row.componentFn /></li>);@@ -472,7 +503,20 @@ export function rowInNextColumn(/** The rows the keyboard can reach: those that run something, and are enabled. */function runnableRows<T>(items: MenuItem<T>[]) {- return menuRows(items).filter((row): row is MenuCommandItem<T> => !("kind" in row) && row.enabled !== false);+ return menuRows(items).filter(isRunnable);+}++function isRunnable<T>(row: MenuItem<T>): row is MenuCommandItem<T> {+ return !("kind" in row) && row.enabled !== false;+}++function isCustom<T>(row: MenuItem<T>): row is CustomMenuItem {+ return "kind" in row && row.kind === "custom";+}++/** Where a custom row takes focus: the element its content marks as its way in with `tabindex="0"`. */+function focusTarget(row: HTMLElement | undefined) {+ return row?.querySelector<HTMLElement>("[tabindex='0']") ?? null;}/** The items with a run of separators reduced to one. */