refactor: 统一管理页面布局 — FilterToolbar + usePageSearchParams + parseListParams

This commit is contained in:
2026-06-04 17:25:36 +08:00
parent 61b479e2be
commit 6f547560d1
40 changed files with 1805 additions and 628 deletions

View File

@@ -1,184 +1,169 @@
import type { TableColumnsType } from "antd";
import type { TableColumnsType, TableProps } from "antd";
import { DeleteOutlined, EditOutlined, InboxOutlined, LoginOutlined, RedoOutlined } from "@ant-design/icons";
import { App as AntApp, Button, Popconfirm, Space, Table, Tag } from "antd";
import { useCallback, useMemo } from "react";
import { Button, Popconfirm, Space, Table, Tag } from "antd";
import { useMemo } from "react";
import { useNavigate } from "react-router";
import type { Project, ProjectListResponse, ProjectStatus } from "../../../../shared/api";
import type { Project, ProjectListResponse } from "../../../../shared/api";
import { formatDatetime } from "../../../shared/utils/format";
interface ProjectTableProps {
data: ProjectListResponse | undefined;
loading: boolean;
onArchive: (id: string) => Promise<unknown>;
onDelete: (id: string) => Promise<unknown>;
onArchive: (id: string) => Promise<void>;
onChange: (
pagination: { current?: number; pageSize?: number },
sorter: { columnKey?: string; field?: string | string[]; order?: string },
) => void;
onDelete: (id: string) => Promise<void>;
onEdit: (project: Project) => void;
onPageChange: (page: number, pageSize: number) => void;
onRestore: (id: string) => Promise<unknown>;
onRestore: (id: string) => Promise<void>;
page: number;
pageSize: number;
status: ProjectStatus;
sortBy?: string;
sortOrder?: string;
}
const COLUMNS: TableColumnsType<Project> = [
{ dataIndex: "name", ellipsis: true, title: "名称", width: 140 },
{ dataIndex: "description", ellipsis: true, title: "描述" },
{
align: "center",
dataIndex: "status",
render: (_value, record: Project) => {
if (record.status === "archived") {
return <Tag></Tag>;
}
return <Tag color="blue"></Tag>;
},
title: "状态",
width: 90,
},
{
align: "center",
dataIndex: "createdAt",
render: (_value, record: Project) => formatDatetime(record.createdAt),
title: "创建时间",
width: 180,
},
{
align: "center",
dataIndex: "updatedAt",
render: (_value, record: Project) => formatDatetime(record.updatedAt),
title: "更新时间",
width: 180,
},
];
export function ProjectTable({
data,
loading,
onArchive,
onChange,
onDelete,
onEdit,
onPageChange,
onRestore,
page,
pageSize,
status,
sortBy,
sortOrder,
}: ProjectTableProps) {
const { message } = AntApp.useApp();
const navigate = useNavigate();
const handleArchive = useCallback(
async (id: string) => {
try {
await onArchive(id);
message.success("项目已归档");
} catch (err: unknown) {
message.error((err as Error).message);
}
},
[onArchive, message],
);
const handleRestore = useCallback(
async (id: string) => {
try {
await onRestore(id);
message.success("项目已恢复");
} catch (err: unknown) {
message.error((err as Error).message);
}
},
[onRestore, message],
);
const handleDelete = useCallback(
async (id: string) => {
try {
await onDelete(id);
message.success("项目已永久删除");
} catch (err: unknown) {
message.error((err as Error).message);
}
},
[onDelete, message],
);
const operationColumn = useMemo<TableColumnsType<Project>[number]>(
() => ({
dataIndex: "op",
render: (_value, record: Project) => {
if (record.status === "active") {
const columns = useMemo<TableColumnsType<Project>>(
() => [
{
dataIndex: "name",
ellipsis: true,
sorter: true,
sortOrder:
sortBy === "name" ? (sortOrder === "asc" ? "ascend" : sortOrder === "desc" ? "descend" : null) : null,
title: "名称",
width: 140,
},
{ dataIndex: "description", ellipsis: true, title: "描述" },
{
align: "center",
dataIndex: "status",
render: (_value: unknown, record: Project) => {
if (record.status === "archived") {
return <Tag></Tag>;
}
return <Tag color="blue"></Tag>;
},
title: "状态",
width: 90,
},
{
align: "center",
dataIndex: "createdAt",
render: (_value: unknown, record: Project) => formatDatetime(record.createdAt),
sorter: true,
sortOrder:
sortBy === "createdAt" ? (sortOrder === "asc" ? "ascend" : sortOrder === "desc" ? "descend" : null) : null,
title: "创建时间",
width: 180,
},
{
align: "center",
dataIndex: "updatedAt",
render: (_value: unknown, record: Project) => formatDatetime(record.updatedAt),
sorter: true,
sortOrder:
sortBy === "updatedAt" ? (sortOrder === "asc" ? "ascend" : sortOrder === "desc" ? "descend" : null) : null,
title: "更新时间",
width: 180,
},
{
dataIndex: "op",
render: (_value: unknown, record: Project) => {
if (record.status === "active") {
return (
<Space size="small">
<Button
icon={<LoginOutlined />}
onClick={() => void navigate(`/workbench/${record.id}`)}
size="small"
type="link"
>
</Button>
<Button icon={<EditOutlined />} onClick={() => onEdit(record)} size="small" type="link">
</Button>
<Popconfirm
description="归档后项目将变为只读。"
onConfirm={() => void onArchive(record.id)}
title="确认归档此项目?"
>
<Button color="orange" icon={<InboxOutlined />} size="small" variant="link">
</Button>
</Popconfirm>
</Space>
);
}
return (
<Space size="small">
<Button
icon={<LoginOutlined />}
onClick={() => void navigate(`/workbench/${record.id}`)}
size="small"
type="link"
>
</Button>
<Button icon={<EditOutlined />} onClick={() => onEdit(record)} size="small" type="link">
</Button>
<Popconfirm onConfirm={() => void onRestore(record.id)} title="确认恢复此项目?">
<Button icon={<RedoOutlined />} size="small" type="link">
</Button>
</Popconfirm>
<Popconfirm
description="归档后项目将变为只读。"
onConfirm={() => void handleArchive(record.id)}
title="确认归档此项目?"
description="此操作不可恢复。"
onConfirm={() => void onDelete(record.id)}
title="确认永久删除此项目?"
>
<Button color="orange" icon={<InboxOutlined />} size="small" variant="link">
<Button danger icon={<DeleteOutlined />} size="small" type="link">
</Button>
</Popconfirm>
</Space>
);
}
return (
<Space size="small">
<Popconfirm onConfirm={() => void handleRestore(record.id)} title="确认恢复此项目?">
<Button icon={<RedoOutlined />} size="small" type="link">
</Button>
</Popconfirm>
<Popconfirm
description="此操作不可恢复。"
onConfirm={() => void handleDelete(record.id)}
title="确认永久删除此项目?"
>
<Button danger icon={<DeleteOutlined />} size="small" type="link">
</Button>
</Popconfirm>
</Space>
);
},
title: "操作",
width: 260,
},
title: "操作",
width: status === "active" ? 260 : 160,
}),
[navigate, onEdit, handleArchive, handleRestore, handleDelete, status],
],
[navigate, onEdit, onArchive, onRestore, onDelete, sortBy, sortOrder],
);
const columns = useMemo(() => [...COLUMNS, operationColumn], [operationColumn]);
const handleTableChange: TableProps<Project>["onChange"] = (pagination, _filters, sorter) => {
const sortInfo =
sorter && typeof sorter === "object" && "columnKey" in sorter
? (sorter as { columnKey?: string; field?: string | string[]; order?: string })
: {};
onChange({ current: pagination.current, pageSize: pagination.pageSize }, sortInfo);
};
return (
<Table
columns={columns}
dataSource={data?.items ?? []}
loading={loading}
locale={{ emptyText: "暂无项目数据" }}
onChange={handleTableChange}
pagination={{
current: page,
hideOnSinglePage: false,
onChange: onPageChange,
pageSize,
showSizeChanger: true,
showTotal: (total) => `${total}`,
total: data?.total ?? 0,
}}
rowKey="id"
/>
);
}
function formatDatetime(dateStr: string): string {
const d = new Date(dateStr);
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

View File

@@ -1,55 +0,0 @@
import { PlusOutlined } from "@ant-design/icons";
import { Button, Flex, Input, Space, Tabs } from "antd";
import { useState } from "react";
import type { ProjectStatus } from "../../../../shared/api";
interface ProjectToolbarProps {
activeTab: ProjectStatus;
keyword: string;
onSearch: (value: string) => void;
onSearchClear: () => void;
onTabChange: (key: string) => void;
openCreateDialog: () => void;
}
const STATUS_TAB_ITEMS = [
{ key: "active", label: "进行中" },
{ key: "archived", label: "已归档" },
];
export function ProjectToolbar({
activeTab,
keyword,
onSearch,
onSearchClear,
onTabChange,
openCreateDialog,
}: ProjectToolbarProps) {
const [draftKeyword, setDraftKeyword] = useState(keyword);
return (
<Flex align="center" gap="large" justify="space-between" wrap="wrap">
<Tabs activeKey={activeTab} items={STATUS_TAB_ITEMS} onChange={onTabChange} />
<Space size="small">
<Input.Search
allowClear
enterButton="搜索"
onChange={(event) => setDraftKeyword(event.target.value)}
onClear={() => {
setDraftKeyword("");
onSearchClear();
}}
onSearch={(value) => onSearch(value)}
placeholder="搜索名称或描述"
value={draftKeyword}
/>
{activeTab === "active" && (
<Button icon={<PlusOutlined />} onClick={openCreateDialog} type="primary">
</Button>
)}
</Space>
</Flex>
);
}

View File

@@ -1,8 +1,10 @@
import { Space } from "antd";
import { useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
import { Button, Space } from "antd";
import { useCallback, useMemo, useState } from "react";
import type { Project, ProjectStatus } from "../../../shared/api";
import { FilterToolbar } from "../../shared/components/FilterToolbar";
import {
useArchiveProject,
useCreateProject,
@@ -11,20 +13,40 @@ import {
useRestoreProject,
useUpdateProject,
} from "../../shared/hooks/use-projects";
import { useConfirmAction } from "../../shared/hooks/useConfirmAction";
import { usePageSearchParams } from "../../shared/hooks/usePageSearchParams";
import { ProjectFormModal } from "./components/ProjectFormModal";
import { ProjectTable } from "./components/ProjectTable";
import { ProjectToolbar } from "./components/ProjectToolbar";
const STATUS_OPTIONS = [
{ label: "进行中", value: "active" },
{ label: "已归档", value: "archived" },
];
export function ProjectsPage() {
const [tabValue, setTabValue] = useState<ProjectStatus>("active");
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [keyword, setKeyword] = useState("");
const { confirmAction } = useConfirmAction();
const { params, resetAll, setParams } = usePageSearchParams({
defaults: { page: "1", pageSize: "20" },
});
const [dialogOpen, setDialogOpen] = useState(false);
const [editingProject, setEditingProject] = useState<null | Project>(null);
const { data, isLoading } = useProjectList({ keyword: keyword || undefined, page, pageSize, status: tabValue });
const apiPage = Number(params["page"]) || 1;
const apiPageSize = Number(params["pageSize"]) || 20;
const keyword = params["keyword"] ?? "";
const statusFilter = params["status"] as ProjectStatus | undefined;
const sortBy = params["sortBy"];
const sortOrder = params["sortOrder"];
const { data, isFetching } = useProjectList({
keyword: keyword || undefined,
page: apiPage,
pageSize: apiPageSize,
sortBy: sortBy ?? undefined,
sortOrder: sortOrder,
status: statusFilter,
});
const createMutation = useCreateProject();
const updateMutation = useUpdateProject();
const archiveMutation = useArchiveProject();
@@ -32,54 +54,111 @@ export function ProjectsPage() {
const deleteMutation = useDeleteProject();
const isSubmitting = createMutation.isPending || updateMutation.isPending;
const isRowActionPending = archiveMutation.isPending || restoreMutation.isPending || deleteMutation.isPending;
const handleSearch = useCallback(
(value: string) => {
setParams({ keyword: value || undefined, page: "1" });
},
[setParams],
);
const handleReset = useCallback(() => {
resetAll();
}, [resetAll]);
const handleTableChange = useCallback(
(
pagination: { current?: number; pageSize?: number },
sorter: { columnKey?: string; field?: string | string[]; order?: string },
) => {
const patch: Record<string, string | undefined> = {
page: String(pagination.current ?? apiPage),
pageSize: String(pagination.pageSize ?? apiPageSize),
};
const sortField = sorter.columnKey! ?? (typeof sorter.field === "string" ? sorter.field : undefined);
if (sorter.order && sortField) {
patch["sortBy"] = sortField;
patch["sortOrder"] = sorter.order === "ascend" ? "asc" : "desc";
} else {
patch["sortBy"] = undefined;
patch["sortOrder"] = undefined;
}
setParams(patch);
},
[setParams, apiPage, apiPageSize],
);
const filters = useMemo(
() => [
{
key: "status",
label: "状态",
onChange: (value: string | undefined) => {
setParams({ page: "1", status: value });
},
options: STATUS_OPTIONS,
placeholder: "状态",
value: statusFilter,
},
],
[setParams, statusFilter],
);
const handleArchive = useCallback(
(id: string) => confirmAction(() => archiveMutation.mutateAsync(id), "项目已归档"),
[confirmAction, archiveMutation],
);
const handleRestore = useCallback(
(id: string) => confirmAction(() => restoreMutation.mutateAsync(id), "项目已恢复"),
[confirmAction, restoreMutation],
);
const handleDelete = useCallback(
(id: string) => confirmAction(() => deleteMutation.mutateAsync(id), "项目已永久删除"),
[confirmAction, deleteMutation],
);
return (
<Space className="app-page-flex" orientation="vertical" size="large">
<ProjectToolbar
activeTab={tabValue}
keyword={keyword}
onSearch={(value) => {
setKeyword(value);
setPage(1);
}}
onSearchClear={() => {
setKeyword("");
setPage(1);
}}
onTabChange={(key) => {
setTabValue(key as ProjectStatus);
setPage(1);
}}
openCreateDialog={() => {
setEditingProject(null);
setDialogOpen(true);
}}
<FilterToolbar
actions={
<Button
icon={<PlusOutlined />}
onClick={() => {
setEditingProject(null);
setDialogOpen(true);
}}
type="primary"
>
</Button>
}
filters={filters}
search={{ keyword, onReset: handleReset, onSearch: handleSearch, placeholder: "搜索名称或描述" }}
/>
<ProjectTable
data={data}
loading={isLoading || isRowActionPending}
onArchive={(id) => archiveMutation.mutateAsync(id)}
onDelete={(id) => deleteMutation.mutateAsync(id)}
loading={isFetching}
onArchive={handleArchive}
onChange={handleTableChange}
onDelete={handleDelete}
onEdit={(project) => {
setEditingProject(project);
setDialogOpen(true);
}}
onPageChange={(p, ps) => {
setPage(p);
setPageSize(ps);
}}
onRestore={(id) => restoreMutation.mutateAsync(id)}
page={page}
pageSize={pageSize}
status={tabValue}
onRestore={handleRestore}
page={apiPage}
pageSize={apiPageSize}
sortBy={sortBy}
sortOrder={sortOrder}
/>
<ProjectFormModal
editingProject={editingProject}
onCancel={() => setDialogOpen(false)}
onCreate={(data) => createMutation.mutateAsync(data)}
onCreate={(formData) => createMutation.mutateAsync(formData)}
onOpenChange={setDialogOpen}
onUpdate={(args) => updateMutation.mutateAsync(args)}
open={dialogOpen}