Skip to content

Build your personal knowledge base with Trilium Notes

client/media player: create a preview/embed dedicated renderer

Adorian Dorane49ff1da1311
diff --git a/apps/client/src/print.spec.tsx b/apps/client/src/print.spec.tsx
index 135ec7284c..171437ca98 100644
--- a/apps/client/src/print.spec.tsx
+++ b/apps/client/src/print.spec.tsx
@@ -174,7 +174,7 @@ describe("SingleNoteRenderer", () => {
expect(onReady).toHaveBeenCalledWith({ type: "single-note" });
});
// Printing preserves full include-note nesting via expandNestedIncludes.
- expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedIncludes: true });
+ expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedIncludes: true, mediaEnvironment: "native" });
});
it("renders a non-text, non-spreadsheet note via the content renderer", async () => {
@@ -184,7 +184,7 @@ describe("SingleNoteRenderer", () => {
await vi.waitFor(() => expect(onReady).toHaveBeenCalledWith({ type: "single-note" }));
// Printing preserves full include-note nesting via expandNestedIncludes.
- expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedIncludes: true });
+ expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedIncludes: true, mediaEnvironment: "native" });
});
});
diff --git a/apps/client/src/print.tsx b/apps/client/src/print.tsx
index 567d57aa61..3c7ee275dc 100644
--- a/apps/client/src/print.tsx
+++ b/apps/client/src/print.tsx
@@ -112,7 +112,7 @@ export function SingleNoteRenderer({ note, onReady }: RendererProps) {
await import("@triliumnext/ckeditor5/src/theme/ck-content.css");
}
// Printing preserves full include-note nesting (see expandNestedIncludes).
- const { $renderedContent } = await content_renderer.getRenderedContent(note, { noChildrenList: true, expandNestedIncludes: true });
+ const { $renderedContent } = await content_renderer.getRenderedContent(note, { noChildrenList: true, expandNestedIncludes: true, mediaEnvironment: "native" });
container.replaceChildren(...$renderedContent);
// Note types rendered as a mounted component (an AI chat) start their transform
diff --git a/apps/client/src/services/content_renderer.css b/apps/client/src/services/content_renderer.css
index eb50f24bef..c965895a0b 100644
--- a/apps/client/src/services/content_renderer.css
+++ b/apps/client/src/services/content_renderer.css
@@ -30,3 +30,10 @@
height: 100%;
min-height: 120px;
}
+
+/* The mounted media player (placeholder or full) takes the space its host gives it, above the file footer,
+ down to a floor that keeps it usable in a short host such as a collection tile. */
+.rendered-content .rendered-media {
+ flex: 1;
+ min-height: 8rem;
+}
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index 867208ee41..3ef6accc2e 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -72,6 +72,9 @@ vi.mock("../widgets/type_widgets/file/PdfViewer", () => ({ default: pdfViewerCom
const webViewComponent = vi.fn((_props: any): VNode<any> => h("span", { class: "mock-webview-marker" }));
vi.mock("../widgets/type_widgets/WebView", () => ({ default: webViewComponent }));
+const mediaPreviewComponent = vi.fn((_props: any): VNode<any> => h("span", { class: "mock-media-marker" }));
+vi.mock("../widgets/type_widgets/file/MediaPreview", () => ({ default: mediaPreviewComponent }));
+
const embeddedNoteListComponent = vi.fn((_props: any) => null);
vi.mock("../widgets/collections/NoteList", () => ({ EmbeddedNoteList: embeddedNoteListComponent }));
@@ -301,20 +304,41 @@ describe("getRenderedContent file rendering", () => {
expect($renderedContent.hasClass("no-preview")).toBe(true);
});
- it("renders an audio file note", async () => {
+ it("mounts a lazy media player for an audio or video note, streaming nothing until it is played", async () => {
const note = buildNote({ title: "A", type: "file" });
note.mime = "audio/mpeg";
const { type, $renderedContent } = await getRenderedContent(note);
expect(type).toBe("audio");
- expect($renderedContent.find("audio").attr("src")).toBe(getUrlForDownload(`api/notes/${note.noteId}/open-partial`));
+ expect($renderedContent.find(".rendered-media").length).toBe(1);
+ expect(mediaPreviewComponent).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: note, environment: "preview" }), expect.anything());
+ // No media element is emitted here at all — the placeholder creates one only once it is clicked.
+ expect($renderedContent.find("audio, video").length).toBe(0);
});
- it("renders a video file note", async () => {
+ it("mounts the full media player when the caller embeds the note", async () => {
const note = buildNote({ title: "V", type: "file" });
note.mime = "video/mp4";
- const { type, $renderedContent } = await getRenderedContent(note);
+ const { type } = await getRenderedContent(note, { mediaEnvironment: "embedded" });
expect(type).toBe("video");
- expect($renderedContent.find("video").length).toBe(1);
+ expect(mediaPreviewComponent).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: note, environment: "embedded" }), expect.anything());
+ });
+
+ it("renders the plain media element for callers that serialize to HTML (presentation, printing)", async () => {
+ const note = buildNote({ title: "V", type: "file" });
+ note.mime = "video/mp4";
+ const { $renderedContent } = await getRenderedContent(note, { mediaEnvironment: "native" });
+ expect(mediaPreviewComponent).not.toHaveBeenCalled();
+
+ const $video = $renderedContent.find("video");
+ expect($video.attr("src")).toBe(getUrlForDownload(`api/notes/${note.noteId}/open-partial`));
+ expect($video.attr("controls")).toBeDefined();
+
+ const audio = buildNote({ title: "A", type: "file" });
+ audio.mime = "audio/mpeg";
+ const rendered = await getRenderedContent(audio, { mediaEnvironment: "native" });
+ expect(rendered.$renderedContent.find("audio").attr("src")).toBe(getUrlForDownload(`api/notes/${audio.noteId}/open-partial`));
});
it("hides the open button for protected file notes", async () => {
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 80047a238f..a4e299a703 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -8,6 +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 { 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";
@@ -54,6 +55,14 @@ export interface RenderOptions {
* default and intentionally left off for lightweight previews such as tooltips and the note list.
*/
interactive?: boolean;
+ /**
+ * 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 full 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.
+ */
+ mediaEnvironment?: "preview" | "embedded" | "native";
}
const CODE_MIME_TYPES = new Set(["application/json"]);
@@ -304,20 +313,19 @@ async function renderFile(entity: FNote | FAttachment, type: string, $renderedCo
$content.append($viewer);
- } else if (type === "audio") {
- const $audioPreview = $("<audio controls></audio>")
- .attr("src", openService.getUrlForDownload(`api/${entityType}/${entityId}/open-partial`))
- .attr("type", entity.mime)
- .css("width", "100%");
+ } else if (type === "audio" || type === "video") {
+ const environment = options.mediaEnvironment ?? "preview";
- $content.append($audioPreview);
- } else if (type === "video") {
- const $videoPreview = $("<video controls></video>")
- .attr("src", openService.getUrlForDownload(`api/${entityType}/${entityId}/open-partial`))
- .attr("type", entity.mime)
- .css("width", "100%");
+ if (environment === "native") {
+ const $nativePreview = $(type === "audio" ? "<audio controls></audio>" : "<video controls></video>")
+ .attr("src", openService.getUrlForDownload(`api/${entityType}/${entityId}/open-partial`))
+ .attr("type", entity.mime)
+ .css("width", "100%");
- $content.append($videoPreview);
+ $content.append($nativePreview);
+ } else {
+ await renderMedia(entity, environment, $content);
+ }
}
if (entity instanceof FNote && options.showTextRepresentation) {
@@ -363,6 +371,22 @@ async function renderFile(entity: FNote | FAttachment, type: string, $renderedCo
$renderedContent.append($content);
}
+/**
+ * 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`
+ * 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>) {
+ const MediaPreview = (await import("../widgets/type_widgets/file/MediaPreview")).default;
+ const $container = $('<div class="rendered-media">');
+ const container = $container.get(0);
+ if (container) {
+ await mountInteractiveWidget(h(MediaPreview, { entity, environment }), container);
+ }
+ $content.append($container);
+}
+
async function renderMermaid(note: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>) {
const mermaid = (await import("mermaid")).default;
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index d4b7fd0d0e..79900ec82a 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1318,6 +1318,7 @@
},
"media": {
"play": "Play (Space)",
+ "activate": "Play {{- title}}",
"pause": "Pause (Space)",
"seek": "Seek (Left/Right arrow keys)",
"back-10s": "Back 10s (Left arrow key)",
diff --git a/apps/client/src/widgets/collections/legacy/ListPrintView.tsx b/apps/client/src/widgets/collections/legacy/ListPrintView.tsx
index c063a7c69e..17b5f87d13 100644
--- a/apps/client/src/widgets/collections/legacy/ListPrintView.tsx
+++ b/apps/client/src/widgets/collections/legacy/ListPrintView.tsx
@@ -34,7 +34,8 @@ export function ListPrintView({ note, noteIds: unfilteredNoteIds, onReady, onPro
trim: false,
noChildrenList: true,
// Printing preserves full include-note nesting (see expandNestedIncludes).
- expandNestedIncludes: true
+ expandNestedIncludes: true,
+ mediaEnvironment: "native"
});
const contentEl = content.$renderedContent[0];
diff --git a/apps/client/src/widgets/collections/presentation/model.ts b/apps/client/src/widgets/collections/presentation/model.ts
index 8bb8831651..eec5eb85b2 100644
--- a/apps/client/src/widgets/collections/presentation/model.ts
+++ b/apps/client/src/widgets/collections/presentation/model.ts
@@ -71,7 +71,8 @@ async function buildSlideModel(note: FNote): Promise<PresentationSlideBaseModel>
async function processContent(note: FNote): Promise<DangerouslySetInnerHTML> {
const { $renderedContent } = await contentRenderer.getRenderedContent(note, {
- noChildrenList: true
+ noChildrenList: true,
+ mediaEnvironment: "native"
});
return { __html: sanitizeNoteContentHtml($renderedContent.html()) };
}
diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsx
index dcb56f2905..d182632eca 100644
--- a/apps/client/src/widgets/type_widgets/Attachment.tsx
+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx
@@ -160,10 +160,18 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
const isZoomableImage = !!isFullDetail && attachment.role === "image";
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
+ * or discarding the content doesn't leak its Preact root — or leave its audio playing. */
+ function disposeContent() {
+ const wrapper = contentWrapper.current;
+ if (wrapper) content_renderer.disposeInteractiveContent($(wrapper));
+ }
+
function refresh() {
if (!isZoomableImage) {
content_renderer.getRenderedContent(attachment)
.then(({ $renderedContent }) => {
+ disposeContent();
contentWrapper.current?.replaceChildren(...$renderedContent);
});
}
@@ -176,7 +184,10 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
setScheduledForErasureSince(attachment.utcDateScheduledForErasureSince);
}
- useEffect(refresh, [ attachment, isZoomableImage ]);
+ useEffect(() => {
+ refresh();
+ return disposeContent;
+ }, [ attachment, isZoomableImage ]);
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
if (loadResults.getAttachmentRows().find(attachment => attachment.attachmentId)) {
refresh();
diff --git a/apps/client/src/widgets/type_widgets/File.tsx b/apps/client/src/widgets/type_widgets/File.tsx
index 94a3b9e84c..eba2ad6a1b 100644
--- a/apps/client/src/widgets/type_widgets/File.tsx
+++ b/apps/client/src/widgets/type_widgets/File.tsx
@@ -3,9 +3,8 @@ import "./File.css";
import { t } from "../../services/i18n";
import Alert from "../react/Alert";
import { useNoteBlob } from "../react/hooks";
-import AudioPreview from "./file/Audio";
+import MediaPreview from "./file/MediaPreview";
import PdfPreview from "./file/Pdf";
-import VideoPreview from "./file/Video";
import { TypeWidgetProps } from "./type_widget";
const TEXT_MAX_NUM_CHARS = 5000;
@@ -17,10 +16,8 @@ export default function FileTypeWidget({ note, parentComponent, noteContext, isV
return <TextPreview content={blob.content} />;
} 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} isVisible={isVisible} />;
- } else if (note.mime.startsWith("audio/")) {
- return <AudioPreview note={note} noteContext={noteContext} isVisible={isVisible} />;
+ } else if (note.mime.startsWith("video/") || note.mime.startsWith("audio/")) {
+ return <MediaPreview entity={note} environment="standalone" noteContext={noteContext} isVisible={isVisible} />;
}
return <NoPreview />;
diff --git a/apps/client/src/widgets/type_widgets/canvas/NoteEmbeddable.tsx b/apps/client/src/widgets/type_widgets/canvas/NoteEmbeddable.tsx
index 5898fbc615..3754661a8c 100644
--- a/apps/client/src/widgets/type_widgets/canvas/NoteEmbeddable.tsx
+++ b/apps/client/src/widgets/type_widgets/canvas/NoteEmbeddable.tsx
@@ -30,7 +30,7 @@ export default function NoteEmbeddable({ noteId }: { noteId: string }) {
return;
}
- const { $renderedContent } = await content_renderer.getRenderedContent(note, { interactive: true });
+ const { $renderedContent } = await content_renderer.getRenderedContent(note, { interactive: true, mediaEnvironment: "embedded" });
if (cancelled) {
// We were unmounted while rendering; tear down what was just mounted.
content_renderer.disposeInteractiveContent($renderedContent);
diff --git a/apps/client/src/widgets/type_widgets/file/Audio.tsx b/apps/client/src/widgets/type_widgets/file/Audio.tsx
index 4b6b918286..da098ec39d 100644
--- a/apps/client/src/widgets/type_widgets/file/Audio.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Audio.tsx
@@ -1,17 +1,15 @@
import { MutableRef, useCallback, useEffect, useRef, useState } from "preact/hooks";
-import type NoteContext from "../../../components/note_context";
-import FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
-import { getUrlForDownload } from "../../../services/open";
import Icon from "../../react/Icon";
import NoItems from "../../react/NoItems";
import { loadWaveform } from "./audio_waveform";
import { AudioVisualizer } from "./AudioVisualizer";
-import { MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";
+import { preloadFor } from "./media_environment";
+import { MediaPlayerProps, MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";
import { WaveformSeekBar } from "./WaveformSeekBar";
-export default function AudioPreview({ note, noteContext, isVisible = true }: { note: FNote, noteContext?: NoteContext, isVisible?: boolean }) {
+export default function AudioPreview({ source, environment, note, noteContext, isVisible = true, autoPlay }: MediaPlayerProps) {
const wrapperRef = useRef<HTMLDivElement>(null);
const audioRef = useRef<HTMLAudioElement>(null);
const [playing, setPlaying] = useState(false);
@@ -32,24 +30,25 @@ export default function AudioPreview({ note, noteContext, isVisible = true }: {
// The player instance is reused across notes (just a new src), which stops playback but doesn't
// reliably fire "pause" — reset so the controls don't keep showing the previous note's playing state.
setPlaying(false);
- }, [note.noteId]);
+ }, [source.id]);
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(!!audioRef.current && !audioRef.current.paused), []);
const { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, audioRef);
- const siblingNavigation = useMediaSessionController(note, noteContext, "audio/", audioRef, isVisible, playMode);
- const waveformPeaks = useWaveformPeaks(note.noteId);
+ const siblingNavigation = useMediaSessionController({ source, environment, note, noteContext, isVisible, autoPlay, mimePrefix: "audio/", mediaRef: audioRef, playMode });
+ const waveformPeaks = useWaveformPeaks(source.fullUrl);
if (error) {
- return <NoItems icon="bx bx-volume-mute" text={t("media.unsupported-format", { mime: note.mime.replace("/", "-") })} />;
+ return <NoItems icon="bx bx-volume-mute" text={t("media.unsupported-format", { mime: source.mime.replace("/", "-") })} />;
}
return (
- <div ref={wrapperRef} className="audio-preview-wrapper" onKeyDown={onKeyDown} tabIndex={0}>
+ <div ref={wrapperRef} className={`audio-preview-wrapper media-env-${environment}`} onKeyDown={onKeyDown} tabIndex={0}>
<audio
class="audio-preview"
- src={getUrlForDownload(`api/notes/${note.noteId}/open-partial`)}
+ src={source.streamUrl}
+ preload={preloadFor(environment)}
ref={audioRef}
onPlay={syncPlaying}
onPause={syncPlaying}
@@ -67,7 +66,8 @@ export default function AudioPreview({ note, noteContext, isVisible = true }: {
<div class="media-buttons-row">
<div className="left">
<PlaybackSpeed mediaRef={audioRef} />
- <PlayModeButton mode={playMode} onSelectMode={setPlayMode} />
+ {/* The play mode lives on the parent folder, which only the note detail knows. */}
+ {noteContext && <PlayModeButton mode={playMode} onSelectMode={setPlayMode} />}
</div>
<div className="center">
@@ -88,22 +88,22 @@ export default function AudioPreview({ note, noteContext, isVisible = true }: {
);
}
-/** Decode the note's audio into a normalized waveform for the seek bar. Returns `null` while loading or when no
+/** Decode the audio into a normalized waveform for the seek bar. Returns `null` while loading or when no
* waveform is available (oversized/undecodable file); the seek bar then falls back to a plain track. The fetch
- * is aborted when the note changes so a slow decode for a previous note can't paint over the current one. */
-function useWaveformPeaks(noteId: string): number[] | null {
+ * is aborted when the media changes so a slow decode for a previous one can't paint over the current one. */
+function useWaveformPeaks(fullUrl: string): number[] | null {
const [peaks, setPeaks] = useState<number[] | null>(null);
useEffect(() => {
setPeaks(null);
const controller = new AbortController();
- loadWaveform(getUrlForDownload(`api/notes/${noteId}/open`), { signal: controller.signal })
+ loadWaveform(fullUrl, { signal: controller.signal })
.then((waveform) => {
if (!controller.signal.aborted) setPeaks(waveform?.peaks ?? null);
})
.catch(() => {});
return () => controller.abort();
- }, [ noteId ]);
+ }, [ fullUrl ]);
return peaks;
}
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
index 88b0edee34..63dd511cad 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
@@ -16,10 +16,28 @@ import { 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 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";
const NO_KEYS: readonly string[] = [];
+/** What {@link AudioPreview} and {@link VideoPreview} are given, whichever environment they render in. */
+export interface MediaPlayerProps {
+ 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.
+ */
+ note?: FNote;
+ noteContext?: NoteContext;
+ isVisible?: boolean;
+ /** Start playing as soon as the media is ready — the user just activated a lazy preview. */
+ autoPlay?: boolean;
+}
+
export function SeekBar({ mediaRef }: { mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement> }) {
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
@@ -184,7 +202,11 @@ 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(note: FNote, noteContext: NoteContext | undefined, mimePrefix: string, mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>, isVisible: boolean, playMode: MediaPlayMode) {
+export function useMediaSessionController({ source, note, noteContext, mimePrefix, mediaRef, isVisible = true, playMode, autoPlay }: MediaPlayerProps & {
+ mimePrefix: string;
+ mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>;
+ playMode: MediaPlayMode;
+}) {
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;
@@ -287,18 +309,18 @@ export function useMediaSessionController(note: FNote, noteContext: NoteContext
mediaSessionOwner = self;
// Metadata makes Chromium reliably present the OS controls for video (it does so for audio by
// default) and shows the note title there.
- if (typeof MediaMetadata !== "undefined") mediaSession.metadata = new MediaMetadata({ title: note.title });
+ 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, note.noteId)) wrappedRef.current?.navigatePrevious(); } : null);
- setHandler("nexttrack", hasMediaNav ? () => { if (isCurrentContextNote(noteContext, note.noteId)) wrappedRef.current?.navigateNext(); } : null);
+ setHandler("previoustrack", hasMediaNav ? () => { if (isCurrentContextNote(noteContext, source.id)) wrappedRef.current?.navigatePrevious(); } : null);
+ setHandler("nexttrack", hasMediaNav ? () => { if (isCurrentContextNote(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));
setHandler("seekto", (details) => { if (details.seekTime != null) seekTo(mediaRef, details.seekTime); });
setHandler("stop", () => stopMedia(mediaRef));
return release;
- }, [ ownsSession, hasMediaNav, noteContext, note.noteId, note.title, mediaRef, self ]);
+ }, [ ownsSession, hasMediaNav, noteContext, source.id, source.title, mediaRef, self ]);
// Keep the OS Media Session's playback and position state in sync while we own it. Android Chrome relies on
// these to treat the page as actively playing media: it keeps the notification controls present and makes
@@ -355,10 +377,13 @@ export function useMediaSessionController(note: FNote, noteContext: NoteContext
};
}, [ ownsSession, mediaRef, self ]);
- // Auto-play the freshly-opened sibling once it can play (only when reached via navigation).
+ // 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(() => {
- if (autoPlayTargetNoteId !== note.noteId) return;
- autoPlayTargetNoteId = null;
+ const jumpedTo = autoPlayTargetNoteId === source.id;
+ if (jumpedTo) autoPlayTargetNoteId = null;
+ if (!jumpedTo && !autoPlay) return;
+
const media = mediaRef.current;
if (!media) return;
const play = () => { media.play().catch(() => {}); };
@@ -368,7 +393,7 @@ export function useMediaSessionController(note: FNote, noteContext: NoteContext
media.addEventListener("canplay", play, { once: true });
return () => media.removeEventListener("canplay", play);
}
- }, [ note.noteId, mediaRef ]);
+ }, [ source.id, autoPlay, mediaRef ]);
return wrapped;
}
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx b/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx
new file mode 100644
index 0000000000..82bcd9ab82
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx
@@ -0,0 +1,110 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// The audio player's extras reach for the network and the Web Audio API, neither of which exists here —
+// and neither is what these tests are about (they're covered by audio_waveform.spec / audio_visualizer.spec).
+vi.mock("./audio_waveform", () => ({ loadWaveform: vi.fn(async () => null) }));
+vi.mock("./AudioVisualizer", () => ({ AudioVisualizer: () => null }));
+
+import type FAttachment from "../../../entities/fattachment";
+import type FNote from "../../../entities/fnote";
+import MediaPreview from "./MediaPreview";
+
+const videoNote = { noteId: "vid1", title: "Holiday", mime: "video/mp4" } as FNote;
+const audioNote = { noteId: "snd1", title: "Podcast", mime: "audio/mpeg" } as FNote;
+const audioAttachment = { attachmentId: "att1", title: "Recording", mime: "audio/mpeg" } as FAttachment;
+
+describe("MediaPreview", () => {
+ let container: HTMLElement;
+ let play: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ // happy-dom doesn't implement playback; the player calls play() when a preview is activated.
+ play = vi.fn(async () => {});
+ HTMLMediaElement.prototype.play = play as unknown as HTMLMediaElement["play"];
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ const mediaElement = () => container.querySelector("video, audio") as HTMLMediaElement | null;
+ const proxyPlayButton = () => container.querySelector(".media-proxy .media-proxy-play") as HTMLElement | null;
+
+ describe("preview (lazy)", () => {
+ it("shows the placeholder and creates no media element, so nothing is streamed", async () => {
+ await act(async () => render(<MediaPreview entity={videoNote} environment="preview" />, container));
+
+ expect(container.querySelector(".media-proxy")).not.toBeNull();
+ expect(proxyPlayButton()).not.toBeNull();
+ // The whole point: no <video>/<audio> exists, so the server is never asked for the media.
+ expect(mediaElement()).toBeNull();
+ expect(play).not.toHaveBeenCalled();
+ });
+
+ it("mounts the player on the media itself, and starts playing, once the user presses play", async () => {
+ await act(async () => render(<MediaPreview entity={videoNote} environment="preview" />, container));
+ await act(async () => proxyPlayButton()?.click());
+
+ expect(container.querySelector(".media-proxy")).toBeNull();
+ const media = mediaElement();
+ expect(media?.tagName).toBe("VIDEO");
+ expect(media?.getAttribute("src")).toBe("api/notes/vid1/open-partial");
+
+ // The media is only just being fetched, so playback waits for it to become playable.
+ expect(play).not.toHaveBeenCalled();
+ await act(async () => { media?.dispatchEvent(new Event("canplay")); });
+ expect(play).toHaveBeenCalled();
+ });
+
+ it("plays an attachment through the same placeholder", async () => {
+ await act(async () => render(<MediaPreview entity={audioAttachment} environment="preview" />, container));
+ expect(mediaElement()).toBeNull();
+
+ await act(async () => proxyPlayButton()?.click());
+
+ const media = mediaElement();
+ expect(media?.tagName).toBe("AUDIO");
+ expect(media?.getAttribute("src")).toBe("api/attachments/att1/open-partial");
+ });
+ });
+
+ describe("eager environments", () => {
+ it("mounts an embedded player straight away, without auto-playing it", async () => {
+ await act(async () => render(<MediaPreview entity={videoNote} environment="embedded" />, container));
+
+ expect(container.querySelector(".media-proxy")).toBeNull();
+ const media = mediaElement();
+ expect(media?.getAttribute("src")).toBe("api/notes/vid1/open-partial");
+ // Embedded is "ready to play", not "playing".
+ expect(media?.getAttribute("preload")).toBe("metadata");
+ expect(play).not.toHaveBeenCalled();
+ });
+
+ it("mounts the standalone player, which may buffer ahead in full", async () => {
+ await act(async () => render(<MediaPreview entity={audioNote} environment="standalone" />, container));
+
+ const media = mediaElement();
+ expect(media?.tagName).toBe("AUDIO");
+ expect(media?.getAttribute("preload")).toBe("auto");
+ expect(play).not.toHaveBeenCalled();
+ });
+ });
+
+ it("picks the player from the mime type and tags the wrapper with its environment", async () => {
+ await act(async () => render(<MediaPreview entity={videoNote} environment="embedded" />, container));
+ expect(container.querySelector(".video-preview-wrapper.media-env-embedded")).not.toBeNull();
+
+ await act(async () => render(<MediaPreview entity={audioNote} environment="standalone" />, container));
+ expect(container.querySelector(".audio-preview-wrapper.media-env-standalone")).not.toBeNull();
+ });
+
+ it("hides the folder play mode outside the note detail, where there is no folder to set it on", async () => {
+ await act(async () => render(<MediaPreview entity={videoNote} environment="embedded" />, container));
+ expect(container.querySelector(".play-mode-dropdown")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx b/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx
new file mode 100644
index 0000000000..2a6bd88044
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/MediaPreview.tsx
@@ -0,0 +1,49 @@
+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 AudioPreview from "./Audio";
+import { loadsEagerly, type MediaEnvironment } from "./media_environment";
+import { getMediaSource } from "./media_source";
+import MediaProxy from "./MediaProxy";
+import VideoPreview from "./Video";
+
+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. */
+ noteContext?: NoteContext;
+ isVisible?: boolean;
+}
+
+/**
+ * The single entry point for rendering audio and video, in every environment. In a lazy one (a `preview`,
+ * i.e. a collection tile or an attachment list) the player is replaced by a {@link MediaProxy} placeholder
+ * 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) {
+ const eager = loadsEagerly(environment);
+ const [ activated, setActivated ] = useState(eager);
+ const source = getMediaSource(entity);
+
+ if (!activated) {
+ return <MediaProxy source={source} onActivate={() => setActivated(true)} />;
+ }
+
+ const props = {
+ 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.
+ autoPlay: !eager
+ };
+
+ return source.mime.startsWith("video/")
+ ? <VideoPreview {...props} />
+ : <AudioPreview {...props} />;
+}
diff --git a/apps/client/src/widgets/type_widgets/file/MediaProxy.css b/apps/client/src/widgets/type_widgets/file/MediaProxy.css
new file mode 100644
index 0000000000..3465b4c55e
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/MediaProxy.css
@@ -0,0 +1,28 @@
+.media-proxy {
+ --media-proxy-icon-size: 4rem;
+
+ position: relative;
+ width: 100%;
+ height: 100%;
+ min-height: 8rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background-color: var(--accented-background-color);
+ border-radius: 0.5em;
+ overflow: hidden;
+
+ .media-proxy-icon {
+ position: absolute;
+ font-size: var(--media-proxy-icon-size);
+ opacity: 0.15;
+ }
+
+ .media-proxy-play {
+ --icon-button-size: 56px;
+ position: relative;
+ background-color: var(--main-background-color);
+ border-radius: 50%;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/file/MediaProxy.tsx b/apps/client/src/widgets/type_widgets/file/MediaProxy.tsx
new file mode 100644
index 0000000000..e4b0039cbb
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/MediaProxy.tsx
@@ -0,0 +1,27 @@
+import "./MediaProxy.css";
+
+import { t } from "../../../services/i18n";
+import ActionButton from "../../react/ActionButton";
+import Icon from "../../react/Icon";
+import type { MediaSource } from "./media_source";
+
+/**
+ * Stands in for the player in a lazy preview: a play button over the media's icon. No media element exists
+ * until it is clicked, which is the point — a collection of media notes would otherwise have every one of
+ * them streaming from the server at once, just to show a tile.
+ */
+export default function MediaProxy({ source, onActivate }: { source: MediaSource, onActivate: () => void }) {
+ const isVideo = source.mime.startsWith("video/");
+
+ return (
+ <div className="media-proxy">
+ <Icon icon={isVideo ? "bx bx-movie-play" : "bx bx-music"} className="media-proxy-icon" />
+ <ActionButton
+ className="media-proxy-play"
+ icon="bx bx-play"
+ text={t("media.activate", { title: source.title })}
+ onClick={onActivate}
+ />
+ </div>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/file/Video.css b/apps/client/src/widgets/type_widgets/file/Video.css
index 4b46b1059d..1a486fd2d7 100644
--- a/apps/client/src/widgets/type_widgets/file/Video.css
+++ b/apps/client/src/widgets/type_widgets/file/Video.css
@@ -1,4 +1,6 @@
-.note-detail-file > .video-preview-wrapper {
+/* Not scoped to the note detail: the same player is also mounted into rendered content (collection
+ previews, included notes) by the content renderer. */
+.video-preview-wrapper {
width: 100%;
height: 100%;
position: relative;
diff --git a/apps/client/src/widgets/type_widgets/file/Video.tsx b/apps/client/src/widgets/type_widgets/file/Video.tsx
index 334e72e563..06b3c534c3 100644
--- a/apps/client/src/widgets/type_widgets/file/Video.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Video.tsx
@@ -3,17 +3,15 @@ import "./Video.css";
import { RefObject } from "preact";
import { MutableRef, useCallback, useEffect, useRef, useState } from "preact/hooks";
-import type NoteContext from "../../../components/note_context";
-import FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
-import { getUrlForDownload } from "../../../services/open";
import ActionButton from "../../react/ActionButton";
import NoItems from "../../react/NoItems";
-import { MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SeekBar, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";
+import { preloadFor } 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({ note, noteContext, isVisible = true }: { note: FNote, noteContext?: NoteContext, isVisible?: boolean }) {
+export default function VideoPreview({ source, environment, note, noteContext, isVisible = true, autoPlay }: MediaPlayerProps) {
const wrapperRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const [playing, setPlaying] = useState(false);
@@ -25,7 +23,7 @@ export default function VideoPreview({ note, noteContext, isVisible = true }: {
// The player instance is reused across notes (just a new src), which stops playback but doesn't
// reliably fire "pause" — reset so the controls don't keep showing the previous note's playing state.
setPlaying(false);
- }, [note.noteId]);
+ }, [source.id]);
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.
@@ -65,19 +63,20 @@ export default function VideoPreview({ note, noteContext, isVisible = true }: {
const onKeyDown = useKeyboardShortcuts(videoRef, wrapperRef, togglePlayback, flashControls);
const { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, videoRef);
- const siblingNavigation = useMediaSessionController(note, noteContext, "video/", videoRef, isVisible, playMode);
+ const siblingNavigation = useMediaSessionController({ source, environment, note, noteContext, isVisible, autoPlay, mimePrefix: "video/", mediaRef: videoRef, playMode });
if (error) {
- return <NoItems icon="bx bx-video-off" text={t("media.unsupported-format", { mime: note.mime.replace("/", "-") })} />;
+ return <NoItems icon="bx bx-video-off" text={t("media.unsupported-format", { mime: source.mime.replace("/", "-") })} />;
}
return (
- <div ref={wrapperRef} className={`video-preview-wrapper ${controlsVisible ? "" : "controls-hidden"}`} tabIndex={0} onClick={onVideoClick} onKeyDown={onKeyDown} onPointerDown={onPointerDown} onPointerMove={onPointerMove}>
+ <div ref={wrapperRef} className={`video-preview-wrapper media-env-${environment} ${controlsVisible ? "" : "controls-hidden"}`} tabIndex={0} onClick={onVideoClick} onKeyDown={onKeyDown} onPointerDown={onPointerDown} onPointerMove={onPointerMove}>
<video
ref={videoRef}
class="video-preview"
- src={getUrlForDownload(`api/notes/${note.noteId}/open-partial`)}
- datatype={note?.mime}
+ src={source.streamUrl}
+ preload={preloadFor(environment)}
+ datatype={source.mime}
onPlay={syncPlaying}
onPause={syncPlaying}
onEnded={syncPlaying}
@@ -90,7 +89,8 @@ export default function VideoPreview({ note, noteContext, isVisible = true }: {
<div class="media-buttons-row">
<div className="left">
<PlaybackSpeed mediaRef={videoRef} />
- <PlayModeButton mode={playMode} onSelectMode={setPlayMode} />
+ {/* The play mode lives on the parent folder, which only the note detail knows. */}
+ {noteContext && <PlayModeButton mode={playMode} onSelectMode={setPlayMode} />}
<RotateButton videoRef={videoRef} />
</div>
<div className="center">
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
new file mode 100644
index 0000000000..61c6403591
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/media_environment.spec.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+
+import { loadsEagerly, preloadFor } 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", () => {
+ expect(loadsEagerly("preview")).toBe(false);
+ expect(loadsEagerly("embedded")).toBe(true);
+ expect(loadsEagerly("standalone")).toBe(true);
+ });
+
+ it("only the note detail buffers ahead in full", () => {
+ expect(preloadFor("standalone")).toBe("auto");
+ expect(preloadFor("embedded")).toBe("metadata");
+ expect(preloadFor("preview")).toBe("metadata");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/file/media_environment.ts b/apps/client/src/widgets/type_widgets/file/media_environment.ts
new file mode 100644
index 0000000000..250e458795
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/media_environment.ts
@@ -0,0 +1,20 @@
+/**
+ * Where a media player is being rendered. The note detail is `standalone`; a note included in a text note
+ * or embedded in a canvas is `embedded`; a lightweight preview such as a collection tile or an attachment
+ * list is `preview`.
+ */
+export type MediaEnvironment = "standalone" | "embedded" | "preview";
+
+/**
+ * Whether the player is mounted right away, or only once the user clicks the placeholder's play button.
+ * A preview is lazy: many of them are on screen at once, and each media element that exists starts
+ * streaming from the server, so none is created until the user actually asks for it.
+ */
+export function loadsEagerly(environment: MediaEnvironment): boolean {
+ return environment !== "preview";
+}
+
+/** How much a mounted player may buffer ahead: only the note detail is worth pre-loading in full. */
+export function preloadFor(environment: MediaEnvironment): "auto" | "metadata" {
+ return environment === "standalone" ? "auto" : "metadata";
+}
diff --git a/apps/client/src/widgets/type_widgets/file/media_source.spec.ts b/apps/client/src/widgets/type_widgets/file/media_source.spec.ts
new file mode 100644
index 0000000000..f4207b2aba
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/media_source.spec.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+
+import type FAttachment from "../../../entities/fattachment";
+import type FNote from "../../../entities/fnote";
+import { getMediaSource } from "./media_source";
+
+const note = { noteId: "vid1", title: "Holiday", mime: "video/mp4" } as FNote;
+const attachment = { attachmentId: "att1", title: "Recording", mime: "audio/mpeg" } as FAttachment;
+
+describe("getMediaSource", () => {
+ it("resolves a note to its streaming and whole-file endpoints", () => {
+ expect(getMediaSource(note)).toEqual({
+ id: "vid1",
+ title: "Holiday",
+ mime: "video/mp4",
+ streamUrl: "api/notes/vid1/open-partial",
+ fullUrl: "api/notes/vid1/open"
+ });
+ });
+
+ it("resolves an attachment to the attachment endpoints", () => {
+ expect(getMediaSource(attachment)).toEqual({
+ id: "att1",
+ title: "Recording",
+ mime: "audio/mpeg",
+ streamUrl: "api/attachments/att1/open-partial",
+ fullUrl: "api/attachments/att1/open"
+ });
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/file/media_source.ts b/apps/client/src/widgets/type_widgets/file/media_source.ts
new file mode 100644
index 0000000000..293bc9c483
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/media_source.ts
@@ -0,0 +1,28 @@
+import type FAttachment from "../../../entities/fattachment";
+import type FNote from "../../../entities/fnote";
+import { getUrlForDownload } from "../../../services/open";
+
+/** The media a player plays, resolved from either a file note or an attachment. */
+export interface MediaSource {
+ /** Identifies the media across every mounted player (a noteId or an attachmentId). */
+ id: string;
+ title: string;
+ mime: string;
+ /** Range-request endpoint the media element streams from. */
+ streamUrl: string;
+ /** Whole-file endpoint, used to decode the audio waveform. */
+ fullUrl: string;
+}
+
+export function getMediaSource(entity: FNote | FAttachment): MediaSource {
+ const isNote = "noteId" in entity;
+ const path = isNote ? `api/notes/${entity.noteId}` : `api/attachments/${entity.attachmentId}`;
+
+ return {
+ id: isNote ? entity.noteId : entity.attachmentId,
+ title: entity.title,
+ mime: entity.mime,
+ streamUrl: getUrlForDownload(`${path}/open-partial`),
+ fullUrl: getUrlForDownload(`${path}/open`)
+ };
+}
diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.ts
index 5a0faf4889..5c4deca8be 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts
@@ -60,7 +60,7 @@ describe("loadIncludedNote", () => {
expect($el.children(".include-note-title-row").length).toBe(1);
expect($el.find("button.include-note-toggle").length).toBe(1);
// The included note is rendered with its own includes reduced to reference links.
- expect(content_renderer.getRenderedContent).toHaveBeenCalledWith(note, { interactive: true, includesAsReferenceLinks: true });
+ expect(content_renderer.getRenderedContent).toHaveBeenCalledWith(note, { interactive: true, includesAsReferenceLinks: true, mediaEnvironment: "embedded" });
});
it("disposes interactive content of a previous render before replacing it", async () => {
diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.ts
index 9b423985c6..df0334feaf 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.ts
@@ -36,7 +36,7 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,
// The include widget itself is the first level of inclusion, so the included note's own
// includes are rendered as reference links rather than expanded (see includesAsReferenceLinks).
- const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true, includesAsReferenceLinks: true });
+ const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true, includesAsReferenceLinks: true, mediaEnvironment: "embedded" });
const $content = $(`<div class="include-note-content type-${type}" style="display: none;">`).append($renderedContent);
$wrapper.append($content);
@@ -54,7 +54,7 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,
// The include widget itself is the first level of inclusion, so the included note's own
// includes are rendered as reference links rather than expanded (see includesAsReferenceLinks).
- const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true, includesAsReferenceLinks: true });
+ const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true, includesAsReferenceLinks: true, mediaEnvironment: "embedded" });
$wrapper.append($(`<div class="include-note-content type-${type}">`).append($renderedContent));
}