import React, { useState, useEffect, useCallback, useMemo, useRef, useContext, useReducer } from 'react'; import PropTypes from 'prop-types'; const ThemeContext = React.createContext({ theme: 'light', toggleTheme: () => { }, colors: { primary: '#007bff', secondary: '#6c757d', success: '#28a745', danger: '#dc3545', warning: '#ffc107', info: '#17a2b8' } }); const NotificationContext = React.createContext({ notifications: [], addNotification: () => { }, removeNotification: () => { }, clearNotifications: () => { } }); function notificationReducer(state, action) { switch (action.type) { case 'ADD_NOTIFICATION': return { ...state, notifications: [...state.notifications, { id: Date.now() + Math.random(), ...action.payload, timestamp: new Date() }] }; case 'REMOVE_NOTIFICATION': return { ...state, notifications: state.notifications.filter(n => n.id !== action.payload.id) }; case 'CLEAR_NOTIFICATIONS': return { ...state, notifications: [] }; case 'UPDATE_NOTIFICATION': return { ...state, notifications: state.notifications.map(n => n.id === action.payload.id ? { ...n, ...action.payload.updates } : n ) }; default: return state; } } function useNotifications() { const [state, dispatch] = useReducer(notificationReducer, { notifications: [] }); const addNotification = useCallback((notification) => { dispatch({ type: 'ADD_NOTIFICATION', payload: { type: 'info', duration: 5000, ...notification } }); }, []); const removeNotification = useCallback((id) => { dispatch({ type: 'REMOVE_NOTIFICATION', payload: { id } }); }, []); const clearNotifications = useCallback(() => { dispatch({ type: 'CLEAR_NOTIFICATIONS' }); }, []); const updateNotification = useCallback((id, updates) => { dispatch({ type: 'UPDATE_NOTIFICATION', payload: { id, updates } }); }, []); return { notifications: state.notifications, addNotification, removeNotification, clearNotifications, updateNotification }; } function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error(`Error reading localStorage key "${key}":`, error); return initialValue; } }); const setValue = useCallback((value) => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.error(`Error setting localStorage key "${key}":`, error); } }, [key, storedValue]); const removeValue = useCallback(() => { try { window.localStorage.removeItem(key); setStoredValue(initialValue); } catch (error) { console.error(`Error removing localStorage key "${key}":`, error); } }, [key, initialValue]); return [storedValue, setValue, removeValue]; } function useDebounce(value, delay) { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value); }, delay); return () => { clearTimeout(handler); }; }, [value, delay]); return debouncedValue; } function useApi(url, options = {}) { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const abortControllerRef = useRef(); const fetchData = useCallback(async (customUrl = url, customOptions = {}) => { try { setLoading(true); setError(null); if (abortControllerRef.current) { abortControllerRef.current.abort(); } abortControllerRef.current = new AbortController(); const response = await fetch(customUrl, { signal: abortControllerRef.current.signal, headers: { 'Content-Type': 'application/json', ...options.headers, ...customOptions.headers }, ...options, ...customOptions }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const result = await response.json(); setData(result); return result; } catch (err) { if (err.name !== 'AbortError') { setError(err.message); throw err; } } finally { setLoading(false); } }, [url, options]); useEffect(() => { if (url && options.immediate !== false) { fetchData(); } return () => { if (abortControllerRef.current) { abortControllerRef.current.abort(); } }; }, [fetchData, url]); const refetch = useCallback(() => fetchData(), [fetchData]); return { data, loading, error, refetch, fetchData }; } function Modal({ isOpen, onClose, title, children, size = 'medium', backdrop = true, keyboard = true }) { const modalRef = useRef(); useEffect(() => { const handleEscape = (event) => { if (keyboard && event.key === 'Escape' && isOpen) { onClose(); } }; const handleClickOutside = (event) => { if (backdrop && modalRef.current && !modalRef.current.contains(event.target) && isOpen) { onClose(); } }; if (isOpen) { document.addEventListener('keydown', handleEscape); document.addEventListener('mousedown', handleClickOutside); document.body.style.overflow = 'hidden'; } return () => { document.removeEventListener('keydown', handleEscape); document.removeEventListener('mousedown', handleClickOutside); document.body.style.overflow = 'unset'; }; }, [isOpen, onClose, backdrop, keyboard]); if (!isOpen) return null; const sizeClasses = { small: 'max-w-md', medium: 'max-w-2xl', large: 'max-w-4xl', fullscreen: 'max-w-full h-full' }; return (

{title}

{children}
); } Modal.propTypes = { isOpen: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, title: PropTypes.string.isRequired, children: PropTypes.node.isRequired, size: PropTypes.oneOf(['small', 'medium', 'large', 'fullscreen']), backdrop: PropTypes.bool, keyboard: PropTypes.bool }; function DataTable({ data = [], columns = [], sortable = true, filterable = true, paginated = true, pageSize = 10, onRowClick, onSelectionChange, selectable = false, loading = false, emptyMessage = "No data available" }) { const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' }); const [filterText, setFilterText] = useState(''); const [currentPage, setCurrentPage] = useState(1); const [selectedRows, setSelectedRows] = useState(new Set()); const debouncedFilterText = useDebounce(filterText, 300); const filteredData = useMemo(() => { if (!debouncedFilterText) return data; return data.filter(row => columns.some(column => { const value = row[column.key]; return value && value.toString().toLowerCase().includes(debouncedFilterText.toLowerCase()); }) ); }, [data, columns, debouncedFilterText]); const sortedData = useMemo(() => { if (!sortConfig.key) return filteredData; return [...filteredData].sort((a, b) => { const aValue = a[sortConfig.key]; const bValue = b[sortConfig.key]; if (aValue < bValue) { return sortConfig.direction === 'asc' ? -1 : 1; } if (aValue > bValue) { return sortConfig.direction === 'asc' ? 1 : -1; } return 0; }); }, [filteredData, sortConfig]); const paginatedData = useMemo(() => { if (!paginated) return sortedData; const startIndex = (currentPage - 1) * pageSize; return sortedData.slice(startIndex, startIndex + pageSize); }, [sortedData, currentPage, pageSize, paginated]); const totalPages = Math.ceil(sortedData.length / pageSize); const handleSort = (key) => { if (!sortable) return; setSortConfig(prevConfig => ({ key, direction: prevConfig.key === key && prevConfig.direction === 'asc' ? 'desc' : 'asc' })); }; const handleRowSelection = (rowId, isSelected) => { const newSelectedRows = new Set(selectedRows); if (isSelected) { newSelectedRows.add(rowId); } else { newSelectedRows.delete(rowId); } setSelectedRows(newSelectedRows); onSelectionChange && onSelectionChange(Array.from(newSelectedRows)); }; const handleSelectAll = (isSelected) => { if (isSelected) { const allRowIds = new Set(paginatedData.map(row => row.id)); setSelectedRows(allRowIds); onSelectionChange && onSelectionChange(Array.from(allRowIds)); } else { setSelectedRows(new Set()); onSelectionChange && onSelectionChange([]); } }; const isAllSelected = paginatedData.length > 0 && paginatedData.every(row => selectedRows.has(row.id)); const isIndeterminate = paginatedData.some(row => selectedRows.has(row.id)) && !isAllSelected; return (
{filterable && (
setFilterText(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" />
)}
{selectable && ( )} {columns.map((column) => ( ))} {loading ? ( ) : paginatedData.length === 0 ? ( ) : ( paginatedData.map((row, index) => ( onRowClick && onRowClick(row)} > {selectable && ( )} {columns.map((column) => ( ))} )) )}
{ if (input) input.indeterminate = isIndeterminate; }} onChange={(e) => handleSelectAll(e.target.checked)} className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded" /> handleSort(column.key)} >
{column.title} {sortable && sortConfig.key === column.key && ( {sortConfig.direction === 'asc' ? '' : ''} )}
Loading...
{emptyMessage}
{ e.stopPropagation(); handleRowSelection(row.id, e.target.checked); }} className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded" /> {column.render ? column.render(row[column.key], row) : row[column.key] }
{paginated && totalPages > 1 && (
Showing {((currentPage - 1) * pageSize) + 1} to {Math.min(currentPage * pageSize, sortedData.length)} of {sortedData.length} results
{Array.from({ length: Math.min(5, totalPages) }, (_, i) => { const pageNumber = i + 1; return ( ); })}
)}
); } DataTable.propTypes = { data: PropTypes.array, columns: PropTypes.arrayOf(PropTypes.shape({ key: PropTypes.string.isRequired, title: PropTypes.string.isRequired, render: PropTypes.func })), sortable: PropTypes.bool, filterable: PropTypes.bool, paginated: PropTypes.bool, pageSize: PropTypes.number, onRowClick: PropTypes.func, onSelectionChange: PropTypes.func, selectable: PropTypes.bool, loading: PropTypes.bool, emptyMessage: PropTypes.string }; function FormBuilder({ schema, onSubmit, initialValues = {}, validation = {} }) { const [formData, setFormData] = useState(initialValues); const [errors, setErrors] = useState({}); const [touched, setTouched] = useState({}); const [isSubmitting, setIsSubmitting] = useState(false); const validateField = useCallback((name, value) => { const fieldValidation = validation[name]; if (!fieldValidation) return ''; for (const rule of fieldValidation) { if (rule.required && (!value || value.toString().trim() === '')) { return rule.message || `${name} is required`; } if (rule.minLength && value && value.toString().length < rule.minLength) { return rule.message || `${name} must be at least ${rule.minLength} characters`; } if (rule.maxLength && value && value.toString().length > rule.maxLength) { return rule.message || `${name} must be no more than ${rule.maxLength} characters`; } if (rule.pattern && value && !rule.pattern.test(value.toString())) { return rule.message || `${name} format is invalid`; } if (rule.custom && value) { const customResult = rule.custom(value, formData); if (typeof customResult === 'string') { return customResult; } if (!customResult) { return rule.message || `${name} is invalid`; } } } return ''; }, [validation, formData]); const handleChange = useCallback((name, value) => { setFormData(prev => ({ ...prev, [name]: value })); if (touched[name]) { const error = validateField(name, value); setErrors(prev => ({ ...prev, [name]: error })); } }, [touched, validateField]); const handleBlur = useCallback((name) => { setTouched(prev => ({ ...prev, [name]: true })); const value = formData[name]; const error = validateField(name, value); setErrors(prev => ({ ...prev, [name]: error })); }, [formData, validateField]); const handleSubmit = useCallback(async (e) => { e.preventDefault(); setIsSubmitting(true); const newErrors = {}; const allFields = Object.keys(schema); for (const fieldName of allFields) { const error = validateField(fieldName, formData[fieldName]); if (error) { newErrors[fieldName] = error; } } setErrors(newErrors); setTouched(Object.fromEntries(allFields.map(field => [field, true]))); if (Object.keys(newErrors).length === 0) { try { await onSubmit(formData); } catch (error) { console.error('Form submission error:', error); } } setIsSubmitting(false); }, [schema, formData, validateField, onSubmit]); const renderField = (field) => { const { name, type, label, placeholder, options, ...fieldProps } = field; const value = formData[name] || ''; const error = errors[name]; const hasError = touched[name] && error; const baseClassName = `w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 ${hasError ? 'border-red-500 focus:ring-red-500' : 'border-gray-300 focus:ring-blue-500' }`; switch (type) { case 'text': case 'email': case 'password': case 'number': return ( handleChange(name, e.target.value)} onBlur={() => handleBlur(name)} className={baseClassName} {...fieldProps} /> ); case 'textarea': return (