Refactor code structure for improved readability and maintainability

This commit is contained in:
2026-03-11 17:02:31 +07:00
parent 1139125460
commit 5686753ab7
42 changed files with 4659 additions and 309 deletions
+40 -14
View File
@@ -62,9 +62,11 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
// Extract paragraphs for TTS
const paragraphs = chapter.content.split("\n").map((p: string) => p.trim()).filter(Boolean)
const chapterLabel = (chapter as any).volumeChapterNumber ? `Chương ${(chapter as any).volumeChapterNumber}` : `Chương ${chapter.number}`
const volumeLabel = (chapter as any).volumeTitle || ((chapter as any).volumeNumber ? `Quyển ${(chapter as any).volumeNumber}` : null)
return (
<div className="mx-auto max-w-4xl lg:max-w-screen-lg px-4 py-6 md:px-8">
<div className="mx-auto max-w-4xl px-3 py-4 md:px-8 md:py-6 lg:max-w-screen-lg">
{/* Top navigation */}
<div className="mb-6 flex flex-col gap-3">
<Link href={`/truyen/${slug}`} className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors">
@@ -73,20 +75,26 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
<div className="flex items-center justify-between gap-2">
<h1 className="text-lg font-bold text-foreground md:text-xl lg:text-2xl">
Chương {chapter.number}: {chapter.title}
{volumeLabel ? `${volumeLabel} - ` : ""}{chapterLabel}: {chapter.title}
</h1>
</div>
</div>
{/* Chapter navigation top */}
<div className="mb-6 flex items-center justify-between">
<div className="mb-6 flex items-center justify-between gap-2">
<Button variant="outline" size="sm" disabled={!hasPrev} asChild={hasPrev}>
{hasPrev ? (
<Link href={`/truyen/${slug}/${chapterNumber - 1}`}>
<ChevronLeft className="mr-1 h-4 w-4" /> Ch. trước
<ChevronLeft className="mr-1 h-4 w-4" />
<span className="hidden sm:inline">Ch. trước</span>
<span className="sm:hidden">Trước</span>
</Link>
) : (
<span><ChevronLeft className="mr-1 h-4 w-4" /> Ch. trước</span>
<span>
<ChevronLeft className="mr-1 h-4 w-4" />
<span className="hidden sm:inline">Ch. trước</span>
<span className="sm:hidden">Trước</span>
</span>
)}
</Button>
<Button variant="outline" size="sm" asChild>
@@ -97,16 +105,22 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
<Button variant="outline" size="sm" disabled={!hasNext} asChild={hasNext}>
{hasNext ? (
<Link href={`/truyen/${slug}/${chapterNumber + 1}`}>
Ch. sau <ChevronRight className="ml-1 h-4 w-4" />
<span className="hidden sm:inline">Ch. sau</span>
<span className="sm:hidden">Sau</span>
<ChevronRight className="ml-1 h-4 w-4" />
</Link>
) : (
<span>Ch. sau <ChevronRight className="ml-1 h-4 w-4" /></span>
<span>
<span className="hidden sm:inline">Ch. sau</span>
<span className="sm:hidden">Sau</span>
<ChevronRight className="ml-1 h-4 w-4" />
</span>
)}
</Button>
</div>
{/* Chapter content */}
<article className="chapter-content mb-8 rounded-lg border border-border bg-card p-6 font-serif text-foreground/90 md:p-8 lg:p-12 text-justify">
<article className="chapter-content mb-8 rounded-lg border border-border bg-card p-4 font-serif text-foreground/90 text-justify md:p-8 lg:p-12">
{paragraphs.map((text: string, idx: number) => (
<p key={idx} data-p-index={idx} className="mb-4 last:mb-0">
{text}
@@ -115,23 +129,35 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
</article>
{/* Chapter navigation bottom */}
<div className="mb-8 flex items-center justify-between">
<div className="mb-8 flex items-center justify-between gap-2">
<Button variant="outline" size="sm" disabled={!hasPrev} asChild={hasPrev}>
{hasPrev ? (
<Link href={`/truyen/${slug}/${chapterNumber - 1}`}>
<ChevronLeft className="mr-1 h-4 w-4" /> Chương trước
<ChevronLeft className="mr-1 h-4 w-4" />
<span className="hidden sm:inline">Chương trước</span>
<span className="sm:hidden">Trước</span>
</Link>
) : (
<span><ChevronLeft className="mr-1 h-4 w-4" /> Chương trước</span>
<span>
<ChevronLeft className="mr-1 h-4 w-4" />
<span className="hidden sm:inline">Chương trước</span>
<span className="sm:hidden">Trước</span>
</span>
)}
</Button>
<Button variant="outline" size="sm" disabled={!hasNext} asChild={hasNext}>
{hasNext ? (
<Link href={`/truyen/${slug}/${chapterNumber + 1}`}>
Chương sau <ChevronRight className="ml-1 h-4 w-4" />
<span className="hidden sm:inline">Chương sau</span>
<span className="sm:hidden">Sau</span>
<ChevronRight className="ml-1 h-4 w-4" />
</Link>
) : (
<span>Chương sau <ChevronRight className="ml-1 h-4 w-4" /></span>
<span>
<span className="hidden sm:inline">Chương sau</span>
<span className="sm:hidden">Sau</span>
<ChevronRight className="ml-1 h-4 w-4" />
</span>
)}
</Button>
</div>
@@ -151,7 +177,7 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
paragraphs={paragraphs}
currentChapter={chapterNumber}
maxChapter={maxChapter}
chapterTitle={`Chương ${chapter.number}: ${chapter.title}`}
chapterTitle={`${volumeLabel ? `${volumeLabel} - ` : ""}${chapterLabel}: ${chapter.title}`}
/>
</div>
)
+108 -42
View File
@@ -10,6 +10,7 @@ import { NovelDetailActions } from "./novel-detail-actions"
import { prisma } from "@/lib/prisma"
import connectToMongoDB from "@/lib/mongoose"
import { Chapter } from "@/lib/models/chapter"
import { getNovelStatusBadgeClass } from "@/lib/novel-status"
export const dynamic = "force-dynamic"
@@ -39,32 +40,72 @@ export default async function NovelDetailPage({
notFound()
}
// Fetch chapters from MongoDB
let formattedChapters: any[] = []
let totalChapters = 0
let totalPages = 1
let firstChapterNumber: number | undefined
let seriesVolumes: Array<{
id: string
slug: string
title: string
status: string
totalChapters: number
coverUrl: string | null
updatedAt: Date
}> = []
await connectToMongoDB()
const skip = (currentPage - 1) * limit
const [chapters, totalChapters] = await Promise.all([
Chapter.find({ novelId: novel.id })
.sort({ number: 1 })
.skip(skip)
.limit(limit)
.select("id novelId number title createdAt views")
.lean(),
Chapter.countDocuments({ novelId: novel.id })
])
if (novel.seriesId) {
const [firstChapter, volumes] = await Promise.all([
Chapter.findOne({ novelId: novel.id }).sort({ number: 1 }).select("number").lean(),
prisma.novel.findMany({
where: { seriesId: novel.seriesId },
select: {
id: true,
slug: true,
title: true,
status: true,
totalChapters: true,
coverUrl: true,
updatedAt: true,
},
orderBy: { createdAt: "asc" },
}),
])
const totalPages = Math.ceil(totalChapters / limit)
firstChapterNumber = (firstChapter as any)?.number
seriesVolumes = volumes
} else {
const skip = (currentPage - 1) * limit
const [chapters, chaptersCount, firstChapter] = await Promise.all([
Chapter.find({ novelId: novel.id })
.sort({ number: 1 })
.skip(skip)
.limit(limit)
.select("id novelId number title createdAt views volumeNumber volumeTitle volumeChapterNumber")
.lean(),
Chapter.countDocuments({ novelId: novel.id }),
Chapter.findOne({ novelId: novel.id }).sort({ number: 1 }).select("number").lean(),
])
// Convert Mongoose documents to plain objects for Server Component
const formattedChapters = chapters.map(c => ({
id: c._id.toString(),
novelId: c.novelId,
number: c.number,
title: c.title,
createdAt: (c.createdAt as Date).toISOString(),
views: c.views || 0,
content: "" // We don't fetch content for the list
}))
totalChapters = chaptersCount
totalPages = Math.ceil(totalChapters / limit)
firstChapterNumber = (firstChapter as any)?.number
formattedChapters = chapters.map(c => ({
id: c._id.toString(),
novelId: c.novelId,
number: c.number,
volumeNumber: (c as any).volumeNumber ?? null,
volumeTitle: (c as any).volumeTitle ?? null,
volumeChapterNumber: (c as any).volumeChapterNumber ?? null,
title: c.title,
createdAt: (c.createdAt as Date).toISOString(),
views: c.views || 0,
content: ""
}))
}
const commentsData = await prisma.comment.findMany({
where: { novelId: novel.id, chapterId: null },
@@ -107,7 +148,7 @@ export default async function NovelDetailPage({
{/* Novel Header */}
<div className="flex flex-col gap-6 md:flex-row">
{/* Cover */}
<img src={novel.coverUrl || "/default-cover.svg"} alt={novel.title} className="h-64 w-44 shrink-0 self-center rounded-xl object-cover shadow-lg md:self-start bg-muted" />
<img src={novel.coverUrl || "/default-cover.svg"} alt={novel.title} className="h-64 w-44 shrink-0 self-center rounded-xl bg-muted object-contain shadow-lg md:self-start" />
{/* Info */}
<div className="flex flex-1 flex-col gap-3">
@@ -132,11 +173,7 @@ export default async function NovelDetailPage({
<div className="flex flex-col gap-3 mt-3">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-muted-foreground">Trạng thái:</span>
<span className={`inline-block rounded-full px-4 py-1.5 text-xs font-semibold ${
novel.status === "Hoàn thành" ? "bg-green-500/10 text-green-600 dark:text-green-400" :
novel.status === "Tạm dừng" || novel.status === "Tạm ngưng" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" :
"bg-primary/10 text-primary" // Đang ra
}`}>
<span className={`inline-block rounded-full px-4 py-1.5 text-xs font-semibold ${getNovelStatusBadgeClass(novel.status)}`}>
{novel.status}
</span>
</div>
@@ -177,7 +214,7 @@ export default async function NovelDetailPage({
</div>
<div className="mt-4">
<NovelDetailActions novelId={novel.id} novelSlug={novel.slug} firstChapterNumber={formattedChapters[0]?.number} />
<NovelDetailActions novelId={novel.id} novelSlug={novel.slug} firstChapterNumber={firstChapterNumber} />
</div>
</div>
</div>
@@ -188,19 +225,48 @@ export default async function NovelDetailPage({
<div className="text-sm leading-relaxed text-foreground/80 whitespace-pre-wrap">{novel.description}</div>
</section>
{/* Chapter list */}
<section className="mt-8">
<h2 className="mb-3 text-lg font-bold text-foreground">Danh Sách Chương</h2>
<div className="rounded-lg border border-border bg-card">
<ChapterList
chapters={formattedChapters as any}
novelSlug={novel.slug}
currentPage={currentPage}
totalPages={totalPages}
totalChapters={totalChapters}
/>
</div>
</section>
{/* Chapter list or series volumes */}
{novel.seriesId ? (
<section className="mt-8">
<h2 className="mb-3 text-lg font-bold text-foreground">Danh Sách Quyển</h2>
<div className="rounded-lg border border-border bg-card divide-y divide-border">
{seriesVolumes.map((volume, idx) => (
<Link
key={volume.id}
href={`/truyen/${volume.slug}`}
className={`flex items-center gap-4 px-4 py-3 hover:bg-muted/40 transition-colors ${volume.id === novel.id ? "bg-primary/5" : ""}`}
>
<span className="w-8 text-center text-sm font-semibold text-muted-foreground">{idx + 1}</span>
<img
src={volume.coverUrl || "/default-cover.svg"}
alt={volume.title}
className="h-14 w-10 rounded bg-muted object-contain"
/>
<div className="min-w-0 flex-1">
<p className="font-medium text-foreground truncate">{volume.title}</p>
<p className="text-xs text-muted-foreground">{volume.totalChapters} chương</p>
</div>
<span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold ${getNovelStatusBadgeClass(volume.status)}`}>
{volume.status}
</span>
</Link>
))}
</div>
</section>
) : (
<section className="mt-8">
<h2 className="mb-3 text-lg font-bold text-foreground">Danh Sách Chương</h2>
<div className="rounded-lg border border-border bg-card">
<ChapterList
chapters={formattedChapters as any}
novelSlug={novel.slug}
currentPage={currentPage}
totalPages={totalPages}
totalChapters={totalChapters}
/>
</div>
</section>
)}
{/* Comments */}
<section className="mt-8">