Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/media player/preview-embed renderer: use a dedicated layout for the audio player (compact layout)
Adorian Dorane9ffba0779ce
diff --git a/apps/client/src/services/content_renderer.css b/apps/client/src/services/content_renderer.cssindex c965895a0b..50749e6b10 100644--- a/apps/client/src/services/content_renderer.css+++ b/apps/client/src/services/content_renderer.css@@ -31,6 +31,12 @@min-height: 120px;}+/* A media player fills the height its host provides — a dashboard tile is resized freely, so the player has+ to follow it. In a content-sized host (a list row) this resolves to auto, leaving the floor below to apply. */+.rendered-content:has(.rendered-media) {+ height: 100%;+}+/* 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 {diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 2e80f7a10c..68aab4c33c 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1341,6 +1341,17 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-theight: 10em;}+/* The small box has room for the compact audio player's visualizer band (which carries a floor of its own) or+ for its controls row and the file footer below it — not for all three. Drop the band, and release the floor+ so the box shrinks to what is left instead of overflowing onto the Download / Open buttons. */+.include-note[data-box-size="small"] .include-note-content.type-audio .audio-preview-visualization-wrapper {+ display: none;+}++.include-note[data-box-size="small"] .include-note-content.type-audio .rendered-media {+ min-height: 0;+}+.include-note[data-box-size="medium"] .include-note-content {max-height: 20em;overflow: auto;diff --git a/apps/client/src/widgets/collections/dashboard/index.css b/apps/client/src/widgets/collections/dashboard/index.cssindex b217954bfa..43a1c43b9f 100644--- a/apps/client/src/widgets/collections/dashboard/index.css+++ b/apps/client/src/widgets/collections/dashboard/index.css@@ -101,6 +101,7 @@&.type-image,&.type-pdf,&.type-canvas,+ &.type-audio,&.type-video,&.type-code,&.type-mindMap,diff --git a/apps/client/src/widgets/type_widgets/file/Audio.tsx b/apps/client/src/widgets/type_widgets/file/Audio.tsxindex 26f5a35758..5ad8eb8295 100644--- a/apps/client/src/widgets/type_widgets/file/Audio.tsx+++ b/apps/client/src/widgets/type_widgets/file/Audio.tsx@@ -5,7 +5,7 @@ import Icon from "../../react/Icon";import NoItems from "../../react/NoItems";import { loadWaveform } from "./audio_waveform";import { AudioVisualizer } from "./AudioVisualizer";-import { playerRootClasses, preloadFor } from "./media_environment";+import { playerRootClasses, preloadFor, usesCompactControls } from "./media_environment";import { MediaPlayerProps, MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";import { WaveformSeekBar } from "./WaveformSeekBar";@@ -43,6 +43,8 @@ export default function AudioPreview({ source, environment, note, noteContext, ireturn <NoItems icon="bx bx-volume-mute" text={t("media.unsupported-format", { mime: source.mime.replace("/", "-") })} />;}+ const compact = usesCompactControls(environment);+return (<div ref={wrapperRef} className={`audio-preview-wrapper ${playerRootClasses(environment)}`} onKeyDown={onKeyDown} tabIndex={0}><audio@@ -57,32 +59,43 @@ export default function AudioPreview({ source, environment, note, noteContext, ionError={onError}/><div className="audio-preview-visualization-wrapper">- <AudioVisualizer mediaRef={audioRef} isPlaying={playing} />- <Icon icon="bx bx-music" className="audio-preview-icon" />+ <AudioVisualizer mediaRef={audioRef} isPlaying={playing} compact={compact} />+ {/* The compact player gives the whole band to the visualizer instead. */}+ {!compact && <Icon icon="bx bx-music" className="audio-preview-icon" />}</div><div className="media-preview-controls">- <WaveformSeekBar mediaRef={audioRef} peaks={waveformPeaks} />-- <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. */}- {noteContext && <PlayModeButton mode={playMode} onSelectMode={setPlayMode} />}- </div>-- <div className="center">- <div className="spacer" />- <MediaSiblingButton navigation={siblingNavigation} direction="previous" tooltipI18nKey="media.previous-audio" />- <SkipButton mediaRef={audioRef} seconds={-10} icon="bx bx-rewind" text={t("media.back-10s")} />+ {compact ? (+ <div class="media-compact-row"><PlayPauseButton playing={playing} togglePlayback={togglePlayback} />- <SkipButton mediaRef={audioRef} seconds={10} icon="bx bx-fast-forward" text={t("media.forward-10s")} />- <MediaSiblingButton navigation={siblingNavigation} direction="next" tooltipI18nKey="media.next-audio" />- </div>-- <div className="right">+ <WaveformSeekBar mediaRef={audioRef} peaks={waveformPeaks} /><VolumeControl mediaRef={audioRef} /></div>- </div>+ ) : (+ <>+ <WaveformSeekBar mediaRef={audioRef} peaks={waveformPeaks} />++ <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. */}+ {noteContext && <PlayModeButton mode={playMode} onSelectMode={setPlayMode} />}+ </div>++ <div className="center">+ <div className="spacer" />+ <MediaSiblingButton navigation={siblingNavigation} direction="previous" tooltipI18nKey="media.previous-audio" />+ <SkipButton mediaRef={audioRef} seconds={-10} icon="bx bx-rewind" text={t("media.back-10s")} />+ <PlayPauseButton playing={playing} togglePlayback={togglePlayback} />+ <SkipButton mediaRef={audioRef} seconds={10} icon="bx bx-fast-forward" text={t("media.forward-10s")} />+ <MediaSiblingButton navigation={siblingNavigation} direction="next" tooltipI18nKey="media.next-audio" />+ </div>++ <div className="right">+ <VolumeControl mediaRef={audioRef} />+ </div>+ </div>+ </>+ )}</div></div>);diff --git a/apps/client/src/widgets/type_widgets/file/AudioVisualizer.tsx b/apps/client/src/widgets/type_widgets/file/AudioVisualizer.tsxindex 90c48965cd..3d46d156a4 100644--- a/apps/client/src/widgets/type_widgets/file/AudioVisualizer.tsx+++ b/apps/client/src/widgets/type_widgets/file/AudioVisualizer.tsx@@ -11,6 +11,8 @@ import { useAudioAnalyser } from "./useAudioAnalyser";/** Cell geometry, in CSS pixels. The grid fits as many of these as the canvas allows. */const CELL_SIZE = 8;const CELL_GAP = 2;+/** The compact player's band is short, so it halves the cells to keep a comparable number of rows. */+const COMPACT_SCALE = 0.5;/** Slice of the spectrum spread across the bars — broad (not voice-specific). The very top bins are usually* silent, so the top quarter is dropped to keep the bars lively. */const LO_FRACTION = 0;@@ -27,7 +29,9 @@ const DEFAULT_HIGH_COLOR = "rgb(136, 136, 136)";* lights up from the bottom and each cell takes a single colour from a low→high vertical gradient. Runs an rAF* loop only while playing (and briefly after, to animate the decay); when not playing every column rests at zero.*/-export function AudioVisualizer({ mediaRef, isPlaying }: { mediaRef: RefObject<HTMLAudioElement>; isPlaying: boolean }) {+export function AudioVisualizer({ mediaRef, isPlaying, compact }: { mediaRef: RefObject<HTMLAudioElement>; isPlaying: boolean; compact?: boolean }) {+ const cellSize = compact ? CELL_SIZE * COMPACT_SCALE : CELL_SIZE;+ const cellGap = compact ? CELL_GAP * COMPACT_SCALE : CELL_GAP;const canvasRef = useRef<HTMLCanvasElement>(null);const getFrequencyData = useAudioAnalyser(mediaRef);const [ size, setSize ] = useState({ width: 0, height: 0 });@@ -84,7 +88,7 @@ export function AudioVisualizer({ mediaRef, isPlaying }: { mediaRef: RefObject<H}ctx.setTransform(dpr, 0, 0, dpr, 0, 0);- const grid = computeGrid(width, height, CELL_SIZE, CELL_GAP);+ const grid = computeGrid(width, height, cellSize, cellGap);// Keep the per-column buffers sized to the grid, preserving values across resizes to avoid a jump.if (displayRef.current.length !== grid.cols) {displayRef.current = resizePreserving(displayRef.current, grid.cols);@@ -105,11 +109,11 @@ export function AudioVisualizer({ mediaRef, isPlaying }: { mediaRef: RefObject<Hconst targets = spectrum ? computeColumnAmplitudes(spectrum, targetRef.current, LO_FRACTION, HI_FRACTION) : null;smoothAmplitudes(displayRef.current, targets, RISE, FALL);- drawGrid(ctx, width, height, grid, displayRef.current, rowColorsRef.current.colors);+ drawGrid(ctx, width, height, grid, displayRef.current, rowColorsRef.current.colors, cellSize, cellGap);// Keep animating while playing, or while bars are still settling toward zero after a pause.rafRef.current = isPlayingRef.current || hasMotion(displayRef.current) ? requestAnimationFrame(renderFrame) : 0;- }, [ getFrequencyData ]);+ }, [ getFrequencyData, cellSize, cellGap ]);// Start the loop when playback starts; it self-terminates once paused and fully decayed.useEffect(() => {@@ -135,20 +139,20 @@ export function AudioVisualizer({ mediaRef, isPlaying }: { mediaRef: RefObject<Hreturn <canvas ref={canvasRef} class="audio-visualizer-canvas" aria-hidden="true" />;}-function drawGrid(ctx: CanvasRenderingContext2D, width: number, height: number, grid: VisualizerGrid, amplitudes: Float32Array, rowColors: string[]) {+function drawGrid(ctx: CanvasRenderingContext2D, width: number, height: number, grid: VisualizerGrid, amplitudes: Float32Array, rowColors: string[], cellSize: number, cellGap: number) {ctx.clearRect(0, 0, width, height);const { cols, rows, offsetX } = grid;- const stride = CELL_SIZE + CELL_GAP;+ const stride = cellSize + cellGap;// Iterate row-by-row so the (per-row) fill colour is set once rather than per cell; each cell's alpha is its// intensity, fading the leading cell between off and on.for (let r = 0; r < rows; r++) {ctx.fillStyle = rowColors[r];- const y = height - CELL_SIZE - r * stride;+ const y = height - cellSize - r * stride;for (let c = 0; c < cols; c++) {const intensity = cellIntensity(amplitudes[c], rows, r);if (intensity <= 0) continue;ctx.globalAlpha = intensity;- ctx.fillRect(offsetX + c * stride, y, CELL_SIZE, CELL_SIZE);+ ctx.fillRect(offsetX + c * stride, y, cellSize, cellSize);}}ctx.globalAlpha = 1;diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.css b/apps/client/src/widgets/type_widgets/file/MediaPlayer.cssindex 7840b3d5ec..8324e5cb70 100644--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.css+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.css@@ -100,3 +100,49 @@display: flex;flex-direction: column;}++/* The compact audio player, worn everywhere but the note detail: a full-height visualizer band above a single+ play / seek / volume row. A collection tile or an included note has no room for the speed, skip and+ play-mode controls. */+.audio-preview-wrapper.media-compact {+ .audio-preview-visualization-wrapper {+ /* The icon this player drops was the band's only in-flow child (the canvas is absolutely positioned),+ so without a floor the band collapses to nothing wherever the host is content-sized — a list-view+ row, as opposed to a fixed-height grid card. It still grows to fill a taller host. */+ min-height: 8rem;+ }++ .audio-visualizer-canvas {+ /* No icon to sit behind, so the grid takes the whole band rather than its bottom half, inset by 12px+ from the top and sides. The canvas is absolutely positioned, so padding on the wrapper wouldn't move+ it — and its size has to be stated outright: it is a replaced element, for which `auto` means "use+ the intrinsic size" rather than "stretch between the offsets". It stays anchored to the bottom+ (`bottom: 0`), where the bars grow from. */+ left: 12px;+ width: calc(100% - 24px);+ height: calc(100% - 12px);+ }++ .media-preview-controls {+ padding: 0.5em;+ }++ .media-compact-row {+ display: flex;+ align-items: center;+ gap: 0.5em;++ .play-button {+ --icon-button-size: 36px;+ }++ .media-seekbar-row {+ flex: 1;+ min-width: 0;+ }++ .waveform-canvas {+ height: 28px;+ }+ }+}diff --git a/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx b/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsxindex b23e1d882d..bc5a8dbcd8 100644--- a/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx+++ b/apps/client/src/widgets/type_widgets/file/MediaPreview.spec.tsx@@ -4,8 +4,10 @@ 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).+// Hoisted: Audio.tsx imports the visualizer statically, so the factory runs before this module's body.+const { audioVisualizer } = vi.hoisted(() => ({ audioVisualizer: vi.fn((_props: { compact?: boolean }) => null) }));vi.mock("./audio_waveform", () => ({ loadWaveform: vi.fn(async () => null) }));-vi.mock("./AudioVisualizer", () => ({ AudioVisualizer: () => null }));+vi.mock("./AudioVisualizer", () => ({ AudioVisualizer: audioVisualizer }));import type FAttachment from "../../../entities/fattachment";import type FNote from "../../../entities/fnote";@@ -108,6 +110,51 @@ describe("MediaPreview", () => {expect(container.querySelector(".play-mode-dropdown")).toBeNull();});+ describe("compact audio chrome", () => {+ /** The compact chrome is worn everywhere but the note detail — an activated preview and an embed alike. */+ const renderCompactAudio = async (environment: "preview" | "embedded") => {+ await act(async () => render(<MediaPreview entity={audioNote} environment={environment} />, container));+ if (environment === "preview") {+ await act(async () => proxyPlayButton()?.click());+ }+ };++ it.each([ "preview", "embedded" ] as const)("lays %s out as a single play / seek / volume row", async (environment) => {+ await renderCompactAudio(environment);++ expect(container.querySelector(".audio-preview-wrapper.media-compact")).not.toBeNull();+ const row = container.querySelector(".media-compact-row");+ expect(row).not.toBeNull();+ expect(row?.querySelector(".play-button")).not.toBeNull();+ expect(row?.querySelector(".waveform-seekbar")).not.toBeNull();+ expect(row?.querySelector(".media-volume-row")).not.toBeNull();++ // Everything a small host has no room for is gone, along with the full player's stacked rows.+ expect(container.querySelector(".speed-dropdown")).toBeNull();+ expect(container.querySelector(".media-buttons-row")).toBeNull();+ });++ it.each([ "preview", "embedded" ] as const)("gives %s's whole band to a half-scale visualizer, dropping the music icon", async (environment) => {+ await renderCompactAudio(environment);++ expect(container.querySelector(".audio-preview-icon")).toBeNull();+ expect(audioVisualizer).toHaveBeenCalledWith(+ expect.objectContaining({ compact: true }), expect.anything());+ });++ it("leaves the note detail with the full controls and the icon", async () => {+ await act(async () => render(<MediaPreview entity={audioNote} environment="standalone" />, container));++ expect(container.querySelector(".media-compact")).toBeNull();+ expect(container.querySelector(".media-compact-row")).toBeNull();+ expect(container.querySelector(".media-buttons-row")).not.toBeNull();+ expect(container.querySelector(".speed-dropdown")).not.toBeNull();+ expect(container.querySelector(".audio-preview-icon")).not.toBeNull();+ expect(audioVisualizer).toHaveBeenCalledWith(+ expect.objectContaining({ compact: false }), expect.anything());+ });+ });+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/media_environment.spec.ts b/apps/client/src/widgets/type_widgets/file/media_environment.spec.tsindex 3e8f019995..064cd72aa0 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 } from "./media_environment";+import { loadsEagerly, playerRootClasses, preloadFor, 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", () => {@@ -16,8 +16,14 @@ describe("media environment", () => {});it("makes only a preview opt out of link navigation, since its host card is itself a link", () => {- expect(playerRootClasses("preview")).toBe("media-env-preview no-link-navigation");- expect(playerRootClasses("embedded")).toBe("media-env-embedded");+ expect(playerRootClasses("preview")).toBe("media-env-preview media-compact no-link-navigation");+ expect(playerRootClasses("embedded")).toBe("media-env-embedded media-compact");expect(playerRootClasses("standalone")).toBe("media-env-standalone");});++ it("gives everything but the note detail the compact chrome — nothing else has room for the full set", () => {+ expect(usesCompactControls("preview")).toBe(true);+ expect(usesCompactControls("embedded")).toBe(true);+ expect(usesCompactControls("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.tsindex 489050ee7e..3eea829ce7 100644--- a/apps/client/src/widgets/type_widgets/file/media_environment.ts+++ b/apps/client/src/widgets/type_widgets/file/media_environment.ts@@ -20,10 +20,23 @@ export function preloadFor(environment: MediaEnvironment): "auto" | "metadata" {}/**- * Classes for a player's root element. A preview sits inside a clickable host (a collection card is itself a- * link), so it opts out of link navigation — otherwise pressing play, seeking or opening the speed dropdown- * would also open the note. See `no-link-navigation` in services/link.ts.+ * Classes for a player's root element:+ * - `media-compact` styles the compact chrome, keeping {@link usesCompactControls} the one thing that decides+ * who wears it (the markup and the stylesheet both follow from it).+ * - `no-link-navigation` is only for a preview, which sits inside a clickable host (a collection card is itself+ * a link): without it, pressing play or seeking would also open the note. See services/link.ts.*/export function playerRootClasses(environment: MediaEnvironment): string {- return `media-env-${environment}${environment === "preview" ? " no-link-navigation" : ""}`;+ const classes = [ `media-env-${environment}` ];+ if (usesCompactControls(environment)) classes.push("media-compact");+ if (environment === "preview") classes.push("no-link-navigation");+ return classes.join(" ");+}++/**+ * Whether the player wears its compact chrome: only the note detail has room for the full control set, so+ * everywhere else keeps just what a small host needs — play, seek, volume — and drops the rest.+ */+export function usesCompactControls(environment: MediaEnvironment): boolean {+ return environment !== "standalone";}