feat: implement dashboard CRUD status column and toggle actions; refactor related components for improved functionality
This commit is contained in:
@@ -5,11 +5,12 @@ import {
|
|||||||
MessagesSquareIcon,
|
MessagesSquareIcon,
|
||||||
MessageSquareMoreIcon,
|
MessageSquareMoreIcon,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { toast } from "sonner"
|
|
||||||
|
|
||||||
import { DashboardCrudPage } from "@/components/dashboard/crud"
|
import {
|
||||||
|
createDashboardStatusColumn,
|
||||||
|
DashboardCrudPage,
|
||||||
|
} from "@/components/dashboard/crud"
|
||||||
import { Badge } from "@/components/ui/badge"
|
import { Badge } from "@/components/ui/badge"
|
||||||
import { Switch } from "@/components/ui/switch"
|
|
||||||
import {
|
import {
|
||||||
createChannel,
|
createChannel,
|
||||||
deleteChannel,
|
deleteChannel,
|
||||||
@@ -147,49 +148,28 @@ export default function DashboardChannelsPage() {
|
|||||||
label: t("channel.columnAgent"),
|
label: t("channel.columnAgent"),
|
||||||
render: (item) => item.aiAgentName || "-",
|
render: (item) => item.aiAgentName || "-",
|
||||||
},
|
},
|
||||||
{
|
createDashboardStatusColumn<AdminChannel, Status>({
|
||||||
key: "status",
|
|
||||||
label: t("channel.columnStatus"),
|
label: t("channel.columnStatus"),
|
||||||
render: (item, { actionLoading, reload, setActionLoadingId }) => (
|
getStatus: (item) => item.status as Status,
|
||||||
<div className="flex items-center gap-3">
|
getLabel: (status) => getStatusLabel(status, t),
|
||||||
<Switch
|
getBadgeVariant: (status) => (status === Status.Ok ? "default" : "outline"),
|
||||||
checked={item.status === Status.Ok}
|
isEnabled: (status) => status === Status.Ok,
|
||||||
disabled={actionLoading}
|
toggle: {
|
||||||
onCheckedChange={() => {
|
getNextStatus: (item) =>
|
||||||
void (async () => {
|
item.status === Status.Ok ? Status.Disabled : Status.Ok,
|
||||||
setActionLoadingId(item.id)
|
updateStatus: (item, nextStatus) =>
|
||||||
try {
|
updateChannelStatus(item.id, nextStatus),
|
||||||
const nextStatus =
|
successMessage: (item, nextStatus) =>
|
||||||
item.status === Status.Ok ? Status.Disabled : Status.Ok
|
t(
|
||||||
await updateChannelStatus(item.id, nextStatus)
|
nextStatus === Status.Ok
|
||||||
toast.success(
|
? "channel.statusEnabled"
|
||||||
t(
|
: "channel.statusDisabled",
|
||||||
nextStatus === Status.Ok
|
{ name: item.name }
|
||||||
? "channel.statusEnabled"
|
),
|
||||||
: "channel.statusDisabled",
|
errorMessage: t("channel.statusUpdateFailed"),
|
||||||
{ name: item.name }
|
ariaLabel: (item) => t("channel.toggleStatus", { name: item.name }),
|
||||||
)
|
},
|
||||||
)
|
}),
|
||||||
await reload()
|
|
||||||
} catch (error) {
|
|
||||||
toast.error(
|
|
||||||
error instanceof Error
|
|
||||||
? error.message
|
|
||||||
: t("channel.statusUpdateFailed")
|
|
||||||
)
|
|
||||||
} finally {
|
|
||||||
setActionLoadingId(null)
|
|
||||||
}
|
|
||||||
})()
|
|
||||||
}}
|
|
||||||
aria-label={t("channel.toggleStatus", { name: item.name })}
|
|
||||||
/>
|
|
||||||
<Badge variant={item.status === Status.Ok ? "default" : "outline"}>
|
|
||||||
{getStatusLabel(item.status as Status, t)}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]}
|
]}
|
||||||
fetchList={fetchChannels}
|
fetchList={fetchChannels}
|
||||||
getItemId={(item) => item.id}
|
getItemId={(item) => item.id}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { BanIcon, CheckCircle2Icon } from "lucide-react"
|
import { BanIcon, CheckCircle2Icon } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
|
||||||
|
|
||||||
import { DashboardCrudPage } from "@/components/dashboard/crud"
|
import {
|
||||||
import { Badge } from "@/components/ui/badge"
|
createDashboardStatusColumn,
|
||||||
import { DropdownMenuItem } from "@/components/ui/dropdown-menu"
|
createDashboardStatusToggleAction,
|
||||||
|
DashboardCrudPage,
|
||||||
|
} from "@/components/dashboard/crud"
|
||||||
import {
|
import {
|
||||||
createCompany,
|
createCompany,
|
||||||
deleteCompany,
|
deleteCompany,
|
||||||
@@ -96,26 +97,19 @@ export default function DashboardCompaniesPage() {
|
|||||||
className: "w-28",
|
className: "w-28",
|
||||||
render: (item) => item.customerCount,
|
render: (item) => item.customerCount,
|
||||||
},
|
},
|
||||||
{
|
createDashboardStatusColumn<AdminCompany, Status>({
|
||||||
key: "status",
|
|
||||||
label: t("company.columnStatus"),
|
label: t("company.columnStatus"),
|
||||||
className: "w-24",
|
className: "w-24",
|
||||||
render: (item) => (
|
getStatus: (item) => item.status as Status,
|
||||||
<Badge
|
getLabel: (status) =>
|
||||||
variant={
|
StatusLabels[status] ? getStatusLabel(status, t) : t("company.unknownStatus"),
|
||||||
item.status === Status.Ok
|
getBadgeVariant: (status) =>
|
||||||
? "default"
|
status === Status.Ok
|
||||||
: item.status === Status.Deleted
|
? "default"
|
||||||
? "outline"
|
: status === Status.Deleted
|
||||||
: "secondary"
|
? "outline"
|
||||||
}
|
: "secondary",
|
||||||
>
|
}),
|
||||||
{StatusLabels[item.status as Status]
|
|
||||||
? getStatusLabel(item.status as Status, t)
|
|
||||||
: t("company.unknownStatus")}
|
|
||||||
</Badge>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
key: "remark",
|
key: "remark",
|
||||||
label: t("company.columnRemark"),
|
label: t("company.columnRemark"),
|
||||||
@@ -177,48 +171,23 @@ export default function DashboardCompaniesPage() {
|
|||||||
maxValue: () => t("company.nameRequired"),
|
maxValue: () => t("company.nameRequired"),
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
renderRowActions={({ item, actionLoading, reload, setActionLoadingId }) => (
|
rowActions={[
|
||||||
<DropdownMenuItem
|
createDashboardStatusToggleAction<AdminCompany, Status>({
|
||||||
disabled={item.status === Status.Deleted}
|
disabled: (item) => item.status === Status.Deleted,
|
||||||
onClick={() => {
|
icon: (item) =>
|
||||||
void (async () => {
|
item.status === Status.Ok ? <BanIcon /> : <CheckCircle2Icon />,
|
||||||
setActionLoadingId(item.id)
|
label: (item) =>
|
||||||
try {
|
item.status === Status.Ok ? t("company.disable") : t("company.enable"),
|
||||||
const nextStatus = item.status === Status.Ok ? Status.Disabled : Status.Ok
|
getNextStatus: (item) =>
|
||||||
await updateCompanyStatus(item.id, nextStatus)
|
item.status === Status.Ok ? Status.Disabled : Status.Ok,
|
||||||
toast.success(
|
updateStatus: (item, nextStatus) => updateCompanyStatus(item.id, nextStatus),
|
||||||
t(nextStatus === Status.Ok ? "company.enabled" : "company.disabled", {
|
successMessage: (item, nextStatus) =>
|
||||||
name: item.name,
|
t(nextStatus === Status.Ok ? "company.enabled" : "company.disabled", {
|
||||||
})
|
name: item.name,
|
||||||
)
|
}),
|
||||||
await reload()
|
errorMessage: t("company.statusUpdateFailed"),
|
||||||
} catch (error) {
|
}),
|
||||||
toast.error(
|
]}
|
||||||
error instanceof Error
|
|
||||||
? error.message
|
|
||||||
: t("company.statusUpdateFailed")
|
|
||||||
)
|
|
||||||
} finally {
|
|
||||||
setActionLoadingId(null)
|
|
||||||
}
|
|
||||||
})()
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{actionLoading ? (
|
|
||||||
t("company.processing")
|
|
||||||
) : item.status === Status.Ok ? (
|
|
||||||
<>
|
|
||||||
<BanIcon />
|
|
||||||
{t("company.disable")}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<CheckCircle2Icon />
|
|
||||||
{t("company.enable")}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
labels={{
|
labels={{
|
||||||
refresh: t("company.refresh"),
|
refresh: t("company.refresh"),
|
||||||
create: t("company.new"),
|
create: t("company.new"),
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { FileTextIcon, RefreshCwIcon } from "lucide-react"
|
import { FileTextIcon, RefreshCwIcon } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
|
||||||
|
|
||||||
import { DashboardCrudPage } from "@/components/dashboard/crud"
|
import {
|
||||||
|
createDashboardStatusColumn,
|
||||||
|
createDashboardStatusToggleAction,
|
||||||
|
DashboardCrudPage,
|
||||||
|
} from "@/components/dashboard/crud"
|
||||||
import { Badge } from "@/components/ui/badge"
|
import { Badge } from "@/components/ui/badge"
|
||||||
import { DropdownMenuItem } from "@/components/ui/dropdown-menu"
|
|
||||||
import {
|
import {
|
||||||
createQuickReply,
|
createQuickReply,
|
||||||
deleteQuickReply,
|
deleteQuickReply,
|
||||||
@@ -93,15 +95,12 @@ export default function DashboardQuickRepliesPage() {
|
|||||||
label: t("quickReply.columnGroup"),
|
label: t("quickReply.columnGroup"),
|
||||||
render: (item) => <Badge variant="outline">{item.groupName}</Badge>,
|
render: (item) => <Badge variant="outline">{item.groupName}</Badge>,
|
||||||
},
|
},
|
||||||
{
|
createDashboardStatusColumn<AdminQuickReply, Status>({
|
||||||
key: "status",
|
|
||||||
label: t("quickReply.columnStatus"),
|
label: t("quickReply.columnStatus"),
|
||||||
render: (item) => (
|
getStatus: (item) => item.status as Status,
|
||||||
<Badge variant={item.status === Status.Ok ? "default" : "outline"}>
|
getLabel: (status) => getStatusLabel(status, t),
|
||||||
{getStatusLabel(item.status as Status, t)}
|
getBadgeVariant: (status) => (status === Status.Ok ? "default" : "outline"),
|
||||||
</Badge>
|
}),
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
key: "sortNo",
|
key: "sortNo",
|
||||||
label: t("quickReply.columnSort"),
|
label: t("quickReply.columnSort"),
|
||||||
@@ -193,51 +192,34 @@ export default function DashboardQuickRepliesPage() {
|
|||||||
maxValue: () => t("quickReply.sortInvalid"),
|
maxValue: () => t("quickReply.sortInvalid"),
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
renderRowActions={({ item, actionLoading, reload, setActionLoadingId }) => (
|
rowActions={[
|
||||||
<DropdownMenuItem
|
createDashboardStatusToggleAction<AdminQuickReply, Status>({
|
||||||
onClick={() => {
|
icon: <RefreshCwIcon />,
|
||||||
void (async () => {
|
label: (item) =>
|
||||||
setActionLoadingId(item.id)
|
item.status === Status.Ok
|
||||||
try {
|
|
||||||
const nextStatus =
|
|
||||||
item.status === Status.Ok ? Status.Disabled : Status.Ok
|
|
||||||
await updateQuickReply({
|
|
||||||
id: item.id,
|
|
||||||
groupName: item.groupName,
|
|
||||||
title: item.title,
|
|
||||||
content: item.content,
|
|
||||||
sortNo: item.sortNo,
|
|
||||||
status: nextStatus,
|
|
||||||
})
|
|
||||||
toast.success(
|
|
||||||
t(
|
|
||||||
nextStatus === Status.Ok
|
|
||||||
? "quickReply.enabled"
|
|
||||||
: "quickReply.disabled",
|
|
||||||
{ title: item.title }
|
|
||||||
)
|
|
||||||
)
|
|
||||||
await reload()
|
|
||||||
} catch (error) {
|
|
||||||
toast.error(
|
|
||||||
error instanceof Error
|
|
||||||
? error.message
|
|
||||||
: t("quickReply.statusUpdateFailed")
|
|
||||||
)
|
|
||||||
} finally {
|
|
||||||
setActionLoadingId(null)
|
|
||||||
}
|
|
||||||
})()
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<RefreshCwIcon />
|
|
||||||
{actionLoading
|
|
||||||
? t("quickReply.processing")
|
|
||||||
: item.status === Status.Ok
|
|
||||||
? t("quickReply.disable")
|
? t("quickReply.disable")
|
||||||
: t("quickReply.enable")}
|
: t("quickReply.enable"),
|
||||||
</DropdownMenuItem>
|
getNextStatus: (item) =>
|
||||||
)}
|
item.status === Status.Ok ? Status.Disabled : Status.Ok,
|
||||||
|
updateStatus: (item, nextStatus) =>
|
||||||
|
updateQuickReply({
|
||||||
|
id: item.id,
|
||||||
|
groupName: item.groupName,
|
||||||
|
title: item.title,
|
||||||
|
content: item.content,
|
||||||
|
sortNo: item.sortNo,
|
||||||
|
status: nextStatus,
|
||||||
|
}),
|
||||||
|
successMessage: (item, nextStatus) =>
|
||||||
|
t(
|
||||||
|
nextStatus === Status.Ok
|
||||||
|
? "quickReply.enabled"
|
||||||
|
: "quickReply.disabled",
|
||||||
|
{ title: item.title }
|
||||||
|
),
|
||||||
|
errorMessage: t("quickReply.statusUpdateFailed"),
|
||||||
|
}),
|
||||||
|
]}
|
||||||
labels={{
|
labels={{
|
||||||
refresh: t("quickReply.refresh"),
|
refresh: t("quickReply.refresh"),
|
||||||
create: t("quickReply.new"),
|
create: t("quickReply.new"),
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
buildDashboardCrudFormValues,
|
buildDashboardCrudFormValues,
|
||||||
normalizeDashboardCrudSubmitValues,
|
normalizeDashboardCrudSubmitValues,
|
||||||
type DashboardCrudFormField,
|
type DashboardCrudFormField,
|
||||||
|
type DashboardCrudFormOption,
|
||||||
} from "./dashboard-crud-utils"
|
} from "./dashboard-crud-utils"
|
||||||
import { DashboardCrudFieldControl } from "./dashboard-crud-field-control"
|
import { DashboardCrudFieldControl } from "./dashboard-crud-field-control"
|
||||||
|
|
||||||
@@ -116,6 +117,9 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
|
|||||||
id: number
|
id: number
|
||||||
item: TItem
|
item: TItem
|
||||||
} | null>(null)
|
} | null>(null)
|
||||||
|
const [fieldOptions, setFieldOptions] = useState<
|
||||||
|
Record<string, ReadonlyArray<DashboardCrudFormOption>>
|
||||||
|
>({})
|
||||||
const form = useForm<Record<string, string>, undefined, Record<string, string>>({
|
const form = useForm<Record<string, string>, undefined, Record<string, string>>({
|
||||||
resolver,
|
resolver,
|
||||||
defaultValues: initialValues,
|
defaultValues: initialValues,
|
||||||
@@ -157,6 +161,32 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
|
|||||||
}
|
}
|
||||||
}, [fetchDetail, fields, initialValues, item, itemId, reset])
|
}, [fetchDetail, fields, initialValues, item, itemId, reset])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
|
||||||
|
let cancelled = false
|
||||||
|
const loaders = fields
|
||||||
|
.filter((field) => field.type === "select" && field.loadOptions)
|
||||||
|
.map(async (field) => {
|
||||||
|
const options = await field.loadOptions!()
|
||||||
|
return [field.name, options] as const
|
||||||
|
})
|
||||||
|
|
||||||
|
if (loaders.length === 0) return
|
||||||
|
|
||||||
|
void Promise.all(loaders).then((entries) => {
|
||||||
|
if (cancelled) return
|
||||||
|
setFieldOptions((current) => ({
|
||||||
|
...current,
|
||||||
|
...Object.fromEntries(entries),
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
}, [fields, open])
|
||||||
|
|
||||||
async function submit(values: Record<string, string>) {
|
async function submit(values: Record<string, string>) {
|
||||||
const normalizedValues = normalizeDashboardCrudSubmitValues(fields, values)
|
const normalizedValues = normalizeDashboardCrudSubmitValues(fields, values)
|
||||||
const payload = transformSubmitValues
|
const payload = transformSubmitValues
|
||||||
@@ -205,7 +235,10 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
|
|||||||
{layoutFields.map((field) => (
|
{layoutFields.map((field) => (
|
||||||
<DashboardCrudFieldControl
|
<DashboardCrudFieldControl
|
||||||
key={field.name}
|
key={field.name}
|
||||||
field={field}
|
field={{
|
||||||
|
...field,
|
||||||
|
options: fieldOptions[field.name] ?? field.options,
|
||||||
|
}}
|
||||||
control={control}
|
control={control}
|
||||||
register={register}
|
register={register}
|
||||||
error={errors[field.name]}
|
error={errors[field.name]}
|
||||||
|
|||||||
@@ -1,8 +1,26 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import type { ReactNode } from "react"
|
import type { ReactNode } from "react"
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
import { useCallback, useEffect, useState } from "react"
|
||||||
import {
|
import {
|
||||||
|
closestCenter,
|
||||||
|
DndContext,
|
||||||
|
KeyboardSensor,
|
||||||
|
PointerSensor,
|
||||||
|
useSensor,
|
||||||
|
useSensors,
|
||||||
|
type DragEndEvent,
|
||||||
|
} from "@dnd-kit/core"
|
||||||
|
import {
|
||||||
|
arrayMove,
|
||||||
|
SortableContext,
|
||||||
|
sortableKeyboardCoordinates,
|
||||||
|
useSortable,
|
||||||
|
verticalListSortingStrategy,
|
||||||
|
} from "@dnd-kit/sortable"
|
||||||
|
import { CSS } from "@dnd-kit/utilities"
|
||||||
|
import {
|
||||||
|
GripVerticalIcon,
|
||||||
MoreHorizontalIcon,
|
MoreHorizontalIcon,
|
||||||
PlusIcon,
|
PlusIcon,
|
||||||
RefreshCwIcon,
|
RefreshCwIcon,
|
||||||
@@ -11,6 +29,7 @@ import {
|
|||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
|
import { useConfirm, type ConfirmOptions } from "@/components/confirm-provider"
|
||||||
import {
|
import {
|
||||||
DashboardPage,
|
DashboardPage,
|
||||||
DashboardTableShell,
|
DashboardTableShell,
|
||||||
@@ -38,15 +57,19 @@ import {
|
|||||||
} from "@/components/ui/table"
|
} from "@/components/ui/table"
|
||||||
import {
|
import {
|
||||||
buildDashboardCrudQuery,
|
buildDashboardCrudQuery,
|
||||||
|
isDashboardCrudActionDisabled,
|
||||||
|
isDashboardCrudActionVisible,
|
||||||
normalizeDashboardCrudPageResult,
|
normalizeDashboardCrudPageResult,
|
||||||
|
type DashboardCrudActionRule,
|
||||||
type DashboardCrudFormField,
|
type DashboardCrudFormField,
|
||||||
type DashboardCrudPageResult,
|
type DashboardCrudPageResult,
|
||||||
type DashboardCrudQueryFilter,
|
type DashboardCrudQueryFilter,
|
||||||
type DashboardCrudQueryValue,
|
type DashboardCrudQueryValue,
|
||||||
} from "./dashboard-crud-utils"
|
} from "./dashboard-crud-utils"
|
||||||
import { DashboardCrudFormDialog } from "./dashboard-crud-form-dialog"
|
import { DashboardCrudFormDialog } from "./dashboard-crud-form-dialog"
|
||||||
|
import { useDashboardCrudFilters } from "./use-dashboard-crud-filters"
|
||||||
|
|
||||||
type DashboardCrudFilter<TValue extends string | number = string> =
|
export type DashboardCrudFilter<TValue extends string | number = string> =
|
||||||
DashboardCrudQueryFilter & {
|
DashboardCrudQueryFilter & {
|
||||||
label: string
|
label: string
|
||||||
placeholder?: string
|
placeholder?: string
|
||||||
@@ -56,14 +79,14 @@ type DashboardCrudFilter<TValue extends string | number = string> =
|
|||||||
options?: ReadonlyArray<{ value: string; label: string }>
|
options?: ReadonlyArray<{ value: string; label: string }>
|
||||||
}
|
}
|
||||||
|
|
||||||
type DashboardCrudColumn<TItem> = {
|
export type DashboardCrudColumn<TItem> = {
|
||||||
key: string
|
key: string
|
||||||
label: ReactNode
|
label: ReactNode
|
||||||
className?: string
|
className?: string
|
||||||
render: (item: TItem, context: DashboardCrudRowActionContext<TItem>) => ReactNode
|
render: (item: TItem, context: DashboardCrudRowActionContext<TItem>) => ReactNode
|
||||||
}
|
}
|
||||||
|
|
||||||
type DashboardCrudDialogProps<TItem, TPayload> = {
|
export type DashboardCrudDialogProps<TItem, TPayload> = {
|
||||||
open: boolean
|
open: boolean
|
||||||
saving: boolean
|
saving: boolean
|
||||||
item: TItem | null
|
item: TItem | null
|
||||||
@@ -72,15 +95,25 @@ type DashboardCrudDialogProps<TItem, TPayload> = {
|
|||||||
onSubmit: (payload: TPayload) => Promise<void>
|
onSubmit: (payload: TPayload) => Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
type DashboardCrudRowActionContext<TItem> = {
|
export type DashboardCrudRowActionContext<TItem> = {
|
||||||
item: TItem
|
item: TItem
|
||||||
|
itemId: number
|
||||||
actionLoading: boolean
|
actionLoading: boolean
|
||||||
actionLoadingId: number | null
|
actionLoadingId: number | null
|
||||||
reload: () => Promise<void>
|
reload: () => Promise<void>
|
||||||
setActionLoadingId: (id: number | null) => void
|
setActionLoadingId: (id: number | null) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
type DashboardCrudPageProps<TItem, TPayload> = {
|
export type DashboardCrudRowAction<TItem> = DashboardCrudActionRule<TItem> & {
|
||||||
|
key: string
|
||||||
|
label: ReactNode | ((item: TItem) => ReactNode)
|
||||||
|
icon?: ReactNode | ((item: TItem) => ReactNode)
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
confirm?: ConfirmOptions | ((item: TItem) => ConfirmOptions)
|
||||||
|
run: (context: DashboardCrudRowActionContext<TItem>) => Promise<void> | void
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DashboardCrudPageProps<TItem, TPayload> = {
|
||||||
filters: DashboardCrudFilter[]
|
filters: DashboardCrudFilter[]
|
||||||
columns: DashboardCrudColumn<TItem>[]
|
columns: DashboardCrudColumn<TItem>[]
|
||||||
fetchList: (
|
fetchList: (
|
||||||
@@ -113,7 +146,17 @@ type DashboardCrudPageProps<TItem, TPayload> = {
|
|||||||
updateItem: (item: TItem, payload: TPayload) => Promise<unknown>
|
updateItem: (item: TItem, payload: TPayload) => Promise<unknown>
|
||||||
deleteItem?: (item: TItem) => Promise<unknown>
|
deleteItem?: (item: TItem) => Promise<unknown>
|
||||||
canDelete?: (item: TItem) => boolean
|
canDelete?: (item: TItem) => boolean
|
||||||
|
deleteConfirm?: ConfirmOptions | ((item: TItem) => ConfirmOptions)
|
||||||
|
rowActions?: DashboardCrudRowAction<TItem>[]
|
||||||
renderRowActions?: (context: DashboardCrudRowActionContext<TItem>) => ReactNode
|
renderRowActions?: (context: DashboardCrudRowActionContext<TItem>) => ReactNode
|
||||||
|
sort?: {
|
||||||
|
enabled?: boolean
|
||||||
|
disabled?: boolean
|
||||||
|
onReorder: (items: TItem[]) => Promise<unknown>
|
||||||
|
successMessage?: string
|
||||||
|
errorMessage: string
|
||||||
|
handleLabel: string
|
||||||
|
}
|
||||||
pageSize?: number
|
pageSize?: number
|
||||||
labels: {
|
labels: {
|
||||||
refresh: string
|
refresh: string
|
||||||
@@ -146,19 +189,26 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
updateItem,
|
updateItem,
|
||||||
deleteItem,
|
deleteItem,
|
||||||
canDelete,
|
canDelete,
|
||||||
|
deleteConfirm,
|
||||||
|
rowActions = [],
|
||||||
renderRowActions,
|
renderRowActions,
|
||||||
|
sort,
|
||||||
pageSize = 20,
|
pageSize = 20,
|
||||||
labels,
|
labels,
|
||||||
}: DashboardCrudPageProps<TItem, TPayload>) {
|
}: DashboardCrudPageProps<TItem, TPayload>) {
|
||||||
const initialFilters = useMemo(
|
const confirm = useConfirm()
|
||||||
() =>
|
const sensors = useSensors(
|
||||||
Object.fromEntries(
|
useSensor(PointerSensor, {
|
||||||
filters.map((filter) => [filter.name, filter.defaultValue])
|
activationConstraint: {
|
||||||
) as Record<string, string | number | undefined>,
|
distance: 6,
|
||||||
[filters]
|
},
|
||||||
|
}),
|
||||||
|
useSensor(KeyboardSensor, {
|
||||||
|
coordinateGetter: sortableKeyboardCoordinates,
|
||||||
|
})
|
||||||
)
|
)
|
||||||
const [draftFilters, setDraftFilters] = useState(initialFilters)
|
const { draftFilters, appliedFilters, setDraftFilter, applyFilters } =
|
||||||
const [appliedFilters, setAppliedFilters] = useState(initialFilters)
|
useDashboardCrudFilters(filters)
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [limit, setLimit] = useState(pageSize)
|
const [limit, setLimit] = useState(pageSize)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
@@ -171,11 +221,6 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
page: { page: 1, limit: pageSize, total: 0 },
|
page: { page: 1, limit: pageSize, total: 0 },
|
||||||
})
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setDraftFilters(initialFilters)
|
|
||||||
setAppliedFilters(initialFilters)
|
|
||||||
}, [initialFilters])
|
|
||||||
|
|
||||||
const loadData = useCallback(async () => {
|
const loadData = useCallback(async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
try {
|
try {
|
||||||
@@ -199,15 +244,15 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
void loadData()
|
void loadData()
|
||||||
}, [loadData])
|
}, [loadData])
|
||||||
|
|
||||||
function applyFilters() {
|
function handleApplyFilters() {
|
||||||
setAppliedFilters(draftFilters)
|
applyFilters()
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
|
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
|
||||||
if (event.key !== "Enter") return
|
if (event.key !== "Enter") return
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
applyFilters()
|
handleApplyFilters()
|
||||||
}
|
}
|
||||||
|
|
||||||
function openCreateDialog() {
|
function openCreateDialog() {
|
||||||
@@ -249,6 +294,12 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
|
|
||||||
async function handleDelete(item: TItem) {
|
async function handleDelete(item: TItem) {
|
||||||
if (!deleteItem) return
|
if (!deleteItem) return
|
||||||
|
if (deleteConfirm) {
|
||||||
|
const confirmed = await confirm(
|
||||||
|
typeof deleteConfirm === "function" ? deleteConfirm(item) : deleteConfirm
|
||||||
|
)
|
||||||
|
if (!confirmed) return
|
||||||
|
}
|
||||||
const id = getItemId(item)
|
const id = getItemId(item)
|
||||||
setActionLoadingId(id)
|
setActionLoadingId(id)
|
||||||
try {
|
try {
|
||||||
@@ -262,7 +313,185 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const colSpan = columns.length + 1
|
async function runRowAction(
|
||||||
|
action: DashboardCrudRowAction<TItem>,
|
||||||
|
item: TItem,
|
||||||
|
actionLoading: boolean
|
||||||
|
) {
|
||||||
|
if (actionLoading || isDashboardCrudActionDisabled(action, item)) return
|
||||||
|
|
||||||
|
if (action.confirm) {
|
||||||
|
const confirmed = await confirm(
|
||||||
|
typeof action.confirm === "function" ? action.confirm(item) : action.confirm
|
||||||
|
)
|
||||||
|
if (!confirmed) return
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = getItemId(item)
|
||||||
|
setActionLoadingId(id)
|
||||||
|
try {
|
||||||
|
await action.run({
|
||||||
|
item,
|
||||||
|
itemId: id,
|
||||||
|
actionLoading: true,
|
||||||
|
actionLoadingId: id,
|
||||||
|
reload: loadData,
|
||||||
|
setActionLoadingId,
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
setActionLoadingId(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSortEnd(event: DragEndEvent) {
|
||||||
|
if (!sort?.enabled || sort.disabled) return
|
||||||
|
|
||||||
|
const { active, over } = event
|
||||||
|
if (!over || active.id === over.id) return
|
||||||
|
|
||||||
|
const oldIndex = result.results.findIndex(
|
||||||
|
(item) => String(getItemId(item)) === String(active.id)
|
||||||
|
)
|
||||||
|
const newIndex = result.results.findIndex(
|
||||||
|
(item) => String(getItemId(item)) === String(over.id)
|
||||||
|
)
|
||||||
|
if (oldIndex < 0 || newIndex < 0) return
|
||||||
|
|
||||||
|
const previousResults = result.results
|
||||||
|
const nextResults = arrayMove(result.results, oldIndex, newIndex)
|
||||||
|
setResult((current) => ({ ...current, results: nextResults }))
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sort.onReorder(nextResults)
|
||||||
|
if (sort.successMessage) {
|
||||||
|
toast.success(sort.successMessage)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setResult((current) => ({ ...current, results: previousResults }))
|
||||||
|
toast.error(error instanceof Error ? error.message : sort.errorMessage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortable = Boolean(sort?.enabled)
|
||||||
|
const colSpan = columns.length + 1 + (sortable ? 1 : 0)
|
||||||
|
|
||||||
|
function renderTableRow(
|
||||||
|
item: TItem,
|
||||||
|
options: { sortable?: boolean; sortDisabled?: boolean } = {}
|
||||||
|
) {
|
||||||
|
const id = getItemId(item)
|
||||||
|
const actionLoading = actionLoadingId === id
|
||||||
|
const rowCells = (
|
||||||
|
<>
|
||||||
|
{columns.map((column) => (
|
||||||
|
<TableCell key={column.key} className={column.className}>
|
||||||
|
{column.render(item, {
|
||||||
|
item,
|
||||||
|
itemId: id,
|
||||||
|
actionLoading,
|
||||||
|
actionLoadingId,
|
||||||
|
reload: loadData,
|
||||||
|
setActionLoadingId,
|
||||||
|
})}
|
||||||
|
</TableCell>
|
||||||
|
))}
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<ButtonGroup className="ml-auto">
|
||||||
|
<Button variant="outline" size="sm" onClick={() => openEditDialog(item)}>
|
||||||
|
{labels.edit}
|
||||||
|
</Button>
|
||||||
|
{renderRowActions || rowActions.length > 0 || deleteItem ? (
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger
|
||||||
|
render={<Button variant="outline" size="icon-sm" />}
|
||||||
|
aria-label={labels.moreActions(item)}
|
||||||
|
>
|
||||||
|
<MoreHorizontalIcon />
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-40 min-w-40">
|
||||||
|
{rowActions
|
||||||
|
.filter((action) => isDashboardCrudActionVisible(action, item))
|
||||||
|
.map((action) => {
|
||||||
|
const icon =
|
||||||
|
typeof action.icon === "function"
|
||||||
|
? action.icon(item)
|
||||||
|
: action.icon
|
||||||
|
const label =
|
||||||
|
typeof action.label === "function"
|
||||||
|
? action.label(item)
|
||||||
|
: action.label
|
||||||
|
return (
|
||||||
|
<DropdownMenuItem
|
||||||
|
key={action.key}
|
||||||
|
disabled={
|
||||||
|
actionLoading ||
|
||||||
|
isDashboardCrudActionDisabled(action, item)
|
||||||
|
}
|
||||||
|
className={
|
||||||
|
action.variant === "destructive"
|
||||||
|
? "text-destructive focus:text-destructive"
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onClick={() => void runRowAction(action, item, actionLoading)}
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
{actionLoading ? labels.processing : label}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{renderRowActions?.({
|
||||||
|
item,
|
||||||
|
itemId: id,
|
||||||
|
actionLoading,
|
||||||
|
actionLoadingId,
|
||||||
|
reload: loadData,
|
||||||
|
setActionLoadingId,
|
||||||
|
})}
|
||||||
|
{deleteItem ? (
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => void handleDelete(item)}
|
||||||
|
disabled={canDelete ? !canDelete(item) : false}
|
||||||
|
className="text-destructive focus:text-destructive"
|
||||||
|
>
|
||||||
|
<Trash2Icon />
|
||||||
|
{actionLoading ? labels.processing : labels.delete}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
) : null}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
) : null}
|
||||||
|
</ButtonGroup>
|
||||||
|
</TableCell>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
|
||||||
|
if (options.sortable) {
|
||||||
|
return (
|
||||||
|
<DashboardCrudSortableRow
|
||||||
|
key={id}
|
||||||
|
id={String(id)}
|
||||||
|
disabled={loading || options.sortDisabled}
|
||||||
|
handleLabel={sort?.handleLabel ?? labels.actions}
|
||||||
|
>
|
||||||
|
{rowCells}
|
||||||
|
</DashboardCrudSortableRow>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return <TableRow key={id}>{rowCells}</TableRow>
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderStateRow() {
|
||||||
|
if (!loading && result.results.length > 0) return null
|
||||||
|
return (
|
||||||
|
<DashboardTableStateRow
|
||||||
|
colSpan={colSpan}
|
||||||
|
loading={loading}
|
||||||
|
loadingText={labels.loading}
|
||||||
|
emptyText={labels.empty}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -288,12 +517,7 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
<div key={filter.name} className={filter.className ?? "w-full sm:w-40"}>
|
<div key={filter.name} className={filter.className ?? "w-full sm:w-40"}>
|
||||||
<OptionCombobox
|
<OptionCombobox
|
||||||
value={String(value ?? "")}
|
value={String(value ?? "")}
|
||||||
onChange={(nextValue) =>
|
onChange={(nextValue) => setDraftFilter(filter.name, nextValue)}
|
||||||
setDraftFilters((current) => ({
|
|
||||||
...current,
|
|
||||||
[filter.name]: nextValue,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
placeholder={filter.placeholder ?? filter.label}
|
placeholder={filter.placeholder ?? filter.label}
|
||||||
options={[...(filter.options ?? [])]}
|
options={[...(filter.options ?? [])]}
|
||||||
/>
|
/>
|
||||||
@@ -306,10 +530,7 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
<Input
|
<Input
|
||||||
value={String(value ?? "")}
|
value={String(value ?? "")}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
setDraftFilters((current) => ({
|
setDraftFilter(filter.name, event.target.value)
|
||||||
...current,
|
|
||||||
[filter.name]: event.target.value,
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
onKeyDown={handleFilterKeyDown}
|
onKeyDown={handleFilterKeyDown}
|
||||||
placeholder={filter.placeholder ?? filter.label}
|
placeholder={filter.placeholder ?? filter.label}
|
||||||
@@ -317,7 +538,7 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
<Button variant="outline" onClick={applyFilters} disabled={loading}>
|
<Button variant="outline" onClick={handleApplyFilters} disabled={loading}>
|
||||||
<SearchIcon />
|
<SearchIcon />
|
||||||
{labels.query}
|
{labels.query}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -344,6 +565,7 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
<Table>
|
<Table>
|
||||||
<TableHeader className="bg-muted/40">
|
<TableHeader className="bg-muted/40">
|
||||||
<TableRow>
|
<TableRow>
|
||||||
|
{sortable ? <TableHead className="w-10" /> : null}
|
||||||
{columns.map((column) => (
|
{columns.map((column) => (
|
||||||
<TableHead key={column.key} className={column.className}>
|
<TableHead key={column.key} className={column.className}>
|
||||||
{column.label}
|
{column.label}
|
||||||
@@ -354,75 +576,33 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
</TableHead>
|
</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
{sortable ? (
|
||||||
{result.results.map((item) => {
|
<DndContext
|
||||||
const id = getItemId(item)
|
sensors={sensors}
|
||||||
const actionLoading = actionLoadingId === id
|
collisionDetection={closestCenter}
|
||||||
return (
|
onDragEnd={(event) => void handleSortEnd(event)}
|
||||||
<TableRow key={id}>
|
>
|
||||||
{columns.map((column) => (
|
<SortableContext
|
||||||
<TableCell key={column.key} className={column.className}>
|
items={result.results.map((item) => String(getItemId(item)))}
|
||||||
{column.render(item, {
|
strategy={verticalListSortingStrategy}
|
||||||
item,
|
>
|
||||||
actionLoading,
|
<TableBody>
|
||||||
actionLoadingId,
|
{result.results.map((item) =>
|
||||||
reload: loadData,
|
renderTableRow(item, {
|
||||||
setActionLoadingId,
|
sortable: true,
|
||||||
})}
|
sortDisabled: sort?.disabled,
|
||||||
</TableCell>
|
})
|
||||||
))}
|
)}
|
||||||
<TableCell className="text-right">
|
{renderStateRow()}
|
||||||
<ButtonGroup className="ml-auto">
|
</TableBody>
|
||||||
<Button
|
</SortableContext>
|
||||||
variant="outline"
|
</DndContext>
|
||||||
size="sm"
|
) : (
|
||||||
onClick={() => openEditDialog(item)}
|
<TableBody>
|
||||||
>
|
{result.results.map((item) => renderTableRow(item))}
|
||||||
{labels.edit}
|
{renderStateRow()}
|
||||||
</Button>
|
</TableBody>
|
||||||
{renderRowActions || deleteItem ? (
|
)}
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger
|
|
||||||
render={<Button variant="outline" size="icon-sm" />}
|
|
||||||
aria-label={labels.moreActions(item)}
|
|
||||||
>
|
|
||||||
<MoreHorizontalIcon />
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align="end" className="w-40 min-w-40">
|
|
||||||
{renderRowActions?.({
|
|
||||||
item,
|
|
||||||
actionLoading,
|
|
||||||
actionLoadingId,
|
|
||||||
reload: loadData,
|
|
||||||
setActionLoadingId,
|
|
||||||
})}
|
|
||||||
{deleteItem ? (
|
|
||||||
<DropdownMenuItem
|
|
||||||
onClick={() => void handleDelete(item)}
|
|
||||||
disabled={canDelete ? !canDelete(item) : false}
|
|
||||||
className="text-destructive focus:text-destructive"
|
|
||||||
>
|
|
||||||
<Trash2Icon />
|
|
||||||
{actionLoading ? labels.processing : labels.delete}
|
|
||||||
</DropdownMenuItem>
|
|
||||||
) : null}
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
) : null}
|
|
||||||
</ButtonGroup>
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
{loading || result.results.length === 0 ? (
|
|
||||||
<DashboardTableStateRow
|
|
||||||
colSpan={colSpan}
|
|
||||||
loading={loading}
|
|
||||||
loadingText={labels.loading}
|
|
||||||
emptyText={labels.empty}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
</TableBody>
|
|
||||||
</Table>
|
</Table>
|
||||||
</DashboardTableShell>
|
</DashboardTableShell>
|
||||||
</DashboardPage>
|
</DashboardPage>
|
||||||
@@ -452,3 +632,50 @@ export function DashboardCrudPage<TItem, TPayload>({
|
|||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function DashboardCrudSortableRow({
|
||||||
|
id,
|
||||||
|
disabled,
|
||||||
|
handleLabel,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
id: string
|
||||||
|
disabled?: boolean
|
||||||
|
handleLabel: string
|
||||||
|
children: ReactNode
|
||||||
|
}) {
|
||||||
|
const {
|
||||||
|
attributes,
|
||||||
|
listeners,
|
||||||
|
setNodeRef,
|
||||||
|
transform,
|
||||||
|
transition,
|
||||||
|
isDragging,
|
||||||
|
} = useSortable({ id, disabled })
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TableRow
|
||||||
|
ref={setNodeRef}
|
||||||
|
style={{
|
||||||
|
transform: CSS.Transform.toString(transform),
|
||||||
|
transition,
|
||||||
|
}}
|
||||||
|
className={isDragging ? "relative z-10 bg-muted/60" : undefined}
|
||||||
|
>
|
||||||
|
<TableCell className="w-10">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-sm"
|
||||||
|
disabled={disabled}
|
||||||
|
aria-label={handleLabel}
|
||||||
|
{...attributes}
|
||||||
|
{...listeners}
|
||||||
|
>
|
||||||
|
<GripVerticalIcon className="text-muted-foreground" />
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
{children}
|
||||||
|
</TableRow>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import type { ComponentProps, ReactNode } from "react"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { Switch } from "@/components/ui/switch"
|
||||||
|
import type {
|
||||||
|
DashboardCrudColumn,
|
||||||
|
DashboardCrudRowAction,
|
||||||
|
} from "./dashboard-crud-page"
|
||||||
|
|
||||||
|
type BadgeVariant = ComponentProps<typeof Badge>["variant"]
|
||||||
|
|
||||||
|
export type DashboardCrudStatusColumnOptions<TItem, TStatus> = {
|
||||||
|
key?: string
|
||||||
|
label: ReactNode
|
||||||
|
className?: string
|
||||||
|
getStatus: (item: TItem) => TStatus
|
||||||
|
getLabel: (status: TStatus, item: TItem) => ReactNode
|
||||||
|
getBadgeVariant?: (status: TStatus, item: TItem) => BadgeVariant
|
||||||
|
isEnabled?: (status: TStatus, item: TItem) => boolean
|
||||||
|
toggle?: {
|
||||||
|
disabled?: (item: TItem) => boolean
|
||||||
|
getNextStatus: (item: TItem) => TStatus
|
||||||
|
updateStatus: (item: TItem, nextStatus: TStatus) => Promise<unknown>
|
||||||
|
successMessage: (item: TItem, nextStatus: TStatus) => string
|
||||||
|
errorMessage: string
|
||||||
|
ariaLabel: (item: TItem) => string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DashboardCrudStatusToggleActionOptions<TItem, TStatus> = {
|
||||||
|
key?: string
|
||||||
|
icon?: ReactNode | ((item: TItem) => ReactNode)
|
||||||
|
label: (item: TItem, nextStatus: TStatus) => ReactNode
|
||||||
|
visible?: (item: TItem) => boolean
|
||||||
|
disabled?: (item: TItem) => boolean
|
||||||
|
getNextStatus: (item: TItem) => TStatus
|
||||||
|
updateStatus: (item: TItem, nextStatus: TStatus) => Promise<unknown>
|
||||||
|
successMessage: (item: TItem, nextStatus: TStatus) => string
|
||||||
|
errorMessage: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDashboardStatusColumn<TItem, TStatus>({
|
||||||
|
key = "status",
|
||||||
|
label,
|
||||||
|
className,
|
||||||
|
getStatus,
|
||||||
|
getLabel,
|
||||||
|
getBadgeVariant,
|
||||||
|
isEnabled,
|
||||||
|
toggle,
|
||||||
|
}: DashboardCrudStatusColumnOptions<TItem, TStatus>): DashboardCrudColumn<TItem> {
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
label,
|
||||||
|
className,
|
||||||
|
render: (item, { itemId, actionLoading, reload, setActionLoadingId }) => {
|
||||||
|
const status = getStatus(item)
|
||||||
|
const badge = (
|
||||||
|
<Badge variant={getBadgeVariant?.(status, item) ?? "outline"}>
|
||||||
|
{getLabel(status, item)}
|
||||||
|
</Badge>
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!toggle) {
|
||||||
|
return badge
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Switch
|
||||||
|
checked={isEnabled ? isEnabled(status, item) : Boolean(status)}
|
||||||
|
disabled={actionLoading || toggle.disabled?.(item)}
|
||||||
|
onCheckedChange={() => {
|
||||||
|
void (async () => {
|
||||||
|
setActionLoadingId(itemId)
|
||||||
|
try {
|
||||||
|
const nextStatus = toggle.getNextStatus(item)
|
||||||
|
await toggle.updateStatus(item, nextStatus)
|
||||||
|
toast.success(toggle.successMessage(item, nextStatus))
|
||||||
|
await reload()
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(
|
||||||
|
error instanceof Error ? error.message : toggle.errorMessage
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
setActionLoadingId(null)
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
}}
|
||||||
|
aria-label={toggle.ariaLabel(item)}
|
||||||
|
/>
|
||||||
|
{badge}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDashboardStatusToggleAction<TItem, TStatus>({
|
||||||
|
key = "toggle-status",
|
||||||
|
icon,
|
||||||
|
label,
|
||||||
|
visible,
|
||||||
|
disabled,
|
||||||
|
getNextStatus,
|
||||||
|
updateStatus,
|
||||||
|
successMessage,
|
||||||
|
errorMessage,
|
||||||
|
}: DashboardCrudStatusToggleActionOptions<TItem, TStatus>): DashboardCrudRowAction<TItem> {
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
icon,
|
||||||
|
visible,
|
||||||
|
disabled,
|
||||||
|
label: (item) => label(item, getNextStatus(item)),
|
||||||
|
run: async ({ item, reload }) => {
|
||||||
|
try {
|
||||||
|
const nextStatus = getNextStatus(item)
|
||||||
|
await updateStatus(item, nextStatus)
|
||||||
|
toast.success(successMessage(item, nextStatus))
|
||||||
|
await reload()
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : errorMessage)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -75,6 +75,27 @@ describe("buildDashboardCrudQuery", () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe("buildDashboardCrudInitialFilters", () => {
|
||||||
|
it("creates stable filter state from defaults", async () => {
|
||||||
|
const { buildDashboardCrudInitialFilters } = await loadModule()
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
plain(
|
||||||
|
buildDashboardCrudInitialFilters([
|
||||||
|
{ name: "keyword", defaultValue: "" },
|
||||||
|
{ name: "status", defaultValue: "all" },
|
||||||
|
{ name: "companyId", defaultValue: 0 },
|
||||||
|
])
|
||||||
|
),
|
||||||
|
{
|
||||||
|
keyword: "",
|
||||||
|
status: "all",
|
||||||
|
companyId: 0,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe("normalizeDashboardCrudPageResult", () => {
|
describe("normalizeDashboardCrudPageResult", () => {
|
||||||
it("returns a stable empty page when the API result is missing", async () => {
|
it("returns a stable empty page when the API result is missing", async () => {
|
||||||
const { normalizeDashboardCrudPageResult } = await loadModule()
|
const { normalizeDashboardCrudPageResult } = await loadModule()
|
||||||
@@ -143,3 +164,32 @@ describe("normalizeDashboardCrudSubmitValues", () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe("dashboard CRUD action rules", () => {
|
||||||
|
it("defaults actions to visible and enabled", async () => {
|
||||||
|
const {
|
||||||
|
isDashboardCrudActionVisible,
|
||||||
|
isDashboardCrudActionDisabled,
|
||||||
|
} = await loadModule()
|
||||||
|
const action = {}
|
||||||
|
|
||||||
|
assert.equal(isDashboardCrudActionVisible(action, { status: 0 }), true)
|
||||||
|
assert.equal(isDashboardCrudActionDisabled(action, { status: 0 }), false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("honors visible and disabled predicates", async () => {
|
||||||
|
const {
|
||||||
|
isDashboardCrudActionVisible,
|
||||||
|
isDashboardCrudActionDisabled,
|
||||||
|
} = await loadModule()
|
||||||
|
const action = {
|
||||||
|
visible: (item) => item.status !== 2,
|
||||||
|
disabled: (item) => item.status === 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(isDashboardCrudActionVisible(action, { status: 2 }), false)
|
||||||
|
assert.equal(isDashboardCrudActionVisible(action, { status: 0 }), true)
|
||||||
|
assert.equal(isDashboardCrudActionDisabled(action, { status: 1 }), true)
|
||||||
|
assert.equal(isDashboardCrudActionDisabled(action, { status: 0 }), false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -7,6 +7,13 @@ export type DashboardCrudQueryFilter = {
|
|||||||
valueType?: "string" | "number"
|
valueType?: "string" | "number"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type DashboardCrudFilterStateConfig<
|
||||||
|
TValue extends string | number = string | number,
|
||||||
|
> = {
|
||||||
|
name: string
|
||||||
|
defaultValue: TValue
|
||||||
|
}
|
||||||
|
|
||||||
export type DashboardCrudPageResult<T> = {
|
export type DashboardCrudPageResult<T> = {
|
||||||
results: T[]
|
results: T[]
|
||||||
page: {
|
page: {
|
||||||
@@ -39,11 +46,17 @@ export type DashboardCrudFormField<TItem = unknown> = {
|
|||||||
pattern?: RegExp
|
pattern?: RegExp
|
||||||
patternMessage?: string
|
patternMessage?: string
|
||||||
options?: ReadonlyArray<DashboardCrudFormOption>
|
options?: ReadonlyArray<DashboardCrudFormOption>
|
||||||
|
loadOptions?: () => Promise<ReadonlyArray<DashboardCrudFormOption>>
|
||||||
colSpan?: 1 | 2
|
colSpan?: 1 | 2
|
||||||
rows?: number
|
rows?: number
|
||||||
valueFromItem?: (item: TItem) => DashboardCrudFormValue
|
valueFromItem?: (item: TItem) => DashboardCrudFormValue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type DashboardCrudActionRule<TItem> = {
|
||||||
|
visible?: (item: TItem) => boolean
|
||||||
|
disabled?: (item: TItem) => boolean
|
||||||
|
}
|
||||||
|
|
||||||
export function buildDashboardCrudQuery({
|
export function buildDashboardCrudQuery({
|
||||||
values,
|
values,
|
||||||
filters,
|
filters,
|
||||||
@@ -86,6 +99,14 @@ export function buildDashboardCrudQuery({
|
|||||||
return query
|
return query
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function buildDashboardCrudInitialFilters(
|
||||||
|
filters: ReadonlyArray<DashboardCrudFilterStateConfig>
|
||||||
|
): Record<string, string | number | undefined> {
|
||||||
|
return Object.fromEntries(
|
||||||
|
filters.map((filter) => [filter.name, filter.defaultValue])
|
||||||
|
) as Record<string, string | number | undefined>
|
||||||
|
}
|
||||||
|
|
||||||
export function normalizeDashboardCrudPageResult<T>(
|
export function normalizeDashboardCrudPageResult<T>(
|
||||||
result: Partial<DashboardCrudPageResult<T>> | null | undefined,
|
result: Partial<DashboardCrudPageResult<T>> | null | undefined,
|
||||||
page: number,
|
page: number,
|
||||||
@@ -139,3 +160,17 @@ export function normalizeDashboardCrudSubmitValues<TItem>(
|
|||||||
|
|
||||||
return output
|
return output
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isDashboardCrudActionVisible<TItem>(
|
||||||
|
action: DashboardCrudActionRule<TItem>,
|
||||||
|
item: TItem
|
||||||
|
) {
|
||||||
|
return action.visible ? action.visible(item) : true
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDashboardCrudActionDisabled<TItem>(
|
||||||
|
action: DashboardCrudActionRule<TItem>,
|
||||||
|
item: TItem
|
||||||
|
) {
|
||||||
|
return action.disabled ? action.disabled(item) : false
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,18 @@
|
|||||||
export { DashboardCrudPage } from "./dashboard-crud-page"
|
export { DashboardCrudPage } from "./dashboard-crud-page"
|
||||||
export { DashboardCrudFormDialog } from "./dashboard-crud-form-dialog"
|
export { DashboardCrudFormDialog } from "./dashboard-crud-form-dialog"
|
||||||
|
export {
|
||||||
|
createDashboardStatusColumn,
|
||||||
|
createDashboardStatusToggleAction,
|
||||||
|
} from "./dashboard-crud-presets"
|
||||||
|
export { useDashboardCrudFilters } from "./use-dashboard-crud-filters"
|
||||||
|
export type {
|
||||||
|
DashboardCrudColumn,
|
||||||
|
DashboardCrudDialogProps,
|
||||||
|
DashboardCrudFilter,
|
||||||
|
DashboardCrudPageProps,
|
||||||
|
DashboardCrudRowAction,
|
||||||
|
DashboardCrudRowActionContext,
|
||||||
|
} from "./dashboard-crud-page"
|
||||||
export type {
|
export type {
|
||||||
DashboardCrudFormField,
|
DashboardCrudFormField,
|
||||||
DashboardCrudPageResult,
|
DashboardCrudPageResult,
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useEffect, useMemo, useState } from "react"
|
||||||
|
|
||||||
|
import {
|
||||||
|
buildDashboardCrudInitialFilters,
|
||||||
|
type DashboardCrudFilterStateConfig,
|
||||||
|
} from "./dashboard-crud-utils"
|
||||||
|
|
||||||
|
export function useDashboardCrudFilters(
|
||||||
|
filters: ReadonlyArray<DashboardCrudFilterStateConfig>
|
||||||
|
) {
|
||||||
|
const initialFilters = useMemo(
|
||||||
|
() => buildDashboardCrudInitialFilters(filters),
|
||||||
|
[filters]
|
||||||
|
)
|
||||||
|
const [draftFilters, setDraftFilters] = useState(initialFilters)
|
||||||
|
const [appliedFilters, setAppliedFilters] = useState(initialFilters)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setDraftFilters(initialFilters)
|
||||||
|
setAppliedFilters(initialFilters)
|
||||||
|
}, [initialFilters])
|
||||||
|
|
||||||
|
function setDraftFilter(name: string, value: string | number | undefined) {
|
||||||
|
setDraftFilters((current) => ({
|
||||||
|
...current,
|
||||||
|
[name]: value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyFilters() {
|
||||||
|
setAppliedFilters(draftFilters)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
draftFilters,
|
||||||
|
appliedFilters,
|
||||||
|
setDraftFilter,
|
||||||
|
setDraftFilters,
|
||||||
|
applyFilters,
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user