BookChapter.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. <template>
  2. <div
  3. class="chapter-wrapper"
  4. :style="bodyTheme"
  5. :class="{ night: isNight, day: !isNight }"
  6. @click="showToolBar = !showToolBar"
  7. >
  8. <div class="tool-bar" :style="leftBarTheme">
  9. <div class="tools">
  10. <el-popover
  11. placement="right"
  12. :width="popupWidth"
  13. trigger="click"
  14. :show-arrow="false"
  15. v-model:visible="popCataVisible"
  16. popper-class="pop-cata"
  17. >
  18. <PopCatalog @getContent="getContent" class="popup" />
  19. <template #reference>
  20. <div class="tool-icon" :class="{ 'no-point': noPoint }">
  21. <div class="iconfont">&#58905;</div>
  22. <div class="icon-text">目录</div>
  23. </div>
  24. </template>
  25. </el-popover>
  26. <el-popover
  27. placement="right"
  28. :width="popupWidth"
  29. trigger="click"
  30. :show-arrow="false"
  31. v-model:visible="readSettingsVisible"
  32. popper-class="pop-setting"
  33. >
  34. <read-settings class="popup" />
  35. <template #reference>
  36. <div class="tool-icon" :class="{ 'no-point': noPoint }">
  37. <div class="iconfont">&#58971;</div>
  38. <div class="icon-text">设置</div>
  39. </div>
  40. </template>
  41. </el-popover>
  42. <div class="tool-icon" @click="toShelf">
  43. <div class="iconfont">&#58892;</div>
  44. <div class="icon-text">书架</div>
  45. </div>
  46. <div class="tool-icon" :class="{ 'no-point': noPoint }" @click="toTop">
  47. <div class="iconfont">&#58914;</div>
  48. <div class="icon-text">顶部</div>
  49. </div>
  50. <div
  51. class="tool-icon"
  52. :class="{ 'no-point': noPoint }"
  53. @click="toBottom"
  54. >
  55. <div class="iconfont">&#58915;</div>
  56. <div class="icon-text">底部</div>
  57. </div>
  58. </div>
  59. </div>
  60. <div class="read-bar" :style="rightBarTheme">
  61. <div class="tools">
  62. <div
  63. class="tool-icon"
  64. :class="{ 'no-point': noPoint }"
  65. @click="toPreChapter"
  66. >
  67. <div class="iconfont">&#58920;</div>
  68. <span v-if="miniInterface">上一章</span>
  69. </div>
  70. <div
  71. class="tool-icon"
  72. :class="{ 'no-point': noPoint }"
  73. @click="toNextChapter"
  74. >
  75. <span v-if="miniInterface">下一章</span>
  76. <div class="iconfont">&#58913;</div>
  77. </div>
  78. </div>
  79. </div>
  80. <div class="chapter-bar"></div>
  81. <div class="chapter" ref="content" :style="chapterTheme">
  82. <div class="content">
  83. <div class="top-bar" ref="top"></div>
  84. <div
  85. v-for="data in chapterData"
  86. :key="data.index"
  87. :chapterIndex="data.index"
  88. ref="chapter"
  89. >
  90. <chapter-content
  91. ref="chapterRef"
  92. :chapterIndex="data.index"
  93. :contents="data.content"
  94. :title="data.title"
  95. :spacing="store.config.spacing"
  96. :fontSize="fontSize"
  97. :fontFamily="fontFamily"
  98. @readedLengthChange="onReadedLengthChange"
  99. v-if="showContent"
  100. />
  101. </div>
  102. <div class="loading" ref="loading"></div>
  103. <div class="bottom-bar" ref="bottom"></div>
  104. </div>
  105. </div>
  106. </div>
  107. </template>
  108. <script setup>
  109. import jump from "@/plugins/jump";
  110. import settings from "@/plugins/config";
  111. import API from "@api";
  112. import { useLoading } from "@/hooks/loading";
  113. const content = ref();
  114. // loading spinner
  115. const { isLoading, loadingWrapper } = useLoading(content, "正在获取信息");
  116. const store = useBookStore();
  117. // 读取阅读配置
  118. try {
  119. const browerConfig = JSON.parse(localStorage.getItem("config"));
  120. if (browerConfig != null) store.setConfig(browerConfig);
  121. } catch {
  122. localStorage.removeItem("config");
  123. }
  124. const {
  125. catalog,
  126. popCataVisible,
  127. readSettingsVisible,
  128. miniInterface,
  129. showContent,
  130. config,
  131. readingBook,
  132. bookProgress,
  133. } = storeToRefs(store);
  134. const chapterPos = computed({
  135. get: () => readingBook.value.chapterPos,
  136. set: (value) => (readingBook.value.chapterPos = value),
  137. });
  138. const chapterIndex = computed({
  139. get: () => readingBook.value.index,
  140. set: (value) => (readingBook.value.index = value),
  141. });
  142. const theme = computed(() => config.value.theme);
  143. const infiniteLoading = computed(() => config.value.infiniteLoading);
  144. // 字体
  145. const fontFamily = computed(() => {
  146. if (store.config.font >= 0) {
  147. return settings.fonts[store.config.font];
  148. }
  149. return store.config.customFontName;
  150. });
  151. const fontSize = computed(() => {
  152. return store.config.fontSize + "px";
  153. });
  154. // 主题部分
  155. const bodyColor = computed(() => settings.themes[theme.value].body);
  156. const chapterColor = computed(() => settings.themes[theme.value].content);
  157. const popupColor = computed(() => settings.themes[theme.value].popup);
  158. const readWidth = computed(() => {
  159. if (!miniInterface.value) {
  160. return store.config.readWidth - 130 + "px";
  161. } else {
  162. return window.innerWidth + "px";
  163. }
  164. });
  165. const popupWidth = computed(() => {
  166. if (!miniInterface.value) {
  167. return store.config.readWidth - 33;
  168. } else {
  169. return window.innerWidth - 33;
  170. }
  171. });
  172. const bodyTheme = computed(() => {
  173. return {
  174. background: bodyColor.value,
  175. };
  176. });
  177. const chapterTheme = computed(() => {
  178. return {
  179. background: chapterColor.value,
  180. width: readWidth.value,
  181. };
  182. });
  183. const showToolBar = ref(false);
  184. const leftBarTheme = computed(() => {
  185. return {
  186. background: popupColor.value,
  187. marginLeft: miniInterface.value
  188. ? 0
  189. : -(store.config.readWidth / 2 + 68) + "px",
  190. display: miniInterface.value && !showToolBar.value ? "none" : "block",
  191. };
  192. });
  193. const rightBarTheme = computed(() => {
  194. return {
  195. background: popupColor.value,
  196. marginRight: miniInterface.value
  197. ? 0
  198. : -(store.config.readWidth / 2 + 52) + "px",
  199. display: miniInterface.value && !showToolBar.value ? "none" : "block",
  200. };
  201. });
  202. const isNight = computed(() => theme.value == 6);
  203. // 顶部底部跳转
  204. const top = ref();
  205. const bottom = ref();
  206. const toTop = () => {
  207. jump(top.value);
  208. };
  209. const toBottom = () => {
  210. jump(bottom.value);
  211. };
  212. // 书架路由切换
  213. const router = useRouter();
  214. const toShelf = () => {
  215. router.push("/");
  216. };
  217. // 获取章节内容
  218. const chapterData = ref([]);
  219. const noPoint = ref(true);
  220. const getContent = (index, reloadChapter = true, chapterPos = 0) => {
  221. if (reloadChapter) {
  222. //展示进度条
  223. store.setShowContent(false);
  224. //强制滚回顶层
  225. jump(top.value, { duration: 0 });
  226. //从目录,按钮切换章节时保存进度 预加载时不保存
  227. saveReadingBookProgressToBrowser(index, chapterPos);
  228. chapterData.value = [];
  229. }
  230. let bookUrl = sessionStorage.getItem("bookUrl");
  231. let { title, index: chapterIndex } = catalog.value[index];
  232. loadingWrapper(
  233. API.getBookContent(bookUrl, chapterIndex).then(
  234. (res) => {
  235. if (res.data.isSuccess) {
  236. let data = res.data.data;
  237. let content = data.split(/\n+/);
  238. chapterData.value.push({ index, content, title });
  239. if (reloadChapter) toChapterPos(chapterPos);
  240. } else {
  241. ElMessage({ message: res.data.errorMsg, type: "error" });
  242. let content = [res.data.errorMsg];
  243. chapterData.value.push({ index, content, title });
  244. }
  245. store.setContentLoading(true);
  246. noPoint.value = false;
  247. store.setShowContent(true);
  248. if (!res.data.isSuccess) {
  249. throw res.data;
  250. }
  251. },
  252. (err) => {
  253. ElMessage({ message: "获取章节内容失败", type: "error" });
  254. let content = ["获取章节内容失败!"];
  255. chapterData.value.push({ index, content, title });
  256. store.setShowContent(true);
  257. throw err;
  258. }
  259. )
  260. );
  261. };
  262. // 章节进度跳转和计算
  263. const chapter = ref();
  264. const chapterRef = ref();
  265. const toChapterPos = (pos) => {
  266. nextTick(() => {
  267. if (chapterRef.value.length === 1)
  268. chapterRef.value[0].scrollToReadedLength(pos);
  269. });
  270. };
  271. const onReadedLengthChange = (index, pos) => {
  272. saveReadingBookProgressToBrowser(index, pos);
  273. };
  274. // 文档标题
  275. watchEffect(() => {
  276. document.title = catalog.value[chapterIndex.value]?.title || document.title;
  277. });
  278. // 阅读记录保存浏览器
  279. const saveReadingBookProgressToBrowser = (index, pos) => {
  280. //保存localStorage
  281. let bookUrl = sessionStorage.getItem("bookUrl");
  282. var book = JSON.parse(localStorage.getItem(bookUrl));
  283. book.index = index;
  284. book.chapterPos = pos;
  285. localStorage.setItem(bookUrl, JSON.stringify(book));
  286. //最近阅读
  287. book = JSON.parse(localStorage.getItem("readingRecent"));
  288. book.chapterIndex = index;
  289. book.chapterPos = pos;
  290. localStorage.setItem("readingRecent", JSON.stringify(book));
  291. //保存vuex
  292. chapterIndex.value = index;
  293. chapterPos.value = pos;
  294. //保存sessionStorage
  295. sessionStorage.setItem("chapterIndex", index);
  296. sessionStorage.setItem("chapterPos", String(pos));
  297. };
  298. // 进度同步
  299. // 返回同步 同步请求会在获取书架前完成
  300. // 关闭页面 切换tab 返回桌面 等操作 https://developer.mozilla.org/zh-CN/docs/Web/API/Document/visibilitychange_event
  301. const onVisibilityChange = () => {
  302. if (!bookProgress.value) return;
  303. if (document.visibilityState == "hidden") {
  304. // Safari > 14 和 非Safari移除额外pagehide event
  305. document.removeEventListener("pagehide", onVisibilityChange);
  306. // 常规请求可能会被取消 使用Fetch keep-alive 或者 navigator.sendBeacon
  307. navigator.sendBeacon(
  308. `${import.meta.env.VITE_API || location.origin}/saveBookProgress`,
  309. JSON.stringify(bookProgress.value)
  310. );
  311. }
  312. };
  313. // 定时同步
  314. // 章节切换
  315. const toNextChapter = () => {
  316. store.setContentLoading(true);
  317. let index = chapterIndex.value + 1;
  318. if (typeof catalog.value[index] !== "undefined") {
  319. ElMessage({
  320. message: "下一章",
  321. type: "info",
  322. });
  323. getContent(index);
  324. } else {
  325. ElMessage({
  326. message: "本章是最后一章",
  327. type: "error",
  328. });
  329. }
  330. };
  331. const toPreChapter = () => {
  332. store.setContentLoading(true);
  333. let index = chapterIndex.value - 1;
  334. if (typeof catalog.value[index] !== "undefined") {
  335. ElMessage({
  336. message: "上一章",
  337. type: "info",
  338. });
  339. getContent(index);
  340. } else {
  341. ElMessage({
  342. message: "本章是第一章",
  343. type: "error",
  344. });
  345. }
  346. };
  347. // 无限滚动
  348. const scrollObserve = ref(null);
  349. const loading = ref();
  350. watchEffect(() => {
  351. if (!infiniteLoading.value) {
  352. scrollObserve.value?.disconnect();
  353. } else {
  354. scrollObserve.value?.observe(loading.value);
  355. }
  356. });
  357. const loadMore = () => {
  358. let index = chapterData.value.slice(-1)[0].index;
  359. if (catalog.value.length - 1 > index) {
  360. getContent(index + 1, false);
  361. }
  362. };
  363. // IntersectionObserver回调 底部加载
  364. const handleIScrollObserve = (entries) => {
  365. if (isLoading.value) return;
  366. for (let { isIntersecting } of entries) {
  367. if (!isIntersecting) return;
  368. loadMore();
  369. }
  370. };
  371. // 监听方向键
  372. const handleKeyPress = (event) => {
  373. switch (event.key) {
  374. case "ArrowLeft":
  375. event.stopPropagation();
  376. event.preventDefault();
  377. toPreChapter();
  378. break;
  379. case "ArrowRight":
  380. event.stopPropagation();
  381. event.preventDefault();
  382. toNextChapter();
  383. break;
  384. case "ArrowUp":
  385. event.stopPropagation();
  386. event.preventDefault();
  387. if (document.documentElement.scrollTop === 0) {
  388. ElMessage({
  389. message: "已到达页面顶部",
  390. type: "warn",
  391. });
  392. } else {
  393. jump(0 - document.documentElement.clientHeight + 100);
  394. }
  395. break;
  396. case "ArrowDown":
  397. event.stopPropagation();
  398. event.preventDefault();
  399. if (
  400. document.documentElement.clientHeight +
  401. document.documentElement.scrollTop ===
  402. document.documentElement.scrollHeight
  403. ) {
  404. ElMessage({
  405. message: "已到达页面底部",
  406. type: "warn",
  407. });
  408. } else {
  409. jump(document.documentElement.clientHeight - 100);
  410. }
  411. break;
  412. }
  413. };
  414. onMounted(() => {
  415. //获取书籍数据
  416. let bookUrl = sessionStorage.getItem("bookUrl");
  417. let bookName = sessionStorage.getItem("bookName");
  418. let bookAuthor = sessionStorage.getItem("bookAuthor");
  419. let chapterIndex = Number(sessionStorage.getItem("chapterIndex") || 0);
  420. let chapterPos = Number(sessionStorage.getItem("chapterPos") || 0);
  421. var book = JSON.parse(localStorage.getItem(bookUrl));
  422. if (
  423. book == null ||
  424. chapterIndex != book.index ||
  425. chapterPos != book.chapterPos
  426. ) {
  427. book = {
  428. bookName: bookName,
  429. bookAuthor: bookAuthor,
  430. bookUrl: bookUrl,
  431. index: chapterIndex,
  432. chapterPos: chapterPos,
  433. };
  434. localStorage.setItem(bookUrl, JSON.stringify(book));
  435. }
  436. loadingWrapper(
  437. API.getChapterList(bookUrl).then(
  438. (res) => {
  439. if (!res.data.isSuccess) {
  440. ElMessage({ message: res.data.errorMsg, type: "error" });
  441. setTimeout(toShelf, 500);
  442. return;
  443. }
  444. let data = res.data.data;
  445. store.setCatalog(data);
  446. store.setReadingBook(book);
  447. getContent(chapterIndex, true, chapterPos);
  448. window.addEventListener("keyup", handleKeyPress);
  449. // 兼容Safari < 14
  450. document.addEventListener("visibilitychange", onVisibilityChange);
  451. // 兼容Safari < 14.5
  452. document.addEventListener("pagehide", onVisibilityChange);
  453. //监听底部加载
  454. scrollObserve.value = new IntersectionObserver(handleIScrollObserve, {
  455. rootMargin: "-100% 0% 20% 0%",
  456. });
  457. infiniteLoading.value && scrollObserve.value.observe(loading.value);
  458. //第二次点击同一本书 页面标题不会变化
  459. document.title = null;
  460. document.title = bookName + " | " + catalog.value[chapterIndex].title;
  461. },
  462. (err) => {
  463. ElMessage({ message: "获取书籍目录失败", type: "error" });
  464. throw err;
  465. }
  466. )
  467. );
  468. });
  469. onUnmounted(() => {
  470. window.removeEventListener("keyup", handleKeyPress);
  471. // 兼容Safari < 14
  472. document.removeEventListener("visibilitychange", onVisibilityChange);
  473. // 兼容Safari < 14.5
  474. document.removeEventListener("pagehide", onVisibilityChange);
  475. readSettingsVisible.value = false;
  476. popCataVisible.value = false;
  477. scrollObserve.value?.disconnect();
  478. });
  479. </script>
  480. <style lang="scss" scoped>
  481. :deep(.pop-setting) {
  482. margin-left: 68px;
  483. top: 0;
  484. }
  485. :deep(.pop-cata) {
  486. margin-left: 10px;
  487. }
  488. .chapter-wrapper {
  489. padding: 0 4%;
  490. flex-direction: column;
  491. align-items: center;
  492. :deep(.no-point) {
  493. pointer-events: none;
  494. }
  495. .tool-bar {
  496. position: fixed;
  497. top: 0;
  498. left: 50%;
  499. z-index: 100;
  500. .tools {
  501. display: flex;
  502. flex-direction: column;
  503. .tool-icon {
  504. font-size: 18px;
  505. width: 58px;
  506. height: 48px;
  507. text-align: center;
  508. padding-top: 12px;
  509. cursor: pointer;
  510. outline: none;
  511. .iconfont {
  512. font-family: iconfont;
  513. width: 16px;
  514. height: 16px;
  515. font-size: 16px;
  516. margin: 0 auto 6px;
  517. }
  518. .icon-text {
  519. font-size: 12px;
  520. }
  521. }
  522. }
  523. }
  524. .read-bar {
  525. position: fixed;
  526. bottom: 0;
  527. right: 50%;
  528. z-index: 100;
  529. .tools {
  530. display: flex;
  531. flex-direction: column;
  532. .tool-icon {
  533. font-size: 18px;
  534. width: 42px;
  535. height: 31px;
  536. padding-top: 12px;
  537. text-align: center;
  538. align-items: center;
  539. cursor: pointer;
  540. outline: none;
  541. margin-top: -1px;
  542. .iconfont {
  543. font-family: iconfont;
  544. width: 16px;
  545. height: 16px;
  546. font-size: 16px;
  547. margin: 0 auto 6px;
  548. }
  549. }
  550. }
  551. }
  552. .chapter {
  553. font-family: "Microsoft YaHei", PingFangSC-Regular, HelveticaNeue-Light,
  554. "Helvetica Neue Light", sans-serif;
  555. text-align: left;
  556. padding: 0 65px;
  557. min-height: 100vh;
  558. width: 670px;
  559. margin: 0 auto;
  560. .content {
  561. overflow: hidden;
  562. font-size: 18px;
  563. line-height: 1.8;
  564. font-family: "Microsoft YaHei", PingFangSC-Regular, HelveticaNeue-Light,
  565. "Helvetica Neue Light", sans-serif;
  566. .bottom-bar,
  567. .top-bar {
  568. height: 64px;
  569. }
  570. }
  571. }
  572. }
  573. .day {
  574. :deep(.popup) {
  575. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  576. }
  577. :deep(.tool-icon) {
  578. border: 1px solid rgba(0, 0, 0, 0.1);
  579. margin-top: -1px;
  580. color: #000;
  581. .icon-text {
  582. color: rgba(0, 0, 0, 0.4);
  583. }
  584. }
  585. :deep(.chapter) {
  586. border: 1px solid #d8d8d8;
  587. color: #262626;
  588. }
  589. }
  590. .night {
  591. :deep(.popup) {
  592. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.48), 0 0 6px rgba(0, 0, 0, 0.16);
  593. }
  594. :deep(.tool-icon) {
  595. border: 1px solid #444;
  596. margin-top: -1px;
  597. color: #666;
  598. .icon-text {
  599. color: #666;
  600. }
  601. }
  602. :deep(.chapter) {
  603. border: 1px solid #444;
  604. color: #666;
  605. }
  606. :deep(.popper__arrow) {
  607. background: #666;
  608. }
  609. }
  610. @media screen and (max-width: 750px) {
  611. .chapter-wrapper {
  612. padding: 0;
  613. .tool-bar {
  614. left: 0;
  615. width: 100vw;
  616. margin-left: 0 !important;
  617. .tools {
  618. flex-direction: row;
  619. justify-content: space-between;
  620. .tool-icon {
  621. border: none;
  622. }
  623. }
  624. }
  625. .read-bar {
  626. right: 0;
  627. width: 100vw;
  628. margin-right: 0 !important;
  629. .tools {
  630. flex-direction: row;
  631. justify-content: space-between;
  632. padding: 0 15px;
  633. .tool-icon {
  634. border: none;
  635. width: auto;
  636. .iconfont {
  637. display: inline-block;
  638. }
  639. }
  640. }
  641. }
  642. .chapter {
  643. width: 100vw !important;
  644. padding: 0 20px;
  645. box-sizing: border-box;
  646. }
  647. }
  648. }
  649. </style>