latest
This commit is contained in:
@@ -27,6 +27,8 @@ import {
|
||||
} from '@mui/icons-material';
|
||||
import { CCShapesPanel } from './CCShapesPanel';
|
||||
import { CCSlidesPanel } from './CCSlidesPanel';
|
||||
import { CCFilesPanel } from './CCFilesPanel';
|
||||
import { CCCabinetsPanel } from './CCCabinetsPanel';
|
||||
import { CCYoutubePanel } from './CCYoutubePanel';
|
||||
import { CCGraphPanel } from './CCGraphPanel';
|
||||
import { CCExamMarkerPanel } from './CCExamMarkerPanel';
|
||||
@@ -40,8 +42,10 @@ import { useTLDraw } from '../../../../../contexts/TLDrawContext';
|
||||
|
||||
export const PANEL_TYPES = {
|
||||
default: [
|
||||
{ id: 'cabinets', label: 'Cabinets', order: 5 },
|
||||
{ id: 'navigation', label: 'Navigation', order: 10 },
|
||||
{ id: 'node-snapshot', label: 'Node', order: 20 },
|
||||
{ id: 'files', label: 'Files', order: 25 },
|
||||
{ id: 'cc-shapes', label: 'Shapes', order: 30 },
|
||||
{ id: 'slides', label: 'Slides', order: 40 },
|
||||
{ id: 'youtube', label: 'YouTube', order: 50 },
|
||||
@@ -111,7 +115,7 @@ const StyledMenuItem = styled(MenuItem)(() => ({
|
||||
}));
|
||||
|
||||
export const BasePanel: React.FC<BasePanelProps> = ({
|
||||
initialPanelType = 'cc-shapes',
|
||||
initialPanelType = 'files',
|
||||
examMarkerProps,
|
||||
isExpanded: controlledIsExpanded,
|
||||
isPinned: controlledIsPinned,
|
||||
@@ -151,8 +155,8 @@ export const BasePanel: React.FC<BasePanelProps> = ({
|
||||
);
|
||||
|
||||
// Use controlled state if provided, otherwise use internal state
|
||||
const [internalIsExpanded, setInternalIsExpanded] = React.useState(false);
|
||||
const [internalIsPinned, setInternalIsPinned] = React.useState(false);
|
||||
const [internalIsExpanded, setInternalIsExpanded] = React.useState(true);
|
||||
const [internalIsPinned, setInternalIsPinned] = React.useState(true);
|
||||
|
||||
const isExpanded = controlledIsExpanded ?? internalIsExpanded;
|
||||
const isPinned = controlledIsPinned ?? internalIsPinned;
|
||||
@@ -200,6 +204,8 @@ export const BasePanel: React.FC<BasePanelProps> = ({
|
||||
|
||||
const getIconForPanel = (panelId: PanelType) => {
|
||||
switch (panelId) {
|
||||
case 'cabinets':
|
||||
return <NavigationIcon />;
|
||||
case 'cc-shapes':
|
||||
return <ShapesIcon />;
|
||||
case 'slides':
|
||||
@@ -223,6 +229,8 @@ export const BasePanel: React.FC<BasePanelProps> = ({
|
||||
|
||||
const getDescriptionForPanel = (panelId: PanelType) => {
|
||||
switch (panelId) {
|
||||
case 'cabinets':
|
||||
return 'Manage file cabinets';
|
||||
case 'cc-shapes':
|
||||
return 'Add shapes and elements to your canvas';
|
||||
case 'slides':
|
||||
@@ -250,6 +258,10 @@ export const BasePanel: React.FC<BasePanelProps> = ({
|
||||
}
|
||||
|
||||
switch (currentPanelType) {
|
||||
case 'cabinets':
|
||||
return <CCCabinetsPanel />;
|
||||
case 'files':
|
||||
return <CCFilesPanel />;
|
||||
case 'cc-shapes':
|
||||
return <CCShapesPanel />;
|
||||
case 'slides':
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { ThemeProvider, createTheme, useMediaQuery, Box, Grid, Card, CardContent, CardActions, Typography, Button, TextField, Dialog, DialogTitle, DialogContent, DialogActions, IconButton, styled } from '@mui/material';
|
||||
import EditIcon from '@mui/icons-material/Edit';
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import AddIcon from '@mui/icons-material/Add';
|
||||
import { useTLDraw } from '../../../../../contexts/TLDrawContext';
|
||||
import { supabase } from '../../../../../supabaseClient';
|
||||
|
||||
type Cabinet = { id: string; name: string };
|
||||
|
||||
const Toolbar = styled('div')(() => ({ display: 'flex', gap: '8px', marginBottom: '8px' }));
|
||||
|
||||
export const CCCabinetsPanel: React.FC = () => {
|
||||
const { tldrawPreferences, authToken } = useTLDraw() as { tldrawPreferences?: { colorScheme?: 'light' | 'dark' | 'system' }, authToken?: string };
|
||||
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
|
||||
const [cabinets, setCabinets] = useState<Cabinet[]>([]);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [renameOpen, setRenameOpen] = useState<null | Cabinet>(null);
|
||||
const [newName, setNewName] = useState('');
|
||||
|
||||
const theme = useMemo(() => {
|
||||
const mode = (tldrawPreferences?.colorScheme === 'system')
|
||||
? (prefersDarkMode ? 'dark' : 'light')
|
||||
: (tldrawPreferences?.colorScheme === 'dark' ? 'dark' : 'light');
|
||||
return createTheme({ palette: { mode, divider: 'var(--color-divider)' } });
|
||||
}, [tldrawPreferences?.colorScheme, prefersDarkMode]);
|
||||
|
||||
const API_BASE: string = (import.meta as unknown as { env?: { VITE_API_BASE?: string } })?.env?.VITE_API_BASE || (location.port.startsWith('517') ? 'http://127.0.0.1:8080' : '/api');
|
||||
|
||||
type RequestInitLite = { method?: string; body?: string | FormData | Blob | null; headers?: Record<string, string> } | undefined;
|
||||
const apiFetch = async (url: string, init?: RequestInitLite) => {
|
||||
const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`;
|
||||
const { data: { session } } = await supabase.auth.getSession();
|
||||
const bearer = session?.access_token || authToken || '';
|
||||
const res = await fetch(fullUrl, {
|
||||
...init,
|
||||
headers: {
|
||||
'Authorization': `Bearer ${bearer}`,
|
||||
...(init?.headers || {})
|
||||
}
|
||||
});
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
return res.json();
|
||||
};
|
||||
|
||||
const loadCabinets = async () => {
|
||||
const data = await apiFetch('/database/cabinets');
|
||||
setCabinets([...(data.owned || []), ...(data.shared || [])]);
|
||||
};
|
||||
|
||||
useEffect(() => { loadCabinets(); /* eslint-disable-line react-hooks/exhaustive-deps */ }, []);
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!newName.trim()) return;
|
||||
await apiFetch('/database/cabinets', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: newName }) });
|
||||
setNewName('');
|
||||
setCreateOpen(false);
|
||||
await loadCabinets();
|
||||
};
|
||||
|
||||
const handleRename = async () => {
|
||||
if (!renameOpen || !newName.trim()) return;
|
||||
await apiFetch(`/database/cabinets/${renameOpen.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: newName }) });
|
||||
setRenameOpen(null);
|
||||
setNewName('');
|
||||
await loadCabinets();
|
||||
};
|
||||
|
||||
const handleDelete = async (cabinetId: string) => {
|
||||
await apiFetch(`/database/cabinets/${cabinetId}`, { method: 'DELETE' });
|
||||
await loadCabinets();
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeProvider theme={theme}>
|
||||
<Box sx={{ p: 1, height: '100%', display: 'flex', flexDirection: 'column', gap: 1 }}>
|
||||
<Toolbar>
|
||||
<Button size="small" variant="outlined" startIcon={<AddIcon/>} onClick={() => { setNewName(''); setCreateOpen(true); }}>New Cabinet</Button>
|
||||
</Toolbar>
|
||||
<Grid container spacing={1} sx={{ overflow: 'auto' }}>
|
||||
{cabinets.map(c => (
|
||||
<Grid item xs={12} key={c.id}>
|
||||
<Card variant="outlined">
|
||||
<CardContent sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<div>
|
||||
<Typography variant="subtitle1" sx={{ color: 'var(--color-text)' }}>{c.name}</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'var(--color-text-secondary)' }}>{c.id}</Typography>
|
||||
</div>
|
||||
<CardActions>
|
||||
<IconButton size="small" onClick={() => { setRenameOpen(c); setNewName(c.name); }} title="Rename">
|
||||
<EditIcon />
|
||||
</IconButton>
|
||||
<IconButton size="small" onClick={() => handleDelete(c.id)} title="Delete">
|
||||
<DeleteIcon />
|
||||
</IconButton>
|
||||
</CardActions>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
|
||||
<Dialog open={createOpen} onClose={() => setCreateOpen(false)}>
|
||||
<DialogTitle>Create Cabinet</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField autoFocus fullWidth label="Name" value={newName} onChange={(e) => setNewName(e.target.value)} />
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setCreateOpen(false)}>Cancel</Button>
|
||||
<Button onClick={handleCreate} disabled={!newName.trim()}>Create</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={!!renameOpen} onClose={() => setRenameOpen(null)}>
|
||||
<DialogTitle>Rename Cabinet</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField autoFocus fullWidth label="New name" value={newName} onChange={(e) => setNewName(e.target.value)} />
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setRenameOpen(null)}>Cancel</Button>
|
||||
<Button onClick={handleRename} disabled={!newName.trim()}>Save</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Box>
|
||||
</ThemeProvider>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,863 @@
|
||||
import React, { useEffect, useMemo, useState, useCallback, useRef } from 'react';
|
||||
import {
|
||||
ThemeProvider,
|
||||
createTheme,
|
||||
useMediaQuery,
|
||||
Button,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemText,
|
||||
IconButton,
|
||||
styled,
|
||||
CircularProgress,
|
||||
Divider,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Box,
|
||||
Typography,
|
||||
TextField,
|
||||
Select,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Pagination,
|
||||
Stack,
|
||||
Chip,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Paper,
|
||||
Alert,
|
||||
LinearProgress
|
||||
} from '@mui/material';
|
||||
import UploadIcon from '@mui/icons-material/Upload';
|
||||
import FolderIcon from '@mui/icons-material/Folder';
|
||||
import FolderOpenIcon from '@mui/icons-material/FolderOpen';
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import RefreshIcon from '@mui/icons-material/Refresh';
|
||||
import MoreVertIcon from '@mui/icons-material/MoreVert';
|
||||
import ImageIcon from '@mui/icons-material/Image';
|
||||
import DescriptionIcon from '@mui/icons-material/Description';
|
||||
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
|
||||
import { useTLDraw } from '../../../../../contexts/TLDrawContext';
|
||||
import { supabase } from '../../../../../supabaseClient';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
calculateDirectoryStats,
|
||||
isDirectoryPickerSupported,
|
||||
FileWithPath
|
||||
} from '../../../../../utils/folderPicker';
|
||||
|
||||
const Container = styled('div')(() => ({
|
||||
padding: '8px',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '8px',
|
||||
height: '100%'
|
||||
}));
|
||||
|
||||
type Cabinet = { id: string; name: string };
|
||||
type FileRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
mime_type?: string;
|
||||
is_directory?: boolean;
|
||||
size_bytes?: number;
|
||||
processing_status?: string;
|
||||
relative_path?: string;
|
||||
created_at?: string;
|
||||
};
|
||||
type Artefact = { id: string; type: string; rel_path: string; created_at: string };
|
||||
|
||||
interface PaginationInfo {
|
||||
page: number;
|
||||
per_page: number;
|
||||
total_count: number;
|
||||
total_pages: number;
|
||||
has_next: boolean;
|
||||
has_prev: boolean;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
interface FileListResponse {
|
||||
files: FileRow[];
|
||||
pagination: PaginationInfo;
|
||||
filters: {
|
||||
search?: string;
|
||||
sort_by: string;
|
||||
sort_order: string;
|
||||
include_directories: boolean;
|
||||
parent_directory_id?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const CCFilesPanel: React.FC = () => {
|
||||
const { tldrawPreferences, authToken } = useTLDraw() as { tldrawPreferences?: { colorScheme?: 'light' | 'dark' | 'system' }, authToken?: string };
|
||||
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
|
||||
const [cabinets, setCabinets] = useState<Cabinet[]>([]);
|
||||
const [selectedCabinet, setSelectedCabinet] = useState<string>('');
|
||||
const [files, setFiles] = useState<FileRow[]>([]);
|
||||
const [pagination, setPagination] = useState<PaginationInfo | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [menuAnchor, setMenuAnchor] = useState<null | { el: HTMLElement; fileId: string }>(null);
|
||||
const [artefacts, setArtefacts] = useState<Artefact[]>([]);
|
||||
|
||||
// Pagination and filtering state
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [itemsPerPage, setItemsPerPage] = useState(15); // Slightly more for main panel
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [sortBy, setSortBy] = useState('created_at');
|
||||
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
|
||||
const previousSearchTerm = useRef(searchTerm);
|
||||
|
||||
// Directory navigation state
|
||||
const [currentDirectoryId, setCurrentDirectoryId] = useState<string | null>(null);
|
||||
const [breadcrumbs, setBreadcrumbs] = useState<{ id: string | null; name: string }[]>([
|
||||
{ id: null, name: 'Root' }
|
||||
]);
|
||||
|
||||
// Directory upload state
|
||||
const [selectedFiles, setSelectedFiles] = useState<FileWithPath[]>([]);
|
||||
const [showDirectoryDialog, setShowDirectoryDialog] = useState(false);
|
||||
const [isDirectoryUploading, setIsDirectoryUploading] = useState(false);
|
||||
const [directoryStats, setDirectoryStats] = useState<{
|
||||
fileCount: number;
|
||||
directoryCount: number;
|
||||
totalSize: number;
|
||||
formattedSize: string;
|
||||
} | null>(null);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const theme = useMemo(() => {
|
||||
const mode = (tldrawPreferences?.colorScheme === 'system')
|
||||
? (prefersDarkMode ? 'dark' : 'light')
|
||||
: (tldrawPreferences?.colorScheme === 'dark' ? 'dark' : 'light');
|
||||
return createTheme({ palette: { mode, divider: 'var(--color-divider)' } });
|
||||
}, [tldrawPreferences?.colorScheme, prefersDarkMode]);
|
||||
|
||||
type RequestInitLike = { method?: string; body?: FormData | string | Blob | null; headers?: Record<string, string> } | undefined;
|
||||
type HeadersInitLike = Record<string, string>;
|
||||
|
||||
const API_BASE: string = (import.meta as unknown as { env?: { VITE_API_BASE?: string } })?.env?.VITE_API_BASE || (location.port.startsWith('517') ? 'http://127.0.0.1:8080' : '/api');
|
||||
|
||||
const apiFetch = useCallback(async (url: string, init?: RequestInitLike) => {
|
||||
const headers: HeadersInitLike = {
|
||||
'Authorization': `Bearer ${(await supabase.auth.getSession()).data.session?.access_token || authToken || ''}`,
|
||||
...(init?.headers || {})
|
||||
};
|
||||
const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`;
|
||||
const res = await fetch(fullUrl, { ...(init || {}), headers });
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
return res.json();
|
||||
}, [authToken, API_BASE]);
|
||||
|
||||
const loadCabinets = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await apiFetch('/database/cabinets');
|
||||
const all = [...(data.owned || []), ...(data.shared || [])];
|
||||
setCabinets(all);
|
||||
if (all.length && !selectedCabinet) setSelectedCabinet(all[0].id);
|
||||
} catch (error) {
|
||||
console.error('Failed to load cabinets:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [selectedCabinet, apiFetch]);
|
||||
|
||||
const loadFiles = useCallback(async (cabinetId: string, page: number = currentPage) => {
|
||||
if (!cabinetId) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
// Build query parameters for pagination, search, and sorting
|
||||
const params = new URLSearchParams({
|
||||
cabinet_id: cabinetId,
|
||||
page: page.toString(),
|
||||
per_page: itemsPerPage.toString(),
|
||||
sort_by: sortBy,
|
||||
sort_order: sortOrder,
|
||||
include_directories: 'true'
|
||||
});
|
||||
|
||||
// Add directory filtering
|
||||
if (currentDirectoryId) {
|
||||
params.append('parent_directory_id', currentDirectoryId);
|
||||
}
|
||||
|
||||
if (searchTerm) {
|
||||
params.append('search', searchTerm);
|
||||
}
|
||||
|
||||
// Use the new simple upload endpoint for listing files with pagination
|
||||
const data: FileListResponse = await apiFetch(`/simple-upload/files?${params.toString()}`);
|
||||
|
||||
setFiles(data.files || []);
|
||||
setPagination(data.pagination);
|
||||
} catch (error) {
|
||||
console.error('Failed to load files:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [currentPage, itemsPerPage, sortBy, sortOrder, searchTerm, apiFetch, currentDirectoryId]);
|
||||
|
||||
useEffect(() => {
|
||||
loadCabinets();
|
||||
}, [loadCabinets]);
|
||||
|
||||
// Main loading effect - handles pagination, sorting, cabinet changes, directory navigation
|
||||
useEffect(() => {
|
||||
if (selectedCabinet) {
|
||||
loadFiles(selectedCabinet, currentPage);
|
||||
}
|
||||
}, [selectedCabinet, loadFiles, currentPage, itemsPerPage, sortBy, sortOrder, currentDirectoryId]);
|
||||
|
||||
// Reset to page 1 and root directory when cabinet changes
|
||||
useEffect(() => {
|
||||
if (selectedCabinet) {
|
||||
setCurrentPage(1);
|
||||
setCurrentDirectoryId(null);
|
||||
setBreadcrumbs([{ id: null, name: 'Root' }]);
|
||||
}
|
||||
}, [selectedCabinet]);
|
||||
|
||||
// Search with debouncing - only when search term actually changes
|
||||
useEffect(() => {
|
||||
if (selectedCabinet && searchTerm !== previousSearchTerm.current) {
|
||||
previousSearchTerm.current = searchTerm;
|
||||
|
||||
const timeoutId = setTimeout(() => {
|
||||
setCurrentPage(1); // Reset to first page when searching
|
||||
loadFiles(selectedCabinet, 1);
|
||||
}, 500); // 500ms debounce
|
||||
|
||||
return () => clearTimeout(timeoutId);
|
||||
}
|
||||
}, [searchTerm, selectedCabinet, loadFiles]);
|
||||
|
||||
// Directory navigation handlers
|
||||
const navigateToFolder = useCallback((folder: FileRow) => {
|
||||
if (!folder.is_directory) return;
|
||||
|
||||
setCurrentDirectoryId(folder.id);
|
||||
setCurrentPage(1); // Reset to first page when entering folder
|
||||
|
||||
// Add to breadcrumbs
|
||||
setBreadcrumbs(prev => [...prev, { id: folder.id, name: folder.name }]);
|
||||
}, []);
|
||||
|
||||
const navigateToBreadcrumb = useCallback((targetBreadcrumb: { id: string | null; name: string }) => {
|
||||
setCurrentDirectoryId(targetBreadcrumb.id);
|
||||
setCurrentPage(1); // Reset to first page
|
||||
|
||||
// Trim breadcrumbs to the selected one
|
||||
setBreadcrumbs(prev => {
|
||||
const targetIndex = prev.findIndex(b => b.id === targetBreadcrumb.id && b.name === targetBreadcrumb.name);
|
||||
return targetIndex !== -1 ? prev.slice(0, targetIndex + 1) : [{ id: null, name: 'Root' }];
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Sort files to group directories first, then regular files
|
||||
const sortedFiles = useMemo(() => {
|
||||
return [...files].sort((a, b) => {
|
||||
// Directories come first
|
||||
if (a.is_directory && !b.is_directory) return -1;
|
||||
if (!a.is_directory && b.is_directory) return 1;
|
||||
|
||||
// Within the same type (both directories or both files), sort alphabetically by name
|
||||
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
|
||||
});
|
||||
}, [files]);
|
||||
|
||||
// Check if we need a separator between directories and files
|
||||
const needsGroupSeparator = useMemo(() => {
|
||||
const hasDirectories = sortedFiles.some(f => f.is_directory);
|
||||
const hasFiles = sortedFiles.some(f => !f.is_directory);
|
||||
return hasDirectories && hasFiles;
|
||||
}, [sortedFiles]);
|
||||
|
||||
const getGroupSeparatorIndex = useMemo(() => {
|
||||
if (!needsGroupSeparator) return -1;
|
||||
return sortedFiles.findIndex(f => !f.is_directory) - 1;
|
||||
}, [sortedFiles, needsGroupSeparator]);
|
||||
|
||||
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!e.target.files || !selectedCabinet) return;
|
||||
const file = e.target.files[0];
|
||||
await uploadFile(file);
|
||||
(e.target as HTMLInputElement).value = '';
|
||||
};
|
||||
|
||||
const handleDirectorySelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!e.target.files || !selectedCabinet) return;
|
||||
|
||||
// Convert FileList to FileWithPath array with relative paths
|
||||
const files: FileWithPath[] = [];
|
||||
Array.from(e.target.files).forEach(file => {
|
||||
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
|
||||
(file as FileWithPath).relativePath = relativePath;
|
||||
files.push(file as FileWithPath);
|
||||
});
|
||||
|
||||
if (files.length > 0) {
|
||||
prepareDirectoryUpload(files);
|
||||
}
|
||||
|
||||
(e.target as HTMLInputElement).value = '';
|
||||
};
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
if (!selectedCabinet) return;
|
||||
const form = new FormData();
|
||||
form.append('cabinet_id', selectedCabinet);
|
||||
form.append('path', file.name);
|
||||
form.append('scope', 'teacher');
|
||||
form.append('file', file);
|
||||
await apiFetch('/database/files/upload', { method: 'POST', body: form });
|
||||
await loadFiles(selectedCabinet);
|
||||
};
|
||||
|
||||
|
||||
const prepareDirectoryUpload = (files: FileWithPath[]) => {
|
||||
if (files.length === 0) return;
|
||||
|
||||
setSelectedFiles(files);
|
||||
setDirectoryStats(calculateDirectoryStats(files));
|
||||
setShowDirectoryDialog(true);
|
||||
};
|
||||
|
||||
const startDirectoryUpload = async () => {
|
||||
if (!selectedCabinet || selectedFiles.length === 0) return;
|
||||
|
||||
setIsDirectoryUploading(true);
|
||||
|
||||
try {
|
||||
const firstFilePath = selectedFiles[0].relativePath;
|
||||
const directoryName = firstFilePath.split('/')[0] || 'uploaded-folder';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('cabinet_id', selectedCabinet);
|
||||
formData.append('scope', 'teacher');
|
||||
formData.append('directory_name', directoryName);
|
||||
|
||||
selectedFiles.forEach(file => {
|
||||
formData.append('files', file);
|
||||
});
|
||||
|
||||
const relativePaths = selectedFiles.map(f => f.relativePath);
|
||||
formData.append('file_paths', JSON.stringify(relativePaths));
|
||||
|
||||
await apiFetch('/simple-upload/files/upload-directory', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
await loadFiles(selectedCabinet);
|
||||
|
||||
setShowDirectoryDialog(false);
|
||||
setSelectedFiles([]);
|
||||
setDirectoryStats(null);
|
||||
} catch (error) {
|
||||
console.error('Directory upload failed:', error);
|
||||
} finally {
|
||||
setIsDirectoryUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (fileId: string) => {
|
||||
await apiFetch(`/database/files/${fileId}`, { method: 'DELETE' });
|
||||
await loadFiles(selectedCabinet);
|
||||
};
|
||||
|
||||
const handleGenerateInitial = async (fileId: string) => {
|
||||
await apiFetch(`/database/files/${fileId}/artefacts/initial`, { method: 'POST' });
|
||||
const arts = await apiFetch(`/database/files/${fileId}/artefacts`);
|
||||
setArtefacts(arts || []);
|
||||
};
|
||||
|
||||
const openMenu = (el: HTMLElement, fileId: string) => setMenuAnchor({ el, fileId });
|
||||
const closeMenu = () => setMenuAnchor(null);
|
||||
const goToAIContent = () => {
|
||||
if (!menuAnchor) return;
|
||||
const fileId = menuAnchor.fileId;
|
||||
closeMenu();
|
||||
navigate(`/doc-intelligence/${encodeURIComponent(fileId)}`);
|
||||
};
|
||||
|
||||
const iconForMime = (mime?: string, isDirectory?: boolean) => {
|
||||
if (isDirectory) return <FolderIcon />;
|
||||
if (!mime) return <InsertDriveFileIcon/>;
|
||||
if (mime.startsWith('image/')) return <ImageIcon/>;
|
||||
if (mime === 'application/pdf' || mime.startsWith('application/')) return <DescriptionIcon/>;
|
||||
return <InsertDriveFileIcon/>;
|
||||
};
|
||||
|
||||
const formatFileSize = (bytes: number): string => {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
const k = 1024;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
const getStatusColor = (status?: string) => {
|
||||
switch (status) {
|
||||
case 'uploaded': return 'primary';
|
||||
case 'processing': return 'warning';
|
||||
case 'completed': return 'success';
|
||||
case 'failed': return 'error';
|
||||
default: return 'default';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeProvider theme={theme}>
|
||||
<Container>
|
||||
{/* Cabinet Selection Dropdown */}
|
||||
<Box sx={{ display: 'flex', gap: 1, alignItems: 'center', mb: 1 }}>
|
||||
<FormControl size="small" fullWidth>
|
||||
<InputLabel>Cabinet</InputLabel>
|
||||
<Select
|
||||
value={selectedCabinet}
|
||||
label="Cabinet"
|
||||
onChange={(e) => setSelectedCabinet(e.target.value)}
|
||||
startAdornment={<FolderIcon sx={{ color: 'action.active', mr: 1, fontSize: '1rem' }} />}
|
||||
>
|
||||
{cabinets.map(c => (
|
||||
<MenuItem key={c.id} value={c.id}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
|
||||
<Typography variant="body2">{c.name}</Typography>
|
||||
{pagination && selectedCabinet === c.id && (
|
||||
<Chip label={`${pagination.total_count} files`} size="small" sx={{ ml: 1 }} />
|
||||
)}
|
||||
</Box>
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
onClick={() => {
|
||||
setCurrentPage(1);
|
||||
setSearchTerm('');
|
||||
loadCabinets();
|
||||
}}
|
||||
sx={{
|
||||
minWidth: 40,
|
||||
width: 40,
|
||||
height: 40, // Match the height of Select components
|
||||
padding: 0,
|
||||
'& .MuiButton-startIcon': {
|
||||
margin: 0
|
||||
}
|
||||
}}
|
||||
>
|
||||
<RefreshIcon fontSize="small" />
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{/* Search Box - Full Width */}
|
||||
<Box sx={{ mb: 1 }}>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Search files"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
fullWidth
|
||||
placeholder="Type to search files..."
|
||||
/>
|
||||
</Box>
|
||||
|
||||
|
||||
{/* Sort and Filter Controls */}
|
||||
<Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', alignItems: 'center', py: 1 }}>
|
||||
<FormControl size="small" sx={{ minWidth: 80 }}>
|
||||
<InputLabel>Sort</InputLabel>
|
||||
<Select
|
||||
value={sortBy}
|
||||
label="Sort"
|
||||
onChange={(e) => setSortBy(e.target.value)}
|
||||
>
|
||||
<MenuItem value="name">Name</MenuItem>
|
||||
<MenuItem value="created_at">Date</MenuItem>
|
||||
<MenuItem value="size_bytes">Size</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl size="small" sx={{ minWidth: 60 }}>
|
||||
<InputLabel>Order</InputLabel>
|
||||
<Select
|
||||
value={sortOrder}
|
||||
label="Order"
|
||||
onChange={(e) => setSortOrder(e.target.value as 'asc' | 'desc')}
|
||||
>
|
||||
<MenuItem value="asc">↑</MenuItem>
|
||||
<MenuItem value="desc">↓</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl size="small" sx={{ minWidth: 60 }}>
|
||||
<InputLabel>Per page</InputLabel>
|
||||
<Select
|
||||
value={itemsPerPage}
|
||||
label="Per page"
|
||||
onChange={(e) => {
|
||||
setItemsPerPage(Number(e.target.value));
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
>
|
||||
<MenuItem value={10}>10</MenuItem>
|
||||
<MenuItem value={15}>15</MenuItem>
|
||||
<MenuItem value={25}>25</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
{/* Breadcrumb Navigation */}
|
||||
<Box sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 1,
|
||||
py: 1,
|
||||
px: 1,
|
||||
bgcolor: 'background.paper',
|
||||
borderBottom: '1px solid var(--color-divider)'
|
||||
}}>
|
||||
{breadcrumbs.map((breadcrumb, index) => (
|
||||
<React.Fragment key={`${breadcrumb.id}-${breadcrumb.name}`}>
|
||||
{index > 0 && (
|
||||
<Typography variant="caption" color="textSecondary">
|
||||
/
|
||||
</Typography>
|
||||
)}
|
||||
<Button
|
||||
size="small"
|
||||
variant="text"
|
||||
onClick={() => navigateToBreadcrumb(breadcrumb)}
|
||||
sx={{
|
||||
minWidth: 'auto',
|
||||
textTransform: 'none',
|
||||
color: index === breadcrumbs.length - 1 ? 'primary.main' : 'text.secondary',
|
||||
fontWeight: index === breadcrumbs.length - 1 ? 600 : 400
|
||||
}}
|
||||
>
|
||||
{breadcrumb.name}
|
||||
</Button>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
{/* File List with Fixed Height */}
|
||||
<Box sx={{
|
||||
border: '1px solid var(--color-divider)',
|
||||
borderRadius: '4px',
|
||||
height: 300, // Fixed height for main panel
|
||||
overflow: 'auto',
|
||||
flex: 1,
|
||||
// Hide scrollbar while keeping scroll functionality
|
||||
scrollbarWidth: 'none', // Firefox
|
||||
'&::-webkit-scrollbar': {
|
||||
display: 'none' // WebKit browsers (Chrome, Safari, Edge)
|
||||
}
|
||||
}}>
|
||||
{loading ? (
|
||||
<Box sx={{ p: 2, textAlign: 'center' }}>
|
||||
<CircularProgress size={20}/>
|
||||
<Typography variant="caption" display="block" sx={{ mt: 1 }}>
|
||||
Loading files...
|
||||
</Typography>
|
||||
</Box>
|
||||
) : sortedFiles.length === 0 ? (
|
||||
<Box sx={{ p: 2, textAlign: 'center' }}>
|
||||
<Typography variant="body2" color="textSecondary">
|
||||
{searchTerm ? 'No files found matching your search.' : 'No files found. Upload some files!'}
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<List dense disablePadding>
|
||||
{sortedFiles.map((f, index) => (
|
||||
<React.Fragment key={f.id}>
|
||||
{f.is_directory ? (
|
||||
<ListItem
|
||||
button
|
||||
onClick={() => navigateToFolder(f)}
|
||||
sx={{
|
||||
cursor: 'pointer',
|
||||
'&:hover': {
|
||||
backgroundColor: 'action.hover'
|
||||
}
|
||||
}}
|
||||
secondaryAction={
|
||||
<>
|
||||
<IconButton size="small" onClick={(e) => openMenu(e.currentTarget, f.id)} title="File actions">
|
||||
<MoreVertIcon/>
|
||||
</IconButton>
|
||||
<IconButton edge="end" size="small" onClick={() => handleDelete(f.id)} title="Delete file">
|
||||
<DeleteIcon/>
|
||||
</IconButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{iconForMime(f.mime_type, f.is_directory)}
|
||||
<ListItemText
|
||||
sx={{ ml: 1 }}
|
||||
primary={
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
<Typography variant="body2" sx={{ wordBreak: 'break-all' }}>
|
||||
{f.name}
|
||||
</Typography>
|
||||
{f.is_directory && <Chip label="Dir" size="small" />}
|
||||
{f.processing_status && f.processing_status !== 'uploaded' && (
|
||||
<Chip
|
||||
label={f.processing_status}
|
||||
size="small"
|
||||
color={getStatusColor(f.processing_status)}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
}
|
||||
secondary={
|
||||
<Typography variant="caption" color="textSecondary">
|
||||
{f.size_bytes ? formatFileSize(f.size_bytes) : 'Unknown size'}
|
||||
{f.mime_type && ` • ${f.mime_type.split('/')[1]}`}
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
</ListItem>
|
||||
) : (
|
||||
<ListItem
|
||||
secondaryAction={
|
||||
<>
|
||||
<IconButton size="small" onClick={(e) => openMenu(e.currentTarget, f.id)} title="File actions">
|
||||
<MoreVertIcon/>
|
||||
</IconButton>
|
||||
<IconButton edge="end" size="small" onClick={() => handleDelete(f.id)} title="Delete file">
|
||||
<DeleteIcon/>
|
||||
</IconButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{iconForMime(f.mime_type, f.is_directory)}
|
||||
<ListItemText
|
||||
sx={{ ml: 1 }}
|
||||
primary={
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
<Typography variant="body2" sx={{ wordBreak: 'break-all' }}>
|
||||
{f.name}
|
||||
</Typography>
|
||||
{f.is_directory && <Chip label="Dir" size="small" />}
|
||||
{f.processing_status && f.processing_status !== 'uploaded' && (
|
||||
<Chip
|
||||
label={f.processing_status}
|
||||
size="small"
|
||||
color={getStatusColor(f.processing_status)}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
}
|
||||
secondary={
|
||||
<Typography variant="caption" color="textSecondary">
|
||||
{f.size_bytes ? formatFileSize(f.size_bytes) : 'Unknown size'}
|
||||
{f.mime_type && ` • ${f.mime_type.split('/')[1]}`}
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
</ListItem>
|
||||
)}
|
||||
{/* Group separator between directories and files */}
|
||||
{index === getGroupSeparatorIndex && needsGroupSeparator && (
|
||||
<Divider sx={{ my: 1, borderStyle: 'dashed', borderColor: 'divider' }} />
|
||||
)}
|
||||
{/* Regular divider between items */}
|
||||
{index < sortedFiles.length - 1 && index !== getGroupSeparatorIndex && <Divider />}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Pagination Controls */}
|
||||
{pagination && pagination.total_pages > 1 && (
|
||||
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
|
||||
<Stack spacing={1} alignItems="center">
|
||||
<Pagination
|
||||
count={pagination.total_pages}
|
||||
page={pagination.page}
|
||||
onChange={(event, value) => setCurrentPage(value)}
|
||||
color="primary"
|
||||
size="small"
|
||||
showFirstButton
|
||||
showLastButton
|
||||
/>
|
||||
<Typography variant="caption" color="textSecondary">
|
||||
{pagination.offset + 1}-{Math.min(pagination.offset + pagination.per_page, pagination.total_count)} of {pagination.total_count}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Upload Controls */}
|
||||
<Box sx={{ mt: 2, display: 'flex', gap: 1, flexDirection: 'column' }}>
|
||||
{/* File Inputs */}
|
||||
<input
|
||||
id="cc-file-input"
|
||||
type="file"
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleUpload}
|
||||
disabled={!selectedCabinet}
|
||||
/>
|
||||
|
||||
<input
|
||||
id="cc-directory-input"
|
||||
type="file"
|
||||
style={{ display: 'none' }}
|
||||
{...({ webkitdirectory: '' } as React.InputHTMLAttributes<HTMLInputElement>)}
|
||||
multiple
|
||||
onChange={handleDirectorySelect}
|
||||
disabled={!selectedCabinet}
|
||||
/>
|
||||
|
||||
{/* Upload Buttons */}
|
||||
<Box sx={{ display: 'flex', gap: 1 }}>
|
||||
<Button
|
||||
variant="outlined"
|
||||
startIcon={<UploadIcon />}
|
||||
onClick={() => selectedCabinet && document.getElementById('cc-file-input')?.click()}
|
||||
disabled={!selectedCabinet}
|
||||
fullWidth
|
||||
>
|
||||
Upload File
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outlined"
|
||||
startIcon={<FolderOpenIcon />}
|
||||
onClick={() => selectedCabinet && document.getElementById('cc-directory-input')?.click()}
|
||||
disabled={!selectedCabinet}
|
||||
fullWidth
|
||||
>
|
||||
Upload Folder
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{!selectedCabinet && (
|
||||
<Typography variant="caption" color="text.secondary" sx={{ textAlign: 'center', mt: 0.5 }}>
|
||||
Select a cabinet first to enable uploads
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
{selectedCabinet && !isDirectoryPickerSupported() && (
|
||||
<Typography variant="caption" color="warning.main" sx={{ textAlign: 'center', mt: 0.5 }}>
|
||||
⚠️ Folder uploads may have limited support in this browser
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Menu
|
||||
anchorEl={menuAnchor?.el ?? null}
|
||||
open={!!menuAnchor}
|
||||
onClose={closeMenu}
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
|
||||
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
|
||||
>
|
||||
<MenuItem onClick={() => { if (menuAnchor) { handleGenerateInitial(menuAnchor.fileId); closeMenu(); } }}>Generate initial artefacts</MenuItem>
|
||||
<MenuItem onClick={goToAIContent}>Open AI content</MenuItem>
|
||||
</Menu>
|
||||
|
||||
{artefacts.length > 0 && (
|
||||
<>
|
||||
<Divider/>
|
||||
<List dense sx={{
|
||||
border: '1px solid var(--color-divider)',
|
||||
borderRadius: '4px',
|
||||
overflow: 'auto',
|
||||
maxHeight: 160,
|
||||
// Hide scrollbar while keeping scroll functionality
|
||||
scrollbarWidth: 'none', // Firefox
|
||||
'&::-webkit-scrollbar': {
|
||||
display: 'none' // WebKit browsers (Chrome, Safari, Edge)
|
||||
}
|
||||
}}>
|
||||
{artefacts.map(a => (
|
||||
<ListItem key={a.id}>
|
||||
<ListItemText primary={a.type} secondary={a.rel_path} />
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Directory Upload Dialog */}
|
||||
<Dialog
|
||||
open={showDirectoryDialog}
|
||||
onClose={() => !isDirectoryUploading && setShowDirectoryDialog(false)}
|
||||
maxWidth="md"
|
||||
fullWidth
|
||||
>
|
||||
<DialogTitle>
|
||||
<Box display="flex" alignItems="center" gap={1}>
|
||||
<FolderOpenIcon />
|
||||
Directory Upload
|
||||
{isDirectoryUploading && <LinearProgress sx={{ flexGrow: 1, ml: 2 }} />}
|
||||
</Box>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
{directoryStats && (
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
<Typography variant="body2">
|
||||
<strong>{directoryStats.fileCount} files</strong> in{' '}
|
||||
<strong>{directoryStats.directoryCount} folders</strong><br/>
|
||||
Total size: <strong>{directoryStats.formattedSize}</strong>
|
||||
</Typography>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Paper variant="outlined" sx={{
|
||||
p: 2,
|
||||
maxHeight: 200,
|
||||
overflow: 'auto',
|
||||
// Hide scrollbar while keeping scroll functionality
|
||||
scrollbarWidth: 'none', // Firefox
|
||||
'&::-webkit-scrollbar': {
|
||||
display: 'none' // WebKit browsers (Chrome, Safari, Edge)
|
||||
}
|
||||
}}>
|
||||
<Typography variant="body2" color="textSecondary" gutterBottom>
|
||||
Files to upload:
|
||||
</Typography>
|
||||
{selectedFiles.map((file, i) => (
|
||||
<Box key={i} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', py: 0.5 }}>
|
||||
<Typography variant="body2" sx={{ flex: 1, mr: 2 }} noWrap>
|
||||
{file.relativePath}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="textSecondary">
|
||||
{formatFileSize(file.size)}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
</Paper>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button onClick={() => setShowDirectoryDialog(false)} disabled={isDirectoryUploading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={startDirectoryUpload}
|
||||
variant="contained"
|
||||
disabled={isDirectoryUploading || selectedFiles.length === 0}
|
||||
>
|
||||
{isDirectoryUploading ? 'Uploading...' : 'Upload Directory'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Container>
|
||||
</ThemeProvider>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
import React, { useEffect, useMemo, useState, useRef } from 'react';
|
||||
import {
|
||||
ThemeProvider,
|
||||
createTheme,
|
||||
useMediaQuery,
|
||||
Button,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemText,
|
||||
IconButton,
|
||||
styled,
|
||||
CircularProgress,
|
||||
Divider,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Box,
|
||||
Typography,
|
||||
LinearProgress,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Chip,
|
||||
Tooltip,
|
||||
Alert
|
||||
} from '@mui/material';
|
||||
import UploadIcon from '@mui/icons-material/Upload';
|
||||
import FolderIcon from '@mui/icons-material/Folder';
|
||||
import FolderOpenIcon from '@mui/icons-material/FolderOpen';
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import RefreshIcon from '@mui/icons-material/Refresh';
|
||||
import MoreVertIcon from '@mui/icons-material/MoreVert';
|
||||
import ImageIcon from '@mui/icons-material/Image';
|
||||
import DescriptionIcon from '@mui/icons-material/Description';
|
||||
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
|
||||
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
|
||||
import { useTLDraw } from '../../../../../contexts/TLDrawContext';
|
||||
import { supabase } from '../../../../../supabaseClient';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
pickDirectory,
|
||||
processDirectoryFiles,
|
||||
calculateDirectoryStats,
|
||||
createDirectoryTree,
|
||||
formatFileSize,
|
||||
isDirectoryPickerSupported,
|
||||
FileWithPath
|
||||
} from '../../../../folderPicker';
|
||||
import pLimit from 'p-limit';
|
||||
|
||||
const Container = styled('div')(() => ({
|
||||
padding: '8px',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '8px',
|
||||
height: '100%'
|
||||
}));
|
||||
|
||||
const Row = styled('div')(() => ({
|
||||
display: 'flex',
|
||||
gap: '8px',
|
||||
alignItems: 'center'
|
||||
}));
|
||||
|
||||
type Cabinet = { id: string; name: string };
|
||||
type FileRow = { id: string; name: string; mime_type?: string; is_directory?: boolean; size_bytes?: number };
|
||||
type Artefact = { id: string; type: string; rel_path: string; created_at: string };
|
||||
|
||||
interface UploadProgress {
|
||||
path: string;
|
||||
size: number;
|
||||
status: 'queued' | 'uploading' | 'done' | 'error';
|
||||
progress: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const CCFilesPanelEnhanced: React.FC = () => {
|
||||
const { tldrawPreferences, authToken } = useTLDraw() as { tldrawPreferences?: { colorScheme?: 'light' | 'dark' | 'system' }, authToken?: string };
|
||||
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
|
||||
const [cabinets, setCabinets] = useState<Cabinet[]>([]);
|
||||
const [selectedCabinet, setSelectedCabinet] = useState<string>('');
|
||||
const [files, setFiles] = useState<FileRow[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [menuAnchor, setMenuAnchor] = useState<null | { el: HTMLElement; fileId: string }>(null);
|
||||
const [artefacts, setArtefacts] = useState<Artefact[]>([]);
|
||||
|
||||
// Directory upload states
|
||||
const [uploadProgress, setUploadProgress] = useState<UploadProgress[]>([]);
|
||||
const [showUploadDialog, setShowUploadDialog] = useState(false);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [selectedFiles, setSelectedFiles] = useState<FileWithPath[]>([]);
|
||||
const [directoryStats, setDirectoryStats] = useState<any>(null);
|
||||
|
||||
const navigate = useNavigate();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const dirInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const theme = useMemo(() => {
|
||||
const mode = (tldrawPreferences?.colorScheme === 'system')
|
||||
? (prefersDarkMode ? 'dark' : 'light')
|
||||
: (tldrawPreferences?.colorScheme === 'dark' ? 'dark' : 'light');
|
||||
return createTheme({ palette: { mode, divider: 'var(--color-divider)' } });
|
||||
}, [tldrawPreferences?.colorScheme, prefersDarkMode]);
|
||||
|
||||
type RequestInitLike = { method?: string; body?: FormData | string | Blob | null; headers?: Record<string, string> } | undefined;
|
||||
type HeadersInitLike = Record<string, string>;
|
||||
|
||||
const API_BASE: string = (import.meta as unknown as { env?: { VITE_API_BASE?: string } })?.env?.VITE_API_BASE || (location.port.startsWith('517') ? 'http://127.0.0.1:8080' : '/api');
|
||||
|
||||
const apiFetch = async (url: string, init?: RequestInitLike) => {
|
||||
const headers: HeadersInitLike = {
|
||||
'Authorization': `Bearer ${(await supabase.auth.getSession()).data.session?.access_token || authToken || ''}`,
|
||||
...(init?.headers || {})
|
||||
};
|
||||
const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`;
|
||||
const res = await fetch(fullUrl, { ...(init || {}), headers });
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
return res.json();
|
||||
};
|
||||
|
||||
const loadCabinets = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await apiFetch('/database/cabinets');
|
||||
const all = [...(data.owned || []), ...(data.shared || [])];
|
||||
setCabinets(all);
|
||||
if (all.length && !selectedCabinet) setSelectedCabinet(all[0].id);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadFiles = async (cabinetId: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await apiFetch(`/simple-upload/files?cabinet_id=${encodeURIComponent(cabinetId)}`);
|
||||
setFiles(data.files || []);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { loadCabinets(); }, []);
|
||||
useEffect(() => { if (selectedCabinet) loadFiles(selectedCabinet); }, [selectedCabinet]);
|
||||
|
||||
const handleSingleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!e.target.files || !selectedCabinet) return;
|
||||
const file = e.target.files[0];
|
||||
const form = new FormData();
|
||||
form.append('cabinet_id', selectedCabinet);
|
||||
form.append('path', file.name);
|
||||
form.append('scope', 'teacher');
|
||||
form.append('file', file);
|
||||
|
||||
try {
|
||||
await apiFetch('/simple-upload/files/upload', { method: 'POST', body: form });
|
||||
await loadFiles(selectedCabinet);
|
||||
(e.target as HTMLInputElement).value = '';
|
||||
} catch (error) {
|
||||
console.error('Upload failed:', error);
|
||||
alert(`Upload failed: ${error}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDirectoryPicker = async () => {
|
||||
try {
|
||||
const files = await pickDirectory();
|
||||
prepareDirectoryUpload(files);
|
||||
} catch (error: any) {
|
||||
if (error.message === 'fallback-input') {
|
||||
// Use fallback input
|
||||
dirInputRef.current?.click();
|
||||
} else if (error.message === 'user-cancelled') {
|
||||
// User cancelled, do nothing
|
||||
} else {
|
||||
console.error('Directory picker error:', error);
|
||||
alert('Failed to pick directory. Please try the fallback method.');
|
||||
dirInputRef.current?.click();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleFallbackDirectorySelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!e.target.files) return;
|
||||
const files = processDirectoryFiles(e.target.files);
|
||||
prepareDirectoryUpload(files);
|
||||
e.target.value = ''; // Reset input
|
||||
};
|
||||
|
||||
const prepareDirectoryUpload = (files: FileWithPath[]) => {
|
||||
if (files.length === 0) {
|
||||
alert('No files selected');
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedFiles(files);
|
||||
setDirectoryStats(calculateDirectoryStats(files));
|
||||
|
||||
// Initialize upload progress
|
||||
const progress: UploadProgress[] = files.map(file => ({
|
||||
path: file.relativePath,
|
||||
size: file.size,
|
||||
status: 'queued',
|
||||
progress: 0
|
||||
}));
|
||||
setUploadProgress(progress);
|
||||
setShowUploadDialog(true);
|
||||
};
|
||||
|
||||
const startDirectoryUpload = async () => {
|
||||
if (!selectedCabinet || selectedFiles.length === 0) return;
|
||||
|
||||
setIsUploading(true);
|
||||
|
||||
try {
|
||||
// Get directory name from first file's path
|
||||
const firstFilePath = selectedFiles[0].relativePath;
|
||||
const directoryName = firstFilePath.split('/')[0] || 'uploaded-folder';
|
||||
|
||||
// Prepare form data
|
||||
const formData = new FormData();
|
||||
formData.append('cabinet_id', selectedCabinet);
|
||||
formData.append('scope', 'teacher');
|
||||
formData.append('directory_name', directoryName);
|
||||
|
||||
// Add all files
|
||||
selectedFiles.forEach(file => {
|
||||
formData.append('files', file);
|
||||
});
|
||||
|
||||
// Add relative paths as JSON
|
||||
const relativePaths = selectedFiles.map(f => f.relativePath);
|
||||
formData.append('file_paths', JSON.stringify(relativePaths));
|
||||
|
||||
// Upload directory
|
||||
const result = await apiFetch('/simple-upload/files/upload-directory', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
console.log('Directory upload result:', result);
|
||||
|
||||
// Update progress to completed
|
||||
setUploadProgress(prev => prev.map(item => ({
|
||||
...item,
|
||||
status: 'done',
|
||||
progress: 100
|
||||
})));
|
||||
|
||||
// Refresh file list
|
||||
await loadFiles(selectedCabinet);
|
||||
|
||||
// Close dialog after a short delay
|
||||
setTimeout(() => {
|
||||
setShowUploadDialog(false);
|
||||
setIsUploading(false);
|
||||
setSelectedFiles([]);
|
||||
setUploadProgress([]);
|
||||
}, 2000);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Directory upload failed:', error);
|
||||
alert(`Directory upload failed: ${error}`);
|
||||
|
||||
// Mark all as error
|
||||
setUploadProgress(prev => prev.map(item => ({
|
||||
...item,
|
||||
status: 'error',
|
||||
error: String(error)
|
||||
})));
|
||||
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (fileId: string) => {
|
||||
try {
|
||||
await apiFetch(`/simple-upload/files/${fileId}`, { method: 'DELETE' });
|
||||
await loadFiles(selectedCabinet);
|
||||
} catch (error) {
|
||||
console.error('Delete failed:', error);
|
||||
alert(`Delete failed: ${error}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleGenerateInitial = async (fileId: string) => {
|
||||
// This would trigger manual processing if we implement it later
|
||||
alert('Manual processing not yet implemented');
|
||||
};
|
||||
|
||||
const openMenu = (el: HTMLElement, fileId: string) => setMenuAnchor({ el, fileId });
|
||||
const closeMenu = () => setMenuAnchor(null);
|
||||
|
||||
const goToAIContent = () => {
|
||||
if (!menuAnchor) return;
|
||||
const fileId = menuAnchor.fileId;
|
||||
closeMenu();
|
||||
navigate(`/doc-intelligence/${encodeURIComponent(fileId)}`);
|
||||
};
|
||||
|
||||
const iconForMime = (mime?: string, isDirectory?: boolean) => {
|
||||
if (isDirectory) return <FolderIcon />;
|
||||
if (!mime) return <InsertDriveFileIcon />;
|
||||
if (mime.startsWith('image/')) return <ImageIcon />;
|
||||
if (mime === 'application/pdf' || mime.startsWith('application/')) return <DescriptionIcon />;
|
||||
return <InsertDriveFileIcon />;
|
||||
};
|
||||
|
||||
const formatFileInfo = (file: FileRow) => {
|
||||
if (file.is_directory) {
|
||||
return `Directory • ${file.size_bytes ? formatFileSize(file.size_bytes) : 'Unknown size'}`;
|
||||
}
|
||||
return file.size_bytes ? formatFileSize(file.size_bytes) : 'Unknown size';
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeProvider theme={theme}>
|
||||
<Container>
|
||||
<Row>
|
||||
<Button size="small" startIcon={<RefreshIcon/>} onClick={loadCabinets}>Refresh</Button>
|
||||
</Row>
|
||||
|
||||
<List dense sx={{ border: '1px solid var(--color-divider)', borderRadius: '4px', overflow: 'auto', maxHeight: 140 }}>
|
||||
{cabinets.map(c => (
|
||||
<ListItem key={c.id} selected={c.id === selectedCabinet} onClick={() => setSelectedCabinet(c.id)} sx={{ cursor: 'pointer' }}>
|
||||
<FolderIcon sx={{ mr: 1 }}/>
|
||||
<ListItemText primary={c.name} secondary={c.id} />
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
|
||||
<Divider/>
|
||||
|
||||
<Row>
|
||||
{/* Single file upload */}
|
||||
<input id="cc-file-input" type="file" style={{ display: 'none' }} onChange={handleSingleUpload}/>
|
||||
<label htmlFor="cc-file-input">
|
||||
<Button size="small" variant="outlined" startIcon={<UploadIcon/>} component="span" disabled={!selectedCabinet}>
|
||||
Upload File
|
||||
</Button>
|
||||
</label>
|
||||
|
||||
{/* Directory upload */}
|
||||
<input
|
||||
ref={dirInputRef}
|
||||
type="file"
|
||||
style={{ display: 'none' }}
|
||||
webkitdirectory=""
|
||||
multiple
|
||||
onChange={handleFallbackDirectorySelect}
|
||||
/>
|
||||
|
||||
<Tooltip title={isDirectoryPickerSupported() ? "Uses modern directory picker" : "Uses fallback method"}>
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
startIcon={<FolderOpenIcon/>}
|
||||
onClick={handleDirectoryPicker}
|
||||
disabled={!selectedCabinet}
|
||||
>
|
||||
Upload Folder
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Row>
|
||||
|
||||
{loading ? <CircularProgress size={20}/> : (
|
||||
<List dense sx={{ border: '1px solid var(--color-divider)', borderRadius: '4px', overflow: 'auto', flex: 1 }}>
|
||||
{files.map(f => (
|
||||
<ListItem key={f.id}
|
||||
secondaryAction={
|
||||
<>
|
||||
<IconButton size="small" onClick={(e) => openMenu(e.currentTarget, f.id)} title="File actions">
|
||||
<MoreVertIcon/>
|
||||
</IconButton>
|
||||
<IconButton edge="end" size="small" onClick={() => handleDelete(f.id)} title="Delete file">
|
||||
<DeleteIcon/>
|
||||
</IconButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{iconForMime(f.mime_type, f.is_directory)}
|
||||
<ListItemText
|
||||
sx={{ ml: 1 }}
|
||||
primary={f.name}
|
||||
secondary={formatFileInfo(f)}
|
||||
/>
|
||||
{f.is_directory && <Chip label="Directory" size="small" />}
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
|
||||
<Menu
|
||||
anchorEl={menuAnchor?.el ?? null}
|
||||
open={!!menuAnchor}
|
||||
onClose={closeMenu}
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
|
||||
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
|
||||
>
|
||||
<MenuItem onClick={() => { if (menuAnchor) { handleGenerateInitial(menuAnchor.fileId); closeMenu(); } }}>
|
||||
Process manually
|
||||
</MenuItem>
|
||||
<MenuItem onClick={goToAIContent}>Open AI content</MenuItem>
|
||||
</Menu>
|
||||
|
||||
{/* Directory Upload Dialog */}
|
||||
<Dialog open={showUploadDialog} onClose={() => !isUploading && setShowUploadDialog(false)} maxWidth="md" fullWidth>
|
||||
<DialogTitle>
|
||||
<Box display="flex" alignItems="center" gap={1}>
|
||||
<CloudUploadIcon />
|
||||
Directory Upload
|
||||
{isUploading && <CircularProgress size={20} />}
|
||||
</Box>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
{directoryStats && (
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Alert severity="info">
|
||||
<Typography variant="body2">
|
||||
<strong>{directoryStats.fileCount} files</strong> in{' '}
|
||||
<strong>{directoryStats.directoryCount} folders</strong><br/>
|
||||
Total size: <strong>{directoryStats.formattedSize}</strong>
|
||||
</Typography>
|
||||
</Alert>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Upload Progress
|
||||
</Typography>
|
||||
|
||||
{uploadProgress.length > 0 && (
|
||||
<>
|
||||
<Box sx={{ mb: 1 }}>
|
||||
<Typography variant="body2" color="textSecondary">
|
||||
{uploadProgress.filter(p => p.status === 'done').length} / {uploadProgress.length} files completed
|
||||
</Typography>
|
||||
<LinearProgress
|
||||
variant="determinate"
|
||||
value={(uploadProgress.filter(p => p.status === 'done').length / uploadProgress.length) * 100}
|
||||
sx={{ mt: 1 }}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ maxHeight: 300, overflow: 'auto', border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
|
||||
<table style={{ width: '100%', fontSize: '0.875rem' }}>
|
||||
<thead>
|
||||
<tr style={{ borderBottom: '1px solid', backgroundColor: 'rgba(0,0,0,0.05)' }}>
|
||||
<th style={{ textAlign: 'left', padding: '8px' }}>Path</th>
|
||||
<th style={{ textAlign: 'right', padding: '8px' }}>Size</th>
|
||||
<th style={{ textAlign: 'center', padding: '8px' }}>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{uploadProgress.map((item, i) => (
|
||||
<tr key={i} style={{ borderBottom: '1px solid rgba(0,0,0,0.1)' }}>
|
||||
<td style={{ padding: '4px 8px', maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{item.path}
|
||||
</td>
|
||||
<td style={{ padding: '4px 8px', textAlign: 'right' }}>
|
||||
{formatFileSize(item.size)}
|
||||
</td>
|
||||
<td style={{ padding: '4px 8px', textAlign: 'center' }}>
|
||||
<Chip
|
||||
label={item.status}
|
||||
size="small"
|
||||
color={
|
||||
item.status === 'done' ? 'success' :
|
||||
item.status === 'error' ? 'error' :
|
||||
item.status === 'uploading' ? 'primary' : 'default'
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button onClick={() => setShowUploadDialog(false)} disabled={isUploading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={startDirectoryUpload}
|
||||
variant="contained"
|
||||
disabled={isUploading || selectedFiles.length === 0}
|
||||
startIcon={isUploading ? <CircularProgress size={16} /> : <CloudUploadIcon />}
|
||||
>
|
||||
{isUploading ? 'Uploading...' : 'Start Upload'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Container>
|
||||
</ThemeProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default CCFilesPanelEnhanced;
|
||||
@@ -4,11 +4,21 @@ export const PANEL_DIMENSIONS = {
|
||||
topOffset: `0px`,
|
||||
bottomOffset: '0px',
|
||||
},
|
||||
'cabinets': {
|
||||
width: '300px',
|
||||
topOffset: `0px`,
|
||||
bottomOffset: '0px',
|
||||
},
|
||||
'node-snapshot': {
|
||||
width: '300px',
|
||||
topOffset: `0px`,
|
||||
bottomOffset: '0px',
|
||||
},
|
||||
'files': {
|
||||
width: '300px',
|
||||
topOffset: `0px`,
|
||||
bottomOffset: '0px',
|
||||
},
|
||||
'cc-shapes': {
|
||||
width: '300px',
|
||||
topOffset: `0px`,
|
||||
|
||||
Reference in New Issue
Block a user