Archived
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e80c2673ef | ||
|
|
26c5f6f06b | ||
|
|
22ded87250 | ||
|
|
84c0497f21 | ||
|
|
724eae1142 | ||
|
|
654cfec147 |
+25
@@ -1,4 +1,29 @@
|
||||
node_modules
|
||||
dist
|
||||
frontend/dist
|
||||
frontend/dist/assets
|
||||
frontend/dist/assets/index.html
|
||||
frontend/dist/assets/index.html.gz
|
||||
frontend/dist/assets/index.html.br
|
||||
frontend/dist/assets/index.html.brotli
|
||||
frontend/dist/assets/index.html.gzip
|
||||
frontend/dist/assets/index.html.br
|
||||
frontend/dist/assets/index.html.brotli
|
||||
frontend/dist/assets/index.html.gzip
|
||||
frontend/dist/assets/index.html.br
|
||||
frontend/dist/assets/index.html.brotli
|
||||
frontend/dist/assets/index.html.gzip
|
||||
frontend/dist/assets/index.html.br
|
||||
frontend/dist/assets/index.html.brotli
|
||||
frontend/dist/assets/index.html.gzip
|
||||
frontend/dist/assets/index.html.br
|
||||
frontend/dist/assets/index.html.brotli
|
||||
frontend/dist/assets/index.html.gzip
|
||||
mobile/dist
|
||||
backend/media
|
||||
backend/staticfiles
|
||||
backend/media
|
||||
backend/staticfiles
|
||||
.pycache__
|
||||
__pycache__
|
||||
*.pyc
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from apps.groups.models import (
|
||||
GroupMeeting,
|
||||
GroupMembership,
|
||||
NotificationPreference,
|
||||
PaceNotification,
|
||||
ReadingGroup,
|
||||
)
|
||||
|
||||
|
||||
@admin.register(ReadingGroup)
|
||||
class ReadingGroupAdmin(admin.ModelAdmin):
|
||||
list_display = ["name", "created_by", "created_at"]
|
||||
search_fields = ["name"]
|
||||
|
||||
|
||||
@admin.register(GroupMembership)
|
||||
class GroupMembershipAdmin(admin.ModelAdmin):
|
||||
list_display = ["user", "group", "role", "joined_at"]
|
||||
list_filter = ["role"]
|
||||
|
||||
|
||||
@admin.register(GroupMeeting)
|
||||
class GroupMeetingAdmin(admin.ModelAdmin):
|
||||
list_display = ["group", "title", "target_section_label", "scheduled_at"]
|
||||
list_filter = ["group"]
|
||||
|
||||
|
||||
@admin.register(NotificationPreference)
|
||||
class NotificationPreferenceAdmin(admin.ModelAdmin):
|
||||
list_display = ["user", "pace_notifications_enabled", "reminder_enabled", "frequency"]
|
||||
|
||||
|
||||
@admin.register(PaceNotification)
|
||||
class PaceNotificationAdmin(admin.ModelAdmin):
|
||||
list_display = ["user", "meeting", "status", "created_at"]
|
||||
list_filter = ["status"]
|
||||
@@ -0,0 +1,8 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class GroupsConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "apps.groups"
|
||||
verbose_name = "Reading Groups"
|
||||
label = "groups"
|
||||
@@ -0,0 +1,109 @@
|
||||
# Generated by Django 5.1.7 on 2026-06-20 19:22
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('books', '0003_readingprogress_epub_location'),
|
||||
('users', '0001_initial'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='NotificationPreference',
|
||||
fields=[
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='notification_preference', serialize=False, to=settings.AUTH_USER_MODEL)),
|
||||
('pace_notifications_enabled', models.BooleanField(default=True)),
|
||||
('reminder_enabled', models.BooleanField(default=True)),
|
||||
('frequency', models.CharField(choices=[('daily', 'Daily'), ('weekly', 'Weekly')], default='daily', max_length=16)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Notification Preference',
|
||||
'verbose_name_plural': 'Notification Preferences',
|
||||
'db_table': 'groups_notification_preference',
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ReadingGroup',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(db_index=True, max_length=256)),
|
||||
('description', models.TextField(blank=True, default='')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('book', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='reading_groups', to='books.book')),
|
||||
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='created_groups', to=settings.AUTH_USER_MODEL)),
|
||||
('ebook', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='reading_groups', to='books.ebook')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Reading Group',
|
||||
'verbose_name_plural': 'Reading Groups',
|
||||
'db_table': 'groups_reading_group',
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='GroupMeeting',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(blank=True, default='', max_length=512)),
|
||||
('scheduled_at', models.DateTimeField(db_index=True)),
|
||||
('target_section', models.PositiveIntegerField(default=0, help_text='Target chapter/section index to reach by this meeting')),
|
||||
('target_section_label', models.CharField(blank=True, default='', help_text="Human-readable label for the target section (e.g. 'Section 3')", max_length=512)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='meetings', to='groups.readinggroup')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Group Meeting',
|
||||
'verbose_name_plural': 'Group Meetings',
|
||||
'db_table': 'groups_meeting',
|
||||
'ordering': ['scheduled_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='PaceNotification',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('status', models.CharField(choices=[('pending', 'Pending'), ('sent', 'Sent'), ('dismissed', 'Dismissed')], default='pending', max_length=16)),
|
||||
('current_section', models.PositiveIntegerField(default=0)),
|
||||
('target_section', models.PositiveIntegerField(default=0)),
|
||||
('ahead_behind_delta', models.IntegerField(default=0)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('ebook', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='pace_notifications', to='books.ebook')),
|
||||
('meeting', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='pace_notifications', to='groups.groupmeeting')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='pace_notifications', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Pace Notification',
|
||||
'verbose_name_plural': 'Pace Notifications',
|
||||
'db_table': 'groups_pace_notification',
|
||||
'ordering': ['-created_at'],
|
||||
'indexes': [models.Index(fields=['user', 'meeting', 'ebook'], name='groups_pace_user_id_18e929_idx')],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='GroupMembership',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('role', models.CharField(choices=[('admin', 'Admin'), ('member', 'Member')], default='member', max_length=16)),
|
||||
('joined_at', models.DateTimeField(auto_now_add=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='group_memberships', to=settings.AUTH_USER_MODEL)),
|
||||
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='memberships', to='groups.readinggroup')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Group Membership',
|
||||
'verbose_name_plural': 'Group Memberships',
|
||||
'db_table': 'groups_membership',
|
||||
'indexes': [models.Index(fields=['user', 'group'], name='groups_memb_user_id_9cda7e_idx')],
|
||||
'unique_together': {('user', 'group')},
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,190 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
|
||||
class FrequencyChoice(models.TextChoices):
|
||||
DAILY = "daily", "Daily"
|
||||
WEEKLY = "weekly", "Weekly"
|
||||
|
||||
|
||||
class MembershipRole(models.TextChoices):
|
||||
ADMIN = "admin", "Admin"
|
||||
MEMBER = "member", "Member"
|
||||
|
||||
|
||||
class NotificationStatus(models.TextChoices):
|
||||
PENDING = "pending", "Pending"
|
||||
SENT = "sent", "Sent"
|
||||
DISMISSED = "dismissed", "Dismissed"
|
||||
|
||||
|
||||
class ReadingGroup(models.Model):
|
||||
"""A group of users reading a book together with scheduled meetings."""
|
||||
|
||||
name = models.CharField(max_length=256, db_index=True)
|
||||
description = models.TextField(blank=True, default="")
|
||||
book = models.ForeignKey(
|
||||
"books.Book",
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="reading_groups",
|
||||
)
|
||||
ebook = models.ForeignKey(
|
||||
"books.EBook",
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="reading_groups",
|
||||
)
|
||||
created_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="created_groups",
|
||||
)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "groups_reading_group"
|
||||
verbose_name = "Reading Group"
|
||||
verbose_name_plural = "Reading Groups"
|
||||
ordering = ["-created_at"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
|
||||
class GroupMembership(models.Model):
|
||||
"""User membership in a reading group."""
|
||||
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="group_memberships",
|
||||
)
|
||||
group = models.ForeignKey(
|
||||
ReadingGroup,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="memberships",
|
||||
)
|
||||
role = models.CharField(
|
||||
max_length=16,
|
||||
choices=MembershipRole.choices,
|
||||
default=MembershipRole.MEMBER,
|
||||
)
|
||||
joined_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "groups_membership"
|
||||
verbose_name = "Group Membership"
|
||||
verbose_name_plural = "Group Memberships"
|
||||
unique_together = [("user", "group")]
|
||||
indexes = [models.Index(fields=["user", "group"])]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.user} in {self.group}"
|
||||
|
||||
|
||||
class GroupMeeting(models.Model):
|
||||
"""A scheduled meeting for a reading group with a target section."""
|
||||
|
||||
group = models.ForeignKey(
|
||||
ReadingGroup,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="meetings",
|
||||
)
|
||||
title = models.CharField(max_length=512, blank=True, default="")
|
||||
scheduled_at = models.DateTimeField(db_index=True)
|
||||
target_section = models.PositiveIntegerField(
|
||||
default=0,
|
||||
help_text="Target chapter/section index to reach by this meeting",
|
||||
)
|
||||
target_section_label = models.CharField(
|
||||
max_length=512,
|
||||
blank=True,
|
||||
default="",
|
||||
help_text="Human-readable label for the target section (e.g. 'Section 3')",
|
||||
)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "groups_meeting"
|
||||
verbose_name = "Group Meeting"
|
||||
verbose_name_plural = "Group Meetings"
|
||||
ordering = ["scheduled_at"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.group.name} — {self.title or self.target_section_label} ({self.scheduled_at.date()})"
|
||||
|
||||
|
||||
class NotificationPreference(models.Model):
|
||||
"""Per-user notification settings for reading pace alerts."""
|
||||
|
||||
user = models.OneToOneField(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="notification_preference",
|
||||
primary_key=True,
|
||||
)
|
||||
pace_notifications_enabled = models.BooleanField(default=True)
|
||||
reminder_enabled = models.BooleanField(default=True)
|
||||
frequency = models.CharField(
|
||||
max_length=16,
|
||||
choices=FrequencyChoice.choices,
|
||||
default=FrequencyChoice.DAILY,
|
||||
)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "groups_notification_preference"
|
||||
verbose_name = "Notification Preference"
|
||||
verbose_name_plural = "Notification Preferences"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.user} — pace={'on' if self.pace_notifications_enabled else 'off'}, freq={self.frequency}"
|
||||
|
||||
|
||||
class PaceNotification(models.Model):
|
||||
"""Tracks reading pace notifications sent to users to avoid duplicates."""
|
||||
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="pace_notifications",
|
||||
)
|
||||
meeting = models.ForeignKey(
|
||||
GroupMeeting,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="pace_notifications",
|
||||
)
|
||||
ebook = models.ForeignKey(
|
||||
"books.EBook",
|
||||
on_delete=models.CASCADE,
|
||||
related_name="pace_notifications",
|
||||
null=True,
|
||||
blank=True,
|
||||
)
|
||||
status = models.CharField(
|
||||
max_length=16,
|
||||
choices=NotificationStatus.choices,
|
||||
default=NotificationStatus.PENDING,
|
||||
)
|
||||
current_section = models.PositiveIntegerField(default=0)
|
||||
target_section = models.PositiveIntegerField(default=0)
|
||||
ahead_behind_delta = models.IntegerField(default=0)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "groups_pace_notification"
|
||||
verbose_name = "Pace Notification"
|
||||
verbose_name_plural = "Pace Notifications"
|
||||
ordering = ["-created_at"]
|
||||
indexes = [
|
||||
models.Index(fields=["user", "meeting", "ebook"]),
|
||||
]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.user} — meeting {self.meeting_id}: {self.get_status_display()}"
|
||||
@@ -0,0 +1,137 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from rest_framework import serializers
|
||||
|
||||
from apps.groups.models import (
|
||||
FrequencyChoice,
|
||||
GroupMeeting,
|
||||
GroupMembership,
|
||||
NotificationPreference,
|
||||
PaceNotification,
|
||||
ReadingGroup,
|
||||
)
|
||||
from apps.groups.services.pace import PaceStatus
|
||||
|
||||
|
||||
class NotificationPreferenceSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = NotificationPreference
|
||||
fields = [
|
||||
"pace_notifications_enabled",
|
||||
"reminder_enabled",
|
||||
"frequency",
|
||||
]
|
||||
|
||||
def validate_frequency(self, value: str) -> str:
|
||||
valid = {choice[0] for choice in FrequencyChoice.choices}
|
||||
if value not in valid:
|
||||
raise serializers.ValidationError(
|
||||
f"Frequency must be one of: {', '.join(valid)}"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
class GroupMeetingSerializer(serializers.ModelSerializer):
|
||||
group_name = serializers.CharField(source="group.name", read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = GroupMeeting
|
||||
fields = [
|
||||
"id",
|
||||
"group",
|
||||
"group_name",
|
||||
"title",
|
||||
"scheduled_at",
|
||||
"target_section",
|
||||
"target_section_label",
|
||||
"created_at",
|
||||
]
|
||||
read_only_fields = ["id", "created_at"]
|
||||
|
||||
def validate_target_section(self, value: int) -> int:
|
||||
if value < 0:
|
||||
raise serializers.ValidationError("Target section must be non-negative.")
|
||||
return value
|
||||
|
||||
|
||||
class ReadingGroupSerializer(serializers.ModelSerializer):
|
||||
member_count = serializers.SerializerMethodField()
|
||||
meeting_count = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = ReadingGroup
|
||||
fields = [
|
||||
"id",
|
||||
"name",
|
||||
"description",
|
||||
"book",
|
||||
"ebook",
|
||||
"created_by",
|
||||
"created_at",
|
||||
"member_count",
|
||||
"meeting_count",
|
||||
]
|
||||
read_only_fields = ["id", "created_by", "created_at"]
|
||||
|
||||
def get_member_count(self, obj: ReadingGroup) -> int:
|
||||
return obj.memberships.count()
|
||||
|
||||
def get_meeting_count(self, obj: ReadingGroup) -> int:
|
||||
return obj.meetings.count()
|
||||
|
||||
|
||||
class GroupMembershipSerializer(serializers.ModelSerializer):
|
||||
user_email = serializers.CharField(source="user.email", read_only=True)
|
||||
group_name = serializers.CharField(source="group.name", read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = GroupMembership
|
||||
fields = ["id", "user", "user_email", "group", "group_name", "role", "joined_at"]
|
||||
read_only_fields = ["id", "joined_at"]
|
||||
|
||||
|
||||
class PaceNotificationSerializer(serializers.ModelSerializer):
|
||||
status_display = serializers.CharField(source="get_status_display", read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = PaceNotification
|
||||
fields = [
|
||||
"id",
|
||||
"user",
|
||||
"meeting",
|
||||
"ebook",
|
||||
"status",
|
||||
"status_display",
|
||||
"current_section",
|
||||
"target_section",
|
||||
"ahead_behind_delta",
|
||||
"created_at",
|
||||
]
|
||||
read_only_fields = ["id", "created_at"]
|
||||
|
||||
|
||||
class PaceStatusSerializer(serializers.Serializer):
|
||||
meeting_id = serializers.IntegerField()
|
||||
meeting_title = serializers.CharField()
|
||||
scheduled_at = serializers.CharField()
|
||||
target_section = serializers.IntegerField()
|
||||
target_section_label = serializers.CharField()
|
||||
current_section = serializers.IntegerField()
|
||||
ahead_behind_delta = serializers.IntegerField()
|
||||
status = serializers.CharField()
|
||||
days_until_meeting = serializers.IntegerField()
|
||||
sections_to_catch_up = serializers.IntegerField()
|
||||
ebook_id = serializers.IntegerField()
|
||||
ebook_title = serializers.CharField()
|
||||
|
||||
|
||||
class ReminderSerializer(serializers.Serializer):
|
||||
meeting_id = serializers.IntegerField()
|
||||
meeting_title = serializers.CharField()
|
||||
scheduled_at = serializers.CharField()
|
||||
target_section = serializers.IntegerField()
|
||||
target_section_label = serializers.CharField()
|
||||
group_name = serializers.CharField()
|
||||
hours_until = serializers.IntegerField()
|
||||
ebook_id = serializers.IntegerField()
|
||||
ebook_title = serializers.CharField()
|
||||
@@ -0,0 +1,219 @@
|
||||
"""Pace calculation service for reading progress vs meeting targets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from typing import TypedDict
|
||||
|
||||
from django.db.models import QuerySet
|
||||
from django.utils import timezone
|
||||
|
||||
from apps.books.models import EBook, ReadingProgress
|
||||
from apps.groups.models import (
|
||||
GroupMeeting,
|
||||
GroupMembership,
|
||||
NotificationPreference,
|
||||
PaceNotification,
|
||||
NotificationStatus,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PaceStatus(TypedDict):
|
||||
meeting_id: int
|
||||
meeting_title: str
|
||||
scheduled_at: str
|
||||
target_section: int
|
||||
target_section_label: str
|
||||
current_section: int
|
||||
ahead_behind_delta: int
|
||||
status: str # "ahead", "behind", "on_track", "completed"
|
||||
days_until_meeting: int
|
||||
sections_to_catch_up: int
|
||||
ebook_id: int
|
||||
ebook_title: str
|
||||
|
||||
|
||||
def get_relevant_ebooks_for_user(user) -> QuerySet[EBook]:
|
||||
"""Return ebooks that belong to groups the user is a member of."""
|
||||
group_ids = (
|
||||
GroupMembership.objects.filter(user=user)
|
||||
.values_list("group_id", flat=True)
|
||||
)
|
||||
return (
|
||||
EBook.objects.filter(reading_groups__in=group_ids)
|
||||
.select_related("reading_progress")
|
||||
.prefetch_related("chapters")
|
||||
.distinct()
|
||||
)
|
||||
|
||||
|
||||
def calculate_pace(
|
||||
user,
|
||||
ebook: EBook | None = None,
|
||||
meeting: GroupMeeting | None = None,
|
||||
) -> list[PaceStatus]:
|
||||
"""Calculate reading pace for a user's upcoming meetings.
|
||||
|
||||
Compares the user's current reading progress (chapter index) against
|
||||
the target section for each upcoming meeting within 3 days.
|
||||
"""
|
||||
now = timezone.now()
|
||||
three_days_from_now = now + timedelta(days=3)
|
||||
|
||||
# Find upcoming meetings for groups the user belongs to
|
||||
user_group_ids = (
|
||||
GroupMembership.objects.filter(user=user)
|
||||
.values_list("group_id", flat=True)
|
||||
)
|
||||
meetings_qs = GroupMeeting.objects.filter(
|
||||
group_id__in=user_group_ids,
|
||||
scheduled_at__gte=now,
|
||||
scheduled_at__lte=three_days_from_now,
|
||||
).select_related("group", "group__ebook")
|
||||
|
||||
if meeting:
|
||||
meetings_qs = meetings_qs.filter(pk=meeting.pk)
|
||||
|
||||
meetings = list(meetings_qs)
|
||||
|
||||
results: list[PaceStatus] = []
|
||||
|
||||
for m in meetings:
|
||||
group_ebook = m.group.ebook
|
||||
ebooks_to_check: list[EBook] = []
|
||||
|
||||
if ebook:
|
||||
ebooks_to_check = [ebook]
|
||||
elif group_ebook:
|
||||
ebooks_to_check = [group_ebook]
|
||||
else:
|
||||
# Check all ebooks in the group
|
||||
ebooks_to_check = list(
|
||||
EBook.objects.filter(reading_groups=m.group)
|
||||
.select_related("reading_progress")
|
||||
.prefetch_related("chapters")
|
||||
)
|
||||
|
||||
for eb in ebooks_to_check:
|
||||
pace = _compute_single_pace(user, m, eb, now)
|
||||
if pace:
|
||||
results.append(pace)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def _compute_single_pace(
|
||||
user,
|
||||
meeting: GroupMeeting,
|
||||
ebook: EBook,
|
||||
now: datetime,
|
||||
) -> PaceStatus | None:
|
||||
"""Compute pace for one user + meeting + ebook combination."""
|
||||
try:
|
||||
progress = ebook.reading_progress
|
||||
except ReadingProgress.DoesNotExist:
|
||||
# No progress yet — user hasn't started reading
|
||||
return None
|
||||
|
||||
# Current section: based on last_page (chapter index) or computed from progress %
|
||||
if progress.last_page > 0:
|
||||
current_section = progress.last_page
|
||||
elif progress.current_position > 0:
|
||||
chapter_count = ebook.chapters.count() or ebook.page_count or 1
|
||||
current_section = max(1, int((progress.current_position / 100) * chapter_count))
|
||||
else:
|
||||
current_section = 0
|
||||
|
||||
target_section = meeting.target_section or 0
|
||||
if target_section == 0:
|
||||
return None
|
||||
|
||||
delta = current_section - target_section
|
||||
days_until = max(0, (meeting.scheduled_at - now).days)
|
||||
|
||||
if current_section >= target_section:
|
||||
if current_section >= target_section and progress.current_position > 0:
|
||||
status = "completed"
|
||||
else:
|
||||
status = "ahead"
|
||||
elif delta >= -1:
|
||||
status = "on_track"
|
||||
else:
|
||||
status = "behind"
|
||||
|
||||
return PaceStatus(
|
||||
meeting_id=meeting.pk,
|
||||
meeting_title=meeting.title or meeting.target_section_label,
|
||||
scheduled_at=meeting.scheduled_at.isoformat(),
|
||||
target_section=target_section,
|
||||
target_section_label=meeting.target_section_label,
|
||||
current_section=current_section,
|
||||
ahead_behind_delta=delta,
|
||||
status=status,
|
||||
days_until_meeting=days_until,
|
||||
sections_to_catch_up=max(0, target_section - current_section),
|
||||
ebook_id=ebook.pk,
|
||||
ebook_title=ebook.title,
|
||||
)
|
||||
|
||||
|
||||
def should_send_notification(
|
||||
user,
|
||||
meeting: GroupMeeting,
|
||||
ebook: EBook,
|
||||
) -> bool:
|
||||
"""Check if a pace notification should be sent based on user preferences."""
|
||||
pref, _ = NotificationPreference.objects.get_or_create(user=user)
|
||||
|
||||
if not pref.pace_notifications_enabled:
|
||||
return False
|
||||
|
||||
# Check if notification was already sent today
|
||||
today = timezone.now().date()
|
||||
existing = PaceNotification.objects.filter(
|
||||
user=user,
|
||||
meeting=meeting,
|
||||
ebook=ebook,
|
||||
created_at__date=today,
|
||||
).exclude(status=NotificationStatus.DISMISSED)
|
||||
|
||||
if existing.exists():
|
||||
return False
|
||||
|
||||
# Frequency check
|
||||
if pref.frequency == "weekly":
|
||||
week_ago = today - timedelta(days=7)
|
||||
recent = PaceNotification.objects.filter(
|
||||
user=user,
|
||||
meeting=meeting,
|
||||
ebook=ebook,
|
||||
created_at__date__gte=week_ago,
|
||||
).exclude(status=NotificationStatus.DISMISSED)
|
||||
if recent.exists():
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def get_reminder_meetings(user) -> list[GroupMeeting]:
|
||||
"""Get meetings that are within 24 hours for reminder notifications."""
|
||||
now = timezone.now()
|
||||
tomorrow = now + timedelta(days=1)
|
||||
|
||||
user_group_ids = (
|
||||
GroupMembership.objects.filter(user=user)
|
||||
.values_list("group_id", flat=True)
|
||||
)
|
||||
|
||||
return list(
|
||||
GroupMeeting.objects.filter(
|
||||
group_id__in=user_group_ids,
|
||||
scheduled_at__gte=now,
|
||||
scheduled_at__lte=tomorrow,
|
||||
)
|
||||
.select_related("group", "group__ebook")
|
||||
.order_by("scheduled_at")
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
from django.urls import include, path
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from apps.groups.views import (
|
||||
GroupMeetingViewSet,
|
||||
ReadingGroupViewSet,
|
||||
dismiss_pace_notification_view,
|
||||
notification_preferences_view,
|
||||
pace_status_view,
|
||||
reminder_view,
|
||||
)
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(r"groups", ReadingGroupViewSet, basename="reading-group")
|
||||
router.register(r"meetings", GroupMeetingViewSet, basename="group-meeting")
|
||||
|
||||
urlpatterns = [
|
||||
path("", include(router.urls)),
|
||||
path("notifications/preferences/", notification_preferences_view, name="notification-preferences"),
|
||||
path("notifications/pace/", pace_status_view, name="pace-status"),
|
||||
path("notifications/dismiss/", dismiss_pace_notification_view, name="dismiss-pace"),
|
||||
path("notifications/reminders/", reminder_view, name="meeting-reminders"),
|
||||
]
|
||||
@@ -0,0 +1,207 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from django.db.models import QuerySet
|
||||
from rest_framework import permissions, status, viewsets
|
||||
from rest_framework.decorators import action, api_view, permission_classes
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.request import Request
|
||||
from rest_framework.response import Response
|
||||
|
||||
from apps.books.models import EBook
|
||||
from apps.groups.models import (
|
||||
GroupMeeting,
|
||||
GroupMembership,
|
||||
NotificationPreference,
|
||||
PaceNotification,
|
||||
NotificationStatus,
|
||||
ReadingGroup,
|
||||
)
|
||||
from apps.groups.serializers import (
|
||||
GroupMeetingSerializer,
|
||||
GroupMembershipSerializer,
|
||||
NotificationPreferenceSerializer,
|
||||
PaceNotificationSerializer,
|
||||
PaceStatusSerializer,
|
||||
ReadingGroupSerializer,
|
||||
ReminderSerializer,
|
||||
)
|
||||
from apps.groups.services.pace import (
|
||||
calculate_pace,
|
||||
get_reminder_meetings,
|
||||
should_send_notification,
|
||||
)
|
||||
|
||||
|
||||
class IsGroupMember(permissions.BasePermission):
|
||||
"""Only allow group members to access group resources."""
|
||||
|
||||
def has_object_permission(self, request: Request, view: object, obj: ReadingGroup) -> bool:
|
||||
return obj.memberships.filter(user=request.user).exists()
|
||||
|
||||
|
||||
class ReadingGroupViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated, IsGroupMember]
|
||||
serializer_class = ReadingGroupSerializer
|
||||
|
||||
def get_queryset(self) -> QuerySet[ReadingGroup]:
|
||||
return (
|
||||
ReadingGroup.objects.filter(memberships__user=self.request.user)
|
||||
.prefetch_related("memberships", "meetings")
|
||||
.distinct()
|
||||
)
|
||||
|
||||
def perform_create(self, serializer) -> None:
|
||||
group = serializer.save(created_by=self.request.user)
|
||||
GroupMembership.objects.create(
|
||||
user=self.request.user,
|
||||
group=group,
|
||||
role="admin",
|
||||
)
|
||||
|
||||
@action(detail=False, methods=["get"], url_path="all")
|
||||
def all_groups(self, request: Request) -> Response:
|
||||
"""Return all groups (for discovery)."""
|
||||
qs = ReadingGroup.objects.all().prefetch_related("memberships", "meetings")
|
||||
page = self.paginate_queryset(qs)
|
||||
if page is not None:
|
||||
serializer = self.get_serializer(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
serializer = self.get_serializer(qs, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class GroupMeetingViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
serializer_class = GroupMeetingSerializer
|
||||
|
||||
def get_queryset(self) -> QuerySet[GroupMeeting]:
|
||||
user_group_ids = (
|
||||
GroupMembership.objects.filter(user=self.request.user)
|
||||
.values_list("group_id", flat=True)
|
||||
)
|
||||
return GroupMeeting.objects.filter(group_id__in=user_group_ids).select_related(
|
||||
"group"
|
||||
)
|
||||
|
||||
def perform_create(self, serializer) -> None:
|
||||
group = serializer.validated_data["group"]
|
||||
if not group.memberships.filter(user=self.request.user).exists():
|
||||
raise permissions.PermissionDenied("You must be a group member to create meetings.")
|
||||
serializer.save()
|
||||
|
||||
@action(detail=False, methods=["get"], url_path="upcoming")
|
||||
def upcoming(self, request: Request) -> Response:
|
||||
"""Return upcoming meetings for the user's groups (within 3 days)."""
|
||||
from django.utils import timezone
|
||||
from datetime import timedelta
|
||||
|
||||
now = timezone.now()
|
||||
three_days = now + timedelta(days=3)
|
||||
qs = self.get_queryset().filter(
|
||||
scheduled_at__gte=now,
|
||||
scheduled_at__lte=three_days,
|
||||
)
|
||||
serializer = self.get_serializer(qs, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
@api_view(["GET", "PATCH"])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def notification_preferences_view(request: Request) -> Response:
|
||||
"""Get or update notification preferences for the current user."""
|
||||
pref, _created = NotificationPreference.objects.get_or_create(user=request.user)
|
||||
|
||||
if request.method == "GET":
|
||||
serializer = NotificationPreferenceSerializer(pref)
|
||||
return Response(serializer.data)
|
||||
|
||||
serializer = NotificationPreferenceSerializer(pref, data=request.data, partial=True)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
serializer.save()
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
@api_view(["GET"])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def pace_status_view(request: Request) -> Response:
|
||||
"""Get reading pace status for the current user's upcoming meetings."""
|
||||
ebook_id = request.query_params.get("ebook_id")
|
||||
ebook: EBook | None = None
|
||||
|
||||
if ebook_id:
|
||||
try:
|
||||
ebook = EBook.objects.select_related("reading_progress").prefetch_related("chapters").get(
|
||||
pk=ebook_id, user=request.user
|
||||
)
|
||||
except EBook.DoesNotExist:
|
||||
return Response(
|
||||
{"error": "EBook not found."}, status=status.HTTP_404_NOT_FOUND
|
||||
)
|
||||
|
||||
pace_data = calculate_pace(request.user, ebook=ebook)
|
||||
serializer = PaceStatusSerializer(pace_data, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def dismiss_pace_notification_view(request: Request) -> Response:
|
||||
"""Dismiss a pace notification so it won't show again."""
|
||||
meeting_id = request.data.get("meeting_id")
|
||||
ebook_id = request.data.get("ebook_id")
|
||||
|
||||
if not meeting_id or not ebook_id:
|
||||
return Response(
|
||||
{"error": "meeting_id and ebook_id are required."},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
PaceNotification.objects.filter(
|
||||
user=request.user,
|
||||
meeting_id=meeting_id,
|
||||
ebook_id=ebook_id,
|
||||
status=NotificationStatus.PENDING,
|
||||
).update(status=NotificationStatus.DISMISSED)
|
||||
|
||||
return Response({"status": "dismissed"})
|
||||
|
||||
|
||||
@api_view(["GET"])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def reminder_view(request: Request) -> Response:
|
||||
"""Get pre-meeting reminders for meetings within 24 hours."""
|
||||
pref, _ = NotificationPreference.objects.get_or_create(user=request.user)
|
||||
if not pref.reminder_enabled:
|
||||
return Response([])
|
||||
|
||||
meetings = get_reminder_meetings(request.user)
|
||||
now_dt = __import__("django").utils.timezone.now()
|
||||
|
||||
reminders = []
|
||||
for mtg in meetings:
|
||||
group_ebook = mtg.group.ebook
|
||||
ebook: EBook | None = group_ebook
|
||||
if not ebook:
|
||||
ebooks = list(
|
||||
EBook.objects.filter(reading_groups=mtg.group).select_related("reading_progress")[:1]
|
||||
)
|
||||
ebook = ebooks[0] if ebooks else None
|
||||
|
||||
if not ebook:
|
||||
continue
|
||||
|
||||
hours_until = max(0, int((mtg.scheduled_at - now_dt).total_seconds() / 3600))
|
||||
reminders.append({
|
||||
"meeting_id": mtg.pk,
|
||||
"meeting_title": mtg.title or mtg.target_section_label,
|
||||
"scheduled_at": mtg.scheduled_at.isoformat(),
|
||||
"target_section": mtg.target_section,
|
||||
"target_section_label": mtg.target_section_label,
|
||||
"group_name": mtg.group.name,
|
||||
"hours_until": hours_until,
|
||||
"ebook_id": ebook.pk,
|
||||
"ebook_title": ebook.title,
|
||||
})
|
||||
|
||||
serializer = ReminderSerializer(reminders, many=True)
|
||||
return Response(serializer.data)
|
||||
@@ -41,6 +41,7 @@ INSTALLED_APPS = [
|
||||
"apps.books",
|
||||
"apps.annotations",
|
||||
"apps.reader",
|
||||
"apps.groups",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
|
||||
@@ -8,6 +8,7 @@ urlpatterns = [
|
||||
path("api/books/", include("apps.books.urls")),
|
||||
path("api/annotations/", include("apps.annotations.urls")),
|
||||
path("api/reader/", include("apps.reader.urls")),
|
||||
path("api/groups/", include("apps.groups.urls")),
|
||||
]
|
||||
|
||||
if settings.DEBUG:
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 24 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 29 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 66 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1 +0,0 @@
|
||||
x
|
||||
@@ -1 +0,0 @@
|
||||
fake
|
||||
@@ -0,0 +1,150 @@
|
||||
# 010 — Mobile EPUB Reader
|
||||
|
||||
**Status:** Implemented
|
||||
**Created:** 2026-06-04
|
||||
|
||||
## Objective
|
||||
|
||||
Mirror the web reading experience (`frontend/src/pages/ReadingPage.tsx` and
|
||||
`frontend/src/components/reader/*`) inside the Expo app so users can open their
|
||||
uploaded library, read EPUBs with persisted progress and typography settings,
|
||||
and manage bookmarks/highlights — reusing the same Django REST API as the web
|
||||
client.
|
||||
|
||||
The web EPUB renderer (`react-reader` / epub.js) is DOM-only, so mobile renders
|
||||
EPUBs with `@epubjs-react-native/core`, which runs epub.js inside a
|
||||
`react-native-webview`. This keeps behavior (CFI locations, themes, font
|
||||
controls, TOC, annotations) close to web while staying inside the managed Expo
|
||||
workflow.
|
||||
|
||||
## Scope
|
||||
|
||||
### Mirrored from web
|
||||
|
||||
- EPUB rendering with swipe pagination (`flow: "paginated"`).
|
||||
- Resume position and debounced progress save (CFI + percentage).
|
||||
- Table of contents drawer with jump-to-chapter.
|
||||
- Reading settings: theme presets (light/sepia/paper/dark), font family, font
|
||||
size, line spacing — persisted to `/api/reader/settings/`.
|
||||
- Bookmarks: bookmark the current page, list/jump/delete, and create highlights
|
||||
from a text selection. Highlights are re-applied on open (best-effort).
|
||||
|
||||
### Deferred (not in this pass)
|
||||
|
||||
- PDF reading. PDF books show a placeholder pointing to the web reader.
|
||||
- Brightness and orientation-lock controls.
|
||||
- Per-highlight color picker (highlights use a single default color).
|
||||
- App-wide internationalization (web uses `react-i18n-lite`).
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
LibraryScreen (EBook list)
|
||||
| navigate("BookDetail", { ebookId })
|
||||
v
|
||||
BookDetailScreen ----------------> ReaderScreen ({ ebookId })
|
||||
|
|
||||
GET /api/books/ebooks/:id/ (format guard)
|
||||
|
|
||||
epub? --------------------- pdf? -> placeholder
|
||||
|
|
||||
EpubReaderView (ReaderProvider)
|
||||
|
|
||||
expo-file-system downloadAsync(file/, Bearer token) -> file:// uri
|
||||
|
|
||||
<Reader src=file:// fileSystem=useFileSystem flow="paginated" />
|
||||
|
|
||||
onLocationChange -> debounce 800ms -> PATCH progress/
|
||||
onSelected -> POST bookmarks/ (+ highlight annotation)
|
||||
useReader().toc -> goToLocation(href)
|
||||
settings change -> changeTheme / changeFontSize / changeFontFamily
|
||||
+ PATCH /api/reader/settings/ (debounced)
|
||||
```
|
||||
|
||||
The ebook file is downloaded to the app cache with an `Authorization` header
|
||||
(the `/file/` endpoint is JWT-protected) and the local `file://` URI is handed
|
||||
to the renderer — mirroring how the web client downloads a blob rather than
|
||||
using a public/signed URL.
|
||||
|
||||
## Mobile changes
|
||||
|
||||
| File | Role |
|
||||
|------|------|
|
||||
| `mobile/src/api/client.ts` | Adds `apiClient`, `saveTokens`, `loadTokens`, `getApiBaseUrl` |
|
||||
| `mobile/src/api/ebooks.ts` | `/api/books/ebooks/` list/detail/toc + `getFileUrl(id)` |
|
||||
| `mobile/src/api/reader.ts` | Reader settings + per-book progress (mirrors web `api/reader.ts`) |
|
||||
| `mobile/src/api/annotations.ts` | Bookmarks CRUD against `/api/annotations/bookmarks/` |
|
||||
| `mobile/src/types/reader.ts` | `ReadingSettings`, `ReadingProgress` (full reader shapes) |
|
||||
| `mobile/src/types/index.ts` | `AppStackParamList`, `Bookmark`, `CreateMarkerPayload` |
|
||||
| `mobile/src/hooks/useReadingSettings.ts` | Loads + debounced-saves reader settings |
|
||||
| `mobile/src/utils/epubTheme.ts` | Font stacks, theme palettes, `buildEpubTheme()` |
|
||||
| `mobile/src/navigation/AppStack.tsx` | Native stack: Tabs / BookDetail / Reader |
|
||||
| `mobile/src/screens/LibraryScreen.tsx` | Lists user EBooks (`ebooksApi.list`) |
|
||||
| `mobile/src/screens/BookDetailScreen.tsx` | Metadata + start/resume button |
|
||||
| `mobile/src/screens/ReaderScreen.tsx` | Format guard: EPUB view vs PDF placeholder |
|
||||
| `mobile/src/components/reader/EpubReaderView.tsx` | Reader, progress, bookmarks, settings wiring |
|
||||
| `mobile/src/components/reader/ReaderToolbar.tsx` | Title, chapter, progress bar, action buttons |
|
||||
| `mobile/src/components/reader/TocModal.tsx` | Table of contents sheet |
|
||||
| `mobile/src/components/reader/ReadingSettingsModal.tsx` | Theme/font/size/spacing controls |
|
||||
| `mobile/src/components/reader/BookmarksModal.tsx` | Bookmarks & highlights list |
|
||||
| `mobile/App.tsx` | Wraps the tree in `GestureHandlerRootView` |
|
||||
|
||||
Removed unused scaffolding: `mobile/src/navigation/AppNavigator.tsx`,
|
||||
`mobile/src/navigation/MainTabs.tsx`.
|
||||
|
||||
## API contracts (consumed)
|
||||
|
||||
| Method | Path | Purpose |
|
||||
|--------|------|---------|
|
||||
| GET | `/api/books/ebooks/` | User library list |
|
||||
| GET | `/api/books/ebooks/:id/` | EBook detail (format, progress, cover) |
|
||||
| GET | `/api/books/ebooks/:id/file/` | Stream EPUB bytes (JWT, owner) |
|
||||
| GET/PATCH | `/api/books/ebooks/:id/progress/` | Reading progress (`current_position`, `last_page`, `epub_location`) |
|
||||
| GET/PATCH | `/api/reader/settings/` | Reader typography/theme settings |
|
||||
| GET/POST/DELETE | `/api/annotations/bookmarks/` | Bookmarks & highlights (`ebook`, `epub_cfi`, `chapter_index`, ...) |
|
||||
|
||||
## Settings mapping (web -> mobile)
|
||||
|
||||
| Reader setting | Web (epub.js) | Mobile (`@epubjs-react-native/core`) |
|
||||
|----------------|---------------|--------------------------------------|
|
||||
| `theme` / colors | `themes.register/select` | `changeTheme(buildEpubTheme())` + `defaultTheme` |
|
||||
| `font_size` | `themes.fontSize` | `changeFontSize("Npx")` |
|
||||
| `font_family` | body font-family | `changeFontFamily(stack)` |
|
||||
| `line_height` | body line-height | `buildEpubTheme()` CSS rule |
|
||||
| `margin_width` | gap-based padding | not applied (deferred) |
|
||||
| `brightness` / `orientation_lock` | applied on web | deferred |
|
||||
|
||||
## Dependencies added
|
||||
|
||||
- `@epubjs-react-native/core@1.4.7`
|
||||
- `@epubjs-react-native/expo-file-system@1.1.4`
|
||||
- `react-native-webview@13.12.5`
|
||||
|
||||
(`react-native-gesture-handler`, `react-native-reanimated`, and
|
||||
`expo-file-system` were already present.)
|
||||
|
||||
## Configuration
|
||||
|
||||
| Env var | Purpose |
|
||||
|---------|---------|
|
||||
| `EXPO_PUBLIC_API_URL` | Backend base URL (e.g. `http://10.0.2.2:8000` on Android emulator, LAN IP on a device) |
|
||||
|
||||
## Compatibility notes
|
||||
|
||||
- The Expo file-system adapter (`@epubjs-react-native/expo-file-system`) depends
|
||||
only on `expo-file-system`, so the reader runs in Expo Go. (The library's
|
||||
bare adapter pulls native `@dr.pogodin/react-native-fs`; that path is not
|
||||
used here.)
|
||||
- React 19 / Expo SDK 52 may surface peer-dependency warnings for the
|
||||
`@epubjs-react-native/*` packages.
|
||||
|
||||
## Verification
|
||||
|
||||
- [ ] Log in; Library lists the user's uploaded EBooks with covers/progress.
|
||||
- [ ] Open an EPUB; it renders and paginates by swipe.
|
||||
- [ ] Reopen a book; it resumes at the last position.
|
||||
- [ ] Change theme/font/size/spacing; the page updates and persists across reopen.
|
||||
- [ ] Open the TOC and jump to a chapter.
|
||||
- [ ] Bookmark the current page; it appears in the bookmarks list and can be re-opened/deleted.
|
||||
- [ ] Select text to create a highlight; it persists and re-renders on reopen.
|
||||
- [ ] Open a PDF book; the placeholder is shown instead of a crash.
|
||||
@@ -1 +0,0 @@
|
||||
import{X as c,j as e}from"./index-BQiEVoRj.js";function h({bookTitle:s,chapterTitle:l,progress:a,onBack:t,onToggleToc:n,onToggleSettings:o,onToggleMarkers:i}){const{t:r}=c(),d=(a==null?void 0:a.percentage)??0;return e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"reader-top-bar",children:[t?e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:t,"aria-label":r("reader.backToLibraryAria"),children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M20 12H4M10 18l-6-6 6-6"})})}):e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:n,"aria-label":r("reader.tocAria"),children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),e.jsxs("div",{className:"reader-bar-title",children:[e.jsx("span",{className:"reader-bar-book",children:s}),e.jsx("span",{className:"reader-bar-chapter",children:l})]}),e.jsxs("div",{className:"reader-bar-actions",children:[t&&e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:n,"aria-label":r("reader.tocAria"),children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),i&&e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:i,"aria-label":r("annotations.inBookPanel"),children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})}),e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:o,"aria-label":r("reader.settingsAria"),children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"})]})})]})]}),e.jsx("div",{className:"reader-progress-bar",children:e.jsx("div",{className:"reader-progress-fill",style:{width:`${Math.min(d,100)}%`}})})]})}export{h as default};
|
||||
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
|
||||
import{X as m,j as e}from"./index-BQiEVoRj.js";const g=[{value:"sepia",labelKey:"reader.themeSepia"},{value:"dark",labelKey:"reader.themeDark"},{value:"light",labelKey:"reader.themeLight"},{value:"paper",labelKey:"reader.themePaper"}],u=[{value:"sans-serif",labelKey:"reader.fontSans"},{value:"serif",labelKey:"reader.fontSerif"},{value:"monospace",labelKey:"reader.fontMonospace"}],x=[{value:"auto",labelKey:"reader.orientationAuto"},{value:"portrait",labelKey:"reader.orientationPortrait"},{value:"landscape",labelKey:"reader.orientationLandscape"}];function v({settings:t,isOpen:c,onClose:d,onUpdate:o,onFlush:h}){const{t:s}=m(),n=()=>{h(),d()},i=(a,r)=>{o({[a]:r},"debounced")},l=(a,r)=>{o({[a]:r},"immediate")};return e.jsxs(e.Fragment,{children:[c&&e.jsx("div",{className:"settings-overlay",onClick:n,onKeyDown:a=>{a.key==="Escape"&&n()},role:"presentation"}),e.jsxs("aside",{className:`settings-drawer ${c?"settings-drawer--open":""}`,children:[e.jsxs("div",{className:"settings-header",children:[e.jsx("h2",{className:"settings-title",children:s("reader.settingsTitle")}),e.jsx("button",{type:"button",className:"settings-close-btn",onClick:n,"aria-label":s("reader.closeSettingsAria"),children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsxs("div",{className:"settings-body",children:[e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.theme")}),e.jsx("div",{className:"theme-grid",children:g.map(a=>e.jsx("button",{type:"button",className:`theme-btn ${t.theme===a.value?"theme-btn--active":""}`,onClick:()=>l("theme",a.value),children:s(a.labelKey)},a.value))})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.font")}),e.jsx("div",{className:"font-grid",children:u.map(a=>e.jsx("button",{type:"button",className:`font-btn ${t.font_family===a.value?"font-btn--active":""}`,onClick:()=>l("font_family",a.value),children:s(a.labelKey)},a.value))})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.fontSize",{size:String(t.font_size)})}),e.jsx("input",{type:"range",min:"12",max:"32",value:t.font_size,onChange:a=>i("font_size",Number(a.target.value)),className:"settings-slider","aria-label":s("reader.fontSizeAria")})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.lineHeight",{value:t.line_height.toFixed(1)})}),e.jsx("input",{type:"range",min:"1.2",max:"2.0",step:"0.1",value:t.line_height,onChange:a=>i("line_height",Number(a.target.value)),className:"settings-slider","aria-label":s("reader.lineHeightAria")})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.margins",{value:String(t.margin_width)})}),e.jsx("input",{type:"range",min:"8",max:"48",value:t.margin_width,onChange:a=>i("margin_width",Number(a.target.value)),className:"settings-slider","aria-label":s("reader.marginWidthAria")})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.brightness",{value:String(t.brightness)})}),e.jsx("input",{type:"range",min:"0",max:"100",value:t.brightness,onChange:a=>i("brightness",Number(a.target.value)),className:"settings-slider","aria-label":s("reader.brightnessAria")})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.orientation")}),e.jsx("div",{className:"orientation-grid",children:x.map(a=>e.jsx("button",{type:"button",className:`orientation-btn ${t.orientation_lock===a.value?"orientation-btn--active":""}`,onClick:()=>l("orientation_lock",a.value),children:s(a.labelKey)},a.value))})]})]})]})]})}export{v as default};
|
||||
@@ -12,13 +12,12 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.7.9",
|
||||
"dompurify": "^3.4.7",
|
||||
"react-router-dom": "^7.1.0",
|
||||
"pdfjs-dist": "^4.10.38",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-i18n-lite": "^1.0.10",
|
||||
"react-reader": "^2.0.15",
|
||||
"react-router-dom": "^7.1.0"
|
||||
"react-reader": "^2.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { lazy, Suspense, useState } from "react";
|
||||
import React, { lazy, Suspense } from "react";
|
||||
import { BrowserRouter, Navigate, Route, Routes, useParams } from "react-router-dom";
|
||||
import { AuthProvider, useAuth } from "./context/AuthContext";
|
||||
import { I18nProvider } from "./i18n/I18nProvider";
|
||||
@@ -13,14 +13,7 @@ const SettingsPage = lazy(() => import("./pages/Settings").then((m) => ({ defaul
|
||||
const BookmarksNotesPage = lazy(() => import("./components/annotations/BookmarksNotesPage").then((m) => ({ default: m.BookmarksNotesPage })));
|
||||
const ReadingPage = lazy(() => import("./pages/ReadingPage").then((m) => ({ default: m.default })));
|
||||
|
||||
const AuthPage = lazy(() =>
|
||||
import("./pages/AuthPage").then((m) => ({
|
||||
default: () => {
|
||||
const [isLogin, setIsLogin] = useState(true);
|
||||
return isLogin ? <m.LoginPage onToggle={() => setIsLogin(false)} /> : <m.RegisterPage onToggle={() => setIsLogin(true)} />;
|
||||
},
|
||||
})),
|
||||
);
|
||||
const AuthPage = lazy(() => import("./pages/AuthPage"));
|
||||
|
||||
function LoadingFallback() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -27,6 +27,3 @@ export async function createMarker(
|
||||
export async function deleteBookmark(id: string): Promise<void> {
|
||||
await api.delete(`/annotations/bookmarks/${id}/`);
|
||||
}
|
||||
|
||||
/** @deprecated Use createMarker */
|
||||
export const createBookmark = createMarker;
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import api from "./client";
|
||||
import type {
|
||||
GroupMeeting,
|
||||
MeetingReminder,
|
||||
NotificationPreferences,
|
||||
PaceStatus,
|
||||
ReadingGroup,
|
||||
} from "../types/notifications";
|
||||
|
||||
export const groupsApi = {
|
||||
async getPaceStatus(ebookId?: number): Promise<PaceStatus[]> {
|
||||
const params: Record<string, string> = {};
|
||||
if (ebookId) params.ebook_id = String(ebookId);
|
||||
const { data } = await api.get<PaceStatus[]>("/groups/notifications/pace/", { params });
|
||||
return data;
|
||||
},
|
||||
|
||||
async getPreferences(): Promise<NotificationPreferences> {
|
||||
const { data } = await api.get<NotificationPreferences>("/groups/notifications/preferences/");
|
||||
return data;
|
||||
},
|
||||
|
||||
async updatePreferences(
|
||||
prefs: Partial<NotificationPreferences>,
|
||||
): Promise<NotificationPreferences> {
|
||||
const { data } = await api.patch<NotificationPreferences>(
|
||||
"/groups/notifications/preferences/",
|
||||
prefs,
|
||||
);
|
||||
return data;
|
||||
},
|
||||
|
||||
async dismissPaceNotification(meetingId: number, ebookId: number): Promise<void> {
|
||||
await api.post("/groups/notifications/dismiss/", {
|
||||
meeting_id: meetingId,
|
||||
ebook_id: ebookId,
|
||||
});
|
||||
},
|
||||
|
||||
async getReminders(): Promise<MeetingReminder[]> {
|
||||
const { data } = await api.get<MeetingReminder[]>("/groups/notifications/reminders/");
|
||||
return data;
|
||||
},
|
||||
|
||||
async getGroups(): Promise<ReadingGroup[]> {
|
||||
const { data } = await api.get<{ count: number; results: ReadingGroup[] } | ReadingGroup[]>(
|
||||
"/groups/groups/",
|
||||
);
|
||||
if (Array.isArray(data)) return data;
|
||||
return data.results ?? [];
|
||||
},
|
||||
|
||||
async getUpcomingMeetings(): Promise<GroupMeeting[]> {
|
||||
const { data } = await api.get<GroupMeeting[]>("/groups/meetings/upcoming/");
|
||||
return data;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { booksApi } from "@/api/books";
|
||||
import { getReadingProgress } from "@/api/reader";
|
||||
import type { ReadingProgress } from "@/types/reader";
|
||||
|
||||
export async function loadEbookWithProgress(bookId: number): Promise<{
|
||||
progressData: ReadingProgress | null;
|
||||
blob: Blob;
|
||||
}> {
|
||||
const [progressData, blob] = await Promise.all([
|
||||
getReadingProgress(bookId).catch(() => null),
|
||||
booksApi.getEbookFile(bookId),
|
||||
]);
|
||||
return { progressData, blob };
|
||||
}
|
||||
@@ -1,22 +1,10 @@
|
||||
/**
|
||||
* API client for the reader module — reading settings, chapters, and progress.
|
||||
* API client for the reader module — reading settings and progress.
|
||||
* Uses the shared axios client so JWT auth is attached automatically.
|
||||
*/
|
||||
|
||||
import api from "./client";
|
||||
import type {
|
||||
ChapterDetail,
|
||||
ChapterSummary,
|
||||
ReadingProgress,
|
||||
ReadingSettings,
|
||||
} from "../types/reader";
|
||||
|
||||
interface TocChapter {
|
||||
id: number;
|
||||
title: string;
|
||||
index: number;
|
||||
href?: string;
|
||||
}
|
||||
import type { ReadingProgress, ReadingSettings } from "../types/reader";
|
||||
|
||||
export async function getReadingSettings(): Promise<ReadingSettings> {
|
||||
const { data } = await api.get<ReadingSettings>("/reader/settings/");
|
||||
@@ -30,39 +18,6 @@ export async function updateReadingSettings(
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getChapters(bookId: number): Promise<ChapterSummary[]> {
|
||||
const { data } = await api.get<{ chapters: TocChapter[] }>(
|
||||
`/books/ebooks/${bookId}/toc/`,
|
||||
);
|
||||
const chapters = data.chapters ?? [];
|
||||
return chapters.map((ch) => ({
|
||||
id: ch.id,
|
||||
book: bookId,
|
||||
title: ch.title,
|
||||
number: ch.index + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getChapterContent(
|
||||
bookId: number,
|
||||
chapterNumber: number,
|
||||
): Promise<ChapterDetail> {
|
||||
const { data } = await api.get<{
|
||||
page: number;
|
||||
chapter_title: string;
|
||||
content: string;
|
||||
}>(`/books/ebooks/${bookId}/content/`, { params: { page: chapterNumber } });
|
||||
return {
|
||||
id: chapterNumber,
|
||||
book: bookId,
|
||||
title: data.chapter_title ?? "",
|
||||
number: data.page ?? chapterNumber,
|
||||
content: data.content ?? "",
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
};
|
||||
}
|
||||
|
||||
export async function getReadingProgress(
|
||||
bookId: number,
|
||||
): Promise<ReadingProgress> {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
|
||||
interface MarkerPassageActionsProps {
|
||||
onGoToPassage: () => void;
|
||||
onDelete: () => void;
|
||||
}
|
||||
|
||||
export function MarkerPassageActions({ onGoToPassage, onDelete }: MarkerPassageActionsProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="annotation-actions">
|
||||
<button type="button" className="btn btn-sm" onClick={onGoToPassage}>
|
||||
{t("annotations.goToPassage")}
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={onDelete}>
|
||||
{t("common.delete")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
CollapsibleMarkerPassage,
|
||||
CollapsibleMarkerThought,
|
||||
} from "@/components/annotations/CollapsibleMarkerText";
|
||||
import { MarkerPassageActions } from "@/components/annotations/MarkerPassageActions";
|
||||
|
||||
interface MarkerThreadsViewProps {
|
||||
ebookIdFilter?: string;
|
||||
@@ -91,22 +92,10 @@ export function MarkerThreadsView({
|
||||
) : (
|
||||
<span className="annotation-kind-badge bookmark-badge">{t("annotations.bookmarkOnly")}</span>
|
||||
)}
|
||||
<div className="annotation-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => onGoToPassage(m.ebook_id, m.epub_cfi)}
|
||||
>
|
||||
{t("annotations.goToPassage")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() => removeBookmark(m.id)}
|
||||
>
|
||||
{t("common.delete")}
|
||||
</button>
|
||||
</div>
|
||||
<MarkerPassageActions
|
||||
onGoToPassage={() => onGoToPassage(m.ebook_id, m.epub_cfi)}
|
||||
onDelete={() => removeBookmark(m.id)}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
export { BookmarksNotesPage } from "./BookmarksNotesPage";
|
||||
export { MarkerThreadsView } from "./MarkerThreadsView";
|
||||
@@ -1,28 +0,0 @@
|
||||
import React from "react";
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
|
||||
interface LayoutProps {
|
||||
children: React.ReactNode;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export function Layout({
|
||||
children,
|
||||
title,
|
||||
}: LayoutProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const pageTitle = title ?? t("common.appName");
|
||||
|
||||
return (
|
||||
<div className="app-container">
|
||||
<header className="app-header">
|
||||
<h1 className="app-title">{pageTitle}</h1>
|
||||
<nav className="app-nav">
|
||||
<a href="/" className="nav-link">{t("annotations.home")}</a>
|
||||
<a href="/bookmarks-notes" className="nav-link">{t("annotations.bookmarksNotes")}</a>
|
||||
</nav>
|
||||
</header>
|
||||
<main className="app-main">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
|
||||
interface SimpleFormPageLayoutProps {
|
||||
title: string;
|
||||
onBack: () => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function SimpleFormPageLayout({ title, onBack, children }: SimpleFormPageLayoutProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||
<header style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24, padding: "16px 0", borderBottom: "1px solid #eee" }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBack}
|
||||
style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}
|
||||
>
|
||||
← {t("common.back")}
|
||||
</button>
|
||||
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>{title}</h1>
|
||||
</header>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export { Layout } from "./Layout";
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
import styles from "./FinishedBooksShelf.module.css";
|
||||
|
||||
export interface ShelfBook {
|
||||
interface ShelfBook {
|
||||
id: number;
|
||||
title: string;
|
||||
author: string;
|
||||
|
||||
@@ -2,14 +2,14 @@ import { useTranslation } from "react-i18n-lite";
|
||||
import { readingStatusKey } from "@/locales";
|
||||
import styles from "../../pages/Library.module.css";
|
||||
|
||||
export const LIBRARY_STATUS_COLORS: Record<string, { bg: string; text: string }> = {
|
||||
const LIBRARY_STATUS_COLORS: Record<string, { bg: string; text: string }> = {
|
||||
want_to_read: { bg: "#dbeafe", text: "#1d4ed8" },
|
||||
reading: { bg: "#dcfce7", text: "#16a34a" },
|
||||
finished: { bg: "#f3e8ff", text: "#9333ea" },
|
||||
dnf: { bg: "#fef3c7", text: "#b45309" },
|
||||
};
|
||||
|
||||
export interface LibraryBookCardData {
|
||||
interface LibraryBookCardData {
|
||||
id: number;
|
||||
title: string;
|
||||
author: string;
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
import { groupsApi } from "../api/groups";
|
||||
import type { PaceStatus } from "../types/notifications";
|
||||
|
||||
interface PaceNotificationProps {
|
||||
ebookId?: number;
|
||||
}
|
||||
|
||||
export function PaceNotification({ ebookId }: PaceNotificationProps) {
|
||||
const { t } = useTranslation();
|
||||
const [paceItems, setPaceItems] = useState<PaceStatus[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dismissed, setDismissed] = useState<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
try {
|
||||
const data = await groupsApi.getPaceStatus(ebookId);
|
||||
setPaceItems(data);
|
||||
} catch {
|
||||
// Silently fail — notifications are non-critical
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
void load();
|
||||
}, [ebookId]);
|
||||
|
||||
const handleDismiss = async (meetingId: number, itemEbookId: number) => {
|
||||
const key = `${meetingId}-${itemEbookId}`;
|
||||
setDismissed((prev) => new Set(prev).add(key));
|
||||
try {
|
||||
await groupsApi.dismissPaceNotification(meetingId, itemEbookId);
|
||||
} catch {
|
||||
// Best effort dismissal
|
||||
}
|
||||
};
|
||||
|
||||
if (loading || paceItems.length === 0) return null;
|
||||
|
||||
const visibleItems = paceItems.filter(
|
||||
(p) => !dismissed.has(`${p.meeting_id}-${p.ebook_id}`),
|
||||
);
|
||||
if (visibleItems.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 8, padding: "12px 0" }}>
|
||||
{visibleItems.map((item) => {
|
||||
const isBehind = item.status === "behind";
|
||||
const isAhead = item.status === "ahead" || item.status === "completed";
|
||||
const isOnTrack = item.status === "on_track";
|
||||
|
||||
const bgColor = isBehind ? "#fde8e8" : isAhead ? "#d4edda" : "#e8f4fd";
|
||||
const borderColor = isBehind ? "#e74c3c" : isAhead ? "#27ae60" : "#3498db";
|
||||
const textColor = isBehind ? "#a71d2a" : isAhead ? "#155724" : "#0c5460";
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${item.meeting_id}-${item.ebook_id}`}
|
||||
style={{
|
||||
background: bgColor,
|
||||
border: `1px solid ${borderColor}`,
|
||||
borderRadius: 8,
|
||||
padding: "12px 16px",
|
||||
display: "flex",
|
||||
alignItems: "flex-start",
|
||||
justifyContent: "space-between",
|
||||
gap: 12,
|
||||
}}
|
||||
>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 600, color: textColor, marginBottom: 4 }}>
|
||||
{isBehind
|
||||
? `Behind schedule — catch up ${item.sections_to_catch_up} section${item.sections_to_catch_up !== 1 ? "s" : ""}`
|
||||
: isOnTrack
|
||||
? "On track — keep going!"
|
||||
: item.status === "completed"
|
||||
? "Meeting target completed!"
|
||||
: "Ahead of schedule — great job!"}
|
||||
</div>
|
||||
<div style={{ fontSize: 13, color: textColor, opacity: 0.85 }}>
|
||||
{item.meeting_title || `Target: ${item.target_section_label || `Section ${item.target_section}`}`}
|
||||
{" — "}
|
||||
{item.ebook_title}
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: textColor, opacity: 0.7, marginTop: 2 }}>
|
||||
{isBehind
|
||||
? `Currently at section ${item.current_section}, need section ${item.target_section}`
|
||||
: `Section ${item.current_section} of ${item.target_section}`}
|
||||
{item.days_until_meeting > 0 &&
|
||||
` · ${item.days_until_meeting} day${item.days_until_meeting !== 1 ? "s" : ""} until meeting`}
|
||||
{item.days_until_meeting === 0 && " · Meeting today"}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDismiss(item.meeting_id, item.ebook_id)}
|
||||
style={{
|
||||
background: "none",
|
||||
border: "none",
|
||||
color: textColor,
|
||||
fontSize: 20,
|
||||
cursor: "pointer",
|
||||
padding: "0 4px",
|
||||
lineHeight: 1,
|
||||
opacity: 0.6,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
title="Dismiss"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { groupsApi } from "../../api/groups";
|
||||
import type { PaceStatus } from "../../types/notifications";
|
||||
|
||||
interface ReadingPaceBannerProps {
|
||||
ebookId: number;
|
||||
currentSection: number;
|
||||
}
|
||||
|
||||
export function ReadingPaceBanner({ ebookId, currentSection }: ReadingPaceBannerProps) {
|
||||
const [paceItems, setPaceItems] = useState<PaceStatus[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
try {
|
||||
const data = await groupsApi.getPaceStatus(ebookId);
|
||||
setPaceItems(data);
|
||||
} catch {
|
||||
// Silently fail
|
||||
}
|
||||
};
|
||||
void load();
|
||||
}, [ebookId, currentSection]);
|
||||
|
||||
if (paceItems.length === 0) return null;
|
||||
|
||||
// Only show if user is one section away from target
|
||||
const relevantItems = paceItems.filter(
|
||||
(p) => Math.abs(p.target_section - p.current_section) <= 1 && p.status !== "completed",
|
||||
);
|
||||
|
||||
if (relevantItems.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
|
||||
color: "#fff",
|
||||
padding: "10px 16px",
|
||||
fontSize: 13,
|
||||
fontWeight: 500,
|
||||
textAlign: "center",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 8,
|
||||
flexWrap: "wrap",
|
||||
position: "sticky",
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
}}
|
||||
>
|
||||
{relevantItems.map((item) => {
|
||||
const isAlmostThere = item.sections_to_catch_up === 1;
|
||||
const isAtTarget = item.sections_to_catch_up === 0;
|
||||
|
||||
return (
|
||||
<span key={item.meeting_id}>
|
||||
{isAtTarget
|
||||
? `You've reached the target for ${item.meeting_title || `Section ${item.target_section}`}!`
|
||||
: isAlmostThere
|
||||
? `Almost there! Just 1 section to go for ${item.meeting_title || `Section ${item.target_section}`}.`
|
||||
: `You should be on ${item.target_section_label || `Section ${item.target_section}`} by the upcoming meeting.`}
|
||||
{item.days_until_meeting > 0 &&
|
||||
` (${item.days_until_meeting} day${item.days_until_meeting !== 1 ? "s" : ""} left)`}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
CollapsibleMarkerPassage,
|
||||
CollapsibleMarkerThought,
|
||||
} from "@/components/annotations/CollapsibleMarkerText";
|
||||
import { MarkerPassageActions } from "@/components/annotations/MarkerPassageActions";
|
||||
|
||||
interface BookMarkersPanelProps {
|
||||
ebookId: number;
|
||||
@@ -67,18 +68,10 @@ export function BookMarkersPanel({
|
||||
) : (
|
||||
<span className="annotation-kind-badge bookmark-badge">{t("annotations.bookmarkOnly")}</span>
|
||||
)}
|
||||
<div className="annotation-actions">
|
||||
<button type="button" className="btn btn-sm" onClick={() => onGoToPassage(m)}>
|
||||
{t("annotations.goToPassage")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() => removeBookmark(m.id)}
|
||||
>
|
||||
{t("common.delete")}
|
||||
</button>
|
||||
</div>
|
||||
<MarkerPassageActions
|
||||
onGoToPassage={() => onGoToPassage(m)}
|
||||
onDelete={() => removeBookmark(m.id)}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* EpubReadingView — full-screen EPUB reading powered by react-reader (epub.js).
|
||||
*/
|
||||
|
||||
import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { lazy, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
import { EpubView, EpubViewStyle } from "react-reader";
|
||||
@@ -12,12 +12,17 @@ import { useEpubHighlights } from "../../hooks/useEpubHighlights";
|
||||
import { useEpubReader } from "../../hooks/useEpubReader";
|
||||
import { useEpubSelection } from "../../hooks/useEpubSelection";
|
||||
import { useReadingSettings } from "../../hooks/useReadingSettings";
|
||||
import { useReaderOrientationCss } from "../../hooks/useReaderOrientationCss";
|
||||
import { ReaderErrorScreen } from "./ReaderErrorScreen";
|
||||
import { ReaderLoadingScreen } from "./ReaderLoadingScreen";
|
||||
import { ReaderSuspenseShell } from "./ReaderSuspenseShell";
|
||||
import type { EBookDetail } from "../../types/book";
|
||||
import type { EpubTocItem } from "./TableOfContents";
|
||||
import { SelectionPopover } from "./SelectionPopover";
|
||||
import { BookMarkersPanel } from "./BookMarkersPanel";
|
||||
import { BookmarkReaderRail } from "./BookmarkReaderRail";
|
||||
import { ResumeReadingButton } from "./ResumeReadingButton";
|
||||
import { ReadingPaceBanner } from "../notifications/ReadingPaceBanner";
|
||||
import type { MarkerEntry } from "@/types";
|
||||
|
||||
const ReaderToolbar = lazy(() => import("./ReaderToolbar"));
|
||||
@@ -82,17 +87,7 @@ export function EpubReadingView({ book, bookId, initialEpubLocation }: EpubReadi
|
||||
applySettings(settings);
|
||||
}, [settings, applySettings]);
|
||||
|
||||
useEffect(() => {
|
||||
const root = document.documentElement;
|
||||
if (settings.orientation_lock !== "auto") {
|
||||
root.style.setProperty(
|
||||
"--reader-orientation",
|
||||
settings.orientation_lock === "portrait" ? "portrait" : "landscape",
|
||||
);
|
||||
} else {
|
||||
root.style.removeProperty("--reader-orientation");
|
||||
}
|
||||
}, [settings.orientation_lock]);
|
||||
useReaderOrientationCss(settings.orientation_lock);
|
||||
|
||||
const handleTocChanged = useCallback((toc: EpubTocItem[]) => {
|
||||
setTocItems(toc);
|
||||
@@ -122,34 +117,24 @@ export function EpubReadingView({ book, bookId, initialEpubLocation }: EpubReadi
|
||||
);
|
||||
|
||||
if (epubLoading) {
|
||||
return (
|
||||
<div className="reader-loading">
|
||||
<div className="spinner" />
|
||||
<p>{t("reader.loading")}</p>
|
||||
</div>
|
||||
);
|
||||
return <ReaderLoadingScreen />;
|
||||
}
|
||||
|
||||
if (epubError || !epubUrl) {
|
||||
return (
|
||||
<div className="reader-loading">
|
||||
<p className="reader-error">{epubError ?? t("reader.unableToOpen")}</p>
|
||||
<button type="button" className="back-button" onClick={() => navigate("/")}>
|
||||
{t("reader.backToLibrary")}
|
||||
</button>
|
||||
</div>
|
||||
<ReaderErrorScreen
|
||||
message={epubError ?? t("reader.unableToOpen")}
|
||||
onBack={() => navigate("/")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="reader-loading">
|
||||
<div className="spinner" />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="reader-container" data-theme={settings.theme}>
|
||||
<ReaderSuspenseShell theme={settings.theme}>
|
||||
<ReadingPaceBanner
|
||||
ebookId={bookId}
|
||||
currentSection={tocItems.length > 0 ? Math.max(1, Math.ceil((progress / 100) * tocItems.length)) : 0}
|
||||
/>
|
||||
<ReaderToolbar
|
||||
bookTitle={book.title}
|
||||
chapterTitle={chapterTitle || t("reader.reading")}
|
||||
@@ -235,7 +220,6 @@ export function EpubReadingView({ book, bookId, initialEpubLocation }: EpubReadi
|
||||
›
|
||||
</button>
|
||||
</main>
|
||||
</div>
|
||||
</Suspense>
|
||||
</ReaderSuspenseShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
interface PanelCloseButtonProps {
|
||||
className: string;
|
||||
onClick: () => void;
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
export function PanelCloseButton({ className, onClick, ariaLabel }: PanelCloseButtonProps) {
|
||||
return (
|
||||
<button type="button" className={className} onClick={onClick} aria-label={ariaLabel}>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="18" y1="6" x2="6" y2="18" />
|
||||
<line x1="6" y1="6" x2="18" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -2,13 +2,17 @@
|
||||
* PdfReadingView — full-screen PDF reading powered by PDF.js.
|
||||
*/
|
||||
|
||||
import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { lazy, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
import { useAnnotations } from "@/context/AnnotationsContext";
|
||||
import { useBookmarkRailLayout } from "../../hooks/useBookmarkRailLayout";
|
||||
import { usePdfReader } from "../../hooks/usePdfReader";
|
||||
import { useReadingSettings } from "../../hooks/useReadingSettings";
|
||||
import { useReaderOrientationCss } from "../../hooks/useReaderOrientationCss";
|
||||
import { ReaderErrorScreen } from "./ReaderErrorScreen";
|
||||
import { ReaderLoadingScreen } from "./ReaderLoadingScreen";
|
||||
import { ReaderSuspenseShell } from "./ReaderSuspenseShell";
|
||||
import { useToast } from "../../hooks/useToast";
|
||||
import { booksApi } from "../../api/books";
|
||||
import type { EBookDetail } from "../../types/book";
|
||||
@@ -20,6 +24,7 @@ import { BookmarkReaderRail } from "./BookmarkReaderRail";
|
||||
import { ResumeReadingButton } from "./ResumeReadingButton";
|
||||
import { PdfLimitationsNotice } from "./PdfLimitationsNotice";
|
||||
import { PdfViewer } from "./PdfViewer";
|
||||
import { ReadingPaceBanner } from "../notifications/ReadingPaceBanner";
|
||||
import type { MarkerEntry } from "@/types";
|
||||
|
||||
const ReaderToolbar = lazy(() => import("./ReaderToolbar"));
|
||||
@@ -96,17 +101,7 @@ export function PdfReadingView({ book, bookId, initialAnchor }: PdfReadingViewPr
|
||||
);
|
||||
}, [bookId, pageCount, t]);
|
||||
|
||||
useEffect(() => {
|
||||
const root = document.documentElement;
|
||||
if (settings.orientation_lock !== "auto") {
|
||||
root.style.setProperty(
|
||||
"--reader-orientation",
|
||||
settings.orientation_lock === "portrait" ? "portrait" : "landscape",
|
||||
);
|
||||
} else {
|
||||
root.style.removeProperty("--reader-orientation");
|
||||
}
|
||||
}, [settings.orientation_lock]);
|
||||
useReaderOrientationCss(settings.orientation_lock);
|
||||
|
||||
const handleTocNavigate = useCallback(
|
||||
(href: string) => {
|
||||
@@ -165,36 +160,21 @@ export function PdfReadingView({ book, bookId, initialAnchor }: PdfReadingViewPr
|
||||
}, [bookMarkers, currentPage]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="reader-loading">
|
||||
<div className="spinner" />
|
||||
<p>{t("reader.loading")}</p>
|
||||
</div>
|
||||
);
|
||||
return <ReaderLoadingScreen />;
|
||||
}
|
||||
|
||||
if (error || !pdfDocument) {
|
||||
const message =
|
||||
error === "PDF_PASSWORD" ? t("reader.pdfPassword") : (error ?? t("reader.unableToOpen"));
|
||||
return (
|
||||
<div className="reader-loading">
|
||||
<p className="reader-error">{message}</p>
|
||||
<button type="button" className="back-button" onClick={() => navigate("/")}>
|
||||
{t("reader.backToLibrary")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
return <ReaderErrorScreen message={message} onBack={() => navigate("/")} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="reader-loading">
|
||||
<div className="spinner" />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="reader-container" data-theme={settings.theme}>
|
||||
<ReaderSuspenseShell theme={settings.theme}>
|
||||
<ReadingPaceBanner
|
||||
ebookId={bookId}
|
||||
currentSection={currentPage}
|
||||
/>
|
||||
<ReaderToolbar
|
||||
bookTitle={book.title}
|
||||
chapterTitle={chapterTitle || t("reader.reading")}
|
||||
@@ -270,7 +250,6 @@ export function PdfReadingView({ book, bookId, initialAnchor }: PdfReadingViewPr
|
||||
›
|
||||
</button>
|
||||
</main>
|
||||
</div>
|
||||
</Suspense>
|
||||
</ReaderSuspenseShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
|
||||
interface ReaderErrorScreenProps {
|
||||
message: string;
|
||||
onBack: () => void;
|
||||
}
|
||||
|
||||
export function ReaderErrorScreen({ message, onBack }: ReaderErrorScreenProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="reader-loading">
|
||||
<p className="reader-error">{message}</p>
|
||||
<button type="button" className="back-button" onClick={onBack}>
|
||||
{t("reader.backToLibrary")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
|
||||
interface ReaderLoadingScreenProps {
|
||||
showMessage?: boolean;
|
||||
}
|
||||
|
||||
export function ReaderLoadingScreen({ showMessage = true }: ReaderLoadingScreenProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="reader-loading">
|
||||
<div className="spinner" />
|
||||
{showMessage && <p>{t("reader.loading")}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Suspense, type ReactNode } from "react";
|
||||
import { ReaderLoadingScreen } from "./ReaderLoadingScreen";
|
||||
|
||||
interface ReaderSuspenseShellProps {
|
||||
theme: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ReaderSuspenseShell({ theme, children }: ReaderSuspenseShellProps) {
|
||||
return (
|
||||
<Suspense fallback={<ReaderLoadingScreen showMessage={false} />}>
|
||||
<div className="reader-container" data-theme={theme}>
|
||||
{children}
|
||||
</div>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
|
||||
interface ReaderTocButtonProps {
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export function ReaderTocButton({ onClick }: ReaderTocButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="reader-bar-btn"
|
||||
onClick={onClick}
|
||||
aria-label={t("reader.tocAria")}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="3" y1="6" x2="21" y2="6" />
|
||||
<line x1="3" y1="12" x2="21" y2="12" />
|
||||
<line x1="3" y1="18" x2="21" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
import type { ReadingProgress } from "../../types/reader";
|
||||
import { ReaderTocButton } from "./ReaderTocButton";
|
||||
|
||||
interface ReaderToolbarProps {
|
||||
bookTitle: string;
|
||||
@@ -47,38 +48,14 @@ export default function ReaderToolbar({
|
||||
</svg>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="reader-bar-btn"
|
||||
onClick={onToggleToc}
|
||||
aria-label={t("reader.tocAria")}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="3" y1="6" x2="21" y2="6" />
|
||||
<line x1="3" y1="12" x2="21" y2="12" />
|
||||
<line x1="3" y1="18" x2="21" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
<ReaderTocButton onClick={onToggleToc} />
|
||||
)}
|
||||
<div className="reader-bar-title">
|
||||
<span className="reader-bar-book">{bookTitle}</span>
|
||||
<span className="reader-bar-chapter">{chapterTitle}</span>
|
||||
</div>
|
||||
<div className="reader-bar-actions">
|
||||
{onBack && (
|
||||
<button
|
||||
type="button"
|
||||
className="reader-bar-btn"
|
||||
onClick={onToggleToc}
|
||||
aria-label={t("reader.tocAria")}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="3" y1="6" x2="21" y2="6" />
|
||||
<line x1="3" y1="12" x2="21" y2="12" />
|
||||
<line x1="3" y1="18" x2="21" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
{onBack && <ReaderTocButton onClick={onToggleToc} />}
|
||||
{onBookmarkPage && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
ThemePreset,
|
||||
} from "../../types/reader";
|
||||
import type { SettingsPersistMode } from "../../hooks/useReadingSettings";
|
||||
import { PanelCloseButton } from "./PanelCloseButton";
|
||||
|
||||
interface ReadingSettingsPanelProps {
|
||||
format?: "epub" | "pdf";
|
||||
@@ -89,17 +90,11 @@ export default function ReadingSettingsPanel({
|
||||
>
|
||||
<div className="settings-header">
|
||||
<h2 className="settings-title">{t("reader.settingsTitle")}</h2>
|
||||
<button
|
||||
type="button"
|
||||
<PanelCloseButton
|
||||
className="settings-close-btn"
|
||||
onClick={handleClose}
|
||||
aria-label={t("reader.closeSettingsAria")}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="18" y1="6" x2="6" y2="18" />
|
||||
<line x1="6" y1="6" x2="18" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
ariaLabel={t("reader.closeSettingsAria")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="settings-body">
|
||||
@@ -124,7 +119,7 @@ export default function ReadingSettingsPanel({
|
||||
{format === "pdf" && onPdfScaleChange && (
|
||||
<section className="settings-section">
|
||||
<h3 className="settings-section-title">
|
||||
{t("reader.pdfZoom", { value: Math.round(pdfScale * 100) })}
|
||||
{t("reader.pdfZoom", { value: String(Math.round(pdfScale * 100)) })}
|
||||
</h3>
|
||||
<input
|
||||
type="range"
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
import type { KeyboardEvent } from "react";
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
import { PanelCloseButton } from "./PanelCloseButton";
|
||||
|
||||
export interface EpubTocItem {
|
||||
label: string;
|
||||
@@ -73,17 +74,11 @@ export default function TableOfContents({
|
||||
<aside className={`toc-drawer ${isOpen ? "toc-drawer--open" : ""}`}>
|
||||
<div className="toc-header">
|
||||
<h2 className="toc-title">{t("reader.tocTitle")}</h2>
|
||||
<button
|
||||
type="button"
|
||||
<PanelCloseButton
|
||||
className="toc-close-btn"
|
||||
onClick={onClose}
|
||||
aria-label={t("reader.closeTocAria")}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="18" y1="6" x2="6" y2="18" />
|
||||
<line x1="6" y1="6" x2="18" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
ariaLabel={t("reader.closeTocAria")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<nav className="toc-list">
|
||||
|
||||
@@ -48,7 +48,7 @@ export function highlightBackgroundStyle(color: string): {
|
||||
};
|
||||
}
|
||||
|
||||
export const BOOKMARK_COLOR_STORAGE_KEY = "cloud-reader:lastBookmarkHighlightColor";
|
||||
const BOOKMARK_COLOR_STORAGE_KEY = "cloud-reader:lastBookmarkHighlightColor";
|
||||
|
||||
export function loadLastHighlightColor(): string {
|
||||
try {
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "react";
|
||||
import type { Bookmark, CreateMarkerPayload, MarkerEntry, MarkersByBook } from "@/types";
|
||||
import * as annotationsApi from "@/api/annotations";
|
||||
import { bookmarkToMarkerEntry, groupMarkersByBook, sortMarkers } from "@/utils/markers";
|
||||
import { bookmarkToMarkerEntry, groupMarkersByBook, sortBookmarks } from "@/utils/markers";
|
||||
|
||||
interface AnnotationsState {
|
||||
bookmarks: Bookmark[];
|
||||
@@ -37,10 +37,7 @@ function annotationsReducer(
|
||||
case "FETCH_BOOKMARKS_START":
|
||||
return { ...state, bookmarksLoading: true, error: null };
|
||||
case "FETCH_BOOKMARKS_SUCCESS": {
|
||||
const sorted = [...action.payload].sort((a, b) => {
|
||||
if (a.chapter_index !== b.chapter_index) return a.chapter_index - b.chapter_index;
|
||||
return a.epub_cfi.localeCompare(b.epub_cfi);
|
||||
});
|
||||
const sorted = [...action.payload].sort(sortBookmarks);
|
||||
return { ...state, bookmarks: sorted, bookmarksLoading: false };
|
||||
}
|
||||
case "SET_ERROR":
|
||||
@@ -51,10 +48,7 @@ function annotationsReducer(
|
||||
bookmarks: state.bookmarks.filter((b) => b.id !== action.payload),
|
||||
};
|
||||
case "ADD_BOOKMARK": {
|
||||
const next = [...state.bookmarks, action.payload].sort((a, b) => {
|
||||
if (a.chapter_index !== b.chapter_index) return a.chapter_index - b.chapter_index;
|
||||
return a.epub_cfi.localeCompare(b.epub_cfi);
|
||||
});
|
||||
const next = [...state.bookmarks, action.payload].sort(sortBookmarks);
|
||||
return { ...state, bookmarks: next };
|
||||
}
|
||||
default:
|
||||
@@ -105,7 +99,7 @@ export function AnnotationsProvider({
|
||||
}, []);
|
||||
|
||||
const markers = useMemo(
|
||||
() => state.bookmarks.map(bookmarkToMarkerEntry).sort(sortMarkers),
|
||||
() => [...state.bookmarks].sort(sortBookmarks).map(bookmarkToMarkerEntry),
|
||||
[state.bookmarks],
|
||||
);
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
export { usePaginatedQuery } from "./usePaginatedQuery";
|
||||
export { useDebounce } from "./useDebounce";
|
||||
export { useVoiceSearch } from "./useVoiceSearch";
|
||||
export { useMediaQuery } from "./useMediaQuery";
|
||||
@@ -3,8 +3,8 @@
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { booksApi } from "../api/books";
|
||||
import { getReadingProgress, updateReadingProgress } from "../api/reader";
|
||||
import { loadEbookWithProgress } from "../api/loadEbookWithProgress";
|
||||
import { updateReadingProgress } from "../api/reader";
|
||||
import type { ReadingProgress, ReadingSettings } from "../types/reader";
|
||||
import {
|
||||
applyRenditionSettings,
|
||||
@@ -197,10 +197,7 @@ export function useEpubReader(
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [progressData, blob] = await Promise.all([
|
||||
getReadingProgress(bookId).catch(() => null),
|
||||
booksApi.getEbookFile(bookId),
|
||||
]);
|
||||
const { progressData, blob } = await loadEbookWithProgress(bookId);
|
||||
if (cancelled) return;
|
||||
|
||||
blobUrl = URL.createObjectURL(blob);
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import { useState, useCallback, useRef, useEffect } from "react";
|
||||
import type { PaginatedResponse } from "@/types";
|
||||
|
||||
interface UsePaginatedQueryOptions<T> {
|
||||
fetchFn: (cursor?: string) => Promise<PaginatedResponse<T>>;
|
||||
}
|
||||
|
||||
interface UsePaginatedQueryResult<T> {
|
||||
items: T[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
hasMore: boolean;
|
||||
loadMore: () => Promise<void>;
|
||||
refresh: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for paginated list fetching with infinite scroll support.
|
||||
*/
|
||||
export function usePaginatedQuery<T>({
|
||||
fetchFn,
|
||||
}: UsePaginatedQueryOptions<T>): UsePaginatedQueryResult<T> {
|
||||
const [items, setItems] = useState<T[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [nextCursor, setNextCursor] = useState<string | null>(null);
|
||||
const loadingRef = useRef(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetchFn();
|
||||
setItems(response.results);
|
||||
setNextCursor(response.next);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to fetch data");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [fetchFn]);
|
||||
|
||||
const loadMore = useCallback(async () => {
|
||||
if (!nextCursor || loadingRef.current) return;
|
||||
loadingRef.current = true;
|
||||
try {
|
||||
const response = await fetchFn(nextCursor);
|
||||
setItems((prev) => [...prev, ...response.results]);
|
||||
setNextCursor(response.next);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to load more");
|
||||
} finally {
|
||||
loadingRef.current = false;
|
||||
}
|
||||
}, [nextCursor, fetchFn]);
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return {
|
||||
items,
|
||||
loading,
|
||||
error,
|
||||
hasMore: nextCursor !== null,
|
||||
loadMore,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -3,8 +3,8 @@
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { booksApi } from "../api/books";
|
||||
import { getReadingProgress, updateReadingProgress } from "../api/reader";
|
||||
import { loadEbookWithProgress } from "../api/loadEbookWithProgress";
|
||||
import { updateReadingProgress } from "../api/reader";
|
||||
import type { ReadingProgress } from "../types/reader";
|
||||
import { parsePdfAnchor } from "../utils/pdfAnchor";
|
||||
import { pdfjs, type PdfDocumentProxy } from "../utils/pdfjsSetup";
|
||||
@@ -175,10 +175,7 @@ export function usePdfReader(
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [progressData, blob] = await Promise.all([
|
||||
getReadingProgress(bookId).catch(() => null),
|
||||
booksApi.getEbookFile(bookId),
|
||||
]);
|
||||
const { progressData, blob } = await loadEbookWithProgress(bookId);
|
||||
if (cancelled) return;
|
||||
|
||||
const loadingTask = pdfjs.getDocument({ data: await blob.arrayBuffer() });
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useEffect } from "react";
|
||||
import type { ReadingSettings } from "@/types/reader";
|
||||
|
||||
export function useReaderOrientationCss(orientationLock: ReadingSettings["orientation_lock"]): void {
|
||||
useEffect(() => {
|
||||
const root = document.documentElement;
|
||||
if (orientationLock !== "auto") {
|
||||
root.style.setProperty(
|
||||
"--reader-orientation",
|
||||
orientationLock === "portrait" ? "portrait" : "landscape",
|
||||
);
|
||||
} else {
|
||||
root.style.removeProperty("--reader-orientation");
|
||||
}
|
||||
}, [orientationLock]);
|
||||
}
|
||||
@@ -36,7 +36,7 @@ const DEFAULT_SETTINGS: ReadingSettings = {
|
||||
|
||||
const SAVE_DEBOUNCE_MS = 600;
|
||||
|
||||
export function applyReadingCssVariables(settings: ReadingSettings): void {
|
||||
function applyReadingCssVariables(settings: ReadingSettings): void {
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty("--reader-bg", settings.background_color);
|
||||
root.style.setProperty("--reader-text", settings.text_color);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
import { booksApi } from "../api/books";
|
||||
import { getApiErrorMessage } from "../api/errors";
|
||||
import { SimpleFormPageLayout } from "../components/layout/SimpleFormPageLayout";
|
||||
|
||||
export function AddBookPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -33,11 +34,7 @@ export function AddBookPage() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||
<header style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24, padding: "16px 0", borderBottom: "1px solid #eee" }}>
|
||||
<button onClick={() => navigate("/")} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>← {t("common.back")}</button>
|
||||
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>{t("addBook.title")}</h1>
|
||||
</header>
|
||||
<SimpleFormPageLayout title={t("addBook.title")} onBack={() => navigate("/")}>
|
||||
<form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
|
||||
{error && <div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14 }}>{error}</div>}
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||
@@ -55,6 +52,6 @@ export function AddBookPage() {
|
||||
</div>
|
||||
<button type="submit" disabled={uploading} style={{ padding: "12px 24px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 16, fontWeight: 600, cursor: "pointer", opacity: uploading ? 0.6 : 1, marginTop: 8 }}>{uploading ? t("addBook.uploading") : t("addBook.upload")}</button>
|
||||
</form>
|
||||
</div>
|
||||
</SimpleFormPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -56,5 +56,7 @@ function AuthForm({ isLogin, onToggle }: { isLogin: boolean; onToggle: () => voi
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginPage({ onToggle }: { onToggle: () => void }) { return <AuthForm isLogin={true} onToggle={onToggle} />; }
|
||||
export function RegisterPage({ onToggle }: { onToggle: () => void }) { return <AuthForm isLogin={false} onToggle={onToggle} />; }
|
||||
export default function AuthPage() {
|
||||
const [isLogin, setIsLogin] = useState(true);
|
||||
return <AuthForm isLogin={isLogin} onToggle={() => setIsLogin((v) => !v)} />;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import { useVoiceSearch } from "../hooks/useVoiceSearch";
|
||||
import { useMediaQuery, BREAKPOINTS } from "../hooks/useMediaQuery";
|
||||
import { SearchSuggestions } from "../components/search/SearchSuggestions";
|
||||
import { BookContextMenu } from "../components/BookContextMenu";
|
||||
import { PaceNotification } from "../components/notifications/PaceNotification";
|
||||
|
||||
interface FilterState {
|
||||
genre: string;
|
||||
@@ -57,7 +58,6 @@ export function LibraryPage() {
|
||||
const [filters, setFilters] = useState<FilterState>({ genre: "", author: "", reading_status: "" });
|
||||
const [genres, setGenres] = useState<string[]>([]);
|
||||
const [authors, setAuthors] = useState<string[]>([]);
|
||||
const [totalCount, setTotalCount] = useState(0);
|
||||
const [showFilters, setShowFilters] = useState(false);
|
||||
const [showSuggestions, setShowSuggestions] = useState(false);
|
||||
const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
|
||||
@@ -95,11 +95,9 @@ export function LibraryPage() {
|
||||
items = items.filter((b) => b.reading_status === params.reading_status);
|
||||
}
|
||||
setBooks(items);
|
||||
setTotalCount(items.length);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t("library.loadFailed"));
|
||||
setBooks([]);
|
||||
setTotalCount(0);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -169,7 +167,6 @@ export function LibraryPage() {
|
||||
refreshFilterOptions(next);
|
||||
return next;
|
||||
});
|
||||
setTotalCount((count) => Math.max(0, count - 1));
|
||||
}, [refreshFilterOptions]);
|
||||
|
||||
const handleBookContextMenu = useCallback((e: React.MouseEvent, book: LibraryBook) => {
|
||||
@@ -260,6 +257,9 @@ export function LibraryPage() {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Pace Notifications */}
|
||||
<PaceNotification />
|
||||
|
||||
{/* Search Bar */}
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
|
||||
|
||||
@@ -2,8 +2,11 @@ import { useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18n-lite";
|
||||
import { booksApi } from "../api/books";
|
||||
import { groupsApi } from "../api/groups";
|
||||
import type { ReadingSettings } from "../types/book";
|
||||
import type { NotificationPreferences } from "../types/notifications";
|
||||
import type { SupportedLanguage } from "../locales";
|
||||
import { SimpleFormPageLayout } from "../components/layout/SimpleFormPageLayout";
|
||||
|
||||
const BG_COLORS = [
|
||||
{ value: "#ffffff", labelKey: "settings.bgWhite" },
|
||||
@@ -16,6 +19,7 @@ export function SettingsPage() {
|
||||
const { t, language, setLanguage } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [settings, setSettings] = useState<ReadingSettings | null>(null);
|
||||
const [notifPrefs, setNotifPrefs] = useState<NotificationPreferences | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -23,7 +27,14 @@ export function SettingsPage() {
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
try { const data = await booksApi.getSettings(); setSettings(data); }
|
||||
try {
|
||||
const [data, notifData] = await Promise.all([
|
||||
booksApi.getSettings(),
|
||||
groupsApi.getPreferences(),
|
||||
]);
|
||||
setSettings(data);
|
||||
setNotifPrefs(notifData);
|
||||
}
|
||||
catch (err) { setError(err instanceof Error ? err.message : t("settings.loadFailed")); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
@@ -31,9 +42,15 @@ export function SettingsPage() {
|
||||
}, [t]);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!settings) return;
|
||||
if (!settings || !notifPrefs) return;
|
||||
setSaving(true); setError(null); setSuccess(false);
|
||||
try { await booksApi.updateSettings(settings); setSuccess(true); setTimeout(() => setSuccess(false), 2000); }
|
||||
try {
|
||||
await Promise.all([
|
||||
booksApi.updateSettings(settings),
|
||||
groupsApi.updatePreferences(notifPrefs),
|
||||
]);
|
||||
setSuccess(true); setTimeout(() => setSuccess(false), 2000);
|
||||
}
|
||||
catch (err) { setError(err instanceof Error ? err.message : t("settings.saveFailed")); }
|
||||
finally { setSaving(false); }
|
||||
};
|
||||
@@ -41,11 +58,7 @@ export function SettingsPage() {
|
||||
if (loading) return <div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}><p>{t("settings.loading")}</p></div>;
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||
<header style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24, padding: "16px 0", borderBottom: "1px solid #eee" }}>
|
||||
<button onClick={() => navigate("/")} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>← {t("common.back")}</button>
|
||||
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>{t("settings.title")}</h1>
|
||||
</header>
|
||||
<SimpleFormPageLayout title={t("settings.title")} onBack={() => navigate("/")}>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
|
||||
{error && <div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14 }}>{error}</div>}
|
||||
{success && <div style={{ background: "#d4edda", padding: 12, borderRadius: 6, color: "#155724", fontSize: 14 }}>{t("settings.saved")}</div>}
|
||||
@@ -88,8 +101,50 @@ export function SettingsPage() {
|
||||
</div>
|
||||
</>}
|
||||
|
||||
{notifPrefs && <>
|
||||
<div style={{ borderTop: "1px solid #e5e7eb", paddingTop: 20 }}>
|
||||
<h3 style={{ fontSize: 16, fontWeight: 600, color: "#1f2937", marginBottom: 16 }}>
|
||||
Notification Settings
|
||||
</h3>
|
||||
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 14, color: "#374151", cursor: "pointer" }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={notifPrefs.pace_notifications_enabled}
|
||||
onChange={(e) => setNotifPrefs({ ...notifPrefs, pace_notifications_enabled: e.target.checked })}
|
||||
style={{ width: 18, height: 18, cursor: "pointer" }}
|
||||
/>
|
||||
Enable pace notifications
|
||||
</label>
|
||||
|
||||
<label style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 14, color: "#374151", cursor: "pointer" }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={notifPrefs.reminder_enabled}
|
||||
onChange={(e) => setNotifPrefs({ ...notifPrefs, reminder_enabled: e.target.checked })}
|
||||
style={{ width: 18, height: 18, cursor: "pointer" }}
|
||||
/>
|
||||
Enable pre-meeting reminders (24h before)
|
||||
</label>
|
||||
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>Notification frequency</label>
|
||||
<select
|
||||
value={notifPrefs.frequency}
|
||||
onChange={(e) => setNotifPrefs({ ...notifPrefs, frequency: e.target.value as NotificationPreferences["frequency"] })}
|
||||
style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 16, background: "#fff", outline: "none" }}
|
||||
>
|
||||
<option value="daily">Daily</option>
|
||||
<option value="weekly">Weekly</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>}
|
||||
|
||||
<button onClick={handleSave} disabled={saving} style={{ padding: "12px 24px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 16, fontWeight: 600, cursor: "pointer", opacity: saving ? 0.6 : 1, marginTop: 8 }}>{saving ? t("common.saving") : t("settings.saveSettings")}</button>
|
||||
</div>
|
||||
</div>
|
||||
</SimpleFormPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -102,11 +102,3 @@ export interface BookSearchParams {
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export const READING_STATUS_OPTIONS: { value: string; label: string }[] = [
|
||||
{ value: "", label: "All Statuses" },
|
||||
{ value: "want_to_read", label: "Want to Read" },
|
||||
{ value: "reading", label: "Reading" },
|
||||
{ value: "finished", label: "Finished" },
|
||||
{ value: "dnf", label: "Did Not Finish" },
|
||||
];
|
||||
@@ -1,29 +1,5 @@
|
||||
/** Core domain types for Cloud Reader */
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
email: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface Book {
|
||||
id: string;
|
||||
title: string;
|
||||
author: string;
|
||||
total_pages: number;
|
||||
cover_image: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface BookSummary {
|
||||
id: string;
|
||||
title: string;
|
||||
author: string;
|
||||
total_pages: number;
|
||||
cover_image: string;
|
||||
}
|
||||
|
||||
export interface Bookmark {
|
||||
id: string;
|
||||
ebook: number;
|
||||
@@ -39,17 +15,6 @@ export interface Bookmark {
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface Note {
|
||||
id: string;
|
||||
book: string;
|
||||
book_title: string;
|
||||
page: number;
|
||||
location_text: string;
|
||||
content: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface CreateMarkerPayload {
|
||||
ebook: number;
|
||||
epub_cfi: string;
|
||||
@@ -60,18 +25,6 @@ export interface CreateMarkerPayload {
|
||||
highlight_color?: string;
|
||||
}
|
||||
|
||||
/** @deprecated Legacy note create */
|
||||
export interface CreateNotePayload {
|
||||
book: string;
|
||||
page: number;
|
||||
location_text?: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface UpdateNotePayload {
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
count: number;
|
||||
next: string | null;
|
||||
@@ -79,11 +32,6 @@ export interface PaginatedResponse<T> {
|
||||
results: T[];
|
||||
}
|
||||
|
||||
export interface TokenResponse {
|
||||
access: string;
|
||||
refresh: string;
|
||||
}
|
||||
|
||||
export interface MarkerEntry {
|
||||
id: string;
|
||||
ebook_id: number;
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
export interface PaceStatus {
|
||||
meeting_id: number;
|
||||
meeting_title: string;
|
||||
scheduled_at: string;
|
||||
target_section: number;
|
||||
target_section_label: string;
|
||||
current_section: number;
|
||||
ahead_behind_delta: number;
|
||||
status: "ahead" | "behind" | "on_track" | "completed";
|
||||
days_until_meeting: number;
|
||||
sections_to_catch_up: number;
|
||||
ebook_id: number;
|
||||
ebook_title: string;
|
||||
}
|
||||
|
||||
export interface NotificationPreferences {
|
||||
pace_notifications_enabled: boolean;
|
||||
reminder_enabled: boolean;
|
||||
frequency: "daily" | "weekly";
|
||||
}
|
||||
|
||||
export interface MeetingReminder {
|
||||
meeting_id: number;
|
||||
meeting_title: string;
|
||||
scheduled_at: string;
|
||||
target_section: number;
|
||||
target_section_label: string;
|
||||
group_name: string;
|
||||
hours_until: number;
|
||||
ebook_id: number;
|
||||
ebook_title: string;
|
||||
}
|
||||
|
||||
export interface ReadingGroup {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
book: number | null;
|
||||
ebook: number | null;
|
||||
created_by: number;
|
||||
created_at: string;
|
||||
member_count: number;
|
||||
meeting_count: number;
|
||||
}
|
||||
|
||||
export interface GroupMeeting {
|
||||
id: number;
|
||||
group: number;
|
||||
group_name: string;
|
||||
title: string;
|
||||
scheduled_at: string;
|
||||
target_section: number;
|
||||
target_section_label: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface GroupMembership {
|
||||
id: number;
|
||||
user: number;
|
||||
user_email: string;
|
||||
group: number;
|
||||
group_name: string;
|
||||
role: "admin" | "member";
|
||||
joined_at: string;
|
||||
}
|
||||
@@ -3,19 +3,6 @@
|
||||
* Reading view, settings, chapters, and progress types.
|
||||
*/
|
||||
|
||||
export interface ChapterSummary {
|
||||
id: number;
|
||||
book: number;
|
||||
title: string;
|
||||
number: number;
|
||||
}
|
||||
|
||||
export interface ChapterDetail extends ChapterSummary {
|
||||
content: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ReadingSettings {
|
||||
font_family: "sans-serif" | "serif" | "monospace";
|
||||
font_size: number;
|
||||
|
||||
@@ -55,7 +55,10 @@ export function ebookMatchesQuery(item: Pick<EbookLibraryItem, "title" | "author
|
||||
return item.subjects.some((s) => s.toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
export function collectGenresFromEbooks(ebooks: EBookListItem[], locale: SupportedLanguage): string[] {
|
||||
export function collectGenresFromEbooks(
|
||||
ebooks: Pick<EBookListItem, "subjects">[],
|
||||
locale: SupportedLanguage,
|
||||
): string[] {
|
||||
const set = new Set<string>();
|
||||
for (const e of ebooks) {
|
||||
for (const s of filterSubjectsByLocale(e.subjects ?? [], locale)) set.add(s);
|
||||
@@ -63,7 +66,7 @@ export function collectGenresFromEbooks(ebooks: EBookListItem[], locale: Support
|
||||
return [...set].sort((a, b) => a.localeCompare(b, locale));
|
||||
}
|
||||
|
||||
export function collectAuthorsFromEbooks(ebooks: EBookListItem[]): string[] {
|
||||
export function collectAuthorsFromEbooks(ebooks: Pick<EBookListItem, "author">[]): string[] {
|
||||
const set = new Set<string>();
|
||||
for (const e of ebooks) {
|
||||
if (e.author?.trim()) set.add(e.author.trim());
|
||||
|
||||
@@ -28,7 +28,7 @@ function annotationId(bookmarkId: string): string {
|
||||
return `bookmark-hl-${bookmarkId}`;
|
||||
}
|
||||
|
||||
export function applyBookmarkHighlight(
|
||||
function applyBookmarkHighlight(
|
||||
rendition: EpubRenditionWithHighlights,
|
||||
bookmark: BookmarkHighlight,
|
||||
): void {
|
||||
@@ -53,7 +53,7 @@ export function applyBookmarkHighlight(
|
||||
}
|
||||
}
|
||||
|
||||
export function removeBookmarkHighlight(
|
||||
function removeBookmarkHighlight(
|
||||
rendition: EpubRenditionWithHighlights,
|
||||
bookmark: BookmarkHighlight,
|
||||
): void {
|
||||
|
||||
@@ -67,11 +67,6 @@ export function percentageFromCfi(rendition: EpubRendition, cfi: string): number
|
||||
}
|
||||
}
|
||||
|
||||
export function spineLength(rendition: EpubRendition): number {
|
||||
const items = rendition.book?.spine?.spineItems;
|
||||
return items?.length ?? 0;
|
||||
}
|
||||
|
||||
/** Map nav/TOC href to a spine href epub.js can display. */
|
||||
export function resolveSpineHref(book: EpubBookForNav, href: string): string {
|
||||
const hashIndex = href.indexOf("#");
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
export const FINISHED_PROGRESS_THRESHOLD = 99;
|
||||
const FINISHED_PROGRESS_THRESHOLD = 99;
|
||||
|
||||
export type LibraryReadingStatus = "want_to_read" | "reading" | "finished";
|
||||
|
||||
/** API may return progress as a number or numeric string. */
|
||||
export function coerceProgressPercent(progress: unknown): number | null {
|
||||
function coerceProgressPercent(progress: unknown): number | null {
|
||||
if (progress == null || progress === "") return null;
|
||||
const n = typeof progress === "number" ? progress : Number(progress);
|
||||
if (!Number.isFinite(n)) return null;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { DEFAULT_BOOKMARK_HIGHLIGHT_COLOR } from "@/constants/bookmarkHighlightColors";
|
||||
import { DEFAULT_BOOKMARK_HIGHLIGHT_COLOR } from "@/constants/bookmarkHighlightColors";
|
||||
import type { Bookmark, MarkerEntry, MarkersByBook } from "@/types";
|
||||
|
||||
export function bookmarkToMarkerEntry(b: Bookmark): MarkerEntry {
|
||||
@@ -19,7 +18,14 @@ export function bookmarkToMarkerEntry(b: Bookmark): MarkerEntry {
|
||||
};
|
||||
}
|
||||
|
||||
export function sortMarkers(a: MarkerEntry, b: MarkerEntry): number {
|
||||
function sortMarkers(a: MarkerEntry, b: MarkerEntry): number {
|
||||
if (a.chapter_index !== b.chapter_index) {
|
||||
return a.chapter_index - b.chapter_index;
|
||||
}
|
||||
return a.epub_cfi.localeCompare(b.epub_cfi);
|
||||
}
|
||||
|
||||
export function sortBookmarks(a: Bookmark, b: Bookmark): number {
|
||||
if (a.chapter_index !== b.chapter_index) {
|
||||
return a.chapter_index - b.chapter_index;
|
||||
}
|
||||
|
||||
@@ -7,10 +7,6 @@ export interface ParsedPdfAnchor {
|
||||
|
||||
const PDF_ANCHOR_PREFIX = "pdf:v1:";
|
||||
|
||||
export function isPdfAnchor(anchor: string): boolean {
|
||||
return anchor.startsWith(PDF_ANCHOR_PREFIX) || anchor.startsWith("pdf:page:");
|
||||
}
|
||||
|
||||
export function parsePageHref(href: string): number | null {
|
||||
const match = href.match(/^pdf:page:(\d+)$/);
|
||||
if (!match) return null;
|
||||
@@ -38,7 +34,7 @@ export function parsePdfAnchor(anchor: string): ParsedPdfAnchor | null {
|
||||
|
||||
const rectsMatch = anchor.match(/rects=([^;]+)/);
|
||||
let rects: PdfRect[] = [];
|
||||
if (rectsMatch) {
|
||||
if (rectsMatch?.[1]) {
|
||||
try {
|
||||
const parsed = JSON.parse(decodeURIComponent(rectsMatch[1])) as unknown;
|
||||
if (Array.isArray(parsed)) {
|
||||
@@ -56,27 +52,3 @@ export function parsePdfAnchor(anchor: string): ParsedPdfAnchor | null {
|
||||
|
||||
return { page, rects };
|
||||
}
|
||||
|
||||
export function rectsFromSelection(
|
||||
range: Range,
|
||||
pageElement: HTMLElement,
|
||||
): PdfRect[] {
|
||||
const pageRect = pageElement.getBoundingClientRect();
|
||||
if (pageRect.width <= 0 || pageRect.height <= 0) return [];
|
||||
|
||||
const rects: PdfRect[] = [];
|
||||
for (const clientRect of range.getClientRects()) {
|
||||
if (clientRect.width <= 0 || clientRect.height <= 0) continue;
|
||||
const x = (clientRect.left - pageRect.left) / pageRect.width;
|
||||
const y = (clientRect.top - pageRect.top) / pageRect.height;
|
||||
const w = clientRect.width / pageRect.width;
|
||||
const h = clientRect.height / pageRect.height;
|
||||
rects.push([
|
||||
Math.max(0, Math.min(1, x)),
|
||||
Math.max(0, Math.min(1, y)),
|
||||
Math.max(0, Math.min(1, w)),
|
||||
Math.max(0, Math.min(1, h)),
|
||||
]);
|
||||
}
|
||||
return rects;
|
||||
}
|
||||
|
||||
@@ -7,4 +7,6 @@ pdfjs.GlobalWorkerOptions.workerSrc = new URL(
|
||||
|
||||
export { pdfjs };
|
||||
|
||||
export type PdfDocumentProxy = Awaited<ReturnType<typeof pdfjs.getDocument>>["promise"];
|
||||
export type PdfDocumentProxy = Awaited<
|
||||
ReturnType<typeof pdfjs.getDocument>["promise"]
|
||||
>;
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { ReactReaderStyle, type IReactReaderStyle } from "react-reader";
|
||||
import type { ReadingSettings } from "../types/reader";
|
||||
|
||||
const THEME_ARROWS: Record<ReadingSettings["theme"], string> = {
|
||||
sepia: "#b8a898",
|
||||
dark: "#666666",
|
||||
light: "#cccccc",
|
||||
paper: "#c4b8a8",
|
||||
};
|
||||
|
||||
const THEME_ARROW_HOVER: Record<ReadingSettings["theme"], string> = {
|
||||
sepia: "#8a7a6a",
|
||||
dark: "#aaaaaa",
|
||||
light: "#888888",
|
||||
paper: "#7a6a5a",
|
||||
};
|
||||
|
||||
/** Build complete react-reader styles — must spread ReactReaderStyle; partial objects break layout. */
|
||||
export function buildReaderStyles(settings: ReadingSettings): IReactReaderStyle {
|
||||
return {
|
||||
...ReactReaderStyle,
|
||||
container: {
|
||||
...ReactReaderStyle.container,
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
},
|
||||
containerExpanded: ReactReaderStyle.containerExpanded,
|
||||
readerArea: {
|
||||
...ReactReaderStyle.readerArea,
|
||||
backgroundColor: settings.background_color,
|
||||
transition: undefined,
|
||||
},
|
||||
titleArea: {
|
||||
...ReactReaderStyle.titleArea,
|
||||
display: "none",
|
||||
},
|
||||
reader: {
|
||||
...ReactReaderStyle.reader,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
},
|
||||
arrow: {
|
||||
...ReactReaderStyle.arrow,
|
||||
color: THEME_ARROWS[settings.theme],
|
||||
fontSize: 48,
|
||||
marginTop: -24,
|
||||
},
|
||||
arrowHover: {
|
||||
...ReactReaderStyle.arrowHover,
|
||||
color: THEME_ARROW_HOVER[settings.theme],
|
||||
},
|
||||
tocButton: {
|
||||
...ReactReaderStyle.tocButton,
|
||||
display: "none",
|
||||
},
|
||||
tocArea: ReactReaderStyle.tocArea,
|
||||
tocAreaButton: ReactReaderStyle.tocAreaButton,
|
||||
loadingView: {
|
||||
...ReactReaderStyle.loadingView,
|
||||
color: "#999",
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/api/annotations.ts","./src/api/books.ts","./src/api/client.ts","./src/api/errors.ts","./src/api/reader.ts","./src/components/bookcontextmenu.tsx","./src/components/toastcontainer.tsx","./src/components/annotations/bookmarksnotespage.tsx","./src/components/annotations/markerthreadsview.tsx","./src/components/annotations/index.ts","./src/components/layout/layout.tsx","./src/components/layout/index.ts","./src/components/reader/bookmarkerspanel.tsx","./src/components/reader/readertoolbar.tsx","./src/components/reader/readingsettingspanel.tsx","./src/components/reader/selectionpopover.tsx","./src/components/reader/tableofcontents.tsx","./src/components/search/searchsuggestions.tsx","./src/context/annotationscontext.tsx","./src/context/authcontext.tsx","./src/hooks/index.ts","./src/hooks/usedebounce.ts","./src/hooks/useepubreader.ts","./src/hooks/useepubselection.ts","./src/hooks/usemediaquery.ts","./src/hooks/usepaginatedquery.ts","./src/hooks/usereadingsettings.ts","./src/hooks/usetoast.tsx","./src/hooks/usevoicesearch.ts","./src/i18n/i18nprovider.tsx","./src/locales/en-us.ts","./src/locales/es-es.ts","./src/locales/index.ts","./src/pages/addbook.tsx","./src/pages/authpage.tsx","./src/pages/bookdetailpage.tsx","./src/pages/library.tsx","./src/pages/readingpage.tsx","./src/pages/settings.tsx","./src/types/book.ts","./src/types/index.ts","./src/types/reader.ts","./src/types/speech-recognition.d.ts","./src/types/__tests__/types.test.ts","./src/utils/epubrendition.ts","./src/utils/librarystatus.ts","./src/utils/markers.ts","./src/utils/reactreadertheme.ts","./vite-env.d.ts"],"version":"5.7.3"}
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/api/annotations.ts","./src/api/books.ts","./src/api/client.ts","./src/api/errors.ts","./src/api/loadebookwithprogress.ts","./src/api/reader.ts","./src/components/bookcontextmenu.tsx","./src/components/toastcontainer.tsx","./src/components/annotations/bookmarksnotespage.tsx","./src/components/annotations/collapsiblemarkertext.tsx","./src/components/annotations/markerpassageactions.tsx","./src/components/annotations/markerthreadsview.tsx","./src/components/layout/simpleformpagelayout.tsx","./src/components/library/finishedbooksshelf.tsx","./src/components/library/librarybookcard.tsx","./src/components/reader/bookmarkerspanel.tsx","./src/components/reader/bookmarkcolorpicker.tsx","./src/components/reader/bookmarkicon.tsx","./src/components/reader/bookmarkreaderrail.tsx","./src/components/reader/epubreadingview.tsx","./src/components/reader/panelclosebutton.tsx","./src/components/reader/pdflimitationsnotice.tsx","./src/components/reader/pdfreadingview.tsx","./src/components/reader/pdfviewer.tsx","./src/components/reader/readererrorscreen.tsx","./src/components/reader/readerloadingscreen.tsx","./src/components/reader/readersuspenseshell.tsx","./src/components/reader/readertocbutton.tsx","./src/components/reader/readertoolbar.tsx","./src/components/reader/readingsettingspanel.tsx","./src/components/reader/resumereadingbutton.tsx","./src/components/reader/selectionpopover.tsx","./src/components/reader/tableofcontents.tsx","./src/components/search/searchsuggestions.tsx","./src/constants/bookmarkhighlightcolors.ts","./src/context/annotationscontext.tsx","./src/context/authcontext.tsx","./src/hooks/usebookmarkraillayout.ts","./src/hooks/usedebounce.ts","./src/hooks/useepubhighlights.ts","./src/hooks/useepubreader.ts","./src/hooks/useepubselection.ts","./src/hooks/usemediaquery.ts","./src/hooks/usepdfreader.ts","./src/hooks/usereaderorientationcss.ts","./src/hooks/usereadingsettings.ts","./src/hooks/usetoast.tsx","./src/hooks/usevoicesearch.ts","./src/i18n/i18nprovider.tsx","./src/locales/en-us.ts","./src/locales/es-es.ts","./src/locales/index.ts","./src/pages/addbook.tsx","./src/pages/authpage.tsx","./src/pages/bookdetailpage.tsx","./src/pages/library.tsx","./src/pages/readingpage.tsx","./src/pages/settings.tsx","./src/types/book.ts","./src/types/index.ts","./src/types/reader.ts","./src/types/speech-recognition.d.ts","./src/types/__tests__/types.test.ts","./src/utils/bookmarkraillayout.ts","./src/utils/ebooklibrary.ts","./src/utils/epubhighlights.ts","./src/utils/epubrendition.ts","./src/utils/librarystatus.ts","./src/utils/markers.ts","./src/utils/pdfanchor.ts","./src/utils/pdftoc.ts","./src/utils/pdfjssetup.ts","./src/utils/subjectlocale.ts","./vite-env.d.ts"],"version":"5.7.3"}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Mobile (Expo) environment (example – never commit real secrets)
|
||||
# Base URL of the Django backend. Must be reachable from the device/emulator.
|
||||
# - Android emulator: http://10.0.2.2:8000
|
||||
# - iOS simulator: http://localhost:8000
|
||||
# - Physical device: http://<your-lan-ip>:8000
|
||||
EXPO_PUBLIC_API_URL=http://10.0.2.2:8000
|
||||
|
||||
# EAS Build: set per profile in mobile/eas.json or via:
|
||||
# eas secret:create --name EXPO_PUBLIC_API_URL --value https://your-api.example.com
|
||||
# Run all eas commands from mobile/ (not repo root).
|
||||
+12
-6
@@ -1,4 +1,8 @@
|
||||
import React from "react";
|
||||
// Peer dependencies for @epubjs-react-native/core and gesture-handler.
|
||||
import "react-native-webview";
|
||||
import "react-native-reanimated";
|
||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
import { NavigationContainer } from "@react-navigation/native";
|
||||
import { StatusBar } from "expo-status-bar";
|
||||
import { AuthProvider } from "./src/context/AuthContext";
|
||||
@@ -6,11 +10,13 @@ import { RootNavigator } from "./src/navigation/RootNavigator";
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<NavigationContainer>
|
||||
<StatusBar style="auto" />
|
||||
<RootNavigator />
|
||||
</NavigationContainer>
|
||||
</AuthProvider>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<AuthProvider>
|
||||
<NavigationContainer>
|
||||
<StatusBar style="auto" />
|
||||
<RootNavigator />
|
||||
</NavigationContainer>
|
||||
</AuthProvider>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
}
|
||||
@@ -21,7 +21,6 @@
|
||||
"package": "com.cloudreader.app"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-document-picker",
|
||||
"expo-file-system"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"cli": {
|
||||
"version": ">= 13.0.0",
|
||||
"appVersionSource": "remote"
|
||||
},
|
||||
"build": {
|
||||
"base": {
|
||||
"node": "20.18.0",
|
||||
"env": {
|
||||
"EXPO_PUBLIC_API_URL": "https://api.example.com"
|
||||
}
|
||||
},
|
||||
"development": {
|
||||
"extends": "base",
|
||||
"developmentClient": true,
|
||||
"distribution": "internal",
|
||||
"ios": {
|
||||
"simulator": true
|
||||
},
|
||||
"android": {
|
||||
"buildType": "apk"
|
||||
},
|
||||
"env": {
|
||||
"EXPO_PUBLIC_API_URL": "http://10.0.2.2:8000"
|
||||
}
|
||||
},
|
||||
"preview": {
|
||||
"extends": "base",
|
||||
"distribution": "internal",
|
||||
"android": {
|
||||
"buildType": "apk"
|
||||
}
|
||||
},
|
||||
"production": {
|
||||
"extends": "base",
|
||||
"autoIncrement": true
|
||||
}
|
||||
},
|
||||
"submit": {
|
||||
"production": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
const { getDefaultConfig } = require("expo/metro-config");
|
||||
const path = require("path");
|
||||
|
||||
const projectRoot = __dirname;
|
||||
const monorepoRoot = path.resolve(projectRoot, "..");
|
||||
|
||||
/**
|
||||
* Expo SDK 52+ configures Metro for Yarn/npm/pnpm workspaces automatically
|
||||
* when using expo/metro-config. This file keeps an explicit monorepo root so
|
||||
* @cloud-reader/shared (packages/shared) resolves reliably in dev and on EAS.
|
||||
*
|
||||
* If you previously added manual watchFolders/nodeModulesPaths and things
|
||||
* work, prefer this minimal config. After changes: npx expo start --clear
|
||||
*
|
||||
* @see https://docs.expo.dev/guides/monorepos/
|
||||
*/
|
||||
const config = getDefaultConfig(projectRoot);
|
||||
|
||||
config.watchFolders = [monorepoRoot];
|
||||
config.resolver.nodeModulesPaths = [
|
||||
path.resolve(projectRoot, "node_modules"),
|
||||
path.resolve(monorepoRoot, "node_modules"),
|
||||
];
|
||||
|
||||
module.exports = config;
|
||||
+8
-2
@@ -8,7 +8,11 @@
|
||||
"android": "expo start --android",
|
||||
"ios": "expo start --ios",
|
||||
"web": "expo start --web",
|
||||
"lint": "eslint ."
|
||||
"lint": "eslint .",
|
||||
"eas:init": "eas init",
|
||||
"eas:build:dev": "eas build --profile development --platform all",
|
||||
"eas:build:preview": "eas build --profile preview --platform all",
|
||||
"eas:build:prod": "eas build --profile production --platform all"
|
||||
},
|
||||
"dependencies": {
|
||||
"expo": "~52.0.0",
|
||||
@@ -22,10 +26,12 @@
|
||||
"@react-navigation/bottom-tabs": "^7.0.0",
|
||||
"axios": "^1.7.9",
|
||||
"@react-native-async-storage/async-storage": "2.1.0",
|
||||
"expo-document-picker": "~13.0.0",
|
||||
"@epubjs-react-native/core": "1.4.7",
|
||||
"@epubjs-react-native/expo-file-system": "1.1.4",
|
||||
"expo-file-system": "~18.0.0",
|
||||
"react-native-gesture-handler": "~2.20.0",
|
||||
"react-native-reanimated": "~3.16.0",
|
||||
"react-native-webview": "13.12.5",
|
||||
"@cloud-reader/shared": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,55 +1,31 @@
|
||||
import api from "./client";
|
||||
import type {
|
||||
Bookmark,
|
||||
Note,
|
||||
CreateBookmarkPayload,
|
||||
CreateNotePayload,
|
||||
PaginatedResponse,
|
||||
} from "@cloud-reader/shared";
|
||||
import type { PaginatedResponse } from "@cloud-reader/shared";
|
||||
import type { Bookmark, CreateMarkerPayload } from "../types";
|
||||
|
||||
export function fetchBookmarks(
|
||||
bookId?: string,
|
||||
export async function fetchBookmarks(
|
||||
ebookId?: string | number,
|
||||
): Promise<PaginatedResponse<Bookmark>> {
|
||||
const params = bookId ? { book: bookId } : {};
|
||||
return api
|
||||
.get<PaginatedResponse<Bookmark>>("/api/annotations/bookmarks/", { params })
|
||||
.then((res) => res.data);
|
||||
const params: Record<string, string> = {};
|
||||
if (ebookId != null && ebookId !== "") {
|
||||
params.ebook = String(ebookId);
|
||||
}
|
||||
const { data } = await api.get<PaginatedResponse<Bookmark>>(
|
||||
"/api/annotations/bookmarks/",
|
||||
{ params },
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
export function createBookmark(
|
||||
payload: CreateBookmarkPayload,
|
||||
export async function createMarker(
|
||||
payload: CreateMarkerPayload,
|
||||
): Promise<Bookmark> {
|
||||
return api
|
||||
.post<Bookmark>("/api/annotations/bookmarks/", payload)
|
||||
.then((res) => res.data);
|
||||
const { data } = await api.post<Bookmark>(
|
||||
"/api/annotations/bookmarks/",
|
||||
payload,
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
export function deleteBookmark(id: string): Promise<void> {
|
||||
return api.delete(`/api/annotations/bookmarks/${id}/`).then(() => {});
|
||||
}
|
||||
|
||||
export function fetchNotes(bookId?: string): Promise<PaginatedResponse<Note>> {
|
||||
const params = bookId ? { book: bookId } : {};
|
||||
return api
|
||||
.get<PaginatedResponse<Note>>("/api/annotations/notes/", { params })
|
||||
.then((res) => res.data);
|
||||
}
|
||||
|
||||
export function createNote(payload: CreateNotePayload): Promise<Note> {
|
||||
return api
|
||||
.post<Note>("/api/annotations/notes/", payload)
|
||||
.then((res) => res.data);
|
||||
}
|
||||
|
||||
export function updateNote(
|
||||
id: string,
|
||||
content: string,
|
||||
): Promise<Note> {
|
||||
return api
|
||||
.patch<Note>(`/api/annotations/notes/${id}/`, { content })
|
||||
.then((res) => res.data);
|
||||
}
|
||||
|
||||
export function deleteNote(id: string): Promise<void> {
|
||||
return api.delete(`/api/annotations/notes/${id}/`).then(() => {});
|
||||
export async function deleteBookmark(id: string): Promise<void> {
|
||||
await api.delete(`/api/annotations/bookmarks/${id}/`);
|
||||
}
|
||||
+1
-20
@@ -1,31 +1,12 @@
|
||||
import api from "./client";
|
||||
import type { Book, PaginatedResponse } from "@cloud-reader/shared";
|
||||
|
||||
export function fetchBooks(
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
): Promise<PaginatedResponse<Book>> {
|
||||
return api
|
||||
.get<PaginatedResponse<Book>>("/api/books/", {
|
||||
params: { page, page_size: pageSize },
|
||||
})
|
||||
.then((res) => res.data);
|
||||
}
|
||||
|
||||
export function fetchBook(id: string): Promise<Book> {
|
||||
return api.get<Book>(`/api/books/${id}/`).then((res) => res.data);
|
||||
}
|
||||
|
||||
export function searchBooks(
|
||||
query: string,
|
||||
): Promise<PaginatedResponse<Book>> {
|
||||
return api
|
||||
.get<PaginatedResponse<Book>>("/api/books/search/", {
|
||||
.get<PaginatedResponse<Book>>("/api/books/", {
|
||||
params: { q: query },
|
||||
})
|
||||
.then((res) => res.data);
|
||||
}
|
||||
|
||||
export function deleteBook(id: string): Promise<void> {
|
||||
return api.delete(`/api/books/${id}/`).then(() => {});
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import axios, { type AxiosError, type InternalAxiosRequestConfig } from "axios";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import type { TokenResponse } from "@cloud-reader/shared";
|
||||
|
||||
const STORAGE_KEYS = {
|
||||
ACCESS_TOKEN: "access_token",
|
||||
@@ -39,6 +40,26 @@ async function clearTokens(): Promise<void> {
|
||||
]);
|
||||
}
|
||||
|
||||
async function saveTokens(tokens: TokenResponse): Promise<void> {
|
||||
await setTokens(tokens.access, tokens.refresh);
|
||||
}
|
||||
|
||||
async function loadTokens(): Promise<TokenResponse | null> {
|
||||
const [access, refresh] = await Promise.all([
|
||||
getAccessToken(),
|
||||
getRefreshToken(),
|
||||
]);
|
||||
if (!access || !refresh) {
|
||||
return null;
|
||||
}
|
||||
return { access, refresh };
|
||||
}
|
||||
|
||||
/** Absolute base URL used for direct (non-axios) requests like file downloads. */
|
||||
function getApiBaseUrl(): string {
|
||||
return api.defaults.baseURL ?? "";
|
||||
}
|
||||
|
||||
// ── Request interceptor ─────────────────────────────────────────────
|
||||
|
||||
api.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
|
||||
@@ -136,5 +157,14 @@ api.interceptors.response.use(
|
||||
},
|
||||
);
|
||||
|
||||
export { getAccessToken, getRefreshToken, setTokens, clearTokens };
|
||||
const apiClient = api;
|
||||
|
||||
export {
|
||||
apiClient,
|
||||
getAccessToken,
|
||||
saveTokens,
|
||||
loadTokens,
|
||||
clearTokens,
|
||||
getApiBaseUrl,
|
||||
};
|
||||
export default api;
|
||||
+16
-35
@@ -1,54 +1,35 @@
|
||||
import { apiClient } from "./client";
|
||||
import { apiClient, getApiBaseUrl } from "./client";
|
||||
import type {
|
||||
EBookListItem,
|
||||
EBookDetail,
|
||||
ReadingProgress,
|
||||
ReadingSettings,
|
||||
TocResponse,
|
||||
ContentResponse,
|
||||
PaginatedResponse,
|
||||
} from "@cloud-reader/shared";
|
||||
|
||||
export const ebooksApi = {
|
||||
/** List uploaded e-books */
|
||||
/** List the authenticated user's uploaded e-books */
|
||||
list() {
|
||||
return apiClient.get<PaginatedResponse<EBookListItem>>("/api/ebooks/");
|
||||
return apiClient.get<PaginatedResponse<EBookListItem>>(
|
||||
"/api/books/ebooks/",
|
||||
);
|
||||
},
|
||||
|
||||
/** Get e-book detail */
|
||||
/** Get e-book detail (metadata, format, progress) */
|
||||
get(id: number) {
|
||||
return apiClient.get<EBookDetail>(`/api/ebooks/${id}/`);
|
||||
return apiClient.get<EBookDetail>(`/api/books/ebooks/${id}/`);
|
||||
},
|
||||
|
||||
/** Get table of contents */
|
||||
/** Get the table of contents (used as a fallback for chapter navigation) */
|
||||
getToc(id: number) {
|
||||
return apiClient.get<TocResponse>(`/api/ebooks/${id}/toc/`);
|
||||
return apiClient.get<TocResponse>(`/api/books/ebooks/${id}/toc/`);
|
||||
},
|
||||
|
||||
/** Get page content */
|
||||
getContent(id: number, page: number) {
|
||||
return apiClient.get<ContentResponse>(
|
||||
`/api/ebooks/${id}/content/?page=${page}`,
|
||||
);
|
||||
},
|
||||
|
||||
/** Update reading progress */
|
||||
updateProgress(id: number, data: Partial<ReadingProgress>) {
|
||||
return apiClient.patch<ReadingProgress>(
|
||||
`/api/ebooks/${id}/progress/`,
|
||||
data,
|
||||
);
|
||||
},
|
||||
|
||||
/** Get or update reading settings */
|
||||
getSettings(id: number) {
|
||||
return apiClient.get<ReadingSettings>(`/api/ebooks/${id}/settings/`);
|
||||
},
|
||||
|
||||
updateSettings(id: number, data: Partial<ReadingSettings>) {
|
||||
return apiClient.patch<ReadingSettings>(
|
||||
`/api/ebooks/${id}/settings/`,
|
||||
data,
|
||||
);
|
||||
/**
|
||||
* Absolute URL to stream the raw ebook file. The endpoint requires JWT auth,
|
||||
* so callers download it with an Authorization header (e.g. via
|
||||
* expo-file-system) rather than handing the URL to a renderer directly.
|
||||
*/
|
||||
getFileUrl(id: number): string {
|
||||
return `${getApiBaseUrl()}/api/books/ebooks/${id}/file/`;
|
||||
},
|
||||
};
|
||||
@@ -1,4 +0,0 @@
|
||||
export { apiClient, saveTokens, loadTokens, clearTokens } from "./client";
|
||||
export { booksApi } from "./books";
|
||||
export { ebooksApi } from "./ebooks";
|
||||
export { annotationsApi } from "./annotations";
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Reader API client — reading settings and per-book progress.
|
||||
* Mirrors frontend/src/api/reader.ts. Uses the shared axios client so the
|
||||
* JWT access token is attached automatically.
|
||||
*/
|
||||
|
||||
import api from "./client";
|
||||
import type { ReadingProgress, ReadingSettings } from "../types/reader";
|
||||
|
||||
export async function getReadingSettings(): Promise<ReadingSettings> {
|
||||
const { data } = await api.get<ReadingSettings>("/api/reader/settings/");
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateReadingSettings(
|
||||
settings: Partial<ReadingSettings>,
|
||||
): Promise<ReadingSettings> {
|
||||
const { data } = await api.patch<ReadingSettings>(
|
||||
"/api/reader/settings/",
|
||||
settings,
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
interface ProgressWire {
|
||||
current_position: number;
|
||||
last_page: number;
|
||||
epub_location?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
function toReadingProgress(bookId: number, data: ProgressWire): ReadingProgress {
|
||||
return {
|
||||
id: bookId,
|
||||
book: bookId,
|
||||
current_chapter: data.last_page || 1,
|
||||
current_position: data.current_position ?? 0,
|
||||
percentage: data.current_position ?? 0,
|
||||
epub_location: data.epub_location ?? "",
|
||||
updated_at: data.updated_at ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export async function getReadingProgress(
|
||||
bookId: number,
|
||||
): Promise<ReadingProgress> {
|
||||
const { data } = await api.get<ProgressWire>(
|
||||
`/api/books/ebooks/${bookId}/progress/`,
|
||||
);
|
||||
return toReadingProgress(bookId, data);
|
||||
}
|
||||
|
||||
export async function updateReadingProgress(
|
||||
bookId: number,
|
||||
progress: Partial<ReadingProgress>,
|
||||
): Promise<ReadingProgress> {
|
||||
const body: Record<string, string | number> = {};
|
||||
if (
|
||||
progress.percentage !== undefined ||
|
||||
progress.current_position !== undefined
|
||||
) {
|
||||
body.current_position = progress.percentage ?? progress.current_position ?? 0;
|
||||
}
|
||||
if (progress.current_chapter !== undefined) {
|
||||
body.last_page = progress.current_chapter;
|
||||
}
|
||||
if (progress.epub_location !== undefined) {
|
||||
body.epub_location = progress.epub_location;
|
||||
}
|
||||
const { data } = await api.patch<ProgressWire>(
|
||||
`/api/books/ebooks/${bookId}/progress/`,
|
||||
body,
|
||||
);
|
||||
return toReadingProgress(bookId, data);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { type ReactNode } from "react";
|
||||
import {
|
||||
Text,
|
||||
FlatList,
|
||||
TouchableOpacity,
|
||||
StyleSheet,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { resolvePalette } from "../../utils/epubTheme";
|
||||
import type { ReadingSettings } from "../../types/reader";
|
||||
import type { Bookmark } from "../../types";
|
||||
import { ReaderBottomSheet } from "./ReaderBottomSheet";
|
||||
|
||||
interface BookmarksModalProps {
|
||||
visible: boolean;
|
||||
bookmarks: Bookmark[];
|
||||
settings: ReadingSettings;
|
||||
onSelect: (bookmark: Bookmark) => void;
|
||||
onDelete: (bookmark: Bookmark) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function BookmarksModal({
|
||||
visible,
|
||||
bookmarks,
|
||||
settings,
|
||||
onSelect,
|
||||
onDelete,
|
||||
onClose,
|
||||
}: BookmarksModalProps): ReactNode {
|
||||
const palette = resolvePalette(settings);
|
||||
|
||||
return (
|
||||
<ReaderBottomSheet
|
||||
visible={visible}
|
||||
title="Bookmarks & highlights"
|
||||
chromeColor={palette.chrome}
|
||||
textColor={palette.text}
|
||||
onClose={onClose}
|
||||
>
|
||||
<FlatList
|
||||
data={bookmarks}
|
||||
keyExtractor={(item) => item.id}
|
||||
ListEmptyComponent={
|
||||
<Text style={[styles.empty, { color: palette.text }]}>
|
||||
No bookmarks yet. Tap the star to bookmark a page, or select text to
|
||||
highlight it.
|
||||
</Text>
|
||||
}
|
||||
renderItem={({ item }) => (
|
||||
<View style={styles.row}>
|
||||
<TouchableOpacity
|
||||
style={styles.rowMain}
|
||||
onPress={() => onSelect(item)}
|
||||
>
|
||||
{item.highlight_color ? (
|
||||
<View
|
||||
style={[
|
||||
styles.dot,
|
||||
{ backgroundColor: item.highlight_color },
|
||||
]}
|
||||
/>
|
||||
) : (
|
||||
<Text style={styles.star}>★</Text>
|
||||
)}
|
||||
<View style={styles.rowTextWrap}>
|
||||
{item.chapter_title ? (
|
||||
<Text
|
||||
style={[styles.chapter, { color: palette.text }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{item.chapter_title}
|
||||
</Text>
|
||||
) : null}
|
||||
<Text
|
||||
style={[styles.excerpt, { color: palette.text }]}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{item.content || item.location_text || "Bookmarked page"}
|
||||
</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
onPress={() => onDelete(item)}
|
||||
hitSlop={8}
|
||||
style={styles.deleteButton}
|
||||
>
|
||||
<Text style={styles.deleteText}>Delete</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
</ReaderBottomSheet>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingVertical: 12,
|
||||
paddingHorizontal: 16,
|
||||
borderTopWidth: StyleSheet.hairlineWidth,
|
||||
borderTopColor: "rgba(127,127,127,0.2)",
|
||||
},
|
||||
rowMain: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
},
|
||||
rowTextWrap: {
|
||||
flex: 1,
|
||||
marginLeft: 10,
|
||||
},
|
||||
star: {
|
||||
fontSize: 16,
|
||||
color: "#4f8ef7",
|
||||
},
|
||||
dot: {
|
||||
width: 14,
|
||||
height: 14,
|
||||
borderRadius: 7,
|
||||
},
|
||||
chapter: {
|
||||
fontSize: 12,
|
||||
opacity: 0.7,
|
||||
marginBottom: 2,
|
||||
},
|
||||
excerpt: {
|
||||
fontSize: 14,
|
||||
},
|
||||
deleteButton: {
|
||||
marginLeft: 12,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 6,
|
||||
},
|
||||
deleteText: {
|
||||
color: "#ff453a",
|
||||
fontSize: 13,
|
||||
fontWeight: "600",
|
||||
},
|
||||
empty: {
|
||||
padding: 24,
|
||||
textAlign: "center",
|
||||
opacity: 0.7,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,436 @@
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
ActivityIndicator,
|
||||
StyleSheet,
|
||||
type LayoutChangeEvent,
|
||||
} from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
import { Reader, ReaderProvider, useReader } from "@epubjs-react-native/core";
|
||||
import { useFileSystem } from "@epubjs-react-native/expo-file-system";
|
||||
import * as FileSystem from "expo-file-system";
|
||||
import type { EBookDetail } from "@cloud-reader/shared";
|
||||
import { getAccessToken } from "../../api/client";
|
||||
import { ebooksApi } from "../../api/ebooks";
|
||||
import { getReadingProgress, updateReadingProgress } from "../../api/reader";
|
||||
import {
|
||||
fetchBookmarks,
|
||||
createMarker,
|
||||
deleteBookmark,
|
||||
} from "../../api/annotations";
|
||||
import { useReadingSettings } from "../../hooks/useReadingSettings";
|
||||
import {
|
||||
buildEpubTheme,
|
||||
FONT_STACKS,
|
||||
resolvePalette,
|
||||
} from "../../utils/epubTheme";
|
||||
import type { Bookmark } from "../../types";
|
||||
import { ReaderToolbar } from "./ReaderToolbar";
|
||||
import { TocModal, type TocItem } from "./TocModal";
|
||||
import { ReadingSettingsModal } from "./ReadingSettingsModal";
|
||||
import { BookmarksModal } from "./BookmarksModal";
|
||||
|
||||
const HIGHLIGHT_COLOR = "#ffd54a";
|
||||
const PROGRESS_SAVE_MS = 800;
|
||||
|
||||
/** Loose view of the epubjs-react-native reader API we rely on. */
|
||||
interface ReaderApi {
|
||||
goToLocation?: (target: string) => void;
|
||||
changeTheme?: (theme: Record<string, Record<string, string>>) => void;
|
||||
changeFontSize?: (size: string) => void;
|
||||
changeFontFamily?: (font: string) => void;
|
||||
addAnnotation?: (
|
||||
type: string,
|
||||
cfiRange: string,
|
||||
data?: unknown,
|
||||
styles?: Record<string, unknown>,
|
||||
) => void;
|
||||
removeAnnotationByCfi?: (cfi: string) => void;
|
||||
removeSelection?: () => void;
|
||||
toc?: TocItem[];
|
||||
}
|
||||
|
||||
interface EpubLocation {
|
||||
start?: { cfi?: string };
|
||||
}
|
||||
|
||||
interface EpubSection {
|
||||
label?: string;
|
||||
index?: number;
|
||||
}
|
||||
|
||||
interface EpubReaderViewProps {
|
||||
book: EBookDetail;
|
||||
ebookId: number;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function EpubReaderView(props: EpubReaderViewProps): ReactNode {
|
||||
return (
|
||||
<ReaderProvider>
|
||||
<EpubReaderInner {...props} />
|
||||
</ReaderProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function EpubReaderInner({
|
||||
book,
|
||||
ebookId,
|
||||
onClose,
|
||||
}: EpubReaderViewProps): ReactNode {
|
||||
const reader = useReader() as unknown as ReaderApi;
|
||||
const { settings, updateSettings } = useReadingSettings();
|
||||
|
||||
const [src, setSrc] = useState<string | null>(null);
|
||||
const [initialLocation, setInitialLocation] = useState<string | undefined>();
|
||||
const [fileError, setFileError] = useState(false);
|
||||
const [ready, setReady] = useState(false);
|
||||
const [size, setSize] = useState<{ width: number; height: number } | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const [progressPct, setProgressPct] = useState(
|
||||
Math.round(book.progress?.current_position ?? 0),
|
||||
);
|
||||
const [chapterTitle, setChapterTitle] = useState("");
|
||||
const [currentCfi, setCurrentCfi] = useState("");
|
||||
const [bookmarks, setBookmarks] = useState<Bookmark[]>([]);
|
||||
|
||||
const [tocOpen, setTocOpen] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [bookmarksOpen, setBookmarksOpen] = useState(false);
|
||||
|
||||
const currentCfiRef = useRef("");
|
||||
const progressPctRef = useRef(progressPct);
|
||||
const sectionRef = useRef<{ index: number; label: string }>({
|
||||
index: 0,
|
||||
label: "",
|
||||
});
|
||||
const bookmarksRef = useRef<Bookmark[]>([]);
|
||||
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
bookmarksRef.current = bookmarks;
|
||||
}, [bookmarks]);
|
||||
|
||||
// Download the EPUB with auth, and resolve the saved resume location.
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
(async () => {
|
||||
try {
|
||||
const progress = await getReadingProgress(ebookId).catch(() => null);
|
||||
if (active && progress?.epub_location) {
|
||||
setInitialLocation(progress.epub_location);
|
||||
currentCfiRef.current = progress.epub_location;
|
||||
setCurrentCfi(progress.epub_location);
|
||||
}
|
||||
const token = await getAccessToken();
|
||||
const url = ebooksApi.getFileUrl(ebookId);
|
||||
const dest = `${FileSystem.cacheDirectory}ebook-${ebookId}.epub`;
|
||||
const result = await FileSystem.downloadAsync(url, dest, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
||||
});
|
||||
if (!active) return;
|
||||
if (result.status >= 400) {
|
||||
setFileError(true);
|
||||
return;
|
||||
}
|
||||
setSrc(result.uri);
|
||||
} catch {
|
||||
if (active) setFileError(true);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [ebookId]);
|
||||
|
||||
// Load existing bookmarks/highlights for this book.
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
fetchBookmarks(ebookId)
|
||||
.then((res) => {
|
||||
if (active) setBookmarks(res.results);
|
||||
})
|
||||
.catch(() => {
|
||||
/* bookmarks are optional */
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [ebookId]);
|
||||
|
||||
// Apply typography/theme to the rendition once it is ready and on changes.
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
try {
|
||||
reader.changeTheme?.(buildEpubTheme(settings));
|
||||
reader.changeFontSize?.(`${settings.font_size}px`);
|
||||
reader.changeFontFamily?.(FONT_STACKS[settings.font_family]);
|
||||
} catch {
|
||||
/* ignore rendition styling errors */
|
||||
}
|
||||
}, [ready, settings, reader]);
|
||||
|
||||
const flushProgress = useCallback(() => {
|
||||
const cfi = currentCfiRef.current;
|
||||
if (!cfi) return;
|
||||
updateReadingProgress(ebookId, {
|
||||
percentage: progressPctRef.current,
|
||||
epub_location: cfi,
|
||||
current_chapter: sectionRef.current.index + 1,
|
||||
}).catch(() => {
|
||||
/* progress is best-effort */
|
||||
});
|
||||
}, [ebookId]);
|
||||
|
||||
// Flush the latest progress when leaving the reader.
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
|
||||
flushProgress();
|
||||
},
|
||||
[flushProgress],
|
||||
);
|
||||
|
||||
const handleReady = useCallback(() => {
|
||||
setReady(true);
|
||||
bookmarksRef.current.forEach((bookmark) => {
|
||||
if (bookmark.highlight_color && bookmark.epub_cfi) {
|
||||
try {
|
||||
reader.addAnnotation?.("highlight", bookmark.epub_cfi, undefined, {
|
||||
fill: bookmark.highlight_color,
|
||||
});
|
||||
} catch {
|
||||
/* highlight rendering is best-effort */
|
||||
}
|
||||
}
|
||||
});
|
||||
}, [reader]);
|
||||
|
||||
const handleLocationChange = useCallback(
|
||||
(
|
||||
_total: number,
|
||||
location: EpubLocation,
|
||||
progress: number,
|
||||
section: EpubSection | null,
|
||||
) => {
|
||||
const cfi = location?.start?.cfi ?? "";
|
||||
if (cfi) {
|
||||
currentCfiRef.current = cfi;
|
||||
setCurrentCfi(cfi);
|
||||
}
|
||||
const pct = Math.round(progress ?? 0);
|
||||
progressPctRef.current = pct;
|
||||
setProgressPct(pct);
|
||||
const label = section?.label?.trim() ?? "";
|
||||
sectionRef.current = {
|
||||
index: section?.index ?? sectionRef.current.index,
|
||||
label,
|
||||
};
|
||||
setChapterTitle(label);
|
||||
|
||||
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
|
||||
saveTimerRef.current = setTimeout(flushProgress, PROGRESS_SAVE_MS);
|
||||
},
|
||||
[flushProgress],
|
||||
);
|
||||
|
||||
const handleSelected = useCallback(
|
||||
async (selectedText: string, cfiRange: string) => {
|
||||
const excerpt = (selectedText ?? "").slice(0, 280);
|
||||
try {
|
||||
const created = await createMarker({
|
||||
ebook: ebookId,
|
||||
epub_cfi: cfiRange,
|
||||
chapter_index: sectionRef.current.index,
|
||||
chapter_title: sectionRef.current.label,
|
||||
location_text: excerpt,
|
||||
content: excerpt,
|
||||
highlight_color: HIGHLIGHT_COLOR,
|
||||
});
|
||||
setBookmarks((prev) => [created, ...prev]);
|
||||
try {
|
||||
reader.addAnnotation?.("highlight", cfiRange, undefined, {
|
||||
fill: HIGHLIGHT_COLOR,
|
||||
});
|
||||
reader.removeSelection?.();
|
||||
} catch {
|
||||
/* annotation rendering is best-effort */
|
||||
}
|
||||
} catch {
|
||||
/* ignore highlight save failures */
|
||||
}
|
||||
},
|
||||
[ebookId, reader],
|
||||
);
|
||||
|
||||
const handleToggleBookmarkHere = useCallback(async () => {
|
||||
const cfi = currentCfiRef.current;
|
||||
if (!cfi) return;
|
||||
const existing = bookmarksRef.current.find((b) => b.epub_cfi === cfi);
|
||||
if (existing) {
|
||||
setBookmarks((prev) => prev.filter((b) => b.id !== existing.id));
|
||||
try {
|
||||
reader.removeAnnotationByCfi?.(cfi);
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
deleteBookmark(existing.id).catch(() => {});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const created = await createMarker({
|
||||
ebook: ebookId,
|
||||
epub_cfi: cfi,
|
||||
chapter_index: sectionRef.current.index,
|
||||
chapter_title: sectionRef.current.label,
|
||||
location_text: sectionRef.current.label,
|
||||
});
|
||||
setBookmarks((prev) => [created, ...prev]);
|
||||
} catch {
|
||||
/* ignore bookmark save failures */
|
||||
}
|
||||
}, [ebookId, reader]);
|
||||
|
||||
const handleSelectBookmark = useCallback(
|
||||
(bookmark: Bookmark) => {
|
||||
setBookmarksOpen(false);
|
||||
try {
|
||||
reader.goToLocation?.(bookmark.epub_cfi);
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
},
|
||||
[reader],
|
||||
);
|
||||
|
||||
const handleDeleteBookmark = useCallback(
|
||||
(bookmark: Bookmark) => {
|
||||
setBookmarks((prev) => prev.filter((b) => b.id !== bookmark.id));
|
||||
try {
|
||||
if (bookmark.highlight_color) {
|
||||
reader.removeAnnotationByCfi?.(bookmark.epub_cfi);
|
||||
}
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
deleteBookmark(bookmark.id).catch(() => {});
|
||||
},
|
||||
[reader],
|
||||
);
|
||||
|
||||
const handleTocSelect = useCallback(
|
||||
(href: string) => {
|
||||
setTocOpen(false);
|
||||
try {
|
||||
reader.goToLocation?.(href);
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
},
|
||||
[reader],
|
||||
);
|
||||
|
||||
const onReaderLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { width, height } = event.nativeEvent.layout;
|
||||
setSize((prev) =>
|
||||
prev && prev.width === width && prev.height === height
|
||||
? prev
|
||||
: { width, height },
|
||||
);
|
||||
}, []);
|
||||
|
||||
const palette = resolvePalette(settings);
|
||||
const isBookmarked = bookmarks.some((b) => b.epub_cfi === currentCfi);
|
||||
|
||||
return (
|
||||
<SafeAreaView
|
||||
style={[styles.container, { backgroundColor: palette.background }]}
|
||||
edges={["top", "bottom"]}
|
||||
>
|
||||
<ReaderToolbar
|
||||
title={book.title}
|
||||
chapterTitle={chapterTitle}
|
||||
progressPct={progressPct}
|
||||
settings={settings}
|
||||
isBookmarked={isBookmarked}
|
||||
onBack={onClose}
|
||||
onToggleToc={() => setTocOpen(true)}
|
||||
onToggleSettings={() => setSettingsOpen(true)}
|
||||
onToggleBookmarks={() => setBookmarksOpen(true)}
|
||||
onToggleBookmarkHere={handleToggleBookmarkHere}
|
||||
/>
|
||||
|
||||
<View style={styles.readerArea} onLayout={onReaderLayout}>
|
||||
{fileError ? (
|
||||
<View style={styles.centered}>
|
||||
<Text style={[styles.message, { color: palette.text }]}>
|
||||
Could not download this book. Check your connection and try again.
|
||||
</Text>
|
||||
</View>
|
||||
) : src && size ? (
|
||||
<Reader
|
||||
src={src}
|
||||
fileSystem={useFileSystem}
|
||||
width={size.width}
|
||||
height={size.height}
|
||||
initialLocation={initialLocation}
|
||||
enableSelection
|
||||
flow="paginated"
|
||||
defaultTheme={buildEpubTheme(settings)}
|
||||
onReady={handleReady}
|
||||
onLocationChange={handleLocationChange}
|
||||
onSelected={handleSelected}
|
||||
/>
|
||||
) : (
|
||||
<View style={styles.centered}>
|
||||
<ActivityIndicator size="large" color="#4f8ef7" />
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<TocModal
|
||||
visible={tocOpen}
|
||||
toc={reader.toc ?? []}
|
||||
settings={settings}
|
||||
onSelect={handleTocSelect}
|
||||
onClose={() => setTocOpen(false)}
|
||||
/>
|
||||
<ReadingSettingsModal
|
||||
visible={settingsOpen}
|
||||
settings={settings}
|
||||
onChange={updateSettings}
|
||||
onClose={() => setSettingsOpen(false)}
|
||||
/>
|
||||
<BookmarksModal
|
||||
visible={bookmarksOpen}
|
||||
bookmarks={bookmarks}
|
||||
settings={settings}
|
||||
onSelect={handleSelectBookmark}
|
||||
onDelete={handleDeleteBookmark}
|
||||
onClose={() => setBookmarksOpen(false)}
|
||||
/>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
readerArea: {
|
||||
flex: 1,
|
||||
},
|
||||
centered: {
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
padding: 24,
|
||||
},
|
||||
message: {
|
||||
fontSize: 15,
|
||||
textAlign: "center",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { type ReactNode } from "react";
|
||||
import {
|
||||
Modal,
|
||||
View,
|
||||
Text,
|
||||
TouchableOpacity,
|
||||
StyleSheet,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
|
||||
interface ReaderBottomSheetProps {
|
||||
visible: boolean;
|
||||
title: string;
|
||||
chromeColor: string;
|
||||
textColor: string;
|
||||
onClose: () => void;
|
||||
children: ReactNode;
|
||||
/** When true, caps sheet height (TOC/bookmarks). Settings uses a full-width panel. */
|
||||
tall?: boolean;
|
||||
sheetStyle?: StyleProp<ViewStyle>;
|
||||
}
|
||||
|
||||
export function ReaderBottomSheet({
|
||||
visible,
|
||||
title,
|
||||
chromeColor,
|
||||
textColor,
|
||||
onClose,
|
||||
children,
|
||||
tall = true,
|
||||
sheetStyle,
|
||||
}: ReaderBottomSheetProps): ReactNode {
|
||||
return (
|
||||
<Modal
|
||||
visible={visible}
|
||||
animationType="slide"
|
||||
transparent
|
||||
onRequestClose={onClose}
|
||||
>
|
||||
<View style={styles.backdrop}>
|
||||
<View
|
||||
style={[
|
||||
styles.sheet,
|
||||
tall && styles.sheetTall,
|
||||
{ backgroundColor: chromeColor },
|
||||
sheetStyle,
|
||||
]}
|
||||
>
|
||||
<View style={styles.header}>
|
||||
<Text style={[styles.headerTitle, { color: textColor }]}>
|
||||
{title}
|
||||
</Text>
|
||||
<TouchableOpacity onPress={onClose} hitSlop={12}>
|
||||
<Text style={[styles.close, { color: textColor }]}>✕</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
{children}
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
backdrop: {
|
||||
flex: 1,
|
||||
backgroundColor: "rgba(0,0,0,0.4)",
|
||||
justifyContent: "flex-end",
|
||||
},
|
||||
sheet: {
|
||||
borderTopLeftRadius: 16,
|
||||
borderTopRightRadius: 16,
|
||||
paddingBottom: 24,
|
||||
},
|
||||
sheetTall: {
|
||||
maxHeight: "75%",
|
||||
},
|
||||
header: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
padding: 16,
|
||||
},
|
||||
headerTitle: {
|
||||
fontSize: 16,
|
||||
fontWeight: "700",
|
||||
},
|
||||
close: {
|
||||
fontSize: 18,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { type ReactNode } from "react";
|
||||
import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
|
||||
import { resolvePalette } from "../../utils/epubTheme";
|
||||
import type { ReadingSettings } from "../../types/reader";
|
||||
|
||||
interface ReaderToolbarProps {
|
||||
title: string;
|
||||
chapterTitle: string;
|
||||
progressPct: number;
|
||||
settings: ReadingSettings;
|
||||
isBookmarked: boolean;
|
||||
onBack: () => void;
|
||||
onToggleToc: () => void;
|
||||
onToggleSettings: () => void;
|
||||
onToggleBookmarks: () => void;
|
||||
onToggleBookmarkHere: () => void;
|
||||
}
|
||||
|
||||
export function ReaderToolbar({
|
||||
title,
|
||||
chapterTitle,
|
||||
progressPct,
|
||||
settings,
|
||||
isBookmarked,
|
||||
onBack,
|
||||
onToggleToc,
|
||||
onToggleSettings,
|
||||
onToggleBookmarks,
|
||||
onToggleBookmarkHere,
|
||||
}: ReaderToolbarProps): ReactNode {
|
||||
const palette = resolvePalette(settings);
|
||||
|
||||
return (
|
||||
<View style={[styles.bar, { backgroundColor: palette.chrome }]}>
|
||||
<View style={styles.row}>
|
||||
<TouchableOpacity
|
||||
onPress={onBack}
|
||||
hitSlop={12}
|
||||
style={styles.iconButton}
|
||||
>
|
||||
<Text style={[styles.icon, { color: palette.text }]}>‹</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
<View style={styles.titles}>
|
||||
<Text
|
||||
style={[styles.title, { color: palette.text }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{title}
|
||||
</Text>
|
||||
{chapterTitle ? (
|
||||
<Text
|
||||
style={[styles.chapter, { color: palette.text }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{chapterTitle}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<TouchableOpacity
|
||||
onPress={onToggleBookmarkHere}
|
||||
hitSlop={12}
|
||||
style={styles.iconButton}
|
||||
>
|
||||
<Text style={[styles.icon, { color: palette.text }]}>
|
||||
{isBookmarked ? "★" : "☆"}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
onPress={onToggleBookmarks}
|
||||
hitSlop={12}
|
||||
style={styles.iconButton}
|
||||
>
|
||||
<Text style={[styles.iconSmall, { color: palette.text }]}>≡</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
onPress={onToggleToc}
|
||||
hitSlop={12}
|
||||
style={styles.iconButton}
|
||||
>
|
||||
<Text style={[styles.iconSmall, { color: palette.text }]}>⊟</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
onPress={onToggleSettings}
|
||||
hitSlop={12}
|
||||
style={styles.iconButton}
|
||||
>
|
||||
<Text style={[styles.iconSmall, { color: palette.text }]}>Aa</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<View style={styles.progressTrack}>
|
||||
<View
|
||||
style={[
|
||||
styles.progressFill,
|
||||
{ width: `${Math.min(100, Math.max(0, progressPct))}%` },
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
bar: {
|
||||
paddingTop: 8,
|
||||
paddingHorizontal: 8,
|
||||
paddingBottom: 6,
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
},
|
||||
titles: {
|
||||
flex: 1,
|
||||
marginHorizontal: 8,
|
||||
},
|
||||
title: {
|
||||
fontSize: 14,
|
||||
fontWeight: "600",
|
||||
},
|
||||
chapter: {
|
||||
fontSize: 11,
|
||||
opacity: 0.7,
|
||||
},
|
||||
iconButton: {
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 4,
|
||||
minWidth: 28,
|
||||
alignItems: "center",
|
||||
},
|
||||
icon: {
|
||||
fontSize: 28,
|
||||
lineHeight: 30,
|
||||
},
|
||||
iconSmall: {
|
||||
fontSize: 17,
|
||||
fontWeight: "600",
|
||||
},
|
||||
progressTrack: {
|
||||
height: 3,
|
||||
borderRadius: 2,
|
||||
backgroundColor: "rgba(127,127,127,0.25)",
|
||||
marginTop: 6,
|
||||
overflow: "hidden",
|
||||
},
|
||||
progressFill: {
|
||||
height: "100%",
|
||||
backgroundColor: "#4f8ef7",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import { type ReactNode } from "react";
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
TouchableOpacity,
|
||||
StyleSheet,
|
||||
} from "react-native";
|
||||
import { resolvePalette, THEME_PALETTES } from "../../utils/epubTheme";
|
||||
import type {
|
||||
FontFamily,
|
||||
ReadingSettings,
|
||||
ThemePreset,
|
||||
} from "../../types/reader";
|
||||
import { ReaderBottomSheet } from "./ReaderBottomSheet";
|
||||
|
||||
const THEMES: ThemePreset[] = ["light", "sepia", "paper", "dark"];
|
||||
const FONTS: { value: FontFamily; label: string }[] = [
|
||||
{ value: "serif", label: "Serif" },
|
||||
{ value: "sans-serif", label: "Sans" },
|
||||
{ value: "monospace", label: "Mono" },
|
||||
];
|
||||
const FONT_SIZE_MIN = 12;
|
||||
const FONT_SIZE_MAX = 32;
|
||||
const LINE_HEIGHT_MIN = 1.2;
|
||||
const LINE_HEIGHT_MAX = 2.2;
|
||||
|
||||
interface ReadingSettingsModalProps {
|
||||
visible: boolean;
|
||||
settings: ReadingSettings;
|
||||
onChange: (patch: Partial<ReadingSettings>) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ReadingSettingsModal({
|
||||
visible,
|
||||
settings,
|
||||
onChange,
|
||||
onClose,
|
||||
}: ReadingSettingsModalProps): ReactNode {
|
||||
const palette = resolvePalette(settings);
|
||||
|
||||
const adjustFontSize = (delta: number) => {
|
||||
const next = Math.min(
|
||||
FONT_SIZE_MAX,
|
||||
Math.max(FONT_SIZE_MIN, settings.font_size + delta),
|
||||
);
|
||||
onChange({ font_size: next });
|
||||
};
|
||||
|
||||
const adjustLineHeight = (delta: number) => {
|
||||
const next = Math.min(
|
||||
LINE_HEIGHT_MAX,
|
||||
Math.max(
|
||||
LINE_HEIGHT_MIN,
|
||||
Math.round((settings.line_height + delta) * 10) / 10,
|
||||
),
|
||||
);
|
||||
onChange({ line_height: next });
|
||||
};
|
||||
|
||||
return (
|
||||
<ReaderBottomSheet
|
||||
visible={visible}
|
||||
title="Display"
|
||||
chromeColor={palette.chrome}
|
||||
textColor={palette.text}
|
||||
onClose={onClose}
|
||||
tall={false}
|
||||
sheetStyle={styles.sheetBody}
|
||||
>
|
||||
<Text style={[styles.sectionLabel, { color: palette.text }]}>Theme</Text>
|
||||
<View style={styles.rowWrap}>
|
||||
{THEMES.map((theme) => {
|
||||
const p = THEME_PALETTES[theme];
|
||||
const active = settings.theme === theme;
|
||||
return (
|
||||
<TouchableOpacity
|
||||
key={theme}
|
||||
onPress={() =>
|
||||
onChange({
|
||||
theme,
|
||||
background_color: p.background,
|
||||
text_color: p.text,
|
||||
})
|
||||
}
|
||||
style={[
|
||||
styles.themeSwatch,
|
||||
{ backgroundColor: p.background },
|
||||
active && styles.themeSwatchActive,
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.themeSwatchText, { color: p.text }]}>
|
||||
Aa
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
<Text style={[styles.sectionLabel, { color: palette.text }]}>Font</Text>
|
||||
<View style={styles.rowWrap}>
|
||||
{FONTS.map((font) => {
|
||||
const active = settings.font_family === font.value;
|
||||
return (
|
||||
<TouchableOpacity
|
||||
key={font.value}
|
||||
onPress={() => onChange({ font_family: font.value })}
|
||||
style={[styles.pill, active && styles.pillActive]}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.pillText,
|
||||
{ color: active ? "#fff" : palette.text },
|
||||
]}
|
||||
>
|
||||
{font.label}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
<Stepper
|
||||
label="Font size"
|
||||
value={`${settings.font_size}px`}
|
||||
color={palette.text}
|
||||
onDecrease={() => adjustFontSize(-1)}
|
||||
onIncrease={() => adjustFontSize(1)}
|
||||
/>
|
||||
<Stepper
|
||||
label="Line spacing"
|
||||
value={settings.line_height.toFixed(1)}
|
||||
color={palette.text}
|
||||
onDecrease={() => adjustLineHeight(-0.1)}
|
||||
onIncrease={() => adjustLineHeight(0.1)}
|
||||
/>
|
||||
</ReaderBottomSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function Stepper({
|
||||
label,
|
||||
value,
|
||||
color,
|
||||
onDecrease,
|
||||
onIncrease,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
color: string;
|
||||
onDecrease: () => void;
|
||||
onIncrease: () => void;
|
||||
}): ReactNode {
|
||||
return (
|
||||
<View style={styles.stepperRow}>
|
||||
<Text style={[styles.sectionLabel, { color, marginBottom: 0 }]}>
|
||||
{label}
|
||||
</Text>
|
||||
<View style={styles.stepperControls}>
|
||||
<TouchableOpacity style={styles.stepperButton} onPress={onDecrease}>
|
||||
<Text style={styles.stepperButtonText}>−</Text>
|
||||
</TouchableOpacity>
|
||||
<Text style={[styles.stepperValue, { color }]}>{value}</Text>
|
||||
<TouchableOpacity style={styles.stepperButton} onPress={onIncrease}>
|
||||
<Text style={styles.stepperButtonText}>+</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
sheetBody: {
|
||||
paddingHorizontal: 20,
|
||||
paddingBottom: 32,
|
||||
},
|
||||
sectionLabel: {
|
||||
fontSize: 13,
|
||||
fontWeight: "600",
|
||||
marginBottom: 8,
|
||||
marginTop: 8,
|
||||
opacity: 0.8,
|
||||
},
|
||||
rowWrap: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
gap: 10,
|
||||
},
|
||||
themeSwatch: {
|
||||
width: 56,
|
||||
height: 48,
|
||||
borderRadius: 10,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
borderWidth: 2,
|
||||
borderColor: "transparent",
|
||||
},
|
||||
themeSwatchActive: {
|
||||
borderColor: "#4f8ef7",
|
||||
},
|
||||
themeSwatchText: {
|
||||
fontSize: 16,
|
||||
fontWeight: "600",
|
||||
},
|
||||
pill: {
|
||||
paddingHorizontal: 16,
|
||||
paddingVertical: 8,
|
||||
borderRadius: 20,
|
||||
borderWidth: 1,
|
||||
borderColor: "rgba(127,127,127,0.4)",
|
||||
},
|
||||
pillActive: {
|
||||
backgroundColor: "#4f8ef7",
|
||||
borderColor: "#4f8ef7",
|
||||
},
|
||||
pillText: {
|
||||
fontSize: 14,
|
||||
fontWeight: "600",
|
||||
},
|
||||
stepperRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
marginTop: 16,
|
||||
},
|
||||
stepperControls: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
},
|
||||
stepperButton: {
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: 18,
|
||||
backgroundColor: "rgba(127,127,127,0.2)",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
stepperButtonText: {
|
||||
fontSize: 20,
|
||||
fontWeight: "700",
|
||||
color: "#4f8ef7",
|
||||
},
|
||||
stepperValue: {
|
||||
minWidth: 56,
|
||||
textAlign: "center",
|
||||
fontSize: 15,
|
||||
fontWeight: "600",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { type ReactNode } from "react";
|
||||
import {
|
||||
Text,
|
||||
FlatList,
|
||||
TouchableOpacity,
|
||||
StyleSheet,
|
||||
} from "react-native";
|
||||
import { resolvePalette } from "../../utils/epubTheme";
|
||||
import type { ReadingSettings } from "../../types/reader";
|
||||
import { ReaderBottomSheet } from "./ReaderBottomSheet";
|
||||
|
||||
export interface TocItem {
|
||||
id?: string;
|
||||
label: string;
|
||||
href: string;
|
||||
subitems?: TocItem[];
|
||||
}
|
||||
|
||||
interface FlatTocItem {
|
||||
key: string;
|
||||
label: string;
|
||||
href: string;
|
||||
depth: number;
|
||||
}
|
||||
|
||||
function flatten(items: TocItem[], depth = 0, acc: FlatTocItem[] = []) {
|
||||
items.forEach((item, index) => {
|
||||
acc.push({
|
||||
key: `${item.id ?? item.href}-${depth}-${index}`,
|
||||
label: (item.label ?? "").trim() || "Untitled section",
|
||||
href: item.href,
|
||||
depth,
|
||||
});
|
||||
if (item.subitems?.length) {
|
||||
flatten(item.subitems, depth + 1, acc);
|
||||
}
|
||||
});
|
||||
return acc;
|
||||
}
|
||||
|
||||
interface TocModalProps {
|
||||
visible: boolean;
|
||||
toc: TocItem[];
|
||||
settings: ReadingSettings;
|
||||
onSelect: (href: string) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function TocModal({
|
||||
visible,
|
||||
toc,
|
||||
settings,
|
||||
onSelect,
|
||||
onClose,
|
||||
}: TocModalProps): ReactNode {
|
||||
const palette = resolvePalette(settings);
|
||||
const data = flatten(toc);
|
||||
|
||||
return (
|
||||
<ReaderBottomSheet
|
||||
visible={visible}
|
||||
title="Contents"
|
||||
chromeColor={palette.chrome}
|
||||
textColor={palette.text}
|
||||
onClose={onClose}
|
||||
>
|
||||
<FlatList
|
||||
data={data}
|
||||
keyExtractor={(item) => item.key}
|
||||
ListEmptyComponent={
|
||||
<Text style={[styles.empty, { color: palette.text }]}>
|
||||
No table of contents available.
|
||||
</Text>
|
||||
}
|
||||
renderItem={({ item }) => (
|
||||
<TouchableOpacity
|
||||
style={styles.row}
|
||||
onPress={() => onSelect(item.href)}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.rowText,
|
||||
{ color: palette.text, marginLeft: item.depth * 16 },
|
||||
]}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{item.label}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
/>
|
||||
</ReaderBottomSheet>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
row: {
|
||||
paddingVertical: 12,
|
||||
paddingHorizontal: 16,
|
||||
borderTopWidth: StyleSheet.hairlineWidth,
|
||||
borderTopColor: "rgba(127,127,127,0.2)",
|
||||
},
|
||||
rowText: {
|
||||
fontSize: 14,
|
||||
},
|
||||
empty: {
|
||||
padding: 24,
|
||||
textAlign: "center",
|
||||
opacity: 0.7,
|
||||
},
|
||||
});
|
||||
@@ -1,2 +0,0 @@
|
||||
export { useAuth } from "../context/AuthContext";
|
||||
export { useAsyncData } from "./useAsyncData";
|
||||
@@ -1,33 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
|
||||
/**
|
||||
* Generic async data fetching hook for mobile screens.
|
||||
*/
|
||||
export function useAsyncData<T>(
|
||||
fetcher: () => Promise<T>,
|
||||
deps: unknown[] = [],
|
||||
) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
const execute = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await fetcher();
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err : new Error(String(err)));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, deps);
|
||||
|
||||
useEffect(() => {
|
||||
execute();
|
||||
}, [execute]);
|
||||
|
||||
return { data, loading, error, refetch: execute };
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user