chore: import clean Agent Desk snapshot (6/7)
This commit is contained in:
321
web/components/dashboard/crud/dashboard-crud-field-control.tsx
Normal file
321
web/components/dashboard/crud/dashboard-crud-field-control.tsx
Normal file
@@ -0,0 +1,321 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { CheckIcon, ChevronsUpDownIcon } from "lucide-react"
|
||||
import type {
|
||||
FieldError as HookFormFieldError,
|
||||
UseFormReturn,
|
||||
} from "react-hook-form"
|
||||
import { Controller, type Control, type UseFormRegister } from "react-hook-form"
|
||||
|
||||
import { OptionCombobox } from "@/components/option-combobox"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command"
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldError,
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { useI18n } from "@/i18n/provider"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type {
|
||||
DashboardCrudFormField,
|
||||
DashboardCrudFormInputValue,
|
||||
DashboardCrudFormOption,
|
||||
} from "./dashboard-crud-utils"
|
||||
|
||||
export function DashboardCrudFieldControl<TItem>({
|
||||
field,
|
||||
control,
|
||||
form,
|
||||
register,
|
||||
error,
|
||||
}: {
|
||||
field: DashboardCrudFormField<TItem>
|
||||
control: Control<Record<string, DashboardCrudFormInputValue>>
|
||||
form: UseFormReturn<
|
||||
Record<string, DashboardCrudFormInputValue>,
|
||||
undefined,
|
||||
Record<string, DashboardCrudFormInputValue>
|
||||
>
|
||||
register: UseFormRegister<Record<string, DashboardCrudFormInputValue>>
|
||||
error?: HookFormFieldError
|
||||
}) {
|
||||
const inputId = `dashboard-crud-field-${field.name}`
|
||||
|
||||
if (field.type === "section" || field.type === "group") {
|
||||
return (
|
||||
<div className="md:col-span-2">
|
||||
<div className="border-t pt-4">
|
||||
<div className="text-sm font-medium">{field.label}</div>
|
||||
{field.description ? (
|
||||
<div className="mt-1 text-sm text-muted-foreground">
|
||||
{field.description}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Field
|
||||
data-invalid={!!error}
|
||||
className={cn(
|
||||
(field.colSpan === 2 ||
|
||||
["textarea", "json", "code", "custom"].includes(field.type ?? "")) &&
|
||||
"md:col-span-2"
|
||||
)}
|
||||
>
|
||||
<FieldLabel
|
||||
htmlFor={
|
||||
["select", "multiSelect", "switch", "checkbox", "custom"].includes(
|
||||
field.type ?? ""
|
||||
)
|
||||
? undefined
|
||||
: inputId
|
||||
}
|
||||
>
|
||||
{field.label}
|
||||
</FieldLabel>
|
||||
<FieldContent>
|
||||
{field.type === "select" ? (
|
||||
<Controller
|
||||
control={control}
|
||||
name={field.name}
|
||||
render={({ field: controllerField }) => (
|
||||
<OptionCombobox
|
||||
value={String(controllerField.value ?? "")}
|
||||
options={[...(field.options ?? [])]}
|
||||
placeholder={field.placeholder ?? field.label}
|
||||
onChange={controllerField.onChange}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : field.type === "multiSelect" ? (
|
||||
<Controller
|
||||
control={control}
|
||||
name={field.name}
|
||||
render={({ field: controllerField }) => (
|
||||
<DashboardCrudMultiSelect
|
||||
value={
|
||||
Array.isArray(controllerField.value)
|
||||
? controllerField.value
|
||||
: []
|
||||
}
|
||||
options={[...(field.options ?? [])]}
|
||||
placeholder={field.placeholder ?? field.label}
|
||||
onChange={controllerField.onChange}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : field.type === "switch" ? (
|
||||
<Controller
|
||||
control={control}
|
||||
name={field.name}
|
||||
render={({ field: controllerField }) => (
|
||||
<Switch
|
||||
checked={Boolean(controllerField.value)}
|
||||
onCheckedChange={controllerField.onChange}
|
||||
aria-label={field.label}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : field.type === "checkbox" ? (
|
||||
<Controller
|
||||
control={control}
|
||||
name={field.name}
|
||||
render={({ field: controllerField }) => (
|
||||
<label className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
checked={Boolean(controllerField.value)}
|
||||
onCheckedChange={controllerField.onChange}
|
||||
aria-label={field.label}
|
||||
/>
|
||||
<span>{field.description ?? field.label}</span>
|
||||
</label>
|
||||
)}
|
||||
/>
|
||||
) : field.type === "custom" && field.render ? (
|
||||
<Controller
|
||||
control={control}
|
||||
name={field.name}
|
||||
render={({ field: controllerField }) => (
|
||||
<>
|
||||
{field.render?.({
|
||||
name: field.name,
|
||||
label: field.label,
|
||||
value: controllerField.value,
|
||||
values: form.watch(),
|
||||
setValue: (name, value) =>
|
||||
form.setValue(name, value, {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
}),
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
) : field.type === "textarea" ? (
|
||||
<Textarea
|
||||
id={inputId}
|
||||
rows={field.rows ?? 4}
|
||||
placeholder={field.placeholder}
|
||||
aria-invalid={!!error}
|
||||
{...register(field.name)}
|
||||
/>
|
||||
) : field.type === "json" || field.type === "code" ? (
|
||||
<Textarea
|
||||
id={inputId}
|
||||
rows={field.rows ?? 8}
|
||||
placeholder={field.placeholder}
|
||||
aria-invalid={!!error}
|
||||
spellCheck={false}
|
||||
className="font-mono text-xs leading-5"
|
||||
{...register(field.name)}
|
||||
/>
|
||||
) : field.normalizeInput ? (
|
||||
<Controller
|
||||
control={control}
|
||||
name={field.name}
|
||||
render={({ field: controllerField }) => (
|
||||
<Input
|
||||
id={inputId}
|
||||
type="text"
|
||||
placeholder={field.placeholder}
|
||||
aria-invalid={!!error}
|
||||
value={String(controllerField.value ?? "")}
|
||||
onChange={(event) => controllerField.onChange(field.normalizeInput!(event.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
id={inputId}
|
||||
type={
|
||||
field.type === "number"
|
||||
? "number"
|
||||
: field.type === "password"
|
||||
? "password"
|
||||
: "text"
|
||||
}
|
||||
min={field.type === "number" ? field.min : undefined}
|
||||
max={field.type === "number" ? field.max : undefined}
|
||||
step={field.type === "number" ? field.step : undefined}
|
||||
placeholder={field.placeholder}
|
||||
aria-invalid={!!error}
|
||||
{...register(field.name)}
|
||||
/>
|
||||
)}
|
||||
{field.description && field.type !== "checkbox" ? (
|
||||
<div className="text-sm text-muted-foreground">{field.description}</div>
|
||||
) : null}
|
||||
<FieldError errors={error ? [error] : []} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
)
|
||||
}
|
||||
|
||||
function DashboardCrudMultiSelect({
|
||||
value,
|
||||
options,
|
||||
placeholder,
|
||||
onChange,
|
||||
}: {
|
||||
value: string[]
|
||||
options: DashboardCrudFormOption[]
|
||||
placeholder: string
|
||||
onChange: (value: string[]) => void
|
||||
}) {
|
||||
const t = useI18n()
|
||||
const [open, setOpen] = useState(false)
|
||||
const selectedOptions = options.filter((option) => value.includes(option.value))
|
||||
const selectedText =
|
||||
selectedOptions.length > 0
|
||||
? selectedOptions.map((option) => option.label).join(", ")
|
||||
: placeholder
|
||||
|
||||
function toggleValue(nextValue: string) {
|
||||
if (value.includes(nextValue)) {
|
||||
onChange(value.filter((item) => item !== nextValue))
|
||||
return
|
||||
}
|
||||
onChange([...value, nextValue])
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className="w-full justify-between font-normal"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="truncate">{selectedText}</span>
|
||||
<ChevronsUpDownIcon className="ml-2 size-4 shrink-0 opacity-50" />
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-(--radix-popover-trigger-width) p-0" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder={t("common.searchKeyword")} />
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("common.emptyOptions")}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{options.map((option) => {
|
||||
const checked = value.includes(option.value)
|
||||
return (
|
||||
<CommandItem
|
||||
key={option.value}
|
||||
value={`${option.label} ${option.value}`}
|
||||
onSelect={() => toggleValue(option.value)}
|
||||
>
|
||||
<CheckIcon
|
||||
className={cn(
|
||||
"mr-2 size-4 shrink-0",
|
||||
checked ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{option.label}</span>
|
||||
</CommandItem>
|
||||
)
|
||||
})}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
{selectedOptions.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1 border-t p-2">
|
||||
{selectedOptions.slice(0, 8).map((option) => (
|
||||
<Badge key={option.value} variant="secondary">
|
||||
{option.label}
|
||||
</Badge>
|
||||
))}
|
||||
{selectedOptions.length > 8 ? (
|
||||
<Badge variant="outline">+{selectedOptions.length - 8}</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
295
web/components/dashboard/crud/dashboard-crud-form-dialog.tsx
Normal file
295
web/components/dashboard/crud/dashboard-crud-form-dialog.tsx
Normal file
@@ -0,0 +1,295 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import type { Resolver } from "react-hook-form"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod/v4"
|
||||
|
||||
import { ProjectDialog } from "@/components/project-dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
buildDashboardCrudFormValues,
|
||||
normalizeDashboardCrudSubmitValues,
|
||||
type DashboardCrudFormInputValue,
|
||||
type DashboardCrudFormField,
|
||||
type DashboardCrudFormOption,
|
||||
} from "./dashboard-crud-utils"
|
||||
import { DashboardCrudFieldControl } from "./dashboard-crud-field-control"
|
||||
|
||||
type DashboardCrudFormDialogProps<TItem, TPayload> = {
|
||||
open: boolean
|
||||
saving: boolean
|
||||
item: TItem | null
|
||||
itemId: number | null
|
||||
fields: DashboardCrudFormField<TItem>[]
|
||||
fetchDetail?: (id: number) => Promise<TItem>
|
||||
transformSubmitValues?: (
|
||||
values: Record<string, string | number | boolean | string[] | number[]>,
|
||||
context: { mode: "create" | "edit"; item: TItem | null }
|
||||
) => TPayload
|
||||
labels: {
|
||||
createTitle: string
|
||||
editTitle: string
|
||||
create: string
|
||||
save: string
|
||||
saving: string
|
||||
cancel: string
|
||||
loadingDetail: string
|
||||
required: string
|
||||
invalidNumber: string
|
||||
minValue: (min: number) => string
|
||||
maxValue: (max: number) => string
|
||||
}
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: TPayload) => Promise<void>
|
||||
}
|
||||
|
||||
function createFormSchema<TItem>(
|
||||
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
||||
labels: DashboardCrudFormDialogProps<TItem, unknown>["labels"]
|
||||
) {
|
||||
const shape: Record<string, z.ZodType> = {}
|
||||
|
||||
fields.forEach((field) => {
|
||||
if (field.type === "section" || field.type === "group") {
|
||||
return
|
||||
}
|
||||
if (field.type === "switch" || field.type === "checkbox") {
|
||||
shape[field.name] = field.required
|
||||
? z.boolean().refine((value) => value, field.requiredMessage ?? labels.required)
|
||||
: z.boolean()
|
||||
return
|
||||
}
|
||||
if (field.type === "multiSelect") {
|
||||
shape[field.name] = field.required
|
||||
? z.array(z.string()).min(1, field.requiredMessage ?? labels.required)
|
||||
: z.array(z.string())
|
||||
return
|
||||
}
|
||||
if (field.type === "custom") {
|
||||
shape[field.name] = z.any()
|
||||
return
|
||||
}
|
||||
let schema = field.trim ? z.string().trim() : z.string()
|
||||
if (field.required) {
|
||||
schema = schema.min(1, field.requiredMessage ?? labels.required)
|
||||
}
|
||||
if (field.pattern) {
|
||||
schema = schema.regex(field.pattern, field.patternMessage ?? labels.required)
|
||||
}
|
||||
if (field.type === "number") {
|
||||
schema = schema.refine((value) => {
|
||||
if (!value.trim()) return !field.required
|
||||
return Number.isFinite(Number(value))
|
||||
}, labels.invalidNumber)
|
||||
if (field.min !== undefined) {
|
||||
schema = schema.refine((value) => !value.trim() || Number(value) >= field.min!, {
|
||||
message: labels.minValue(field.min),
|
||||
})
|
||||
}
|
||||
if (field.max !== undefined) {
|
||||
schema = schema.refine((value) => !value.trim() || Number(value) <= field.max!, {
|
||||
message: labels.maxValue(field.max),
|
||||
})
|
||||
}
|
||||
}
|
||||
if (field.type === "json" && field.validateJson !== false) {
|
||||
schema = schema.refine((value) => {
|
||||
if (!value.trim()) return !field.required
|
||||
try {
|
||||
JSON.parse(value)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}, field.patternMessage ?? labels.required)
|
||||
}
|
||||
shape[field.name] = schema
|
||||
})
|
||||
|
||||
return z.object(shape)
|
||||
}
|
||||
|
||||
function normalizeFormLayoutFields<TItem>(fields: DashboardCrudFormField<TItem>[]) {
|
||||
return fields.map((field) =>
|
||||
["textarea", "json", "code", "custom", "section", "group"].includes(
|
||||
field.type ?? ""
|
||||
)
|
||||
? { ...field, colSpan: field.colSpan ?? 2 }
|
||||
: field
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardCrudFormDialog<TItem, TPayload>({
|
||||
open,
|
||||
saving,
|
||||
item,
|
||||
itemId,
|
||||
fields,
|
||||
fetchDetail,
|
||||
transformSubmitValues,
|
||||
labels,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: DashboardCrudFormDialogProps<TItem, TPayload>) {
|
||||
const layoutFields = useMemo(() => normalizeFormLayoutFields(fields), [fields])
|
||||
const initialValues = useMemo(
|
||||
() => buildDashboardCrudFormValues(fields, item),
|
||||
[fields, item]
|
||||
)
|
||||
const schema = useMemo(() => createFormSchema(fields, labels), [fields, labels])
|
||||
const resolver = useMemo(
|
||||
() =>
|
||||
zodResolver(schema as never) as Resolver<
|
||||
Record<string, DashboardCrudFormInputValue>,
|
||||
undefined,
|
||||
Record<string, DashboardCrudFormInputValue>
|
||||
>,
|
||||
[schema]
|
||||
)
|
||||
const [fetchedDetail, setFetchedDetail] = useState<{
|
||||
id: number
|
||||
item: TItem
|
||||
} | null>(null)
|
||||
const [fieldOptions, setFieldOptions] = useState<
|
||||
Record<string, ReadonlyArray<DashboardCrudFormOption>>
|
||||
>({})
|
||||
const form = useForm<
|
||||
Record<string, DashboardCrudFormInputValue>,
|
||||
undefined,
|
||||
Record<string, DashboardCrudFormInputValue>
|
||||
>({
|
||||
resolver,
|
||||
defaultValues: initialValues,
|
||||
})
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
register,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = form
|
||||
const formId = "dashboard-crud-edit-form"
|
||||
const mode = itemId ? "edit" : "create"
|
||||
const loadingDetail = Boolean(
|
||||
itemId && fetchDetail && fetchedDetail?.id !== itemId
|
||||
)
|
||||
const detailItem =
|
||||
itemId && fetchDetail && fetchedDetail?.id === itemId
|
||||
? fetchedDetail.item
|
||||
: item
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
if (!itemId || !fetchDetail) {
|
||||
reset(initialValues)
|
||||
return
|
||||
}
|
||||
|
||||
void fetchDetail(itemId)
|
||||
.then((detail) => {
|
||||
if (cancelled) return
|
||||
setFetchedDetail({ id: itemId, item: detail })
|
||||
reset(buildDashboardCrudFormValues(fields, detail))
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [fetchDetail, fields, initialValues, item, itemId, reset])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
|
||||
let cancelled = false
|
||||
const loaders = fields
|
||||
.filter(
|
||||
(field) =>
|
||||
(field.type === "select" || field.type === "multiSelect") &&
|
||||
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, DashboardCrudFormInputValue>) {
|
||||
const normalizedValues = normalizeDashboardCrudSubmitValues(fields, values)
|
||||
const payload = transformSubmitValues
|
||||
? transformSubmitValues(normalizedValues, { mode, item: detailItem })
|
||||
: (normalizedValues as TPayload)
|
||||
await onSubmit(payload)
|
||||
}
|
||||
|
||||
if (!open || fields.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<ProjectDialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={mode === "edit" ? labels.editTitle : labels.createTitle}
|
||||
size="md"
|
||||
allowFullscreen
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={saving}
|
||||
>
|
||||
{labels.cancel}
|
||||
</Button>
|
||||
<Button type="submit" form={formId} disabled={saving || loadingDetail}>
|
||||
{saving ? labels.saving : mode === "edit" ? labels.save : labels.create}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{loadingDetail ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-muted-foreground">{labels.loadingDetail}</div>
|
||||
</div>
|
||||
) : (
|
||||
<form
|
||||
id={formId}
|
||||
onSubmit={handleSubmit(submit)}
|
||||
className="grid gap-4 md:grid-cols-2"
|
||||
>
|
||||
{layoutFields.map((field) => (
|
||||
<DashboardCrudFieldControl
|
||||
key={field.name}
|
||||
field={{
|
||||
...field,
|
||||
options: fieldOptions[field.name] ?? field.options,
|
||||
}}
|
||||
control={control}
|
||||
form={form}
|
||||
register={register}
|
||||
error={errors[field.name]}
|
||||
/>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
</ProjectDialog>
|
||||
)
|
||||
}
|
||||
741
web/components/dashboard/crud/dashboard-crud-page.tsx
Normal file
741
web/components/dashboard/crud/dashboard-crud-page.tsx
Normal file
@@ -0,0 +1,741 @@
|
||||
"use client"
|
||||
|
||||
import type { ReactNode } from "react"
|
||||
import { useCallback, useEffect, useRef, useState } from "react"
|
||||
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,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SearchIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useConfirm, type ConfirmOptions } from "@/components/confirm-provider"
|
||||
import {
|
||||
DashboardPage,
|
||||
DashboardTableShell,
|
||||
DashboardTableStateRow,
|
||||
DashboardToolbar,
|
||||
} from "@/components/dashboard-page"
|
||||
import { ListPagination } from "@/components/list-pagination"
|
||||
import { OptionCombobox } from "@/components/option-combobox"
|
||||
import { useDashboardPagedList } from "@/components/dashboard/list"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
isDashboardCrudActionDisabled,
|
||||
isDashboardCrudActionVisible,
|
||||
type DashboardCrudActionRule,
|
||||
type DashboardCrudFormField,
|
||||
type DashboardCrudPageResult,
|
||||
type DashboardCrudQueryFilter,
|
||||
type DashboardCrudQueryValue,
|
||||
} from "./dashboard-crud-utils"
|
||||
import { DashboardCrudFormDialog } from "./dashboard-crud-form-dialog"
|
||||
|
||||
export type DashboardCrudFilter<TValue extends string | number = string> =
|
||||
DashboardCrudQueryFilter & {
|
||||
label: string
|
||||
placeholder?: string
|
||||
defaultValue: TValue
|
||||
type?: "text" | "select"
|
||||
className?: string
|
||||
options?: ReadonlyArray<{ value: string; label: string }>
|
||||
}
|
||||
|
||||
export type DashboardCrudColumn<TItem> = {
|
||||
key: string
|
||||
label: ReactNode
|
||||
className?: string
|
||||
render: (item: TItem, context: DashboardCrudRowActionContext<TItem>) => ReactNode
|
||||
}
|
||||
|
||||
export type DashboardCrudDialogProps<TItem, TPayload> = {
|
||||
open: boolean
|
||||
saving: boolean
|
||||
item: TItem | null
|
||||
itemId: number | null
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: TPayload) => Promise<void>
|
||||
}
|
||||
|
||||
export type DashboardCrudRowActionContext<TItem> = {
|
||||
item: TItem
|
||||
itemId: number
|
||||
actionLoading: boolean
|
||||
actionLoadingId: number | null
|
||||
reload: () => Promise<void>
|
||||
setActionLoadingId: (id: number | null) => void
|
||||
}
|
||||
|
||||
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 DashboardCrudActionState = {
|
||||
onRefresh: () => void
|
||||
onCreate: () => void
|
||||
loading: boolean
|
||||
}
|
||||
|
||||
export type DashboardCrudPageProps<TItem, TPayload> = {
|
||||
filters: DashboardCrudFilter[]
|
||||
columns: DashboardCrudColumn<TItem>[]
|
||||
fetchList: (
|
||||
query: Record<string, DashboardCrudQueryValue>
|
||||
) => Promise<DashboardCrudPageResult<TItem>>
|
||||
renderEditDialog?: (props: DashboardCrudDialogProps<TItem, TPayload>) => ReactNode
|
||||
form?: {
|
||||
fields: DashboardCrudFormField<TItem>[]
|
||||
fetchDetail?: (id: number) => Promise<TItem>
|
||||
transformSubmitValues?: (
|
||||
values: Record<string, string | number | boolean | string[] | number[]>,
|
||||
context: { mode: "create" | "edit"; item: TItem | null }
|
||||
) => TPayload
|
||||
labels: {
|
||||
createTitle: string
|
||||
editTitle: string
|
||||
create: string
|
||||
save: string
|
||||
saving: string
|
||||
cancel: string
|
||||
loadingDetail: string
|
||||
required: string
|
||||
invalidNumber: string
|
||||
minValue: (min: number) => string
|
||||
maxValue: (max: number) => string
|
||||
}
|
||||
}
|
||||
getItemId: (item: TItem) => number
|
||||
createItem: (payload: TPayload) => Promise<unknown>
|
||||
updateItem: (item: TItem, payload: TPayload) => Promise<unknown>
|
||||
onCreateItem?: () => void
|
||||
canEdit?: (item: TItem) => boolean
|
||||
onEditItem?: (item: TItem) => void
|
||||
deleteItem?: (item: TItem) => Promise<unknown>
|
||||
canDelete?: (item: TItem) => boolean
|
||||
deleteConfirm?: false | ConfirmOptions | ((item: TItem) => ConfirmOptions)
|
||||
rowActions?: DashboardCrudRowAction<TItem>[]
|
||||
renderRowActions?: (context: DashboardCrudRowActionContext<TItem>) => ReactNode
|
||||
sort?: {
|
||||
enabled?: boolean
|
||||
disabled?: boolean
|
||||
onReorder: (items: TItem[]) => Promise<unknown>
|
||||
successMessage?: string
|
||||
errorMessage: string
|
||||
handleLabel: string
|
||||
}
|
||||
pageSize?: number
|
||||
reloadKey?: string | number | null
|
||||
layout?: "page" | "fragment"
|
||||
showToolbar?: boolean
|
||||
showToolbarActions?: boolean
|
||||
tableShellClassName?: string
|
||||
onActionStateChange?: (state: DashboardCrudActionState) => void
|
||||
labels: {
|
||||
refresh: string
|
||||
create: string
|
||||
query: string
|
||||
loading: string
|
||||
empty: string
|
||||
actions: string
|
||||
edit: string
|
||||
delete: string
|
||||
processing: string
|
||||
moreActions: (item: TItem) => string
|
||||
loadFailed: string
|
||||
saveFailed: string
|
||||
deleteFailed: string
|
||||
created: (item: TPayload) => string
|
||||
updated: (item: TItem, payload: TPayload) => string
|
||||
deleted?: (item: TItem) => string
|
||||
}
|
||||
}
|
||||
|
||||
export function DashboardCrudPage<TItem, TPayload>({
|
||||
filters,
|
||||
columns,
|
||||
fetchList,
|
||||
renderEditDialog,
|
||||
form,
|
||||
getItemId,
|
||||
createItem,
|
||||
updateItem,
|
||||
onCreateItem,
|
||||
canEdit,
|
||||
onEditItem,
|
||||
deleteItem,
|
||||
canDelete,
|
||||
deleteConfirm,
|
||||
rowActions = [],
|
||||
renderRowActions,
|
||||
sort,
|
||||
pageSize = 20,
|
||||
reloadKey,
|
||||
layout = "page",
|
||||
showToolbar = true,
|
||||
showToolbarActions = true,
|
||||
tableShellClassName,
|
||||
onActionStateChange,
|
||||
labels,
|
||||
}: DashboardCrudPageProps<TItem, TPayload>) {
|
||||
const confirm = useConfirm()
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
activationConstraint: {
|
||||
distance: 6,
|
||||
},
|
||||
}),
|
||||
useSensor(KeyboardSensor, {
|
||||
coordinateGetter: sortableKeyboardCoordinates,
|
||||
})
|
||||
)
|
||||
const list = useDashboardPagedList<TItem>({
|
||||
filters,
|
||||
fetchList,
|
||||
pageSize,
|
||||
reloadKey,
|
||||
loadFailed: labels.loadFailed,
|
||||
})
|
||||
const draftFilters = list.draftFilters
|
||||
const setDraftFilter = list.setDraftFilter
|
||||
const loading = list.loading
|
||||
const result = list.result
|
||||
const loadData = list.loadData
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingItem, setEditingItem] = useState<TItem | null>(null)
|
||||
|
||||
function handleApplyFilters() {
|
||||
list.applyFilters()
|
||||
}
|
||||
|
||||
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
|
||||
if (event.key !== "Enter") return
|
||||
event.preventDefault()
|
||||
handleApplyFilters()
|
||||
}
|
||||
|
||||
const openCreateDialog = useCallback(() => {
|
||||
if (onCreateItem) {
|
||||
onCreateItem()
|
||||
return
|
||||
}
|
||||
setEditingItem(null)
|
||||
setDialogOpen(true)
|
||||
}, [onCreateItem])
|
||||
const loadDataRef = useRef(loadData)
|
||||
const openCreateDialogRef = useRef(openCreateDialog)
|
||||
loadDataRef.current = loadData
|
||||
openCreateDialogRef.current = openCreateDialog
|
||||
const actionRefresh = useCallback(() => void loadDataRef.current(), [])
|
||||
const actionCreate = useCallback(() => openCreateDialogRef.current(), [])
|
||||
|
||||
function openEditDialog(item: TItem) {
|
||||
setEditingItem(item)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
onActionStateChange?.({
|
||||
onRefresh: actionRefresh,
|
||||
onCreate: actionCreate,
|
||||
loading,
|
||||
})
|
||||
}, [actionCreate, actionRefresh, loading, onActionStateChange])
|
||||
|
||||
function handleDialogOpenChange(open: boolean) {
|
||||
if (saving) return
|
||||
if (!open) setEditingItem(null)
|
||||
setDialogOpen(open)
|
||||
}
|
||||
|
||||
async function handleSubmit(payload: TPayload) {
|
||||
if (saving) return
|
||||
setSaving(true)
|
||||
try {
|
||||
if (editingItem) {
|
||||
await updateItem(editingItem, payload)
|
||||
toast.success(labels.updated(editingItem, payload))
|
||||
} else {
|
||||
await createItem(payload)
|
||||
toast.success(labels.created(payload))
|
||||
}
|
||||
setDialogOpen(false)
|
||||
setEditingItem(null)
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : labels.saveFailed)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(item: TItem) {
|
||||
if (!deleteItem) return
|
||||
if (deleteConfirm !== false) {
|
||||
const confirmed = await confirm(
|
||||
typeof deleteConfirm === "function"
|
||||
? deleteConfirm(item)
|
||||
: {
|
||||
confirmText: labels.delete,
|
||||
variant: "destructive",
|
||||
...deleteConfirm,
|
||||
}
|
||||
)
|
||||
if (!confirmed) return
|
||||
}
|
||||
const id = getItemId(item)
|
||||
setActionLoadingId(id)
|
||||
try {
|
||||
await deleteItem(item)
|
||||
toast.success(labels.deleted?.(item) ?? labels.delete)
|
||||
await loadData()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : labels.deleteFailed)
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
list.setResult((current) => ({ ...current, results: nextResults }))
|
||||
|
||||
try {
|
||||
await sort.onReorder(nextResults)
|
||||
if (sort.successMessage) {
|
||||
toast.success(sort.successMessage)
|
||||
}
|
||||
} catch (error) {
|
||||
list.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"
|
||||
disabled={canEdit ? !canEdit(item) : false}
|
||||
onClick={() => {
|
||||
if (onEditItem) {
|
||||
onEditItem(item)
|
||||
return
|
||||
}
|
||||
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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const tableElement = (
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow>
|
||||
{sortable ? <TableHead className="w-10" /> : null}
|
||||
{columns.map((column) => (
|
||||
<TableHead key={column.key} className={column.className}>
|
||||
{column.label}
|
||||
</TableHead>
|
||||
))}
|
||||
<TableHead className="w-[92px] text-right">
|
||||
{labels.actions}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
{sortable ? (
|
||||
<SortableContext
|
||||
items={result.results.map((item) => String(getItemId(item)))}
|
||||
strategy={verticalListSortingStrategy}
|
||||
>
|
||||
<TableBody>
|
||||
{result.results.map((item) =>
|
||||
renderTableRow(item, {
|
||||
sortable: true,
|
||||
sortDisabled: sort?.disabled,
|
||||
})
|
||||
)}
|
||||
{renderStateRow()}
|
||||
</TableBody>
|
||||
</SortableContext>
|
||||
) : (
|
||||
<TableBody>
|
||||
{result.results.map((item) => renderTableRow(item))}
|
||||
{renderStateRow()}
|
||||
</TableBody>
|
||||
)}
|
||||
</Table>
|
||||
)
|
||||
|
||||
const table = sortable ? (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={(event) => void handleSortEnd(event)}
|
||||
>
|
||||
{tableElement}
|
||||
</DndContext>
|
||||
) : (
|
||||
tableElement
|
||||
)
|
||||
|
||||
const content = (
|
||||
<>
|
||||
{showToolbar ? (
|
||||
<DashboardToolbar
|
||||
actions={
|
||||
showToolbarActions ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
|
||||
<RefreshCwIcon className={loading ? "animate-spin" : undefined} />
|
||||
{labels.refresh}
|
||||
</Button>
|
||||
<Button onClick={openCreateDialog}>
|
||||
<PlusIcon />
|
||||
{labels.create}
|
||||
</Button>
|
||||
</>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{filters.map((filter) => {
|
||||
const value = draftFilters[filter.name]
|
||||
if (filter.type === "select") {
|
||||
return (
|
||||
<div key={filter.name} className={filter.className ?? "w-full sm:w-40"}>
|
||||
<OptionCombobox
|
||||
value={String(value ?? "")}
|
||||
onChange={(nextValue) => setDraftFilter(filter.name, nextValue)}
|
||||
placeholder={filter.placeholder ?? filter.label}
|
||||
options={[...(filter.options ?? [])]}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={filter.name} className={filter.className ?? "w-full sm:w-64"}>
|
||||
<Input
|
||||
value={String(value ?? "")}
|
||||
onChange={(event) =>
|
||||
setDraftFilter(filter.name, event.target.value)
|
||||
}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
placeholder={filter.placeholder ?? filter.label}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<Button variant="outline" onClick={handleApplyFilters} disabled={loading}>
|
||||
<SearchIcon />
|
||||
{labels.query}
|
||||
</Button>
|
||||
</DashboardToolbar>
|
||||
) : null}
|
||||
|
||||
<DashboardTableShell
|
||||
className={tableShellClassName}
|
||||
pagination={
|
||||
<ListPagination
|
||||
page={result.page.page}
|
||||
total={result.page.total}
|
||||
limit={list.limit}
|
||||
loading={loading}
|
||||
onPageChange={list.handlePageChange}
|
||||
onLimitChange={list.handleLimitChange}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{table}
|
||||
</DashboardTableShell>
|
||||
</>
|
||||
)
|
||||
|
||||
const dialog = form ? (
|
||||
<DashboardCrudFormDialog
|
||||
open={dialogOpen}
|
||||
saving={saving}
|
||||
item={editingItem}
|
||||
itemId={editingItem ? getItemId(editingItem) : null}
|
||||
fields={form.fields}
|
||||
fetchDetail={form.fetchDetail}
|
||||
transformSubmitValues={form.transformSubmitValues}
|
||||
labels={form.labels}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
) : (
|
||||
renderEditDialog?.({
|
||||
open: dialogOpen,
|
||||
saving,
|
||||
item: editingItem,
|
||||
itemId: editingItem ? getItemId(editingItem) : null,
|
||||
onOpenChange: handleDialogOpenChange,
|
||||
onSubmit: handleSubmit,
|
||||
})
|
||||
)
|
||||
|
||||
if (layout === "fragment") {
|
||||
return (
|
||||
<>
|
||||
{content}
|
||||
{dialog}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardPage>{content}</DashboardPage>
|
||||
{dialog}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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>
|
||||
)
|
||||
}
|
||||
130
web/components/dashboard/crud/dashboard-crud-presets.tsx
Normal file
130
web/components/dashboard/crud/dashboard-crud-presets.tsx
Normal file
@@ -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)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
250
web/components/dashboard/crud/dashboard-crud-utils.test.mjs
Normal file
250
web/components/dashboard/crud/dashboard-crud-utils.test.mjs
Normal file
@@ -0,0 +1,250 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { describe, it } from "node:test"
|
||||
import ts from "typescript"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import vm from "node:vm"
|
||||
|
||||
function plain(value) {
|
||||
return JSON.parse(JSON.stringify(value))
|
||||
}
|
||||
|
||||
async function loadModule() {
|
||||
const source = await readFile(
|
||||
new URL("./dashboard-crud-utils.ts", import.meta.url),
|
||||
"utf8"
|
||||
)
|
||||
const compiled = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
target: ts.ScriptTarget.ES2017,
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
},
|
||||
fileName: "dashboard-crud-utils.ts",
|
||||
})
|
||||
const sandbox = {
|
||||
exports: {},
|
||||
module: { exports: {} },
|
||||
}
|
||||
sandbox.exports = sandbox.module.exports
|
||||
vm.runInNewContext(compiled.outputText, sandbox)
|
||||
return sandbox.module.exports
|
||||
}
|
||||
|
||||
describe("buildDashboardCrudQuery", () => {
|
||||
it("trims text filters and omits empty values", async () => {
|
||||
const { buildDashboardCrudQuery } = await loadModule()
|
||||
const query = buildDashboardCrudQuery({
|
||||
values: {
|
||||
title: " hello ",
|
||||
groupName: " ",
|
||||
},
|
||||
filters: [
|
||||
{ name: "title", trim: true },
|
||||
{ name: "groupName", trim: true },
|
||||
],
|
||||
page: 2,
|
||||
limit: 50,
|
||||
})
|
||||
|
||||
assert.deepEqual(plain(query), {
|
||||
title: "hello",
|
||||
page: 2,
|
||||
limit: 50,
|
||||
})
|
||||
})
|
||||
|
||||
it("omits configured all values and parses numbers", async () => {
|
||||
const { buildDashboardCrudQuery } = await loadModule()
|
||||
const query = buildDashboardCrudQuery({
|
||||
values: {
|
||||
status: "all",
|
||||
companyId: "42",
|
||||
},
|
||||
filters: [
|
||||
{ name: "status", allValue: "all" },
|
||||
{ name: "companyId", allValue: "0", valueType: "number" },
|
||||
],
|
||||
page: 1,
|
||||
limit: 20,
|
||||
})
|
||||
|
||||
assert.deepEqual(plain(query), {
|
||||
companyId: 42,
|
||||
page: 1,
|
||||
limit: 20,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
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", () => {
|
||||
it("returns a stable empty page when the API result is missing", async () => {
|
||||
const { normalizeDashboardCrudPageResult } = await loadModule()
|
||||
assert.deepEqual(plain(normalizeDashboardCrudPageResult(null, 3, 10)), {
|
||||
results: [],
|
||||
page: {
|
||||
page: 3,
|
||||
limit: 10,
|
||||
total: 0,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("buildDashboardCrudFormValues", () => {
|
||||
it("uses defaults for create forms and item values for edit forms", async () => {
|
||||
const { buildDashboardCrudFormValues } = await loadModule()
|
||||
const fields = [
|
||||
{ name: "title", defaultValue: "Untitled" },
|
||||
{ name: "sortNo", type: "number", defaultValue: "0" },
|
||||
{
|
||||
name: "status",
|
||||
defaultValue: "0",
|
||||
valueFromItem: (item) => String(item.status),
|
||||
},
|
||||
]
|
||||
|
||||
assert.deepEqual(plain(buildDashboardCrudFormValues(fields)), {
|
||||
title: "Untitled",
|
||||
sortNo: "0",
|
||||
status: "0",
|
||||
})
|
||||
assert.deepEqual(
|
||||
plain(buildDashboardCrudFormValues(fields, { title: "Hello", sortNo: 7, status: 1 })),
|
||||
{
|
||||
title: "Hello",
|
||||
sortNo: "7",
|
||||
status: "1",
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it("normalizes boolean and multi-select defaults", async () => {
|
||||
const { buildDashboardCrudFormValues } = await loadModule()
|
||||
const fields = [
|
||||
{ name: "enabled", type: "switch", defaultValue: true },
|
||||
{ name: "required", type: "checkbox" },
|
||||
{ name: "toolIds", type: "multiSelect", defaultValue: [1, "2"] },
|
||||
]
|
||||
|
||||
assert.deepEqual(plain(buildDashboardCrudFormValues(fields)), {
|
||||
enabled: true,
|
||||
required: false,
|
||||
toolIds: ["1", "2"],
|
||||
})
|
||||
assert.deepEqual(
|
||||
plain(
|
||||
buildDashboardCrudFormValues(fields, {
|
||||
enabled: 0,
|
||||
required: "1",
|
||||
toolIds: [3, "4"],
|
||||
})
|
||||
),
|
||||
{
|
||||
enabled: false,
|
||||
required: true,
|
||||
toolIds: ["3", "4"],
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("normalizeDashboardCrudSubmitValues", () => {
|
||||
it("trims strings and converts number fields", async () => {
|
||||
const { normalizeDashboardCrudSubmitValues } = await loadModule()
|
||||
const fields = [
|
||||
{ name: "title", trim: true },
|
||||
{ name: "sortNo", type: "number" },
|
||||
{ name: "status", type: "select", valueType: "number" },
|
||||
]
|
||||
|
||||
assert.deepEqual(
|
||||
plain(
|
||||
normalizeDashboardCrudSubmitValues(fields, {
|
||||
title: " Hello ",
|
||||
sortNo: "12",
|
||||
status: "1",
|
||||
})
|
||||
),
|
||||
{
|
||||
title: "Hello",
|
||||
sortNo: 12,
|
||||
status: 1,
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it("converts boolean and multi-select fields", async () => {
|
||||
const { normalizeDashboardCrudSubmitValues } = await loadModule()
|
||||
const fields = [
|
||||
{ name: "enabled", type: "switch" },
|
||||
{ name: "toolCodes", type: "multiSelect" },
|
||||
{ name: "roleIds", type: "multiSelect", valueType: "number" },
|
||||
{ name: "section", type: "section" },
|
||||
]
|
||||
|
||||
assert.deepEqual(
|
||||
plain(
|
||||
normalizeDashboardCrudSubmitValues(fields, {
|
||||
enabled: true,
|
||||
toolCodes: ["search", "faq"],
|
||||
roleIds: ["1", "2", "bad"],
|
||||
section: "",
|
||||
})
|
||||
),
|
||||
{
|
||||
enabled: true,
|
||||
toolCodes: ["search", "faq"],
|
||||
roleIds: [1, 2],
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
262
web/components/dashboard/crud/dashboard-crud-utils.ts
Normal file
262
web/components/dashboard/crud/dashboard-crud-utils.ts
Normal file
@@ -0,0 +1,262 @@
|
||||
import type { ReactNode } from "react"
|
||||
|
||||
export type DashboardCrudQueryValue = string | number | undefined
|
||||
|
||||
export type DashboardCrudQueryFilter = {
|
||||
name: string
|
||||
trim?: boolean
|
||||
allValue?: string | number
|
||||
valueType?: "string" | "number"
|
||||
}
|
||||
|
||||
export type DashboardCrudFilterStateConfig<
|
||||
TValue extends string | number = string | number,
|
||||
> = {
|
||||
name: string
|
||||
defaultValue: TValue
|
||||
}
|
||||
|
||||
export type DashboardCrudPageResult<T> = {
|
||||
results: T[]
|
||||
page: {
|
||||
page: number
|
||||
limit: number
|
||||
total: number
|
||||
}
|
||||
}
|
||||
|
||||
export type DashboardCrudFormValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| ReadonlyArray<string | number>
|
||||
| undefined
|
||||
|
||||
export type DashboardCrudFormOption = {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export type DashboardCrudFormInputValue = string | boolean | string[]
|
||||
|
||||
export type DashboardCrudFormCustomRenderContext = {
|
||||
name: string
|
||||
label: string
|
||||
value: DashboardCrudFormInputValue
|
||||
values: Record<string, DashboardCrudFormInputValue>
|
||||
setValue: (name: string, value: DashboardCrudFormInputValue) => void
|
||||
}
|
||||
|
||||
export type DashboardCrudFormField<TItem = unknown> = {
|
||||
name: string
|
||||
label: string
|
||||
type?:
|
||||
| "text"
|
||||
| "textarea"
|
||||
| "number"
|
||||
| "select"
|
||||
| "multiSelect"
|
||||
| "switch"
|
||||
| "checkbox"
|
||||
| "password"
|
||||
| "json"
|
||||
| "code"
|
||||
| "custom"
|
||||
| "section"
|
||||
| "group"
|
||||
placeholder?: string
|
||||
defaultValue?: DashboardCrudFormValue
|
||||
description?: string
|
||||
required?: boolean
|
||||
requiredMessage?: string
|
||||
trim?: boolean
|
||||
normalizeInput?: (value: string) => string
|
||||
valueType?: "string" | "number" | "boolean"
|
||||
min?: number
|
||||
max?: number
|
||||
step?: number
|
||||
pattern?: RegExp
|
||||
patternMessage?: string
|
||||
options?: ReadonlyArray<DashboardCrudFormOption>
|
||||
loadOptions?: () => Promise<ReadonlyArray<DashboardCrudFormOption>>
|
||||
colSpan?: 1 | 2
|
||||
rows?: number
|
||||
language?: string
|
||||
validateJson?: boolean
|
||||
valueFromItem?: (item: TItem) => DashboardCrudFormValue
|
||||
render?: (context: DashboardCrudFormCustomRenderContext) => ReactNode
|
||||
}
|
||||
|
||||
export type DashboardCrudActionRule<TItem> = {
|
||||
visible?: (item: TItem) => boolean
|
||||
disabled?: (item: TItem) => boolean
|
||||
}
|
||||
|
||||
export function buildDashboardCrudQuery({
|
||||
values,
|
||||
filters,
|
||||
page,
|
||||
limit,
|
||||
}: {
|
||||
values: Record<string, string | number | undefined>
|
||||
filters: DashboardCrudQueryFilter[]
|
||||
page: number
|
||||
limit: number
|
||||
}): Record<string, DashboardCrudQueryValue> {
|
||||
const query: Record<string, DashboardCrudQueryValue> = {}
|
||||
|
||||
filters.forEach((filter) => {
|
||||
const rawValue = values[filter.name]
|
||||
const value =
|
||||
filter.trim && typeof rawValue === "string" ? rawValue.trim() : rawValue
|
||||
|
||||
if (
|
||||
value === undefined ||
|
||||
value === "" ||
|
||||
(filter.allValue !== undefined && String(value) === String(filter.allValue))
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (filter.valueType === "number") {
|
||||
const numberValue = Number(value)
|
||||
if (Number.isFinite(numberValue)) {
|
||||
query[filter.name] = numberValue
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
query[filter.name] = value
|
||||
})
|
||||
|
||||
query.page = page
|
||||
query.limit = limit
|
||||
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>(
|
||||
result: Partial<DashboardCrudPageResult<T>> | null | undefined,
|
||||
page: number,
|
||||
limit: number
|
||||
): DashboardCrudPageResult<T> {
|
||||
return {
|
||||
results: Array.isArray(result?.results) ? result.results : [],
|
||||
page: {
|
||||
page: result?.page?.page ?? page,
|
||||
limit: result?.page?.limit ?? limit,
|
||||
total: result?.page?.total ?? 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function buildDashboardCrudFormValues<TItem>(
|
||||
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
||||
item?: TItem | null
|
||||
): Record<string, DashboardCrudFormInputValue> {
|
||||
return Object.fromEntries(
|
||||
fields.map((field) => {
|
||||
let value: unknown = field.defaultValue ?? getDashboardCrudFormDefaultValue(field)
|
||||
if (item) {
|
||||
if (field.valueFromItem) {
|
||||
value = field.valueFromItem(item)
|
||||
} else if (typeof item === "object" && item && field.name in item) {
|
||||
value = (item as Record<string, unknown>)[field.name]
|
||||
}
|
||||
}
|
||||
return [field.name, normalizeDashboardCrudFormInputValue(field, value)]
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
export function normalizeDashboardCrudSubmitValues<TItem>(
|
||||
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
||||
values: Record<string, DashboardCrudFormInputValue>
|
||||
): Record<string, string | number | boolean | string[] | number[]> {
|
||||
const output: Record<string, string | number | boolean | string[] | number[]> = {}
|
||||
|
||||
fields.forEach((field) => {
|
||||
if (field.type === "section" || field.type === "group") {
|
||||
return
|
||||
}
|
||||
|
||||
const rawValue = values[field.name] ?? getDashboardCrudFormDefaultValue(field)
|
||||
if (field.type === "switch" || field.type === "checkbox" || field.valueType === "boolean") {
|
||||
output[field.name] = Boolean(rawValue)
|
||||
return
|
||||
}
|
||||
if (field.type === "multiSelect") {
|
||||
const list = Array.isArray(rawValue) ? rawValue : []
|
||||
if (field.valueType === "number") {
|
||||
output[field.name] = list
|
||||
.map((value) => Number(value))
|
||||
.filter((value) => Number.isFinite(value))
|
||||
return
|
||||
}
|
||||
output[field.name] = list.map(String)
|
||||
return
|
||||
}
|
||||
const rawText = typeof rawValue === "string" ? rawValue : String(rawValue ?? "")
|
||||
const text = field.trim ? rawText.trim() : rawText
|
||||
if (field.type === "number" || field.valueType === "number") {
|
||||
const numberValue = Number(text)
|
||||
output[field.name] = Number.isFinite(numberValue) ? numberValue : 0
|
||||
return
|
||||
}
|
||||
output[field.name] = text
|
||||
})
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
function getDashboardCrudFormDefaultValue<TItem>(
|
||||
field: DashboardCrudFormField<TItem>
|
||||
): DashboardCrudFormInputValue {
|
||||
if (field.type === "switch" || field.type === "checkbox") {
|
||||
return false
|
||||
}
|
||||
if (field.type === "multiSelect") {
|
||||
return []
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
function normalizeDashboardCrudFormInputValue<TItem>(
|
||||
field: DashboardCrudFormField<TItem>,
|
||||
value: unknown
|
||||
): DashboardCrudFormInputValue {
|
||||
if (value === undefined || value === null) {
|
||||
return getDashboardCrudFormDefaultValue(field)
|
||||
}
|
||||
if (field.type === "switch" || field.type === "checkbox" || field.valueType === "boolean") {
|
||||
return value === true || value === "true" || value === 1 || value === "1"
|
||||
}
|
||||
if (field.type === "multiSelect") {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value
|
||||
.filter((item) => item !== undefined && item !== null)
|
||||
.map((item) => String(item))
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
30
web/components/dashboard/crud/index.ts
Normal file
30
web/components/dashboard/crud/index.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
export { DashboardCrudPage } from "./dashboard-crud-page"
|
||||
export { DashboardCrudFormDialog } from "./dashboard-crud-form-dialog"
|
||||
export {
|
||||
buildDashboardCrudQuery,
|
||||
normalizeDashboardCrudPageResult,
|
||||
} from "./dashboard-crud-utils"
|
||||
export {
|
||||
createDashboardStatusColumn,
|
||||
createDashboardStatusToggleAction,
|
||||
} from "./dashboard-crud-presets"
|
||||
export { useDashboardCrudFilters } from "./use-dashboard-crud-filters"
|
||||
export type {
|
||||
DashboardCrudColumn,
|
||||
DashboardCrudActionState,
|
||||
DashboardCrudDialogProps,
|
||||
DashboardCrudFilter,
|
||||
DashboardCrudPageProps,
|
||||
DashboardCrudRowAction,
|
||||
DashboardCrudRowActionContext,
|
||||
} from "./dashboard-crud-page"
|
||||
export type {
|
||||
DashboardCrudFormField,
|
||||
DashboardCrudFormInputValue,
|
||||
DashboardCrudFormOption,
|
||||
DashboardCrudFormValue,
|
||||
DashboardCrudFilterStateConfig,
|
||||
DashboardCrudPageResult,
|
||||
DashboardCrudQueryFilter,
|
||||
DashboardCrudQueryValue,
|
||||
} from "./dashboard-crud-utils"
|
||||
65
web/components/dashboard/crud/use-dashboard-crud-filters.ts
Normal file
65
web/components/dashboard/crud/use-dashboard-crud-filters.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
|
||||
import {
|
||||
buildDashboardCrudInitialFilters,
|
||||
type DashboardCrudFilterStateConfig,
|
||||
} from "./dashboard-crud-utils"
|
||||
|
||||
export function useDashboardCrudFilters(
|
||||
filters: ReadonlyArray<DashboardCrudFilterStateConfig>
|
||||
) {
|
||||
const defaultsKey = filters
|
||||
.map((filter) => `${filter.name}:${String(filter.defaultValue)}`)
|
||||
.join("|")
|
||||
const initialFilters = useMemo(
|
||||
() => buildDashboardCrudInitialFilters(filters),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[defaultsKey]
|
||||
)
|
||||
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)
|
||||
}
|
||||
|
||||
function applyFilter(name: string, value: string | number | undefined) {
|
||||
setDraftFilters((current) => ({
|
||||
...current,
|
||||
[name]: value,
|
||||
}))
|
||||
setAppliedFilters((current) => ({
|
||||
...current,
|
||||
[name]: value,
|
||||
}))
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
setDraftFilters(initialFilters)
|
||||
setAppliedFilters(initialFilters)
|
||||
}
|
||||
|
||||
return {
|
||||
draftFilters,
|
||||
appliedFilters,
|
||||
setDraftFilter,
|
||||
setDraftFilters,
|
||||
applyFilter,
|
||||
applyFilters,
|
||||
resetFilters,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user