mirror of
https://github.com/rgrgogu/new_starr.git
synced 2026-09-27 00:12:54 +08:00
Adjusted
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
// components/generic/Dashboard/BarBreakdown.jsx
|
||||
|
||||
import { BarChart, Bar, XAxis, YAxis, Tooltip, Cell, ResponsiveContainer } from "recharts";
|
||||
|
||||
const DEFAULT_COLORS = [
|
||||
"#6366f1", "#22c55e", "#f59e0b", "#ef4444",
|
||||
"#06b6d4", "#a855f7", "#ec4899", "#84cc16",
|
||||
];
|
||||
|
||||
/**
|
||||
* A horizontal bar chart card for ranked data.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {string} props.label Card title
|
||||
* @param {Array} props.data [{ label, value }]
|
||||
* @param {Function} [props.onBarClick] (entry) => void — called with the clicked bar
|
||||
* @param {string[]} [props.colors]
|
||||
* @param {number} [props.height] Default: 240
|
||||
* @param {number} [props.yAxisWidth] Default: 130
|
||||
* @param {string} [props.className]
|
||||
*
|
||||
* @example
|
||||
* <BarBreakdown
|
||||
* label="Top Groups by Members"
|
||||
* data={breakdown.data}
|
||||
* onBarClick={(entry) => navigate(`/admin/users/groups`)}
|
||||
* />
|
||||
*/
|
||||
export function BarBreakdown({
|
||||
label,
|
||||
data = [],
|
||||
onBarClick,
|
||||
colors = DEFAULT_COLORS,
|
||||
height = 240,
|
||||
yAxisWidth = 130,
|
||||
className = "",
|
||||
}) {
|
||||
if (!data.length) return null;
|
||||
|
||||
const isClickable = typeof onBarClick === "function";
|
||||
|
||||
return (
|
||||
<div className={`bg-card border rounded-xl p-4 flex flex-col gap-2 ${className}`}>
|
||||
<p className="text-sm font-medium">{label}</p>
|
||||
<ResponsiveContainer width="100%" height={height}>
|
||||
<BarChart
|
||||
data={data}
|
||||
layout="vertical"
|
||||
margin={{ left: 0, right: 24, top: 4, bottom: 4 }}
|
||||
onClick={isClickable ? ({ activePayload }) => {
|
||||
if (activePayload?.[0]) onBarClick(activePayload[0].payload);
|
||||
} : undefined}
|
||||
style={isClickable ? { cursor: "pointer" } : undefined}
|
||||
>
|
||||
<XAxis type="number" tick={{ fontSize: 11 }} />
|
||||
<YAxis
|
||||
type="category"
|
||||
dataKey="label"
|
||||
tick={{ fontSize: 11 }}
|
||||
width={yAxisWidth}
|
||||
/>
|
||||
<Tooltip />
|
||||
<Bar dataKey="value" radius={[0, 4, 4, 0]}>
|
||||
{data.map((_, i) => (
|
||||
<Cell key={i} fill={colors[i % colors.length]} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// components/generic/Dashboard/DashboardSection.jsx
|
||||
|
||||
import { StatGrid } from "./StatGrid";
|
||||
import { PieBreakdown } from "./PieBreakdown";
|
||||
import { BarBreakdown } from "./BarBreakdown";
|
||||
|
||||
/**
|
||||
* Renders a titled section with a stat grid and breakdown charts.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {string} props.title
|
||||
* @param {Array} props.stats [{ key, label, value, icon? }]
|
||||
* @param {Array} [props.breakdowns] [{ key, label, chartType, data[] }]
|
||||
* @param {Object} [props.iconMap] { [statKey]: <ReactNode> }
|
||||
* @param {Object} [props.linkMap] { [statKey]: () => void } — stat card click handlers
|
||||
* @param {Object} [props.chartLinkMap] { [breakdownKey]: (entry) => void } — chart segment click handlers
|
||||
* @param {string} [props.className]
|
||||
*
|
||||
* @example
|
||||
* <DashboardSection
|
||||
* title="Users"
|
||||
* stats={dashboard.users.stats}
|
||||
* breakdowns={dashboard.users.breakdowns}
|
||||
* iconMap={USER_ICON_MAP}
|
||||
* linkMap={{
|
||||
* total: () => navigate('/admin/users/all'),
|
||||
* archived: () => navigate('/admin/users/all/archived'),
|
||||
* }}
|
||||
* chartLinkMap={{
|
||||
* acc_type: (entry) => navigate(`/admin/users/all`),
|
||||
* }}
|
||||
* />
|
||||
*/
|
||||
export function DashboardSection({
|
||||
title,
|
||||
stats = [],
|
||||
breakdowns = [],
|
||||
iconMap = {},
|
||||
linkMap = {},
|
||||
chartLinkMap = {},
|
||||
className = "",
|
||||
}) {
|
||||
return (
|
||||
<section className={`flex flex-col gap-4 ${className}`}>
|
||||
{title && <h2 className="text-base font-medium">{title}</h2>}
|
||||
|
||||
{stats.length > 0 && (
|
||||
<StatGrid stats={stats} iconMap={iconMap} linkMap={linkMap} />
|
||||
)}
|
||||
|
||||
{breakdowns.length > 0 && (
|
||||
<div className={`grid gap-4 ${breakdowns.length > 1 ? "sm:grid-cols-2" : "grid-cols-1"}`}>
|
||||
{breakdowns.map((b) =>
|
||||
b.chartType === "bar" ? (
|
||||
<BarBreakdown
|
||||
key={b.key}
|
||||
label={b.label}
|
||||
data={b.data}
|
||||
onBarClick={chartLinkMap[b.key]}
|
||||
/>
|
||||
) : (
|
||||
<PieBreakdown
|
||||
key={b.key}
|
||||
label={b.label}
|
||||
data={b.data}
|
||||
onSliceClick={chartLinkMap[b.key]}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// components/generic/Dashboard/PieBreakdown.jsx
|
||||
|
||||
import { PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer } from "recharts";
|
||||
|
||||
const DEFAULT_COLORS = [
|
||||
"#6366f1", "#22c55e", "#f59e0b", "#ef4444",
|
||||
"#06b6d4", "#a855f7", "#ec4899", "#84cc16",
|
||||
];
|
||||
|
||||
/**
|
||||
* A pie chart card for small-cardinality breakdowns.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {string} props.label Card title
|
||||
* @param {Array} props.data [{ label, value }]
|
||||
* @param {Function} [props.onSliceClick] (entry) => void — called with the clicked slice
|
||||
* @param {string[]} [props.colors]
|
||||
* @param {number} [props.height] Default: 220
|
||||
* @param {string} [props.className]
|
||||
*
|
||||
* @example
|
||||
* <PieBreakdown
|
||||
* label="By Account Type"
|
||||
* data={breakdown.data}
|
||||
* onSliceClick={(entry) => navigate(`/admin/users/all?acc_type=${entry.label}`)}
|
||||
* />
|
||||
*/
|
||||
export function PieBreakdown({
|
||||
label,
|
||||
data = [],
|
||||
onSliceClick,
|
||||
colors = DEFAULT_COLORS,
|
||||
height = 220,
|
||||
className = "",
|
||||
}) {
|
||||
if (!data.length) return null;
|
||||
|
||||
const isClickable = typeof onSliceClick === "function";
|
||||
|
||||
return (
|
||||
<div className={`bg-card border rounded-xl p-4 flex flex-col gap-2 ${className}`}>
|
||||
<p className="text-sm font-medium">{label}</p>
|
||||
<ResponsiveContainer width="100%" height={height}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={data}
|
||||
dataKey="value"
|
||||
nameKey="label"
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
outerRadius={80}
|
||||
label={({ label: l, percent }) =>
|
||||
`${l} ${(percent * 100).toFixed(0)}%`
|
||||
}
|
||||
labelLine={false}
|
||||
onClick={isClickable ? (entry) => onSliceClick(entry) : undefined}
|
||||
cursor={isClickable ? "pointer" : undefined}
|
||||
>
|
||||
{data.map((_, i) => (
|
||||
<Cell key={i} fill={colors[i % colors.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip formatter={(v, n) => [v, n]} />
|
||||
<Legend />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// components/generic/Dashboard/StatCard.jsx
|
||||
|
||||
/**
|
||||
* A single metric card. Optionally clickable for navigation.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {string} props.label Display label
|
||||
* @param {number|string} props.value Metric value
|
||||
* @param {ReactNode} [props.icon] Optional icon
|
||||
* @param {Function} [props.onClick] If provided, card becomes clickable
|
||||
* @param {string} [props.className] Extra classes on the card
|
||||
*
|
||||
* @example
|
||||
* <StatCard
|
||||
* label="Total Users"
|
||||
* value={128}
|
||||
* icon={<Users className="size-5" />}
|
||||
* onClick={() => navigate('/admin/users/all')}
|
||||
* />
|
||||
*/
|
||||
export function StatCard({ label, value, icon, onClick, className = "" }) {
|
||||
const isClickable = typeof onClick === "function";
|
||||
|
||||
return (
|
||||
<div
|
||||
role={isClickable ? "button" : undefined}
|
||||
tabIndex={isClickable ? 0 : undefined}
|
||||
onClick={isClickable ? onClick : undefined}
|
||||
onKeyDown={isClickable ? (e) => e.key === "Enter" && onClick() : undefined}
|
||||
className={`
|
||||
bg-card border rounded-xl px-4 py-4 flex items-center gap-4
|
||||
${isClickable ? "cursor-pointer hover:border-foreground/30 hover:bg-accent transition-colors" : ""}
|
||||
${className}
|
||||
`}
|
||||
>
|
||||
{icon && (
|
||||
<div className="shrink-0 bg-muted rounded-lg p-2">
|
||||
{icon}
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<p className="text-[11px] uppercase tracking-wide text-muted-foreground truncate">
|
||||
{label}
|
||||
</p>
|
||||
<p className="text-2xl font-semibold leading-tight">{value ?? 0}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// components/generic/Dashboard/StatGrid.jsx
|
||||
|
||||
import { StatCard } from "./StatCard";
|
||||
|
||||
/**
|
||||
* Renders a responsive grid of StatCards from a stats array.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {Array} props.stats [{ key, label, value, icon? }]
|
||||
* @param {Object} [props.iconMap] { [key]: <ReactNode> }
|
||||
* @param {Object} [props.linkMap] { [key]: () => void } — maps stat key → navigate callback
|
||||
* @param {string} [props.className]
|
||||
*
|
||||
* @example
|
||||
* const linkMap = {
|
||||
* total: () => navigate('/admin/users/all'),
|
||||
* active: () => navigate('/admin/users/all'),
|
||||
* archived: () => navigate('/admin/users/all/archived'),
|
||||
* };
|
||||
* <StatGrid stats={dashboard.users.stats} iconMap={iconMap} linkMap={linkMap} />
|
||||
*/
|
||||
export function StatGrid({ stats = [], iconMap = {}, linkMap = {}, className = "" }) {
|
||||
return (
|
||||
<div className={`grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 ${className}`}>
|
||||
{stats.map((s) => (
|
||||
<StatCard
|
||||
key={s.key}
|
||||
label={s.label}
|
||||
value={s.value}
|
||||
icon={s.icon ?? iconMap[s.key]}
|
||||
onClick={linkMap[s.key]}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// components/generic/Dashboard/TableDashboard.jsx
|
||||
|
||||
import { StatCard } from "./StatCard";
|
||||
import { PieBreakdown } from "./PieBreakdown";
|
||||
import { BarBreakdown } from "./BarBreakdown";
|
||||
|
||||
/**
|
||||
* A dashboard strip rendered above a DataTable.
|
||||
* Clicking any stat card or chart segment applies a filter to the table
|
||||
* via tableRefsRef.current.setFilters([{ id, value }]).
|
||||
*
|
||||
* Clicking the same card/segment again clears that filter (toggle).
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {Array} props.stats
|
||||
* [{ key, label, value, icon?, filterId?, filterValue? }]
|
||||
* - filterId: column id to filter on (e.g. "is_active")
|
||||
* - filterValue: value array to apply (e.g. ["true"])
|
||||
*
|
||||
* @param {Array} props.breakdowns
|
||||
* [{ key, label, chartType, filterId?, data: [{ label, value }] }]
|
||||
* - filterId: column id for the breakdown (e.g. "acc_type")
|
||||
* - Each data entry's `label` becomes the filterValue when clicked
|
||||
*
|
||||
* @param {Object} props.iconMap { [statKey]: <ReactNode> }
|
||||
* @param {Array} props.activeFilters filtersRef.current — to highlight active items
|
||||
* @param {Object} props.tableRefsRef ref with { setFilters, getFilters }
|
||||
* @param {string} [props.className]
|
||||
*
|
||||
* @example — Users table
|
||||
* <TableDashboard
|
||||
* stats={dashboard.users.stats}
|
||||
* breakdowns={dashboard.users.breakdowns}
|
||||
* iconMap={USER_ICON_MAP}
|
||||
* activeFilters={tableRefsRef.current.getFilters?.() ?? []}
|
||||
* tableRefsRef={tableRefsRef}
|
||||
* />
|
||||
*/
|
||||
export function TableDashboard({
|
||||
stats = [],
|
||||
breakdowns = [],
|
||||
statMap = {},
|
||||
tableRefsRef, // ← remove activeFilters prop entirely
|
||||
className = "",
|
||||
}) {
|
||||
// ─── Always read live from ref ────────────────────────────────────────────
|
||||
function getActiveFilters() {
|
||||
return tableRefsRef?.current?.getFilters?.() ?? [];
|
||||
}
|
||||
|
||||
function isFilterActive(filterId, filterValue) {
|
||||
if (!filterId) return false;
|
||||
const existing = getActiveFilters().find((f) => f.id === filterId);
|
||||
if (!existing) return false;
|
||||
if (!filterValue) return true;
|
||||
return filterValue.every((v) => existing.value?.includes(v));
|
||||
}
|
||||
|
||||
function toggleFilter(filterId, filterValue) {
|
||||
if (!filterId || !tableRefsRef?.current?.setFilters) return;
|
||||
|
||||
const managedIds = new Set([
|
||||
...stats.map((s) => s.filterId),
|
||||
...breakdowns.map((b) => b.filterId),
|
||||
].filter(Boolean));
|
||||
|
||||
const current = getActiveFilters();
|
||||
const existing = current.find((f) => f.id === filterId);
|
||||
const isActive = existing &&
|
||||
(!filterValue || filterValue.every((v) => existing.value?.includes(v)));
|
||||
|
||||
const unrelated = current.filter((f) => !managedIds.has(f.id));
|
||||
|
||||
if (isActive) {
|
||||
tableRefsRef.current.setFilters(unrelated);
|
||||
} else {
|
||||
tableRefsRef.current.setFilters([
|
||||
...unrelated,
|
||||
{ id: filterId, value: filterValue ?? [] },
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
function handleStatClick(stat) {
|
||||
if (!stat.filterId) return;
|
||||
toggleFilter(stat.filterId, stat.filterValue);
|
||||
}
|
||||
|
||||
function handleChartClick(breakdown, entry) {
|
||||
if (!breakdown.filterId) return;
|
||||
toggleFilter(breakdown.filterId, [String(entry.label)]);
|
||||
}
|
||||
|
||||
if (!stats.length && !breakdowns.length) return null;
|
||||
|
||||
return (
|
||||
<div className={`flex flex-col gap-4 mb-4 ${className}`}>
|
||||
{stats.length > 0 && (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
|
||||
{stats.map((s) => {
|
||||
const active = isFilterActive(s.filterId, s.filterValue);
|
||||
const mapping = statMap[s.key] ?? {};
|
||||
return (
|
||||
<StatCard
|
||||
key={s.key}
|
||||
label={mapping.label ?? s.label}
|
||||
value={s.value}
|
||||
icon={mapping.icon}
|
||||
onClick={s.filterId ? () => handleStatClick(s) : undefined}
|
||||
className={active ? "ring-2 ring-primary border-primary" : ""}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{breakdowns.length > 0 && (
|
||||
<div className={`grid gap-4 ${breakdowns.length > 1 ? "sm:grid-cols-2" : "grid-cols-1"}`}>
|
||||
{breakdowns.map((b) =>
|
||||
b.chartType === "bar" ? (
|
||||
<BarBreakdown
|
||||
key={b.key}
|
||||
label={b.label}
|
||||
data={b.data}
|
||||
onBarClick={b.filterId ? (entry) => handleChartClick(b, entry) : undefined}
|
||||
/>
|
||||
) : (
|
||||
<PieBreakdown
|
||||
key={b.key}
|
||||
label={b.label}
|
||||
data={b.data}
|
||||
onSliceClick={b.filterId ? (entry) => handleChartClick(b, entry) : undefined}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
// components/generic/Sheet/AddUsersSheet.jsx
|
||||
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
|
||||
/**
|
||||
* Generic sheet for selecting and adding users to any entity
|
||||
* (groups, tasks, projects, etc.)
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {boolean} props.open
|
||||
* @param {Function} props.onOpenChange
|
||||
*
|
||||
* @param {string} [props.title] Sheet heading. Default: "Add members"
|
||||
* @param {string} [props.submitLabel] Submit button label. Default: "Add"
|
||||
*
|
||||
* @param {Array} props.users [{ [idKey], [labelKey] }] — list to display
|
||||
* @param {boolean} props.loading
|
||||
* @param {Function} props.onFetch Called on open to (re)load the list
|
||||
*
|
||||
* @param {string} [props.idKey] Key for the user id. Default: "user_id"
|
||||
* @param {string} [props.labelKey] Key for the display name. Default: "full_name"
|
||||
* @param {string} [props.subLabelKey] Optional secondary line (e.g. "email")
|
||||
*
|
||||
* @param {Function} props.onSubmit Called with selected ids[]
|
||||
*
|
||||
* @example — groups
|
||||
* <AddUsersSheet
|
||||
* title="Add members"
|
||||
* users={usersNotIn}
|
||||
* onFetch={() => fetchUsersNotInGroup(gid)}
|
||||
* onSubmit={(ids) => addUsersToGroup(gid, ids)}
|
||||
* ...
|
||||
* />
|
||||
*
|
||||
* @example — tasks
|
||||
* <AddUsersSheet
|
||||
* title="Assign users"
|
||||
* users={unassignedUsers}
|
||||
* onFetch={() => fetchUnassignedUsers(taskId)}
|
||||
* onSubmit={(ids) => assignUsersToTask(taskId, ids)}
|
||||
* idKey="user_id"
|
||||
* labelKey="full_name"
|
||||
* subLabelKey="email"
|
||||
* ...
|
||||
* />
|
||||
*/
|
||||
export function AddSheet({
|
||||
open,
|
||||
onOpenChange,
|
||||
|
||||
title = "Add members",
|
||||
submitLabel = "Add",
|
||||
|
||||
users = [],
|
||||
loading = false,
|
||||
onFetch,
|
||||
|
||||
idKey = "user_id",
|
||||
labelKey = "full_name",
|
||||
subLabelKey = null,
|
||||
|
||||
onSubmit,
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [selected, setSelected] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
onFetch?.();
|
||||
setSearch("");
|
||||
setSelected([]);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (!search.trim()) return users;
|
||||
return users.filter((u) =>
|
||||
String(u[labelKey] ?? "").toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
}, [search, users, labelKey]);
|
||||
|
||||
const toggle = (id) =>
|
||||
setSelected((prev) =>
|
||||
prev.includes(id) ? prev.filter((v) => v !== id) : [...prev, id]
|
||||
);
|
||||
|
||||
const toggleAll = () => {
|
||||
const allIds = filtered.map((u) => u[idKey]);
|
||||
const allSelected = allIds.every((id) => selected.includes(id));
|
||||
setSelected((prev) =>
|
||||
allSelected
|
||||
? prev.filter((id) => !allIds.includes(id))
|
||||
: [...new Set([...prev, ...allIds])]
|
||||
);
|
||||
};
|
||||
|
||||
const allFilteredSelected =
|
||||
filtered.length > 0 && filtered.every((u) => selected.includes(u[idKey]));
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!selected.length) return;
|
||||
await onSubmit(selected);
|
||||
onOpenChange(false);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
setSearch("");
|
||||
setSelected([]);
|
||||
onOpenChange(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={handleClose}>
|
||||
{/*
|
||||
SheetContent is a flex column with fixed height (100dvh).
|
||||
We split it into 3 rows: header (shrink-0), body (flex-1 overflow-hidden), footer (shrink-0).
|
||||
The body itself is a flex column — search and select-all shrink, list overflows.
|
||||
*/}
|
||||
<SheetContent side="right" className="w-[400px] flex flex-col h-full p-0">
|
||||
|
||||
{/* Header */}
|
||||
<SheetHeader className="shrink-0 border-b px-6 py-4">
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
{/* Body — fills remaining space, clips overflow */}
|
||||
<div className="flex-1 min-h-0 flex flex-col gap-3 px-6 py-4 relative">
|
||||
{loading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/60 backdrop-blur-sm z-10">
|
||||
<Spinner className="size-8" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search — fixed height */}
|
||||
<div className="shrink-0">
|
||||
<Input
|
||||
placeholder="Search..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Select all — fixed height */}
|
||||
{filtered.length > 0 && (
|
||||
<label className="shrink-0 flex items-center gap-2 text-sm font-medium cursor-pointer select-none border-b pb-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allFilteredSelected}
|
||||
onChange={toggleAll}
|
||||
/>
|
||||
Select all ({filtered.length})
|
||||
</label>
|
||||
)}
|
||||
|
||||
{/* Scrollable list — takes all remaining space */}
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
<div className="space-y-1 pr-1">
|
||||
{!loading && filtered.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-6">
|
||||
{search ? `No results for "${search}".` : "No users available."}
|
||||
</p>
|
||||
) : (
|
||||
filtered.map((user) => {
|
||||
const id = user[idKey];
|
||||
const label = user[labelKey];
|
||||
const sub = subLabelKey ? user[subLabelKey] : null;
|
||||
|
||||
return (
|
||||
<label
|
||||
key={id}
|
||||
className="flex items-center gap-3 p-1 rounded-md hover:bg-muted cursor-pointer text-sm select-none"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(id)}
|
||||
onChange={() => toggle(id)}
|
||||
/>
|
||||
<div className="flex flex-col min-w-0">
|
||||
<span className="truncate">{label}</span>
|
||||
{sub && (
|
||||
<span className="text-xs text-muted-foreground truncate">
|
||||
{sub}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="shrink-0 flex gap-2 border-t px-6 py-4">
|
||||
<Button variant="outline" className="flex-1" onClick={handleClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
className="flex-1"
|
||||
disabled={!selected.length || loading}
|
||||
onClick={handleSubmit}
|
||||
>
|
||||
{selected.length > 0 ? `${submitLabel} (${selected.length})` : submitLabel}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useMemo, useRef, useEffect } from "react";
|
||||
import { useState, useMemo, useRef, useEffect, useCallback } from "react";
|
||||
import { useReactTable, getCoreRowModel, flexRender, } from "@tanstack/react-table";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
@@ -35,31 +35,62 @@ export default function DataTable({
|
||||
}) {
|
||||
// ─── Refs — always hold latest filters and sort ───────────────────────────
|
||||
const filtersRef = useRef([]);
|
||||
const sortRef = useRef([]);
|
||||
|
||||
const sortRef = useRef([]);
|
||||
|
||||
// ─── State ────────────────────────────────────────────────────────────────
|
||||
const [activeColumn, setActiveColumn] = useState(null);
|
||||
const [sorting, setSorting] = useState([]);
|
||||
const [columnFilters, setColumnFilters] = useState([]);
|
||||
const [columnVisibility, setColumnVisibility] = useState({});
|
||||
const [rowSelection, setRowSelection] = useState({});
|
||||
const [filterState, setFilterState] = useState({
|
||||
const [activeColumn, setActiveColumn] = useState(null);
|
||||
const [sorting, setSorting] = useState([]);
|
||||
const [columnFilters, setColumnFilters] = useState([]);
|
||||
const [columnVisibility, setColumnVisibility] = useState({});
|
||||
const [rowSelection, setRowSelection] = useState({});
|
||||
const [filterState, setFilterState] = useState({
|
||||
open: false, column: null, attr: null, data: [],
|
||||
});
|
||||
|
||||
const activeFilters = columnFilters.filter((f) => f.value !== "");
|
||||
|
||||
// ─── Initial fetch on mount only ─────────────────────────────────────────
|
||||
// ─── setFilters — called externally by dashboard charts ──────────────────
|
||||
// Merges incoming filters with existing ones (replaces by id, appends new).
|
||||
// Pass an empty array [] to clear all filters.
|
||||
const setFilters = useCallback((incomingFilters) => {
|
||||
setColumnFilters((prev) => {
|
||||
let next;
|
||||
|
||||
if (!incomingFilters.length) {
|
||||
next = [];
|
||||
} else {
|
||||
// Replace matching ids, keep the rest
|
||||
const incomingIds = new Set(incomingFilters.map((f) => f.id));
|
||||
const kept = prev.filter((f) => !incomingIds.has(f.id));
|
||||
next = [...kept, ...incomingFilters];
|
||||
}
|
||||
|
||||
const newFilters = next.filter((f) => f.value !== "");
|
||||
filtersRef.current = newFilters;
|
||||
|
||||
onFetch({
|
||||
page: 1,
|
||||
limit: pagination.limit,
|
||||
filters: newFilters,
|
||||
sort: sortRef.current,
|
||||
});
|
||||
|
||||
return next;
|
||||
});
|
||||
}, [onFetch, pagination.limit]);
|
||||
|
||||
// ─── Expose refs to parent ────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
onRefsReady?.({
|
||||
getFilters: () => filtersRef.current,
|
||||
getSort: () => sortRef.current,
|
||||
resetSelection: () => table.resetRowSelection(), // ← expose this
|
||||
getFilters: () => filtersRef.current,
|
||||
getSort: () => sortRef.current,
|
||||
resetSelection: () => table.resetRowSelection(),
|
||||
setFilters, // ← new
|
||||
});
|
||||
|
||||
onFetch({ page: 1, limit: pagination.limit, filters: [], sort: [] });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
}, [setFilters]);
|
||||
|
||||
const handleOpenFilterSheet = async (e, column, attr) => {
|
||||
e.preventDefault();
|
||||
@@ -79,61 +110,60 @@ export default function DataTable({
|
||||
rowSelection,
|
||||
pagination: {
|
||||
pageIndex: pagination.page - 1,
|
||||
pageSize: pagination.limit,
|
||||
pageSize: pagination.limit,
|
||||
},
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
manualPagination: true,
|
||||
manualSorting: true,
|
||||
manualFiltering: true,
|
||||
pageCount: pagination.totalPages,
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
manualPagination: true,
|
||||
manualSorting: true,
|
||||
manualFiltering: true,
|
||||
pageCount: pagination.totalPages,
|
||||
|
||||
// ─── Sort change ────────────────────────────────────────────────────────
|
||||
// ─── Sort change ──────────────────────────────────────────────────────
|
||||
onSortingChange: (updater) => {
|
||||
const next = typeof updater === "function" ? updater(sorting) : updater;
|
||||
const next = typeof updater === "function" ? updater(sorting) : updater;
|
||||
const newSort = next.length ? [{ id: next[0].id, desc: next[0].desc }] : [];
|
||||
|
||||
setSorting(next);
|
||||
sortRef.current = newSort;
|
||||
|
||||
onFetch({
|
||||
page: 1,
|
||||
limit: pagination.limit,
|
||||
page: 1,
|
||||
limit: pagination.limit,
|
||||
filters: filtersRef.current,
|
||||
sort: newSort,
|
||||
sort: newSort,
|
||||
});
|
||||
},
|
||||
|
||||
// ─── Filter change ──────────────────────────────────────────────────────
|
||||
// ─── Filter change ────────────────────────────────────────────────────
|
||||
onColumnFiltersChange: (updater) => {
|
||||
const next = typeof updater === "function" ? updater(columnFilters) : updater;
|
||||
const next = typeof updater === "function" ? updater(columnFilters) : updater;
|
||||
const newFilters = next.filter((f) => f.value !== "");
|
||||
|
||||
setColumnFilters(next);
|
||||
filtersRef.current = newFilters;
|
||||
|
||||
onFetch({
|
||||
page: 1,
|
||||
limit: pagination.limit,
|
||||
page: 1,
|
||||
limit: pagination.limit,
|
||||
filters: newFilters,
|
||||
sort: sortRef.current,
|
||||
sort: sortRef.current,
|
||||
});
|
||||
},
|
||||
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
|
||||
// ─── Single handler for all page changes ──────────────────────────────────────
|
||||
// ─── Page change ──────────────────────────────────────────────────────────
|
||||
const handlePageChange = (page) => {
|
||||
setPagination((p) => ({ ...p, page }));
|
||||
onFetch({
|
||||
page,
|
||||
limit: pagination.limit,
|
||||
limit: pagination.limit,
|
||||
filters: filtersRef.current,
|
||||
sort: sortRef.current,
|
||||
sort: sortRef.current,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -169,7 +199,7 @@ export default function DataTable({
|
||||
onFetch({ page: 1, limit: pagination.limit, filters: [], sort: sortRef.current });
|
||||
}}
|
||||
onRemove={(id) => {
|
||||
const next = columnFilters.filter((c) => c.id !== id);
|
||||
const next = columnFilters.filter((c) => c.id !== id);
|
||||
const newFilters = next.filter((f) => f.value !== "");
|
||||
setColumnFilters(next);
|
||||
filtersRef.current = newFilters;
|
||||
@@ -187,7 +217,7 @@ export default function DataTable({
|
||||
filters={activeFilters}
|
||||
attributes={attributes}
|
||||
onRemove={(id) => {
|
||||
const next = columnFilters.filter((c) => c.id !== id);
|
||||
const next = columnFilters.filter((c) => c.id !== id);
|
||||
const newFilters = next.filter((f) => f.value !== "");
|
||||
setColumnFilters(next);
|
||||
filtersRef.current = newFilters;
|
||||
@@ -204,8 +234,8 @@ export default function DataTable({
|
||||
<TableRow key={hg.id} className="bg-muted/40 hover:bg-muted/40">
|
||||
{hg.headers.map((header) => {
|
||||
const isPinned = header.column.getIsPinned();
|
||||
const attr = header.column.columnDef.meta?.attr;
|
||||
const isPlain = header.column.id === "select" || header.column.id === "actions";
|
||||
const attr = header.column.columnDef.meta?.attr;
|
||||
const isPlain = header.column.id === "select" || header.column.id === "actions";
|
||||
|
||||
return (
|
||||
<TableHead
|
||||
@@ -213,10 +243,10 @@ export default function DataTable({
|
||||
className={cn("align-middle whitespace-nowrap", isPinned ? "bg-muted" : "")}
|
||||
style={{
|
||||
position: isPinned ? "sticky" : "relative",
|
||||
right: isPinned === "right" ? header.column.getStart("right") : undefined,
|
||||
left: isPinned === "left" ? header.column.getStart("left") : undefined,
|
||||
zIndex: isPinned ? 2 : 0,
|
||||
width: header.column.columnDef.size,
|
||||
right: isPinned === "right" ? header.column.getStart("right") : undefined,
|
||||
left: isPinned === "left" ? header.column.getStart("left") : undefined,
|
||||
zIndex: isPinned ? 2 : 0,
|
||||
width: header.column.columnDef.size,
|
||||
}}
|
||||
>
|
||||
{isPlain ? (
|
||||
@@ -238,11 +268,11 @@ export default function DataTable({
|
||||
</TableHeader>
|
||||
|
||||
{renderFilterSheet?.({
|
||||
open: filterState.open,
|
||||
open: filterState.open,
|
||||
onOpenChange: (v) => setFilterState((p) => ({ ...p, open: v })),
|
||||
column: filterState.column,
|
||||
attr: filterState.attr,
|
||||
data: filterState.data,
|
||||
column: filterState.column,
|
||||
attr: filterState.attr,
|
||||
data: filterState.data,
|
||||
loading,
|
||||
})}
|
||||
|
||||
@@ -271,9 +301,9 @@ export default function DataTable({
|
||||
className={cn("m-0", isPinned && "bg-card")}
|
||||
style={{
|
||||
position: isPinned ? "sticky" : "relative",
|
||||
right: isPinned === "right" ? 0 : undefined,
|
||||
left: isPinned === "left" ? cell.column.getStart("left") : undefined,
|
||||
zIndex: isPinned ? 1 : 0,
|
||||
right: isPinned === "right" ? 0 : undefined,
|
||||
left: isPinned === "left" ? cell.column.getStart("left") : undefined,
|
||||
zIndex: isPinned ? 1 : 0,
|
||||
}}
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
@@ -298,16 +328,16 @@ export default function DataTable({
|
||||
<TablePagination
|
||||
table={table}
|
||||
pagination={pagination}
|
||||
onPageChange={handlePageChange} // ← replaces setPagination
|
||||
onPageChange={handlePageChange}
|
||||
totalRecords={pagination.totalRecords}
|
||||
rowCount={data.length}
|
||||
onPageSizeChange={(size) => {
|
||||
setPagination((p) => ({ ...p, limit: size, page: 1 })); // ← updates your state
|
||||
setPagination((p) => ({ ...p, limit: size, page: 1 }));
|
||||
onFetch({
|
||||
page: 1,
|
||||
limit: size,
|
||||
page: 1,
|
||||
limit: size,
|
||||
filters: filtersRef.current,
|
||||
sort: sortRef.current,
|
||||
sort: sortRef.current,
|
||||
});
|
||||
}}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
|
||||
Reference in New Issue
Block a user