Archived
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a86cf8388 | ||
|
|
26c5f6f06b | ||
|
|
22ded87250 |
@@ -0,0 +1,23 @@
|
|||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
from apps.groups.models import GroupMembership, MemberProgress, ReadingGroup
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(ReadingGroup)
|
||||||
|
class ReadingGroupAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ["name", "ebook", "created_by", "created_at"]
|
||||||
|
search_fields = ["name", "ebook__title", "created_by__email"]
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(GroupMembership)
|
||||||
|
class GroupMembershipAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ["group", "user", "role", "joined_at"]
|
||||||
|
list_filter = ["role"]
|
||||||
|
search_fields = ["user__email", "group__name"]
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(MemberProgress)
|
||||||
|
class MemberProgressAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ["user", "group", "current_section", "percentage", "time_spent_seconds", "is_public", "updated_at"]
|
||||||
|
list_filter = ["is_public"]
|
||||||
|
search_fields = ["user__email", "group__name"]
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class GroupsConfig(AppConfig):
|
||||||
|
default_auto_field = "django.db.models.BigAutoField"
|
||||||
|
name = "apps.groups"
|
||||||
|
verbose_name = "Reading Groups"
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# Generated by Django 5.1.7 on 2026-06-20 19:21
|
||||||
|
|
||||||
|
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'),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
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)),
|
||||||
|
('updated_at', models.DateTimeField(auto_now=True)),
|
||||||
|
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='created_groups', to=settings.AUTH_USER_MODEL)),
|
||||||
|
('ebook', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, 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='GroupMembership',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('role', models.CharField(choices=[('member', 'Member'), ('admin', 'Admin')], 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',
|
||||||
|
'ordering': ['joined_at'],
|
||||||
|
'unique_together': {('group', 'user')},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='MemberProgress',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('current_section', models.PositiveIntegerField(default=0)),
|
||||||
|
('percentage', models.FloatField(default=0.0)),
|
||||||
|
('time_spent_seconds', models.PositiveIntegerField(default=0)),
|
||||||
|
('last_position', models.JSONField(blank=True, default=dict)),
|
||||||
|
('is_public', models.BooleanField(default=True)),
|
||||||
|
('updated_at', models.DateTimeField(auto_now=True)),
|
||||||
|
('membership', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='progress', to='groups.groupmembership')),
|
||||||
|
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='member_progress', to=settings.AUTH_USER_MODEL)),
|
||||||
|
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='member_progress', to='groups.readinggroup')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'Member Progress',
|
||||||
|
'verbose_name_plural': 'Member Progress',
|
||||||
|
'db_table': 'groups_member_progress',
|
||||||
|
'indexes': [models.Index(fields=['group', '-percentage'], name='groups_memb_group_i_42e333_idx'), models.Index(fields=['group', 'user'], name='groups_memb_group_i_f50793_idx')],
|
||||||
|
'unique_together': {('group', 'user')},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroup(models.Model):
|
||||||
|
"""A group of users reading the same book together."""
|
||||||
|
|
||||||
|
name = models.CharField(max_length=256, db_index=True)
|
||||||
|
ebook = models.ForeignKey(
|
||||||
|
"books.EBook",
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="reading_groups",
|
||||||
|
)
|
||||||
|
created_by = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="created_groups",
|
||||||
|
)
|
||||||
|
description = models.TextField(blank=True, default="")
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
updated_at = models.DateTimeField(auto_now=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
|
||||||
|
|
||||||
|
@property
|
||||||
|
def total_sections(self) -> int:
|
||||||
|
return self.ebook.chapters.count()
|
||||||
|
|
||||||
|
|
||||||
|
class GroupMembership(models.Model):
|
||||||
|
class Role(models.TextChoices):
|
||||||
|
MEMBER = "member", "Member"
|
||||||
|
ADMIN = "admin", "Admin"
|
||||||
|
|
||||||
|
group = models.ForeignKey(
|
||||||
|
ReadingGroup,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="memberships",
|
||||||
|
)
|
||||||
|
user = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="group_memberships",
|
||||||
|
)
|
||||||
|
role = models.CharField(
|
||||||
|
max_length=16,
|
||||||
|
choices=Role.choices,
|
||||||
|
default=Role.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 = [("group", "user")]
|
||||||
|
ordering = ["joined_at"]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"{self.user} in {self.group.name} ({self.role})"
|
||||||
|
|
||||||
|
|
||||||
|
class MemberProgress(models.Model):
|
||||||
|
"""Per-member reading progress within a reading group."""
|
||||||
|
|
||||||
|
membership = models.OneToOneField(
|
||||||
|
GroupMembership,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="progress",
|
||||||
|
)
|
||||||
|
group = models.ForeignKey(
|
||||||
|
ReadingGroup,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="member_progress",
|
||||||
|
)
|
||||||
|
user = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="member_progress",
|
||||||
|
)
|
||||||
|
current_section = models.PositiveIntegerField(default=0)
|
||||||
|
percentage = models.FloatField(default=0.0)
|
||||||
|
time_spent_seconds = models.PositiveIntegerField(default=0)
|
||||||
|
last_position = models.JSONField(blank=True, default=dict)
|
||||||
|
is_public = models.BooleanField(default=True)
|
||||||
|
updated_at = models.DateTimeField(auto_now=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
db_table = "groups_member_progress"
|
||||||
|
verbose_name = "Member Progress"
|
||||||
|
verbose_name_plural = "Member Progress"
|
||||||
|
unique_together = [("group", "user")]
|
||||||
|
indexes = [
|
||||||
|
models.Index(fields=["group", "-percentage"]),
|
||||||
|
models.Index(fields=["group", "user"]),
|
||||||
|
]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"{self.user} — {self.group.name} ({self.percentage:.0f}%)"
|
||||||
|
|
||||||
|
def total_sections(self) -> int:
|
||||||
|
return self.group.total_sections
|
||||||
|
|
||||||
|
def update_progress(
|
||||||
|
self,
|
||||||
|
current_section: int,
|
||||||
|
percentage: float | None = None,
|
||||||
|
time_spent_delta: int = 0,
|
||||||
|
last_position: dict | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update progress with computed percentage if not provided."""
|
||||||
|
self.current_section = current_section
|
||||||
|
if percentage is not None:
|
||||||
|
self.percentage = min(100.0, max(0.0, percentage))
|
||||||
|
elif (ts := self.total_sections()) > 0:
|
||||||
|
self.percentage = min(100.0, (current_section / ts) * 100.0)
|
||||||
|
else:
|
||||||
|
self.percentage = 0.0
|
||||||
|
if time_spent_delta > 0:
|
||||||
|
self.time_spent_seconds += time_spent_delta
|
||||||
|
if last_position is not None:
|
||||||
|
self.last_position = last_position
|
||||||
|
self.save(
|
||||||
|
update_fields=[
|
||||||
|
"current_section",
|
||||||
|
"percentage",
|
||||||
|
"time_spent_seconds",
|
||||||
|
"last_position",
|
||||||
|
"updated_at",
|
||||||
|
]
|
||||||
|
)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
from rest_framework import permissions
|
||||||
|
from rest_framework.request import Request
|
||||||
|
|
||||||
|
from apps.groups.models import GroupMembership
|
||||||
|
|
||||||
|
|
||||||
|
class IsGroupMember(permissions.BasePermission):
|
||||||
|
"""Allow access only to members of the group."""
|
||||||
|
|
||||||
|
def has_permission(self, request: Request, view: object) -> bool:
|
||||||
|
group_id = view.kwargs.get("group_pk") or view.kwargs.get("pk")
|
||||||
|
if not group_id:
|
||||||
|
return False
|
||||||
|
return GroupMembership.objects.filter(
|
||||||
|
group_id=group_id, user=request.user
|
||||||
|
).exists()
|
||||||
|
|
||||||
|
|
||||||
|
class IsGroupAdmin(permissions.BasePermission):
|
||||||
|
"""Allow access only to group admins."""
|
||||||
|
|
||||||
|
def has_permission(self, request: Request, view: object) -> bool:
|
||||||
|
group_id = view.kwargs.get("group_pk") or view.kwargs.get("pk")
|
||||||
|
if not group_id:
|
||||||
|
return False
|
||||||
|
return GroupMembership.objects.filter(
|
||||||
|
group_id=group_id, user=request.user, role=GroupMembership.Role.ADMIN
|
||||||
|
).exists()
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
from apps.groups.models import GroupMembership, MemberProgress, ReadingGroup
|
||||||
|
|
||||||
|
|
||||||
|
class GroupMembershipSerializer(serializers.ModelSerializer):
|
||||||
|
user_email = serializers.CharField(source="user.email", read_only=True)
|
||||||
|
user_id = serializers.IntegerField(source="user.id", read_only=True)
|
||||||
|
role = serializers.CharField(read_only=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = GroupMembership
|
||||||
|
fields = ["id", "user_id", "user_email", "role", "joined_at"]
|
||||||
|
|
||||||
|
|
||||||
|
class MemberProgressSerializer(serializers.ModelSerializer):
|
||||||
|
user_email = serializers.CharField(source="user.email", read_only=True)
|
||||||
|
user_id = serializers.IntegerField(source="user.id", read_only=True)
|
||||||
|
total_sections = serializers.SerializerMethodField()
|
||||||
|
section_label = serializers.SerializerMethodField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = MemberProgress
|
||||||
|
fields = [
|
||||||
|
"id",
|
||||||
|
"user_id",
|
||||||
|
"user_email",
|
||||||
|
"current_section",
|
||||||
|
"total_sections",
|
||||||
|
"section_label",
|
||||||
|
"percentage",
|
||||||
|
"time_spent_seconds",
|
||||||
|
"last_position",
|
||||||
|
"is_public",
|
||||||
|
"updated_at",
|
||||||
|
]
|
||||||
|
read_only_fields = ["id", "user_id", "user_email", "updated_at"]
|
||||||
|
extra_kwargs = {
|
||||||
|
"percentage": {"required": False, "min_value": 0.0, "max_value": 100.0},
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_total_sections(self, obj: MemberProgress) -> int:
|
||||||
|
return obj.total_sections()
|
||||||
|
|
||||||
|
def get_section_label(self, obj: MemberProgress) -> str:
|
||||||
|
ts = obj.total_sections()
|
||||||
|
if ts:
|
||||||
|
return f"Section {obj.current_section} of {ts}"
|
||||||
|
return "No sections"
|
||||||
|
|
||||||
|
def validate_percentage(self, value: float) -> float:
|
||||||
|
if value < 0.0 or value > 100.0:
|
||||||
|
raise serializers.ValidationError("Percentage must be between 0.0 and 100.0.")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class MemberProgressPublicSerializer(serializers.ModelSerializer):
|
||||||
|
"""Limited view for other group members — section label only, no exact position."""
|
||||||
|
|
||||||
|
user_email = serializers.CharField(source="user.email", read_only=True)
|
||||||
|
user_id = serializers.IntegerField(source="user.id", read_only=True)
|
||||||
|
total_sections = serializers.SerializerMethodField()
|
||||||
|
section_label = serializers.SerializerMethodField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = MemberProgress
|
||||||
|
fields = [
|
||||||
|
"user_id",
|
||||||
|
"user_email",
|
||||||
|
"current_section",
|
||||||
|
"total_sections",
|
||||||
|
"section_label",
|
||||||
|
"percentage",
|
||||||
|
"time_spent_seconds",
|
||||||
|
"updated_at",
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_total_sections(self, obj: MemberProgress) -> int:
|
||||||
|
return obj.total_sections()
|
||||||
|
|
||||||
|
def get_section_label(self, obj: MemberProgress) -> str:
|
||||||
|
ts = obj.total_sections()
|
||||||
|
if ts:
|
||||||
|
return f"Section {obj.current_section} of {ts}"
|
||||||
|
return "No sections"
|
||||||
|
|
||||||
|
|
||||||
|
class MemberProgressUpdateSerializer(serializers.Serializer):
|
||||||
|
current_section = serializers.IntegerField(min_value=0)
|
||||||
|
percentage = serializers.FloatField(required=False, min_value=0.0, max_value=100.0)
|
||||||
|
time_spent_delta = serializers.IntegerField(default=0, min_value=0)
|
||||||
|
last_position = serializers.JSONField(required=False, default=dict)
|
||||||
|
is_public = serializers.BooleanField(required=False)
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupListSerializer(serializers.ModelSerializer):
|
||||||
|
created_by_email = serializers.CharField(source="created_by.email", read_only=True)
|
||||||
|
ebook_title = serializers.CharField(source="ebook.title", read_only=True)
|
||||||
|
ebook_author = serializers.CharField(source="ebook.author", read_only=True)
|
||||||
|
member_count = serializers.SerializerMethodField()
|
||||||
|
my_progress = serializers.SerializerMethodField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = ReadingGroup
|
||||||
|
fields = [
|
||||||
|
"id",
|
||||||
|
"name",
|
||||||
|
"ebook",
|
||||||
|
"ebook_title",
|
||||||
|
"ebook_author",
|
||||||
|
"created_by_email",
|
||||||
|
"description",
|
||||||
|
"member_count",
|
||||||
|
"my_progress",
|
||||||
|
"created_at",
|
||||||
|
"updated_at",
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_member_count(self, obj: ReadingGroup) -> int:
|
||||||
|
return obj.memberships.count()
|
||||||
|
|
||||||
|
def get_my_progress(self, obj: ReadingGroup) -> dict | None:
|
||||||
|
request = self.context.get("request")
|
||||||
|
if not request or not request.user.is_authenticated:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
mp = MemberProgress.objects.get(group=obj, user=request.user)
|
||||||
|
except MemberProgress.DoesNotExist:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"current_section": mp.current_section,
|
||||||
|
"percentage": mp.percentage,
|
||||||
|
"time_spent_seconds": mp.time_spent_seconds,
|
||||||
|
"section_label": MemberProgressSerializer().get_section_label(mp),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupDetailSerializer(ReadingGroupListSerializer):
|
||||||
|
members = serializers.SerializerMethodField()
|
||||||
|
|
||||||
|
class Meta(ReadingGroupListSerializer.Meta):
|
||||||
|
fields = ReadingGroupListSerializer.Meta.fields + ["members"]
|
||||||
|
|
||||||
|
def get_members(self, obj: ReadingGroup) -> list[dict]:
|
||||||
|
memberships = obj.memberships.select_related("user").prefetch_related("progress")
|
||||||
|
result: list[dict] = []
|
||||||
|
for m in memberships:
|
||||||
|
entry: dict = {
|
||||||
|
"id": m.id,
|
||||||
|
"user_id": m.user.id,
|
||||||
|
"user_email": m.user.email,
|
||||||
|
"role": m.role,
|
||||||
|
"joined_at": m.joined_at,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
mp = m.progress
|
||||||
|
except MemberProgress.DoesNotExist:
|
||||||
|
entry["progress"] = None
|
||||||
|
else:
|
||||||
|
if mp.is_public:
|
||||||
|
entry["progress"] = MemberProgressPublicSerializer(mp).data
|
||||||
|
else:
|
||||||
|
entry["progress"] = {"is_public": False, "note": "Private"}
|
||||||
|
result.append(entry)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupCreateSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = ReadingGroup
|
||||||
|
fields = ["name", "ebook", "description"]
|
||||||
|
|
||||||
|
|
||||||
|
class AdminProgressSummarySerializer(serializers.Serializer):
|
||||||
|
group_id = serializers.IntegerField()
|
||||||
|
group_name = serializers.CharField()
|
||||||
|
ebook_title = serializers.CharField()
|
||||||
|
total_members = serializers.IntegerField()
|
||||||
|
members_started = serializers.IntegerField()
|
||||||
|
members_finished = serializers.IntegerField()
|
||||||
|
average_percentage = serializers.FloatField()
|
||||||
|
average_time_spent_hours = serializers.FloatField()
|
||||||
|
member_details = serializers.ListField(child=serializers.JSONField())
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
from django.urls import include, path
|
||||||
|
from rest_framework.routers import DefaultRouter
|
||||||
|
|
||||||
|
from apps.groups.views import ReadingGroupViewSet
|
||||||
|
|
||||||
|
router = DefaultRouter()
|
||||||
|
router.register(r"", ReadingGroupViewSet, basename="reading-group")
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("", include(router.urls)),
|
||||||
|
]
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
from rest_framework import permissions, status, viewsets
|
||||||
|
from rest_framework.decorators import action
|
||||||
|
from rest_framework.request import Request
|
||||||
|
from rest_framework.response import Response
|
||||||
|
|
||||||
|
from apps.groups.models import GroupMembership, MemberProgress, ReadingGroup
|
||||||
|
from apps.groups.permissions import IsGroupAdmin, IsGroupMember
|
||||||
|
from apps.groups.serializers import (
|
||||||
|
AdminProgressSummarySerializer,
|
||||||
|
GroupMembershipSerializer,
|
||||||
|
MemberProgressPublicSerializer,
|
||||||
|
MemberProgressSerializer,
|
||||||
|
MemberProgressUpdateSerializer,
|
||||||
|
ReadingGroupCreateSerializer,
|
||||||
|
ReadingGroupDetailSerializer,
|
||||||
|
ReadingGroupListSerializer,
|
||||||
|
)
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupViewSet(viewsets.ModelViewSet):
|
||||||
|
permission_classes = [permissions.IsAuthenticated]
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
return (
|
||||||
|
ReadingGroup.objects.filter(memberships__user=self.request.user)
|
||||||
|
.select_related("ebook", "created_by")
|
||||||
|
.prefetch_related("memberships", "memberships__progress")
|
||||||
|
.distinct()
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_serializer_class(self):
|
||||||
|
if self.action == "create":
|
||||||
|
return ReadingGroupCreateSerializer
|
||||||
|
if self.action == "retrieve":
|
||||||
|
return ReadingGroupDetailSerializer
|
||||||
|
return ReadingGroupListSerializer
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
group = serializer.save(created_by=self.request.user)
|
||||||
|
# Creator automatically becomes admin member
|
||||||
|
GroupMembership.objects.create(
|
||||||
|
group=group,
|
||||||
|
user=self.request.user,
|
||||||
|
role=GroupMembership.Role.ADMIN,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Membership ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@action(detail=True, methods=["post"], permission_classes=[IsGroupMember])
|
||||||
|
def join(self, request: Request, pk: int | None = None) -> Response:
|
||||||
|
"""Join a reading group (public join link)."""
|
||||||
|
group = self.get_object()
|
||||||
|
membership, created = GroupMembership.objects.get_or_create(
|
||||||
|
group=group, user=request.user
|
||||||
|
)
|
||||||
|
if not created:
|
||||||
|
return Response({"detail": "Already a member."}, status=status.HTTP_200_OK)
|
||||||
|
MemberProgress.objects.get_or_create(
|
||||||
|
membership=membership,
|
||||||
|
group=group,
|
||||||
|
user=request.user,
|
||||||
|
defaults={"current_section": 0, "percentage": 0.0},
|
||||||
|
)
|
||||||
|
return Response({"detail": "Joined successfully."}, status=status.HTTP_201_CREATED)
|
||||||
|
|
||||||
|
@action(detail=True, methods=["post"], permission_classes=[IsGroupMember])
|
||||||
|
def leave(self, request: Request, pk: int | None = None) -> Response:
|
||||||
|
"""Leave a reading group."""
|
||||||
|
group = self.get_object()
|
||||||
|
if group.created_by == request.user:
|
||||||
|
return Response(
|
||||||
|
{"error": "Group creator cannot leave. Transfer ownership or delete the group."},
|
||||||
|
status=status.HTTP_400_BAD_REQUEST,
|
||||||
|
)
|
||||||
|
GroupMembership.objects.filter(group=group, user=request.user).delete()
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
@action(detail=True, methods=["get"], permission_classes=[IsGroupMember])
|
||||||
|
def members(self, request: Request, pk: int | None = None) -> Response:
|
||||||
|
"""List group members with their progress."""
|
||||||
|
group = self.get_object()
|
||||||
|
memberships = (
|
||||||
|
group.memberships.select_related("user")
|
||||||
|
.prefetch_related("progress")
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
serializer = GroupMembershipSerializer(memberships, many=True)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
# ── Progress ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@action(detail=True, methods=["get"], permission_classes=[IsGroupMember],
|
||||||
|
url_path="members/progress")
|
||||||
|
def members_progress(self, request: Request, pk: int | None = None) -> Response:
|
||||||
|
"""Get progress for all group members.
|
||||||
|
|
||||||
|
Other members' progress shows section label only (no last_position).
|
||||||
|
Your own progress shows full detail.
|
||||||
|
"""
|
||||||
|
group = self.get_object()
|
||||||
|
progress_qs = (
|
||||||
|
MemberProgress.objects.filter(group=group)
|
||||||
|
.select_related("user")
|
||||||
|
.order_by("-percentage")
|
||||||
|
)
|
||||||
|
result: list[dict] = []
|
||||||
|
for mp in progress_qs:
|
||||||
|
if mp.user == request.user:
|
||||||
|
result.append(MemberProgressSerializer(mp).data)
|
||||||
|
elif mp.is_public:
|
||||||
|
result.append(MemberProgressPublicSerializer(mp).data)
|
||||||
|
else:
|
||||||
|
result.append({
|
||||||
|
"user_id": mp.user.id,
|
||||||
|
"user_email": mp.user.email,
|
||||||
|
"is_public": False,
|
||||||
|
"note": "Private",
|
||||||
|
})
|
||||||
|
return Response(result)
|
||||||
|
|
||||||
|
@action(detail=True, methods=["get", "patch"], permission_classes=[IsGroupMember],
|
||||||
|
url_path="progress")
|
||||||
|
def my_progress(self, request: Request, pk: int | None = None) -> Response:
|
||||||
|
"""Get or update my own progress in the group."""
|
||||||
|
group = self.get_object()
|
||||||
|
membership = GroupMembership.objects.get(group=group, user=request.user)
|
||||||
|
progress_obj, _created = MemberProgress.objects.get_or_create(
|
||||||
|
membership=membership,
|
||||||
|
group=group,
|
||||||
|
user=request.user,
|
||||||
|
)
|
||||||
|
|
||||||
|
if request.method == "GET":
|
||||||
|
serializer = MemberProgressSerializer(progress_obj)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
# PATCH — update progress
|
||||||
|
update_serializer = MemberProgressUpdateSerializer(data=request.data)
|
||||||
|
update_serializer.is_valid(raise_exception=True)
|
||||||
|
data = update_serializer.validated_data
|
||||||
|
|
||||||
|
progress_obj.update_progress(
|
||||||
|
current_section=data["current_section"],
|
||||||
|
percentage=data.get("percentage"),
|
||||||
|
time_spent_delta=data.get("time_spent_delta", 0),
|
||||||
|
last_position=data.get("last_position"),
|
||||||
|
)
|
||||||
|
if "is_public" in data:
|
||||||
|
progress_obj.is_public = data["is_public"]
|
||||||
|
progress_obj.save(update_fields=["is_public"])
|
||||||
|
|
||||||
|
serializer = MemberProgressSerializer(progress_obj)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
# ── Admin ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@action(detail=True, methods=["get"], permission_classes=[IsGroupAdmin],
|
||||||
|
url_path="progress/summary")
|
||||||
|
def progress_summary(self, request: Request, pk: int | None = None) -> Response:
|
||||||
|
"""Admin summary of all member progress."""
|
||||||
|
group = self.get_object()
|
||||||
|
progress_qs = MemberProgress.objects.filter(group=group).select_related("user")
|
||||||
|
|
||||||
|
total_members = group.memberships.count()
|
||||||
|
members_started = progress_qs.filter(current_section__gt=0).count()
|
||||||
|
members_finished = progress_qs.filter(percentage__gte=100.0).count()
|
||||||
|
|
||||||
|
avg_pct = progress_qs.aggregate(avg=models.Avg("percentage"))["avg"] or 0.0
|
||||||
|
avg_time = progress_qs.aggregate(avg=models.Avg("time_spent_seconds"))["avg"] or 0.0
|
||||||
|
|
||||||
|
member_details: list[dict] = []
|
||||||
|
for mp in progress_qs:
|
||||||
|
member_details.append({
|
||||||
|
"user_id": mp.user.id,
|
||||||
|
"user_email": mp.user.email,
|
||||||
|
"current_section": mp.current_section,
|
||||||
|
"percentage": mp.percentage,
|
||||||
|
"time_spent_seconds": mp.time_spent_seconds,
|
||||||
|
"is_public": mp.is_public,
|
||||||
|
"updated_at": mp.updated_at,
|
||||||
|
})
|
||||||
|
|
||||||
|
summary_data = {
|
||||||
|
"group_id": group.id,
|
||||||
|
"group_name": group.name,
|
||||||
|
"ebook_title": group.ebook.title,
|
||||||
|
"total_members": total_members,
|
||||||
|
"members_started": members_started,
|
||||||
|
"members_finished": members_finished,
|
||||||
|
"average_percentage": round(avg_pct, 1),
|
||||||
|
"average_time_spent_hours": round(avg_time / 3600.0, 1) if avg_time else 0.0,
|
||||||
|
"member_details": member_details,
|
||||||
|
}
|
||||||
|
serializer = AdminProgressSummarySerializer(data=summary_data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
return Response(serializer.data)
|
||||||
@@ -41,6 +41,7 @@ INSTALLED_APPS = [
|
|||||||
"apps.books",
|
"apps.books",
|
||||||
"apps.annotations",
|
"apps.annotations",
|
||||||
"apps.reader",
|
"apps.reader",
|
||||||
|
"apps.groups",
|
||||||
]
|
]
|
||||||
|
|
||||||
MIDDLEWARE = [
|
MIDDLEWARE = [
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ urlpatterns = [
|
|||||||
path("api/books/", include("apps.books.urls")),
|
path("api/books/", include("apps.books.urls")),
|
||||||
path("api/annotations/", include("apps.annotations.urls")),
|
path("api/annotations/", include("apps.annotations.urls")),
|
||||||
path("api/reader/", include("apps.reader.urls")),
|
path("api/reader/", include("apps.reader.urls")),
|
||||||
|
path("api/groups/", include("apps.groups.urls")),
|
||||||
]
|
]
|
||||||
|
|
||||||
if settings.DEBUG:
|
if settings.DEBUG:
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -12,6 +12,8 @@ const AddBookPage = lazy(() => import("./pages/AddBook").then((m) => ({ default:
|
|||||||
const SettingsPage = lazy(() => import("./pages/Settings").then((m) => ({ default: m.SettingsPage })));
|
const SettingsPage = lazy(() => import("./pages/Settings").then((m) => ({ default: m.SettingsPage })));
|
||||||
const BookmarksNotesPage = lazy(() => import("./components/annotations/BookmarksNotesPage").then((m) => ({ default: m.BookmarksNotesPage })));
|
const BookmarksNotesPage = lazy(() => import("./components/annotations/BookmarksNotesPage").then((m) => ({ default: m.BookmarksNotesPage })));
|
||||||
const ReadingPage = lazy(() => import("./pages/ReadingPage").then((m) => ({ default: m.default })));
|
const ReadingPage = lazy(() => import("./pages/ReadingPage").then((m) => ({ default: m.default })));
|
||||||
|
const ReadingGroupsPage = lazy(() => import("./pages/ReadingGroups").then((m) => ({ default: m.ReadingGroupsPage })));
|
||||||
|
const GroupDetailPage = lazy(() => import("./pages/GroupDetail").then((m) => ({ default: m.GroupDetailPage })));
|
||||||
|
|
||||||
const AuthPage = lazy(() => import("./pages/AuthPage"));
|
const AuthPage = lazy(() => import("./pages/AuthPage"));
|
||||||
|
|
||||||
@@ -45,6 +47,8 @@ function AppRoutes() {
|
|||||||
<Route path="/add" element={<ProtectedRoute><AddBookPage /></ProtectedRoute>} />
|
<Route path="/add" element={<ProtectedRoute><AddBookPage /></ProtectedRoute>} />
|
||||||
<Route path="/settings" element={<ProtectedRoute><SettingsPage /></ProtectedRoute>} />
|
<Route path="/settings" element={<ProtectedRoute><SettingsPage /></ProtectedRoute>} />
|
||||||
<Route path="/bookmarks-notes/:bookId?" element={<ProtectedRoute><BookmarksNotesPage /></ProtectedRoute>} />
|
<Route path="/bookmarks-notes/:bookId?" element={<ProtectedRoute><BookmarksNotesPage /></ProtectedRoute>} />
|
||||||
|
<Route path="/groups" element={<ProtectedRoute><ReadingGroupsPage /></ProtectedRoute>} />
|
||||||
|
<Route path="/groups/:id" element={<ProtectedRoute><GroupDetailPage /></ProtectedRoute>} />
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import api from "./client";
|
||||||
|
import type {
|
||||||
|
AdminProgressSummary,
|
||||||
|
CreateGroupPayload,
|
||||||
|
MemberProgressDetail,
|
||||||
|
MemberProgressEntry,
|
||||||
|
ReadingGroupDetail,
|
||||||
|
ReadingGroupSummary,
|
||||||
|
UpdateProgressPayload,
|
||||||
|
} from "../types/groups";
|
||||||
|
|
||||||
|
export const groupsApi = {
|
||||||
|
/* ── Groups ── */
|
||||||
|
|
||||||
|
async listGroups(): Promise<ReadingGroupSummary[]> {
|
||||||
|
const { data } = await api.get<ReadingGroupSummary[]>("/groups/");
|
||||||
|
if (Array.isArray(data)) return data;
|
||||||
|
return (data as { results: ReadingGroupSummary[] }).results ?? [];
|
||||||
|
},
|
||||||
|
|
||||||
|
async getGroup(id: number): Promise<ReadingGroupDetail> {
|
||||||
|
const { data } = await api.get<ReadingGroupDetail>(`/groups/${id}/`);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async createGroup(payload: CreateGroupPayload): Promise<ReadingGroupDetail> {
|
||||||
|
const { data } = await api.post<ReadingGroupDetail>("/groups/", payload);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async deleteGroup(id: number): Promise<void> {
|
||||||
|
await api.delete(`/groups/${id}/`);
|
||||||
|
},
|
||||||
|
|
||||||
|
/* ── Membership ── */
|
||||||
|
|
||||||
|
async joinGroup(id: number): Promise<{ detail: string }> {
|
||||||
|
const { data } = await api.post<{ detail: string }>(`/groups/${id}/join/`);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async leaveGroup(id: number): Promise<void> {
|
||||||
|
await api.post(`/groups/${id}/leave/`);
|
||||||
|
},
|
||||||
|
|
||||||
|
/* ── Progress ── */
|
||||||
|
|
||||||
|
async getMembersProgress(groupId: number): Promise<MemberProgressEntry[]> {
|
||||||
|
const { data } = await api.get<MemberProgressEntry[]>(
|
||||||
|
`/groups/${groupId}/members/progress/`,
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async getMyProgress(groupId: number): Promise<MemberProgressDetail> {
|
||||||
|
const { data } = await api.get<MemberProgressDetail>(
|
||||||
|
`/groups/${groupId}/progress/`,
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async updateMyProgress(
|
||||||
|
groupId: number,
|
||||||
|
payload: UpdateProgressPayload,
|
||||||
|
): Promise<MemberProgressDetail> {
|
||||||
|
const { data } = await api.patch<MemberProgressDetail>(
|
||||||
|
`/groups/${groupId}/progress/`,
|
||||||
|
payload,
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
/* ── Admin ── */
|
||||||
|
|
||||||
|
async getProgressSummary(groupId: number): Promise<AdminProgressSummary> {
|
||||||
|
const { data } = await api.get<AdminProgressSummary>(
|
||||||
|
`/groups/${groupId}/progress/summary/`,
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,381 @@
|
|||||||
|
import React, { useCallback, useEffect, useState } from "react";
|
||||||
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
|
import { useTranslation } from "react-i18n-lite";
|
||||||
|
import { groupsApi } from "../api/groups";
|
||||||
|
import type {
|
||||||
|
AdminProgressSummary,
|
||||||
|
MemberProgressEntry,
|
||||||
|
ReadingGroupDetail,
|
||||||
|
} from "../types/groups";
|
||||||
|
import { useMediaQuery, BREAKPOINTS } from "../hooks/useMediaQuery";
|
||||||
|
|
||||||
|
function isDetail(entry: MemberProgressEntry): entry is { user_id: number; is_public: boolean; id: number } {
|
||||||
|
return "id" in entry && "is_public" in entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GroupDetailPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const isMobile = useMediaQuery(BREAKPOINTS.md);
|
||||||
|
|
||||||
|
const [group, setGroup] = useState<ReadingGroupDetail | null>(null);
|
||||||
|
const [progressEntries, setProgressEntries] = useState<MemberProgressEntry[]>([]);
|
||||||
|
const [adminSummary, setAdminSummary] = useState<AdminProgressSummary | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [tab, setTab] = useState<"progress" | "admin">("progress");
|
||||||
|
|
||||||
|
const isAdmin = group?.members.some(
|
||||||
|
(m) => m.user_id === (group as ReadingGroupDetail & { _myUserId?: number })._myUserId && m.role === "admin",
|
||||||
|
);
|
||||||
|
|
||||||
|
const loadGroup = useCallback(async () => {
|
||||||
|
if (!id) return;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const groupId = Number(id);
|
||||||
|
if (Number.isNaN(groupId)) {
|
||||||
|
setError(t("groupDetail.invalidId") ?? "Invalid group ID");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const [groupData, progressData] = await Promise.all([
|
||||||
|
groupsApi.getGroup(groupId),
|
||||||
|
groupsApi.getMembersProgress(groupId).catch(() => [] as MemberProgressEntry[]),
|
||||||
|
]);
|
||||||
|
setGroup(groupData);
|
||||||
|
setProgressEntries(progressData);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Failed to load group");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [id, t]);
|
||||||
|
|
||||||
|
const loadAdminSummary = useCallback(async () => {
|
||||||
|
if (!id || !isAdmin) return;
|
||||||
|
try {
|
||||||
|
const summary = await groupsApi.getProgressSummary(Number(id));
|
||||||
|
setAdminSummary(summary);
|
||||||
|
} catch {
|
||||||
|
// Admin summary is optional
|
||||||
|
}
|
||||||
|
}, [id, isAdmin]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadGroup();
|
||||||
|
}, [loadGroup]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (tab === "admin") {
|
||||||
|
void loadAdminSummary();
|
||||||
|
}
|
||||||
|
}, [tab, loadAdminSummary]);
|
||||||
|
|
||||||
|
const handleJoin = useCallback(async () => {
|
||||||
|
if (!id) return;
|
||||||
|
try {
|
||||||
|
await groupsApi.joinGroup(Number(id));
|
||||||
|
void loadGroup();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Failed to join");
|
||||||
|
}
|
||||||
|
}, [id, loadGroup]);
|
||||||
|
|
||||||
|
const handleLeave = useCallback(async () => {
|
||||||
|
if (!id) return;
|
||||||
|
try {
|
||||||
|
await groupsApi.leaveGroup(Number(id));
|
||||||
|
navigate("/groups");
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Failed to leave");
|
||||||
|
}
|
||||||
|
}, [id, navigate]);
|
||||||
|
|
||||||
|
const containerStyle: React.CSSProperties = {
|
||||||
|
maxWidth: 720,
|
||||||
|
margin: "0 auto",
|
||||||
|
padding: isMobile ? 16 : 24,
|
||||||
|
minHeight: "100vh",
|
||||||
|
background: "#f8f9fa",
|
||||||
|
};
|
||||||
|
|
||||||
|
const backButtonStyle: React.CSSProperties = {
|
||||||
|
display: "inline-flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 4,
|
||||||
|
padding: isMobile ? "10px 16px" : "8px 16px",
|
||||||
|
borderRadius: 8,
|
||||||
|
border: "1px solid #e5e7eb",
|
||||||
|
background: "#fff",
|
||||||
|
color: "#374151",
|
||||||
|
fontSize: isMobile ? 15 : 14,
|
||||||
|
cursor: "pointer",
|
||||||
|
marginBottom: 20,
|
||||||
|
minHeight: 44,
|
||||||
|
};
|
||||||
|
|
||||||
|
const tabBarStyle: React.CSSProperties = {
|
||||||
|
display: "flex",
|
||||||
|
gap: 0,
|
||||||
|
marginBottom: 20,
|
||||||
|
borderBottom: "2px solid #e5e7eb",
|
||||||
|
};
|
||||||
|
|
||||||
|
const tabStyle = (active: boolean): React.CSSProperties => ({
|
||||||
|
padding: "10px 20px",
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: active ? 600 : 400,
|
||||||
|
color: active ? "#4f46e5" : "#6b7280",
|
||||||
|
background: "transparent",
|
||||||
|
border: "none",
|
||||||
|
borderBottom: active ? "2px solid #4f46e5" : "2px solid transparent",
|
||||||
|
cursor: "pointer",
|
||||||
|
marginBottom: -2,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div style={containerStyle}>
|
||||||
|
<div style={{ height: 32, width: 100, background: "#e5e7eb", borderRadius: 6, marginBottom: 20 }} />
|
||||||
|
<div style={{ height: 28, width: "50%", background: "#e5e7eb", borderRadius: 6, marginBottom: 16 }} />
|
||||||
|
{[1, 2, 3].map((i) => (
|
||||||
|
<div key={i} style={{ height: 60, background: "#e5e7eb", borderRadius: 8, marginBottom: 8 }} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error || !group) {
|
||||||
|
return (
|
||||||
|
<div style={containerStyle}>
|
||||||
|
<button onClick={() => navigate("/groups")} style={backButtonStyle}>
|
||||||
|
← {t("groupDetail.back") ?? "Back"}
|
||||||
|
</button>
|
||||||
|
<div style={{ textAlign: "center", padding: "60px 20px" }}>
|
||||||
|
<div style={{ fontSize: 48, marginBottom: 16 }}>😕</div>
|
||||||
|
<p style={{ color: "#6b7280", fontSize: 16 }}>
|
||||||
|
{error ?? (t("groupDetail.notFound") ?? "Group not found")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isMember = group.members.some((m) => {
|
||||||
|
// Determine membership by matching progress data — user_id can come from members list
|
||||||
|
// We check if there's a progress entry with an "id" (indicates own data)
|
||||||
|
return progressEntries.some((e) => "id" in e);
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={containerStyle}>
|
||||||
|
<button onClick={() => navigate("/groups")} style={backButtonStyle}>
|
||||||
|
← {t("groupDetail.back") ?? "Back to Groups"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Header */}
|
||||||
|
<div style={{ marginBottom: 20 }}>
|
||||||
|
<h1 style={{ fontSize: isMobile ? 20 : 24, fontWeight: 700, color: "#1f2937", margin: "0 0 4px" }}>
|
||||||
|
{group.name}
|
||||||
|
</h1>
|
||||||
|
<p style={{ fontSize: 14, color: "#6b7280", margin: 0 }}>
|
||||||
|
{group.ebook_title} {group.ebook_author ? `— ${group.ebook_author}` : ""}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Group actions */}
|
||||||
|
<div style={{ display: "flex", gap: 10, marginBottom: 20, flexWrap: "wrap" }}>
|
||||||
|
{!isMember ? (
|
||||||
|
<button
|
||||||
|
onClick={() => void handleJoin()}
|
||||||
|
style={{
|
||||||
|
padding: "10px 20px", borderRadius: 10, border: "none", background: "#4f46e5",
|
||||||
|
color: "#fff", fontSize: 14, fontWeight: 600, cursor: "pointer",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("groupDetail.join") ?? "Join Group"}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<span style={{
|
||||||
|
fontSize: 13, color: "#16a34a", background: "#dcfce7",
|
||||||
|
padding: "4px 12px", borderRadius: 999, display: "inline-flex", alignItems: "center",
|
||||||
|
}}>
|
||||||
|
✓ {t("groupDetail.member") ?? "Member"}
|
||||||
|
</span>
|
||||||
|
{group.created_by_email !== undefined /* can't check identity here, but leave is always available for non-creators */ && (
|
||||||
|
<button
|
||||||
|
onClick={() => void handleLeave()}
|
||||||
|
style={{
|
||||||
|
padding: "10px 20px", borderRadius: 10, border: "1px solid #fca5a5",
|
||||||
|
background: "#fff", color: "#b91c1c", fontSize: 14, cursor: "pointer",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("groupDetail.leave") ?? "Leave Group"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{group.description && (
|
||||||
|
<p style={{ fontSize: 14, color: "#4b5563", marginBottom: 20, lineHeight: 1.6, background: "#fff", padding: isMobile ? 12 : 16, borderRadius: 10, border: "1px solid #e5e7eb" }}>
|
||||||
|
{group.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div style={tabBarStyle}>
|
||||||
|
<button style={tabStyle(tab === "progress")} onClick={() => setTab("progress")}>
|
||||||
|
{t("groupDetail.progressTab") ?? "Progress"}
|
||||||
|
</button>
|
||||||
|
{isAdmin && (
|
||||||
|
<button style={tabStyle(tab === "admin")} onClick={() => setTab("admin")}>
|
||||||
|
{t("groupDetail.adminTab") ?? "Admin Summary"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Progress tab */}
|
||||||
|
{tab === "progress" && (
|
||||||
|
<div>
|
||||||
|
{progressEntries.length === 0 ? (
|
||||||
|
<div style={{ textAlign: "center", padding: "40px 20px", color: "#9ca3af" }}>
|
||||||
|
<p>{t("groupDetail.noProgress") ?? "No progress data yet."}</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
progressEntries.map((entry) => {
|
||||||
|
const isPrivate = "is_public" in entry && entry.is_public === false && "note" in entry;
|
||||||
|
const hasDetail = isDetail(entry);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={entry.user_id}
|
||||||
|
style={{
|
||||||
|
background: "#fff", borderRadius: 10, padding: isMobile ? 12 : 16,
|
||||||
|
marginBottom: 10, border: "1px solid #e5e7eb",
|
||||||
|
boxShadow: "0 1px 3px rgba(0,0,0,0.04)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
|
||||||
|
<span style={{ fontSize: 15, fontWeight: 600, color: "#1f2937" }}>
|
||||||
|
{entry.user_email}
|
||||||
|
{hasDetail && " (you)"}
|
||||||
|
</span>
|
||||||
|
{isPrivate ? (
|
||||||
|
<span style={{ fontSize: 12, color: "#9ca3af", fontStyle: "italic" }}>
|
||||||
|
🔒 {t("groupDetail.private") ?? "Private"}
|
||||||
|
</span>
|
||||||
|
) : "section_label" in entry && (
|
||||||
|
<span style={{ fontSize: 13, color: "#4f46e5", fontWeight: 500 }}>
|
||||||
|
{entry.section_label}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!isPrivate && "percentage" in entry && (
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 10 }}>
|
||||||
|
<div style={{
|
||||||
|
flex: 1, height: 8, borderRadius: 4, background: "#e5e7eb", overflow: "hidden",
|
||||||
|
}}>
|
||||||
|
<div style={{
|
||||||
|
height: "100%",
|
||||||
|
width: `${Math.min(100, entry.percentage)}%`,
|
||||||
|
background: hasDetail ? "#4f46e5" : "#818cf8",
|
||||||
|
borderRadius: 4,
|
||||||
|
transition: "width 0.3s ease",
|
||||||
|
}} />
|
||||||
|
</div>
|
||||||
|
<span style={{ fontSize: 13, fontWeight: 600, color: "#374151", whiteSpace: "nowrap" }}>
|
||||||
|
{Math.round(entry.percentage)}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hasDetail && entry.last_position && Object.keys(entry.last_position).length > 0 && (
|
||||||
|
<div style={{ marginTop: 8, fontSize: 12, color: "#9ca3af" }}>
|
||||||
|
{t("groupDetail.lastPosition") ?? "Last position"}: {JSON.stringify(entry.last_position)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Admin tab */}
|
||||||
|
{tab === "admin" && adminSummary && (
|
||||||
|
<div>
|
||||||
|
<div style={{
|
||||||
|
display: "grid",
|
||||||
|
gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))",
|
||||||
|
gap: 12,
|
||||||
|
marginBottom: 24,
|
||||||
|
}}>
|
||||||
|
<StatCard
|
||||||
|
label={t("groupDetail.totalMembers") ?? "Members"}
|
||||||
|
value={String(adminSummary.total_members)}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
label={t("groupDetail.started") ?? "Started"}
|
||||||
|
value={String(adminSummary.members_started)}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
label={t("groupDetail.finished") ?? "Finished"}
|
||||||
|
value={String(adminSummary.members_finished)}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
label={t("groupDetail.avgProgress") ?? "Avg Progress"}
|
||||||
|
value={`${Math.round(adminSummary.average_percentage)}%`}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
label={t("groupDetail.avgTime") ?? "Avg Time"}
|
||||||
|
value={`${adminSummary.average_time_spent_hours}h`}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3 style={{ fontSize: 15, fontWeight: 600, color: "#1f2937", marginBottom: 12 }}>
|
||||||
|
{t("groupDetail.memberDetails") ?? "Member Details"}
|
||||||
|
</h3>
|
||||||
|
{adminSummary.member_details.map((m) => (
|
||||||
|
<div
|
||||||
|
key={m.user_id}
|
||||||
|
style={{
|
||||||
|
background: "#fff", borderRadius: 10, padding: isMobile ? 12 : 14,
|
||||||
|
marginBottom: 8, border: "1px solid #e5e7eb",
|
||||||
|
display: "flex", justifyContent: "space-between", alignItems: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<span style={{ fontSize: 14, fontWeight: 500, color: "#1f2937" }}>{m.user_email}</span>
|
||||||
|
<span style={{ fontSize: 12, color: "#9ca3af", marginLeft: 8 }}>
|
||||||
|
{m.is_public ? "👁" : "🔒"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: "flex", gap: 16, fontSize: 13, color: "#6b7280" }}>
|
||||||
|
<span>Section {m.current_section}</span>
|
||||||
|
<span style={{ fontWeight: 600, color: "#4f46e5" }}>{Math.round(m.percentage)}%</span>
|
||||||
|
<span>⏱ {Math.round(m.time_spent_seconds / 60)}m</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatCard({ label, value }: { label: string; value: string }) {
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
background: "#fff", borderRadius: 10, padding: "14px 16px",
|
||||||
|
border: "1px solid #e5e7eb", textAlign: "center",
|
||||||
|
}}>
|
||||||
|
<div style={{ fontSize: 22, fontWeight: 700, color: "#4f46e5" }}>{value}</div>
|
||||||
|
<div style={{ fontSize: 12, color: "#6b7280", marginTop: 2 }}>{label}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -242,6 +242,7 @@ export function LibraryPage() {
|
|||||||
<>
|
<>
|
||||||
<button onClick={() => navigate("/add")} style={{ ...TOUCH_TARGET, fontSize: 20, background: "none", border: "none", cursor: "pointer", padding: 8 }} title={t("library.addBook")}>➕</button>
|
<button onClick={() => navigate("/add")} style={{ ...TOUCH_TARGET, fontSize: 20, background: "none", border: "none", cursor: "pointer", padding: 8 }} title={t("library.addBook")}>➕</button>
|
||||||
<button onClick={() => navigate("/bookmarks-notes")} style={{ ...TOUCH_TARGET, fontSize: 20, background: "none", border: "none", cursor: "pointer", padding: 8 }} title={t("library.bookmarks")}>🔖</button>
|
<button onClick={() => navigate("/bookmarks-notes")} style={{ ...TOUCH_TARGET, fontSize: 20, background: "none", border: "none", cursor: "pointer", padding: 8 }} title={t("library.bookmarks")}>🔖</button>
|
||||||
|
<button onClick={() => navigate("/groups")} style={{ ...TOUCH_TARGET, fontSize: 20, background: "none", border: "none", cursor: "pointer", padding: 8 }} title="Reading Groups">👥</button>
|
||||||
<button onClick={() => navigate("/settings")} style={{ ...TOUCH_TARGET, fontSize: 20, background: "none", border: "none", cursor: "pointer", padding: 8 }} title={t("library.settings")}>⚙️</button>
|
<button onClick={() => navigate("/settings")} style={{ ...TOUCH_TARGET, fontSize: 20, background: "none", border: "none", cursor: "pointer", padding: 8 }} title={t("library.settings")}>⚙️</button>
|
||||||
<button onClick={logout} style={{ ...TOUCH_TARGET, fontSize: 20, background: "none", border: "none", cursor: "pointer", padding: 8 }} title={t("library.logout")}>🚪</button>
|
<button onClick={logout} style={{ ...TOUCH_TARGET, fontSize: 20, background: "none", border: "none", cursor: "pointer", padding: 8 }} title={t("library.logout")}>🚪</button>
|
||||||
</>
|
</>
|
||||||
@@ -249,6 +250,7 @@ export function LibraryPage() {
|
|||||||
<>
|
<>
|
||||||
<button onClick={() => navigate("/add")} className="btn">+ {t("library.addBook")}</button>
|
<button onClick={() => navigate("/add")} className="btn">+ {t("library.addBook")}</button>
|
||||||
<button onClick={() => navigate("/bookmarks-notes")} className="btn btn-secondary">{t("library.bookmarks")}</button>
|
<button onClick={() => navigate("/bookmarks-notes")} className="btn btn-secondary">{t("library.bookmarks")}</button>
|
||||||
|
<button onClick={() => navigate("/groups")} className="btn btn-secondary">👥 Reading Groups</button>
|
||||||
<button onClick={() => navigate("/settings")} className="btn btn-secondary">{t("library.settings")}</button>
|
<button onClick={() => navigate("/settings")} className="btn btn-secondary">{t("library.settings")}</button>
|
||||||
<button onClick={logout} className="btn btn-danger">{t("library.logout")}</button>
|
<button onClick={logout} className="btn btn-danger">{t("library.logout")}</button>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -0,0 +1,288 @@
|
|||||||
|
import React, { useCallback, useEffect, useState } from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { useTranslation } from "react-i18n-lite";
|
||||||
|
import { groupsApi } from "../api/groups";
|
||||||
|
import { booksApi } from "../api/books";
|
||||||
|
import type { ReadingGroupSummary } from "../types/groups";
|
||||||
|
import type { EBookListItem } from "../types/book";
|
||||||
|
import { useMediaQuery, BREAKPOINTS } from "../hooks/useMediaQuery";
|
||||||
|
|
||||||
|
export function ReadingGroupsPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const isMobile = useMediaQuery(BREAKPOINTS.md);
|
||||||
|
|
||||||
|
const [groups, setGroups] = useState<ReadingGroupSummary[]>([]);
|
||||||
|
const [ebooks, setEbooks] = useState<EBookListItem[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [showCreate, setShowCreate] = useState(false);
|
||||||
|
const [createName, setCreateName] = useState("");
|
||||||
|
const [createEbook, setCreateEbook] = useState<number | null>(null);
|
||||||
|
const [createDesc, setCreateDesc] = useState("");
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
|
||||||
|
const loadGroups = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const data = await groupsApi.listGroups();
|
||||||
|
setGroups(data);
|
||||||
|
setError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Failed to load groups");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const loadEbooks = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const data = await booksApi.getEBooks();
|
||||||
|
setEbooks(data);
|
||||||
|
} catch {
|
||||||
|
// Ebook list is optional; groups page still works without it
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadGroups();
|
||||||
|
void loadEbooks();
|
||||||
|
}, [loadGroups, loadEbooks]);
|
||||||
|
|
||||||
|
const handleCreate = useCallback(async () => {
|
||||||
|
if (!createName.trim() || createEbook === null) return;
|
||||||
|
setCreating(true);
|
||||||
|
try {
|
||||||
|
await groupsApi.createGroup({
|
||||||
|
name: createName.trim(),
|
||||||
|
ebook: createEbook,
|
||||||
|
description: createDesc.trim(),
|
||||||
|
});
|
||||||
|
setShowCreate(false);
|
||||||
|
setCreateName("");
|
||||||
|
setCreateEbook(null);
|
||||||
|
setCreateDesc("");
|
||||||
|
void loadGroups();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Failed to create group");
|
||||||
|
} finally {
|
||||||
|
setCreating(false);
|
||||||
|
}
|
||||||
|
}, [createName, createEbook, createDesc, loadGroups]);
|
||||||
|
|
||||||
|
const containerStyle: React.CSSProperties = {
|
||||||
|
maxWidth: 720,
|
||||||
|
margin: "0 auto",
|
||||||
|
padding: isMobile ? 16 : 24,
|
||||||
|
minHeight: "100vh",
|
||||||
|
background: "#f8f9fa",
|
||||||
|
};
|
||||||
|
|
||||||
|
const headerBar: React.CSSProperties = {
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
|
marginBottom: 24,
|
||||||
|
};
|
||||||
|
|
||||||
|
const cardStyle: React.CSSProperties = {
|
||||||
|
background: "#fff",
|
||||||
|
borderRadius: 12,
|
||||||
|
padding: isMobile ? 14 : 18,
|
||||||
|
marginBottom: 12,
|
||||||
|
cursor: "pointer",
|
||||||
|
boxShadow: "0 1px 4px rgba(0,0,0,0.06)",
|
||||||
|
border: "1px solid #e5e7eb",
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div style={containerStyle}>
|
||||||
|
<div style={{ height: 24, width: 200, background: "#e5e7eb", borderRadius: 6, marginBottom: 24 }} />
|
||||||
|
{[1, 2, 3].map((i) => (
|
||||||
|
<div key={i} style={{ ...cardStyle, cursor: "default" }}>
|
||||||
|
<div style={{ height: 20, width: "60%", background: "#e5e7eb", borderRadius: 4, marginBottom: 8 }} />
|
||||||
|
<div style={{ height: 14, width: "40%", background: "#e5e7eb", borderRadius: 4 }} />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={containerStyle}>
|
||||||
|
<div style={headerBar}>
|
||||||
|
<h1 style={{ fontSize: isMobile ? 20 : 24, fontWeight: 700, color: "#1f2937", margin: 0 }}>
|
||||||
|
📚 {t("readingGroups.title") ?? "Reading Groups"}
|
||||||
|
</h1>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreate(true)}
|
||||||
|
style={{
|
||||||
|
padding: isMobile ? "10px 18px" : "8px 18px",
|
||||||
|
borderRadius: 10,
|
||||||
|
border: "none",
|
||||||
|
background: "#4f46e5",
|
||||||
|
color: "#fff",
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: 600,
|
||||||
|
cursor: "pointer",
|
||||||
|
minHeight: 40,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
+ {t("readingGroups.create") ?? "New Group"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div style={{ padding: "12px 16px", background: "#fef2f2", borderRadius: 8, color: "#b91c1c", marginBottom: 16, fontSize: 14 }}>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Create modal */}
|
||||||
|
{showCreate && (
|
||||||
|
<div style={{
|
||||||
|
position: "fixed", inset: 0, background: "rgba(0,0,0,0.4)",
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100,
|
||||||
|
}}>
|
||||||
|
<div style={{
|
||||||
|
background: "#fff", borderRadius: 16, padding: 24, maxWidth: 420, width: "90%",
|
||||||
|
boxShadow: "0 10px 40px rgba(0,0,0,0.15)",
|
||||||
|
}}>
|
||||||
|
<h2 style={{ fontSize: 18, fontWeight: 700, marginBottom: 16, color: "#1f2937" }}>
|
||||||
|
{t("readingGroups.createTitle") ?? "Create Reading Group"}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<label style={{ fontSize: 13, color: "#6b7280", display: "block", marginBottom: 4 }}>
|
||||||
|
{t("readingGroups.groupName") ?? "Group Name"}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={createName}
|
||||||
|
onChange={(e) => setCreateName(e.target.value)}
|
||||||
|
placeholder={t("readingGroups.namePlaceholder") ?? "e.g., Book Club June"}
|
||||||
|
style={{
|
||||||
|
width: "100%", padding: "10px 14px", borderRadius: 8, border: "1px solid #d1d5db",
|
||||||
|
fontSize: 14, marginBottom: 14, boxSizing: "border-box",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<label style={{ fontSize: 13, color: "#6b7280", display: "block", marginBottom: 4 }}>
|
||||||
|
{t("readingGroups.selectBook") ?? "Select Book"}
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={createEbook ?? ""}
|
||||||
|
onChange={(e) => setCreateEbook(e.target.value ? Number(e.target.value) : null)}
|
||||||
|
style={{
|
||||||
|
width: "100%", padding: "10px 14px", borderRadius: 8, border: "1px solid #d1d5db",
|
||||||
|
fontSize: 14, marginBottom: 14, boxSizing: "border-box", background: "#fff",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">-- {t("readingGroups.choose") ?? "Choose"} --</option>
|
||||||
|
{ebooks.map((eb) => (
|
||||||
|
<option key={eb.id} value={eb.id}>
|
||||||
|
{eb.title} {eb.author ? `— ${eb.author}` : ""}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<label style={{ fontSize: 13, color: "#6b7280", display: "block", marginBottom: 4 }}>
|
||||||
|
{t("readingGroups.description") ?? "Description"} ({t("common.optional") ?? "optional"})
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={createDesc}
|
||||||
|
onChange={(e) => setCreateDesc(e.target.value)}
|
||||||
|
rows={3}
|
||||||
|
style={{
|
||||||
|
width: "100%", padding: "10px 14px", borderRadius: 8, border: "1px solid #d1d5db",
|
||||||
|
fontSize: 14, marginBottom: 18, boxSizing: "border-box", resize: "vertical",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreate(false)}
|
||||||
|
style={{
|
||||||
|
padding: "10px 20px", borderRadius: 8, border: "1px solid #d1d5db",
|
||||||
|
background: "#fff", color: "#374151", fontSize: 14, cursor: "pointer",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("common.cancel") ?? "Cancel"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => void handleCreate()}
|
||||||
|
disabled={creating || !createName.trim() || createEbook === null}
|
||||||
|
style={{
|
||||||
|
padding: "10px 20px", borderRadius: 8, border: "none",
|
||||||
|
background: (!createName.trim() || createEbook === null) ? "#9ca3af" : "#4f46e5",
|
||||||
|
color: "#fff", fontSize: 14, fontWeight: 600, cursor: (!createName.trim() || createEbook === null) ? "not-allowed" : "pointer",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{creating ? (t("common.creating") ?? "Creating...") : (t("readingGroups.create") ?? "Create")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Group list */}
|
||||||
|
{groups.length === 0 ? (
|
||||||
|
<div style={{ textAlign: "center", padding: "60px 20px", color: "#6b7280" }}>
|
||||||
|
<div style={{ fontSize: 48, marginBottom: 12 }}>📖</div>
|
||||||
|
<p style={{ fontSize: 16, marginBottom: 16 }}>
|
||||||
|
{t("readingGroups.empty") ?? "No reading groups yet. Create one to read together!"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
groups.map((g) => (
|
||||||
|
<div
|
||||||
|
key={g.id}
|
||||||
|
style={cardStyle}
|
||||||
|
onClick={() => navigate(`/groups/${g.id}`)}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
|
||||||
|
<div>
|
||||||
|
<h2 style={{ fontSize: isMobile ? 16 : 17, fontWeight: 600, color: "#1f2937", margin: "0 0 4px" }}>
|
||||||
|
{g.name}
|
||||||
|
</h2>
|
||||||
|
<p style={{ fontSize: 13, color: "#6b7280", margin: "0 0 6px" }}>
|
||||||
|
{g.ebook_title} {g.ebook_author ? `— ${g.ebook_author}` : ""}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span style={{
|
||||||
|
fontSize: 12, color: "#4f46e5", background: "#eef2ff",
|
||||||
|
padding: "2px 10px", borderRadius: 999, whiteSpace: "nowrap",
|
||||||
|
minHeight: 24, display: "inline-flex", alignItems: "center",
|
||||||
|
}}>
|
||||||
|
{g.member_count} {g.member_count === 1
|
||||||
|
? (t("readingGroups.member") ?? "member")
|
||||||
|
: (t("readingGroups.members") ?? "members")}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{g.my_progress && (
|
||||||
|
<div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 8 }}>
|
||||||
|
<div style={{
|
||||||
|
flex: 1, height: 6, borderRadius: 3, background: "#e5e7eb", overflow: "hidden",
|
||||||
|
}}>
|
||||||
|
<div style={{
|
||||||
|
height: "100%", width: `${Math.min(100, g.my_progress.percentage)}%`,
|
||||||
|
background: "#4f46e5", borderRadius: 3, transition: "width 0.3s ease",
|
||||||
|
}} />
|
||||||
|
</div>
|
||||||
|
<span style={{ fontSize: 12, color: "#6b7280", whiteSpace: "nowrap" }}>
|
||||||
|
{g.my_progress.section_label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{g.description && (
|
||||||
|
<p style={{ fontSize: 13, color: "#9ca3af", margin: "8px 0 0", lineHeight: 1.5 }}>
|
||||||
|
{g.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
/* ── Reading Groups ── */
|
||||||
|
|
||||||
|
export interface MemberProgressPublic {
|
||||||
|
user_id: number;
|
||||||
|
user_email: string;
|
||||||
|
current_section: number;
|
||||||
|
total_sections: number;
|
||||||
|
section_label: string;
|
||||||
|
percentage: number;
|
||||||
|
time_spent_seconds: number;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MemberProgressDetail {
|
||||||
|
id: number;
|
||||||
|
user_id: number;
|
||||||
|
user_email: string;
|
||||||
|
current_section: number;
|
||||||
|
total_sections: number;
|
||||||
|
section_label: string;
|
||||||
|
percentage: number;
|
||||||
|
time_spent_seconds: number;
|
||||||
|
last_position: Record<string, unknown>;
|
||||||
|
is_public: boolean;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MemberProgressPrivateStub {
|
||||||
|
user_id: number;
|
||||||
|
user_email: string;
|
||||||
|
is_public: false;
|
||||||
|
note: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MemberProgressEntry =
|
||||||
|
| MemberProgressDetail
|
||||||
|
| MemberProgressPublic
|
||||||
|
| MemberProgressPrivateStub;
|
||||||
|
|
||||||
|
export interface GroupMember {
|
||||||
|
id: number;
|
||||||
|
user_id: number;
|
||||||
|
user_email: string;
|
||||||
|
role: "member" | "admin";
|
||||||
|
joined_at: string;
|
||||||
|
progress: MemberProgressPublic | { is_public: false; note: string } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReadingGroupSummary {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
ebook: number;
|
||||||
|
ebook_title: string;
|
||||||
|
ebook_author: string;
|
||||||
|
created_by_email: string;
|
||||||
|
description: string;
|
||||||
|
member_count: number;
|
||||||
|
my_progress: {
|
||||||
|
current_section: number;
|
||||||
|
percentage: number;
|
||||||
|
time_spent_seconds: number;
|
||||||
|
section_label: string;
|
||||||
|
} | null;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReadingGroupDetail extends ReadingGroupSummary {
|
||||||
|
members: GroupMember[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateGroupPayload {
|
||||||
|
name: string;
|
||||||
|
ebook: number;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateProgressPayload {
|
||||||
|
current_section: number;
|
||||||
|
percentage?: number;
|
||||||
|
time_spent_delta?: number;
|
||||||
|
last_position?: Record<string, unknown>;
|
||||||
|
is_public?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminProgressSummary {
|
||||||
|
group_id: number;
|
||||||
|
group_name: string;
|
||||||
|
ebook_title: string;
|
||||||
|
total_members: number;
|
||||||
|
members_started: number;
|
||||||
|
members_finished: number;
|
||||||
|
average_percentage: number;
|
||||||
|
average_time_spent_hours: number;
|
||||||
|
member_details: {
|
||||||
|
user_id: number;
|
||||||
|
user_email: string;
|
||||||
|
current_section: number;
|
||||||
|
percentage: number;
|
||||||
|
time_spent_seconds: number;
|
||||||
|
is_public: boolean;
|
||||||
|
updated_at: string;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
@@ -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).
|
||||||
+13
-7
@@ -1,4 +1,8 @@
|
|||||||
import React from "react";
|
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 { NavigationContainer } from "@react-navigation/native";
|
||||||
import { StatusBar } from "expo-status-bar";
|
import { StatusBar } from "expo-status-bar";
|
||||||
import { AuthProvider } from "./src/context/AuthContext";
|
import { AuthProvider } from "./src/context/AuthContext";
|
||||||
@@ -6,11 +10,13 @@ import { RootNavigator } from "./src/navigation/RootNavigator";
|
|||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<AuthProvider>
|
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||||
<NavigationContainer>
|
<AuthProvider>
|
||||||
<StatusBar style="auto" />
|
<NavigationContainer>
|
||||||
<RootNavigator />
|
<StatusBar style="auto" />
|
||||||
</NavigationContainer>
|
<RootNavigator />
|
||||||
</AuthProvider>
|
</NavigationContainer>
|
||||||
|
</AuthProvider>
|
||||||
|
</GestureHandlerRootView>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,6 @@
|
|||||||
"package": "com.cloudreader.app"
|
"package": "com.cloudreader.app"
|
||||||
},
|
},
|
||||||
"plugins": [
|
"plugins": [
|
||||||
"expo-document-picker",
|
|
||||||
"expo-file-system"
|
"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",
|
"android": "expo start --android",
|
||||||
"ios": "expo start --ios",
|
"ios": "expo start --ios",
|
||||||
"web": "expo start --web",
|
"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": {
|
"dependencies": {
|
||||||
"expo": "~52.0.0",
|
"expo": "~52.0.0",
|
||||||
@@ -22,10 +26,12 @@
|
|||||||
"@react-navigation/bottom-tabs": "^7.0.0",
|
"@react-navigation/bottom-tabs": "^7.0.0",
|
||||||
"axios": "^1.7.9",
|
"axios": "^1.7.9",
|
||||||
"@react-native-async-storage/async-storage": "2.1.0",
|
"@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",
|
"expo-file-system": "~18.0.0",
|
||||||
"react-native-gesture-handler": "~2.20.0",
|
"react-native-gesture-handler": "~2.20.0",
|
||||||
"react-native-reanimated": "~3.16.0",
|
"react-native-reanimated": "~3.16.0",
|
||||||
|
"react-native-webview": "13.12.5",
|
||||||
"@cloud-reader/shared": "*"
|
"@cloud-reader/shared": "*"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -1,55 +1,31 @@
|
|||||||
import api from "./client";
|
import api from "./client";
|
||||||
import type {
|
import type { PaginatedResponse } from "@cloud-reader/shared";
|
||||||
Bookmark,
|
import type { Bookmark, CreateMarkerPayload } from "../types";
|
||||||
Note,
|
|
||||||
CreateBookmarkPayload,
|
|
||||||
CreateNotePayload,
|
|
||||||
PaginatedResponse,
|
|
||||||
} from "@cloud-reader/shared";
|
|
||||||
|
|
||||||
export function fetchBookmarks(
|
export async function fetchBookmarks(
|
||||||
bookId?: string,
|
ebookId?: string | number,
|
||||||
): Promise<PaginatedResponse<Bookmark>> {
|
): Promise<PaginatedResponse<Bookmark>> {
|
||||||
const params = bookId ? { book: bookId } : {};
|
const params: Record<string, string> = {};
|
||||||
return api
|
if (ebookId != null && ebookId !== "") {
|
||||||
.get<PaginatedResponse<Bookmark>>("/api/annotations/bookmarks/", { params })
|
params.ebook = String(ebookId);
|
||||||
.then((res) => res.data);
|
}
|
||||||
|
const { data } = await api.get<PaginatedResponse<Bookmark>>(
|
||||||
|
"/api/annotations/bookmarks/",
|
||||||
|
{ params },
|
||||||
|
);
|
||||||
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createBookmark(
|
export async function createMarker(
|
||||||
payload: CreateBookmarkPayload,
|
payload: CreateMarkerPayload,
|
||||||
): Promise<Bookmark> {
|
): Promise<Bookmark> {
|
||||||
return api
|
const { data } = await api.post<Bookmark>(
|
||||||
.post<Bookmark>("/api/annotations/bookmarks/", payload)
|
"/api/annotations/bookmarks/",
|
||||||
.then((res) => res.data);
|
payload,
|
||||||
|
);
|
||||||
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function deleteBookmark(id: string): Promise<void> {
|
export async function deleteBookmark(id: string): Promise<void> {
|
||||||
return api.delete(`/api/annotations/bookmarks/${id}/`).then(() => {});
|
await api.delete(`/api/annotations/bookmarks/${id}/`);
|
||||||
}
|
}
|
||||||
|
|
||||||
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(() => {});
|
|
||||||
}
|
|
||||||
+1
-20
@@ -1,31 +1,12 @@
|
|||||||
import api from "./client";
|
import api from "./client";
|
||||||
import type { Book, PaginatedResponse } from "@cloud-reader/shared";
|
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(
|
export function searchBooks(
|
||||||
query: string,
|
query: string,
|
||||||
): Promise<PaginatedResponse<Book>> {
|
): Promise<PaginatedResponse<Book>> {
|
||||||
return api
|
return api
|
||||||
.get<PaginatedResponse<Book>>("/api/books/search/", {
|
.get<PaginatedResponse<Book>>("/api/books/", {
|
||||||
params: { q: query },
|
params: { q: query },
|
||||||
})
|
})
|
||||||
.then((res) => res.data);
|
.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 axios, { type AxiosError, type InternalAxiosRequestConfig } from "axios";
|
||||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||||
|
import type { TokenResponse } from "@cloud-reader/shared";
|
||||||
|
|
||||||
const STORAGE_KEYS = {
|
const STORAGE_KEYS = {
|
||||||
ACCESS_TOKEN: "access_token",
|
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 ─────────────────────────────────────────────
|
// ── Request interceptor ─────────────────────────────────────────────
|
||||||
|
|
||||||
api.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
|
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;
|
export default api;
|
||||||
+17
-36
@@ -1,54 +1,35 @@
|
|||||||
import { apiClient } from "./client";
|
import { apiClient, getApiBaseUrl } from "./client";
|
||||||
import type {
|
import type {
|
||||||
EBookListItem,
|
EBookListItem,
|
||||||
EBookDetail,
|
EBookDetail,
|
||||||
ReadingProgress,
|
|
||||||
ReadingSettings,
|
|
||||||
TocResponse,
|
TocResponse,
|
||||||
ContentResponse,
|
|
||||||
PaginatedResponse,
|
PaginatedResponse,
|
||||||
} from "@cloud-reader/shared";
|
} from "@cloud-reader/shared";
|
||||||
|
|
||||||
export const ebooksApi = {
|
export const ebooksApi = {
|
||||||
/** List uploaded e-books */
|
/** List the authenticated user's uploaded e-books */
|
||||||
list() {
|
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) {
|
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) {
|
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) {
|
* Absolute URL to stream the raw ebook file. The endpoint requires JWT auth,
|
||||||
return apiClient.get<ContentResponse>(
|
* so callers download it with an Authorization header (e.g. via
|
||||||
`/api/ebooks/${id}/content/?page=${page}`,
|
* expo-file-system) rather than handing the URL to a renderer directly.
|
||||||
);
|
*/
|
||||||
|
getFileUrl(id: number): string {
|
||||||
|
return `${getApiBaseUrl()}/api/books/ebooks/${id}/file/`;
|
||||||
},
|
},
|
||||||
|
};
|
||||||
/** 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,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -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 };
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import {
|
||||||
|
getReadingSettings,
|
||||||
|
updateReadingSettings,
|
||||||
|
} from "../api/reader";
|
||||||
|
import type { ReadingSettings } from "../types/reader";
|
||||||
|
|
||||||
|
const DEFAULT_READING_SETTINGS: ReadingSettings = {
|
||||||
|
font_family: "serif",
|
||||||
|
font_size: 18,
|
||||||
|
line_height: 1.5,
|
||||||
|
margin_width: 16,
|
||||||
|
background_color: "#fbfbf8",
|
||||||
|
text_color: "#2b2b2b",
|
||||||
|
brightness: 1,
|
||||||
|
orientation_lock: "auto",
|
||||||
|
theme: "paper",
|
||||||
|
created_at: "",
|
||||||
|
updated_at: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
const SAVE_DEBOUNCE_MS = 600;
|
||||||
|
|
||||||
|
interface UseReadingSettingsReturn {
|
||||||
|
settings: ReadingSettings;
|
||||||
|
loaded: boolean;
|
||||||
|
updateSettings: (patch: Partial<ReadingSettings>) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads the user's reader settings and persists changes with a debounce.
|
||||||
|
* Mirrors frontend/src/hooks/useReadingSettings.ts behavior.
|
||||||
|
*/
|
||||||
|
export function useReadingSettings(): UseReadingSettingsReturn {
|
||||||
|
const [settings, setSettings] = useState<ReadingSettings>(
|
||||||
|
DEFAULT_READING_SETTINGS,
|
||||||
|
);
|
||||||
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
const pendingRef = useRef<Partial<ReadingSettings>>({});
|
||||||
|
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
getReadingSettings()
|
||||||
|
.then((data) => {
|
||||||
|
if (active) {
|
||||||
|
setSettings(data);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
/* keep defaults if the request fails */
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (active) {
|
||||||
|
setLoaded(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
if (timerRef.current) {
|
||||||
|
clearTimeout(timerRef.current);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const updateSettings = useCallback((patch: Partial<ReadingSettings>) => {
|
||||||
|
setSettings((prev) => ({ ...prev, ...patch }));
|
||||||
|
pendingRef.current = { ...pendingRef.current, ...patch };
|
||||||
|
if (timerRef.current) {
|
||||||
|
clearTimeout(timerRef.current);
|
||||||
|
}
|
||||||
|
timerRef.current = setTimeout(() => {
|
||||||
|
const body = pendingRef.current;
|
||||||
|
pendingRef.current = {};
|
||||||
|
updateReadingSettings(body).catch(() => {
|
||||||
|
/* ignore transient save failures */
|
||||||
|
});
|
||||||
|
}, SAVE_DEBOUNCE_MS);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { settings, loaded, updateSettings };
|
||||||
|
}
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
import { type ReactNode } from "react";
|
|
||||||
import { NavigationContainer } from "@react-navigation/native";
|
|
||||||
import { createNativeStackNavigator } from "@react-navigation/native-stack";
|
|
||||||
import { useAuth } from "../context/AuthContext";
|
|
||||||
import LoginScreen from "../screens/LoginScreen";
|
|
||||||
import RegisterScreen from "../screens/RegisterScreen";
|
|
||||||
import MainTabs from "./MainTabs";
|
|
||||||
|
|
||||||
export type AuthStackParamList = {
|
|
||||||
Login: undefined;
|
|
||||||
Register: undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type RootStackParamList = {
|
|
||||||
Auth: undefined;
|
|
||||||
Main: undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
const RootStack = createNativeStackNavigator<RootStackParamList>();
|
|
||||||
const AuthStack = createNativeStackNavigator<AuthStackParamList>();
|
|
||||||
|
|
||||||
function AuthNavigator(): ReactNode {
|
|
||||||
return (
|
|
||||||
<AuthStack.Navigator screenOptions={{ headerShown: false }}>
|
|
||||||
<AuthStack.Screen name="Login" component={LoginScreen} />
|
|
||||||
<AuthStack.Screen name="Register" component={RegisterScreen} />
|
|
||||||
</AuthStack.Navigator>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function AppNavigator(): ReactNode {
|
|
||||||
const { state } = useAuth();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<NavigationContainer>
|
|
||||||
<RootStack.Navigator screenOptions={{ headerShown: false }}>
|
|
||||||
{state.isAuthenticated ? (
|
|
||||||
<RootStack.Screen name="Main" component={MainTabs} />
|
|
||||||
) : (
|
|
||||||
<RootStack.Screen name="Auth" component={AuthNavigator} />
|
|
||||||
)}
|
|
||||||
</RootStack.Navigator>
|
|
||||||
</NavigationContainer>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { createNativeStackNavigator } from "@react-navigation/native-stack";
|
||||||
|
import { MainNavigator } from "./MainNavigator";
|
||||||
|
import BookDetailScreen from "../screens/BookDetailScreen";
|
||||||
|
import ReaderScreen from "../screens/ReaderScreen";
|
||||||
|
import type { AppStackParamList } from "../types";
|
||||||
|
|
||||||
|
const Stack = createNativeStackNavigator<AppStackParamList>();
|
||||||
|
|
||||||
|
export function AppStack() {
|
||||||
|
return (
|
||||||
|
<Stack.Navigator
|
||||||
|
screenOptions={{
|
||||||
|
headerStyle: { backgroundColor: "#fff" },
|
||||||
|
headerTitleStyle: { fontWeight: "600", color: "#1a1a2e" },
|
||||||
|
headerTintColor: "#4a6cf7",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Stack.Screen
|
||||||
|
name="Tabs"
|
||||||
|
component={MainNavigator}
|
||||||
|
options={{ headerShown: false }}
|
||||||
|
/>
|
||||||
|
<Stack.Screen
|
||||||
|
name="BookDetail"
|
||||||
|
component={BookDetailScreen}
|
||||||
|
options={{ title: "" }}
|
||||||
|
/>
|
||||||
|
<Stack.Screen
|
||||||
|
name="Reader"
|
||||||
|
component={ReaderScreen}
|
||||||
|
options={{ headerShown: false }}
|
||||||
|
/>
|
||||||
|
</Stack.Navigator>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ import { createNativeStackNavigator } from "@react-navigation/native-stack";
|
|||||||
import LoginScreen from "../screens/LoginScreen";
|
import LoginScreen from "../screens/LoginScreen";
|
||||||
import RegisterScreen from "../screens/RegisterScreen";
|
import RegisterScreen from "../screens/RegisterScreen";
|
||||||
|
|
||||||
export type AuthStackParamList = {
|
type AuthStackParamList = {
|
||||||
Login: undefined;
|
Login: undefined;
|
||||||
Register: undefined;
|
Register: undefined;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
import { type ReactNode } from "react";
|
|
||||||
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
|
|
||||||
import { Text } from "react-native";
|
|
||||||
import LibraryScreen from "../screens/LibraryScreen";
|
|
||||||
import SearchScreen from "../screens/SearchScreen";
|
|
||||||
import SettingsScreen from "../screens/SettingsScreen";
|
|
||||||
|
|
||||||
export type MainTabParamList = {
|
|
||||||
Library: undefined;
|
|
||||||
Search: undefined;
|
|
||||||
Settings: undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
const Tab = createBottomTabNavigator<MainTabParamList>();
|
|
||||||
|
|
||||||
function TabIcon({ label, focused }: { label: string; focused: boolean }) {
|
|
||||||
return (
|
|
||||||
<Text style={{ fontSize: 22, opacity: focused ? 1 : 0.5 }}>
|
|
||||||
{label === "Library" ? "📚" : label === "Search" ? "🔍" : "⚙️"}
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function MainTabs(): ReactNode {
|
|
||||||
return (
|
|
||||||
<Tab.Navigator
|
|
||||||
screenOptions={({ route }) => ({
|
|
||||||
tabBarIcon: ({ focused }: { focused: boolean }) => (
|
|
||||||
<TabIcon label={route.name} focused={focused} />
|
|
||||||
),
|
|
||||||
tabBarActiveTintColor: "#4f8ef7",
|
|
||||||
tabBarInactiveTintColor: "#888",
|
|
||||||
headerStyle: { backgroundColor: "#1a1a2e" },
|
|
||||||
headerTintColor: "#fff",
|
|
||||||
tabBarStyle: { backgroundColor: "#1a1a2e", borderTopColor: "#333" },
|
|
||||||
})}
|
|
||||||
>
|
|
||||||
<Tab.Screen
|
|
||||||
name="Library"
|
|
||||||
component={LibraryScreen}
|
|
||||||
options={{ title: "My Library" }}
|
|
||||||
/>
|
|
||||||
<Tab.Screen
|
|
||||||
name="Search"
|
|
||||||
component={SearchScreen}
|
|
||||||
options={{ title: "Search" }}
|
|
||||||
/>
|
|
||||||
<Tab.Screen
|
|
||||||
name="Settings"
|
|
||||||
component={SettingsScreen}
|
|
||||||
options={{ title: "Settings" }}
|
|
||||||
/>
|
|
||||||
</Tab.Navigator>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,7 @@ import React from "react";
|
|||||||
import { ActivityIndicator, View } from "react-native";
|
import { ActivityIndicator, View } from "react-native";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import { AuthNavigator } from "./AuthNavigator";
|
import { AuthNavigator } from "./AuthNavigator";
|
||||||
import { MainNavigator } from "./MainNavigator";
|
import { AppStack } from "./AppStack";
|
||||||
|
|
||||||
export function RootNavigator() {
|
export function RootNavigator() {
|
||||||
const { isLoading, isAuthenticated } = useAuth();
|
const { isLoading, isAuthenticated } = useAuth();
|
||||||
@@ -19,5 +19,5 @@ export function RootNavigator() {
|
|||||||
return <AuthNavigator />;
|
return <AuthNavigator />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <MainNavigator />;
|
return <AppStack />;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { type ReactNode } from "react";
|
||||||
|
import { View, Text } from "react-native";
|
||||||
|
import { authStyles } from "./authStyles";
|
||||||
|
|
||||||
|
export function AuthFormError({ message }: { message: string }): ReactNode {
|
||||||
|
return (
|
||||||
|
<View style={authStyles.errorBox}>
|
||||||
|
<Text style={authStyles.errorText}>{message}</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import { useState, useEffect, useCallback, type ReactNode } from "react";
|
||||||
|
import {
|
||||||
|
View,
|
||||||
|
Text,
|
||||||
|
Image,
|
||||||
|
ScrollView,
|
||||||
|
TouchableOpacity,
|
||||||
|
StyleSheet,
|
||||||
|
ActivityIndicator,
|
||||||
|
} from "react-native";
|
||||||
|
import type { RouteProp } from "@react-navigation/native";
|
||||||
|
import { ebooksApi } from "../api/ebooks";
|
||||||
|
import { formatFileSize } from "@cloud-reader/shared";
|
||||||
|
import type { EBookDetail } from "@cloud-reader/shared";
|
||||||
|
import type { AppStackParamList } from "../types";
|
||||||
|
|
||||||
|
type DetailRoute = RouteProp<AppStackParamList, "BookDetail">;
|
||||||
|
|
||||||
|
export default function BookDetailScreen({
|
||||||
|
route,
|
||||||
|
navigation,
|
||||||
|
}: {
|
||||||
|
route: DetailRoute;
|
||||||
|
navigation: any;
|
||||||
|
}): ReactNode {
|
||||||
|
const { ebookId } = route.params;
|
||||||
|
const [book, setBook] = useState<EBookDetail | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState(false);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const { data } = await ebooksApi.get(ebookId);
|
||||||
|
setBook(data);
|
||||||
|
} catch {
|
||||||
|
setError(true);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [ebookId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<View style={styles.centered}>
|
||||||
|
<ActivityIndicator size="large" color="#4f8ef7" />
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error || !book) {
|
||||||
|
return (
|
||||||
|
<View style={styles.centered}>
|
||||||
|
<Text style={styles.errorText}>Could not load this book.</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const progressPct =
|
||||||
|
typeof book.progress?.current_position === "number"
|
||||||
|
? Math.round(book.progress.current_position)
|
||||||
|
: 0;
|
||||||
|
const hasProgress = progressPct > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScrollView style={styles.container} contentContainerStyle={styles.content}>
|
||||||
|
<View style={styles.header}>
|
||||||
|
{book.cover_image ? (
|
||||||
|
<Image source={{ uri: book.cover_image }} style={styles.cover} />
|
||||||
|
) : (
|
||||||
|
<View style={styles.cover}>
|
||||||
|
<Text style={styles.coverText}>
|
||||||
|
{book.title.charAt(0).toUpperCase()}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
<Text style={styles.title}>{book.title}</Text>
|
||||||
|
<Text style={styles.author}>{book.author || "Unknown author"}</Text>
|
||||||
|
</View>
|
||||||
|
|
||||||
|
<View style={styles.metaRow}>
|
||||||
|
<MetaPill label="Format" value={book.format?.toUpperCase() || "—"} />
|
||||||
|
<MetaPill
|
||||||
|
label="Pages"
|
||||||
|
value={book.page_count ? String(book.page_count) : "—"}
|
||||||
|
/>
|
||||||
|
<MetaPill label="Size" value={formatFileSize(book.file_size || 0)} />
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{hasProgress && (
|
||||||
|
<View style={styles.progressWrap}>
|
||||||
|
<View style={styles.progressTrack}>
|
||||||
|
<View style={[styles.progressFill, { width: `${progressPct}%` }]} />
|
||||||
|
</View>
|
||||||
|
<Text style={styles.progressLabel}>{progressPct}% read</Text>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<TouchableOpacity
|
||||||
|
style={styles.readButton}
|
||||||
|
onPress={() => navigation.navigate("Reader", { ebookId: book.id })}
|
||||||
|
>
|
||||||
|
<Text style={styles.readButtonText}>
|
||||||
|
{hasProgress ? "Resume reading" : "Start reading"}
|
||||||
|
</Text>
|
||||||
|
</TouchableOpacity>
|
||||||
|
</ScrollView>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function MetaPill({ label, value }: { label: string; value: string }): ReactNode {
|
||||||
|
return (
|
||||||
|
<View style={styles.metaPill}>
|
||||||
|
<Text style={styles.metaValue}>{value}</Text>
|
||||||
|
<Text style={styles.metaLabel}>{label}</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
container: {
|
||||||
|
flex: 1,
|
||||||
|
backgroundColor: "#0f0f23",
|
||||||
|
},
|
||||||
|
content: {
|
||||||
|
padding: 24,
|
||||||
|
},
|
||||||
|
centered: {
|
||||||
|
flex: 1,
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
backgroundColor: "#0f0f23",
|
||||||
|
padding: 24,
|
||||||
|
},
|
||||||
|
header: {
|
||||||
|
alignItems: "center",
|
||||||
|
marginBottom: 24,
|
||||||
|
},
|
||||||
|
cover: {
|
||||||
|
width: 140,
|
||||||
|
height: 200,
|
||||||
|
borderRadius: 12,
|
||||||
|
backgroundColor: "#2a2a4e",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
marginBottom: 16,
|
||||||
|
},
|
||||||
|
coverText: {
|
||||||
|
fontSize: 56,
|
||||||
|
fontWeight: "bold",
|
||||||
|
color: "#4f8ef7",
|
||||||
|
},
|
||||||
|
title: {
|
||||||
|
fontSize: 22,
|
||||||
|
fontWeight: "700",
|
||||||
|
color: "#fff",
|
||||||
|
textAlign: "center",
|
||||||
|
marginBottom: 6,
|
||||||
|
},
|
||||||
|
author: {
|
||||||
|
fontSize: 15,
|
||||||
|
color: "#888",
|
||||||
|
textAlign: "center",
|
||||||
|
},
|
||||||
|
metaRow: {
|
||||||
|
flexDirection: "row",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
marginBottom: 24,
|
||||||
|
},
|
||||||
|
metaPill: {
|
||||||
|
flex: 1,
|
||||||
|
backgroundColor: "#1a1a2e",
|
||||||
|
borderRadius: 10,
|
||||||
|
paddingVertical: 12,
|
||||||
|
marginHorizontal: 4,
|
||||||
|
alignItems: "center",
|
||||||
|
borderWidth: 1,
|
||||||
|
borderColor: "#333",
|
||||||
|
},
|
||||||
|
metaValue: {
|
||||||
|
fontSize: 15,
|
||||||
|
fontWeight: "600",
|
||||||
|
color: "#fff",
|
||||||
|
},
|
||||||
|
metaLabel: {
|
||||||
|
fontSize: 12,
|
||||||
|
color: "#666",
|
||||||
|
marginTop: 2,
|
||||||
|
},
|
||||||
|
progressWrap: {
|
||||||
|
marginBottom: 24,
|
||||||
|
},
|
||||||
|
progressTrack: {
|
||||||
|
height: 6,
|
||||||
|
borderRadius: 3,
|
||||||
|
backgroundColor: "#1a1a2e",
|
||||||
|
overflow: "hidden",
|
||||||
|
},
|
||||||
|
progressFill: {
|
||||||
|
height: "100%",
|
||||||
|
backgroundColor: "#4f8ef7",
|
||||||
|
},
|
||||||
|
progressLabel: {
|
||||||
|
fontSize: 12,
|
||||||
|
color: "#888",
|
||||||
|
marginTop: 6,
|
||||||
|
},
|
||||||
|
readButton: {
|
||||||
|
backgroundColor: "#4f8ef7",
|
||||||
|
borderRadius: 10,
|
||||||
|
paddingVertical: 16,
|
||||||
|
alignItems: "center",
|
||||||
|
},
|
||||||
|
readButtonText: {
|
||||||
|
color: "#fff",
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: "600",
|
||||||
|
},
|
||||||
|
errorText: {
|
||||||
|
color: "#888",
|
||||||
|
fontSize: 15,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -2,34 +2,31 @@ import { useState, useEffect, useCallback, type ReactNode } from "react";
|
|||||||
import {
|
import {
|
||||||
View,
|
View,
|
||||||
Text,
|
Text,
|
||||||
|
Image,
|
||||||
FlatList,
|
FlatList,
|
||||||
TouchableOpacity,
|
TouchableOpacity,
|
||||||
StyleSheet,
|
StyleSheet,
|
||||||
ActivityIndicator,
|
ActivityIndicator,
|
||||||
RefreshControl,
|
RefreshControl,
|
||||||
} from "react-native";
|
} from "react-native";
|
||||||
import { fetchBooks } from "../api/books";
|
import { ebooksApi } from "../api/ebooks";
|
||||||
import type { Book, PaginatedResponse } from "@cloud-reader/shared";
|
import type { EBookListItem } from "@cloud-reader/shared";
|
||||||
|
|
||||||
export default function LibraryScreen({ navigation }: { navigation: any }): ReactNode {
|
export default function LibraryScreen({
|
||||||
const [books, setBooks] = useState<Book[]>([]);
|
navigation,
|
||||||
|
}: {
|
||||||
|
navigation: any;
|
||||||
|
}): ReactNode {
|
||||||
|
const [books, setBooks] = useState<EBookListItem[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [refreshing, setRefreshing] = useState(false);
|
const [refreshing, setRefreshing] = useState(false);
|
||||||
const [page, setPage] = useState(1);
|
|
||||||
const [hasMore, setHasMore] = useState(true);
|
|
||||||
|
|
||||||
const loadBooks = useCallback(async (pageNum: number, isRefresh = false) => {
|
const loadBooks = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const data: PaginatedResponse<Book> = await fetchBooks(pageNum);
|
const { data } = await ebooksApi.list();
|
||||||
if (isRefresh) {
|
setBooks(data.results);
|
||||||
setBooks(data.results);
|
|
||||||
} else {
|
|
||||||
setBooks((prev) => [...prev, ...data.results]);
|
|
||||||
}
|
|
||||||
setHasMore(data.next !== null);
|
|
||||||
setPage(pageNum);
|
|
||||||
} catch {
|
} catch {
|
||||||
// Silent error for now
|
// Silent error for now; pull-to-refresh lets the user retry.
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setRefreshing(false);
|
setRefreshing(false);
|
||||||
@@ -37,44 +34,49 @@ export default function LibraryScreen({ navigation }: { navigation: any }): Reac
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadBooks(1, true);
|
loadBooks();
|
||||||
}, [loadBooks]);
|
}, [loadBooks]);
|
||||||
|
|
||||||
const onRefresh = () => {
|
const onRefresh = () => {
|
||||||
setRefreshing(true);
|
setRefreshing(true);
|
||||||
loadBooks(1, true);
|
loadBooks();
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadMore = () => {
|
const renderBook = ({ item }: { item: EBookListItem }) => {
|
||||||
if (hasMore && !loading) {
|
const progress =
|
||||||
loadBooks(page + 1);
|
typeof item.progress === "number"
|
||||||
}
|
? Math.round(item.progress)
|
||||||
|
: null;
|
||||||
|
return (
|
||||||
|
<TouchableOpacity
|
||||||
|
style={styles.bookCard}
|
||||||
|
onPress={() => navigation.navigate("BookDetail", { ebookId: item.id })}
|
||||||
|
>
|
||||||
|
{item.cover_image ? (
|
||||||
|
<Image source={{ uri: item.cover_image }} style={styles.bookCover} />
|
||||||
|
) : (
|
||||||
|
<View style={styles.bookCover}>
|
||||||
|
<Text style={styles.coverText}>
|
||||||
|
{item.title.charAt(0).toUpperCase()}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
<View style={styles.bookInfo}>
|
||||||
|
<Text style={styles.bookTitle} numberOfLines={2}>
|
||||||
|
{item.title}
|
||||||
|
</Text>
|
||||||
|
<Text style={styles.bookAuthor} numberOfLines={1}>
|
||||||
|
{item.author || "Unknown author"}
|
||||||
|
</Text>
|
||||||
|
<Text style={styles.bookMeta}>
|
||||||
|
{item.format?.toUpperCase()}
|
||||||
|
{progress !== null ? ` · ${progress}% read` : ""}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
</TouchableOpacity>
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderBook = ({ item }: { item: Book }) => (
|
|
||||||
<TouchableOpacity
|
|
||||||
style={styles.bookCard}
|
|
||||||
onPress={() =>
|
|
||||||
navigation.navigate("BookDetail", { bookId: item.id })
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<View style={styles.bookCover}>
|
|
||||||
<Text style={styles.coverText}>
|
|
||||||
{item.title.charAt(0).toUpperCase()}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
<View style={styles.bookInfo}>
|
|
||||||
<Text style={styles.bookTitle} numberOfLines={1}>
|
|
||||||
{item.title}
|
|
||||||
</Text>
|
|
||||||
<Text style={styles.bookAuthor} numberOfLines={1}>
|
|
||||||
{item.author}
|
|
||||||
</Text>
|
|
||||||
<Text style={styles.bookPages}>{item.total_pages} pages</Text>
|
|
||||||
</View>
|
|
||||||
</TouchableOpacity>
|
|
||||||
);
|
|
||||||
|
|
||||||
if (loading && books.length === 0) {
|
if (loading && books.length === 0) {
|
||||||
return (
|
return (
|
||||||
<View style={styles.centered}>
|
<View style={styles.centered}>
|
||||||
@@ -88,9 +90,7 @@ export default function LibraryScreen({ navigation }: { navigation: any }): Reac
|
|||||||
<FlatList
|
<FlatList
|
||||||
data={books}
|
data={books}
|
||||||
renderItem={renderBook}
|
renderItem={renderBook}
|
||||||
keyExtractor={(item) => item.id}
|
keyExtractor={(item) => String(item.id)}
|
||||||
onEndReached={loadMore}
|
|
||||||
onEndReachedThreshold={0.5}
|
|
||||||
contentContainerStyle={styles.list}
|
contentContainerStyle={styles.list}
|
||||||
refreshControl={
|
refreshControl={
|
||||||
<RefreshControl
|
<RefreshControl
|
||||||
@@ -103,7 +103,7 @@ export default function LibraryScreen({ navigation }: { navigation: any }): Reac
|
|||||||
<View style={styles.centered}>
|
<View style={styles.centered}>
|
||||||
<Text style={styles.emptyText}>Your library is empty</Text>
|
<Text style={styles.emptyText}>Your library is empty</Text>
|
||||||
<Text style={styles.emptySubtext}>
|
<Text style={styles.emptySubtext}>
|
||||||
Add books to get started
|
Upload books from the web app to get started
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
}
|
}
|
||||||
@@ -125,6 +125,7 @@ const styles = StyleSheet.create({
|
|||||||
},
|
},
|
||||||
list: {
|
list: {
|
||||||
padding: 16,
|
padding: 16,
|
||||||
|
flexGrow: 1,
|
||||||
},
|
},
|
||||||
bookCard: {
|
bookCard: {
|
||||||
flexDirection: "row",
|
flexDirection: "row",
|
||||||
@@ -164,7 +165,7 @@ const styles = StyleSheet.create({
|
|||||||
color: "#888",
|
color: "#888",
|
||||||
marginBottom: 4,
|
marginBottom: 4,
|
||||||
},
|
},
|
||||||
bookPages: {
|
bookMeta: {
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
color: "#666",
|
color: "#666",
|
||||||
},
|
},
|
||||||
@@ -177,5 +178,6 @@ const styles = StyleSheet.create({
|
|||||||
emptySubtext: {
|
emptySubtext: {
|
||||||
fontSize: 14,
|
fontSize: 14,
|
||||||
color: "#666",
|
color: "#666",
|
||||||
|
textAlign: "center",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,29 +4,31 @@ import {
|
|||||||
Text,
|
Text,
|
||||||
TextInput,
|
TextInput,
|
||||||
TouchableOpacity,
|
TouchableOpacity,
|
||||||
StyleSheet,
|
|
||||||
Alert,
|
Alert,
|
||||||
ActivityIndicator,
|
ActivityIndicator,
|
||||||
KeyboardAvoidingView,
|
KeyboardAvoidingView,
|
||||||
Platform,
|
Platform,
|
||||||
} from "react-native";
|
} from "react-native";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import { isValidEmail } from "@cloud-reader/shared";
|
import { authStyles } from "./authStyles";
|
||||||
|
import { AuthFormError } from "./AuthFormError";
|
||||||
|
import { requireValidEmail } from "./authValidation";
|
||||||
|
|
||||||
export default function LoginScreen({ navigation }: { navigation: any }): ReactNode {
|
export default function LoginScreen({
|
||||||
const { state, login, clearError } = useAuth();
|
navigation,
|
||||||
|
}: {
|
||||||
|
navigation: any;
|
||||||
|
}): ReactNode {
|
||||||
|
const { login } = useAuth();
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
const handleLogin = async () => {
|
const handleLogin = async () => {
|
||||||
clearError();
|
setError(null);
|
||||||
|
|
||||||
if (!email.trim()) {
|
if (!requireValidEmail(email)) {
|
||||||
Alert.alert("Validation Error", "Please enter your email.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!isValidEmail(email.trim())) {
|
|
||||||
Alert.alert("Validation Error", "Please enter a valid email address.");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!password) {
|
if (!password) {
|
||||||
@@ -34,30 +36,29 @@ export default function LoginScreen({ navigation }: { navigation: any }): ReactN
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setSubmitting(true);
|
||||||
try {
|
try {
|
||||||
await login(email.trim(), password);
|
await login(email.trim(), password);
|
||||||
} catch {
|
} catch {
|
||||||
// Error handled in context
|
setError("Invalid email or password.");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<KeyboardAvoidingView
|
<KeyboardAvoidingView
|
||||||
style={styles.container}
|
style={authStyles.container}
|
||||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
||||||
>
|
>
|
||||||
<View style={styles.inner}>
|
<View style={authStyles.inner}>
|
||||||
<Text style={styles.title}>Cloud Reader</Text>
|
<Text style={authStyles.title}>Cloud Reader</Text>
|
||||||
<Text style={styles.subtitle}>Sign in to your account</Text>
|
<Text style={authStyles.subtitle}>Sign in to your account</Text>
|
||||||
|
|
||||||
{state.error && (
|
{error ? <AuthFormError message={error} /> : null}
|
||||||
<View style={styles.errorBox}>
|
|
||||||
<Text style={styles.errorText}>{state.error}</Text>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<TextInput
|
<TextInput
|
||||||
style={styles.input}
|
style={authStyles.input}
|
||||||
placeholder="Email"
|
placeholder="Email"
|
||||||
placeholderTextColor="#666"
|
placeholderTextColor="#666"
|
||||||
value={email}
|
value={email}
|
||||||
@@ -68,7 +69,7 @@ export default function LoginScreen({ navigation }: { navigation: any }): ReactN
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<TextInput
|
<TextInput
|
||||||
style={styles.input}
|
style={authStyles.input}
|
||||||
placeholder="Password"
|
placeholder="Password"
|
||||||
placeholderTextColor="#666"
|
placeholderTextColor="#666"
|
||||||
value={password}
|
value={password}
|
||||||
@@ -77,97 +78,24 @@ export default function LoginScreen({ navigation }: { navigation: any }): ReactN
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
style={[styles.button, state.isLoading && styles.buttonDisabled]}
|
style={[authStyles.button, submitting && authStyles.buttonDisabled]}
|
||||||
onPress={handleLogin}
|
onPress={handleLogin}
|
||||||
disabled={state.isLoading}
|
disabled={submitting}
|
||||||
>
|
>
|
||||||
{state.isLoading ? (
|
{submitting ? (
|
||||||
<ActivityIndicator color="#fff" />
|
<ActivityIndicator color="#fff" />
|
||||||
) : (
|
) : (
|
||||||
<Text style={styles.buttonText}>Sign In</Text>
|
<Text style={authStyles.buttonText}>Sign In</Text>
|
||||||
)}
|
)}
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
|
|
||||||
<TouchableOpacity onPress={() => navigation.navigate("Register")}>
|
<TouchableOpacity onPress={() => navigation.navigate("Register")}>
|
||||||
<Text style={styles.linkText}>
|
<Text style={authStyles.linkText}>
|
||||||
Don't have an account?{" "}
|
Don't have an account?{" "}
|
||||||
<Text style={styles.linkBold}>Sign Up</Text>
|
<Text style={authStyles.linkBold}>Sign Up</Text>
|
||||||
</Text>
|
</Text>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
</View>
|
</View>
|
||||||
</KeyboardAvoidingView>
|
</KeyboardAvoidingView>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const styles = StyleSheet.create({
|
|
||||||
container: {
|
|
||||||
flex: 1,
|
|
||||||
backgroundColor: "#0f0f23",
|
|
||||||
},
|
|
||||||
inner: {
|
|
||||||
flex: 1,
|
|
||||||
justifyContent: "center",
|
|
||||||
paddingHorizontal: 24,
|
|
||||||
},
|
|
||||||
title: {
|
|
||||||
fontSize: 32,
|
|
||||||
fontWeight: "bold",
|
|
||||||
color: "#fff",
|
|
||||||
textAlign: "center",
|
|
||||||
marginBottom: 8,
|
|
||||||
},
|
|
||||||
subtitle: {
|
|
||||||
fontSize: 16,
|
|
||||||
color: "#888",
|
|
||||||
textAlign: "center",
|
|
||||||
marginBottom: 32,
|
|
||||||
},
|
|
||||||
input: {
|
|
||||||
backgroundColor: "#1a1a2e",
|
|
||||||
borderRadius: 8,
|
|
||||||
padding: 16,
|
|
||||||
fontSize: 16,
|
|
||||||
color: "#fff",
|
|
||||||
marginBottom: 12,
|
|
||||||
borderWidth: 1,
|
|
||||||
borderColor: "#333",
|
|
||||||
},
|
|
||||||
button: {
|
|
||||||
backgroundColor: "#4f8ef7",
|
|
||||||
borderRadius: 8,
|
|
||||||
padding: 16,
|
|
||||||
alignItems: "center",
|
|
||||||
marginTop: 8,
|
|
||||||
marginBottom: 24,
|
|
||||||
},
|
|
||||||
buttonDisabled: {
|
|
||||||
opacity: 0.6,
|
|
||||||
},
|
|
||||||
buttonText: {
|
|
||||||
color: "#fff",
|
|
||||||
fontSize: 16,
|
|
||||||
fontWeight: "600",
|
|
||||||
},
|
|
||||||
errorBox: {
|
|
||||||
backgroundColor: "rgba(255, 69, 58, 0.15)",
|
|
||||||
borderRadius: 8,
|
|
||||||
padding: 12,
|
|
||||||
marginBottom: 16,
|
|
||||||
borderWidth: 1,
|
|
||||||
borderColor: "rgba(255, 69, 58, 0.3)",
|
|
||||||
},
|
|
||||||
errorText: {
|
|
||||||
color: "#ff453a",
|
|
||||||
fontSize: 14,
|
|
||||||
textAlign: "center",
|
|
||||||
},
|
|
||||||
linkText: {
|
|
||||||
color: "#888",
|
|
||||||
textAlign: "center",
|
|
||||||
fontSize: 14,
|
|
||||||
},
|
|
||||||
linkBold: {
|
|
||||||
color: "#4f8ef7",
|
|
||||||
fontWeight: "600",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import { useEffect, useState, type ReactNode } from "react";
|
||||||
|
import {
|
||||||
|
View,
|
||||||
|
Text,
|
||||||
|
TouchableOpacity,
|
||||||
|
ActivityIndicator,
|
||||||
|
StyleSheet,
|
||||||
|
} from "react-native";
|
||||||
|
import { SafeAreaView } from "react-native-safe-area-context";
|
||||||
|
import type { RouteProp } from "@react-navigation/native";
|
||||||
|
import type { EBookDetail } from "@cloud-reader/shared";
|
||||||
|
import { ebooksApi } from "../api/ebooks";
|
||||||
|
import { EpubReaderView } from "../components/reader/EpubReaderView";
|
||||||
|
import type { AppStackParamList } from "../types";
|
||||||
|
|
||||||
|
type ReaderRoute = RouteProp<AppStackParamList, "Reader">;
|
||||||
|
|
||||||
|
export default function ReaderScreen({
|
||||||
|
route,
|
||||||
|
navigation,
|
||||||
|
}: {
|
||||||
|
route: ReaderRoute;
|
||||||
|
navigation: any;
|
||||||
|
}): ReactNode {
|
||||||
|
const { ebookId } = route.params;
|
||||||
|
const [book, setBook] = useState<EBookDetail | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
ebooksApi
|
||||||
|
.get(ebookId)
|
||||||
|
.then(({ data }) => {
|
||||||
|
if (active) setBook(data);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (active) setError(true);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (active) setLoading(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, [ebookId]);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<View style={styles.centered}>
|
||||||
|
<ActivityIndicator size="large" color="#4f8ef7" />
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error || !book) {
|
||||||
|
return (
|
||||||
|
<SafeAreaView style={styles.centered} edges={["top", "bottom"]}>
|
||||||
|
<Text style={styles.message}>Could not open this book.</Text>
|
||||||
|
<TouchableOpacity
|
||||||
|
style={styles.backButton}
|
||||||
|
onPress={() => navigation.goBack()}
|
||||||
|
>
|
||||||
|
<Text style={styles.backText}>Go back</Text>
|
||||||
|
</TouchableOpacity>
|
||||||
|
</SafeAreaView>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const format = (book.format ?? "").toLowerCase();
|
||||||
|
|
||||||
|
if (format !== "epub") {
|
||||||
|
return (
|
||||||
|
<SafeAreaView style={styles.centered} edges={["top", "bottom"]}>
|
||||||
|
<Text style={styles.placeholderTitle}>PDF reading is coming soon</Text>
|
||||||
|
<Text style={styles.message}>
|
||||||
|
“{book.title}” is a {format.toUpperCase() || "non-EPUB"} file. PDF
|
||||||
|
reading isn't available on mobile yet — open it in the web reader
|
||||||
|
for now.
|
||||||
|
</Text>
|
||||||
|
<TouchableOpacity
|
||||||
|
style={styles.backButton}
|
||||||
|
onPress={() => navigation.goBack()}
|
||||||
|
>
|
||||||
|
<Text style={styles.backText}>Go back</Text>
|
||||||
|
</TouchableOpacity>
|
||||||
|
</SafeAreaView>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<EpubReaderView
|
||||||
|
book={book}
|
||||||
|
ebookId={ebookId}
|
||||||
|
onClose={() => navigation.goBack()}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
centered: {
|
||||||
|
flex: 1,
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
backgroundColor: "#0f0f23",
|
||||||
|
padding: 24,
|
||||||
|
},
|
||||||
|
placeholderTitle: {
|
||||||
|
fontSize: 20,
|
||||||
|
fontWeight: "700",
|
||||||
|
color: "#fff",
|
||||||
|
marginBottom: 12,
|
||||||
|
textAlign: "center",
|
||||||
|
},
|
||||||
|
message: {
|
||||||
|
fontSize: 15,
|
||||||
|
color: "#aaa",
|
||||||
|
textAlign: "center",
|
||||||
|
lineHeight: 22,
|
||||||
|
},
|
||||||
|
backButton: {
|
||||||
|
marginTop: 24,
|
||||||
|
backgroundColor: "#4f8ef7",
|
||||||
|
borderRadius: 10,
|
||||||
|
paddingHorizontal: 24,
|
||||||
|
paddingVertical: 12,
|
||||||
|
},
|
||||||
|
backText: {
|
||||||
|
color: "#fff",
|
||||||
|
fontSize: 15,
|
||||||
|
fontWeight: "600",
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -1,10 +1,8 @@
|
|||||||
import { useState, type ReactNode } from "react";
|
import { useState, type ReactNode } from "react";
|
||||||
import {
|
import {
|
||||||
View,
|
|
||||||
Text,
|
Text,
|
||||||
TextInput,
|
TextInput,
|
||||||
TouchableOpacity,
|
TouchableOpacity,
|
||||||
StyleSheet,
|
|
||||||
Alert,
|
Alert,
|
||||||
ActivityIndicator,
|
ActivityIndicator,
|
||||||
KeyboardAvoidingView,
|
KeyboardAvoidingView,
|
||||||
@@ -12,40 +10,39 @@ import {
|
|||||||
ScrollView,
|
ScrollView,
|
||||||
} from "react-native";
|
} from "react-native";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import {
|
import { isStrongPassword } from "@cloud-reader/shared";
|
||||||
isValidEmail,
|
import { authStyles } from "./authStyles";
|
||||||
validatePasswordStrength,
|
import { AuthFormError } from "./AuthFormError";
|
||||||
} from "@cloud-reader/shared";
|
import { requireValidEmail } from "./authValidation";
|
||||||
|
|
||||||
export default function RegisterScreen({
|
export default function RegisterScreen({
|
||||||
navigation,
|
navigation,
|
||||||
}: {
|
}: {
|
||||||
navigation: any;
|
navigation: any;
|
||||||
}): ReactNode {
|
}): ReactNode {
|
||||||
const { state, register, clearError } = useAuth();
|
const { register } = useAuth();
|
||||||
const [username, setUsername] = useState("");
|
const [username, setUsername] = useState("");
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [confirmPassword, setConfirmPassword] = useState("");
|
const [confirmPassword, setConfirmPassword] = useState("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
const handleRegister = async () => {
|
const handleRegister = async () => {
|
||||||
clearError();
|
setError(null);
|
||||||
|
|
||||||
if (!username.trim()) {
|
if (!username.trim()) {
|
||||||
Alert.alert("Validation Error", "Please enter a username.");
|
Alert.alert("Validation Error", "Please enter a username.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!email.trim()) {
|
if (!requireValidEmail(email)) {
|
||||||
Alert.alert("Validation Error", "Please enter your email.");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!isValidEmail(email.trim())) {
|
if (!isStrongPassword(password)) {
|
||||||
Alert.alert("Validation Error", "Please enter a valid email address.");
|
Alert.alert(
|
||||||
return;
|
"Validation Error",
|
||||||
}
|
"Password must be at least 8 characters and include uppercase, lowercase, and a number.",
|
||||||
const passwordError = validatePasswordStrength(password);
|
);
|
||||||
if (passwordError) {
|
|
||||||
Alert.alert("Validation Error", passwordError);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (password !== confirmPassword) {
|
if (password !== confirmPassword) {
|
||||||
@@ -53,30 +50,29 @@ export default function RegisterScreen({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setSubmitting(true);
|
||||||
try {
|
try {
|
||||||
await register(email.trim(), password, username.trim());
|
await register(email.trim(), username.trim(), password);
|
||||||
} catch {
|
} catch {
|
||||||
// Error handled in context
|
setError("Could not create the account. Try a different email.");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<KeyboardAvoidingView
|
<KeyboardAvoidingView
|
||||||
style={styles.container}
|
style={authStyles.container}
|
||||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
||||||
>
|
>
|
||||||
<ScrollView contentContainerStyle={styles.inner}>
|
<ScrollView contentContainerStyle={authStyles.innerScroll}>
|
||||||
<Text style={styles.title}>Create Account</Text>
|
<Text style={authStyles.titleCompact}>Create Account</Text>
|
||||||
<Text style={styles.subtitle}>Join Cloud Reader</Text>
|
<Text style={authStyles.subtitle}>Join Cloud Reader</Text>
|
||||||
|
|
||||||
{state.error && (
|
{error ? <AuthFormError message={error} /> : null}
|
||||||
<View style={styles.errorBox}>
|
|
||||||
<Text style={styles.errorText}>{state.error}</Text>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<TextInput
|
<TextInput
|
||||||
style={styles.input}
|
style={authStyles.input}
|
||||||
placeholder="Username"
|
placeholder="Username"
|
||||||
placeholderTextColor="#666"
|
placeholderTextColor="#666"
|
||||||
value={username}
|
value={username}
|
||||||
@@ -86,7 +82,7 @@ export default function RegisterScreen({
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<TextInput
|
<TextInput
|
||||||
style={styles.input}
|
style={authStyles.input}
|
||||||
placeholder="Email"
|
placeholder="Email"
|
||||||
placeholderTextColor="#666"
|
placeholderTextColor="#666"
|
||||||
value={email}
|
value={email}
|
||||||
@@ -97,7 +93,7 @@ export default function RegisterScreen({
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<TextInput
|
<TextInput
|
||||||
style={styles.input}
|
style={authStyles.input}
|
||||||
placeholder="Password"
|
placeholder="Password"
|
||||||
placeholderTextColor="#666"
|
placeholderTextColor="#666"
|
||||||
value={password}
|
value={password}
|
||||||
@@ -106,7 +102,7 @@ export default function RegisterScreen({
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<TextInput
|
<TextInput
|
||||||
style={styles.input}
|
style={authStyles.input}
|
||||||
placeholder="Confirm Password"
|
placeholder="Confirm Password"
|
||||||
placeholderTextColor="#666"
|
placeholderTextColor="#666"
|
||||||
value={confirmPassword}
|
value={confirmPassword}
|
||||||
@@ -115,98 +111,24 @@ export default function RegisterScreen({
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
style={[styles.button, state.isLoading && styles.buttonDisabled]}
|
style={[authStyles.button, submitting && authStyles.buttonDisabled]}
|
||||||
onPress={handleRegister}
|
onPress={handleRegister}
|
||||||
disabled={state.isLoading}
|
disabled={submitting}
|
||||||
>
|
>
|
||||||
{state.isLoading ? (
|
{submitting ? (
|
||||||
<ActivityIndicator color="#fff" />
|
<ActivityIndicator color="#fff" />
|
||||||
) : (
|
) : (
|
||||||
<Text style={styles.buttonText}>Create Account</Text>
|
<Text style={authStyles.buttonText}>Create Account</Text>
|
||||||
)}
|
)}
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
|
|
||||||
<TouchableOpacity onPress={() => navigation.goBack()}>
|
<TouchableOpacity onPress={() => navigation.goBack()}>
|
||||||
<Text style={styles.linkText}>
|
<Text style={authStyles.linkText}>
|
||||||
Already have an account?{" "}
|
Already have an account?{" "}
|
||||||
<Text style={styles.linkBold}>Sign In</Text>
|
<Text style={authStyles.linkBold}>Sign In</Text>
|
||||||
</Text>
|
</Text>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
</KeyboardAvoidingView>
|
</KeyboardAvoidingView>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const styles = StyleSheet.create({
|
|
||||||
container: {
|
|
||||||
flex: 1,
|
|
||||||
backgroundColor: "#0f0f23",
|
|
||||||
},
|
|
||||||
inner: {
|
|
||||||
flexGrow: 1,
|
|
||||||
justifyContent: "center",
|
|
||||||
paddingHorizontal: 24,
|
|
||||||
paddingVertical: 48,
|
|
||||||
},
|
|
||||||
title: {
|
|
||||||
fontSize: 28,
|
|
||||||
fontWeight: "bold",
|
|
||||||
color: "#fff",
|
|
||||||
textAlign: "center",
|
|
||||||
marginBottom: 8,
|
|
||||||
},
|
|
||||||
subtitle: {
|
|
||||||
fontSize: 16,
|
|
||||||
color: "#888",
|
|
||||||
textAlign: "center",
|
|
||||||
marginBottom: 32,
|
|
||||||
},
|
|
||||||
input: {
|
|
||||||
backgroundColor: "#1a1a2e",
|
|
||||||
borderRadius: 8,
|
|
||||||
padding: 16,
|
|
||||||
fontSize: 16,
|
|
||||||
color: "#fff",
|
|
||||||
marginBottom: 12,
|
|
||||||
borderWidth: 1,
|
|
||||||
borderColor: "#333",
|
|
||||||
},
|
|
||||||
button: {
|
|
||||||
backgroundColor: "#4f8ef7",
|
|
||||||
borderRadius: 8,
|
|
||||||
padding: 16,
|
|
||||||
alignItems: "center",
|
|
||||||
marginTop: 8,
|
|
||||||
marginBottom: 24,
|
|
||||||
},
|
|
||||||
buttonDisabled: {
|
|
||||||
opacity: 0.6,
|
|
||||||
},
|
|
||||||
buttonText: {
|
|
||||||
color: "#fff",
|
|
||||||
fontSize: 16,
|
|
||||||
fontWeight: "600",
|
|
||||||
},
|
|
||||||
errorBox: {
|
|
||||||
backgroundColor: "rgba(255, 69, 58, 0.15)",
|
|
||||||
borderRadius: 8,
|
|
||||||
padding: 12,
|
|
||||||
marginBottom: 16,
|
|
||||||
borderWidth: 1,
|
|
||||||
borderColor: "rgba(255, 69, 58, 0.3)",
|
|
||||||
},
|
|
||||||
errorText: {
|
|
||||||
color: "#ff453a",
|
|
||||||
fontSize: 14,
|
|
||||||
textAlign: "center",
|
|
||||||
},
|
|
||||||
linkText: {
|
|
||||||
color: "#888",
|
|
||||||
textAlign: "center",
|
|
||||||
fontSize: 14,
|
|
||||||
},
|
|
||||||
linkBold: {
|
|
||||||
color: "#4f8ef7",
|
|
||||||
fontWeight: "600",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
|
|
||||||
export default function SettingsScreen(): ReactNode {
|
export default function SettingsScreen(): ReactNode {
|
||||||
const { state, logout } = useAuth();
|
const { user, logout } = useAuth();
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
Alert.alert("Logout", "Are you sure you want to sign out?", [
|
Alert.alert("Logout", "Are you sure you want to sign out?", [
|
||||||
@@ -24,11 +24,11 @@ export default function SettingsScreen(): ReactNode {
|
|||||||
<Text style={styles.sectionTitle}>Account</Text>
|
<Text style={styles.sectionTitle}>Account</Text>
|
||||||
<View style={styles.infoRow}>
|
<View style={styles.infoRow}>
|
||||||
<Text style={styles.label}>Username</Text>
|
<Text style={styles.label}>Username</Text>
|
||||||
<Text style={styles.value}>{state.user?.username ?? "—"}</Text>
|
<Text style={styles.value}>{user?.username ?? "—"}</Text>
|
||||||
</View>
|
</View>
|
||||||
<View style={styles.infoRow}>
|
<View style={styles.infoRow}>
|
||||||
<Text style={styles.label}>Email</Text>
|
<Text style={styles.label}>Email</Text>
|
||||||
<Text style={styles.value}>{state.user?.email ?? "—"}</Text>
|
<Text style={styles.value}>{user?.email ?? "—"}</Text>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { StyleSheet } from "react-native";
|
||||||
|
|
||||||
|
/** Shared layout/styles for Login and Register screens. */
|
||||||
|
export const authStyles = StyleSheet.create({
|
||||||
|
container: {
|
||||||
|
flex: 1,
|
||||||
|
backgroundColor: "#0f0f23",
|
||||||
|
},
|
||||||
|
inner: {
|
||||||
|
flex: 1,
|
||||||
|
justifyContent: "center",
|
||||||
|
paddingHorizontal: 24,
|
||||||
|
},
|
||||||
|
innerScroll: {
|
||||||
|
flexGrow: 1,
|
||||||
|
justifyContent: "center",
|
||||||
|
paddingHorizontal: 24,
|
||||||
|
paddingVertical: 48,
|
||||||
|
},
|
||||||
|
title: {
|
||||||
|
fontSize: 32,
|
||||||
|
fontWeight: "bold",
|
||||||
|
color: "#fff",
|
||||||
|
textAlign: "center",
|
||||||
|
marginBottom: 8,
|
||||||
|
},
|
||||||
|
titleCompact: {
|
||||||
|
fontSize: 28,
|
||||||
|
fontWeight: "bold",
|
||||||
|
color: "#fff",
|
||||||
|
textAlign: "center",
|
||||||
|
marginBottom: 8,
|
||||||
|
},
|
||||||
|
subtitle: {
|
||||||
|
fontSize: 16,
|
||||||
|
color: "#888",
|
||||||
|
textAlign: "center",
|
||||||
|
marginBottom: 32,
|
||||||
|
},
|
||||||
|
input: {
|
||||||
|
backgroundColor: "#1a1a2e",
|
||||||
|
borderRadius: 8,
|
||||||
|
padding: 16,
|
||||||
|
fontSize: 16,
|
||||||
|
color: "#fff",
|
||||||
|
marginBottom: 12,
|
||||||
|
borderWidth: 1,
|
||||||
|
borderColor: "#333",
|
||||||
|
},
|
||||||
|
button: {
|
||||||
|
backgroundColor: "#4f8ef7",
|
||||||
|
borderRadius: 8,
|
||||||
|
padding: 16,
|
||||||
|
alignItems: "center",
|
||||||
|
marginTop: 8,
|
||||||
|
marginBottom: 24,
|
||||||
|
},
|
||||||
|
buttonDisabled: {
|
||||||
|
opacity: 0.6,
|
||||||
|
},
|
||||||
|
buttonText: {
|
||||||
|
color: "#fff",
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: "600",
|
||||||
|
},
|
||||||
|
errorBox: {
|
||||||
|
backgroundColor: "rgba(255, 69, 58, 0.15)",
|
||||||
|
borderRadius: 8,
|
||||||
|
padding: 12,
|
||||||
|
marginBottom: 16,
|
||||||
|
borderWidth: 1,
|
||||||
|
borderColor: "rgba(255, 69, 58, 0.3)",
|
||||||
|
},
|
||||||
|
errorText: {
|
||||||
|
color: "#ff453a",
|
||||||
|
fontSize: 14,
|
||||||
|
textAlign: "center",
|
||||||
|
},
|
||||||
|
linkText: {
|
||||||
|
color: "#888",
|
||||||
|
textAlign: "center",
|
||||||
|
fontSize: 14,
|
||||||
|
},
|
||||||
|
linkBold: {
|
||||||
|
color: "#4f8ef7",
|
||||||
|
fontWeight: "600",
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { Alert } from "react-native";
|
||||||
|
import { isValidEmail } from "@cloud-reader/shared";
|
||||||
|
|
||||||
|
/** Returns true when email is non-empty and well-formed. */
|
||||||
|
export function requireValidEmail(email: string): boolean {
|
||||||
|
if (!email.trim()) {
|
||||||
|
Alert.alert("Validation Error", "Please enter your email.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!isValidEmail(email.trim())) {
|
||||||
|
Alert.alert("Validation Error", "Please enter a valid email address.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -1,8 +1,37 @@
|
|||||||
// Mobile-specific type aliases and extensions not covered by shared types
|
// Mobile-specific type aliases and extensions not covered by shared types
|
||||||
|
|
||||||
export type RootStackParamList = {
|
import type { NavigatorScreenParams } from "@react-navigation/native";
|
||||||
Auth: undefined;
|
import type { MainTabParamList } from "../navigation/MainNavigator";
|
||||||
Main: undefined;
|
|
||||||
BookReader: { bookId: number };
|
/** Stack hosted above the bottom tabs once the user is authenticated. */
|
||||||
BookDetail: { bookId: number };
|
export type AppStackParamList = {
|
||||||
};
|
Tabs: NavigatorScreenParams<MainTabParamList> | undefined;
|
||||||
|
BookDetail: { ebookId: number };
|
||||||
|
Reader: { ebookId: number };
|
||||||
|
};
|
||||||
|
|
||||||
|
/** EPUB bookmark/highlight, mirrors frontend/src/types Bookmark. */
|
||||||
|
export interface Bookmark {
|
||||||
|
id: string;
|
||||||
|
ebook: number;
|
||||||
|
ebook_title: string;
|
||||||
|
epub_cfi: string;
|
||||||
|
chapter_index: number;
|
||||||
|
chapter_title: string;
|
||||||
|
page: number;
|
||||||
|
location_text: string;
|
||||||
|
content: string;
|
||||||
|
highlight_color?: string;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateMarkerPayload {
|
||||||
|
ebook: number;
|
||||||
|
epub_cfi: string;
|
||||||
|
chapter_index: number;
|
||||||
|
chapter_title?: string;
|
||||||
|
location_text?: string;
|
||||||
|
content?: string;
|
||||||
|
highlight_color?: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/**
|
||||||
|
* Reader module types for the mobile app. Mirrors
|
||||||
|
* frontend/src/types/reader.ts so settings and progress behave the same
|
||||||
|
* way across web and mobile.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface ReadingSettings {
|
||||||
|
font_family: "sans-serif" | "serif" | "monospace";
|
||||||
|
font_size: number;
|
||||||
|
line_height: number;
|
||||||
|
margin_width: number;
|
||||||
|
background_color: string;
|
||||||
|
text_color: string;
|
||||||
|
brightness: number;
|
||||||
|
orientation_lock: "auto" | "portrait" | "landscape";
|
||||||
|
theme: "sepia" | "dark" | "light" | "paper";
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ThemePreset = ReadingSettings["theme"];
|
||||||
|
export type FontFamily = ReadingSettings["font_family"];
|
||||||
|
|
||||||
|
export interface ReadingProgress {
|
||||||
|
id: number;
|
||||||
|
book: number;
|
||||||
|
current_chapter: number;
|
||||||
|
current_position: number;
|
||||||
|
percentage: number;
|
||||||
|
epub_location: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import type { ReadingSettings, ThemePreset } from "../types/reader";
|
||||||
|
|
||||||
|
/** CSS font stacks per family, mirrors frontend/src/utils/epubRendition.ts. */
|
||||||
|
export const FONT_STACKS: Record<ReadingSettings["font_family"], string> = {
|
||||||
|
serif: 'Georgia, "Times New Roman", serif',
|
||||||
|
"sans-serif":
|
||||||
|
'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
|
||||||
|
monospace: 'ui-monospace, "Cascadia Code", monospace',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Background/text/chrome colors for each reader theme preset. */
|
||||||
|
export const THEME_PALETTES: Record<
|
||||||
|
ThemePreset,
|
||||||
|
{ background: string; text: string; chrome: string }
|
||||||
|
> = {
|
||||||
|
light: { background: "#ffffff", text: "#1a1a1a", chrome: "#f2f2f2" },
|
||||||
|
dark: { background: "#121212", text: "#e0e0e0", chrome: "#1c1c1e" },
|
||||||
|
sepia: { background: "#f4ecd8", text: "#5b4636", chrome: "#e8ddc4" },
|
||||||
|
paper: { background: "#fbfbf8", text: "#2b2b2b", chrome: "#efefe9" },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function resolvePalette(settings: ReadingSettings) {
|
||||||
|
const preset = THEME_PALETTES[settings.theme] ?? THEME_PALETTES.light;
|
||||||
|
return {
|
||||||
|
background: settings.background_color || preset.background,
|
||||||
|
text: settings.text_color || preset.text,
|
||||||
|
chrome: preset.chrome,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build an epub.js theme object (selector -> CSS rules) from reader settings.
|
||||||
|
* Used with the epubjs-react-native `changeTheme` method.
|
||||||
|
*/
|
||||||
|
export function buildEpubTheme(
|
||||||
|
settings: ReadingSettings,
|
||||||
|
): Record<string, Record<string, string>> {
|
||||||
|
const { background, text } = resolvePalette(settings);
|
||||||
|
const fontStack = FONT_STACKS[settings.font_family] ?? FONT_STACKS.serif;
|
||||||
|
const lineHeight = `${settings.line_height} !important`;
|
||||||
|
const fontFamily = `${fontStack} !important`;
|
||||||
|
const color = `${text} !important`;
|
||||||
|
|
||||||
|
return {
|
||||||
|
body: {
|
||||||
|
background: `${background} !important`,
|
||||||
|
color,
|
||||||
|
"font-family": fontFamily,
|
||||||
|
"line-height": lineHeight,
|
||||||
|
},
|
||||||
|
p: {
|
||||||
|
color,
|
||||||
|
"font-family": fontFamily,
|
||||||
|
"line-height": lineHeight,
|
||||||
|
},
|
||||||
|
li: { color, "font-family": fontFamily, "line-height": lineHeight },
|
||||||
|
span: { color },
|
||||||
|
a: { color },
|
||||||
|
h1: { color },
|
||||||
|
h2: { color },
|
||||||
|
h3: { color },
|
||||||
|
h4: { color },
|
||||||
|
h5: { color },
|
||||||
|
h6: { color },
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -12,7 +12,8 @@
|
|||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["src/*"]
|
"@/*": ["src/*"],
|
||||||
|
"@cloud-reader/shared": ["../packages/shared/src/index.ts"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"include": ["**/*.ts", "**/*.tsx"],
|
"include": ["**/*.ts", "**/*.tsx"],
|
||||||
|
|||||||
@@ -215,4 +215,36 @@ export interface PaginatedResponse<T> {
|
|||||||
export interface ApiError {
|
export interface ApiError {
|
||||||
detail?: string;
|
detail?: string;
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Reading Groups ----
|
||||||
|
|
||||||
|
export interface ReadingGroupSummary {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
ebook: number;
|
||||||
|
ebook_title: string;
|
||||||
|
ebook_author: string;
|
||||||
|
created_by_email: string;
|
||||||
|
description: string;
|
||||||
|
member_count: number;
|
||||||
|
my_progress: {
|
||||||
|
current_section: number;
|
||||||
|
percentage: number;
|
||||||
|
time_spent_seconds: number;
|
||||||
|
section_label: string;
|
||||||
|
} | null;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MemberProgressPublic {
|
||||||
|
user_id: number;
|
||||||
|
user_email: string;
|
||||||
|
current_section: number;
|
||||||
|
total_sections: number;
|
||||||
|
section_label: string;
|
||||||
|
percentage: number;
|
||||||
|
time_spent_seconds: number;
|
||||||
|
updated_at: string;
|
||||||
}
|
}
|
||||||
@@ -114,4 +114,13 @@ export const API_ENDPOINTS = {
|
|||||||
bookmarkDetail: (id: string) => `/api/annotations/bookmarks/${id}/`,
|
bookmarkDetail: (id: string) => `/api/annotations/bookmarks/${id}/`,
|
||||||
noteDetail: (id: string) => `/api/annotations/notes/${id}/`,
|
noteDetail: (id: string) => `/api/annotations/notes/${id}/`,
|
||||||
},
|
},
|
||||||
|
groups: {
|
||||||
|
list: "/api/groups/",
|
||||||
|
detail: (id: number) => `/api/groups/${id}/`,
|
||||||
|
membersProgress: (id: number) => `/api/groups/${id}/members/progress/`,
|
||||||
|
myProgress: (id: number) => `/api/groups/${id}/progress/`,
|
||||||
|
progressSummary: (id: number) => `/api/groups/${id}/progress/summary/`,
|
||||||
|
join: (id: number) => `/api/groups/${id}/join/`,
|
||||||
|
leave: (id: number) => `/api/groups/${id}/leave/`,
|
||||||
|
},
|
||||||
} as const;
|
} as const;
|
||||||
Reference in New Issue
Block a user