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: increase test coverage
Adorian Doran21b158c64d3d
diff --git a/apps/client/src/widgets/type_widgets/file/Audio.spec.tsx b/apps/client/src/widgets/type_widgets/file/Audio.spec.tsxnew file mode 100644index 0000000000..f73750013c--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/Audio.spec.tsx@@ -0,0 +1,191 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// The visualizer needs the Web Audio API and the waveform loader fetches the whole file; neither exists+// here, and both have specs of their own. Hoisted: Audio.tsx imports them statically.+const { loadWaveform, audioVisualizer } = vi.hoisted(() => ({+ loadWaveform: vi.fn(async (_url: string, _options?: { signal?: AbortSignal }) => null as { peaks: number[] } | null),+ audioVisualizer: vi.fn(() => null)+}));+vi.mock("./audio_waveform", () => ({ loadWaveform }));+vi.mock("./AudioVisualizer", () => ({ AudioVisualizer: audioVisualizer }));++import AudioPreview from "./Audio";+import type FNote from "../../../entities/fnote";+import type { MediaSource } from "./media_source";++const source: MediaSource = {+ id: "snd1",+ title: "Podcast",+ mime: "audio/mpeg",+ streamUrl: "api/notes/snd1/open-partial?v=blobA",+ fullUrl: "api/notes/snd1/open?v=blobA"+};+const audioNote = { noteId: "snd1", title: "Podcast", mime: "audio/mpeg", blobId: "blobA" } as FNote;++describe("AudioPreview", () => {+ let container: HTMLElement;++ beforeEach(() => {+ loadWaveform.mockClear();+ loadWaveform.mockResolvedValue(null);+ container = document.createElement("div");+ document.body.appendChild(container);+ HTMLMediaElement.prototype.play = vi.fn(async () => {}) as unknown as HTMLMediaElement["play"];+ HTMLMediaElement.prototype.pause = vi.fn();+ });++ afterEach(() => {+ act(() => render(null, container));+ container.remove();+ });++ const renderPlayer = (overrides: Partial<MediaSource> = {}) => {+ act(() => render(<AudioPreview entity={audioNote} source={{ ...source, ...overrides }} environment="standalone" />, container));+ const audio = container.querySelector("audio");+ if (!audio) throw new Error("no audio element rendered");+ return audio;+ };++ const wrapper = () => {+ const el = container.querySelector(".audio-preview-wrapper");+ if (!el) throw new Error("no wrapper rendered");+ return el as HTMLElement;+ };++ /** `duration` is read-only on a media element, and happy-dom leaves it NaN — seeking needs a real one. */+ const setDuration = (audio: HTMLAudioElement, duration: number) =>+ Object.defineProperty(audio, "duration", { value: duration, configurable: true });++ const press = (key: string, init: KeyboardEventInit = {}) =>+ act(() => { wrapper().dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, ...init })); });++ describe("keyboard shortcuts", () => {+ it("seeks by 10s, or a minute with Ctrl, and clamps to the media's bounds", async () => {+ const audio = renderPlayer();+ setDuration(audio, 120);+ audio.currentTime = 60;++ await press("ArrowRight");+ expect(audio.currentTime).toBe(70);+ await press("ArrowLeft");+ expect(audio.currentTime).toBe(60);+ await press("ArrowLeft", { ctrlKey: true });+ expect(audio.currentTime).toBe(0);+ // Already at the start: another jump back can't go negative.+ await press("ArrowLeft");+ expect(audio.currentTime).toBe(0);++ await press("End");+ expect(audio.currentTime).toBe(120);+ await press("ArrowRight");+ expect(audio.currentTime).toBe(120);+ await press("Home");+ expect(audio.currentTime).toBe(0);+ });++ it("toggles playback with Space, following the element's own state", async () => {+ const audio = renderPlayer();++ await press(" ");+ expect(audio.play).toHaveBeenCalledTimes(1);++ Object.defineProperty(audio, "paused", { value: false, configurable: true });+ await press(" ");+ expect(audio.pause).toHaveBeenCalledTimes(1);+ });++ it("toggles mute and steps the volume within range", async () => {+ const audio = renderPlayer();+ audio.volume = 0.5;++ await press("m");+ expect(audio.muted).toBe(true);+ await press("M");+ expect(audio.muted).toBe(false);++ await press("ArrowUp");+ expect(audio.volume).toBeCloseTo(0.55);+ await press("ArrowDown");+ expect(audio.volume).toBeCloseTo(0.5);++ audio.volume = 1;+ await press("ArrowUp");+ expect(audio.volume).toBe(1);+ audio.volume = 0;+ await press("ArrowDown");+ expect(audio.volume).toBe(0);+ });++ it("has no fullscreen to toggle, and ignores keys it doesn't bind", async () => {+ const audio = renderPlayer();+ setDuration(audio, 100);+ audio.currentTime = 20;++ await press("f");+ await press("k");+ expect(audio.currentTime).toBe(20);+ expect(audio.play).not.toHaveBeenCalled();+ });+ });++ describe("waveform", () => {+ it("decodes the whole file for the current media only, abandoning a previous decode", async () => {+ let firstSignal: AbortSignal | undefined;+ loadWaveform.mockImplementation(async (_url, options) => {+ firstSignal ??= options?.signal;+ return null;+ });++ renderPlayer();+ expect(loadWaveform).toHaveBeenCalledWith(source.fullUrl, expect.objectContaining({ signal: expect.anything() }));+ expect(firstSignal?.aborted).toBe(false);++ // Switching media abandons the in-flight decode, so a slow one can't paint over the new track.+ await act(async () => { renderPlayer({ id: "snd2", fullUrl: "api/notes/snd2/open?v=blobB" }); });+ expect(firstSignal?.aborted).toBe(true);+ expect(loadWaveform).toHaveBeenLastCalledWith("api/notes/snd2/open?v=blobB", expect.objectContaining({ signal: expect.anything() }));+ });++ it("keeps a plain seek bar when the file has no usable waveform", async () => {+ loadWaveform.mockResolvedValue(null);+ await act(async () => { renderPlayer(); });++ expect(container.querySelector(".waveform-seekbar")).not.toBeNull();+ });++ it("survives a decode that fails outright", async () => {+ loadWaveform.mockRejectedValue(new Error("decode failed"));+ await act(async () => { renderPlayer(); });++ expect(container.querySelector(".waveform-seekbar")).not.toBeNull();+ expect(container.querySelector(".no-items")).toBeNull();+ });+ });++ it("gives the whole visualizer band to the full player, alongside the music icon", () => {+ renderPlayer();++ expect(container.querySelector(".audio-preview-icon")).not.toBeNull();+ expect(audioVisualizer).toHaveBeenCalledWith(expect.objectContaining({ compact: false }), expect.anything());+ });++ it("replaces the player with an unsupported-format message when the media fails to load", async () => {+ const audio = renderPlayer();++ await act(async () => { audio.dispatchEvent(new Event("error")); });++ expect(container.querySelector("audio")).toBeNull();+ expect(container.querySelector(".no-items")).not.toBeNull();+ });++ it("resets the error when a new media is shown in the same player", async () => {+ const audio = renderPlayer();+ await act(async () => { audio.dispatchEvent(new Event("error")); });+ expect(container.querySelector("audio")).toBeNull();++ renderPlayer({ id: "snd2", streamUrl: "api/notes/snd2/open-partial?v=blobB" });+ expect(container.querySelector("audio")?.getAttribute("src")).toBe("api/notes/snd2/open-partial?v=blobB");+ });+});diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.spec.tsx b/apps/client/src/widgets/type_widgets/file/MediaPlayer.spec.tsxindex 7ff51349cd..baee99c39d 100644--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.spec.tsx+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.spec.tsx@@ -1,33 +1,90 @@-import { render } from "preact";+import $ from "jquery";+import { RefObject, render } from "preact";import { act } from "preact/test-utils";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+const { getNote, setLabel, removeAttributeById, logError } = vi.hoisted(() => ({+ getNote: vi.fn(async (_noteId: string) => null as unknown),+ setLabel: vi.fn(async () => {}),+ removeAttributeById: vi.fn(async () => {}),+ logError: vi.fn()+}));+vi.mock("../../../services/froca", () => ({ default: { getNote } }));+vi.mock("../../../services/attributes", () => ({ default: { setLabel, removeAttributeById } }));+// Replaces the setup-wide ws mock for this file, so it has to keep the subscription surface that mock+// provides (other services subscribe at import time) while adding the logError the play mode reports through.+vi.mock("../../../services/ws", () => ({+ default: { subscribeToMessages: () => {} },+ logError,+ subscribeToMessages: () => {},+ unsubscribeToMessage: () => {}+}));++import type NoteContext from "../../../components/note_context";import Component from "../../../components/component";+import type FNote from "../../../entities/fnote";import { collectShortcutHints } from "../../../services/shortcut_hints";import { ParentComponent } from "../../react/react_utils";-import { useMediaPlayerShortcutHints } from "./MediaPlayer";+import { formatTime, PlaybackSpeed, PlayModeButton, PlayPauseButton, SeekBar, SkipButton, useMediaPlayerShortcutHints, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";+import type { MediaPlayMode } from "./media_play_mode";+import type { MediaSource } from "./media_source";let container: HTMLDivElement;+beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ getNote.mockReset();+ getNote.mockResolvedValue(null);+ setLabel.mockClear();+ removeAttributeById.mockClear();+ logError.mockClear();+});+afterEach(() => {act(() => render(null, container));container.remove();});-function collectHints(fullscreen: boolean) {- const host = new Component();- container = document.createElement("div");- document.body.appendChild(container);-- function Probe() {- useMediaPlayerShortcutHints({ fullscreen });- return null;- }- act(() => render(<ParentComponent.Provider value={host}><Probe /></ParentComponent.Provider>, container));- return collectShortcutHints(host);+/** A media element standing in for a mounted player's, with the read-only bits made writable. */+function fakeMedia({ duration = 100, currentTime = 0 } = {}) {+ const media = document.createElement("audio");+ Object.defineProperty(media, "duration", { value: duration, writable: true, configurable: true });+ media.currentTime = currentTime;+ return { current: media } as RefObject<HTMLAudioElement>;}+const click = (el: Element | null | undefined) =>+ act(() => { el?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });++const input = (el: Element | null, value: string) =>+ act(() => {+ (el as HTMLInputElement).value = value;+ el?.dispatchEvent(new Event("input", { bubbles: true }));+ });++/** A Dropdown only mounts its items once Bootstrap announces the open, which is what this stands in for. */+const openDropdown = () =>+ act(() => { $(container.querySelector(".dropdown") as HTMLElement).trigger("show.bs.dropdown"); });++/** Lets a chain of promises inside the component settle, then flushes the renders and effects it caused. */+const settle = async () => {+ await act(async () => { await Promise.resolve(); });+ await act(async () => { await Promise.resolve(); });+};+describe("useMediaPlayerShortcutHints", () => {+ function collectHints(fullscreen: boolean) {+ const host = new Component();++ function Probe() {+ useMediaPlayerShortcutHints({ fullscreen });+ return null;+ }+ act(() => render(<ParentComponent.Provider value={host}><Probe /></ParentComponent.Provider>, container));+ return collectShortcutHints(host);+ }+it("registers playback (incl. fullscreen) and navigation for video", () => {const sections = collectHints(true);@@ -57,3 +114,517 @@ describe("useMediaPlayerShortcutHints", () => {]);});});++describe("formatTime", () => {+ it("renders m:ss, zero-padding the seconds and flooring the remainder", () => {+ expect(formatTime(0)).toBe("0:00");+ expect(formatTime(9.9)).toBe("0:09");+ expect(formatTime(65)).toBe("1:05");+ expect(formatTime(3600)).toBe("60:00");+ });+});++describe("SeekBar", () => {+ const trackbar = () => container.querySelector(".media-trackbar") as HTMLInputElement;+ const times = () => Array.from(container.querySelectorAll(".media-time")).map(el => el.textContent);++ it("seeds from an element whose metadata already loaded, so the thumb isn't pinned at zero", () => {+ // The element is ready before the (passive) effect runs — common for cached media — so the initial+ // durationchange/timeupdate already fired and listeners alone would leave duration at 0.+ const mediaRef = fakeMedia({ duration: 200, currentTime: 30 });+ act(() => render(<SeekBar mediaRef={mediaRef} />, container));++ expect(trackbar().getAttribute("max")).toBe("200");+ expect(times()).toEqual([ "0:30", "-2:50" ]);+ });++ it("follows the element as it plays and as its duration resolves", () => {+ const mediaRef = fakeMedia({ duration: 0, currentTime: 0 });+ act(() => render(<SeekBar mediaRef={mediaRef} />, container));+ expect(trackbar().getAttribute("max")).toBe("0");++ const media = mediaRef.current;+ if (!media) throw new Error("no media");+ act(() => {+ Object.defineProperty(media, "duration", { value: 60, writable: true, configurable: true });+ media.dispatchEvent(new Event("durationchange"));+ });+ expect(trackbar().getAttribute("max")).toBe("60");++ act(() => {+ media.currentTime = 15;+ media.dispatchEvent(new Event("timeupdate"));+ });+ expect(times()).toEqual([ "0:15", "-0:45" ]);+ });++ it("scrubs the element to the dragged position", () => {+ const mediaRef = fakeMedia({ duration: 100 });+ act(() => render(<SeekBar mediaRef={mediaRef} />, container));++ input(trackbar(), "42.5");+ expect(mediaRef.current?.currentTime).toBe(42.5);+ });+});++describe("VolumeControl", () => {+ const slider = () => container.querySelector(".media-volume-slider") as HTMLInputElement;+ const muteButton = () => container.querySelector(".media-volume-row button");++ it("shows the element's level, picking the icon from how loud it is", () => {+ const mediaRef = fakeMedia();+ const media = mediaRef.current;+ if (!media) throw new Error("no media");++ media.volume = 0.8;+ act(() => render(<VolumeControl mediaRef={mediaRef} />, container));+ expect(container.querySelector(".bx-volume-full")).not.toBeNull();++ act(() => {+ media.volume = 0.2;+ media.dispatchEvent(new Event("volumechange"));+ });+ expect(container.querySelector(".bx-volume-low")).not.toBeNull();++ act(() => {+ media.volume = 0;+ media.dispatchEvent(new Event("volumechange"));+ });+ expect(container.querySelector(".bx-volume-mute")).not.toBeNull();+ });++ it("sets the element's volume, and unmutes when dragged up from silence", () => {+ const mediaRef = fakeMedia();+ const media = mediaRef.current;+ if (!media) throw new Error("no media");+ media.muted = true;+ act(() => render(<VolumeControl mediaRef={mediaRef} />, container));+ // A muted player reads as silent whatever its stored level.+ expect(slider().value).toBe("0");++ input(slider(), "0.4");+ expect(media.volume).toBeCloseTo(0.4);+ expect(media.muted).toBe(false);+ expect(slider().value).toBe("0.4");+ });++ it("toggles mute from the icon button", () => {+ const mediaRef = fakeMedia();+ const media = mediaRef.current;+ if (!media) throw new Error("no media");+ act(() => render(<VolumeControl mediaRef={mediaRef} />, container));++ click(muteButton());+ expect(media.muted).toBe(true);+ expect(container.querySelector(".bx-volume-mute")).not.toBeNull();++ click(muteButton());+ expect(media.muted).toBe(false);+ });+});++describe("PlaybackSpeed", () => {+ const items = () => Array.from(container.querySelectorAll(".dropdown-item"));++ it("offers the speeds, marking the element's current one", () => {+ const mediaRef = fakeMedia();+ const media = mediaRef.current;+ if (!media) throw new Error("no media");+ media.playbackRate = 1.5;+ act(() => render(<PlaybackSpeed mediaRef={mediaRef} />, container));+ openDropdown();++ expect(items().map(el => el.textContent)).toEqual([ "0.5x", "1x", "1.25x", "1.5x", "2x" ]);+ expect(items().find(el => el.classList.contains("active"))?.textContent).toBe("1.5x");+ expect(container.querySelector(".media-speed-label")?.textContent).toBe("1.5x");+ });++ it("applies a chosen speed, and follows one changed elsewhere", () => {+ const mediaRef = fakeMedia();+ const media = mediaRef.current;+ if (!media) throw new Error("no media");+ act(() => render(<PlaybackSpeed mediaRef={mediaRef} />, container));+ openDropdown();++ click(items().find(el => el.textContent === "2x"));+ expect(media.playbackRate).toBe(2);+ expect(container.querySelector(".media-speed-label")?.textContent).toBe("2x");++ act(() => {+ media.playbackRate = 0.5;+ media.dispatchEvent(new Event("ratechange"));+ });+ expect(container.querySelector(".media-speed-label")?.textContent).toBe("0.5x");+ });+});++describe("SkipButton", () => {+ it("jumps by its offset, staying inside the media", () => {+ const mediaRef = fakeMedia({ duration: 100, currentTime: 50 });+ act(() => render(<SkipButton mediaRef={mediaRef} seconds={10} icon="bx bx-fast-forward" text="forward" />, container));++ click(container.querySelector("button"));+ expect(mediaRef.current?.currentTime).toBe(60);++ if (mediaRef.current) mediaRef.current.currentTime = 95;+ click(container.querySelector("button"));+ expect(mediaRef.current?.currentTime).toBe(100);+ });++ it("jumps backwards without going below zero", () => {+ const mediaRef = fakeMedia({ duration: 100, currentTime: 4 });+ act(() => render(<SkipButton mediaRef={mediaRef} seconds={-10} icon="bx bx-rewind" text="back" />, container));++ click(container.querySelector("button"));+ expect(mediaRef.current?.currentTime).toBe(0);+ });+});++describe("PlayPauseButton", () => {+ it("shows play or pause for the current state, and reports the press", () => {+ const togglePlayback = vi.fn();+ act(() => render(<PlayPauseButton playing={false} togglePlayback={togglePlayback} />, container));+ expect(container.querySelector(".bx-play")).not.toBeNull();++ click(container.querySelector("button"));+ expect(togglePlayback).toHaveBeenCalledTimes(1);++ act(() => render(<PlayPauseButton playing togglePlayback={togglePlayback} />, container));+ expect(container.querySelector(".bx-pause")).not.toBeNull();+ });+});++describe("PlayModeButton", () => {+ it("shows the current mode, ticks it in the menu, and reports a new choice", () => {+ const onSelectMode = vi.fn();+ act(() => render(<PlayModeButton mode="loop" onSelectMode={onSelectMode} />, container));+ openDropdown();++ const items = Array.from(container.querySelectorAll(".dropdown-item"));+ expect(items).toHaveLength(3);+ const active = items.find(el => el.classList.contains("active"));+ expect(active?.querySelector(".bx-repeat")).not.toBeNull();+ expect(active?.querySelector(".play-mode-check")).not.toBeNull();++ click(items[2]);+ expect(onSelectMode).toHaveBeenCalledWith("next");+ });+});++describe("useMediaPlayMode", () => {+ let latest: { mode: MediaPlayMode; setMode: (mode: MediaPlayMode) => void } | undefined;++ /** A note whose play-mode label is `labelValue`, owned unless stated otherwise (i.e. inherited). */+ const noteWithMode = (labelValue: string | null, { owned = true } = {}) => ({+ noteId: "parent1",+ getLabelValue: () => labelValue,+ getOwnedLabel: () => (owned && labelValue ? { attributeId: "attr1" } : null)+ });++ async function renderHook({ notePath, playlistNoteId, mediaRef = fakeMedia() }: {+ notePath?: string;+ playlistNoteId?: string;+ mediaRef?: RefObject<HTMLAudioElement>;+ }) {+ const noteContext = { notePath } as NoteContext;++ function Probe() {+ latest = useMediaPlayMode(noteContext, mediaRef, playlistNoteId);+ return null;+ }+ await act(async () => { render(<Probe />, container); });+ // The mode arrives from the note lookup a microtask later, and the element's `loop` an effect after that.+ await settle();+ return mediaRef;+ }++ it("reads the mode from the folder the media sits in, and loops the element to match", async () => {+ getNote.mockResolvedValue(noteWithMode("loop"));+ const mediaRef = await renderHook({ notePath: "root/folder1/snd1" });++ expect(getNote).toHaveBeenCalledWith("folder1");+ expect(latest?.mode).toBe("loop");+ expect(mediaRef.current?.loop).toBe(true);+ });++ it("takes the mode from the owning note instead, for one of its attachments", async () => {+ getNote.mockResolvedValue(noteWithMode("next"));+ await renderHook({ notePath: "root/folder1/own1", playlistNoteId: "own1" });++ // The attachment's playlist is the note owning it — not that note's folder.+ expect(getNote).toHaveBeenCalledWith("own1");+ expect(latest?.mode).toBe("next");+ });++ it("falls back to playing once for an unlabelled playlist, an unknown value, or no playlist at all", async () => {+ getNote.mockResolvedValue(noteWithMode(null));+ const mediaRef = await renderHook({ notePath: "root/folder1/snd1" });+ expect(latest?.mode).toBe("once");+ expect(mediaRef.current?.loop).toBe(false);++ getNote.mockResolvedValue(noteWithMode("nonsense"));+ await renderHook({ notePath: "root/folder2/snd1" });+ expect(latest?.mode).toBe("once");++ // A top-level note has no parent in its path, so there is nothing to read a mode from.+ getNote.mockClear();+ await renderHook({ notePath: "root" });+ expect(getNote).not.toHaveBeenCalled();+ expect(latest?.mode).toBe("once");+ });++ it("persists a chosen mode onto the playlist note", async () => {+ getNote.mockResolvedValue(noteWithMode(null));+ await renderHook({ notePath: "root/folder1/snd1" });++ await act(async () => { latest?.setMode("next"); });+ await settle();++ expect(latest?.mode).toBe("next");+ expect(setLabel).toHaveBeenCalledWith("parent1", "mediaNotesPlayMode", "next");+ });++ it("removes the label for 'play once', and only ever its own", async () => {+ getNote.mockResolvedValue(noteWithMode("loop"));+ await renderHook({ notePath: "root/folder1/snd1" });++ await act(async () => { latest?.setMode("once"); });+ await settle();++ expect(setLabel).not.toHaveBeenCalled();+ expect(removeAttributeById).toHaveBeenCalledWith("parent1", "attr1");++ // An inherited label belongs to an ancestor, so there is nothing of ours to remove.+ removeAttributeById.mockClear();+ getNote.mockResolvedValue(noteWithMode("loop", { owned: false }));+ await renderHook({ notePath: "root/folder2/snd1" });+ await act(async () => { latest?.setMode("once"); });+ await settle();+ expect(removeAttributeById).not.toHaveBeenCalled();+ });++ it("reports a failed write instead of silently keeping the optimistic mode", async () => {+ getNote.mockResolvedValue(noteWithMode(null));+ setLabel.mockRejectedValueOnce(new Error("offline"));+ await renderHook({ notePath: "root/folder1/snd1" });++ await act(async () => { latest?.setMode("loop"); });+ await settle();++ expect(logError).toHaveBeenCalledWith(expect.stringContaining("Could not persist media play mode"));+ });+});++describe("useMediaSessionController", () => {+ const source = (id: string, title = "Track"): MediaSource => ({+ id,+ title,+ mime: "audio/mpeg",+ streamUrl: `api/notes/${id}/open-partial?v=b`,+ fullUrl: `api/notes/${id}/open?v=b`+ });+ const noteOf = (id: string) => ({ noteId: id, title: id, type: "file", mime: "audio/mpeg" } as unknown as FNote);++ let actionHandlers: Map<string, MediaSessionActionHandler | null>;+ let mediaSession: { metadata: unknown; playbackState: string; setActionHandler: ReturnType<typeof vi.fn>; setPositionState: ReturnType<typeof vi.fn> };++ beforeEach(() => {+ actionHandlers = new Map();+ mediaSession = {+ metadata: null,+ playbackState: "none",+ setActionHandler: vi.fn((action: string, handler: MediaSessionActionHandler | null) => actionHandlers.set(action, handler)),+ setPositionState: vi.fn()+ };+ Object.defineProperty(navigator, "mediaSession", { value: mediaSession, configurable: true });+ (globalThis as { MediaMetadata?: unknown }).MediaMetadata = class {+ title: string;+ constructor(init: { title: string }) { this.title = init.title; }+ };+ });++ afterEach(() => {+ Reflect.deleteProperty(navigator, "mediaSession");+ Reflect.deleteProperty(globalThis as object, "MediaMetadata");+ });++ /** A folder holding `siblingIds` as same-type, same-mime children — what the media navigates between. */+ function withSiblings(...siblingIds: string[]) {+ getNote.mockImplementation(async (noteId: string) => (noteId === "folder1"+ ? { noteId: "folder1", getChildNotes: async () => siblingIds.map(noteOf) }+ : null));+ }++ function makeContext(noteId: string) {+ return {+ noteId,+ notePath: `root/folder1/${noteId}`,+ viewScope: {},+ isActive: () => true,+ setNote: vi.fn()+ } as unknown as NoteContext;+ }++ /** Mounts one controller per entry, all in one tree so a test's players share the module-wide slot. */+ async function renderPlayers(players: {+ id: string;+ noteContext?: NoteContext;+ isVisible?: boolean;+ playMode?: MediaPlayMode;+ autoPlay?: boolean;+ }[]) {+ const refs = players.map(() => fakeMedia());++ function Probe({ index, player }: { index: number; player: (typeof players)[number] }) {+ useMediaSessionController({+ source: source(player.id),+ entity: noteOf(player.id),+ environment: "standalone",+ noteContext: player.noteContext,+ isVisible: player.isVisible ?? true,+ autoPlay: player.autoPlay,+ mimePrefix: "audio/",+ mediaRef: refs[index],+ playMode: player.playMode ?? "once"+ });+ return null;+ }++ await act(async () => {+ render(<>{players.map((player, index) => <Probe key={player.id} index={index} player={player} />)}</>, container);+ });+ await settle();+ return { refs };+ }++ it("lets only one player play at a time, pausing whoever held the slot", async () => {+ const { refs } = await renderPlayers([ { id: "a" }, { id: "b" } ]);+ const [ first, second ] = refs.map(ref => ref.current);+ if (!first || !second) throw new Error("no media");+ const firstPause = vi.spyOn(first, "pause");++ await act(async () => { first.dispatchEvent(new Event("play")); });+ expect(firstPause).not.toHaveBeenCalled();++ await act(async () => { second.dispatchEvent(new Event("play")); });+ expect(firstPause).toHaveBeenCalled();+ });++ it("advances to the next sibling when the playlist plays through", async () => {+ withSiblings("a", "b");+ const noteContext = makeContext("a");+ const { refs } = await renderPlayers([ { id: "a", noteContext, playMode: "next" } ]);++ await act(async () => { refs[0].current?.dispatchEvent(new Event("ended")); });++ expect(noteContext.setNote).toHaveBeenCalledWith("root/folder1/b");+ });++ it("does not advance when playing once, nor past the last sibling", async () => {+ withSiblings("a", "b");+ const playOnce = makeContext("a");+ const { refs } = await renderPlayers([ { id: "a", noteContext: playOnce, playMode: "once" } ]);+ await act(async () => { refs[0].current?.dispatchEvent(new Event("ended")); });+ expect(playOnce.setNote).not.toHaveBeenCalled();++ // "next" doesn't wrap: the last sibling simply stops.+ const atEnd = makeContext("b");+ const last = await renderPlayers([ { id: "b", noteContext: atEnd, playMode: "next" } ]);+ await act(async () => { last.refs[0].current?.dispatchEvent(new Event("ended")); });+ expect(atEnd.setNote).not.toHaveBeenCalled();+ });++ it("hands the OS media session the title and the sibling actions while it owns it", async () => {+ withSiblings("a", "b");+ const noteContext = makeContext("a");+ const { refs } = await renderPlayers([ { id: "a", noteContext } ]);++ await act(async () => { refs[0].current?.dispatchEvent(new Event("play")); });+ await settle();++ expect((mediaSession.metadata as { title: string } | null)?.title).toBe("Track");+ expect(actionHandlers.get("nexttrack")).toBeTypeOf("function");++ actionHandlers.get("nexttrack")?.({ action: "nexttrack" });+ expect(noteContext.setNote).toHaveBeenCalledWith("root/folder1/b");+ });++ it("offers no sibling actions to the OS when the media has none", async () => {+ withSiblings("a");+ const { refs } = await renderPlayers([ { id: "a", noteContext: makeContext("a") } ]);+ await act(async () => { refs[0].current?.dispatchEvent(new Event("play")); });+ await settle();++ expect(actionHandlers.get("nexttrack")).toBeNull();+ expect(actionHandlers.get("previoustrack")).toBeNull();+ });++ it("drives the element from the OS seek and stop actions", async () => {+ const { refs } = await renderPlayers([ { id: "a", noteContext: makeContext("a") } ]);+ const media = refs[0].current;+ if (!media) throw new Error("no media");+ const pause = vi.spyOn(media, "pause");+ await act(async () => { media.dispatchEvent(new Event("play")); });+ await settle();++ media.currentTime = 40;+ actionHandlers.get("seekforward")?.({ action: "seekforward" });+ expect(media.currentTime).toBe(70);+ actionHandlers.get("seekbackward")?.({ action: "seekbackward" });+ expect(media.currentTime).toBe(60);++ // An explicit offset from the OS wins over the button-matching default.+ actionHandlers.get("seekbackward")?.({ action: "seekbackward", seekOffset: 5 });+ expect(media.currentTime).toBe(55);+ actionHandlers.get("seekto")?.({ action: "seekto", seekTime: 12 });+ expect(media.currentTime).toBe(12);++ actionHandlers.get("stop")?.({ action: "stop" });+ expect(pause).toHaveBeenCalled();+ expect(media.currentTime).toBe(0);+ });++ it("keeps the session state in step with the element, and clears it on the way out", async () => {+ const { refs } = await renderPlayers([ { id: "a", noteContext: makeContext("a") } ]);+ const media = refs[0].current;+ if (!media) throw new Error("no media");++ Object.defineProperty(media, "paused", { value: false, configurable: true });+ await act(async () => { media.dispatchEvent(new Event("play")); });+ await settle();+ expect(mediaSession.playbackState).toBe("playing");+ expect(mediaSession.setPositionState).toHaveBeenCalledWith(expect.objectContaining({ duration: 100 }));++ Object.defineProperty(media, "paused", { value: true, configurable: true });+ await act(async () => { media.dispatchEvent(new Event("pause")); });+ expect(mediaSession.playbackState).toBe("paused");++ // Closing the tab unmounts the player, which hands the session back rather than leaving it stale.+ await act(async () => { render(<></>, container); });+ expect(mediaSession.metadata).toBeNull();+ expect(actionHandlers.get("stop")).toBeNull();+ });++ it("pauses a player that is no longer the displayed one", async () => {+ const { refs } = await renderPlayers([ { id: "a" } ]);+ const media = refs[0].current;+ if (!media) throw new Error("no media");+ await act(async () => { media.dispatchEvent(new Event("play")); });+ const pause = vi.spyOn(media, "pause");++ await renderPlayers([ { id: "a", isVisible: false } ]);+ expect(pause).toHaveBeenCalled();+ });++ it("starts playing a player mounted for a just-activated preview", async () => {+ const { refs } = await renderPlayers([ { id: "a", autoPlay: true } ]);+ const media = refs[0].current;+ if (!media) throw new Error("no media");+ const play = vi.spyOn(media, "play").mockResolvedValue(undefined);++ // Playback waits for the media to become playable rather than racing the fetch.+ expect(play).not.toHaveBeenCalled();+ await act(async () => { media.dispatchEvent(new Event("canplay")); });+ expect(play).toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/type_widgets/file/Video.spec.tsx b/apps/client/src/widgets/type_widgets/file/Video.spec.tsxnew file mode 100644index 0000000000..24b6973b3c--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/Video.spec.tsx@@ -0,0 +1,337 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type FNote from "../../../entities/fnote";+import type { MediaSource } from "./media_source";+import VideoPreview from "./Video";++const source: MediaSource = {+ id: "vid1",+ title: "Holiday",+ mime: "video/mp4",+ streamUrl: "api/notes/vid1/open-partial?v=blobV",+ fullUrl: "api/notes/vid1/open?v=blobV"+};+const videoNote = { noteId: "vid1", title: "Holiday", mime: "video/mp4", blobId: "blobV" } as FNote;++describe("VideoPreview", () => {+ let container: HTMLElement;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ // happy-dom implements neither playback nor the fullscreen/PiP APIs the controls drive.+ HTMLMediaElement.prototype.play = vi.fn(async () => {}) as unknown as HTMLMediaElement["play"];+ HTMLMediaElement.prototype.pause = vi.fn();+ HTMLElement.prototype.requestFullscreen = vi.fn(async () => {});+ document.exitFullscreen = vi.fn(async () => {});+ setFullscreenElement(null);+ });++ afterEach(() => {+ vi.useRealTimers();+ act(() => render(null, container));+ container.remove();+ });++ const renderPlayer = (props: Partial<Parameters<typeof VideoPreview>[0]> = {}) => {+ act(() => render(<VideoPreview entity={videoNote} source={source} environment="standalone" {...props} />, container));+ const video = container.querySelector("video");+ if (!video) throw new Error("no video element rendered");+ return video;+ };++ const wrapper = () => {+ const el = container.querySelector(".video-preview-wrapper");+ if (!el) throw new Error("no wrapper rendered");+ return el as HTMLElement;+ };++ /** `duration` is read-only on a media element, and happy-dom leaves it NaN — seeking needs a real one. */+ const setDuration = (video: HTMLVideoElement, duration: number) =>+ Object.defineProperty(video, "duration", { value: duration, configurable: true });++ const press = (key: string, init: KeyboardEventInit = {}) =>+ act(() => { wrapper().dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, ...init })); });++ describe("keyboard shortcuts", () => {+ it("seeks by 10s, or a minute with Ctrl, and clamps to the media's bounds", async () => {+ const video = renderPlayer();+ setDuration(video, 100);+ video.currentTime = 50;++ await press("ArrowRight");+ expect(video.currentTime).toBe(60);+ await press("ArrowLeft");+ expect(video.currentTime).toBe(50);+ await press("ArrowRight", { ctrlKey: true });+ expect(video.currentTime).toBe(100);+ // Already at the end: another jump forward can't run past the duration.+ await press("ArrowRight");+ expect(video.currentTime).toBe(100);++ video.currentTime = 5;+ await press("ArrowLeft");+ expect(video.currentTime).toBe(0);+ });++ it("jumps to the start and the end", async () => {+ const video = renderPlayer();+ setDuration(video, 80);+ video.currentTime = 30;++ await press("End");+ expect(video.currentTime).toBe(80);+ await press("Home");+ expect(video.currentTime).toBe(0);+ });++ it("toggles playback with Space, following the element's own state", async () => {+ const video = renderPlayer();++ await press(" ");+ expect(video.play).toHaveBeenCalledTimes(1);++ // A playing element pauses instead.+ Object.defineProperty(video, "paused", { value: false, configurable: true });+ await press(" ");+ expect(video.pause).toHaveBeenCalledTimes(1);+ });++ it("toggles mute and steps the volume", async () => {+ const video = renderPlayer();+ video.volume = 0.5;++ await press("m");+ expect(video.muted).toBe(true);+ await press("M");+ expect(video.muted).toBe(false);++ await press("ArrowUp");+ expect(video.volume).toBeCloseTo(0.55);+ await press("ArrowDown");+ expect(video.volume).toBeCloseTo(0.5);++ // Volume is capped at both ends rather than running out of range.+ video.volume = 1;+ await press("ArrowUp");+ expect(video.volume).toBe(1);+ video.volume = 0;+ await press("ArrowDown");+ expect(video.volume).toBe(0);+ });++ it("enters and leaves fullscreen with F", async () => {+ renderPlayer();++ await press("f");+ expect(wrapper().requestFullscreen).toHaveBeenCalled();++ setFullscreenElement(wrapper());+ await press("F");+ expect(document.exitFullscreen).toHaveBeenCalled();+ });++ it("ignores keys it doesn't bind", async () => {+ const video = renderPlayer();+ setDuration(video, 100);+ video.currentTime = 20;++ await press("k");+ expect(video.currentTime).toBe(20);+ expect(video.play).not.toHaveBeenCalled();+ });+ });++ describe("click and tap", () => {+ const pointerDown = (pointerType: string) =>+ act(() => { wrapper().dispatchEvent(new PointerEvent("pointerdown", { pointerType, bubbles: true })); });+ const click = (target: Element = wrapper()) =>+ act(() => { target.dispatchEvent(new MouseEvent("click", { bubbles: true })); });++ it("plays or pauses on a mouse click", async () => {+ const video = renderPlayer();+ await pointerDown("mouse");+ await click();+ expect(video.play).toHaveBeenCalled();+ });++ it("only reveals the controls on a touch tap, leaving playback to the play button", async () => {+ const video = renderPlayer();+ await pointerDown("touch");+ await click();++ expect(video.play).not.toHaveBeenCalled();+ // The tap hid the (initially visible) controls instead.+ expect(wrapper().classList.contains("controls-hidden")).toBe(true);++ await pointerDown("touch");+ await click();+ expect(wrapper().classList.contains("controls-hidden")).toBe(false);+ });++ it("leaves clicks on the controls themselves alone", async () => {+ const video = renderPlayer();+ const controls = container.querySelector(".media-preview-controls");+ if (!controls) throw new Error("no controls rendered");++ await pointerDown("mouse");+ await click(controls);+ expect(video.play).not.toHaveBeenCalled();+ });+ });++ describe("auto-hiding controls", () => {+ it("hides them while playing and brings them back on pause", async () => {+ const video = renderPlayer();+ expect(wrapper().classList.contains("controls-hidden")).toBe(false);++ Object.defineProperty(video, "paused", { value: false, configurable: true });+ await act(async () => { video.dispatchEvent(new Event("play")); });+ expect(wrapper().classList.contains("controls-hidden")).toBe(true);++ Object.defineProperty(video, "paused", { value: true, configurable: true });+ await act(async () => { video.dispatchEvent(new Event("pause")); });+ expect(wrapper().classList.contains("controls-hidden")).toBe(false);+ });++ it("reveals them on mouse movement, then hides them again while playback continues", async () => {+ vi.useFakeTimers();+ const video = renderPlayer();+ Object.defineProperty(video, "paused", { value: false, configurable: true });+ await act(async () => { video.dispatchEvent(new Event("play")); });+ expect(wrapper().classList.contains("controls-hidden")).toBe(true);++ act(() => { wrapper().dispatchEvent(new PointerEvent("pointermove", { pointerType: "mouse", bubbles: true })); });+ expect(wrapper().classList.contains("controls-hidden")).toBe(false);++ act(() => { vi.advanceTimersByTime(3000); });+ expect(wrapper().classList.contains("controls-hidden")).toBe(true);+ });++ it("ignores pointer movement from a touch drag, which has no hover to reveal with", async () => {+ const video = renderPlayer();+ Object.defineProperty(video, "paused", { value: false, configurable: true });+ await act(async () => { video.dispatchEvent(new Event("play")); });++ act(() => { wrapper().dispatchEvent(new PointerEvent("pointermove", { pointerType: "touch", bubbles: true })); });+ expect(wrapper().classList.contains("controls-hidden")).toBe(true);+ });+ });++ describe("view controls", () => {+ const clickButton = (iconClass: string) => {+ const button = container.querySelector(`.${iconClass}`)?.closest("button");+ if (!button) throw new Error(`no button with icon ${iconClass}`);+ act(() => { button.dispatchEvent(new MouseEvent("click", { bubbles: true })); });+ };++ it("rotates in quarter turns, scaling the sideways ones down to fit", () => {+ const video = renderPlayer();++ clickButton("bx-rotate-right");+ expect(video.style.transform).toContain("rotate(90deg)");+ // A sideways video is scaled by the container's aspect ratio so it still fits.+ expect(video.style.transform).toContain("scale(");++ clickButton("bx-rotate-right");+ expect(video.style.transform).toBe("rotate(180deg)");++ clickButton("bx-rotate-right");+ expect(video.style.transform).toContain("rotate(270deg)");++ // Back to upright: the transform is dropped rather than left as rotate(0deg).+ clickButton("bx-rotate-right");+ expect(video.style.transform).toBe("");+ });++ it("toggles zoom-to-fit between cover and the default fit", () => {+ const video = renderPlayer();++ clickButton("bx-expand");+ expect(video.style.objectFit).toBe("cover");+ expect(container.querySelector(".bx-collapse")).not.toBeNull();++ clickButton("bx-collapse");+ expect(video.style.objectFit).toBe("");+ expect(container.querySelector(".bx-expand")).not.toBeNull();+ });++ it("swaps the fullscreen button for its exit form while fullscreen", async () => {+ renderPlayer();+ expect(container.querySelector(".bx-fullscreen")).not.toBeNull();++ setFullscreenElement(wrapper());+ await act(async () => { document.dispatchEvent(new Event("fullscreenchange")); });+ expect(container.querySelector(".bx-exit-fullscreen")).not.toBeNull();++ clickFullscreen();+ expect(document.exitFullscreen).toHaveBeenCalled();+ });++ it("offers picture-in-picture only where the browser supports it", async () => {+ renderPlayer();+ // happy-dom has no PiP, matching Firefox: the button is left out entirely.+ expect(container.querySelector(".bx-window-open")).toBeNull();++ const requestPictureInPicture = vi.fn(async () => ({}));+ Object.defineProperty(HTMLVideoElement.prototype, "requestPictureInPicture", { value: requestPictureInPicture, configurable: true });+ try {+ act(() => render(null, container));+ const video = renderPlayer();+ const button = container.querySelector(".bx-window-open")?.closest("button");+ expect(button).not.toBeNull();++ act(() => { button?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });+ expect(requestPictureInPicture).toHaveBeenCalled();++ // Entering PiP swaps the icon; clicking again leaves it.+ await act(async () => { video.dispatchEvent(new Event("enterpictureinpicture")); });+ const exitButton = container.querySelector(".bx-exit")?.closest("button");+ expect(exitButton).not.toBeNull();++ const exitPictureInPicture = vi.fn(async () => {});+ Object.defineProperty(document, "pictureInPictureElement", { value: video, configurable: true });+ document.exitPictureInPicture = exitPictureInPicture;+ act(() => { exitButton?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });+ expect(exitPictureInPicture).toHaveBeenCalled();++ await act(async () => { video.dispatchEvent(new Event("leavepictureinpicture")); });+ expect(container.querySelector(".bx-window-open")).not.toBeNull();+ } finally {+ Reflect.deleteProperty(HTMLVideoElement.prototype, "requestPictureInPicture");+ Reflect.deleteProperty(document, "pictureInPictureElement");+ }+ });++ function clickFullscreen() {+ const button = container.querySelector(".bx-exit-fullscreen, .bx-fullscreen")?.closest("button");+ act(() => { button?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });+ }+ });++ it("replaces the player with an unsupported-format message when the media fails to load", async () => {+ const video = renderPlayer();++ await act(async () => { video.dispatchEvent(new Event("error")); });++ expect(container.querySelector("video")).toBeNull();+ expect(container.querySelector(".no-items")).not.toBeNull();+ });++ it("resets the error when a new media is shown in the same player", async () => {+ const video = renderPlayer();+ await act(async () => { video.dispatchEvent(new Event("error")); });+ expect(container.querySelector("video")).toBeNull();++ const nextSource = { ...source, id: "vid2", streamUrl: "api/notes/vid2/open-partial?v=blobW" };+ act(() => render(<VideoPreview entity={videoNote} source={nextSource} environment="standalone" />, container));+ expect(container.querySelector("video")?.getAttribute("src")).toBe(nextSource.streamUrl);+ });+});++/** `document.fullscreenElement` is a read-only getter, so the tests swap it out per case. */+function setFullscreenElement(element: Element | null) {+ Object.defineProperty(document, "fullscreenElement", { value: element, configurable: true });+}diff --git a/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.spec.tsx b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.spec.tsxnew file mode 100644index 0000000000..bc26dff412--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.spec.tsx@@ -0,0 +1,154 @@+import { RefObject, render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { WaveformSeekBar } from "./WaveformSeekBar";++/** Canvas width the scrub tests work in: happy-dom lays nothing out, so the box is stated outright. */+const CANVAS_WIDTH = 200;++describe("WaveformSeekBar", () => {+ let container: HTMLElement;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ act(() => render(null, container));+ container.remove();+ });++ function fakeMedia({ duration = 100, currentTime = 0 } = {}) {+ const media = document.createElement("audio");+ Object.defineProperty(media, "duration", { value: duration, writable: true, configurable: true });+ media.currentTime = currentTime;+ return { current: media } as RefObject<HTMLAudioElement>;+ }++ function renderSeekBar(mediaRef = fakeMedia(), peaks: number[] | null = null) {+ act(() => render(<WaveformSeekBar mediaRef={mediaRef} peaks={peaks} />, container));+ const canvas = container.querySelector("canvas");+ if (!canvas) throw new Error("no canvas rendered");+ // The scrub maths reads the canvas' box, which happy-dom reports as zero-sized.+ canvas.getBoundingClientRect = () => ({ left: 0, width: CANVAS_WIDTH, right: CANVAS_WIDTH, top: 0, bottom: 20, height: 20, x: 0, y: 0, toJSON: () => ({}) });+ canvas.setPointerCapture = vi.fn();+ canvas.releasePointerCapture = vi.fn();+ canvas.hasPointerCapture = vi.fn(() => false);+ return { mediaRef, canvas };+ }++ const times = () => Array.from(container.querySelectorAll(".media-time")).map(el => el.textContent);++ const press = (canvas: HTMLCanvasElement, key: string) =>+ act(() => { canvas.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true })); });++ const pointer = (canvas: HTMLCanvasElement, type: "pointerdown" | "pointermove", clientX: number) =>+ act(() => { canvas.dispatchEvent(new PointerEvent(type, { clientX, pointerId: 1, bubbles: true })); });++ it("mirrors the element's clock, seeded from one whose metadata already loaded", () => {+ const mediaRef = fakeMedia({ duration: 200, currentTime: 50 });+ renderSeekBar(mediaRef);++ expect(times()).toEqual([ "0:50", "-2:30" ]);++ const media = mediaRef.current;+ if (!media) throw new Error("no media");+ act(() => {+ media.currentTime = 100;+ media.dispatchEvent(new Event("timeupdate"));+ });+ expect(times()).toEqual([ "1:40", "-1:40" ]);+ });++ it("exposes the position to assistive technology as a slider", () => {+ const { canvas } = renderSeekBar(fakeMedia({ duration: 100, currentTime: 25 }));++ expect(canvas.getAttribute("role")).toBe("slider");+ expect(canvas.getAttribute("aria-valuenow")).toBe("25");+ expect(canvas.getAttribute("aria-valuetext")).toBe("0:25 / 1:40");+ });++ describe("scrubbing with a pointer", () => {+ it("seeks to the pressed position", () => {+ const { mediaRef, canvas } = renderSeekBar(fakeMedia({ duration: 100 }));++ pointer(canvas, "pointerdown", CANVAS_WIDTH * 0.25);++ expect(mediaRef.current?.currentTime).toBe(25);+ // Focus follows the press, since the default focus-on-click was suppressed to start the drag.+ expect(canvas.setPointerCapture).toHaveBeenCalledWith(1);+ });++ it("keeps seeking while dragging, and ignores movement that isn't a drag", () => {+ const { mediaRef, canvas } = renderSeekBar(fakeMedia({ duration: 100 }));++ // A hover with no button held must not scrub.+ pointer(canvas, "pointermove", CANVAS_WIDTH * 0.9);+ expect(mediaRef.current?.currentTime).toBe(0);++ canvas.hasPointerCapture = vi.fn(() => true);+ pointer(canvas, "pointermove", CANVAS_WIDTH * 0.5);+ expect(mediaRef.current?.currentTime).toBe(50);+ });++ it("clamps a drag that strays outside the bar", () => {+ const { mediaRef, canvas } = renderSeekBar(fakeMedia({ duration: 100 }));+ canvas.hasPointerCapture = vi.fn(() => true);++ pointer(canvas, "pointermove", -50);+ expect(mediaRef.current?.currentTime).toBe(0);++ pointer(canvas, "pointermove", CANVAS_WIDTH + 50);+ expect(mediaRef.current?.currentTime).toBe(100);+ });+ });++ describe("scrubbing with the keyboard", () => {+ it("steps by 5% and jumps to either end", () => {+ const mediaRef = fakeMedia({ duration: 100, currentTime: 50 });+ const { canvas } = renderSeekBar(mediaRef);+ const media = mediaRef.current;+ if (!media) throw new Error("no media");+ const seek = (key: string) => {+ press(canvas, key);+ // The bar steps from its rendered position, which follows the element's clock.+ act(() => { media.dispatchEvent(new Event("timeupdate")); });+ };++ seek("ArrowRight");+ expect(media.currentTime).toBeCloseTo(55);+ seek("ArrowLeft");+ expect(media.currentTime).toBeCloseTo(50);++ seek("End");+ expect(media.currentTime).toBe(100);+ // At the end, stepping further is clamped rather than overrunning.+ seek("ArrowRight");+ expect(media.currentTime).toBe(100);++ seek("Home");+ expect(media.currentTime).toBe(0);+ seek("ArrowLeft");+ expect(media.currentTime).toBe(0);+ });++ it("leaves other keys to the player", () => {+ const { mediaRef, canvas } = renderSeekBar(fakeMedia({ duration: 100, currentTime: 30 }));++ press(canvas, " ");+ expect(mediaRef.current?.currentTime).toBe(30);+ });+ });++ it("does nothing until the media has a duration to seek within", () => {+ const { mediaRef, canvas } = renderSeekBar(fakeMedia({ duration: 0 }));++ pointer(canvas, "pointerdown", CANVAS_WIDTH * 0.5);+ press(canvas, "End");++ expect(mediaRef.current?.currentTime).toBe(0);+ expect(times()).toEqual([ "0:00", "-0:00" ]);+ });+});