Ajout de la visualisation des pdf dans le front

This commit is contained in:
2025-10-06 00:43:59 +02:00
parent 8ae9754fde
commit 79bfae4ba8
12 changed files with 1318 additions and 8 deletions

View File

@@ -1,12 +1,93 @@
# React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
# MyDocManager Frontend
Currently, two official plugins are available:
## Overview
MyDocManager Frontend is a modern web application built with React and Vite that serves as the user interface for the MyDocManager document management system. The application provides a seamless experience for users to manage, process, and organize their documents with an intuitive and responsive interface.
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Project Structure
frontend/
├── public/ # Public assets and static files
├── src/ # Source code
│ ├── assets/ # Icons, images, and other static assets
│ ├── components/ # Reusable UI components
│ │ ├── auth/ # Authentication-related components
│ │ └── common/ # Shared components (Header, Layout, etc.)
│ ├── contexts/ # React contexts for state management
│ ├── hooks/ # Custom React hooks
│ ├── pages/ # Page components representing full views
│ ├── services/ # API service interfaces
│ └── utils/ # Utility functions and helpers
├── Dockerfile # Container configuration for deployment
├── package.json # Dependencies and scripts
├── tailwind.config.js # Tailwind CSS configuration
└── vite.config.js # Vite bundler configuration
## Expanding the ESLint configuration
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
## Key Components
### Authentication
- **AuthContext**: Provides authentication state and methods throughout the application
- **AuthLayout**: Layout wrapper specifically for authentication screens
- **LoginForm**: Form component for user authentication
- **ProtectedRoute**: Route guard that ensures authenticated access to protected pages
### UI Components
- **Layout**: Main application layout structure with menu and content areas
- **Header**: Application header with navigation and user controls
- **Menu**: Side navigation menu with application links
- **ThemeSwitcher**: Toggle for switching between light and dark themes
### Pages
- **LoginPage**: User authentication page
- **DashboardPage**: Main dashboard view for authenticated users
### Services
- **authService**: Handles API communication for authentication operations
- **api**: Base API utility for making HTTP requests to the backend
## Getting Started
### Prerequisites
- Node.js (latest LTS version)
- npm or yarn package manager
### Installation
1. Clone the repository
2. Navigate to the frontend directory
3. Install dependencies:
```
npm install
```
### Development
Run the development server:
```
npm run dev
```
This will start the application in development mode at http://localhost:5173
### Building for Production
Create a production build:
```
npm run build
```
## Technologies
- React 19.1.1
- Vite 7.1.2
- Tailwind CSS 4.1.13
- DaisyUI 5.1.24
- React Router 7.9.3
- Axios for API requests
## Features
- Responsive design with Tailwind CSS
- Authentication and authorization
- Light/dark theme support
- Document management interface
- Secure API communication
## Project Integration
This frontend application works in conjunction with the backend services and workers defined in other parts of the MyDocManager project to provide a complete document management solution.

View File

@@ -4,6 +4,7 @@ import ProtectedRoute from './components/common/ProtectedRoute';
import Layout from './components/common/Layout';
import LoginPage from './pages/LoginPage';
import DashboardPage from './pages/DashboardPage';
import DocumentsPage from './pages/DocumentsPage';
function App() {
return (
@@ -16,7 +17,8 @@ function App() {
{/* Protected Routes */}
<Route path="/" element={<ProtectedRoute><Layout /></ProtectedRoute>}>
<Route index element={<Navigate to="/dashboard" replace />} />
<Route index element={<Navigate to="/documents" replace />} />
<Route path="documents" element={<DocumentsPage />} />
<Route path="dashboard" element={<DashboardPage />} />
<Route path="documents" element={<div>Documents Page - Coming Soon</div>} />
<Route path="users" element={<div>User Management - Coming Soon</div>} />

View File

@@ -0,0 +1,68 @@
/**
* DeleteConfirmModal Component
* Modal dialog to confirm document deletion
*/
import React from 'react';
/**
* DeleteConfirmModal component
* @param {Object} props
* @param {boolean} props.isOpen - Whether the modal is open
* @param {Object|null} props.document - Document to delete
* @param {function(): void} props.onClose - Callback when modal is closed
* @param {function(): void} props.onConfirm - Callback when deletion is confirmed
* @param {boolean} props.isDeleting - Whether deletion is in progress
* @returns {JSX.Element}
*/
const DeleteConfirmModal = ({
isOpen,
document,
onClose,
onConfirm,
isDeleting = false
}) => {
if (!isOpen || !document) return null;
return (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold text-lg">Confirm Deletion</h3>
<p className="py-4">
Are you sure you want to delete <span className="font-semibold">"{document.name}"</span>?
</p>
<p className="text-sm text-gray-500">
This action cannot be undone.
</p>
<div className="modal-action">
<button
className="btn btn-ghost"
onClick={onClose}
disabled={isDeleting}
>
Cancel
</button>
<button
className="btn btn-error"
onClick={onConfirm}
disabled={isDeleting}
>
{isDeleting ? (
<>
<span className="loading loading-spinner loading-sm"></span>
Deleting...
</>
) : (
'Delete'
)}
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop" onClick={onClose}>
<button disabled={isDeleting}>close</button>
</form>
</dialog>
);
};
export default DeleteConfirmModal;

View File

@@ -0,0 +1,193 @@
/**
* DocumentCard Component
* Displays a document as a DaisyUI card with thumbnail and metadata
* Supports different view modes: small, large, and detail
*/
import React, { memo } from 'react';
/**
* Formats file size to human-readable format
* @param {number} bytes - File size in bytes
* @returns {string} Formatted file size
*/
const formatFileSize = (bytes) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
};
/**
* Formats date to localized string
* @param {string} dateString - ISO date string
* @returns {string} Formatted date
*/
const formatDate = (dateString) => {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
};
/**
* DocumentCard component
* @param {Object} props
* @param {Object} props.document - Document object
* @param {'small'|'large'|'detail'} props.viewMode - Current view mode
* @param {function(): void} props.onEdit - Callback when edit is clicked
* @param {function(): void} props.onDelete - Callback when delete is clicked
* @returns {JSX.Element}
*/
const DocumentCard = memo(({ document, viewMode, onEdit, onDelete }) => {
const { name, originalFileType, thumbnailUrl, pageCount, fileSize, createdAt, tags, categories } = document;
// Determine card classes based on view mode
const getCardClasses = () => {
const baseClasses = 'card bg-base-100 shadow-xl hover:shadow-2xl transition-shadow group relative';
switch (viewMode) {
case 'small':
return `${baseClasses} w-full`;
case 'large':
return `${baseClasses} w-full`;
case 'detail':
return `${baseClasses} w-full`;
default:
return baseClasses;
}
};
// Render thumbnail with hover actions
const renderThumbnail = () => (
<figure className="relative overflow-hidden">
<img
src={thumbnailUrl}
alt={`${name} thumbnail`}
className={`w-full object-cover ${
viewMode === 'small' ? 'h-32' : viewMode === 'large' ? 'h-48' : 'h-64'
}`}
loading="lazy"
/>
{/* Hover overlay with actions */}
<div className="absolute top-2 right-2 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
<button
className="btn btn-sm btn-circle btn-primary"
onClick={onEdit}
aria-label="Edit document"
title="Edit"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</button>
<button
className="btn btn-sm btn-circle btn-error"
onClick={onDelete}
aria-label="Delete document"
title="Delete"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
{/* File type badge */}
<div className="absolute bottom-2 left-2">
<span className="badge badge-accent badge-sm">{originalFileType}</span>
</div>
</figure>
);
// Render card body based on view mode
const renderCardBody = () => {
if (viewMode === 'small') {
return (
<div className="card-body p-3">
<h3 className="card-title text-sm truncate" title={name}>{name}</h3>
<p className="text-xs text-gray-500">{pageCount} page{pageCount > 1 ? 's' : ''}</p>
</div>
);
}
if (viewMode === 'large') {
return (
<div className="card-body p-4">
<h3 className="card-title text-base truncate" title={name}>{name}</h3>
<div className="flex flex-wrap gap-1 mb-2">
{tags.slice(0, 3).map(tag => (
<span key={tag} className="badge badge-primary badge-xs">{tag}</span>
))}
{tags.length > 3 && (
<span className="badge badge-ghost badge-xs">+{tags.length - 3}</span>
)}
</div>
<div className="text-sm space-y-1">
<p className="text-gray-500">{pageCount} page{pageCount > 1 ? 's' : ''}</p>
<p className="text-gray-500">{formatFileSize(fileSize)}</p>
</div>
</div>
);
}
// Detail mode
return (
<div className="card-body">
<h3 className="card-title text-lg" title={name}>{name}</h3>
{/* Tags */}
{tags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-2">
{tags.map(tag => (
<span key={tag} className="badge badge-primary badge-sm">{tag}</span>
))}
</div>
)}
{/* Categories */}
{categories.length > 0 && (
<div className="flex flex-wrap gap-1 mb-3">
{categories.map(category => (
<span key={category} className="badge badge-secondary badge-sm">{category}</span>
))}
</div>
)}
{/* Metadata */}
<div className="grid grid-cols-2 gap-2 text-sm">
<div>
<span className="font-semibold">Pages:</span>
<span className="ml-2 text-gray-500">{pageCount}</span>
</div>
<div>
<span className="font-semibold">Size:</span>
<span className="ml-2 text-gray-500">{formatFileSize(fileSize)}</span>
</div>
<div>
<span className="font-semibold">Type:</span>
<span className="ml-2 text-gray-500">{originalFileType}</span>
</div>
<div>
<span className="font-semibold">Date:</span>
<span className="ml-2 text-gray-500">{formatDate(createdAt)}</span>
</div>
</div>
</div>
);
};
return (
<div className={getCardClasses()}>
{renderThumbnail()}
{renderCardBody()}
</div>
);
});
DocumentCard.displayName = 'DocumentCard';
export default DocumentCard;

View File

@@ -0,0 +1,164 @@
/**
* DocumentDetailView Component
* Displays a document in detail mode with all pages visible
* This is a placeholder that shows multiple page thumbnails
* When real PDF backend is ready, this can be replaced with actual PDF rendering
*/
import React from 'react';
/**
* Formats file size to human-readable format
* @param {number} bytes - File size in bytes
* @returns {string} Formatted file size
*/
const formatFileSize = (bytes) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
};
/**
* Formats date to localized string
* @param {string} dateString - ISO date string
* @returns {string} Formatted date
*/
const formatDate = (dateString) => {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
/**
* DocumentDetailView component
* @param {Object} props
* @param {Object} props.document - Document object
* @param {function(): void} props.onEdit - Callback when edit is clicked
* @param {function(): void} props.onDelete - Callback when delete is clicked
* @returns {JSX.Element}
*/
const DocumentDetailView = ({ document, onEdit, onDelete }) => {
const {
name,
originalFileType,
thumbnailUrl,
pageCount,
fileSize,
createdAt,
tags,
categories
} = document;
// Generate placeholder pages (in real implementation, these would be actual PDF pages)
const pages = Array.from({ length: pageCount }, (_, i) => ({
pageNumber: i + 1,
thumbnailUrl: thumbnailUrl.replace('Page+1', `Page+${i + 1}`)
}));
return (
<div className="card bg-base-100 shadow-xl">
{/* Header with actions */}
<div className="card-body">
<div className="flex justify-between items-start mb-4">
<div className="flex-1">
<h2 className="card-title text-2xl mb-2">{name}</h2>
{/* Tags */}
{tags.length > 0 && (
<div className="flex flex-wrap gap-2 mb-2">
<span className="text-sm font-semibold text-gray-600">Tags:</span>
{tags.map(tag => (
<span key={tag} className="badge badge-primary">{tag}</span>
))}
</div>
)}
{/* Categories */}
{categories.length > 0 && (
<div className="flex flex-wrap gap-2 mb-3">
<span className="text-sm font-semibold text-gray-600">Categories:</span>
{categories.map(category => (
<span key={category} className="badge badge-secondary">{category}</span>
))}
</div>
)}
</div>
{/* Action buttons */}
<div className="flex gap-2">
<button
className="btn btn-primary btn-sm"
onClick={onEdit}
aria-label="Edit document"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
Edit
</button>
<button
className="btn btn-error btn-sm"
onClick={onDelete}
aria-label="Delete document"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
Delete
</button>
</div>
</div>
{/* Metadata grid */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6 p-4 bg-base-200 rounded-lg">
<div>
<span className="text-sm font-semibold text-gray-600">Original Type</span>
<p className="text-lg">{originalFileType}</p>
</div>
<div>
<span className="text-sm font-semibold text-gray-600">Pages</span>
<p className="text-lg">{pageCount}</p>
</div>
<div>
<span className="text-sm font-semibold text-gray-600">File Size</span>
<p className="text-lg">{formatFileSize(fileSize)}</p>
</div>
<div>
<span className="text-sm font-semibold text-gray-600">Created</span>
<p className="text-lg">{formatDate(createdAt)}</p>
</div>
</div>
{/* Pages preview */}
<div>
<h3 className="text-lg font-semibold mb-4">Document Pages ({pageCount})</h3>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{pages.map((page) => (
<div key={page.pageNumber} className="relative group">
<div className="aspect-[3/4] bg-base-200 rounded-lg overflow-hidden shadow-md hover:shadow-xl transition-shadow">
<img
src={page.thumbnailUrl}
alt={`Page ${page.pageNumber}`}
className="w-full h-full object-cover"
loading="lazy"
/>
</div>
<div className="text-center mt-2">
<span className="text-sm text-gray-600">Page {page.pageNumber}</span>
</div>
</div>
))}
</div>
</div>
</div>
</div>
);
};
export default DocumentDetailView;

View File

@@ -0,0 +1,180 @@
/**
* DocumentGallery Component
* Main container for displaying documents in different view modes
*/
import React, { useState } from 'react';
import DocumentCard from './DocumentCard';
import DocumentDetailView from './DocumentDetailView';
import ViewModeSwitcher from './ViewModeSwitcher';
import EditDocumentModal from './EditDocumentModal';
import DeleteConfirmModal from './DeleteConfirmModal';
import { useDocuments } from '../../hooks/useDocuments';
/**
* DocumentGallery component
* @returns {JSX.Element}
*/
const DocumentGallery = () => {
const { documents, loading, error, updateDocument, deleteDocument } = useDocuments();
const [viewMode, setViewMode] = useState('large');
const [editingDocument, setEditingDocument] = useState(null);
const [deletingDocument, setDeletingDocument] = useState(null);
const [isSaving, setIsSaving] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
/**
* Handles opening the edit modal
* @param {Object} document - Document to edit
*/
const handleEditClick = (document) => {
setEditingDocument(document);
};
/**
* Handles opening the delete confirmation modal
* @param {Object} document - Document to delete
*/
const handleDeleteClick = (document) => {
setDeletingDocument(document);
};
/**
* Handles saving document changes
* @param {Object} updates - Updates object with tags and categories
*/
const handleSaveEdit = async (updates) => {
if (!editingDocument) return;
setIsSaving(true);
const success = await updateDocument(editingDocument.id, updates);
setIsSaving(false);
if (success) {
setEditingDocument(null);
}
};
/**
* Handles confirming document deletion
*/
const handleConfirmDelete = async () => {
if (!deletingDocument) return;
setIsDeleting(true);
const success = await deleteDocument(deletingDocument.id);
setIsDeleting(false);
if (success) {
setDeletingDocument(null);
}
};
/**
* Gets grid classes based on view mode
* @returns {string} Tailwind CSS classes
*/
const getGridClasses = () => {
switch (viewMode) {
case 'small':
return 'grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4';
case 'large':
return 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6';
case 'detail':
return 'flex flex-col gap-6';
default:
return 'grid grid-cols-1 gap-4';
}
};
// Loading state
if (loading) {
return (
<div className="flex justify-center items-center min-h-[400px]">
<span className="loading loading-spinner loading-lg"></span>
</div>
);
}
// Error state
if (error) {
return (
<div className="alert alert-error">
<svg xmlns="http://www.w3.org/2000/svg" className="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>Error loading documents: {error}</span>
</div>
);
}
// Empty state
if (documents.length === 0) {
return (
<div className="flex flex-col items-center justify-center min-h-[400px] text-center">
<svg xmlns="http://www.w3.org/2000/svg" className="h-24 w-24 text-gray-300 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<h3 className="text-xl font-semibold mb-2">No documents yet</h3>
<p className="text-gray-500">Upload your first document to get started</p>
</div>
);
}
return (
<div>
{/* Header with view mode switcher */}
<div className="flex justify-between items-center mb-6">
<div>
<h2 className="text-2xl font-bold">Documents</h2>
<p className="text-gray-500">{documents.length} document{documents.length !== 1 ? 's' : ''}</p>
</div>
<ViewModeSwitcher
currentMode={viewMode}
onModeChange={setViewMode}
/>
</div>
{/* Document grid/list */}
<div className={getGridClasses()}>
{documents.map(document => (
viewMode === 'detail' ? (
<DocumentDetailView
key={document.id}
document={document}
onEdit={() => handleEditClick(document)}
onDelete={() => handleDeleteClick(document)}
/>
) : (
<DocumentCard
key={document.id}
document={document}
viewMode={viewMode}
onEdit={() => handleEditClick(document)}
onDelete={() => handleDeleteClick(document)}
/>
)
))}
</div>
{/* Modals */}
<EditDocumentModal
isOpen={!!editingDocument}
document={editingDocument}
onClose={() => setEditingDocument(null)}
onSave={handleSaveEdit}
isSaving={isSaving}
/>
<DeleteConfirmModal
isOpen={!!deletingDocument}
document={deletingDocument}
onClose={() => setDeletingDocument(null)}
onConfirm={handleConfirmDelete}
isDeleting={isDeleting}
/>
</div>
);
};
export default DocumentGallery;

View File

@@ -0,0 +1,225 @@
/**
* EditDocumentModal Component
* Modal dialog for editing document tags and categories
*/
import React, { useState, useEffect } from 'react';
import { getAvailableTags, getAvailableCategories } from '../../services/documentService';
/**
* EditDocumentModal component
* @param {Object} props
* @param {boolean} props.isOpen - Whether the modal is open
* @param {Object|null} props.document - Document to edit
* @param {function(): void} props.onClose - Callback when modal is closed
* @param {function(Object): void} props.onSave - Callback when changes are saved
* @param {boolean} props.isSaving - Whether save is in progress
* @returns {JSX.Element}
*/
const EditDocumentModal = ({
isOpen,
document,
onClose,
onSave,
isSaving = false
}) => {
const [selectedTags, setSelectedTags] = useState([]);
const [selectedCategories, setSelectedCategories] = useState([]);
const [availableTags, setAvailableTags] = useState([]);
const [availableCategories, setAvailableCategories] = useState([]);
const [newTag, setNewTag] = useState('');
const [newCategory, setNewCategory] = useState('');
// Load available tags and categories
useEffect(() => {
const loadOptions = async () => {
const [tags, categories] = await Promise.all([
getAvailableTags(),
getAvailableCategories()
]);
setAvailableTags(tags);
setAvailableCategories(categories);
};
loadOptions();
}, []);
// Initialize selected values when document changes
useEffect(() => {
if (document) {
setSelectedTags(document.tags || []);
setSelectedCategories(document.categories || []);
}
}, [document]);
const handleAddTag = (tag) => {
if (tag && !selectedTags.includes(tag)) {
setSelectedTags([...selectedTags, tag]);
}
setNewTag('');
};
const handleRemoveTag = (tag) => {
setSelectedTags(selectedTags.filter(t => t !== tag));
};
const handleAddCategory = (category) => {
if (category && !selectedCategories.includes(category)) {
setSelectedCategories([...selectedCategories, category]);
}
setNewCategory('');
};
const handleRemoveCategory = (category) => {
setSelectedCategories(selectedCategories.filter(c => c !== category));
};
const handleSave = () => {
onSave({
tags: selectedTags,
categories: selectedCategories
});
};
if (!isOpen || !document) return null;
return (
<dialog className="modal modal-open">
<div className="modal-box max-w-2xl">
<h3 className="font-bold text-lg mb-4">Edit Document</h3>
<div className="mb-4">
<p className="text-sm text-gray-500">
Document: <span className="font-semibold">{document.name}</span>
</p>
</div>
{/* Tags Section */}
<div className="mb-6">
<label className="label">
<span className="label-text font-semibold">Tags</span>
</label>
{/* Selected Tags */}
<div className="flex flex-wrap gap-2 mb-3">
{selectedTags.map(tag => (
<div key={tag} className="badge badge-primary gap-2">
{tag}
<button
type="button"
className="btn btn-ghost btn-xs"
onClick={() => handleRemoveTag(tag)}
disabled={isSaving}
>
</button>
</div>
))}
</div>
{/* Add Tag */}
<div className="flex gap-2">
<select
className="select select-bordered flex-1"
value={newTag}
onChange={(e) => setNewTag(e.target.value)}
disabled={isSaving}
>
<option value="">Select a tag...</option>
{availableTags
.filter(tag => !selectedTags.includes(tag))
.map(tag => (
<option key={tag} value={tag}>{tag}</option>
))
}
</select>
<button
className="btn btn-primary"
onClick={() => handleAddTag(newTag)}
disabled={!newTag || isSaving}
>
Add
</button>
</div>
</div>
{/* Categories Section */}
<div className="mb-6">
<label className="label">
<span className="label-text font-semibold">Categories</span>
</label>
{/* Selected Categories */}
<div className="flex flex-wrap gap-2 mb-3">
{selectedCategories.map(category => (
<div key={category} className="badge badge-secondary gap-2">
{category}
<button
type="button"
className="btn btn-ghost btn-xs"
onClick={() => handleRemoveCategory(category)}
disabled={isSaving}
>
</button>
</div>
))}
</div>
{/* Add Category */}
<div className="flex gap-2">
<select
className="select select-bordered flex-1"
value={newCategory}
onChange={(e) => setNewCategory(e.target.value)}
disabled={isSaving}
>
<option value="">Select a category...</option>
{availableCategories
.filter(cat => !selectedCategories.includes(cat))
.map(cat => (
<option key={cat} value={cat}>{cat}</option>
))
}
</select>
<button
className="btn btn-secondary"
onClick={() => handleAddCategory(newCategory)}
disabled={!newCategory || isSaving}
>
Add
</button>
</div>
</div>
<div className="modal-action">
<button
className="btn btn-ghost"
onClick={onClose}
disabled={isSaving}
>
Cancel
</button>
<button
className="btn btn-primary"
onClick={handleSave}
disabled={isSaving}
>
{isSaving ? (
<>
<span className="loading loading-spinner loading-sm"></span>
Saving...
</>
) : (
'Save Changes'
)}
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop" onClick={onClose}>
<button disabled={isSaving}>close</button>
</form>
</dialog>
);
};
export default EditDocumentModal;

View File

@@ -0,0 +1,46 @@
/**
* ViewModeSwitcher Component
* Allows users to switch between different view modes (small, large, detail)
*/
import React from 'react';
/**
* @typedef {'small' | 'large' | 'detail'} ViewMode
*/
/**
* ViewModeSwitcher component
* @param {Object} props
* @param {ViewMode} props.currentMode - Current active view mode
* @param {function(ViewMode): void} props.onModeChange - Callback when mode changes
* @returns {JSX.Element}
*/
const ViewModeSwitcher = ({ currentMode, onModeChange }) => {
const modes = [
{ id: 'small', label: 'Small', icon: '⊞' },
{ id: 'large', label: 'Large', icon: '⊡' },
{ id: 'detail', label: 'Detail', icon: '☰' }
];
return (
<div className="flex gap-2">
{modes.map(mode => (
<button
key={mode.id}
onClick={() => onModeChange(mode.id)}
className={`btn btn-sm ${
currentMode === mode.id ? 'btn-primary' : 'btn-ghost'
}`}
aria-label={`Switch to ${mode.label} view`}
title={`${mode.label} view`}
>
<span className="text-lg">{mode.icon}</span>
<span className="hidden sm:inline ml-1">{mode.label}</span>
</button>
))}
</div>
);
};
export default ViewModeSwitcher;

View File

@@ -0,0 +1,85 @@
/**
* Custom hook for managing documents
* Handles fetching, updating, and deleting documents
*/
import { useState, useEffect, useCallback } from 'react';
import * as documentService from '../services/documentService';
/**
* Hook for managing documents state and operations
* @returns {Object} Documents state and operations
*/
export const useDocuments = () => {
const [documents, setDocuments] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
/**
* Fetches all documents from the service
*/
const fetchDocuments = useCallback(async () => {
try {
setLoading(true);
setError(null);
const data = await documentService.getAllDocuments();
setDocuments(data);
} catch (err) {
setError(err.message);
console.error('Error fetching documents:', err);
} finally {
setLoading(false);
}
}, []);
/**
* Updates a document's tags and categories
* @param {string} id - Document ID
* @param {Object} updates - Updates object
* @returns {Promise<boolean>} Success status
*/
const updateDocument = useCallback(async (id, updates) => {
try {
const updatedDoc = await documentService.updateDocument(id, updates);
setDocuments(prevDocs =>
prevDocs.map(doc => (doc.id === id ? updatedDoc : doc))
);
return true;
} catch (err) {
setError(err.message);
console.error('Error updating document:', err);
return false;
}
}, []);
/**
* Deletes a document
* @param {string} id - Document ID
* @returns {Promise<boolean>} Success status
*/
const deleteDocument = useCallback(async (id) => {
try {
await documentService.deleteDocument(id);
setDocuments(prevDocs => prevDocs.filter(doc => doc.id !== id));
return true;
} catch (err) {
setError(err.message);
console.error('Error deleting document:', err);
return false;
}
}, []);
// Fetch documents on mount
useEffect(() => {
fetchDocuments();
}, [fetchDocuments]);
return {
documents,
loading,
error,
fetchDocuments,
updateDocument,
deleteDocument
};
};

View File

@@ -0,0 +1,21 @@
/**
* DocumentsPage Component
* Main page for displaying and managing documents
*/
import React from 'react';
import DocumentGallery from '../components/documents/DocumentGallery';
/**
* DocumentsPage component
* @returns {JSX.Element}
*/
const DocumentsPage = () => {
return (
<div className="container mx-auto px-4 py-8">
<DocumentGallery />
</div>
);
};
export default DocumentsPage;

View File

@@ -0,0 +1,90 @@
/**
* Document Service
* Handles all API calls related to documents
* Currently using mock data for development
*/
import { mockDocuments, availableTags, availableCategories } from '../utils/mockData';
// Simulate network delay
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
/**
* Fetches all documents
* @returns {Promise<Array>} Array of document objects
*/
export const getAllDocuments = async () => {
await delay(500); // Simulate network latency
return [...mockDocuments];
};
/**
* Fetches a single document by ID
* @param {string} id - Document ID
* @returns {Promise<Object|null>} Document object or null if not found
*/
export const getDocumentById = async (id) => {
await delay(300);
const document = mockDocuments.find(doc => doc.id === id);
return document || null;
};
/**
* Updates a document's tags and categories
* @param {string} id - Document ID
* @param {Object} updates - Object containing tags and/or categories
* @param {Array<string>} updates.tags - New tags array
* @param {Array<string>} updates.categories - New categories array
* @returns {Promise<Object>} Updated document object
*/
export const updateDocument = async (id, updates) => {
await delay(400);
const index = mockDocuments.findIndex(doc => doc.id === id);
if (index === -1) {
throw new Error('Document not found');
}
// Update the document
mockDocuments[index] = {
...mockDocuments[index],
...updates
};
return mockDocuments[index];
};
/**
* Deletes a document
* @param {string} id - Document ID
* @returns {Promise<boolean>} True if deletion was successful
*/
export const deleteDocument = async (id) => {
await delay(300);
const index = mockDocuments.findIndex(doc => doc.id === id);
if (index === -1) {
throw new Error('Document not found');
}
mockDocuments.splice(index, 1);
return true;
};
/**
* Gets all available tags
* @returns {Promise<Array<string>>} Array of tag strings
*/
export const getAvailableTags = async () => {
await delay(200);
return [...availableTags];
};
/**
* Gets all available categories
* @returns {Promise<Array<string>>} Array of category strings
*/
export const getAvailableCategories = async () => {
await delay(200);
return [...availableCategories];
};

View File

@@ -0,0 +1,155 @@
/**
* Mock data for PDF documents
* This file provides sample data for development and testing purposes
*/
/**
* Generates a placeholder thumbnail URL
* @param {number} index - Document index for unique colors
* @returns {string} Placeholder image URL
*/
const generateThumbnailUrl = (index) => {
const colors = ['3B82F6', '10B981', 'F59E0B', 'EF4444', '8B5CF6', 'EC4899'];
const color = colors[index % colors.length];
return `https://via.placeholder.com/300x400/${color}/FFFFFF?text=Page+1`;
};
/**
* Mock documents data
* @type {Array<Object>}
*/
export const mockDocuments = [
{
id: 'doc-001',
name: 'Contrat-2025.pdf',
originalFileType: 'DOCX',
createdAt: '2025-10-01T10:30:00Z',
fileSize: 2048576, // 2 MB
pageCount: 12,
thumbnailUrl: generateThumbnailUrl(0),
pdfUrl: '/mock/contrat-2025.pdf',
tags: ['contrat', '2025'],
categories: ['legal']
},
{
id: 'doc-002',
name: 'Facture-Janvier.pdf',
originalFileType: 'XLSX',
createdAt: '2025-09-15T14:20:00Z',
fileSize: 512000, // 512 KB
pageCount: 3,
thumbnailUrl: generateThumbnailUrl(1),
pdfUrl: '/mock/facture-janvier.pdf',
tags: ['facture', 'comptabilité'],
categories: ['finance']
},
{
id: 'doc-003',
name: 'Présentation-Projet.pdf',
originalFileType: 'PPTX',
createdAt: '2025-09-28T09:15:00Z',
fileSize: 5242880, // 5 MB
pageCount: 24,
thumbnailUrl: generateThumbnailUrl(2),
pdfUrl: '/mock/presentation-projet.pdf',
tags: ['présentation', 'projet'],
categories: ['marketing']
},
{
id: 'doc-004',
name: 'Photo-Identité.pdf',
originalFileType: 'JPG',
createdAt: '2025-10-05T16:45:00Z',
fileSize: 204800, // 200 KB
pageCount: 1,
thumbnailUrl: generateThumbnailUrl(3),
pdfUrl: '/mock/photo-identite.pdf',
tags: ['photo', 'identité'],
categories: ['personnel']
},
{
id: 'doc-005',
name: 'Manuel-Utilisateur.pdf',
originalFileType: 'PDF',
createdAt: '2025-09-20T11:00:00Z',
fileSize: 3145728, // 3 MB
pageCount: 45,
thumbnailUrl: generateThumbnailUrl(4),
pdfUrl: '/mock/manuel-utilisateur.pdf',
tags: ['manuel', 'documentation'],
categories: ['technique']
},
{
id: 'doc-006',
name: 'Rapport-Annuel.pdf',
originalFileType: 'DOCX',
createdAt: '2025-08-30T13:30:00Z',
fileSize: 4194304, // 4 MB
pageCount: 67,
thumbnailUrl: generateThumbnailUrl(5),
pdfUrl: '/mock/rapport-annuel.pdf',
tags: ['rapport', 'annuel'],
categories: ['finance', 'management']
},
{
id: 'doc-007',
name: 'CV-Candidat.pdf',
originalFileType: 'DOCX',
createdAt: '2025-10-02T08:00:00Z',
fileSize: 153600, // 150 KB
pageCount: 2,
thumbnailUrl: generateThumbnailUrl(0),
pdfUrl: '/mock/cv-candidat.pdf',
tags: ['cv', 'recrutement'],
categories: ['rh']
},
{
id: 'doc-008',
name: 'Devis-Travaux.pdf',
originalFileType: 'XLSX',
createdAt: '2025-09-25T15:20:00Z',
fileSize: 409600, // 400 KB
pageCount: 5,
thumbnailUrl: generateThumbnailUrl(1),
pdfUrl: '/mock/devis-travaux.pdf',
tags: ['devis', 'travaux'],
categories: ['finance']
}
];
/**
* Available tags for documents
* @type {Array<string>}
*/
export const availableTags = [
'contrat',
'facture',
'présentation',
'photo',
'manuel',
'rapport',
'cv',
'devis',
'comptabilité',
'projet',
'identité',
'documentation',
'annuel',
'recrutement',
'travaux',
'2025'
];
/**
* Available categories for documents
* @type {Array<string>}
*/
export const availableCategories = [
'legal',
'finance',
'marketing',
'personnel',
'technique',
'management',
'rh'
];