Video page: the Edit menu owns the transcode Job; polling survives Close and errors

Review fixes.  The transcode Job's id and polling (useJob) move from the
modal to VideoEditMenu, so closing the modal no longer stops the page
from learning the Job finished (and refetching the video, whose path may
have changed).  While a Job runs the menu shows Transcoding..., reopening
shows its progress instead of the form, and Delete waits.  A failed poll
request is retried instead of ending the polling.  getJobs checks the
response like its siblings.  Design narration trimmed from comments.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-09-14 19:39:23 -06:00
parent 42b17ea51b
commit bd6b0012b7
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
4 changed files with 282 additions and 106 deletions

View file

@ -264,6 +264,9 @@ export async function transcodeVideo(fileGroupId, {video_codec = null, audio_cod
export async function getJobs() {
const response = await apiGet(`${API_URI}/jobs`);
if (!response.ok) {
throw new Error(await getErrorMessage(response, 'Unable to get the jobs'));
}
const data = await response.json();
return data['jobs'];
}

View file

@ -385,10 +385,7 @@ export function ThemeSamplePage() {
</div>
<div style={{marginTop: 12}}>
<Header as='h5'>A dropdown of actions</Header>
{/* The video page's Edit button: one labelled button opens a menu of the
rarer actions, so the row stays short. The trailing chevron is what
says "menu" rather than "does the thing"; a disabled item stays listed
so the user learns it exists. */}
{/* Mirrors the video page's Edit control. */}
<Row>
<Menu position='bottom-start' withinPortal>
<Menu.Target>

View file

@ -1,7 +1,9 @@
import React, {useEffect, useRef, useState} from 'react';
import {cancelJob, fetchVideoDownloadDefaults, getJob, transcodeVideo, updateVideo} from '../api';
import {useWROLMode} from '../hooks/customHooks';
import {Button, Confirm, Group, Icon, Menu, Modal, Progress, Select, Stack, Status, Text, Textarea, TextInput, toast} from './ui';
import {
Button, Confirm, Group, Icon, Menu, Modal, Progress, Select, Stack, Status, Text, Textarea, TextInput, toast,
} from './ui';
import {
TRANSCODE_COPY,
transcodeAudioCodecOptions,
@ -9,12 +11,13 @@ import {
transcodeVideoCodecOptions,
} from './Vars';
// How often the modal asks the API about the running Job.
const JOB_POLL_MS = 2000;
const FINISHED_STATUSES = ['complete', 'failed', 'cancelled'];
// Embedded thumbnails are "video" streams to ffprobe, but not codecs a user chooses.
export const FINISHED_STATUSES = ['complete', 'failed', 'cancelled'];
// ffprobe calls an embedded thumbnail a video stream.
const THUMBNAIL_CODECS = ['mjpeg', 'png', 'bmp', 'gif'];
export const isJobFinished = (job) => !!job && FINISHED_STATUSES.includes(job.status);
/** The codec names of a Video's real streams, from the `codec_names`/`codec_types` the API sends. */
export function currentCodecs(video) {
const names = video?.codec_names || [];
@ -38,6 +41,12 @@ export function preferredTarget(preferences, options) {
return TRANSCODE_COPY;
}
/** The container of a video file, when it is one ffmpeg can write for us. */
export function currentContainer(video) {
const suffix = String(video?.video_path || '').split('.').pop().toLowerCase();
return transcodeContainerOptions.some(i => i.value === suffix) ? suffix : null;
}
const statusKind = (status) => {
if (status === 'complete') return 'complete';
if (status === 'running') return 'active';
@ -45,51 +54,68 @@ const statusKind = (status) => {
return 'pending';
}
/** Progress, status and log tail of one Job, polled until it finishes. */
export function JobProgress({jobId, onFinished}) {
/**
* Poll a Job until it finishes. Lives in whichever component must outlive the UI showing the Job:
* the page must learn the Job finished even when the user closed the modal that started it.
*
* A failed request is retried on the next tick; only unmount, a new `jobId`, or a finished status
* stops the polling. `onFinished` is called once per Job.
*/
export function useJob(jobId, onFinished) {
const [job, setJob] = useState(null);
const [cancelling, setCancelling] = useState(false);
const timer = useRef(null);
const finishedRef = useRef(false);
const onFinishedRef = useRef(onFinished);
onFinishedRef.current = onFinished;
useEffect(() => {
finishedRef.current = false;
let cancelled = false;
setJob(null);
if (!jobId) {
return;
}
let stopped = false;
let timer = null;
const poll = async () => {
let latest;
let latest = null;
try {
latest = await getJob(jobId);
} catch (e) {
console.error(e);
return;
}
if (cancelled) return;
setJob(latest);
if (FINISHED_STATUSES.includes(latest.status)) {
if (!finishedRef.current) {
finishedRef.current = true;
if (onFinished) onFinished(latest);
if (stopped) return;
if (latest) {
setJob(latest);
if (isJobFinished(latest)) {
if (onFinishedRef.current) onFinishedRef.current(latest);
return;
}
return;
}
timer.current = window.setTimeout(poll, JOB_POLL_MS);
timer = window.setTimeout(poll, JOB_POLL_MS);
};
poll();
return () => {
cancelled = true;
clearTimeout(timer.current);
stopped = true;
clearTimeout(timer);
};
// Only a new Job restarts polling; `onFinished` may be a fresh closure on every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [jobId]);
const cancel = async () => {
const latest = await cancelJob(jobId);
setJob(latest);
return latest;
};
return {job, cancel};
}
/** Progress, status and log tail of one Job. */
export function JobProgress({job, onCancel}) {
const [cancelling, setCancelling] = useState(false);
const handleCancel = async () => {
setCancelling(true);
try {
const latest = await cancelJob(jobId);
setJob(latest);
await onCancel();
} catch (e) {
console.error(e);
} finally {
@ -101,14 +127,14 @@ export function JobProgress({jobId, onFinished}) {
return <Progress indeterminate showPercent={false} label='Starting...'/>;
}
const finished = FINISHED_STATUSES.includes(job.status);
const finished = isJobFinished(job);
const percent = job.progress ?? 0;
const logTail = (job.log || []).slice(-8);
return <Stack gap='sm'>
<Group justify='space-between' wrap='wrap'>
<Status kind={statusKind(job.status)}>{job.status}</Status>
{!finished && <Button
{!finished && onCancel && <Button
role='danger'
size='small'
icon='stop'
@ -143,25 +169,19 @@ export function JobProgress({jobId, onFinished}) {
}
/**
* Choose target codecs for one Video, queue the transcode Job, then watch it.
* Choose target codecs for one Video and queue the transcode Job, or show the Job already
* queued for it. The Job itself is owned by the parent (`useJob`), so closing this modal does not
* stop the page from learning when it finishes.
*
* The selects start at the user's preferred codecs from the Videos settings (the same preference
* lists the downloader honors), so the common case is a glance and a click.
* The selects start at the user's preferred codecs from the Videos settings.
*/
/** The container of a video file, when it is one ffmpeg can write for us. */
export function currentContainer(video) {
const suffix = String(video?.video_path || '').split('.').pop().toLowerCase();
return transcodeContainerOptions.some(i => i.value === suffix) ? suffix : null;
}
export function TranscodeModal({open, onClose, fileGroupId, video, onComplete}) {
export function TranscodeModal({open, onClose, fileGroupId, video, job, jobId, onQueued, onCancelJob}) {
const wrolModeEnabled = useWROLMode();
const [videoCodec, setVideoCodec] = useState(TRANSCODE_COPY);
const [audioCodec, setAudioCodec] = useState(TRANSCODE_COPY);
const [container, setContainer] = useState('mp4');
const [defaultsLoaded, setDefaultsLoaded] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [jobId, setJobId] = useState(null);
const current = currentCodecs(video);
@ -169,10 +189,7 @@ export function TranscodeModal({open, onClose, fileGroupId, video, onComplete})
if (!open) {
return;
}
// Each opening starts over: a finished Job's progress must not linger on the next open.
setJobId(null);
setDefaultsLoaded(false);
// Start from the file's own container so a codec-only change keeps it.
setContainer(currentContainer(video) || 'mp4');
let stale = false;
const load = async () => {
@ -193,7 +210,6 @@ export function TranscodeModal({open, onClose, fileGroupId, video, onComplete})
};
}, [open]);
// Both streams kept: a remux. Cheap, and it fixes the container (or adds fast start).
const remuxOnly = videoCodec === TRANSCODE_COPY && audioCodec === TRANSCODE_COPY;
const sameContainer = container === currentContainer(video);
@ -205,7 +221,7 @@ export function TranscodeModal({open, onClose, fileGroupId, video, onComplete})
audio_codec: audioCodec === TRANSCODE_COPY ? null : audioCodec,
container,
});
setJobId(id);
onQueued(id);
} catch (e) {
// transcodeVideo already toasted.
console.error(e);
@ -214,14 +230,9 @@ export function TranscodeModal({open, onClose, fileGroupId, video, onComplete})
}
};
const handleFinished = (job) => {
if (job.status === 'complete') {
toast({type: 'success', title: 'Transcode complete', description: job.description, time: 5000});
if (onComplete) onComplete(job);
}
};
const describe = (codecs) => codecs.length ? codecs.join(', ') : 'unknown';
// A queued or finished Job replaces the form until the parent forgets it.
const showJob = !!jobId;
return <Modal open={open} onClose={onClose} size='small'>
<Modal.Header>Transcode Video</Modal.Header>
@ -232,7 +243,7 @@ export function TranscodeModal({open, onClose, fileGroupId, video, onComplete})
Streams set to Keep are copied without re-encoding. Transcoding is slow and slightly
reduces quality; the original file is replaced when it finishes.
</Text>
{!jobId && <>
{!showJob && <>
<Select
label='Video codec'
data={transcodeVideoCodecOptions}
@ -262,12 +273,12 @@ export function TranscodeModal({open, onClose, fileGroupId, video, onComplete})
: `Both streams are kept: only the container changes to ${container} (a quick remux, no quality loss).`}
</Text>}
</>}
{jobId && <JobProgress jobId={jobId} onFinished={handleFinished}/>}
{showJob && <JobProgress job={job} onCancel={onCancelJob}/>}
</Stack>
</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={onClose}>{jobId ? 'Close' : 'Cancel'}</Button>
{!jobId && <Button
<Button role='cancel' onClick={onClose}>{showJob ? 'Close' : 'Cancel'}</Button>
{!showJob && <Button
role='primary'
icon='film'
onClick={handleStart}
@ -367,19 +378,51 @@ export function EditVideoModal({open, onClose, fileGroupId, videoFile, descripti
}
/**
* The "Edit" dropdown on the Video page: Refresh (re-download metadata), Transcode, and Delete.
* The "Edit" dropdown on the Video page: Edit, Refresh, Transcode, Delete.
*
* `onRefresh` is awaited; `onTranscodeComplete` is called after the file was replaced so the
* page can fetch the Video again (its path and codecs changed). `onDelete` is awaited after the
* user confirms; the page decides what happens next (navigate away, or the tagged-files prompt).
* Owns the active transcode Job for this video, so the page hears about its completion whether or
* not the modal is open, and a second transcode cannot be queued while one is running.
*/
export function VideoEditMenu({videoFile, video, description, onRefresh, onTranscodeComplete, onDelete, onSaved}) {
export function VideoEditMenu({
videoFile, video, description, onRefresh, onTranscodeComplete, onDelete, onSaved,
initialJobId = null,
}) {
const wrolModeEnabled = useWROLMode();
const [editOpen, setEditOpen] = useState(false);
const [transcodeOpen, setTranscodeOpen] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
// `initialJobId`: resume watching a Job already queued for this video (tests use it too).
const [jobId, setJobId] = useState(initialJobId);
const handleJobFinished = (finished) => {
if (finished.status === 'complete') {
toast({type: 'success', title: 'Transcode complete', description: finished.description, time: 5000});
if (onTranscodeComplete) onTranscodeComplete(finished);
}
if (!transcodeOpen) {
// Nobody is looking at the result; make room for the next transcode.
setJobId(null);
}
};
const {job, cancel} = useJob(jobId, handleJobFinished);
// Another video: its transcodes are its own.
const firstVideoId = useRef(videoFile?.id);
useEffect(() => {
if (videoFile?.id !== firstVideoId.current) {
firstVideoId.current = videoFile?.id;
setJobId(null);
}
}, [videoFile?.id]);
const handleTranscodeClose = () => {
setTranscodeOpen(false);
if (isJobFinished(job)) {
setJobId(null);
}
};
const handleDelete = async () => {
setDeleting(true);
@ -401,6 +444,7 @@ export function VideoEditMenu({videoFile, video, description, onRefresh, onTrans
};
const isVideo = !!videoFile?.mimetype?.startsWith('video/');
const transcoding = !!jobId && !isJobFinished(job);
return <>
<Menu position='bottom-start' withinPortal>
@ -425,21 +469,31 @@ export function VideoEditMenu({videoFile, video, description, onRefresh, onTrans
<Menu.Item
leftSection={<Icon name='film'/>}
onClick={() => setTranscodeOpen(true)}
disabled={!isVideo || !!wrolModeEnabled}
disabled={!isVideo || (!!wrolModeEnabled && !transcoding)}
>
Transcode...
{transcoding ? 'Transcoding...' : 'Transcode...'}
</Menu.Item>
<Menu.Divider/>
<Menu.Item
color='var(--danger)'
leftSection={<Icon name='trash'/>}
onClick={() => setDeleteOpen(true)}
disabled={!onDelete || !!wrolModeEnabled}
disabled={!onDelete || !!wrolModeEnabled || transcoding}
>
Delete...
</Menu.Item>
</Menu.Dropdown>
</Menu>
<TranscodeModal
open={transcodeOpen}
onClose={handleTranscodeClose}
fileGroupId={videoFile?.id}
video={video}
job={job}
jobId={jobId}
onQueued={setJobId}
onCancelJob={cancel}
/>
<EditVideoModal
open={editOpen}
onClose={() => setEditOpen(false)}
@ -460,12 +514,5 @@ export function VideoEditMenu({videoFile, video, description, onRefresh, onTrans
Are you sure you want to delete this video? All files related to this video will be deleted.
It will not be downloaded again!
</Confirm>
<TranscodeModal
open={transcodeOpen}
onClose={() => setTranscodeOpen(false)}
fileGroupId={videoFile?.id}
video={video}
onComplete={onTranscodeComplete}
/>
</>
}

View file

@ -2,7 +2,8 @@ import React from 'react';
import {act, fireEvent, screen, waitFor} from '@testing-library/react';
import {renderWithProviders} from '../test-utils';
import {
currentCodecs, currentContainer, EditVideoModal, JobProgress, preferredTarget, TranscodeModal, VideoEditMenu,
currentCodecs, currentContainer, EditVideoModal, JobProgress, preferredTarget, TranscodeModal, useJob,
VideoEditMenu,
} from './VideoEditMenu';
import {TRANSCODE_COPY, transcodeAudioCodecOptions, transcodeVideoCodecOptions} from './Vars';
@ -34,6 +35,8 @@ const pendingJob = {
id: 'transcode_video-abc', status: 'pending', progress: null, log: [], error: null, cancel_requested: false,
description: 'Transcode movie.webm',
};
const runningJob = {...pendingJob, status: 'running', progress: 40, log: ['out_time_us=1']};
const completeJob = {...pendingJob, status: 'complete', progress: 100, log: ['done']};
describe('helpers', () => {
test('currentCodecs ignores embedded thumbnail streams', () => {
@ -62,11 +65,13 @@ describe('TranscodeModal', () => {
jest.clearAllMocks();
fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: ['h264'], audio_codecs: ['vorbis', 'aac']});
transcodeVideo.mockResolvedValue('transcode_video-abc');
getJob.mockResolvedValue(pendingJob);
});
test('pre-populates from the preferred codecs and queues the Job', async () => {
renderWithProviders(<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video}/>);
const onQueued = jest.fn();
renderWithProviders(
<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video} onQueued={onQueued}/>,
);
expect(screen.getByText(/Current codecs: video vp9, audio opus/)).toBeInTheDocument();
@ -80,16 +85,26 @@ describe('TranscodeModal', () => {
await waitFor(() => expect(transcodeVideo).toHaveBeenCalledWith(7, {
video_codec: 'h264', audio_codec: 'aac', container: 'mp4',
}));
// The form is replaced by the Job's progress.
await waitFor(() => expect(getJob).toHaveBeenCalledWith('transcode_video-abc'));
await waitFor(() => expect(onQueued).toHaveBeenCalledWith('transcode_video-abc'));
});
test('shows the Job instead of the form once one is queued', () => {
renderWithProviders(
<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video}
jobId='transcode_video-abc' job={runningJob} onCancelJob={jest.fn()}/>,
);
expect(screen.queryAllByLabelText('Video codec')).toHaveLength(0);
expect(await screen.findByText('pending')).toBeInTheDocument();
expect(screen.getByText('running')).toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Close'})).toBeInTheDocument();
expect(screen.queryByRole('button', {name: /Transcode/})).not.toBeInTheDocument();
});
test('keeping every stream is a remux into the chosen container', async () => {
fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: [], audio_codecs: []});
// A webm cannot be kept (not a container we write), so the select starts at mp4: a change.
renderWithProviders(<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video}/>);
renderWithProviders(
<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video} onQueued={jest.fn()}/>,
);
await waitFor(() => expect(selectInput('Container')).toHaveValue('mp4'));
expect(await screen.findByText(/only the container changes to mp4/)).toBeInTheDocument();
@ -190,7 +205,23 @@ describe('EditVideoModal', () => {
});
});
describe('JobProgress', () => {
// A tiny harness so the hook can be driven like the menu drives it.
function JobHarness({jobId, onFinished}) {
const {job, cancel} = useJob(jobId, onFinished);
return <JobProgress job={job} onCancel={cancel}/>;
}
// Let pending promise callbacks run (a settled request schedules its next poll), then advance
// the fake clock past the poll interval.
const nextPoll = async () => {
await act(async () => {
await Promise.resolve();
await Promise.resolve();
jest.advanceTimersByTime(2000);
});
};
describe('useJob + JobProgress', () => {
beforeEach(() => {
jest.clearAllMocks();
jest.useFakeTimers();
@ -202,11 +233,9 @@ describe('JobProgress', () => {
test('polls until the Job finishes, then reports once', async () => {
const onFinished = jest.fn();
getJob
.mockResolvedValueOnce({...pendingJob, status: 'running', progress: 40, log: ['out_time_us=1']})
.mockResolvedValueOnce({...pendingJob, status: 'complete', progress: 100, log: ['done']});
getJob.mockResolvedValueOnce(runningJob).mockResolvedValueOnce(completeJob);
renderWithProviders(<JobProgress jobId='transcode_video-abc' onFinished={onFinished}/>);
renderWithProviders(<JobHarness jobId='transcode_video-abc' onFinished={onFinished}/>);
await waitFor(() => expect(screen.getByText('running')).toBeInTheDocument());
expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '40');
@ -225,11 +254,36 @@ describe('JobProgress', () => {
expect(screen.queryByRole('button', {name: 'Cancel'})).not.toBeInTheDocument();
});
test('a failed request is retried instead of ending the polling', async () => {
getJob
.mockRejectedValueOnce(new Error('network'))
.mockResolvedValueOnce(runningJob)
.mockRejectedValueOnce(new Error('network'))
.mockResolvedValueOnce(completeJob);
const onFinished = jest.fn();
renderWithProviders(<JobHarness jobId='transcode_video-abc' onFinished={onFinished}/>);
// First poll failed: still "Starting...", but another poll is scheduled.
await waitFor(() => expect(getJob).toHaveBeenCalledTimes(1));
expect(screen.getByText('Starting...')).toBeInTheDocument();
await nextPoll();
await waitFor(() => expect(screen.getByText('running')).toBeInTheDocument());
// A failure mid-way keeps the last good state and keeps polling.
await nextPoll();
await waitFor(() => expect(getJob).toHaveBeenCalledTimes(3));
expect(screen.getByText('running')).toBeInTheDocument();
await nextPoll();
await waitFor(() => expect(screen.getByText('complete')).toBeInTheDocument());
expect(onFinished).toHaveBeenCalledTimes(1);
});
test('Cancel asks the API to cancel the Job', async () => {
getJob.mockResolvedValue({...pendingJob, status: 'running', progress: 10});
cancelJob.mockResolvedValue({...pendingJob, status: 'running', progress: 10, cancel_requested: true});
renderWithProviders(<JobProgress jobId='transcode_video-abc'/>);
renderWithProviders(<JobHarness jobId='transcode_video-abc'/>);
await waitFor(() => expect(screen.getByRole('button', {name: 'Cancel'})).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
@ -241,7 +295,7 @@ describe('JobProgress', () => {
test('shows the error of a failed Job', async () => {
getJob.mockResolvedValue({...pendingJob, status: 'failed', error: 'ffmpeg exited with 1', log: ['boom']});
renderWithProviders(<JobProgress jobId='transcode_video-abc'/>);
renderWithProviders(<JobHarness jobId='transcode_video-abc'/>);
await waitFor(() => expect(screen.getByText('failed')).toBeInTheDocument());
expect(screen.getByText('ffmpeg exited with 1')).toBeInTheDocument();
@ -251,22 +305,46 @@ describe('JobProgress', () => {
describe('VideoEditMenu', () => {
beforeEach(() => {
jest.clearAllMocks();
fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: [], audio_codecs: []});
fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: ['h264'], audio_codecs: ['aac']});
transcodeVideo.mockResolvedValue('transcode_video-abc');
});
// Mantine's Menu in jsdom: after a modal has closed, the first click on the target can land
// while the dropdown still counts as open (and so toggles it shut). Click until items show.
const openMenu = async () => {
for (let attempt = 0; attempt < 3; attempt++) {
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
try {
return await screen.findByRole('menuitem', {name: /Refresh/}, {timeout: 300});
} catch (e) {
// Toggled shut; try again.
}
}
throw new Error('The Edit menu did not open');
};
const openMenuItem = async (name) => {
await openMenu();
fireEvent.click(screen.getByRole('menuitem', {name}));
};
test('Refresh calls onRefresh; Transcode opens the modal', async () => {
const onRefresh = jest.fn().mockResolvedValue(undefined);
renderWithProviders(<VideoEditMenu videoFile={videoFile} video={video} onRefresh={onRefresh}/>);
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
fireEvent.click(await screen.findByRole('menuitem', {name: /Refresh/}));
await openMenuItem(/Refresh/);
await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
fireEvent.click(await screen.findByRole('menuitem', {name: /Transcode/}));
await openMenuItem(/Transcode/);
await waitFor(() => expect(screen.getByText('Transcode Video')).toBeInTheDocument());
});
test('Edit opens the details modal', async () => {
renderWithProviders(<VideoEditMenu videoFile={videoFile} video={video} onRefresh={jest.fn()}/>);
await openMenuItem(/^Edit/);
expect(await screen.findByText('Edit Video')).toBeInTheDocument();
expect(screen.getByLabelText('Title')).toHaveValue('Old Title');
});
test('Refresh is unavailable without a URL, Transcode for non-video files', async () => {
const audioFile = {...videoFile, url: null, mimetype: 'audio/mpeg'};
renderWithProviders(<VideoEditMenu videoFile={audioFile} video={video} onRefresh={jest.fn()}/>);
@ -289,22 +367,13 @@ describe('VideoEditMenu', () => {
expect(screen.getByRole('menuitem', {name: /^Edit/})).toBeDisabled();
});
test('Edit opens the details modal', async () => {
renderWithProviders(<VideoEditMenu videoFile={videoFile} video={video} onRefresh={jest.fn()}/>);
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
fireEvent.click(await screen.findByRole('menuitem', {name: /^Edit/}));
expect(await screen.findByText('Edit Video')).toBeInTheDocument();
expect(screen.getByLabelText('Title')).toHaveValue('Old Title');
});
test('Delete asks for confirmation before calling onDelete', async () => {
const onDelete = jest.fn().mockResolvedValue(undefined);
renderWithProviders(
<VideoEditMenu videoFile={videoFile} video={video} onRefresh={jest.fn()} onDelete={onDelete}/>,
);
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
fireEvent.click(await screen.findByRole('menuitem', {name: /Delete/}));
await openMenuItem(/Delete/);
expect(await screen.findByText('Delete video?')).toBeInTheDocument();
expect(onDelete).not.toHaveBeenCalled();
@ -318,12 +387,72 @@ describe('VideoEditMenu', () => {
<VideoEditMenu videoFile={videoFile} video={video} onRefresh={jest.fn()} onDelete={onDelete}/>,
);
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
fireEvent.click(await screen.findByRole('menuitem', {name: /Delete/}));
await openMenuItem(/Delete/);
expect(await screen.findByText('Delete video?')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
await waitFor(() => expect(screen.queryByText('Delete video?')).not.toBeInTheDocument());
expect(onDelete).not.toHaveBeenCalled();
});
test('closing the modal keeps watching the Job and reports completion to the page', async () => {
jest.useFakeTimers();
try {
getJob.mockResolvedValueOnce(runningJob).mockResolvedValueOnce(completeJob);
const onTranscodeComplete = jest.fn();
renderWithProviders(
<VideoEditMenu videoFile={videoFile} video={video} onRefresh={jest.fn()} onDelete={jest.fn()}
onTranscodeComplete={onTranscodeComplete}/>,
);
await openMenuItem(/Transcode/);
await waitFor(() => expect(selectInput('Video codec')).toHaveValue('h264 (avc1)'));
fireEvent.click(screen.getByRole('button', {name: 'Transcode'}));
await waitFor(() => expect(screen.getByText('running')).toBeInTheDocument());
// Close while it runs. The modal is gone but the Job is still watched.
fireEvent.click(screen.getByRole('button', {name: 'Close'}));
await waitFor(() => expect(screen.queryByText('Transcode Video')).not.toBeInTheDocument());
await nextPoll();
await waitFor(() => expect(onTranscodeComplete).toHaveBeenCalledTimes(1));
expect(onTranscodeComplete.mock.calls[0][0].status).toBe('complete');
expect(getJob).toHaveBeenCalledTimes(2);
} finally {
jest.useRealTimers();
}
});
test('while a Job runs, Transcode shows its progress and Delete waits', async () => {
getJob.mockResolvedValue(runningJob);
renderWithProviders(
<VideoEditMenu videoFile={videoFile} video={video} onRefresh={jest.fn()} onDelete={jest.fn()}
initialJobId='transcode_video-abc'/>,
);
await waitFor(() => expect(getJob).toHaveBeenCalled());
await openMenu();
expect(screen.getByRole('menuitem', {name: 'Transcoding...'})).toBeEnabled();
expect(screen.getByRole('menuitem', {name: /Delete/})).toBeDisabled();
fireEvent.click(screen.getByRole('menuitem', {name: 'Transcoding...'}));
expect(await screen.findByText('running')).toBeInTheDocument();
expect(screen.queryAllByLabelText('Video codec')).toHaveLength(0);
expect(transcodeVideo).not.toHaveBeenCalled();
});
test('a Job that finished unwatched is forgotten, so the next open offers the form', async () => {
getJob.mockResolvedValue(completeJob);
renderWithProviders(
<VideoEditMenu videoFile={videoFile} video={video} onRefresh={jest.fn()} onDelete={jest.fn()}
initialJobId='transcode_video-abc'/>,
);
await waitFor(() => expect(getJob).toHaveBeenCalled());
await openMenu();
expect(await screen.findByRole('menuitem', {name: 'Transcode...'})).toBeEnabled();
expect(screen.getByRole('menuitem', {name: /Delete/})).toBeEnabled();
fireEvent.click(screen.getByRole('menuitem', {name: 'Transcode...'}));
await waitFor(() => expect(selectInput('Video codec')).toBeInTheDocument());
});
});