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
client/collections/board: add keyboard shortcut hints
Adorian Doranff4a5c0b68e6
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e0a21dc478..5b016df4f5 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3375,6 +3375,22 @@"column-already-exists": "This column already exists on the board.","column-definition-save-error": "The columns were saved on the board, but could not be saved to the status attribute.","save-error": "The change could not be saved.",+ "hints": {+ "navigation": "Navigation",+ "navigate_items": "Navigate between items",+ "navigate_columns": "Navigate between columns",+ "first_last_item": "First / last item of the column",+ "editing": "Editing",+ "insert_item": "Insert item below / above",+ "open_item": "Open item",+ "rename": "Rename item or column",+ "moving": "Moving",+ "move_item": "Move item up / down",+ "move_across": "Move to the previous / next column",+ "move_to_edge": "Move to the first / last column",+ "move_within": "Move to the top / bottom of the column",+ "move_column": "Move the column left / right"+ },"status-alias": "Status"},"dashboard_view": {diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 76c07f2859..d250b5282a 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -18,6 +18,7 @@ import { executeBulkActions } from "../../../services/bulk_action";import { buildNote } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";import BoardView, { BoardViewData } from ".";+import { collectShortcutHints } from "../../../services/shortcut_hints";import { getPendingWrites } from "./api";import { DEFAULT_COLUMN_ICON } from "./columns";@@ -277,6 +278,58 @@ describe("Board column rename", () => {second.remove();});+ it("offers its keys as contextual shortcut hints", async () => {+ const host = new Component();+ const note = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [ { title: "First", "#status": "To Do" } ]+ });++ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);+ await act(async () => {+ render(+ <ParentComponent.Provider value={host}>+ <Harness+ note={note}+ noteIds={[ ...note.getChildNoteIds() ]}+ initialConfig={DEFAULT_CONFIG}+ />+ </ParentComponent.Provider>,+ mountPoint+ );+ });+ await act(async () => { await flush(); });++ const sections = collectShortcutHints(host);++ expect(sections.map(section => section.titleKey)).toEqual([+ "board_view.hints.navigation",+ "board_view.hints.editing",+ "board_view.hints.moving"+ ]);+ // Every key the board answers for is spoken for, and none it does not.+ expect(sections.flatMap(section => section.hints)).toEqual([+ { keys: [ "Up", "Down" ], labelKey: "board_view.hints.navigate_items" },+ { keys: [ "Left", "Right" ], labelKey: "board_view.hints.navigate_columns" },+ { keys: [ "Home", "End" ], labelKey: "board_view.hints.first_last_item" },+ { keys: [ "Enter", "Shift+Enter" ], labelKey: "board_view.hints.insert_item" },+ { keys: [ "Space" ], labelKey: "board_view.hints.open_item" },+ { keys: [ "F2" ], labelKey: "board_view.hints.rename" },+ { keys: [ "Ctrl+Up", "Ctrl+Down" ], labelKey: "board_view.hints.move_item" },+ { keys: [ "Ctrl+Left", "Ctrl+Right" ], labelKey: "board_view.hints.move_across" },+ { keys: [ "Ctrl+Home", "Ctrl+End" ], labelKey: "board_view.hints.move_to_edge" },+ { keys: [ "Ctrl+PageUp", "Ctrl+PageDown" ], labelKey: "board_view.hints.move_within" },+ {+ keys: [ "Ctrl+Alt+Left", "Ctrl+Alt+Right" ],+ labelKey: "board_view.hints.move_column"+ }+ ]);+ });+/** Renames the middle column, so a slot that is not the last one has to survive. */async function renameSecondColumn(container: HTMLElement, newName: string) {return renameColumnAt(container, 1, newName);diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 41e7dd0eed..f694130991 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -7,13 +7,18 @@ import FNote from "../../../entities/fnote";import { t } from "../../../services/i18n";import type LoadResults from "../../../services/load_results";import { isIMEComposing } from "../../../services/shortcuts";+import type { ShortcutHintDefinition } from "../../../services/shortcut_hints";import toast from "../../../services/toast";+import { isMobile } from "../../../services/utils";import CollectionProperties from "../../note_bars/CollectionProperties";import FormTextArea from "../../react/FormTextArea";import FormTextBox from "../../react/FormTextBox";-import { useNoteLabelBoolean, useNoteLabelWithDefault, useTriliumEvent } from "../../react/hooks";+import {+ useContextualShortcutHints, useNoteLabelBoolean, useNoteLabelWithDefault, useTriliumEvent+} from "../../react/hooks";import Icon from "../../react/Icon";import NoteAutocomplete from "../../react/NoteAutocomplete";+import ShortcutHintButton from "../../shortcut_hints/shortcut_hint_button";import { onWheelHorizontalScroll } from "../../widget_utils";import { ViewModeProps } from "../interface";import Api, {@@ -104,6 +109,43 @@ export const BoardDragStateContext = createContext<BoardDragState>({dropTarget: null});+/**+ * What the board answers with when asked for contextual keyboard help. Every entry is a key the+ * board handles itself (see `keyboard.ts` and the card and column handlers), none of them+ * rebindable, so each is listed literally rather than through a registered action.+ */+const BOARD_HINTS: ShortcutHintDefinition = [+ {+ titleKey: "board_view.hints.navigation",+ hints: [+ { keys: [ "Up", "Down" ], labelKey: "board_view.hints.navigate_items" },+ { keys: [ "Left", "Right" ], labelKey: "board_view.hints.navigate_columns" },+ { keys: [ "Home", "End" ], labelKey: "board_view.hints.first_last_item" }+ ]+ },+ {+ titleKey: "board_view.hints.editing",+ hints: [+ { keys: [ "Enter", "Shift+Enter" ], labelKey: "board_view.hints.insert_item" },+ { keys: [ "Space" ], labelKey: "board_view.hints.open_item" },+ { keys: [ "F2" ], labelKey: "board_view.hints.rename" }+ ]+ },+ {+ titleKey: "board_view.hints.moving",+ hints: [+ { keys: [ "Ctrl+Up", "Ctrl+Down" ], labelKey: "board_view.hints.move_item" },+ { keys: [ "Ctrl+Left", "Ctrl+Right" ], labelKey: "board_view.hints.move_across" },+ { keys: [ "Ctrl+Home", "Ctrl+End" ], labelKey: "board_view.hints.move_to_edge" },+ { keys: [ "Ctrl+PageUp", "Ctrl+PageDown" ], labelKey: "board_view.hints.move_within" },+ {+ keys: [ "Ctrl+Alt+Left", "Ctrl+Alt+Right" ],+ labelKey: "board_view.hints.move_column"+ }+ ]+ }+];+export default function BoardView({ note: parentNote, noteIds, viewConfig, saveConfig }: ViewModeProps<BoardViewData>) {const [ statusAttributeWithPrefix ] = useNoteLabelWithDefault(parentNote, "board:groupBy", DEFAULT_GROUP_BY);const [ includeArchived ] = useNoteLabelBoolean(parentNote, "includeArchived");@@ -134,6 +176,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// here, so that another view of the same board reads the same record; moving to another board// takes up that board's own, leaving a write still in flight to undo into the one it recorded// itself in. Done while rendering, so the `api` below is handed the map the refresh reads.+ useContextualShortcutHints(BOARD_HINTS);const boardIdentity = `${parentNote.noteId}|${statusAttributeWithPrefix}`;if (pendingRenamesRef.current.board !== boardIdentity) {pendingRenamesRef.current = {@@ -338,6 +381,12 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC)}<AddNewColumn api={api} isInRelationMode={isInRelationMode} />+ {!isMobile() && (+ <ShortcutHintButton+ className="board-shortcut-hint-button"+ placement="bottom-end"+ />+ )}</div>}</BoardDragStateContext.Provider></BoardActionsContext.Provider>diff --git a/apps/client/src/widgets/collections/board/keyboard.spec.tsx b/apps/client/src/widgets/collections/board/keyboard.spec.tsxindex 39f6ab6241..1fa7a13073 100644--- a/apps/client/src/widgets/collections/board/keyboard.spec.tsx+++ b/apps/client/src/widgets/collections/board/keyboard.spec.tsx@@ -335,6 +335,31 @@ describe("Board keyboard", () => {expect(focusedName(board)).toBe("Done");});+ it("carries a card the whole way with Ctrl and Home or End", async () => {+ const board = await renderBoard();+ focusCard(board, 1, 0);+ const moved = noteOf(board, "Second");++ press(board, "Home", { ctrlKey: true });+ setStatus(moved, "To Do");+ await redraw();+ expect(columnOf(board, "Second")).toBe(0);++ press(board, "End", { ctrlKey: true });+ setStatus(moved, "Done");+ await redraw();+ expect(columnOf(board, "Second")).toBe(2);+ });++ it("does not move a card already in the column Home or End would send it to", async () => {+ const board = await renderBoard();+ focusCard(board, 0, 0);++ press(board, "Home", { ctrlKey: true });++ expect(columnOf(board, "First")).toBe(0);+ });+it("does nothing at the edges it cannot move past", async () => {const board = await renderBoard();diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.tsindex db5a16cce5..740c565643 100644--- a/apps/client/src/widgets/collections/board/keyboard.ts+++ b/apps/client/src/widgets/collections/board/keyboard.ts@@ -8,7 +8,9 @@ import { ColumnMap } from "./data";const NAVIGATION_KEYS = [ "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End" ];/** With Ctrl, these carry the focused card: a step, a column across, or all the way to an end. */-const ITEM_MOVE_KEYS = [ "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "PageUp", "PageDown" ];+const ITEM_MOVE_KEYS = [+ "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "PageUp", "PageDown", "Home", "End"+];/** With Ctrl and Alt, these carry the column focus is in, from wherever inside it focus sits. */const COLUMN_MOVE_KEYS = [ "ArrowLeft", "ArrowRight", "PageUp", "PageDown" ];@@ -275,9 +277,12 @@ function move(const { noteId } = item.note;const { branchId } = item.branch;- if (key === "ArrowLeft" || key === "ArrowRight") {- const target = columns[spot.column + (key === "ArrowRight" ? 1 : -1)];- if (!target) return false;+ if (key === "ArrowLeft" || key === "ArrowRight" || key === "Home" || key === "End") {+ // Home and End carry the card the whole way, the way they carry the cursor within a column.+ const target = key === "Home" ? columns[0]+ : key === "End" ? columns[columns.length - 1]+ : columns[spot.column + (key === "ArrowRight" ? 1 : -1)];+ if (!target || target === column) return false;return { intent: { noteId }, done: api.moveToColumnEnd(noteId, branchId, target) };}diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsx b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsxindex f285400959..525337d575 100644--- a/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsx+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hint_button.tsx@@ -10,7 +10,9 @@ import { t } from "../../services/i18n.js";import keyboard_actions from "../../services/keyboard_actions.js";import { formatShortcut, joinShortcut } from "../../services/keyboard_shortcut_display.js";import { collectShortcutHints } from "../../services/shortcut_hints.js";-import OverlayControlGroup, { OverlayControlButton } from "../react/OverlayControlGroup.js";+import OverlayControlGroup, {+ OverlayControlButton, type OverlayPlacement+} from "../react/OverlayControlGroup.js";import { ParentComponent } from "../react/react_utils.js";/**@@ -18,11 +20,16 @@ import { ParentComponent } from "../react/react_utils.js";* this when the widget has no existing overlay controls. To add the button to an *existing** {@link OverlayControlGroup}, use the {@link ShortcutHintOverlayButton} named export instead.*/-export default function ShortcutHintButton({ className }: { className?: string }) {+export default function ShortcutHintButton(+ { className, placement = "top-end" }: { className?: string; placement?: OverlayPlacement }+) {return (- // Standing at the head of what it is put over, its tooltip opens downwards of its own accord,- // away from that edge (see `placement` on OverlayControlGroup).- <OverlayControlGroup className={clsx("shortcut-hint-button-group", className)} placement="top-end">+ // The group opens its tooltips away from the edge it is pinned to, of its own accord (see+ // `placement` on OverlayControlGroup).+ <OverlayControlGroup+ className={clsx("shortcut-hint-button-group", className)}+ placement={placement}+ ><ShortcutHintOverlayButton /></OverlayControlGroup>);diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.spec.tsx b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.spec.tsxindex d4d92df13b..57d97f5549 100644--- a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.spec.tsx+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.spec.tsx@@ -113,6 +113,32 @@ describe("ShortcutHintsPanel", () => {expect(document.querySelector(".shortcut-hints-panel")).toBeNull();});+ /** A button pinned to the foot of what it sits over, as the board's is. */+ it("opens the dropdown upwards when the anchor stands low in the window", () => {+ const host = mountPanel();+ const anchor = document.createElement("button");+ document.body.appendChild(anchor);+ // happy-dom lays nothing out, so the anchor is put near the foot of the window by hand.+ anchor.getBoundingClientRect = () => ({+ top: window.innerHeight - 40,+ bottom: window.innerHeight - 10,+ right: 300+ }) as DOMRect;++ try {+ act(() => {+ host.handleEvent("shortcutHintsRequested", { sections: SECTIONS, anchor });+ });++ const panel = document.querySelector<HTMLElement>(".shortcut-hints-panel");+ // Its foot sits a gap above the anchor's head, and the corner offset is cleared.+ expect(panel?.style.bottom).toBe("46px");+ expect(panel?.style.top).toBe("auto");+ } finally {+ anchor.remove();+ }+ });+it("opens as a dropdown positioned under an anchor, and clicking the anchor does not dismiss it", () => {const host = mountPanel();const anchor = document.createElement("button");diff --git a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsx b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsxindex ecc2618ce2..6fd02af0e3 100644--- a/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsx+++ b/apps/client/src/widgets/shortcut_hints/shortcut_hints_panel.tsx@@ -78,12 +78,10 @@ export default function ShortcutHintsPanel() {return null;}- // Anchored: position the dropdown under the anchor, right edges aligned. The rect is a genuinely- // dynamic value, so it belongs in an inline style rather than CSS.+ // Anchored: position the dropdown beside the anchor, right edges aligned. The rect is a+ // genuinely dynamic value, so it belongs in an inline style rather than CSS.const anchorRect = state.anchor?.getBoundingClientRect();- const style = anchorRect- ? { top: `${anchorRect.bottom + ANCHOR_GAP}px`, right: `${Math.max(ANCHOR_GAP, window.innerWidth - anchorRect.right)}px`, bottom: "auto" }- : undefined;+ const style = anchorRect ? anchoredStyle(anchorRect) : undefined;// Portal to <body> so no transformed / contained / overflow-clipped ancestor breaks the fixed// positioning or hides it behind content.@@ -101,6 +99,23 @@ export default function ShortcutHintsPanel() {);}+/**+ * Where an anchored panel stands: under the anchor, or over it where there is more room that way.+ *+ * Which side it takes is read off the room around the anchor rather than told to it, so a button+ * pinned to the foot of what it sits over drops its panel upwards instead of off the window. The+ * side not used is cleared, the corner placement the stylesheet gives otherwise being the one that+ * would fight it.+ */+function anchoredStyle(anchor: DOMRect) {+ const right = `${Math.max(ANCHOR_GAP, window.innerWidth - anchor.right)}px`;+ const opensUp = window.innerHeight - anchor.bottom < anchor.top;++ return opensUp+ ? { bottom: `${window.innerHeight - anchor.top + ANCHOR_GAP}px`, top: "auto", right }+ : { top: `${anchor.bottom + ANCHOR_GAP}px`, bottom: "auto", right };+}+export function ShortcutHintsSections({ sections }: { sections: ShortcutHintSection[] }) {return (<>