Skip to content

Build your personal knowledge base with Trilium Notes

client/media player: add media keys binding for prev/next

Adorian Doran7bec3c1c7a0b
diff --git a/apps/client/src/widgets/react/sibling_navigation.spec.ts b/apps/client/src/widgets/react/sibling_navigation.spec.ts
index 23ad47472b..2b6eb86b52 100644
--- a/apps/client/src/widgets/react/sibling_navigation.spec.ts
+++ b/apps/client/src/widgets/react/sibling_navigation.spec.ts
@@ -45,6 +45,11 @@ describe("codeToSiblingDirection", () => {
expect(codeToSiblingDirection("End", [], [])).toBe("last");
});
+ it("maps the Previous/Next Track media keys", () => {
+ expect(codeToSiblingDirection("MediaTrackPrevious", [], [])).toBe("previous");
+ expect(codeToSiblingDirection("MediaTrackNext", [], [])).toBe("next");
+ });
+
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");
diff --git a/apps/client/src/widgets/react/sibling_navigation.ts b/apps/client/src/widgets/react/sibling_navigation.ts
index 7352e9bb0e..3931948e49 100644
--- a/apps/client/src/widgets/react/sibling_navigation.ts
+++ b/apps/client/src/widgets/react/sibling_navigation.ts
@@ -29,14 +29,14 @@ export function getSiblingNavigation(siblingNoteIds: string[], currentNoteId: st
export type SiblingDirection = "previous" | "next" | "first" | "last";
/**
- * Maps a `KeyboardEvent.code` to a navigation direction. PageUp/PageDown (prev/next) are built in, as
- * are Home/End (first/last) unless `includeEdges` is false (e.g. media players reserve Home/End for
- * seeking); a renderer can supply extra codes for prev/next (e.g. the image viewer adds
- * `Backspace`/`Space`). Using `code` keeps it keyboard-layout independent.
+ * Maps a `KeyboardEvent.code` to a navigation direction. PageUp/PageDown and the Previous/Next Track
+ * media keys (prev/next) are built in, as are Home/End (first/last) unless `includeEdges` is false (e.g.
+ * media players reserve Home/End for seeking); 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[], includeEdges = true): SiblingDirection | null {
- if (code === "PageUp" || extraPrevious.includes(code)) return "previous";
- if (code === "PageDown" || extraNext.includes(code)) return "next";
+ if (code === "PageUp" || code === "MediaTrackPrevious" || extraPrevious.includes(code)) return "previous";
+ if (code === "PageDown" || code === "MediaTrackNext" || extraNext.includes(code)) return "next";
if (includeEdges && code === "Home") return "first";
if (includeEdges && code === "End") return "last";
return null;
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
index f24d45d776..d5db307bf0 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
@@ -1,13 +1,15 @@
import "./MediaPlayer.css";
import { RefObject } from "preact";
-import { useEffect, useState } from "preact/hooks";
+import { useEffect, useRef, useState } from "preact/hooks";
+import appContext from "../../../components/app_context";
import type NoteContext from "../../../components/note_context";
import type FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
import ActionButton from "../../react/ActionButton";
import Dropdown from "../../react/Dropdown";
+import { useTriliumEvents } from "../../react/hooks";
import Icon from "../../react/Icon";
import { noteSiblingProvider, type SiblingNavigationState, useSiblingKeyboard, useSiblingNavigation } from "../../react/SiblingNavigator";
@@ -137,6 +139,9 @@ export function VolumeControl({ mediaRef }: { mediaRef: RefObject<HTMLVideoEleme
/** Set when jumping to a sibling, so the media opened next auto-plays — like a playlist. */
let autoPlayNextMedia = false;
+/** noteId of the player currently owning the (global) Media Session action handlers, if any. */
+let mediaSessionOwner: string | null = null;
+
/**
* Sibling navigation across the note's same-mime media siblings (e.g. all `video/` files in the parent),
* with PageUp/PageDown wired to previous/next (Home/End and Space are left to the player). Jumping to a
@@ -144,14 +149,60 @@ let autoPlayNextMedia = false;
*/
export function useMediaSiblingNavigation(note: FNote, noteContext: NoteContext | undefined, mimePrefix: string, mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>) {
const navigation = useSiblingNavigation(noteSiblingProvider(note, noteContext, { mimePrefix }));
- const wrapped = navigation && {
+
+ // The previous note's player can linger mounted (cached) in the background while its context still
+ // reports active, so gate everything — keyboard, media keys and buttons — on this note being the one
+ // actually shown in the active tab. Computed each render so it tracks navigation immediately; the
+ // events only force a re-render for cached players, which otherwise wouldn't re-evaluate.
+ const [ , bumpOnNoteSwitch ] = useState(0);
+ useTriliumEvents([ "activeContextChanged", "activeNoteChanged" ], () => bumpOnNoteSwitch((tick) => tick + 1));
+ const isShown = isShownNote(noteContext, note.noteId);
+
+ const wrapped = navigation && isShown ? {
...navigation,
navigatePrevious: () => { autoPlayNextMedia = true; navigation.navigatePrevious(); },
navigateNext: () => { autoPlayNextMedia = true; navigation.navigateNext(); }
- };
+ } : null;
useSiblingKeyboard(wrapped, noteContext, undefined, NO_KEYS, NO_KEYS, { edgeKeys: false });
+ // Bind the OS media controls / hardware media keys (previous/next track) to navigation — desktop
+ // routes these to the (global) Media Session rather than to keydown. Gated on `wrapped`, with a
+ // live re-check inside the handler to cover the window before a backgrounded player re-renders.
+ const hasMediaNav = !!wrapped;
+ const wrappedRef = useRef(wrapped);
+ wrappedRef.current = wrapped;
+ useEffect(() => {
+ if (!("mediaSession" in navigator)) return;
+ const mediaSession = navigator.mediaSession;
+ const setHandler = (action: MediaSessionAction, handler: MediaSessionActionHandler | null) => {
+ try { mediaSession.setActionHandler(action, handler); } catch { /* action unsupported */ }
+ };
+ // The handlers are global, so only ever release our own — otherwise the outgoing player's cleanup
+ // (when switching media → media) would clobber the handlers the incoming player just registered.
+ const release = () => {
+ if (mediaSessionOwner !== note.noteId) return;
+ mediaSessionOwner = null;
+ setHandler("previoustrack", null);
+ setHandler("nexttrack", null);
+ };
+ if (!hasMediaNav) {
+ release();
+ return;
+ }
+ mediaSessionOwner = note.noteId;
+ setHandler("previoustrack", () => { if (isShownNote(noteContext, note.noteId)) wrappedRef.current?.navigatePrevious(); });
+ setHandler("nexttrack", () => { if (isShownNote(noteContext, note.noteId)) wrappedRef.current?.navigateNext(); });
+ return release;
+ }, [ hasMediaNav, noteContext, note.noteId ]);
+
+ // Give the session metadata while shown: Chromium otherwise often won't present the OS media controls
+ // for video (it does for audio), and this also shows the note title in those controls.
+ useEffect(() => {
+ if (!("mediaSession" in navigator) || !isShown) return;
+ navigator.mediaSession.metadata = new MediaMetadata({ title: note.title });
+ }, [ isShown, note.noteId, note.title ]);
+
// Auto-play the freshly-opened sibling once it can play (only when reached via navigation).
useEffect(() => {
if (!autoPlayNextMedia) return;
@@ -170,6 +221,11 @@ export function useMediaSiblingNavigation(note: FNote, noteContext: NoteContext
return wrapped;
}
+/** Whether `noteId` is the note actually shown in the active tab (so a cached background player stands down). */
+function isShownNote(noteContext: NoteContext | undefined, noteId: string): boolean {
+ return !!noteContext && noteContext.isActive() && appContext.tabManager.getActiveContextNoteId() === noteId;
+}
+
/** "Skip to previous/next sibling" control, styled like the other media buttons; renders nothing without siblings. */
export function MediaSiblingButton({ navigation, direction, tooltipI18nKey }: { navigation: SiblingNavigationState | null, direction: "previous" | "next", tooltipI18nKey: string }) {
if (!navigation) return null;