This commit is contained in:
Tomas Dvorak
2025-10-19 18:09:28 +02:00
parent abe127fb51
commit 9ccca365b3
40 changed files with 6885 additions and 20 deletions
@@ -0,0 +1,177 @@
.data-table-container {
width: 100%;
overflow-x: auto;
position: relative;
}
.data-table {
width: 100%;
border-collapse: collapse;
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.data-table thead {
background: #f9fafb;
border-bottom: 2px solid #e5e7eb;
}
.data-table th {
padding: 12px 16px;
text-align: left;
font-weight: 600;
font-size: 14px;
color: #374151;
white-space: nowrap;
}
.data-table-sortable {
cursor: pointer;
user-select: none;
transition: background-color 0.2s;
}
.data-table-sortable:hover {
background: #f3f4f6;
}
.data-table-header-content {
display: flex;
align-items: center;
gap: 8px;
}
.data-table-sort-icon {
color: #9ca3af;
font-size: 12px;
}
.data-table td {
padding: 12px 16px;
border-bottom: 1px solid #e5e7eb;
font-size: 14px;
color: #1f2937;
}
.data-table tbody tr:last-child td {
border-bottom: none;
}
/* Striped rows */
.data-table-striped tbody tr:nth-child(even) {
background: #f9fafb;
}
/* Hoverable rows */
.data-table-hoverable tbody tr {
transition: background-color 0.15s;
}
.data-table-hoverable tbody tr:hover {
background: #f3f4f6;
}
/* Clickable rows */
.data-table-row-clickable {
cursor: pointer;
}
/* Selected rows */
.data-table-row-selected {
background: #dbeafe !important;
}
/* Alignment */
.data-table-align-left {
text-align: left;
}
.data-table-align-center {
text-align: center;
}
.data-table-align-right {
text-align: right;
}
/* Select column */
.data-table-select-col {
width: 40px;
text-align: center;
}
.data-table-select-col input[type="checkbox"] {
cursor: pointer;
width: 16px;
height: 16px;
}
/* Actions column */
.data-table-actions-col {
width: 120px;
text-align: right;
}
/* Loading state */
.data-table-loading-overlay {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 60px 20px;
background: white;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #e5e7eb;
border-top-color: #3b82f6;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.data-table-loading-overlay p {
margin-top: 16px;
color: #6b7280;
font-size: 14px;
}
/* Empty state */
.data-table-empty {
display: flex;
align-items: center;
justify-content: center;
padding: 60px 20px;
background: white;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.data-table-empty p {
color: #6b7280;
font-size: 14px;
}
/* Responsive */
@media (max-width: 768px) {
.data-table th,
.data-table td {
padding: 8px 12px;
font-size: 13px;
}
.data-table-header-content {
gap: 4px;
}
}
@@ -0,0 +1,216 @@
import React, { useMemo } from 'react';
import './DataTable.css';
export interface Column<T> {
key: keyof T | string;
label: string;
sortable?: boolean;
render?: (item: T, index: number) => React.ReactNode;
width?: string;
align?: 'left' | 'center' | 'right';
}
export interface SortConfig {
field: string;
order: 'asc' | 'desc';
}
export interface DataTableProps<T> {
data: T[];
columns: Column<T>[];
keyField?: keyof T;
loading?: boolean;
emptyMessage?: string;
sortConfig?: SortConfig | null;
onSort?: (field: string) => void;
onRowClick?: (item: T, index: number) => void;
selectable?: boolean;
selectedIds?: Set<number | string>;
onToggleSelect?: (id: number | string) => void;
onToggleSelectAll?: () => void;
isAllSelected?: boolean;
isSomeSelected?: boolean;
actions?: (item: T, index: number) => React.ReactNode;
className?: string;
striped?: boolean;
hoverable?: boolean;
}
/**
* Enhanced data table component with sorting, selection, and custom rendering
* Works seamlessly with usePaginatedData, useQueryBuilder, and useBatchSelection hooks
*
* @example
* const { data, loading, setSort } = usePaginatedData('/articles');
* const selection = useBatchSelection(data, 'id');
*
* <DataTable
* data={data}
* columns={columns}
* loading={loading}
* onSort={setSort}
* selectable
* selectedIds={selection.selectedIds}
* onToggleSelect={selection.toggle}
* onToggleSelectAll={selection.toggleAll}
* />
*/
export function DataTable<T extends Record<string, any>>({
data,
columns,
keyField = 'id' as keyof T,
loading = false,
emptyMessage = 'No data available',
sortConfig,
onSort,
onRowClick,
selectable = false,
selectedIds,
onToggleSelect,
onToggleSelectAll,
isAllSelected = false,
isSomeSelected = false,
actions,
className = '',
striped = true,
hoverable = true,
}: DataTableProps<T>) {
const tableClasses = useMemo(() => {
const classes = ['data-table'];
if (striped) classes.push('data-table-striped');
if (hoverable) classes.push('data-table-hoverable');
if (loading) classes.push('data-table-loading');
if (className) classes.push(className);
return classes.join(' ');
}, [striped, hoverable, loading, className]);
const handleSort = (field: string, sortable?: boolean) => {
if (sortable && onSort) {
onSort(field);
}
};
const getSortIcon = (field: string) => {
if (!sortConfig || sortConfig.field !== field) {
return '⇅';
}
return sortConfig.order === 'asc' ? '↑' : '↓';
};
if (loading) {
return (
<div className="data-table-container">
<div className="data-table-loading-overlay">
<div className="spinner"></div>
<p>Loading...</p>
</div>
</div>
);
}
if (data.length === 0) {
return (
<div className="data-table-container">
<div className="data-table-empty">
<p>{emptyMessage}</p>
</div>
</div>
);
}
return (
<div className="data-table-container">
<table className={tableClasses}>
<thead>
<tr>
{selectable && (
<th className="data-table-select-col">
<input
type="checkbox"
checked={isAllSelected}
ref={(input) => {
if (input) {
input.indeterminate = isSomeSelected;
}
}}
onChange={onToggleSelectAll}
aria-label="Select all rows"
/>
</th>
)}
{columns.map((column) => (
<th
key={String(column.key)}
className={`
${column.sortable ? 'data-table-sortable' : ''}
data-table-align-${column.align || 'left'}
`}
style={{ width: column.width }}
onClick={() => handleSort(String(column.key), column.sortable)}
>
<div className="data-table-header-content">
<span>{column.label}</span>
{column.sortable && (
<span className="data-table-sort-icon">
{getSortIcon(String(column.key))}
</span>
)}
</div>
</th>
))}
{actions && <th className="data-table-actions-col">Actions</th>}
</tr>
</thead>
<tbody>
{data.map((item, index) => {
const itemId = item[keyField];
const isSelected = selectedIds?.has(itemId) || false;
return (
<tr
key={String(itemId)}
className={`
${isSelected ? 'data-table-row-selected' : ''}
${onRowClick ? 'data-table-row-clickable' : ''}
`}
onClick={() => onRowClick?.(item, index)}
>
{selectable && (
<td
className="data-table-select-col"
onClick={(e) => e.stopPropagation()}
>
<input
type="checkbox"
checked={isSelected}
onChange={() => onToggleSelect?.(itemId)}
aria-label={`Select row ${index + 1}`}
/>
</td>
)}
{columns.map((column) => (
<td
key={String(column.key)}
className={`data-table-align-${column.align || 'left'}`}
>
{column.render
? column.render(item, index)
: String(item[column.key] ?? '')}
</td>
))}
{actions && (
<td
className="data-table-actions-col"
onClick={(e) => e.stopPropagation()}
>
{actions(item, index)}
</td>
)}
</tr>
);
})}
</tbody>
</table>
</div>
);
}
@@ -0,0 +1,127 @@
.toast-container {
position: fixed;
top: 20px;
right: 20px;
z-index: 9999;
display: flex;
flex-direction: column;
gap: 12px;
max-width: 400px;
}
.toast {
display: flex;
align-items: center;
gap: 12px;
padding: 16px;
background: white;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
border-left: 4px solid;
animation: slideIn 0.3s ease-out;
min-width: 300px;
}
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
.toast-icon {
flex-shrink: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
font-weight: bold;
font-size: 16px;
}
.toast-message {
flex: 1;
font-size: 14px;
line-height: 1.5;
color: #333;
}
.toast-close {
flex-shrink: 0;
width: 24px;
height: 24px;
border: none;
background: transparent;
cursor: pointer;
font-size: 24px;
line-height: 1;
color: #666;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
transition: color 0.2s;
}
.toast-close:hover {
color: #333;
}
/* Success */
.toast-success {
border-left-color: #10b981;
}
.toast-success .toast-icon {
background: #d1fae5;
color: #10b981;
}
/* Error */
.toast-error {
border-left-color: #ef4444;
}
.toast-error .toast-icon {
background: #fee2e2;
color: #ef4444;
}
/* Warning */
.toast-warning {
border-left-color: #f59e0b;
}
.toast-warning .toast-icon {
background: #fef3c7;
color: #f59e0b;
}
/* Info */
.toast-info {
border-left-color: #3b82f6;
}
.toast-info .toast-icon {
background: #dbeafe;
color: #3b82f6;
}
/* Responsive */
@media (max-width: 640px) {
.toast-container {
left: 20px;
right: 20px;
max-width: none;
}
.toast {
min-width: auto;
}
}
@@ -0,0 +1,64 @@
import React from 'react';
import { Toast } from '../../hooks/useToast';
import './ToastContainer.css';
interface ToastContainerProps {
toasts: Toast[];
onDismiss: (id: string) => void;
}
/**
* Container component for displaying toast notifications
* Use with the useToast hook
*
* @example
* const toast = useToast();
* return <ToastContainer toasts={toast.toasts} onDismiss={toast.dismiss} />
*/
export const ToastContainer: React.FC<ToastContainerProps> = ({ toasts, onDismiss }) => {
if (toasts.length === 0) return null;
return (
<div className="toast-container">
{toasts.map((toast) => (
<ToastItem key={toast.id} toast={toast} onDismiss={onDismiss} />
))}
</div>
);
};
interface ToastItemProps {
toast: Toast;
onDismiss: (id: string) => void;
}
const ToastItem: React.FC<ToastItemProps> = ({ toast, onDismiss }) => {
const getIcon = () => {
switch (toast.type) {
case 'success':
return '✓';
case 'error':
return '✕';
case 'warning':
return '⚠';
case 'info':
return '';
default:
return '';
}
};
return (
<div className={`toast toast-${toast.type}`} role="alert">
<div className="toast-icon">{getIcon()}</div>
<div className="toast-message">{toast.message}</div>
<button
className="toast-close"
onClick={() => onDismiss(toast.id)}
aria-label="Close notification"
>
×
</button>
</div>
);
};
@@ -0,0 +1,233 @@
.article-list-example {
padding: 24px;
max-width: 1400px;
margin: 0 auto;
}
.page-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
}
.page-header h1 {
margin: 0;
font-size: 28px;
font-weight: 700;
color: #111827;
}
.filters-bar {
display: flex;
gap: 12px;
margin-bottom: 20px;
flex-wrap: wrap;
}
.search-box {
flex: 1;
min-width: 250px;
}
.search-input {
width: 100%;
padding: 10px 16px;
border: 1px solid #d1d5db;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.2s;
}
.search-input:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.filter-select {
padding: 10px 16px;
border: 1px solid #d1d5db;
border-radius: 6px;
font-size: 14px;
background: white;
cursor: pointer;
transition: border-color 0.2s;
}
.filter-select:focus {
outline: none;
border-color: #3b82f6;
}
.batch-actions {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: #eff6ff;
border: 1px solid #bfdbfe;
border-radius: 6px;
margin-bottom: 16px;
}
.selected-count {
font-size: 14px;
font-weight: 500;
color: #1e40af;
}
.error-message {
padding: 16px;
background: #fef2f2;
border: 1px solid #fecaca;
border-radius: 6px;
margin-bottom: 16px;
display: flex;
justify-content: space-between;
align-items: center;
}
.error-message p {
margin: 0;
color: #991b1b;
font-size: 14px;
}
.article-title {
display: flex;
align-items: center;
gap: 8px;
}
.badge {
display: inline-block;
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
font-weight: 500;
}
.badge-draft {
background: #fef3c7;
color: #92400e;
}
.table-actions {
display: flex;
gap: 8px;
justify-content: flex-end;
}
.btn-icon {
background: none;
border: none;
cursor: pointer;
font-size: 18px;
padding: 4px;
transition: transform 0.2s;
}
.btn-icon:hover {
transform: scale(1.2);
}
.pagination {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 20px;
padding: 16px;
background: white;
border-radius: 6px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.pagination-info {
font-size: 14px;
color: #6b7280;
}
/* Buttons */
.btn {
padding: 10px 20px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-primary {
background: #3b82f6;
color: white;
}
.btn-primary:hover:not(:disabled) {
background: #2563eb;
}
.btn-secondary {
background: #6b7280;
color: white;
}
.btn-secondary:hover:not(:disabled) {
background: #4b5563;
}
.btn-danger {
background: #ef4444;
color: white;
}
.btn-danger:hover:not(:disabled) {
background: #dc2626;
}
.btn-ghost {
background: transparent;
color: #6b7280;
border: 1px solid #d1d5db;
}
.btn-ghost:hover:not(:disabled) {
background: #f9fafb;
}
.btn-sm {
padding: 6px 12px;
font-size: 13px;
}
/* Responsive */
@media (max-width: 768px) {
.article-list-example {
padding: 16px;
}
.page-header {
flex-direction: column;
align-items: flex-start;
gap: 12px;
}
.filters-bar {
flex-direction: column;
}
.search-box {
width: 100%;
}
.pagination {
flex-direction: column;
gap: 12px;
}
}
@@ -0,0 +1,284 @@
import React, { useState, useEffect } from 'react';
import { usePaginatedData } from '../../hooks/usePaginatedData';
import { useApiDelete } from '../../hooks/useApiMutation';
import { useBatchSelection } from '../../hooks/useBatchSelection';
import { useToast } from '../../hooks/useToast';
import { DataTable, Column } from '../common/DataTable';
import { ToastContainer } from '../common/ToastContainer';
import { exportToCSV, getExportFilename } from '../../utils/export';
import './ArticleListExample.css';
interface Article {
id: number;
title: string;
published: boolean;
created_at: string;
author?: {
name: string;
};
}
/**
* Complete example showing how to use all the new utility hooks and components
* This demonstrates:
* - usePaginatedData for fetching with pagination, search, sort, filters
* - useBatchSelection for selecting multiple items
* - useApiDelete for deleting items
* - useToast for notifications
* - DataTable for displaying data
* - Export utilities
*/
export const ArticleListExample: React.FC = () => {
// Data fetching with pagination, search, sort, filters
const {
data: articles,
meta,
loading,
error,
setPage,
setSearch,
setSort,
setFilters,
refresh,
} = usePaginatedData<Article>('/articles', {
page_size: 20,
});
// Batch selection
const selection = useBatchSelection<Article>(articles, 'id');
// Update selection when articles change
useEffect(() => {
selection.setItems(articles);
}, [articles]);
// Toast notifications
const toast = useToast();
// Delete mutation
const deleteArticle = useApiDelete<void, { id: number }>((data) => `/articles/${data.id}`);
// Local state
const [searchTerm, setSearchTerm] = useState('');
const [publishedFilter, setPublishedFilter] = useState<string>('all');
// Handle search input
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setSearchTerm(value);
// Debounce search
const timeoutId = setTimeout(() => {
setSearch(value);
}, 500);
return () => clearTimeout(timeoutId);
};
// Handle filter change
const handleFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const value = e.target.value;
setPublishedFilter(value);
if (value === 'all') {
setFilters({});
} else {
setFilters({ published: value === 'published' });
}
};
// Handle sort
const handleSort = (field: string) => {
// Toggle sort order
setSort(field, 'desc'); // You'd want to track current order and toggle
};
// Handle delete
const handleDelete = async (id: number) => {
if (!window.confirm('Are you sure you want to delete this article?')) return;
const result = await deleteArticle.mutate({ id });
if (result !== null) {
toast.success('Article deleted successfully');
refresh();
} else {
toast.error(deleteArticle.error || 'Failed to delete article');
}
};
// Handle batch delete
const handleBatchDelete = async () => {
const count = selection.selectedIds.size;
if (!window.confirm(`Are you sure you want to delete ${count} articles?`)) return;
// In real implementation, you'd call a batch delete API
toast.info(`Would delete ${count} articles`);
selection.deselectAll();
};
// Handle export
const handleExport = () => {
const filename = getExportFilename('articles', 'csv');
const exportData = articles.map((article) => ({
ID: article.id,
Title: article.title,
Published: article.published ? 'Yes' : 'No',
Author: article.author?.name || 'Unknown',
'Created At': new Date(article.created_at).toLocaleString(),
}));
exportToCSV(exportData, filename);
toast.success('Articles exported successfully');
};
// Table columns configuration
const columns: Column<Article>[] = [
{
key: 'id',
label: 'ID',
sortable: true,
width: '80px',
},
{
key: 'title',
label: 'Title',
sortable: true,
render: (article) => (
<div className="article-title">
<strong>{article.title}</strong>
{!article.published && <span className="badge badge-draft">Draft</span>}
</div>
),
},
{
key: 'author',
label: 'Author',
render: (article) => article.author?.name || 'Unknown',
},
{
key: 'created_at',
label: 'Created',
sortable: true,
render: (article) => new Date(article.created_at).toLocaleDateString(),
},
];
return (
<div className="article-list-example">
<ToastContainer toasts={toast.toasts} onDismiss={toast.dismiss} />
<div className="page-header">
<h1>Articles</h1>
<button className="btn btn-primary" onClick={refresh}>
Refresh
</button>
</div>
{/* Filters and Search */}
<div className="filters-bar">
<div className="search-box">
<input
type="text"
placeholder="Search articles..."
value={searchTerm}
onChange={handleSearchChange}
className="search-input"
/>
</div>
<select
value={publishedFilter}
onChange={handleFilterChange}
className="filter-select"
>
<option value="all">All Articles</option>
<option value="published">Published</option>
<option value="draft">Drafts</option>
</select>
<button
className="btn btn-secondary"
onClick={handleExport}
disabled={articles.length === 0}
>
Export CSV
</button>
</div>
{/* Batch Actions */}
{selection.selectedIds.size > 0 && (
<div className="batch-actions">
<span className="selected-count">
{selection.selectedIds.size} article(s) selected
</span>
<button className="btn btn-danger" onClick={handleBatchDelete}>
Delete Selected
</button>
<button className="btn btn-ghost" onClick={selection.deselectAll}>
Clear Selection
</button>
</div>
)}
{/* Error Message */}
{error && (
<div className="error-message">
<p>Error: {error}</p>
<button onClick={refresh}>Retry</button>
</div>
)}
{/* Data Table */}
<DataTable
data={articles}
columns={columns}
loading={loading}
emptyMessage="No articles found"
selectable
selectedIds={selection.selectedIds}
onToggleSelect={selection.toggle}
onToggleSelectAll={selection.toggleAll}
isAllSelected={selection.isAllSelected}
isSomeSelected={selection.isSomeSelected}
onSort={handleSort}
actions={(article) => (
<div className="table-actions">
<button
className="btn-icon"
onClick={() => console.log('Edit', article.id)}
title="Edit"
>
</button>
<button
className="btn-icon"
onClick={() => handleDelete(article.id)}
title="Delete"
>
🗑
</button>
</div>
)}
/>
{/* Pagination */}
{meta && meta.total_pages > 1 && (
<div className="pagination">
<button
className="btn btn-sm"
onClick={() => setPage(meta.page - 1)}
disabled={!meta.has_prev}
>
Previous
</button>
<span className="pagination-info">
Page {meta.page} of {meta.total_pages} ({meta.total} total)
</span>
<button
className="btn btn-sm"
onClick={() => setPage(meta.page + 1)}
disabled={!meta.has_next}
>
Next
</button>
</div>
)}
</div>
);
};
+96
View File
@@ -0,0 +1,96 @@
import { useState, useCallback } from 'react';
import { api } from '../services/api';
import { AxiosError } from 'axios';
export interface ApiResponse<T = any> {
success: boolean;
message?: string;
data?: T;
error?: string;
}
export interface UseApiMutationResult<T, P = any> {
mutate: (data: P) => Promise<T | null>;
loading: boolean;
error: string | null;
success: boolean;
reset: () => void;
}
/**
* Hook for API mutations (POST, PUT, PATCH, DELETE)
* Handles loading states, errors, and success messages
*
* @example
* const { mutate, loading, error } = useApiMutation<Article>('post', '/articles');
* await mutate({ title: 'New Article' });
*/
export function useApiMutation<T = any, P = any>(
method: 'post' | 'put' | 'patch' | 'delete',
endpoint: string | ((data: P) => string)
): UseApiMutationResult<T, P> {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const mutate = useCallback(
async (data: P): Promise<T | null> => {
try {
setLoading(true);
setError(null);
setSuccess(false);
const url = typeof endpoint === 'function' ? endpoint(data) : endpoint;
const response = await api[method]<ApiResponse<T>>(url, data);
if (response.data.success !== false) {
setSuccess(true);
return response.data.data || (response.data as any);
} else {
setError(response.data.error || response.data.message || 'Operation failed');
return null;
}
} catch (err) {
const axiosError = err as AxiosError<ApiResponse>;
const errorMsg =
axiosError.response?.data?.error ||
axiosError.response?.data?.message ||
axiosError.message ||
'An error occurred';
setError(errorMsg);
return null;
} finally {
setLoading(false);
}
},
[method, endpoint]
);
const reset = useCallback(() => {
setError(null);
setSuccess(false);
}, []);
return {
mutate,
loading,
error,
success,
reset,
};
}
/**
* Convenience hooks for specific HTTP methods
*/
export const useApiPost = <T = any, P = any>(endpoint: string | ((data: P) => string)) =>
useApiMutation<T, P>('post', endpoint);
export const useApiPut = <T = any, P = any>(endpoint: string | ((data: P) => string)) =>
useApiMutation<T, P>('put', endpoint);
export const useApiPatch = <T = any, P = any>(endpoint: string | ((data: P) => string)) =>
useApiMutation<T, P>('patch', endpoint);
export const useApiDelete = <T = any, P = any>(endpoint: string | ((data: P) => string)) =>
useApiMutation<T, P>('delete', endpoint);
+126
View File
@@ -0,0 +1,126 @@
import { useState, useCallback, useMemo } from 'react';
export interface UseBatchSelectionResult<T = any> {
selectedIds: Set<number | string>;
selectedItems: T[];
isSelected: (id: number | string) => boolean;
isAllSelected: boolean;
isSomeSelected: boolean;
toggle: (id: number | string) => void;
select: (id: number | string) => void;
deselect: (id: number | string) => void;
selectAll: () => void;
deselectAll: () => void;
toggleAll: () => void;
setItems: (items: T[]) => void;
getSelectedIds: () => (number | string)[];
getSelectedItems: () => T[];
}
/**
* Hook for managing batch selection in tables/lists
* Handles select all, toggle, and individual selections
*
* @example
* const selection = useBatchSelection(articles, 'id');
* <Checkbox checked={selection.isSelected(article.id)} onChange={() => selection.toggle(article.id)} />
* <button disabled={selection.selectedIds.size === 0} onClick={handleBatchDelete}>
* Delete Selected ({selection.selectedIds.size})
* </button>
*/
export function useBatchSelection<T = any>(
items: T[] = [],
idField: keyof T = 'id' as keyof T
): UseBatchSelectionResult<T> {
const [selectedIds, setSelectedIds] = useState<Set<number | string>>(new Set());
const [currentItems, setCurrentItems] = useState<T[]>(items);
const setItems = useCallback((newItems: T[]) => {
setCurrentItems(newItems);
// Clear selection when items change
setSelectedIds(new Set());
}, []);
const isSelected = useCallback(
(id: number | string) => selectedIds.has(id),
[selectedIds]
);
const toggle = useCallback((id: number | string) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) {
next.delete(id);
} else {
next.add(id);
}
return next;
});
}, []);
const select = useCallback((id: number | string) => {
setSelectedIds((prev) => new Set(prev).add(id));
}, []);
const deselect = useCallback((id: number | string) => {
setSelectedIds((prev) => {
const next = new Set(prev);
next.delete(id);
return next;
});
}, []);
const selectAll = useCallback(() => {
const allIds = currentItems.map((item) => item[idField] as number | string);
setSelectedIds(new Set(allIds));
}, [currentItems, idField]);
const deselectAll = useCallback(() => {
setSelectedIds(new Set());
}, []);
const toggleAll = useCallback(() => {
if (selectedIds.size === currentItems.length && currentItems.length > 0) {
deselectAll();
} else {
selectAll();
}
}, [selectedIds.size, currentItems.length, selectAll, deselectAll]);
const selectedItems = useMemo(() => {
return currentItems.filter((item) => selectedIds.has(item[idField] as number | string));
}, [currentItems, selectedIds, idField]);
const isAllSelected = useMemo(() => {
return currentItems.length > 0 && selectedIds.size === currentItems.length;
}, [currentItems.length, selectedIds.size]);
const isSomeSelected = useMemo(() => {
return selectedIds.size > 0 && selectedIds.size < currentItems.length;
}, [selectedIds.size, currentItems.length]);
const getSelectedIds = useCallback(() => {
return Array.from(selectedIds);
}, [selectedIds]);
const getSelectedItems = useCallback(() => {
return selectedItems;
}, [selectedItems]);
return {
selectedIds,
selectedItems,
isSelected,
isAllSelected,
isSomeSelected,
toggle,
select,
deselect,
selectAll,
deselectAll,
toggleAll,
setItems,
getSelectedIds,
getSelectedItems,
};
}
+272
View File
@@ -0,0 +1,272 @@
import { useState, useCallback } from 'react';
export interface ValidationRule {
required?: boolean;
min?: number;
max?: number;
pattern?: RegExp;
email?: boolean;
url?: boolean;
custom?: (value: any) => string | null;
message?: string;
}
export interface ValidationRules {
[field: string]: ValidationRule | ValidationRule[];
}
export interface ValidationErrors {
[field: string]: string;
}
export interface UseFormValidationResult<T> {
values: T;
errors: ValidationErrors;
touched: { [K in keyof T]?: boolean };
isValid: boolean;
isSubmitting: boolean;
setValue: (field: keyof T, value: any) => void;
setValues: (values: Partial<T>) => void;
setError: (field: keyof T, error: string) => void;
setErrors: (errors: ValidationErrors) => void;
clearError: (field: keyof T) => void;
clearErrors: () => void;
touch: (field: keyof T) => void;
validate: () => boolean;
validateField: (field: keyof T) => boolean;
handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
handleBlur: (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
handleSubmit: (onSubmit: (values: T) => void | Promise<void>) => (e: React.FormEvent) => Promise<void>;
reset: () => void;
}
/**
* Hook for form validation with built-in rules
* Supports required, min/max length, patterns, email, URL, and custom validators
*
* @example
* const { values, errors, handleChange, handleSubmit } = useFormValidation({
* title: '',
* email: ''
* }, {
* title: { required: true, min: 3, max: 100 },
* email: { required: true, email: true }
* });
*/
export function useFormValidation<T extends Record<string, any>>(
initialValues: T,
rules: ValidationRules = {}
): UseFormValidationResult<T> {
const [values, setValuesState] = useState<T>(initialValues);
const [errors, setErrorsState] = useState<ValidationErrors>({});
const [touched, setTouched] = useState<{ [K in keyof T]?: boolean }>({});
const [isSubmitting, setIsSubmitting] = useState(false);
const validateValue = useCallback(
(field: keyof T, value: any): string | null => {
const fieldRules = rules[field as string];
if (!fieldRules) return null;
const rulesArray = Array.isArray(fieldRules) ? fieldRules : [fieldRules];
for (const rule of rulesArray) {
// Required
if (rule.required && (!value || (typeof value === 'string' && !value.trim()))) {
return rule.message || `${String(field)} is required`;
}
// Skip other validations if empty and not required
if (!value || (typeof value === 'string' && !value.trim())) {
continue;
}
// Min length
if (rule.min !== undefined && typeof value === 'string' && value.length < rule.min) {
return rule.message || `${String(field)} must be at least ${rule.min} characters`;
}
// Max length
if (rule.max !== undefined && typeof value === 'string' && value.length > rule.max) {
return rule.message || `${String(field)} must be at most ${rule.max} characters`;
}
// Pattern
if (rule.pattern && typeof value === 'string' && !rule.pattern.test(value)) {
return rule.message || `${String(field)} format is invalid`;
}
// Email
if (rule.email && typeof value === 'string') {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(value)) {
return rule.message || `${String(field)} must be a valid email`;
}
}
// URL
if (rule.url && typeof value === 'string') {
try {
new URL(value);
} catch {
return rule.message || `${String(field)} must be a valid URL`;
}
}
// Custom validator
if (rule.custom) {
const customError = rule.custom(value);
if (customError) return customError;
}
}
return null;
},
[rules]
);
const validateField = useCallback(
(field: keyof T): boolean => {
const error = validateValue(field, values[field]);
if (error) {
setErrorsState((prev) => ({ ...prev, [field]: error }));
return false;
} else {
setErrorsState((prev) => {
const newErrors = { ...prev };
delete newErrors[field as string];
return newErrors;
});
return true;
}
},
[values, validateValue]
);
const validate = useCallback((): boolean => {
const newErrors: ValidationErrors = {};
let isValid = true;
Object.keys(rules).forEach((field) => {
const error = validateValue(field as keyof T, values[field as keyof T]);
if (error) {
newErrors[field] = error;
isValid = false;
}
});
setErrorsState(newErrors);
return isValid;
}, [rules, values, validateValue]);
const setValue = useCallback((field: keyof T, value: any) => {
setValuesState((prev) => ({ ...prev, [field]: value }));
}, []);
const setValues = useCallback((newValues: Partial<T>) => {
setValuesState((prev) => ({ ...prev, ...newValues }));
}, []);
const setError = useCallback((field: keyof T, error: string) => {
setErrorsState((prev) => ({ ...prev, [field]: error }));
}, []);
const setErrors = useCallback((newErrors: ValidationErrors) => {
setErrorsState(newErrors);
}, []);
const clearError = useCallback((field: keyof T) => {
setErrorsState((prev) => {
const newErrors = { ...prev };
delete newErrors[field as string];
return newErrors;
});
}, []);
const clearErrors = useCallback(() => {
setErrorsState({});
}, []);
const touch = useCallback((field: keyof T) => {
setTouched((prev) => ({ ...prev, [field]: true }));
}, []);
const handleChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
const { name, value, type } = e.target;
const fieldValue = type === 'checkbox' ? (e.target as HTMLInputElement).checked : value;
setValue(name as keyof T, fieldValue);
// Clear error on change if field was touched
if (touched[name as keyof T]) {
clearError(name as keyof T);
}
},
[setValue, clearError, touched]
);
const handleBlur = useCallback(
(e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
const { name } = e.target;
touch(name as keyof T);
validateField(name as keyof T);
},
[touch, validateField]
);
const handleSubmit = useCallback(
(onSubmit: (values: T) => void | Promise<void>) => {
return async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
// Mark all fields as touched
const allTouched = Object.keys(rules).reduce(
(acc, key) => ({ ...acc, [key]: true }),
{}
);
setTouched(allTouched);
if (validate()) {
try {
await onSubmit(values);
} finally {
setIsSubmitting(false);
}
} else {
setIsSubmitting(false);
}
};
},
[validate, values, rules]
);
const reset = useCallback(() => {
setValuesState(initialValues);
setErrorsState({});
setTouched({});
setIsSubmitting(false);
}, [initialValues]);
const isValid = Object.keys(errors).length === 0;
return {
values,
errors,
touched,
isValid,
isSubmitting,
setValue,
setValues,
setError,
setErrors,
clearError,
clearErrors,
touch,
validate,
validateField,
handleChange,
handleBlur,
handleSubmit,
reset,
};
}
+146
View File
@@ -0,0 +1,146 @@
import { useState, useEffect, useCallback } from 'react';
import { api } from '../services/api';
import { AxiosError } from 'axios';
export interface PaginationMeta {
page: number;
page_size: number;
total: number;
total_pages: number;
has_next: boolean;
has_prev: boolean;
}
export interface PaginatedResponse<T> {
success: boolean;
message?: string;
data: T[];
meta: PaginationMeta;
}
export interface QueryParams {
page?: number;
page_size?: number;
search?: string;
sort?: string;
[key: string]: any;
}
export interface UsePaginatedDataResult<T> {
data: T[];
meta: PaginationMeta | null;
loading: boolean;
error: string | null;
refresh: () => void;
setPage: (page: number) => void;
setPageSize: (size: number) => void;
setSearch: (search: string) => void;
setSort: (field: string, order: 'asc' | 'desc') => void;
setFilters: (filters: Record<string, any>) => void;
updateQueryParams: (params: Partial<QueryParams>) => void;
}
/**
* Hook for fetching paginated data with search, sort, and filters
* Automatically handles pagination, loading states, and errors
*
* @example
* const { data, meta, loading, setSearch, setPage } = usePaginatedData<Article>('/articles');
*/
export function usePaginatedData<T = any>(
endpoint: string,
initialParams: QueryParams = {}
): UsePaginatedDataResult<T> {
const [data, setData] = useState<T[]>([]);
const [meta, setMeta] = useState<PaginationMeta | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [queryParams, setQueryParams] = useState<QueryParams>({
page: 1,
page_size: 20,
...initialParams,
});
const fetchData = useCallback(async () => {
try {
setLoading(true);
setError(null);
// Build query string
const params = new URLSearchParams();
Object.entries(queryParams).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
params.append(key, String(value));
}
});
const response = await api.get<PaginatedResponse<T>>(
`${endpoint}?${params.toString()}`
);
if (response.data.success) {
setData(response.data.data || []);
setMeta(response.data.meta || null);
} else {
setError(response.data.message || 'Failed to fetch data');
}
} catch (err) {
const axiosError = err as AxiosError<{ error: string }>;
setError(
axiosError.response?.data?.error ||
axiosError.message ||
'An error occurred'
);
setData([]);
setMeta(null);
} finally {
setLoading(false);
}
}, [endpoint, queryParams]);
useEffect(() => {
fetchData();
}, [fetchData]);
const updateQueryParams = useCallback((params: Partial<QueryParams>) => {
setQueryParams((prev) => ({ ...prev, ...params }));
}, []);
const setPage = useCallback((page: number) => {
updateQueryParams({ page });
}, [updateQueryParams]);
const setPageSize = useCallback((page_size: number) => {
updateQueryParams({ page_size, page: 1 }); // Reset to first page
}, [updateQueryParams]);
const setSearch = useCallback((search: string) => {
updateQueryParams({ search, page: 1 }); // Reset to first page
}, [updateQueryParams]);
const setSort = useCallback((field: string, order: 'asc' | 'desc') => {
updateQueryParams({ sort: `${field}:${order}` });
}, [updateQueryParams]);
const setFilters = useCallback((filters: Record<string, any>) => {
updateQueryParams({ ...filters, page: 1 }); // Reset to first page
}, [updateQueryParams]);
const refresh = useCallback(() => {
fetchData();
}, [fetchData]);
return {
data,
meta,
loading,
error,
refresh,
setPage,
setPageSize,
setSearch,
setSort,
setFilters,
updateQueryParams,
};
}
+161
View File
@@ -0,0 +1,161 @@
import { useState, useCallback, useMemo } from 'react';
export interface QueryFilters {
[key: string]: any;
}
export interface SortConfig {
field: string;
order: 'asc' | 'desc';
}
export interface UseQueryBuilderResult {
filters: QueryFilters;
search: string;
sort: SortConfig | null;
page: number;
pageSize: number;
queryString: string;
queryParams: URLSearchParams;
setFilter: (key: string, value: any) => void;
removeFilter: (key: string) => void;
clearFilters: () => void;
setSearch: (search: string) => void;
setSort: (field: string, order: 'asc' | 'desc') => void;
toggleSort: (field: string) => void;
clearSort: () => void;
setPage: (page: number) => void;
setPageSize: (size: number) => void;
reset: () => void;
}
/**
* Hook for building query strings with filters, search, sort, and pagination
* Works seamlessly with the backend QueryParser
*
* @example
* const { queryString, setFilter, setSearch, setSort } = useQueryBuilder();
* setFilter('published', true);
* setSearch('football');
* setSort('created_at', 'desc');
* // queryString: "published=true&search=football&sort=created_at:desc&page=1&page_size=20"
*/
export function useQueryBuilder(initialPageSize: number = 20): UseQueryBuilderResult {
const [filters, setFilters] = useState<QueryFilters>({});
const [search, setSearchState] = useState('');
const [sort, setSortState] = useState<SortConfig | null>(null);
const [page, setPageState] = useState(1);
const [pageSize, setPageSizeState] = useState(initialPageSize);
const setFilter = useCallback((key: string, value: any) => {
setFilters((prev) => ({ ...prev, [key]: value }));
setPageState(1); // Reset to first page when filter changes
}, []);
const removeFilter = useCallback((key: string) => {
setFilters((prev) => {
const newFilters = { ...prev };
delete newFilters[key];
return newFilters;
});
setPageState(1);
}, []);
const clearFilters = useCallback(() => {
setFilters({});
setPageState(1);
}, []);
const setSearch = useCallback((searchTerm: string) => {
setSearchState(searchTerm);
setPageState(1); // Reset to first page when search changes
}, []);
const setSort = useCallback((field: string, order: 'asc' | 'desc') => {
setSortState({ field, order });
}, []);
const toggleSort = useCallback((field: string) => {
setSortState((prev) => {
if (!prev || prev.field !== field) {
return { field, order: 'asc' };
}
if (prev.order === 'asc') {
return { field, order: 'desc' };
}
return null; // Clear sort
});
}, []);
const clearSort = useCallback(() => {
setSortState(null);
}, []);
const setPage = useCallback((newPage: number) => {
setPageState(newPage);
}, []);
const setPageSize = useCallback((size: number) => {
setPageSizeState(size);
setPageState(1); // Reset to first page
}, []);
const reset = useCallback(() => {
setFilters({});
setSearchState('');
setSortState(null);
setPageState(1);
setPageSizeState(initialPageSize);
}, [initialPageSize]);
const queryParams = useMemo(() => {
const params = new URLSearchParams();
// Add filters
Object.entries(filters).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
params.append(key, String(value));
}
});
// Add search
if (search) {
params.append('search', search);
}
// Add sort
if (sort) {
params.append('sort', `${sort.field}:${sort.order}`);
}
// Add pagination
params.append('page', String(page));
params.append('page_size', String(pageSize));
return params;
}, [filters, search, sort, page, pageSize]);
const queryString = useMemo(() => {
return queryParams.toString();
}, [queryParams]);
return {
filters,
search,
sort,
page,
pageSize,
queryString,
queryParams,
setFilter,
removeFilter,
clearFilters,
setSearch,
setSort,
toggleSort,
clearSort,
setPage,
setPageSize,
reset,
};
}
+95
View File
@@ -0,0 +1,95 @@
import { useState, useCallback, useRef } from 'react';
export type ToastType = 'success' | 'error' | 'warning' | 'info';
export interface Toast {
id: string;
type: ToastType;
message: string;
duration?: number;
}
export interface UseToastResult {
toasts: Toast[];
success: (message: string, duration?: number) => void;
error: (message: string, duration?: number) => void;
warning: (message: string, duration?: number) => void;
info: (message: string, duration?: number) => void;
dismiss: (id: string) => void;
dismissAll: () => void;
}
/**
* Hook for displaying toast notifications
* Automatically dismisses toasts after specified duration
*
* @example
* const toast = useToast();
* toast.success('Article created successfully');
* toast.error('Failed to save changes');
*/
export function useToast(): UseToastResult {
const [toasts, setToasts] = useState<Toast[]>([]);
const timeoutsRef = useRef<Map<string, NodeJS.Timeout>>(new Map());
const addToast = useCallback((type: ToastType, message: string, duration: number = 5000) => {
const id = `toast-${Date.now()}-${Math.random()}`;
const toast: Toast = { id, type, message, duration };
setToasts((prev) => [...prev, toast]);
// Auto-dismiss after duration
if (duration > 0) {
const timeout = setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== id));
timeoutsRef.current.delete(id);
}, duration);
timeoutsRef.current.set(id, timeout);
}
}, []);
const dismiss = useCallback((id: string) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
const timeout = timeoutsRef.current.get(id);
if (timeout) {
clearTimeout(timeout);
timeoutsRef.current.delete(id);
}
}, []);
const dismissAll = useCallback(() => {
setToasts([]);
timeoutsRef.current.forEach((timeout) => clearTimeout(timeout));
timeoutsRef.current.clear();
}, []);
const success = useCallback(
(message: string, duration?: number) => addToast('success', message, duration),
[addToast]
);
const error = useCallback(
(message: string, duration?: number) => addToast('error', message, duration),
[addToast]
);
const warning = useCallback(
(message: string, duration?: number) => addToast('warning', message, duration),
[addToast]
);
const info = useCallback(
(message: string, duration?: number) => addToast('info', message, duration),
[addToast]
);
return {
toasts,
success,
error,
warning,
info,
dismiss,
dismissAll,
};
}
+116
View File
@@ -0,0 +1,116 @@
import { api } from '../services/api';
/**
* Utility functions for exporting data
*/
/**
* Converts array of objects to CSV string
*/
export function arrayToCSV<T extends Record<string, any>>(
data: T[],
columns?: string[]
): string {
if (data.length === 0) return '';
const headers = columns || Object.keys(data[0]);
const rows = data.map((item) =>
headers.map((header) => {
const value = item[header];
// Escape CSV special characters
if (value === null || value === undefined) return '';
const stringValue = String(value);
if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
return `"${stringValue.replace(/"/g, '""')}"`;
}
return stringValue;
})
);
return [headers.join(','), ...rows.map((row) => row.join(','))].join('\n');
}
/**
* Triggers a file download in the browser
*/
export function downloadFile(content: string, filename: string, mimeType: string = 'text/plain') {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
/**
* Exports data to CSV file
*/
export function exportToCSV<T extends Record<string, any>>(
data: T[],
filename: string = 'export.csv',
columns?: string[]
) {
const csv = arrayToCSV(data, columns);
downloadFile(csv, filename, 'text/csv');
}
/**
* Exports data to JSON file
*/
export function exportToJSON<T>(data: T, filename: string = 'export.json') {
const json = JSON.stringify(data, null, 2);
downloadFile(json, filename, 'application/json');
}
/**
* Fetches and downloads export from API endpoint
*/
export async function exportFromAPI(
endpoint: string,
filename: string,
format: 'csv' | 'json' = 'csv'
): Promise<void> {
try {
const response = await api.get(endpoint, {
responseType: 'blob',
});
const url = URL.createObjectURL(response.data);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} catch (error) {
console.error('Export failed:', error);
throw error;
}
}
/**
* Copies data to clipboard
*/
export async function copyToClipboard(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (error) {
console.error('Failed to copy to clipboard:', error);
return false;
}
}
/**
* Formats date for export filenames
*/
export function getExportFilename(prefix: string, extension: string): string {
const date = new Date();
const dateStr = date.toISOString().split('T')[0];
const timeStr = date.toTimeString().split(' ')[0].replace(/:/g, '-');
return `${prefix}_${dateStr}_${timeStr}.${extension}`;
}