Skip to content

Build your personal knowledge base with Trilium Notes

client/media player: add support for media navigation in full-detail attachments

Adorian Doranb59db981a1e7
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index 2eff4cd441..a8aa3cf0b7 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -327,16 +327,6 @@ describe("getRenderedContent file rendering", () => {
expect($renderedContent.find(".file-footer").length).toBe(0);
});
- it("mounts the full media player when the caller gives the media a pane of its own", async () => {
- const note = buildNote({ title: "A", type: "file" });
- note.mime = "audio/mpeg";
- const { $renderedContent } = await getRenderedContent(note, { mediaEnvironment: "standalone" });
- expect(mediaPreviewComponent).toHaveBeenCalledWith(
- expect.objectContaining({ entity: note, environment: "standalone" }), expect.anything());
- // Unlike an embed, the full player leaves Download / Open to the footer below it.
- expect($renderedContent.find(".file-footer").length).toBe(1);
- });
-
it("keeps the footer for a media preview, and for the file types that have no player", async () => {
const video = buildNote({ title: "V", type: "file" });
video.mime = "video/mp4";
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 033d81c7e0..18d7374ae7 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -57,12 +57,14 @@ export interface RenderOptions {
/**
* How audio/video renders. `preview` (the default) shows a click-to-load placeholder, so that a screen
* full of media notes doesn't have every one of them streaming from the server at once; `embedded`
- * mounts the compact player straight away; `standalone` mounts the full one, for a host that gives the
- * media a pane of its own (the attachment full-detail view). `native` emits a plain `<audio>`/`<video>`
- * element instead of the player, for the callers that serialize the rendered content into an HTML string
- * or into a separate document (presentation, printing) — a mounted player would be dead markup there.
+ * mounts the compact player straight away. `native` emits a plain `<audio>`/`<video>` element instead of
+ * the player, for the callers that serialize the rendered content into an HTML string or into a separate
+ * document (presentation, printing) — a mounted player would be dead markup there.
+ *
+ * A full-size player has no entry here: it needs the tab it lives in (for sibling navigation and the OS
+ * media session), which the renderer has no access to, so its hosts mount {@link MediaPreview} themselves.
*/
- mediaEnvironment?: MediaEnvironment | "native";
+ mediaEnvironment?: "preview" | "embedded" | "native";
/**
* If enabled, PDFs render with the pdf.js toolbar (zoom, page navigation, print, download).
* Off by default so that lightweight previews (attachment list, tooltips, embeds) stay bare;
@@ -383,7 +385,7 @@ async function renderFile(entity: FNote | FAttachment, type: string, $renderedCo
/**
* Mounts the Trilium media player for an audio/video note or attachment. In a `preview` it starts as a
* placeholder and only loads the media once the user presses play (see {@link MediaPreview}); an `embedded`
- * or `standalone` one loads straight away. Like every other mounted widget here, the caller must tear it down via
+ * one loads straight away. Like every other mounted widget here, the embedding caller must tear it down via
* {@link disposeInteractiveContent} — otherwise the Preact root leaks and its media keeps playing.
*/
async function renderMedia(entity: FNote | FAttachment, environment: MediaEnvironment, $content: JQuery<HTMLElement>) {
diff --git a/apps/client/src/widgets/react/SiblingNavigator.tsx b/apps/client/src/widgets/react/SiblingNavigator.tsx
index 6dfcca4bf9..67aa40d795 100644
--- a/apps/client/src/widgets/react/SiblingNavigator.tsx
+++ b/apps/client/src/widgets/react/SiblingNavigator.tsx
@@ -202,18 +202,23 @@ export function noteSiblingProvider(note: FNote | undefined, noteContext: NoteCo
};
}
-/** Iterator over the note's same-role attachments, with the role taken from the currently-shown attachment. */
-function attachmentSiblingProvider(note: FNote | undefined, noteContext: NoteContext | undefined, viewScope: ViewScope): SiblingNavigationProvider {
+/**
+ * Iterator over the note's same-role attachments, with the role taken from the currently-shown attachment.
+ * `mimePrefix` narrows it further, for a host that can only show one kind — a media player cycles the
+ * owner's `audio/` attachments rather than every `file`-role one.
+ */
+export function attachmentSiblingProvider(note: FNote | undefined, noteContext: NoteContext | undefined, viewScope: ViewScope, filter: { mimePrefix?: string } = {}): SiblingNavigationProvider {
const notePath = noteContext?.notePath;
const attachmentId = viewScope.attachmentId;
+ const { mimePrefix } = filter;
// Key on the role rather than the id, so cycling same-role attachments doesn't re-fetch the list.
const role = note?.attachments?.find((attachment) => attachment.attachmentId === attachmentId)?.role;
return {
currentId: attachmentId,
- depsKey: `attachment:${note?.noteId ?? ""}:${role ?? attachmentId ?? ""}`,
+ depsKey: `attachment:${note?.noteId ?? ""}:${role ?? attachmentId ?? ""}:${mimePrefix ?? ""}`,
loadSiblings: async () => {
if (!note) return [];
- return sameRoleAttachments(Array.from(await note.getAttachments()), attachmentId);
+ return sameRoleAttachments(Array.from(await note.getAttachments()), attachmentId, mimePrefix);
},
navigateTo: (id) => { if (notePath) void noteContext?.setNote(notePath, { viewScope: { ...viewScope, attachmentId: id } }); },
shouldRefresh: (loadResults) => !!note && loadResults.getAttachmentRows().some((row) => row.ownerId === note.noteId)
diff --git a/apps/client/src/widgets/react/sibling_navigation.spec.ts b/apps/client/src/widgets/react/sibling_navigation.spec.ts
index 26e08fadab..434a91160f 100644
--- a/apps/client/src/widgets/react/sibling_navigation.spec.ts
+++ b/apps/client/src/widgets/react/sibling_navigation.spec.ts
@@ -113,4 +113,21 @@ describe("sameRoleAttachments", () => {
expect(sameRoleAttachments(attachments, undefined)).toEqual([]);
expect(sameRoleAttachments([], "a")).toEqual([]);
});
+
+ it("narrows the role to a mime prefix, so a player only cycles what it can play", () => {
+ // Audio, video, PDFs and archives all share the "file" role — only the mime tells them apart.
+ const files = [
+ { attachmentId: "a", role: "file", title: "A", mime: "audio/mpeg" },
+ { attachmentId: "b", role: "file", title: "B", mime: "application/pdf" },
+ { attachmentId: "c", role: "file", title: "C", mime: "audio/ogg" },
+ { attachmentId: "d", role: "image", title: "D", mime: "image/png" },
+ { attachmentId: "e", role: "file", title: "E" }
+ ];
+ expect(sameRoleAttachments(files, "a", "audio/")).toEqual([ { id: "a", title: "A" }, { id: "c", title: "C" } ]);
+ // Without a prefix the role alone decides, as it does for the image viewer.
+ expect(sameRoleAttachments(files, "a")).toEqual([ { id: "a", title: "A" }, { id: "b", title: "B" }, { id: "c", title: "C" }, { id: "e", title: "E" } ]);
+ // An attachment the prefix excludes drops out of its own list; the engine, which needs the current
+ // id to be in it, then reports no navigation at all rather than jumping somewhere unplayable.
+ expect(sameRoleAttachments(files, "b", "audio/").some((sibling) => sibling.id === "b")).toBe(false);
+ });
});
diff --git a/apps/client/src/widgets/react/sibling_navigation.ts b/apps/client/src/widgets/react/sibling_navigation.ts
index 8692aa03ea..914a737c30 100644
--- a/apps/client/src/widgets/react/sibling_navigation.ts
+++ b/apps/client/src/widgets/react/sibling_navigation.ts
@@ -60,10 +60,13 @@ export function isInteractiveTarget(target: { tagName?: string; getAttribute?(na
/**
* From a note's ordered attachments and the currently-shown one, keeps those sharing its role (so the
- * viewer cycles e.g. image-with-image), mapped to `{ id, title }`. Empty when the current one is absent.
+ * viewer cycles e.g. image-with-image), optionally narrowed to a mime prefix — a media player only
+ * advances between playable attachments, where the `file` role alone would also hand it a PDF or a ZIP.
+ * Mapped to `{ id, title }`. Empty when the current one is absent.
*/
-export function sameRoleAttachments(attachments: readonly { attachmentId: string; role: string; title: string }[], currentAttachmentId: string | undefined): { id: string; title: string }[] {
+export function sameRoleAttachments(attachments: readonly { attachmentId: string; role: string; title: string; mime?: string }[], currentAttachmentId: string | undefined, mimePrefix?: string): { id: string; title: string }[] {
const role = attachments.find((attachment) => attachment.attachmentId === currentAttachmentId)?.role;
if (!role) return [];
- return attachments.filter((attachment) => attachment.role === role).map((attachment) => ({ id: attachment.attachmentId, title: attachment.title }));
+ const matches = (attachment: { role: string; mime?: string }) => attachment.role === role && (!mimePrefix || !!attachment.mime?.startsWith(mimePrefix));
+ return attachments.filter(matches).map((attachment) => ({ id: attachment.attachmentId, title: attachment.title }));
}
diff --git a/apps/client/src/widgets/type_widgets/Attachment.css b/apps/client/src/widgets/type_widgets/Attachment.css
index 9ff1173962..a8d088463d 100644
--- a/apps/client/src/widgets/type_widgets/Attachment.css
+++ b/apps/client/src/widgets/type_widgets/Attachment.css
@@ -124,6 +124,12 @@
overflow: hidden;
}
+/* Same flex-slot constraint for the media player, which is height:100% of whatever it is given: without
+ it the video (and the audio player's visualizer band) grows the layout instead of fitting the pane. */
+.attachment-content-wrapper.attachment-media-player {
+ overflow: hidden;
+}
+
.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 e66a924c93..2d64ee2400 100644
--- a/apps/client/src/widgets/type_widgets/Attachment.tsx
+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx
@@ -34,6 +34,7 @@ import NoteLink from "../react/NoteLink";
import { ParentComponent, refToJQuerySelector } from "../react/react_utils";
import SiblingNavigator from "../react/SiblingNavigator";
import { TextPreview } from "./File";
+import MediaPreview from "./file/MediaPreview";
import { TypeWidgetProps } from "./type_widget";
/**
@@ -155,9 +156,13 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
const isFileLike = attachment.role === "file" || attachment.role === "importSource";
const supportsOcr = attachment.role === "image" || isFileLike;
- // Image attachments opened in full detail get the interactive zoom/pan viewer; everything
- // else is rendered imperatively via the content renderer.
+ // Opened in full detail, an image gets the interactive zoom/pan viewer and audio/video the full media
+ // player — both mounted here rather than through the content renderer, which has no tab context to hand
+ // them (and it is the tab that lets them navigate between the note's other attachments). Everything else,
+ // in either view, is rendered imperatively via the content renderer.
const isZoomableImage = !!isFullDetail && attachment.role === "image";
+ const isPlayableMedia = !!isFullDetail && (attachment.mime.startsWith("audio/") || attachment.mime.startsWith("video/"));
+ const rendersItself = isZoomableImage || isPlayableMedia;
const imageSrc = `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}?${attachment.utcDateModified}`;
/** Unmounts whatever the content renderer previously mounted here (a media player), so that replacing
@@ -168,13 +173,10 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
}
function refresh() {
- if (!isZoomableImage) {
- // The full-detail view has a pane to itself, so it gets the pdf.js toolbar and the full media
- // player; a list-view preview stays bare and click-to-play.
- content_renderer.getRenderedContent(attachment, {
- pdfToolbar: !!isFullDetail,
- mediaEnvironment: isFullDetail ? "standalone" : "preview"
- })
+ if (!rendersItself) {
+ // The full-detail view has a pane to itself, so it gets the pdf.js toolbar; a list-view preview
+ // stays bare.
+ content_renderer.getRenderedContent(attachment, { pdfToolbar: !!isFullDetail })
.then(({ $renderedContent }) => {
disposeContent();
contentWrapper.current?.replaceChildren(...$renderedContent);
@@ -192,7 +194,7 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
useEffect(() => {
refresh();
return disposeContent;
- }, [ attachment, isZoomableImage ]);
+ }, [ attachment, rendersItself ]);
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
if (loadResults.getAttachmentRows().find(attachment => attachment.attachmentId)) {
refresh();
@@ -276,6 +278,16 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
extraNextKeys={[ "Space" ]}
/>
</div>
+ ) : isPlayableMedia ? (
+ <div key="media-player" className="attachment-content-wrapper attachment-media-player">
+ <MediaPreview
+ entity={attachment}
+ environment="standalone"
+ noteContext={noteContext}
+ ownerNote={ownerNote}
+ viewScope={viewScope}
+ />
+ </div>
) : (
<div key="rendered" ref={contentWrapper} className="attachment-content-wrapper" />
)}
diff --git a/apps/client/src/widgets/type_widgets/file/Audio.tsx b/apps/client/src/widgets/type_widgets/file/Audio.tsx
index 07c378f41c..b233599419 100644
--- a/apps/client/src/widgets/type_widgets/file/Audio.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Audio.tsx
@@ -12,7 +12,7 @@ import { playerRootClasses, preloadFor, showsFileActions, usesCompactControls }
import { MediaPlayerProps, MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SkipButton, useMediaPlayerShortcutHints, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";
import { WaveformSeekBar } from "./WaveformSeekBar";
-export default function AudioPreview({ source, entity, environment, noteContext, isVisible = true, autoPlay }: MediaPlayerProps) {
+export default function AudioPreview({ source, entity, environment, noteContext, ownerNote, viewScope, isVisible = true, autoPlay }: MediaPlayerProps) {
const wrapperRef = useRef<HTMLDivElement>(null);
const audioRef = useRef<HTMLAudioElement>(null);
const [playing, setPlaying] = useState(false);
@@ -38,8 +38,8 @@ export default function AudioPreview({ source, entity, environment, noteContext,
// 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 { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, audioRef);
- const siblingNavigation = useMediaSessionController({ source, entity, environment, noteContext, isVisible, autoPlay, mimePrefix: "audio/", mediaRef: audioRef, playMode });
+ const { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, audioRef, ownerNote?.noteId);
+ const siblingNavigation = useMediaSessionController({ source, entity, environment, noteContext, ownerNote, viewScope, isVisible, autoPlay, mimePrefix: "audio/", mediaRef: audioRef, playMode });
useMediaPlayerShortcutHints({ fullscreen: false });
const waveformPeaks = useWaveformPeaks(source.fullUrl);
@@ -82,7 +82,7 @@ export default function AudioPreview({ source, entity, environment, noteContext,
<div class="media-buttons-row">
<div className="left">
<PlaybackSpeed mediaRef={audioRef} />
- {/* The play mode lives on the parent folder, which only the note detail knows. */}
+ {/* The play mode lives on the parent folder (or, for an attachment, its owner note), which only a detail view knows. */}
{noteContext && <PlayModeButton mode={playMode} onSelectMode={setPlayMode} />}
</div>
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
index 91fae114a9..e1ed41e9fa 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
@@ -9,6 +9,7 @@ import type FNote from "../../../entities/fnote";
import attributes from "../../../services/attributes";
import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
+import type { ViewScope } from "../../../services/link";
import type { ShortcutHint, ShortcutHintDefinition, ShortcutHintSection } from "../../../services/shortcut_hints";
import { isMobile } from "../../../services/utils";
import { logError } from "../../../services/ws";
@@ -17,7 +18,7 @@ import Dropdown from "../../react/Dropdown";
import { useContextualShortcutHints, useTriliumEvent, useTriliumEvents } from "../../react/hooks";
import Icon from "../../react/Icon";
import { getParentFromNotePath } from "../../react/sibling_navigation";
-import { noteSiblingProvider, type SiblingNavigationState, useSiblingKeyboard, useSiblingNavigation } from "../../react/SiblingNavigator";
+import { attachmentSiblingProvider, noteSiblingProvider, type SiblingNavigationState, useSiblingKeyboard, useSiblingNavigation } from "../../react/SiblingNavigator";
import type { MediaEnvironment } from "./media_environment";
import { getAutoAdvanceTarget, MEDIA_PLAY_MODE_ICONS, MEDIA_PLAY_MODE_LABEL, MEDIA_PLAY_MODE_LABEL_KEYS, MEDIA_PLAY_MODES, type MediaPlayMode, playModeFromLabel, playModeToLabel, shouldLoop } from "./media_play_mode";
import type { MediaSource } from "./media_source";
@@ -31,10 +32,16 @@ export interface MediaPlayerProps {
source: MediaSource;
environment: MediaEnvironment;
/**
- * The tab showing the note. Only the note detail has one; it enables sibling navigation, the folder-level
+ * The tab showing the media. Only a detail view has one; it enables sibling navigation, the folder-level
* play mode and OS media session ownership, all of which are silently skipped without it.
*/
noteContext?: NoteContext;
+ /**
+ * When {@link entity} is an attachment: the note owning it and the tab's view scope. Together they are what
+ * lets the player cycle the owner's other media attachments — the equivalent of a note's folder siblings.
+ */
+ ownerNote?: FNote;
+ viewScope?: ViewScope;
isVisible?: boolean;
/** Start playing as soon as the media is ready — the user just activated a lazy preview. */
autoPlay?: boolean;
@@ -206,8 +213,8 @@ export function VolumeControl({ mediaRef }: { mediaRef: RefObject<HTMLVideoEleme
);
}
-/** noteId of the sibling we're jumping to, so only *that* note auto-plays (a cancelled jump can't leak). */
-let autoPlayTargetNoteId: string | null = null;
+/** Id of the sibling we're jumping to, so only *that* media auto-plays (a cancelled jump can't leak). */
+let autoPlayTargetId: string | null = null;
/** The player instance currently owning the (global) Media Session action handlers, if any. */
let mediaSessionOwner: object | null = null;
@@ -238,14 +245,17 @@ const OWNED_MEDIA_ACTIONS: MediaSessionAction[] = [ "previoustrack", "nexttrack"
* 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({ source, entity, noteContext, mimePrefix, mediaRef, isVisible = true, playMode, autoPlay }: MediaPlayerProps & {
+export function useMediaSessionController({ source, entity, noteContext, ownerNote, viewScope, mimePrefix, mediaRef, isVisible = true, playMode, autoPlay }: MediaPlayerProps & {
mimePrefix: string;
mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>;
playMode: MediaPlayMode;
}) {
- // Siblings are a note-tree notion, so an attachment has none (and neither has a note without a tab).
+ // A note cycles the playable siblings in its folder; an attachment cycles the owner note's playable
+ // attachments. Either way it takes a tab to navigate in, so without one there is nothing to move between.
const note = "noteId" in entity ? entity : undefined;
- const navigation = useSiblingNavigation(noteSiblingProvider(note, noteContext, { mimePrefix }));
+ const navigation = useSiblingNavigation(note
+ ? noteSiblingProvider(note, noteContext, { mimePrefix })
+ : attachmentSiblingProvider(ownerNote, noteContext, viewScope ?? {}, { mimePrefix }));
// Stable identity for this player instance, used to coordinate with the other mounted players.
const self = useRef<object>({}).current;
@@ -265,8 +275,8 @@ export function useMediaSessionController({ source, entity, noteContext, mimePre
const wrapped = navigation && isVisible ? {
...navigation,
- navigatePrevious: () => { autoPlayTargetNoteId = navigation.previousId; navigation.navigatePrevious(); },
- navigateNext: () => { autoPlayTargetNoteId = navigation.nextId; navigation.navigateNext(); }
+ navigatePrevious: () => { autoPlayTargetId = navigation.previousId; navigation.navigatePrevious(); },
+ navigateNext: () => { autoPlayTargetId = navigation.nextId; navigation.navigateNext(); }
} : null;
useSiblingKeyboard(wrapped, noteContext, undefined, NO_KEYS, NO_KEYS, { edgeKeys: false });
@@ -350,8 +360,8 @@ export function useMediaSessionController({ source, entity, noteContext, mimePre
if (typeof MediaMetadata !== "undefined") mediaSession.metadata = new MediaMetadata({ title: source.title });
// Previous/next track navigate siblings (only when there are any); the live re-check guards against
// the context having navigated to a different note since these handlers were bound.
- setHandler("previoustrack", hasMediaNav ? () => { if (isCurrentContextNote(noteContext, source.id)) wrappedRef.current?.navigatePrevious(); } : null);
- setHandler("nexttrack", hasMediaNav ? () => { if (isCurrentContextNote(noteContext, source.id)) wrappedRef.current?.navigateNext(); } : null);
+ setHandler("previoustrack", hasMediaNav ? () => { if (isCurrentContextMedia(noteContext, source.id)) wrappedRef.current?.navigatePrevious(); } : null);
+ setHandler("nexttrack", hasMediaNav ? () => { if (isCurrentContextMedia(noteContext, source.id)) wrappedRef.current?.navigateNext(); } : null);
// Seek/stop drive this player's element, using the same amounts as its rewind/fast-forward buttons.
setHandler("seekbackward", (details) => seekBy(mediaRef, -(details.seekOffset || SEEK_BACK_SECONDS)));
setHandler("seekforward", (details) => seekBy(mediaRef, details.seekOffset || SEEK_FORWARD_SECONDS));
@@ -418,8 +428,8 @@ export function useMediaSessionController({ source, entity, noteContext, mimePre
// Play as soon as the media can: either this note was reached by a sibling jump, or the user just
// activated a lazy preview (whose player only mounts on that click, so it starts playing right away).
useEffect(() => {
- const jumpedTo = autoPlayTargetNoteId === source.id;
- if (jumpedTo) autoPlayTargetNoteId = null;
+ const jumpedTo = autoPlayTargetId === source.id;
+ if (jumpedTo) autoPlayTargetId = null;
if (!jumpedTo && !autoPlay) return;
const media = mediaRef.current;
@@ -437,14 +447,16 @@ export function useMediaSessionController({ source, entity, noteContext, mimePre
}
/**
- * Whether `noteId` is the current note of `noteContext` — the note this player is showing in its own
- * tab/split, regardless of whether that tab is the active one. This gates Media Session ownership: a
- * backgrounded player stays the owner while its media plays, and only a stale/cached player (whose context
- * has since moved to a different note) reports false and stands down. Closing the tab unmounts the player,
- * which releases the session via the effect cleanup instead.
+ * Whether `id` (a noteId, or an attachmentId when playing an attachment) is what `noteContext` currently
+ * shows in its own tab/split, regardless of whether that tab is the active one. This gates Media Session
+ * ownership: a backgrounded player stays the owner while its media plays, and only a stale/cached player
+ * (whose context has since moved elsewhere) reports false and stands down. Closing the tab unmounts the
+ * player, which releases the session via the effect cleanup instead.
*/
-function isCurrentContextNote(noteContext: NoteContext | undefined, noteId: string): boolean {
- return !!noteContext && noteContext.noteId === noteId;
+function isCurrentContextMedia(noteContext: NoteContext | undefined, id: string): boolean {
+ if (!noteContext) return false;
+ // An attachment view names its attachment in the view scope; the note behind it is only the owner.
+ return noteContext.viewScope?.attachmentId ? noteContext.viewScope.attachmentId === id : noteContext.noteId === id;
}
/** Marks `player` as the one currently playing and notifies the rest so they pause and release the session. */
@@ -498,13 +510,14 @@ export function SkipButton({ mediaRef, seconds, icon, text }: { mediaRef: RefObj
}
/**
- * The folder-level play mode (read from the parent's `#mediaNotesPlayMode` label) for the current media note,
- * kept in sync as that label changes. Derives the element's `loop` from the mode and persists changes back to
- * the parent — the `next` mode's actual auto-advance is handled by {@link useMediaSessionController} (which
- * receives the resolved `mode`).
+ * The play mode (a `#mediaNotesPlayMode` label) shared by everything the player can move between, kept in sync
+ * as that label changes. It lives on whatever holds that playlist: the parent folder for a media note, or — via
+ * `playlistNoteId` — the owner note for one of its media attachments. Derives the element's `loop` from the
+ * mode and persists changes back there; the `next` mode's actual auto-advance is handled by
+ * {@link useMediaSessionController} (which receives the resolved `mode`).
*/
-export function useMediaPlayMode(noteContext: NoteContext | undefined, mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>): { mode: MediaPlayMode; setMode: (mode: MediaPlayMode) => void } {
- const parentNoteId = getParentFromNotePath(noteContext?.notePath)?.parentNoteId;
+export function useMediaPlayMode(noteContext: NoteContext | undefined, mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>, playlistNoteId?: string): { mode: MediaPlayMode; setMode: (mode: MediaPlayMode) => void } {
+ const parentNoteId = playlistNoteId ?? getParentFromNotePath(noteContext?.notePath)?.parentNoteId;
const [ mode, setLocalMode ] = useState<MediaPlayMode>("once");
const [ refreshCounter, setRefreshCounter ] = useState(0);
@@ -559,7 +572,7 @@ export function useMediaPlayMode(noteContext: NoteContext | undefined, mediaRef:
return { mode, setMode };
}
-/** Replaces the loop toggle: a dropdown to pick the folder's play mode (play once / loop / autoplay). */
+/** Replaces the loop toggle: a dropdown to pick the playlist's play mode (play once / loop / autoplay). */
export function PlayModeButton({ mode, onSelectMode }: { mode: MediaPlayMode, onSelectMode: (mode: MediaPlayMode) => void }) {
return (
<Dropdown
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx b/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx
index 86cf873789..4e0e8dc064 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx
@@ -9,6 +9,7 @@ const { audioVisualizer } = vi.hoisted(() => ({ audioVisualizer: vi.fn((_props:
vi.mock("./audio_waveform", () => ({ loadWaveform: vi.fn(async () => null) }));
vi.mock("./AudioVisualizer", () => ({ AudioVisualizer: audioVisualizer }));
+import type NoteContext from "../../../components/note_context";
import type FAttachment from "../../../entities/fattachment";
import type FNote from "../../../entities/fnote";
import MediaPreview from "./MediaPreview";
@@ -110,6 +111,52 @@ describe("MediaPreview", () => {
expect(container.querySelector(".play-mode-dropdown")).toBeNull();
});
+ describe("attachment siblings", () => {
+ // Audio, video, PDFs and archives all carry the "file" role, so only the mime tells them apart.
+ const attachments = [
+ { attachmentId: "att1", role: "file", title: "Recording", mime: "audio/mpeg" },
+ { attachmentId: "att2", role: "file", title: "Manual", mime: "application/pdf" },
+ { attachmentId: "att3", role: "file", title: "Interview", mime: "audio/ogg" }
+ ];
+ const viewScope = { viewMode: "attachments" as const, attachmentId: "att1" };
+ const ownerNote = { noteId: "own1", attachments, getAttachments: async () => attachments } as unknown as FNote;
+
+ const renderAttachmentPlayer = async (setNote: ReturnType<typeof vi.fn>) => {
+ const noteContext = { noteId: "own1", notePath: "root/own1", viewScope, isActive: () => true, setNote } as unknown as NoteContext;
+ await act(async () => render(
+ <MediaPreview entity={audioAttachment} environment="standalone" noteContext={noteContext} ownerNote={ownerNote} viewScope={viewScope} />,
+ container));
+ // Siblings are loaded asynchronously, so the buttons only appear on the following render.
+ await act(async () => {});
+ };
+
+ it("moves to the owner note's other playable attachments, skipping what it can't play", async () => {
+ const setNote = vi.fn();
+ await renderAttachmentPlayer(setNote);
+
+ const next = container.querySelector(".bx-skip-next");
+ expect(next).not.toBeNull();
+ expect(container.querySelector(".bx-skip-previous")).not.toBeNull();
+
+ await act(async () => (next as HTMLElement).click());
+ // att2 is the PDF sitting between them, and is passed over.
+ expect(setNote).toHaveBeenCalledWith("root/own1", { viewScope: { ...viewScope, attachmentId: "att3" } });
+ });
+
+ it("has nothing to move between when the owner has a single playable attachment", async () => {
+ const setNote = vi.fn();
+ const lonelyOwner = { noteId: "own1", attachments: attachments.slice(0, 2), getAttachments: async () => attachments.slice(0, 2) } as unknown as FNote;
+ const noteContext = { noteId: "own1", notePath: "root/own1", viewScope, isActive: () => true, setNote } as unknown as NoteContext;
+ await act(async () => render(
+ <MediaPreview entity={audioAttachment} environment="standalone" noteContext={noteContext} ownerNote={lonelyOwner} viewScope={viewScope} />,
+ container));
+ await act(async () => {});
+
+ expect(container.querySelector(".bx-skip-next")).toBeNull();
+ expect(container.querySelector(".bx-skip-previous")).toBeNull();
+ });
+ });
+
describe("compact audio chrome", () => {
/** The compact chrome is worn everywhere but a standalone player — an activated preview and an embed alike. */
const renderCompactAudio = async (environment: "preview" | "embedded") => {
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx b/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx
index d17b095e56..eefc9628fd 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx
@@ -3,6 +3,7 @@ import { useState } from "preact/hooks";
import type NoteContext from "../../../components/note_context";
import type FAttachment from "../../../entities/fattachment";
import type FNote from "../../../entities/fnote";
+import type { ViewScope } from "../../../services/link";
import AudioPreview from "./Audio";
import { loadsEagerly, type MediaEnvironment } from "./media_environment";
import { getMediaSource } from "./media_source";
@@ -13,8 +14,11 @@ interface MediaPreviewProps {
/** The media to play: an audio/video file note, or an attachment with such a mime type. */
entity: FNote | FAttachment;
environment?: MediaEnvironment;
- /** The tab showing the note; only the note detail has one. Enables siblings, play mode and the OS session. */
+ /** The tab showing the media; only a detail view has one. Enables siblings, play mode and the OS session. */
noteContext?: NoteContext;
+ /** For an attachment: the note owning it, and the tab's view scope — together they enable sibling navigation. */
+ ownerNote?: FNote;
+ viewScope?: ViewScope;
isVisible?: boolean;
}
@@ -24,7 +28,7 @@ interface MediaPreviewProps {
* until the user clicks its play button — only then is a media element created, and it starts playing right
* away. Everywhere else the player mounts immediately, ready to play.
*/
-export default function MediaPreview({ entity, environment = "standalone", noteContext, isVisible }: MediaPreviewProps) {
+export default function MediaPreview({ entity, environment = "standalone", noteContext, ownerNote, viewScope, isVisible }: MediaPreviewProps) {
const eager = loadsEagerly(environment);
const [ activated, setActivated ] = useState(eager);
const source = getMediaSource(entity);
@@ -38,6 +42,8 @@ export default function MediaPreview({ entity, environment = "standalone", noteC
source,
environment,
noteContext,
+ ownerNote,
+ viewScope,
isVisible,
// We only got here from the user pressing play on the placeholder, so honour that press.
autoPlay: !eager
diff --git a/apps/client/src/widgets/type_widgets/file/Video.tsx b/apps/client/src/widgets/type_widgets/file/Video.tsx
index eba840ca5a..4349440f26 100644
--- a/apps/client/src/widgets/type_widgets/file/Video.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Video.tsx
@@ -14,7 +14,7 @@ import { MediaPlayerProps, MediaSiblingButton, PlaybackSpeed, PlayModeButton, Pl
const AUTO_HIDE_DELAY = 3000;
-export default function VideoPreview({ source, entity, environment, noteContext, isVisible = true, autoPlay }: MediaPlayerProps) {
+export default function VideoPreview({ source, entity, environment, noteContext, ownerNote, viewScope, isVisible = true, autoPlay }: MediaPlayerProps) {
const wrapperRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const [playing, setPlaying] = useState(false);
@@ -65,8 +65,8 @@ export default function VideoPreview({ source, entity, environment, noteContext,
}, [togglePlayback, toggleControls]);
const onKeyDown = useKeyboardShortcuts(videoRef, wrapperRef, togglePlayback, flashControls);
- const { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, videoRef);
- const siblingNavigation = useMediaSessionController({ source, entity, environment, noteContext, isVisible, autoPlay, mimePrefix: "video/", mediaRef: videoRef, playMode });
+ const { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, videoRef, ownerNote?.noteId);
+ const siblingNavigation = useMediaSessionController({ source, entity, environment, noteContext, ownerNote, viewScope, isVisible, autoPlay, mimePrefix: "video/", mediaRef: videoRef, playMode });
useMediaPlayerShortcutHints({ fullscreen: true });
const compact = usesCompactControls(environment);
@@ -109,7 +109,7 @@ export default function VideoPreview({ source, entity, environment, noteContext,
<div class="media-buttons-row">
<div className="left">
<PlaybackSpeed mediaRef={videoRef} />
- {/* The play mode lives on the parent folder, which only the note detail knows. */}
+ {/* The play mode lives on the parent folder (or, for an attachment, its owner note), which only a detail view knows. */}
{noteContext && <PlayModeButton mode={playMode} onSelectMode={setPlayMode} />}
<RotateButton videoRef={videoRef} />
</div>