Skip to content

Commit

Permalink
增加搜索,分页和性能优化
Browse files Browse the repository at this point in the history
  • Loading branch information
wanghao1993 committed Sep 9, 2024
1 parent 6563890 commit 0bec0a1
Show file tree
Hide file tree
Showing 9 changed files with 171 additions and 19 deletions.
11 changes: 6 additions & 5 deletions app/api/blog/detail/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { BusinessCode, responseHandler } from "@/lib/fetch_utils";
import prisma from "@/lib/pg";
import { PostTypes } from "@/types/post";
import { getServerSession } from "next-auth";
import { getSession } from "next-auth/react";

import { authOptions } from "@/lib/auth_options";
export const dynamic = "force-dynamic"; // defaults to auto
export async function GET(request: Request) {
const key = new URL(request.url).searchParams.get("key");
Expand Down Expand Up @@ -40,16 +41,16 @@ export async function GET(request: Request) {
}
}

export async function POST(request: Request) {
const body: PostTypes.PostDetail = await request.json();
const session = await getSession();
export async function POST(req: Request, res: Response) {
const body: PostTypes.PostDetail = await req.json();
const session = await getServerSession(authOptions);
const post = await prisma.post.findUnique({
where: {
blog_key: body.blog_key,
},
});

if (post && session?.user.email) {
if (post && session?.user) {
const user = await prisma.user.findUnique({
where: {
email: session.user.email,
Expand Down
82 changes: 75 additions & 7 deletions app/blog/page.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,90 @@
import ArticleItem from "@/components/Article/ArticleItem";
"use client";
import ArticleList from "@/components/Article/ArticleList";
import MainLayout from "@/components/Layouts/MainLayout";
import { getAllPostsMeta } from "data/utils";
import Tags from "@/components/blog/Tags";
import Category from "@/components/blog/Categories";
import { memo, useEffect, useMemo, useState } from "react";
import { Post } from "contentlayer/generated";
import Pagination from "@/components/pagination";

export default async function BlogHomePage() {
const MemoCategory = memo(Category);
const MemoTags = memo(Tags);
const MemoPagination = memo(Pagination);
const MemoList = memo(ArticleList);
export default function BlogHomePage() {
const list = getAllPostsMeta();

const [searchValue, setSearchValue] = useState("");

const [renderList, setRenderList] = useState<Post[]>([]);
const pageSize = 5;
const [curPage, setCurPage] = useState(1);
const [totalPage, setTotalPage] = useState(1);

useEffect(() => {
setCurPage(1);
}, [searchValue]);
useEffect(() => {
setRenderList(
list.filter(
(item) =>
item.title.toLowerCase().includes(searchValue) ||
item.tags.toLowerCase().includes(searchValue) ||
item.categories.toLowerCase().includes(searchValue) ||
item.description.toLowerCase().includes(searchValue)
)
);
}, [searchValue, list, curPage]);

const [posts, setPost] = useState<Post[]>([]);

const memoPost = useMemo(() => posts, [posts]);

useEffect(() => {
setPost(renderList.slice((curPage - 1) * pageSize, curPage * pageSize));
}, [curPage, renderList]);

useEffect(() => {
setTotalPage(Math.ceil(renderList.length / pageSize));
}, [renderList]);
return (
<MainLayout>
<div className="flex flex-col lg:flex-row gap-8">
<div className="lg:w-3/4 space-y-4">
{list.map((item) => (
<ArticleItem articleInfo={item} key={item.key} />
))}
<div className="relative max-w-full">
<input
aria-label="Search articles"
type="text"
onChange={(e) => setSearchValue(e.target.value)}
placeholder="输入标题,标签,分类,描述查询"
className="block w-full rounded-md border-0 bg-gray-200 bg-opacity-50 px-4 py-3 text-gray-900 focus:border-sky-500 focus:ring-sky-500 dark:border-gray-900 dark:bg-gray-800 dark:text-gray-100"
/>
<svg
className="absolute right-3 top-3 h-6 w-6 text-gray-400 dark:text-gray-300"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
</div>
<MemoList posts={memoPost} />
<MemoPagination
currentPage={curPage}
pageChange={setCurPage}
totalPages={totalPage}
/>
</div>
<div className="lg:w-1/4 space-y-4">
<Category />
<Tags />
<MemoCategory />
<MemoTags />
</div>
</div>
</MainLayout>
Expand Down
1 change: 0 additions & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import LenisProvider from "@/components/Providers/LenisProvider";
import ThemeProvider from "@/components/Providers/ThemeProvider";
import "./ui/globals.scss";
import Header from "@/components/Header";
import { AntdRegistry } from "@ant-design/nextjs-registry";
import { content } from "@/lib/font";
import Footer from "@/components/Footer";
Expand Down
17 changes: 17 additions & 0 deletions components/Article/ArticleList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Post } from "./../../.contentlayer/generated";
import React, { memo, useEffect } from "react";
import ArticleItem from "./ArticleItem";
interface Props {
posts: Post[];
}
const ArticleList = ({ posts }: Props) => {
return (
<>
{posts.map((item) => (
<ArticleItem articleInfo={item} key={item.key} />
))}
</>
);
};

export default ArticleList;
6 changes: 3 additions & 3 deletions components/MobileNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { MenuOutlined, CloseOutlined } from "@ant-design/icons";
import LoginModal from "./login/page";
import { signOut, useSession } from "next-auth/react";
import Image from "next/image";
import useLoginModal from "./LoginModal";
const headerNavLinks = [
{
title: "博客",
Expand Down Expand Up @@ -38,11 +37,12 @@ export default function MobileNav() {
}
}, [navShow]);

const [setVisible] = useLoginModal();

const [visible, setVisible] = useState(false);
const { data: session, status } = useSession();
return (
<div className="sm:hidden">
<LoginModal open={visible} onClose={() => setVisible(false)}></LoginModal>

<button
type="button"
className="ml-1 flex justify-center items-center mr-1 h-8 w-8 rounded py-1"
Expand Down
4 changes: 2 additions & 2 deletions components/blog/Categories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ const getCategory = () => {
return getAllCategory();
};

export default async function Category() {
export default function Category() {
const categories = getCategory();

console.log("render");
return (
<div className="border rounded-lg">
<h2 className="px-4 py-2 border-b">分类</h2>
Expand Down
2 changes: 1 addition & 1 deletion components/blog/Tags.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Link from "next/link";
const getTags = () => {
return getAllTags();
};
export default async function Tags() {
export default function Tags() {
const tags = getTags();

return (
Expand Down
61 changes: 61 additions & 0 deletions components/pagination.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React from "react";

interface Props {
totalPages: number;
currentPage: number;
pageChange: (num: number) => void;
}

export default function Pagination({
totalPages,
currentPage,
pageChange,
}: Props) {
const prevPage = currentPage - 1 > 0;
const nextPage = currentPage + 1 <= totalPages;

return (
<div className="space-y-2 md:space-y-5">
<nav className="flex justify-between">
{!prevPage && (
<button
className="cursor-auto disabled:opacity-50"
disabled={!prevPage}
>
上一页
</button>
)}
{prevPage && (
<button
onClick={() => pageChange(currentPage > 1 ? currentPage - 1 : 1)}
>
{" "}
上一页
</button>
)}
<span>
{currentPage} of {totalPages}
</span>
{!nextPage && (
<button
className="cursor-auto disabled:opacity-50"
disabled={!nextPage}
>
下一页
</button>
)}
{nextPage && (
<button
onClick={() =>
pageChange(
currentPage < totalPages ? currentPage + 1 : totalPages
)
}
>
下一页
</button>
)}
</nav>
</div>
);
}
6 changes: 6 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@
"incremental": true,
"baseUrl": "./",
"paths": {
"@/content/*": [
"content/*"
],
"@/layouts/*": [
"components/layouts/*"
],
"contentlayer/generated": [
"./.contentlayer/generated"
],
Expand Down

0 comments on commit 0bec0a1

Please sign in to comment.