add pagination

This commit is contained in:
yoan
2024-09-02 22:55:17 +08:00
23 changed files with 1224 additions and 329 deletions

View File

@@ -0,0 +1,173 @@
import { Input } from "@/components/ui/input";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import z from "zod";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { Access, accessFormType, CloudflareConfig } from "@/domain/access";
import { save } from "@/repository/access";
import { useConfig } from "@/providers/config";
import { ClientResponseError } from "pocketbase";
import { PbErrorData } from "@/domain/base";
const AccessCloudflareForm = ({
data,
onAfterReq,
}: {
data?: Access;
onAfterReq: () => void;
}) => {
const { addAccess, updateAccess } = useConfig();
const formSchema = z.object({
id: z.string().optional(),
name: z.string().min(1).max(64),
configType: accessFormType,
dnsApiToken: z.string().min(1).max(64),
});
let config: CloudflareConfig = {
dnsApiToken: "",
};
if (data) config = data.config as CloudflareConfig;
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
id: data?.id,
name: data?.name,
configType: "cloudflare",
dnsApiToken: config.dnsApiToken,
},
});
const onSubmit = async (data: z.infer<typeof formSchema>) => {
console.log(data);
const req: Access = {
id: data.id as string,
name: data.name,
configType: data.configType,
config: {
dnsApiToken: data.dnsApiToken,
},
};
try {
const rs = await save(req);
onAfterReq();
req.id = rs.id;
req.created = rs.created;
req.updated = rs.updated;
if (data.id) {
updateAccess(req);
return;
}
addAccess(req);
} catch (e) {
const err = e as ClientResponseError;
Object.entries(err.response.data as PbErrorData).forEach(
([key, value]) => {
form.setError(key as keyof z.infer<typeof formSchema>, {
type: "manual",
message: value.message,
});
}
);
}
};
return (
<>
<div className="max-w-[35em] mx-auto mt-10">
<Form {...form}>
<form
onSubmit={(e) => {
console.log(e);
e.stopPropagation();
form.handleSubmit(onSubmit)(e);
}}
className="space-y-8"
>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input placeholder="请输入授权名称" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="id"
render={({ field }) => (
<FormItem className="hidden">
<FormLabel></FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="configType"
render={({ field }) => (
<FormItem className="hidden">
<FormLabel></FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dnsApiToken"
render={({ field }) => (
<FormItem>
<FormLabel>CLOUD_DNS_API_TOKEN</FormLabel>
<FormControl>
<Input placeholder="请输入CLOUD_DNS_API_TOKEN" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-end">
<Button type="submit"></Button>
</div>
</form>
</Form>
</div>
</>
);
};
export default AccessCloudflareForm;

View File

@@ -15,10 +15,19 @@ import { Label } from "../ui/label";
import { Access, accessTypeMap } from "@/domain/access";
import AccessAliyunForm from "./AccessAliyunForm";
import { cn } from "@/lib/utils";
import { RadioGroup, RadioGroupItem } from "../ui/radio-group";
import AccessSSHForm from "./AccessSSHForm";
import WebhookForm from "./AccessWebhookFrom";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "../ui/select";
import AccessCloudflareForm from "./AccessCloudflareForm";
type TargetConfigEditProps = {
op: "add" | "edit";
@@ -79,6 +88,17 @@ export function AccessEdit({
}}
/>
);
break;
case "cloudflare":
form = (
<AccessCloudflareForm
data={data}
onAfterReq={() => {
setOpen(false);
}}
/>
);
break;
}
const getOptionCls = (val: string) => {
@@ -96,31 +116,38 @@ export function AccessEdit({
</DialogHeader>
<div className="container">
<Label></Label>
<RadioGroup
value={configType}
className="flex mt-3 space-x-2"
<Select
onValueChange={(val) => {
console.log(val);
setConfigType(val);
}}
>
{typeKeys.map((key) => (
<div className="flex items-center space-x-2" key={key}>
<Label>
<RadioGroupItem value={key} hidden />
<div
className={cn(
"flex items-center space-x-2 border p-2 rounded cursor-pointer",
getOptionCls(key)
)}
>
<img src={accessTypeMap.get(key)?.[1]} className="h-6" />
<div>{accessTypeMap.get(key)?.[0]}</div>
</div>
</Label>
</div>
))}
</RadioGroup>
<SelectTrigger className="mt-3">
<SelectValue placeholder="请选择服务商" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel></SelectLabel>
{typeKeys.map((key) => (
<SelectItem value={key}>
<div
className={cn(
"flex items-center space-x-2 rounded cursor-pointer",
getOptionCls(key)
)}
>
<img
src={accessTypeMap.get(key)?.[1]}
className="h-6 w-6"
/>
<div>{accessTypeMap.get(key)?.[0]}</div>
</div>
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
{form}
</div>

View File

@@ -1,4 +1,10 @@
import { Button } from "../ui/button";
import {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
} from "../ui/pagination";
type PaginationProps = {
totalPages: number;
@@ -8,12 +14,12 @@ type PaginationProps = {
type PageNumber = number | string;
const Pagination = ({
const XPagination = ({
totalPages,
currentPage,
onPageChange,
}: PaginationProps) => {
const pageNeighbours = 2; // Number of page numbers to show on either side of the current page
const pageNeighbours = 1; // Number of page numbers to show on either side of the current page
const getPageNumbers = () => {
const totalNumbers = pageNeighbours * 2 + 3; // total pages to display (left + right neighbours + current + 2 for start and end)
@@ -60,31 +66,37 @@ const Pagination = ({
const pages = getPageNumbers();
return (
<div className="pagination dark:text-stone-200">
{pages.map((page, index) => {
if (page === "...") {
return (
<span key={index} className="pagination-ellipsis">
&hellip;
</span>
);
}
<>
<Pagination className="dark:text-stone-200 justify-end mt-3">
<PaginationContent>
{pages.map((page, index) => {
if (page === "...") {
return (
<PaginationItem key={index}>
<PaginationEllipsis />
</PaginationItem>
);
}
return (
<Button
key={index}
className={`pagination-button ${
currentPage === page ? "active" : ""
}`}
variant={currentPage === page ? "default" : "outline"}
onClick={() => onPageChange(page as number)}
>
{page}
</Button>
);
})}
</div>
return (
<PaginationItem key={index}>
<PaginationLink
href="#"
isActive={currentPage == page}
onClick={(e) => {
e.preventDefault();
onPageChange(page as number);
}}
>
{page}
</PaginationLink>
</PaginationItem>
);
})}
</PaginationContent>
</Pagination>
</>
);
};
export default Pagination;
export default XPagination;

View File

@@ -3,6 +3,7 @@ import { z } from "zod";
export const accessTypeMap: Map<string, [string, string]> = new Map([
["tencent", ["腾讯云", "/imgs/providers/tencent.svg"]],
["aliyun", ["阿里云", "/imgs/providers/aliyun.svg"]],
["cloudflare", ["Cloudflare", "/imgs/providers/cloudflare.svg"]],
["ssh", ["SSH部署", "/imgs/providers/ssh.svg"]],
["webhook", ["Webhook", "/imgs/providers/webhook.svg"]],
]);
@@ -13,6 +14,7 @@ export const accessFormType = z.union(
z.literal("tencent"),
z.literal("ssh"),
z.literal("webhook"),
z.literal("cloudflare"),
],
{ message: "请选择云服务商" }
);
@@ -21,7 +23,12 @@ export type Access = {
id: string;
name: string;
configType: string;
config: TencentConfig | AliyunConfig | SSHConfig | WebhookConfig;
config:
| TencentConfig
| AliyunConfig
| SSHConfig
| WebhookConfig
| CloudflareConfig;
deleted?: string;
created?: string;
updated?: string;
@@ -31,6 +38,10 @@ export type WebhookConfig = {
url: string;
};
export type CloudflareConfig = {
dnsApiToken: string;
};
export type TencentConfig = {
secretId: string;
secretKey: string;

View File

@@ -22,6 +22,7 @@ import { cn } from "@/lib/utils";
import { ConfigProvider } from "@/providers/config";
import { getPb } from "@/repository/api";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Separator } from "@/components/ui/separator";
export default function Dashboard() {
const navigate = useNavigate();
@@ -184,12 +185,16 @@ export default function Dashboard() {
<div className="fixed right-0 bottom-0 w-full flex justify-between p-5">
<div className=""></div>
<div className="text-muted-foreground text-sm hover:text-stone-900 dark:hover:text-stone-200">
<div className="text-muted-foreground text-sm hover:text-stone-900 dark:hover:text-stone-200 flex">
<a href="https://docs.certimate.me" target="_blank">
</a>
<Separator orientation="vertical" className="mx-2" />
<a
href="https://github.com/usual2970/certimate/releases"
target="_blank"
>
Certimate v0.0.10
Certimate v0.0.14
</a>
</div>
</div>

View File

@@ -1,4 +1,5 @@
import { AccessEdit } from "@/components/certimate/AccessEdit";
import XPagination from "@/components/certimate/XPagination";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Access as AccessType, accessTypeMap } from "@/domain/access";
@@ -6,11 +7,25 @@ import { convertZulu2Beijing } from "@/lib/time";
import { useConfig } from "@/providers/config";
import { remove } from "@/repository/access";
import { Key } from "lucide-react";
import { useLocation, useNavigate } from "react-router-dom";
const Access = () => {
const { config, deleteAccess } = useConfig();
const { accesses } = config;
const perPage = 10;
const totalPages = Math.ceil(accesses.length / perPage);
const navigate = useNavigate();
const location = useLocation();
const query = new URLSearchParams(location.search);
const page = query.get("page");
const pageNumber = page ? Number(page) : 1;
const startIndex = (pageNumber - 1) * perPage;
const endIndex = startIndex + perPage;
const handleDelete = async (data: AccessType) => {
const rs = await remove(data);
deleteAccess(rs.id);
@@ -50,7 +65,7 @@ const Access = () => {
<div className="sm:hidden flex text-sm text-muted-foreground">
</div>
{accesses.map((access) => (
{accesses.slice(startIndex, endIndex).map((access) => (
<div
className="flex flex-col sm:flex-row text-secondary-foreground border-b dark:border-stone-500 sm:p-2 hover:bg-muted/50 text-sm"
key={access.id}
@@ -95,6 +110,14 @@ const Access = () => {
</div>
</div>
))}
<XPagination
totalPages={totalPages}
currentPage={pageNumber}
onPageChange={(page) => {
query.set("page", page.toString());
navigate({ search: query.toString() });
}}
/>
</>
)}
</div>

View File

@@ -1,5 +1,5 @@
import DeployProgress from "@/components/certimate/DeployProgress";
import Pagination from "@/components/certimate/Pagination";
import XPagination from "@/components/certimate/XPagination";
import Show from "@/components/Show";
import {
AlertDialogAction,
@@ -33,16 +33,28 @@ import {
import { TooltipContent, TooltipProvider } from "@radix-ui/react-tooltip";
import { CircleCheck, CircleX, Earth } from "lucide-react";
import { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Link, useLocation, useNavigate } from "react-router-dom";
const Home = () => {
const toast = useToast();
const navigate = useNavigate();
const location = useLocation();
const query = new URLSearchParams(location.search);
const page = query.get("page");
const [totalPage, setTotalPage] = useState(0);
const handleCreateClick = () => {
navigate("/edit");
};
const setPage = (newPage: number) => {
query.set("page", newPage.toString());
navigate(`?${query.toString()}`);
};
const handleEditClick = (id: string) => {
navigate(`/edit?id=${id}`);
};
@@ -64,11 +76,16 @@ const Home = () => {
useEffect(() => {
const fetchData = async () => {
const data = await list();
setDomains(data);
const data = await list({
page: page ? Number(page) : 1,
perPage: 10,
});
setDomains(data.items);
setTotalPage(data.totalPages);
};
fetchData();
}, []);
}, [page]);
const handelCheckedChange = async (id: string) => {
const checkedDomains = domains.filter((domain) => domain.id === id);
@@ -325,11 +342,11 @@ const Home = () => {
</div>
))}
<Pagination
totalPages={1000}
currentPage={3}
<XPagination
totalPages={totalPage}
currentPage={page ? Number(page) : 1}
onPageChange={(page) => {
console.log(page);
setPage(page);
}}
/>
</>

View File

@@ -1,11 +1,28 @@
import { Domain } from "@/domain/domain";
import { getPb } from "./api";
export const list = async () => {
const response = getPb().collection("domains").getFullList<Domain>({
sort: "-created",
expand: "lastDeployment",
});
type DomainListReq = {
domain?: string;
page?: number;
perPage?: number;
};
export const list = async (req: DomainListReq) => {
let page = 1;
if (req.page) {
page = req.page;
}
let perPage = 2;
if (req.perPage) {
perPage = req.perPage;
}
const response = getPb()
.collection("domains")
.getList<Domain>(page, perPage, {
sort: "-created",
expand: "lastDeployment",
});
return response;
};