All files / src/components/Dynamic DynamicTable.js

0% Statements 0/66
0% Branches 0/62
0% Functions 0/22
0% Lines 0/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import React from 'react'
import {
	CTable,
	CTableHead,
	CTableBody,
	CTableRow,
	CTableHeaderCell,
	CTableDataCell,
	CCard,
	CCardBody,
	CFormInput,
	CForm,
	CCollapse,
	CButton,
	CFormSelect,
	CCardHeader,
} from '@coreui/react'
import { useNavigate } from 'react-router-dom'
 
/**
 * `DynamicTable` is a reusable, fully-configurable table component that supports sorting, filtering,
 * pagination, and row-click navigation. It is designed to render dynamic column and row data,
 * and can optionally provide search filters and clickable rows that navigate to a specific route.
 *
 * @component
 *
 * @example
 * <DynamicTable
 *   title="Users"
 *   columns={[
 *     { label: 'Name', value: 'name' },
 *     { label: 'Email', value: 'email' },
 *     { label: 'Role', value: 'role' }
 *   ]}
 *   data={userData}
 *   onRowClickPath="/users"
 *   rowIdField="_id"
 * />
 *
 * @param {Object} props
 * @param {string} [props.title] - Optional title displayed above the table.
 * @param {Array<Object>} props.columns - Column definitions. Each object should have:
 * @param {string} props.columns[].label - The label shown in the table header.
 * @param {string} props.columns[].value - The key used to extract data from each row object.
 * @param {Array<Object>} props.data - Array of objects representing the table rows.
 * @param {boolean} [props.enableFilters=true] - Enables or disables the filter inputs above the table.
 * @param {string} [props.onRowClickPath] - Optional base route path to navigate to when a row is clicked.
 * @param {string} [props.rowIdField] - The key used to extract the unique identifier for navigation (e.g., `_id`).
 * @param {Array<number>} [props.itemsPerPageOptions=[10, 20, 50]] - Options for how many items to show per page.
 *
 * @returns {JSX.Element} The rendered table component with filters, pagination, and navigation.
 */
const DynamicTable = ({
	title,
	columns = [],
	data = [],
	enableFilters = true,
	onRowClickPath,
	rowIdField,
	itemsPerPageOptions = [10, 20, 50],
}) => {
	const navigate = useNavigate()
 
	// Pagination state
	const [currentPage, setCurrentPage] = React.useState(1)
	const [itemsPerPage, setItemsPerPage] = React.useState(itemsPerPageOptions[0])
 
	// Sorting state
	const [sortConfig, setSortConfig] = React.useState({ key: null, direction: 'asc' })
 
	// Filters
	const [filters, setFilters] = React.useState(
		Object.fromEntries(columns.map((col) => [col.value, '']))
	)
	const [collapse, setCollapse] = React.useState(true)
 
	const requestSort = (key) => {
		const direction =
			sortConfig.key === key && sortConfig.direction === 'asc' ? 'desc' : 'asc'
		setSortConfig({ key, direction })
	}
 
	const getSortIndicator = (key) => {
		if (sortConfig.key !== key) return ''
		return sortConfig.direction === 'asc' ? ' ▲' : ' ▼'
	}
 
	// Apply filters
	const filteredData = data
		.filter((row) =>
			columns.every(({ value }) => {
				const cellValue = row[value]
				if (cellValue == null) return true
				return cellValue.toString().toLowerCase().includes(filters[value].toLowerCase())
			})
		)
		.map((row) => {
			const newRow = { ...row }
			for (const key in newRow) {
				if (typeof newRow[key] === 'boolean') {
					newRow[key] = newRow[key].toString()
				}
				if (newRow[key] == null || newRow[key] === '') {
					newRow[key] = ''
				}
			}
			return newRow
		})
 
	// Sort the data
	const sortedData = [...filteredData].sort((a, b) => {
		if (!sortConfig.key) return 0
		const aVal = a[sortConfig.key]
		const bVal = b[sortConfig.key]
 
		if (typeof aVal === 'number' && typeof bVal === 'number') {
			return sortConfig.direction === 'asc' ? aVal - bVal : bVal - aVal
		}
 
		if (typeof aVal === 'string' && typeof bVal === 'string') {
			const aStr = aVal.toLowerCase()
			const bStr = bVal.toLowerCase()
			return sortConfig.direction === 'asc' ? aStr.localeCompare(bStr) : bStr.localeCompare(aStr)
		}
 
		if (aVal == null) return sortConfig.direction === 'asc' ? 1 : -1
		if (bVal == null) return sortConfig.direction === 'asc' ? -1 : 1
 
		return 0
	})
 
	// Pagination
	const indexOfLast = currentPage * itemsPerPage
	const indexOfFirst = indexOfLast - itemsPerPage
	const currentItems = sortedData.slice(indexOfFirst, indexOfLast)
	const totalPages = Math.ceil(sortedData.length / itemsPerPage)
 
	// Handle row click navigation
	const handleRowClick = (item) => {
		if (onRowClickPath && rowIdField) navigate(`${onRowClickPath}/${item[rowIdField]}`)
	}
 
	return (
		<>
			<CCard>
				{title && <CCardHeader as="h5">{title}</CCardHeader>}
				<CCardBody>
					{/* Filters Toggle */}
					{enableFilters && (
						<>
							<CButton
								color="secondary"
								variant="outline"
								onClick={() => setCollapse(!collapse)}
								className="mb-3"
							>
								{collapse ? 'Show Filters' : 'Hide Filters'}
							</CButton>
 
							<CCollapse visible={!collapse}>
								<CForm className="row g-3 mb-3">
									{columns.map(
										({ label, value }) => value !== 'id' && (
											<div className="col-md-4" key={value}>
												<CFormInput
													label={label}
													value={filters[value]}
													onChange={(e) =>
														setFilters((prev) => ({
															...prev,
															[value]: e.target.value,
														}))
													}
													placeholder={`Search ${label.toLowerCase()}`}
												/>
											</div>
										)
									)}
								</CForm>
							</CCollapse>
						</>
					)}
 
					{/* Table */}
					<CTable hover responsive>
						<CTableHead>
							<CTableRow>
								{columns.map(({ label, value }) => (
									<CTableHeaderCell
										key={value}
										onClick={() => requestSort(value)}
										style={{ cursor: 'pointer' }}
									>
										{label}
										{getSortIndicator(value)}
									</CTableHeaderCell>
								))}
							</CTableRow>
						</CTableHead>
						<CTableBody>
							{currentItems.map((item, index) => (
								<CTableRow
									key={item._id ?? index}
									style={{ cursor: onRowClickPath ? 'pointer' : 'default' }}
									onClick={() => handleRowClick(item)}
								>
									{columns.map(({ value }) => (
										<CTableDataCell key={value}>{item[value]}</CTableDataCell>
									))}
								</CTableRow>
							))}
						</CTableBody>
					</CTable>
 
					{/* Pagination Controls */}
					<div className="d-flex justify-content-between align-items-center mt-3">
						<div>
							{sortedData.length > 0 && (
								<small className="text-muted"> Showing {indexOfFirst + 1}–{Math.min(indexOfLast, sortedData.length)} of {sortedData.length}</small>
							)}
						</div>
						<div className="d-flex align-items-center">
							<CFormSelect
								style={{ width: '70px', marginRight: '10px' }}
								value={itemsPerPage}
								onChange={(e) => {
									setItemsPerPage(Number(e.target.value))
									setCurrentPage(1)
								}}
							>
								{itemsPerPageOptions.map((option) => (
									<option key={option} value={option}>
										{option}
									</option>
								))}
							</CFormSelect>
 
							<CButton
								color="secondary"
								disabled={currentPage === 1}
								onClick={() => setCurrentPage(currentPage - 1)}
								className="me-2"
							>
								Previous
							</CButton>
							<CButton
								color="secondary"
								disabled={currentPage === totalPages || totalPages === 0}
								onClick={() => setCurrentPage(currentPage + 1)}
							>
								Next
							</CButton>
						</div>
					</div>
				</CCardBody>
			</CCard>
			<br />
		</>
	)
}
 
export default DynamicTable