fix(attachments): keep latest requested preview authoritative

This commit is contained in:
cesnimda
2026-11-17 07:54:41 +01:00
parent 3b661d12d7
commit 7830396a2b
2 changed files with 31 additions and 2 deletions
@@ -244,3 +244,29 @@ test('switching application closes and releases its already-open attachment prev
URL.createObjectURL = originalCreate; URL.revokeObjectURL = originalRevoke;
}
});
test.each(['resolve', 'reject'] as const)('older preview %s cannot replace or notify over the latest requested file', async outcome => {
const first = deferred();
const second = deferred();
const other = { ...file, id: 8, fileName: 'Latest.pdf' };
mockedApi.get.mockImplementation((url: any) => url === '/attachments/download/7' ? first.promise : url === '/attachments/download/8' ? second.promise : Promise.resolve({ data: [file, other] }));
const originalCreate = URL.createObjectURL;
const originalRevoke = URL.revokeObjectURL;
URL.createObjectURL = jest.fn(() => 'blob:latest-preview');
URL.revokeObjectURL = jest.fn();
const view = render(page());
try {
fireEvent.click(await screen.findByRole('button', { name: `Preview: ${file.fileName}` }));
fireEvent.click(screen.getByRole('button', { name: `Preview: ${other.fileName}` }));
await act(async () => second.resolve({ data: new Blob(['latest'], { type: 'application/pdf' }) }));
expect(await screen.findByTitle(`Preview: ${other.fileName}`)).toHaveAttribute('src', 'blob:latest-preview');
await act(async () => { if (outcome === 'resolve') first.resolve({ data: new Blob(['obsolete'], { type: 'application/pdf' }) }); else first.reject(new Error('obsolete preview failure')); });
expect(screen.getByTitle(`Preview: ${other.fileName}`)).toHaveAttribute('src', 'blob:latest-preview');
expect(URL.createObjectURL).toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL).not.toHaveBeenCalled();
expect(screen.queryByText(translations.en.attachmentsPreviewFailed)).not.toBeInTheDocument();
} finally {
view.unmount();
URL.createObjectURL = originalCreate; URL.revokeObjectURL = originalRevoke;
}
});
@@ -100,6 +100,7 @@ export default function Attachments({ jobId }: { jobId: number }) {
const [dragActive, setDragActive] = useState(false);
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const previewRequest = useRef(0);
const actionOwner = useRef({ mounted: true, jobId, generation: 0 });
useEffect(() => {
@@ -254,8 +255,10 @@ export default function Attachments({ jobId }: { jobId: number }) {
};
const openPreview = async (a: AttachmentItem) => {
const active = captureAction();
if (!active) return;
const ownerActive = captureAction();
if (!ownerActive) return;
const request = ++previewRequest.current;
const active = () => ownerActive() && previewRequest.current === request;
try {
if (preview?.url) URL.revokeObjectURL(preview.url);
const url = await getBlobUrl(a.id, active);