reader-view.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. "use client";
  2. import Link from "next/link";
  3. import { CSSProperties, useEffect, useMemo, useRef, useState } from "react";
  4. import { getBookEntries } from "@/lib/book-helpers";
  5. import { Book } from "@/types/book";
  6. type ReaderViewProps = {
  7. book: Book;
  8. chapterIndex: number;
  9. initialThemeKey?: string;
  10. initialFontKey?: string;
  11. initialWidthKey?: string;
  12. };
  13. const themeOptions = [
  14. { key: "warm", label: "暖米", page: "#f7f0e4", stage: "#d8d0c4", text: "#2b241e", catalog: "#e6ddd0" },
  15. { key: "mist", label: "浅灰", page: "#efede7", stage: "#d6d4cf", text: "#2a2723", catalog: "#dfddd7" },
  16. { key: "sepia", label: "茶褐", page: "#eee0cf", stage: "#d4c3b1", text: "#35281f", catalog: "#dfcdbb" }
  17. ] as const;
  18. const fontOptions = [
  19. { key: "sm", label: "小", size: "1.02rem", lineHeight: 2.05 },
  20. { key: "md", label: "中", size: "1.18rem", lineHeight: 2.28 },
  21. { key: "lg", label: "大", size: "1.34rem", lineHeight: 2.55 }
  22. ] as const;
  23. const widthOptions = [
  24. { key: "narrow", label: "窄", width: 760 },
  25. { key: "medium", label: "中", width: 920 },
  26. { key: "wide", label: "宽", width: 1080 }
  27. ] as const;
  28. export function ReaderView({
  29. book,
  30. chapterIndex,
  31. initialThemeKey,
  32. initialFontKey,
  33. initialWidthKey
  34. }: ReaderViewProps) {
  35. const entries = useMemo(() => getBookEntries(book), [book]);
  36. const entry = entries[chapterIndex];
  37. const prevChapterIndex = chapterIndex > 0 ? chapterIndex - 1 : null;
  38. const nextChapterIndex = chapterIndex < entries.length - 1 ? chapterIndex + 1 : null;
  39. const initialThemeIndex = Math.max(0, themeOptions.findIndex((item) => item.key === initialThemeKey));
  40. const initialFontIndex = Math.max(0, fontOptions.findIndex((item) => item.key === initialFontKey));
  41. const initialWidthIndex = Math.max(0, widthOptions.findIndex((item) => item.key === initialWidthKey));
  42. const [themeIndex, setThemeIndex] = useState(initialThemeKey ? initialThemeIndex : 0);
  43. const [fontIndex, setFontIndex] = useState(initialFontKey ? initialFontIndex : 1);
  44. const [widthIndex, setWidthIndex] = useState(initialWidthKey ? initialWidthIndex : 1);
  45. const [catalogOpen, setCatalogOpen] = useState(false);
  46. const [progress, setProgress] = useState(0);
  47. const stageRef = useRef<HTMLElement | null>(null);
  48. useEffect(() => {
  49. const { page: pageColor, stage: stageColor } = themeOptions[themeIndex];
  50. document.body.classList.add("reader-body");
  51. const previousBodyBackground = document.body.style.background;
  52. const previousHtmlBackground = document.documentElement.style.background;
  53. document.body.style.background = pageColor;
  54. document.documentElement.style.background = pageColor;
  55. // Sync browser chrome (status bar + navigation bar) with theme
  56. let metaTheme = document.querySelector<HTMLMetaElement>('meta[name="theme-color"]');
  57. if (!metaTheme) {
  58. metaTheme = document.createElement("meta");
  59. metaTheme.name = "theme-color";
  60. document.head.appendChild(metaTheme);
  61. }
  62. const previousThemeColor = metaTheme.content;
  63. metaTheme.content = pageColor;
  64. return () => {
  65. document.body.classList.remove("reader-body");
  66. document.body.style.background = previousBodyBackground;
  67. document.documentElement.style.background = previousHtmlBackground;
  68. if (metaTheme) metaTheme.content = previousThemeColor;
  69. };
  70. }, [themeIndex]);
  71. useEffect(() => {
  72. const stage = stageRef.current;
  73. if (!stage) return;
  74. stage.scrollTo({ top: 0, behavior: "auto" });
  75. setCatalogOpen(false);
  76. const updateProgress = () => {
  77. const maxScroll = stage.scrollHeight - stage.clientHeight;
  78. const nextProgress = maxScroll <= 0 ? 0 : (stage.scrollTop / maxScroll) * 100;
  79. setProgress(nextProgress);
  80. };
  81. updateProgress();
  82. stage.addEventListener("scroll", updateProgress);
  83. window.addEventListener("resize", updateProgress);
  84. return () => {
  85. stage.removeEventListener("scroll", updateProgress);
  86. window.removeEventListener("resize", updateProgress);
  87. };
  88. }, [chapterIndex]);
  89. useEffect(() => {
  90. const stage = stageRef.current;
  91. if (!stage) return;
  92. const maxScroll = stage.scrollHeight - stage.clientHeight;
  93. setProgress(maxScroll <= 0 ? 0 : (stage.scrollTop / maxScroll) * 100);
  94. }, [fontIndex, widthIndex, themeIndex]);
  95. const currentTheme = themeOptions[themeIndex];
  96. const currentFont = fontOptions[fontIndex];
  97. const currentWidth = widthOptions[widthIndex];
  98. const entryWords = entry.content.join("").length;
  99. const isLoreEntry = entry.kind === "lore";
  100. const shellWidthStyle = useMemo(
  101. () =>
  102. ({
  103. width: "var(--reader-shell-width)"
  104. }) as CSSProperties,
  105. []
  106. );
  107. const cycleFont = () => setFontIndex((value) => (value + 1) % fontOptions.length);
  108. const cycleTheme = () => setThemeIndex((value) => (value + 1) % themeOptions.length);
  109. const cycleWidth = () => setWidthIndex((value) => (value + 1) % widthOptions.length);
  110. const catalogContent = (
  111. <>
  112. <div className="reader-catalog__header">
  113. <h2>目录</h2>
  114. <button type="button" className="reader-catalog__close" onClick={() => setCatalogOpen(false)}>
  115. 关闭
  116. </button>
  117. </div>
  118. <div className="reader-catalog-groups">
  119. {book.sections
  120. .slice()
  121. .sort((a, b) => a.order - b.order)
  122. .map((section) => {
  123. const sectionEntries = entries.filter((item) => item.sectionId === section.id);
  124. return (
  125. <section className="reader-catalog__section" key={section.id}>
  126. <div className="reader-catalog__section-title">
  127. <span className={`reader-catalog__kind reader-catalog__kind--${section.kind}`}>
  128. {section.kind === "lore" ? "资料" : "正文"}
  129. </span>
  130. <strong>{section.title}</strong>
  131. </div>
  132. <div className="reader-catalog__grid">
  133. {sectionEntries.map((item, index) => (
  134. <Link
  135. key={item.id}
  136. href={`/reader/${book.id}?entry=${item.flatIndex}`}
  137. className={`reader-catalog__item${item.flatIndex === chapterIndex ? " reader-catalog__item--active" : ""}`}
  138. onClick={() => setCatalogOpen(false)}
  139. >
  140. <span>
  141. {section.kind === "lore" ? `资料 ${index + 1}` : `第 ${index + 1} 章`}
  142. </span>
  143. <strong>{item.title}</strong>
  144. </Link>
  145. ))}
  146. </div>
  147. </section>
  148. );
  149. })}
  150. </div>
  151. </>
  152. );
  153. return (
  154. <main
  155. className="reader-stage"
  156. style={
  157. {
  158. background: currentTheme.stage,
  159. "--reader-page": currentTheme.page,
  160. "--reader-stage-color": currentTheme.stage,
  161. "--reader-shell-width": `min(${currentWidth.width}px, calc(100vw - 280px))`
  162. } as CSSProperties
  163. }
  164. ref={stageRef}
  165. >
  166. <div className="reader-progress-rail" aria-hidden="true">
  167. <div className="reader-progress-rail__track">
  168. <div className="reader-progress-rail__fill" style={{ height: `${progress}%` }} />
  169. </div>
  170. </div>
  171. <div className="reader-mobile-bar reader-mobile-bar--top">
  172. <Link className="reader-mobile-bar__icon reader-mobile-bar__icon--back" href="/library" aria-label="返回书架">
  173. 返回
  174. </Link>
  175. <button className="reader-mobile-bar__icon" type="button" onClick={cycleTheme} aria-label="切换主题">
  176. 主题 {currentTheme.label}
  177. </button>
  178. <button className="reader-mobile-bar__icon" type="button" onClick={cycleFont} aria-label="切换字体">
  179. 字体 {currentFont.label}
  180. </button>
  181. </div>
  182. <div className="reader-mobile-bar reader-mobile-bar--bottom">
  183. <button className="reader-mobile-bar__action" type="button" onClick={() => setCatalogOpen(true)}>
  184. 目录
  185. </button>
  186. {prevChapterIndex !== null ? (
  187. <Link className="reader-mobile-bar__action" href={`/reader/${book.id}?entry=${prevChapterIndex}`}>
  188. 上一章
  189. </Link>
  190. ) : (
  191. <span className="reader-mobile-bar__action reader-mobile-bar__action--disabled">上一章</span>
  192. )}
  193. {nextChapterIndex !== null ? (
  194. <Link className="reader-mobile-bar__action" href={`/reader/${book.id}?entry=${nextChapterIndex}`}>
  195. 下一章
  196. </Link>
  197. ) : (
  198. <span className="reader-mobile-bar__action reader-mobile-bar__action--disabled">下一章</span>
  199. )}
  200. </div>
  201. <div className="reader-desktop-layout">
  202. <div className="reader-float reader-float--left" aria-label="阅读左侧工具">
  203. <Link className="reader-float__button" href="/library">
  204. <strong>返回</strong>
  205. <span>回到书架</span>
  206. </Link>
  207. <button className="reader-float__button" type="button" onClick={() => setCatalogOpen(true)}>
  208. <strong>目录</strong>
  209. <span>弹出目录</span>
  210. </button>
  211. </div>
  212. <section className="reader-qq-shell" style={shellWidthStyle}>
  213. <div className="reader-catalog-mobile-mask" hidden={!catalogOpen} onClick={() => setCatalogOpen(false)} />
  214. <div
  215. className={`reader-catalog-mobile-sheet${catalogOpen ? " is-open" : ""}`}
  216. style={{ background: currentTheme.catalog }}
  217. aria-hidden={!catalogOpen}
  218. >
  219. {catalogContent}
  220. </div>
  221. {catalogOpen ? (
  222. <div className="reader-catalog-inline" style={{ background: currentTheme.catalog }}>
  223. {catalogContent}
  224. </div>
  225. ) : null}
  226. <div
  227. className={`reader-qq-paper${catalogOpen ? " reader-qq-paper--desktop-hidden" : ""}`}
  228. style={{ background: currentTheme.page }}
  229. >
  230. <header className={`reader-qq-header${isLoreEntry ? " reader-qq-header--lore" : ""}`}>
  231. <div className="reader-entry-badges">
  232. <span className={`reader-entry-badge reader-entry-badge--${entry.kind}`}>
  233. {isLoreEntry ? "资料" : "正文"}
  234. </span>
  235. <span className="reader-entry-badge reader-entry-badge--section">{entry.sectionTitle}</span>
  236. </div>
  237. <h1>{entry.title}</h1>
  238. <div className="reader-qq-meta">
  239. <span>书名:{book.title}</span>
  240. <span>作者:{book.author}</span>
  241. <span>当前:{entry.sectionTitle}</span>
  242. <span>本节字数:{entryWords} 字</span>
  243. <span>总字数:{book.wordCount}</span>
  244. </div>
  245. </header>
  246. <article
  247. className={`reader-qq-content${isLoreEntry ? " reader-qq-content--lore" : ""}`}
  248. style={{ color: currentTheme.text }}
  249. >
  250. {entry.content.map((paragraph) => (
  251. <p key={paragraph} style={{ fontSize: currentFont.size, lineHeight: currentFont.lineHeight }}>
  252. {paragraph}
  253. </p>
  254. ))}
  255. </article>
  256. <footer className="reader-qq-footer">
  257. <button className="reader-qq-footer__ghost" type="button" onClick={() => setCatalogOpen(true)}>
  258. 目录
  259. </button>
  260. {prevChapterIndex !== null ? (
  261. <Link className="reader-qq-footer__button" href={`/reader/${book.id}?entry=${prevChapterIndex}`}>
  262. 上一章
  263. </Link>
  264. ) : (
  265. <span className="reader-qq-footer__button reader-qq-footer__button--disabled">已是第一节</span>
  266. )}
  267. {nextChapterIndex !== null ? (
  268. <Link className="reader-qq-footer__button" href={`/reader/${book.id}?entry=${nextChapterIndex}`}>
  269. 下一章
  270. </Link>
  271. ) : (
  272. <span className="reader-qq-footer__button reader-qq-footer__button--disabled">已是最后一节</span>
  273. )}
  274. </footer>
  275. </div>
  276. </section>
  277. <div className="reader-float reader-float--right" aria-label="阅读右侧工具">
  278. <button className="reader-float__button" type="button" onClick={cycleFont}>
  279. <strong>字号</strong>
  280. <span>当前{currentFont.label}</span>
  281. </button>
  282. <button className="reader-float__button" type="button" onClick={cycleTheme}>
  283. <strong>主题</strong>
  284. <span>当前{currentTheme.label}</span>
  285. </button>
  286. <button className="reader-float__button" type="button" onClick={cycleWidth}>
  287. <strong>版心</strong>
  288. <span>当前{currentWidth.label}</span>
  289. </button>
  290. </div>
  291. </div>
  292. </main>
  293. );
  294. }