Refactor code structure for improved readability and maintainability

This commit is contained in:
2026-03-23 11:12:56 +07:00
parent e345d9ccce
commit ffd177718f
39 changed files with 5258 additions and 520 deletions
+184
View File
@@ -0,0 +1,184 @@
"use client"
import { useMemo, useState } from "react"
import Link from "next/link"
import { ChevronLeft, ChevronRight, Star } from "lucide-react"
import { Button } from "@/components/ui/button"
type RecommendationNovel = {
id: string
slug: string
title: string
authorName: string
coverUrl: string | null
rating: number
}
type TopRecommendationItem = {
novel: RecommendationNovel
recommendCount: number
}
type EditorRecommendationItem = {
novel: RecommendationNovel
editorName: string
recommendCount: number
}
interface HomeRecommendationBoardsProps {
topItems: TopRecommendationItem[]
editorItems: EditorRecommendationItem[]
pageSize?: number
}
function BoardHeader({
title,
page,
totalPages,
onPrev,
onNext,
}: {
title: string
page: number
totalPages: number
onPrev: () => void
onNext: () => void
}) {
return (
<div className="mb-4 flex items-center justify-between">
<h2 className="text-xl font-bold text-foreground">{title}</h2>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="icon"
className="h-7 w-7"
onClick={onPrev}
disabled={totalPages <= 1 || page === 0}
aria-label="Trang trước"
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
className="h-7 w-7"
onClick={onNext}
disabled={totalPages <= 1 || page >= totalPages - 1}
aria-label="Trang sau"
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)
}
export function HomeRecommendationBoards({ topItems, editorItems, pageSize = 5 }: HomeRecommendationBoardsProps) {
const [topPage, setTopPage] = useState(0)
const [editorPage, setEditorPage] = useState(0)
const sortedTopItems = useMemo(() => {
return [...topItems].sort((a, b) => b.recommendCount - a.recommendCount)
}, [topItems])
const sortedEditorItems = useMemo(() => {
return [...editorItems].sort((a, b) => {
if (b.recommendCount !== a.recommendCount) return b.recommendCount - a.recommendCount
return a.editorName.localeCompare(b.editorName, "vi")
})
}, [editorItems])
const totalTopPages = Math.max(1, Math.ceil(sortedTopItems.length / pageSize))
const totalEditorPages = Math.max(1, Math.ceil(sortedEditorItems.length / pageSize))
const topPageStart = topPage * pageSize
const editorPageStart = editorPage * pageSize
const visibleTopItems = sortedTopItems.slice(topPageStart, topPageStart + pageSize)
const visibleEditorItems = sortedEditorItems.slice(editorPageStart, editorPageStart + pageSize)
return (
<section className="grid gap-6 lg:grid-cols-2">
<div className="rounded-2xl border border-border/70 bg-card/70 p-4">
<BoardHeader
title="Top đề cử"
page={topPage}
totalPages={totalTopPages}
onPrev={() => setTopPage((prev) => Math.max(0, prev - 1))}
onNext={() => setTopPage((prev) => Math.min(totalTopPages - 1, prev + 1))}
/>
<div className="space-y-2">
{visibleTopItems.length > 0 ? visibleTopItems.map((item, index) => (
<Link
key={item.novel.id}
href={`/truyen/${item.novel.slug}`}
className="group flex items-center gap-3 rounded-xl border border-border bg-background/80 p-2.5 transition hover:border-primary/40"
>
<span className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/15 text-xs font-bold text-primary">
{topPageStart + index + 1}
</span>
<img
src={item.novel.coverUrl || "/default-cover.svg"}
alt={item.novel.title}
className="h-20 w-14 shrink-0 rounded-md border border-border/70 object-cover"
/>
<div className="min-w-0 flex-1">
<h3 className="line-clamp-1 text-sm font-semibold text-foreground group-hover:text-primary">{item.novel.title}</h3>
<p className="text-xs text-muted-foreground">{item.novel.authorName}</p>
<p className="mt-1 text-xs text-muted-foreground">{item.recommendCount} đ cử</p>
</div>
<div className="inline-flex items-center gap-1 text-xs font-semibold text-primary">
<Star className="h-3.5 w-3.5 fill-primary text-primary" />
{item.novel.rating.toFixed(1)}
</div>
</Link>
)) : (
<p className="text-sm text-muted-foreground">Chưa truyện đ cử.</p>
)}
</div>
</div>
<div className="rounded-2xl border border-border/70 bg-card/70 p-4">
<BoardHeader
title="Biên tập viên đề cử"
page={editorPage}
totalPages={totalEditorPages}
onPrev={() => setEditorPage((prev) => Math.max(0, prev - 1))}
onNext={() => setEditorPage((prev) => Math.min(totalEditorPages - 1, prev + 1))}
/>
<div className="space-y-2">
{visibleEditorItems.length > 0 ? visibleEditorItems.map((item, index) => (
<Link
key={`${item.novel.id}-${item.editorName}-${editorPageStart + index}`}
href={`/truyen/${item.novel.slug}`}
className="group flex items-center gap-3 rounded-xl border border-border bg-background/80 p-2.5 transition hover:border-primary/40"
>
<span className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/15 text-xs font-bold text-primary">
{editorPageStart + index + 1}
</span>
<img
src={item.novel.coverUrl || "/default-cover.svg"}
alt={item.novel.title}
className="h-20 w-14 shrink-0 rounded-md border border-border/70 object-cover"
/>
<div className="min-w-0 flex-1">
<h3 className="line-clamp-1 text-sm font-semibold text-foreground group-hover:text-primary">{item.novel.title}</h3>
<p className="text-xs text-muted-foreground">{item.novel.authorName}</p>
<p className="mt-1 text-xs text-muted-foreground">Biên tập viên: {item.editorName}</p>
<p className="text-xs text-muted-foreground">{item.recommendCount} đ cử</p>
</div>
<div className="inline-flex items-center gap-1 text-xs font-semibold text-primary">
<Star className="h-3.5 w-3.5 fill-primary text-primary" />
{item.novel.rating.toFixed(1)}
</div>
</Link>
)) : (
<p className="text-sm text-muted-foreground">Chưa đ cử từ biên tập viên.</p>
)}
</div>
</div>
</section>
)
}
+54 -1
View File
@@ -68,6 +68,55 @@ export function ReaderFAB({ novelId, novelSlug, paragraphs, currentChapter, maxC
const [fontSize, setFontSize] = useState(18)
const [lineHeight, setLineHeight] = useState(1.8)
const [letterSpacing, setLetterSpacing] = useState(0)
const [fontFamily, setFontFamily] = useState("font-serif")
useEffect(() => {
// Dùng local storage chạy tạm thời gian đầu để khỏi giật màn hình
const savedFontSize = localStorage.getItem("reader_fontSize")
const savedLineHeight = localStorage.getItem("reader_lineHeight")
const savedLetterSpacing = localStorage.getItem("reader_letterSpacing")
const savedFontFamily = localStorage.getItem("reader_fontFamily")
if (savedFontSize) setFontSize(Number(savedFontSize))
if (savedLineHeight) setLineHeight(Number(savedLineHeight))
if (savedLetterSpacing) setLetterSpacing(Number(savedLetterSpacing))
if (savedFontFamily) setFontFamily(savedFontFamily)
// Đồng bộ Settings từ DB về (Ghi đè nếu có)
fetch("/api/user/settings")
.then(res => res.json())
.then(data => {
if (data && !data.error && data.fontSize) {
setFontSize(data.fontSize)
setLineHeight(data.lineHeight)
setLetterSpacing(data.letterSpacing)
setFontFamily(data.fontFamily)
localStorage.setItem("reader_fontSize", data.fontSize.toString())
localStorage.setItem("reader_lineHeight", data.lineHeight.toString())
localStorage.setItem("reader_letterSpacing", data.letterSpacing.toString())
localStorage.setItem("reader_fontFamily", data.fontFamily)
}
})
.catch(() => {})
}, [])
useEffect(() => {
localStorage.setItem("reader_fontSize", fontSize.toString())
localStorage.setItem("reader_lineHeight", lineHeight.toString())
localStorage.setItem("reader_letterSpacing", letterSpacing.toString())
localStorage.setItem("reader_fontFamily", fontFamily)
const timer = setTimeout(() => {
fetch("/api/user/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fontSize, lineHeight, letterSpacing, fontFamily })
}).catch(() => {})
}, 1000)
return () => clearTimeout(timer)
}, [fontSize, lineHeight, letterSpacing, fontFamily])
return (
<>
@@ -134,6 +183,7 @@ export function ReaderFAB({ novelId, novelSlug, paragraphs, currentChapter, maxC
fontSize={fontSize} setFontSize={setFontSize}
lineHeight={lineHeight} setLineHeight={setLineHeight}
letterSpacing={letterSpacing} setLetterSpacing={setLetterSpacing}
fontFamily={fontFamily} setFontFamily={setFontFamily}
/>
</PopoverContent>
</Popover>
@@ -158,10 +208,13 @@ export function ReaderFAB({ novelId, novelSlug, paragraphs, currentChapter, maxC
{/* Inject styles OUTSIDE the popover so it survives */}
<style>{`
.chapter-content {
.chapter-content, .chapter-content p {
font-size: ${fontSize}px !important;
line-height: ${lineHeight} !important;
letter-spacing: ${letterSpacing}px !important;
font-family: ${fontFamily === 'font-serif' ? 'ui-serif, Georgia, Cambria, "Times New Roman", Times, serif' :
fontFamily === 'font-sans' ? 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif' :
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace'} !important;
}
`}</style>
+90 -3
View File
@@ -1,6 +1,6 @@
"use client"
import { useState } from "react"
import { useState, useEffect } from "react"
import { Minus, Plus, ALargeSmall, RotateCcw } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
@@ -11,12 +11,15 @@ interface ReadingSettingsProps {
setLineHeight: (v: number) => void
letterSpacing: number
setLetterSpacing: (v: number) => void
fontFamily: string
setFontFamily: (v: string) => void
}
export function ReadingSettingsContent({
fontSize, setFontSize,
lineHeight, setLineHeight,
letterSpacing, setLetterSpacing
letterSpacing, setLetterSpacing,
fontFamily, setFontFamily
}: ReadingSettingsProps) {
return (
<>
@@ -109,6 +112,36 @@ export function ReadingSettingsContent({
</div>
</div>
<div>
<label className="mb-2 block text-xs font-medium text-muted-foreground">Phông chữ</label>
<div className="grid grid-cols-3 gap-2">
<Button
variant={fontFamily === "font-serif" ? "default" : "outline"}
size="sm"
className="font-serif text-xs"
onClick={() => setFontFamily("font-serif")}
>
Serif
</Button>
<Button
variant={fontFamily === "font-sans" ? "default" : "outline"}
size="sm"
className="font-sans text-xs"
onClick={() => setFontFamily("font-sans")}
>
Sans
</Button>
<Button
variant={fontFamily === "font-mono" ? "default" : "outline"}
size="sm"
className="font-mono text-xs"
onClick={() => setFontFamily("font-mono")}
>
Mono
</Button>
</div>
</div>
<div className="pt-2">
<Button
variant="ghost"
@@ -118,6 +151,7 @@ export function ReadingSettingsContent({
setFontSize(18)
setLineHeight(1.8)
setLetterSpacing(0)
setFontFamily("font-serif")
}}
>
<RotateCcw className="mr-2 h-3 w-3" />
@@ -133,6 +167,55 @@ export function ReadingSettings() {
const [fontSize, setFontSize] = useState(18)
const [lineHeight, setLineHeight] = useState(1.8)
const [letterSpacing, setLetterSpacing] = useState(0)
const [fontFamily, setFontFamily] = useState("font-serif")
useEffect(() => {
// Dùng local storage chạy tạm thời gian đầu để khỏi giật màn hình
const savedFontSize = localStorage.getItem("reader_fontSize")
const savedLineHeight = localStorage.getItem("reader_lineHeight")
const savedLetterSpacing = localStorage.getItem("reader_letterSpacing")
const savedFontFamily = localStorage.getItem("reader_fontFamily")
if (savedFontSize) setFontSize(Number(savedFontSize))
if (savedLineHeight) setLineHeight(Number(savedLineHeight))
if (savedLetterSpacing) setLetterSpacing(Number(savedLetterSpacing))
if (savedFontFamily) setFontFamily(savedFontFamily)
// Đồng bộ Settings từ DB về (Ghi đè nếu có)
fetch("/api/user/settings")
.then(res => res.json())
.then(data => {
if (data && !data.error && data.fontSize) {
setFontSize(data.fontSize)
setLineHeight(data.lineHeight)
setLetterSpacing(data.letterSpacing)
setFontFamily(data.fontFamily)
localStorage.setItem("reader_fontSize", data.fontSize.toString())
localStorage.setItem("reader_lineHeight", data.lineHeight.toString())
localStorage.setItem("reader_letterSpacing", data.letterSpacing.toString())
localStorage.setItem("reader_fontFamily", data.fontFamily)
}
})
.catch(() => {})
}, [])
useEffect(() => {
localStorage.setItem("reader_fontSize", fontSize.toString())
localStorage.setItem("reader_lineHeight", lineHeight.toString())
localStorage.setItem("reader_letterSpacing", letterSpacing.toString())
localStorage.setItem("reader_fontFamily", fontFamily)
const timer = setTimeout(() => {
fetch("/api/user/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fontSize, lineHeight, letterSpacing, fontFamily })
}).catch(() => {})
}, 1000)
return () => clearTimeout(timer)
}, [fontSize, lineHeight, letterSpacing, fontFamily])
return (
<>
@@ -148,15 +231,19 @@ export function ReadingSettings() {
fontSize={fontSize} setFontSize={setFontSize}
lineHeight={lineHeight} setLineHeight={setLineHeight}
letterSpacing={letterSpacing} setLetterSpacing={setLetterSpacing}
fontFamily={fontFamily} setFontFamily={setFontFamily}
/>
</PopoverContent>
</Popover>
{/* Inject styles */}
<style>{`
.chapter-content {
.chapter-content, .chapter-content p {
font-size: ${fontSize}px !important;
line-height: ${lineHeight} !important;
letter-spacing: ${letterSpacing}px !important;
font-family: ${fontFamily === 'font-serif' ? 'ui-serif, Georgia, Cambria, "Times New Roman", Times, serif' :
fontFamily === 'font-sans' ? 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif' :
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace'} !important;
}
`}</style>
</>