feat: refactor quick replies page to use DashboardCrudPage component

- Removed redundant state management and effects from DashboardQuickRepliesPage.
- Integrated DashboardCrudPage for handling CRUD operations and filtering.
- Created a new DashboardCrudPage component to encapsulate common CRUD logic.
- Added utility functions for building and normalizing dashboard CRUD queries.
- Implemented tests for the new utility functions to ensure correctness.
This commit is contained in:
mlogclub
2026-05-28 08:39:14 +08:00
parent dd1b0d1b81
commit fe480ff131
7 changed files with 1054 additions and 987 deletions
@@ -0,0 +1,415 @@
"use client"
import type { ReactNode } from "react"
import { useCallback, useEffect, useMemo, useState } from "react"
import {
MoreHorizontalIcon,
PlusIcon,
RefreshCwIcon,
SearchIcon,
Trash2Icon,
} from "lucide-react"
import { toast } from "sonner"
import {
DashboardPage,
DashboardTableShell,
DashboardTableStateRow,
DashboardToolbar,
} from "@/components/dashboard-page"
import { ListPagination } from "@/components/list-pagination"
import { OptionCombobox } from "@/components/option-combobox"
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 {
buildDashboardCrudQuery,
normalizeDashboardCrudPageResult,
type DashboardCrudPageResult,
type DashboardCrudQueryFilter,
type DashboardCrudQueryValue,
} from "./dashboard-crud-utils"
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 }>
}
type DashboardCrudColumn<TItem> = {
key: string
label: ReactNode
className?: string
render: (item: TItem, context: DashboardCrudRowActionContext<TItem>) => ReactNode
}
type DashboardCrudDialogProps<TItem, TPayload> = {
open: boolean
saving: boolean
item: TItem | null
itemId: number | null
onOpenChange: (open: boolean) => void
onSubmit: (payload: TPayload) => Promise<void>
}
type DashboardCrudRowActionContext<TItem> = {
item: TItem
actionLoading: boolean
actionLoadingId: number | null
reload: () => Promise<void>
setActionLoadingId: (id: number | null) => void
}
type DashboardCrudPageProps<TItem, TPayload> = {
filters: DashboardCrudFilter[]
columns: DashboardCrudColumn<TItem>[]
fetchList: (
query: Record<string, DashboardCrudQueryValue>
) => Promise<DashboardCrudPageResult<TItem>>
renderEditDialog: (props: DashboardCrudDialogProps<TItem, TPayload>) => ReactNode
getItemId: (item: TItem) => number
createItem: (payload: TPayload) => Promise<unknown>
updateItem: (item: TItem, payload: TPayload) => Promise<unknown>
deleteItem?: (item: TItem) => Promise<unknown>
canDelete?: (item: TItem) => boolean
renderRowActions?: (context: DashboardCrudRowActionContext<TItem>) => ReactNode
pageSize?: number
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,
getItemId,
createItem,
updateItem,
deleteItem,
canDelete,
renderRowActions,
pageSize = 20,
labels,
}: DashboardCrudPageProps<TItem, TPayload>) {
const initialFilters = useMemo(
() =>
Object.fromEntries(
filters.map((filter) => [filter.name, filter.defaultValue])
) as Record<string, string | number | undefined>,
[filters]
)
const [draftFilters, setDraftFilters] = useState(initialFilters)
const [appliedFilters, setAppliedFilters] = useState(initialFilters)
const [page, setPage] = useState(1)
const [limit, setLimit] = useState(pageSize)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [editingItem, setEditingItem] = useState<TItem | null>(null)
const [result, setResult] = useState<DashboardCrudPageResult<TItem>>({
results: [],
page: { page: 1, limit: pageSize, total: 0 },
})
useEffect(() => {
setDraftFilters(initialFilters)
setAppliedFilters(initialFilters)
}, [initialFilters])
const loadData = useCallback(async () => {
setLoading(true)
try {
const data = await fetchList(
buildDashboardCrudQuery({
values: appliedFilters,
filters,
page,
limit,
})
)
setResult(normalizeDashboardCrudPageResult(data, page, limit))
} catch (error) {
toast.error(error instanceof Error ? error.message : labels.loadFailed)
} finally {
setLoading(false)
}
}, [appliedFilters, fetchList, filters, labels.loadFailed, limit, page])
useEffect(() => {
void loadData()
}, [loadData])
function applyFilters() {
setAppliedFilters(draftFilters)
setPage(1)
}
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
if (event.key !== "Enter") return
event.preventDefault()
applyFilters()
}
function openCreateDialog() {
setEditingItem(null)
setDialogOpen(true)
}
function openEditDialog(item: TItem) {
setEditingItem(item)
setDialogOpen(true)
}
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
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)
}
}
const colSpan = columns.length + 1
return (
<>
<DashboardPage>
<DashboardToolbar
actions={
<>
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
<RefreshCwIcon className={loading ? "animate-spin" : undefined} />
{labels.refresh}
</Button>
<Button onClick={openCreateDialog}>
<PlusIcon />
{labels.create}
</Button>
</>
}
>
{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) =>
setDraftFilters((current) => ({
...current,
[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) =>
setDraftFilters((current) => ({
...current,
[filter.name]: event.target.value,
}))
}
onKeyDown={handleFilterKeyDown}
placeholder={filter.placeholder ?? filter.label}
/>
</div>
)
})}
<Button variant="outline" onClick={applyFilters} disabled={loading}>
<SearchIcon />
{labels.query}
</Button>
</DashboardToolbar>
<DashboardTableShell
pagination={
<ListPagination
page={result.page.page}
total={result.page.total}
limit={limit}
loading={loading}
onPageChange={(nextPage) => {
if (nextPage < 1 || nextPage === page) return
setPage(nextPage)
}}
onLimitChange={(nextLimit) => {
setLimit(nextLimit)
setPage(1)
}}
/>
}
>
<Table>
<TableHeader className="bg-muted/40">
<TableRow>
{columns.map((column) => (
<TableHead key={column.key} className={column.className}>
{column.label}
</TableHead>
))}
<TableHead className="w-[92px] text-right">
{labels.actions}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{result.results.map((item) => {
const id = getItemId(item)
const actionLoading = actionLoadingId === id
return (
<TableRow key={id}>
{columns.map((column) => (
<TableCell key={column.key} className={column.className}>
{column.render(item, {
item,
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 || 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>
</DashboardTableShell>
</DashboardPage>
{renderEditDialog({
open: dialogOpen,
saving,
item: editingItem,
itemId: editingItem ? getItemId(editingItem) : null,
onOpenChange: handleDialogOpenChange,
onSubmit: handleSubmit,
})}
</>
)
}
@@ -0,0 +1,90 @@
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("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,
},
})
})
})
@@ -0,0 +1,74 @@
export type DashboardCrudQueryValue = string | number | undefined
export type DashboardCrudQueryFilter = {
name: string
trim?: boolean
allValue?: string | number
valueType?: "string" | "number"
}
export type DashboardCrudPageResult<T> = {
results: T[]
page: {
page: number
limit: number
total: number
}
}
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 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,
},
}
}
+5
View File
@@ -0,0 +1,5 @@
export { DashboardCrudPage } from "./dashboard-crud-page"
export type {
DashboardCrudPageResult,
DashboardCrudQueryValue,
} from "./dashboard-crud-utils"