Compare commits

...

54 Commits

Author SHA1 Message Date
Huang Xin def157cacb release: version 0.9.43 (#1196) 2025-05-19 16:51:34 +02:00
Huang Xin 7c464b9a8d feat: add prev/next section buttons in footer bar, closes #1125 (#1195) 2025-05-19 16:40:11 +02:00
Huang Xin 90f3512ae2 feat: add scrolling overlap in pixels option to paginate in scrolled mode (#1194) 2025-05-19 15:21:06 +02:00
Huang Xin 12d93ba749 fix: adjust scroll offset to account for header/footer bars when paginating in scroll mode, closes #1181 (#1193) 2025-05-19 10:34:05 +02:00
Huang Xin 554d786105 fix: update library in store when deleting book in bookshelf, closes #1178 (#1191) 2025-05-19 08:31:25 +02:00
Huang Xin eb71c59524 chore: config wrangler before deployment in Cloudflare (#1189) 2025-05-19 07:55:11 +02:00
Huang Xin 93e81ee05b release: remove deprecated MSI installer, closes #1174 (#1187) 2025-05-19 03:29:44 +02:00
Huang Xin b83972e366 refactor: use translator hook to support more translator providers (#1186) 2025-05-18 18:35:37 +02:00
Huang Xin 967536aa23 refactor: update wrangler config (#1185) 2025-05-18 17:52:50 +02:00
Huang Xin 4523437e34 refactor: add kv cache for translation backend (#1184) 2025-05-18 17:16:44 +02:00
Huang Xin e49dd4accb feat: show cloud backup status for each book on mobile and desktop, closes #1167 (#1173) 2025-05-17 17:02:42 +02:00
Huang Xin b7c1f5703c fix: less sensitive magic trackpad and mouse when flipping page, closes #1165 (#1172) 2025-05-17 08:56:22 +02:00
Huang Xin 5373b67aae css: get rid of most overriding for background color, closes #1162 (#1164) 2025-05-16 08:23:34 +02:00
Huang Xin ddc9673260 css: compat for background colors in chapter headers of Feedbooks eBooks (#1163) 2025-05-16 03:29:07 +02:00
Huang Xin 16b0821eab i18n: add translations of Nederlands (#1161) 2025-05-15 18:32:38 +02:00
Huang Xin 93876a73cc layout: responsive translator popup, also closes #1157 (#1160) 2025-05-15 18:19:32 +02:00
Huang Xin 048867e595 settings: disable spell check in color input (#1159) 2025-05-15 05:33:35 +02:00
Huang Xin 602be376a1 css: include additional weight variants for built-in fonts (#1158) 2025-05-15 05:04:16 +02:00
Huang Xin c52ae43cd9 settings: avoid horizontal margin default to zero, fixes #1151 (#1155) 2025-05-14 15:25:32 +02:00
Huang Xin 348d743e82 css: styling adjustments for better compatibility with Gutenberg eBooks (#1154)
This also closes #1153, #1148, #1147 and the css problem in #1151.
2025-05-14 14:55:07 +02:00
Huang Xin c7e495c379 settings: keep screen awake is disabled by default, closes #1145 (#1149)
* layout: hint info now takes up full width in scrolled mode

* settings: keep screen awake is disabled by default, closes #1145
2025-05-14 11:11:32 +02:00
Huang Xin e368076cac chore: update bundleVersion for macOS AppStore build (#1146) 2025-05-14 03:45:00 +02:00
Huang Xin 382e0ca3c6 release: version 0.9.41 (#1143) 2025-05-13 14:17:01 +02:00
Huang Xin d96fb32bcf fix: apply layout styles to div tag, closes #1130 (#1142) 2025-05-13 13:48:21 +02:00
Huang Xin 4779e2638f fix: disable updater for non-appimage app on linux, closes #1129 (#1141) 2025-05-13 12:50:40 +02:00
Huang Xin d094ba9916 chore: cache avatar image for offline usage (#1140) 2025-05-13 10:42:00 +02:00
Huang Xin e4ba0c302e fix: segment txt with paragraph count if no chapter titles are parsed, closes #1134 (#1139) 2025-05-13 10:21:47 +02:00
Huang Xin 0150177a9d chore: bump tauri to version 2.5.1 (#1138) 2025-05-13 09:30:34 +02:00
Huang Xin 74e32d47b0 release: add linux arch armhf (#1133) 2025-05-13 14:57:27 +08:00
Huang Xin 2dd7cf54e6 refactor: use text selector hook in annotator, closes #1020 (#1131) 2025-05-12 18:00:45 +02:00
Huang Xin a5cbfe97db fix: replace background when attribute changed, closes #1124 (#1126) 2025-05-11 17:07:17 +02:00
Huang Xin da49526f4c fix: now auto orientation follows system settings, closes #1093 and closes #1098 (#1122) 2025-05-11 14:57:05 +02:00
Huang Xin 2e46bc1627 css: get rid of hardcoded font color only when overriding font, closes #1095 (#1120) 2025-05-11 14:34:51 +02:00
Huang Xin 7e542e8694 fix: reorganize TTS control view hierarchy, closes #1080 (#1119) 2025-05-11 12:06:15 +02:00
Huang Xin 2a624ef57a css: only override background color in dark mode, closes #1066 (#1117) 2025-05-11 09:33:03 +02:00
Huang Xin 60ae0c9ac3 feat: show book file size in book details (#1114) 2025-05-10 18:28:08 +02:00
Huang Xin 110b4b37cd ui: various UI fixes and enhancements on mobile platforms (#1113) 2025-05-10 18:18:15 +02:00
Huang Xin f0edbf14a9 fix: padding top of the drag handler with the cutouts, closes #1101 (#1110) 2025-05-10 08:27:40 +02:00
Huang Xin 20669a9cb3 fix: show updating status in the about window, closes #1079 (#1109) 2025-05-10 08:00:25 +02:00
Huang Xin 3756bec66c css: special case for align center and zero text indent (#1105) 2025-05-09 14:40:55 +02:00
Huang Xin 3e1d03dc17 css: override text align and fix hardcoded text intent (#1104) 2025-05-09 14:20:38 +02:00
Huang Xin 4aebbf679f fix: various on styles of UI and footnote visibility (#1099)
* fix: footnote now should be hidden in srcdoc iframes

* fix: eliminate white flash on startup when using dark mode

* feat: rescale UI size with pixel density
2025-05-08 18:21:31 +02:00
Huang Xin 0a562d90ac fix: maintain library state across reader/library navigation, closes #1072 (#1096) 2025-05-08 09:26:58 +02:00
Huang Xin e91a39e8b6 release: version 0.9.40 (#1092) 2025-05-07 20:03:58 +02:00
Huang Xin 2006baac4b revert: unbreak style overriding, closes #1058 and closes #1075 (#1091) 2025-05-07 19:56:14 +02:00
Huang Xin 0d4f61f08a compat: fix insane img dimension might cause layout miscalculation, closes #1073 (#1090) 2025-05-07 18:33:13 +02:00
Huang Xin 0b5f0ede3b fix: close action bar when the footbar is dismissed, closes #1064 (#1086) 2025-05-07 14:44:17 +02:00
Huang Xin 99a146525f fix: transient navigation bar in Android 9, closes #1059 (#1085) 2025-05-07 14:11:46 +02:00
Huang Xin 6080f9e0f3 fix: revert to unlock screen orientation for library page, closes #1063 (#1084) 2025-05-07 13:50:40 +02:00
Huang Xin 6b3d41a4b8 fix: styling links and also the content of links, closes #1057 (#1083) 2025-05-07 12:46:28 +02:00
Huang Xin e403c009c2 fix: avoid glitches when expanding toc sub items, closes #1033 (#1081) 2025-05-07 12:22:42 +02:00
Huang Xin 14bf2bcf8f fix: segment separator now should be more than 8 dash, closes #1056 (#1077) 2025-05-07 09:58:30 +02:00
Huang Xin 7f66af71c8 fix: dialog drag handler layout, closes #1036 (#1076) 2025-05-07 09:27:20 +02:00
Huang Xin cbab201138 doc: format issue templates (#1071) 2025-05-07 06:04:20 +02:00
109 changed files with 3569 additions and 2008 deletions
+8 -4
View File
@@ -7,13 +7,17 @@ assignees: ''
---
**Does your feature request involve difficulty for you to complete a task? Please describe.**
A clear and concise description of what the problem is. Ex. I think it takes too many steps to [...]
> A clear and concise description of what the problem is. Ex. I think it takes too many steps to [...]
**Describe the solution you'd like**
A clear and concise description of what you'd like to happen.
> A clear and concise description of what you'd like to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
> A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any additional context or screenshots about the feature request here.
> Add any additional context or screenshots about the feature request here.
+10 -19
View File
@@ -11,22 +11,16 @@ assignees: ''
A clear and concise description of what the current behavior is.
Please also add **screenshots** of the existing application.
**Example:**
```
In DarkMode, when scrollbar are displayed (for example on Companies page, with enough companies in the list), we see a blank square in the bottom right corner
[screenshot]
```
> **Example:**
> In DarkMode, when scrollbar are displayed (for example on Companies page, with enough companies in the list), we see a blank square in the bottom right corner
> [screenshot]
## Expected behavior
A clear and concise description of what the expected behavior is.
**Example:**
```
The blank square should be transparent (invisible)
```
> **Example:**
> The blank square should be transparent (invisible)
## Technical inputs
@@ -34,11 +28,8 @@ Operating System:
Readest Version:
**Example:**
```
Operating System: macOS 14.3.1
Readest Version: 0.9.0
We are displaying custom scrollbars that disappear when the user is not scrolling. See ScrollWrapper.
Probably fixable with CSS
```
> **Example:**
> Operating System: Android 14 (WebView 135.0)
> Readest Version: 0.9.0
> We are displaying custom scrollbars that disappear when the user is not scrolling. See ScrollWrapper.
> Probably fixable with CSS
+18 -2
View File
@@ -67,6 +67,11 @@ jobs:
release: linux
arch: aarch64
rust_target: aarch64-unknown-linux-gnu
- os: ubuntu-22.04-arm
release: linux
arch: armhf
rust_target: arm-unknown-linux-gnueabihf
args: '--target arm-unknown-linux-gnueabihf --bundles deb'
- os: macos-latest
release: macos
arch: aarch64
@@ -76,7 +81,7 @@ jobs:
release: windows
arch: x86_64
rust_target: x86_64-pc-windows-msvc
args: '--target x86_64-pc-windows-msvc'
args: '--target x86_64-pc-windows-msvc --bundles nsis'
- os: windows-latest
release: windows
arch: aarch64
@@ -133,11 +138,22 @@ jobs:
key: ${{ matrix.config.os }}-${{ matrix.config.release }}-${{ matrix.config.arch }}-cargo
- name: install dependencies (ubuntu only)
if: contains(matrix.config.os, 'ubuntu') && matrix.config.release != 'android'
if: contains(matrix.config.os, 'ubuntu') && matrix.config.release != 'android' && matrix.config.arch != 'armhf'
run: |
sudo apt-get update
sudo apt-get install -y pkg-config libfontconfig-dev libgtk-3-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf xdg-utils
- name: install dependencies (ubuntu only - armhf specific)
if: contains(matrix.config.os, 'ubuntu') && matrix.config.arch == 'armhf'
run: |
sudo dpkg --add-architecture armhf
sudo apt-get update
sudo apt-get install -y pkg-config libfontconfig-dev:armhf libgtk-3-dev:armhf libwebkit2gtk-4.1-dev:armhf libappindicator3-dev:armhf librsvg2-dev:armhf gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf
echo 'PKG_CONFIG_ALLOW_CROSS=1' >> $GITHUB_ENV
echo 'PKG_CONFIG_PATH=/usr/lib/arm-linux-gnueabihf/pkgconfig:/usr/share/pkgconfig' >> $GITHUB_ENV
echo 'PKG_CONFIG_SYSROOT_DIR=/usr/arm-linux-gnueabihf' >> $GITHUB_ENV
echo 'CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc' >> $GITHUB_ENV
- name: create .env.local file for Next.js
run: |
echo "NEXT_PUBLIC_POSTHOG_KEY=${{ secrets.NEXT_PUBLIC_POSTHOG_KEY }}" >> .env.local
+1 -1
View File
@@ -3,4 +3,4 @@
url = https://github.com/readest/foliate-js.git
[submodule "packages/tauri"]
path = packages/tauri
url = https://github.com/tauri-apps/tauri.git
url = https://github.com/readest/tauri.git
Generated
+490 -446
View File
File diff suppressed because it is too large Load Diff
@@ -17,6 +17,7 @@ module.exports = {
'el',
'ko',
'uk',
'nl',
'pl',
'pt',
'ru',
+6 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@readest/readest-app",
"version": "0.9.39",
"version": "0.9.43",
"private": true,
"scripts": {
"dev": "dotenv -e .env.tauri -- next dev",
@@ -32,6 +32,7 @@
"release-ios-appstore": "dotenv -e .env.ios-appstore.local -- bash scripts/release-ios-appstore.sh",
"preview": "NEXT_PUBLIC_APP_PLATFORM=web opennextjs-cloudflare && wrangler dev",
"deploy": "NEXT_PUBLIC_APP_PLATFORM=web opennextjs-cloudflare && wrangler deploy",
"config-wrangler": "sed -i \"s/\\${TRANSLATIONS_KV_ID}/$TRANSLATIONS_KV_ID/g\" wrangler.toml",
"cf-typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts"
},
"dependencies": {
@@ -42,19 +43,19 @@
"@supabase/auth-ui-react": "^0.4.7",
"@supabase/auth-ui-shared": "^0.1.8",
"@supabase/supabase-js": "^2.47.7",
"@tauri-apps/api": "2.4.1",
"@tauri-apps/api": "2.5.0",
"@tauri-apps/plugin-cli": "^2.2.0",
"@tauri-apps/plugin-deep-link": "^2.2.1",
"@tauri-apps/plugin-dialog": "^2.2.1",
"@tauri-apps/plugin-fs": "^2.2.1",
"@tauri-apps/plugin-haptics": "^2.2.4",
"@tauri-apps/plugin-http": "^2.4.3",
"@tauri-apps/plugin-log": "^2.3.1",
"@tauri-apps/plugin-log": "^2.4.0",
"@tauri-apps/plugin-opener": "^2.2.6",
"@tauri-apps/plugin-os": "^2.2.1",
"@tauri-apps/plugin-process": "^2.2.1",
"@tauri-apps/plugin-shell": "~2.2.1",
"@tauri-apps/plugin-updater": "^2.7.0",
"@tauri-apps/plugin-updater": "^2.7.1",
"@zip.js/zip.js": "^2.7.53",
"aws4fetch": "^1.0.20",
"clsx": "^2.1.1",
@@ -80,7 +81,7 @@
},
"devDependencies": {
"@opennextjs/cloudflare": "^0.5.12",
"@tauri-apps/cli": "2.4.1",
"@tauri-apps/cli": "2.5.0",
"@types/cors": "^2.8.17",
"@types/cssbeautify": "^0.3.5",
"@types/node": "^22.10.1",
@@ -42,15 +42,12 @@
"Global Settings": "الإعدادات العامة",
"Go Back": "العودة",
"Go Forward": "التقدم",
"Go Left": "الذهاب لليسار",
"Go Right": "الذهاب لليمين",
"Grass": "عشبي",
"Gray": "رمادي",
"Gruvbox": "چروفبوكس",
"Highlight": "تمييز",
"Horizontal Direction": "الاتجاه الأفقي",
"Hyphenation": "الواصلة",
"Identifier:": "المعرف:",
"Import Books": "استيراد الكتب",
"Language:": "اللغة:",
"Layout": "التخطيط",
@@ -303,5 +300,17 @@
"Orientation": "الاتجاه",
"Portrait": "العمودي",
"Landscape": "الأفقي",
"Open Last Book on Start": "فتح آخر كتاب عند البدء"
"Open Last Book on Start": "فتح آخر كتاب عند البدء",
"Checking for updates...": "جارٍ التحقق من التحديثات...",
"Error checking for updates": "خطأ في التحقق من التحديثات",
"Details": "التفاصيل",
"Cancel Selection": "إلغاء التحديد",
"File Size:": "حجم الملف:",
"Auto Detect": "الكشف التلقائي",
"Touch": "اللمس",
"Scrolling Overlap (px)": "تداخل التمرير (بكسل)",
"Next Section": "القسم التالي",
"Previous Section": "القسم السابق",
"Next Page": "الصفحة التالية",
"Previous Page": "الصفحة السابقة"
}
@@ -42,15 +42,12 @@
"Global Settings": "Globale Einstellungen",
"Go Back": "Zurück",
"Go Forward": "Vorwärts",
"Go Left": "Nach links",
"Go Right": "Nach rechts",
"Grass": "Grasgrün",
"Gray": "Grau",
"Gruvbox": "Gruvbox",
"Highlight": "Hervorheben",
"Horizontal Direction": "Horizontale Richtung",
"Hyphenation": "Silbentrennung",
"Identifier:": "Kennung:",
"Import Books": "Bücher importieren",
"Language:": "Sprache:",
"Layout": "Layout",
@@ -134,7 +131,7 @@
"Book downloaded: {{title}}": "Buch heruntergeladen: {{title}}",
"Failed to download book: {{title}}": "Fehler beim Herunterladen des Buches: {{title}}",
"Upload Book": "Buch hochladen",
"Auto Upload Books to Cloud": "Bücher automatisch in die Cloud hochladen",
"Auto Upload Books to Cloud": "Bücher automatisch hochladen",
"{{percentage}}% of Cloud Storage Used.": "{{percentage}}% des Cloud-Speichers verwendet.",
"Storage": "Speicher",
"Book deleted: {{title}}": "Buch gelöscht: {{title}}",
@@ -303,5 +300,17 @@
"Orientation": "Orientierung",
"Portrait": "Hochformat",
"Landscape": "Querformat",
"Open Last Book on Start": "Letztes Buch beim Start öffnen"
"Open Last Book on Start": "Letztes Buch beim Start öffnen",
"Checking for updates...": "Auf Updates prüfen...",
"Error checking for updates": "Fehler beim Überprüfen auf Updates",
"Details": "Details",
"Cancel Selection": "Auswahl abbrechen",
"File Size:": "Dateigröße:",
"Auto Detect": "Automatisch erkennen",
"Touch": "Berührung",
"Scrolling Overlap (px)": "Scroll-Überlappung (px)",
"Next Section": "Nächster Abschnitt",
"Previous Section": "Vorheriger Abschnitt",
"Next Page": "Nächste Seite",
"Previous Page": "Vorherige Seite"
}
@@ -42,15 +42,12 @@
"Global Settings": "Γενικές ρυθμίσεις",
"Go Back": "Πίσω",
"Go Forward": "Μπροστά",
"Go Left": "Αριστερά",
"Go Right": "Δεξιά",
"Grass": "Γρασίδι",
"Gray": "Γκρι",
"Gruvbox": "Gruvbox",
"Highlight": "Επισήμανση",
"Horizontal Direction": "Οριζόντια κατεύθυνση",
"Hyphenation": "Συλλαβισμός",
"Identifier:": "Αναγνωριστικό:",
"Import Books": "Εισαγωγή βιβλίων",
"Language:": "Γλώσσα:",
"Layout": "Διάταξη",
@@ -134,12 +131,12 @@
"Book downloaded: {{title}}": "Το βιβλίο με τίτλο {{title}} κατέβηκε",
"Failed to download book: {{title}}": "Αποτυχία λήψης βιβλίου: {{title}}",
"Upload Book": "Ανέβασμα βιβλίου",
"Auto Upload Books to Cloud": "Αυτόματο ανέβασμα βιβλίων στο cloud",
"Auto Upload Books to Cloud": "Αυτόματη αποθήκευση στο cloud",
"{{percentage}}% of Cloud Storage Used.": "{{percentage}}% της αποθήκευσης στο cloud χρησιμοποιήθηκε.",
"Storage": "Αποθήκευση",
"Book deleted: {{title}}": "Το βιβλίο με τίτλο {{title}} διαγράφηκε",
"Failed to delete book: {{title}}": "Αποτυχία διαγραφής βιβλίου: {{title}}",
"Check Updates on Start": "Έλεγχος ενημερώσεων κατά την εκκίνηση",
"Check Updates on Start": "Αυτόματος έλεγχος ενημερώσεων",
"Insufficient storage quota": "Ανεπαρκές όριο αποθήκευσης",
"Font Weight": "Βάρος γραμματοσειράς",
"Line Spacing": "Διάκενο γραμμών",
@@ -296,12 +293,24 @@
"Grid": "Πλέγμα",
"(from 'As You Like It', Act II)": "('Όπως σας αρέσει', Πράξη II)",
"Link Color": "Χρώμα συνδέσμου",
"Volume Keys for Page Flip": "Πλήκτρα έντασης για ανατροπή σελίδας",
"Volume Keys for Page Flip": "Ανατροπή με πλήκτρα έντασης",
"Clicks for Page Flip": "Κλικ για ανατροπή σελίδας",
"Swap Clicks Area": "Ανταλλαγή περιοχής κλικ",
"Screen": "Οθόνη",
"Orientation": "Προσανατολισμός",
"Portrait": "Πορτραίτο",
"Landscape": "Τοπίο",
"Open Last Book on Start": "Άνοιγμα τελευταίου βιβλίου κατά την εκκίνηση"
"Open Last Book on Start": "Άνοιγμα τελευταίου βιβλίου",
"Checking for updates...": "Έλεγχος για ενημερώσεις...",
"Error checking for updates": "Σφάλμα κατά τον έλεγχο για ενημερώσεις",
"Details": "Πληρ.",
"Cancel Selection": "Ακύρωση επιλογής",
"File Size:": "Μέγεθος αρχείου:",
"Auto Detect": "Αυτόματη ανίχνευση",
"Touch": "Αφή",
"Scrolling Overlap (px)": "Επικάλυψη κύλισης (px)",
"Next Section": "Επόμενη ενότητα",
"Previous Section": "Προηγούμενη ενότητα",
"Next Page": "Επόμενη σελίδα",
"Previous Page": "Προηγούμενη σελίδα"
}
@@ -42,15 +42,12 @@
"Global Settings": "Configuración global",
"Go Back": "Volver",
"Go Forward": "Avanzar",
"Go Left": "Ir a la izquierda",
"Go Right": "Ir a la derecha",
"Grass": "Hierba",
"Gray": "Gris",
"Gruvbox": "Gruvbox",
"Highlight": "Resaltar",
"Horizontal Direction": "Dirección horizontal",
"Hyphenation": "Guionización",
"Identifier:": "Identificador:",
"Import Books": "Importar libros",
"Language:": "Idioma:",
"Layout": "Diseño",
@@ -303,5 +300,17 @@
"Orientation": "Orientación",
"Portrait": "Vertical",
"Landscape": "Horizontal",
"Open Last Book on Start": "Abrir último libro al iniciar"
"Open Last Book on Start": "Abrir último libro al iniciar",
"Checking for updates...": "Comprobando actualizaciones...",
"Error checking for updates": "Error al comprobar actualizaciones",
"Details": "Detalles",
"Cancel Selection": "Cancelar selección",
"File Size:": "Peso del archivo:",
"Auto Detect": "Detección automática",
"Touch": "Toque",
"Scrolling Overlap (px)": "Superposición de desplazamiento (px)",
"Next Section": "Siguiente sección",
"Previous Section": "Sección anterior",
"Next Page": "Página siguiente",
"Previous Page": "Página anterior"
}
@@ -42,15 +42,12 @@
"Global Settings": "Paramètres globaux",
"Go Back": "Retour",
"Go Forward": "Avancer",
"Go Left": "Aller à gauche",
"Go Right": "Aller à droite",
"Grass": "Herbe",
"Gray": "Gris",
"Gruvbox": "Gruvbox",
"Highlight": "Surligner",
"Horizontal Direction": "Direction horizontale",
"Hyphenation": "Césure",
"Identifier:": "Identifiant :",
"Import Books": "Importer des livres",
"Language:": "Langue :",
"Layout": "Mise en page",
@@ -303,5 +300,17 @@
"Orientation": "Orientation",
"Portrait": "Portrait",
"Landscape": "Paysage",
"Open Last Book on Start": "Ouvrir le dernier livre au démarrage"
"Open Last Book on Start": "Ouvrir le dernier livre au démarrage",
"Checking for updates...": "Vérification des mises à jour...",
"Error checking for updates": "Erreur lors de la vérification des mises à jour",
"Details": "Détails",
"Cancel Selection": "Annuler la sélection",
"File Size:": "Taille du fichier :",
"Auto Detect": "Détection automatique",
"Touch": "Touch",
"Scrolling Overlap (px)": "Chevauchement de défilement (px)",
"Next Section": "Section suivante",
"Previous Section": "Section précédente",
"Next Page": "Page suivante",
"Previous Page": "Page précédente"
}
@@ -42,15 +42,12 @@
"Global Settings": "वैश्विक सेटिंग्स",
"Go Back": "वापस जाएं",
"Go Forward": "आगे जाएं",
"Go Left": "बाएं जाएं",
"Go Right": "दाएं जाएं",
"Grass": "घास",
"Gray": "ग्रे",
"Gruvbox": "ग्रूवबॉक्स",
"Highlight": "हाइलाइट",
"Horizontal Direction": "क्षैतिज दिशा",
"Hyphenation": "हाइफ़नेशन",
"Identifier:": "पहचानकर्ता:",
"Import Books": "पुस्तकें आयात करें",
"Language:": "भाषा:",
"Layout": "लेआउट",
@@ -303,5 +300,17 @@
"Orientation": "अवयव",
"Portrait": "पोर्ट्रेट",
"Landscape": "लैंडस्केप",
"Open Last Book on Start": "शुरू में अंतिम पुस्तक खोलें"
"Open Last Book on Start": "शुरू में अंतिम पुस्तक खोलें",
"Checking for updates...": "अपडेट की जांच कर रहा है...",
"Error checking for updates": "अपडेट की जांच करते समय त्रुटि",
"Details": "विवरण",
"Cancel Selection": "चयन रद्द करें",
"File Size:": "फ़ाइल आकार:",
"Auto Detect": "स्वचालित पहचान",
"Touch": "स्पर्श",
"Scrolling Overlap (px)": "स्क्रॉलिंग ओवरलैप (px)",
"Next Section": "अगला अनुभाग",
"Previous Section": "पिछला अनुभाग",
"Next Page": "अगला पृष्ठ",
"Previous Page": "पिछला पृष्ठ"
}
@@ -42,15 +42,12 @@
"Global Settings": "Pengaturan Global",
"Go Back": "Kembali",
"Go Forward": "Maju",
"Go Left": "Ke Kiri",
"Go Right": "Ke Kanan",
"Grass": "Rumput",
"Gray": "Abu-abu",
"Gruvbox": "Gruvbox",
"Highlight": "Sorot",
"Horizontal Direction": "Arah Horizontal",
"Hyphenation": "Pemenggalan Kata",
"Identifier:": "Pengenal:",
"Import Books": "Impor Buku",
"Language:": "Bahasa:",
"Layout": "Tata Letak",
@@ -303,5 +300,17 @@
"Orientation": "Orientasi",
"Portrait": "Potret",
"Landscape": "Lanskap",
"Open Last Book on Start": "Buka Buku Terakhir saat Memulai"
"Open Last Book on Start": "Buka Buku Terakhir saat Memulai",
"Checking for updates...": "Memeriksa pembaruan...",
"Error checking for updates": "Kesalahan saat memeriksa pembaruan",
"Details": "Detail",
"Cancel Selection": "Batalkan Pilihan",
"File Size:": "Ukuran File:",
"Auto Detect": "Deteksi Otomatis",
"Touch": "Sentuh",
"Scrolling Overlap (px)": "Overlapping Gulir (px)",
"Next Section": "Bagian Selanjutnya",
"Previous Section": "Bagian Sebelumnya",
"Next Page": "Halaman Berikutnya",
"Previous Page": "Halaman Sebelumnya"
}
@@ -42,15 +42,12 @@
"Global Settings": "Impostazioni globali",
"Go Back": "Indietro",
"Go Forward": "Avanti",
"Go Left": "Vai a sinistra",
"Go Right": "Vai a destra",
"Grass": "Erba",
"Gray": "Grigio",
"Gruvbox": "Gruvbox",
"Highlight": "Evidenzia",
"Horizontal Direction": "Direzione orizzontale",
"Hyphenation": "Sillabazione",
"Identifier:": "Identificatore:",
"Import Books": "Importa libri",
"Language:": "Lingua:",
"Layout": "Layout",
@@ -303,5 +300,17 @@
"Orientation": "Orientamento",
"Portrait": "Ritratto",
"Landscape": "Paesaggio",
"Open Last Book on Start": "Apri ultimo libro all'avvio"
"Open Last Book on Start": "Apri ultimo libro all'avvio",
"Checking for updates...": "Controllo aggiornamenti...",
"Error checking for updates": "Errore durante il controllo degli aggiornamenti",
"Details": "Dettagli",
"Cancel Selection": "Annulla selezione",
"File Size:": "Dimensione file:",
"Auto Detect": "Rilevamento automatico",
"Touch": "Touch",
"Scrolling Overlap (px)": "Overlap scorrimento (px)",
"Next Section": "Sezione successiva",
"Previous Section": "Sezione precedente",
"Next Page": "Pagina successiva",
"Previous Page": "Pagina precedente"
}
@@ -42,15 +42,12 @@
"Global Settings": "全体設定",
"Go Back": "戻る",
"Go Forward": "進む",
"Go Left": "左へ",
"Go Right": "右へ",
"Grass": "グリーン",
"Gray": "グレー",
"Gruvbox": "グルーブボックス",
"Highlight": "ハイライト",
"Horizontal Direction": "横書",
"Hyphenation": "ハイフネーション",
"Identifier:": "識別子:",
"Import Books": "書籍をインポート",
"Language:": "言語:",
"Layout": "レイアウト",
@@ -303,5 +300,17 @@
"Orientation": "向き",
"Portrait": "縦",
"Landscape": "横",
"Open Last Book on Start": "開始時に最後の書籍を開く"
"Open Last Book on Start": "開始時に最後の書籍を開く",
"Checking for updates...": "更新を確認中...",
"Error checking for updates": "更新の確認中にエラーが発生しました",
"Details": "詳細",
"Cancel Selection": "選択をキャンセル",
"File Size:": "ファイルサイズ:",
"Auto Detect": "自動検出",
"Touch": "タッチ",
"Scrolling Overlap (px)": "スクロール重複(px",
"Next Section": "次のセクション",
"Previous Section": "前のセクション",
"Next Page": "次のページ",
"Previous Page": "前のページ"
}
@@ -42,15 +42,12 @@
"Global Settings": "전역 설정",
"Go Back": "뒤로",
"Go Forward": "앞으로",
"Go Left": "왼쪽으로",
"Go Right": "오른쪽으로",
"Grass": "잔디색",
"Gray": "회색",
"Gruvbox": "그러브박스",
"Highlight": "하이라이트",
"Horizontal Direction": "수평 방향",
"Hyphenation": "하이픈 넣기",
"Identifier:": "식별자:",
"Import Books": "책 가져오기",
"Language:": "언어:",
"Layout": "레이아웃",
@@ -303,5 +300,17 @@
"Orientation": "방향",
"Portrait": "세로",
"Landscape": "가로",
"Open Last Book on Start": "시작 시 마지막 책 열기"
"Open Last Book on Start": "시작 시 마지막 책 열기",
"Checking for updates...": "업데이트 확인 중...",
"Error checking for updates": "업데이트 확인 중 오류 발생",
"Details": "세부정보",
"Cancel Selection": "선택 취소",
"File Size:": "파일 크기:",
"Auto Detect": "자동 감지",
"Touch": "터치",
"Scrolling Overlap (px)": "스크롤 겹침 (px)",
"Next Section": "다음 섹션",
"Previous Section": "이전 섹션",
"Next Page": "다음 페이지",
"Previous Page": "이전 페이지"
}
@@ -0,0 +1,316 @@
{
"Email address": "E-mailadres",
"Your Password": "Uw wachtwoord",
"Your email address": "Uw e-mailadres",
"Your password": "Uw wachtwoord",
"Sign in": "Inloggen",
"Signing in...": "Bezig met inloggen...",
"Sign in with {{provider}}": "Inloggen met {{provider}}",
"Already have an account? Sign in": "Heeft u al een account? Log in",
"Create a Password": "Maak een wachtwoord aan",
"Sign up": "Registreren",
"Signing up...": "Bezig met registreren...",
"Check your email for the confirmation link": "Controleer uw e-mail voor de bevestigingslink",
"Signing in ...": "Bezig met inloggen ...",
"Send a magic link email": "Stuur een magic link e-mail",
"Check your email for the magic link": "Controleer uw e-mail voor de magic link",
"Send reset password instructions": "Stuur instructies voor wachtwoordherstel",
"Sending reset instructions ...": "Bezig met versturen van herstelinstructies ...",
"Forgot your password?": "Wachtwoord vergeten?",
"Check your email for the password reset link": "Controleer uw e-mail voor de link om uw wachtwoord te herstellen",
"Phone number": "Telefoonnummer",
"Your phone number": "Uw telefoonnummer",
"Token": "Token",
"Your OTP token": "Uw OTP-token",
"Verify token": "Token verifiëren",
"Sign in with Google": "Inloggen met Google",
"Sign in with Apple": "Inloggen met Apple",
"Sign in with GitHub": "Inloggen met GitHub",
"New Password": "Nieuw wachtwoord",
"Your new password": "Uw nieuwe wachtwoord",
"Update password": "Wachtwoord bijwerken",
"Updating password ...": "Wachtwoord bijwerken ...",
"Your password has been updated": "Uw wachtwoord is bijgewerkt",
"Open": "Openen",
"Group": "Groep",
"Details": "Details",
"Delete": "Verwijderen",
"Cancel": "Annuleren",
"Confirm Deletion": "Verwijdering bevestigen",
"Are you sure to delete the selected books?": "Weet u zeker dat u de geselecteerde boeken wilt verwijderen?",
"Deselect Book": "Boek deselecteren",
"Select Book": "Boek selecteren",
"Show Book Details": "Boekdetails weergeven",
"Download Book": "Boek downloaden",
"Upload Book": "Boek uploaden",
"Deselect Group": "Groep deselecteren",
"Select Group": "Groep selecteren",
"Untitled Group": "Groep zonder titel",
"Group Books": "Boeken groeperen",
"Remove From Group": "Uit groep verwijderen",
"Create New Group": "Nieuwe groep maken",
"Save": "Opslaan",
"Confirm": "Bevestigen",
"From Local File": "Van lokaal bestand",
"Go Back": "Terug",
"Search Books...": "Boeken zoeken...",
"Clear Search": "Zoekopdracht wissen",
"Import Books": "Boeken importeren",
"Select Multiple Books": "Meerdere boeken selecteren",
"Select Books": "Boeken selecteren",
"Cancel Selection": "Selectie annuleren",
"Storage": "Opslag",
"{{percentage}}% of Cloud Storage Used.": "{{percentage}}% van cloudopslag gebruikt.",
"Logged in as {{userDisplayName}}": "Ingelogd als {{userDisplayName}}",
"Logged in": "Ingelogd",
"Account": "Account",
"Sign In": "Inloggen",
"Auto Upload Books to Cloud": "Boeken automatisch uploaden naar cloud",
"Auto Import on File Open": "Automatisch importeren bij bestand openen",
"Open Last Book on Start": "Open laatste boek bij opstarten",
"Check Updates on Start": "Controleer updates bij opstarten",
"Fullscreen": "Volledig scherm",
"Always on Top": "Altijd bovenaan",
"Keep Screen Awake": "Scherm wakker houden",
"Reload Page": "Pagina herladen",
"Download Readest": "Readest downloaden",
"About Readest": "Over Readest",
"List": "Lijst",
"Grid": "Raster",
"Title": "Titel",
"Author": "Auteur",
"Format": "Formaat",
"Date Read": "Datum gelezen",
"Date Added": "Datum toegevoegd",
"Ascending": "Oplopend",
"Descending": "Aflopend",
"Sort by...": "Sorteren op...",
"No supported files found. Supported formats: {{formats}}": "Geen ondersteunde bestanden gevonden. Ondersteunde formaten: {{formats}}",
"No chapters detected.": "Geen hoofdstukken gedetecteerd.",
"Failed to parse the EPUB file.": "EPUB-bestand kon niet worden verwerkt.",
"This book format is not supported.": "Dit boekformaat wordt niet ondersteund.",
"Failed to import book(s): {{filenames}}": "Importeren van boek(en) mislukt: {{filenames}}",
"Book uploaded: {{title}}": "Boek geüpload: {{title}}",
"Insufficient storage quota": "Onvoldoende opslagruimte",
"Failed to upload book: {{title}}": "Uploaden van boek mislukt: {{title}}",
"Book downloaded: {{title}}": "Boek gedownload: {{title}}",
"Failed to download book: {{title}}": "Downloaden van boek mislukt: {{title}}",
"Book deleted: {{title}}": "Boek verwijderd: {{title}}",
"Failed to delete book: {{title}}": "Verwijderen van boek mislukt: {{title}}",
"Your Library": "Uw bibliotheek",
"Welcome to your library. You can import your books here and read them anytime.": "Welkom bij uw bibliotheek. U kunt hier uw boeken importeren en ze op elk moment lezen.",
"Copied to notebook": "Gekopieerd naar notitieblok",
"No annotations to export": "Geen annotaties om te exporteren",
"Exported from Readest": "Geëxporteerd uit Readest",
"Highlights & Annotations": "Markeringen & annotaties",
"Untitled": "Zonder titel",
"Note": "Notitie",
"Copied to clipboard": "Gekopieerd naar klembord",
"Copy": "Kopiëren",
"Delete Highlight": "Markering verwijderen",
"Highlight": "Markeren",
"Annotate": "Annoteren",
"Search": "Zoeken",
"Dictionary": "Woordenboek",
"Wikipedia": "Wikipedia",
"Translate": "Vertalen",
"Speak": "Voorlezen",
"Unable to fetch the translation. Please log in first and try again.": "Kan de vertaling niet ophalen. Log eerst in en probeer het opnieuw.",
"Unable to fetch the translation. Try again later.": "Kan de vertaling niet ophalen. Probeer het later opnieuw.",
"Original Text": "Originele tekst",
"Auto Detect": "Automatisch detecteren",
"(detected)": "(gedetecteerd)",
"Translated Text": "Vertaalde tekst",
"Loading...": "Laden...",
"Bookmark": "Bladwijzer",
"Go Forward": "Vooruit",
"Small": "Klein",
"Large": "Groot",
"Notebook": "Notitieblok",
"Excerpts": "Fragmenten",
"Notes": "Notities",
"Add your notes here...": "Voeg hier uw notities toe...",
"Theme Mode": "Thema modus",
"Auto Mode": "Automatische modus",
"Light Mode": "Lichte modus",
"Dark Mode": "Donkere modus",
"Theme Color": "Themakleur",
"Custom": "Aangepast",
"Apply to All Books": "Toepassen op alle boeken",
"Apply to This Book": "Toepassen op dit boek",
"Global Settings": "Algemene instellingen",
"System Fonts": "Systeemlettertypen",
"Serif Font": "Serif lettertype",
"Sans-Serif Font": "Sans-serif lettertype",
"Font Size": "Lettergrootte",
"Default Font Size": "Standaard lettergrootte",
"Minimum Font Size": "Minimale lettergrootte",
"Font Weight": "Letterdikte",
"Font Family": "Lettertypefamilie",
"Default Font": "Standaard lettertype",
"CJK Font": "CJK lettertype",
"Override Book Font": "Boek lettertype overschrijven",
"Font Face": "Lettertype",
"Monospace Font": "Monospace lettertype",
"Scrolled Mode": "Scroll-modus",
"Writing Mode": "Schrijfmodus",
"Default": "Standaard",
"Horizontal Direction": "Horizontale richting",
"Vertical Direction": "Verticale richting",
"RTL Direction": "RTL-richting",
"Border Frame": "Randkader",
"Double Border": "Dubbele rand",
"Border Color": "Randkleur",
"Paragraph": "Alinea",
"Paragraph Margin": "Alinea marge",
"Line Spacing": "Regelafstand",
"Word Spacing": "Woordafstand",
"Letter Spacing": "Letterafstand",
"Text Indent": "Tekstinspringing",
"Full Justification": "Volledig uitvullen",
"Hyphenation": "Woordafbreking",
"Override Book Layout": "Boekopmaak overschrijven",
"Page": "Pagina",
"Vertical Margins (px)": "Verticale marges (px)",
"Horizontal Margins (%)": "Horizontale marges (%)",
"Maximum Number of Columns": "Maximum aantal kolommen",
"Maximum Column Height": "Maximale kolomhoogte",
"Maximum Column Width": "Maximale kolombreedte",
"Header & Footer": "Koptekst & voettekst",
"Show Header": "Koptekst weergeven",
"Show Footer": "Voettekst weergeven",
"Apply also in Scrolled Mode": "Ook toepassen in scroll-modus",
"Auto": "Automatisch",
"Language": "Taal",
"Animation": "Animatie",
"Paging Animation": "Paginering animatie",
"Screen": "Scherm",
"Orientation": "Oriëntatie",
"Portrait": "Portret",
"Landscape": "Landschap",
"Behavior": "Gedrag",
"Continuous Scroll": "Doorlopend scrollen",
"Volume Keys for Page Flip": "Volumetoetsen voor pagina omslaan",
"Clicks for Page Flip": "Klikken voor pagina omslaan",
"Swap Clicks Area": "Klikgebieden omwisselen",
"Custom CSS": "Aangepaste CSS",
"Enter your custom CSS here...": "Voer hier uw aangepaste CSS in...",
"Apply": "Toepassen",
"Font": "Lettertype",
"Layout": "Opmaak",
"Color": "Kleur",
"Misc": "Overig",
"(from 'As You Like It', Act II)": "(uit 'As You Like It', Akte II)",
"Custom Theme": "Aangepast thema",
"Theme Name": "Themanaam",
"Text Color": "Tekstkleur",
"Background Color": "Achtergrondkleur",
"Link Color": "Linkkleur",
"Preview": "Voorbeeld",
"Font & Layout": "Lettertype & opmaak",
"Book Cover": "Boekomslag",
"More Info": "Meer informatie",
"Parallel Read": "Parallel lezen",
"Export Annotations": "Annotaties exporteren",
"Edit": "Bewerken",
"Search...": "Zoeken...",
"Book": "Boek",
"Chapter": "Hoofdstuk",
"Match Case": "Hoofdlettergevoelig",
"Match Whole Words": "Hele woorden",
"Match Diacritics": "Diakritische tekens",
"TOC": "Inhoudsopgave",
"Sidebar": "Zijbalk",
"TTS not supported for PDF": "TTS niet ondersteund voor PDF",
"TTS not supported in this device": "TTS niet ondersteund op dit apparaat",
"No Timeout": "Geen time-out",
"{{value}} minute": "{{value}} minuut",
"{{value}} minutes": "{{value}} minuten",
"{{value}} hour": "{{value}} uur",
"{{value}} hours": "{{value}} uren",
"Slow": "Langzaam",
"Fast": "Snel",
"Reading Progress Synced": "Leesvoortgang gesynchroniseerd",
"Cloud Storage": "Cloudopslag",
"Failed to delete user. Please try again later.": "Gebruiker verwijderen mislukt. Probeer het later opnieuw.",
"Free Tier": "Gratis niveau",
"Community Support": "Community-ondersteuning",
"DeepL Free Access": "DeepL gratis toegang",
"Essential Text-to-Speech Voices": "Essentiële tekst-naar-spraak stemmen",
"Unlimited Offline/Online Reading": "Onbeperkt offline/online lezen",
"Unlimited Cloud Sync Devices": "Onbeperkt aantal cloud-synchronisatie apparaten",
"500 MB Cloud Sync Space": "500 MB cloud-synchronisatieruimte",
"Plus Tier": "Plus niveau",
"Includes All Free Tier Benefits": "Inclusief alle voordelen van het gratis niveau",
"Priority Support": "Prioriteitsondersteuning",
"AI Summaries": "AI-samenvattingen",
"AI Translations": "AI-vertalingen",
"DeepL Pro Access": "DeepL Pro toegang",
"Expanded Text-to-Speech Voices": "Uitgebreide tekst-naar-spraak stemmen",
"2000 MB Cloud Sync Space": "2000 MB cloud-synchronisatieruimte",
"Pro Tier": "Pro niveau",
"Includes All Plus Tier Benefits": "Inclusief alle voordelen van het Plus niveau",
"Unlimited AI Summaries": "Onbeperkte AI-samenvattingen",
"Unlimited AI Translations": "Onbeperkte AI-vertalingen",
"Unlimited DeepL Pro Access": "Onbeperkte DeepL Pro toegang",
"Advanced AI Tools": "Geavanceerde AI-tools",
"Early Feature Access": "Vroege toegang tot functies",
"10 GB Cloud Sync Space": "10 GB cloud-synchronisatieruimte",
"Loading profile...": "Profiel laden...",
"Features": "Functies",
"Sign Out": "Uitloggen",
"Delete Account": "Account verwijderen",
"Delete Your Account?": "Uw account verwijderen?",
"This action cannot be undone. All your data in the cloud will be permanently deleted.": "Deze actie kan niet ongedaan worden gemaakt. Al uw gegevens in de cloud worden permanent verwijderd.",
"Delete Permanently": "Permanent verwijderen",
"Version {{version}}": "Versie {{version}}",
"Check Update": "Update controleren",
"Already the latest version": "Reeds de nieuwste versie",
"Checking for updates...": "Controleren op updates...",
"Error checking for updates": "Fout bij controleren op updates",
"Book Details": "Boekdetails",
"Unknown": "Onbekend",
"Publisher:": "Uitgever:",
"Published:": "Gepubliceerd:",
"Updated:": "Bijgewerkt:",
"Added:": "Toegevoegd:",
"Language:": "Taal:",
"Subjects:": "Onderwerpen:",
"Format:": "Formaat:",
"File Size:": "Bestandsgrootte:",
"Description:": "Beschrijving:",
"No description available": "Geen beschrijving beschikbaar",
"Drop to Import Books": "Sleep om boeken te importeren",
"A new version of Readest is Available!": "Een nieuwe versie van Readest is beschikbaar!",
"Readest {{newVersion}} is available (installed version {{currentVersion}}).": "Readest {{newVersion}} is beschikbaar (geïnstalleerde versie {{currentVersion}}).",
"Download and install now?": "Nu downloaden en installeren?",
"Downloading {{downloaded}} of {{contentLength}}": "Downloaden {{downloaded}} van {{contentLength}}",
"Download finished": "Download voltooid",
"DOWNLOAD & INSTALL": "DOWNLOADEN & INSTALLEREN",
"Changelog:": "Wijzigingslogboek:",
"Software Update": "Software-update",
"LXGW WenKai GB Screen": "LXGW WenKai GB Scherm",
"LXGW WenKai TC": "LXGW WenKai TC",
"GuanKiapTsingKhai-T": "GuanKiapTsingKhai-T",
"Gray": "Grijs",
"Sepia": "Sepia",
"Grass": "Gras",
"Cherry": "Kers",
"Sky": "Hemel",
"Solarized": "Gesolariseerd",
"Gruvbox": "Gruvbox",
"Nord": "Noord",
"Contrast": "Contrast",
"Sunset": "Zonsondergang",
"Reveal in Finder": "Tonen in Finder",
"Reveal in File Explorer": "Tonen in Verkenner",
"Reveal in Folder": "Tonen in map",
"Dont have an account? Sign up": "Nog geen account? Registreer u",
"All the world's a stage,\nAnd all the men and women merely players;\nThey have their exits and their entrances,\nAnd one man in his time plays many parts,\nHis acts being seven ages.\n\n— William Shakespeare": "De hele wereld is een toneel,\nEn alle mannen en vrouwen slechts spelers;\nZij hebben hun uitgangen en hun entrees,\nEn één man speelt in zijn tijd vele rollen,\nZijn daden zijnde zeven leeftijden.\n\n— William Shakespeare",
"Touch": "Raak",
"Scrolling Overlap (px)": "Scroll-overlap (px)",
"Next Section": "Volgende sectie",
"Previous Section": "Vorige sectie",
"Next Page": "Volgende pagina",
"Previous Page": "Vorige pagina"
}
@@ -42,15 +42,12 @@
"Global Settings": "Ustawienia globalne",
"Go Back": "Wstecz",
"Go Forward": "Dalej",
"Go Left": "W lewo",
"Go Right": "W prawo",
"Grass": "Trawiasty",
"Gray": "Szary",
"Gruvbox": "Ciepły pomarańczowy",
"Highlight": "Zaznacz",
"Horizontal Direction": "Kierunek poziomy",
"Hyphenation": "Dzielenie wyrazów",
"Identifier:": "Identyfikator:",
"Import Books": "Importuj książki",
"Language:": "Język:",
"Layout": "Układ",
@@ -303,5 +300,17 @@
"Orientation": "Orientacja",
"Portrait": "Portret",
"Landscape": "Krajobraz",
"Open Last Book on Start": "Otwórz ostatnią książkę przy starcie"
"Open Last Book on Start": "Otwórz ostatnią książkę przy starcie",
"Checking for updates...": "Sprawdzanie aktualizacji...",
"Error checking for updates": "Błąd podczas sprawdzania aktualizacji",
"Details": "Szczegóły",
"Cancel Selection": "Anuluj zaznaczenie",
"File Size:": "Rozmiar pliku:",
"Auto Detect": "Automatyczne wykrywanie",
"Touch": "Dotyk",
"Scrolling Overlap (px)": "Nakładanie przewijania (px)",
"Next Section": "Następna sekcja",
"Previous Section": "Poprzednia sekcja",
"Next Page": "Następna strona",
"Previous Page": "Poprzednia strona"
}
@@ -42,15 +42,12 @@
"Global Settings": "Configurações Globais",
"Go Back": "Voltar",
"Go Forward": "Avançar",
"Go Left": "Ir para Esquerda",
"Go Right": "Ir para Direita",
"Grass": "Grama",
"Gray": "Cinza",
"Gruvbox": "Gruvbox",
"Highlight": "Destaque",
"Horizontal Direction": "Direção Horizontal",
"Hyphenation": "Hifenização",
"Identifier:": "Identificador:",
"Import Books": "Importar Livros",
"Language:": "Idioma:",
"Layout": "Layout",
@@ -303,5 +300,17 @@
"Orientation": "Orientação",
"Portrait": "Retrato",
"Landscape": "Paisagem",
"Open Last Book on Start": "Abrir o Último Livro ao Iniciar"
"Open Last Book on Start": "Abrir o Último Livro ao Iniciar",
"Checking for updates...": "Verificando atualizações...",
"Error checking for updates": "Erro ao verificar atualizações",
"Details": "Detalhes",
"Cancel Selection": "Cancelar Seleção",
"File Size:": "Tamanho do arquivo:",
"Auto Detect": "Detectar Automaticamente",
"Touch": "Toque",
"Scrolling Overlap (px)": "Sobreposição de Rolagem (px)",
"Next Section": "Próxima seção",
"Previous Section": "Seção anterior",
"Next Page": "Próxima página",
"Previous Page": "Página anterior"
}
@@ -42,15 +42,12 @@
"Global Settings": "Общие настройки",
"Go Back": "Назад",
"Go Forward": "Вперёд",
"Go Left": "Влево",
"Go Right": "Вправо",
"Grass": "Трава",
"Gray": "Серый",
"Gruvbox": "Gruvbox",
"Highlight": "Выделить",
"Horizontal Direction": "Горизонтальное направление",
"Hyphenation": "Перенос слов",
"Identifier:": "Идентификатор:",
"Import Books": "Импорт книг",
"Language:": "Язык:",
"Layout": "Макет",
@@ -303,5 +300,17 @@
"Orientation": "Ориентация",
"Portrait": "Портрет",
"Landscape": "Ландшафт",
"Open Last Book on Start": "Открыть последнюю книгу при запуске"
"Open Last Book on Start": "Открыть последнюю книгу при запуске",
"Checking for updates...": "Проверка обновлений...",
"Error checking for updates": "Ошибка при проверке обновлений",
"Details": "Инфо",
"Cancel Selection": "Отменить выбор",
"File Size:": "Размер файла:",
"Auto Detect": "Автоопределение",
"Touch": "Сенсорный экран",
"Scrolling Overlap (px)": "Перекрытие прокрутки (px)",
"Next Section": "Следующий раздел",
"Previous Section": "Предыдущий раздел",
"Next Page": "Следующая страница",
"Previous Page": "Предыдущая страница"
}
@@ -42,15 +42,12 @@
"Global Settings": "Genel Ayarlar",
"Go Back": "Geri Git",
"Go Forward": "İleri Git",
"Go Left": "Sola Git",
"Go Right": "Sağa Git",
"Grass": "Çimen",
"Gray": "Gri",
"Gruvbox": "Gruvbox",
"Highlight": "Vurgula",
"Horizontal Direction": "Yatay Yön",
"Hyphenation": "Heceleme",
"Identifier:": "Tanımlayıcı:",
"Import Books": "Kitapları İçe Aktar",
"Language:": "Dil:",
"Layout": "Düzen",
@@ -303,5 +300,17 @@
"Orientation": "Yönlendirme",
"Portrait": "Portre",
"Landscape": "Yatay",
"Open Last Book on Start": "Açılışta Son Kitabı Aç"
"Open Last Book on Start": "Açılışta Son Kitabı Aç",
"Checking for updates...": "Yenilikler kontrol ediliyor...",
"Error checking for updates": "Güncellemeleri kontrol ederken hata oluştu",
"Details": "Detaylar",
"Cancel Selection": "Işaretlemeyi İptal Et",
"File Size:": "Dosya Boyutu:",
"Auto Detect": "Algıla",
"Touch": "Dokunmatik",
"Scrolling Overlap (px)": "Kaydırma Üst Üste Binen (px)",
"Next Section": "Sonraki Bölüm",
"Previous Section": "Önceki Bölüm",
"Next Page": "Sonraki Sayfa",
"Previous Page": "Önceki Sayfa"
}
@@ -42,15 +42,12 @@
"Global Settings": "Глобальні налаштування",
"Go Back": "Назад",
"Go Forward": "Вперед",
"Go Left": "Вліво",
"Go Right": "Вправо",
"Grass": "Трав'яний",
"Gray": "Сірий",
"Gruvbox": "Теплий помаранчевий",
"Highlight": "Виділення",
"Horizontal Direction": "Горизонтальний напрямок",
"Hyphenation": "Перенесення слів",
"Identifier:": "Ідентифікатор:",
"Import Books": "Імпортувати книги",
"Language:": "Мова:",
"Layout": "Макет",
@@ -303,5 +300,17 @@
"Orientation": "Орієнтація",
"Portrait": "Портрет",
"Landscape": "Ландшафт",
"Open Last Book on Start": "Відкрити останню книгу при запуску"
"Open Last Book on Start": "Відкрити останню книгу при запуску",
"Checking for updates...": "Перевірка наявності оновлень...",
"Error checking for updates": "Помилка перевірки наявності оновлень",
"Details": "Деталі",
"Cancel Selection": "Скасувати вибір",
"File Size:": "Розмір файлу:",
"Auto Detect": "Авто виявлення",
"Touch": "Дотик",
"Scrolling Overlap (px)": "Прокрутка перекриття (px)",
"Next Section": "Наступний розділ",
"Previous Section": "Попередній розділ",
"Next Page": "Наступна сторінка",
"Previous Page": "Попередня сторінка"
}
@@ -42,15 +42,12 @@
"Global Settings": "Cài đặt chung",
"Go Back": "Quay lại",
"Go Forward": "Tiến tới",
"Go Left": "Sang trái",
"Go Right": "Sang phải",
"Grass": "Xanh cỏ",
"Gray": "Xám",
"Gruvbox": "Gruvbox",
"Highlight": "Đánh dấu",
"Horizontal Direction": "Hướng ngang",
"Hyphenation": "Gạch nối từ",
"Identifier:": "Định danh:",
"Import Books": "Nhập sách",
"Language:": "Ngôn ngữ:",
"Layout": "Bố cục",
@@ -303,5 +300,17 @@
"Orientation": "Định hướng",
"Portrait": "Chân dung",
"Landscape": "Phong cảnh",
"Open Last Book on Start": "Mở sách cuối cùng khi khởi động"
"Open Last Book on Start": "Mở sách cuối cùng khi khởi động",
"Checking for updates...": "Đang kiểm tra cập nhật...",
"Error checking for updates": "Lỗi khi kiểm tra cập nhật",
"Details": "Chi tiết",
"Cancel Selection": "Hủy chọn",
"File Size:": "Kích thước tệp:",
"Auto Detect": "Phát hiện tự động",
"Touch": "Chạm",
"Scrolling Overlap (px)": "Chồng chéo cuộn (px)",
"Next Section": "Phần tiếp theo",
"Previous Section": "Phần trước",
"Next Page": "Trang tiếp theo",
"Previous Page": "Trang trước"
}
@@ -42,15 +42,12 @@
"Global Settings": "全局设置",
"Go Back": "返回",
"Go Forward": "前进",
"Go Left": "向左",
"Go Right": "向右",
"Grass": "青草",
"Gray": "素雅",
"Gruvbox": "暖橘",
"Highlight": "划线",
"Horizontal Direction": "横排",
"Hyphenation": "断字",
"Identifier:": "识别码",
"Import Books": "导入书籍",
"Language:": "语言",
"Layout": "布局",
@@ -303,5 +300,17 @@
"Orientation": "屏幕方向",
"Portrait": "竖屏",
"Landscape": "横屏",
"Open Last Book on Start": "启动时打开上次阅读的书籍"
"Open Last Book on Start": "启动时打开上次阅读的书籍",
"Checking for updates...": "检查更新中...",
"Error checking for updates": "检查更新时出错",
"Details": "详情",
"Cancel Selection": "取消选择",
"File Size:": "文件大小",
"Auto Detect": "自动检测",
"Touch": "触控",
"Scrolling Overlap (px)": "滚动重叠(px",
"Next Section": "下一章",
"Previous Section": "上一章",
"Next Page": "下一页",
"Previous Page": "上一页"
}
@@ -42,15 +42,12 @@
"Global Settings": "全局設置",
"Go Back": "返回",
"Go Forward": "前進",
"Go Left": "向左",
"Go Right": "向右",
"Grass": "青草",
"Gray": "素雅",
"Gruvbox": "暖橘",
"Highlight": "劃線",
"Horizontal Direction": "橫排",
"Hyphenation": "斷字",
"Identifier:": "識別碼",
"Import Books": "導入書籍",
"Language:": "語言",
"Layout": "版面",
@@ -303,5 +300,17 @@
"Orientation": "螢幕方向",
"Portrait": "豎屏",
"Landscape": "橫屏",
"Open Last Book on Start": "啟動時打開上次閱讀的書籍"
"Open Last Book on Start": "啟動時打開上次閱讀的書籍",
"Checking for updates...": "檢查更新中...",
"Error checking for updates": "檢查更新時出錯",
"Details": "詳情",
"Cancel Selection": "取消選擇",
"File Size:": "檔案大小",
"Auto Detect": "自動檢測",
"Touch": "觸控",
"Scrolling Overlap (px)": "滾動重疊(px",
"Next Section": "下一章",
"Previous Section": "上一章",
"Next Page": "下一頁",
"Previous Page": "上一頁"
}
+37
View File
@@ -1,5 +1,42 @@
{
"releases": {
"0.9.43": {
"date": "2025-05-19",
"notes": [
"Enhanced compatibility with Gutenberg and Feedbooks ebooks for better styling",
"Reduced sensitivity of trackpad and mouse during page flips",
"Cloud backup status is now visible for each book on mobile and desktop",
"New option to control scroll overlap when paginating in scroll mode",
"Added Dutch language translations",
"Added more font weight options for built-in fonts",
"Added previous and next section buttons in the footer bar for easier navigation"
]
},
"0.9.41": {
"date": "2025-05-13",
"notes": [
"Improved UI and layout on mobile devices",
"Avatar images are now cached for offline use",
"Book file size is now displayed in the book details view",
"Update status is now correctly shown in the About window",
"TTS control positioning improved for notebook and RTL modes",
"TXT files are segmented by paragraph count if no chapter titles are found",
"Android: App now respects system auto-rotation settings",
"Linux: Updater is disabled on Linux when not using AppImage",
"Linux: Added support for Linux ARMHF builds",
"CSS: Resolved layout and color issues caused by hardcoded CSS"
]
},
"0.9.40": {
"date": "2025-05-08",
"notes": [
"Prevented oversized images from causing layout issues",
"Resolved issue with transient navigation bar on Android 9",
"Action bar now closes properly when the footbar is dismissed",
"Smoother experience when expanding Table of Contents sections",
"Reverted unintended style overrides"
]
},
"0.9.39": {
"date": "2025-05-07",
"notes": [
@@ -1,3 +1,22 @@
#!/bin/bash
set -e
echo "Updating bundleVersion in tauri.appstore.conf.json..."
CONFIG_FILE="src-tauri/tauri.appstore.conf.json"
CURRENT_DATE=$(date "+%Y%m%d.%H%M%S")
if [ ! -f "$CONFIG_FILE" ]; then
echo "Error: Config file $CONFIG_FILE not found!"
exit 1
fi
TMP_FILE=$(mktemp)
cat "$CONFIG_FILE" | jq --arg version "$CURRENT_DATE" '.bundle.macOS.bundleVersion = $version' > "$TMP_FILE"
mv "$TMP_FILE" "$CONFIG_FILE"
echo "Updated bundleVersion to $CURRENT_DATE"
echo "Building macOS universal app for App Store..."
pnpm run build-macos-universial-appstore
BUNDLE_DIR=../../target/universal-apple-darwin/release/bundle/macos
+2 -2
View File
@@ -31,9 +31,9 @@ reqwest = { version = "0.12", default-features = false, features = [
"stream",
] }
# FIXME: remove the devtools feature in production
tauri = { version = "2.4.1", features = [ "protocol-asset", "devtools"] }
tauri = { version = "2.5.1", features = [ "protocol-asset", "devtools"] }
tauri-build = "2.1.1"
tauri-plugin-log = "2.3.1"
tauri-plugin-log = "2.4.0"
tauri-plugin-fs = "2.2.1"
tauri-plugin-dialog = "2.2.1"
tauri-plugin-os = "2.2.1"
@@ -225,7 +225,7 @@ class NativeBridgePlugin(private val activity: Activity): Plugin(activity) {
controller.hide(WindowInsets.Type.systemBars())
}
}
} else {
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val compatController = WindowCompat.getInsetsController(window, decorView)
compatController?.let {
it.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
@@ -240,6 +240,21 @@ class NativeBridgePlugin(private val activity: Activity): Plugin(activity) {
it.hide(WindowInsetsCompat.Type.systemBars())
}
}
} else {
@Suppress("DEPRECATION")
decorView.systemUiVisibility = when {
visible && !isDarkMode -> View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
visible -> View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
else -> View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_FULLSCREEN
}
}
window.statusBarColor = Color.TRANSPARENT
window.navigationBarColor = Color.TRANSPARENT
@@ -340,7 +355,7 @@ class NativeBridgePlugin(private val activity: Activity): Plugin(activity) {
when (orientation) {
"portrait" -> activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
"landscape" -> activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
"auto" -> activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
"auto" -> activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER
else -> {
invoke.reject("Invalid orientation mode")
return
+15 -3
View File
@@ -191,9 +191,8 @@ pub fn run() {
let app_handle = app.handle().clone();
app.listen("window-ready", move |_| {
app_handle
.get_webview_window("main")
.unwrap()
let webview = app_handle.get_webview_window("main").unwrap();
webview
.eval("window.__READEST_CLI_ACCESS = true;")
.expect("Failed to set cli access config");
@@ -204,6 +203,19 @@ pub fn run() {
{
set_rounded_window(&app_handle, false);
}
#[cfg(target_os = "linux")]
{
let is_appimage = std::env::var("APPIMAGE").is_ok()
|| std::env::current_exe()
.map(|path| path.to_string_lossy().contains("/tmp/.mount_"))
.unwrap_or(false);
let script =
format!("window.__READEST_UPDATER_DISABLED = {};", !is_appimage);
webview
.eval(&script)
.expect("Failed to set updater disabled config");
}
});
}
+3 -3
View File
@@ -78,8 +78,8 @@ export default function AuthPage() {
useTheme({ systemUIVisible: false });
const getTauriRedirectTo = (isOAuth: boolean) => {
if (process.env.NODE_ENV === 'production' || appService?.isMobile || USE_APPLE_SIGN_IN) {
if (appService?.isMobile) {
if (process.env.NODE_ENV === 'production' || appService?.isMobileApp || USE_APPLE_SIGN_IN) {
if (appService?.isMobileApp) {
return isOAuth ? DEEPLINK_CALLBACK : WEB_AUTH_CALLBACK;
}
return DEEPLINK_CALLBACK;
@@ -172,7 +172,7 @@ export default function AuthPage() {
const startTauriOAuth = async () => {
try {
if (process.env.NODE_ENV === 'production' || appService?.isMobile || USE_APPLE_SIGN_IN) {
if (process.env.NODE_ENV === 'production' || appService?.isMobileApp || USE_APPLE_SIGN_IN) {
const { getCurrentWindow } = await import('@tauri-apps/api/window');
const currentWindow = getCurrentWindow();
currentWindow.listen('single-instance', ({ event, payload }) => {
-1
View File
@@ -2,7 +2,6 @@ import * as React from 'react';
import Providers from '@/components/Providers';
import '../styles/globals.css';
import '../styles/fonts.css';
const url = 'https://web.readest.com/';
const title = 'Readest — Where You Read, Digest and Get Insight';
@@ -1,12 +1,18 @@
import clsx from 'clsx';
import { MdCheckCircle, MdCheckCircleOutline } from 'react-icons/md';
import { CiCircleMore } from 'react-icons/ci';
import { LiaCloudUploadAltSolid, LiaCloudDownloadAltSolid } from 'react-icons/lia';
import {
LiaCloudUploadAltSolid,
LiaCloudDownloadAltSolid,
LiaInfoCircleSolid,
} from 'react-icons/lia';
import { Book } from '@/types/book';
import { useEnv } from '@/context/EnvContext';
import { useAuth } from '@/context/AuthContext';
import { useRouter } from 'next/navigation';
import { useResponsiveSize } from '@/hooks/useResponsiveSize';
import { LibraryViewModeType } from '@/types/settings';
import { navigateToLogin } from '@/utils/nav';
import { formatAuthors } from '@/utils/book';
import ReadingProgress from './ReadingProgress';
import BookCover from '@/components/BookCover';
@@ -32,8 +38,10 @@ const BookItem: React.FC<BookItemProps> = ({
handleBookDownload,
showBookDetailsModal,
}) => {
const iconSize15 = useResponsiveSize(15);
const router = useRouter();
const { user } = useAuth();
const { appService } = useEnv();
const iconSize15 = useResponsiveSize(15);
const stopEvent = (e: React.MouseEvent | React.TouchEvent) => {
e.preventDefault();
@@ -96,11 +104,26 @@ const BookItem: React.FC<BookItemProps> = ({
className={clsx('flex items-center', book.progress ? 'justify-between' : 'justify-end')}
>
{book.progress && <ReadingProgress book={book} />}
<div className='flex items-center gap-x-1'>
<div className='flex items-center justify-center gap-x-2'>
{!appService?.isMobile && (
<button
className='show-detail-button -m-2 p-2 sm:opacity-0 sm:group-hover:opacity-100'
onPointerDown={(e) => stopEvent(e)}
onPointerUp={(e) => stopEvent(e)}
onPointerMove={(e) => stopEvent(e)}
onPointerCancel={(e) => stopEvent(e)}
onPointerLeave={(e) => stopEvent(e)}
onClick={() => showBookDetailsModal(book)}
>
<div className='pt-[1px]'>
<LiaInfoCircleSolid size={iconSize15} />
</div>
</button>
)}
{transferProgress !== null ? (
transferProgress === 100 ? null : (
<div
className='radial-progress opacity-0 group-hover:opacity-100'
className='radial-progress'
style={
{
'--value': transferProgress,
@@ -112,38 +135,33 @@ const BookItem: React.FC<BookItemProps> = ({
></div>
)
) : (
<button
className='show-detail-button opacity-0 group-hover:opacity-100'
onPointerDown={(e) => stopEvent(e)}
onPointerUp={(e) => stopEvent(e)}
onPointerMove={(e) => stopEvent(e)}
onPointerCancel={(e) => stopEvent(e)}
onPointerLeave={(e) => stopEvent(e)}
onClick={() => {
if (!book.uploadedAt) {
handleBookUpload(book);
} else if (!book.downloadedAt) {
handleBookDownload(book);
}
}}
>
{!book.uploadedAt && <LiaCloudUploadAltSolid size={iconSize15} />}
{book.uploadedAt && !book.downloadedAt && (
<LiaCloudDownloadAltSolid size={iconSize15} />
)}
</button>
(!book.uploadedAt || (book.uploadedAt && !book.downloadedAt)) && (
<button
className='show-cloud-button -m-2 p-2'
onPointerDown={(e) => stopEvent(e)}
onPointerUp={(e) => stopEvent(e)}
onPointerMove={(e) => stopEvent(e)}
onPointerCancel={(e) => stopEvent(e)}
onPointerLeave={(e) => stopEvent(e)}
onClick={() => {
if (!user) {
navigateToLogin(router);
return;
}
if (!book.uploadedAt) {
handleBookUpload(book);
} else if (!book.downloadedAt) {
handleBookDownload(book);
}
}}
>
{!book.uploadedAt && <LiaCloudUploadAltSolid size={iconSize15} />}
{book.uploadedAt && !book.downloadedAt && (
<LiaCloudDownloadAltSolid size={iconSize15} />
)}
</button>
)
)}
<button
className='show-detail-button opacity-0 group-hover:opacity-100'
onPointerDown={(e) => stopEvent(e)}
onPointerUp={(e) => stopEvent(e)}
onPointerMove={(e) => stopEvent(e)}
onPointerCancel={(e) => stopEvent(e)}
onPointerLeave={(e) => stopEvent(e)}
onClick={() => showBookDetailsModal(book)}
>
<CiCircleMore size={iconSize15} />
</button>
</div>
</div>
</div>
@@ -2,7 +2,7 @@ import clsx from 'clsx';
import * as React from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { MdDelete, MdOpenInNew, MdOutlineCancel } from 'react-icons/md';
import { MdDelete, MdOpenInNew, MdOutlineCancel, MdInfoOutline } from 'react-icons/md';
import { LuFolderPlus } from 'react-icons/lu';
import { PiPlus } from 'react-icons/pi';
import { Book, BooksGroup } from '@/types/book';
@@ -162,6 +162,13 @@ const Bookshelf: React.FC<BookshelfProps> = ({
navigateToReader(router, selectedBooks);
};
const openBookDetails = () => {
const book = libraryBooks.find((book) => book.hash === selectedBooks[0]);
if (book) {
handleShowDetailsBook(book);
}
};
const confirmDelete = async () => {
selectedBooks.forEach((id) => {
for (const book of libraryBooks.filter((book) => book.hash === id || book.groupId === id)) {
@@ -290,14 +297,14 @@ const Bookshelf: React.FC<BookshelfProps> = ({
<div
className={clsx(
'flex items-center justify-center shadow-lg',
'text-base-content bg-base-300 text-sm',
'bg-gray-600 text-xs text-white',
'mx-auto w-fit space-x-6 rounded-lg p-4',
)}
>
<button
onClick={openSelectedBooks}
className={clsx(
'flex flex-col items-center justify-center',
'flex flex-col items-center justify-center gap-1',
(!selectedBooks.length || !selectedBooks.every((id) => isMd5(id))) &&
'btn-disabled opacity-50',
)}
@@ -308,17 +315,28 @@ const Bookshelf: React.FC<BookshelfProps> = ({
<button
onClick={groupSelectedBooks}
className={clsx(
'flex flex-col items-center justify-center',
'flex flex-col items-center justify-center gap-1',
!selectedBooks.length && 'btn-disabled opacity-50',
)}
>
<LuFolderPlus />
<div>{_('Group')}</div>
</button>
<button
onClick={openBookDetails}
className={clsx(
'flex flex-col items-center justify-center gap-1',
(selectedBooks.length !== 1 || !selectedBooks.every((id) => isMd5(id))) &&
'btn-disabled opacity-50',
)}
>
<MdInfoOutline />
<div>{_('Details')}</div>
</button>
<button
onClick={deleteSelectedBooks}
className={clsx(
'flex flex-col items-center justify-center',
'flex flex-col items-center justify-center gap-1',
!selectedBooks.length && 'btn-disabled opacity-50',
)}
>
@@ -327,7 +345,7 @@ const Bookshelf: React.FC<BookshelfProps> = ({
</button>
<button
onClick={() => handleSetSelectMode(false)}
className={clsx('flex flex-col items-center justify-center')}
className={clsx('flex flex-col items-center justify-center gap-1')}
>
<MdOutlineCancel />
<div>{_('Cancel')}</div>
@@ -1,3 +1,5 @@
import clsx from 'clsx';
import { useEnv } from '@/context/EnvContext';
import { useTranslation } from '@/hooks/useTranslation';
import MenuItem from '@/components/MenuItem';
@@ -8,6 +10,7 @@ interface ImportMenuProps {
const ImportMenu: React.FC<ImportMenuProps> = ({ setIsDropdownOpen, onImportBooks }) => {
const _ = useTranslation();
const { appService } = useEnv();
const handleImportBooks = () => {
onImportBooks();
@@ -17,7 +20,10 @@ const ImportMenu: React.FC<ImportMenuProps> = ({ setIsDropdownOpen, onImportBook
return (
<ul
tabIndex={-1}
className='dropdown-content dropdown-center bg-base-100 menu rounded-box z-[1] mt-3 w-52 p-2 shadow'
className={clsx(
'dropdown-content bg-base-100 menu rounded-box z-[1] mt-3 w-52 p-2 shadow',
appService?.isMobile ? 'no-triangle' : 'dropdown-center',
)}
>
<MenuItem label={_('From Local File')} onClick={handleImportBooks} />
</ul>
@@ -142,7 +142,7 @@ const LibraryHeader: React.FC<LibraryHeaderProps> = ({
setSearchQuery('');
throttledUpdateQueryParam('');
}}
className='text-gray-400 hover:text-gray-600'
className='pe-1 text-gray-400 hover:text-gray-600'
aria-label={_('Clear Search')}
>
<IoMdCloseCircle className='h-4 w-4' />
@@ -150,7 +150,10 @@ const LibraryHeader: React.FC<LibraryHeaderProps> = ({
)}
<span className='bg-base-content/50 mx-2 h-4 w-[0.5px]'></span>
<Dropdown
className='exclude-title-bar-mousedown dropdown-bottom flex h-6 cursor-pointer justify-center'
className={clsx(
'exclude-title-bar-mousedown dropdown-bottom flex h-6 cursor-pointer justify-center',
appService?.isMobile ? 'dropdown-end' : 'dropdown-center',
)}
buttonClassName='p-0 h-6 min-h-6 w-6 flex items-center justify-center'
toggleButton={
<div className='lg:tooltip lg:tooltip-bottom' data-tip={_('Import Books')}>
@@ -160,47 +163,61 @@ const LibraryHeader: React.FC<LibraryHeaderProps> = ({
>
<ImportMenu onImportBooks={onImportBooks} />
</Dropdown>
<button
onClick={onToggleSelectMode}
aria-label={_('Select Multiple Books')}
className='h-6'
>
<div
className='lg:tooltip lg:tooltip-bottom cursor-pointer'
data-tip={_('Select Books')}
{appService?.isMobile ? null : (
<button
onClick={onToggleSelectMode}
aria-label={_('Select Multiple Books')}
className='h-6'
>
<PiSelectionAllDuotone
role='button'
className={`h-6 w-6 ${isSelectMode ? 'fill-gray-400' : 'fill-gray-500'}`}
/>
</div>
</button>
<div
className='lg:tooltip lg:tooltip-bottom cursor-pointer'
data-tip={_('Select Books')}
>
<PiSelectionAllDuotone
role='button'
className={`h-6 w-6 ${isSelectMode ? 'fill-gray-400' : 'fill-gray-500'}`}
/>
</div>
</button>
)}
</div>
</div>
<div className='flex h-full items-center gap-x-2 sm:gap-x-4'>
<Dropdown
className='exclude-title-bar-mousedown dropdown-bottom dropdown-end'
buttonClassName='btn btn-ghost h-8 min-h-8 w-8 p-0'
toggleButton={<PiDotsThreeCircle size={iconSize18} />}
>
<SortMenu />
</Dropdown>
<Dropdown
className='exclude-title-bar-mousedown dropdown-bottom dropdown-end'
buttonClassName='btn btn-ghost h-8 min-h-8 w-8 p-0'
toggleButton={<MdOutlineMenu size={iconSize18} />}
>
<SettingsMenu />
</Dropdown>
{appService?.hasWindowBar && (
<WindowButtons
headerRef={headerRef}
showMinimize={windowButtonVisible}
showMaximize={windowButtonVisible}
showClose={windowButtonVisible}
/>
)}
</div>
{appService?.isMobile && isSelectMode ? (
<div className='w-max-[72px] w-min-[72px] flex h-full items-center'>
<button
onClick={onToggleSelectMode}
className='btn btn-ghost text-base-content/85 h-8 min-h-8 w-[72px] p-0'
aria-label={_('Cancel Selection')}
>
{_('Cancel')}
</button>
</div>
) : (
<div className='flex h-full items-center gap-x-2 sm:gap-x-4'>
<Dropdown
className='exclude-title-bar-mousedown dropdown-bottom dropdown-end'
buttonClassName='btn btn-ghost h-8 min-h-8 w-8 p-0'
toggleButton={<PiDotsThreeCircle size={iconSize18} />}
>
<SortMenu />
</Dropdown>
<Dropdown
className='exclude-title-bar-mousedown dropdown-bottom dropdown-end'
buttonClassName='btn btn-ghost h-8 min-h-8 w-8 p-0'
toggleButton={<MdOutlineMenu size={iconSize18} />}
>
<SettingsMenu />
</Dropdown>
{appService?.hasWindowBar && (
<WindowButtons
headerRef={headerRef}
showMinimize={windowButtonVisible}
showMaximize={windowButtonVisible}
showClose={windowButtonVisible}
/>
)}
</div>
)}
</div>
</div>
);
@@ -1,3 +1,4 @@
import clsx from 'clsx';
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { PiUserCircle } from 'react-icons/pi';
@@ -134,7 +135,6 @@ const SettingsMenu: React.FC<SettingsMenuProps> = ({ setIsDropdownOpen }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [token]);
const isWebApp = isWebAppPlatform();
const avatarUrl = user?.user_metadata?.['picture'] || user?.user_metadata?.['avatar_url'];
const userFullName = user?.user_metadata?.['full_name'];
const userDisplayName = userFullName ? userFullName.split(' ')[0] : null;
@@ -142,7 +142,10 @@ const SettingsMenu: React.FC<SettingsMenuProps> = ({ setIsDropdownOpen }) => {
return (
<div
tabIndex={0}
className='settings-menu dropdown-content no-triangle border-base-100 z-20 mt-2 shadow-2xl'
className={clsx(
'settings-menu dropdown-content no-triangle border-base-100',
'z-20 mt-2 max-w-[90vw] shadow-2xl',
)}
>
{user ? (
<MenuItem
@@ -180,11 +183,13 @@ const SettingsMenu: React.FC<SettingsMenuProps> = ({ setIsDropdownOpen }) => {
onClick={toggleAutoImportBooksOnOpen}
/>
)}
<MenuItem
label={_('Open Last Book on Start')}
Icon={isOpenLastBooks ? MdCheck : undefined}
onClick={toggleOpenLastBooks}
/>
{isTauriAppPlatform() && (
<MenuItem
label={_('Open Last Book on Start')}
Icon={isOpenLastBooks ? MdCheck : undefined}
onClick={toggleOpenLastBooks}
/>
)}
{appService?.hasUpdater && (
<MenuItem
label={_('Check Updates on Start')}
@@ -208,7 +213,7 @@ const SettingsMenu: React.FC<SettingsMenuProps> = ({ setIsDropdownOpen }) => {
/>
<MenuItem label={_('Reload Page')} onClick={handleReloadPage} />
<hr className='border-base-200 my-1' />
{isWebApp && <MenuItem label={_('Download Readest')} onClick={downloadReadest} />}
{isWebAppPlatform() && <MenuItem label={_('Download Readest')} onClick={downloadReadest} />}
<MenuItem label={_('About Readest')} onClick={showAboutReadest} />
</div>
);
+38 -28
View File
@@ -32,6 +32,7 @@ import { useThemeStore } from '@/store/themeStore';
import { useScreenWakeLock } from '@/hooks/useScreenWakeLock';
import { useOpenWithBooks } from '@/hooks/useOpenWithBooks';
import { lockScreenOrientation } from '@/utils/bridge';
import { mountAdditionalFonts } from '@/utils/style';
import {
tauriHandleSetAlwaysOnTop,
tauriHandleToggleFullScreen,
@@ -78,6 +79,7 @@ const LibraryPageContent = ({ searchParams }: { searchParams: ReadonlyURLSearchP
const [booksTransferProgress, setBooksTransferProgress] = useState<{
[key: string]: number | null;
}>({});
const [pendingNavigationBookIds, setPendingNavigationBookIds] = useState<string[] | null>(null);
const [isDragging, setIsDragging] = useState(false);
const demoBooks = useDemoBooks();
const containerRef = useRef<HTMLDivElement>(null);
@@ -106,6 +108,10 @@ const LibraryPageContent = ({ searchParams }: { searchParams: ReadonlyURLSearchP
},
});
useEffect(() => {
mountAdditionalFonts(document);
}, []);
useEffect(() => {
const doCheckAppUpdates = async () => {
if (appService?.hasUpdater && settings.autoCheckUpdates) {
@@ -121,7 +127,7 @@ const LibraryPageContent = ({ searchParams }: { searchParams: ReadonlyURLSearchP
useEffect(() => {
if (appService?.isMobileApp) {
lockScreenOrientation({ orientation: 'portrait' });
lockScreenOrientation({ orientation: 'auto' });
}
}, [appService]);
@@ -231,10 +237,10 @@ const LibraryPageContent = ({ searchParams }: { searchParams: ReadonlyURLSearchP
console.log('Opening books:', bookIds);
if (bookIds.length > 0) {
setTimeout(() => {
navigateToReader(router, bookIds);
}, 0);
setPendingNavigationBookIds(bookIds);
return true;
}
return false;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
@@ -245,21 +251,31 @@ const LibraryPageContent = ({ searchParams }: { searchParams: ReadonlyURLSearchP
lastBookIds: string[],
libraryBooks: Book[],
) => {
if (lastBookIds.length === 0) return;
if (lastBookIds.length === 0) return false;
const bookIds: string[] = [];
for (const bookId of lastBookIds) {
const book = libraryBooks.find((b) => b.hash === bookId);
if (book && (await appService.isBookAvailable(book))) {
bookIds.push(book.hash);
}
console.log('Opening last books:', bookIds);
}
console.log('Opening last books:', bookIds);
if (bookIds.length > 0) {
setPendingNavigationBookIds(bookIds);
return true;
}
return false;
};
useEffect(() => {
if (pendingNavigationBookIds) {
const bookIds = pendingNavigationBookIds;
setPendingNavigationBookIds(null);
if (bookIds.length > 0) {
setTimeout(() => {
navigateToReader(router, bookIds);
}, 0);
navigateToReader(router, bookIds);
}
}
};
}, [pendingNavigationBookIds, router]);
useEffect(() => {
if (isInitiating.current) return;
@@ -285,34 +301,28 @@ const LibraryPageContent = ({ searchParams }: { searchParams: ReadonlyURLSearchP
const settings = await appService.loadSettings();
setSettings(settings);
const libraryBooks = await appService.loadLibraryBooks();
if (checkOpenWithBooks) {
await handleOpenWithBooks(appService, libraryBooks);
} else {
setCheckOpenWithBooks(false);
setLibrary(libraryBooks);
}
if (checkLastOpenBooks && settings.openLastBooks) {
await handleOpenLastBooks(appService, settings.lastOpenBooks, libraryBooks);
} else {
setCheckLastOpenBooks(false);
}
// Reuse the library from the store when we return from the reader
const library = libraryBooks.length > 0 ? libraryBooks : await appService.loadLibraryBooks();
setCheckOpenWithBooks(checkOpenWithBooks && (await handleOpenWithBooks(appService, library)));
setCheckLastOpenBooks(
checkLastOpenBooks &&
settings.openLastBooks &&
(await handleOpenLastBooks(appService, settings.lastOpenBooks, library)),
);
setLibrary(library);
setLibraryLoaded(true);
if (loadingTimeout) clearTimeout(loadingTimeout);
setLoading(false);
};
const handleOpenWithBooks = async (appService: AppService, libraryBooks: Book[]) => {
const handleOpenWithBooks = async (appService: AppService, library: Book[]) => {
const openWithFiles = (await parseOpenWithFiles()) || [];
if (openWithFiles.length > 0) {
await processOpenWithFiles(appService, openWithFiles, libraryBooks);
} else {
setCheckOpenWithBooks(false);
setLibrary(libraryBooks);
return await processOpenWithFiles(appService, openWithFiles, library);
}
return false;
};
initLogin();
+12 -5
View File
@@ -1,7 +1,14 @@
import { redirectToLibrary } from '@/utils/nav';
'use client';
const HomePage = () => {
redirectToLibrary();
};
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
export default HomePage;
export default function HomePage() {
const router = useRouter();
useEffect(() => {
router.replace('/library');
}, [router]);
return null;
}
@@ -18,6 +18,7 @@ import Annotator from './annotator/Annotator';
import FootnotePopup from './FootnotePopup';
import HintInfo from './HintInfo';
import DoubleBorder from './DoubleBorder';
import TTSControl from './tts/TTSControl';
interface BooksGridProps {
bookKeys: string[];
@@ -42,7 +43,7 @@ const BooksGrid: React.FC<BooksGridProps> = ({ bookKeys, onCloseBook }) => {
return (
<div
className={clsx('grid h-full flex-grow')}
className={clsx('relative grid h-full flex-grow')}
style={{
gridTemplateColumns: gridTemplate.columns,
gridTemplateRows: gridTemplate.rows,
@@ -132,6 +133,7 @@ const BooksGrid: React.FC<BooksGridProps> = ({ bookKeys, onCloseBook }) => {
<HintInfo
bookKey={bookKey}
showDoubleBorder={viewSettings.vertical && viewSettings.doubleBorder}
isScrolled={viewSettings.scrolled}
isVertical={viewSettings.vertical}
horizontalGap={horizontalGapPercent}
verticalMargin={verticalMarginPixels}
@@ -161,6 +163,7 @@ const BooksGrid: React.FC<BooksGridProps> = ({ bookKeys, onCloseBook }) => {
</div>
);
})}
<TTSControl />
</div>
);
};
@@ -42,7 +42,6 @@ const FoliateViewer: React.FC<{
const { getViewSettings, setViewSettings } = useReaderStore();
const { getParallels } = useParallelViewStore();
const { themeCode, isDarkMode } = useThemeStore();
const viewSettings = getViewSettings(bookKey)!;
const [toastMessage, setToastMessage] = useState('');
useEffect(() => {
@@ -50,7 +49,7 @@ const FoliateViewer: React.FC<{
return () => clearTimeout(timer);
}, [toastMessage]);
useUICSS(bookKey, viewSettings);
useUICSS(bookKey);
useProgressSync(bookKey);
useProgressAutoSave(bookKey);
@@ -72,7 +71,7 @@ const FoliateViewer: React.FC<{
bookKey,
viewSettings,
content: data,
transformers: ['punctuation'],
transformers: ['punctuation', 'footnote'],
};
return Promise.resolve(transformContent(ctx));
}
@@ -170,6 +169,7 @@ const FoliateViewer: React.FC<{
const width = containerRect?.width || window.innerWidth;
const height = containerRect?.height || window.innerHeight;
const viewSettings = getViewSettings(bookKey)!;
const writingMode = viewSettings.writingMode;
if (writingMode) {
const settingsDir = getBookDirFromWritingMode(writingMode);
@@ -1,7 +1,8 @@
import React from 'react';
import React, { useEffect } from 'react';
import clsx from 'clsx';
import { RiArrowLeftWideLine, RiArrowRightWideLine } from 'react-icons/ri';
import { RiArrowLeftSLine, RiArrowRightSLine } from 'react-icons/ri';
import { RiArrowGoBackLine, RiArrowGoForwardLine } from 'react-icons/ri';
import { RiArrowLeftDoubleLine, RiArrowRightDoubleLine } from 'react-icons/ri';
import { FaHeadphones } from 'react-icons/fa6';
import { IoIosList as TOCIcon } from 'react-icons/io';
import { PiNotePencil as NoteIcon } from 'react-icons/pi';
@@ -17,6 +18,7 @@ import { useSidebarStore } from '@/store/sidebarStore';
import { useTranslation } from '@/hooks/useTranslation';
import { useResponsiveSize } from '@/hooks/useResponsiveSize';
import { eventDispatcher } from '@/utils/event';
import { viewPagination } from '../hooks/usePagination';
import { saveViewSettings } from '../utils/viewSettingsHelper';
import { PageInfo } from '@/types/book';
import Button from '@/components/Button';
@@ -76,12 +78,24 @@ const FooterBar: React.FC<FooterBarProps> = ({
saveViewSettings(envConfig, bookKey, 'lineHeight', value / 10);
};
const handleGoPrev = () => {
view?.goLeft();
const handleGoPrevPage = () => {
viewPagination(view, viewSettings, 'left');
};
const handleGoNext = () => {
view?.goRight();
const handleGoNextPage = () => {
viewPagination(view, viewSettings, 'right');
};
const handleGoPrevSection = () => {
if (view?.renderer.prevSection) {
view?.renderer.prevSection();
}
};
const handleGoNextSection = () => {
if (view?.renderer.nextSection) {
view?.renderer.nextSection();
}
};
const handleGoBack = () => {
@@ -122,6 +136,12 @@ const FooterBar: React.FC<FooterBarProps> = ({
}
};
useEffect(() => {
if (hoveredBookKey !== bookKey) {
setActionTab('');
}
}, [hoveredBookKey, bookKey]);
const getMarginProgressValue = (marginPx: number, gapPercent: number) => {
return (marginPx / 88 + gapPercent / 10) * 50;
};
@@ -167,7 +187,7 @@ const FooterBar: React.FC<FooterBarProps> = ({
{/* Mobile footer bar */}
<div
className={clsx(
'bg-base-200 absolute bottom-16 flex w-full items-center gap-x-2 px-4 transition-all sm:hidden',
'bg-base-200 absolute bottom-16 flex w-full flex-col items-center gap-y-8 px-4 transition-all sm:hidden',
actionTab === 'progress'
? 'pointer-events-auto translate-y-0 pb-4 pt-8 ease-out'
: 'pointer-events-none invisible translate-y-full overflow-hidden pb-0 pt-0 ease-in',
@@ -178,34 +198,48 @@ const FooterBar: React.FC<FooterBarProps> = ({
: '64px',
}}
>
<Button
icon={viewSettings?.rtl ? <RiArrowRightWideLine /> : <RiArrowLeftWideLine />}
onClick={viewSettings?.rtl ? handleGoNext : handleGoPrev}
tooltip={viewSettings?.rtl ? _('Go Right') : _('Go Left')}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowGoForwardLine /> : <RiArrowGoBackLine />}
onClick={handleGoBack}
tooltip={_('Go Back')}
disabled={!view?.history.canGoBack}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowGoBackLine /> : <RiArrowGoForwardLine />}
onClick={handleGoForward}
tooltip={_('Go Forward')}
disabled={!view?.history.canGoForward}
/>
<Slider
heightPx={sliderHeight}
bubbleLabel={`${Math.round(progressFraction * 100)}%`}
initialValue={progressValid ? progressFraction * 100 : 0}
onChange={(e) => handleProgressChange(e)}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowLeftWideLine /> : <RiArrowRightWideLine />}
onClick={viewSettings?.rtl ? handleGoPrev : handleGoNext}
tooltip={viewSettings?.rtl ? _('Go Left') : _('Go Right')}
/>
<div className='flex w-full items-center justify-between gap-x-6'>
<Slider
heightPx={sliderHeight}
bubbleLabel={`${Math.round(progressFraction * 100)}%`}
initialValue={progressValid ? progressFraction * 100 : 0}
onChange={(e) => handleProgressChange(e)}
/>
</div>
<div className='flex w-full items-center justify-between gap-x-6'>
<Button
icon={viewSettings?.rtl ? <RiArrowRightDoubleLine /> : <RiArrowLeftDoubleLine />}
onClick={viewSettings?.rtl ? handleGoNextSection : handleGoPrevSection}
tooltip={viewSettings?.rtl ? _('Next Section') : _('Previous Section')}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowRightSLine /> : <RiArrowLeftSLine />}
onClick={viewSettings?.rtl ? handleGoNextPage : handleGoPrevPage}
tooltip={viewSettings?.rtl ? _('Next Page') : _('Previous Page')}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowGoForwardLine /> : <RiArrowGoBackLine />}
onClick={handleGoBack}
tooltip={_('Go Back')}
disabled={!view?.history.canGoBack}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowGoBackLine /> : <RiArrowGoForwardLine />}
onClick={handleGoForward}
tooltip={_('Go Forward')}
disabled={!view?.history.canGoForward}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowLeftSLine /> : <RiArrowRightSLine />}
onClick={viewSettings?.rtl ? handleGoPrevPage : handleGoNextPage}
tooltip={viewSettings?.rtl ? _('Previous Page') : _('Next Page')}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowLeftDoubleLine /> : <RiArrowRightDoubleLine />}
onClick={viewSettings?.rtl ? handleGoPrevSection : handleGoNextSection}
tooltip={viewSettings?.rtl ? _('Previous Section') : _('Next Section')}
/>
</div>
</div>
<div
className={clsx(
@@ -283,9 +317,14 @@ const FooterBar: React.FC<FooterBarProps> = ({
{/* Desktop footer bar */}
<div className='hidden w-full items-center gap-x-4 px-4 sm:flex'>
<Button
icon={viewSettings?.rtl ? <RiArrowRightWideLine /> : <RiArrowLeftWideLine />}
onClick={viewSettings?.rtl ? handleGoNext : handleGoPrev}
tooltip={viewSettings?.rtl ? _('Go Right') : _('Go Left')}
icon={viewSettings?.rtl ? <RiArrowRightDoubleLine /> : <RiArrowLeftDoubleLine />}
onClick={viewSettings?.rtl ? handleGoNextSection : handleGoPrevSection}
tooltip={viewSettings?.rtl ? _('Next Section') : _('Previous Section')}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowRightSLine /> : <RiArrowLeftSLine />}
onClick={viewSettings?.rtl ? handleGoNextPage : handleGoPrevPage}
tooltip={viewSettings?.rtl ? _('Next Page') : _('Previous Page')}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowGoForwardLine /> : <RiArrowGoBackLine />}
@@ -314,9 +353,14 @@ const FooterBar: React.FC<FooterBarProps> = ({
/>
<Button icon={<FaHeadphones />} onClick={handleSpeakText} tooltip={_('Speak')} />
<Button
icon={viewSettings?.rtl ? <RiArrowLeftWideLine /> : <RiArrowRightWideLine />}
onClick={viewSettings?.rtl ? handleGoPrev : handleGoNext}
tooltip={viewSettings?.rtl ? _('Go Left') : _('Go Right')}
icon={viewSettings?.rtl ? <RiArrowLeftSLine /> : <RiArrowRightSLine />}
onClick={viewSettings?.rtl ? handleGoPrevPage : handleGoNextPage}
tooltip={viewSettings?.rtl ? _('Previous Page') : _('Next Page')}
/>
<Button
icon={viewSettings?.rtl ? <RiArrowLeftDoubleLine /> : <RiArrowRightDoubleLine />}
onClick={viewSettings?.rtl ? handleGoPrevSection : handleGoNextSection}
tooltip={viewSettings?.rtl ? _('Previous Section') : _('Next Section')}
/>
</div>
</div>
@@ -5,6 +5,7 @@ import { eventDispatcher } from '@/utils/event';
interface SectionInfoProps {
bookKey: string;
showDoubleBorder: boolean;
isScrolled: boolean;
isVertical: boolean;
horizontalGap: number;
verticalMargin: number;
@@ -13,6 +14,7 @@ interface SectionInfoProps {
const HintInfo: React.FC<SectionInfoProps> = ({
bookKey,
showDoubleBorder,
isScrolled,
isVertical,
horizontalGap,
verticalMargin,
@@ -57,7 +59,14 @@ const HintInfo: React.FC<SectionInfoProps> = ({
'hintinfo absolute flex items-center justify-end overflow-hidden ps-2',
'mt-[env(safe-area-inset-top)]',
hintMessage ? 'bg-base-100' : 'bg-transparent',
isVertical ? 'writing-vertical-rl max-h-[50%]' : 'top-0 h-[44px] max-w-[50%]',
isVertical ? 'writing-vertical-rl' : 'top-0 h-[44px]',
isScrolled
? isVertical
? 'h-full'
: 'w-full'
: isVertical
? 'max-h-[50%]'
: 'max-w-[50%]',
)}
style={
isVertical
@@ -15,6 +15,7 @@ import { useSettingsStore } from '@/store/settingsStore';
import { useDeviceControlStore } from '@/store/deviceStore';
import { useScreenWakeLock } from '@/hooks/useScreenWakeLock';
import { eventDispatcher } from '@/utils/event';
import { mountAdditionalFonts } from '@/utils/style';
import { setSystemUIVisibility } from '@/utils/bridge';
import { AboutWindow } from '@/components/AboutWindow';
import { UpdaterWindow } from '@/components/UpdaterWindow';
@@ -36,6 +37,10 @@ const Reader: React.FC<{ ids?: string }> = ({ ids }) => {
useTheme({ systemUIVisible: false, appThemeColor: 'base-100' });
useScreenWakeLock(settings.screenWakeLock);
useEffect(() => {
mountAdditionalFonts(document);
}, []);
useEffect(() => {
const handleVisibilityChange = () => {
if (appService?.isMobileApp && !document.hidden) {
@@ -94,7 +99,7 @@ const Reader: React.FC<{ ids?: string }> = ({ ids }) => {
}, []);
useEffect(() => {
if (!appService?.isMobile) return;
if (!appService?.isMobileApp) return;
const systemUIVisible = !!hoveredBookKey;
setSystemUIVisibility({ visible: systemUIVisible, darkMode: isDarkMode });
if (systemUIVisible) {
@@ -27,7 +27,6 @@ import Spinner from '@/components/Spinner';
import SideBar from './sidebar/SideBar';
import Notebook from './notebook/Notebook';
import BooksGrid from './BooksGrid';
import TTSControl from './tts/TTSControl';
const ReaderContent: React.FC<{ ids?: string; settings: SystemSettings }> = ({ ids, settings }) => {
const router = useRouter();
@@ -166,7 +165,6 @@ const ReaderContent: React.FC<{ ids?: string; settings: SystemSettings }> = ({ i
<div className={clsx('flex', appService?.isIOSApp ? 'h-[100vh]' : 'h-dvh')}>
<SideBar onGoToLibrary={handleCloseBooksToLibrary} />
<BooksGrid bookKeys={bookKeys} onCloseBook={handleCloseBook} />
<TTSControl />
<Notebook />
{showDetailsBook && (
<BookDetailModal
@@ -1,14 +1,17 @@
import React from 'react';
import { RiFontSize } from 'react-icons/ri';
import { useReaderStore } from '@/store/readerStore';
import { useTranslation } from '@/hooks/useTranslation';
import { useSettingsStore } from '@/store/settingsStore';
import Button from '@/components/Button';
const SettingsToggler = () => {
const _ = useTranslation();
const { setHoveredBookKey } = useReaderStore();
const { isFontLayoutSettingsDialogOpen, setFontLayoutSettingsDialogOpen } = useSettingsStore();
const handleToggleSettings = () => {
setHoveredBookKey('');
setFontLayoutSettingsDialogOpen(!isFontLayoutSettingsDialogOpen);
};
return (
@@ -1,4 +1,4 @@
import React, { useState, useEffect, useRef } from 'react';
import React, { useState, useEffect } from 'react';
import { FiSearch } from 'react-icons/fi';
import { FiCopy } from 'react-icons/fi';
import { PiHighlighterFill } from 'react-icons/pi';
@@ -22,16 +22,10 @@ import { useTranslation } from '@/hooks/useTranslation';
import { useResponsiveSize } from '@/hooks/useResponsiveSize';
import { useFoliateEvents } from '../../hooks/useFoliateEvents';
import { useNotesSync } from '../../hooks/useNotesSync';
import {
getPopupPosition,
getPosition,
getTextFromRange,
Position,
TextSelection,
} from '@/utils/sel';
import { useTextSelector } from '../../hooks/useTextSelector';
import { getPopupPosition, getPosition, Position, TextSelection } from '@/utils/sel';
import { eventDispatcher } from '@/utils/event';
import { findTocItemBS } from '@/utils/toc';
import { transformContent } from '@/services/transformService';
import { HIGHLIGHT_COLOR_HEX } from '@/services/constants';
import AnnotationPopup from './AnnotationPopup';
import WiktionaryPopup from './WiktionaryPopup';
@@ -54,15 +48,8 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
const bookData = getBookData(bookKey)!;
const view = getView(bookKey);
const viewSettings = getViewSettings(bookKey)!;
const primaryLang = bookData.book?.primaryLanguage || 'en';
const isShowingPopup = useRef(false);
const isTextSelected = useRef(false);
const isUpToShowPopup = useRef(false);
const isTouchstarted = useRef(false);
const selectionStartRef = useRef<number | null>(null);
const selectionAnchorRef = useRef<{ node: Node; offset: number } | null>(null);
const [selection, setSelection] = useState<TextSelection | null>();
const [selection, setSelection] = useState<TextSelection | null>(null);
const [showAnnotPopup, setShowAnnotPopup] = useState(false);
const [showWiktionaryPopup, setShowWiktionaryPopup] = useState(false);
const [showWikipediaPopup, setShowWikipediaPopup] = useState(false);
@@ -86,142 +73,41 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
const dictPopupWidth = Math.min(480, maxWidth);
const dictPopupHeight = Math.min(300, maxHeight);
const transPopupWidth = Math.min(480, maxWidth);
const transPopupHeight = Math.min(360, maxHeight);
const transPopupHeight = Math.min(265, maxHeight);
const annotPopupWidth = Math.min(useResponsiveSize(300), maxWidth);
const annotPopupHeight = useResponsiveSize(44);
const androidSelectionHandlerHeight = 0;
const handleDismissPopup = () => {
setSelection(null);
setShowAnnotPopup(false);
setShowWiktionaryPopup(false);
setShowWikipediaPopup(false);
setShowDeepLPopup(false);
};
const handleDismissPopupAndSelection = () => {
handleDismissPopup();
view?.deselect();
};
const { handleScroll, handlePointerup, handleSelectionchange, handleShowPopup, handleUpToPopup } =
useTextSelector(bookKey, setSelection, handleDismissPopup);
const onLoad = (event: Event) => {
const detail = (event as CustomEvent).detail;
const { doc, index } = detail;
const isValidSelection = (sel: Selection) => {
return sel && sel.toString().trim().length > 0 && sel.rangeCount > 0;
};
const transformCtx = {
bookKey,
viewSettings: getViewSettings(bookKey)!,
content: '',
transformers: ['punctuation'],
reversePunctuationTransform: true,
};
const getAnnotationText = (range: Range) => {
return getTextFromRange(range, primaryLang.startsWith('ja') ? ['rt'] : []);
};
const makeSelection = async (sel: Selection, rebuildRange = false) => {
isTextSelected.current = true;
const range = sel.getRangeAt(0);
if (rebuildRange) {
sel.removeAllRanges();
sel.addRange(range);
}
transformCtx['content'] = getAnnotationText(range);
setSelection({ key: bookKey, text: await transformContent(transformCtx), range, index });
};
// FIXME: extremely hacky way to dismiss system selection tools on iOS
const makeSelectionOnIOS = async (sel: Selection) => {
isTextSelected.current = true;
const range = sel.getRangeAt(0);
setTimeout(() => {
sel.removeAllRanges();
setTimeout(async () => {
if (!isTextSelected.current) return;
sel.addRange(range);
transformCtx['content'] = getAnnotationText(range);
setSelection({ key: bookKey, text: await transformContent(transformCtx), range, index });
}, 40);
}, 0);
};
const handleSelectstart = () => {
selectionAnchorRef.current = null;
};
const handleSelectionchange = () => {
// Available on iOS, Android and Desktop, fired when the selection is changed
// Ideally the popup only shows when the selection is done,
// but on Android no proper events are fired to notify selection done or I didn't find it,
// we make the popup show when the selection is changed
if (osPlatform === 'ios' || appService?.isIOSApp) return;
const sel = doc.getSelection();
if (isValidSelection(sel)) {
if (osPlatform === 'android' && isTouchstarted.current) {
if (!selectionAnchorRef.current) {
const range = sel.getRangeAt(0);
selectionAnchorRef.current = {
node: range.startContainer,
offset: range.startOffset,
};
}
if (selectionAnchorRef.current) {
const currentRange = sel.getRangeAt(0);
if (
currentRange.startContainer !== selectionAnchorRef.current.node ||
currentRange.startOffset !== selectionAnchorRef.current.offset
) {
const newRange = doc.createRange();
newRange.setStart(selectionAnchorRef.current.node, selectionAnchorRef.current.offset);
newRange.setEnd(currentRange.endContainer, currentRange.endOffset);
sel.removeAllRanges();
sel.addRange(newRange);
}
}
makeSelection(sel, false);
}
} else if (!isUpToShowPopup.current) {
isTextSelected.current = false;
setShowAnnotPopup(false);
setShowWiktionaryPopup(false);
setShowWikipediaPopup(false);
setShowDeepLPopup(false);
}
};
const handlePointerup = () => {
// Available on iOS and Desktop, fired when release the long press
// Note that on Android, pointerup event is fired after an additional touch event
const sel = doc.getSelection();
if (isValidSelection(sel)) {
if (osPlatform === 'ios' || appService?.isIOSApp) {
makeSelectionOnIOS(sel);
} else {
makeSelection(sel, true);
}
}
};
const handleTouchstart = () => {
// Available on iOS and Android for the initial touch event
isTouchstarted.current = true;
};
const handleTouchmove = () => {
// Available on iOS, on Android not fired
// To make the popup not to follow the selection
setShowAnnotPopup(false);
};
const handleTouchend = () => {
// Available on iOS, on Android fired after an additional touch event
isTouchstarted.current = false;
};
const handleScroll = () => {
// Prevent the container from scrolling when text is selected in paginated mode
// This is a workaround for the issue #873
// TODO: support text selection across pages
if (
!viewSettings?.scrolled &&
isTextSelected.current &&
view?.renderer?.containerPosition &&
selectionStartRef.current
) {
view.renderer.containerPosition = selectionStartRef.current;
}
};
if (bookData.book?.format !== 'PDF') {
view?.renderer?.addEventListener('scroll', handleScroll);
detail.doc?.addEventListener('pointerup', handlePointerup);
detail.doc?.addEventListener('touchstart', handleTouchstart);
detail.doc?.addEventListener('touchmove', handleTouchmove);
detail.doc?.addEventListener('touchend', handleTouchend);
detail.doc?.addEventListener('selectstart', handleSelectstart);
detail.doc?.addEventListener('selectionchange', handleSelectionchange);
detail.doc?.addEventListener('pointerup', () => handlePointerup(doc, index));
detail.doc?.addEventListener('selectionchange', () => handleSelectionchange(doc, index));
// Disable the default context menu on mobile devices,
// although it should but doesn't work on iOS
@@ -269,60 +155,22 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
const annotation = annotations.find((annotation) => annotation.cfi === cfi);
if (!annotation) return;
const selection = { key: bookKey, annotated: true, text: annotation.text ?? '', range, index };
isUpToShowPopup.current = true;
setSelectedStyle(annotation.style!);
setSelectedColor(annotation.color!);
setSelection(selection);
handleUpToPopup();
};
useFoliateEvents(view, { onLoad, onDrawAnnotation, onShowAnnotation });
const handleDismissPopup = () => {
setSelection(null);
setShowAnnotPopup(false);
setShowWiktionaryPopup(false);
setShowWikipediaPopup(false);
setShowDeepLPopup(false);
isShowingPopup.current = false;
};
const handleDismissPopupAndSelection = () => {
handleDismissPopup();
view?.deselect();
isTextSelected.current = false;
};
useEffect(() => {
if (isTextSelected.current && !selectionStartRef.current) {
selectionStartRef.current = view?.renderer?.start || null;
} else if (!isTextSelected.current) {
selectionStartRef.current = null;
selectionAnchorRef.current = null;
}
handleShowPopup(showAnnotPopup || showWiktionaryPopup || showWikipediaPopup || showDeepLPopup);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isTextSelected.current]);
}, [showAnnotPopup, showWiktionaryPopup, showWikipediaPopup, showDeepLPopup]);
useEffect(() => {
const handleSingleClick = (): boolean => {
if (isUpToShowPopup.current) {
isUpToShowPopup.current = false;
return true;
}
if (isTextSelected.current) {
handleDismissPopupAndSelection();
return true;
}
if (showAnnotPopup || isShowingPopup.current) {
handleDismissPopup();
return true;
}
return false;
};
eventDispatcher.onSync('iframe-single-click', handleSingleClick);
eventDispatcher.on('export-annotations', handleExportMarkdown);
return () => {
eventDispatcher.offSync('iframe-single-click', handleSingleClick);
eventDispatcher.off('export-annotations', handleExportMarkdown);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -342,7 +190,7 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
viewSettings.vertical ? annotPopupWidth : annotPopupHeight,
popupPadding,
);
if (isTextSelected.current && annotPopupPos.dir === 'down' && osPlatform === 'android') {
if (annotPopupPos.dir === 'down' && osPlatform === 'android') {
triangPos.point.y += androidSelectionHandlerHeight;
annotPopupPos.point.y += androidSelectionHandlerHeight;
}
@@ -361,12 +209,11 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
popupPadding,
);
if (triangPos.point.x == 0 || triangPos.point.y == 0) return;
setShowAnnotPopup(true);
setAnnotPopupPosition(annotPopupPos);
setDictPopupPosition(dictPopupPos);
setTranslatorPopupPosition(transPopupPos);
setTrianglePosition(triangPos);
isShowingPopup.current = true;
handleShowAnnotPopup();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selection, bookKey]);
@@ -393,6 +240,13 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [progress]);
const handleShowAnnotPopup = () => {
setShowAnnotPopup(true);
setShowDeepLPopup(false);
setShowWiktionaryPopup(false);
setShowWikipediaPopup(false);
};
const handleCopy = () => {
if (!selection || !selection.text) return;
eventDispatcher.dispatch('toast', {
@@ -1,34 +1,31 @@
import React, { useEffect, useState } from 'react';
import Popup from '@/components/Popup';
import { Position } from '@/utils/sel';
import { getAPIBaseUrl } from '@/services/environment';
import { useAuth } from '@/context/AuthContext';
import { useSettingsStore } from '@/store/settingsStore';
import { useTranslation } from '@/hooks/useTranslation';
import { useAuth } from '@/context/AuthContext';
import { useTranslator } from '@/hooks/useTranslator';
import { TRANSLATED_LANGS } from '@/services/constants';
const LANGUAGES = {
AUTO: 'Auto Detect',
EN: 'English',
DE: 'German',
FR: 'French',
ES: 'Spanish',
IT: 'Italian',
EL: 'Greek',
PT: 'Portuguese',
NL: 'Dutch',
PL: 'Polish',
UK: 'Ukrainian',
RU: 'Russian',
AR: 'Arabic',
TR: 'Turkish',
ID: 'Indonesian',
KO: 'Korean',
JA: 'Japanese',
'ZH-HANS': 'Chinese (Simplified)',
'ZH-HANT': 'Chinese (Traditional)',
const notSupportedLangs = ['hi', 'vi'];
const generateTranslatorLangs = () => {
const langs = { ...TRANSLATED_LANGS };
const result: Record<string, string> = {};
for (const [code, name] of Object.entries(langs)) {
if (notSupportedLangs.includes(code)) continue;
let newCode = code.toUpperCase();
if (newCode === 'ZH-CN') {
newCode = 'ZH-HANS';
} else if (newCode === 'ZH-TW') {
newCode = 'ZH-HANT';
}
result[newCode] = name;
}
return result;
};
const DEEPL_API_ENDPOINT = getAPIBaseUrl() + '/deepl/translate';
const TRANSLATOR_LANGS = generateTranslatorLangs();
interface DeepLPopupProps {
text: string;
@@ -51,9 +48,16 @@ const DeepLPopup: React.FC<DeepLPopupProps> = ({
const [sourceLang, setSourceLang] = useState('AUTO');
const [targetLang, setTargetLang] = useState(settings.globalReadSettings.translateTargetLang);
const [translation, setTranslation] = useState<string | null>(null);
const [detectedSourceLang, setDetectedSourceLang] = useState<keyof typeof LANGUAGES | null>(null);
const [detectedSourceLang, setDetectedSourceLang] = useState<
keyof typeof TRANSLATOR_LANGS | null
>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const { translate } = useTranslator({
sourceLang,
targetLang,
});
const handleSourceLangChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
setSourceLang(event.target.value);
@@ -72,35 +76,18 @@ const DeepLPopup: React.FC<DeepLPopupProps> = ({
setTranslation(null);
try {
const response = await fetch(DEEPL_API_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token ?? ''}`,
},
body: JSON.stringify({
text: [text],
target_lang: targetLang.toUpperCase(),
source_lang: sourceLang === 'AUTO' ? undefined : sourceLang.toUpperCase(),
}),
});
if (!response.ok) {
throw new Error('Failed to fetch translation');
}
const data = await response.json();
const translatedText = data.translations[0]?.text;
const detectedSource = data.translations[0]?.detected_source_language;
const result = await translate([text]);
const translatedText = result[0];
const detectedSource = null;
if (!translatedText) {
throw new Error('No translation found');
}
setTranslation(translatedText);
if (sourceLang === 'AUTO' && detectedSource) {
setDetectedSourceLang(detectedSource);
}
setTranslation(translatedText);
} catch (err) {
console.error(err);
if (!token) {
@@ -122,42 +109,50 @@ const DeepLPopup: React.FC<DeepLPopupProps> = ({
<Popup
trianglePosition={trianglePosition}
width={popupWidth}
height={popupHeight}
minHeight={popupHeight}
maxHeight={720}
position={position}
className='select-text'
className='grid h-full select-text grid-rows-[1fr,auto,1fr] bg-gray-600 text-white'
triangleClassName='text-gray-600'
>
<div className='text-neutral-content relative h-[50%] overflow-y-auto border-b border-neutral-400/75 p-4 font-sans'>
<div className='overflow-y-auto p-4 font-sans'>
<div className='mb-2 flex items-center justify-between'>
<h1 className='text-base font-semibold'>{_('Original Text')}</h1>
<h1 className='text-sm font-normal'>{_('Original Text')}</h1>
<select
value={sourceLang}
onChange={handleSourceLangChange}
className='select text-neutral-content h-8 min-h-8 rounded-md border-none bg-neutral-200/50 text-sm focus:outline-none focus:ring-0'
className='select h-8 min-h-8 rounded-md border-none bg-gray-600 text-sm text-white/75 focus:outline-none focus:ring-0'
>
{Object.entries(LANGUAGES).map(([code, name]) => {
{[
['AUTO', _('Auto Detect')],
...Object.entries(TRANSLATOR_LANGS).sort((a, b) => a[1].localeCompare(b[1])),
].map(([code, name]) => {
return (
<option key={code} value={code}>
{detectedSourceLang && sourceLang === 'AUTO' && code === 'AUTO'
? `${LANGUAGES[detectedSourceLang] || detectedSourceLang} ` + _('(detected)')
? `${TRANSLATOR_LANGS[detectedSourceLang] || detectedSourceLang} ` +
_('(detected)')
: name}
</option>
);
})}
</select>
</div>
<p className='text-base'>{text}</p>
<p className='text-base text-white/90'>{text}</p>
</div>
<div className='text-neutral-content relative h-[50%] overflow-y-auto p-4 font-sans'>
<div className='mx-4 flex-shrink-0 border-t border-gray-500/30'></div>
<div className='overflow-y-auto p-4 font-sans'>
<div className='mb-2 flex items-center justify-between'>
<h2 className='text-base font-semibold'>{_('Translated Text')}</h2>
<h2 className='text-sm font-normal'>{_('Translated Text')}</h2>
<select
value={targetLang}
onChange={handleTargetLangChange}
className='select text-neutral-content h-8 min-h-8 rounded-md border-none bg-neutral-200/50 text-sm focus:outline-none focus:ring-0'
className='select h-8 min-h-8 rounded-md border-none bg-gray-600 text-sm text-white/75 focus:outline-none focus:ring-0'
>
{Object.entries(LANGUAGES)
.filter(([code]) => code !== 'AUTO')
{Object.entries(TRANSLATOR_LANGS)
.sort((a, b) => a[1].localeCompare(b[1]))
.map(([code, name]) => (
<option key={code} value={code}>
{name}
@@ -172,7 +167,9 @@ const DeepLPopup: React.FC<DeepLPopupProps> = ({
<p className='text-base text-red-600'>{error}</p>
) : (
<div>
<p className='text-base'>{translation || 'No translation available.'}</p>
<p className='text-base text-white/90'>
{translation || 'No translation available.'}
</p>
<div className='pt-4 text-sm opacity-60'>Translated by DeepL.</div>
</div>
)}
@@ -16,11 +16,11 @@ const NotebookHeader: React.FC<{
const iconSize14 = useResponsiveSize(14);
return (
<div className='notebook-header relative flex h-11 items-center px-3' dir='ltr'>
<div className='absolute inset-0 flex items-center justify-center space-x-2'>
<div className='absolute inset-0 z-[-1] flex items-center justify-center space-x-2'>
<LuNotebookPen />
<div className='notebook-title hidden text-sm font-medium sm:flex'>{_('Notebook')}</div>
</div>
<div className='z-10 flex items-center gap-x-4'>
<div className='flex w-full items-center gap-x-4'>
<button
onClick={handleTogglePin}
className={clsx(
@@ -36,6 +36,8 @@ const NotebookHeader: React.FC<{
>
<MdArrowBackIosNew />
</button>
</div>
<div className='flex items-center justify-end gap-x-4'>
<button className='btn btn-ghost left-0 h-8 min-h-8 w-8 p-0'>
<FiSearch />
</button>
@@ -42,6 +42,7 @@ const ColorInput: React.FC<ColorInputProps> = ({ label, value, onChange }) => {
<input
type='text'
value={value}
spellCheck={false}
onChange={(e) => onChange(e.target.value)}
className='bg-base-100 text-base-content border-base-200 min-w-4 max-w-36 flex-1 rounded border p-1 font-mono text-sm'
/>
@@ -0,0 +1,140 @@
import React, { useEffect, useState } from 'react';
import { useEnv } from '@/context/EnvContext';
import { useReaderStore } from '@/store/readerStore';
import { useDeviceControlStore } from '@/store/deviceStore';
import { useTranslation } from '@/hooks/useTranslation';
import { getStyles } from '@/utils/style';
import { getMaxInlineSize } from '@/utils/config';
import { saveViewSettings } from '../../utils/viewSettingsHelper';
import NumberInput from './NumberInput';
const ControlPanel: React.FC<{ bookKey: string }> = ({ bookKey }) => {
const _ = useTranslation();
const { envConfig, appService } = useEnv();
const { getView, getViewSettings } = useReaderStore();
const { acquireVolumeKeyInterception, releaseVolumeKeyInterception } = useDeviceControlStore();
const viewSettings = getViewSettings(bookKey)!;
const [isScrolledMode, setScrolledMode] = useState(viewSettings.scrolled!);
const [isContinuousScroll, setIsContinuousScroll] = useState(viewSettings.continuousScroll!);
const [scrollingOverlap, setScrollingOverlap] = useState(viewSettings.scrollingOverlap!);
const [volumeKeysToFlip, setVolumeKeysToFlip] = useState(viewSettings.volumeKeysToFlip!);
const [isDisableClick, setIsDisableClick] = useState(viewSettings.disableClick!);
const [swapClickArea, setSwapClickArea] = useState(viewSettings.swapClickArea!);
useEffect(() => {
if (isScrolledMode === viewSettings.scrolled) return;
saveViewSettings(envConfig, bookKey, 'scrolled', isScrolledMode);
getView(bookKey)?.renderer.setAttribute('flow', isScrolledMode ? 'scrolled' : 'paginated');
getView(bookKey)?.renderer.setAttribute(
'max-inline-size',
`${getMaxInlineSize(viewSettings)}px`,
);
getView(bookKey)?.renderer.setStyles?.(getStyles(viewSettings!));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isScrolledMode]);
useEffect(() => {
saveViewSettings(envConfig, bookKey, 'continuousScroll', isContinuousScroll, false, false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isContinuousScroll]);
useEffect(() => {
if (scrollingOverlap === viewSettings.scrollingOverlap) return;
saveViewSettings(envConfig, bookKey, 'scrollingOverlap', scrollingOverlap, false, false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [scrollingOverlap]);
useEffect(() => {
saveViewSettings(envConfig, bookKey, 'volumeKeysToFlip', volumeKeysToFlip, false, false);
if (appService?.isMobileApp) {
if (volumeKeysToFlip) {
acquireVolumeKeyInterception();
} else {
releaseVolumeKeyInterception();
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [volumeKeysToFlip]);
useEffect(() => {
saveViewSettings(envConfig, bookKey, 'disableClick', isDisableClick, false, false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isDisableClick]);
useEffect(() => {
saveViewSettings(envConfig, bookKey, 'swapClickArea', swapClickArea, false, false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [swapClickArea]);
return (
<div className='my-4 w-full space-y-6'>
<div className='w-full'>
<h2 className='mb-2 font-medium'>{_('Touch')}</h2>
<div className='card border-base-200 bg-base-100 border shadow'>
<div className='divide-base-200 divide-y'>
<div className='config-item'>
<span className=''>{_('Scrolled Mode')}</span>
<input
type='checkbox'
className='toggle'
checked={isScrolledMode}
onChange={() => setScrolledMode(!isScrolledMode)}
/>
</div>
<div className='config-item'>
<span className=''>{_('Continuous Scroll')}</span>
<input
type='checkbox'
className='toggle'
checked={isContinuousScroll}
onChange={() => setIsContinuousScroll(!isContinuousScroll)}
/>
</div>
<NumberInput
label={_('Scrolling Overlap (px)')}
value={scrollingOverlap}
onChange={setScrollingOverlap}
disabled={!viewSettings.scrolled}
min={0}
max={200}
step={10}
/>
{appService?.isMobileApp && (
<div className='config-item'>
<span className=''>{_('Volume Keys for Page Flip')}</span>
<input
type='checkbox'
className='toggle'
checked={volumeKeysToFlip}
onChange={() => setVolumeKeysToFlip(!volumeKeysToFlip)}
/>
</div>
)}
<div className='config-item'>
<span className=''>{_('Clicks for Page Flip')}</span>
<input
type='checkbox'
className='toggle'
checked={!isDisableClick}
onChange={() => setIsDisableClick(!isDisableClick)}
/>
</div>
<div className='config-item'>
<span className=''>{_('Swap Clicks Area')}</span>
<input
type='checkbox'
className='toggle'
checked={swapClickArea}
disabled={isDisableClick}
onChange={() => setSwapClickArea(!swapClickArea)}
/>
</div>
</div>
</div>
</div>
</div>
);
};
export default ControlPanel;
@@ -24,7 +24,7 @@ const DialogMenu: React.FC<DialogMenuProps> = ({ toggleDropdown }) => {
className='dropdown-content dropdown-right no-triangle border-base-200 z-20 mt-1 border shadow-2xl'
>
<button
className='hover:bg-base-200 text-base-content flex w-full items-center justify-between rounded-md p-2'
className='hover:bg-base-200 text-base-content flex w-full items-center justify-between rounded-md p-1'
onClick={handleToggleGlobal}
>
<div className='flex items-center'>
@@ -40,7 +40,6 @@ const LayoutPanel: React.FC<{ bookKey: string }> = ({ bookKey }) => {
const [maxBlockSize, setMaxBlockSize] = useState(viewSettings.maxBlockSize!);
const [writingMode, setWritingMode] = useState(viewSettings.writingMode!);
const [overrideLayout, setOverrideLayout] = useState(viewSettings.overrideLayout!);
const [isScrolledMode, setScrolledMode] = useState(viewSettings.scrolled!);
const [doubleBorder, setDoubleBorder] = useState(viewSettings.doubleBorder!);
const [borderColor, setBorderColor] = useState(viewSettings.borderColor!);
const [showHeader, setShowHeader] = useState(viewSettings.showHeader!);
@@ -167,18 +166,6 @@ const LayoutPanel: React.FC<{ bookKey: string }> = ({ bookKey }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [overrideLayout]);
useEffect(() => {
if (isScrolledMode === viewSettings.scrolled) return;
saveViewSettings(envConfig, bookKey, 'scrolled', isScrolledMode);
getView(bookKey)?.renderer.setAttribute('flow', isScrolledMode ? 'scrolled' : 'paginated');
getView(bookKey)?.renderer.setAttribute(
'max-inline-size',
`${getMaxInlineSize(viewSettings)}px`,
);
getView(bookKey)?.renderer.setStyles?.(getStyles(viewSettings!));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isScrolledMode]);
useEffect(() => {
if (doubleBorder === viewSettings.doubleBorder) return;
if (doubleBorder && viewSettings.vertical) {
@@ -259,18 +246,6 @@ const LayoutPanel: React.FC<{ bookKey: string }> = ({ bookKey }) => {
return (
<div className='my-4 w-full space-y-6'>
<div className='w-full'>
<div className='flex items-center justify-between'>
<h2 className='font-medium'>{_('Scrolled Mode')}</h2>
<input
type='checkbox'
className='toggle'
checked={isScrolledMode}
onChange={() => setScrolledMode(!isScrolledMode)}
/>
</div>
</div>
{mightBeRTLBook && (
<div className='w-full'>
<div className='flex items-center justify-between'>
@@ -360,7 +335,7 @@ const LayoutPanel: React.FC<{ bookKey: string }> = ({ bookKey }) => {
onChange={setParagraphMargin}
min={0}
max={4}
step={0.5}
step={0.2}
/>
<NumberInput
label={_('Line Spacing')}
@@ -7,7 +7,6 @@ import { useEnv } from '@/context/EnvContext';
import { useReaderStore } from '@/store/readerStore';
import { useSettingsStore } from '@/store/settingsStore';
import { useTranslation } from '@/hooks/useTranslation';
import { useDeviceControlStore } from '@/store/deviceStore';
import { getStyles } from '@/utils/style';
import { lockScreenOrientation } from '@/utils/bridge';
import { saveViewSettings } from '../../utils/viewSettingsHelper';
@@ -20,15 +19,10 @@ const MiscPanel: React.FC<{ bookKey: string }> = ({ bookKey }) => {
const _ = useTranslation();
const { envConfig, appService } = useEnv();
const { settings, isFontLayoutSettingsGlobal, setSettings } = useSettingsStore();
const { acquireVolumeKeyInterception, releaseVolumeKeyInterception } = useDeviceControlStore();
const { getView, getViewSettings, setViewSettings } = useReaderStore();
const viewSettings = getViewSettings(bookKey)!;
const [animated, setAnimated] = useState(viewSettings.animated!);
const [isDisableClick, setIsDisableClick] = useState(viewSettings.disableClick!);
const [swapClickArea, setSwapClickArea] = useState(viewSettings.swapClickArea!);
const [volumeKeysToFlip, setVolumeKeysToFlip] = useState(viewSettings.volumeKeysToFlip!);
const [isContinuousScroll, setIsContinuousScroll] = useState(viewSettings.continuousScroll!);
const [draftStylesheet, setDraftStylesheet] = useState(viewSettings.userStylesheet!);
const [draftStylesheetSaved, setDraftStylesheetSaved] = useState(true);
const [screenOrientation, setScreenOrientation] = useState(viewSettings.screenOrientation!);
@@ -137,33 +131,6 @@ const MiscPanel: React.FC<{ bookKey: string }> = ({ bookKey }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [animated]);
useEffect(() => {
saveViewSettings(envConfig, bookKey, 'disableClick', isDisableClick, false, false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isDisableClick]);
useEffect(() => {
saveViewSettings(envConfig, bookKey, 'swapClickArea', swapClickArea, false, false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [swapClickArea]);
useEffect(() => {
saveViewSettings(envConfig, bookKey, 'volumeKeysToFlip', volumeKeysToFlip, false, false);
if (appService?.isMobileApp) {
if (volumeKeysToFlip) {
acquireVolumeKeyInterception();
} else {
releaseVolumeKeyInterception();
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [volumeKeysToFlip]);
useEffect(() => {
saveViewSettings(envConfig, bookKey, 'continuousScroll', isContinuousScroll, false, false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isContinuousScroll]);
useEffect(() => {
saveViewSettings(envConfig, bookKey, 'screenOrientation', screenOrientation, false, false);
if (appService?.isMobileApp) {
@@ -253,53 +220,6 @@ const MiscPanel: React.FC<{ bookKey: string }> = ({ bookKey }) => {
</div>
)}
<div className='w-full'>
<h2 className='mb-2 font-medium'>{_('Behavior')}</h2>
<div className='card border-base-200 bg-base-100 border shadow'>
<div className='divide-base-200 divide-y'>
<div className='config-item'>
<span className=''>{_('Continuous Scroll')}</span>
<input
type='checkbox'
className='toggle'
checked={isContinuousScroll}
onChange={() => setIsContinuousScroll(!isContinuousScroll)}
/>
</div>
{appService?.isMobileApp && (
<div className='config-item'>
<span className=''>{_('Volume Keys for Page Flip')}</span>
<input
type='checkbox'
className='toggle'
checked={volumeKeysToFlip}
onChange={() => setVolumeKeysToFlip(!volumeKeysToFlip)}
/>
</div>
)}
<div className='config-item'>
<span className=''>{_('Clicks for Page Flip')}</span>
<input
type='checkbox'
className='toggle'
checked={!isDisableClick}
onChange={() => setIsDisableClick(!isDisableClick)}
/>
</div>
<div className='config-item'>
<span className=''>{_('Swap Clicks Area')}</span>
<input
type='checkbox'
className='toggle'
checked={swapClickArea}
disabled={isDisableClick}
onChange={() => setSwapClickArea(!swapClickArea)}
/>
</div>
</div>
</div>
</div>
<div className='w-full'>
<h2 className='mb-2 font-medium'>{_('Custom CSS')}</h2>
<div
@@ -1,12 +1,14 @@
import clsx from 'clsx';
import React, { useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { BookConfig } from '@/types/book';
import { useEnv } from '@/context/EnvContext';
import { useSettingsStore } from '@/store/settingsStore';
import { useTranslation } from '@/hooks/useTranslation';
import { RiFontSize } from 'react-icons/ri';
import { RiDashboardLine } from 'react-icons/ri';
import { VscSymbolColor } from 'react-icons/vsc';
import { PiDotsThreeVerticalBold } from 'react-icons/pi';
import { LiaHandPointerSolid } from 'react-icons/lia';
import { IoAccessibilityOutline } from 'react-icons/io5';
import { MdArrowBackIosNew, MdArrowForwardIos } from 'react-icons/md';
import { getDirFromUILanguage } from '@/utils/rtl';
@@ -16,9 +18,10 @@ import ColorPanel from './ColorPanel';
import Dropdown from '@/components/Dropdown';
import Dialog from '@/components/Dialog';
import DialogMenu from './DialogMenu';
import ControlPanel from './ControlPanel';
import MiscPanel from './MiscPanel';
type SettingsPanelType = 'Font' | 'Layout' | 'Color' | 'Misc';
type SettingsPanelType = 'Font' | 'Layout' | 'Color' | 'Control' | 'Misc';
type TabConfig = {
tab: SettingsPanelType;
@@ -28,7 +31,10 @@ type TabConfig = {
const SettingsDialog: React.FC<{ bookKey: string; config: BookConfig }> = ({ bookKey }) => {
const _ = useTranslation();
const { appService } = useEnv();
const [isRtl] = useState(() => getDirFromUILanguage() === 'rtl');
const tabsRef = useRef<HTMLDivElement | null>(null);
const [showTabLabels, setShowTabLabels] = useState(false);
const [activePanel, setActivePanel] = useState<SettingsPanelType>(
(localStorage.getItem('lastConfigPanel') || 'Font') as SettingsPanelType,
);
@@ -50,6 +56,11 @@ const SettingsDialog: React.FC<{ bookKey: string; config: BookConfig }> = ({ boo
icon: VscSymbolColor,
label: _('Color'),
},
{
tab: 'Control',
icon: LiaHandPointerSolid,
label: _('Behavior'),
},
{
tab: 'Misc',
icon: IoAccessibilityOutline,
@@ -66,14 +77,56 @@ const SettingsDialog: React.FC<{ bookKey: string; config: BookConfig }> = ({ boo
setFontLayoutSettingsDialogOpen(false);
};
useEffect(() => {
const container = tabsRef.current;
if (!container) return;
const checkButtonWidths = () => {
const threshold = (container.clientWidth - 64) * 0.25;
const hideLabel = Array.from(container.querySelectorAll('button')).some((button) => {
const labelSpan = button.querySelector('span');
const labelText = labelSpan?.textContent || '';
const clone = button.cloneNode(true) as HTMLButtonElement;
clone.style.position = 'absolute';
clone.style.visibility = 'hidden';
clone.style.width = 'auto';
const cloneSpan = clone.querySelector('span');
if (cloneSpan) {
cloneSpan.classList.remove('hidden');
cloneSpan.textContent = labelText;
}
document.body.appendChild(clone);
const fullWidth = clone.scrollWidth;
document.body.removeChild(clone);
return fullWidth > threshold;
});
setShowTabLabels(!hideLabel);
};
checkButtonWidths();
const resizeObserver = new ResizeObserver(checkButtonWidths);
resizeObserver.observe(container);
const mutationObserver = new MutationObserver(checkButtonWidths);
mutationObserver.observe(container, {
subtree: true,
characterData: true,
});
return () => {
resizeObserver.disconnect();
mutationObserver.disconnect();
};
}, []);
return (
<>
<Dialog
isOpen={true}
onClose={handleClose}
className='modal-open'
boxClassName='sm:min-w-[520px]'
snapHeight={window.innerWidth < 640 ? 0.7 : undefined}
boxClassName={clsx('sm:min-w-[520px]', appService?.isMobile && 'sm:max-w-[90%] sm:w-3/4')}
snapHeight={appService?.isMobile ? 0.7 : undefined}
header={
<div className='flex w-full items-center justify-between'>
<button
@@ -85,32 +138,41 @@ const SettingsDialog: React.FC<{ bookKey: string; config: BookConfig }> = ({ boo
>
{isRtl ? <MdArrowForwardIos /> : <MdArrowBackIosNew />}
</button>
<div className='dialog-tabs flex h-10 max-w-[100%] flex-grow items-center gap-2 pl-4'>
<div
ref={tabsRef}
className={clsx(
'dialog-tabs flex h-10 w-full items-center',
showTabLabels ? 'gap-4 sm:gap-2' : 'gap-4',
)}
>
{tabConfig.map(({ tab, icon: Icon, label }) => (
<button
key={tab}
data-tab={tab}
className={clsx(
'btn btn-ghost text-base-content btn-sm',
'btn btn-ghost text-base-content btn-sm px-1',
activePanel === tab ? 'btn-active' : '',
)}
onClick={() => handleSetActivePanel(tab)}
>
<Icon className='mr-0' />
{window.innerWidth >= 500 ? label : ''}
<span className={clsx('label', !showTabLabels && 'hidden')}>{label}</span>
</button>
))}
</div>
<div className='flex h-full items-center justify-end gap-x-2'>
<Dropdown
className='dropdown-bottom dropdown-end'
buttonClassName='btn btn-ghost h-8 min-h-8 w-8 p-0'
buttonClassName='btn btn-ghost h-8 min-h-8 w-8 p-0 flex items-center justify-center'
toggleButton={<PiDotsThreeVerticalBold />}
>
<DialogMenu />
</Dropdown>
<button
onClick={handleClose}
className={'bg-base-300/65 btn btn-ghost btn-circle hidden h-6 min-h-6 w-6 sm:flex'}
className={
'bg-base-300/65 btn btn-ghost btn-circle hidden h-6 min-h-6 w-6 p-0 sm:flex'
}
>
<svg
xmlns='http://www.w3.org/2000/svg'
@@ -131,6 +193,7 @@ const SettingsDialog: React.FC<{ bookKey: string; config: BookConfig }> = ({ boo
{activePanel === 'Font' && <FontPanel bookKey={bookKey} />}
{activePanel === 'Layout' && <LayoutPanel bookKey={bookKey} />}
{activePanel === 'Color' && <ColorPanel bookKey={bookKey} />}
{activePanel === 'Control' && <ControlPanel bookKey={bookKey} />}
{activePanel === 'Misc' && <MiscPanel bookKey={bookKey} />}
</Dialog>
</>
@@ -59,14 +59,15 @@ const ThemeEditor: React.FC<ThemeEditorProps> = ({ customTheme, onSave, onDelete
{_(
"All the world's a stage,\nAnd all the men and women merely players;\nThey have their exits and their entrances,\nAnd one man in his time plays many parts,\nHis acts being seven ages.\n\n— William Shakespeare",
)}
<p
{'\n\n'}
<span
className='mt-4 cursor-pointer italic'
style={{
color: primaryColor,
}}
>
{_("(from 'As You Like It', Act II)")}
</p>
</span>
</p>
</div>
</div>
@@ -123,7 +123,7 @@ const TOCView: React.FC<{
toc: TOCItem[];
}> = ({ bookKey, toc }) => {
const { getProgress } = useReaderStore();
const { sideBarBookKey } = useSidebarStore();
const { sideBarBookKey, isSideBarVisible } = useSidebarStore();
const progress = getProgress(bookKey);
const [expandedItems, setExpandedItems] = useState<string[]>([]);
@@ -146,9 +146,6 @@ const TOCView: React.FC<{
}
(currentItem as HTMLElement).setAttribute('aria-current', 'page');
}
if (currentHref) {
expandParents(toc, currentHref);
}
};
useEffect(() => {
@@ -165,13 +162,19 @@ const TOCView: React.FC<{
}
return () => observer.disconnect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [viewRef]);
}, [viewRef.current]);
useEffect(() => {
if (!progress || eventDispatcher.dispatchSync('tts-is-speaking')) return;
if (sideBarBookKey !== bookKey) return;
if (!isSideBarVisible) return;
const { sectionHref: currentHref } = progress;
if (currentHref) {
expandParents(toc, currentHref);
}
scrollToProgress(progress);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [toc, progress, sideBarBookKey]);
}, [toc, progress, sideBarBookKey, isSideBarVisible]);
return (
<div className='rounded pt-2'>
@@ -38,6 +38,7 @@ const TTSControl = () => {
const [timeoutTimestamp, setTimeoutTimestamp] = useState(0);
const [timeoutFunc, setTimeoutFunc] = useState<ReturnType<typeof setTimeout> | null>(null);
const viewSettings = getViewSettings(bookKey);
const popupPadding = useResponsiveSize(POPUP_PADDING);
const maxWidth = window.innerWidth - 2 * popupPadding;
const popupWidth = Math.min(maxWidth, useResponsiveSize(POPUP_WIDTH));
@@ -286,16 +287,18 @@ const TTSControl = () => {
const updatePanelPosition = () => {
if (iconRef.current) {
const rect = iconRef.current.getBoundingClientRect();
const windowRect = document.documentElement.getBoundingClientRect();
const parentRect =
iconRef.current.parentElement?.getBoundingClientRect() ||
document.documentElement.getBoundingClientRect();
const trianglePos = {
dir: 'up',
point: { x: rect.left + rect.width / 2, y: rect.top - 12 },
point: { x: rect.left + rect.width / 2 - parentRect.left, y: rect.top - 12 },
} as Position;
const popupPos = getPopupPosition(
trianglePos,
windowRect,
parentRect,
popupWidth,
popupHeight,
popupPadding,
@@ -315,8 +318,23 @@ const TTSControl = () => {
setShowPanel(false);
};
useEffect(() => {
if (!iconRef.current || !showPanel) return;
const parentElement = iconRef.current.parentElement;
if (!parentElement) return;
const resizeObserver = new ResizeObserver(() => {
updatePanelPosition();
});
resizeObserver.observe(parentElement);
return () => {
resizeObserver.disconnect();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showPanel]);
return (
<div>
<>
{showPanel && (
<div
className='fixed inset-0'
@@ -328,7 +346,8 @@ const TTSControl = () => {
<div
ref={iconRef}
className={clsx(
'fixed right-6 h-12 w-12',
'absolute h-12 w-12',
viewSettings?.rtl ? 'left-6' : 'right-6',
appService?.hasSafeAreaInset
? 'bottom-[calc(env(safe-area-inset-bottom)+70px)]'
: 'bottom-[70px] sm:bottom-14',
@@ -343,7 +362,7 @@ const TTSControl = () => {
height={popupHeight}
position={panelPosition}
trianglePosition={trianglePosition}
className='bg-base-200 absolute flex shadow-lg'
className='bg-base-200 flex shadow-lg'
>
<TTSPanel
bookKey={bookKey}
@@ -362,7 +381,7 @@ const TTSControl = () => {
/>
</Popup>
)}
</div>
</>
);
};
@@ -9,6 +9,7 @@ import { getStyles } from '@/utils/style';
import { tauriHandleToggleFullScreen, tauriQuitApp } from '@/utils/window';
import { eventDispatcher } from '@/utils/event';
import { MAX_ZOOM_LEVEL, MIN_ZOOM_LEVEL, ZOOM_STEP } from '@/services/constants';
import { viewPagination } from './usePagination';
interface UseBookShortcutsProps {
sideBarBookKey: string | null;
@@ -41,11 +42,13 @@ const useBookShortcuts = ({ sideBarBookKey, bookKeys }: UseBookShortcutsProps) =
};
const goLeft = () => {
getView(sideBarBookKey)?.goLeft();
const viewSettings = getViewSettings(sideBarBookKey ?? '');
viewPagination(getView(sideBarBookKey), viewSettings, 'left');
};
const goRight = () => {
getView(sideBarBookKey)?.goRight();
const viewSettings = getViewSettings(sideBarBookKey ?? '');
viewPagination(getView(sideBarBookKey), viewSettings, 'right');
};
const goPrev = () => {
@@ -12,13 +12,20 @@ export const useMouseEvent = (
const throttledScroll = throttle(handleContinuousScroll, 500, {
emitLast: false,
});
const throttledFlip = throttle(handlePageFlip, 1000, {
emitLast: false,
});
const handleMouseEvent = (msg: MessageEvent | React.MouseEvent<HTMLDivElement, MouseEvent>) => {
if (msg instanceof MessageEvent) {
if (msg.data && msg.data.bookKey === bookKey) {
if (msg.data.type === 'iframe-wheel') {
throttledScroll('mouse', -msg.data.deltaY, 0);
}
handlePageFlip(msg);
if (msg.data.type === 'iframe-wheel') {
throttledFlip(msg);
} else {
handlePageFlip(msg);
}
}
} else if (msg.type === 'wheel') {
const event = msg as React.WheelEvent<HTMLDivElement>;
@@ -1,6 +1,7 @@
import { useEffect } from 'react';
import { useEnv } from '@/context/EnvContext';
import { FoliateView } from '@/types/view';
import { ViewSettings } from '@/types/book';
import { useReaderStore } from '@/store/readerStore';
import { useDeviceControlStore } from '@/store/deviceStore';
import { eventDispatcher } from '@/utils/event';
@@ -9,6 +10,28 @@ import { tauriGetWindowLogicalPosition } from '@/utils/window';
export type ScrollSource = 'touch' | 'mouse';
export const viewPagination = (
view: FoliateView | null,
viewSettings: ViewSettings | null | undefined,
side: 'left' | 'right',
) => {
if (!view || !viewSettings) return;
const renderer = view.renderer;
if (renderer.scrolled) {
if (view.book.dir === 'rtl') {
side = side === 'left' ? 'right' : 'left';
}
const { size } = renderer;
const showHeader = viewSettings.showHeader && viewSettings.showBarsOnScroll;
const showFooter = viewSettings.showFooter && viewSettings.showBarsOnScroll;
const scrollingOverlap = viewSettings.scrollingOverlap;
const distance = size - scrollingOverlap - (showHeader ? 44 : 0) - (showFooter ? 44 : 0);
return side === 'left' ? view.prev(distance) : view.next(distance);
} else {
return side === 'left' ? view.goLeft() : view.goRight();
}
};
export const usePagination = (
bookKey: string,
viewRef: React.MutableRefObject<FoliateView | null>,
@@ -64,15 +87,15 @@ export const usePagination = (
}
if (!viewSettings.disableClick! && screenX >= viewCenterX) {
if (viewSettings.swapClickArea) {
viewRef.current?.goLeft();
viewPagination(viewRef.current, viewSettings, 'left');
} else {
viewRef.current?.goRight();
viewPagination(viewRef.current, viewSettings, 'right');
}
} else if (!viewSettings.disableClick! && screenX < viewCenterX) {
if (viewSettings.swapClickArea) {
viewRef.current?.goRight();
viewPagination(viewRef.current, viewSettings, 'right');
} else {
viewRef.current?.goLeft();
viewPagination(viewRef.current, viewSettings, 'left');
}
}
}
@@ -100,9 +123,9 @@ export const usePagination = (
if (viewSettings?.volumeKeysToFlip) {
setHoveredBookKey('');
if (keyName === 'VolumeUp') {
viewRef.current?.goLeft();
viewPagination(viewRef.current, viewSettings, 'left');
} else if (keyName === 'VolumeDown') {
viewRef.current?.goRight();
viewPagination(viewRef.current, viewSettings, 'right');
}
}
} else {
@@ -111,10 +134,11 @@ export const usePagination = (
const width = window.innerWidth;
const leftThreshold = width * 0.5;
const rightThreshold = width * 0.5;
const viewSettings = getViewSettings(bookKey);
if (clientX < leftThreshold) {
viewRef.current?.goLeft();
viewPagination(viewRef.current, viewSettings, 'left');
} else if (clientX > rightThreshold) {
viewRef.current?.goRight();
viewPagination(viewRef.current, viewSettings, 'right');
}
}
}
@@ -0,0 +1,166 @@
import { useEffect, useRef } from 'react';
import { useReaderStore } from '@/store/readerStore';
import { useBookDataStore } from '@/store/bookDataStore';
import { getOSPlatform } from '@/utils/misc';
import { eventDispatcher } from '@/utils/event';
import { getTextFromRange, TextSelection } from '@/utils/sel';
import { transformContent } from '@/services/transformService';
export const useTextSelector = (
bookKey: string,
setSelection: React.Dispatch<React.SetStateAction<TextSelection | null>>,
handleDismissPopup: () => void,
) => {
const { getBookData } = useBookDataStore();
const { getView, getViewSettings } = useReaderStore();
const view = getView(bookKey);
const viewSettings = getViewSettings(bookKey)!;
const bookData = getBookData(bookKey)!;
const primaryLang = bookData.book?.primaryLanguage || 'en';
const osPlatform = getOSPlatform();
const isPopuped = useRef(false);
const isUpToPopup = useRef(false);
const isTextSelected = useRef(false);
const selectionPosition = useRef<number | null>(null);
const isValidSelection = (sel: Selection) => {
return sel && sel.toString().trim().length > 0 && sel.rangeCount > 0;
};
const transformCtx = {
bookKey,
viewSettings: getViewSettings(bookKey)!,
content: '',
transformers: ['punctuation'],
reversePunctuationTransform: true,
};
const getAnnotationText = async (range: Range) => {
transformCtx['content'] = getTextFromRange(range, primaryLang.startsWith('ja') ? ['rt'] : []);
return await transformContent(transformCtx);
};
const makeSelection = async (sel: Selection, index: number, rebuildRange = false) => {
isTextSelected.current = true;
const range = sel.getRangeAt(0);
if (rebuildRange) {
sel.removeAllRanges();
sel.addRange(range);
}
setSelection({ key: bookKey, text: await getAnnotationText(range), range, index });
};
// FIXME: extremely hacky way to dismiss system selection tools on iOS
const makeSelectionOnIOS = async (sel: Selection, index: number) => {
isTextSelected.current = true;
const range = sel.getRangeAt(0);
setTimeout(() => {
sel.removeAllRanges();
setTimeout(async () => {
if (!isTextSelected.current) return;
sel.addRange(range);
setSelection({ key: bookKey, text: await getAnnotationText(range), range, index });
}, 40);
}, 0);
};
const handleSelectionchange = (doc: Document, index: number) => {
// Available on iOS, Android and Desktop, fired when the selection is changed
// Ideally the popup only shows when the selection is done,
const sel = doc.getSelection() as Selection;
if (osPlatform === 'ios') return;
if (!isValidSelection(sel)) {
if (!isUpToPopup.current) {
handleDismissPopup();
isTextSelected.current = false;
}
if (isPopuped.current) {
isUpToPopup.current = false;
}
return;
}
// On Android no proper events are fired to notify selection done,
// we make the popup show when the selection is changed
if (osPlatform === 'android') {
makeSelection(sel, index, false);
}
isUpToPopup.current = true;
};
const handlePointerup = (doc: Document, index: number) => {
// Available on iOS and Desktop, fired at touchend or mouseup
// Note that on Android, pointerup event is fired after an additional touch event
const sel = doc.getSelection() as Selection;
if (isValidSelection(sel)) {
if (osPlatform === 'ios') {
makeSelectionOnIOS(sel, index);
} else {
makeSelection(sel, index, true);
}
}
};
const handleScroll = () => {
// Prevent the container from scrolling when text is selected in paginated mode
// This is a workaround for the issue #873
// TODO: support text selection across pages
if (!viewSettings?.scrolled && view?.renderer?.containerPosition && selectionPosition.current) {
view.renderer.containerPosition = selectionPosition.current;
}
};
const handleShowPopup = (showPopup: boolean) => {
setTimeout(
() => {
if (showPopup && !isPopuped.current) {
isUpToPopup.current = false;
}
isPopuped.current = showPopup;
},
['android', 'ios'].includes(osPlatform) ? 0 : 500,
);
};
const handleUpToPopup = () => {
isUpToPopup.current = true;
};
useEffect(() => {
if (isTextSelected.current && !selectionPosition.current) {
selectionPosition.current = view?.renderer?.start || null;
} else if (!isTextSelected.current) {
selectionPosition.current = null;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isTextSelected.current]);
useEffect(() => {
const handleSingleClick = (): boolean => {
if (isUpToPopup.current) {
isUpToPopup.current = false;
return true;
}
if (isTextSelected.current) {
handleDismissPopup();
isTextSelected.current = false;
view?.deselect();
return true;
}
if (isPopuped.current) {
handleDismissPopup();
return true;
}
return false;
};
eventDispatcher.onSync('iframe-single-click', handleSingleClick);
return () => {
eventDispatcher.offSync('iframe-single-click', handleSingleClick);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return {
handleScroll,
handlePointerup,
handleSelectionchange,
handleShowPopup,
handleUpToPopup,
};
};
+1
View File
@@ -8,6 +8,7 @@ import { useSettingsStore } from '@/store/settingsStore';
import { checkForAppUpdates } from '@/helpers/updater';
import Reader from './components/Reader';
// This is only used for the Tauri app in the app router
export default function Page() {
const _ = useTranslation();
const { appService } = useEnv();
@@ -122,11 +122,15 @@ export const handleClick = (bookKey: string, event: MouseEvent) => {
if (['sup', 'a', 'audio', 'video'].includes(element.tagName.toLowerCase())) {
return;
}
if (element.classList.contains('js_readerFooterNote')) {
if (
element.classList.contains('js_readerFooterNote') ||
element.classList.contains('zhangyue-footnote')
) {
eventDispatcher.dispatch('footnote-popup', {
bookKey,
element,
footnote: element.getAttribute('data-wr-footernote') || '',
footnote:
element.getAttribute('data-wr-footernote') || element.getAttribute('zy-footnote') || '',
});
return;
}
+34 -15
View File
@@ -18,10 +18,12 @@ export const setAboutDialogVisible = (visible: boolean) => {
}
};
type UpdateStatus = 'checking' | 'updating' | 'updated' | 'error';
export const AboutWindow = () => {
const _ = useTranslation();
const { appService } = useEnv();
const [isUpdated, setIsUpdated] = useState(false);
const [updateStatus, setUpdateStatus] = useState<UpdateStatus | null>(null);
const [browserInfo, setBrowserInfo] = useState('');
const [isOpen, setIsOpen] = useState(false);
@@ -46,46 +48,63 @@ export const AboutWindow = () => {
}, []);
const handleCheckUpdate = async () => {
const update = await checkForAppUpdates(_, false);
if (update) {
setIsOpen(false);
} else {
setIsUpdated(true);
setUpdateStatus('checking');
try {
const update = await checkForAppUpdates(_, false);
if (update) {
setIsOpen(false);
} else {
setUpdateStatus('updated');
}
} catch (error) {
console.info('Error checking for updates:', error);
setUpdateStatus('error');
}
};
const handleClose = () => {
setIsOpen(false);
setUpdateStatus(null);
};
return (
<Dialog
id='about_window'
isOpen={isOpen}
title={_('About Readest')}
onClose={() => setIsOpen(false)}
onClose={handleClose}
boxClassName='sm:!w-96 sm:h-auto'
>
<div className='about-content flex h-full flex-col items-center justify-center'>
<div className='flex flex-col items-center px-8'>
<div className='mb-3'>
<Image src='/icon.png' alt='App Logo' className='h-24 w-24' width={64} height={64} />
<div className='flex flex-col items-center gap-2 px-8'>
<div className='mb-2 mt-8'>
<Image src='/icon.png' alt='App Logo' className='h-20 w-20' width={64} height={64} />
</div>
<div className='flex select-text flex-col items-center'>
<h2 className='text-2xl font-bold'>Readest</h2>
<h2 className='mb-2 text-2xl font-bold'>Readest</h2>
<p className='text-neutral-content text-center text-sm'>
{_('Version {{version}}', { version: packageJson.version })} {`(${browserInfo})`}
</p>
</div>
<div className='h-5'>
{appService?.hasUpdater && !isUpdated && (
<span className='badge badge-primary mt-2 cursor-pointer' onClick={handleCheckUpdate}>
{appService?.hasUpdater && !updateStatus && (
<span className='badge badge-primary cursor-pointer p-1' onClick={handleCheckUpdate}>
{_('Check Update')}
</span>
)}
{isUpdated && (
{updateStatus === 'updated' && (
<p className='text-neutral-content mt-2 text-xs'>{_('Already the latest version')}</p>
)}
{updateStatus === 'checking' && (
<p className='text-neutral-content mt-2 text-xs'>{_('Checking for updates...')}</p>
)}
{updateStatus === 'error' && (
<p className='text-error mt-2 text-xs'>{_('Error checking for updates')}</p>
)}
</div>
</div>
<div className='divider py-12 sm:py-2'></div>
<div className='divider py-16 sm:py-2'></div>
<div className='flex flex-col items-center px-4 text-center' dir='ltr'>
<p className='text-neutral-content text-sm'>
@@ -10,6 +10,7 @@ import { useTranslation } from '@/hooks/useTranslation';
import {
formatAuthors,
formatDate,
formatFileSize,
formatLanguage,
formatPublisher,
formatSubject,
@@ -41,6 +42,7 @@ const BookDetailModal = ({
const [loading, setLoading] = useState(false);
const [showDeleteAlert, setShowDeleteAlert] = useState(false);
const [bookMeta, setBookMeta] = useState<BookDoc['metadata'] | null>(null);
const [fileSize, setFileSize] = useState<number | null>(null);
const { envConfig } = useEnv();
const { settings } = useSettingsStore();
@@ -50,7 +52,9 @@ const BookDetailModal = ({
const appService = await envConfig.getAppService();
try {
const details = await appService.fetchBookDetails(book, settings);
const size = await appService.getBookFileSize(book);
setBookMeta(details);
setFileSize(size);
} finally {
if (loadingTimeout) clearTimeout(loadingTimeout);
setLoading(false);
@@ -173,12 +177,6 @@ const BookDetailModal = ({
{formatLanguage(bookMeta.language) || _('Unknown')}
</p>
</div>
<div className='overflow-hidden'>
<span className='font-bold'>{_('Identifier:')}</span>
<p className='text-neutral-content line-clamp-1 text-sm'>
{bookMeta.identifier || 'N/A'}
</p>
</div>
<div className='overflow-hidden'>
<span className='font-bold'>{_('Subjects:')}</span>
<p className='text-neutral-content line-clamp-1 text-sm'>
@@ -191,6 +189,12 @@ const BookDetailModal = ({
{book.format || _('Unknown')}
</p>
</div>
<div className='overflow-hidden'>
<span className='font-bold'>{_('File Size:')}</span>
<p className='text-neutral-content line-clamp-1 text-sm'>
{formatFileSize(fileSize) || _('Unknown')}
</p>
</div>
</div>
<div>
<span className='font-bold'>{_('Description:')}</span>
+4 -1
View File
@@ -1,5 +1,6 @@
import React from 'react';
import clsx from 'clsx';
import React from 'react';
import { useEnv } from '@/context/EnvContext';
interface ButtonProps {
icon: React.ReactNode;
@@ -18,6 +19,7 @@ const Button: React.FC<ButtonProps> = ({
tooltipDirection = 'top',
className,
}) => {
const { appService } = useEnv();
return (
<div
className={clsx(
@@ -32,6 +34,7 @@ const Button: React.FC<ButtonProps> = ({
<button
className={clsx(
'btn btn-ghost h-8 min-h-8 w-8 p-0',
appService?.isMobileApp && 'hover:bg-transparent',
disabled && 'btn-disabled !bg-transparent',
className,
)}
+21 -30
View File
@@ -43,7 +43,7 @@ const Dialog: React.FC<DialogProps> = ({
const { appService } = useEnv();
const { systemUIVisible, statusBarHeight } = useThemeStore();
const { acquireBackKeyInterception, releaseBackKeyInterception } = useDeviceControlStore();
const [isFullHeightInMobile, setIsFullHeightInMobile] = React.useState(!snapHeight);
const [isFullHeightInMobile, setIsFullHeightInMobile] = useState(!snapHeight);
const [isRtl] = useState(() => getDirFromUILanguage() === 'rtl');
const iconSize22 = useResponsiveSize(22);
const isMobile = window.innerWidth < 640;
@@ -62,6 +62,7 @@ const Dialog: React.FC<DialogProps> = ({
useEffect(() => {
if (!isOpen) return;
setIsFullHeightInMobile(!snapHeight);
window.addEventListener('keydown', handleKeyDown);
if (appService?.isAndroidApp) {
acquireBackKeyInterception();
@@ -166,38 +167,28 @@ const Dialog: React.FC<DialogProps> = ({
window.innerWidth < window.innerHeight
? 'sm:h-[50%] sm:w-3/4'
: 'sm:h-[65%] sm:w-1/2 sm:max-w-[600px]',
appService?.hasSafeAreaInset &&
isFullHeightInMobile &&
'pt-[env(safe-area-inset-top)] sm:pt-0',
boxClassName,
)}
style={
snapHeight
? {
height: `${snapHeight * 100}%`,
bottom: 0,
}
: {}
}
style={{
paddingTop:
appService?.hasSafeAreaInset && isFullHeightInMobile
? `max(env(safe-area-inset-top), ${systemUIVisible ? statusBarHeight : 0}px)`
: '0px',
...(appService?.isMobile
? { height: snapHeight ? `${snapHeight * 100}%` : '100%', bottom: 0 }
: {}),
}}
>
{window.innerWidth < 640 && (
<div
className={clsx(
'drag-handle flex h-10 max-h-10 min-h-10 w-full cursor-row-resize items-center justify-center',
'transition-padding-top duration-300 ease-out',
)}
style={{
paddingTop:
appService?.isAndroidApp && systemUIVisible && isFullHeightInMobile
? statusBarHeight
: 0,
}}
onMouseDown={handleDragStart}
onTouchStart={handleDragStart}
>
<div className='bg-base-content/50 h-1 w-10 rounded-full'></div>
</div>
)}
<div
className={clsx(
'drag-handle h-10 max-h-10 min-h-10 w-full cursor-row-resize items-center justify-center',
'transition-padding-top flex duration-300 ease-out sm:hidden',
)}
onMouseDown={handleDragStart}
onTouchStart={handleDragStart}
>
<div className='bg-base-content/50 h-1 w-10 rounded-full'></div>
</div>
<div className='dialog-header bg-base-100 sticky top-1 z-10 flex items-center justify-between px-4'>
{header ? (
header
+125 -61
View File
@@ -1,8 +1,13 @@
import clsx from 'clsx';
import { Position } from '@/utils/sel';
import { useEffect, useRef, useState } from 'react';
import { useResponsiveSize } from '@/hooks/useResponsiveSize';
const Popup = ({
width,
height,
minHeight,
maxHeight,
position,
trianglePosition,
children,
@@ -11,74 +16,133 @@ const Popup = ({
additionalStyle = {},
}: {
width: number;
height: number;
height?: number;
minHeight?: number;
maxHeight?: number;
position?: Position;
trianglePosition?: Position;
children: React.ReactNode;
className?: string;
triangleClassName?: string;
additionalStyle?: React.CSSProperties;
}) => (
<div>
<div
id='popup-container'
className={`bg-base-300 absolute rounded-lg font-sans shadow-xl ${className}`}
style={{
width: `${width}px`,
height: `${height}px`,
left: `${position ? position.point.x : -999}px`,
top: `${position ? position.point.y : -999}px`,
...additionalStyle,
}}
>
{children}
</div>
<div
className={`triangle text-base-300 absolute ${triangleClassName}`}
style={{
left:
trianglePosition?.dir === 'left'
? `${trianglePosition.point.x}px`
: trianglePosition?.dir === 'right'
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const [adjustedPosition, setAdjustedPosition] = useState(position);
const [childrenHeight, setChildrenHeight] = useState(height || minHeight || 0);
const popupPadding = useResponsiveSize(10);
let availableHeight = window.innerHeight - 2 * popupPadding;
if (trianglePosition?.dir === 'up') {
availableHeight = trianglePosition.point.y - popupPadding;
} else if (trianglePosition?.dir === 'down') {
availableHeight = window.innerHeight - trianglePosition.point.y - popupPadding;
}
maxHeight = Math.min(maxHeight || availableHeight, availableHeight);
if (minHeight) {
minHeight = Math.min(minHeight, availableHeight);
}
useEffect(() => {
if (!containerRef.current) return;
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const newHeight = entry.contentRect.height;
if (newHeight !== childrenHeight) {
setChildrenHeight(newHeight);
return;
}
}
});
resizeObserver.observe(containerRef.current);
return () => {
resizeObserver.disconnect();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!containerRef.current) return;
if (!position || !trianglePosition || position.dir !== 'up') {
setAdjustedPosition(position);
return;
}
const containerHeight = childrenHeight || containerRef.current.offsetHeight;
const newPosition = {
...position,
point: {
...position.point,
y: trianglePosition.point.y - containerHeight,
},
};
setAdjustedPosition(newPosition);
}, [position, trianglePosition, childrenHeight]);
return (
<div>
<div
id='popup-container'
ref={containerRef}
className={clsx('bg-base-300 absolute rounded-lg font-sans shadow-xl', className)}
style={{
width: `${width}px`,
height: height ? `${height}px` : 'auto',
minHeight: minHeight ? `${minHeight}px` : 'none',
maxHeight: maxHeight ? `${maxHeight}px` : 'none',
left: `${adjustedPosition ? adjustedPosition.point.x : -999}px`,
top: `${adjustedPosition ? adjustedPosition.point.y : -999}px`,
...additionalStyle,
}}
>
{children}
</div>
<div
className={`triangle text-base-300 absolute ${triangleClassName}`}
style={{
left:
trianglePosition?.dir === 'left'
? `${trianglePosition.point.x}px`
: `${trianglePosition ? trianglePosition.point.x : -999}px`,
top:
trianglePosition?.dir === 'up'
? `${trianglePosition.point.y}px`
: trianglePosition?.dir === 'down'
: trianglePosition?.dir === 'right'
? `${trianglePosition.point.x}px`
: `${trianglePosition ? trianglePosition.point.x : -999}px`,
top:
trianglePosition?.dir === 'up'
? `${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>
);
: 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>
);
};
export default Popup;
+6 -3
View File
@@ -65,7 +65,7 @@ const Slider: React.FC<SliderProps> = ({
return (
<div
ref={sliderRef}
className={`slider bg-base-200 mx-auto w-full max-w-md rounded-xl ${className}`}
className={`slider bg-base-200 mx-auto w-full rounded-xl ${className}`}
dir={isRtl ? 'rtl' : undefined}
>
<div className='relative' style={{ height: `${heightPx}px` }}>
@@ -75,7 +75,10 @@ const Slider: React.FC<SliderProps> = ({
<div
className='bg-base-300 absolute h-full rounded-full'
style={{
width: percentage > 0 ? `calc(${percentage}% + ${heightPx / 2}px)` : '0px',
width:
percentage > 0
? `max(calc(${percentage}% + ${heightPx / 2}px), ${heightPx}px)`
: '0px',
[isRtl ? 'right' : 'left']: 0,
}}
></div>
@@ -94,7 +97,7 @@ const Slider: React.FC<SliderProps> = ({
}}
>
<div
className={`bg-base-200 flex h-full items-center justify-center rounded-full text-sm shadow-md ${bubbleClassName}`}
className={`bg-base-200 flex h-full items-center justify-center rounded-full text-xs shadow-md ${bubbleClassName}`}
style={{ width: `${heightPx}px` }}
>
{bubbleElement || bubbleLabel}
@@ -7,10 +7,12 @@ import { type as osType, arch as osArch } from '@tauri-apps/plugin-os';
import { check, Update } from '@tauri-apps/plugin-updater';
import { relaunch } from '@tauri-apps/plugin-process';
import { fetch } from '@tauri-apps/plugin-http';
import { useTranslator } from '@/hooks/useTranslator';
import { useTranslation } from '@/hooks/useTranslation';
import { useSearchParams } from 'next/navigation';
import { tauriDownload } from '@/utils/transfer';
import { installPackage } from '@/utils/bridge';
import { getLocale } from '@/utils/misc';
import { READEST_UPDATER_FILE, READEST_CHANGELOG_FILE } from '@/services/constants';
import packageJson from '../../package.json';
import Dialog from '@/components/Dialog';
@@ -58,6 +60,11 @@ interface GenericUpdate {
export const UpdaterContent = ({ version }: { version?: string }) => {
const _ = useTranslation();
const [targetLang, setTargetLang] = useState('EN');
const { translate } = useTranslator({
sourceLang: 'AUTO',
targetLang,
});
const { appService } = useEnv();
const searchParams = useSearchParams();
const currentVersion = packageJson.version;
@@ -71,6 +78,17 @@ export const UpdaterContent = ({ version }: { version?: string }) => {
const [isDownloading, setIsDownloading] = useState(false);
const [downloaded, setDownloaded] = useState<number | null>(null);
useEffect(() => {
const locale = getLocale();
let userLang = locale.split('-')[0] || 'en';
if (locale === 'zh-CN') {
userLang = 'zh-Hans';
} else if (locale.startsWith('zh')) {
userLang = 'zh-Hant';
}
setTargetLang(userLang.toUpperCase());
}, []);
useEffect(() => {
const checkDesktopUpdate = async () => {
const update = await check();
@@ -181,18 +199,25 @@ export const UpdaterContent = ({ version }: { version?: string }) => {
};
const updateChangelogs = async (update: GenericUpdate) => {
setNewVersion(update.version);
const changelogs = await fetchChangelogs(currentVersion, update.version);
if (changelogs.length > 0) {
setChangelogs(changelogs);
} else {
setChangelogs([
let changelogs = await fetchChangelogs(currentVersion, update.version);
if (changelogs.length === 0) {
changelogs = [
{
version: update.version,
date: new Date(update.date!).toDateString(),
notes: parseNumberedList(update.body ?? ''),
},
]);
];
}
for (const entry of changelogs) {
try {
entry.notes = await translate(entry.notes, { useCache: true });
} catch (error) {
console.log('Failed to translate changelog:', error);
}
}
setChangelogs(changelogs);
};
if (update) {
updateChangelogs(update);
+37 -1
View File
@@ -1,5 +1,6 @@
import clsx from 'clsx';
import Image from 'next/image';
import { useEffect, useState } from 'react';
import { IconType } from 'react-icons';
interface UserAvatarProps {
@@ -17,6 +18,41 @@ const UserAvatar: React.FC<UserAvatarProps> = ({
borderClassName,
DefaultIcon,
}) => {
const [cachedImageUrl, setCachedImageUrl] = useState<string | null>(null);
useEffect(() => {
if (!url) return;
const storageKey = `avatar_${btoa(url).replace(/[^a-zA-Z0-9]/g, '')}`;
const cached = localStorage.getItem(storageKey);
if (cached) {
setCachedImageUrl(cached);
return;
}
const cacheImage = async () => {
try {
const response = await fetch(url, { referrerPolicy: 'no-referrer' });
const blob = await response.blob();
const reader = new FileReader();
reader.onloadend = () => {
const base64data = reader.result as string;
try {
localStorage.setItem(storageKey, base64data);
setCachedImageUrl(base64data);
} catch (e) {
console.warn('Failed to cache avatar in localStorage:', e);
}
};
reader.readAsDataURL(blob);
} catch (error) {
console.error('Failed to cache avatar:', error);
}
};
cacheImage();
}, [url]);
return (
<div
className='relative flex h-full w-full items-center justify-center rounded-full'
@@ -25,7 +61,7 @@ const UserAvatar: React.FC<UserAvatarProps> = ({
{url ? (
<div>
<Image
src={url}
src={cachedImageUrl || url}
alt='User Avatar'
className={clsx('rounded-full', className, borderClassName)}
referrerPolicy='no-referrer'
+2 -2
View File
@@ -47,7 +47,7 @@ export const checkForAppUpdates = async (
return !!update;
} else if (OS_TYPE === 'android') {
try {
const response = await fetch(READEST_UPDATER_FILE);
const response = await fetch(READEST_UPDATER_FILE, { connectTimeout: 5000 });
const data = await response.json();
const isNewer = semver.gt(data.version, packageJson.version);
if (isNewer && ('android-arm64' in data.platforms || 'android-universal' in data.platforms)) {
@@ -56,7 +56,7 @@ export const checkForAppUpdates = async (
return isNewer;
} catch (err) {
console.warn('Failed to fetch Android update info', err);
return false;
throw new Error('Failed to fetch Android update info');
}
}
@@ -1,11 +1,17 @@
import { getOSPlatform } from '@/utils/misc';
import { useMediaQuery } from 'react-responsive';
// use desktop size as base size
export const useResponsiveSize = (baseSize: number) => {
const isPhone = useMediaQuery({ maxWidth: 480 });
const isTablet = useMediaQuery({ minWidth: 481, maxWidth: 1024 });
if (isPhone) return baseSize * 1.25;
if (isTablet) return baseSize * 1.15;
if (typeof window === 'undefined') {
return baseSize;
}
const pixelRatio = window.devicePixelRatio || 2.4;
const isMobile = ['android', 'ios'].includes(getOSPlatform());
if (isPhone && isMobile) return baseSize * (pixelRatio / 3) * 1.25;
if (isTablet && isMobile) return baseSize * (pixelRatio / 3) * 1.25;
return baseSize;
};
+1 -1
View File
@@ -27,7 +27,7 @@ export const useTheme = ({
useEffect(() => {
updateAppTheme(appThemeColor);
if (appService?.isMobile) {
if (appService?.isMobileApp) {
if (systemUIVisible) {
showSystemUI();
} else {
+131
View File
@@ -0,0 +1,131 @@
import { useState, useCallback, useEffect } from 'react';
import { useAuth } from '@/context/AuthContext';
import {
deeplProvider,
getFromCache,
storeInCache,
UseTranslatorOptions,
} from '@/services/translators';
export function useTranslator({
provider = deeplProvider,
sourceLang = 'AUTO',
targetLang = 'EN',
}: UseTranslatorOptions = {}) {
const { token } = useAuth();
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(false);
}, [provider.name, sourceLang, targetLang]);
const translate = useCallback(
async (
input: string[],
options?: { source?: string; target?: string; useCache?: boolean },
): Promise<string[]> => {
const sourceLanguage = options?.source || sourceLang;
const targetLanguage = options?.target || targetLang;
const useCache = options?.useCache ?? false;
const textsToTranslate = input;
if (textsToTranslate.length === 0 || textsToTranslate.every((t) => !t?.trim())) {
return textsToTranslate;
}
const textsNeedingTranslation: string[] = [];
const indicesNeedingTranslation: number[] = [];
await Promise.all(
textsToTranslate.map(async (text, index) => {
if (!text?.trim()) return;
const cachedTranslation = await getFromCache(
text,
sourceLanguage,
targetLanguage,
provider.name,
);
if (cachedTranslation) return;
textsNeedingTranslation.push(text);
indicesNeedingTranslation.push(index);
}),
);
if (textsNeedingTranslation.length === 0) {
const results = await Promise.all(
textsToTranslate.map((text) =>
getFromCache(text, sourceLanguage, targetLanguage, provider.name).then(
(cached) => cached || text,
),
),
);
return results;
}
setLoading(true);
try {
const translatedTexts = await provider.translate(
textsNeedingTranslation,
sourceLanguage,
targetLanguage,
token,
useCache,
);
await Promise.all(
textsNeedingTranslation.map(async (text, index) => {
return storeInCache(
text,
translatedTexts[index] || '',
sourceLanguage,
targetLanguage,
provider.name,
);
}),
);
const results = [...textsToTranslate];
indicesNeedingTranslation.forEach((originalIndex, translationIndex) => {
results[originalIndex] = translatedTexts[translationIndex] || '';
});
await Promise.all(
results.map(async (_, index) => {
if (!indicesNeedingTranslation.includes(index)) {
const originalText = textsToTranslate[index];
if (!originalText?.trim()) return;
const cachedTranslation = await getFromCache(
originalText,
sourceLanguage,
targetLanguage,
provider.name,
);
if (cachedTranslation) {
results[index] = cachedTranslation;
}
}
}),
);
setLoading(false);
return results;
} catch (err) {
console.error('Translation error:', err);
setLoading(false);
throw err instanceof Error ? err : new Error(String(err));
}
},
[provider, sourceLang, targetLang, token],
);
return {
translate,
loading,
};
}
+4 -2
View File
@@ -1,9 +1,11 @@
import { ViewSettings } from '@/types/book';
import { useEffect, useState } from 'react';
import { useReaderStore } from '@/store/readerStore';
// This hook allows you to inject custom CSS into the reader UI.
// Note that the book content is rendered in an iframe, so UI CSS won't affect book rendering.
export const useUICSS = (bookKey: string, viewSettings: ViewSettings) => {
export const useUICSS = (bookKey: string) => {
const { getViewSettings } = useReaderStore();
const viewSettings = getViewSettings(bookKey);
const [styleElement, setStyleElement] = useState<HTMLStyleElement | null>(null);
useEffect(() => {
-1
View File
@@ -3,7 +3,6 @@ import Head from 'next/head';
import Providers from '@/components/Providers';
import '../styles/globals.css';
import '../styles/fonts.css';
function MyApp({ Component, pageProps }: AppProps) {
return (
+117 -40
View File
@@ -1,12 +1,22 @@
import crypto from 'crypto';
import { NextApiRequest, NextApiResponse } from 'next';
import { corsAllMethods, runMiddleware } from '@/utils/cors';
import { supabase } from '@/utils/supabase';
import { getUserPlan } from '@/utils/access';
import { query as deeplQuery } from '@/utils/deepl';
const DEFAULT_DEEPL_FREE_API = 'https://api-free.deepl.com/v2/translate';
const DEFAULT_DEEPL_PRO_API = 'https://api.deepl.com/v2/translate';
interface KVNamespace {
get(key: string): Promise<string | null>;
put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;
delete(key: string): Promise<void>;
}
interface CloudflareEnv {
TRANSLATIONS_KV?: KVNamespace;
}
const getUserAndToken = async (authHeader: string | undefined) => {
if (!authHeader) return {};
@@ -27,7 +37,13 @@ const LANG_V2_V1_MAP: Record<string, string> = {
const getDeepLAPIKey = (keys: string | undefined) => {
const keyArray = keys?.split(',') ?? [];
return keyArray.length ? keyArray[Math.floor(Math.random() * keyArray.length)] : '';
return keyArray.length ? keyArray[Math.floor(Math.random() * keyArray.length)]! : '';
};
const generateCacheKey = (text: string, sourceLang: string, targetLang: string): string => {
const inputString = `${sourceLang}:${targetLang}:${text}`;
const hash = crypto.createHash('sha1').update(inputString).digest('hex');
return `tr:${hash}`;
};
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
@@ -37,6 +53,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.status(405).json({ error: 'Method not allowed' });
}
const env = (req.env || {}) as CloudflareEnv;
const hasKVCache = !!env['TRANSLATIONS_KV'];
const { user, token } = await getUserAndToken(req.headers['authorization']);
const { DEEPL_PRO_API, DEEPL_FREE_API } = process.env;
const deepFreeApiUrl = DEEPL_FREE_API || DEFAULT_DEEPL_FREE_API;
@@ -47,8 +66,6 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (user && token) {
userPlan = getUserPlan(token);
if (userPlan === 'pro') deeplApiUrl = deeplProApiUrl;
} else {
res.status(403).json({ error: 'Not authenticated' });
}
const deeplAuthKey =
deeplApiUrl === deeplProApiUrl
@@ -59,46 +76,106 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
text,
source_lang: sourceLang = 'AUTO',
target_lang: targetLang = 'EN',
}: { text: string[]; source_lang: string; target_lang: string } = req.body;
use_cache: useCache = false,
}: { text: string[]; source_lang: string; target_lang: string; use_cache: boolean } = req.body;
try {
if (user && token) {
const isV2Api = deeplApiUrl.endsWith('/v2/translate');
const requestBody = {
text: isV2Api ? text : (text[0] ?? ''),
source_lang: isV2Api ? sourceLang : (LANG_V2_V1_MAP[sourceLang] ?? sourceLang),
target_lang: isV2Api ? targetLang : (LANG_V2_V1_MAP[targetLang] ?? targetLang),
};
const response = await fetch(deeplApiUrl, {
method: 'POST',
headers: {
Authorization: `DeepL-Auth-Key ${deeplAuthKey}`,
'x-fingerprint': process.env['DEEPL_X_FINGERPRINT'] || '',
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
const data = await response.json();
const result = {
...data,
translations: data.translations || [
{
text: data.data,
},
],
};
res.status(response.status).json(result);
} else {
const result = await deeplQuery({
text: text[0] ?? '',
sourceLang,
targetLang,
});
res.status(200).json(result);
}
const translations = await Promise.all(
text.map(async (singleText) => {
if (!singleText?.trim()) {
return { text: '' };
}
if (useCache && hasKVCache) {
try {
const cacheKey = generateCacheKey(singleText, sourceLang, targetLang);
const cachedTranslation = await env['TRANSLATIONS_KV']!.get(cacheKey);
if (cachedTranslation) {
return {
text: cachedTranslation,
detected_source_language: sourceLang,
};
}
} catch (cacheError) {
console.error('Cache retrieval error:', cacheError);
}
}
return await callDeepLAPI(
singleText,
sourceLang,
targetLang,
deeplApiUrl,
deeplAuthKey,
env['TRANSLATIONS_KV'],
useCache,
);
}),
);
return res.status(200).json({ translations });
} catch (error) {
console.error('Error proxying DeepL request:', error);
res.status(500).json({ error: 'Internal Server Error' });
return res.status(500).json({ error: 'Internal Server Error' });
}
};
async function callDeepLAPI(
text: string,
sourceLang: string,
targetLang: string,
apiUrl: string,
authKey: string,
translationsKV: KVNamespace | undefined,
useCache: boolean,
) {
const isV2Api = apiUrl.endsWith('/v2/translate');
const requestBody = {
text: isV2Api ? [text] : text,
source_lang: isV2Api ? sourceLang : (LANG_V2_V1_MAP[sourceLang] ?? sourceLang),
target_lang: isV2Api ? targetLang : (LANG_V2_V1_MAP[targetLang] ?? targetLang),
};
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
Authorization: `DeepL-Auth-Key ${authKey}`,
'x-fingerprint': process.env['DEEPL_X_FINGERPRINT'] || '',
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`DeepL API error (${response.status}): ${errorText}`);
}
const data = await response.json();
let translatedText = '';
let detectedSourceLanguage = '';
if (data.translations && data.translations.length > 0) {
translatedText = data.translations[0].text;
detectedSourceLanguage = data.translations[0].detected_source_language || '';
} else if (data.data) {
translatedText = data.data;
}
if (useCache && translationsKV && translatedText) {
try {
const cacheKey = generateCacheKey(text, sourceLang, targetLang);
await translationsKV.put(cacheKey, translatedText, { expirationTtl: 86400 * 90 });
} catch (cacheError) {
console.error('Cache storage error:', cacheError);
}
}
return {
text: translatedText,
detected_source_language: detectedSourceLanguage,
};
}
export default handler;
@@ -428,6 +428,20 @@ export abstract class BaseAppService implements AppService {
return false;
}
async getBookFileSize(book: Book): Promise<number | null> {
const fp = getLocalBookFilename(book);
if (await this.fs.exists(fp, 'Books')) {
const file = await this.fs.openFile(fp, 'Books');
const size = file.size;
const f = file as ClosableFile;
if (f && f.close) {
await f.close();
}
return size;
}
return null;
}
async loadBookContent(book: Book, settings: SystemSettings): Promise<BookContent> {
let file: File;
const fp = getLocalBookFilename(book);
+5 -3
View File
@@ -37,7 +37,7 @@ export const DEFAULT_SYSTEM_SETTINGS: Partial<SystemSettings> = {
autoUpload: true,
alwaysOnTop: false,
autoCheckUpdates: true,
screenWakeLock: true,
screenWakeLock: false,
openLastBooks: false,
lastOpenBooks: [],
autoImportBooksOnOpen: false,
@@ -87,7 +87,7 @@ export const DEFAULT_BOOK_LAYOUT: BookLayout = {
marginPx: 44,
gapPercent: 5,
compactMarginPx: 0,
compactGapPercent: 0,
compactGapPercent: 5,
scrolled: false,
disableClick: false,
swapClickArea: false,
@@ -105,6 +105,7 @@ export const DEFAULT_BOOK_LAYOUT: BookLayout = {
showHeader: true,
showFooter: true,
showBarsOnScroll: false,
scrollingOverlap: 0,
};
export const DEFAULT_BOOK_STYLE: BookStyle = {
@@ -119,7 +120,7 @@ export const DEFAULT_BOOK_STYLE: BookStyle = {
invert: false,
theme: 'light',
overrideFont: false,
overrideLayout: true,
overrideLayout: false,
userStylesheet: '',
};
@@ -587,6 +588,7 @@ export const TRANSLATED_LANGS = {
en: 'English',
fr: 'Français',
de: 'Deutsch',
nl: 'Nederlands',
it: 'Italiano',
ja: '日本語',
ko: '한국어',
@@ -30,6 +30,7 @@ import { LOCAL_BOOKS_SUBDIR } from './constants';
declare global {
interface Window {
IS_ROUNDED?: boolean;
__READEST_UPDATER_DISABLED?: boolean;
}
}
@@ -222,7 +223,10 @@ export class NativeAppService extends BaseAppService {
override hasRoundedWindow = !(OS_TYPE === 'ios' || OS_TYPE === 'android') && !!window.IS_ROUNDED;
override hasSafeAreaInset = OS_TYPE === 'ios' || OS_TYPE === 'android';
override hasHaptics = OS_TYPE === 'ios' || OS_TYPE === 'android';
override hasUpdater = OS_TYPE !== 'ios' && !process.env['NEXT_PUBLIC_DISABLE_UPDATER'];
override hasUpdater =
OS_TYPE !== 'ios' &&
!process.env['NEXT_PUBLIC_DISABLE_UPDATER'] &&
!window.__READEST_UPDATER_DISABLED;
override resolvePath(fp: string, base: BaseDir): { baseDir: number; base: BaseDir; fp: string } {
return resolvePath(fp, base);
@@ -0,0 +1,14 @@
import type { Transformer } from './types';
export const footnoteTransformer: Transformer = {
name: 'footnote',
transform: async (ctx) => {
let result = ctx.content;
result = result.replace(
/<aside\s+epub:type\s*=\s*["'](footnote|endnote|note|rearnote)["']([^>]*)>/gi,
'<aside class="epubtype-footnote" epub:type="$1"$2>',
);
return result;
},
};
@@ -1,9 +1,9 @@
import type { Transformer } from './types';
import { translateTransformer } from './translate';
import { footnoteTransformer } from './footnote';
import { punctuationTransformer } from './punctuation';
export const availableTransformers: Transformer[] = [
punctuationTransformer,
translateTransformer,
footnoteTransformer,
// Add more transformers here
];
@@ -1,9 +0,0 @@
import type { Transformer } from './types';
export const translateTransformer: Transformer = {
name: 'translate',
transform: async (ctx) => {
return ctx.content;
},
};
@@ -0,0 +1,593 @@
import { TranslationCache } from './types';
const DB_NAME = 'TranslationCache';
const DB_VERSION = 1;
const STORE_NAME = 'translations';
interface CacheEntry {
key: string;
translation: string;
timestamp: number;
provider: string;
sourceLang: string;
targetLang: string;
originalText: string;
}
const memoryCache: TranslationCache = {};
const memoryTimestamps: Record<string, number> = {};
const openDatabase = (): Promise<IDBDatabase> => {
return new Promise((resolve, reject) => {
if (!window.indexedDB) {
console.warn('IndexedDB not supported. Using in-memory cache only.');
reject(new Error('IndexedDB not supported'));
return;
}
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = (event) => {
console.error('IndexedDB error:', event);
reject(new Error('Could not open IndexedDB'));
};
request.onsuccess = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
resolve(db);
};
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
const store = db.createObjectStore(STORE_NAME, { keyPath: 'key' });
store.createIndex('provider', 'provider', { unique: false });
store.createIndex('timestamp', 'timestamp', { unique: false });
}
};
});
};
export const loadCacheFromDB = async (
options: {
maxAge?: number;
maxEntries?: number;
onlyLoadProviders?: string[];
onlyLoadLanguages?: { source?: string[]; target?: string[] };
} = {},
): Promise<void> => {
try {
const db = await openDatabase();
const transaction = db.transaction(STORE_NAME, 'readonly');
const store = transaction.objectStore(STORE_NAME);
let request: IDBRequest;
if (options.onlyLoadProviders && options.onlyLoadProviders.length > 0) {
const providerPromises = options.onlyLoadProviders.map((provider) => {
return new Promise<CacheEntry[]>((resolve) => {
const providerIndex = store.index('provider');
const request = providerIndex.getAll(provider);
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
resolve([]);
};
});
});
const allEntries = (await Promise.all(providerPromises)).flat();
processLoadedEntries(allEntries, options);
} else {
request = store.getAll();
request.onsuccess = () => {
const entries = request.result as CacheEntry[];
processLoadedEntries(entries, options);
};
request.onerror = (event) => {
console.error('Error loading cache from IndexedDB:', event);
};
}
transaction.oncomplete = () => {
db.close();
};
} catch (error) {
console.error('Failed to load cache from IndexedDB:', error);
}
};
const processLoadedEntries = (
entries: CacheEntry[],
options: {
maxAge?: number;
maxEntries?: number;
onlyLoadLanguages?: { source?: string[]; target?: string[] };
},
): void => {
let filteredEntries = entries;
if (options.maxAge) {
const cutoff = Date.now() - options.maxAge;
filteredEntries = filteredEntries.filter((entry) => entry.timestamp >= cutoff);
}
if (options.onlyLoadLanguages) {
if (options.onlyLoadLanguages.source && options.onlyLoadLanguages.source.length > 0) {
filteredEntries = filteredEntries.filter((entry) =>
options.onlyLoadLanguages!.source!.includes(entry.sourceLang),
);
}
if (options.onlyLoadLanguages.target && options.onlyLoadLanguages.target.length > 0) {
filteredEntries = filteredEntries.filter((entry) =>
options.onlyLoadLanguages!.target!.includes(entry.targetLang),
);
}
}
if (options.maxEntries && filteredEntries.length > options.maxEntries) {
filteredEntries.sort((a, b) => b.timestamp - a.timestamp);
filteredEntries = filteredEntries.slice(0, options.maxEntries);
}
filteredEntries.forEach((entry) => {
memoryCache[entry.key] = entry.translation;
memoryTimestamps[entry.key] = entry.timestamp;
});
// console.log(`Loaded ${filteredEntries.length} translations into memory cache`);
};
export const getCacheKey = (
text: string,
sourceLang: string,
targetLang: string,
provider: string,
): string => {
return `${provider}:${sourceLang}:${targetLang}:${text}`;
};
export const getFromCache = async (
text: string,
sourceLang: string,
targetLang: string,
provider: string,
): Promise<string | null> => {
if (!text?.trim()) return null;
const key = getCacheKey(text, sourceLang, targetLang, provider);
if (memoryCache[key]) {
return memoryCache[key];
}
try {
const db = await openDatabase();
const transaction = db.transaction(STORE_NAME, 'readonly');
const store = transaction.objectStore(STORE_NAME);
const request = store.get(key);
return new Promise((resolve) => {
request.onsuccess = () => {
const entry = request.result as CacheEntry;
if (entry) {
memoryCache[key] = entry.translation;
memoryTimestamps[key] = entry.timestamp;
resolve(entry.translation);
} else {
resolve(null);
}
};
request.onerror = () => {
resolve(null);
};
transaction.oncomplete = () => {
db.close();
};
});
} catch (error) {
console.error('Error accessing IndexedDB:', error);
return null;
}
};
export const storeInCache = async (
text: string,
translation: string,
sourceLang: string,
targetLang: string,
provider: string,
): Promise<void> => {
if (!text?.trim() || !translation) return;
const key = getCacheKey(text, sourceLang, targetLang, provider);
const timestamp = Date.now();
memoryCache[key] = translation;
memoryTimestamps[key] = timestamp;
try {
const db = await openDatabase();
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const entry: CacheEntry = {
key,
translation,
timestamp,
provider,
sourceLang,
targetLang,
originalText: text,
};
store.put(entry);
return new Promise((resolve, reject) => {
transaction.oncomplete = () => {
db.close();
resolve();
};
transaction.onerror = (event) => {
console.error('Error storing in IndexedDB:', event);
reject(new Error('Failed to store in IndexedDB'));
};
});
} catch (error) {
console.error('Error accessing IndexedDB:', error);
}
};
export interface CacheFilterOptions {
provider?: string;
maxAge?: number;
}
export const clearCache = async (filter?: CacheFilterOptions): Promise<number> => {
let deletedCount = 0;
if (!filter) {
const count = Object.keys(memoryCache).length;
Object.keys(memoryCache).forEach((key) => {
delete memoryCache[key];
delete memoryTimestamps[key];
});
deletedCount = count;
} else {
const keysToDelete: string[] = [];
Object.keys(memoryCache).forEach((key) => {
let shouldDelete = true;
if (filter.provider) {
const parts = key.split(':');
const provider = parts[0];
if (filter.provider && provider !== filter.provider) {
shouldDelete = false;
}
}
if (shouldDelete && filter.maxAge && memoryTimestamps[key]) {
const timestamp = memoryTimestamps[key];
if (Date.now() - timestamp < filter.maxAge) {
shouldDelete = false;
}
}
if (shouldDelete) {
keysToDelete.push(key);
}
});
keysToDelete.forEach((key) => {
delete memoryCache[key];
delete memoryTimestamps[key];
});
deletedCount = keysToDelete.length;
}
try {
const db = await openDatabase();
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
if (!filter) {
store.clear();
} else {
const request = store.getAll();
request.onsuccess = () => {
const entries = request.result as CacheEntry[];
const filteredEntries = entries.filter((entry) => {
if (filter.provider && entry.provider !== filter.provider) {
return false;
}
if (filter.maxAge && Date.now() - entry.timestamp >= filter.maxAge) {
return true;
}
return true;
});
filteredEntries.forEach((entry) => {
store.delete(entry.key);
});
};
}
return new Promise((resolve) => {
transaction.oncomplete = () => {
db.close();
resolve(deletedCount);
};
transaction.onerror = () => {
db.close();
resolve(deletedCount);
};
});
} catch (error) {
console.error('Error clearing IndexedDB cache:', error);
return deletedCount;
}
};
export const getCacheStats = async (
includeDB: boolean = false,
): Promise<{
memoryCacheEntries: number;
memoryCacheSizeInBytes: number;
dbCacheEntries?: number;
dbCacheSizeInBytes?: number;
totalEntries?: number;
totalSizeInBytes?: number;
}> => {
const memoryCacheEntries = Object.keys(memoryCache).length;
let memoryCacheSizeInBytes = 0;
for (const key in memoryCache) {
memoryCacheSizeInBytes += key.length;
const value = memoryCache[key] || '';
memoryCacheSizeInBytes += value.length;
}
if (!includeDB) {
return { memoryCacheEntries, memoryCacheSizeInBytes };
}
try {
const db = await openDatabase();
const transaction = db.transaction(STORE_NAME, 'readonly');
const store = transaction.objectStore(STORE_NAME);
const countRequest = store.count();
return new Promise((resolve) => {
countRequest.onsuccess = () => {
const dbCacheEntries = countRequest.result;
const getAllRequest = store.getAll();
getAllRequest.onsuccess = () => {
const entries = getAllRequest.result as CacheEntry[];
let dbCacheSizeInBytes = 0;
entries.forEach((entry) => {
const entryString = JSON.stringify(entry);
dbCacheSizeInBytes += entryString.length;
});
const totalEntries =
memoryCacheEntries + dbCacheEntries - Math.min(memoryCacheEntries, dbCacheEntries);
const totalSizeInBytes = memoryCacheSizeInBytes + dbCacheSizeInBytes;
resolve({
memoryCacheEntries,
memoryCacheSizeInBytes,
dbCacheEntries,
dbCacheSizeInBytes,
totalEntries,
totalSizeInBytes,
});
};
};
transaction.oncomplete = () => {
db.close();
};
transaction.onerror = () => {
db.close();
resolve({
memoryCacheEntries,
memoryCacheSizeInBytes,
});
};
});
} catch (error) {
console.error('Error getting IndexedDB stats:', error);
return { memoryCacheEntries, memoryCacheSizeInBytes };
}
};
export const pruneCache = async (
options: {
maxAge?: number;
maxEntries?: number;
maxSizeInBytes?: number;
dryRun?: boolean;
} = {},
): Promise<number> => {
const { maxAge, maxEntries, maxSizeInBytes, dryRun = false } = options;
if (!maxAge && !maxEntries && !maxSizeInBytes) {
return 0;
}
try {
const db = await openDatabase();
const transaction = db.transaction(STORE_NAME, dryRun ? 'readonly' : 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const getAllRequest = store.getAll();
return new Promise((resolve) => {
getAllRequest.onsuccess = () => {
const entries = getAllRequest.result as CacheEntry[];
const entriesToPrune: CacheEntry[] = [];
if (maxAge) {
const cutoffTime = Date.now() - maxAge;
const agedEntries = entries.filter((entry) => entry.timestamp < cutoffTime);
entriesToPrune.push(...agedEntries);
}
if (maxEntries && entries.length > maxEntries) {
const sortedEntries = [...entries].sort((a, b) => a.timestamp - b.timestamp);
const excessEntries = sortedEntries.slice(0, entries.length - maxEntries);
const prunedKeys = new Set(entriesToPrune.map((e) => e.key));
excessEntries.forEach((entry) => {
if (!prunedKeys.has(entry.key)) {
entriesToPrune.push(entry);
}
});
}
if (maxSizeInBytes) {
let currentSize = 0;
entries.forEach((entry) => {
const entryString = JSON.stringify(entry);
currentSize += entryString.length;
});
if (currentSize > maxSizeInBytes) {
const remainingEntries = entries
.filter((entry) => !entriesToPrune.some((e) => e.key === entry.key))
.sort((a, b) => a.timestamp - b.timestamp);
let sizeToRemove = currentSize - maxSizeInBytes;
const prunedKeys = new Set(entriesToPrune.map((e) => e.key));
for (const entry of remainingEntries) {
if (sizeToRemove <= 0) break;
if (!prunedKeys.has(entry.key)) {
const entryString = JSON.stringify(entry);
const entrySize = entryString.length * 2;
entriesToPrune.push(entry);
prunedKeys.add(entry.key);
sizeToRemove -= entrySize;
}
}
}
}
const pruneCount = entriesToPrune.length;
if (!dryRun && pruneCount > 0) {
entriesToPrune.forEach((entry) => {
store.delete(entry.key);
delete memoryCache[entry.key];
delete memoryTimestamps[entry.key];
});
}
resolve(pruneCount);
};
getAllRequest.onerror = () => {
resolve(0);
};
transaction.oncomplete = () => {
db.close();
};
});
} catch (error) {
console.error('Error pruning cache:', error);
return 0;
}
};
export const initCache = async (
options: {
preload?: boolean;
preloadOptions?: {
maxAge?: number;
maxEntries?: number;
onlyLoadProviders?: string[];
onlyLoadLanguages?: { source?: string[]; target?: string[] };
};
autoPrune?: boolean;
pruneInterval?: number;
pruneOptions?: {
maxAge?: number;
maxEntries?: number;
maxSizeInBytes?: number;
};
} = {},
): Promise<() => void> => {
const {
preload = true,
preloadOptions = {
maxAge: 7 * 24 * 60 * 60 * 1000,
maxEntries: 1000,
},
autoPrune = true,
pruneInterval = 60 * 60 * 1000,
pruneOptions = {
maxAge: 30 * 24 * 60 * 60 * 1000,
maxEntries: 10000,
maxSizeInBytes: 10 * 1024 * 1024,
},
} = options;
if (preload) {
await loadCacheFromDB(preloadOptions);
}
let intervalId: number | null = null;
if (autoPrune) {
await pruneCache(pruneOptions);
intervalId = window.setInterval(async () => {
await pruneCache(pruneOptions);
}, pruneInterval);
}
return () => {
if (intervalId !== null) {
clearInterval(intervalId);
}
};
};
let cleanupFunction: (() => void) | null = null;
if (typeof window !== 'undefined') {
initCache().then((cleanup) => {
cleanupFunction = cleanup;
});
window.addEventListener('beforeunload', () => {
if (cleanupFunction) {
cleanupFunction();
}
});
}
@@ -0,0 +1,3 @@
export * from './types';
export * from './cache';
export * from './providers';
@@ -0,0 +1,57 @@
import { getAPIBaseUrl } from '@/services/environment';
import { TranslationProvider } from '../types';
const DEEPL_API_ENDPOINT = getAPIBaseUrl() + '/deepl/translate';
export const deeplProvider: TranslationProvider = {
name: 'deepl',
translate: async (
text: string[],
sourceLang: string,
targetLang: string,
token?: string | null,
useCache: boolean = false,
): Promise<string[]> => {
try {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const response = await fetch(DEEPL_API_ENDPOINT, {
method: 'POST',
headers,
body: JSON.stringify({
text: text,
source_lang: sourceLang,
target_lang: targetLang,
use_cache: useCache,
}),
});
if (!response.ok) {
throw new Error(`Translation failed with status ${response.status}`);
}
const data = await response.json();
const result = [...text];
let translationIndex = 0;
for (let i = 0; i < text.length; i++) {
if (text[i]!.trim().length > 0) {
result[i] = data.translations?.[translationIndex]?.text || text[i];
translationIndex++;
}
}
return result;
} catch (error) {
console.error('Translation error:', error);
return text;
}
},
};
@@ -0,0 +1 @@
export * from './deepl';
@@ -0,0 +1,20 @@
export interface TranslationProvider {
name: string;
translate: (
texts: string[],
sourceLang: string,
targetLang: string,
token?: string | null,
useCache?: boolean,
) => Promise<string[]>;
}
export interface TranslationCache {
[key: string]: string;
}
export interface UseTranslatorOptions {
provider?: TranslationProvider;
sourceLang?: string;
targetLang?: string;
}
+1 -1
View File
@@ -28,7 +28,7 @@ export const useLibraryStore = create<LibraryState>((set, get) => ({
if (bookIndex !== -1) {
library[bookIndex] = book;
}
set({ library });
set({ library: [...library] });
appService.saveLibraryBooks(library);
},
}));
-538
View File
@@ -1,538 +0,0 @@
/* cyrillic-ext */
@font-face {
font-family: 'Bitter';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxjHiqOu8IVPmn7epZnDMyKBvHf5D6c4Pz-UnByn-ChBltdqi4.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Bitter';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxjHiqOu8IVPmn7epZnDMyKBvHf5D6c4Pz-W3Byn-ChBltdqi4.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* vietnamese */
@font-face {
font-family: 'Bitter';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxjHiqOu8IVPmn7epZnDMyKBvHf5D6c4Pz-UHByn-ChBltdqi4.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Bitter';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxjHiqOu8IVPmn7epZnDMyKBvHf5D6c4Pz-UXByn-ChBltdqi4.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Bitter';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxjHiqOu8IVPmn7epZnDMyKBvHf5D6c4Pz-X3Byn-ChBltd.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Bitter';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxhHiqOu8IVPmnRc6SY1KXhnF_Y8fbfOLXOXXpzveS5B3Nd.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Bitter';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxhHiqOu8IVPmnRc6SY1KXhnF_Y8fbfOLzOXXpzveS5B3Nd.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* vietnamese */
@font-face {
font-family: 'Bitter';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxhHiqOu8IVPmnRc6SY1KXhnF_Y8fbfOLfOXXpzveS5B3Nd.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Bitter';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxhHiqOu8IVPmnRc6SY1KXhnF_Y8fbfOLbOXXpzveS5B3Nd.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Bitter';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/bitter/v36/raxhHiqOu8IVPmnRc6SY1KXhnF_Y8fbfOLjOXXpzveS5Bw.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Fira Code';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/firacode/v22/uU9eCBsR6Z2vfE9aq3bL0fxyUs4tcw4W_D1sJV37NuzlojwUKaJO.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Fira Code';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/firacode/v22/uU9eCBsR6Z2vfE9aq3bL0fxyUs4tcw4W_D1sJVT7NuzlojwUKaJO.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Fira Code';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/firacode/v22/uU9eCBsR6Z2vfE9aq3bL0fxyUs4tcw4W_D1sJVz7NuzlojwUKaJO.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Fira Code';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/firacode/v22/uU9eCBsR6Z2vfE9aq3bL0fxyUs4tcw4W_D1sJVP7NuzlojwUKaJO.woff2) format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
/* latin-ext */
@font-face {
font-family: 'Fira Code';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/firacode/v22/uU9eCBsR6Z2vfE9aq3bL0fxyUs4tcw4W_D1sJV77NuzlojwUKaJO.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Fira Code';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/firacode/v22/uU9eCBsR6Z2vfE9aq3bL0fxyUs4tcw4W_D1sJVD7NuzlojwUKQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Literata';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or3yQ6P12-iJxAIgLYT1PLs1a-t7PU0AbeE9KK5Z5Cl4OOCTVNg.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Literata';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or3yQ6P12-iJxAIgLYT1PLs1a-t7PU0AbeE9KK5Q5Cl4OOCTVNg.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Literata';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or3yQ6P12-iJxAIgLYT1PLs1a-t7PU0AbeE9KK5Y5Cl4OOCTVNg.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Literata';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or3yQ6P12-iJxAIgLYT1PLs1a-t7PU0AbeE9KK5X5Cl4OOCTVNg.woff2) format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Literata';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or3yQ6P12-iJxAIgLYT1PLs1a-t7PU0AbeE9KK5b5Cl4OOCTVNg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Literata';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or3yQ6P12-iJxAIgLYT1PLs1a-t7PU0AbeE9KK5a5Cl4OOCTVNg.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Literata';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or3yQ6P12-iJxAIgLYT1PLs1a-t7PU0AbeE9KK5U5Cl4OOCT.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Literata';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or38Q6P12-iJxAIgLa78DkTtAoDhk0oVpaLlYZ5W7i5aOtCS.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Literata';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or38Q6P12-iJxAIgLa78DkTtAoDhk0oVpaLlaJ5W7i5aOtCS.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Literata';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or38Q6P12-iJxAIgLa78DkTtAoDhk0oVpaLlYJ5W7i5aOtCS.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Literata';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or38Q6P12-iJxAIgLa78DkTtAoDhk0oVpaLlb55W7i5aOtCS.woff2) format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Literata';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or38Q6P12-iJxAIgLa78DkTtAoDhk0oVpaLlY55W7i5aOtCS.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Literata';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or38Q6P12-iJxAIgLa78DkTtAoDhk0oVpaLlYp5W7i5aOtCS.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Literata';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/literata/v35/or38Q6P12-iJxAIgLa78DkTtAoDhk0oVpaLlbJ5W7i5aOg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Merriweather';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/merriweather/v30/u-440qyriQwlOrhSvowK_l5-cSZMdeX3rsHo.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Merriweather';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/merriweather/v30/u-440qyriQwlOrhSvowK_l5-eCZMdeX3rsHo.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* vietnamese */
@font-face {
font-family: 'Merriweather';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/merriweather/v30/u-440qyriQwlOrhSvowK_l5-cyZMdeX3rsHo.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Merriweather';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/merriweather/v30/u-440qyriQwlOrhSvowK_l5-ciZMdeX3rsHo.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Merriweather';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/merriweather/v30/u-440qyriQwlOrhSvowK_l5-fCZMdeX3rg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Noto Sans';
font-style: italic;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0kIpQlx3QUlC5A4PNr4C5OaxRsfNNlKbCePevHtVtX57DGjDU1QDce2V3SyEldxrO-96OU.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Noto Sans';
font-style: italic;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0kIpQlx3QUlC5A4PNr4C5OaxRsfNNlKbCePevHtVtX57DGjDU1QDce2VTSyEldxrO-96OU.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* devanagari */
@font-face {
font-family: 'Noto Sans';
font-style: italic;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0kIpQlx3QUlC5A4PNr4C5OaxRsfNNlKbCePevHtVtX57DGjDU1QDce2VHSyEldxrO-96OU.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF9, U+200C-200D, U+20A8, U+20B9, U+20F0, U+25CC, U+A830-A839, U+A8E0-A8FF, U+11B00-11B09;
}
/* greek-ext */
@font-face {
font-family: 'Noto Sans';
font-style: italic;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0kIpQlx3QUlC5A4PNr4C5OaxRsfNNlKbCePevHtVtX57DGjDU1QDce2VzSyEldxrO-96OU.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Noto Sans';
font-style: italic;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0kIpQlx3QUlC5A4PNr4C5OaxRsfNNlKbCePevHtVtX57DGjDU1QDce2VPSyEldxrO-96OU.woff2) format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Noto Sans';
font-style: italic;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0kIpQlx3QUlC5A4PNr4C5OaxRsfNNlKbCePevHtVtX57DGjDU1QDce2V_SyEldxrO-96OU.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Noto Sans';
font-style: italic;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0kIpQlx3QUlC5A4PNr4C5OaxRsfNNlKbCePevHtVtX57DGjDU1QDce2V7SyEldxrO-96OU.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Noto Sans';
font-style: italic;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0kIpQlx3QUlC5A4PNr4C5OaxRsfNNlKbCePevHtVtX57DGjDU1QDce2VDSyEldxrO-9w.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Noto Sans';
font-style: normal;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A-9X6VLYyWtZ3rKW9w.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Noto Sans';
font-style: normal;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A-9e6VLYyWtZ3rKW9w.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* devanagari */
@font-face {
font-family: 'Noto Sans';
font-style: normal;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A-9b6VLYyWtZ3rKW9w.woff2) format('woff2');
unicode-range: U+0900-097F, U+1CD0-1CF9, U+200C-200D, U+20A8, U+20B9, U+20F0, U+25CC, U+A830-A839, U+A8E0-A8FF, U+11B00-11B09;
}
/* greek-ext */
@font-face {
font-family: 'Noto Sans';
font-style: normal;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A-9W6VLYyWtZ3rKW9w.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Noto Sans';
font-style: normal;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A-9Z6VLYyWtZ3rKW9w.woff2) format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Noto Sans';
font-style: normal;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A-9V6VLYyWtZ3rKW9w.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Noto Sans';
font-style: normal;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A-9U6VLYyWtZ3rKW9w.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Noto Sans';
font-style: normal;
font-weight: 400;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/notosans/v36/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A-9a6VLYyWtZ3rI.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu72xKKTU1Kvnz.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu5mxKKTU1Kvnz.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu7mxKKTU1Kvnz.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu4WxKKTU1Kvnz.woff2) format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu7WxKKTU1Kvnz.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu7GxKKTU1Kvnz.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
+1 -12
View File
@@ -3,8 +3,6 @@
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
border-radius: 10px;
scrollbar-gutter: auto !important;
overscroll-behavior: none;
@@ -23,15 +21,8 @@
scrollbar-gutter: unset !important;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #222222;
--foreground: #e0e0e0;
}
}
html[data-page='default'] {
background: #ffffff;
background: theme('colors.base-100');
}
html[data-page='library'] {
@@ -43,8 +34,6 @@ html[data-page='reader'] {
}
body {
color: var(--foreground);
background: var(--background);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
sans-serif;
border-radius: 10px;
+1
View File
@@ -87,6 +87,7 @@ export interface BookLayout {
showHeader: boolean;
showFooter: boolean;
showBarsOnScroll: boolean;
scrollingOverlap: number;
}
export interface BookStyle {
+1
View File
@@ -58,6 +58,7 @@ export interface AppService {
uploadBook(book: Book, onProgress?: ProgressHandler): Promise<void>;
downloadBook(book: Book, onlyCover?: boolean, onProgress?: ProgressHandler): Promise<void>;
isBookAvailable(book: Book): Promise<boolean>;
getBookFileSize(book: Book): Promise<number | null>;
loadBookConfig(book: Book, settings: SystemSettings): Promise<BookConfig>;
fetchBookDetails(book: Book, settings: SystemSettings): Promise<BookDoc['metadata']>;
saveBookConfig(book: Book, config: BookConfig, settings?: SystemSettings): Promise<void>;
+2
View File
@@ -45,6 +45,8 @@ export interface FoliateView extends HTMLElement {
removeAttribute: (name: string) => void;
next: () => Promise<void>;
prev: () => Promise<void>;
nextSection?: () => Promise<void>;
prevSection?: () => Promise<void>;
goTo?: (params: { index: number; anchor: number }) => void;
setStyles?: (css: string) => void;
getContents: () => { doc: Document; index?: number }[];
+13
View File
@@ -47,6 +47,7 @@ export const getBaseFilename = (filename: string) => {
const baseName = normalizedPath.split('/').pop()?.split('.').slice(0, -1).join('.') || '';
return baseName;
};
export const INIT_BOOK_CONFIG: BookConfig = {
updatedAt: 0,
};
@@ -141,6 +142,18 @@ export const formatSubject = (subject: string | string[] | undefined) => {
return Array.isArray(subject) ? subject.join(', ') : subject;
};
export const formatFileSize = (size: number | null) => {
if (size === null) return '';
const formatter = new Intl.NumberFormat('en', {
style: 'unit',
unit: 'byte',
unitDisplay: 'narrow',
notation: 'compact',
compactDisplay: 'short',
});
return formatter.format(size);
};
export const getCurrentPage = (book: Book, progress: BookProgress) => {
const bookFormat = book.format;
const { section, pageinfo } = progress;
+2 -2
View File
@@ -187,11 +187,11 @@ export class NativeFile extends File implements ClosableFile {
return new DeferredBlob(dataPromise, contentType);
}
override stream(): ReadableStream<Uint8Array> {
override stream(): ReadableStream<Uint8Array<ArrayBuffer>> {
const CHUNK_SIZE = 1024 * 1024;
let offset = 0;
return new ReadableStream<Uint8Array>({
return new ReadableStream<Uint8Array<ArrayBuffer>>({
pull: async (controller) => {
if (!this.#handle) {
controller.error(new Error('File handle is not open'));
+5 -1
View File
@@ -31,8 +31,12 @@ export const makeSafeFilename = (filename: string, replacement = '_') => {
return safeName.trim();
};
export const getLocale = () => {
return localStorage?.getItem('i18nextLng') || navigator?.language || '';
};
export const getUserLang = () => {
const locale = localStorage?.getItem('i18nextLng') || navigator?.language || '';
const locale = getLocale();
return locale.split('-')[0] || 'en';
};

Some files were not shown because too many files have changed in this diff Show More