This commit is contained in:
Reece 2025-06-20 23:00:26 +01:00
parent cbc5616a39
commit 25e9db2570
8 changed files with 215 additions and 120 deletions

View File

@ -1653,6 +1653,17 @@
"uploadError": "Failed to upload some files.",
"failedToOpen": "Failed to open file. It may have been removed from storage.",
"failedToLoad": "Failed to load file to active set.",
"storageCleared": "Browser cleared storage. Files have been removed. Please re-upload."
"storageCleared": "Browser cleared storage. Files have been removed. Please re-upload.",
"clearAll": "Clear All",
"reloadFiles": "Reload Files"
},
"storage": {
"temporaryNotice": "Files are stored temporarily in your browser and may be cleared automatically",
"storageLimit": "Storage limit",
"storageUsed": "Temporary Storage used",
"storageFull": "Storage is nearly full. Consider removing some files.",
"fileTooLarge": "File too large. Maximum size per file is",
"storageQuotaExceeded": "Storage quota exceeded. Please remove some files before uploading more.",
"approximateSize": "Approximate size"
}
}

View File

@ -163,7 +163,7 @@ const FileCard = ({ file, onRemove, onDoubleClick, onView, onEdit, isSelected, o
</Text>
<Group gap="xs" justify="center">
<Badge color="gray" variant="light" size="sm">
<Badge color="red" variant="light" size="sm">
{getFileSize(file)}
</Badge>
<Badge color="blue" variant="light" size="sm">

View File

@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next";
import { GlobalWorkerOptions } from "pdfjs-dist";
import { StorageStats } from "../../services/fileStorage";
import { FileWithUrl, defaultStorageConfig } from "../../types/file";
import { FileWithUrl, defaultStorageConfig, initializeStorageConfig, StorageConfig } from "../../types/file";
// Refactored imports
import { fileOperationsService } from "../../services/fileOperationsService";
@ -39,6 +39,7 @@ const FileManager = ({
const [notification, setNotification] = useState<string | null>(null);
const [filesLoaded, setFilesLoaded] = useState(false);
const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
const [storageConfig, setStorageConfig] = useState<StorageConfig>(defaultStorageConfig);
// Extract operations from service for cleaner code
const {
@ -75,6 +76,21 @@ const FileManager = ({
}
}, [filesLoaded]);
// Initialize storage configuration on mount
useEffect(() => {
const initStorage = async () => {
try {
const config = await initializeStorageConfig();
setStorageConfig(config);
console.log('Initialized storage config:', config);
} catch (error) {
console.warn('Failed to initialize storage config, using defaults:', error);
}
};
initStorage();
}, []);
// Load storage stats and set up periodic updates
useEffect(() => {
handleLoadStorageStats();
@ -143,11 +159,47 @@ const FileManager = ({
}
};
const validateStorageLimits = (filesToUpload: File[]): { valid: boolean; error?: string } => {
// Check individual file sizes
for (const file of filesToUpload) {
if (file.size > storageConfig.maxFileSize) {
const maxSizeMB = Math.round(storageConfig.maxFileSize / (1024 * 1024));
return {
valid: false,
error: `${t("storage.fileTooLarge", "File too large. Maximum size per file is")} ${maxSizeMB}MB`
};
}
}
// Check total storage capacity
if (storageStats) {
const totalNewSize = filesToUpload.reduce((sum, file) => sum + file.size, 0);
const projectedUsage = storageStats.totalSize + totalNewSize;
if (projectedUsage > storageConfig.maxTotalStorage) {
return {
valid: false,
error: t("storage.storageQuotaExceeded", "Storage quota exceeded. Please remove some files before uploading more.")
};
}
}
return { valid: true };
};
const handleDrop = async (uploadedFiles: File[]) => {
setLoading(true);
try {
const newFiles = await uploadFiles(uploadedFiles, defaultStorageConfig.useIndexedDB);
// Validate storage limits before uploading
const validation = validateStorageLimits(uploadedFiles);
if (!validation.valid) {
setNotification(validation.error);
setLoading(false);
return;
}
const newFiles = await uploadFiles(uploadedFiles, storageConfig.useIndexedDB);
// Update files state
setFiles((prevFiles) => (allowMultiple ? [...prevFiles, ...newFiles] : newFiles));
@ -286,12 +338,11 @@ const FileManager = ({
return (
<div style={{
width: "100%",
margin: "0 auto",
justifyContent: "center",
display: "flex",
flexDirection: "column",
alignItems: "center",
padding: "20px"
paddingTop: "3rem"
}}>
{/* File upload is now handled by FileUploadSelector when no files exist */}
@ -302,6 +353,7 @@ const FileManager = ({
filesCount={files.length}
onClearAll={handleClearAll}
onReloadFiles={handleReloadFiles}
storageConfig={storageConfig}
/>
{/* Multi-selection controls */}
@ -332,31 +384,12 @@ const FileManager = ({
</Box>
)}
{/* Files Display */}
{files.length === 0 ? (
<FileUploadSelector
title={t("fileManager.title", "Upload PDF Files")}
subtitle={t("fileManager.subtitle", "Add files to your storage for easy access across tools")}
sharedFiles={[]} // FileManager is the source, so no shared files
onFilesSelect={(uploadedFiles) => {
// Handle multiple files - add to storage AND active set
handleDrop(uploadedFiles);
if (onLoadFileToActive && uploadedFiles.length > 0) {
uploadedFiles.forEach(onLoadFileToActive);
}
}}
allowMultiple={allowMultiple}
accept={["application/pdf"]}
loading={loading}
showDropzone={true}
/>
) : (
<Box>
<Flex
wrap="wrap"
gap="lg"
justify="flex-start"
style={{ width: "fit-content", margin: "0 auto" }}
style={{ width: "90%", marginTop: "1rem"}}
>
{files.map((file, idx) => (
<FileCard
@ -371,8 +404,7 @@ const FileManager = ({
/>
))}
</Flex>
</Box>
)}
{/* Notifications */}
{notification && (

View File

@ -1,17 +1,20 @@
import React from "react";
import { Card, Group, Text, Button, Progress } from "@mantine/core";
import { Card, Group, Text, Button, Progress, Alert, Stack } from "@mantine/core";
import { useTranslation } from "react-i18next";
import StorageIcon from "@mui/icons-material/Storage";
import DeleteIcon from "@mui/icons-material/Delete";
import WarningIcon from "@mui/icons-material/Warning";
import { StorageStats } from "../../services/fileStorage";
import { formatFileSize } from "../../utils/fileUtils";
import { getStorageUsagePercent } from "../../utils/storageUtils";
import { StorageConfig } from "../../types/file";
interface StorageStatsCardProps {
storageStats: StorageStats | null;
filesCount: number;
onClearAll: () => void;
onReloadFiles: () => void;
storageConfig: StorageConfig;
}
const StorageStatsCard = ({
@ -19,57 +22,70 @@ const StorageStatsCard = ({
filesCount,
onClearAll,
onReloadFiles,
storageConfig,
}: StorageStatsCardProps) => {
const { t } = useTranslation();
if (!storageStats) return null;
const storageUsagePercent = getStorageUsagePercent(storageStats);
const totalUsed = storageStats.totalSize || storageStats.used;
const hardLimitPercent = (totalUsed / storageConfig.maxTotalStorage) * 100;
const isNearLimit = hardLimitPercent >= storageConfig.warningThreshold * 100;
return (
<Card withBorder p="sm" mb="md" style={{ width: "90%", maxWidth: 600 }}>
<Group align="center" gap="md">
<StorageIcon />
<div style={{ flex: 1 }}>
<Text size="sm" fw={500}>
{t("fileManager.storage", "Storage")}: {formatFileSize(storageStats.used)}
{storageStats.quota && ` / ${formatFileSize(storageStats.quota)}`}
</Text>
{storageStats.quota && (
<Stack gap="sm" style={{ width: "90%", maxWidth: 600 }}>
<Card withBorder p="sm">
<Group align="center" gap="md">
<StorageIcon />
<div style={{ flex: 1 }}>
<Text size="sm" fw={500}>
{t("storage.storageUsed", "Storage used")}: {formatFileSize(totalUsed)} / {formatFileSize(storageConfig.maxTotalStorage)}
</Text>
<Progress
value={storageUsagePercent}
color={storageUsagePercent > 80 ? "red" : storageUsagePercent > 60 ? "yellow" : "blue"}
value={hardLimitPercent}
color={isNearLimit ? "red" : hardLimitPercent > 60 ? "yellow" : "blue"}
size="sm"
mt={4}
/>
)}
<Text size="xs" c="dimmed">
{storageStats.fileCount} {t("fileManager.filesStored", "files stored")}
</Text>
</div>
<Group gap="xs">
{filesCount > 0 && (
<Group justify="space-between" mt={2}>
<Text size="xs" c="dimmed">
{storageStats.fileCount} files {t("storage.approximateSize", "Approximate size")}
</Text>
<Text size="xs" c={isNearLimit ? "red" : "dimmed"}>
{Math.round(hardLimitPercent)}% used
</Text>
</Group>
{isNearLimit && (
<Text size="xs" c="red" mt={4}>
{t("storage.storageFull", "Storage is nearly full. Consider removing some files.")}
</Text>
)}
</div>
<Group gap="xs">
{filesCount > 0 && (
<Button
variant="light"
color="red"
size="xs"
onClick={onClearAll}
leftSection={<DeleteIcon style={{ fontSize: 16 }} />}
>
{t("fileManager.clearAll", "Clear All")}
</Button>
)}
<Button
variant="light"
color="red"
color="blue"
size="xs"
onClick={onClearAll}
leftSection={<DeleteIcon style={{ fontSize: 16 }} />}
onClick={onReloadFiles}
>
{t("fileManager.clearAll", "Clear All")}
{t("fileManager.reloadFiles", "Reload Files")}
</Button>
)}
<Button
variant="light"
color="blue"
size="xs"
onClick={onReloadFiles}
>
Reload Files
</Button>
</Group>
</Group>
</Group>
</Card>
</Card>
</Stack>
);
};

View File

@ -87,10 +87,7 @@ const FileUploadSelector = ({
disabled={disabled || sharedFiles.length === 0}
loading={loading}
>
{loading
? t("fileUpload.loading", "Loading...")
: `${t("fileUpload.loadFromStorage", "Load from Storage")} (${sharedFiles.length} ${t("fileUpload.filesAvailable", "files available")})`
}
{loading ? "Loading..." : `Load from Storage (${sharedFiles.length} files available)`}
</Button>
<Text size="md" c="dimmed">

View File

@ -2,6 +2,14 @@
/* Import minimal theme variables */
@import './theme.css';
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
@tailwind base;
}
@layer components {
@tailwind components;
}
@layer utilities {
@tailwind utilities;
}

View File

@ -245,7 +245,7 @@ export const mantineTheme = createTheme({
},
control: {
color: 'var(--text-secondary)',
'&[data-active]': {
'[dataActive]': {
backgroundColor: 'var(--bg-surface)',
color: 'var(--text-primary)',
boxShadow: 'var(--shadow-sm)',

View File

@ -11,9 +11,40 @@ export interface FileWithUrl extends File {
export interface StorageConfig {
useIndexedDB: boolean;
// Simplified - no thresholds needed, IndexedDB for everything
maxFileSize: number; // Maximum size per file in bytes
maxTotalStorage: number; // Maximum total storage in bytes
warningThreshold: number; // Warning threshold (percentage 0-1)
}
export const defaultStorageConfig: StorageConfig = {
useIndexedDB: true,
maxFileSize: 100 * 1024 * 1024, // 100MB per file
maxTotalStorage: 1024 * 1024 * 1024, // 1GB default, will be updated dynamically
warningThreshold: 0.8, // Warn at 80% capacity
};
// Calculate and update storage limit: half of available storage or 10GB, whichever is smaller
export const initializeStorageConfig = async (): Promise<StorageConfig> => {
const tenGB = 10 * 1024 * 1024 * 1024; // 10GB in bytes
const oneGB = 1024 * 1024 * 1024; // 1GB fallback
let maxTotalStorage = oneGB; // Default fallback
// Try to estimate available storage
if ('storage' in navigator && 'estimate' in navigator.storage) {
try {
const estimate = await navigator.storage.estimate();
if (estimate.quota) {
const halfQuota = estimate.quota / 2;
maxTotalStorage = Math.min(halfQuota, tenGB);
}
} catch (error) {
console.warn('Could not estimate storage quota, using 1GB default:', error);
}
}
return {
...defaultStorageConfig,
maxTotalStorage
};
};