Skip to content

Build your personal knowledge base with Trilium Notes

client/image viewer: add keyboard support for navigation

Adorian Doran8359117c15a2
diff --git a/apps/client/src/widgets/react/SiblingNavigator.tsx b/apps/client/src/widgets/react/SiblingNavigator.tsx
index e4c1b2a5d4..1b25f94bba 100644
--- a/apps/client/src/widgets/react/SiblingNavigator.tsx
+++ b/apps/client/src/widgets/react/SiblingNavigator.tsx
@@ -1,5 +1,6 @@
import "./SiblingNavigator.css";
+import type { RefObject } from "preact";
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import type NoteContext from "../../components/note_context";
@@ -8,7 +9,9 @@ import froca from "../../services/froca";
import { t } from "../../services/i18n";
import { isMobile } from "../../services/utils";
import { useStaticTooltip, useTriliumEvent } from "./hooks";
-import { getParentFromNotePath, getSiblingNavigation } from "./sibling_navigation";
+import { codeToSiblingDirection, getParentFromNotePath, getSiblingNavigation, isTextEntryTarget } from "./sibling_navigation";
+
+const NO_KEYS: readonly string[] = [];
interface SiblingNavigatorProps {
note?: FNote;
@@ -21,6 +24,14 @@ interface SiblingNavigatorProps {
previousTooltip: string;
/** i18n key for the next-button tooltip; receives the target note's title as `{{title}}`. */
nextTooltip: string;
+ /**
+ * Optional element to scope keyboard navigation to: keys act only while focus is inside it. When
+ * omitted, navigation is scoped to the active tab/pane instead, so it works without any wiring.
+ */
+ keyboardTarget?: RefObject<HTMLElement | null>;
+ /** Extra `KeyboardEvent.code`s that trigger previous/next, on top of PageUp/PageDown. */
+ extraPreviousKeys?: readonly string[];
+ extraNextKeys?: readonly string[];
}
interface SiblingNavigationState {
@@ -30,6 +41,8 @@ interface SiblingNavigationState {
nextTitle: string;
navigatePrevious: () => void;
navigateNext: () => void;
+ navigateFirst: () => void;
+ navigateLast: () => void;
}
/**
@@ -73,13 +86,16 @@ export function useSiblingNavigation(note: FNote | undefined, noteContext: NoteC
if (!navigation) return null;
const titleOf = (noteId: string) => siblings.find((sibling) => sibling.noteId === noteId)?.title ?? "";
+ const navigateTo = (noteId: string) => void noteContext?.setNote(`${parent.parentPath}/${noteId}`);
return {
index: navigation.index,
total: navigation.total,
previousTitle: titleOf(navigation.previous),
nextTitle: titleOf(navigation.next),
- navigatePrevious: () => void noteContext?.setNote(`${parent.parentPath}/${navigation.previous}`),
- navigateNext: () => void noteContext?.setNote(`${parent.parentPath}/${navigation.next}`)
+ navigatePrevious: () => navigateTo(navigation.previous),
+ navigateNext: () => navigateTo(navigation.next),
+ navigateFirst: () => navigateTo(navigation.first),
+ navigateLast: () => navigateTo(navigation.last)
};
}
@@ -90,11 +106,12 @@ export function useSiblingNavigation(note: FNote | undefined, noteContext: NoteC
* phrase it ("Previous image: …", "Previous video: …"). Renders nothing when there is no sibling to
* move between — unless `disabled`, which shows the buttons in an inert state.
*/
-export default function SiblingNavigator({ note, noteContext, siblingType, disabled, previousTooltip, nextTooltip }: SiblingNavigatorProps) {
+export default function SiblingNavigator({ note, noteContext, siblingType, disabled, previousTooltip, nextTooltip, keyboardTarget, extraPreviousKeys = NO_KEYS, extraNextKeys = NO_KEYS }: SiblingNavigatorProps) {
const previousRef = useRef<HTMLButtonElement>(null);
const nextRef = useRef<HTMLButtonElement>(null);
const navigation = useSiblingNavigation(note, noteContext, siblingType);
+ useSiblingKeyboard(disabled ? null : navigation, noteContext, keyboardTarget, extraPreviousKeys, extraNextKeys);
const previousText = navigation ? t(previousTooltip, { title: navigation.previousTitle }) : "";
const nextText = navigation ? t(nextTooltip, { title: navigation.nextTitle }) : "";
@@ -124,3 +141,46 @@ export default function SiblingNavigator({ note, noteContext, siblingType, disab
</div>
);
}
+
+/**
+ * Drives sibling navigation from the keyboard. A single document-level listener (stable across the
+ * viewer remounting on each navigation) maps PageUp/PageDown — plus any caller-provided extra keys —
+ * to previous/next. It acts only when a `keyboardTarget` (if given) holds focus, otherwise when the
+ * note context is the active tab/pane, and never while the user is typing in a text field.
+ */
+function useSiblingKeyboard(
+ navigation: SiblingNavigationState | null,
+ noteContext: NoteContext | undefined,
+ keyboardTarget: RefObject<HTMLElement | null> | undefined,
+ extraPreviousKeys: readonly string[],
+ extraNextKeys: readonly string[]
+) {
+ // Read the freshest values from inside the listener without re-attaching it on every change.
+ const stateRef = useRef({ navigation, noteContext, keyboardTarget, extraPreviousKeys, extraNextKeys });
+ stateRef.current = { navigation, noteContext, keyboardTarget, extraPreviousKeys, extraNextKeys };
+
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return;
+
+ const { navigation, noteContext, keyboardTarget, extraPreviousKeys, extraNextKeys } = stateRef.current;
+ if (!navigation || isTextEntryTarget(e.target as Element | null)) return;
+ if (keyboardTarget) {
+ if (!keyboardTarget.current?.contains(document.activeElement)) return;
+ } else if (noteContext && !noteContext.isActive()) {
+ return;
+ }
+
+ const direction = codeToSiblingDirection(e.code, extraPreviousKeys, extraNextKeys);
+ if (!direction) return;
+ e.preventDefault();
+ if (direction === "previous") navigation.navigatePrevious();
+ else if (direction === "next") navigation.navigateNext();
+ else if (direction === "first") navigation.navigateFirst();
+ else navigation.navigateLast();
+ };
+
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, []);
+}
diff --git a/apps/client/src/widgets/react/sibling_navigation.spec.ts b/apps/client/src/widgets/react/sibling_navigation.spec.ts
index 277d2144db..df61068bc0 100644
--- a/apps/client/src/widgets/react/sibling_navigation.spec.ts
+++ b/apps/client/src/widgets/react/sibling_navigation.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { getParentFromNotePath, getSiblingNavigation } from "./sibling_navigation";
+import { codeToSiblingDirection, getParentFromNotePath, getSiblingNavigation, isTextEntryTarget } from "./sibling_navigation";
describe("getParentFromNotePath", () => {
it("splits the in-tab path into parent path + parent note id", () => {
@@ -17,17 +17,17 @@ describe("getParentFromNotePath", () => {
});
describe("getSiblingNavigation", () => {
- it("returns the adjacent siblings with a 1-based index and total", () => {
- expect(getSiblingNavigation([ "a", "b", "c" ], "b")).toEqual({ previous: "a", next: "c", index: 2, total: 3 });
+ it("returns the adjacent and edge siblings with a 1-based index and total", () => {
+ expect(getSiblingNavigation([ "a", "b", "c" ], "b")).toEqual({ previous: "a", next: "c", first: "a", last: "c", index: 2, total: 3 });
});
- it("wraps around infinitely at both ends", () => {
- expect(getSiblingNavigation([ "a", "b", "c" ], "a")).toEqual({ previous: "c", next: "b", index: 1, total: 3 });
- expect(getSiblingNavigation([ "a", "b", "c" ], "c")).toEqual({ previous: "b", next: "a", index: 3, total: 3 });
+ it("wraps prev/next around infinitely while first/last stay absolute", () => {
+ expect(getSiblingNavigation([ "a", "b", "c" ], "a")).toEqual({ previous: "c", next: "b", first: "a", last: "c", index: 1, total: 3 });
+ expect(getSiblingNavigation([ "a", "b", "c" ], "c")).toEqual({ previous: "b", next: "a", first: "a", last: "c", index: 3, total: 3 });
});
it("wraps to the other sibling with exactly two", () => {
- expect(getSiblingNavigation([ "a", "b" ], "a")).toEqual({ previous: "b", next: "b", index: 1, total: 2 });
+ expect(getSiblingNavigation([ "a", "b" ], "a")).toEqual({ previous: "b", next: "b", first: "a", last: "b", index: 1, total: 2 });
});
it("returns null with fewer than two siblings or when the note is absent", () => {
@@ -36,3 +36,36 @@ describe("getSiblingNavigation", () => {
expect(getSiblingNavigation([ "a", "b" ], "x")).toBeNull();
});
});
+
+describe("codeToSiblingDirection", () => {
+ it("maps PageUp/PageDown (prev/next) and Home/End (first/last) by default", () => {
+ expect(codeToSiblingDirection("PageUp", [], [])).toBe("previous");
+ expect(codeToSiblingDirection("PageDown", [], [])).toBe("next");
+ expect(codeToSiblingDirection("Home", [], [])).toBe("first");
+ expect(codeToSiblingDirection("End", [], [])).toBe("last");
+ });
+
+ it("honors caller-provided extra keys (e.g. the image viewer's Backspace/Space)", () => {
+ expect(codeToSiblingDirection("Backspace", [ "Backspace" ], [ "Space" ])).toBe("previous");
+ expect(codeToSiblingDirection("Space", [ "Backspace" ], [ "Space" ])).toBe("next");
+ });
+
+ it("returns null for unrelated keys", () => {
+ expect(codeToSiblingDirection("Space", [], [])).toBeNull();
+ expect(codeToSiblingDirection("KeyA", [ "Backspace" ], [ "Space" ])).toBeNull();
+ });
+});
+
+describe("isTextEntryTarget", () => {
+ it("is true for text-entry elements", () => {
+ expect(isTextEntryTarget({ tagName: "INPUT" })).toBe(true);
+ expect(isTextEntryTarget({ tagName: "textarea" })).toBe(true);
+ expect(isTextEntryTarget({ tagName: "DIV", isContentEditable: true })).toBe(true);
+ });
+
+ it("is false for non-text targets and nullish input", () => {
+ expect(isTextEntryTarget({ tagName: "DIV" })).toBe(false);
+ expect(isTextEntryTarget({ tagName: "BUTTON" })).toBe(false);
+ expect(isTextEntryTarget(null)).toBe(false);
+ });
+});
diff --git a/apps/client/src/widgets/react/sibling_navigation.ts b/apps/client/src/widgets/react/sibling_navigation.ts
index e265fa5e3e..5e36a67055 100644
--- a/apps/client/src/widgets/react/sibling_navigation.ts
+++ b/apps/client/src/widgets/react/sibling_navigation.ts
@@ -8,17 +8,42 @@ export function getParentFromNotePath(notePath: string | null | undefined): { pa
/**
* From the ordered note ids of the matching siblings (including the current note) and the current
- * note id, returns the previous/next sibling — wrapping around infinitely — plus the 1-based index
- * and total. Returns null when the current note isn't among them or there are fewer than two.
+ * note id, returns the previous/next sibling — wrapping around infinitely — plus the first/last
+ * sibling, the 1-based index and total. Returns null when the current note isn't among them or there
+ * are fewer than two.
*/
-export function getSiblingNavigation(siblingNoteIds: string[], currentNoteId: string): { previous: string; next: string; index: number; total: number } | null {
+export function getSiblingNavigation(siblingNoteIds: string[], currentNoteId: string): { previous: string; next: string; first: string; last: string; index: number; total: number } | null {
const index = siblingNoteIds.indexOf(currentNoteId);
const total = siblingNoteIds.length;
if (index === -1 || total < 2) return null;
return {
previous: siblingNoteIds[(index - 1 + total) % total],
next: siblingNoteIds[(index + 1) % total],
+ first: siblingNoteIds[0],
+ last: siblingNoteIds[total - 1],
index: index + 1,
total
};
}
+
+export type SiblingDirection = "previous" | "next" | "first" | "last";
+
+/**
+ * Maps a `KeyboardEvent.code` to a navigation direction. PageUp/PageDown (prev/next) and Home/End
+ * (first/last) are built in; a renderer can supply extra codes for prev/next (e.g. the image viewer
+ * adds `Backspace`/`Space`). Using `code` keeps it keyboard-layout independent.
+ */
+export function codeToSiblingDirection(code: string, extraPrevious: readonly string[], extraNext: readonly string[]): SiblingDirection | null {
+ if (code === "PageUp" || extraPrevious.includes(code)) return "previous";
+ if (code === "PageDown" || extraNext.includes(code)) return "next";
+ if (code === "Home") return "first";
+ if (code === "End") return "last";
+ return null;
+}
+
+/** Whether the event originated in a text-entry field, where navigation keys must not be hijacked. */
+export function isTextEntryTarget(target: { tagName?: string; isContentEditable?: boolean } | null | undefined): boolean {
+ if (!target?.tagName) return false;
+ const tag = target.tagName.toUpperCase();
+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable === true;
+}
diff --git a/apps/client/src/widgets/type_widgets/Image.tsx b/apps/client/src/widgets/type_widgets/Image.tsx
index 014788985d..b9a3c640ef 100644
--- a/apps/client/src/widgets/type_widgets/Image.tsx
+++ b/apps/client/src/widgets/type_widgets/Image.tsx
@@ -11,6 +11,10 @@ import { refToJQuerySelector } from "../react/react_utils";
import SiblingNavigator from "../react/SiblingNavigator";
import { TypeWidgetProps } from "./type_widget";
+// In addition to PageUp/PageDown, the image viewer navigates with Backspace (previous) and Space (next).
+const IMAGE_PREVIOUS_KEYS = [ "Backspace" ];
+const IMAGE_NEXT_KEYS = [ "Space" ];
+
export default function Image({ note, ntxId, noteContext }: TypeWidgetProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [ refreshCounter, setRefreshCounter ] = useState(0);
@@ -45,6 +49,8 @@ export default function Image({ note, ntxId, noteContext }: TypeWidgetProps) {
noteContext={noteContext}
previousTooltip="image_navigation.previous"
nextTooltip="image_navigation.next"
+ extraPreviousKeys={IMAGE_PREVIOUS_KEYS}
+ extraNextKeys={IMAGE_NEXT_KEYS}
/>
</div>
);