Compare commits

...

20 Commits

Author SHA1 Message Date
chrox bad45a72ba Fix following link after page flipping on macOS, closes #12 2024-12-12 08:49:27 +01:00
chrox 852d16daf3 Fix body element color 2024-12-11 22:10:27 +01:00
chrox 410d57e6f1 Import books from URLs in library page with url parameter 2024-12-11 20:31:41 +01:00
chrox 89c6c4d971 Fix formating authors 2024-12-11 19:29:58 +01:00
chrox 3f4a274412 Add demo library (books from Feedbooks) 2024-12-11 18:57:39 +01:00
chrox 9dd7e6de5e Avoid overriding some background colors 2024-12-11 18:16:02 +01:00
chrox 902a230095 Fix background image color and font server csp 2024-12-11 03:45:51 +01:00
chrox 5a521b6e6f Mount additional fonts when loading documents 2024-12-11 02:31:39 +01:00
chrox fb31212005 Hide some footnotes elements and handle background image in two columns 2024-12-10 23:30:43 +01:00
chrox b57fd8bd3d Support left / right popover on vertical writing documents 2024-12-10 17:57:51 +01:00
chrox 811f377dc0 Update README for more screenshots 2024-12-10 15:23:40 +01:00
chrox 0cbb950c37 Add support of popover footnotes 2024-12-10 14:14:34 +01:00
chrox 6efdbb78e5 Format title and authors when importing books 2024-12-10 14:14:06 +01:00
chrox d940fb8d06 Fix click to page flip not responsive occasionally 2024-12-09 14:40:58 +01:00
chrox 515a133731 Add download readest menu item for readest web 2024-12-08 23:49:38 +01:00
chrox eb90854f69 Fix CSS for background image and background color 2024-12-08 23:15:14 +01:00
chrox 76667fa2f6 Click on media overlay should not trigger a page flip 2024-12-08 23:13:52 +01:00
chrox 7b2bd8a3f8 Add contributing guidelines in README 2024-12-07 19:10:13 +01:00
chrox 8bdcb65883 Fix dynamic route for Next.js
see https://github.com/vercel/next.js/discussions/55393
2024-12-06 23:38:56 +01:00
chrox b985c2664e Add NEXT_PUBLIC_APP_PLATFORM env variable in github workflow 2024-12-06 23:06:04 +01:00
46 changed files with 683 additions and 118 deletions
+11 -4
View File
@@ -56,17 +56,20 @@ jobs:
- name: initialize git submodules
run: git submodule update --init --recursive
- name: Setup pnpm
- name: setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9.14.4
- name: Setup node
- name: setup node
uses: actions/setup-node@v3
with:
node-version: 22
cache: pnpm
- name: install rimraf
run: npm install -g rimraf
- name: install dependencies
run: pnpm install
@@ -83,15 +86,19 @@ jobs:
key: ${{ matrix.config.os }}-cargo-${{ hashFiles('apps/readest-app/src-tauri/Cargo.lock') }}
workspaces: apps/readest-app/src-tauri -> target
- name: Create .env.local file for Next.js
- name: create .env.local file for Next.js
run: |
echo "NEXT_PUBLIC_POSTHOG_KEY=${{ secrets.NEXT_PUBLIC_POSTHOG_KEY }}" >> .env.local
echo "NEXT_PUBLIC_POSTHOG_HOST=${{ secrets.NEXT_PUBLIC_POSTHOG_HOST }}" >> .env.local
echo "NEXT_PUBLIC_DEEPL_API_KEY=${{ secrets.NEXT_PUBLIC_DEEPL_API_KEY }}" >> .env.local
echo "NEXT_PUBLIC_APP_PLATFORM=tauri" >> .env.local
- name: Copy .env.local to apps/readest-app
- name: copy .env.local to apps/readest-app
run: cp .env.local apps/readest-app/.env.local
- name: fix dynamic route for Next.js, see https://github.com/vercel/next.js/discussions/55393
run: rimraf "apps/readest-app/src/app/reader/[ids]"
- name: install dependencies (ubuntu only)
if: matrix.config.os == 'ubuntu-latest'
run: |
+97
View File
@@ -0,0 +1,97 @@
# Contribution Guidelines
When contributing to `Readest`, whether on GitHub or in other community spaces:
- Be respectful, civil, and open-minded.
- Before opening a new pull request, try searching through the [issue tracker](https://github.com/chrox/readest/issues) for known issues or fixes.
- If you want to make code changes based on your personal opinion(s), make sure you open an issue first describing the changes you want to make, and open a pull request only when your suggestions get approved by maintainers.
## How to Contribute
### Prerequisites
In order to not waste your time implementing a change that has already been declined, or is generally not needed, start by [opening an issue](https://github.com/chrox/readest/issues/new/choose) describing the problem you would like to solve.
For the best experience to build Readest for yourself, use a recent version of Node.js and Rust. Refer to the [Tauri documentation](https://v2.tauri.app/start/prerequisites/) for details on setting up the development environment prerequisites on different platforms.
Basically you need to install or update the following development tools:
- **Node.js** and **pnpm** for Next.js development
- **Rust** and **Cargo** for Tauri development
```bash
nvm install v22
nvm use v22
npm install -g pnpm
rustup update
```
### Getting Started
To get started with Readest, follow these steps to clone and build the project.
#### 1. Clone the Repository
```bash
git clone https://github.com/chrox/readest.git
cd readest
git submodule update --init --recursive
```
#### 2. Install Dependencies
```bash
# might need to rerun this when code is updated
pnpm install
# copy pdfjs-dist to Next.js public directory
pnpm --filter @readest/readest-app setup-pdfjs
```
#### 3. Verify Dependencies Installation
To confirm that all dependencies are correctly installed, run the following command:
```bash
pnpm tauri info
```
This command will display information about the installed Tauri dependencies and configuration on your platform. Note that the output may vary depending on the operating system and environment setup. Please review the output specific to your platform for any potential issues.
For Windows targets, “Build Tools for Visual Studio 2022” (or a higher edition of Visual Studio) and the “Desktop development with C++” workflow must be installed. For Windows ARM64 targets, the “VS 2022 C++ ARM64 build tools” and "C++ Clang Compiler for Windows" components must be installed. And make sure `clang` can be found in the path by adding `C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\Llvm\x64\bin` for example in the environment variable `Path`.
#### 4. Build for Development
```bash
pnpm tauri dev
```
#### 5. Build for Production
```bash
pnpm tauri build
```
Now you're all setup and can start implementing your changes.
### Implement your changes
This project is a monorepo. The code for the `readest-app` is in the `app/readest-app` directory. Here are some useful scripts for developing the frontend only without compiling Tauri:
| Command | Description |
| ---------------- | -------------------------------------------------- |
| `pnpm dev-web` | Starts the development server for the web app only |
| `pnpm build-web` | Builds the web app |
### When you're done
Check that your code follows the project's style guidelines by running:
```bash
pnpm build
```
Please also make a manual, functional test of your changes. When all that's done, it's time to file a pull request to upstream and fill out the title and body appropriately.
## Credits
This documented was inspired by the contributing guidelines for [cloudflare/wrangler2](https://github.com/cloudflare/wrangler2/blob/main/CONTRIBUTING.md).
+27 -21
View File
@@ -8,10 +8,11 @@
[Readest][link-website] is an open-source ebook reader designed for immersive and deep reading experiences. Built as a modern rewrite of [Foliate](https://github.com/johnfactotum/foliate), it leverages [Next.js 15](https://github.com/vercel/next.js) and [Tauri v2](https://github.com/tauri-apps/tauri) to offer a seamless cross-platform experience on macOS, Windows, Linux and Web, with support for mobile platforms coming soon.
[![Website][badge-website]][link-website]
[![AGPL Licence][badge-license]](LICENSE)
[![Web App][badge-web-app]][link-web-readest]
[![OS][badge-platforms]][link-website]
[![][badge-discord]][link-discord]
<br>
[![AGPL Licence][badge-license]](LICENSE)
[![Latest release][badge-release]][link-gh-releases]
[![Last commit][badge-last-commit]][link-gh-commits]
[![Commits][badge-commit-activity]][link-gh-pulse]
@@ -24,13 +25,13 @@
<a href="#screenshots">Screenshots</a> •
<a href="#downloads">Downloads</a> •
<a href="#getting-started">Getting Started</a> •
<a href="#contributing">Contributing</a> •
<a href="#contributors">Contributors</a> •
<a href="#license">License</a>
</p>
<div align="center">
<a href="https://readest.com" target="_blank">
<img src="./data/screenshots/readest_landing_preview.png" alt="Readest Banner" width="100%" />
<img src="./data/screenshots/landing_preview.png" alt="Readest Banner" width="100%" />
</a>
</div>
@@ -61,6 +62,7 @@
| **Support iOS and Android** | Expand the APP to work on iOS and Android devices. | 🛠 |
| **Sync Across Platforms** | Synchronize reading progress, notes, and bookmarks across all supported platforms. | 🛠 |
| **Sync with Koreader** | Synchronize reading progress, notes, and bookmarks with [Koreader][link-koreader] devices. | 🔄 |
| **Keyboard Navigation** | Implement vimium-style keybindings for book navigation. | 🔄 |
| **Library Management** | Organize, sort, and manage your entire ebook library. | 🔄 |
| **Support OPDS/Calibre** | Integrate OPDS/Calibre to access online libraries and catalogs. | 🔄 |
| **Text-to-Speech (TTS) Support** | Enable text-to-speech functionality for a more accessible reading experience. | 🔄 |
@@ -74,13 +76,15 @@ Stay tuned for continuous improvements and updates! Contributions and suggestion
## Screenshots
![Annotations](./data/screenshots/annotations.jpeg)
![Annotations](./data/screenshots/annotations.png)
![Wikipedia](./data/screenshots/wikipedia.jpeg)
![DeepL](./data/screenshots/deepl.png)
![DeepL](./data/screenshots/deepl.jpeg)
![Footnote](./data/screenshots/footnote_popover.png)
![Dark Mode](./data/screenshots/dark_mode.jpeg)
![Wikipedia](./data/screenshots/wikipedia_vertical.png)
![Dark Mode](./data/screenshots/dark_mode.png)
---
@@ -96,7 +100,7 @@ The Readest app is available for download! 🥳 🚀
## Requirements
- **Node.js** and **pnpm** for Next.js development
- **Rust and Cargo** for Tauri development
- **Rust** and **Cargo** for Tauri development
For the best experience to build Readest for yourself, use a recent version of Node.js and Rust. Refer to the [Tauri documentation](https://v2.tauri.app/start/prerequisites/) for details on setting up the development environment prerequisites on different platforms.
@@ -152,31 +156,33 @@ pnpm tauri dev
pnpm tauri build
```
## Contributing
Readest is open-source, and contributions are welcome! Feel free to open issues, suggest features, or submit pull requests. Please review our contributing guidelines before you start.
## Contributors
<!---
npx contributor-faces --exclude "*bot*" --limit 100"
--->
Readest is open-source, and contributions are welcome! Feel free to open issues, suggest features, or submit pull requests. Please **review our [contributing guidelines](CONTRIBUTING.md) before you start**. We also welcome you to join our [Discord][link-discord] community for either support or contributing guidance.
[//]: contributor-faces
<a href="https://github.com/chrox"><img src="https://avatars.githubusercontent.com/u/751535?v=4" title="chrox" width="50" height="50"></a>
[//]: contributor-faces
<a href="https://github.com/chrox/readest/graphs/contributors">
<p align="left">
<img width="50" src="https://contrib.rocks/image?repo=chrox/readest" alt="A table of avatars from the project's contributors" />
</p>
</a>
## License
Readest is distributed under the AGPL-3.0 License. See the [LICENSE](<(LICENSE)>) file for details.
Readest is free software: you can redistribute it and/or modify it under the terms of the [GNU Affero General Public License](https://www.gnu.org/licenses/agpl-3.0.html) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. See the [LICENSE](LICENSE) file for details.
The following JavaScript libraries are bundled in this software:
- [foliate-js](https://github.com/johnfactotum/foliate-js), which is MIT licensed.
- [zip.js](https://github.com/gildas-lormeau/zip.js), which is licensed under the BSD-3-Clause license.
- [fflate](https://github.com/101arrowz/fflate), which is MIT licensed.
- [PDF.js](https://github.com/mozilla/pdf.js), which is licensed under Apache License 2.0.
---
<div align="center" style="color: gray;">Happy reading with Readest!</div>
[badge-website]: https://img.shields.io/badge/website-readest.com-orange
[badge-web-app]: https://img.shields.io/badge/read%20online-web.readest.com-orange
[badge-license]: https://img.shields.io/github/license/chrox/readest?color=teal
[badge-release]: https://img.shields.io/github/release/chrox/readest?color=green
[badge-platforms]: https://img.shields.io/badge/OS-macOS%2C%20Windows%2C%20Linux%2C%20Web-green
+1 -1
View File
@@ -7,7 +7,7 @@ const internalHost = process.env.TAURI_DEV_HOST || 'localhost';
const nextConfig = {
// Ensure Next.js uses SSG instead of SSR
// https://nextjs.org/docs/pages/building-your-application/deploying/static-exports
output: process.env['NEXT_PUBLIC_APP_PLATFORM'] === 'web' ? undefined : 'output',
output: process.env['NEXT_PUBLIC_APP_PLATFORM'] === 'web' ? undefined : 'export',
// Note: This feature is required to use the Next.js Image component in SSG mode.
// See https://nextjs.org/docs/messages/export-image-api for different workarounds.
images: {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@readest/readest-app",
"version": "0.8.2",
"version": "0.8.3",
"private": true,
"scripts": {
"dev": "dotenv -e .env.tauri -- next dev",
+1 -1
View File
@@ -13,7 +13,7 @@
"windows": [],
"security": {
"csp": {
"default-src": "'self' 'unsafe-inline' blob: customprotocol: asset: http://asset.localhost ipc: http://ipc.localhost https://fonts.gstatic.com",
"default-src": "'self' 'unsafe-inline' blob: customprotocol: asset: http://asset.localhost ipc: http://ipc.localhost https://fonts.gstatic.com https://db.onlinewebfonts.com",
"connect-src": "'self' blob: asset: http://asset.localhost ipc: http://ipc.localhost https://*.sentry.io https://*.posthog.com https://*.deepl.com https://*.wikipedia.org https://*.wiktionary.org",
"img-src": "'self' blob: data: asset: http://asset.localhost",
"style-src": "'self' 'unsafe-inline' blob: asset: http://asset.localhost",
+2
View File
@@ -16,6 +16,8 @@ export default function RootLayout({ children }: { children: React.ReactNode })
<html lang='en'>
<head>
<title>{title}</title>
<meta name='mobile-web-app-capable' content='yes' />
<meta name='apple-mobile-web-app-status-bar-style' content='default' />
<meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1' />
<link rel='apple-touch-icon' sizes='180x180' href='/apple-touch-icon.png' />
<link rel='icon' href='/favicon.ico' />
@@ -1,11 +1,11 @@
import clsx from 'clsx';
import * as React from 'react';
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { PiPlus } from 'react-icons/pi';
import { MdDelete, MdOpenInNew } from 'react-icons/md';
import { MdCheckCircle, MdCheckCircleOutline } from 'react-icons/md';
import { useRouter } from 'next/navigation';
import { useRouter, useSearchParams } from 'next/navigation';
import Image from 'next/image';
import { Book, BooksGroup } from '@/types/book';
@@ -49,17 +49,41 @@ interface BookshelfProps {
const Bookshelf: React.FC<BookshelfProps> = ({ libraryBooks, isSelectMode, onImportBooks }) => {
const router = useRouter();
const { envConfig } = useEnv();
const searchParams = useSearchParams();
const { envConfig, appService } = useEnv();
const { deleteBook } = useLibraryStore();
const [loading, setLoading] = useState(false);
const [selectedBooks, setSelectedBooks] = useState<string[]>([]);
const [showDeleteAlert, setShowDeleteAlert] = useState(false);
const [clickedImage, setClickedImage] = useState<string | null>(null);
const [importBookUrl] = useState(searchParams.get('url') || '');
const isImportingBook = useRef(false);
React.useEffect(() => {
const { setLibrary } = useLibraryStore();
useEffect(() => {
setSelectedBooks([]);
}, [isSelectMode]);
useEffect(() => {
if (isImportingBook.current) return;
isImportingBook.current = true;
if (importBookUrl && appService) {
const importBook = async () => {
console.log('Importing book from URL:', importBookUrl);
const book = await appService.importBook(importBookUrl, libraryBooks);
if (book) {
setLibrary(libraryBooks);
appService.saveLibraryBooks(libraryBooks);
navigateToReader(router, [book.hash]);
}
};
importBook();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [importBookUrl, appService]);
const bookshelfItems = generateBookshelfItems(libraryBooks);
const handleBookClick = (id: string) => {
@@ -0,0 +1,51 @@
import { useEffect, useRef, useState } from 'react';
import { useEnv } from '@/context/EnvContext';
import { Book } from '@/types/book';
import { getUserLang } from '@/utils/misc';
import libraryEn from '@/data/demo/library.en.json';
import libraryZh from '@/data/demo/library.zh.json';
const libraries = {
en: libraryEn,
zh: libraryZh,
};
interface DemoBooks {
library: string[];
}
export const useDemoBooks = () => {
const { envConfig } = useEnv();
const userLang = getUserLang() as keyof typeof libraries;
const [books, setBooks] = useState<Book[]>([]);
const isLoading = useRef(false);
useEffect(() => {
if (isLoading.current) return;
isLoading.current = true;
const fetchDemoBooks = async () => {
try {
const appService = await envConfig.getAppService();
const demoBooks = libraries[userLang] || (libraries.en as DemoBooks);
const books = await Promise.all(
demoBooks.library.map((url) => appService.importBook(url, [], false, true)),
);
setBooks(books.filter((book) => book !== null) as Book[]);
} catch (error) {
console.error('Failed to import demo books:', error);
}
};
const demoBooksFetchedFlag = localStorage.getItem('demoBooksFetched');
if (!demoBooksFetchedFlag) {
fetchDemoBooks();
localStorage.setItem('demoBooksFetched', 'true');
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return books;
};
+31 -10
View File
@@ -1,7 +1,7 @@
'use client';
import * as React from 'react';
import { useState, useRef } from 'react';
import { useState, useRef, useEffect, Suspense } from 'react';
import { useRouter } from 'next/navigation';
import { Book } from '@/types/book';
@@ -16,10 +16,11 @@ import { useEnv } from '@/context/EnvContext';
import { useTheme } from '@/hooks/useTheme';
import { useLibraryStore } from '@/store/libraryStore';
import { useSettingsStore } from '@/store/settingsStore';
import { useDemoBooks } from './hooks/useDemoBooks';
import Spinner from '@/components/Spinner';
import LibraryHeader from '@/app/library/components/LibraryHeader';
import Bookshelf from '@/app/library/components/Bookshelf';
import LibraryHeader from './components/LibraryHeader';
import Bookshelf from './components/Bookshelf';
const LibraryPage = () => {
const router = useRouter();
@@ -36,8 +37,9 @@ const LibraryPage = () => {
const isInitiating = useRef(false);
const [libraryLoaded, setLibraryLoaded] = useState(false);
const [isSelectMode, setIsSelectMode] = useState(false);
const demoBooks = useDemoBooks();
React.useEffect(() => {
useEffect(() => {
const doAppUpdates = async () => {
if (isTauriAppPlatform()) {
await checkForAppUpdates();
@@ -67,7 +69,7 @@ const LibraryPage = () => {
[],
);
React.useEffect(() => {
useEffect(() => {
if (isInitiating.current) return;
isInitiating.current = true;
@@ -108,6 +110,23 @@ const LibraryPage = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (demoBooks.length > 0 && libraryLoaded) {
const newLibrary = [...libraryBooks];
for (const book of demoBooks) {
const idx = newLibrary.findIndex((b) => b.hash === book.hash);
if (idx === -1) {
newLibrary.push(book);
} else {
newLibrary[idx] = book;
}
}
setLibrary(newLibrary);
appService?.saveLibraryBooks(newLibrary);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [demoBooks, libraryLoaded]);
const importBooks = async (files: [string | File]) => {
setLoading(true);
for (const file of files) {
@@ -188,11 +207,13 @@ const LibraryPage = () => {
{libraryLoaded &&
(libraryBooks.length > 0 ? (
<div className='mt-12 flex-grow overflow-auto px-2'>
<Bookshelf
libraryBooks={libraryBooks}
isSelectMode={isSelectMode}
onImportBooks={handleImportBooks}
/>
<Suspense>
<Bookshelf
libraryBooks={libraryBooks}
isSelectMode={isSelectMode}
onImportBooks={handleImportBooks}
/>
</Suspense>
</div>
) : (
<div className='hero h-screen items-center justify-center'>
@@ -12,6 +12,7 @@ import Ribbon from './Ribbon';
import SettingsDialog from './settings/SettingsDialog';
import Annotator from './annotator/Annotator';
import { useBookDataStore } from '@/store/bookDataStore';
import FootnotePopup from './FootnotePopup';
interface BooksGridProps {
bookKeys: string[];
@@ -60,6 +61,7 @@ const BooksGrid: React.FC<BooksGridProps> = ({ bookKeys, onCloseBook }) => {
onSetSettingsDialogOpen={setFontLayoutSettingsDialogOpen}
/>
<FoliateViewer bookKey={bookKey} bookDoc={bookDoc} config={config} />
<FootnotePopup bookKey={bookKey} bookDoc={bookDoc} />
{viewSettings.scrolled ? null : (
<>
<SectionInfo section={sectionLabel} gapLeft={marginGap} />
@@ -1,11 +1,11 @@
import React, { useEffect, useRef } from 'react';
import { useFoliateEvents } from '../hooks/useFoliateEvents';
import { BookDoc } from '@/libs/document';
import { BookDoc, getDirection } from '@/libs/document';
import { BookConfig, BookNote, BookSearchConfig, BookSearchResult } from '@/types/book';
import { useReaderStore } from '@/store/readerStore';
import { useParallelViewStore } from '@/store/parallelViewStore';
import { useFoliateEvents } from '../hooks/useFoliateEvents';
import { getOSPlatform } from '@/utils/misc';
import { getStyles } from '@/utils/style';
import { getStyles, mountAdditionalFonts } from '@/utils/style';
import { useTheme } from '@/hooks/useTheme';
import { ONE_COLUMN_MAX_INLINE_SIZE } from '@/services/constants';
import {
@@ -76,7 +76,7 @@ const FoliateViewer: React.FC<{
const viewRef = useRef<FoliateView | null>(null);
const isViewCreated = useRef(false);
const { getView, setView: setFoliateView, setProgress, getViewSettings } = useReaderStore();
const { hoveredBookKey, setHoveredBookKey } = useReaderStore();
const { hoveredBookKey, setHoveredBookKey, setViewSettings } = useReaderStore();
const { getParallels } = useParallelViewStore();
const { themeCode } = useTheme();
@@ -118,11 +118,18 @@ const FoliateViewer: React.FC<{
const docLoadHandler = (event: Event) => {
const detail = (event as CustomEvent).detail;
console.log('doc loaded:', detail);
if (detail.doc) {
const writingDir = viewRef.current?.renderer.setStyles && getDirection(detail.doc);
const viewSettings = getViewSettings(bookKey)!;
viewSettings.vertical = writingDir?.vertical || false;
setViewSettings(bookKey, viewSettings);
if (viewSettings.scrolled && shouldAutoHideScrollbar) {
handleScrollbarAutoHide(detail.doc);
}
mountAdditionalFonts(detail.doc);
if (!detail.doc.isEventListenersAdded) {
detail.doc.isEventListenersAdded = true;
detail.doc.addEventListener('keydown', handleKeydown.bind(null, bookKey));
@@ -237,11 +244,12 @@ const FoliateViewer: React.FC<{
const view = wrappedFoliateView(document.createElement('foliate-view') as FoliateView);
document.body.append(view);
containerRef.current?.appendChild(view);
setFoliateView(bookKey, view);
await view.open(bookDoc);
// make sure we can listen renderer events after opening book
viewRef.current = view;
setFoliateView(bookKey, view);
const viewSettings = getViewSettings(bookKey)!;
view.renderer.setStyles?.(getStyles(viewSettings, themeCode));
@@ -0,0 +1,133 @@
import React, { useEffect, useRef, useState } from 'react';
import { BookDoc } from '@/libs/document';
import { useReaderStore } from '@/store/readerStore';
import { useFoliateEvents } from '../hooks/useFoliateEvents';
import { useTheme } from '@/hooks/useTheme';
import { getStyles } from '@/utils/style';
import { getPopupPosition, getPosition, Position } from '@/utils/sel';
import { FoliateView } from './FoliateViewer';
import { FootnoteHandler } from 'foliate-js/footnotes.js';
import Popup from '@/components/Popup';
interface FootnotePopupProps {
bookKey: string;
bookDoc: BookDoc;
}
const popupWidth = 360;
const popupHeight = 88;
const popupPadding = 10;
const FootnotePopup: React.FC<FootnotePopupProps> = ({ bookKey, bookDoc }) => {
const footnoteRef = useRef<HTMLDivElement>(null);
const footnoteViewRef = useRef<FoliateView | null>(null);
const [trianglePosition, setTrianglePosition] = useState<Position | null>();
const [popupPosition, setPopupPosition] = useState<Position | null>();
const [showPopup, setShowPopup] = useState(false);
const { getView, getViewSettings } = useReaderStore();
const { themeCode } = useTheme();
const view = getView(bookKey);
const footnoteHandler = new FootnoteHandler();
useEffect(() => {
const handleBeforeRender = (e: Event) => {
const detail = (e as CustomEvent).detail;
const { view } = detail;
footnoteViewRef.current = view;
footnoteRef.current?.replaceChildren(view);
const { renderer } = view;
renderer.setAttribute('flow', 'scrolled');
renderer.setAttribute('margin', '0px');
renderer.setAttribute('gap', '5%');
const viewSettings = getViewSettings(bookKey)!;
renderer.setStyles?.(getStyles(viewSettings, themeCode));
};
const handleRender = (e: Event) => {
const detail = (e as CustomEvent).detail;
console.log('render footnote', detail);
setShowPopup(true);
};
footnoteHandler.addEventListener('before-render', handleBeforeRender);
footnoteHandler.addEventListener('render', handleRender);
return () => {
footnoteHandler.removeEventListener('before-render', handleBeforeRender);
footnoteHandler.removeEventListener('render', handleRender);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [view]);
const docLinkHandler = async (event: Event) => {
const detail = (event as CustomEvent).detail;
console.log('doc link click', detail);
const gridFrame = document.querySelector(`#gridcell-${bookKey}`);
if (!gridFrame) return;
const rect = gridFrame.getBoundingClientRect();
const viewSettings = getViewSettings(bookKey)!;
const triangPos = getPosition(detail.a, rect, viewSettings.vertical);
const popupPos = getPopupPosition(triangPos, rect, popupWidth, popupHeight, popupPadding);
setTrianglePosition(triangPos);
setPopupPosition(popupPos);
footnoteHandler.handle(bookDoc, event)?.catch((err) => {
console.warn(err);
const detail = (event as CustomEvent).detail;
view?.goTo(detail.href);
});
};
const closePopup = () => {
const view = footnoteRef.current?.querySelector('foliate-view') as FoliateView;
view?.close();
view?.remove();
};
const handleDismissPopup = () => {
closePopup();
setPopupPosition(null);
setTrianglePosition(null);
setShowPopup(false);
};
useFoliateEvents(view, {
onLinkClick: docLinkHandler,
});
useEffect(() => {
if (footnoteViewRef.current) {
footnoteRef.current?.replaceChildren(footnoteViewRef.current);
}
}, [footnoteRef]);
return (
<div>
{showPopup && (
<div
className='fixed inset-0'
onClick={handleDismissPopup}
onContextMenu={handleDismissPopup}
/>
)}
<Popup
width={popupWidth}
height={popupHeight}
position={showPopup ? popupPosition! : undefined}
trianglePosition={showPopup ? trianglePosition! : undefined}
className='select-text overflow-y-auto'
>
<div
className=''
ref={footnoteRef}
style={{
width: `${popupWidth}px`,
height: `${popupHeight}px`,
}}
></div>
</Popup>
</div>
);
};
export default FootnotePopup;
@@ -30,13 +30,14 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
const { envConfig } = useEnv();
const { settings } = useSettingsStore();
const { getConfig, saveConfig, getBookData, updateBooknotes } = useBookDataStore();
const { getProgress, getView, getViewsById } = useReaderStore();
const { getProgress, getView, getViewsById, getViewSettings } = useReaderStore();
const { isNotebookPinned, isNotebookVisible } = useNotebookStore();
const { setNotebookVisible, setNotebookNewAnnotation } = useNotebookStore();
const config = getConfig(bookKey)!;
const progress = getProgress(bookKey)!;
const bookData = getBookData(bookKey)!;
const view = getView(bookKey);
const viewSettings = getViewSettings(bookKey)!;
const isShowingPopup = useRef(false);
const isTextSelected = useRef(false);
@@ -48,6 +49,7 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
const [trianglePosition, setTrianglePosition] = useState<Position>();
const [annotPopupPosition, setAnnotPopupPosition] = useState<Position>();
const [dictPopupPosition, setDictPopupPosition] = useState<Position>();
const [translatorPopupPosition, setTranslatorPopupPosition] = useState<Position>();
const [toastMessage, setToastMessage] = useState('');
const [highlightOptionsVisible, setHighlightOptionsVisible] = useState(false);
@@ -59,7 +61,9 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
);
const dictPopupWidth = 480;
const dictPopupHeight = 360;
const dictPopupHeight = 300;
const transPopupWidth = 480;
const transPopupHeight = 360;
const annotPopupWidth = 280;
const annotPopupHeight = 44;
const popupPadding = 10;
@@ -105,7 +109,7 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
setSelection(selection);
};
useFoliateEvents(view, { onLoad, onDrawAnnotation, onShowAnnotation }, [config]);
useFoliateEvents(view, { onLoad, onDrawAnnotation, onShowAnnotation });
const handleDismissPopup = () => {
setSelection(null);
@@ -148,7 +152,7 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
const gridFrame = document.querySelector(`#gridcell-${bookKey}`);
if (!gridFrame) return;
const rect = gridFrame.getBoundingClientRect();
const triangPos = getPosition(selection.range, rect);
const triangPos = getPosition(selection.range, rect, viewSettings.vertical);
const annotPopupPos = getPopupPosition(
triangPos,
rect,
@@ -163,13 +167,22 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
dictPopupHeight,
popupPadding,
);
const transPopupPos = getPopupPosition(
triangPos,
rect,
transPopupWidth,
transPopupHeight,
popupPadding,
);
if (triangPos.point.x == 0 || triangPos.point.y == 0) return;
setShowAnnotPopup(true);
setAnnotPopupPosition(annotPopupPos);
setDictPopupPosition(dictPopupPos);
setTranslatorPopupPosition(transPopupPos);
setTrianglePosition(triangPos);
isShowingPopup.current = true;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selection, bookKey]);
useEffect(() => {
@@ -357,13 +370,13 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
popupHeight={dictPopupHeight}
/>
)}
{showDeepLPopup && trianglePosition && dictPopupPosition && (
{showDeepLPopup && trianglePosition && translatorPopupPosition && (
<DeepLPopup
text={selection?.text as string}
position={dictPopupPosition}
position={translatorPopupPosition}
trianglePosition={trianglePosition}
popupWidth={dictPopupWidth}
popupHeight={dictPopupHeight}
popupWidth={transPopupWidth}
popupHeight={transPopupHeight}
/>
)}
{showAnnotPopup && trianglePosition && annotPopupPosition && (
@@ -120,8 +120,7 @@ const DeepLPopup: React.FC<DeepLPopupProps> = ({
width={popupWidth}
height={popupHeight}
position={position}
className='bg-neutral select-text'
triangleClassName='text-neutral'
className='select-text'
>
<div className='text-neutral-content relative h-[50%] overflow-y-auto border-b border-neutral-400/75 p-4 font-sans'>
<div className='mb-2 flex items-center justify-between'>
@@ -96,7 +96,8 @@ const WikipediaPopup: React.FC<WikipediaPopupProps> = ({
}
};
const langCode = typeof lang === 'string' ? lang : lang?.[0];
const bookLang = typeof lang === 'string' ? lang : lang?.[0];
const langCode = bookLang ? bookLang.split('-')[0]! : 'en';
fetchSummary(text, langCode);
}, [text, lang]);
@@ -107,8 +108,7 @@ const WikipediaPopup: React.FC<WikipediaPopupProps> = ({
height={popupHeight}
position={position}
trianglePosition={trianglePosition}
className='bg-neutral select-text overflow-y-auto'
triangleClassName='text-neutral'
className='select-text overflow-y-auto'
>
<main className='p-2 font-sans'></main>
<footer className='hidden data-[state=loaded]:block data-[state=error]:hidden data-[state=loading]:hidden'>
@@ -163,8 +163,7 @@ const WiktionaryPopup: React.FC<WiktionaryPopupProps> = ({
width={popupWidth}
height={popupHeight}
position={position}
className='bg-neutral select-text overflow-y-auto'
triangleClassName='text-neutral'
className='select-text overflow-y-auto'
>
<main className='p-4 font-sans' />
<footer className='hidden data-[state=loaded]:block data-[state=error]:hidden data-[state=loading]:hidden'>
@@ -1,7 +1,6 @@
import React from 'react';
import Image from 'next/image';
import { MdInfoOutline } from 'react-icons/md';
import { formatAuthors } from '@/utils/book';
interface BookCardProps {
cover: string;
@@ -24,7 +23,7 @@ const BookCard: React.FC<BookCardProps> = ({ cover, title, author }) => {
/>
<div className='min-w-0 flex-1'>
<h4 className='line-clamp-2 w-[90%] text-sm font-semibold'>{title}</h4>
<p className='text-neutral-content truncate text-xs'>{formatAuthors(author)}</p>
<p className='text-neutral-content truncate text-xs'>{author}</p>
</div>
<button
className='btn btn-ghost hover:bg-base-300 h-6 min-h-6 w-6 rounded-full p-0 transition-colors'
@@ -3,8 +3,10 @@ import Image from 'next/image';
import MenuItem from '@/components/MenuItem';
import { setAboutDialogVisible } from '@/components/AboutWindow';
import useBooksManager from '../../hooks/useBooksManager';
import { useLibraryStore } from '@/store/libraryStore';
import { isWebAppPlatform } from '@/services/environment';
import { DOWNLOAD_READEST_URL } from '@/services/constants';
import useBooksManager from '../../hooks/useBooksManager';
interface BookMenuProps {
setIsDropdownOpen?: (isOpen: boolean) => void;
@@ -25,6 +27,12 @@ const BookMenu: React.FC<BookMenuProps> = ({ setIsDropdownOpen }) => {
setAboutDialogVisible(true);
setIsDropdownOpen?.(false);
};
const downloadReadest = () => {
window.open(DOWNLOAD_READEST_URL, '_blank');
setIsDropdownOpen?.(false);
};
const isWebApp = isWebAppPlatform();
return (
<div
@@ -56,6 +64,7 @@ const BookMenu: React.FC<BookMenuProps> = ({ setIsDropdownOpen }) => {
</MenuItem>
<MenuItem label='Reload Page' noIcon shortcut='Shift+R' onClick={handleReloadPage} />
<hr className='border-base-200 my-1' />
{isWebApp && <MenuItem label='Download Readest' noIcon onClick={downloadReadest} />}
<MenuItem label='About Readest' noIcon onClick={showAboutReadest} />
</div>
);
@@ -4,18 +4,16 @@ import { FoliateView } from '@/app/reader/components/FoliateViewer';
type FoliateEventHandler = {
onLoad?: (event: Event) => void;
onRelocate?: (event: Event) => void;
onLinkClick?: (event: Event) => void;
onRendererRelocate?: (event: Event) => void;
onDrawAnnotation?: (event: Event) => void;
onShowAnnotation?: (event: Event) => void;
};
export const useFoliateEvents = (
view: FoliateView | null,
handlers?: FoliateEventHandler,
dependencies: React.DependencyList = [],
) => {
export const useFoliateEvents = (view: FoliateView | null, handlers?: FoliateEventHandler) => {
const onLoad = handlers?.onLoad;
const onRelocate = handlers?.onRelocate;
const onLinkClick = handlers?.onLinkClick;
const onRendererRelocate = handlers?.onRendererRelocate;
const onDrawAnnotation = handlers?.onDrawAnnotation;
const onShowAnnotation = handlers?.onShowAnnotation;
@@ -24,6 +22,7 @@ export const useFoliateEvents = (
if (!view) return;
if (onLoad) view.addEventListener('load', onLoad);
if (onRelocate) view.addEventListener('relocate', onRelocate);
if (onLinkClick) view.addEventListener('link', onLinkClick);
if (onRendererRelocate) view.renderer.addEventListener('relocate', onRendererRelocate);
if (onDrawAnnotation) view.addEventListener('draw-annotation', onDrawAnnotation);
if (onShowAnnotation) view.addEventListener('show-annotation', onShowAnnotation);
@@ -31,10 +30,11 @@ export const useFoliateEvents = (
return () => {
if (onLoad) view.removeEventListener('load', onLoad);
if (onRelocate) view.removeEventListener('relocate', onRelocate);
if (onLinkClick) view.removeEventListener('link', onLinkClick);
if (onRendererRelocate) view.renderer.removeEventListener('relocate', onRendererRelocate);
if (onDrawAnnotation) view.removeEventListener('draw-annotation', onDrawAnnotation);
if (onShowAnnotation) view.removeEventListener('show-annotation', onShowAnnotation);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [view, ...dependencies]);
}, [view]);
};
@@ -104,7 +104,7 @@ export const handleClick = (bookKey: string, event: MouseEvent) => {
if (Date.now() - lastClickTime >= doubleClickThreshold) {
let element: HTMLElement | null = event.target as HTMLElement;
while (element) {
if (element.tagName.toLowerCase() === 'a') {
if (['sup', 'a', 'audio', 'video'].includes(element.tagName.toLowerCase())) {
return;
}
element = element.parentElement;
+46 -13
View File
@@ -12,8 +12,8 @@ const Popup = ({
}: {
width: number;
height: number;
position: Position;
trianglePosition: Position;
position?: Position;
trianglePosition?: Position;
children: React.ReactNode;
className?: string;
triangleClassName?: string;
@@ -21,24 +21,57 @@ const Popup = ({
}) => (
<div>
<div
className={`triangle absolute z-10 ${triangleClassName}`}
className={`triangle text-base-200 absolute z-10 ${triangleClassName}`}
style={{
left: `${trianglePosition.point.x}px`,
top: `${trianglePosition.point.y}px`,
borderLeft: '6px solid transparent',
borderRight: '6px solid transparent',
borderBottom: trianglePosition.dir === 'up' ? 'none' : `6px solid`,
borderTop: trianglePosition.dir === 'up' ? `6px solid` : 'none',
transform: 'translateX(-50%)',
left:
trianglePosition?.dir === 'left'
? `${trianglePosition.point.x}px`
: trianglePosition?.dir === 'right'
? `${trianglePosition.point.x}px`
: `${trianglePosition ? trianglePosition.point.x : -999}px`,
top:
trianglePosition?.dir === 'up'
? `${trianglePosition.point.y}px`
: trianglePosition?.dir === 'down'
? `${trianglePosition.point.y}px`
: `${trianglePosition ? trianglePosition.point.y : -999}px`,
borderLeft:
trianglePosition?.dir === 'right'
? 'none'
: trianglePosition?.dir === 'left'
? `6px solid`
: '6px solid transparent',
borderRight:
trianglePosition?.dir === 'left'
? 'none'
: trianglePosition?.dir === 'right'
? `6px solid`
: '6px solid transparent',
borderTop:
trianglePosition?.dir === 'down'
? 'none'
: trianglePosition?.dir === 'up'
? `6px solid`
: '6px solid transparent',
borderBottom:
trianglePosition?.dir === 'up'
? 'none'
: trianglePosition?.dir === 'down'
? `6px solid`
: '6px solid transparent',
transform:
trianglePosition?.dir === 'left' || trianglePosition?.dir === 'right'
? 'translateY(-50%)'
: 'translateX(-50%)',
}}
/>
<div
className={`absolute rounded-lg font-sans shadow-lg ${className}`}
className={`bg-base-200 absolute rounded-lg font-sans shadow-xl ${className}`}
style={{
width: `${width}px`,
height: `${height}px`,
left: `${position.point.x}px`,
top: `${position.point.y}px`,
left: `${position ? position.point.x : -999}px`,
top: `${position ? position.point.y : -999}px`,
...additionalStyle,
}}
>
@@ -0,0 +1,10 @@
{
"library": [
"https://cdn.readest.com/books/a-room-of-one-s-own.epub",
"https://cdn.readest.com/books/hamlet.epub",
"https://cdn.readest.com/books/meditations.epub",
"https://cdn.readest.com/books/the-great-gatsby.epub",
"https://cdn.readest.com/books/the-scarlet-letter.epub",
"https://cdn.readest.com/books/this-side-of-paradise.epub"
]
}
@@ -0,0 +1,3 @@
{
"library": ["https://cdn.readest.com/books/four-great-classics.epub"]
}
+8
View File
@@ -166,3 +166,11 @@ export class DocumentLoader {
return { book, format } as { book: BookDoc; format: BookFormat };
}
}
export const getDirection = (doc: Document) => {
const { defaultView } = doc;
const { writingMode, direction } = defaultView!.getComputedStyle(doc.body);
const vertical = writingMode === 'vertical-rl' || writingMode === 'vertical-lr';
const rtl = doc.body.dir === 'rtl' || direction === 'rtl' || doc.documentElement.dir === 'rtl';
return { vertical, rtl };
};
+25 -11
View File
@@ -11,6 +11,8 @@ import {
getConfigFilename,
getLibraryFilename,
INIT_BOOK_CONFIG,
formatTitle,
formatAuthors,
} from '@/utils/book';
import { RemoteFile } from '@/utils/file';
import { partialMD5 } from '@/utils/md5';
@@ -23,6 +25,7 @@ import {
SYSTEM_SETTINGS_VERSION,
DEFAULT_BOOK_SEARCH_CONFIG,
} from './constants';
import { isValidURL } from '@/utils/misc';
export abstract class BaseAppService implements AppService {
localBooksDir: string = '';
@@ -93,6 +96,8 @@ export abstract class BaseAppService implements AppService {
async importBook(
file: string | File,
books: Book[],
saveBook: boolean = true,
saveCover: boolean = true,
overwrite: boolean = false,
): Promise<Book | null> {
try {
@@ -130,21 +135,21 @@ export abstract class BaseAppService implements AppService {
const book: Book = {
hash,
format,
title: loadedBook.metadata.title,
author: loadedBook.metadata.author,
title: formatTitle(loadedBook.metadata.title),
author: formatAuthors(loadedBook.metadata.language, loadedBook.metadata.author),
lastUpdated: Date.now(),
};
if (!(await this.fs.exists(getDir(book), 'Books'))) {
await this.fs.createDir(getDir(book), 'Books');
}
if (!(await this.fs.exists(getFilename(book), 'Books')) || overwrite) {
if (typeof file === 'string') {
if (saveBook && (!(await this.fs.exists(getFilename(book), 'Books')) || overwrite)) {
if (typeof file === 'string' && !isValidURL(file)) {
await this.fs.copyFile(file, getFilename(book), 'Books');
} else {
await this.fs.writeFile(getFilename(book), 'Books', await file.arrayBuffer());
await this.fs.writeFile(getFilename(book), 'Books', await fileobj.arrayBuffer());
}
}
if (!(await this.fs.exists(getCoverFilename(book), 'Books')) || overwrite) {
if (saveCover && (!(await this.fs.exists(getCoverFilename(book), 'Books')) || overwrite)) {
const cover = await loadedBook.getCover();
if (cover) {
await this.fs.writeFile(getCoverFilename(book), 'Books', await cover.arrayBuffer());
@@ -156,6 +161,9 @@ export abstract class BaseAppService implements AppService {
books.splice(0, 0, book);
}
if (typeof file === 'string' && isValidURL(file)) {
book.url = file;
}
if (this.appPlatform === 'web') {
book.coverImageUrl = await this.getCoverImageBlobUrl(book);
} else {
@@ -178,13 +186,19 @@ export abstract class BaseAppService implements AppService {
}
async loadBookContent(book: Book, settings: SystemSettings): Promise<BookContent> {
const fp = getFilename(book);
let file: File;
if (this.appPlatform === 'web') {
const content = await this.fs.readFile(fp, 'Books', 'binary');
file = new File([content], fp);
const fp = getFilename(book);
if (await this.fs.exists(fp, 'Books')) {
if (this.appPlatform === 'web') {
const content = await this.fs.readFile(fp, 'Books', 'binary');
file = new File([content], fp);
} else {
file = await new RemoteFile(this.fs.getURL(`${this.localBooksDir}/${fp}`), fp).open();
}
} else if (book.url) {
file = await new RemoteFile(book.url).open();
} else {
file = await new RemoteFile(this.fs.getURL(`${this.localBooksDir}/${fp}`), fp).open();
throw new Error('Book file not found');
}
return { book, file, config: await this.loadBookConfig(book, settings) };
}
@@ -42,6 +42,7 @@ export const DEFAULT_BOOK_LAYOUT: BookLayout = {
maxInlineSize: 720,
maxBlockSize: 1440,
animated: false,
vertical: false,
};
export const DEFAULT_BOOK_STYLE: BookStyle = {
@@ -80,3 +81,5 @@ export const MONOSPACE_FONTS = ['Fira Code', 'Lucida Console', 'Consolas', 'Cour
export const ONE_COLUMN_MAX_INLINE_SIZE = 9999;
export const BOOK_IDS_SEPARATOR = '+';
export const DOWNLOAD_READEST_URL = 'https://readest.com?utm_source=readest_web';
@@ -18,6 +18,7 @@ import { type as osType } from '@tauri-apps/plugin-os';
import { Book } from '@/types/book';
import { ToastType, FileSystem, BaseDir, AppPlatform } from '@/types/system';
import { getCoverFilename } from '@/utils/book';
import { isValidURL } from '@/utils/misc';
import { BaseAppService } from './appService';
import { LOCAL_BOOKS_SUBDIR } from './constants';
@@ -51,7 +52,7 @@ const resolvePath = (fp: string, base: BaseDir): { baseDir: number; base: BaseDi
export const nativeFileSystem: FileSystem = {
getURL(path: string) {
return convertFileSrc(path);
return isValidURL(path) ? path : convertFileSrc(path);
},
async getBlobURL(path: string, base: BaseDir) {
const content = await this.readFile(path, base, 'binary');
@@ -1,6 +1,7 @@
import { Book } from '@/types/book';
import { ToastType, FileSystem, BaseDir, AppPlatform } from '@/types/system';
import { getCoverFilename } from '@/utils/book';
import { isValidURL } from '@/utils/misc';
import { BaseAppService } from './appService';
import { LOCAL_BOOKS_SUBDIR } from './constants';
@@ -37,7 +38,11 @@ async function openIndexedDB(): Promise<IDBDatabase> {
const indexedDBFileSystem: FileSystem = {
getURL(path: string) {
return URL.createObjectURL(new Blob([path]));
if (isValidURL(path)) {
return path;
} else {
return URL.createObjectURL(new Blob([path]));
}
},
async getBlobURL(path: string, base: BaseDir) {
try {
+3
View File
@@ -4,6 +4,8 @@ export type HighlightStyle = 'highlight' | 'underline' | 'squiggly';
export type HighlightColor = 'red' | 'yellow' | 'green' | 'blue' | 'violet';
export interface Book {
// if Book is a remote book we just lazy load the book content
url?: string;
hash: string;
format: BookFormat;
title: string;
@@ -42,6 +44,7 @@ export interface BookLayout {
maxInlineSize: number;
maxBlockSize: number;
animated: boolean;
vertical: boolean;
}
export interface BookStyle {
+7 -1
View File
@@ -29,7 +29,13 @@ export interface AppService {
loadSettings(): Promise<SystemSettings>;
saveSettings(settings: SystemSettings): Promise<void>;
importBook(file: string | File, books: Book[], overwrite?: boolean): Promise<Book | null>;
importBook(
file: string | File,
books: Book[],
saveBook?: boolean,
saveCover?: boolean,
overwrite?: boolean,
): Promise<Book | null>;
deleteBook(book: Book): Promise<void>;
loadBookConfig(book: Book, settings: SystemSettings): Promise<BookConfig>;
saveBookConfig(book: Book, config: BookConfig, settings?: SystemSettings): Promise<void>;
+29 -5
View File
@@ -1,6 +1,6 @@
import { EXTS } from '@/libs/document';
import { Book, BookConfig } from '@/types/book';
import { makeSafeFilename } from './misc';
import { getUserLang, makeSafeFilename } from './misc';
export const getDir = (book: Book) => {
return `${book.hash}`;
@@ -37,18 +37,38 @@ interface Contributor {
name: LanguageMap;
}
const userLang = getUserLang();
const formatLanguageMap = (x: string | LanguageMap): string => {
if (!x) return '';
if (typeof x === 'string') return x;
const keys = Object.keys(x);
return x[keys[0]!]!;
return x[userLang] || x[keys[0]!]!;
};
const listFormat = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
const listFormat = (lang: string) => {
if (lang === 'zh') {
return new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });
} else {
return new Intl.ListFormat(lang, { style: 'long', type: 'conjunction' });
}
};
export const formatAuthors = (contributors: string | Contributor | [string | Contributor]) =>
const getBookLangCode = (lang: string | string[] | undefined) => {
try {
const bookLang = typeof lang === 'string' ? lang : lang?.[0];
return bookLang ? bookLang.split('-')[0]! : 'en';
} catch {
return 'en';
}
};
export const formatAuthors = (
bookLang: string | string[] | undefined,
contributors: string | Contributor | [string | Contributor],
) =>
Array.isArray(contributors)
? listFormat.format(
? listFormat(getBookLangCode(bookLang)).format(
contributors.map((contributor) =>
typeof contributor === 'string' ? contributor : formatLanguageMap(contributor?.name),
),
@@ -56,3 +76,7 @@ export const formatAuthors = (contributors: string | Contributor | [string | Con
: typeof contributors === 'string'
? contributors
: formatLanguageMap(contributors?.name);
export const formatTitle = (title: string | LanguageMap) => {
return typeof title === 'string' ? title : formatLanguageMap(title);
};
+11
View File
@@ -23,6 +23,8 @@ export const makeSafeFilename = (filename: string, replacement = '_') => {
return safeName.trim();
};
export const getUserLang = () => navigator?.language.split('-')[0] || 'en';
export const getOSPlatform = () => {
const userAgent = navigator.userAgent.toLowerCase();
@@ -34,3 +36,12 @@ export const getOSPlatform = () => {
return '';
};
export const isValidURL = (url: string, allowedSchemes: string[] = ['http', 'https']) => {
try {
const { protocol } = new URL(url);
return allowedSchemes.some((scheme) => `${scheme}:` === protocol);
} catch {
return false;
}
};
+41 -10
View File
@@ -15,7 +15,7 @@ export interface Point {
y: number;
}
export type PositionDir = 'up' | 'down';
export type PositionDir = 'up' | 'down' | 'left' | 'right';
export interface Position {
point: Point;
@@ -42,9 +42,15 @@ const frameRect = (frame: Frame, rect: Rect, sx = 1, sy = 1) => {
const pointIsInView = ({ x, y }: Point) =>
x > 0 && y > 0 && x < window.innerWidth && y < window.innerHeight;
const getIframeElement = (range: Range): HTMLIFrameElement | null => {
let node: Node | null = range.commonAncestorContainer;
const getIframeElement = (nodeElement: Range | Element): HTMLIFrameElement | null => {
let node: Node | null;
if (nodeElement && typeof nodeElement === 'object' && 'tagName' in nodeElement) {
node = nodeElement as Element;
} else if (nodeElement && typeof nodeElement === 'object' && 'collapse' in nodeElement) {
node = nodeElement.commonAncestorContainer;
} else {
node = nodeElement;
}
while (node) {
if (node.nodeType === Node.DOCUMENT_NODE) {
const doc = node as Document;
@@ -58,8 +64,7 @@ const getIframeElement = (range: Range): HTMLIFrameElement | null => {
return null;
};
export const getPosition = (target: Range, rect: Rect) => {
// TODO: vertical text
export const getPosition = (target: Range | Element, rect: Rect, isVertical: boolean = false) => {
const frameElement = getIframeElement(target);
const transform = frameElement ? getComputedStyle(frameElement).transform : '';
const match = transform.match(/matrix\((.+)\)/);
@@ -69,6 +74,22 @@ export const getPosition = (target: Range, rect: Rect) => {
const rects = Array.from(target.getClientRects());
const first = frameRect(frame, rects[0] as Rect, sx, sy);
const last = frameRect(frame, rects.at(-1) as Rect, sx, sy);
if (isVertical) {
const leftSpace = first.left - rect.left;
const rightSpace = rect.right - first.right;
const dir = leftSpace > rightSpace ? 'left' : 'right';
const position = {
point: {
x: dir === 'left' ? first.left - rect.left - 6 : first.right - rect.left + 6,
y: (first.top + first.bottom) / 2 - rect.top,
},
dir,
} as Position;
const inView = pointIsInView(position.point);
return inView ? position : ({ point: { x: 0, y: 0 }, dir } as Position);
}
const start = {
point: { x: (first.left + first.right) / 2 - rect.left, y: first.top - rect.top - 12 },
dir: 'up',
@@ -92,10 +113,20 @@ export const getPopupPosition = (
popupHeightPx: number,
popupPaddingPx: number,
) => {
const popupPoint = {
x: position.point.x - popupWidthPx / 2,
y: position.dir === 'up' ? position.point.y - popupHeightPx : position.point.y + 6,
};
const popupPoint = { x: 0, y: 0 };
if (position.dir === 'up') {
popupPoint.x = position.point.x - popupWidthPx / 2;
popupPoint.y = position.point.y - popupHeightPx;
} else if (position.dir === 'down') {
popupPoint.x = position.point.x - popupWidthPx / 2;
popupPoint.y = position.point.y + 6;
} else if (position.dir === 'left') {
popupPoint.x = position.point.x - popupWidthPx;
popupPoint.y = position.point.y - popupHeightPx / 2;
} else if (position.dir === 'right') {
popupPoint.x = position.point.x + 6;
popupPoint.y = position.point.y - popupHeightPx / 2;
}
if (popupPoint.x < popupPaddingPx) {
popupPoint.x = popupPaddingPx;
+46 -3
View File
@@ -29,6 +29,36 @@ const getFontStyles = (
return fontStyles;
};
const getAdditionalFontFaces = () => `
@font-face {
font-family: "FangSong";
src: url("https://db.onlinewebfonts.com/t/2ecbfe1d9bfc191c6f15c0ccc23cbd43.eot");
src: url("https://db.onlinewebfonts.com/t/2ecbfe1d9bfc191c6f15c0ccc23cbd43.eot?#iefix") format("embedded-opentype"),
url("https://db.onlinewebfonts.com/t/2ecbfe1d9bfc191c6f15c0ccc23cbd43.woff2") format("woff2"),
url("https://db.onlinewebfonts.com/t/2ecbfe1d9bfc191c6f15c0ccc23cbd43.woff") format("woff"),
url("https://db.onlinewebfonts.com/t/2ecbfe1d9bfc191c6f15c0ccc23cbd43.ttf") format("truetype"),
url("https://db.onlinewebfonts.com/t/2ecbfe1d9bfc191c6f15c0ccc23cbd43.svg#FangSong") format("svg");
}
@font-face {
font-family: "Kaiti";
src: url("https://db.onlinewebfonts.com/t/1ee9941f1b8c128110ca4307dda59917.eot");
src: url("https://db.onlinewebfonts.com/t/1ee9941f1b8c128110ca4307dda59917.eot?#iefix")format("embedded-opentype"),
url("https://db.onlinewebfonts.com/t/1ee9941f1b8c128110ca4307dda59917.woff2")format("woff2"),
url("https://db.onlinewebfonts.com/t/1ee9941f1b8c128110ca4307dda59917.woff")format("woff"),
url("https://db.onlinewebfonts.com/t/1ee9941f1b8c128110ca4307dda59917.ttf")format("truetype"),
url("https://db.onlinewebfonts.com/t/1ee9941f1b8c128110ca4307dda59917.svg#STKaiti")format("svg");
}
@font-face {
font-family: "Heiti";
src: url("https://db.onlinewebfonts.com/t/a4948b9d43a91468825a5251df1ec58d.eot");
src: url("https://db.onlinewebfonts.com/t/a4948b9d43a91468825a5251df1ec58d.eot?#iefix")format("embedded-opentype"),
url("https://db.onlinewebfonts.com/t/a4948b9d43a91468825a5251df1ec58d.woff2")format("woff2"),
url("https://db.onlinewebfonts.com/t/a4948b9d43a91468825a5251df1ec58d.woff")format("woff"),
url("https://db.onlinewebfonts.com/t/a4948b9d43a91468825a5251df1ec58d.ttf")format("truetype"),
url("https://db.onlinewebfonts.com/t/a4948b9d43a91468825a5251df1ec58d.svg#WenQuanYi Micro Hei")format("svg");
}
`;
const getLayoutStyles = (
spacing: number,
justify: boolean,
@@ -74,14 +104,16 @@ const getLayoutStyles = (
white-space: pre-wrap !important;
tab-size: 2;
}
body {
html, body {
color: ${fg};
zoom: ${zoomLevel}%;
background-color: ${bg} !important;
}
body *:not(#b1):not(#b1 *):not(#b2):not(#b2 *):not(.bg):not(.bg *):not(.vol):not(.vol *):not(.background):not(.background *) {
border-color: currentColor !important;
${bg === '#ffffff' ? '' : `background-color: ${bg} !important;`}
}
svg, img {
background-color: transparent !important;
mix-blend-mode: multiply;
}
p, li, blockquote, dd {
text-align: ${justify ? 'justify' : 'start'};
@@ -108,6 +140,11 @@ const getLayoutStyles = (
aside[epub|type~="rearnote"] {
display: none;
}
.duokan-footnote-content,
.duokan-footnote-item {
display: none;
}
`;
export interface ThemeCode {
@@ -138,3 +175,9 @@ export const getStyles = (viewSettings: ViewSettings, themeCode: ThemeCode) => {
const userStylesheet = viewSettings.userStylesheet!;
return `${layoutStyles}\n${fontStyles}\n${fontfacesCSS}\n${userStylesheet}`;
};
export const mountAdditionalFonts = (document: Document) => {
const style = document.createElement('style');
style.textContent = getAdditionalFontFaces();
document.head.appendChild(style);
};
Binary file not shown.

Before

Width:  |  Height:  |  Size: 349 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 274 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Before

Width:  |  Height:  |  Size: 948 KiB

After

Width:  |  Height:  |  Size: 948 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB