BookChapter.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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 "@/config/themeConfig";
  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. * pc移动端判断 最大阅读宽度修正
  205. * 阅读宽度最小为640px 加上工具栏 68px 52px 取较大值 为 776px
  206. */
  207. const onResize = () => {
  208. store.setMiniInterface(window.innerWidth < 776);
  209. const width = store.config.readWidth; /**包含padding */
  210. checkPageWidth(width);
  211. };
  212. /** 判断阅读宽度是否超出页面 */
  213. const checkPageWidth = (readWidth) => {
  214. if (store.miniInterface) return;
  215. if (readWidth + 2 * 68 > window.innerWidth) store.config.readWidth -= 160;
  216. };
  217. watch(
  218. () => store.config.readWidth,
  219. (width) => checkPageWidth(width)
  220. );
  221. // 顶部底部跳转
  222. const top = ref();
  223. const bottom = ref();
  224. const toTop = () => {
  225. jump(top.value);
  226. };
  227. const toBottom = () => {
  228. jump(bottom.value);
  229. };
  230. // 书架路由切换
  231. const router = useRouter();
  232. const toShelf = () => {
  233. router.push("/");
  234. };
  235. // 获取章节内容
  236. const chapterData = ref([]);
  237. const noPoint = ref(true);
  238. const getContent = (index, reloadChapter = true, chapterPos = 0) => {
  239. if (reloadChapter) {
  240. //展示进度条
  241. store.setShowContent(false);
  242. //强制滚回顶层
  243. jump(top.value, { duration: 0 });
  244. //从目录,按钮切换章节时保存进度 预加载时不保存
  245. saveReadingBookProgressToBrowser(index, chapterPos);
  246. chapterData.value = [];
  247. }
  248. let bookUrl = sessionStorage.getItem("bookUrl");
  249. let { title, index: chapterIndex } = catalog.value[index];
  250. loadingWrapper(
  251. API.getBookContent(bookUrl, chapterIndex).then(
  252. (res) => {
  253. if (res.data.isSuccess) {
  254. let data = res.data.data;
  255. let content = data.split(/\n+/);
  256. chapterData.value.push({ index, content, title });
  257. if (reloadChapter) toChapterPos(chapterPos);
  258. } else {
  259. ElMessage({ message: res.data.errorMsg, type: "error" });
  260. let content = [res.data.errorMsg];
  261. chapterData.value.push({ index, content, title });
  262. }
  263. store.setContentLoading(true);
  264. noPoint.value = false;
  265. store.setShowContent(true);
  266. if (!res.data.isSuccess) {
  267. throw res.data;
  268. }
  269. },
  270. (err) => {
  271. ElMessage({ message: "获取章节内容失败", type: "error" });
  272. let content = ["获取章节内容失败!"];
  273. chapterData.value.push({ index, content, title });
  274. store.setShowContent(true);
  275. throw err;
  276. }
  277. )
  278. );
  279. };
  280. // 章节进度跳转和计算
  281. const chapter = ref();
  282. const chapterRef = ref();
  283. const toChapterPos = (pos) => {
  284. nextTick(() => {
  285. if (chapterRef.value.length === 1)
  286. chapterRef.value[0].scrollToReadedLength(pos);
  287. });
  288. };
  289. const onReadedLengthChange = (index, pos) => {
  290. saveReadingBookProgressToBrowser(index, pos);
  291. };
  292. // 文档标题
  293. watchEffect(() => {
  294. document.title = catalog.value[chapterIndex.value]?.title || document.title;
  295. });
  296. // 阅读记录保存浏览器
  297. const saveReadingBookProgressToBrowser = (index, pos) => {
  298. //保存localStorage
  299. let bookUrl = sessionStorage.getItem("bookUrl");
  300. var book = JSON.parse(localStorage.getItem(bookUrl));
  301. book.index = index;
  302. book.chapterPos = pos;
  303. localStorage.setItem(bookUrl, JSON.stringify(book));
  304. //最近阅读
  305. book = JSON.parse(localStorage.getItem("readingRecent"));
  306. book.chapterIndex = index;
  307. book.chapterPos = pos;
  308. localStorage.setItem("readingRecent", JSON.stringify(book));
  309. //保存vuex
  310. chapterIndex.value = index;
  311. chapterPos.value = pos;
  312. //保存sessionStorage
  313. sessionStorage.setItem("chapterIndex", index);
  314. sessionStorage.setItem("chapterPos", String(pos));
  315. };
  316. // 进度同步
  317. // 返回导航变化 同步请求会在获取书架前完成
  318. /**
  319. * VisibilityChange https://developer.mozilla.org/zh-CN/docs/Web/API/Document/visibilitychange_event
  320. * 监听关闭页面 切换tab 返回桌面 等操作
  321. * 注意不用监听点击链接导航变化 不对Safari<14.5兼容处理
  322. **/
  323. const onVisibilityChange = () => {
  324. if (document.visibilityState == "hidden") {
  325. API.saveBookProgressWithBeacon(bookProgress.value);
  326. }
  327. };
  328. // 定时同步
  329. // 章节切换
  330. const toNextChapter = () => {
  331. store.setContentLoading(true);
  332. let index = chapterIndex.value + 1;
  333. if (typeof catalog.value[index] !== "undefined") {
  334. ElMessage({
  335. message: "下一章",
  336. type: "info",
  337. });
  338. getContent(index);
  339. } else {
  340. ElMessage({
  341. message: "本章是最后一章",
  342. type: "error",
  343. });
  344. }
  345. };
  346. const toPreChapter = () => {
  347. store.setContentLoading(true);
  348. let index = chapterIndex.value - 1;
  349. if (typeof catalog.value[index] !== "undefined") {
  350. ElMessage({
  351. message: "上一章",
  352. type: "info",
  353. });
  354. getContent(index);
  355. } else {
  356. ElMessage({
  357. message: "本章是第一章",
  358. type: "error",
  359. });
  360. }
  361. };
  362. // 无限滚动
  363. let scrollObserver;
  364. const loading = ref();
  365. watchEffect(() => {
  366. if (!infiniteLoading.value) {
  367. scrollObserver?.disconnect();
  368. } else {
  369. scrollObserver?.observe(loading.value);
  370. }
  371. });
  372. const loadMore = () => {
  373. let index = chapterData.value.slice(-1)[0].index;
  374. if (catalog.value.length - 1 > index) {
  375. getContent(index + 1, false);
  376. }
  377. };
  378. // IntersectionObserver回调 底部加载
  379. const onReachBottom = (entries) => {
  380. if (isLoading.value) return;
  381. for (let { isIntersecting } of entries) {
  382. if (!isIntersecting) return;
  383. loadMore();
  384. }
  385. };
  386. // 监听方向键
  387. const handleKeyPress = (event) => {
  388. switch (event.key) {
  389. case "ArrowLeft":
  390. event.stopPropagation();
  391. event.preventDefault();
  392. toPreChapter();
  393. break;
  394. case "ArrowRight":
  395. event.stopPropagation();
  396. event.preventDefault();
  397. toNextChapter();
  398. break;
  399. case "ArrowUp":
  400. event.stopPropagation();
  401. event.preventDefault();
  402. if (document.documentElement.scrollTop === 0) {
  403. ElMessage({
  404. message: "已到达页面顶部",
  405. type: "warn",
  406. });
  407. } else {
  408. jump(0 - document.documentElement.clientHeight + 100);
  409. }
  410. break;
  411. case "ArrowDown":
  412. event.stopPropagation();
  413. event.preventDefault();
  414. if (
  415. document.documentElement.clientHeight +
  416. document.documentElement.scrollTop ===
  417. document.documentElement.scrollHeight
  418. ) {
  419. ElMessage({
  420. message: "已到达页面底部",
  421. type: "warn",
  422. });
  423. } else {
  424. jump(document.documentElement.clientHeight - 100);
  425. }
  426. break;
  427. }
  428. };
  429. onMounted(() => {
  430. //获取书籍数据
  431. let bookUrl = sessionStorage.getItem("bookUrl");
  432. let bookName = sessionStorage.getItem("bookName");
  433. let bookAuthor = sessionStorage.getItem("bookAuthor");
  434. let chapterIndex = Number(sessionStorage.getItem("chapterIndex") || 0);
  435. let chapterPos = Number(sessionStorage.getItem("chapterPos") || 0);
  436. var book = JSON.parse(localStorage.getItem(bookUrl));
  437. if (
  438. book == null ||
  439. chapterIndex != book.index ||
  440. chapterPos != book.chapterPos
  441. ) {
  442. book = {
  443. bookName: bookName,
  444. bookAuthor: bookAuthor,
  445. bookUrl: bookUrl,
  446. index: chapterIndex,
  447. chapterPos: chapterPos,
  448. };
  449. localStorage.setItem(bookUrl, JSON.stringify(book));
  450. }
  451. onResize();
  452. window.addEventListener("resize", onResize);
  453. loadingWrapper(
  454. API.getChapterList(bookUrl).then(
  455. (res) => {
  456. if (!res.data.isSuccess) {
  457. ElMessage({ message: res.data.errorMsg, type: "error" });
  458. setTimeout(toShelf, 500);
  459. return;
  460. }
  461. let data = res.data.data;
  462. store.setCatalog(data);
  463. store.setReadingBook(book);
  464. getContent(chapterIndex, true, chapterPos);
  465. window.addEventListener("keyup", handleKeyPress);
  466. // 兼容Safari < 14
  467. document.addEventListener("visibilitychange", onVisibilityChange);
  468. //监听底部加载
  469. scrollObserver = new IntersectionObserver(onReachBottom, {
  470. rootMargin: "-100% 0% 20% 0%",
  471. });
  472. infiniteLoading.value && scrollObserver.observe(loading.value);
  473. //第二次点击同一本书 页面标题不会变化
  474. document.title = null;
  475. document.title = bookName + " | " + catalog.value[chapterIndex].title;
  476. },
  477. (err) => {
  478. ElMessage({ message: "获取书籍目录失败", type: "error" });
  479. throw err;
  480. }
  481. )
  482. );
  483. });
  484. onUnmounted(() => {
  485. window.removeEventListener("keyup", handleKeyPress);
  486. window.removeEventListener("resize", onResize);
  487. // 兼容Safari < 14
  488. document.removeEventListener("visibilitychange", onVisibilityChange);
  489. readSettingsVisible.value = false;
  490. popCataVisible.value = false;
  491. scrollObserver?.disconnect();
  492. });
  493. </script>
  494. <style lang="scss" scoped>
  495. :deep(.pop-setting) {
  496. margin-left: 68px;
  497. top: 0;
  498. }
  499. :deep(.pop-cata) {
  500. margin-left: 10px;
  501. }
  502. .chapter-wrapper {
  503. padding: 0 4%;
  504. overflow-x: hidden;
  505. :deep(.no-point) {
  506. pointer-events: none;
  507. }
  508. .tool-bar {
  509. position: fixed;
  510. top: 0;
  511. left: 50%;
  512. z-index: 100;
  513. .tools {
  514. display: flex;
  515. flex-direction: column;
  516. .tool-icon {
  517. font-size: 18px;
  518. width: 58px;
  519. height: 48px;
  520. text-align: center;
  521. padding-top: 12px;
  522. cursor: pointer;
  523. outline: none;
  524. .iconfont {
  525. font-family: iconfont;
  526. width: 16px;
  527. height: 16px;
  528. font-size: 16px;
  529. margin: 0 auto 6px;
  530. }
  531. .icon-text {
  532. font-size: 12px;
  533. }
  534. }
  535. }
  536. }
  537. .read-bar {
  538. position: fixed;
  539. bottom: 0;
  540. right: 50%;
  541. z-index: 100;
  542. .tools {
  543. display: flex;
  544. flex-direction: column;
  545. .tool-icon {
  546. font-size: 18px;
  547. width: 42px;
  548. height: 31px;
  549. padding-top: 12px;
  550. text-align: center;
  551. align-items: center;
  552. cursor: pointer;
  553. outline: none;
  554. margin-top: -1px;
  555. .iconfont {
  556. font-family: iconfont;
  557. width: 16px;
  558. height: 16px;
  559. font-size: 16px;
  560. margin: 0 auto 6px;
  561. }
  562. }
  563. }
  564. }
  565. .chapter {
  566. font-family: "Microsoft YaHei", PingFangSC-Regular, HelveticaNeue-Light,
  567. "Helvetica Neue Light", sans-serif;
  568. text-align: left;
  569. padding: 0 65px;
  570. min-height: 100vh;
  571. width: 670px;
  572. margin: 0 auto;
  573. .content {
  574. font-size: 18px;
  575. line-height: 1.8;
  576. font-family: "Microsoft YaHei", PingFangSC-Regular, HelveticaNeue-Light,
  577. "Helvetica Neue Light", sans-serif;
  578. .bottom-bar,
  579. .top-bar {
  580. height: 64px;
  581. }
  582. }
  583. }
  584. }
  585. .day {
  586. :deep(.popup) {
  587. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  588. }
  589. :deep(.tool-icon) {
  590. border: 1px solid rgba(0, 0, 0, 0.1);
  591. margin-top: -1px;
  592. color: #000;
  593. .icon-text {
  594. color: rgba(0, 0, 0, 0.4);
  595. }
  596. }
  597. :deep(.chapter) {
  598. border: 1px solid #d8d8d8;
  599. color: #262626;
  600. }
  601. }
  602. .night {
  603. :deep(.popup) {
  604. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.48), 0 0 6px rgba(0, 0, 0, 0.16);
  605. }
  606. :deep(.tool-icon) {
  607. border: 1px solid #444;
  608. margin-top: -1px;
  609. color: #666;
  610. .icon-text {
  611. color: #666;
  612. }
  613. }
  614. :deep(.chapter) {
  615. border: 1px solid #444;
  616. color: #666;
  617. }
  618. :deep(.popper__arrow) {
  619. background: #666;
  620. }
  621. }
  622. @media screen and (max-width: 776px) {
  623. .chapter-wrapper {
  624. padding: 0;
  625. .tool-bar {
  626. left: 0;
  627. width: 100vw;
  628. margin-left: 0 !important;
  629. .tools {
  630. flex-direction: row;
  631. justify-content: space-between;
  632. .tool-icon {
  633. border: none;
  634. }
  635. }
  636. }
  637. .read-bar {
  638. right: 0;
  639. width: 100vw;
  640. margin-right: 0 !important;
  641. .tools {
  642. flex-direction: row;
  643. justify-content: space-between;
  644. padding: 0 15px;
  645. .tool-icon {
  646. border: none;
  647. width: auto;
  648. .iconfont {
  649. display: inline-block;
  650. }
  651. }
  652. }
  653. }
  654. .chapter {
  655. width: 100vw !important;
  656. padding: 0 20px;
  657. box-sizing: border-box;
  658. }
  659. }
  660. }
  661. </style>