Compare commits

..

22 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
70 changed files with 2122 additions and 1045 deletions
+1 -1
View File
@@ -81,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
@@ -17,6 +17,7 @@ module.exports = {
'el',
'ko',
'uk',
'nl',
'pl',
'pt',
'ru',
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@readest/readest-app",
"version": "0.9.41",
"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,8 +42,6 @@
"Global Settings": "الإعدادات العامة",
"Go Back": "العودة",
"Go Forward": "التقدم",
"Go Left": "الذهاب لليسار",
"Go Right": "الذهاب لليمين",
"Grass": "عشبي",
"Gray": "رمادي",
"Gruvbox": "چروفبوكس",
@@ -307,5 +305,12 @@
"Error checking for updates": "خطأ في التحقق من التحديثات",
"Details": "التفاصيل",
"Cancel Selection": "إلغاء التحديد",
"File Size:": "حجم الملف:"
"File Size:": "حجم الملف:",
"Auto Detect": "الكشف التلقائي",
"Touch": "اللمس",
"Scrolling Overlap (px)": "تداخل التمرير (بكسل)",
"Next Section": "القسم التالي",
"Previous Section": "القسم السابق",
"Next Page": "الصفحة التالية",
"Previous Page": "الصفحة السابقة"
}
@@ -42,8 +42,6 @@
"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",
@@ -307,5 +305,12 @@
"Error checking for updates": "Fehler beim Überprüfen auf Updates",
"Details": "Details",
"Cancel Selection": "Auswahl abbrechen",
"File Size:": "Dateigröße:"
"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,8 +42,6 @@
"Global Settings": "Γενικές ρυθμίσεις",
"Go Back": "Πίσω",
"Go Forward": "Μπροστά",
"Go Left": "Αριστερά",
"Go Right": "Δεξιά",
"Grass": "Γρασίδι",
"Gray": "Γκρι",
"Gruvbox": "Gruvbox",
@@ -307,5 +305,12 @@
"Error checking for updates": "Σφάλμα κατά τον έλεγχο για ενημερώσεις",
"Details": "Πληρ.",
"Cancel Selection": "Ακύρωση επιλογής",
"File Size:": "Μέγεθος αρχείου:"
"File Size:": "Μέγεθος αρχείου:",
"Auto Detect": "Αυτόματη ανίχνευση",
"Touch": "Αφή",
"Scrolling Overlap (px)": "Επικάλυψη κύλισης (px)",
"Next Section": "Επόμενη ενότητα",
"Previous Section": "Προηγούμενη ενότητα",
"Next Page": "Επόμενη σελίδα",
"Previous Page": "Προηγούμενη σελίδα"
}
@@ -42,8 +42,6 @@
"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",
@@ -307,5 +305,12 @@
"Error checking for updates": "Error al comprobar actualizaciones",
"Details": "Detalles",
"Cancel Selection": "Cancelar selección",
"File Size:": "Peso del archivo:"
"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,8 +42,6 @@
"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",
@@ -307,5 +305,12 @@
"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 :"
"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,8 +42,6 @@
"Global Settings": "वैश्विक सेटिंग्स",
"Go Back": "वापस जाएं",
"Go Forward": "आगे जाएं",
"Go Left": "बाएं जाएं",
"Go Right": "दाएं जाएं",
"Grass": "घास",
"Gray": "ग्रे",
"Gruvbox": "ग्रूवबॉक्स",
@@ -307,5 +305,12 @@
"Error checking for updates": "अपडेट की जांच करते समय त्रुटि",
"Details": "विवरण",
"Cancel Selection": "चयन रद्द करें",
"File Size:": "फ़ाइल आकार:"
"File Size:": "फ़ाइल आकार:",
"Auto Detect": "स्वचालित पहचान",
"Touch": "स्पर्श",
"Scrolling Overlap (px)": "स्क्रॉलिंग ओवरलैप (px)",
"Next Section": "अगला अनुभाग",
"Previous Section": "पिछला अनुभाग",
"Next Page": "अगला पृष्ठ",
"Previous Page": "पिछला पृष्ठ"
}
@@ -42,8 +42,6 @@
"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",
@@ -307,5 +305,12 @@
"Error checking for updates": "Kesalahan saat memeriksa pembaruan",
"Details": "Detail",
"Cancel Selection": "Batalkan Pilihan",
"File Size:": "Ukuran File:"
"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,8 +42,6 @@
"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",
@@ -307,5 +305,12 @@
"Error checking for updates": "Errore durante il controllo degli aggiornamenti",
"Details": "Dettagli",
"Cancel Selection": "Annulla selezione",
"File Size:": "Dimensione file:"
"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,8 +42,6 @@
"Global Settings": "全体設定",
"Go Back": "戻る",
"Go Forward": "進む",
"Go Left": "左へ",
"Go Right": "右へ",
"Grass": "グリーン",
"Gray": "グレー",
"Gruvbox": "グルーブボックス",
@@ -307,5 +305,12 @@
"Error checking for updates": "更新の確認中にエラーが発生しました",
"Details": "詳細",
"Cancel Selection": "選択をキャンセル",
"File Size:": "ファイルサイズ:"
"File Size:": "ファイルサイズ:",
"Auto Detect": "自動検出",
"Touch": "タッチ",
"Scrolling Overlap (px)": "スクロール重複(px",
"Next Section": "次のセクション",
"Previous Section": "前のセクション",
"Next Page": "次のページ",
"Previous Page": "前のページ"
}
@@ -42,8 +42,6 @@
"Global Settings": "전역 설정",
"Go Back": "뒤로",
"Go Forward": "앞으로",
"Go Left": "왼쪽으로",
"Go Right": "오른쪽으로",
"Grass": "잔디색",
"Gray": "회색",
"Gruvbox": "그러브박스",
@@ -307,5 +305,12 @@
"Error checking for updates": "업데이트 확인 중 오류 발생",
"Details": "세부정보",
"Cancel Selection": "선택 취소",
"File Size:": "파일 크기:"
"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,8 +42,6 @@
"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",
@@ -307,5 +305,12 @@
"Error checking for updates": "Błąd podczas sprawdzania aktualizacji",
"Details": "Szczegóły",
"Cancel Selection": "Anuluj zaznaczenie",
"File Size:": "Rozmiar pliku:"
"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,8 +42,6 @@
"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",
@@ -307,5 +305,12 @@
"Error checking for updates": "Erro ao verificar atualizações",
"Details": "Detalhes",
"Cancel Selection": "Cancelar Seleção",
"File Size:": "Tamanho do arquivo:"
"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,8 +42,6 @@
"Global Settings": "Общие настройки",
"Go Back": "Назад",
"Go Forward": "Вперёд",
"Go Left": "Влево",
"Go Right": "Вправо",
"Grass": "Трава",
"Gray": "Серый",
"Gruvbox": "Gruvbox",
@@ -307,5 +305,12 @@
"Error checking for updates": "Ошибка при проверке обновлений",
"Details": "Инфо",
"Cancel Selection": "Отменить выбор",
"File Size:": "Размер файла:"
"File Size:": "Размер файла:",
"Auto Detect": "Автоопределение",
"Touch": "Сенсорный экран",
"Scrolling Overlap (px)": "Перекрытие прокрутки (px)",
"Next Section": "Следующий раздел",
"Previous Section": "Предыдущий раздел",
"Next Page": "Следующая страница",
"Previous Page": "Предыдущая страница"
}
@@ -42,8 +42,6 @@
"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",
@@ -307,5 +305,12 @@
"Error checking for updates": "Güncellemeleri kontrol ederken hata oluştu",
"Details": "Detaylar",
"Cancel Selection": "Işaretlemeyi İptal Et",
"File Size:": "Dosya Boyutu:"
"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,8 +42,6 @@
"Global Settings": "Глобальні налаштування",
"Go Back": "Назад",
"Go Forward": "Вперед",
"Go Left": "Вліво",
"Go Right": "Вправо",
"Grass": "Трав'яний",
"Gray": "Сірий",
"Gruvbox": "Теплий помаранчевий",
@@ -307,5 +305,12 @@
"Error checking for updates": "Помилка перевірки наявності оновлень",
"Details": "Деталі",
"Cancel Selection": "Скасувати вибір",
"File Size:": "Розмір файлу:"
"File Size:": "Розмір файлу:",
"Auto Detect": "Авто виявлення",
"Touch": "Дотик",
"Scrolling Overlap (px)": "Прокрутка перекриття (px)",
"Next Section": "Наступний розділ",
"Previous Section": "Попередній розділ",
"Next Page": "Наступна сторінка",
"Previous Page": "Попередня сторінка"
}
@@ -42,8 +42,6 @@
"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",
@@ -307,5 +305,12 @@
"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:"
"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,8 +42,6 @@
"Global Settings": "全局设置",
"Go Back": "返回",
"Go Forward": "前进",
"Go Left": "向左",
"Go Right": "向右",
"Grass": "青草",
"Gray": "素雅",
"Gruvbox": "暖橘",
@@ -307,5 +305,12 @@
"Error checking for updates": "检查更新时出错",
"Details": "详情",
"Cancel Selection": "取消选择",
"File Size:": "文件大小"
"File Size:": "文件大小",
"Auto Detect": "自动检测",
"Touch": "触控",
"Scrolling Overlap (px)": "滚动重叠(px",
"Next Section": "下一章",
"Previous Section": "上一章",
"Next Page": "下一页",
"Previous Page": "上一页"
}
@@ -42,8 +42,6 @@
"Global Settings": "全局設置",
"Go Back": "返回",
"Go Forward": "前進",
"Go Left": "向左",
"Go Right": "向右",
"Grass": "青草",
"Gray": "素雅",
"Gruvbox": "暖橘",
@@ -307,5 +305,12 @@
"Error checking for updates": "檢查更新時出錯",
"Details": "詳情",
"Cancel Selection": "取消選擇",
"File Size:": "檔案大小"
"File Size:": "檔案大小",
"Auto Detect": "自動檢測",
"Touch": "觸控",
"Scrolling Overlap (px)": "滾動重疊(px",
"Next Section": "下一章",
"Previous Section": "上一章",
"Next Page": "下一頁",
"Previous Page": "上一頁"
}
+12
View File
@@ -1,5 +1,17 @@
{
"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": [
@@ -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
-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 sm:opacity-0 sm:group-hover:opacity-100'
className='radial-progress'
style={
{
'--value': transferProgress,
@@ -112,39 +135,32 @@ const BookItem: React.FC<BookItemProps> = ({
></div>
)
) : (
<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={() => {
if (!book.uploadedAt) {
handleBookUpload(book);
} else if (!book.downloadedAt) {
handleBookDownload(book);
}
}}
>
{!book.uploadedAt && <LiaCloudUploadAltSolid size={iconSize15} />}
{book.uploadedAt && !book.downloadedAt && (
<LiaCloudDownloadAltSolid size={iconSize15} />
)}
</button>
)}
{!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)}
>
<CiCircleMore 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>
)
)}
</div>
</div>
@@ -343,15 +343,13 @@ const Bookshelf: React.FC<BookshelfProps> = ({
<MdDelete className='fill-red-500' />
<div className='text-red-500'>{_('Delete')}</div>
</button>
{!appService?.isMobile && (
<button
onClick={() => handleSetSelectMode(false)}
className={clsx('flex flex-col items-center justify-center gap-1')}
>
<MdOutlineCancel />
<div>{_('Cancel')}</div>
</button>
)}
<button
onClick={() => handleSetSelectMode(false)}
className={clsx('flex flex-col items-center justify-center gap-1')}
>
<MdOutlineCancel />
<div>{_('Cancel')}</div>
</button>
</div>
)}
</div>
@@ -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,
@@ -107,6 +108,10 @@ const LibraryPageContent = ({ searchParams }: { searchParams: ReadonlyURLSearchP
},
});
useEffect(() => {
mountAdditionalFonts(document);
}, []);
useEffect(() => {
const doCheckAppUpdates = async () => {
if (appService?.hasUpdater && settings.autoCheckUpdates) {
@@ -133,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}
@@ -1,7 +1,8 @@
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 = () => {
@@ -173,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',
@@ -184,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(
@@ -289,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 />}
@@ -320,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) {
@@ -73,7 +73,7 @@ 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;
@@ -91,13 +91,8 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
view?.deselect();
};
const {
handleScroll,
handlePointerup,
handleSelectionchange,
handleAnnotPopup,
handleShowAnnotation,
} = useTextSelector(bookKey, setSelection, handleDismissPopup);
const { handleScroll, handlePointerup, handleSelectionchange, handleShowPopup, handleUpToPopup } =
useTextSelector(bookKey, setSelection, handleDismissPopup);
const onLoad = (event: Event) => {
const detail = (event as CustomEvent).detail;
@@ -163,15 +158,15 @@ const Annotator: React.FC<{ bookKey: string }> = ({ bookKey }) => {
setSelectedStyle(annotation.style!);
setSelectedColor(annotation.color!);
setSelection(selection);
handleShowAnnotation();
handleUpToPopup();
};
useFoliateEvents(view, { onLoad, onDrawAnnotation, onShowAnnotation });
useEffect(() => {
handleAnnotPopup(showAnnotPopup);
handleShowPopup(showAnnotPopup || showWiktionaryPopup || showWikipediaPopup || showDeepLPopup);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showAnnotPopup]);
}, [showAnnotPopup, showWiktionaryPopup, showWikipediaPopup, showDeepLPopup]);
useEffect(() => {
eventDispatcher.on('export-annotations', handleExportMarkdown);
@@ -214,11 +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);
handleShowAnnotPopup();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selection, bookKey]);
@@ -245,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>
)}
@@ -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'>
@@ -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
@@ -8,6 +8,7 @@ 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';
@@ -17,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;
@@ -54,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,
@@ -75,7 +82,7 @@ const SettingsDialog: React.FC<{ bookKey: string; config: BookConfig }> = ({ boo
if (!container) return;
const checkButtonWidths = () => {
const threshold = (container.clientWidth - 64) * 0.3;
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 || '';
@@ -135,7 +142,7 @@ const SettingsDialog: React.FC<{ bookKey: string; config: BookConfig }> = ({ boo
ref={tabsRef}
className={clsx(
'dialog-tabs flex h-10 w-full items-center',
showTabLabels ? 'gap-2 sm:gap-1' : 'gap-4',
showTabLabels ? 'gap-4 sm:gap-2' : 'gap-4',
)}
>
{tabConfig.map(({ tab, icon: Icon, label }) => (
@@ -143,7 +150,7 @@ const SettingsDialog: React.FC<{ bookKey: string; config: BookConfig }> = ({ boo
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)}
@@ -186,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>
@@ -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');
}
}
}
@@ -19,9 +19,9 @@ export const useTextSelector = (
const primaryLang = bookData.book?.primaryLanguage || 'en';
const osPlatform = getOSPlatform();
const isPopuped = useRef(false);
const isUpToPopup = useRef(false);
const isTextSelected = useRef(false);
const isAnnotPopuped = useRef(false);
const isAnnotUpToPopup = useRef(false);
const selectionPosition = useRef<number | null>(null);
const isValidSelection = (sel: Selection) => {
@@ -67,10 +67,13 @@ export const useTextSelector = (
const sel = doc.getSelection() as Selection;
if (osPlatform === 'ios') return;
if (!isValidSelection(sel)) {
if (!isAnnotUpToPopup.current) {
if (!isUpToPopup.current) {
handleDismissPopup();
isTextSelected.current = false;
}
if (isPopuped.current) {
isUpToPopup.current = false;
}
return;
}
@@ -79,6 +82,7 @@ export const useTextSelector = (
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
@@ -101,17 +105,20 @@ export const useTextSelector = (
}
};
const handleAnnotPopup = (showAnnotPopup: boolean) => {
const handleShowPopup = (showPopup: boolean) => {
setTimeout(
() => {
isAnnotPopuped.current = showAnnotPopup;
if (showPopup && !isPopuped.current) {
isUpToPopup.current = false;
}
isPopuped.current = showPopup;
},
['android', 'ios'].includes(osPlatform) ? 0 : 500,
);
};
const handleShowAnnotation = () => {
isAnnotUpToPopup.current = true;
const handleUpToPopup = () => {
isUpToPopup.current = true;
};
useEffect(() => {
@@ -125,16 +132,17 @@ export const useTextSelector = (
useEffect(() => {
const handleSingleClick = (): boolean => {
if (isAnnotUpToPopup.current) {
isAnnotUpToPopup.current = false;
if (isUpToPopup.current) {
isUpToPopup.current = false;
return true;
}
if (isTextSelected.current) {
handleDismissPopup();
isTextSelected.current = false;
view?.deselect();
return true;
}
if (isAnnotPopuped.current) {
if (isPopuped.current) {
handleDismissPopup();
return true;
}
@@ -152,7 +160,7 @@ export const useTextSelector = (
handleScroll,
handlePointerup,
handleSelectionchange,
handleAnnotPopup,
handleShowAnnotation,
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;
}
+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;
+1 -1
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` }}>
@@ -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);
+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,
};
}
-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;
+4 -2
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 = {
@@ -587,6 +588,7 @@ export const TRANSLATED_LANGS = {
en: 'English',
fr: 'Français',
de: 'Deutsch',
nl: 'Nederlands',
it: 'Italiano',
ja: '日本語',
ko: '한국어',
@@ -1,11 +1,9 @@
import type { Transformer } from './types';
import { footnoteTransformer } from './footnote';
import { translateTransformer } from './translate';
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
View File
@@ -87,6 +87,7 @@ export interface BookLayout {
showHeader: boolean;
showFooter: boolean;
showBarsOnScroll: boolean;
scrollingOverlap: number;
}
export interface BookStyle {
+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 }[];
+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';
};
+5
View File
@@ -122,6 +122,11 @@ export const getPosition = (
return start.point.y > window.innerHeight - end.point.y ? start : end;
};
// The popup will be positioned based on the triangle position and the direction
// up: above the triangle
// down: below the triangle
// left: to the left of the triangle
// right: to the right of the triangle
export const getPopupPosition = (
position: Position,
boundingReact: Rect,
+59 -18
View File
@@ -15,7 +15,6 @@ import {
generateDarkPalette,
} from '@/styles/themes';
import fontfacesCSS from '!!raw-loader!../styles/fonts.css';
import { getOSPlatform } from './misc';
const getFontStyles = (
@@ -89,6 +88,7 @@ const getFontStyles = (
}
a:any-link, a:any-link * {
${overrideFont ? `color: ${primary};` : ''}
text-decoration: none;
}
/* https://github.com/whatwg/html/issues/5426 */
@media (prefers-color-scheme: dark) {
@@ -107,14 +107,30 @@ const getFontStyles = (
return fontStyles;
};
const googleFontsData = [
{ family: 'Bitter', weights: 'ital,wght@0,100..900;1,100..900' },
{ family: 'Fira Code', weights: 'wght@300..700' },
{ family: 'Literata', weights: 'ital,opsz,wght@0,7..72,200..900;1,7..72,200..900' },
{ family: 'Merriweather', weights: 'ital,opsz,wght@0,18..144,300..900;1,18..144,300..900' },
{ family: 'Noto Sans', weights: 'ital,wght@0,100..900;1,100..900' },
{ family: 'Roboto', weights: 'ital,wght@0,100..900;1,100..900' },
{ family: 'Vollkorn', weights: 'ital,wght@0,400..900;1,400..900' },
{ family: 'LXGW WenKai TC' },
{ family: 'Noto Sans SC' },
{ family: 'Noto Sans TC' },
{ family: 'Noto Serif JP' },
];
const getAdditionalFontLinks = () => `
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/misans-webfont@1.0.4/misans-l3/misans-l3/result.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cn-fontsource-lxgw-wen-kai-gb-screen@1.0.6/font.min.css" crossorigin="anonymous">
<link rel='stylesheet' href='https://fontsapi.zeoseven.com/431/main/result.css' crossorigin="anonymous"/>
<link rel='stylesheet' href="https://fonts.googleapis.com/css2?family=Vollkorn&display=swap" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=LXGW+WenKai+TC&display=swap" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC&family=Noto+Sans+TC&display=swap" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Serif+JP&display=swap" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?${googleFontsData
.map(
({ family, weights }) =>
`family=${encodeURIComponent(family)}${weights ? `:${weights}` : ''}`,
)
.join('&')}&display=swap" crossorigin="anonymous">
`;
const getAdditionalFontFaces = () => `
@@ -179,7 +195,6 @@ const getLayoutStyles = (
@namespace epub "http://www.idpf.org/2007/ops";
html {
color-scheme: ${isDarkMode ? 'dark' : 'light'};
color: ${fg};
}
html {
--theme-bg-color: ${bg};
@@ -211,13 +226,10 @@ const getLayoutStyles = (
text-align: var(--default-text-align);
max-height: unset;
}
html {
html, body {
background-color: var(--theme-bg-color, transparent);
background: var(--background-set, none);
}
body.pbg, body *:not(a):not(#b1):not(#b1 *):not(#b2):not(#b2 *):not(img):not(.bg):not(.bg *):not(.vol):not(.vol *):not(.background):not(.background *) {
${isDarkMode ? `background-color: ${bg} !important;` : ''}
}
body {
overflow: unset;
zoom: ${zoomLevel};
@@ -227,7 +239,7 @@ const getLayoutStyles = (
width: auto;
background-color: transparent !important;
}
p, div, li, blockquote, dd {
p, li, blockquote, dd, div:not(:has(*:not(b, a, em, i, strong, u, span))) {
line-height: ${lineSpacing} ${overrideLayout ? '!important' : ''};
word-spacing: ${wordSpacing}px ${overrideLayout ? '!important' : ''};
letter-spacing: ${letterSpacing}px ${overrideLayout ? '!important' : ''};
@@ -247,11 +259,6 @@ const getLayoutStyles = (
${!vertical ? `margin-top: ${paragraphMargin}em ${overrideLayout ? '!important' : ''};` : ''}
${!vertical ? `margin-bottom: ${paragraphMargin}em ${overrideLayout ? '!important' : ''};` : ''}
}
/* prevent the above from overriding the align attribute */
[align="left"] { text-align: left; }
[align="right"] { text-align: right; }
[align="center"] { text-align: center; }
[align="justify"] { text-align: justify; }
pre {
white-space: pre-wrap !important;
@@ -266,6 +273,9 @@ const getLayoutStyles = (
}
/* Now begins really dirty hacks to fix some badly designed epubs */
body.pbg {
${isDarkMode ? `background-color: ${bg} !important;` : ''}
}
img.pi {
${vertical ? 'transform: rotate(90deg);' : ''}
${vertical ? 'transform-origin: center;' : ''}
@@ -283,8 +293,39 @@ const getLayoutStyles = (
color: unset;
}
.chapterHeader {
/* inline images without dimension */
p img, span img, sup img {
height: 1em;
mix-blend-mode: ${isDarkMode ? 'screen' : 'multiply'};
${isDarkMode ? 'filter: invert(100%);' : ''}
}
p:has(img), span:has(img) {
background-color: ${bg};
}
/* hardcoded inline font size */
[style*="font-size: 16px"], [style*="font-size:16px"] {
font-size: 1rem !important;
}
/* workaround for some badly designed epubs */
div.left *, p.left * { text-align: left; }
div.right *, p.right * { text-align: right; }
div.center *, p.center * { text-align: center; }
div.justify *, p.justify * { text-align: justify; }
/* for the Gutenberg eBooks */
#pg-header * {
color: inherit !important;
}
.x-ebookmaker-cover {
background-color: unset !important;
}
/* for the Feedbooks eBooks */
.chapterHeader, .chapterHeader * {
border-color: unset;
background-color: ${bg} !important;
}
`;
return layoutStyle;
@@ -394,7 +435,7 @@ export const getStyles = (viewSettings: ViewSettings, themeCode?: ThemeCode) =>
themeCode,
);
const userStylesheet = viewSettings.userStylesheet!;
return `${layoutStyles}\n${fontStyles}\n${fontfacesCSS}\n${userStylesheet}`;
return `${layoutStyles}\n${fontStyles}\n${userStylesheet}`;
};
export const mountAdditionalFonts = (document: Document) => {
-12
View File
@@ -1,12 +0,0 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"main": ".open-next/worker.js",
"name": "readest-web",
"compatibility_date": "2025-02-04",
"compatibility_flags": ["nodejs_compat"],
"assets": {
"directory": ".open-next/assets",
"binding": "ASSETS"
},
"kv_namespaces": []
}
+12
View File
@@ -0,0 +1,12 @@
name = "readest-web"
main = ".open-next/worker.js"
compatibility_date = "2025-02-04"
compatibility_flags = ["nodejs_compat"]
[assets]
directory = ".open-next/assets"
binding = "ASSETS"
[[kv_namespaces]]
binding = "TRANSLATIONS_KV"
id = "${TRANSLATIONS_KV_ID}"