Skip to content

Build your personal knowledge base with Trilium Notes

client/media player/embeds: relocate the "Download" and "Open Externally" buttons

Adorian Doran7a4301856792
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index 3ef6accc2e..5a8b925aed 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -316,13 +316,25 @@ describe("getRenderedContent file rendering", () => {
expect($renderedContent.find("audio, video").length).toBe(0);
});
- it("mounts the full media player when the caller embeds the note", async () => {
+ it("mounts the full media player when the caller embeds the note, and drops the footer it carries itself", async () => {
const note = buildNote({ title: "V", type: "file" });
note.mime = "video/mp4";
- const { type } = await getRenderedContent(note, { mediaEnvironment: "embedded" });
+ const { type, $renderedContent } = await getRenderedContent(note, { mediaEnvironment: "embedded" });
expect(type).toBe("video");
expect(mediaPreviewComponent).toHaveBeenCalledWith(
expect.objectContaining({ entity: note, environment: "embedded" }), expect.anything());
+ // An embed has no room for a footer: the player takes Download / Open into its own controls.
+ expect($renderedContent.find(".file-footer").length).toBe(0);
+ });
+
+ 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";
+ expect((await getRenderedContent(video)).$renderedContent.find(".file-footer").length).toBe(1);
+
+ const pdf = buildNote({ title: "P", type: "file" });
+ pdf.mime = "application/pdf";
+ expect((await getRenderedContent(pdf, { mediaEnvironment: "embedded" })).$renderedContent.find(".file-footer").length).toBe(1);
});
it("renders the plain media element for callers that serialize to HTML (presentation, printing)", async () => {
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index a4e299a703..6247960ba6 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -8,7 +8,7 @@ import FAttachment from "../entities/fattachment.js";
import FNote from "../entities/fnote.js";
import imageContextMenuService from "../menus/image_context_menu.js";
import { t } from "../services/i18n.js";
-import type { MediaEnvironment } from "../widgets/type_widgets/file/media_environment.js";
+import { type MediaEnvironment, showsFileActions } from "../widgets/type_widgets/file/media_environment.js";
import type { LlmChatContent, StoredMessage } from "../widgets/type_widgets/llm_chat/llm_chat_types.js";
import renderText, { postProcessRichContent, renderChildrenList } from "./content_renderer_text.js";
import renderDoc from "./doc_renderer.js";
@@ -303,6 +303,9 @@ async function renderFile(entity: FNote | FAttachment, type: string, $renderedCo
}
const $content = $('<div style="display: flex; flex-direction: column; height: 100%; justify-content: end;">');
+ // An embedded player has no room for a footer below it, so it carries Download / Open in its own controls
+ // instead (see showsFileActions) — and this footer stands down.
+ let mediaOwnsFileActions = false;
if (type === "pdf") {
const url = `../../api/${entityType}/${entityId}/open`;
@@ -324,6 +327,7 @@ async function renderFile(entity: FNote | FAttachment, type: string, $renderedCo
$content.append($nativePreview);
} else {
+ mediaOwnsFileActions = showsFileActions(environment);
await renderMedia(entity, environment, $content);
}
}
@@ -332,7 +336,7 @@ async function renderFile(entity: FNote | FAttachment, type: string, $renderedCo
await addOCRTextIfAvailable(entity, $content);
}
- if (entityType === "notes" && "noteId" in entity) {
+ if (entityType === "notes" && "noteId" in entity && !mediaOwnsFileActions) {
// TODO: we should make this available also for attachments, but there's a problem with "Open externally" support
// in attachment list
const $downloadButton = $(`
diff --git a/apps/client/src/widgets/type_widgets/file/Audio.tsx b/apps/client/src/widgets/type_widgets/file/Audio.tsx
index 5ad8eb8295..2528a3eb03 100644
--- a/apps/client/src/widgets/type_widgets/file/Audio.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Audio.tsx
@@ -5,11 +5,12 @@ import Icon from "../../react/Icon";
import NoItems from "../../react/NoItems";
import { loadWaveform } from "./audio_waveform";
import { AudioVisualizer } from "./AudioVisualizer";
-import { playerRootClasses, preloadFor, usesCompactControls } from "./media_environment";
+import MediaFileActions from "./MediaFileActions";
+import { playerRootClasses, preloadFor, showsFileActions, usesCompactControls } from "./media_environment";
import { MediaPlayerProps, MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";
import { WaveformSeekBar } from "./WaveformSeekBar";
-export default function AudioPreview({ source, environment, note, noteContext, isVisible = true, autoPlay }: MediaPlayerProps) {
+export default function AudioPreview({ source, entity, environment, noteContext, isVisible = true, autoPlay }: MediaPlayerProps) {
const wrapperRef = useRef<HTMLDivElement>(null);
const audioRef = useRef<HTMLAudioElement>(null);
const [playing, setPlaying] = useState(false);
@@ -36,7 +37,7 @@ export default function AudioPreview({ source, environment, note, noteContext, i
// 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, environment, note, noteContext, isVisible, autoPlay, mimePrefix: "audio/", mediaRef: audioRef, playMode });
+ const siblingNavigation = useMediaSessionController({ source, entity, environment, noteContext, isVisible, autoPlay, mimePrefix: "audio/", mediaRef: audioRef, playMode });
const waveformPeaks = useWaveformPeaks(source.fullUrl);
if (error) {
@@ -69,6 +70,7 @@ export default function AudioPreview({ source, environment, note, noteContext, i
<PlayPauseButton playing={playing} togglePlayback={togglePlayback} />
<WaveformSeekBar mediaRef={audioRef} peaks={waveformPeaks} />
<VolumeControl mediaRef={audioRef} />
+ {showsFileActions(environment) && <MediaFileActions entity={entity} />}
</div>
) : (
<>
diff --git a/apps/client/src/widgets/type_widgets/file/MediaFileActions.spec.tsx b/apps/client/src/widgets/type_widgets/file/MediaFileActions.spec.tsx
new file mode 100644
index 0000000000..cc0ef354a0
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/MediaFileActions.spec.tsx
@@ -0,0 +1,80 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { openService } = vi.hoisted(() => ({
+ openService: {
+ downloadFileNote: vi.fn(),
+ downloadAttachment: vi.fn(),
+ openNoteExternally: vi.fn(async () => {}),
+ openAttachmentExternally: vi.fn(async () => {})
+ }
+}));
+vi.mock("../../../services/open", () => ({ default: openService }));
+
+import type FAttachment from "../../../entities/fattachment";
+import type FNote from "../../../entities/fnote";
+import MediaFileActions from "./MediaFileActions";
+
+const note = { noteId: "snd1", title: "Podcast", mime: "audio/mpeg", isProtected: false } as FNote;
+const attachment = { attachmentId: "att1", title: "Recording", mime: "audio/mpeg", isProtected: false } as FAttachment;
+
+describe("MediaFileActions", () => {
+ let container: HTMLElement;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ const download = () => container.querySelector(".bx-download") as HTMLElement | null;
+ const open = () => container.querySelector(".bx-link-external") as HTMLElement | null;
+
+ it("downloads and opens a note", async () => {
+ await act(async () => render(<MediaFileActions entity={note} />, container));
+
+ await act(async () => download()?.click());
+ // The parent component is passed as null: media never takes the customDownload path.
+ expect(openService.downloadFileNote).toHaveBeenCalledWith(note, null, null);
+
+ await act(async () => open()?.click());
+ expect(openService.openNoteExternally).toHaveBeenCalledWith("snd1", "audio/mpeg");
+ });
+
+ it("downloads and opens an attachment, which the renderer's own footer cannot", async () => {
+ await act(async () => render(<MediaFileActions entity={attachment} />, container));
+
+ await act(async () => download()?.click());
+ expect(openService.downloadAttachment).toHaveBeenCalledWith("att1");
+
+ await act(async () => open()?.click());
+ expect(openService.openAttachmentExternally).toHaveBeenCalledWith("att1", "audio/mpeg");
+ });
+
+ it("shows a spinner while the external open is in flight", async () => {
+ let finishOpen = () => {};
+ openService.openNoteExternally.mockImplementation(() => new Promise<void>((resolve) => { finishOpen = resolve; }));
+ await act(async () => render(<MediaFileActions entity={note} />, container));
+
+ await act(async () => open()?.click());
+ expect(container.querySelector(".bx-loader")).not.toBeNull();
+ expect(open()).toBeNull();
+
+ await act(async () => { finishOpen(); });
+ expect(container.querySelector(".bx-loader")).toBeNull();
+ expect(open()).not.toBeNull();
+ });
+
+ it("hides Open for a protected note, which the browser can't open outside the protected session", async () => {
+ await act(async () => render(<MediaFileActions entity={{ ...note, isProtected: true } as FNote} />, container));
+
+ expect(download()).not.toBeNull();
+ expect(open()).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/file/MediaFileActions.tsx b/apps/client/src/widgets/type_widgets/file/MediaFileActions.tsx
new file mode 100644
index 0000000000..3c9a9c0f67
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/MediaFileActions.tsx
@@ -0,0 +1,53 @@
+import { useState } from "preact/hooks";
+
+import type FAttachment from "../../../entities/fattachment";
+import type FNote from "../../../entities/fnote";
+import { t } from "../../../services/i18n";
+import openService from "../../../services/open";
+import ActionButton from "../../react/ActionButton";
+
+/**
+ * Download and Open-externally, as two buttons the player carries at the end of its controls. The content
+ * renderer otherwise appends these below the player as a `.file-footer`, which an embed has no room for
+ * (see {@link showsFileActions}).
+ */
+export default function MediaFileActions({ entity }: { entity: FNote | FAttachment }) {
+ const [ opening, setOpening ] = useState(false);
+
+ const download = () => {
+ // The parent component is only there to divert PDFs and the backend log into their own download
+ // handling; media never takes that path, so it downloads straight from the URL.
+ if ("noteId" in entity) {
+ openService.downloadFileNote(entity, null, null);
+ } else {
+ openService.downloadAttachment(entity.attachmentId);
+ }
+ };
+
+ const openExternally = async () => {
+ setOpening(true);
+ try {
+ if ("noteId" in entity) {
+ await openService.openNoteExternally(entity.noteId, entity.mime);
+ } else {
+ await openService.openAttachmentExternally(entity.attachmentId, entity.mime);
+ }
+ } finally {
+ setOpening(false);
+ }
+ };
+
+ return (
+ <>
+ <ActionButton icon="bx bx-download" text={t("file_properties.download")} onClick={download} />
+ {/* Opening goes through the browser, which is not in the protected session. */}
+ {!entity.isProtected && (
+ <ActionButton
+ icon={opening ? "bx bx-loader spin" : "bx bx-link-external"}
+ text={t("file_properties.open")}
+ onClick={() => void openExternally()}
+ />
+ )}
+ </>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
index 63dd511cad..5a1bdfbbaf 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
@@ -4,6 +4,7 @@ import { RefObject } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import type NoteContext from "../../../components/note_context";
+import type FAttachment from "../../../entities/fattachment";
import type FNote from "../../../entities/fnote";
import attributes from "../../../services/attributes";
import froca from "../../../services/froca";
@@ -24,14 +25,14 @@ const NO_KEYS: readonly string[] = [];
/** What {@link AudioPreview} and {@link VideoPreview} are given, whichever environment they render in. */
export interface MediaPlayerProps {
+ /** What is being played: a file note, or an attachment. {@link source} is its resolved media. */
+ entity: FNote | FAttachment;
source: MediaSource;
environment: MediaEnvironment;
/**
- * The note being played, and the tab showing it. Only the note detail has them; they enable sibling
- * navigation, the folder-level play mode and OS media session ownership, all of which are silently
- * skipped without them.
+ * The tab showing the note. Only the note detail has one; it enables sibling navigation, the folder-level
+ * play mode and OS media session ownership, all of which are silently skipped without it.
*/
- note?: FNote;
noteContext?: NoteContext;
isVisible?: boolean;
/** Start playing as soon as the media is ready — the user just activated a lazy preview. */
@@ -202,11 +203,13 @@ 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, note, noteContext, mimePrefix, mediaRef, isVisible = true, playMode, autoPlay }: MediaPlayerProps & {
+export function useMediaSessionController({ source, entity, noteContext, 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).
+ const note = "noteId" in entity ? entity : undefined;
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;
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 a22917f457..b4017192ea 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx
@@ -199,6 +199,33 @@ describe("MediaPreview", () => {
});
});
+ describe("file actions", () => {
+ const fileActions = () => ({
+ download: container.querySelector(".media-compact-row .bx-download"),
+ open: container.querySelector(".media-compact-row .bx-link-external")
+ });
+
+ it.each([ "audio", "video" ] as const)("puts Download / Open at the end of an embedded %s player's controls", async (kind) => {
+ const entity = kind === "audio" ? audioNote : videoNote;
+ await act(async () => render(<MediaPreview entity={entity} environment="embedded" />, container));
+
+ const { download, open } = fileActions();
+ expect(download).not.toBeNull();
+ expect(open).not.toBeNull();
+ // They come last, after the playback controls.
+ expect(download?.previousElementSibling).not.toBeNull();
+ });
+
+ it("leaves them out of a preview, which keeps the renderer's footer below the player instead", async () => {
+ await act(async () => render(<MediaPreview entity={audioNote} environment="preview" />, container));
+ await act(async () => proxyPlayButton()?.click());
+
+ const { download, open } = fileActions();
+ expect(download).toBeNull();
+ expect(open).toBeNull();
+ });
+ });
+
it("keeps a preview's clicks to itself, so pressing play in a collection card doesn't open the note", async () => {
// Both the placeholder and the player it becomes opt out of link navigation (see services/link.ts).
await act(async () => render(<MediaPreview entity={videoNote} environment="preview" />, container));
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx b/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx
index 2a6bd88044..d17b095e56 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx
@@ -34,9 +34,9 @@ export default function MediaPreview({ entity, environment = "standalone", noteC
}
const props = {
+ entity,
source,
environment,
- note: "noteId" in entity ? entity : undefined,
noteContext,
isVisible,
// We only got here from the user pressing play on the placeholder, so honour that press.
diff --git a/apps/client/src/widgets/type_widgets/file/Video.tsx b/apps/client/src/widgets/type_widgets/file/Video.tsx
index 90007e31fd..fa3a1d98b1 100644
--- a/apps/client/src/widgets/type_widgets/file/Video.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Video.tsx
@@ -6,12 +6,13 @@ import { MutableRef, useCallback, useEffect, useRef, useState } from "preact/hoo
import { t } from "../../../services/i18n";
import ActionButton from "../../react/ActionButton";
import NoItems from "../../react/NoItems";
-import { playerRootClasses, preloadFor, showsViewportControls, usesCompactControls } from "./media_environment";
+import MediaFileActions from "./MediaFileActions";
+import { playerRootClasses, preloadFor, showsFileActions, showsViewportControls, usesCompactControls } from "./media_environment";
import { MediaPlayerProps, MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SeekBar, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";
const AUTO_HIDE_DELAY = 3000;
-export default function VideoPreview({ source, environment, note, noteContext, isVisible = true, autoPlay }: MediaPlayerProps) {
+export default function VideoPreview({ source, entity, environment, noteContext, isVisible = true, autoPlay }: MediaPlayerProps) {
const wrapperRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const [playing, setPlaying] = useState(false);
@@ -63,7 +64,7 @@ export default function VideoPreview({ source, environment, note, noteContext, i
const onKeyDown = useKeyboardShortcuts(videoRef, wrapperRef, togglePlayback, flashControls);
const { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, videoRef);
- const siblingNavigation = useMediaSessionController({ source, environment, note, noteContext, isVisible, autoPlay, mimePrefix: "video/", mediaRef: videoRef, playMode });
+ const siblingNavigation = useMediaSessionController({ source, entity, environment, noteContext, isVisible, autoPlay, mimePrefix: "video/", mediaRef: videoRef, playMode });
const compact = usesCompactControls(environment);
if (error) {
@@ -97,6 +98,7 @@ export default function VideoPreview({ source, environment, note, noteContext, i
<FullscreenButton targetRef={wrapperRef} />
</>
)}
+ {showsFileActions(environment) && <MediaFileActions entity={entity} />}
</div>
) : (
<>
diff --git a/apps/client/src/widgets/type_widgets/file/media_environment.spec.ts b/apps/client/src/widgets/type_widgets/file/media_environment.spec.ts
index d4ee27a698..76f7c47b73 100644
--- a/apps/client/src/widgets/type_widgets/file/media_environment.spec.ts
+++ b/apps/client/src/widgets/type_widgets/file/media_environment.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { loadsEagerly, playerRootClasses, preloadFor, showsViewportControls, usesCompactControls } from "./media_environment";
+import { loadsEagerly, playerRootClasses, preloadFor, showsFileActions, showsViewportControls, usesCompactControls } from "./media_environment";
describe("media environment", () => {
it("only a preview is lazy — it must not create a media element until the user asks for one", () => {
@@ -32,4 +32,10 @@ describe("media environment", () => {
expect(showsViewportControls("embedded")).toBe(true);
expect(showsViewportControls("standalone")).toBe(true);
});
+
+ it("has only an embed carry Download / Open in its controls, in place of the renderer's footer", () => {
+ expect(showsFileActions("embedded")).toBe(true);
+ expect(showsFileActions("preview")).toBe(false);
+ expect(showsFileActions("standalone")).toBe(false);
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/file/media_environment.ts b/apps/client/src/widgets/type_widgets/file/media_environment.ts
index 8338262775..d4db6eb60d 100644
--- a/apps/client/src/widgets/type_widgets/file/media_environment.ts
+++ b/apps/client/src/widgets/type_widgets/file/media_environment.ts
@@ -49,3 +49,12 @@ export function usesCompactControls(environment: MediaEnvironment): boolean {
export function showsViewportControls(environment: MediaEnvironment): boolean {
return environment !== "preview";
}
+
+/**
+ * Whether the player carries the Download / Open-externally actions at the end of its own controls. An embed
+ * is tight on height, so it takes them into the controls row instead of letting the content renderer append
+ * its `.file-footer` below — which is why the renderer consults this too, and drops the footer when it does.
+ */
+export function showsFileActions(environment: MediaEnvironment): boolean {
+ return environment === "embedded";
+}