Skip to content

Build your personal knowledge base with Trilium Notes

client/media player: fix several issues

Adorian Doran9ab1971b0b02
diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsx
index ce00a82b5d..6c41d8a1e9 100644
--- a/apps/client/src/widgets/NoteDetail.tsx
+++ b/apps/client/src/widgets/NoteDetail.tsx
@@ -274,7 +274,7 @@ function NoteDetailWrapper({ Element, type, isVisible, isFullHeight, props }: {
height: isFullHeight ? "100%" : ""
}}
>
- <Element {...cachedProps} />
+ <Element {...cachedProps} isVisible={isVisible} />
</div>
);
}
diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsx
index bd84db2571..f8f8775d13 100644
--- a/apps/client/src/widgets/react/Dropdown.tsx
+++ b/apps/client/src/widgets/react/Dropdown.tsx
@@ -43,12 +43,11 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
const { showTooltip, hideTooltip } = useTooltip(containerRef, {
...titleOptions,
- // Drive the tooltip text from the config (not just the `title` attribute): Bootstrap reads the
- // attribute only once on init, so a dynamic title (e.g. the media play-mode button) would otherwise
- // stay stale. useTooltip recreates the tooltip each render, so this keeps it in sync with the prop.
- // Fall back to "" (Bootstrap's default) since it rejects an explicit `undefined`; an empty title
- // simply shows no tooltip.
- title: title ?? "",
+ // Drive the tooltip from config, not just the `title` attribute: Bootstrap reads the attribute once
+ // on init, so a dynamic title (e.g. the media play-mode button) would otherwise go stale (useTooltip
+ // recreates the tooltip each render, keeping this in sync). Prefer the `title` prop, then a
+ // `titleOptions.title` escape-hatch, then "" (Bootstrap rejects `undefined`; "" shows no tooltip).
+ title: title ?? titleOptions?.title ?? "",
placement: titlePosition ?? "bottom",
fallbackPlacements: [ titlePosition ?? "bottom" ],
trigger: "manual"
diff --git a/apps/client/src/widgets/type_widgets/File.tsx b/apps/client/src/widgets/type_widgets/File.tsx
index 8f8fca1f7b..94a3b9e84c 100644
--- a/apps/client/src/widgets/type_widgets/File.tsx
+++ b/apps/client/src/widgets/type_widgets/File.tsx
@@ -10,7 +10,7 @@ import { TypeWidgetProps } from "./type_widget";
const TEXT_MAX_NUM_CHARS = 5000;
-export default function FileTypeWidget({ note, parentComponent, noteContext }: TypeWidgetProps) {
+export default function FileTypeWidget({ note, parentComponent, noteContext, isVisible }: TypeWidgetProps) {
const blob = useNoteBlob(note, parentComponent?.componentId);
if (blob?.content) {
@@ -18,9 +18,9 @@ export default function FileTypeWidget({ note, parentComponent, noteContext }: T
} else if (note.mime === "application/pdf") {
return noteContext && <PdfPreview blob={blob} note={note} componentId={parentComponent?.componentId} noteContext={noteContext} />;
} else if (note.mime.startsWith("video/")) {
- return <VideoPreview note={note} noteContext={noteContext} />;
+ return <VideoPreview note={note} noteContext={noteContext} isVisible={isVisible} />;
} else if (note.mime.startsWith("audio/")) {
- return <AudioPreview note={note} noteContext={noteContext} />;
+ return <AudioPreview note={note} noteContext={noteContext} isVisible={isVisible} />;
}
return <NoPreview />;
diff --git a/apps/client/src/widgets/type_widgets/file/Audio.tsx b/apps/client/src/widgets/type_widgets/file/Audio.tsx
index 9d8dd459b2..6597a0082f 100644
--- a/apps/client/src/widgets/type_widgets/file/Audio.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Audio.tsx
@@ -8,7 +8,7 @@ import Icon from "../../react/Icon";
import NoItems from "../../react/NoItems";
import { MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SeekBar, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";
-export default function AudioPreview({ note, noteContext }: { note: FNote, noteContext?: NoteContext }) {
+export default function AudioPreview({ note, noteContext, isVisible = true }: { note: FNote, noteContext?: NoteContext, isVisible?: boolean }) {
const wrapperRef = useRef<HTMLDivElement>(null);
const audioRef = useRef<HTMLAudioElement>(null);
const [playing, setPlaying] = useState(false);
@@ -31,7 +31,10 @@ export default function AudioPreview({ note, noteContext }: { note: FNote, noteC
setPlaying(false);
}, [note.noteId]);
const onError = useCallback(() => setError(true), []);
- const siblingNavigation = useMediaSessionController(note, noteContext, "audio/", audioRef);
+ // Mirror the element's real play state on every transition: "pause" isn't fired reliably when a track
+ // ends or its src is swapped, so derive from `paused` rather than assuming play→true / pause→false.
+ const syncPlaying = useCallback(() => setPlaying(!!audioRef.current && !audioRef.current.paused), []);
+ const siblingNavigation = useMediaSessionController(note, noteContext, "audio/", audioRef, isVisible);
const { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, audioRef);
if (error) {
@@ -44,8 +47,10 @@ export default function AudioPreview({ note, noteContext }: { note: FNote, noteC
class="audio-preview"
src={getUrlForDownload(`api/notes/${note.noteId}/open-partial`)}
ref={audioRef}
- onPlay={() => setPlaying(true)}
- onPause={() => setPlaying(false)}
+ onPlay={syncPlaying}
+ onPause={syncPlaying}
+ onEnded={syncPlaying}
+ onEmptied={syncPlaying}
onError={onError}
/>
<div className="audio-preview-icon-wrapper">
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
index 3fc9082e81..d0f958a205 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
@@ -8,6 +8,7 @@ import type FNote from "../../../entities/fnote";
import attributes from "../../../services/attributes";
import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
+import { logError } from "../../../services/ws";
import ActionButton from "../../react/ActionButton";
import Dropdown from "../../react/Dropdown";
import { useTriliumEvent, useTriliumEvents } from "../../react/hooks";
@@ -167,28 +168,30 @@ const OWNED_MEDIA_ACTIONS: MediaSessionAction[] = [ "previoustrack", "nexttrack"
* seek-to (scrubber) and stop, with the note title as metadata. Play/pause and basic seek are left to the
* browser's default binding on the element. Jumping to a sibling auto-plays it, like a playlist. Starting
* playback pauses every other media player (audio or video), so only one plays at a time; that player owns
- * the global Media Session and keeps the OS controls even while paused or its tab is backgrounded. It hands
- * the session over only when another player starts playing, or releases it when its tab is closed (unmount).
+ * the global Media Session and keeps the OS controls while paused or while its tab is inactive (it keeps
+ * playing in the background). It releases the session — and, when its tab switches to a different note type so
+ * this player is hidden/cached, also stops playing — on that navigation, on a handover, or on unmount.
*/
-export function useMediaSessionController(note: FNote, noteContext: NoteContext | undefined, mimePrefix: string, mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>) {
+export function useMediaSessionController(note: FNote, noteContext: NoteContext | undefined, mimePrefix: string, mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>, isVisible: boolean) {
const navigation = useSiblingNavigation(noteSiblingProvider(note, noteContext, { mimePrefix }));
// Stable identity for this player instance, used to coordinate with the other mounted players.
const self = useRef<object>({}).current;
- // Forces a re-render so isCurrentNote / ownsSession get re-evaluated after navigation or a playback
- // change (a cached/background player otherwise wouldn't notice its context going stale).
+ // Re-render on tab/note switches so a cached/background player re-evaluates promptly — its ownership of
+ // the session can change when another player starts or its own context navigates.
const [ , bump ] = useState(0);
useTriliumEvents([ "activeContextChanged", "activeNoteChanged" ], () => bump((tick) => tick + 1));
- // The player that's currently playing owns the OS Media Session: starting playback pauses every other
- // player (below), so at most one is active at a time. Ownership is kept through pauses and tab switches,
- // and released only on handover (another player starts) or unmount (its tab is closed) — not when merely
- // paused or navigated away. `isCurrentNote` (this player's own context still shows it) only gates the
- // on-screen prev/next buttons and the session's track-skip handlers, not ownership itself.
- const isCurrentNote = isCurrentContextNote(noteContext, note.noteId);
- const ownsSession = activeMediaPlayer === self;
+ // The currently-playing player owns the OS Media Session. It owns iff it's the *displayed* type widget for
+ // its context (`isVisible`) AND it holds the active-playback slot — so the session is kept through pauses and
+ // while the tab is merely inactive (still the displayed type there → background playback). It's released on a
+ // handover (another player starts), on unmount (tab closed), or when the tab switches to a different note type
+ // so this player is hidden/cached (the stop-on-stale effect below also pauses it then). Using `isVisible`
+ // rather than a note-id match avoids a transient release during a same-type sibling jump, where the cached
+ // props briefly lag the context's note id.
+ const ownsSession = isVisible && activeMediaPlayer === self;
- const wrapped = navigation && isCurrentNote ? {
+ const wrapped = navigation && isVisible ? {
...navigation,
navigatePrevious: () => { autoPlayTargetNoteId = navigation.previousId; navigation.navigatePrevious(); },
navigateNext: () => { autoPlayTargetNoteId = navigation.nextId; navigation.navigateNext(); }
@@ -239,6 +242,16 @@ export function useMediaSessionController(note: FNote, noteContext: NoteContext
return () => { mediaPlayerSubscribers.delete(onActivePlayerChange); };
}, [ self, mediaRef ]);
+ // Stop a hidden/cached player: when its tab switches to a different note type this widget is no longer the
+ // displayed one (`isVisible` false), so pause it and give up the active slot — there's no visible player for
+ // it anymore. A merely-inactive tab still displays this type (isVisible stays true) and so keeps playing.
+ useEffect(() => {
+ if (!isVisible) {
+ mediaRef.current?.pause();
+ if (activeMediaPlayer === self) setActiveMediaPlayer(null);
+ }
+ }, [ isVisible, mediaRef, self ]);
+
// Bind the OS Media Session (which desktop/hardware media keys route to, rather than keydown) and its
// metadata while this player owns the session (its context's current note, and the one playing). They're
// global, so only ever release our own — otherwise the outgoing player's cleanup during a handover would
@@ -362,19 +375,25 @@ export function SkipButton({ mediaRef, seconds, icon, text }: { mediaRef: RefObj
export function useMediaPlayMode(noteContext: NoteContext | undefined, mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>): { mode: MediaPlayMode; setMode: (mode: MediaPlayMode) => void } {
const parentNoteId = getParentFromNotePath(noteContext?.notePath)?.parentNoteId;
const [ mode, setLocalMode ] = useState<MediaPlayMode>("once");
+ const [ refreshCounter, setRefreshCounter ] = useState(0);
- const refresh = useCallback(() => {
+ // Load the mode from the parent's label. The `active` flag discards a stale response when the parent
+ // changes mid-flight (rapid navigation), so a slower earlier fetch can't overwrite a newer note's mode.
+ useEffect(() => {
if (!parentNoteId) {
setLocalMode("once");
return;
}
- froca.getNote(parentNoteId).then((parent) => setLocalMode(playModeFromLabel(parent?.getLabelValue(MEDIA_PLAY_MODE_LABEL)))).catch(() => {});
- }, [ parentNoteId ]);
+ let active = true;
+ froca.getNote(parentNoteId)
+ .then((parent) => { if (active) setLocalMode(playModeFromLabel(parent?.getLabelValue(MEDIA_PLAY_MODE_LABEL))); })
+ .catch(() => {});
+ return () => { active = false; };
+ }, [ parentNoteId, refreshCounter ]);
- useEffect(refresh, [ refresh ]);
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
if (parentNoteId && loadResults.getAttributeRows().some((attr) => attr.noteId === parentNoteId && attr.name === MEDIA_PLAY_MODE_LABEL)) {
- refresh();
+ setRefreshCounter((counter) => counter + 1);
}
});
@@ -395,7 +414,7 @@ export function useMediaPlayMode(noteContext: NoteContext | undefined, mediaRef:
} else {
void attributes.setLabel(parent.noteId, MEDIA_PLAY_MODE_LABEL, value);
}
- }).catch(() => {});
+ }).catch((e) => logError(`Could not persist media play mode: ${e}`));
}, [ parentNoteId ]);
return { mode, setMode };
diff --git a/apps/client/src/widgets/type_widgets/file/Video.tsx b/apps/client/src/widgets/type_widgets/file/Video.tsx
index 9501af5dcb..30bc710300 100644
--- a/apps/client/src/widgets/type_widgets/file/Video.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Video.tsx
@@ -13,7 +13,7 @@ import { MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, See
const AUTO_HIDE_DELAY = 3000;
-export default function VideoPreview({ note, noteContext }: { note: FNote, noteContext?: NoteContext }) {
+export default function VideoPreview({ note, noteContext, isVisible = true }: { note: FNote, noteContext?: NoteContext, isVisible?: boolean }) {
const wrapperRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const [playing, setPlaying] = useState(false);
@@ -27,6 +27,9 @@ export default function VideoPreview({ note, noteContext }: { note: FNote, noteC
setPlaying(false);
}, [note.noteId]);
const onError = useCallback(() => setError(true), []);
+ // Mirror the element's real play state on every transition: "pause" isn't fired reliably when a track
+ // ends or its src is swapped, so derive from `paused` rather than assuming play→true / pause→false.
+ const syncPlaying = useCallback(() => setPlaying(!!videoRef.current && !videoRef.current.paused), []);
const togglePlayback = useCallback(() => {
const video = videoRef.current;
@@ -44,7 +47,7 @@ export default function VideoPreview({ note, noteContext }: { note: FNote, noteC
}, [togglePlayback]);
const onKeyDown = useKeyboardShortcuts(videoRef, wrapperRef, togglePlayback, flashControls);
- const siblingNavigation = useMediaSessionController(note, noteContext, "video/", videoRef);
+ const siblingNavigation = useMediaSessionController(note, noteContext, "video/", videoRef, isVisible);
const { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, videoRef);
if (error) {
@@ -58,8 +61,10 @@ export default function VideoPreview({ note, noteContext }: { note: FNote, noteC
class="video-preview"
src={getUrlForDownload(`api/notes/${note.noteId}/open-partial`)}
datatype={note?.mime}
- onPlay={() => setPlaying(true)}
- onPause={() => setPlaying(false)}
+ onPlay={syncPlaying}
+ onPause={syncPlaying}
+ onEnded={syncPlaying}
+ onEmptied={syncPlaying}
onError={onError}
/>
diff --git a/apps/client/src/widgets/type_widgets/type_widget.ts b/apps/client/src/widgets/type_widgets/type_widget.ts
index 4723060a2e..d59b5f4398 100644
--- a/apps/client/src/widgets/type_widgets/type_widget.ts
+++ b/apps/client/src/widgets/type_widgets/type_widget.ts
@@ -9,4 +9,6 @@ export interface TypeWidgetProps {
ntxId: string | null | undefined;
parentComponent: TypedComponent<any> | undefined;
noteContext: NoteContext | undefined;
+ /** Whether this is the displayed type widget for its context; false when cached/hidden after the note's type changed. */
+ isVisible?: boolean;
}