wrolpi/app/src/components/FilePreview.js
lrnselfreliance 2e0e50c3aa
3D previews load ASCII STLs, stand upright, and fit the preview modal (#952)
* STL files preview with three's own STLLoader

react-stl-viewer inlines a copy of three-stdlib 2.17.2's STLLoader, which reads
ASCII STL text with LoaderUtils.decodeText.  three removed that in r175, so
every ASCII STL preview failed.  The three-stdlib override never reached that
copy, and react-stl-viewer has had no release since January 2024.

The 3MF preview's three.js viewer now previews STL files too, loading each
format with the loader that ships with three, so the loader always matches the
installed three.  react-stl-viewer and the three-stdlib override are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* An e2e spec previews ASCII and binary STL files in a real browser

The STL preview only fails in a browser with WebGL, so the spec opens both
encodings on the live stack and checks the dimensions line appears without a
load error.  fb:reset can now write binary files ({base64: ...}).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STL previews stand Z-up models upright

STLs are Z-up (the 3D printing convention) and three is Y-up, so the
preview rotates STL geometry to stand the model upright, as react-stl-viewer
did.  Model Z reads as Height again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* 3MF previews stand Z-up models upright too

3MF is Z-up like STL, so the rotation moves from the STL loader into the
shared viewer and applies to every model.  Model Z reads as Height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* File previews show their buttons without scrolling

.preview-fit reserved a fixed 18.75rem for the rest of the preview modal,
which was short: every framed preview overflowed a little, and a 3D model's
dimensions line pushed the action buttons below the fold.  The preview modal
now fills its height as a flex column, and the .preview-fit takes whatever
height is left.  Previews without a .preview-fit keep their content's height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* 3D previews frame the model and light it brightly

- The camera fits the model's bounding sphere into the narrower field of view,
  from a raised three-quarter front view, instead of backing off 2.2x along Z.
- A hemisphere light and a headlight that follows the camera (from a little
  above and left) replace lights whose intensities were set before three's
  r155 lighting change and read dim.
- Geometry without normals (3MF) gets creased normals, so flat faces no longer
  shade into their neighbors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 15:33:58 -07:00

712 lines
32 KiB
JavaScript

import React from "react";
import _ from "lodash";
import {TagsSelector} from "../Tags";
import {encodeMediaPath, isSupportedArchive, useLocalStorage} from "./Common";
import {getFile, tagFileGroup, untagFileGroup} from "../api";
import {ArchivePreviewContent} from "./ArchivePreview";
import {CbzViewer} from "./CbzViewer";
import {Button, ButtonGroup, Header, Icon, IconButton, MediaGate, Menu, Modal, toast} from "./ui";
import {useOneQuery} from "../hooks/customHooks";
import {useEpubProgress, useMediaProgress} from "../hooks/useFileProgress";
import {ShareButton} from "./Share";
import {AddToPlaylistButton} from "./AddToPlaylist";
import {pathDirectory} from "./FileBrowser";
import {InlineErrorBoundary} from "./ErrorBoundary";
import {useLocation} from "react-router";
import {ThemeContext} from "../contexts/contexts";
import {isMarkdownFile, MarkdownPreview} from "./MarkdownPreview";
// Routes where file views should not be tracked
const EXCLUDED_TRACKING_ROUTES = [
/^\/videos\/video\//,
/^\/videos\/channel\/[^/]+\/video\//,
/^\/archive\/\d+/
];
function shouldSkipTracking(pathname) {
return EXCLUDED_TRACKING_ROUTES.some(pattern => pattern.test(pathname));
}
function getMediaPathURL(previewFile) {
if (previewFile['primary_path']) {
return `/media/${encodeMediaPath(previewFile['primary_path'])}`;
} else {
return `/media/${encodeMediaPath(previewFile['path'])}`;
}
}
function getDownloadPathURL(previewFile) {
if (previewFile['primary_path']) {
return `/download/${encodeMediaPath(previewFile['primary_path'])}`;
} else {
return `/download/${encodeMediaPath(previewFile['path'])}`;
}
}
// PrusaSlicer is omitted because it only downloads from domains whitelisted by Prusa
// (printables.com, thingiverse.com, cults3d.com), so it cannot fetch from a WROLPi.
// Bambu Studio asks the user to confirm because a WROLPi is not one of its trusted sites.
export const SLICERS = [
{key: 'orcaslicer', text: 'Orca Slicer', scheme: 'orcaslicer'},
{key: 'bambustudio', text: 'Bambu Studio', scheme: 'bambustudio'},
{key: 'cura', text: 'Cura', scheme: 'cura'},
];
export function getSlicerURL(previewFile, scheme) {
// Slicers register their own URL scheme and download the file themselves, so the
// file parameter must be an absolute URL reachable from the user's computer.
const absoluteURL = new URL(getMediaPathURL(previewFile), window.location.origin).href;
return `${scheme}://open?file=${encodeURIComponent(absoluteURL)}`;
}
function OpenInSlicerButton({previewFile}) {
// Browsers cannot report which slicers are installed, so remember the last one used.
const [slicerKey, setSlicerKey] = useLocalStorage('preferredSlicer', SLICERS[0].key);
const slicer = SLICERS.find(s => s.key === slicerKey) || SLICERS[0];
return <ButtonGroup>
<Button color='violet' component='a' href={getSlicerURL(previewFile, slicer.scheme)} icon='cube' size='small'>
Open in {slicer.text}
</Button>
<Menu position='bottom-end' withinPortal>
<Menu.Target>
<IconButton color='violet' icon='dropdown' label='Choose a different slicer' size='small'/>
</Menu.Target>
<Menu.Dropdown>
{SLICERS.map(s =>
<Menu.Item key={s.key}
component='a' href={getSlicerURL(previewFile, s.scheme)}
onClick={(e) => {
// Navigate programmatically so keyboard activation (which may not
// follow the href) still launches the slicer.
if (e) e.preventDefault();
setSlicerKey(s.key);
window.location.assign(getSlicerURL(previewFile, s.scheme));
}}
>
Open in {s.text}
</Menu.Item>)}
</Menu.Dropdown>
</Menu>
</ButtonGroup>
}
function getEpubViewerURL(previewFile) {
let url = previewFile['primary_path'] ?? previewFile['path'];
return `/epub/epub.html?url=/media/${encodeMediaPath(url)}`
}
/*
* The iframe body of a preview.
*
* A component rather than part of `getIframePreviewModal` because it reads the theme: the
* modal builders are plain functions called from an event handler, where hooks cannot run.
*/
export function IframePreview({url, gatePdf, iframeRef}) {
const {isDark, mediaFilterEnabled} = React.useContext(ThemeContext);
/*
* `gatePdf` only for PDFs. Text and the EPUB viewer are documents of our own, which the
* theme's media filter tints; Chrome's PDF viewer is composited out of process and arrives
* in full color however the iframe is styled.
*
* Keyed by `url`, which is load-bearing rather than tidy. The effect that rebuilds a
* preview sets the modal to null and then to the new content in one pass, so React 18
* batches both and reconciles instead of unmounting: the MediaGate fiber survives, and a
* reader who revealed one PDF would get the next one in full color with no prompt -- the
* exact flash this exists to prevent. The key forces a remount per document.
*/
return <MediaGate key={url} gated={!!gatePdf && !!mediaFilterEnabled}>
<div className='preview-fit'>
<iframe title='textModal' src={url} ref={iframeRef}
style={{
height: '100%', width: '100%', border: 'none',
// A same-origin document has no styles of its own; it renders with the
// browser's default stylesheet for whatever color-scheme this element
// declares. Pin the scheme to the theme so text is light-on-dark under
// the dark themes and black-on-white under light, never white-on-white.
backgroundColor: isDark ? 'var(--panel)' : '#ffffff',
colorScheme: isDark ? 'dark' : 'light',
}}/>
</div>
</MediaGate>
}
function getIframePreviewModal(previewFile, url, {gatePdf = false} = {}) {
url = url || getMediaPathURL(previewFile);
return <Modal.Content>
<IframePreview url={url} gatePdf={gatePdf}/>
</Modal.Content>
}
/** The EPUB viewer, opened where the user left off. */
function EpubPreview({previewFile}) {
const path = previewFile.primary_path ?? previewFile.path;
const {iframeRef, resumeCfi} = useEpubProgress(path, previewFile);
let url = getEpubViewerURL(previewFile);
if (resumeCfi) {
url = `${url}&cfi=${encodeURIComponent(resumeCfi)}`;
}
return <Modal.Content>
<IframePreview url={url} iframeRef={iframeRef}/>
</Modal.Content>
}
function getImagePreviewModal(previewFile) {
const path = previewFile.primary_path ?? previewFile.path;
const url = getMediaPathURL(previewFile);
// Get the file name from the absolute path.
const name = path.replace(/^.*[\\\/]/, '');
return <React.Fragment>
<Modal.Header>
{name}
</Modal.Header>
<Modal.Content>
<div className='preview-fit'>
<a href={url}>
<img src={url} alt={name} style={{maxHeight: '100%', maxWidth: '100%', objectFit: 'contain'}}/>
</a>
</div>
</Modal.Content>
</React.Fragment>
}
/** A <video> or <audio> which resumes where the user left off, and saves how far they got. */
function PreviewMediaPlayer({as: Element, previewFile, path, style, children}) {
const progressHandlers = useMediaProgress(path, previewFile);
return <Element controls autoPlay={true} id="player" playsInline={true} style={style} {...progressHandlers}>
{children}
</Element>
}
function getVideoPreviewModal(previewFile) {
const url = getMediaPathURL(previewFile);
const path = previewFile.primary_path ?? previewFile.path;
const name = path.replace(/^.*[\\\/]/, '');
return <React.Fragment>
<Modal.Header>
{name}
</Modal.Header>
<Modal.Content>
<Header as='h5'>{path['path']}</Header>
<div className='preview-fit'>
<PreviewMediaPlayer as='video' previewFile={previewFile} path={path}
style={{maxHeight: '100%', maxWidth: '100%'}}>
<source src={url}/>
</PreviewMediaPlayer>
</div>
</Modal.Content>
</React.Fragment>
}
function getAudioPreviewModal(previewFile) {
const url = getMediaPathURL(previewFile);
const path = previewFile.primary_path ?? previewFile.path;
const name = path.replace(/^.*[\\\/]/, '');
// Some audio files may not have the correct mimetype. Trust the suffix identifies an audio file.
const type = previewFile['mimetype'] !== 'application/octet-stream' ? previewFile['mimetype'] : 'audio/mpeg';
return <React.Fragment>
<Modal.Header>
{name}
</Modal.Header>
<Modal.Content>
<PreviewMediaPlayer as='audio' previewFile={previewFile} path={path}
style={{width: '90%', maxWidth: '95%'}}>
<source src={url} type={type}/>
</PreviewMediaPlayer>
</Modal.Content>
</React.Fragment>
}
// Each 3D format's loader ships with three, so it always matches the installed three. Every
// format is Z-up.
const MODEL_FORMATS = {
'3mf': {
label: '3MF',
loader: async () => new (await import('three/examples/jsm/loaders/3MFLoader.js')).ThreeMFLoader(),
// A 3MF loads as a group of meshes.
toObject: (THREE, group) => group,
},
stl: {
label: 'STL',
loader: async () => new (await import('three/examples/jsm/loaders/STLLoader.js')).STLLoader(),
// An STL loads as a single geometry.
toObject: (THREE, geometry) => new THREE.Mesh(geometry),
},
};
/**
* How far a camera must stand from a sphere of `radius` for the whole sphere to be in view, with
* `margin` to spare. The narrower of the vertical and horizontal fields of view decides: a tall,
* narrow viewer is limited by its width.
*/
export function modelCameraDistance(radius, verticalFovDegrees, aspect, margin = 1.02) {
const halfVertical = (verticalFovDegrees * Math.PI) / 360;
const halfHorizontal = Math.atan(Math.tan(halfVertical) * aspect);
return (radius / Math.sin(Math.min(halfVertical, halfHorizontal))) * margin;
}
function ModelPreviewModal({previewFile, format}) {
const {label, loader: getLoader, toObject} = MODEL_FORMATS[format];
const containerRef = React.useRef(null);
const [dimensions, setDimensions] = React.useState(null);
const [error, setError] = React.useState(null);
const url = getMediaPathURL(previewFile);
const path = previewFile.primary_path ?? previewFile.path;
const name = path.replace(/^.*[\\\/]/, '');
React.useEffect(() => {
// Imperative three.js viewer.
let cancelled = false;
const container = containerRef.current;
if (!container) return;
let renderer, scene, camera, controls, animationId, resizeObserver, loadedGroup;
let THREE;
(async () => {
try {
THREE = await import('three');
const {OrbitControls} = await import('three/examples/jsm/controls/OrbitControls.js');
const {toCreasedNormals} = await import('three/examples/jsm/utils/BufferGeometryUtils.js');
const loader = await getLoader();
if (cancelled) return;
scene = new THREE.Scene();
// Transparent background so the modal/theme color shows through.
const width = container.clientWidth || 1;
const height = container.clientHeight || 1;
camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 10000);
camera.position.set(0, 0, 100);
renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});
renderer.setClearColor(0x000000, 0);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(width, height);
container.appendChild(renderer.domElement);
// Sky above, darker ground below, so top and bottom read differently. The headlight
// follows the camera, so whichever side the user orbits to is lit; it shines from a
// little above and left of the camera so faces turned toward the viewer still shade
// differently.
scene.add(new THREE.HemisphereLight(0xffffff, 0x404040, 2));
const headlight = new THREE.DirectionalLight(0xffffff, 2.5);
scene.add(headlight);
const headlightOffset = new THREE.Vector3();
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
loader.load(
url,
(result) => {
if (cancelled) return;
const group = toObject(THREE, result);
loadedGroup = group;
// STL and 3MF are Z-up (the 3D printing convention) and three is Y-up, so
// stand the model upright: model Z reads as Height, model Y as Length.
group.rotation.x = -Math.PI / 2;
// One violet for every model, so models without authored materials
// are visible against either theme's background.
// Geometry may lack vertex normals (3MF stores none) — compute them so
// MeshPhongMaterial can shade faces instead of rendering flat black.
// Creased: curves are smoothed, but an edge sharper than 30 degrees stays
// sharp, so flat faces do not shade into their neighbors.
group.traverse((obj) => {
if (obj.isMesh) {
if (obj.geometry && !obj.geometry.attributes.normal) {
const creased = toCreasedNormals(obj.geometry, Math.PI / 6);
obj.geometry.dispose();
obj.geometry = creased;
}
obj.material = new THREE.MeshPhongMaterial({
color: 0x7353a8,
flatShading: false,
});
}
});
scene.add(group);
// Frame the model: center it, then view it from the front, raised and a little
// to the right, far enough back that its bounding sphere (every point of it)
// fills the viewer.
const box = new THREE.Box3().setFromObject(group);
const size = new THREE.Vector3();
const center = new THREE.Vector3();
box.getSize(size);
box.getCenter(center);
group.position.sub(center);
const boundingRadius = size.length() / 2 || 1;
const distance = modelCameraDistance(boundingRadius, camera.fov, camera.aspect);
camera.position.set(0.6, 0.5, 1).normalize().multiplyScalar(distance);
camera.near = distance / 100;
camera.far = distance * 100;
camera.updateProjectionMatrix();
controls.target.set(0, 0, 0);
controls.update();
setDimensions({
width: size.x,
height: size.y,
length: size.z,
boundingRadius: size.length() / 2,
});
},
undefined,
(err) => {
console.error(`Failed to load ${label}`, err);
if (!cancelled) setError(`Failed to load ${label} file.`);
},
);
const animate = () => {
animationId = requestAnimationFrame(animate);
controls.update();
headlightOffset.set(-0.4, 0.6, 0).applyQuaternion(camera.quaternion)
.multiplyScalar(camera.position.length());
headlight.position.copy(camera.position).add(headlightOffset);
renderer.render(scene, camera);
};
animate();
resizeObserver = new ResizeObserver(() => {
const w = container.clientWidth || 1;
const h = container.clientHeight || 1;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
});
resizeObserver.observe(container);
} catch (err) {
console.error(`${label} viewer init failed`, err);
if (!cancelled) setError(`Failed to initialize ${label} viewer.`);
}
})();
return () => {
cancelled = true;
if (animationId) cancelAnimationFrame(animationId);
if (resizeObserver) resizeObserver.disconnect();
if (controls) controls.dispose();
if (loadedGroup && THREE) {
loadedGroup.traverse((obj) => {
if (obj.geometry) obj.geometry.dispose();
if (obj.material) {
const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
materials.forEach((m) => {
if (m.map) m.map.dispose();
m.dispose();
});
}
});
}
if (renderer) {
renderer.dispose();
if (renderer.domElement && renderer.domElement.parentNode) {
renderer.domElement.parentNode.removeChild(renderer.domElement);
}
}
};
}, [url, label, getLoader, toObject]);
return <React.Fragment>
<Modal.Header>{name}</Modal.Header>
<Modal.Content>
{dimensions && <div style={{marginBottom: '1em', textAlign: 'center'}}>
<b>Width:</b> {dimensions.width.toFixed(2)}
{' | '}
<b>Height:</b> {dimensions.height.toFixed(2)}
{' | '}
<b>Length:</b> {dimensions.length.toFixed(2)}
{' | '}
<b>Bounding Radius:</b> {dimensions.boundingRadius.toFixed(2)}
{' (model units)'}
</div>}
{error && <div style={{color: 'red', textAlign: 'center'}}>{error}</div>}
<InlineErrorBoundary>
<div className='preview-fit'>
<div ref={containerRef} style={{height: '100%', width: '100%'}}/>
</div>
</InlineErrorBoundary>
</Modal.Content>
</React.Fragment>
}
export function ThreeMFPreviewModal({previewFile}) {
return <ModelPreviewModal previewFile={previewFile} format='3mf'/>;
}
export function STLPreviewModal({previewFile}) {
return <ModelPreviewModal previewFile={previewFile} format='stl'/>;
}
function getGenericPreviewModal(previewFile) {
// No special handler for this file type, just open it.
const path = previewFile.primary_path ?? previewFile.path;
const name = path.replace(/^.*[\\\/]/, '');
return <React.Fragment>
<Modal.Header>{name}</Modal.Header>
</React.Fragment>
}
export const FilePreviewContext = React.createContext({
previewFile: null,
setPreviewFile: null,
previewModal: null,
setPreviewModal: null,
setCallbacks: null,
});
const MAXIMUM_TEXT_SIZE = 5_000_000;
export function FilePreviewProvider({children}) {
// Data about the file that is being previewed.
const [previewFile, setPreviewFile] = React.useState(null);
// A modal is only displayed once we have data about the file.
const [previewModal, setPreviewModal] = React.useState(null);
const [callbacks, setCallbacks] = React.useState(null);
// The file path from the `preview` URL query.
const [previewQuery, setPreviewQuery] = useOneQuery('preview');
const [errorModalOpen, setErrorModalOpen] = React.useState(false);
const location = useLocation();
// The path of the open preview that has been marked viewed. One opening is one view, however
// many times previewFile is replaced while it is open (re-fetching after tagging, for example).
const trackedPathRef = React.useRef(null);
// Determine if tracking should be skipped based on current route
const skipTracking = shouldSkipTracking(location.pathname);
const handleErrorModalClose = () => {
setPreviewQuery(null);
setErrorModalOpen(false);
}
const errorModal = <Modal size='large' open={errorModalOpen}
onClose={handleErrorModalClose}
>
<Modal.Header>Unknown File</Modal.Header>
<Modal.Content>Cannot display preview, no such file exists: {previewQuery}</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={handleErrorModalClose}>Close</Button>
</Modal.Actions>
</Modal>
React.useEffect(() => {
if (!_.isEmpty(previewFile)) {
// Change URL to match the file that is being previewed.
setPreviewQuery(previewFile['primary_path'] || previewFile['path']);
}
}, [previewFile]);
const initPreviewFile = async () => {
// Get simple information about the file, preview the file.
try {
// Not a view; the preview effect marks the file viewed once it is displayed.
const file = await getFile(previewQuery, true);
setPreviewFile(file);
} catch (e) {
console.error(e);
setPreviewModal(errorModal);
setErrorModalOpen(true);
}
}
React.useEffect(() => {
// Navigated to a page which has a file preview active, fetch the information about the file, then display it.
if (previewQuery && !previewFile) {
initPreviewFile();
} else if (!previewQuery && (previewFile || previewModal)) {
// User navigated back/forward and preview query is gone, close the preview.
// Only close if there's actually a preview open (previewFile or previewModal exists).
setPreviewFile(null);
setPreviewModal(null);
}
}, [previewQuery]);
const localFetchFile = async () => {
// Get the file again with its Tags.
const {path, primary_path} = previewFile;
try {
const file = await getFile(primary_path ?? path, true);
setPreviewFile(file);
} finally {
await handleCallbacks();
}
};
const handleClose = (e) => {
if (e) {
e.preventDefault();
}
setPreviewModal(null);
setPreviewFile(null);
setPreviewQuery(null);
}
const handleCallbacks = async () => {
for (const callbacksKey in callbacks) {
try {
await callbacks[callbacksKey]();
} catch (e) {
console.error(e);
}
}
}
const localAddTag = async (name) => {
await tagFileGroup(previewFile, name);
await localFetchFile();
}
const localRemoveTag = async (name) => {
await untagFileGroup(previewFile, name);
await localFetchFile();
}
function setModalContent(content, url, downloadURL, path, taggable = true, extraButtons = null) {
// All action buttons share `size='small'` and `icon` for consistent height across viewports.
// Close is handled by the Modal's close button (X in the top-right corner) — no dedicated button.
const openButton = url
? <Button role='primary' component='a' href={url} size='small' icon='external'>Open</Button>
: null;
const tagsDisplay = taggable ?
<TagsSelector selectedTagNames={previewFile['tags']} onAdd={localAddTag}
onRemove={localRemoveTag}/>
: null;
const downloadButton = downloadURL
? <IconButton color='yellow' component='a' href={downloadURL} size='small' icon='download' label='Download'/>
: null;
const directoryURL = path ? `/files?folders=${encodeURIComponent(pathDirectory(path))}` : null;
const directoryButton = path
? <IconButton component='a' href={directoryURL} size='small' icon='folder' label='Open containing folder'/>
: null;
const pathContent = path ? <Modal.Content>
<pre>{path}</pre>
</Modal.Content>
: null;
console.log('Previewing', path);
console.log('Preview Download URL', downloadURL);
console.log('Preview Open URL', url);
// Single flex toolbar — same button order at every viewport size.
// `flex-wrap: wrap` lets the tags selector drop to a second line on narrow screens
// while the buttons stay together, Open first: [open + file actions] [tags].
setPreviewModal(<Modal size='fullscreen'
open={true}
onClose={e => handleClose(e)}
classNames={{content: 'file-preview-modal-content'}}
>
{pathContent}
<Modal.Actions>
<div className='preview-toolbar'>
<div className='preview-toolbar-group'>
{openButton}
{downloadButton}
{directoryButton}
<ShareButton/>
{extraButtons}
{previewFile && previewFile['id'] &&
<AddToPlaylistButton fileGroupId={previewFile['id']} content={null} size='small'
title='Add to Playlist'/>}
</div>
<div className='preview-toolbar-tags'>{tagsDisplay}</div>
</div>
</Modal.Actions>
{content}
</Modal>);
}
React.useEffect(() => {
setPreviewModal(null);
if (_.isEmpty(previewFile)) {
trackedPathRef.current = null;
}
if (previewFile && !_.isObject(previewFile)) {
console.error(`Unknown previewFile type: ${typeof previewFile}`);
toast({
type: 'error',
title: 'Cannot preview file',
description: 'Cannot preview file',
time: 5000,
});
return;
}
if (previewFile && !_.isEmpty(previewFile)) {
const {mimetype, size, taggable} = previewFile;
const path = previewFile['primary_path'] || previewFile['path'];
console.debug('Previewing file', previewFile);
const lowerPath = path.toLowerCase();
const url = getMediaPathURL(previewFile);
const downloadURL = getDownloadPathURL(previewFile);
if (mimetype.startsWith('text/') && size > MAXIMUM_TEXT_SIZE) {
// Large text files should be downloaded.
window.open(downloadURL);
} else if (isMarkdownFile(mimetype, lowerPath)) {
setModalContent(<Modal.Content><MarkdownPreview url={url}/></Modal.Content>, url, downloadURL, path,
taggable);
} else if (mimetype.startsWith('text/') || mimetype.startsWith('application/json')) {
setModalContent(getIframePreviewModal(previewFile), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('video/')) {
setModalContent(getVideoPreviewModal(previewFile), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('audio/')) {
setModalContent(getAudioPreviewModal(previewFile), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('application/epub')) {
const viewerURL = getEpubViewerURL(previewFile);
setModalContent(<EpubPreview previewFile={previewFile}/>, viewerURL, downloadURL, path, taggable);
} else if (mimetype.startsWith('application/pdf')) {
setModalContent(getIframePreviewModal(previewFile, null, {gatePdf: true}), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('image/')) {
setModalContent(getImagePreviewModal(previewFile), url, null, path, taggable);
} else if (mimetype.startsWith('model/stl')) {
setModalContent(<STLPreviewModal previewFile={previewFile}/>, null, downloadURL, path, taggable,
<OpenInSlicerButton previewFile={previewFile}/>);
} else if (mimetype.startsWith('model/3mf')) {
setModalContent(<ThreeMFPreviewModal previewFile={previewFile}/>, null, downloadURL, path, taggable,
<OpenInSlicerButton previewFile={previewFile}/>);
} else if (mimetype.startsWith('application/octet-stream') && lowerPath.endsWith('.mp3')) {
setModalContent(getAudioPreviewModal(previewFile), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('application/octet-stream') && lowerPath.endsWith('.stl')) {
setModalContent(<STLPreviewModal previewFile={previewFile}/>, null, downloadURL, path, taggable,
<OpenInSlicerButton previewFile={previewFile}/>);
} else if ((mimetype.startsWith('application/octet-stream') || mimetype === 'application/zip')
&& lowerPath.endsWith('.3mf')) {
setModalContent(<ThreeMFPreviewModal previewFile={previewFile}/>, null, downloadURL, path, taggable,
<OpenInSlicerButton previewFile={previewFile}/>);
} else if (mimetype.includes('cbz') || mimetype.includes('cbr') || mimetype.includes('comicbook+zip') || mimetype.includes('comicbook-rar')
|| lowerPath.endsWith('.cbz') || lowerPath.endsWith('.cbr') || lowerPath.endsWith('.cbt') || lowerPath.endsWith('.cb7')) {
setModalContent(<Modal.Content>
<CbzViewer path={path} progressPath={path} fileGroup={previewFile}/>
</Modal.Content>, null, downloadURL, path, taggable);
} else if (isSupportedArchive(mimetype, lowerPath)) {
setModalContent(<ArchivePreviewContent previewFile={previewFile}/>, null, downloadURL, path, taggable);
} else {
// No special handler for this file type, just open it.
setModalContent(getGenericPreviewModal(previewFile), url, downloadURL, path, taggable);
}
// Trigger tracking for the file view (unless on an excluded route)
if (!skipTracking && trackedPathRef.current !== path) {
trackedPathRef.current = path;
getFile(path).catch(e => {
console.error(e);
console.error('Failed to get file to set FileGroup.viewed');
});
}
}
}, [previewFile, skipTracking]);
const value = {previewFile, setPreviewFile, previewModal, setPreviewModal, setCallbacks};
return <FilePreviewContext.Provider value={value}>
{children}
{previewModal}
{errorModal}
</FilePreviewContext.Provider>
}