reader-view.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 } = 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. // Force iOS Safari to pick up theme-color by removing old tags and inserting a fresh one
  56. document.querySelectorAll('meta[name="theme-color"]').forEach((m) => m.remove());
  57. const metaTheme = document.createElement("meta");
  58. metaTheme.setAttribute("name", "theme-color");
  59. metaTheme.setAttribute("content", pageColor);
  60. document.head.appendChild(metaTheme);
  61. return () => {
  62. document.body.classList.remove("reader-body");
  63. document.body.style.background = previousBodyBackground;
  64. document.documentElement.style.background = previousHtmlBackground;
  65. metaTheme.setAttribute("content", "#f4efe7");
  66. };
  67. }, [themeIndex]);
  68. useEffect(() => {
  69. const stage = stageRef.current;
  70. if (!stage) return;
  71. stage.scrollTo({ top: 0, behavior: "auto" });
  72. setCatalogOpen(false);
  73. const updateProgress = () => {
  74. const maxScroll = stage.scrollHeight - stage.clientHeight;
  75. const nextProgress = maxScroll <= 0 ? 0 : (stage.scrollTop / maxScroll) * 100;
  76. setProgress(nextProgress);
  77. };
  78. updateProgress();
  79. stage.addEventListener("scroll", updateProgress);
  80. window.addEventListener("resize", updateProgress);
  81. return () => {
  82. stage.removeEventListener("scroll", updateProgress);
  83. window.removeEventListener("resize", updateProgress);
  84. };
  85. }, [chapterIndex]);
  86. useEffect(() => {
  87. const stage = stageRef.current;
  88. if (!stage) return;
  89. const maxScroll = stage.scrollHeight - stage.clientHeight;
  90. setProgress(maxScroll <= 0 ? 0 : (stage.scrollTop / maxScroll) * 100);
  91. }, [fontIndex, widthIndex, themeIndex]);
  92. const currentTheme = themeOptions[themeIndex];
  93. const currentFont = fontOptions[fontIndex];
  94. const currentWidth = widthOptions[widthIndex];
  95. const entryWords = entry.content.join("").length;
  96. const isLoreEntry = entry.kind === "lore";
  97. const shellWidthStyle = useMemo(
  98. () =>
  99. ({
  100. width: "var(--reader-shell-width)"
  101. }) as CSSProperties,
  102. []
  103. );
  104. const cycleFont = () => setFontIndex((value) => (value + 1) % fontOptions.length);
  105. const cycleTheme = () => setThemeIndex((value) => (value + 1) % themeOptions.length);
  106. const cycleWidth = () => setWidthIndex((value) => (value + 1) % widthOptions.length);
  107. const catalogContent = (
  108. <>
  109. <div className="reader-catalog__header">
  110. <h2>目录</h2>
  111. <button type="button" className="reader-catalog__close" onClick={() => setCatalogOpen(false)}>
  112. 关闭
  113. </button>
  114. </div>
  115. <div className="reader-catalog-groups">
  116. {book.sections
  117. .slice()
  118. .sort((a, b) => a.order - b.order)
  119. .map((section) => {
  120. const sectionEntries = entries.filter((item) => item.sectionId === section.id);
  121. return (
  122. <section className="reader-catalog__section" key={section.id}>
  123. <div className="reader-catalog__section-title">
  124. <span className={`reader-catalog__kind reader-catalog__kind--${section.kind}`}>
  125. {section.kind === "lore" ? "资料" : "正文"}
  126. </span>
  127. <strong>{section.title}</strong>
  128. </div>
  129. <div className="reader-catalog__grid">
  130. {sectionEntries.map((item, index) => (
  131. <Link
  132. key={item.id}
  133. href={`/reader/${book.id}?entry=${item.flatIndex}`}
  134. className={`reader-catalog__item${item.flatIndex === chapterIndex ? " reader-catalog__item--active" : ""}`}
  135. onClick={() => setCatalogOpen(false)}
  136. >
  137. <span>
  138. {section.kind === "lore" ? `资料 ${index + 1}` : `第 ${index + 1} 章`}
  139. </span>
  140. <strong>{item.title}</strong>
  141. </Link>
  142. ))}
  143. </div>
  144. </section>
  145. );
  146. })}
  147. </div>
  148. </>
  149. );
  150. return (
  151. <main
  152. className="reader-stage"
  153. style={
  154. {
  155. background: currentTheme.stage,
  156. "--reader-page": currentTheme.page,
  157. "--reader-stage-color": currentTheme.stage,
  158. "--reader-shell-width": `min(${currentWidth.width}px, calc(100vw - 280px))`
  159. } as CSSProperties
  160. }
  161. ref={stageRef}
  162. >
  163. <div className="reader-progress-rail" aria-hidden="true">
  164. <div className="reader-progress-rail__track">
  165. <div className="reader-progress-rail__fill" style={{ height: `${progress}%` }} />
  166. </div>
  167. </div>
  168. <div className="reader-mobile-bar reader-mobile-bar--top">
  169. <Link className="reader-mobile-bar__icon reader-mobile-bar__icon--back" href="/library" aria-label="返回书架">
  170. 返回
  171. </Link>
  172. <button className="reader-mobile-bar__icon" type="button" onClick={cycleTheme} aria-label="切换主题">
  173. 主题 {currentTheme.label}
  174. </button>
  175. <button className="reader-mobile-bar__icon" type="button" onClick={cycleFont} aria-label="切换字体">
  176. 字体 {currentFont.label}
  177. </button>
  178. </div>
  179. <div className="reader-mobile-bar reader-mobile-bar--bottom">
  180. <button className="reader-mobile-bar__action" type="button" onClick={() => setCatalogOpen(true)}>
  181. 目录
  182. </button>
  183. {prevChapterIndex !== null ? (
  184. <Link className="reader-mobile-bar__action" href={`/reader/${book.id}?entry=${prevChapterIndex}`}>
  185. 上一章
  186. </Link>
  187. ) : (
  188. <span className="reader-mobile-bar__action reader-mobile-bar__action--disabled">上一章</span>
  189. )}
  190. {nextChapterIndex !== null ? (
  191. <Link className="reader-mobile-bar__action" href={`/reader/${book.id}?entry=${nextChapterIndex}`}>
  192. 下一章
  193. </Link>
  194. ) : (
  195. <span className="reader-mobile-bar__action reader-mobile-bar__action--disabled">下一章</span>
  196. )}
  197. </div>
  198. <div className="reader-desktop-layout">
  199. <div className="reader-float reader-float--left" aria-label="阅读左侧工具">
  200. <Link className="reader-float__button" href="/library">
  201. <strong>返回</strong>
  202. <span>回到书架</span>
  203. </Link>
  204. <button className="reader-float__button" type="button" onClick={() => setCatalogOpen(true)}>
  205. <strong>目录</strong>
  206. <span>弹出目录</span>
  207. </button>
  208. </div>
  209. <section className="reader-qq-shell" style={shellWidthStyle}>
  210. <div className="reader-catalog-mobile-mask" hidden={!catalogOpen} onClick={() => setCatalogOpen(false)} />
  211. <div
  212. className={`reader-catalog-mobile-sheet${catalogOpen ? " is-open" : ""}`}
  213. style={{ background: currentTheme.catalog }}
  214. aria-hidden={!catalogOpen}
  215. >
  216. {catalogContent}
  217. </div>
  218. {catalogOpen ? (
  219. <div className="reader-catalog-inline" style={{ background: currentTheme.catalog }}>
  220. {catalogContent}
  221. </div>
  222. ) : null}
  223. <div
  224. className={`reader-qq-paper${catalogOpen ? " reader-qq-paper--desktop-hidden" : ""}`}
  225. style={{ background: currentTheme.page }}
  226. >
  227. <header className={`reader-qq-header${isLoreEntry ? " reader-qq-header--lore" : ""}`}>
  228. <div className="reader-entry-badges">
  229. <span className={`reader-entry-badge reader-entry-badge--${entry.kind}`}>
  230. {isLoreEntry ? "资料" : "正文"}
  231. </span>
  232. <span className="reader-entry-badge reader-entry-badge--section">{entry.sectionTitle}</span>
  233. </div>
  234. <h1>{entry.title}</h1>
  235. <div className="reader-qq-meta">
  236. <span>书名:{book.title}</span>
  237. <span>作者:{book.author}</span>
  238. <span>当前:{entry.sectionTitle}</span>
  239. <span>本节字数:{entryWords} 字</span>
  240. <span>总字数:{book.wordCount}</span>
  241. </div>
  242. </header>
  243. <article
  244. className={`reader-qq-content${isLoreEntry ? " reader-qq-content--lore" : ""}`}
  245. style={{ color: currentTheme.text }}
  246. >
  247. {entry.content.map((paragraph) => (
  248. <p key={paragraph} style={{ fontSize: currentFont.size, lineHeight: currentFont.lineHeight }}>
  249. {paragraph}
  250. </p>
  251. ))}
  252. </article>
  253. <footer className="reader-qq-footer">
  254. <button className="reader-qq-footer__ghost" type="button" onClick={() => setCatalogOpen(true)}>
  255. 目录
  256. </button>
  257. {prevChapterIndex !== null ? (
  258. <Link className="reader-qq-footer__button" href={`/reader/${book.id}?entry=${prevChapterIndex}`}>
  259. 上一章
  260. </Link>
  261. ) : (
  262. <span className="reader-qq-footer__button reader-qq-footer__button--disabled">已是第一节</span>
  263. )}
  264. {nextChapterIndex !== null ? (
  265. <Link className="reader-qq-footer__button" href={`/reader/${book.id}?entry=${nextChapterIndex}`}>
  266. 下一章
  267. </Link>
  268. ) : (
  269. <span className="reader-qq-footer__button reader-qq-footer__button--disabled">已是最后一节</span>
  270. )}
  271. </footer>
  272. </div>
  273. </section>
  274. <div className="reader-float reader-float--right" aria-label="阅读右侧工具">
  275. <button className="reader-float__button" type="button" onClick={cycleFont}>
  276. <strong>字号</strong>
  277. <span>当前{currentFont.label}</span>
  278. </button>
  279. <button className="reader-float__button" type="button" onClick={cycleTheme}>
  280. <strong>主题</strong>
  281. <span>当前{currentTheme.label}</span>
  282. </button>
  283. <button className="reader-float__button" type="button" onClick={cycleWidth}>
  284. <strong>版心</strong>
  285. <span>当前{currentWidth.label}</span>
  286. </button>
  287. </div>
  288. </div>
  289. </main>
  290. );
  291. }