Skip to content

Build your personal knowledge base with Trilium Notes

client/image viewer: add support to navigate to the previous/next image, similar to a photo gallery

Adorian Doran98ab7c6f96a5
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 756a8ea73e..f2e1292852 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -867,6 +867,10 @@
"zoom_out": "Zoom out",
"reset_zoom": "Reset zoom"
},
+ "image_navigation": {
+ "previous": "Previous image: {{- title}}",
+ "next": "Next image: {{- title}}"
+ },
"zpetne_odkazy": {
"backlink_one": "{{count}} Backlink",
"backlink_other": "{{count}} Backlinks",
diff --git a/apps/client/src/widgets/react/SiblingNavigator.css b/apps/client/src/widgets/react/SiblingNavigator.css
new file mode 100644
index 0000000000..3da6e2539d
--- /dev/null
+++ b/apps/client/src/widgets/react/SiblingNavigator.css
@@ -0,0 +1,16 @@
+/* Previous/next sibling navigation pinned to the top-left corner of the viewport. */
+.sibling-navigator {
+ position: absolute;
+ top: 10px;
+ inset-inline-start: 10px;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.sibling-navigator-index {
+ min-width: 3em;
+ text-align: center;
+ font-variant-numeric: tabular-nums;
+}
diff --git a/apps/client/src/widgets/react/SiblingNavigator.tsx b/apps/client/src/widgets/react/SiblingNavigator.tsx
new file mode 100644
index 0000000000..e4c1b2a5d4
--- /dev/null
+++ b/apps/client/src/widgets/react/SiblingNavigator.tsx
@@ -0,0 +1,126 @@
+import "./SiblingNavigator.css";
+
+import { useEffect, useMemo, useRef, useState } from "preact/hooks";
+
+import type NoteContext from "../../components/note_context";
+import type FNote from "../../entities/fnote";
+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";
+
+interface SiblingNavigatorProps {
+ note?: FNote;
+ noteContext?: NoteContext;
+ /** Match siblings of this type; defaults to the current note's type. */
+ siblingType?: string;
+ /** Render inert buttons (e.g. when the viewer is reused for an attachment preview). */
+ disabled?: boolean;
+ /** i18n key for the previous-button tooltip; receives the target note's title as `{{title}}`. */
+ previousTooltip: string;
+ /** i18n key for the next-button tooltip; receives the target note's title as `{{title}}`. */
+ nextTooltip: string;
+}
+
+interface SiblingNavigationState {
+ index: number;
+ total: number;
+ previousTitle: string;
+ nextTitle: string;
+ navigatePrevious: () => void;
+ navigateNext: () => void;
+}
+
+/**
+ * Computes prev/next navigation among the current note's same-type siblings within the parent of the
+ * current tab (clone-aware), exposing the target notes' titles. Pass `siblingType` to match a different
+ * type. Reusable for any note type; returns null when there is nothing to navigate. Served from froca.
+ */
+export function useSiblingNavigation(note: FNote | undefined, noteContext: NoteContext | undefined, siblingType?: string): SiblingNavigationState | null {
+ const notePath = noteContext?.notePath;
+ const type = siblingType ?? note?.type;
+ const [ siblings, setSiblings ] = useState<{ noteId: string; title: string }[]>([]);
+ const [ refreshCounter, setRefreshCounter ] = useState(0);
+
+ useEffect(() => {
+ const parent = getParentFromNotePath(notePath);
+ if (!parent || !type) {
+ setSiblings([]);
+ return;
+ }
+
+ let active = true;
+ void froca.getNote(parent.parentNoteId)
+ .then((parentNote) => parentNote?.getChildNotes() ?? [])
+ .then((children) => {
+ if (active) setSiblings(children.filter((child) => child.type === type).map((child) => ({ noteId: child.noteId, title: child.title })));
+ });
+ return () => { active = false; };
+ }, [ notePath, type, refreshCounter ]);
+
+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
+ const parent = getParentFromNotePath(notePath);
+ if (!parent) return;
+ const branchesChanged = loadResults.getBranchRows().some((branch) => branch.parentNoteId === parent.parentNoteId);
+ const siblingChanged = loadResults.getNoteIds().some((noteId) => siblings.some((sibling) => sibling.noteId === noteId));
+ if (branchesChanged || siblingChanged) setRefreshCounter((counter) => counter + 1);
+ });
+
+ const parent = getParentFromNotePath(notePath);
+ if (!note || !parent) return null;
+ const navigation = getSiblingNavigation(siblings.map((sibling) => sibling.noteId), note.noteId);
+ if (!navigation) return null;
+
+ const titleOf = (noteId: string) => siblings.find((sibling) => sibling.noteId === noteId)?.title ?? "";
+ 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}`)
+ };
+}
+
+/**
+ * Floating previous/next navigation between a note's same-type siblings (within the current tab's
+ * parent), with a "<index>/<total>" indicator and tooltips naming the target note. The tooltip text
+ * comes from the caller-provided i18n keys (`previousTooltip`/`nextTooltip`), so each note type can
+ * 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) {
+ const previousRef = useRef<HTMLButtonElement>(null);
+ const nextRef = useRef<HTMLButtonElement>(null);
+
+ const navigation = useSiblingNavigation(note, noteContext, siblingType);
+
+ const previousText = navigation ? t(previousTooltip, { title: navigation.previousTitle }) : "";
+ const nextText = navigation ? t(nextTooltip, { title: navigation.nextTitle }) : "";
+ // Memoize so the bootstrap tooltip is only recreated when the target note's name actually changes.
+ const previousConfig = useMemo(() => ({ title: previousText, placement: "bottom" as const }), [ previousText ]);
+ const nextConfig = useMemo(() => ({ title: nextText, placement: "bottom" as const }), [ nextText ]);
+ useStaticTooltip(previousRef, previousConfig);
+ useStaticTooltip(nextRef, nextConfig);
+
+ if (isMobile() || (!disabled && !navigation)) return null;
+
+ return (
+ <div className="sibling-navigator">
+ <button
+ ref={previousRef}
+ className="icon-action bx bx-chevron-left"
+ disabled={disabled}
+ onClick={() => navigation?.navigatePrevious()}
+ />
+ {navigation && <span className="sibling-navigator-index">{navigation.index}/{navigation.total}</span>}
+ <button
+ ref={nextRef}
+ className="icon-action bx bx-chevron-right"
+ disabled={disabled}
+ onClick={() => navigation?.navigateNext()}
+ />
+ </div>
+ );
+}
diff --git a/apps/client/src/widgets/react/sibling_navigation.spec.ts b/apps/client/src/widgets/react/sibling_navigation.spec.ts
new file mode 100644
index 0000000000..277d2144db
--- /dev/null
+++ b/apps/client/src/widgets/react/sibling_navigation.spec.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+
+import { getParentFromNotePath, getSiblingNavigation } from "./sibling_navigation";
+
+describe("getParentFromNotePath", () => {
+ it("splits the in-tab path into parent path + parent note id", () => {
+ expect(getParentFromNotePath("root/abc/def/xyz")).toEqual({ parentPath: "root/abc/def", parentNoteId: "def" });
+ expect(getParentFromNotePath("root/xyz")).toEqual({ parentPath: "root", parentNoteId: "root" });
+ });
+
+ it("returns null for a rootless or empty path", () => {
+ expect(getParentFromNotePath("xyz")).toBeNull();
+ expect(getParentFromNotePath("")).toBeNull();
+ expect(getParentFromNotePath(null)).toBeNull();
+ expect(getParentFromNotePath(undefined)).toBeNull();
+ });
+});
+
+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("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 to the other sibling with exactly two", () => {
+ expect(getSiblingNavigation([ "a", "b" ], "a")).toEqual({ previous: "b", next: "b", index: 1, total: 2 });
+ });
+
+ it("returns null with fewer than two siblings or when the note is absent", () => {
+ expect(getSiblingNavigation([ "a" ], "a")).toBeNull();
+ expect(getSiblingNavigation([], "a")).toBeNull();
+ expect(getSiblingNavigation([ "a", "b" ], "x")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/react/sibling_navigation.ts b/apps/client/src/widgets/react/sibling_navigation.ts
new file mode 100644
index 0000000000..e265fa5e3e
--- /dev/null
+++ b/apps/client/src/widgets/react/sibling_navigation.ts
@@ -0,0 +1,24 @@
+/** Splits a note path into the parent path and parent note id (clone-aware: uses the in-tab path). */
+export function getParentFromNotePath(notePath: string | null | undefined): { parentPath: string; parentNoteId: string } | null {
+ if (!notePath) return null;
+ const parts = notePath.split("/");
+ if (parts.length < 2) return null;
+ return { parentPath: parts.slice(0, -1).join("/"), parentNoteId: parts[parts.length - 2] };
+}
+
+/**
+ * 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.
+ */
+export function getSiblingNavigation(siblingNoteIds: string[], currentNoteId: string): { previous: string; next: 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],
+ index: index + 1,
+ total
+ };
+}
diff --git a/apps/client/src/widgets/type_widgets/Attachment.css b/apps/client/src/widgets/type_widgets/Attachment.css
index ff1f8391bc..0c9c01143d 100644
--- a/apps/client/src/widgets/type_widgets/Attachment.css
+++ b/apps/client/src/widgets/type_widgets/Attachment.css
@@ -115,6 +115,11 @@
object-fit: unset;
}
+/* Anchor the (disabled) sibling-navigation overlay to the viewer. */
+.attachment-content-wrapper.attachment-image-viewer {
+ position: relative;
+}
+
.attachment-detail-wrapper.scheduled-for-deletion .attachment-content-wrapper img {
filter: contrast(10%);
}
diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsx
index 0bf34b5887..822e68263e 100644
--- a/apps/client/src/widgets/type_widgets/Attachment.tsx
+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx
@@ -31,6 +31,7 @@ import ImageViewer from "../react/ImageViewer";
import NoItems from "../react/NoItems";
import NoteLink from "../react/NoteLink";
import { ParentComponent, refToJQuerySelector } from "../react/react_utils";
+import SiblingNavigator from "../react/SiblingNavigator";
import { TextPreview } from "./File";
import { TypeWidgetProps } from "./type_widget";
@@ -240,6 +241,7 @@ function AttachmentInfo({ attachment, isFullDetail }: { attachment: FAttachment,
{isZoomableImage ? (
<div key="image-viewer" ref={imageViewerWrapper} className="attachment-content-wrapper attachment-image-viewer">
<ImageViewer key={`${attachment.attachmentId}-${attachment.utcDateModified}`} src={imageSrc} alt={attachment.title} />
+ <SiblingNavigator disabled previousTooltip="image_navigation.previous" nextTooltip="image_navigation.next" />
</div>
) : (
<div key="rendered" ref={contentWrapper} className="attachment-content-wrapper" />
diff --git a/apps/client/src/widgets/type_widgets/Image.tsx b/apps/client/src/widgets/type_widgets/Image.tsx
index 8ab762d400..014788985d 100644
--- a/apps/client/src/widgets/type_widgets/Image.tsx
+++ b/apps/client/src/widgets/type_widgets/Image.tsx
@@ -8,9 +8,10 @@ import { createImageSrcUrl } from "../../services/utils";
import { useTriliumEvent } from "../react/hooks";
import ImageViewer from "../react/ImageViewer";
import { refToJQuerySelector } from "../react/react_utils";
+import SiblingNavigator from "../react/SiblingNavigator";
import { TypeWidgetProps } from "./type_widget";
-export default function Image({ note, ntxId }: TypeWidgetProps) {
+export default function Image({ note, ntxId, noteContext }: TypeWidgetProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [ refreshCounter, setRefreshCounter ] = useState(0);
@@ -39,6 +40,12 @@ export default function Image({ note, ntxId }: TypeWidgetProps) {
src={createImageSrcUrl(note)}
alt={note.title}
/>
+ <SiblingNavigator
+ note={note}
+ noteContext={noteContext}
+ previousTooltip="image_navigation.previous"
+ nextTooltip="image_navigation.next"
+ />
</div>
);
}