mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-01 04:16:24 -05:00
Resume videos and audio where the user left off; show progress on cards (#791)
* Resume videos and audio where the user left off; show progress on cards Videos and audio resume where the user left off, on the video page and in the file preview, and keep playing. `?t=` starts at an explicit time instead. useFileProgress saves how far the user is through a file: every 15 seconds while it changes, and a final save (a beacon, which survives the page closing) on pause, end, hiding the page, leaving it, or switching files. Each save is also kept in sessionStorage; on open the newer of that and the server's position wins, so coming straight back resumes exactly even if the final save is still in flight. Cards show a progress bar along the bottom of their poster. The dashboard's Recently Viewed Files gains All / Continue; Continue uses the new `in_progress` file search filter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Progress review fixes: in_progress totals, latest dashboard request, preview viewed - The in_progress search filter skips the uncounted fast path and is part of the totals cache key, so Continue never reports All's (or the library's) count. - The dashboard's Recently Viewed hook applies only its latest response, and clears the list when switching All/Continue until the new files arrive. - POST /api/files/file returns `viewed`, so a preview can tell a file finished elsewhere from an older position this tab holds. - The progress hook tests restore Blob, fetch and sendBeacon. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
fbdf5bac82
commit
1ad451cddf
15 changed files with 666 additions and 38 deletions
|
|
@ -943,33 +943,46 @@ export const useChannels = () => {
|
|||
return [channels, total, metadata];
|
||||
}
|
||||
|
||||
export const useSearchRecentFiles = () => {
|
||||
export const useSearchRecentFiles = (inProgress = false) => {
|
||||
const [searchFiles, setSearchFiles] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
// All and Continue share this hook; only the latest request may write, so a slow response for the
|
||||
// previous mode cannot replace the current one.
|
||||
const latestRequestRef = React.useRef(0);
|
||||
|
||||
const localSearchFiles = async () => {
|
||||
const requestId = ++latestRequestRef.current;
|
||||
setLoading(true);
|
||||
try {
|
||||
let [file_groups, total] = await filesSearch(
|
||||
// `inProgress` returns only the files the user is part way through.
|
||||
let [file_groups] = await filesSearch(
|
||||
null, 12, null, null, null, [], false,
|
||||
null, null, null, false, 'viewed');
|
||||
setSearchFiles(file_groups);
|
||||
null, null, null, false, 'viewed', null, null, false, inProgress);
|
||||
if (requestId === latestRequestRef.current) {
|
||||
setSearchFiles(file_groups);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Unexpected server response',
|
||||
description: 'Could not get recent files',
|
||||
time: 5000,
|
||||
});
|
||||
if (requestId === latestRequestRef.current) {
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Unexpected server response',
|
||||
description: 'Could not get recent files',
|
||||
time: 5000,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (requestId === latestRequestRef.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
// The other mode's files are not this mode's; show the placeholder until they arrive.
|
||||
setSearchFiles(null);
|
||||
localSearchFiles();
|
||||
}, []);
|
||||
}, [inProgress]);
|
||||
|
||||
return {searchFiles, loading, fetchFiles: localSearchFiles};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,11 +2,12 @@ import React from 'react';
|
|||
import {act, renderHook} from '@testing-library/react';
|
||||
import {render, screen} from '../test-utils';
|
||||
import {
|
||||
usePages, useDriveTemperature, useDriveHealth, useSearchChannels, useSettings, useStatistics, useStatus,
|
||||
useVideoExtras,
|
||||
usePages, useDriveTemperature, useDriveHealth, useSearchChannels, useSearchRecentFiles, useSettings,
|
||||
useStatistics, useStatus, useVideoExtras,
|
||||
} from './customHooks';
|
||||
import {
|
||||
ApiDownError, getSettings, getStatistics, getStatus, getVideoComments, getVideoDescription, searchChannels,
|
||||
ApiDownError, filesSearch, getSettings, getStatistics, getStatus, getVideoComments, getVideoDescription,
|
||||
searchChannels,
|
||||
} from '../api';
|
||||
import {getControllerStats} from '../api/controller';
|
||||
import {QueryContext, StatusContext} from '../contexts/contexts';
|
||||
|
|
@ -48,6 +49,7 @@ jest.mock('../api', () => ({
|
|||
getStatistics: jest.fn(),
|
||||
getStatus: jest.fn(),
|
||||
getSettings: jest.fn(),
|
||||
filesSearch: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock('../api/controller', () => ({
|
||||
|
|
@ -685,3 +687,52 @@ describe('useSettings loaded', () => {
|
|||
expect(result.current.settings.media_directory).toBe('/media/wrolpi');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useSearchRecentFiles', () => {
|
||||
/** A filesSearch call the test resolves when it chooses. */
|
||||
const deferred = () => {
|
||||
let resolve;
|
||||
const promise = new Promise(r => resolve = r);
|
||||
return {promise, resolve};
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
filesSearch.mockReset();
|
||||
});
|
||||
|
||||
test('switching modes shows only the new mode\'s files, even if the old response arrives last', async () => {
|
||||
const all = deferred();
|
||||
const continuing = deferred();
|
||||
filesSearch.mockReturnValueOnce(all.promise).mockReturnValueOnce(continuing.promise);
|
||||
|
||||
const {result, rerender} = renderHook(({inProgress}) => useSearchRecentFiles(inProgress),
|
||||
{initialProps: {inProgress: false}});
|
||||
// Continue, before All's response arrives.
|
||||
rerender({inProgress: true});
|
||||
expect(filesSearch.mock.calls[1][15]).toBe(true);
|
||||
|
||||
await act(async () => continuing.resolve([[{primary_path: 'started.mp4'}], 1]));
|
||||
await act(async () => all.resolve([[{primary_path: 'started.mp4'}, {primary_path: 'finished.mp4'}], 2]));
|
||||
|
||||
expect(result.current.searchFiles).toEqual([{primary_path: 'started.mp4'}]);
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
test('switching modes clears the old files until the new ones arrive', async () => {
|
||||
const continuing = deferred();
|
||||
filesSearch.mockResolvedValueOnce([[{primary_path: 'a.mp4'}], 1]).mockReturnValueOnce(continuing.promise);
|
||||
|
||||
const {result, rerender} = renderHook(({inProgress}) => useSearchRecentFiles(inProgress),
|
||||
{initialProps: {inProgress: false}});
|
||||
await act(async () => {
|
||||
});
|
||||
expect(result.current.searchFiles).toEqual([{primary_path: 'a.mp4'}]);
|
||||
|
||||
rerender({inProgress: true});
|
||||
// Not the All list, and not an empty list ("No results!"): nothing yet.
|
||||
expect(result.current.searchFiles).toBeNull();
|
||||
|
||||
await act(async () => continuing.resolve([[], 0]));
|
||||
expect(result.current.searchFiles).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
200
app/src/hooks/useFileProgress.js
Normal file
200
app/src/hooks/useFileProgress.js
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
import React from "react";
|
||||
import {API_URI} from "../components/Vars";
|
||||
|
||||
/*
|
||||
* How far the user is through a file, and where to resume it (see wrolpi/files/progress.py).
|
||||
*
|
||||
* The server is the source of truth; its FileGroup JSON carries `progress` and `position`. Every save is
|
||||
* also written to sessionStorage, because the final save sent while leaving a page can still be in flight
|
||||
* when the user comes straight back, and the server would then answer with an older position. Whichever
|
||||
* of the two is newer wins.
|
||||
*/
|
||||
|
||||
const HEARTBEAT_MS = 15_000;
|
||||
const CACHE_PREFIX = 'wrolpi-progress:';
|
||||
|
||||
// Mirrors wrolpi/files/progress.py, so a position the server would discard is not resumed from the cache.
|
||||
const FINISHED_PROGRESS = 0.95;
|
||||
const MINIMUM_PROGRESS = 0.01;
|
||||
const MINIMUM_SECONDS = 10;
|
||||
|
||||
function readCache(path) {
|
||||
try {
|
||||
const raw = window.sessionStorage.getItem(CACHE_PREFIX + path);
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(path, entry) {
|
||||
try {
|
||||
window.sessionStorage.setItem(CACHE_PREFIX + path, JSON.stringify(entry));
|
||||
} catch (e) {
|
||||
// Storage is unavailable (private mode, quota); the server still has the position.
|
||||
}
|
||||
}
|
||||
|
||||
/** Send progress to the server. A final save uses a beacon, which survives the page closing. */
|
||||
export function sendProgress(path, progress, position, final = false) {
|
||||
const url = `${API_URI}/files/progress`;
|
||||
const body = JSON.stringify({file: path, progress, position, final});
|
||||
if (final && navigator.sendBeacon) {
|
||||
if (navigator.sendBeacon(url, new Blob([body], {type: 'application/json'}))) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
fetch(url, {method: 'POST', body, keepalive: true})
|
||||
.catch(e => console.error('Failed to save progress', e));
|
||||
}
|
||||
|
||||
export function isResumable(progress, position) {
|
||||
if (!position || progress === null || progress === undefined) {
|
||||
return false;
|
||||
}
|
||||
if (progress >= FINISHED_PROGRESS || progress < MINIMUM_PROGRESS) {
|
||||
return false;
|
||||
}
|
||||
if (position.kind === 'time') {
|
||||
return position.seconds >= MINIMUM_SECONDS;
|
||||
}
|
||||
if (position.kind === 'page') {
|
||||
return position.page > 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where to resume `path`: the newer of the server's position (from `fileGroup`) and this tab's own.
|
||||
*
|
||||
* @returns {object|null} A position, or null to start from the beginning.
|
||||
*/
|
||||
export function getResumePosition(path, fileGroup) {
|
||||
if (!path) {
|
||||
return null;
|
||||
}
|
||||
let best = null;
|
||||
let bestTime = -1;
|
||||
if (fileGroup && fileGroup.progress !== null && fileGroup.progress !== undefined) {
|
||||
// A finished file has no position; when it was finished is when it was viewed.
|
||||
bestTime = fileGroup.position?.updated_at ?? (Date.parse(fileGroup.viewed) || 0);
|
||||
best = {progress: fileGroup.progress, position: fileGroup.position};
|
||||
}
|
||||
const cached = readCache(path);
|
||||
if (cached && cached.updated_at > bestTime) {
|
||||
best = cached;
|
||||
}
|
||||
return best && isResumable(best.progress, best.position) ? best.position : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save how far the user is through `path`.
|
||||
*
|
||||
* The viewer calls `report({progress, position})` as the user moves through the file; that is only
|
||||
* remembered. It is sent every 15 seconds if it changed, and as a final save when `save(true)` is called
|
||||
* (pause, end), when the page is hidden or closed, and when `path` changes or the viewer unmounts.
|
||||
*
|
||||
* The last report is kept rather than read from the viewer at unmount, because by then React has detached
|
||||
* the viewer's elements.
|
||||
*/
|
||||
export function useFileProgress(path, {enabled = true} = {}) {
|
||||
const snapshotRef = React.useRef(null);
|
||||
const sentRef = React.useRef(null);
|
||||
|
||||
const report = React.useCallback((snapshot) => {
|
||||
snapshotRef.current = snapshot;
|
||||
}, []);
|
||||
|
||||
const save = React.useCallback((final = false) => {
|
||||
const snapshot = snapshotRef.current;
|
||||
if (!path || !enabled || !snapshot) {
|
||||
return;
|
||||
}
|
||||
const key = JSON.stringify(snapshot);
|
||||
if (!final && key === sentRef.current) {
|
||||
return;
|
||||
}
|
||||
sentRef.current = key;
|
||||
|
||||
const updated_at = Date.now();
|
||||
const position = snapshot.position ? {...snapshot.position, updated_at} : null;
|
||||
writeCache(path, {progress: snapshot.progress, position, updated_at});
|
||||
sendProgress(path, snapshot.progress, position, final);
|
||||
}, [path, enabled]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!path || !enabled) {
|
||||
return;
|
||||
}
|
||||
// A new file starts with nothing to save.
|
||||
snapshotRef.current = null;
|
||||
sentRef.current = null;
|
||||
|
||||
const interval = setInterval(() => save(false), HEARTBEAT_MS);
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
save(true);
|
||||
}
|
||||
};
|
||||
const onPageHide = () => save(true);
|
||||
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||
window.addEventListener('pagehide', onPageHide);
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
window.removeEventListener('pagehide', onPageHide);
|
||||
save(true);
|
||||
};
|
||||
}, [path, enabled, save]);
|
||||
|
||||
return {report, save};
|
||||
}
|
||||
|
||||
/**
|
||||
* Track and resume a <video> or <audio>. Spread the returned handlers onto the element.
|
||||
*
|
||||
* @param path The FileGroup's primary path, relative to the media directory.
|
||||
* @param fileGroup The FileGroup JSON, which holds the server's position.
|
||||
* @param startSeconds An explicit start (e.g. `?t=`), which wins over any saved position.
|
||||
*/
|
||||
export function useMediaProgress(path, fileGroup, {startSeconds = null, enabled = true} = {}) {
|
||||
const {report, save} = useFileProgress(path, {enabled});
|
||||
// The path whose position was restored; the element fires `loadedmetadata` again on some seeks.
|
||||
const restoredRef = React.useRef(null);
|
||||
|
||||
const onLoadedMetadata = (e) => {
|
||||
if (!enabled || !path || restoredRef.current === path) {
|
||||
return;
|
||||
}
|
||||
restoredRef.current = path;
|
||||
const media = e.currentTarget;
|
||||
let seconds = startSeconds;
|
||||
if (seconds === null || seconds === undefined) {
|
||||
const position = getResumePosition(path, fileGroup);
|
||||
seconds = position && position.kind === 'time' ? position.seconds : null;
|
||||
}
|
||||
if (seconds && Number.isFinite(media.duration) && seconds < media.duration) {
|
||||
media.currentTime = seconds;
|
||||
}
|
||||
};
|
||||
|
||||
const onTimeUpdate = (e) => {
|
||||
const media = e.currentTarget;
|
||||
if (!Number.isFinite(media.duration) || media.duration <= 0) {
|
||||
return;
|
||||
}
|
||||
report({
|
||||
progress: media.currentTime / media.duration,
|
||||
position: {kind: 'time', seconds: media.currentTime},
|
||||
});
|
||||
};
|
||||
|
||||
const onPause = () => save(true);
|
||||
|
||||
const onEnded = () => {
|
||||
report({progress: 1, position: null});
|
||||
save(true);
|
||||
};
|
||||
|
||||
return {onLoadedMetadata, onTimeUpdate, onPause, onEnded};
|
||||
}
|
||||
212
app/src/hooks/useFileProgress.test.js
Normal file
212
app/src/hooks/useFileProgress.test.js
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
import React from 'react';
|
||||
import {act, render, renderHook} from '@testing-library/react';
|
||||
import {getResumePosition, useFileProgress, useMediaProgress} from './useFileProgress';
|
||||
import {ViewProgress} from '../components/Common';
|
||||
|
||||
const PATH = 'videos/movie.mp4';
|
||||
const CACHE_KEY = `wrolpi-progress:${PATH}`;
|
||||
|
||||
/** The bodies of the progress saves sent by beacon or fetch, in order. */
|
||||
const sent = () => [
|
||||
...navigator.sendBeacon.mock.calls.map(([, blob]) => blob.__body),
|
||||
...global.fetch.mock.calls.map(([, init]) => init.body),
|
||||
].map(i => JSON.parse(i));
|
||||
|
||||
const {Blob: realBlob, fetch: realFetch} = global;
|
||||
const realSendBeacon = navigator.sendBeacon;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
window.sessionStorage.clear();
|
||||
navigator.sendBeacon = jest.fn(() => true);
|
||||
global.fetch = jest.fn(() => Promise.resolve({ok: true}));
|
||||
// jsdom's Blob cannot be read synchronously; keep the body so a test can check it.
|
||||
global.Blob = class {
|
||||
constructor(parts) {
|
||||
this.__body = parts.join('');
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.restoreAllMocks();
|
||||
global.Blob = realBlob;
|
||||
global.fetch = realFetch;
|
||||
navigator.sendBeacon = realSendBeacon;
|
||||
});
|
||||
|
||||
describe('getResumePosition', () => {
|
||||
const position = {kind: 'time', seconds: 300, updated_at: 1000};
|
||||
|
||||
test('resumes from the server', () => {
|
||||
expect(getResumePosition(PATH, {progress: 0.5, position})).toEqual(position);
|
||||
});
|
||||
|
||||
test('a newer position from this tab wins over the server', () => {
|
||||
const cached = {kind: 'time', seconds: 400, updated_at: 2000};
|
||||
window.sessionStorage.setItem(CACHE_KEY, JSON.stringify({progress: 0.6, position: cached, updated_at: 2000}));
|
||||
expect(getResumePosition(PATH, {progress: 0.5, position})).toEqual(cached);
|
||||
});
|
||||
|
||||
test('a newer position from the server wins over this tab', () => {
|
||||
const cached = {kind: 'time', seconds: 400, updated_at: 500};
|
||||
window.sessionStorage.setItem(CACHE_KEY, JSON.stringify({progress: 0.6, position: cached, updated_at: 500}));
|
||||
expect(getResumePosition(PATH, {progress: 0.5, position})).toEqual(position);
|
||||
});
|
||||
|
||||
test('a file finished on another device starts over', () => {
|
||||
const cached = {kind: 'time', seconds: 400, updated_at: 500};
|
||||
window.sessionStorage.setItem(CACHE_KEY, JSON.stringify({progress: 0.6, position: cached, updated_at: 500}));
|
||||
const fileGroup = {progress: 1, position: null, viewed: new Date(9000).toISOString()};
|
||||
expect(getResumePosition(PATH, fileGroup)).toBeNull();
|
||||
});
|
||||
|
||||
test('a file finished on another device starts over in a preview, too', () => {
|
||||
// The shape of POST /api/files/file, which the file browser and `?preview=` use.
|
||||
const cached = {kind: 'time', seconds: 400, updated_at: 500};
|
||||
window.sessionStorage.setItem(CACHE_KEY, JSON.stringify({progress: 0.6, position: cached, updated_at: 500}));
|
||||
const previewFile = {path: PATH, progress: 1, position: null, viewed: new Date(9000).toISOString()};
|
||||
expect(getResumePosition(PATH, previewFile)).toBeNull();
|
||||
});
|
||||
|
||||
test.each([
|
||||
['finished', {progress: 1, position: null}],
|
||||
['too early', {progress: 0.2, position: {kind: 'time', seconds: 5}}],
|
||||
['first page', {progress: 0.1, position: {kind: 'page', page: 0}}],
|
||||
['never viewed', {progress: null, position: null}],
|
||||
['no file group', null],
|
||||
])('%s starts from the beginning', (_, fileGroup) => {
|
||||
expect(getResumePosition(PATH, fileGroup)).toBeNull();
|
||||
});
|
||||
|
||||
test('unreadable storage falls back to the server', () => {
|
||||
const getItem = jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
|
||||
throw new Error('denied');
|
||||
});
|
||||
try {
|
||||
expect(getResumePosition(PATH, {progress: 0.5, position})).toEqual(position);
|
||||
} finally {
|
||||
getItem.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('useFileProgress', () => {
|
||||
const snapshot = {progress: 0.25, position: {kind: 'time', seconds: 150}};
|
||||
|
||||
test('a report is sent by the heartbeat, once while it is unchanged', () => {
|
||||
const {result} = renderHook(() => useFileProgress(PATH));
|
||||
act(() => result.current.report(snapshot));
|
||||
expect(sent()).toEqual([]);
|
||||
|
||||
act(() => jest.advanceTimersByTime(15_000));
|
||||
act(() => jest.advanceTimersByTime(15_000));
|
||||
expect(sent()).toEqual([{
|
||||
file: PATH, progress: 0.25, final: false,
|
||||
position: {kind: 'time', seconds: 150, updated_at: expect.any(Number)},
|
||||
}]);
|
||||
// Heartbeats use fetch; only a final save needs a beacon.
|
||||
expect(navigator.sendBeacon).not.toHaveBeenCalled();
|
||||
expect(JSON.parse(window.sessionStorage.getItem(CACHE_KEY)).position.seconds).toBe(150);
|
||||
});
|
||||
|
||||
test('leaving the page sends a final save by beacon', () => {
|
||||
const {result, unmount} = renderHook(() => useFileProgress(PATH));
|
||||
act(() => result.current.report(snapshot));
|
||||
unmount();
|
||||
expect(navigator.sendBeacon).toHaveBeenCalledTimes(1);
|
||||
expect(sent()[0]).toMatchObject({file: PATH, progress: 0.25, final: true});
|
||||
});
|
||||
|
||||
test('hiding the page sends a final save', () => {
|
||||
const {result} = renderHook(() => useFileProgress(PATH));
|
||||
act(() => result.current.report(snapshot));
|
||||
jest.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
|
||||
act(() => document.dispatchEvent(new Event('visibilitychange')));
|
||||
expect(sent()).toEqual([expect.objectContaining({final: true})]);
|
||||
});
|
||||
|
||||
test('a new file saves the old one under its own path, and starts empty', () => {
|
||||
const {result, rerender} = renderHook(({path}) => useFileProgress(path), {initialProps: {path: PATH}});
|
||||
act(() => result.current.report(snapshot));
|
||||
rerender({path: 'videos/next.mp4'});
|
||||
expect(sent()).toEqual([expect.objectContaining({file: PATH, final: true})]);
|
||||
|
||||
// Nothing has been reported for the next file.
|
||||
act(() => jest.advanceTimersByTime(15_000));
|
||||
expect(sent()).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('nothing is sent until something is reported', () => {
|
||||
const {unmount} = renderHook(() => useFileProgress(PATH));
|
||||
act(() => jest.advanceTimersByTime(60_000));
|
||||
unmount();
|
||||
expect(sent()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useMediaProgress', () => {
|
||||
/** A stand-in for the <video> element the handlers receive as `e.currentTarget`. */
|
||||
const media = (props) => ({currentTarget: {duration: 600, currentTime: 0, ...props}});
|
||||
|
||||
test('resumes the saved position when the metadata loads', () => {
|
||||
const fileGroup = {progress: 0.5, position: {kind: 'time', seconds: 300}};
|
||||
const {result} = renderHook(() => useMediaProgress(PATH, fileGroup));
|
||||
const event = media();
|
||||
act(() => result.current.onLoadedMetadata(event));
|
||||
expect(event.currentTarget.currentTime).toBe(300);
|
||||
|
||||
// Only once; a later `loadedmetadata` does not jump back.
|
||||
event.currentTarget.currentTime = 450;
|
||||
act(() => result.current.onLoadedMetadata(event));
|
||||
expect(event.currentTarget.currentTime).toBe(450);
|
||||
});
|
||||
|
||||
test('an explicit start time wins over the saved position', () => {
|
||||
const fileGroup = {progress: 0.5, position: {kind: 'time', seconds: 300}};
|
||||
const {result} = renderHook(() => useMediaProgress(PATH, fileGroup, {startSeconds: 42}));
|
||||
const event = media();
|
||||
act(() => result.current.onLoadedMetadata(event));
|
||||
expect(event.currentTarget.currentTime).toBe(42);
|
||||
});
|
||||
|
||||
test('a finished file starts from the beginning', () => {
|
||||
const {result} = renderHook(() => useMediaProgress(PATH, {progress: 1, position: null}));
|
||||
const event = media();
|
||||
act(() => result.current.onLoadedMetadata(event));
|
||||
expect(event.currentTarget.currentTime).toBe(0);
|
||||
});
|
||||
|
||||
test('pausing saves where the user is; the end saves it finished', () => {
|
||||
const {result} = renderHook(() => useMediaProgress(PATH, null));
|
||||
act(() => result.current.onTimeUpdate(media({currentTime: 120})));
|
||||
act(() => result.current.onPause());
|
||||
act(() => result.current.onEnded());
|
||||
expect(sent()).toEqual([
|
||||
expect.objectContaining({progress: 0.2, position: expect.objectContaining({seconds: 120}), final: true}),
|
||||
expect.objectContaining({progress: 1, position: null, final: true}),
|
||||
]);
|
||||
});
|
||||
|
||||
test('nothing is saved before the duration is known', () => {
|
||||
const {result} = renderHook(() => useMediaProgress(PATH, null));
|
||||
act(() => result.current.onTimeUpdate(media({duration: NaN, currentTime: 3})));
|
||||
act(() => result.current.onPause());
|
||||
expect(sent()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ViewProgress', () => {
|
||||
test.each([[0], [null], [undefined]])('no bar for progress %s', (progress) => {
|
||||
const {container} = render(<ViewProgress progress={progress}/>);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
test('the bar is as wide as the progress', () => {
|
||||
const {getByRole} = render(<ViewProgress progress={0.4}/>);
|
||||
const bar = getByRole('progressbar');
|
||||
expect(bar).toHaveAttribute('aria-valuenow', '40');
|
||||
expect(bar.firstChild).toHaveStyle({width: '40%'});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue