import React, {useContext, useState} from "react";
import {useHotkeys} from "react-hotkeys-hook";
import {
CardContent,
CardDescription,
CardHeader,
CardMeta,
Container,
Form,
GridColumn,
GridRow,
Image,
Input,
PlaceholderHeader,
PlaceholderLine,
StatisticLabel,
StatisticValue,
TableCell,
TextArea,
} from "semantic-ui-react";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {
APIButton,
BackButton,
CardLink,
DirectoryLink,
encodeMediaPath,
ErrorMessage,
ExternalCardLink,
FileIcon,
findPosterPath,
humanFileSize,
humanNumber,
InfoHeader,
isoDatetimeToAgoPopup,
mimetypeColor,
PageContainer,
PreviewPath,
resolveDataPath,
SearchInput,
SortButton,
TabLinks,
textEllipsis,
useTitle
} from "./Common";
import {
deleteArchives,
deleteDomain,
fetchArchiveBrowsers,
fetchArchiveDownloaderConfig,
generateArchiveScreenshot,
getCollectionTagInfo,
postArchiveFileFormat,
postDownload,
previewBatchReorganization,
refreshDomain,
tagDomain,
tagFileGroup,
untagFileGroup,
updateArchiveDownloaderConfig,
} from "../api";
import {InputForm, useForm} from "../hooks/useForm";
import {CollectionTagModal} from "./collections/CollectionTagModal";
import {CollectionReorganizeModal} from "./collections/CollectionReorganizeModal";
import {BatchReorganizeModal} from "./collections/BatchReorganizeModal";
import {useReorganizationStatus} from "../contexts/FileWorkerStatusContext";
import {Link, Route, Routes, useLocation, useNavigate, useParams} from "react-router";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {
useArchive,
useArchiveStatistics,
useDockerized,
useDomain,
useDomains,
useOneQuery,
useSearchArchives,
useSearchDomain,
useSearchOrder
} from "../hooks/customHooks";
import {FileCards, FileRowTagIcon, FilesView} from "./Files";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import _ from "lodash";
import {Media, ThemeContext} from "../contexts/contexts";
import {Button, Card, darkTheme, Header, Loader, Placeholder, Popup, Segment, Statistic, Tab} from "./Theme";
import {BulkTagModal} from "./BulkTagModal";
import {taggedImageLabel, TagsSelector} from "../Tags";
import {toast} from "react-semantic-toasts-2";
import {API_ARCHIVE_UPLOAD_URI, Downloaders} from "./Vars";
import {CollectionTable} from "./collections/CollectionTable";
import {CollectionEditForm} from "./collections/CollectionEditForm";
import {RecurringDownloadsTable} from "./admin/Downloads";
import {DestinationForm} from "./Download";
function ArchivePage() {
const navigate = useNavigate();
const {fileGroupId} = useParams();
const {archiveFile, history, fetchArchive} = useArchive(fileGroupId);
const {theme} = useContext(ThemeContext);
let title = archiveFile ? archiveFile.title ? archiveFile.title : archiveFile.name : null;
useTitle(title);
if (archiveFile === null) {
return ;
}
if (archiveFile === undefined) {
return <>
This archive does not exist
>
}
const {data, size, directory} = archiveFile;
// Resolve data paths (filename-only) to full relative paths using directory
const singlefilePath = resolveDataPath(data.singlefile_path, directory);
const readabilityPath = resolveDataPath(data.readability_path, directory);
const screenshotPath = resolveDataPath(data.screenshot_path, directory);
const singlefileUrl = singlefilePath ? `/media/${encodeMediaPath(singlefilePath)}` : null;
const readabilityUrl = readabilityPath ? `/media/${encodeMediaPath(readabilityPath)}` : null;
const screenshotUrl = screenshotPath ? `/media/${encodeMediaPath(screenshotPath)}` : null;
const singlefileButton =
;
const readButton =
const screenshot = screenshotUrl ?
:
null;
const localDeleteArchive = async () => {
await deleteArchives([archiveFile.id]);
toast({
type: 'success',
title: 'Archive Deleted',
description: 'Archive was successfully deleted.',
time: 2000,
})
navigate(-1);
}
const localUpdateArchive = async () => {
const downloadData = {urls: [archiveFile.url], downloader: Downloaders.Archive};
const response = await postDownload(downloadData);
if (response.ok) {
toast({
type: 'success',
title: 'Archive Downloading',
description: 'Archive update has been scheduled.',
time: 2000,
});
}
}
const localGenerateScreenshot = async () => {
const success = await generateArchiveScreenshot(archiveFile.id);
if (success) {
// Refresh the archive data after a short delay to show the new screenshot
setTimeout(() => fetchArchive(), 2000);
}
}
const updateButton =
Update
;
const deleteButton =
Delete
;
const generateScreenshotButton = !screenshotUrl ?
Generate Screenshot
: null;
let historyList = ;
if (history && history.length === 0) {
historyList =
No history available
;
} else if (history) {
historyList = ;
}
const domain = data.domain ? data.domain : null;
let domainHeader = Unknown
;
if (domain) {
const domainUrl = `/archives?domain=${domain}`;
domainHeader = ;
}
const localAddTag = async (name) => {
await tagFileGroup(archiveFile, name);
await fetchArchive();
}
const localRemoveTag = async (name) => {
await untagFileGroup(archiveFile, name);
await fetchArchive();
}
const downloadDatetimeString = archiveFile.download_datetime ?
isoDatetimeToAgoPopup(archiveFile.download_datetime, true) : 'unknown';
const publishedDatetimeString = archiveFile.published_datetime ?
isoDatetimeToAgoPopup(archiveFile.published_datetime, true) : 'unknown';
const modifiedDatetimeString = archiveFile.published_modified_datetime
? isoDatetimeToAgoPopup(archiveFile.published_modified_datetime, true)
: 'unknown';
const aboutPane = {
menuItem: 'About', render: () =>
{domainHeader}
{humanFileSize(size)}
{archiveFile.url ? {archiveFile.url} : 'N/A'}
{modifiedDatetimeString}
};
// Helper to find file size from the files array by resolved path
const findFileSize = (resolvedPath) => {
if (!resolvedPath || !archiveFile.files) return null;
const file = archiveFile.files.find(i => String(i.path) === String(resolvedPath));
return file && file.size
? ({humanFileSize(file.size)})
: null;
};
// Helper to resolve and preview a data path
const localPreviewPath = (dataPath, mimetype) => {
const resolvedPath = resolveDataPath(dataPath, directory);
if (resolvedPath) {
return <>{resolvedPath} {findFileSize(resolvedPath)}>
} else {
return 'Unknown'
}
}
const tableStyle = {width: '100%', borderCollapse: 'separate', borderSpacing: '0 0.7em'};
const labelStyle = {whiteSpace: 'nowrap', paddingRight: '1.5em', verticalAlign: 'top'};
const filesPane = {
menuItem: 'Files', render: () =>
Singlefile File
{localPreviewPath(data.singlefile_path, 'text/html')}
Readability File
{localPreviewPath(data.readability_path, 'text/html')}
Readability Text File
{localPreviewPath(data.readability_txt_path, 'text/plain')}
Readability JSON File
{localPreviewPath(data.readability_json_path, 'application/json')}
Screenshot File
{screenshotPath
? <>{screenshotPath} {findFileSize(screenshotPath)}>
: 'Unknown'}
Directory
};
const tabPanes = [aboutPane, filesPane];
const tabMenu = theme === darkTheme ? {inverted: true, attached: true} : {attached: true};
return <>
{screenshot}
{textEllipsis(archiveFile.title || data.url)}
Author: {archiveFile.author ? archiveFile.author : 'unknown'}
Published: {publishedDatetimeString}
Downloaded: {downloadDatetimeString}
{singlefileButton}
{readButton}
{updateButton}
{deleteButton}
{generateScreenshotButton}
{historyList}
>
}
export function ArchiveCard({file}) {
const {s} = useContext(ThemeContext);
const {sort} = useSearchOrder();
const sortField = sort ? sort.replace(/^-/, '') : null;
const {data, directory} = file;
// Resolve data paths (filename-only) to full relative paths using directory
const screenshotPath = resolveDataPath(data.screenshot_path, directory);
const singlefilePath = resolveDataPath(data.singlefile_path, directory);
const imageSrc = screenshotPath ? `/media/${encodeMediaPath(screenshotPath)}` : null;
const singlefileUrl = singlefilePath ? `/media/${encodeMediaPath(singlefilePath)}` : null;
let screenshot = ;
const imageLabel = file.tags && file.tags.length ? taggedImageLabel : null;
if (imageSrc) {
screenshot = ;
}
const domain = data ? data.domain : null;
const domainUrl = `/archives?domain=${domain}`;
const title = file.title || data.url;
const header = {title} ;
const dt = file.published_datetime || file.published_modified_datetime || file.modified;
return
{screenshot}
{domain &&
{domain}
}
{sortField === 'published_modified_datetime'
? isoDatetimeToAgoPopup(file.published_modified_datetime, false)
: sortField === 'download_datetime'
? isoDatetimeToAgoPopup(file.download_datetime, false)
: sortField === 'size'
? humanFileSize(file.size)
: sortField === 'viewed'
? isoDatetimeToAgoPopup(file.viewed, false)
: isoDatetimeToAgoPopup(dt, false)
}
}
// Domain table column configuration
const DOMAIN_COLUMNS = [
{key: 'domain', label: 'Domain', sortable: true, width: 7},
{key: 'tag_name', label: 'Tag', sortable: true, width: 2},
{key: 'archive_count', label: 'Archives', sortable: true, align: 'right', width: 2},
{
key: 'min_download_frequency',
label: 'Download Frequency',
sortable: true,
format: 'frequency',
width: 2,
hideOnMobile: true
},
{key: 'size', label: 'Size', sortable: true, align: 'right', format: 'bytes', width: 2, hideOnMobile: true},
{key: 'actions', label: 'Manage', sortable: false, type: 'actions', width: 1}
];
const DOMAIN_ROUTES = {
list: '/archives/domains',
edit: '/archives/domain/:id/edit',
search: '/archives',
searchParam: 'domain'
};
function DomainStatistics({statistics}) {
if (!statistics) {
return <>>
}
return
{statistics.archive_count}
Archives
{humanFileSize(statistics.size, true)}
Total Size
{humanFileSize(statistics.largest_archive, true)}
Largest Archive
{humanNumber(statistics.archive_tags)}
Archive Tags
}
export function DomainsPage() {
useTitle('Archive Domains');
const [domains] = useDomains();
const [searchStr, setSearchStr] = useOneQuery('domain');
const searchInputRef = React.useRef();
useHotkeys('f', (e) => {
e.preventDefault();
if (searchInputRef.current) {
searchInputRef.current.focus();
}
}, {enableOnFormTags: false});
// Header section matching ChannelsPage pattern
const header =
setSearchStr('')}
onChange={setSearchStr}
onSubmit={null}
inputRef={searchInputRef}
/>
{/* No "New Domain" button - domains are auto-created */}
;
// Empty state
if (domains && domains.length === 0) {
return <>
{header}
No domains yet. Archive some webpages!
>;
}
// Error state
if (domains === undefined) {
return <>
{header}
Could not fetch Domains
>;
}
return <>
{header}
>;
}
export function DomainEditPage() {
const {domainId} = useParams();
const navigate = useNavigate();
const {domain, form, fetchDomain} = useDomain(parseInt(domainId));
// Modal state for tagging
const [tagEditModalOpen, setTagEditModalOpen] = useState(false);
// Modal state for reorganization
const [reorganizeModalOpen, setReorganizeModalOpen] = useState(false);
useTitle(`Edit Domain: ${domain?.domain || '...'}`);
// Wrap form.onSubmit to add toast and refresh domain data
React.useEffect(() => {
if (form && form.onSubmit) {
const originalOnSubmit = form.onSubmit;
form.onSubmit = async () => {
try {
await originalOnSubmit();
toast({
type: 'success',
title: 'Domain Updated',
description: 'Domain was successfully updated',
time: 3000,
});
// Refresh domain data to show updated values
await fetchDomain();
} catch (e) {
console.error('Failed to update domain:', e);
throw e;
}
};
}
}, [form, fetchDomain]);
// Handler for tag modal save
const handleTagSave = async (tagName, directory) => {
try {
await tagDomain(parseInt(domainId), tagName, directory);
toast({
type: 'success',
title: 'Domain Tagged',
description: `Domain "${domain?.domain}" has been tagged with "${tagName}"`,
time: 3000,
});
} catch (e) {
console.error('Failed to tag domain', e);
} finally {
setTimeout(async () => {
await fetchDomain();
}, 500);
}
};
// Handler for fetching tag info
const handleGetTagInfo = async (tagName) => {
if (domain?.id) {
return await getCollectionTagInfo(domain.id, tagName);
}
return null;
};
const handleRefreshDomain = async (e) => {
if (e) {
e.preventDefault();
}
await refreshDomain(parseInt(domainId));
// Refresh domain data after completion
await fetchDomain();
};
if (!form.ready) {
return Loading domain... ;
}
// Handler for domain deletion
const handleDelete = async () => {
try {
let response = await deleteDomain(parseInt(domainId));
if (response.status === 204) {
navigate('/archives/domains');
}
} catch (e) {
console.error('Failed to delete domain', e);
}
};
const deleteButton = Delete ;
const refreshButton = domain?.directory ? (
Refresh
) : null;
const tagButton = setTagEditModalOpen(true)}
color='green'
style={{marginTop: '1em'}}
>Tag ;
const reorganizeButton = (
setReorganizeModalOpen(true)}
obeyWROLMode={true}
style={{marginTop: '1em'}}
>Reorganize Files
);
const actionButtons = <>
{deleteButton}
{refreshButton}
{tagButton}
{reorganizeButton}
>;
const [descriptionProps] = form.getCustomProps({name: 'description', path: 'description'});
return <>
Archives
{domain?.needs_reorganization && (
File Format Changed
The file name format has changed. Click "Reorganize Files" to move existing files
to match the new format.
)}
Description
{/* Tag Modal */}
setTagEditModalOpen(false)}
currentTagName={domain?.tag_name}
originalDirectory={domain?.directory}
getTagInfo={handleGetTagInfo}
onSave={handleTagSave}
collectionName="Domain"
hasDirectory={!!domain?.directory}
/>
{/* Reorganize Modal */}
setReorganizeModalOpen(false)}
collectionId={domain?.id}
collectionName={domain?.domain}
onComplete={fetchDomain}
needsReorganization={domain?.needs_reorganization}
/>
{/* Downloads Segment */}
{domain && domain.statistics && }
>;
}
function ArchiveFileNameForm({form}) {
const [message, setMessage] = React.useState(null);
const onChange = async (value) => {
const response = await postArchiveFileFormat(value);
const {error, preview} = await response.json();
if (error) {
setMessage({content: error, header: 'Invalid File Name', negative: true});
} else {
setMessage({content: preview, header: 'File Name Preview', positive: true});
}
}
const label =
Variables:
%(title)s - Page title
%(download_datetime)s - Full datetime (YYYY-MM-DD-HH-MM-SS)
%(download_date)s - Date only (YYYY-MM-DD)
%(download_year)s - Year
%(download_month)s - Month (zero-padded)
%(download_day)s - Day (zero-padded)
%(domain)s - Domain name
%(ext)s - File extension (required, must be at end)
Subdirectories supported: %(download_year)s/%(title)s.%(ext)s
>}
/>;
return
}
function BrowserConfigForm({form, browsers, browsersAvailable}) {
const {t} = React.useContext(ThemeContext);
const [useCustomPath, setUseCustomPath] = useState(false);
// Determine if custom path is being used based on current value
React.useEffect(() => {
const currentBrowser = form.formData?.browser_executable;
if (currentBrowser) {
// Check if current value matches any known browser
const isKnownBrowser = browsers.some(b => b.path === currentBrowser || b.key === currentBrowser);
setUseCustomPath(!isKnownBrowser);
}
}, [form.formData?.browser_executable, browsers]);
if (!browsersAvailable) {
return null;
}
// Build dropdown options: auto-detect + installed browsers + custom
const browserOptions = [
{key: 'auto', value: '', text: 'Auto-detect (recommended)'},
...browsers.map(b => ({key: b.key, value: b.path, text: `${b.name} (${b.path})`})),
{key: 'custom', value: '__custom__', text: 'Custom path...'},
];
const handleBrowserChange = (e, {value}) => {
if (value === '__custom__') {
setUseCustomPath(true);
form.setValue('browser_executable', '');
} else {
setUseCustomPath(false);
form.setValue('browser_executable', value || null);
}
};
const currentValue = form.formData?.browser_executable || '';
const dropdownValue = useCustomPath ? '__custom__' : currentValue;
return <>
Configure which browser SingleFile uses to create archives.
These settings only apply to native deployments (Raspberry Pi/Debian).
Browser
{useCustomPath && (
Custom Browser Path
form.setValue('browser_executable', e.target.value)}
/>
Enter the absolute path to the browser executable.
)}
Browser Arguments
form.setValue('browser_args', e.target.value)}
/>
JSON array of arguments passed to the browser. Default: ["--no-sandbox"]
User Agent
form.setValue('user_agent', e.target.value || null)}
/>
Custom user agent string. Leave empty to use the system default.
>;
}
function ArchiveSettingsPage() {
useTitle('Archive Settings');
const {t} = React.useContext(ThemeContext);
const dockerized = useDockerized();
const [batchModalOpen, setBatchModalOpen] = useState(false);
const [domainsNeedingReorg, setDomainsNeedingReorg] = useState(0);
const [fetchingReorgCount, setFetchingReorgCount] = useState(true);
const [browsers, setBrowsers] = useState([]);
const [browsersAvailable, setBrowsersAvailable] = useState(false);
// Check if batch reorganization is currently active for domains
const {isReorganizing, taskType, collectionKind} = useReorganizationStatus();
const isBatchReorganizingDomains = isReorganizing && taskType === 'batch_reorganize' && collectionKind === 'domain';
// Check how many domains need reorganization on mount (skip if batch is in progress)
React.useEffect(() => {
if (isBatchReorganizingDomains) {
// Skip fetching preview while batch reorganization is in progress
setFetchingReorgCount(false);
return;
}
setFetchingReorgCount(true);
previewBatchReorganization('domain')
.then(data => {
setDomainsNeedingReorg(data.total_collections || 0);
})
.catch(() => {
setDomainsNeedingReorg(0);
})
.finally(() => {
setFetchingReorgCount(false);
});
}, [isBatchReorganizingDomains]);
// Fetch available browsers on mount (only if not dockerized)
React.useEffect(() => {
if (dockerized === false) {
fetchArchiveBrowsers()
.then(data => {
setBrowsers(data.browsers || []);
setBrowsersAvailable(data.available === true);
})
.catch(() => {
setBrowsers([]);
setBrowsersAvailable(false);
});
}
}, [dockerized]);
const emptyFormData = {
file_name_format: '%(download_datetime)s_%(title)s.%(ext)s',
browser_executable: null,
browser_args: '["--no-sandbox"]',
user_agent: null,
};
const configSubmitter = async () => {
return await updateArchiveDownloaderConfig(configForm.formData);
};
const configForm = useForm({
fetcher: fetchArchiveDownloaderConfig,
submitter: configSubmitter,
emptyFormData,
});
const urlClipboardButton = navigator.clipboard.writeText(API_ARCHIVE_UPLOAD_URI)}
/>;
const dataFieldNameClipboardButton = navigator.clipboard.writeText('singlefile_contents')}
/>;
const urlFieldNameClipboardButton = navigator.clipboard.writeText('url')}
/>;
return
Archive Downloader Config
{fetchingReorgCount
? 'Checking for domains that need reorganization...'
: <>
{domainsNeedingReorg} domain{domainsNeedingReorg !== 1 ? 's' : ''}
{domainsNeedingReorg > 0
? ' have files that do not match the current file name format.'
: '. All domains are organized correctly.'}
>
}
setBatchModalOpen(true)}
id='reorganize_all_domains_button'
disabled={fetchingReorgCount || domainsNeedingReorg === 0}
loading={fetchingReorgCount}
>
Reorganize All Domains
setBatchModalOpen(false)}
kind='domain'
onComplete={() => {
setBatchModalOpen(false);
setDomainsNeedingReorg(0);
}}
/>
SingleFile Browser Extension
These are the settings necessary to configure the SingleFile Browser
Extension to automatically upload to your WROLPi.
Upload URL
Data Field Name
URL Field Name
}
function ArchivesPage() {
const [selectedArchives, setSelectedArchives] = useState([]);
const [bulkTagOpen, setBulkTagOpen] = useState(false);
const searchInputRef = React.useRef();
useHotkeys('f', (e) => {
e.preventDefault();
if (searchInputRef.current) {
searchInputRef.current.focus();
}
}, {enableOnFormTags: false});
const {domain, domains} = useSearchDomain();
// Find the domain object from the domains list to get the ID for the edit link
const domainObj = domain && domains ? domains.find(d => d.domain === domain) : null;
let title = 'Archives';
if (domainObj && domainObj.domain) {
title = `${domainObj.domain} Archives`;
}
useTitle(title);
const {
archives,
totalPages,
activePage,
setPage,
searchStr,
setSearchStr,
fetchArchives,
} = useSearchArchives();
let archiveOrders = [
{value: 'published_datetime', text: 'Published Date', short: 'P.Date'},
{value: 'published_modified_datetime', text: 'Modified Date', short: 'M.Date'},
{value: 'download_datetime', text: 'Download Date', short: 'D.Date'},
{value: 'size', text: 'Size'},
{value: 'viewed', text: 'Recently Viewed', short: 'R.Viewed'},
];
if (searchStr) {
archiveOrders = [{value: 'rank', text: 'Rank'}, ...archiveOrders];
}
const onSelect = (path, checked) => {
if (checked && path) {
setSelectedArchives([...selectedArchives, path]);
} else if (path) {
setSelectedArchives(selectedArchives.filter(i => i !== path));
}
}
const onDelete = async () => {
const archiveIds = archives.filter(i => selectedArchives.indexOf(i['primary_path']) >= 0)
.map(i => i['id']);
await deleteArchives(archiveIds);
await fetchArchives();
setSelectedArchives([]);
}
const invertSelection = async () => {
const newSelectedArchives = archives.map(archive => archive['key']).filter(i => selectedArchives.indexOf(i) < 0);
setSelectedArchives(newSelectedArchives);
}
const clearSelection = async (e) => {
if (e) e.preventDefault();
setSelectedArchives([]);
}
const onBulkTagComplete = async () => {
await fetchArchives();
setSelectedArchives([]);
}
const selectElm =
setBulkTagOpen(true)}
>Tag
Delete
Invert
Clear
setBulkTagOpen(false)}
paths={selectedArchives}
onComplete={onBulkTagComplete}
/>
;
const {body, paginator, viewButton, limitDropdown, tagQuerySelector} = FilesView(
{
files: archives,
activePage: activePage,
totalPages: totalPages,
selectElem: selectElm,
selectedKeys: selectedArchives,
onSelect: onSelect,
setPage: setPage,
headlines: !!searchStr
},
);
const [localSearchStr, setLocalSearchStr] = React.useState(searchStr || '');
const searchInput = setLocalSearchStr(null)}
searchStr={localSearchStr}
onSubmit={setSearchStr}
placeholder='Search Archives...'
inputRef={searchInputRef}
/>;
// Domain header with edit link when filtering by domain
let header;
if (domainObj && domainObj.domain) {
const editLink = `/archives/domain/${domainObj.id}/edit`;
header = <>
>;
} else if (domain) {
// Domain filter is set but domain object not loaded yet
header =
;
}
return <>
{header}
{viewButton}
{limitDropdown}
{tagQuerySelector}
{searchInput}
{viewButton}
{limitDropdown}
{tagQuerySelector}
{searchInput}
{body}
{paginator}
>
}
export function ArchiveRowCells({file}) {
const {data} = file;
let {sort} = useSearchOrder();
sort = sort ? sort.replace(/^-+/, '') : null;
const archiveUrl = `/archives/${file.id}`;
const posterPath = findPosterPath(file);
const posterUrl = posterPath ? `/media/${encodeMediaPath(posterPath)}` : null;
let poster;
if (posterUrl) {
poster =
;
} else {
poster = ;
}
let dataCell = file.published_datetime ? isoDatetimeToAgoPopup(file.published_datetime) : '';
if (sort === 'published_modified_datetime') {
dataCell = file.published_modified_datetime ? isoDatetimeToAgoPopup(file.published_modified_datetime) : '';
} else if (sort === 'download_datetime') {
dataCell = file.download_datetime ? isoDatetimeToAgoPopup(file.download_datetime) : '';
} else if (sort === 'size') {
dataCell = humanFileSize(file.size);
} else if (sort === 'viewed') {
dataCell = isoDatetimeToAgoPopup(file.viewed);
}
// Fragment for SelectableRow
return
{poster}
{textEllipsis(file.title || file.stem)}
{dataCell}
}
function ArchiveStatistics() {
useTitle('Archive Statistics');
const {statistics} = useArchiveStatistics();
if (statistics === null) {
// Request is pending.
return
} else if (statistics === undefined) {
return Unable to fetch Archive Statistics
}
const {archives, historical, domains} = statistics;
const archiveNames = [
{key: 'archives', label: 'Archives'},
{key: 'sum_size', label: 'Total Size'},
{key: 'max_size', label: 'Largest Archive'},
{key: 'week', label: 'Downloads Past Week'},
{key: 'month', label: 'Downloads Past Month'},
{key: 'year', label: 'Downloads Past Year'},
];
const historicalNames = [
{key: 'average_count', label: 'Average Monthly Downloads'},
{key: 'average_size', label: 'Average Monthly Usage'},
];
const domainNames = [
{key: 'domains', label: 'Domains'},
{key: 'tagged_domains', label: 'Tagged Domains'},
];
const buildSegment = (title, names, stats) => {
return
{names.map(
({key, label}) =>
{stats[key]}
{label}
)}
}
return <>
{buildSegment('Archives', archiveNames, archives)}
{buildSegment('Historical Archives', historicalNames, historical)}
{buildSegment('Domains', domainNames, domains)}
>
}
export function ArchiveRoute() {
const location = useLocation();
const path = location.pathname;
const links = [
{
text: 'Archives',
to: '/archives',
end: true,
isActive: () => path === '/archives' || /^\/archives\/\d+$/.test(path)
},
{
text: 'Domains',
to: '/archives/domains',
isActive: () => path.startsWith('/archives/domain')
},
{text: 'Settings', to: '/archives/settings'},
{text: 'Statistics', to: '/archives/statistics'},
];
return
}/>
}/>
}/>
}/>
}/>
}/>
}